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/DiagnosticAST.h"
54#include "clang/Basic/ExceptionSpecificationType.h"
55#include "clang/Basic/IdentifierTable.h"
56#include "clang/Basic/LLVM.h"
57#include "clang/Basic/LangOptions.h"
58#include "clang/Basic/Linkage.h"
59#include "clang/Basic/Module.h"
60#include "clang/Basic/NoSanitizeList.h"
61#include "clang/Basic/ObjCRuntime.h"
62#include "clang/Basic/ProfileList.h"
63#include "clang/Basic/SourceLocation.h"
64#include "clang/Basic/SourceManager.h"
65#include "clang/Basic/Specifiers.h"
66#include "clang/Basic/TargetCXXABI.h"
67#include "clang/Basic/TargetInfo.h"
68#include "clang/Basic/XRayLists.h"
69#include "clang/Lex/MacroInfo.h"
70#include "llvm/ADT/APFixedPoint.h"
71#include "llvm/ADT/APInt.h"
72#include "llvm/ADT/APSInt.h"
73#include "llvm/ADT/ArrayRef.h"
74#include "llvm/ADT/DenseMap.h"
75#include "llvm/ADT/DenseSet.h"
76#include "llvm/ADT/FoldingSet.h"
77#include "llvm/ADT/PointerUnion.h"
78#include "llvm/ADT/STLExtras.h"
79#include "llvm/ADT/SmallPtrSet.h"
80#include "llvm/ADT/SmallVector.h"
81#include "llvm/ADT/StringExtras.h"
82#include "llvm/ADT/StringRef.h"
83#include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
84#include "llvm/Support/Capacity.h"
85#include "llvm/Support/Casting.h"
86#include "llvm/Support/Compiler.h"
87#include "llvm/Support/ErrorHandling.h"
88#include "llvm/Support/MD5.h"
89#include "llvm/Support/MathExtras.h"
90#include "llvm/Support/SipHash.h"
91#include "llvm/Support/raw_ostream.h"
92#include "llvm/TargetParser/AArch64TargetParser.h"
93#include "llvm/TargetParser/Triple.h"
94#include <algorithm>
95#include <cassert>
96#include <cstddef>
97#include <cstdint>
98#include <cstdlib>
99#include <map>
100#include <memory>
101#include <optional>
102#include <string>
103#include <tuple>
104#include <utility>
105
106using namespace clang;
107
108enum FloatingRank {
109 BFloat16Rank,
110 Float16Rank,
111 HalfRank,
112 FloatRank,
113 DoubleRank,
114 LongDoubleRank,
115 Float128Rank,
116 Ibm128Rank
117};
118
119/// \returns The locations that are relevant when searching for Doc comments
120/// related to \p Key.
121static SmallVector<SourceLocation, 2>
122getLocsForCommentSearch(ASTContext::RawCommentLookupKey Key,
123 SourceManager &SourceMgr) {
124 if (const auto *MI = dyn_cast<const MacroInfo *>(Val&: Key)) {
125 SourceLocation DefLoc = MI->getDefinitionLoc();
126 if (DefLoc.isInvalid() || !DefLoc.isFileID())
127 return {};
128
129 // The macro's definition location points at its name (e.g. FOO in
130 // `#define FOO 1`). The text between a preceding documentation comment
131 // and the name contains the `#define` directive itself, which would be
132 // rejected by the preprocessor-directive guard in
133 // getRawCommentNoCacheImpl. Walk back to the leading `#` so that
134 // the guard only fires when something *else* sits between the comment
135 // and our directive.
136 FileIDAndOffset Decomposed = SourceMgr.getDecomposedLoc(Loc: DefLoc);
137 bool Invalid = false;
138 StringRef Buffer = SourceMgr.getBufferData(FID: Decomposed.first, Invalid: &Invalid);
139 if (Invalid)
140 return {};
141 unsigned Offset = Decomposed.second;
142 if (size_t Found = Buffer.find_last_of(Chars: "#\n", From: Offset);
143 Found != StringRef::npos)
144 Offset = Found;
145 return {SourceMgr.getLocForStartOfFile(FID: Decomposed.first)
146 .getLocWithOffset(Offset)};
147 }
148
149 const auto *D = cast<const Decl *>(Val&: Key);
150 assert(D);
151
152 // User can not attach documentation to implicit declarations.
153 if (D->isImplicit())
154 return {};
155
156 // User can not attach documentation to implicit instantiations.
157 if (const auto *FD = dyn_cast<FunctionDecl>(Val: D)) {
158 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
159 return {};
160 }
161
162 if (const auto *VD = dyn_cast<VarDecl>(Val: D)) {
163 if (VD->isStaticDataMember() &&
164 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
165 return {};
166 }
167
168 if (const auto *CRD = dyn_cast<CXXRecordDecl>(Val: D)) {
169 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
170 return {};
171 }
172
173 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Val: D)) {
174 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
175 if (TSK == TSK_ImplicitInstantiation ||
176 TSK == TSK_Undeclared)
177 return {};
178 }
179
180 if (const auto *ED = dyn_cast<EnumDecl>(Val: D)) {
181 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
182 return {};
183 }
184 if (const auto *TD = dyn_cast<TagDecl>(Val: D)) {
185 // When tag declaration (but not definition!) is part of the
186 // decl-specifier-seq of some other declaration, it doesn't get comment
187 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
188 return {};
189 }
190 // TODO: handle comments for function parameters properly.
191 if (isa<ParmVarDecl>(Val: D))
192 return {};
193
194 // TODO: we could look up template parameter documentation in the template
195 // documentation.
196 if (isa<TemplateTypeParmDecl>(Val: D) ||
197 isa<NonTypeTemplateParmDecl>(Val: D) ||
198 isa<TemplateTemplateParmDecl>(Val: D))
199 return {};
200
201 SmallVector<SourceLocation, 2> Locations;
202 // Find declaration location.
203 // For Objective-C declarations we generally don't expect to have multiple
204 // declarators, thus use declaration starting location as the "declaration
205 // location".
206 // For all other declarations multiple declarators are used quite frequently,
207 // so we use the location of the identifier as the "declaration location".
208 SourceLocation BaseLocation;
209 if (isa<ObjCMethodDecl>(Val: D) || isa<ObjCContainerDecl>(Val: D) ||
210 isa<ObjCPropertyDecl>(Val: D) || isa<RedeclarableTemplateDecl>(Val: D) ||
211 isa<ClassTemplateSpecializationDecl>(Val: D) ||
212 // Allow association with Y across {} in `typedef struct X {} Y`.
213 isa<TypedefDecl>(Val: D))
214 BaseLocation = D->getBeginLoc();
215 else
216 BaseLocation = D->getLocation();
217
218 if (!D->getLocation().isMacroID()) {
219 Locations.emplace_back(Args&: BaseLocation);
220 } else {
221 const auto *DeclCtx = D->getDeclContext();
222
223 // When encountering definitions generated from a macro (that are not
224 // contained by another declaration in the macro) we need to try and find
225 // the comment at the location of the expansion but if there is no comment
226 // there we should retry to see if there is a comment inside the macro as
227 // well. To this end we return first BaseLocation to first look at the
228 // expansion site, the second value is the spelling location of the
229 // beginning of the declaration defined inside the macro.
230 if (!(DeclCtx &&
231 Decl::castFromDeclContext(DeclCtx)->getLocation().isMacroID())) {
232 Locations.emplace_back(Args: SourceMgr.getExpansionLoc(Loc: BaseLocation));
233 }
234
235 // We use Decl::getBeginLoc() and not just BaseLocation here to ensure that
236 // we don't refer to the macro argument location at the expansion site (this
237 // can happen if the name's spelling is provided via macro argument), and
238 // always to the declaration itself.
239 Locations.emplace_back(Args: SourceMgr.getSpellingLoc(Loc: D->getBeginLoc()));
240 }
241
242 return Locations;
243}
244
245RawComment *ASTContext::getRawCommentNoCacheImpl(
246 RawCommentLookupKey Key, const SourceLocation RepresentativeLoc,
247 const std::map<unsigned, RawComment *> &CommentsInTheFile) const {
248 // If the declaration doesn't map directly to a location in a file, we
249 // can't find the comment.
250 if (RepresentativeLoc.isInvalid() || !RepresentativeLoc.isFileID())
251 return nullptr;
252
253 // If there are no comments anywhere, we won't find anything.
254 if (CommentsInTheFile.empty())
255 return nullptr;
256
257 const auto *D = dyn_cast<const Decl *>(Val&: Key);
258 const bool IsMacro = isa<const MacroInfo *>(Val: Key);
259
260 // Decompose the location for the declaration and find the beginning of the
261 // file buffer.
262 const FileIDAndOffset LocDecomp =
263 SourceMgr.getDecomposedLoc(Loc: RepresentativeLoc);
264
265 // Slow path.
266 auto OffsetCommentBehindDecl =
267 CommentsInTheFile.lower_bound(x: LocDecomp.second);
268
269 // First check whether we have a trailing comment.
270 if (OffsetCommentBehindDecl != CommentsInTheFile.end()) {
271 RawComment *CommentBehindDecl = OffsetCommentBehindDecl->second;
272 if ((CommentBehindDecl->isDocumentation() ||
273 LangOpts.CommentOpts.ParseAllComments) &&
274 CommentBehindDecl->isTrailingComment() &&
275 (IsMacro || (D && (isa<FieldDecl>(Val: D) || isa<EnumConstantDecl>(Val: D) ||
276 isa<VarDecl>(Val: D) || isa<ObjCMethodDecl>(Val: D) ||
277 isa<ObjCPropertyDecl>(Val: D))))) {
278
279 // Check that Doxygen trailing comment comes after the declaration, starts
280 // on the same line and in the same file as the declaration.
281 if (SourceMgr.getLineNumber(FID: LocDecomp.first, FilePos: LocDecomp.second) ==
282 Comments.getCommentBeginLine(C: CommentBehindDecl, File: LocDecomp.first,
283 Offset: OffsetCommentBehindDecl->first)) {
284 return CommentBehindDecl;
285 }
286 }
287 }
288
289 // The comment just after the declaration was not a trailing comment.
290 // Let's look at the previous comment.
291 if (OffsetCommentBehindDecl == CommentsInTheFile.begin())
292 return nullptr;
293
294 auto OffsetCommentBeforeDecl = --OffsetCommentBehindDecl;
295 RawComment *CommentBeforeDecl = OffsetCommentBeforeDecl->second;
296
297 // Check that we actually have a non-member Doxygen comment.
298 if (!(CommentBeforeDecl->isDocumentation() ||
299 LangOpts.CommentOpts.ParseAllComments) ||
300 CommentBeforeDecl->isTrailingComment())
301 return nullptr;
302
303 // Decompose the end of the comment.
304 const unsigned CommentEndOffset =
305 Comments.getCommentEndOffset(C: CommentBeforeDecl);
306
307 // Get the corresponding buffer.
308 bool Invalid = false;
309 const char *Buffer =
310 SourceMgr.getBufferData(FID: LocDecomp.first, Invalid: &Invalid).data();
311 if (Invalid)
312 return nullptr;
313
314 // Extract text between the comment and declaration.
315 StringRef Text(Buffer + CommentEndOffset,
316 LocDecomp.second - CommentEndOffset);
317
318 // There should be no other declarations or preprocessor directives between
319 // comment and declaration.
320 if (Text.find_last_of(Chars: ";{}#@") != StringRef::npos)
321 return nullptr;
322
323 return CommentBeforeDecl;
324}
325
326RawComment *ASTContext::getRawCommentNoCache(RawCommentLookupKey Key) const {
327 const auto Locs = getLocsForCommentSearch(Key, SourceMgr);
328
329 for (const auto Loc : Locs) {
330 // If the declaration or macro doesn't map directly to a location in a file,
331 // we can't find the comment.
332 if (Loc.isInvalid() || !Loc.isFileID())
333 continue;
334
335 if (ExternalSource && !CommentsLoaded) {
336 ExternalSource->ReadComments();
337 CommentsLoaded = true;
338 }
339
340 if (Comments.empty())
341 continue;
342
343 const FileID File = SourceMgr.getDecomposedLoc(Loc).first;
344 if (!File.isValid())
345 continue;
346
347 const auto CommentsInThisFile = Comments.getCommentsInFile(File);
348 if (!CommentsInThisFile || CommentsInThisFile->empty())
349 continue;
350
351 if (RawComment *Comment =
352 getRawCommentNoCacheImpl(Key, RepresentativeLoc: Loc, CommentsInTheFile: *CommentsInThisFile))
353 return Comment;
354 }
355
356 return nullptr;
357}
358
359void ASTContext::addComment(const RawComment &RC) {
360 assert(LangOpts.CommentOpts.RetainCommentsFromSystemHeaders ||
361 !SourceMgr.isInSystemHeader(RC.getSourceRange().getBegin()));
362 Comments.addComment(RC, CommentOpts: LangOpts.CommentOpts, Allocator&: BumpAlloc);
363}
364
365const RawComment *
366ASTContext::getRawCommentForAnyRedecl(RawCommentLookupKey Key,
367 const Decl **OriginalDecl) const {
368 if (Key.isNull()) {
369 if (OriginalDecl)
370 *OriginalDecl = nullptr;
371 return nullptr;
372 }
373
374 // Macros have no redeclaration chain: look up directly, populate the cache,
375 // and return.
376 if (const auto *MI = dyn_cast<const MacroInfo *>(Val&: Key)) {
377 if (OriginalDecl)
378 *OriginalDecl = nullptr;
379 auto Existing = RawComments.find(Val: Key);
380 if (Existing != RawComments.end())
381 return Existing->second;
382 if (const RawComment *RC = getRawCommentNoCache(Key)) {
383 cacheRawComment(Original: MI, Comment: *RC);
384 return RC;
385 }
386 return nullptr;
387 }
388
389 const Decl *D = cast<const Decl *>(Val&: Key);
390 D = &adjustDeclToTemplate(D: *D);
391
392 // Any comment directly attached to D?
393 {
394 auto DeclComment = RawComments.find(Val: D);
395 if (DeclComment != RawComments.end()) {
396 if (OriginalDecl)
397 *OriginalDecl = D;
398 return DeclComment->second;
399 }
400 }
401
402 // Any comment attached to any redeclaration of D?
403 const Decl *CanonicalD = D->getCanonicalDecl();
404 if (!CanonicalD)
405 return nullptr;
406
407 {
408 auto RedeclComment = RedeclChainComments.find(Val: CanonicalD);
409 if (RedeclComment != RedeclChainComments.end()) {
410 if (OriginalDecl)
411 *OriginalDecl = RedeclComment->second;
412 auto CommentAtRedecl = RawComments.find(Val: RedeclComment->second);
413 assert(CommentAtRedecl != RawComments.end() &&
414 "This decl is supposed to have comment attached.");
415 return CommentAtRedecl->second;
416 }
417 }
418
419 // Any redeclarations of D that we haven't checked for comments yet?
420 const Decl *LastCheckedRedecl = [&]() {
421 const Decl *LastChecked = CommentlessRedeclChains.lookup(Val: CanonicalD);
422 bool CanUseCommentlessCache = false;
423 if (LastChecked) {
424 for (auto *Redecl : CanonicalD->redecls()) {
425 if (Redecl == D) {
426 CanUseCommentlessCache = true;
427 break;
428 }
429 if (Redecl == LastChecked)
430 break;
431 }
432 }
433 // FIXME: This could be improved so that even if CanUseCommentlessCache
434 // is false, once we've traversed past CanonicalD we still skip ahead
435 // LastChecked.
436 return CanUseCommentlessCache ? LastChecked : nullptr;
437 }();
438
439 for (const Decl *Redecl : D->redecls()) {
440 assert(Redecl);
441 // Skip all redeclarations that have been checked previously.
442 if (LastCheckedRedecl) {
443 if (LastCheckedRedecl == Redecl) {
444 LastCheckedRedecl = nullptr;
445 }
446 continue;
447 }
448 const RawComment *RedeclComment = getRawCommentNoCache(Key: Redecl);
449 if (RedeclComment) {
450 cacheRawComment(Original: Redecl, Comment: *RedeclComment);
451 if (OriginalDecl)
452 *OriginalDecl = Redecl;
453 return RedeclComment;
454 }
455 CommentlessRedeclChains[CanonicalD] = Redecl;
456 }
457
458 if (OriginalDecl)
459 *OriginalDecl = nullptr;
460 return nullptr;
461}
462
463void ASTContext::cacheRawComment(RawCommentLookupKey Original,
464 const RawComment &Comment) const {
465 assert(Comment.isDocumentation() || LangOpts.CommentOpts.ParseAllComments);
466 RawComments.try_emplace(Key: Original, Args: &Comment);
467 if (const auto *D = dyn_cast<const Decl *>(Val&: Original)) {
468 const Decl *const CanonicalDecl = D->getCanonicalDecl();
469 RedeclChainComments.try_emplace(Key: CanonicalDecl, Args&: D);
470 CommentlessRedeclChains.erase(Val: CanonicalDecl);
471 }
472}
473
474static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
475 SmallVectorImpl<const NamedDecl *> &Redeclared) {
476 const DeclContext *DC = ObjCMethod->getDeclContext();
477 if (const auto *IMD = dyn_cast<ObjCImplDecl>(Val: DC)) {
478 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
479 if (!ID)
480 return;
481 // Add redeclared method here.
482 for (const auto *Ext : ID->known_extensions()) {
483 if (ObjCMethodDecl *RedeclaredMethod =
484 Ext->getMethod(Sel: ObjCMethod->getSelector(),
485 isInstance: ObjCMethod->isInstanceMethod()))
486 Redeclared.push_back(Elt: RedeclaredMethod);
487 }
488 }
489}
490
491void ASTContext::attachCommentsToJustParsedDecls(ArrayRef<Decl *> Decls,
492 const Preprocessor *PP) {
493 if (Comments.empty() || Decls.empty())
494 return;
495
496 FileID File;
497 for (const Decl *D : Decls) {
498 if (D->isInvalidDecl())
499 continue;
500
501 D = &adjustDeclToTemplate(D: *D);
502 SourceLocation Loc = D->getLocation();
503 if (Loc.isValid()) {
504 // See if there are any new comments that are not attached to a decl.
505 // The location doesn't have to be precise - we care only about the file.
506 File = SourceMgr.getDecomposedLoc(Loc).first;
507 break;
508 }
509 }
510
511 if (File.isInvalid())
512 return;
513
514 auto CommentsInThisFile = Comments.getCommentsInFile(File);
515 if (!CommentsInThisFile || CommentsInThisFile->empty() ||
516 CommentsInThisFile->rbegin()->second->isAttached())
517 return;
518
519 // There is at least one comment not attached to a decl.
520 // Maybe it should be attached to one of Decls?
521 //
522 // Note that this way we pick up not only comments that precede the
523 // declaration, but also comments that *follow* the declaration -- thanks to
524 // the lookahead in the lexer: we've consumed the semicolon and looked
525 // ahead through comments.
526 for (const Decl *D : Decls) {
527 assert(D);
528 if (D->isInvalidDecl())
529 continue;
530
531 D = &adjustDeclToTemplate(D: *D);
532
533 if (RawComments.count(Val: D) > 0)
534 continue;
535
536 const auto DeclLocs = getLocsForCommentSearch(Key: D, SourceMgr);
537
538 for (const auto DeclLoc : DeclLocs) {
539 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
540 continue;
541
542 if (RawComment *const DocComment =
543 getRawCommentNoCacheImpl(Key: D, RepresentativeLoc: DeclLoc, CommentsInTheFile: *CommentsInThisFile)) {
544 cacheRawComment(Original: D, Comment: *DocComment);
545 comments::FullComment *FC = DocComment->parse(Context: *this, PP, D);
546 ParsedComments[D->getCanonicalDecl()] = FC;
547 break;
548 }
549 }
550 }
551}
552
553comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
554 const Decl *D) const {
555 auto *ThisDeclInfo = new (*this) comments::DeclInfo;
556 ThisDeclInfo->CommentDecl = D;
557 ThisDeclInfo->IsFilled = false;
558 ThisDeclInfo->fill();
559 ThisDeclInfo->CommentDecl = FC->getDecl();
560 if (!ThisDeclInfo->TemplateParameters)
561 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
562 comments::FullComment *CFC =
563 new (*this) comments::FullComment(FC->getBlocks(),
564 ThisDeclInfo);
565 return CFC;
566}
567
568comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
569 const RawComment *RC = getRawCommentNoCache(Key: D);
570 return RC ? RC->parse(Context: *this, PP: nullptr, D) : nullptr;
571}
572
573comments::FullComment *ASTContext::getCommentForDecl(
574 const Decl *D,
575 const Preprocessor *PP) const {
576 if (!D || D->isInvalidDecl())
577 return nullptr;
578 D = &adjustDeclToTemplate(D: *D);
579
580 const Decl *Canonical = D->getCanonicalDecl();
581 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
582 ParsedComments.find(Val: Canonical);
583
584 if (Pos != ParsedComments.end()) {
585 if (Canonical != D) {
586 comments::FullComment *FC = Pos->second;
587 comments::FullComment *CFC = cloneFullComment(FC, D);
588 return CFC;
589 }
590 return Pos->second;
591 }
592
593 const Decl *OriginalDecl = nullptr;
594
595 const RawComment *RC = getRawCommentForAnyRedecl(Key: D, OriginalDecl: &OriginalDecl);
596 if (!RC) {
597 if (isa<ObjCMethodDecl>(Val: D) || isa<FunctionDecl>(Val: D)) {
598 SmallVector<const NamedDecl*, 8> Overridden;
599 const auto *OMD = dyn_cast<ObjCMethodDecl>(Val: D);
600 if (OMD && OMD->isPropertyAccessor())
601 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
602 if (comments::FullComment *FC = getCommentForDecl(D: PDecl, PP))
603 return cloneFullComment(FC, D);
604 if (OMD)
605 addRedeclaredMethods(ObjCMethod: OMD, Redeclared&: Overridden);
606 getOverriddenMethods(Method: dyn_cast<NamedDecl>(Val: D), Overridden);
607 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
608 if (comments::FullComment *FC = getCommentForDecl(D: Overridden[i], PP))
609 return cloneFullComment(FC, D);
610 }
611 else if (const auto *TD = dyn_cast<TypedefNameDecl>(Val: D)) {
612 // Attach any tag type's documentation to its typedef if latter
613 // does not have one of its own.
614 QualType QT = TD->getUnderlyingType();
615 if (const auto *TT = QT->getAs<TagType>())
616 if (comments::FullComment *FC = getCommentForDecl(D: TT->getDecl(), PP))
617 return cloneFullComment(FC, D);
618 }
619 else if (const auto *IC = dyn_cast<ObjCInterfaceDecl>(Val: D)) {
620 while (IC->getSuperClass()) {
621 IC = IC->getSuperClass();
622 if (comments::FullComment *FC = getCommentForDecl(D: IC, PP))
623 return cloneFullComment(FC, D);
624 }
625 }
626 else if (const auto *CD = dyn_cast<ObjCCategoryDecl>(Val: D)) {
627 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
628 if (comments::FullComment *FC = getCommentForDecl(D: IC, PP))
629 return cloneFullComment(FC, D);
630 }
631 else if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: D)) {
632 if (!(RD = RD->getDefinition()))
633 return nullptr;
634 // Check non-virtual bases.
635 for (const auto &I : RD->bases()) {
636 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
637 continue;
638 QualType Ty = I.getType();
639 if (Ty.isNull())
640 continue;
641 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
642 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
643 continue;
644
645 if (comments::FullComment *FC = getCommentForDecl(D: (NonVirtualBase), PP))
646 return cloneFullComment(FC, D);
647 }
648 }
649 // Check virtual bases.
650 for (const auto &I : RD->vbases()) {
651 if (I.getAccessSpecifier() != AS_public)
652 continue;
653 QualType Ty = I.getType();
654 if (Ty.isNull())
655 continue;
656 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
657 if (!(VirtualBase= VirtualBase->getDefinition()))
658 continue;
659 if (comments::FullComment *FC = getCommentForDecl(D: (VirtualBase), PP))
660 return cloneFullComment(FC, D);
661 }
662 }
663 }
664 return nullptr;
665 }
666
667 // If the RawComment was attached to other redeclaration of this Decl, we
668 // should parse the comment in context of that other Decl. This is important
669 // because comments can contain references to parameter names which can be
670 // different across redeclarations.
671 if (D != OriginalDecl && OriginalDecl)
672 return getCommentForDecl(D: OriginalDecl, PP);
673
674 comments::FullComment *FC = RC->parse(Context: *this, PP, D);
675 ParsedComments[Canonical] = FC;
676 return FC;
677}
678
679void ASTContext::CanonicalTemplateTemplateParm::Profile(
680 llvm::FoldingSetNodeID &ID, const ASTContext &C,
681 TemplateTemplateParmDecl *Parm) {
682 ID.AddInteger(I: Parm->getDepth());
683 ID.AddInteger(I: Parm->getPosition());
684 ID.AddBoolean(B: Parm->isParameterPack());
685 ID.AddInteger(I: Parm->templateParameterKind());
686
687 TemplateParameterList *Params = Parm->getTemplateParameters();
688 ID.AddInteger(I: Params->size());
689 for (TemplateParameterList::const_iterator P = Params->begin(),
690 PEnd = Params->end();
691 P != PEnd; ++P) {
692 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Val: *P)) {
693 ID.AddInteger(I: 0);
694 ID.AddBoolean(B: TTP->isParameterPack());
695 ID.AddInteger(
696 I: TTP->getNumExpansionParameters().toInternalRepresentation());
697 continue;
698 }
699
700 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: *P)) {
701 ID.AddInteger(I: 1);
702 ID.AddBoolean(B: NTTP->isParameterPack());
703 ID.AddPointer(Ptr: C.getUnconstrainedType(T: C.getCanonicalType(T: NTTP->getType()))
704 .getAsOpaquePtr());
705 if (NTTP->isExpandedParameterPack()) {
706 ID.AddBoolean(B: true);
707 ID.AddInteger(I: NTTP->getNumExpansionTypes());
708 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
709 QualType T = NTTP->getExpansionType(I);
710 ID.AddPointer(Ptr: T.getCanonicalType().getAsOpaquePtr());
711 }
712 } else
713 ID.AddBoolean(B: false);
714 continue;
715 }
716
717 auto *TTP = cast<TemplateTemplateParmDecl>(Val: *P);
718 ID.AddInteger(I: 2);
719 Profile(ID, C, Parm: TTP);
720 }
721}
722
723TemplateTemplateParmDecl *
724ASTContext::getCanonicalTemplateTemplateParmDecl(
725 TemplateTemplateParmDecl *TTP) const {
726 // Check if we already have a canonical template template parameter.
727 llvm::FoldingSetNodeID ID;
728 CanonicalTemplateTemplateParm::Profile(ID, C: *this, Parm: TTP);
729 llvm::FoldingSetInsertToken Token;
730 CanonicalTemplateTemplateParm *Canonical =
731 CanonTemplateTemplateParms.lookup(ID, Token);
732 if (Canonical)
733 return Canonical->getParam();
734
735 // Build a canonical template parameter list.
736 TemplateParameterList *Params = TTP->getTemplateParameters();
737 SmallVector<NamedDecl *, 4> CanonParams;
738 CanonParams.reserve(N: Params->size());
739 for (TemplateParameterList::const_iterator P = Params->begin(),
740 PEnd = Params->end();
741 P != PEnd; ++P) {
742 // Note that, per C++20 [temp.over.link]/6, when determining whether
743 // template-parameters are equivalent, constraints are ignored.
744 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Val: *P)) {
745 TemplateTypeParmDecl *NewTTP = TemplateTypeParmDecl::Create(
746 C: *this, DC: getTranslationUnitDecl(), KeyLoc: SourceLocation(), NameLoc: SourceLocation(),
747 D: TTP->getDepth(), P: TTP->getIndex(), Id: nullptr, Typename: false,
748 ParameterPack: TTP->isParameterPack(), /*HasTypeConstraint=*/false,
749 NumExpanded: TTP->getNumExpansionParameters());
750 CanonParams.push_back(Elt: NewTTP);
751 } else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: *P)) {
752 QualType T = getUnconstrainedType(T: getCanonicalType(T: NTTP->getType()));
753 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
754 NonTypeTemplateParmDecl *Param;
755 if (NTTP->isExpandedParameterPack()) {
756 SmallVector<QualType, 2> ExpandedTypes;
757 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
758 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
759 ExpandedTypes.push_back(Elt: getCanonicalType(T: NTTP->getExpansionType(I)));
760 ExpandedTInfos.push_back(
761 Elt: getTrivialTypeSourceInfo(T: ExpandedTypes.back()));
762 }
763
764 Param = NonTypeTemplateParmDecl::Create(C: *this, DC: getTranslationUnitDecl(),
765 StartLoc: SourceLocation(),
766 IdLoc: SourceLocation(),
767 D: NTTP->getDepth(),
768 P: NTTP->getPosition(), Id: nullptr,
769 T,
770 TInfo,
771 ExpandedTypes,
772 ExpandedTInfos);
773 } else {
774 Param = NonTypeTemplateParmDecl::Create(C: *this, DC: getTranslationUnitDecl(),
775 StartLoc: SourceLocation(),
776 IdLoc: SourceLocation(),
777 D: NTTP->getDepth(),
778 P: NTTP->getPosition(), Id: nullptr,
779 T,
780 ParameterPack: NTTP->isParameterPack(),
781 TInfo);
782 }
783 CanonParams.push_back(Elt: Param);
784 } else
785 CanonParams.push_back(Elt: getCanonicalTemplateTemplateParmDecl(
786 TTP: cast<TemplateTemplateParmDecl>(Val: *P)));
787 }
788
789 TemplateTemplateParmDecl *CanonTTP = TemplateTemplateParmDecl::Create(
790 C: *this, DC: getTranslationUnitDecl(), L: SourceLocation(), D: TTP->getDepth(),
791 P: TTP->getPosition(), ParameterPack: TTP->isParameterPack(), Id: nullptr,
792 ParameterKind: TTP->templateParameterKind(),
793 /*Typename=*/false,
794 Params: TemplateParameterList::Create(C: *this, TemplateLoc: SourceLocation(), LAngleLoc: SourceLocation(),
795 Params: CanonParams, RAngleLoc: SourceLocation(),
796 /*RequiresClause=*/nullptr));
797
798 // Get the new insert position for the node we care about.
799 Canonical = CanonTemplateTemplateParms.lookup(ID, Token);
800 assert(!Canonical && "Shouldn't be in the map!");
801 (void)Canonical;
802
803 // Create the canonical template template parameter entry.
804 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
805 CanonTemplateTemplateParms.insert(N: Canonical, Token);
806 return CanonTTP;
807}
808
809TemplateTemplateParmDecl *
810ASTContext::findCanonicalTemplateTemplateParmDeclInternal(
811 TemplateTemplateParmDecl *TTP) const {
812 llvm::FoldingSetNodeID ID;
813 CanonicalTemplateTemplateParm::Profile(ID, C: *this, Parm: TTP);
814 llvm::FoldingSetInsertToken Token;
815 CanonicalTemplateTemplateParm *Canonical =
816 CanonTemplateTemplateParms.lookup(ID, Token);
817 return Canonical ? Canonical->getParam() : nullptr;
818}
819
820TemplateTemplateParmDecl *
821ASTContext::insertCanonicalTemplateTemplateParmDeclInternal(
822 TemplateTemplateParmDecl *CanonTTP) const {
823 llvm::FoldingSetNodeID ID;
824 CanonicalTemplateTemplateParm::Profile(ID, C: *this, Parm: CanonTTP);
825 llvm::FoldingSetInsertToken Token;
826 if (auto *Existing = CanonTemplateTemplateParms.lookup(ID, Token))
827 return Existing->getParam();
828 CanonTemplateTemplateParms.insert(
829 N: new (*this) CanonicalTemplateTemplateParm(CanonTTP), Token);
830 return CanonTTP;
831}
832
833/// For the purposes of overflow pattern exclusion, does this match the
834/// while(i--) pattern?
835static bool matchesPostDecrInWhile(const UnaryOperator *UO, ASTContext &Ctx) {
836 if (UO->getOpcode() != UO_PostDec)
837 return false;
838
839 if (!UO->getType()->isUnsignedIntegerType())
840 return false;
841
842 // -fsanitize-undefined-ignore-overflow-pattern=unsigned-post-decr-while
843 if (!Ctx.getLangOpts().isOverflowPatternExcluded(
844 Kind: LangOptions::OverflowPatternExclusionKind::PostDecrInWhile))
845 return false;
846
847 // all Parents (usually just one) must be a WhileStmt
848 return llvm::all_of(
849 Range: Ctx.getParentMapContext().getParents(Node: *UO),
850 P: [](const DynTypedNode &P) { return P.get<WhileStmt>() != nullptr; });
851}
852
853bool ASTContext::isUnaryOverflowPatternExcluded(const UnaryOperator *UO) {
854 // -fsanitize-undefined-ignore-overflow-pattern=negated-unsigned-const
855 // ... like -1UL;
856 if (UO->getOpcode() == UO_Minus &&
857 getLangOpts().isOverflowPatternExcluded(
858 Kind: LangOptions::OverflowPatternExclusionKind::NegUnsignedConst) &&
859 UO->isIntegerConstantExpr(Ctx: *this)) {
860 return true;
861 }
862
863 if (matchesPostDecrInWhile(UO, Ctx&: *this))
864 return true;
865
866 return false;
867}
868
869/// Check if a type can have its sanitizer instrumentation elided based on its
870/// presence within an ignorelist.
871bool ASTContext::isTypeIgnoredBySanitizer(const SanitizerMask &Mask,
872 const QualType &Ty) const {
873 std::string TyName = Ty.getUnqualifiedType().getAsString(Policy: getPrintingPolicy());
874 return NoSanitizeL->containsType(Mask, MangledTypeName: TyName);
875}
876
877TargetCXXABI::Kind ASTContext::getCXXABIKind() const {
878 auto Kind = getTargetInfo().getCXXABI().getKind();
879 return getLangOpts().CXXABI.value_or(u&: Kind);
880}
881
882CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
883 if (!LangOpts.CPlusPlus) return nullptr;
884
885 switch (getCXXABIKind()) {
886 case TargetCXXABI::AppleARM64:
887 case TargetCXXABI::Fuchsia:
888 case TargetCXXABI::GenericARM: // Same as Itanium at this level
889 case TargetCXXABI::iOS:
890 case TargetCXXABI::WatchOS:
891 case TargetCXXABI::GenericAArch64:
892 case TargetCXXABI::GenericMIPS:
893 case TargetCXXABI::GenericItanium:
894 case TargetCXXABI::WebAssembly:
895 case TargetCXXABI::XL:
896 return CreateItaniumCXXABI(Ctx&: *this);
897 case TargetCXXABI::Microsoft:
898 return CreateMicrosoftCXXABI(Ctx&: *this);
899 }
900 llvm_unreachable("Invalid CXXABI type!");
901}
902
903interp::Context &ASTContext::getInterpContext() const {
904 if (!InterpContext) {
905 InterpContext.reset(p: new interp::Context(const_cast<ASTContext &>(*this)));
906 }
907 return *InterpContext;
908}
909
910static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
911 const LangOptions &LangOpts) {
912 switch (LangOpts.getAddressSpaceMapMangling()) {
913 case LangOptions::ASMM_Target:
914 return TI.useAddressSpaceMapMangling();
915 case LangOptions::ASMM_On:
916 return true;
917 case LangOptions::ASMM_Off:
918 return false;
919 }
920 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
921}
922
923ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
924 IdentifierTable &idents, SelectorTable &sels,
925 Builtin::Context &builtins, TranslationUnitKind TUKind)
926 : ConstantArrayTypes(this_(), ConstantArrayTypesLog2InitSize),
927 DependentSizedArrayTypes(this_()), DependentSizedExtVectorTypes(this_()),
928 DependentAddressSpaceTypes(this_()), DependentVectorTypes(this_()),
929 DependentSizedMatrixTypes(this_()),
930 FunctionProtoTypes(this_(), FunctionProtoTypesLog2InitSize),
931 DependentTypeOfExprTypes(this_()), DependentDecltypeTypes(this_()),
932 DependentPackIndexingTypes(this_()), TemplateSpecializationTypes(this_()),
933 AttributedTypes(this_()), DependentBitIntTypes(this_()),
934 HLSLAttributedResourceTypes(this_()),
935 SubstTemplateTemplateParmPacks(this_()), DeducedTemplates(this_()),
936 PackIndexingTemplates(this_()), ArrayParameterTypes(this_()),
937 CanonTemplateTemplateParms(this_()), SourceMgr(SM), LangOpts(LOpts),
938 NoSanitizeL(new NoSanitizeList(LangOpts.NoSanitizeFiles, SM)),
939 XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles,
940 LangOpts.XRayNeverInstrumentFiles,
941 LangOpts.XRayAttrListFiles, SM)),
942 ProfList(new ProfileList(LangOpts.ProfileListFiles, SM)),
943 PrintingPolicy(LOpts), ParentMapCtx(new ParentMapContext(*this)),
944 Idents(idents), Selectors(sels), BuiltinInfo(builtins), TUKind(TUKind),
945 DeclarationNames(*this), Comments(SM),
946 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
947 CompCategories(this_()), LastSDM(nullptr, 0) {
948 addTranslationUnitDecl();
949}
950
951void ASTContext::cleanup() {
952 // Release the DenseMaps associated with DeclContext objects.
953 // FIXME: Is this the ideal solution?
954 ReleaseDeclContextMaps();
955
956 // Call all of the deallocation functions on all of their targets.
957 for (auto &Pair : Deallocations)
958 (Pair.first)(Pair.second);
959 Deallocations.clear();
960
961 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
962 // because they can contain DenseMaps.
963 for (llvm::DenseMap<const ObjCInterfaceDecl *,
964 const ASTRecordLayout *>::iterator
965 I = ObjCLayouts.begin(),
966 E = ObjCLayouts.end();
967 I != E;)
968 // Increment in loop to prevent using deallocated memory.
969 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
970 R->Destroy(Ctx&: *this);
971 ObjCLayouts.clear();
972
973 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
974 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
975 // Increment in loop to prevent using deallocated memory.
976 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
977 R->Destroy(Ctx&: *this);
978 }
979 ASTRecordLayouts.clear();
980
981 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
982 AEnd = DeclAttrs.end();
983 A != AEnd; ++A)
984 A->second->~AttrVec();
985 DeclAttrs.clear();
986 LastDeclAttrsDecl = nullptr;
987
988 CtorClosureDefaultArgs.clear();
989
990 for (const auto &Value : ModuleInitializers)
991 Value.second->~PerModuleInitializers();
992 ModuleInitializers.clear();
993
994 TUDecl = nullptr;
995 XRayFilter.reset();
996 NoSanitizeL.reset();
997}
998
999ASTContext::~ASTContext() { cleanup(); }
1000
1001void ASTContext::setTraversalScope(const std::vector<Decl *> &TopLevelDecls) {
1002 TraversalScope = TopLevelDecls;
1003 getParentMapContext().clear();
1004}
1005
1006void ASTContext::AddDeallocation(void (*Callback)(void *), void *Data) const {
1007 Deallocations.push_back(Elt: {Callback, Data});
1008}
1009
1010void
1011ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
1012 ExternalSource = std::move(Source);
1013}
1014
1015void ASTContext::PrintStats() const {
1016 llvm::errs() << "\n*** AST Context Stats:\n";
1017 llvm::errs() << " " << Types.size() << " types total.\n";
1018
1019 unsigned counts[] = {
1020#define TYPE(Name, Parent) 0,
1021#define ABSTRACT_TYPE(Name, Parent)
1022#include "clang/AST/TypeNodes.inc"
1023 0 // Extra
1024 };
1025
1026 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
1027 Type *T = Types[i];
1028 counts[(unsigned)T->getTypeClass()]++;
1029 }
1030
1031 unsigned Idx = 0;
1032 unsigned TotalBytes = 0;
1033#define TYPE(Name, Parent) \
1034 if (counts[Idx]) \
1035 llvm::errs() << " " << counts[Idx] << " " << #Name \
1036 << " types, " << sizeof(Name##Type) << " each " \
1037 << "(" << counts[Idx] * sizeof(Name##Type) \
1038 << " bytes)\n"; \
1039 TotalBytes += counts[Idx] * sizeof(Name##Type); \
1040 ++Idx;
1041#define ABSTRACT_TYPE(Name, Parent)
1042#include "clang/AST/TypeNodes.inc"
1043
1044 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
1045
1046 // Implicit special member functions.
1047 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
1048 << NumImplicitDefaultConstructors
1049 << " implicit default constructors created\n";
1050 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
1051 << NumImplicitCopyConstructors
1052 << " implicit copy constructors created\n";
1053 if (getLangOpts().CPlusPlus)
1054 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
1055 << NumImplicitMoveConstructors
1056 << " implicit move constructors created\n";
1057 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
1058 << NumImplicitCopyAssignmentOperators
1059 << " implicit copy assignment operators created\n";
1060 if (getLangOpts().CPlusPlus)
1061 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
1062 << NumImplicitMoveAssignmentOperators
1063 << " implicit move assignment operators created\n";
1064 llvm::errs() << NumImplicitDestructorsDeclared << "/"
1065 << NumImplicitDestructors
1066 << " implicit destructors created\n";
1067
1068 if (ExternalSource) {
1069 llvm::errs() << "\n";
1070 ExternalSource->PrintStats();
1071 }
1072
1073 BumpAlloc.PrintStats();
1074}
1075
1076void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
1077 bool NotifyListeners) {
1078 if (NotifyListeners)
1079 if (auto *Listener = getASTMutationListener();
1080 Listener && !ND->isUnconditionallyVisible())
1081 Listener->RedefinedHiddenDefinition(D: ND, M);
1082
1083 MergedDefModules[cast<NamedDecl>(Val: ND->getCanonicalDecl())].push_back(NewVal: M);
1084}
1085
1086void ASTContext::deduplicateMergedDefinitionsFor(NamedDecl *ND) {
1087 auto It = MergedDefModules.find(Val: cast<NamedDecl>(Val: ND->getCanonicalDecl()));
1088 if (It == MergedDefModules.end())
1089 return;
1090
1091 auto &Merged = It->second;
1092 llvm::DenseSet<Module*> Found;
1093 for (Module *&M : Merged)
1094 if (!Found.insert(V: M).second)
1095 M = nullptr;
1096 llvm::erase(C&: Merged, V: nullptr);
1097}
1098
1099ArrayRef<Module *>
1100ASTContext::getModulesWithMergedDefinition(const NamedDecl *Def) {
1101 auto MergedIt =
1102 MergedDefModules.find(Val: cast<NamedDecl>(Val: Def->getCanonicalDecl()));
1103 if (MergedIt == MergedDefModules.end())
1104 return {};
1105 return MergedIt->second;
1106}
1107
1108void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
1109 if (LazyInitializers.empty())
1110 return;
1111
1112 auto *Source = Ctx.getExternalSource();
1113 assert(Source && "lazy initializers but no external source");
1114
1115 auto LazyInits = std::move(LazyInitializers);
1116 LazyInitializers.clear();
1117
1118 for (auto ID : LazyInits)
1119 Initializers.push_back(Elt: Source->GetExternalDecl(ID));
1120
1121 assert(LazyInitializers.empty() &&
1122 "GetExternalDecl for lazy module initializer added more inits");
1123}
1124
1125void ASTContext::addModuleInitializer(Module *M, Decl *D) {
1126 // One special case: if we add a module initializer that imports another
1127 // module, and that module's only initializer is an ImportDecl, simplify.
1128 if (const auto *ID = dyn_cast<ImportDecl>(Val: D)) {
1129 auto It = ModuleInitializers.find(Val: ID->getImportedModule());
1130
1131 // Maybe the ImportDecl does nothing at all. (Common case.)
1132 if (It == ModuleInitializers.end())
1133 return;
1134
1135 // Maybe the ImportDecl only imports another ImportDecl.
1136 auto &Imported = *It->second;
1137 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
1138 Imported.resolve(Ctx&: *this);
1139 auto *OnlyDecl = Imported.Initializers.front();
1140 if (isa<ImportDecl>(Val: OnlyDecl))
1141 D = OnlyDecl;
1142 }
1143 }
1144
1145 auto *&Inits = ModuleInitializers[M];
1146 if (!Inits)
1147 Inits = new (*this) PerModuleInitializers;
1148 Inits->Initializers.push_back(Elt: D);
1149}
1150
1151void ASTContext::addLazyModuleInitializers(Module *M,
1152 ArrayRef<GlobalDeclID> IDs) {
1153 auto *&Inits = ModuleInitializers[M];
1154 if (!Inits)
1155 Inits = new (*this) PerModuleInitializers;
1156 Inits->LazyInitializers.insert(I: Inits->LazyInitializers.end(),
1157 From: IDs.begin(), To: IDs.end());
1158}
1159
1160ArrayRef<Decl *> ASTContext::getModuleInitializers(Module *M) {
1161 auto It = ModuleInitializers.find(Val: M);
1162 if (It == ModuleInitializers.end())
1163 return {};
1164
1165 auto *Inits = It->second;
1166 Inits->resolve(Ctx&: *this);
1167 return Inits->Initializers;
1168}
1169
1170void ASTContext::setCurrentNamedModule(Module *M) {
1171 assert(M->isNamedModule());
1172 assert(!CurrentCXXNamedModule &&
1173 "We should set named module for ASTContext for only once");
1174 CurrentCXXNamedModule = M;
1175}
1176
1177bool ASTContext::isInSameModule(const Module *M1, const Module *M2) const {
1178 if (!M1 != !M2)
1179 return false;
1180
1181 /// Get the representative module for M. The representative module is the
1182 /// first module unit for a specific primary module name. So that the module
1183 /// units have the same representative module belongs to the same module.
1184 ///
1185 /// The process is helpful to reduce the expensive string operations.
1186 auto GetRepresentativeModule = [this](const Module *M) {
1187 auto Iter = SameModuleLookupSet.find(Val: M);
1188 if (Iter != SameModuleLookupSet.end())
1189 return Iter->second;
1190
1191 const Module *RepresentativeModule =
1192 PrimaryModuleNameMap.try_emplace(Key: M->getPrimaryModuleInterfaceName(), Args&: M)
1193 .first->second;
1194 SameModuleLookupSet[M] = RepresentativeModule;
1195 return RepresentativeModule;
1196 };
1197
1198 assert(M1 && "Shouldn't call `isInSameModule` if both M1 and M2 are none.");
1199 return GetRepresentativeModule(M1) == GetRepresentativeModule(M2);
1200}
1201
1202ExternCContextDecl *ASTContext::getExternCContextDecl() const {
1203 if (!ExternCContext)
1204 ExternCContext = ExternCContextDecl::Create(C: *this, TU: getTranslationUnitDecl());
1205
1206 return ExternCContext;
1207}
1208
1209BuiltinTemplateDecl *
1210ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
1211 const IdentifierInfo *II) const {
1212 auto *BuiltinTemplate =
1213 BuiltinTemplateDecl::Create(C: *this, DC: getTranslationUnitDecl(), Name: II, BTK);
1214 BuiltinTemplate->setImplicit();
1215 getTranslationUnitDecl()->addDecl(D: BuiltinTemplate);
1216
1217 return BuiltinTemplate;
1218}
1219
1220#define BuiltinTemplate(BTName) \
1221 BuiltinTemplateDecl *ASTContext::get##BTName##Decl() const { \
1222 if (!Decl##BTName) \
1223 Decl##BTName = \
1224 buildBuiltinTemplateDecl(BTK##BTName, get##BTName##Name()); \
1225 return Decl##BTName; \
1226 }
1227#include "clang/Basic/BuiltinTemplates.inc"
1228
1229RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
1230 RecordDecl::TagKind TK) const {
1231 SourceLocation Loc;
1232 RecordDecl *NewDecl;
1233 if (getLangOpts().CPlusPlus)
1234 NewDecl = CXXRecordDecl::Create(C: *this, TK, DC: getTranslationUnitDecl(), StartLoc: Loc,
1235 IdLoc: Loc, Id: &Idents.get(Name));
1236 else
1237 NewDecl = RecordDecl::Create(C: *this, TK, DC: getTranslationUnitDecl(), StartLoc: Loc, IdLoc: Loc,
1238 Id: &Idents.get(Name));
1239 NewDecl->setImplicit();
1240 NewDecl->addAttr(A: TypeVisibilityAttr::CreateImplicit(
1241 Ctx&: const_cast<ASTContext &>(*this), Visibility: TypeVisibilityAttr::Default));
1242 return NewDecl;
1243}
1244
1245TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
1246 StringRef Name) const {
1247 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
1248 TypedefDecl *NewDecl = TypedefDecl::Create(
1249 C&: const_cast<ASTContext &>(*this), DC: getTranslationUnitDecl(),
1250 StartLoc: SourceLocation(), IdLoc: SourceLocation(), Id: &Idents.get(Name), TInfo);
1251 NewDecl->setImplicit();
1252 return NewDecl;
1253}
1254
1255TypedefDecl *ASTContext::getInt128Decl() const {
1256 if (!Int128Decl)
1257 Int128Decl = buildImplicitTypedef(T: Int128Ty, Name: "__int128_t");
1258 return Int128Decl;
1259}
1260
1261TypedefDecl *ASTContext::getUInt128Decl() const {
1262 if (!UInt128Decl)
1263 UInt128Decl = buildImplicitTypedef(T: UnsignedInt128Ty, Name: "__uint128_t");
1264 return UInt128Decl;
1265}
1266
1267void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
1268 auto *Ty = new (*this, alignof(BuiltinType)) BuiltinType(K);
1269 R = CanQualType::CreateUnsafe(Other: QualType(Ty, 0));
1270 Types.push_back(Elt: Ty);
1271}
1272
1273void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
1274 const TargetInfo *AuxTarget) {
1275 assert((!this->Target || this->Target == &Target) &&
1276 "Incorrect target reinitialization");
1277 assert(VoidTy.isNull() && "Context reinitialized?");
1278
1279 this->Target = &Target;
1280 this->AuxTarget = AuxTarget;
1281
1282 ABI.reset(p: createCXXABI(T: Target));
1283 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(TI: Target, LangOpts);
1284
1285 // C99 6.2.5p19.
1286 InitBuiltinType(R&: VoidTy, K: BuiltinType::Void);
1287
1288 // C99 6.2.5p2.
1289 InitBuiltinType(R&: BoolTy, K: BuiltinType::Bool);
1290 // C99 6.2.5p3.
1291 if (LangOpts.CharIsSigned)
1292 InitBuiltinType(R&: CharTy, K: BuiltinType::Char_S);
1293 else
1294 InitBuiltinType(R&: CharTy, K: BuiltinType::Char_U);
1295 // C99 6.2.5p4.
1296 InitBuiltinType(R&: SignedCharTy, K: BuiltinType::SChar);
1297 InitBuiltinType(R&: ShortTy, K: BuiltinType::Short);
1298 InitBuiltinType(R&: IntTy, K: BuiltinType::Int);
1299 InitBuiltinType(R&: LongTy, K: BuiltinType::Long);
1300 InitBuiltinType(R&: LongLongTy, K: BuiltinType::LongLong);
1301
1302 // C99 6.2.5p6.
1303 InitBuiltinType(R&: UnsignedCharTy, K: BuiltinType::UChar);
1304 InitBuiltinType(R&: UnsignedShortTy, K: BuiltinType::UShort);
1305 InitBuiltinType(R&: UnsignedIntTy, K: BuiltinType::UInt);
1306 InitBuiltinType(R&: UnsignedLongTy, K: BuiltinType::ULong);
1307 InitBuiltinType(R&: UnsignedLongLongTy, K: BuiltinType::ULongLong);
1308
1309 // C99 6.2.5p10.
1310 InitBuiltinType(R&: FloatTy, K: BuiltinType::Float);
1311 InitBuiltinType(R&: DoubleTy, K: BuiltinType::Double);
1312 InitBuiltinType(R&: LongDoubleTy, K: BuiltinType::LongDouble);
1313
1314 // GNU extension, __float128 for IEEE quadruple precision
1315 InitBuiltinType(R&: Float128Ty, K: BuiltinType::Float128);
1316
1317 // __ibm128 for IBM extended precision
1318 InitBuiltinType(R&: Ibm128Ty, K: BuiltinType::Ibm128);
1319
1320 // C11 extension ISO/IEC TS 18661-3
1321 InitBuiltinType(R&: Float16Ty, K: BuiltinType::Float16);
1322
1323 // ISO/IEC JTC1 SC22 WG14 N1169 Extension
1324 InitBuiltinType(R&: ShortAccumTy, K: BuiltinType::ShortAccum);
1325 InitBuiltinType(R&: AccumTy, K: BuiltinType::Accum);
1326 InitBuiltinType(R&: LongAccumTy, K: BuiltinType::LongAccum);
1327 InitBuiltinType(R&: UnsignedShortAccumTy, K: BuiltinType::UShortAccum);
1328 InitBuiltinType(R&: UnsignedAccumTy, K: BuiltinType::UAccum);
1329 InitBuiltinType(R&: UnsignedLongAccumTy, K: BuiltinType::ULongAccum);
1330 InitBuiltinType(R&: ShortFractTy, K: BuiltinType::ShortFract);
1331 InitBuiltinType(R&: FractTy, K: BuiltinType::Fract);
1332 InitBuiltinType(R&: LongFractTy, K: BuiltinType::LongFract);
1333 InitBuiltinType(R&: UnsignedShortFractTy, K: BuiltinType::UShortFract);
1334 InitBuiltinType(R&: UnsignedFractTy, K: BuiltinType::UFract);
1335 InitBuiltinType(R&: UnsignedLongFractTy, K: BuiltinType::ULongFract);
1336 InitBuiltinType(R&: SatShortAccumTy, K: BuiltinType::SatShortAccum);
1337 InitBuiltinType(R&: SatAccumTy, K: BuiltinType::SatAccum);
1338 InitBuiltinType(R&: SatLongAccumTy, K: BuiltinType::SatLongAccum);
1339 InitBuiltinType(R&: SatUnsignedShortAccumTy, K: BuiltinType::SatUShortAccum);
1340 InitBuiltinType(R&: SatUnsignedAccumTy, K: BuiltinType::SatUAccum);
1341 InitBuiltinType(R&: SatUnsignedLongAccumTy, K: BuiltinType::SatULongAccum);
1342 InitBuiltinType(R&: SatShortFractTy, K: BuiltinType::SatShortFract);
1343 InitBuiltinType(R&: SatFractTy, K: BuiltinType::SatFract);
1344 InitBuiltinType(R&: SatLongFractTy, K: BuiltinType::SatLongFract);
1345 InitBuiltinType(R&: SatUnsignedShortFractTy, K: BuiltinType::SatUShortFract);
1346 InitBuiltinType(R&: SatUnsignedFractTy, K: BuiltinType::SatUFract);
1347 InitBuiltinType(R&: SatUnsignedLongFractTy, K: BuiltinType::SatULongFract);
1348
1349 // GNU extension, 128-bit integers.
1350 InitBuiltinType(R&: Int128Ty, K: BuiltinType::Int128);
1351 InitBuiltinType(R&: UnsignedInt128Ty, K: BuiltinType::UInt128);
1352
1353 // C++ 3.9.1p5
1354 if (TargetInfo::isTypeSigned(T: Target.getWCharType()))
1355 InitBuiltinType(R&: WCharTy, K: BuiltinType::WChar_S);
1356 else // -fshort-wchar makes wchar_t be unsigned.
1357 InitBuiltinType(R&: WCharTy, K: BuiltinType::WChar_U);
1358 if (LangOpts.CPlusPlus && LangOpts.WChar)
1359 WideCharTy = WCharTy;
1360 else {
1361 // C99 (or C++ using -fno-wchar).
1362 WideCharTy = getFromTargetType(Type: Target.getWCharType());
1363 }
1364
1365 WIntTy = getFromTargetType(Type: Target.getWIntType());
1366
1367 // C++20 (proposed)
1368 InitBuiltinType(R&: Char8Ty, K: BuiltinType::Char8);
1369
1370 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1371 InitBuiltinType(R&: Char16Ty, K: BuiltinType::Char16);
1372 else // C99
1373 Char16Ty = getFromTargetType(Type: Target.getChar16Type());
1374
1375 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1376 InitBuiltinType(R&: Char32Ty, K: BuiltinType::Char32);
1377 else // C99
1378 Char32Ty = getFromTargetType(Type: Target.getChar32Type());
1379
1380 // Placeholder type for type-dependent expressions whose type is
1381 // completely unknown. No code should ever check a type against
1382 // DependentTy and users should never see it; however, it is here to
1383 // help diagnose failures to properly check for type-dependent
1384 // expressions.
1385 InitBuiltinType(R&: DependentTy, K: BuiltinType::Dependent);
1386
1387 // Placeholder type for functions.
1388 InitBuiltinType(R&: OverloadTy, K: BuiltinType::Overload);
1389
1390 // Placeholder type for bound members.
1391 InitBuiltinType(R&: BoundMemberTy, K: BuiltinType::BoundMember);
1392
1393 // Placeholder type for unresolved templates.
1394 InitBuiltinType(R&: UnresolvedTemplateTy, K: BuiltinType::UnresolvedTemplate);
1395
1396 // Placeholder type for pseudo-objects.
1397 InitBuiltinType(R&: PseudoObjectTy, K: BuiltinType::PseudoObject);
1398
1399 // "any" type; useful for debugger-like clients.
1400 InitBuiltinType(R&: UnknownAnyTy, K: BuiltinType::UnknownAny);
1401
1402 // Placeholder type for unbridged ARC casts.
1403 InitBuiltinType(R&: ARCUnbridgedCastTy, K: BuiltinType::ARCUnbridgedCast);
1404
1405 // Placeholder type for builtin functions.
1406 InitBuiltinType(R&: BuiltinFnTy, K: BuiltinType::BuiltinFn);
1407
1408 // Placeholder type for OMP array sections.
1409 if (LangOpts.OpenMP) {
1410 InitBuiltinType(R&: ArraySectionTy, K: BuiltinType::ArraySection);
1411 InitBuiltinType(R&: OMPArrayShapingTy, K: BuiltinType::OMPArrayShaping);
1412 InitBuiltinType(R&: OMPIteratorTy, K: BuiltinType::OMPIterator);
1413 }
1414 // Placeholder type for OpenACC array sections, if we are ALSO in OMP mode,
1415 // don't bother, as we're just using the same type as OMP.
1416 if (LangOpts.OpenACC && !LangOpts.OpenMP) {
1417 InitBuiltinType(R&: ArraySectionTy, K: BuiltinType::ArraySection);
1418 }
1419 if (LangOpts.MatrixTypes)
1420 InitBuiltinType(R&: IncompleteMatrixIdxTy, K: BuiltinType::IncompleteMatrixIdx);
1421
1422 // Builtin types for 'id', 'Class', and 'SEL'.
1423 InitBuiltinType(R&: ObjCBuiltinIdTy, K: BuiltinType::ObjCId);
1424 InitBuiltinType(R&: ObjCBuiltinClassTy, K: BuiltinType::ObjCClass);
1425 InitBuiltinType(R&: ObjCBuiltinSelTy, K: BuiltinType::ObjCSel);
1426
1427 if (LangOpts.OpenCL) {
1428#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1429 InitBuiltinType(SingletonId, BuiltinType::Id);
1430#include "clang/Basic/OpenCLImageTypes.def"
1431
1432 InitBuiltinType(R&: OCLSamplerTy, K: BuiltinType::OCLSampler);
1433 InitBuiltinType(R&: OCLEventTy, K: BuiltinType::OCLEvent);
1434 InitBuiltinType(R&: OCLClkEventTy, K: BuiltinType::OCLClkEvent);
1435 InitBuiltinType(R&: OCLQueueTy, K: BuiltinType::OCLQueue);
1436 InitBuiltinType(R&: OCLReserveIDTy, K: BuiltinType::OCLReserveID);
1437
1438#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1439 InitBuiltinType(Id##Ty, BuiltinType::Id);
1440#include "clang/Basic/OpenCLExtensionTypes.def"
1441 }
1442
1443 if (LangOpts.HLSL) {
1444#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
1445 InitBuiltinType(SingletonId, BuiltinType::Id);
1446#include "clang/Basic/HLSLIntangibleTypes.def"
1447
1448#define HLSL_PACKED_TYPE(Name, Id, SingletonId) \
1449 InitBuiltinType(SingletonId, BuiltinType::Id);
1450#include "clang/Basic/HLSLPackedTypes.def"
1451 }
1452
1453 if (Target.hasAArch64ACLETypes() ||
1454 (AuxTarget && AuxTarget->hasAArch64ACLETypes())) {
1455#define SVE_TYPE(Name, Id, SingletonId) \
1456 InitBuiltinType(SingletonId, BuiltinType::Id);
1457#include "clang/Basic/AArch64ACLETypes.def"
1458 }
1459
1460 if (Target.getTriple().isPPC64()) {
1461#define PPC_VECTOR_MMA_TYPE(Name, Id, Size) \
1462 InitBuiltinType(Id##Ty, BuiltinType::Id);
1463#include "clang/Basic/PPCTypes.def"
1464#define PPC_VECTOR_VSX_TYPE(Name, Id, Size) \
1465 InitBuiltinType(Id##Ty, BuiltinType::Id);
1466#include "clang/Basic/PPCTypes.def"
1467 }
1468
1469 if (Target.hasRISCVVTypes()) {
1470#define RVV_TYPE(Name, Id, SingletonId) \
1471 InitBuiltinType(SingletonId, BuiltinType::Id);
1472#include "clang/Basic/RISCVVTypes.def"
1473 }
1474
1475 if (Target.getTriple().isWasm() && Target.hasFeature(Feature: "reference-types")) {
1476#define WASM_TYPE(Name, Id, SingletonId) \
1477 InitBuiltinType(SingletonId, BuiltinType::Id);
1478#include "clang/Basic/WebAssemblyReferenceTypes.def"
1479 }
1480
1481 if (Target.hasAMDGPUTypes() || (AuxTarget && (AuxTarget->hasAMDGPUTypes()))) {
1482#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) \
1483 InitBuiltinType(SingletonId, BuiltinType::Id);
1484#include "clang/Basic/AMDGPUTypes.def"
1485 }
1486
1487 if (Target.getTriple().isSPIRV() ||
1488 (AuxTarget && AuxTarget->getTriple().isSPIRV())) {
1489#define SPIRV_TYPE(Name, Id, SingletonId) \
1490 InitBuiltinType(SingletonId, BuiltinType::Id);
1491#include "clang/Basic/SPIRVTypes.def"
1492 }
1493
1494 // Builtin type for __objc_yes and __objc_no
1495 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1496 SignedCharTy : BoolTy);
1497
1498 ObjCConstantStringType = QualType();
1499
1500 ObjCSuperType = QualType();
1501
1502 // void * type
1503 if (LangOpts.OpenCLGenericAddressSpace) {
1504 auto Q = VoidTy.getQualifiers();
1505 Q.setAddressSpace(LangAS::opencl_generic);
1506 VoidPtrTy = getPointerType(T: getCanonicalType(
1507 T: getQualifiedType(T: VoidTy.getUnqualifiedType(), Qs: Q)));
1508 } else {
1509 VoidPtrTy = getPointerType(T: VoidTy);
1510 }
1511
1512 // nullptr type (C++0x 2.14.7)
1513 InitBuiltinType(R&: NullPtrTy, K: BuiltinType::NullPtr);
1514
1515 // std::meta::info type (C++26 21.4.1)
1516 InitBuiltinType(R&: MetaInfoTy, K: BuiltinType::MetaInfo);
1517
1518 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1519 InitBuiltinType(R&: HalfTy, K: BuiltinType::Half);
1520
1521 InitBuiltinType(R&: BFloat16Ty, K: BuiltinType::BFloat16);
1522
1523 // Builtin type used to help define __builtin_va_list.
1524 VaListTagDecl = nullptr;
1525
1526 // MSVC predeclares struct _GUID, and we need it to create MSGuidDecls.
1527 if (LangOpts.MicrosoftExt || LangOpts.Borland) {
1528 MSGuidTagDecl = buildImplicitRecord(Name: "_GUID");
1529 getTranslationUnitDecl()->addDecl(D: MSGuidTagDecl);
1530 }
1531}
1532
1533DiagnosticsEngine &ASTContext::getDiagnostics() const {
1534 return SourceMgr.getDiagnostics();
1535}
1536
1537AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1538 // 85% of lookups use the most recent D, so use a one-entry cache.
1539 if (LastDeclAttrsDecl == D) {
1540 assert(LastDeclAttrs != nullptr && LastDeclAttrs == DeclAttrs[D]);
1541 return *LastDeclAttrs;
1542 }
1543
1544 AttrVec *&Result = DeclAttrs[D];
1545 if (!Result) {
1546 void *Mem = Allocate(Size: sizeof(AttrVec));
1547 Result = new (Mem) AttrVec;
1548 }
1549
1550 LastDeclAttrsDecl = D;
1551 LastDeclAttrs = Result;
1552 return *Result;
1553}
1554
1555/// Erase the attributes corresponding to the given declaration.
1556void ASTContext::eraseDeclAttrs(const Decl *D) {
1557 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(Val: D);
1558 if (Pos != DeclAttrs.end()) {
1559 Pos->second->~AttrVec();
1560 DeclAttrs.erase(I: Pos);
1561 }
1562 if (LastDeclAttrsDecl == D)
1563 LastDeclAttrsDecl = nullptr;
1564}
1565
1566ArrayRef<CXXDefaultArgExpr *>
1567ASTContext::getCtorClosureDefaultArgs(const CXXConstructorDecl *CD) {
1568 return CtorClosureDefaultArgs.lookup(Val: CD);
1569}
1570
1571void ASTContext::setCtorClosureDefaultArgs(const CXXConstructorDecl *CD,
1572 ArrayRef<CXXDefaultArgExpr *> Args) {
1573 assert(!CtorClosureDefaultArgs.contains(CD));
1574 CtorClosureDefaultArgs[CD] = Args;
1575}
1576
1577ArrayRef<ExplicitInstantiationDecl *>
1578ASTContext::getExplicitInstantiationDecls(const NamedDecl *Spec) const {
1579 auto It =
1580 ExplicitInstantiations.find(Val: cast<NamedDecl>(Val: Spec->getCanonicalDecl()));
1581 if (It != ExplicitInstantiations.end())
1582 return It->second;
1583 return {};
1584}
1585
1586void ASTContext::addExplicitInstantiationDecl(const NamedDecl *Spec,
1587 ExplicitInstantiationDecl *EID) {
1588 ExplicitInstantiations[cast<NamedDecl>(Val: Spec->getCanonicalDecl())].push_back(
1589 NewVal: EID);
1590}
1591
1592// FIXME: Remove ?
1593MemberSpecializationInfo *
1594ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
1595 assert(Var->isStaticDataMember() && "Not a static data member");
1596 return getTemplateOrSpecializationInfo(Var)
1597 .dyn_cast<MemberSpecializationInfo *>();
1598}
1599
1600ASTContext::TemplateOrSpecializationInfo
1601ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1602 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1603 TemplateOrInstantiation.find(Val: Var);
1604 if (Pos == TemplateOrInstantiation.end())
1605 return {};
1606
1607 return Pos->second;
1608}
1609
1610void
1611ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
1612 TemplateSpecializationKind TSK,
1613 SourceLocation PointOfInstantiation) {
1614 assert(Inst->isStaticDataMember() && "Not a static data member");
1615 assert(Tmpl->isStaticDataMember() && "Not a static data member");
1616 setTemplateOrSpecializationInfo(Inst, TSI: new (*this) MemberSpecializationInfo(
1617 Tmpl, TSK, PointOfInstantiation));
1618}
1619
1620void
1621ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1622 TemplateOrSpecializationInfo TSI) {
1623 assert(!TemplateOrInstantiation[Inst] &&
1624 "Already noted what the variable was instantiated from");
1625 TemplateOrInstantiation[Inst] = TSI;
1626}
1627
1628NamedDecl *
1629ASTContext::getInstantiatedFromUsingDecl(NamedDecl *UUD) {
1630 return InstantiatedFromUsingDecl.lookup(Val: UUD);
1631}
1632
1633void
1634ASTContext::setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern) {
1635 assert((isa<UsingDecl>(Pattern) ||
1636 isa<UnresolvedUsingValueDecl>(Pattern) ||
1637 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1638 "pattern decl is not a using decl");
1639 assert((isa<UsingDecl>(Inst) ||
1640 isa<UnresolvedUsingValueDecl>(Inst) ||
1641 isa<UnresolvedUsingTypenameDecl>(Inst)) &&
1642 "instantiation did not produce a using decl");
1643 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1644 InstantiatedFromUsingDecl[Inst] = Pattern;
1645}
1646
1647UsingEnumDecl *
1648ASTContext::getInstantiatedFromUsingEnumDecl(UsingEnumDecl *UUD) {
1649 return InstantiatedFromUsingEnumDecl.lookup(Val: UUD);
1650}
1651
1652void ASTContext::setInstantiatedFromUsingEnumDecl(UsingEnumDecl *Inst,
1653 UsingEnumDecl *Pattern) {
1654 assert(!InstantiatedFromUsingEnumDecl[Inst] && "pattern already exists");
1655 InstantiatedFromUsingEnumDecl[Inst] = Pattern;
1656}
1657
1658UsingShadowDecl *
1659ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1660 return InstantiatedFromUsingShadowDecl.lookup(Val: Inst);
1661}
1662
1663void
1664ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1665 UsingShadowDecl *Pattern) {
1666 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1667 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
1668}
1669
1670FieldDecl *
1671ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) const {
1672 return InstantiatedFromUnnamedFieldDecl.lookup(Val: Field);
1673}
1674
1675void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1676 FieldDecl *Tmpl) {
1677 assert((!Inst->getDeclName() || Inst->isPlaceholderVar(getLangOpts())) &&
1678 "Instantiated field decl is not unnamed");
1679 assert((!Inst->getDeclName() || Inst->isPlaceholderVar(getLangOpts())) &&
1680 "Template field decl is not unnamed");
1681 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1682 "Already noted what unnamed field was instantiated from");
1683
1684 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1685}
1686
1687ASTContext::overridden_cxx_method_iterator
1688ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1689 return overridden_methods(Method).begin();
1690}
1691
1692ASTContext::overridden_cxx_method_iterator
1693ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1694 return overridden_methods(Method).end();
1695}
1696
1697unsigned
1698ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1699 auto Range = overridden_methods(Method);
1700 return Range.end() - Range.begin();
1701}
1702
1703ASTContext::overridden_method_range
1704ASTContext::overridden_methods(const CXXMethodDecl *Method) const {
1705 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1706 OverriddenMethods.find(Val: Method->getCanonicalDecl());
1707 if (Pos == OverriddenMethods.end())
1708 return overridden_method_range(nullptr, nullptr);
1709 return overridden_method_range(Pos->second.begin(), Pos->second.end());
1710}
1711
1712void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1713 const CXXMethodDecl *Overridden) {
1714 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
1715 OverriddenMethods[Method].push_back(NewVal: Overridden);
1716}
1717
1718void ASTContext::getOverriddenMethods(
1719 const NamedDecl *D,
1720 SmallVectorImpl<const NamedDecl *> &Overridden) const {
1721 assert(D);
1722
1723 if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(Val: D)) {
1724 Overridden.append(in_start: overridden_methods_begin(Method: CXXMethod),
1725 in_end: overridden_methods_end(Method: CXXMethod));
1726 return;
1727 }
1728
1729 const auto *Method = dyn_cast<ObjCMethodDecl>(Val: D);
1730 if (!Method)
1731 return;
1732
1733 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1734 Method->getOverriddenMethods(Overridden&: OverDecls);
1735 Overridden.append(in_start: OverDecls.begin(), in_end: OverDecls.end());
1736}
1737
1738std::optional<ASTContext::CXXRecordDeclRelocationInfo>
1739ASTContext::getRelocationInfoForCXXRecord(const CXXRecordDecl *RD) const {
1740 assert(RD);
1741 CXXRecordDecl *D = RD->getDefinition();
1742 auto it = RelocatableClasses.find(Val: D);
1743 if (it != RelocatableClasses.end())
1744 return it->getSecond();
1745 return std::nullopt;
1746}
1747
1748void ASTContext::setRelocationInfoForCXXRecord(
1749 const CXXRecordDecl *RD, CXXRecordDeclRelocationInfo Info) {
1750 assert(RD);
1751 CXXRecordDecl *D = RD->getDefinition();
1752 assert(RelocatableClasses.find(D) == RelocatableClasses.end());
1753 RelocatableClasses.insert(KV: {D, Info});
1754}
1755
1756static bool primaryBaseHaseAddressDiscriminatedVTableAuthentication(
1757 const ASTContext &Context, const CXXRecordDecl *Class) {
1758 if (!Class->isPolymorphic())
1759 return false;
1760 const CXXRecordDecl *BaseType = Context.baseForVTableAuthentication(ThisClass: Class);
1761 using AuthAttr = VTablePointerAuthenticationAttr;
1762 const AuthAttr *ExplicitAuth = BaseType->getAttr<AuthAttr>();
1763 if (!ExplicitAuth)
1764 return Context.getLangOpts().PointerAuthVTPtrAddressDiscrimination;
1765 AuthAttr::AddressDiscriminationMode AddressDiscrimination =
1766 ExplicitAuth->getAddressDiscrimination();
1767 if (AddressDiscrimination == AuthAttr::DefaultAddressDiscrimination)
1768 return Context.getLangOpts().PointerAuthVTPtrAddressDiscrimination;
1769 return AddressDiscrimination == AuthAttr::AddressDiscrimination;
1770}
1771
1772ASTContext::PointerAuthContent
1773ASTContext::findPointerAuthContent(QualType T) const {
1774 assert(isPointerAuthenticationAvailable());
1775
1776 T = T.getCanonicalType();
1777 if (T->isDependentType())
1778 return PointerAuthContent::None;
1779
1780 if (T.hasAddressDiscriminatedPointerAuth())
1781 return PointerAuthContent::AddressDiscriminatedData;
1782 const RecordDecl *RD = T->getAsRecordDecl();
1783 if (!RD)
1784 return PointerAuthContent::None;
1785
1786 if (RD->isInvalidDecl())
1787 return PointerAuthContent::None;
1788
1789 if (auto Existing = RecordContainsAddressDiscriminatedPointerAuth.find(Val: RD);
1790 Existing != RecordContainsAddressDiscriminatedPointerAuth.end())
1791 return Existing->second;
1792
1793 PointerAuthContent Result = PointerAuthContent::None;
1794
1795 auto SaveResultAndReturn = [&]() -> PointerAuthContent {
1796 auto [ResultIter, DidAdd] =
1797 RecordContainsAddressDiscriminatedPointerAuth.try_emplace(Key: RD, Args&: Result);
1798 (void)ResultIter;
1799 (void)DidAdd;
1800 assert(DidAdd);
1801 return Result;
1802 };
1803 auto ShouldContinueAfterUpdate = [&](PointerAuthContent NewResult) {
1804 static_assert(PointerAuthContent::None <
1805 PointerAuthContent::AddressDiscriminatedVTable);
1806 static_assert(PointerAuthContent::AddressDiscriminatedVTable <
1807 PointerAuthContent::AddressDiscriminatedData);
1808 if (NewResult > Result)
1809 Result = NewResult;
1810 return Result != PointerAuthContent::AddressDiscriminatedData;
1811 };
1812 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(Val: RD)) {
1813 if (primaryBaseHaseAddressDiscriminatedVTableAuthentication(Context: *this, Class: CXXRD) &&
1814 !ShouldContinueAfterUpdate(
1815 PointerAuthContent::AddressDiscriminatedVTable))
1816 return SaveResultAndReturn();
1817 for (auto Base : CXXRD->bases()) {
1818 if (!ShouldContinueAfterUpdate(findPointerAuthContent(T: Base.getType())))
1819 return SaveResultAndReturn();
1820 }
1821 }
1822 for (auto *FieldDecl : RD->fields()) {
1823 if (!ShouldContinueAfterUpdate(
1824 findPointerAuthContent(T: FieldDecl->getType())))
1825 return SaveResultAndReturn();
1826 }
1827 return SaveResultAndReturn();
1828}
1829
1830void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1831 assert(!Import->getNextLocalImport() &&
1832 "Import declaration already in the chain");
1833 assert(!Import->isFromASTFile() && "Non-local import declaration");
1834 if (!FirstLocalImport) {
1835 FirstLocalImport = Import;
1836 LastLocalImport = Import;
1837 return;
1838 }
1839
1840 LastLocalImport->setNextLocalImport(Import);
1841 LastLocalImport = Import;
1842}
1843
1844//===----------------------------------------------------------------------===//
1845// Type Sizing and Analysis
1846//===----------------------------------------------------------------------===//
1847
1848/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1849/// scalar floating point type.
1850const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
1851 switch (T->castAs<BuiltinType>()->getKind()) {
1852 default:
1853 llvm_unreachable("Not a floating point type!");
1854 case BuiltinType::BFloat16:
1855 return Target->getBFloat16Format();
1856 case BuiltinType::Float16:
1857 return Target->getHalfFormat();
1858 case BuiltinType::Half:
1859 return Target->getHalfFormat();
1860 case BuiltinType::Float: return Target->getFloatFormat();
1861 case BuiltinType::Double: return Target->getDoubleFormat();
1862 case BuiltinType::Ibm128:
1863 return Target->getIbm128Format();
1864 case BuiltinType::LongDouble:
1865 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice)
1866 return AuxTarget->getLongDoubleFormat();
1867 return Target->getLongDoubleFormat();
1868 case BuiltinType::Float128:
1869 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice)
1870 return AuxTarget->getFloat128Format();
1871 return Target->getFloat128Format();
1872 }
1873}
1874
1875CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
1876 unsigned Align = Target->getCharWidth();
1877
1878 const unsigned AlignFromAttr = D->getMaxAlignment();
1879 if (AlignFromAttr)
1880 Align = AlignFromAttr;
1881
1882 // __attribute__((aligned)) can increase or decrease alignment
1883 // *except* on a struct or struct member, where it only increases
1884 // alignment unless 'packed' is also specified.
1885 //
1886 // It is an error for alignas to decrease alignment, so we can
1887 // ignore that possibility; Sema should diagnose it.
1888 bool UseAlignAttrOnly;
1889 if (const FieldDecl *FD = dyn_cast<FieldDecl>(Val: D))
1890 UseAlignAttrOnly =
1891 FD->hasAttr<PackedAttr>() || FD->getParent()->hasAttr<PackedAttr>();
1892 else
1893 UseAlignAttrOnly = AlignFromAttr != 0;
1894 // If we're using the align attribute only, just ignore everything
1895 // else about the declaration and its type.
1896 if (UseAlignAttrOnly) {
1897 // do nothing
1898 } else if (const auto *VD = dyn_cast<ValueDecl>(Val: D)) {
1899 QualType T = VD->getType();
1900 if (const auto *RT = T->getAs<ReferenceType>()) {
1901 if (ForAlignof)
1902 T = RT->getPointeeType();
1903 else
1904 T = getPointerType(T: RT->getPointeeType());
1905 }
1906 QualType BaseT = getBaseElementType(QT: T);
1907 if (T->isFunctionType())
1908 Align = getTypeInfoImpl(T: T.getTypePtr()).Align;
1909 else if (!BaseT->isIncompleteType()) {
1910 // Adjust alignments of declarations with array type by the
1911 // large-array alignment on the target.
1912 if (const ArrayType *arrayType = getAsArrayType(T)) {
1913 unsigned MinWidth = Target->getLargeArrayMinWidth();
1914 if (!ForAlignof && MinWidth) {
1915 if (isa<VariableArrayType>(Val: arrayType))
1916 Align = std::max(a: Align, b: Target->getLargeArrayAlign());
1917 else if (isa<ConstantArrayType>(Val: arrayType) &&
1918 MinWidth <= getTypeSize(T: cast<ConstantArrayType>(Val: arrayType)))
1919 Align = std::max(a: Align, b: Target->getLargeArrayAlign());
1920 }
1921 }
1922 Align = std::max(a: Align, b: getPreferredTypeAlign(T: T.getTypePtr()));
1923 if (BaseT.getQualifiers().hasUnaligned())
1924 Align = Target->getCharWidth();
1925 }
1926
1927 // Ensure minimum alignment for global variables.
1928 if (const auto *VD = dyn_cast<VarDecl>(Val: D))
1929 if (VD->hasGlobalStorage() && !ForAlignof) {
1930 uint64_t TypeSize =
1931 !BaseT->isIncompleteType() ? getTypeSize(T: T.getTypePtr()) : 0;
1932 Align = std::max(a: Align, b: getMinGlobalAlignOfVar(Size: TypeSize, VD));
1933 }
1934
1935 // Fields can be subject to extra alignment constraints, like if
1936 // the field is packed, the struct is packed, or the struct has a
1937 // a max-field-alignment constraint (#pragma pack). So calculate
1938 // the actual alignment of the field within the struct, and then
1939 // (as we're expected to) constrain that by the alignment of the type.
1940 if (const auto *Field = dyn_cast<FieldDecl>(Val: VD)) {
1941 const RecordDecl *Parent = Field->getParent();
1942 // We can only produce a sensible answer if the record is valid.
1943 if (!Parent->isInvalidDecl()) {
1944 const ASTRecordLayout &Layout = getASTRecordLayout(D: Parent);
1945
1946 // Start with the record's overall alignment.
1947 unsigned FieldAlign = toBits(CharSize: Layout.getAlignment());
1948
1949 // Use the GCD of that and the offset within the record.
1950 uint64_t Offset = Layout.getFieldOffset(FieldNo: Field->getFieldIndex());
1951 if (Offset > 0) {
1952 // Alignment is always a power of 2, so the GCD will be a power of 2,
1953 // which means we get to do this crazy thing instead of Euclid's.
1954 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1955 if (LowBitOfOffset < FieldAlign)
1956 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1957 }
1958
1959 Align = std::min(a: Align, b: FieldAlign);
1960 }
1961 }
1962 }
1963
1964 // Some targets have hard limitation on the maximum requestable alignment in
1965 // aligned attribute for static variables.
1966 const unsigned MaxAlignedAttr = getTargetInfo().getMaxAlignedAttribute();
1967 const auto *VD = dyn_cast<VarDecl>(Val: D);
1968 if (MaxAlignedAttr && VD && VD->getStorageClass() == SC_Static)
1969 Align = std::min(a: Align, b: MaxAlignedAttr);
1970
1971 return toCharUnitsFromBits(BitSize: Align);
1972}
1973
1974CharUnits ASTContext::getExnObjectAlignment() const {
1975 return toCharUnitsFromBits(BitSize: Target->getExnObjectAlignment());
1976}
1977
1978// getTypeInfoDataSizeInChars - Return the size of a type, in
1979// chars. If the type is a record, its data size is returned. This is
1980// the size of the memcpy that's performed when assigning this type
1981// using a trivial copy/move assignment operator.
1982TypeInfoChars ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1983 TypeInfoChars Info = getTypeInfoInChars(T);
1984
1985 // In C++, objects can sometimes be allocated into the tail padding
1986 // of a base-class subobject. We decide whether that's possible
1987 // during class layout, so here we can just trust the layout results.
1988 if (getLangOpts().CPlusPlus) {
1989 if (const auto *RD = T->getAsCXXRecordDecl(); RD && !RD->isInvalidDecl()) {
1990 const ASTRecordLayout &layout = getASTRecordLayout(D: RD);
1991 Info.Width = layout.getDataSize();
1992 }
1993 }
1994
1995 return Info;
1996}
1997
1998/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1999/// instead of in bits prevents overflowing the uint64_t for some large arrays.
2000TypeInfoChars
2001static getConstantArrayInfoInChars(const ASTContext &Context,
2002 const ConstantArrayType *CAT) {
2003 TypeInfoChars EltInfo = Context.getTypeInfoInChars(T: CAT->getElementType());
2004 uint64_t Size = CAT->getZExtSize();
2005 assert((Size == 0 || static_cast<uint64_t>(EltInfo.Width.getQuantity()) <=
2006 (uint64_t)(-1)/Size) &&
2007 "Overflow in array type char size evaluation");
2008 uint64_t Width = EltInfo.Width.getQuantity() * Size;
2009 unsigned Align = EltInfo.Align.getQuantity();
2010 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
2011 Context.getTargetInfo().getPointerWidth(AddrSpace: LangAS::Default) == 64)
2012 Width = llvm::alignTo(Value: Width, Align);
2013 return TypeInfoChars(CharUnits::fromQuantity(Quantity: Width),
2014 CharUnits::fromQuantity(Quantity: Align),
2015 EltInfo.AlignRequirement);
2016}
2017
2018TypeInfoChars ASTContext::getTypeInfoInChars(const Type *T) const {
2019 if (const auto *CAT = dyn_cast<ConstantArrayType>(Val: T))
2020 return getConstantArrayInfoInChars(Context: *this, CAT);
2021 TypeInfo Info = getTypeInfo(T);
2022 return TypeInfoChars(toCharUnitsFromBits(BitSize: Info.Width),
2023 toCharUnitsFromBits(BitSize: Info.Align), Info.AlignRequirement);
2024}
2025
2026TypeInfoChars ASTContext::getTypeInfoInChars(QualType T) const {
2027 return getTypeInfoInChars(T: T.getTypePtr());
2028}
2029
2030bool ASTContext::isPromotableIntegerType(QualType T) const {
2031 // HLSL doesn't promote all small integer types to int, it
2032 // just uses the rank-based promotion rules for all types.
2033 if (getLangOpts().HLSL)
2034 return false;
2035
2036 if (const auto *BT = T->getAs<BuiltinType>())
2037 switch (BT->getKind()) {
2038 case BuiltinType::Bool:
2039 case BuiltinType::Char_S:
2040 case BuiltinType::Char_U:
2041 case BuiltinType::SChar:
2042 case BuiltinType::UChar:
2043 case BuiltinType::Short:
2044 case BuiltinType::UShort:
2045 case BuiltinType::WChar_S:
2046 case BuiltinType::WChar_U:
2047 case BuiltinType::Char8:
2048 case BuiltinType::Char16:
2049 case BuiltinType::Char32:
2050 return true;
2051 default:
2052 return false;
2053 }
2054
2055 // Enumerated types are promotable to their compatible integer types
2056 // (C99 6.3.1.1) a.k.a. its underlying type (C++ [conv.prom]p2).
2057 if (const auto *ED = T->getAsEnumDecl()) {
2058 if (T->isDependentType() || ED->getPromotionType().isNull() ||
2059 ED->isScoped())
2060 return false;
2061
2062 return true;
2063 }
2064
2065 // OverflowBehaviorTypes are promotable if their underlying type is promotable
2066 if (const auto *OBT = T->getAs<OverflowBehaviorType>()) {
2067 return isPromotableIntegerType(T: OBT->getUnderlyingType());
2068 }
2069
2070 return false;
2071}
2072
2073bool ASTContext::isAlignmentRequired(const Type *T) const {
2074 return getTypeInfo(T).AlignRequirement != AlignRequirementKind::None;
2075}
2076
2077bool ASTContext::isAlignmentRequired(QualType T) const {
2078 return isAlignmentRequired(T: T.getTypePtr());
2079}
2080
2081unsigned ASTContext::getTypeAlignIfKnown(QualType T,
2082 bool NeedsPreferredAlignment) const {
2083 // An alignment on a typedef overrides anything else.
2084 if (const auto *TT = T->getAs<TypedefType>())
2085 if (unsigned Align = TT->getDecl()->getMaxAlignment())
2086 return Align;
2087
2088 // If we have an (array of) complete type, we're done.
2089 T = getBaseElementType(QT: T);
2090 if (!T->isIncompleteType())
2091 return NeedsPreferredAlignment ? getPreferredTypeAlign(T) : getTypeAlign(T);
2092
2093 // If we had an array type, its element type might be a typedef
2094 // type with an alignment attribute.
2095 if (const auto *TT = T->getAs<TypedefType>())
2096 if (unsigned Align = TT->getDecl()->getMaxAlignment())
2097 return Align;
2098
2099 // Otherwise, see if the declaration of the type had an attribute.
2100 if (const auto *TD = T->getAsTagDecl())
2101 return TD->getMaxAlignment();
2102
2103 return 0;
2104}
2105
2106TypeInfo ASTContext::getTypeInfo(const Type *T) const {
2107 TypeInfoMap::iterator I = MemoizedTypeInfo.find(Val: T);
2108 if (I != MemoizedTypeInfo.end())
2109 return I->second;
2110
2111 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
2112 TypeInfo TI = getTypeInfoImpl(T);
2113 MemoizedTypeInfo[T] = TI;
2114 return TI;
2115}
2116
2117/// getTypeInfoImpl - Return the size of the specified type, in bits. This
2118/// method does not work on incomplete types.
2119///
2120/// FIXME: Pointers into different addr spaces could have different sizes and
2121/// alignment requirements: getPointerInfo should take an AddrSpace, this
2122/// should take a QualType, &c.
2123TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
2124 uint64_t Width = 0;
2125 unsigned Align = 8;
2126 AlignRequirementKind AlignRequirement = AlignRequirementKind::None;
2127 LangAS AS = LangAS::Default;
2128 switch (T->getTypeClass()) {
2129#define TYPE(Class, Base)
2130#define ABSTRACT_TYPE(Class, Base)
2131#define NON_CANONICAL_TYPE(Class, Base)
2132#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2133#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
2134 case Type::Class: \
2135 assert(!T->isDependentType() && "should not see dependent types here"); \
2136 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
2137#include "clang/AST/TypeNodes.inc"
2138 llvm_unreachable("Should not see dependent types");
2139
2140 case Type::FunctionNoProto:
2141 case Type::FunctionProto:
2142 // GCC extension: alignof(function) = 32 bits
2143 Width = 0;
2144 Align = 32;
2145 break;
2146
2147 case Type::IncompleteArray:
2148 case Type::VariableArray:
2149 case Type::ConstantArray:
2150 case Type::ArrayParameter: {
2151 // Model non-constant sized arrays as size zero, but track the alignment.
2152 uint64_t Size = 0;
2153 if (const auto *CAT = dyn_cast<ConstantArrayType>(Val: T))
2154 Size = CAT->getZExtSize();
2155
2156 TypeInfo EltInfo = getTypeInfo(T: cast<ArrayType>(Val: T)->getElementType());
2157 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
2158 "Overflow in array type bit size evaluation");
2159 Width = EltInfo.Width * Size;
2160 Align = EltInfo.Align;
2161 AlignRequirement = EltInfo.AlignRequirement;
2162 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
2163 getTargetInfo().getPointerWidth(AddrSpace: LangAS::Default) == 64)
2164 Width = llvm::alignTo(Value: Width, Align);
2165 break;
2166 }
2167
2168 case Type::ExtVector:
2169 case Type::Vector: {
2170 const auto *VT = cast<VectorType>(Val: T);
2171 TypeInfo EltInfo = getTypeInfo(T: VT->getElementType());
2172 Width = VT->isPackedVectorBoolType(ctx: *this)
2173 ? VT->getNumElements()
2174 : EltInfo.Width * VT->getNumElements();
2175 // Enforce at least byte size and alignment.
2176 Width = std::max<unsigned>(a: 8, b: Width);
2177 Align = std::max<unsigned>(
2178 a: 8, b: Target->vectorsAreElementAligned() ? EltInfo.Width : Width);
2179
2180 // If the alignment is not a power of 2, round up to the next power of 2.
2181 // This happens for non-power-of-2 length vectors.
2182 if (Align & (Align-1)) {
2183 Align = llvm::bit_ceil(Value: Align);
2184 Width = llvm::alignTo(Value: Width, Align);
2185 }
2186 // Adjust the alignment based on the target max.
2187 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
2188 if (TargetVectorAlign && TargetVectorAlign < Align)
2189 Align = TargetVectorAlign;
2190 if (VT->getVectorKind() == VectorKind::SveFixedLengthData)
2191 // Adjust the alignment for fixed-length SVE vectors. This is important
2192 // for non-power-of-2 vector lengths.
2193 Align = 128;
2194 else if (VT->getVectorKind() == VectorKind::SveFixedLengthPredicate)
2195 // Adjust the alignment for fixed-length SVE predicates.
2196 Align = 16;
2197 else if (VT->getVectorKind() == VectorKind::RVVFixedLengthData ||
2198 VT->getVectorKind() == VectorKind::RVVFixedLengthMask ||
2199 VT->getVectorKind() == VectorKind::RVVFixedLengthMask_1 ||
2200 VT->getVectorKind() == VectorKind::RVVFixedLengthMask_2 ||
2201 VT->getVectorKind() == VectorKind::RVVFixedLengthMask_4)
2202 // Adjust the alignment for fixed-length RVV vectors.
2203 Align = std::min<unsigned>(a: 64, b: Width);
2204 break;
2205 }
2206
2207 case Type::ConstantMatrix: {
2208 const auto *MT = cast<ConstantMatrixType>(Val: T);
2209 TypeInfo ElementInfo = getTypeInfo(T: MT->getElementType());
2210 // The internal layout of a matrix value is implementation defined.
2211 // Initially be ABI compatible with arrays with respect to alignment and
2212 // size.
2213 Width = ElementInfo.Width * MT->getNumRows() * MT->getNumColumns();
2214 Align = ElementInfo.Align;
2215 break;
2216 }
2217
2218 case Type::Builtin:
2219 switch (cast<BuiltinType>(Val: T)->getKind()) {
2220 default: llvm_unreachable("Unknown builtin type!");
2221 case BuiltinType::Void:
2222 // GCC extension: alignof(void) = 8 bits.
2223 Width = 0;
2224 Align = 8;
2225 break;
2226 case BuiltinType::Bool:
2227 Width = Target->getBoolWidth();
2228 Align = Target->getBoolAlign();
2229 break;
2230 case BuiltinType::Char_S:
2231 case BuiltinType::Char_U:
2232 case BuiltinType::UChar:
2233 case BuiltinType::SChar:
2234 case BuiltinType::Char8:
2235 Width = Target->getCharWidth();
2236 Align = Target->getCharAlign();
2237 break;
2238 case BuiltinType::WChar_S:
2239 case BuiltinType::WChar_U:
2240 Width = Target->getWCharWidth();
2241 Align = Target->getWCharAlign();
2242 break;
2243 case BuiltinType::Char16:
2244 Width = Target->getChar16Width();
2245 Align = Target->getChar16Align();
2246 break;
2247 case BuiltinType::Char32:
2248 Width = Target->getChar32Width();
2249 Align = Target->getChar32Align();
2250 break;
2251 case BuiltinType::UShort:
2252 case BuiltinType::Short:
2253 Width = Target->getShortWidth();
2254 Align = Target->getShortAlign();
2255 break;
2256 case BuiltinType::UInt:
2257 case BuiltinType::Int:
2258 Width = Target->getIntWidth();
2259 Align = Target->getIntAlign();
2260 break;
2261 case BuiltinType::ULong:
2262 case BuiltinType::Long:
2263 Width = Target->getLongWidth();
2264 Align = Target->getLongAlign();
2265 break;
2266 case BuiltinType::ULongLong:
2267 case BuiltinType::LongLong:
2268 Width = Target->getLongLongWidth();
2269 Align = Target->getLongLongAlign();
2270 break;
2271 case BuiltinType::Int128:
2272 case BuiltinType::UInt128:
2273 Width = 128;
2274 Align = Target->getInt128Align();
2275 break;
2276 case BuiltinType::ShortAccum:
2277 case BuiltinType::UShortAccum:
2278 case BuiltinType::SatShortAccum:
2279 case BuiltinType::SatUShortAccum:
2280 Width = Target->getShortAccumWidth();
2281 Align = Target->getShortAccumAlign();
2282 break;
2283 case BuiltinType::Accum:
2284 case BuiltinType::UAccum:
2285 case BuiltinType::SatAccum:
2286 case BuiltinType::SatUAccum:
2287 Width = Target->getAccumWidth();
2288 Align = Target->getAccumAlign();
2289 break;
2290 case BuiltinType::LongAccum:
2291 case BuiltinType::ULongAccum:
2292 case BuiltinType::SatLongAccum:
2293 case BuiltinType::SatULongAccum:
2294 Width = Target->getLongAccumWidth();
2295 Align = Target->getLongAccumAlign();
2296 break;
2297 case BuiltinType::ShortFract:
2298 case BuiltinType::UShortFract:
2299 case BuiltinType::SatShortFract:
2300 case BuiltinType::SatUShortFract:
2301 Width = Target->getShortFractWidth();
2302 Align = Target->getShortFractAlign();
2303 break;
2304 case BuiltinType::Fract:
2305 case BuiltinType::UFract:
2306 case BuiltinType::SatFract:
2307 case BuiltinType::SatUFract:
2308 Width = Target->getFractWidth();
2309 Align = Target->getFractAlign();
2310 break;
2311 case BuiltinType::LongFract:
2312 case BuiltinType::ULongFract:
2313 case BuiltinType::SatLongFract:
2314 case BuiltinType::SatULongFract:
2315 Width = Target->getLongFractWidth();
2316 Align = Target->getLongFractAlign();
2317 break;
2318 case BuiltinType::BFloat16:
2319 if (Target->hasBFloat16Type()) {
2320 Width = Target->getBFloat16Width();
2321 Align = Target->getBFloat16Align();
2322 } else if ((getLangOpts().SYCLIsDevice ||
2323 (getLangOpts().OpenMP &&
2324 getLangOpts().OpenMPIsTargetDevice)) &&
2325 AuxTarget->hasBFloat16Type()) {
2326 Width = AuxTarget->getBFloat16Width();
2327 Align = AuxTarget->getBFloat16Align();
2328 }
2329 break;
2330 case BuiltinType::Float16:
2331 case BuiltinType::Half:
2332 if (Target->hasFloat16Type() || !getLangOpts().OpenMP ||
2333 !getLangOpts().OpenMPIsTargetDevice) {
2334 Width = Target->getHalfWidth();
2335 Align = Target->getHalfAlign();
2336 } else {
2337 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2338 "Expected OpenMP device compilation.");
2339 Width = AuxTarget->getHalfWidth();
2340 Align = AuxTarget->getHalfAlign();
2341 }
2342 break;
2343 case BuiltinType::Float:
2344 Width = Target->getFloatWidth();
2345 Align = Target->getFloatAlign();
2346 break;
2347 case BuiltinType::Double:
2348 Width = Target->getDoubleWidth();
2349 Align = Target->getDoubleAlign();
2350 break;
2351 case BuiltinType::Ibm128:
2352 Width = Target->getIbm128Width();
2353 Align = Target->getIbm128Align();
2354 break;
2355 case BuiltinType::LongDouble:
2356 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2357 (Target->getLongDoubleWidth() != AuxTarget->getLongDoubleWidth() ||
2358 Target->getLongDoubleAlign() != AuxTarget->getLongDoubleAlign())) {
2359 Width = AuxTarget->getLongDoubleWidth();
2360 Align = AuxTarget->getLongDoubleAlign();
2361 } else {
2362 Width = Target->getLongDoubleWidth();
2363 Align = Target->getLongDoubleAlign();
2364 }
2365 break;
2366 case BuiltinType::Float128:
2367 if (Target->hasFloat128Type() || !getLangOpts().OpenMP ||
2368 !getLangOpts().OpenMPIsTargetDevice) {
2369 Width = Target->getFloat128Width();
2370 Align = Target->getFloat128Align();
2371 } else {
2372 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2373 "Expected OpenMP device compilation.");
2374 Width = AuxTarget->getFloat128Width();
2375 Align = AuxTarget->getFloat128Align();
2376 }
2377 break;
2378 case BuiltinType::NullPtr:
2379 // C++ 3.9.1p11: sizeof(nullptr_t) == sizeof(void*)
2380 Width = Target->getPointerWidth(AddrSpace: LangAS::Default);
2381 Align = Target->getPointerAlign(AddrSpace: LangAS::Default);
2382 break;
2383 case BuiltinType::MetaInfo:
2384 // sizeof(std::meta::info) == sizeof(void*)
2385 Width = Target->getPointerWidth(AddrSpace: LangAS::Default);
2386 // alignof(std::meta::info) == alignof(void*)
2387 Align = Target->getPointerAlign(AddrSpace: LangAS::Default);
2388 break;
2389 case BuiltinType::ObjCId:
2390 case BuiltinType::ObjCClass:
2391 case BuiltinType::ObjCSel:
2392 Width = Target->getPointerWidth(AddrSpace: LangAS::Default);
2393 Align = Target->getPointerAlign(AddrSpace: LangAS::Default);
2394 break;
2395 case BuiltinType::OCLSampler:
2396 case BuiltinType::OCLEvent:
2397 case BuiltinType::OCLClkEvent:
2398 case BuiltinType::OCLQueue:
2399 case BuiltinType::OCLReserveID:
2400#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2401 case BuiltinType::Id:
2402#include "clang/Basic/OpenCLImageTypes.def"
2403#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2404 case BuiltinType::Id:
2405#include "clang/Basic/OpenCLExtensionTypes.def"
2406 AS = Target->getOpenCLTypeAddrSpace(TK: getOpenCLTypeKind(T));
2407 Width = Target->getPointerWidth(AddrSpace: AS);
2408 Align = Target->getPointerAlign(AddrSpace: AS);
2409 break;
2410 // The SVE types are effectively target-specific. The length of an
2411 // SVE_VECTOR_TYPE is only known at runtime, but it is always a multiple
2412 // of 128 bits. There is one predicate bit for each vector byte, so the
2413 // length of an SVE_PREDICATE_TYPE is always a multiple of 16 bits.
2414 //
2415 // Because the length is only known at runtime, we use a dummy value
2416 // of 0 for the static length. The alignment values are those defined
2417 // by the Procedure Call Standard for the Arm Architecture.
2418#define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId) \
2419 case BuiltinType::Id: \
2420 Width = 0; \
2421 Align = 128; \
2422 break;
2423#define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId) \
2424 case BuiltinType::Id: \
2425 Width = 0; \
2426 Align = 16; \
2427 break;
2428#define SVE_OPAQUE_TYPE(Name, MangledName, Id, SingletonId) \
2429 case BuiltinType::Id: \
2430 Width = 0; \
2431 Align = 16; \
2432 break;
2433#define SVE_SCALAR_TYPE(Name, MangledName, Id, SingletonId, Bits) \
2434 case BuiltinType::Id: \
2435 Width = Bits; \
2436 Align = Bits; \
2437 break;
2438#include "clang/Basic/AArch64ACLETypes.def"
2439#define PPC_VECTOR_TYPE(Name, Id, Size) \
2440 case BuiltinType::Id: \
2441 Width = Size; \
2442 Align = Size; \
2443 break;
2444#include "clang/Basic/PPCTypes.def"
2445#define RVV_VECTOR_TYPE(Name, Id, SingletonId, ElKind, ElBits, NF, IsSigned, \
2446 IsFP, IsBF) \
2447 case BuiltinType::Id: \
2448 Width = 0; \
2449 Align = ElBits; \
2450 break;
2451#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, ElKind) \
2452 case BuiltinType::Id: \
2453 Width = 0; \
2454 Align = 8; \
2455 break;
2456#include "clang/Basic/RISCVVTypes.def"
2457#define WASM_TYPE(Name, Id, SingletonId) \
2458 case BuiltinType::Id: \
2459 Width = 0; \
2460 Align = 8; \
2461 break;
2462#include "clang/Basic/WebAssemblyReferenceTypes.def"
2463#define AMDGPU_TYPE(NAME, ID, SINGLETONID, WIDTH, ALIGN) \
2464 case BuiltinType::ID: \
2465 Width = WIDTH; \
2466 Align = ALIGN; \
2467 break;
2468#include "clang/Basic/AMDGPUTypes.def"
2469#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
2470#include "clang/Basic/HLSLIntangibleTypes.def"
2471 Width = Target->getPointerWidth(AddrSpace: LangAS::Default);
2472 Align = Target->getPointerAlign(AddrSpace: LangAS::Default);
2473 break;
2474#define HLSL_PACKED_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
2475#include "clang/Basic/HLSLPackedTypes.def"
2476 Width = 32;
2477 Align = 32;
2478 break;
2479#define SPIRV_TYPE(Name, Id, SingletonId) \
2480 case BuiltinType::Id: \
2481 Width = Target->getPointerWidth(LangAS::Default); \
2482 Align = Target->getPointerAlign(LangAS::Default); \
2483 break;
2484#include "clang/Basic/SPIRVTypes.def"
2485 }
2486 break;
2487 case Type::ObjCObjectPointer:
2488 Width = Target->getPointerWidth(AddrSpace: LangAS::Default);
2489 Align = Target->getPointerAlign(AddrSpace: LangAS::Default);
2490 break;
2491 case Type::BlockPointer:
2492 AS = cast<BlockPointerType>(Val: T)->getPointeeType().getAddressSpace();
2493 Width = Target->getPointerWidth(AddrSpace: AS);
2494 Align = Target->getPointerAlign(AddrSpace: AS);
2495 break;
2496 case Type::LValueReference:
2497 case Type::RValueReference:
2498 // alignof and sizeof should never enter this code path here, so we go
2499 // the pointer route.
2500 AS = cast<ReferenceType>(Val: T)->getPointeeType().getAddressSpace();
2501 Width = Target->getPointerWidth(AddrSpace: AS);
2502 Align = Target->getPointerAlign(AddrSpace: AS);
2503 break;
2504 case Type::Pointer:
2505 AS = cast<PointerType>(Val: T)->getPointeeType().getAddressSpace();
2506 Width = Target->getPointerWidth(AddrSpace: AS);
2507 Align = Target->getPointerAlign(AddrSpace: AS);
2508 break;
2509 case Type::MemberPointer: {
2510 const auto *MPT = cast<MemberPointerType>(Val: T);
2511 CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT);
2512 Width = MPI.Width;
2513 Align = MPI.Align;
2514 break;
2515 }
2516 case Type::Complex: {
2517 // Complex types have the same alignment as their elements, but twice the
2518 // size.
2519 TypeInfo EltInfo = getTypeInfo(T: cast<ComplexType>(Val: T)->getElementType());
2520 Width = EltInfo.Width * 2;
2521 Align = EltInfo.Align;
2522 break;
2523 }
2524 case Type::ObjCObject:
2525 return getTypeInfo(T: cast<ObjCObjectType>(Val: T)->getBaseType().getTypePtr());
2526 case Type::Adjusted:
2527 case Type::Decayed:
2528 return getTypeInfo(T: cast<AdjustedType>(Val: T)->getAdjustedType().getTypePtr());
2529 case Type::ObjCInterface: {
2530 const auto *ObjCI = cast<ObjCInterfaceType>(Val: T);
2531 if (ObjCI->getDecl()->isInvalidDecl()) {
2532 Width = 8;
2533 Align = 8;
2534 break;
2535 }
2536 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(D: ObjCI->getDecl());
2537 Width = toBits(CharSize: Layout.getSize());
2538 Align = toBits(CharSize: Layout.getAlignment());
2539 break;
2540 }
2541 case Type::BitInt: {
2542 const auto *EIT = cast<BitIntType>(Val: T);
2543 Align = Target->getBitIntAlign(NumBits: EIT->getNumBits());
2544 Width = Target->getBitIntWidth(NumBits: EIT->getNumBits());
2545 break;
2546 }
2547 case Type::Record:
2548 case Type::Enum: {
2549 const auto *TT = cast<TagType>(Val: T);
2550 const TagDecl *TD = TT->getDecl()->getDefinitionOrSelf();
2551
2552 if (TD->isInvalidDecl()) {
2553 Width = 8;
2554 Align = 8;
2555 break;
2556 }
2557
2558 if (isa<EnumType>(Val: TT)) {
2559 const EnumDecl *ED = cast<EnumDecl>(Val: TD);
2560 TypeInfo Info =
2561 getTypeInfo(T: ED->getIntegerType()->getUnqualifiedDesugaredType());
2562 if (unsigned AttrAlign = ED->getMaxAlignment()) {
2563 Info.Align = AttrAlign;
2564 Info.AlignRequirement = AlignRequirementKind::RequiredByEnum;
2565 }
2566 return Info;
2567 }
2568
2569 const auto *RD = cast<RecordDecl>(Val: TD);
2570 const ASTRecordLayout &Layout = getASTRecordLayout(D: RD);
2571 Width = toBits(CharSize: Layout.getSize());
2572 Align = toBits(CharSize: Layout.getAlignment());
2573 AlignRequirement = RD->hasAttr<AlignedAttr>()
2574 ? AlignRequirementKind::RequiredByRecord
2575 : AlignRequirementKind::None;
2576 break;
2577 }
2578
2579 case Type::SubstTemplateTypeParm:
2580 return getTypeInfo(T: cast<SubstTemplateTypeParmType>(Val: T)->
2581 getReplacementType().getTypePtr());
2582
2583 case Type::Auto:
2584 case Type::DeducedTemplateSpecialization: {
2585 const auto *A = cast<DeducedType>(Val: T);
2586 assert(!A->getDeducedType().isNull() &&
2587 "cannot request the size of an undeduced or dependent auto type");
2588 return getTypeInfo(T: A->getDeducedType().getTypePtr());
2589 }
2590
2591 case Type::Paren:
2592 return getTypeInfo(T: cast<ParenType>(Val: T)->getInnerType().getTypePtr());
2593
2594 case Type::MacroQualified:
2595 return getTypeInfo(
2596 T: cast<MacroQualifiedType>(Val: T)->getUnderlyingType().getTypePtr());
2597
2598 case Type::ObjCTypeParam:
2599 return getTypeInfo(T: cast<ObjCTypeParamType>(Val: T)->desugar().getTypePtr());
2600
2601 case Type::Using:
2602 return getTypeInfo(T: cast<UsingType>(Val: T)->desugar().getTypePtr());
2603
2604 case Type::Typedef: {
2605 const auto *TT = cast<TypedefType>(Val: T);
2606 TypeInfo Info = getTypeInfo(T: TT->desugar().getTypePtr());
2607 // If the typedef has an aligned attribute on it, it overrides any computed
2608 // alignment we have. This violates the GCC documentation (which says that
2609 // attribute(aligned) can only round up) but matches its implementation.
2610 if (unsigned AttrAlign = TT->getDecl()->getMaxAlignment()) {
2611 Align = AttrAlign;
2612 AlignRequirement = AlignRequirementKind::RequiredByTypedef;
2613 } else {
2614 Align = Info.Align;
2615 AlignRequirement = Info.AlignRequirement;
2616 }
2617 Width = Info.Width;
2618 break;
2619 }
2620
2621 case Type::Attributed:
2622 return getTypeInfo(
2623 T: cast<AttributedType>(Val: T)->getEquivalentType().getTypePtr());
2624
2625 case Type::CountAttributed:
2626 return getTypeInfo(T: cast<CountAttributedType>(Val: T)->desugar().getTypePtr());
2627
2628 case Type::LateParsedAttr:
2629 return getTypeInfo(T: cast<LateParsedAttrType>(Val: T)->desugar().getTypePtr());
2630
2631 case Type::BTFTagAttributed:
2632 return getTypeInfo(
2633 T: cast<BTFTagAttributedType>(Val: T)->getWrappedType().getTypePtr());
2634
2635 case Type::OverflowBehavior:
2636 return getTypeInfo(
2637 T: cast<OverflowBehaviorType>(Val: T)->getUnderlyingType().getTypePtr());
2638
2639 case Type::HLSLAttributedResource:
2640 return getTypeInfo(
2641 T: cast<HLSLAttributedResourceType>(Val: T)->getWrappedType().getTypePtr());
2642
2643 case Type::HLSLInlineSpirv: {
2644 const auto *ST = cast<HLSLInlineSpirvType>(Val: T);
2645 // Size is specified in bytes, convert to bits
2646 Width = ST->getSize() * 8;
2647 Align = ST->getAlignment();
2648 if (Width == 0 && Align == 0) {
2649 // We are defaulting to laying out opaque SPIR-V types as 32-bit ints.
2650 Width = 32;
2651 Align = 32;
2652 }
2653 break;
2654 }
2655
2656 case Type::Atomic: {
2657 // Start with the base type information.
2658 TypeInfo Info = getTypeInfo(T: cast<AtomicType>(Val: T)->getValueType());
2659 Width = Info.Width;
2660 Align = Info.Align;
2661
2662 if (!Width) {
2663 // An otherwise zero-sized type should still generate an
2664 // atomic operation.
2665 Width = Target->getCharWidth();
2666 assert(Align);
2667 } else if (Width <= Target->getMaxAtomicPromoteWidth()) {
2668 // If the size of the type doesn't exceed the platform's max
2669 // atomic promotion width, make the size and alignment more
2670 // favorable to atomic operations:
2671
2672 // Round the size up to a power of 2.
2673 Width = llvm::bit_ceil(Value: Width);
2674
2675 // Set the alignment equal to the size.
2676 Align = static_cast<unsigned>(Width);
2677 }
2678 }
2679 break;
2680
2681 case Type::PredefinedSugar:
2682 return getTypeInfo(T: cast<PredefinedSugarType>(Val: T)->desugar().getTypePtr());
2683
2684 case Type::Pipe:
2685 Width = Target->getPointerWidth(AddrSpace: LangAS::opencl_global);
2686 Align = Target->getPointerAlign(AddrSpace: LangAS::opencl_global);
2687 break;
2688 }
2689
2690 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
2691 return TypeInfo(Width, Align, AlignRequirement);
2692}
2693
2694unsigned ASTContext::getTypeUnadjustedAlign(const Type *T) const {
2695 UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(Val: T);
2696 if (I != MemoizedUnadjustedAlign.end())
2697 return I->second;
2698
2699 unsigned UnadjustedAlign;
2700 if (const auto *RT = T->getAsCanonical<RecordType>()) {
2701 const ASTRecordLayout &Layout = getASTRecordLayout(D: RT->getDecl());
2702 UnadjustedAlign = toBits(CharSize: Layout.getUnadjustedAlignment());
2703 } else if (const auto *ObjCI = T->getAsCanonical<ObjCInterfaceType>()) {
2704 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(D: ObjCI->getDecl());
2705 UnadjustedAlign = toBits(CharSize: Layout.getUnadjustedAlignment());
2706 } else {
2707 UnadjustedAlign = getTypeAlign(T: T->getUnqualifiedDesugaredType());
2708 }
2709
2710 MemoizedUnadjustedAlign[T] = UnadjustedAlign;
2711 return UnadjustedAlign;
2712}
2713
2714unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
2715 unsigned SimdAlign = llvm::OpenMPIRBuilder::getOpenMPDefaultSimdAlign(
2716 TargetTriple: getTargetInfo().getTriple(), Features: Target->getTargetOpts().FeatureMap);
2717 return SimdAlign;
2718}
2719
2720/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
2721CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
2722 return CharUnits::fromQuantity(Quantity: BitSize / getCharWidth());
2723}
2724
2725/// toBits - Convert a size in characters to a size in characters.
2726int64_t ASTContext::toBits(CharUnits CharSize) const {
2727 return CharSize.getQuantity() * getCharWidth();
2728}
2729
2730/// getTypeSizeInChars - Return the size of the specified type, in characters.
2731/// This method does not work on incomplete types.
2732CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
2733 return getTypeInfoInChars(T).Width;
2734}
2735CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
2736 return getTypeInfoInChars(T).Width;
2737}
2738
2739/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
2740/// characters. This method does not work on incomplete types.
2741CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
2742 return toCharUnitsFromBits(BitSize: getTypeAlign(T));
2743}
2744CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
2745 return toCharUnitsFromBits(BitSize: getTypeAlign(T));
2746}
2747
2748/// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a
2749/// type, in characters, before alignment adjustments. This method does
2750/// not work on incomplete types.
2751CharUnits ASTContext::getTypeUnadjustedAlignInChars(QualType T) const {
2752 return toCharUnitsFromBits(BitSize: getTypeUnadjustedAlign(T));
2753}
2754CharUnits ASTContext::getTypeUnadjustedAlignInChars(const Type *T) const {
2755 return toCharUnitsFromBits(BitSize: getTypeUnadjustedAlign(T));
2756}
2757
2758/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
2759/// type for the current target in bits. This can be different than the ABI
2760/// alignment in cases where it is beneficial for performance or backwards
2761/// compatibility preserving to overalign a data type. (Note: despite the name,
2762/// the preferred alignment is ABI-impacting, and not an optimization.)
2763unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
2764 TypeInfo TI = getTypeInfo(T);
2765 unsigned ABIAlign = TI.Align;
2766
2767 T = T->getBaseElementTypeUnsafe();
2768
2769 // The preferred alignment of member pointers is that of a pointer.
2770 if (T->isMemberPointerType())
2771 return getPreferredTypeAlign(T: getPointerDiffType().getTypePtr());
2772
2773 if (!Target->allowsLargerPreferedTypeAlignment())
2774 return ABIAlign;
2775
2776 if (const auto *RD = T->getAsRecordDecl()) {
2777 // When used as part of a typedef, or together with a 'packed' attribute,
2778 // the 'aligned' attribute can be used to decrease alignment. Note that the
2779 // 'packed' case is already taken into consideration when computing the
2780 // alignment, we only need to handle the typedef case here.
2781 if (TI.AlignRequirement == AlignRequirementKind::RequiredByTypedef ||
2782 RD->isInvalidDecl())
2783 return ABIAlign;
2784
2785 unsigned PreferredAlign = static_cast<unsigned>(
2786 toBits(CharSize: getASTRecordLayout(D: RD).PreferredAlignment));
2787 assert(PreferredAlign >= ABIAlign &&
2788 "PreferredAlign should be at least as large as ABIAlign.");
2789 return PreferredAlign;
2790 }
2791
2792 // Double (and, for targets supporting AIX `power` alignment, long double) and
2793 // long long should be naturally aligned (despite requiring less alignment) if
2794 // possible.
2795 if (const auto *CT = T->getAs<ComplexType>())
2796 T = CT->getElementType().getTypePtr();
2797 if (const auto *ED = T->getAsEnumDecl())
2798 T = ED->getIntegerType().getTypePtr();
2799 if (T->isSpecificBuiltinType(K: BuiltinType::Double) ||
2800 T->isSpecificBuiltinType(K: BuiltinType::LongLong) ||
2801 T->isSpecificBuiltinType(K: BuiltinType::ULongLong) ||
2802 (T->isSpecificBuiltinType(K: BuiltinType::LongDouble) &&
2803 Target->defaultsToAIXPowerAlignment()))
2804 // Don't increase the alignment if an alignment attribute was specified on a
2805 // typedef declaration.
2806 if (!TI.isAlignRequired())
2807 return std::max(a: ABIAlign, b: (unsigned)getTypeSize(T));
2808
2809 return ABIAlign;
2810}
2811
2812/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2813/// for __attribute__((aligned)) on this target, to be used if no alignment
2814/// value is specified.
2815unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const {
2816 return getTargetInfo().getDefaultAlignForAttributeAligned();
2817}
2818
2819/// getAlignOfGlobalVar - Return the alignment in bits that should be given
2820/// to a global variable of the specified type.
2821unsigned ASTContext::getAlignOfGlobalVar(QualType T, const VarDecl *VD) const {
2822 uint64_t TypeSize = getTypeSize(T: T.getTypePtr());
2823 return std::max(a: getPreferredTypeAlign(T),
2824 b: getMinGlobalAlignOfVar(Size: TypeSize, VD));
2825}
2826
2827/// getAlignOfGlobalVarInChars - Return the alignment in characters that
2828/// should be given to a global variable of the specified type.
2829CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T,
2830 const VarDecl *VD) const {
2831 return toCharUnitsFromBits(BitSize: getAlignOfGlobalVar(T, VD));
2832}
2833
2834unsigned ASTContext::getMinGlobalAlignOfVar(uint64_t Size,
2835 const VarDecl *VD) const {
2836 // Make the default handling as that of a non-weak definition in the
2837 // current translation unit.
2838 bool HasNonWeakDef = !VD || (VD->hasDefinition() && !VD->isWeak());
2839 return getTargetInfo().getMinGlobalAlign(Size, HasNonWeakDef);
2840}
2841
2842CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
2843 CharUnits Offset = CharUnits::Zero();
2844 const ASTRecordLayout *Layout = &getASTRecordLayout(D: RD);
2845 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2846 Offset += Layout->getBaseClassOffset(Base);
2847 Layout = &getASTRecordLayout(D: Base);
2848 }
2849 return Offset;
2850}
2851
2852CharUnits ASTContext::getMemberPointerPathAdjustment(const APValue &MP) const {
2853 const ValueDecl *MPD = MP.getMemberPointerDecl();
2854 CharUnits ThisAdjustment = CharUnits::Zero();
2855 ArrayRef<const CXXRecordDecl*> Path = MP.getMemberPointerPath();
2856 bool DerivedMember = MP.isMemberPointerToDerivedMember();
2857 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Val: MPD->getDeclContext());
2858 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
2859 const CXXRecordDecl *Base = RD;
2860 const CXXRecordDecl *Derived = Path[I];
2861 if (DerivedMember)
2862 std::swap(a&: Base, b&: Derived);
2863 ThisAdjustment += getASTRecordLayout(D: Derived).getBaseClassOffset(Base);
2864 RD = Path[I];
2865 }
2866 if (DerivedMember)
2867 ThisAdjustment = -ThisAdjustment;
2868 return ThisAdjustment;
2869}
2870
2871/// DeepCollectObjCIvars -
2872/// This routine first collects all declared, but not synthesized, ivars in
2873/// super class and then collects all ivars, including those synthesized for
2874/// current class. This routine is used for implementation of current class
2875/// when all ivars, declared and synthesized are known.
2876void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
2877 bool leafClass,
2878 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
2879 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2880 DeepCollectObjCIvars(OI: SuperClass, leafClass: false, Ivars);
2881 if (!leafClass) {
2882 llvm::append_range(C&: Ivars, R: OI->ivars());
2883 } else {
2884 auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
2885 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
2886 Iv= Iv->getNextIvar())
2887 Ivars.push_back(Elt: Iv);
2888 }
2889}
2890
2891/// CollectInheritedProtocols - Collect all protocols in current class and
2892/// those inherited by it.
2893void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
2894 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
2895 if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(Val: CDecl)) {
2896 // We can use protocol_iterator here instead of
2897 // all_referenced_protocol_iterator since we are walking all categories.
2898 for (auto *Proto : OI->all_referenced_protocols()) {
2899 CollectInheritedProtocols(CDecl: Proto, Protocols);
2900 }
2901
2902 // Categories of this Interface.
2903 for (const auto *Cat : OI->visible_categories())
2904 CollectInheritedProtocols(CDecl: Cat, Protocols);
2905
2906 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2907 while (SD) {
2908 CollectInheritedProtocols(CDecl: SD, Protocols);
2909 SD = SD->getSuperClass();
2910 }
2911 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(Val: CDecl)) {
2912 for (auto *Proto : OC->protocols()) {
2913 CollectInheritedProtocols(CDecl: Proto, Protocols);
2914 }
2915 } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(Val: CDecl)) {
2916 // Insert the protocol.
2917 if (!Protocols.insert(
2918 Ptr: const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2919 return;
2920
2921 for (auto *Proto : OP->protocols())
2922 CollectInheritedProtocols(CDecl: Proto, Protocols);
2923 }
2924}
2925
2926static bool unionHasUniqueObjectRepresentations(const ASTContext &Context,
2927 const RecordDecl *RD,
2928 bool CheckIfTriviallyCopyable) {
2929 assert(RD->isUnion() && "Must be union type");
2930 CharUnits UnionSize =
2931 Context.getTypeSizeInChars(T: Context.getCanonicalTagType(TD: RD));
2932
2933 for (const auto *Field : RD->fields()) {
2934 if (!Context.hasUniqueObjectRepresentations(Ty: Field->getType(),
2935 CheckIfTriviallyCopyable))
2936 return false;
2937 CharUnits FieldSize = Context.getTypeSizeInChars(T: Field->getType());
2938 if (FieldSize != UnionSize)
2939 return false;
2940 }
2941 return !RD->field_empty();
2942}
2943
2944static int64_t getSubobjectOffset(const FieldDecl *Field,
2945 const ASTContext &Context,
2946 const clang::ASTRecordLayout & /*Layout*/) {
2947 return Context.getFieldOffset(FD: Field);
2948}
2949
2950static int64_t getSubobjectOffset(const CXXRecordDecl *RD,
2951 const ASTContext &Context,
2952 const clang::ASTRecordLayout &Layout) {
2953 return Context.toBits(CharSize: Layout.getBaseClassOffset(Base: RD));
2954}
2955
2956static std::optional<int64_t>
2957structHasUniqueObjectRepresentations(const ASTContext &Context,
2958 const RecordDecl *RD,
2959 bool CheckIfTriviallyCopyable);
2960
2961static std::optional<int64_t>
2962getSubobjectSizeInBits(const FieldDecl *Field, const ASTContext &Context,
2963 bool CheckIfTriviallyCopyable) {
2964 if (const auto *RD = Field->getType()->getAsRecordDecl();
2965 RD && !RD->isUnion())
2966 return structHasUniqueObjectRepresentations(Context, RD,
2967 CheckIfTriviallyCopyable);
2968
2969 // A _BitInt type may not be unique if it has padding bits
2970 // but if it is a bitfield the padding bits are not used.
2971 bool IsBitIntType = Field->getType()->isBitIntType();
2972 if (!Field->getType()->isReferenceType() && !IsBitIntType &&
2973 !Context.hasUniqueObjectRepresentations(Ty: Field->getType(),
2974 CheckIfTriviallyCopyable))
2975 return std::nullopt;
2976
2977 int64_t FieldSizeInBits =
2978 Context.toBits(CharSize: Context.getTypeSizeInChars(T: Field->getType()));
2979 if (Field->isBitField()) {
2980 // If we have explicit padding bits, they don't contribute bits
2981 // to the actual object representation, so return 0.
2982 if (Field->isUnnamedBitField())
2983 return 0;
2984
2985 int64_t BitfieldSize = Field->getBitWidthValue();
2986 if (IsBitIntType) {
2987 if ((unsigned)BitfieldSize >
2988 cast<BitIntType>(Val: Field->getType())->getNumBits())
2989 return std::nullopt;
2990 } else if (BitfieldSize > FieldSizeInBits) {
2991 return std::nullopt;
2992 }
2993 FieldSizeInBits = BitfieldSize;
2994 } else if (IsBitIntType && !Context.hasUniqueObjectRepresentations(
2995 Ty: Field->getType(), CheckIfTriviallyCopyable)) {
2996 return std::nullopt;
2997 }
2998 return FieldSizeInBits;
2999}
3000
3001static std::optional<int64_t>
3002getSubobjectSizeInBits(const CXXRecordDecl *RD, const ASTContext &Context,
3003 bool CheckIfTriviallyCopyable) {
3004 return structHasUniqueObjectRepresentations(Context, RD,
3005 CheckIfTriviallyCopyable);
3006}
3007
3008template <typename RangeT>
3009static std::optional<int64_t> structSubobjectsHaveUniqueObjectRepresentations(
3010 const RangeT &Subobjects, int64_t CurOffsetInBits,
3011 const ASTContext &Context, const clang::ASTRecordLayout &Layout,
3012 bool CheckIfTriviallyCopyable) {
3013 for (const auto *Subobject : Subobjects) {
3014 std::optional<int64_t> SizeInBits =
3015 getSubobjectSizeInBits(Subobject, Context, CheckIfTriviallyCopyable);
3016 if (!SizeInBits)
3017 return std::nullopt;
3018 if (*SizeInBits != 0) {
3019 int64_t Offset = getSubobjectOffset(Subobject, Context, Layout);
3020 if (Offset != CurOffsetInBits)
3021 return std::nullopt;
3022 CurOffsetInBits += *SizeInBits;
3023 }
3024 }
3025 return CurOffsetInBits;
3026}
3027
3028static std::optional<int64_t>
3029structHasUniqueObjectRepresentations(const ASTContext &Context,
3030 const RecordDecl *RD,
3031 bool CheckIfTriviallyCopyable) {
3032 assert(!RD->isUnion() && "Must be struct/class type");
3033 const auto &Layout = Context.getASTRecordLayout(D: RD);
3034
3035 int64_t CurOffsetInBits = 0;
3036 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(Val: RD)) {
3037 if (ClassDecl->isDynamicClass())
3038 return std::nullopt;
3039
3040 SmallVector<CXXRecordDecl *, 4> Bases;
3041 for (const auto &Base : ClassDecl->bases()) {
3042 // Empty types can be inherited from, and non-empty types can potentially
3043 // have tail padding, so just make sure there isn't an error.
3044 Bases.emplace_back(Args: Base.getType()->getAsCXXRecordDecl());
3045 }
3046
3047 llvm::sort(C&: Bases, Comp: [&](const CXXRecordDecl *L, const CXXRecordDecl *R) {
3048 return Layout.getBaseClassOffset(Base: L) < Layout.getBaseClassOffset(Base: R);
3049 });
3050
3051 std::optional<int64_t> OffsetAfterBases =
3052 structSubobjectsHaveUniqueObjectRepresentations(
3053 Subobjects: Bases, CurOffsetInBits, Context, Layout, CheckIfTriviallyCopyable);
3054 if (!OffsetAfterBases)
3055 return std::nullopt;
3056 CurOffsetInBits = *OffsetAfterBases;
3057 }
3058
3059 std::optional<int64_t> OffsetAfterFields =
3060 structSubobjectsHaveUniqueObjectRepresentations(
3061 Subobjects: RD->fields(), CurOffsetInBits, Context, Layout,
3062 CheckIfTriviallyCopyable);
3063 if (!OffsetAfterFields)
3064 return std::nullopt;
3065 CurOffsetInBits = *OffsetAfterFields;
3066
3067 return CurOffsetInBits;
3068}
3069
3070bool ASTContext::hasUniqueObjectRepresentations(
3071 QualType Ty, bool CheckIfTriviallyCopyable) const {
3072 // C++17 [meta.unary.prop]:
3073 // The predicate condition for a template specialization
3074 // has_unique_object_representations<T> shall be satisfied if and only if:
3075 // (9.1) - T is trivially copyable, and
3076 // (9.2) - any two objects of type T with the same value have the same
3077 // object representation, where:
3078 // - two objects of array or non-union class type are considered to have
3079 // the same value if their respective sequences of direct subobjects
3080 // have the same values, and
3081 // - two objects of union type are considered to have the same value if
3082 // they have the same active member and the corresponding members have
3083 // the same value.
3084 // The set of scalar types for which this condition holds is
3085 // implementation-defined. [ Note: If a type has padding bits, the condition
3086 // does not hold; otherwise, the condition holds true for unsigned integral
3087 // types. -- end note ]
3088 assert(!Ty.isNull() && "Null QualType sent to unique object rep check");
3089
3090 // Arrays are unique only if their element type is unique.
3091 if (Ty->isArrayType())
3092 return hasUniqueObjectRepresentations(Ty: getBaseElementType(QT: Ty),
3093 CheckIfTriviallyCopyable);
3094
3095 assert((Ty->isVoidType() || !Ty->isIncompleteType()) &&
3096 "hasUniqueObjectRepresentations should not be called with an "
3097 "incomplete type");
3098
3099 // (9.1) - T is trivially copyable...
3100 if (CheckIfTriviallyCopyable && !Ty.isTriviallyCopyableType(Context: *this))
3101 return false;
3102
3103 // All integrals and enums are unique.
3104 if (Ty->isIntegralOrEnumerationType()) {
3105 // Address discriminated integer types are not unique.
3106 if (Ty.hasAddressDiscriminatedPointerAuth())
3107 return false;
3108 // Except _BitInt types that have padding bits.
3109 if (const auto *BIT = Ty->getAs<BitIntType>())
3110 return getTypeSize(T: BIT) == BIT->getNumBits();
3111
3112 return true;
3113 }
3114
3115 // All other pointers are unique.
3116 if (Ty->isPointerType())
3117 return !Ty.hasAddressDiscriminatedPointerAuth();
3118
3119 if (const auto *MPT = Ty->getAs<MemberPointerType>())
3120 return !ABI->getMemberPointerInfo(MPT).HasPadding;
3121
3122 if (const auto *Record = Ty->getAsRecordDecl()) {
3123 if (Record->isInvalidDecl())
3124 return false;
3125
3126 if (Record->isUnion())
3127 return unionHasUniqueObjectRepresentations(Context: *this, RD: Record,
3128 CheckIfTriviallyCopyable);
3129
3130 std::optional<int64_t> StructSize = structHasUniqueObjectRepresentations(
3131 Context: *this, RD: Record, CheckIfTriviallyCopyable);
3132
3133 return StructSize && *StructSize == static_cast<int64_t>(getTypeSize(T: Ty));
3134 }
3135
3136 // FIXME: More cases to handle here (list by rsmith):
3137 // vectors (careful about, eg, vector of 3 foo)
3138 // _Complex int and friends
3139 // _Atomic T
3140 // Obj-C block pointers
3141 // Obj-C object pointers
3142 // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t,
3143 // clk_event_t, queue_t, reserve_id_t)
3144 // There're also Obj-C class types and the Obj-C selector type, but I think it
3145 // makes sense for those to return false here.
3146
3147 return false;
3148}
3149
3150unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
3151 unsigned count = 0;
3152 // Count ivars declared in class extension.
3153 for (const auto *Ext : OI->known_extensions())
3154 count += Ext->ivar_size();
3155
3156 // Count ivar defined in this class's implementation. This
3157 // includes synthesized ivars.
3158 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
3159 count += ImplDecl->ivar_size();
3160
3161 return count;
3162}
3163
3164bool ASTContext::isSentinelNullExpr(const Expr *E) {
3165 if (!E)
3166 return false;
3167
3168 // nullptr_t is always treated as null.
3169 if (E->getType()->isNullPtrType()) return true;
3170
3171 if (E->getType()->isAnyPointerType() &&
3172 E->IgnoreParenCasts()->isNullPointerConstant(Ctx&: *this,
3173 NPC: Expr::NPC_ValueDependentIsNull))
3174 return true;
3175
3176 // Unfortunately, __null has type 'int'.
3177 if (isa<GNUNullExpr>(Val: E)) return true;
3178
3179 return false;
3180}
3181
3182/// Get the implementation of ObjCInterfaceDecl, or nullptr if none
3183/// exists.
3184ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
3185 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
3186 I = ObjCImpls.find(Val: D);
3187 if (I != ObjCImpls.end())
3188 return cast<ObjCImplementationDecl>(Val: I->second);
3189 return nullptr;
3190}
3191
3192/// Get the implementation of ObjCCategoryDecl, or nullptr if none
3193/// exists.
3194ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
3195 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
3196 I = ObjCImpls.find(Val: D);
3197 if (I != ObjCImpls.end())
3198 return cast<ObjCCategoryImplDecl>(Val: I->second);
3199 return nullptr;
3200}
3201
3202/// Set the implementation of ObjCInterfaceDecl.
3203void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
3204 ObjCImplementationDecl *ImplD) {
3205 assert(IFaceD && ImplD && "Passed null params");
3206 ObjCImpls[IFaceD] = ImplD;
3207}
3208
3209/// Set the implementation of ObjCCategoryDecl.
3210void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
3211 ObjCCategoryImplDecl *ImplD) {
3212 assert(CatD && ImplD && "Passed null params");
3213 ObjCImpls[CatD] = ImplD;
3214}
3215
3216const ObjCMethodDecl *
3217ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const {
3218 return ObjCMethodRedecls.lookup(Val: MD);
3219}
3220
3221void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
3222 const ObjCMethodDecl *Redecl) {
3223 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
3224 ObjCMethodRedecls[MD] = Redecl;
3225}
3226
3227const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
3228 const NamedDecl *ND) const {
3229 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(Val: ND->getDeclContext()))
3230 return ID;
3231 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(Val: ND->getDeclContext()))
3232 return CD->getClassInterface();
3233 if (const auto *IMD = dyn_cast<ObjCImplDecl>(Val: ND->getDeclContext()))
3234 return IMD->getClassInterface();
3235
3236 return nullptr;
3237}
3238
3239/// Get the copy initialization expression of VarDecl, or nullptr if
3240/// none exists.
3241BlockVarCopyInit ASTContext::getBlockVarCopyInit(const VarDecl *VD) const {
3242 assert(VD && "Passed null params");
3243 assert(VD->hasAttr<BlocksAttr>() &&
3244 "getBlockVarCopyInits - not __block var");
3245 auto I = BlockVarCopyInits.find(Val: VD);
3246 if (I != BlockVarCopyInits.end())
3247 return I->second;
3248 return {nullptr, false};
3249}
3250
3251/// Set the copy initialization expression of a block var decl.
3252void ASTContext::setBlockVarCopyInit(const VarDecl*VD, Expr *CopyExpr,
3253 bool CanThrow) {
3254 assert(VD && CopyExpr && "Passed null params");
3255 assert(VD->hasAttr<BlocksAttr>() &&
3256 "setBlockVarCopyInits - not __block var");
3257 BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow);
3258}
3259
3260TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
3261 unsigned DataSize) const {
3262 if (!DataSize)
3263 DataSize = TypeLoc::getFullDataSizeForType(Ty: T);
3264 else
3265 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
3266 "incorrect data size provided to CreateTypeSourceInfo!");
3267
3268 auto *TInfo =
3269 (TypeSourceInfo*)BumpAlloc.Allocate(Size: sizeof(TypeSourceInfo) + DataSize, Alignment: 8);
3270 new (TInfo) TypeSourceInfo(T, DataSize);
3271 return TInfo;
3272}
3273
3274TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
3275 SourceLocation L) const {
3276 TypeSourceInfo *TSI = CreateTypeSourceInfo(T);
3277 TSI->getTypeLoc().initialize(Context&: const_cast<ASTContext &>(*this), Loc: L);
3278 return TSI;
3279}
3280
3281const ASTRecordLayout &
3282ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
3283 return getObjCLayout(D);
3284}
3285
3286static auto getCanonicalTemplateArguments(const ASTContext &C,
3287 ArrayRef<TemplateArgument> Args,
3288 bool &AnyNonCanonArgs) {
3289 SmallVector<TemplateArgument, 16> CanonArgs(Args);
3290 AnyNonCanonArgs |= C.canonicalizeTemplateArguments(Args: CanonArgs);
3291 return CanonArgs;
3292}
3293
3294bool ASTContext::canonicalizeTemplateArguments(
3295 MutableArrayRef<TemplateArgument> Args) const {
3296 bool AnyNonCanonArgs = false;
3297 for (auto &Arg : Args) {
3298 TemplateArgument OrigArg = Arg;
3299 Arg = getCanonicalTemplateArgument(Arg);
3300 AnyNonCanonArgs |= !Arg.structurallyEquals(Other: OrigArg);
3301 }
3302 return AnyNonCanonArgs;
3303}
3304
3305//===----------------------------------------------------------------------===//
3306// Type creation/memoization methods
3307//===----------------------------------------------------------------------===//
3308
3309QualType
3310ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
3311 unsigned fastQuals = quals.getFastQualifiers();
3312 quals.removeFastQualifiers();
3313
3314 // Check if we've already instantiated this type.
3315 llvm::FoldingSetNodeID ID;
3316 ExtQuals::Profile(ID, BaseType: baseType, Quals: quals);
3317 llvm::FoldingSetInsertToken Token;
3318 if (ExtQuals *eq = ExtQualNodes.lookup(ID, Token)) {
3319 assert(eq->getQualifiers() == quals);
3320 return QualType(eq, fastQuals);
3321 }
3322
3323 // If the base type is not canonical, make the appropriate canonical type.
3324 QualType canon;
3325 if (!baseType->isCanonicalUnqualified()) {
3326 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
3327 canonSplit.Quals.addConsistentQualifiers(qs: quals);
3328 canon = getExtQualType(baseType: canonSplit.Ty, quals: canonSplit.Quals);
3329
3330 // Re-find the insert position.
3331 (void)ExtQualNodes.lookup(ID, Token);
3332 }
3333
3334 auto *eq = new (*this, alignof(ExtQuals)) ExtQuals(baseType, canon, quals);
3335 ExtQualNodes.insert(N: eq, Token);
3336 return QualType(eq, fastQuals);
3337}
3338
3339QualType ASTContext::getAddrSpaceQualType(QualType T,
3340 LangAS AddressSpace) const {
3341 QualType CanT = getCanonicalType(T);
3342 if (CanT.getAddressSpace() == AddressSpace)
3343 return T;
3344
3345 // If we are composing extended qualifiers together, merge together
3346 // into one ExtQuals node.
3347 QualifierCollector Quals;
3348 const Type *TypeNode = Quals.strip(type: T);
3349
3350 // If this type already has an address space specified, it cannot get
3351 // another one.
3352 assert(!Quals.hasAddressSpace() &&
3353 "Type cannot be in multiple addr spaces!");
3354 Quals.addAddressSpace(space: AddressSpace);
3355
3356 return getExtQualType(baseType: TypeNode, quals: Quals);
3357}
3358
3359QualType ASTContext::removeAddrSpaceQualType(QualType T) const {
3360 // If the type is not qualified with an address space, just return it
3361 // immediately.
3362 if (!T.hasAddressSpace())
3363 return T;
3364
3365 QualifierCollector Quals;
3366 const Type *TypeNode;
3367 // For arrays, strip the qualifier off the element type, then reconstruct the
3368 // array type
3369 if (T.getTypePtr()->isArrayType()) {
3370 T = getUnqualifiedArrayType(T, Quals);
3371 TypeNode = T.getTypePtr();
3372 } else {
3373 // If we are composing extended qualifiers together, merge together
3374 // into one ExtQuals node.
3375 while (T.hasAddressSpace()) {
3376 TypeNode = Quals.strip(type: T);
3377
3378 // If the type no longer has an address space after stripping qualifiers,
3379 // jump out.
3380 if (!QualType(TypeNode, 0).hasAddressSpace())
3381 break;
3382
3383 // There might be sugar in the way. Strip it and try again.
3384 T = T.getSingleStepDesugaredType(Context: *this);
3385 }
3386 }
3387
3388 Quals.removeAddressSpace();
3389
3390 // Removal of the address space can mean there are no longer any
3391 // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts)
3392 // or required.
3393 if (Quals.hasNonFastQualifiers())
3394 return getExtQualType(baseType: TypeNode, quals: Quals);
3395 else
3396 return QualType(TypeNode, Quals.getFastQualifiers());
3397}
3398
3399uint16_t
3400ASTContext::getPointerAuthVTablePointerDiscriminator(const CXXRecordDecl *RD,
3401 bool IsVTTEntry) {
3402 assert(RD->isPolymorphic() &&
3403 "Attempted to get vtable pointer discriminator on a monomorphic type");
3404
3405 std::unique_ptr<MangleContext> MC(createMangleContext());
3406 SmallString<256> Str;
3407 llvm::raw_svector_ostream Out(Str);
3408 MC->mangleCXXVTable(RD, Out);
3409 if (IsVTTEntry)
3410 Out << VTTVTablePointerDiscriminatorSuffix;
3411 return llvm::getPointerAuthStableSipHash(S: Str);
3412}
3413
3414/// Encode a function type for use in the discriminator of a function pointer
3415/// type. We can't use the itanium scheme for this since C has quite permissive
3416/// rules for type compatibility that we need to be compatible with.
3417///
3418/// Formally, this function associates every function pointer type T with an
3419/// encoded string E(T). Let the equivalence relation T1 ~ T2 be defined as
3420/// E(T1) == E(T2). E(T) is part of the ABI of values of type T. C type
3421/// compatibility requires equivalent treatment under the ABI, so
3422/// CCompatible(T1, T2) must imply E(T1) == E(T2), that is, CCompatible must be
3423/// a subset of ~. Crucially, however, it must be a proper subset because
3424/// CCompatible is not an equivalence relation: for example, int[] is compatible
3425/// with both int[1] and int[2], but the latter are not compatible with each
3426/// other. Therefore this encoding function must be careful to only distinguish
3427/// types if there is no third type with which they are both required to be
3428/// compatible.
3429static void encodeTypeForFunctionPointerAuth(const ASTContext &Ctx,
3430 raw_ostream &OS, QualType QT) {
3431 // FIXME: Consider address space qualifiers.
3432 const Type *T = QT.getCanonicalType().getTypePtr();
3433
3434 // FIXME: Consider using the C++ type mangling when we encounter a construct
3435 // that is incompatible with C.
3436
3437 switch (T->getTypeClass()) {
3438 case Type::Atomic:
3439 return encodeTypeForFunctionPointerAuth(
3440 Ctx, OS, QT: cast<AtomicType>(Val: T)->getValueType());
3441
3442 case Type::LValueReference:
3443 OS << "R";
3444 encodeTypeForFunctionPointerAuth(Ctx, OS,
3445 QT: cast<ReferenceType>(Val: T)->getPointeeType());
3446 return;
3447 case Type::RValueReference:
3448 OS << "O";
3449 encodeTypeForFunctionPointerAuth(Ctx, OS,
3450 QT: cast<ReferenceType>(Val: T)->getPointeeType());
3451 return;
3452
3453 case Type::Pointer:
3454 // C11 6.7.6.1p2:
3455 // For two pointer types to be compatible, both shall be identically
3456 // qualified and both shall be pointers to compatible types.
3457 // FIXME: we should also consider pointee types.
3458 OS << "P";
3459 return;
3460
3461 case Type::ObjCObjectPointer:
3462 case Type::BlockPointer:
3463 OS << "P";
3464 return;
3465
3466 case Type::Complex:
3467 OS << "C";
3468 return encodeTypeForFunctionPointerAuth(
3469 Ctx, OS, QT: cast<ComplexType>(Val: T)->getElementType());
3470
3471 case Type::VariableArray:
3472 case Type::ConstantArray:
3473 case Type::IncompleteArray:
3474 case Type::ArrayParameter:
3475 // C11 6.7.6.2p6:
3476 // For two array types to be compatible, both shall have compatible
3477 // element types, and if both size specifiers are present, and are integer
3478 // constant expressions, then both size specifiers shall have the same
3479 // constant value [...]
3480 //
3481 // So since ElemType[N] has to be compatible ElemType[], we can't encode the
3482 // width of the array.
3483 OS << "A";
3484 return encodeTypeForFunctionPointerAuth(
3485 Ctx, OS, QT: cast<ArrayType>(Val: T)->getElementType());
3486
3487 case Type::ObjCInterface:
3488 case Type::ObjCObject:
3489 OS << "<objc_object>";
3490 return;
3491
3492 case Type::Enum: {
3493 // C11 6.7.2.2p4:
3494 // Each enumerated type shall be compatible with char, a signed integer
3495 // type, or an unsigned integer type.
3496 //
3497 // So we have to treat enum types as integers.
3498 QualType UnderlyingType = T->castAsEnumDecl()->getIntegerType();
3499 return encodeTypeForFunctionPointerAuth(
3500 Ctx, OS, QT: UnderlyingType.isNull() ? Ctx.IntTy : UnderlyingType);
3501 }
3502
3503 case Type::FunctionNoProto:
3504 case Type::FunctionProto: {
3505 // C11 6.7.6.3p15:
3506 // For two function types to be compatible, both shall specify compatible
3507 // return types. Moreover, the parameter type lists, if both are present,
3508 // shall agree in the number of parameters and in the use of the ellipsis
3509 // terminator; corresponding parameters shall have compatible types.
3510 //
3511 // That paragraph goes on to describe how unprototyped functions are to be
3512 // handled, which we ignore here. Unprototyped function pointers are hashed
3513 // as though they were prototyped nullary functions since thats probably
3514 // what the user meant. This behavior is non-conforming.
3515 // FIXME: If we add a "custom discriminator" function type attribute we
3516 // should encode functions as their discriminators.
3517 OS << "F";
3518 const auto *FuncType = cast<FunctionType>(Val: T);
3519 encodeTypeForFunctionPointerAuth(Ctx, OS, QT: FuncType->getReturnType());
3520 if (const auto *FPT = dyn_cast<FunctionProtoType>(Val: FuncType)) {
3521 for (QualType Param : FPT->param_types()) {
3522 Param = Ctx.getSignatureParameterType(T: Param);
3523 encodeTypeForFunctionPointerAuth(Ctx, OS, QT: Param);
3524 }
3525 if (FPT->isVariadic())
3526 OS << "z";
3527 }
3528 OS << "E";
3529 return;
3530 }
3531
3532 case Type::MemberPointer: {
3533 OS << "M";
3534 const auto *MPT = T->castAs<MemberPointerType>();
3535 encodeTypeForFunctionPointerAuth(
3536 Ctx, OS, QT: QualType(MPT->getQualifier().getAsType(), 0));
3537 encodeTypeForFunctionPointerAuth(Ctx, OS, QT: MPT->getPointeeType());
3538 return;
3539 }
3540 case Type::ExtVector:
3541 case Type::Vector:
3542 OS << "Dv" << Ctx.getTypeSizeInChars(T).getQuantity();
3543 break;
3544
3545 // Don't bother discriminating based on these types.
3546 case Type::Pipe:
3547 case Type::BitInt:
3548 case Type::ConstantMatrix:
3549 OS << "?";
3550 return;
3551
3552 case Type::Builtin: {
3553 const auto *BTy = T->castAs<BuiltinType>();
3554 switch (BTy->getKind()) {
3555#define SIGNED_TYPE(Id, SingletonId) \
3556 case BuiltinType::Id: \
3557 OS << "i"; \
3558 return;
3559#define UNSIGNED_TYPE(Id, SingletonId) \
3560 case BuiltinType::Id: \
3561 OS << "i"; \
3562 return;
3563#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
3564#define BUILTIN_TYPE(Id, SingletonId)
3565#include "clang/AST/BuiltinTypes.def"
3566 llvm_unreachable("placeholder types should not appear here.");
3567
3568 case BuiltinType::Half:
3569 OS << "Dh";
3570 return;
3571 case BuiltinType::Float:
3572 OS << "f";
3573 return;
3574 case BuiltinType::Double:
3575 OS << "d";
3576 return;
3577 case BuiltinType::LongDouble:
3578 OS << "e";
3579 return;
3580 case BuiltinType::Float16:
3581 OS << "DF16_";
3582 return;
3583 case BuiltinType::Float128:
3584 OS << "g";
3585 return;
3586
3587 case BuiltinType::Void:
3588 OS << "v";
3589 return;
3590
3591 case BuiltinType::ObjCId:
3592 case BuiltinType::ObjCClass:
3593 case BuiltinType::ObjCSel:
3594 case BuiltinType::NullPtr:
3595 OS << "P";
3596 return;
3597
3598 // Don't bother discriminating based on OpenCL types.
3599 case BuiltinType::OCLSampler:
3600 case BuiltinType::OCLEvent:
3601 case BuiltinType::OCLClkEvent:
3602 case BuiltinType::OCLQueue:
3603 case BuiltinType::OCLReserveID:
3604 case BuiltinType::BFloat16:
3605 case BuiltinType::VectorQuad:
3606 case BuiltinType::VectorPair:
3607 case BuiltinType::DMR1024:
3608 case BuiltinType::DMR2048:
3609 case BuiltinType::MetaInfo:
3610 OS << "?";
3611 return;
3612
3613 // Don't bother discriminating based on these seldom-used types.
3614 case BuiltinType::Ibm128:
3615 return;
3616#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
3617 case BuiltinType::Id: \
3618 return;
3619#include "clang/Basic/OpenCLImageTypes.def"
3620#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
3621 case BuiltinType::Id: \
3622 return;
3623#include "clang/Basic/OpenCLExtensionTypes.def"
3624#define SVE_TYPE(Name, Id, SingletonId) \
3625 case BuiltinType::Id: \
3626 return;
3627#include "clang/Basic/AArch64ACLETypes.def"
3628#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
3629 case BuiltinType::Id: \
3630 return;
3631#include "clang/Basic/HLSLIntangibleTypes.def"
3632#define HLSL_PACKED_TYPE(Name, Id, SingletonId) \
3633 case BuiltinType::Id: \
3634 return;
3635#include "clang/Basic/HLSLPackedTypes.def"
3636 case BuiltinType::Dependent:
3637 llvm_unreachable("should never get here");
3638#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
3639#include "clang/Basic/AMDGPUTypes.def"
3640 case BuiltinType::WasmExternRef:
3641#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
3642#include "clang/Basic/RISCVVTypes.def"
3643#define SPIRV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
3644#include "clang/Basic/SPIRVTypes.def"
3645 llvm_unreachable("not yet implemented");
3646 }
3647 llvm_unreachable("should never get here");
3648 }
3649 case Type::Record: {
3650 const RecordDecl *RD = T->castAsCanonical<RecordType>()->getDecl();
3651 const IdentifierInfo *II = RD->getIdentifier();
3652
3653 // In C++, an immediate typedef of an anonymous struct or union
3654 // is considered to name it for ODR purposes, but C's specification
3655 // of type compatibility does not have a similar rule. Using the typedef
3656 // name in function type discriminators anyway, as we do here,
3657 // therefore technically violates the C standard: two function pointer
3658 // types defined in terms of two typedef'd anonymous structs with
3659 // different names are formally still compatible, but we are assigning
3660 // them different discriminators and therefore incompatible ABIs.
3661 //
3662 // This is a relatively minor violation that significantly improves
3663 // discrimination in some cases and has not caused problems in
3664 // practice. Regardless, it is now part of the ABI in places where
3665 // function type discrimination is used, and it can no longer be
3666 // changed except on new platforms.
3667
3668 if (!II)
3669 if (const TypedefNameDecl *Typedef = RD->getTypedefNameForAnonDecl())
3670 II = Typedef->getDeclName().getAsIdentifierInfo();
3671
3672 if (!II) {
3673 OS << "<anonymous_record>";
3674 return;
3675 }
3676 OS << II->getLength() << II->getName();
3677 return;
3678 }
3679 case Type::HLSLAttributedResource:
3680 case Type::HLSLInlineSpirv:
3681 llvm_unreachable("should never get here");
3682 break;
3683 case Type::OverflowBehavior:
3684 llvm_unreachable("should never get here");
3685 break;
3686 case Type::DeducedTemplateSpecialization:
3687 case Type::Auto:
3688#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3689#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3690#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
3691#define ABSTRACT_TYPE(Class, Base)
3692#define TYPE(Class, Base)
3693#include "clang/AST/TypeNodes.inc"
3694 llvm_unreachable("unexpected non-canonical or dependent type!");
3695 return;
3696 }
3697}
3698
3699uint16_t ASTContext::getPointerAuthTypeDiscriminator(QualType T) {
3700 assert(!T->isDependentType() &&
3701 "cannot compute type discriminator of a dependent type");
3702 SmallString<256> Str;
3703 llvm::raw_svector_ostream Out(Str);
3704
3705 if (T->isFunctionPointerType() || T->isFunctionReferenceType())
3706 T = T->getPointeeType();
3707
3708 if (T->isFunctionType()) {
3709 encodeTypeForFunctionPointerAuth(Ctx: *this, OS&: Out, QT: T);
3710 } else {
3711 T = T.getUnqualifiedType();
3712 // Calls to member function pointers don't need to worry about
3713 // language interop or the laxness of the C type compatibility rules.
3714 // We just mangle the member pointer type directly, which is
3715 // implicitly much stricter about type matching. However, we do
3716 // strip any top-level exception specification before this mangling.
3717 // C++23 requires calls to work when the function type is convertible
3718 // to the pointer type by a function pointer conversion, which can
3719 // change the exception specification. This does not technically
3720 // require the exception specification to not affect representation,
3721 // because the function pointer conversion is still always a direct
3722 // value conversion and therefore an opportunity to resign the
3723 // pointer. (This is in contrast to e.g. qualification conversions,
3724 // which can be applied in nested pointer positions, effectively
3725 // requiring qualified and unqualified representations to match.)
3726 // However, it is pragmatic to ignore exception specifications
3727 // because it allows a certain amount of `noexcept` mismatching
3728 // to not become a visible ODR problem. This also leaves some
3729 // room for the committee to add laxness to function pointer
3730 // conversions in future standards.
3731 if (auto *MPT = T->getAs<MemberPointerType>())
3732 if (MPT->isMemberFunctionPointer()) {
3733 QualType PointeeType = MPT->getPointeeType();
3734 if (PointeeType->castAs<FunctionProtoType>()->getExceptionSpecType() !=
3735 EST_None) {
3736 QualType FT = getFunctionTypeWithExceptionSpec(Orig: PointeeType, ESI: EST_None);
3737 T = getMemberPointerType(T: FT, Qualifier: MPT->getQualifier(),
3738 Cls: MPT->getMostRecentCXXRecordDecl());
3739 }
3740 }
3741 std::unique_ptr<MangleContext> MC(createMangleContext());
3742 MC->mangleCanonicalTypeName(T, Out);
3743 }
3744
3745 return llvm::getPointerAuthStableSipHash(S: Str);
3746}
3747
3748QualType ASTContext::getObjCGCQualType(QualType T,
3749 Qualifiers::GC GCAttr) const {
3750 QualType CanT = getCanonicalType(T);
3751 if (CanT.getObjCGCAttr() == GCAttr)
3752 return T;
3753
3754 if (const auto *ptr = T->getAs<PointerType>()) {
3755 QualType Pointee = ptr->getPointeeType();
3756 if (Pointee->isAnyPointerType()) {
3757 QualType ResultType = getObjCGCQualType(T: Pointee, GCAttr);
3758 return getPointerType(T: ResultType);
3759 }
3760 }
3761
3762 // If we are composing extended qualifiers together, merge together
3763 // into one ExtQuals node.
3764 QualifierCollector Quals;
3765 const Type *TypeNode = Quals.strip(type: T);
3766
3767 // If this type already has an ObjCGC specified, it cannot get
3768 // another one.
3769 assert(!Quals.hasObjCGCAttr() &&
3770 "Type cannot have multiple ObjCGCs!");
3771 Quals.addObjCGCAttr(type: GCAttr);
3772
3773 return getExtQualType(baseType: TypeNode, quals: Quals);
3774}
3775
3776QualType ASTContext::removePtrSizeAddrSpace(QualType T) const {
3777 if (const PointerType *Ptr = T->getAs<PointerType>()) {
3778 QualType Pointee = Ptr->getPointeeType();
3779 if (isPtrSizeAddressSpace(AS: Pointee.getAddressSpace())) {
3780 return getPointerType(T: removeAddrSpaceQualType(T: Pointee));
3781 }
3782 }
3783 return T;
3784}
3785
3786QualType ASTContext::getCountAttributedType(
3787 QualType WrappedTy, Expr *CountExpr, bool CountInBytes, bool OrNull,
3788 ArrayRef<TypeCoupledDeclRefInfo> DependentDecls) const {
3789 assert(WrappedTy->isPointerType() || WrappedTy->isArrayType());
3790 assert(CountExpr && "use getIncompleteCountAttributedType for a null count");
3791
3792 // Complete (non-late-parsed) path: the count expression is known up front.
3793 // This deliberately preserves the pre-existing uniquing behavior -- the
3794 // FoldingSet lookup/insert below is unchanged by late-parse support. Only
3795 // getIncompleteCountAttributedType (count filled in later) opts out of
3796 // uniquing.
3797 llvm::FoldingSetNodeID ID;
3798 CountAttributedType::Profile(ID, WrappedTy, CountExpr, CountInBytes, Nullable: OrNull);
3799
3800 llvm::FoldingSetInsertToken Token;
3801 CountAttributedType *CATy = CountAttributedTypes.lookup(ID, Token);
3802 if (CATy)
3803 return QualType(CATy, 0);
3804
3805 QualType CanonTy = getCanonicalType(T: WrappedTy);
3806 CATy = CountAttributedType::Create(Ctx: *this, Wrapped: WrappedTy, Canon: CanonTy, CountExpr,
3807 CountInBytes, OrNull, CoupledDecls: DependentDecls);
3808 Types.push_back(Elt: CATy);
3809 CountAttributedTypes.insert(N: CATy, Token);
3810
3811 return QualType(CATy, 0);
3812}
3813
3814CountAttributedType *ASTContext::getIncompleteCountAttributedType(
3815 QualType WrappedTy, bool CountInBytes, bool OrNull) const {
3816 assert(WrappedTy->isPointerType() || WrappedTy->isArrayType());
3817
3818 // Deliberately opts out of the uniquing that `getCountAttributedType` does:
3819 // `CountAttributedType::Profile` keys on the `CountExpr` pointer, which is
3820 // null here, so every incomplete node would profile identically as
3821 // `(WrappedTy, flags, nullptr)` and two fields with different counts would
3822 // collide. The node stays un-uniqued even after completion; see
3823 // `completeCountAttributedType`.
3824 //
3825 // Also deliberately not in `Types` yet. An incomplete node can be abandoned
3826 // without ever being completed (a nested counted_by, or an argument that
3827 // fails to parse), and a null-count node must not be reachable by anything
3828 // that scans `Types`. `completeCountAttributedType` registers it once the
3829 // count is in place.
3830 return CountAttributedType::Create(
3831 Ctx: *this, Wrapped: WrappedTy, Canon: getCanonicalType(T: WrappedTy),
3832 /*CountExpr=*/nullptr, CountInBytes, OrNull,
3833 /*CoupledDecls=*/{});
3834}
3835
3836void ASTContext::completeCountAttributedType(
3837 CountAttributedType *CATy, Expr *CountExpr,
3838 ArrayRef<TypeCoupledDeclRefInfo> DependentDecls) const {
3839 CATy->complete(Ctx: *this, E: CountExpr, CoupledDecls: DependentDecls);
3840 // Safe for `Types` scanners now that the count is in place; see
3841 // `getIncompleteCountAttributedType` for why it was held back.
3842 //
3843 // It stays out of the `CountAttributedTypes` FoldingSet permanently, unlike
3844 // an eagerly built node: this pointer is already embedded in the enclosing
3845 // types and handed out, so an equal node that happens to exist cannot be
3846 // merged into. The only cost is that a completed node is never
3847 // pointer-shared with an equal eager one, which does not affect semantic
3848 // type equality -- `hasSameType` compares canonical types, and this sugar's
3849 // canonical type is the wrapped type's.
3850 Types.push_back(Elt: CATy);
3851}
3852
3853QualType ASTContext::getLateParsedAttrType(
3854 QualType WrappedTy, LateParsedTypeAttribute *LateParsedAttr) const {
3855 QualType CanonTy = getCanonicalType(T: WrappedTy);
3856
3857 auto *LPATy = new (*this, alignof(LateParsedAttrType))
3858 LateParsedAttrType(WrappedTy, CanonTy, LateParsedAttr);
3859
3860 Types.push_back(Elt: LPATy);
3861 return QualType(LPATy, 0);
3862}
3863
3864QualType
3865ASTContext::adjustType(QualType Orig,
3866 llvm::function_ref<QualType(QualType)> Adjust) const {
3867 switch (Orig->getTypeClass()) {
3868 case Type::Attributed: {
3869 const auto *AT = cast<AttributedType>(Val&: Orig);
3870 return getAttributedType(attrKind: AT->getAttrKind(),
3871 modifiedType: adjustType(Orig: AT->getModifiedType(), Adjust),
3872 equivalentType: adjustType(Orig: AT->getEquivalentType(), Adjust),
3873 attr: AT->getAttr());
3874 }
3875
3876 case Type::BTFTagAttributed: {
3877 const auto *BTFT = dyn_cast<BTFTagAttributedType>(Val&: Orig);
3878 return getBTFTagAttributedType(BTFAttr: BTFT->getAttr(),
3879 Wrapped: adjustType(Orig: BTFT->getWrappedType(), Adjust));
3880 }
3881
3882 case Type::OverflowBehavior: {
3883 const auto *OB = dyn_cast<OverflowBehaviorType>(Val&: Orig);
3884 return getOverflowBehaviorType(Kind: OB->getBehaviorKind(),
3885 Wrapped: adjustType(Orig: OB->getUnderlyingType(), Adjust));
3886 }
3887
3888 case Type::Paren:
3889 return getParenType(
3890 NamedType: adjustType(Orig: cast<ParenType>(Val&: Orig)->getInnerType(), Adjust));
3891
3892 case Type::Adjusted: {
3893 const auto *AT = cast<AdjustedType>(Val&: Orig);
3894 return getAdjustedType(Orig: AT->getOriginalType(),
3895 New: adjustType(Orig: AT->getAdjustedType(), Adjust));
3896 }
3897
3898 case Type::MacroQualified: {
3899 const auto *MQT = cast<MacroQualifiedType>(Val&: Orig);
3900 return getMacroQualifiedType(UnderlyingTy: adjustType(Orig: MQT->getUnderlyingType(), Adjust),
3901 MacroII: MQT->getMacroIdentifier());
3902 }
3903
3904 default:
3905 return Adjust(Orig);
3906 }
3907}
3908
3909const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
3910 FunctionType::ExtInfo Info) {
3911 if (T->getExtInfo() == Info)
3912 return T;
3913
3914 QualType Result;
3915 if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(Val: T)) {
3916 Result = getFunctionNoProtoType(ResultTy: FNPT->getReturnType(), Info);
3917 } else {
3918 const auto *FPT = cast<FunctionProtoType>(Val: T);
3919 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
3920 EPI.ExtInfo = Info;
3921 Result = getFunctionType(ResultTy: FPT->getReturnType(), Args: FPT->getParamTypes(), EPI);
3922 }
3923
3924 return cast<FunctionType>(Val: Result.getTypePtr());
3925}
3926
3927QualType ASTContext::adjustFunctionResultType(QualType FunctionType,
3928 QualType ResultType) {
3929 return adjustType(Orig: FunctionType, Adjust: [&](QualType Orig) {
3930 if (const auto *FNPT = Orig->getAs<FunctionNoProtoType>())
3931 return getFunctionNoProtoType(ResultTy: ResultType, Info: FNPT->getExtInfo());
3932
3933 const auto *FPT = Orig->castAs<FunctionProtoType>();
3934 return getFunctionType(ResultTy: ResultType, Args: FPT->getParamTypes(),
3935 EPI: FPT->getExtProtoInfo());
3936 });
3937}
3938
3939void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
3940 QualType ResultType) {
3941 FD = FD->getMostRecentDecl();
3942 while (true) {
3943 FD->setType(adjustFunctionResultType(FunctionType: FD->getType(), ResultType));
3944 if (FunctionDecl *Next = FD->getPreviousDecl())
3945 FD = Next;
3946 else
3947 break;
3948 }
3949 if (ASTMutationListener *L = getASTMutationListener())
3950 L->DeducedReturnType(FD, ReturnType: ResultType);
3951}
3952
3953/// Get a function type and produce the equivalent function type with the
3954/// specified exception specification. Type sugar that can be present on a
3955/// declaration of a function with an exception specification is permitted
3956/// and preserved. Other type sugar (for instance, typedefs) is not.
3957QualType ASTContext::getFunctionTypeWithExceptionSpec(
3958 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) const {
3959 return adjustType(Orig, Adjust: [&](QualType Ty) {
3960 const auto *Proto = Ty->castAs<FunctionProtoType>();
3961 return getFunctionType(ResultTy: Proto->getReturnType(), Args: Proto->getParamTypes(),
3962 EPI: Proto->getExtProtoInfo().withExceptionSpec(ESI));
3963 });
3964}
3965
3966bool ASTContext::hasSameFunctionTypeIgnoringExceptionSpec(QualType T,
3967 QualType U) const {
3968 return hasSameType(T1: T, T2: U) ||
3969 (getLangOpts().CPlusPlus17 &&
3970 hasSameType(T1: getFunctionTypeWithExceptionSpec(Orig: T, ESI: EST_None),
3971 T2: getFunctionTypeWithExceptionSpec(Orig: U, ESI: EST_None)));
3972}
3973
3974QualType ASTContext::getFunctionTypeWithoutPtrSizes(QualType T) {
3975 if (const auto *Proto = T->getAs<FunctionProtoType>()) {
3976 QualType RetTy = removePtrSizeAddrSpace(T: Proto->getReturnType());
3977 SmallVector<QualType, 16> Args(Proto->param_types().size());
3978 for (unsigned i = 0, n = Args.size(); i != n; ++i)
3979 Args[i] = removePtrSizeAddrSpace(T: Proto->param_types()[i]);
3980 return getFunctionType(ResultTy: RetTy, Args, EPI: Proto->getExtProtoInfo());
3981 }
3982
3983 if (const FunctionNoProtoType *Proto = T->getAs<FunctionNoProtoType>()) {
3984 QualType RetTy = removePtrSizeAddrSpace(T: Proto->getReturnType());
3985 return getFunctionNoProtoType(ResultTy: RetTy, Info: Proto->getExtInfo());
3986 }
3987
3988 return T;
3989}
3990
3991bool ASTContext::hasSameFunctionTypeIgnoringPtrSizes(QualType T, QualType U) {
3992 return hasSameType(T1: T, T2: U) ||
3993 hasSameType(T1: getFunctionTypeWithoutPtrSizes(T),
3994 T2: getFunctionTypeWithoutPtrSizes(T: U));
3995}
3996
3997QualType ASTContext::getFunctionTypeWithoutParamABIs(QualType T) const {
3998 if (const auto *Proto = T->getAs<FunctionProtoType>()) {
3999 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
4000 EPI.ExtParameterInfos = nullptr;
4001 return getFunctionType(ResultTy: Proto->getReturnType(), Args: Proto->param_types(), EPI);
4002 }
4003 return T;
4004}
4005
4006bool ASTContext::hasSameFunctionTypeIgnoringParamABI(QualType T,
4007 QualType U) const {
4008 return hasSameType(T1: T, T2: U) || hasSameType(T1: getFunctionTypeWithoutParamABIs(T),
4009 T2: getFunctionTypeWithoutParamABIs(T: U));
4010}
4011
4012void ASTContext::adjustExceptionSpec(
4013 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
4014 bool AsWritten) {
4015 // Update the type.
4016 QualType Updated =
4017 getFunctionTypeWithExceptionSpec(Orig: FD->getType(), ESI);
4018 FD->setType(Updated);
4019
4020 if (!AsWritten)
4021 return;
4022
4023 // Update the type in the type source information too.
4024 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
4025 // If the type and the type-as-written differ, we may need to update
4026 // the type-as-written too.
4027 if (TSInfo->getType() != FD->getType())
4028 Updated = getFunctionTypeWithExceptionSpec(Orig: TSInfo->getType(), ESI);
4029
4030 // FIXME: When we get proper type location information for exceptions,
4031 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
4032 // up the TypeSourceInfo;
4033 assert(TypeLoc::getFullDataSizeForType(Updated) ==
4034 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
4035 "TypeLoc size mismatch from updating exception specification");
4036 TSInfo->overrideType(T: Updated);
4037 }
4038}
4039
4040/// getComplexType - Return the uniqued reference to the type for a complex
4041/// number with the specified element type.
4042QualType ASTContext::getComplexType(QualType T) const {
4043 // Unique pointers, to guarantee there is only one pointer of a particular
4044 // structure.
4045 llvm::FoldingSetInsertToken Token;
4046 if (ComplexType *CT = ComplexTypes.lookup(Key: T, Token))
4047 return QualType(CT, 0);
4048
4049 // If the pointee type isn't canonical, this won't be a canonical type either,
4050 // so fill in the canonical type field.
4051 QualType Canonical;
4052 if (!T.isCanonical()) {
4053 Canonical = getComplexType(T: getCanonicalType(T));
4054
4055 assert(!ComplexTypes.lookup(T, Token) && "Shouldn't be in the map!");
4056 }
4057 auto *New = new (*this, alignof(ComplexType)) ComplexType(T, Canonical);
4058 Types.push_back(Elt: New);
4059 ComplexTypes.insert(N: New, Token);
4060 return QualType(New, 0);
4061}
4062
4063/// getPointerType - Return the uniqued reference to the type for a pointer to
4064/// the specified type.
4065QualType ASTContext::getPointerType(QualType T) const {
4066 // Unique pointers, to guarantee there is only one pointer of a particular
4067 // structure.
4068 llvm::FoldingSetInsertToken Token;
4069 if (PointerType *PT = PointerTypes.lookup(Key: T, Token))
4070 return QualType(PT, 0);
4071
4072 // If the pointee type isn't canonical, this won't be a canonical type either,
4073 // so fill in the canonical type field.
4074 QualType Canonical;
4075 if (!T.isCanonical()) {
4076 Canonical = getPointerType(T: getCanonicalType(T));
4077
4078 assert(!PointerTypes.lookup(T, Token) && "Shouldn't be in the map!");
4079 }
4080 auto *New = new (*this, alignof(PointerType)) PointerType(T, Canonical);
4081 Types.push_back(Elt: New);
4082 PointerTypes.insert(N: New, Token);
4083 return QualType(New, 0);
4084}
4085
4086QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
4087 llvm::FoldingSetInsertToken Token;
4088 AdjustedType *AT = AdjustedTypes.lookup(Key: {Orig, New}, Token);
4089 if (AT)
4090 return QualType(AT, 0);
4091
4092 QualType Canonical = getCanonicalType(T: New);
4093
4094 AT = new (*this, alignof(AdjustedType))
4095 AdjustedType(Type::Adjusted, Orig, New, Canonical);
4096 Types.push_back(Elt: AT);
4097 AdjustedTypes.insert(N: AT, Token);
4098 return QualType(AT, 0);
4099}
4100
4101QualType ASTContext::getDecayedType(QualType Orig, QualType Decayed) const {
4102 llvm::FoldingSetInsertToken Token;
4103 AdjustedType *AT = AdjustedTypes.lookup(Key: {Orig, Decayed}, Token);
4104 if (AT)
4105 return QualType(AT, 0);
4106
4107 QualType Canonical = getCanonicalType(T: Decayed);
4108
4109 AT = new (*this, alignof(DecayedType)) DecayedType(Orig, Decayed, Canonical);
4110 Types.push_back(Elt: AT);
4111 AdjustedTypes.insert(N: AT, Token);
4112 return QualType(AT, 0);
4113}
4114
4115QualType ASTContext::getDecayedType(QualType T) const {
4116 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
4117
4118 QualType Decayed;
4119
4120 // C99 6.7.5.3p7:
4121 // A declaration of a parameter as "array of type" shall be
4122 // adjusted to "qualified pointer to type", where the type
4123 // qualifiers (if any) are those specified within the [ and ] of
4124 // the array type derivation.
4125 if (T->isArrayType())
4126 Decayed = getArrayDecayedType(T);
4127
4128 // C99 6.7.5.3p8:
4129 // A declaration of a parameter as "function returning type"
4130 // shall be adjusted to "pointer to function returning type", as
4131 // in 6.3.2.1.
4132 if (T->isFunctionType())
4133 Decayed = getPointerType(T);
4134
4135 return getDecayedType(Orig: T, Decayed);
4136}
4137
4138QualType ASTContext::getArrayParameterType(QualType Ty) const {
4139 if (Ty->isArrayParameterType())
4140 return Ty;
4141 assert(Ty->isConstantArrayType() && "Ty must be an array type.");
4142 QualType DTy = Ty.getDesugaredType(Context: *this);
4143 const auto *ATy = cast<ConstantArrayType>(Val&: DTy);
4144 llvm::FoldingSetNodeID ID;
4145 ATy->Profile(ID, Ctx: *this, ET: ATy->getElementType(), ArraySize: ATy->getZExtSize(),
4146 SizeExpr: ATy->getSizeExpr(), SizeMod: ATy->getSizeModifier(),
4147 TypeQuals: ATy->getIndexTypeQualifiers().getAsOpaqueValue());
4148 llvm::FoldingSetInsertToken Token;
4149 ArrayParameterType *AT = ArrayParameterTypes.lookup(ID, Token);
4150 if (AT)
4151 return QualType(AT, 0);
4152
4153 QualType Canonical;
4154 if (!DTy.isCanonical()) {
4155 Canonical = getArrayParameterType(Ty: getCanonicalType(T: Ty));
4156
4157 // Get the new insert position for the node we care about.
4158 AT = ArrayParameterTypes.lookup(ID, Token);
4159 assert(!AT && "Shouldn't be in the map!");
4160 }
4161
4162 AT = new (*this, alignof(ArrayParameterType))
4163 ArrayParameterType(ATy, Canonical);
4164 Types.push_back(Elt: AT);
4165 ArrayParameterTypes.insert(N: AT, Token);
4166 return QualType(AT, 0);
4167}
4168
4169/// getBlockPointerType - Return the uniqued reference to the type for
4170/// a pointer to the specified block.
4171QualType ASTContext::getBlockPointerType(QualType T) const {
4172 assert(T->isFunctionType() && "block of function types only");
4173 // Unique pointers, to guarantee there is only one block of a particular
4174 // structure.
4175 llvm::FoldingSetInsertToken Token;
4176 if (BlockPointerType *PT = BlockPointerTypes.lookup(Key: T, Token))
4177 return QualType(PT, 0);
4178
4179 // If the block pointee type isn't canonical, this won't be a canonical
4180 // type either so fill in the canonical type field.
4181 QualType Canonical;
4182 if (!T.isCanonical()) {
4183 Canonical = getBlockPointerType(T: getCanonicalType(T));
4184
4185 assert(!BlockPointerTypes.lookup(T, Token) && "Shouldn't be in the map!");
4186 }
4187 auto *New =
4188 new (*this, alignof(BlockPointerType)) BlockPointerType(T, Canonical);
4189 Types.push_back(Elt: New);
4190 BlockPointerTypes.insert(N: New, Token);
4191 return QualType(New, 0);
4192}
4193
4194/// getLValueReferenceType - Return the uniqued reference to the type for an
4195/// lvalue reference to the specified type.
4196QualType
4197ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
4198 assert((!T->isPlaceholderType() ||
4199 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
4200 "Unresolved placeholder type");
4201
4202 // Unique pointers, to guarantee there is only one pointer of a particular
4203 // structure.
4204 llvm::FoldingSetInsertToken Token;
4205 if (LValueReferenceType *RT =
4206 LValueReferenceTypes.lookup(Key: {T, SpelledAsLValue}, Token))
4207 return QualType(RT, 0);
4208
4209 const auto *InnerRef = T->getAs<ReferenceType>();
4210
4211 // If the referencee type isn't canonical, this won't be a canonical type
4212 // either, so fill in the canonical type field.
4213 QualType Canonical;
4214 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
4215 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
4216 Canonical = getLValueReferenceType(T: getCanonicalType(T: PointeeType));
4217
4218 assert(!LValueReferenceTypes.lookup({T, SpelledAsLValue}, Token) &&
4219 "Shouldn't be in the map!");
4220 }
4221
4222 auto *New = new (*this, alignof(LValueReferenceType))
4223 LValueReferenceType(T, Canonical, SpelledAsLValue);
4224 Types.push_back(Elt: New);
4225 LValueReferenceTypes.insert(N: New, Token);
4226
4227 return QualType(New, 0);
4228}
4229
4230/// getRValueReferenceType - Return the uniqued reference to the type for an
4231/// rvalue reference to the specified type.
4232QualType ASTContext::getRValueReferenceType(QualType T) const {
4233 assert((!T->isPlaceholderType() ||
4234 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
4235 "Unresolved placeholder type");
4236
4237 // Unique pointers, to guarantee there is only one pointer of a particular
4238 // structure.
4239 llvm::FoldingSetInsertToken Token;
4240 if (RValueReferenceType *RT = RValueReferenceTypes.lookup(Key: {T, false}, Token))
4241 return QualType(RT, 0);
4242
4243 const auto *InnerRef = T->getAs<ReferenceType>();
4244
4245 // If the referencee type isn't canonical, this won't be a canonical type
4246 // either, so fill in the canonical type field.
4247 QualType Canonical;
4248 if (InnerRef || !T.isCanonical()) {
4249 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
4250 Canonical = getRValueReferenceType(T: getCanonicalType(T: PointeeType));
4251
4252 assert(!RValueReferenceTypes.lookup({T, false}, Token) &&
4253 "Shouldn't be in the map!");
4254 }
4255
4256 auto *New = new (*this, alignof(RValueReferenceType))
4257 RValueReferenceType(T, Canonical);
4258 Types.push_back(Elt: New);
4259 RValueReferenceTypes.insert(N: New, Token);
4260 return QualType(New, 0);
4261}
4262
4263QualType ASTContext::getMemberPointerType(QualType T,
4264 NestedNameSpecifier Qualifier,
4265 const CXXRecordDecl *Cls) const {
4266 if (!Qualifier) {
4267 assert(Cls && "At least one of Qualifier or Cls must be provided");
4268 Qualifier = NestedNameSpecifier(getCanonicalTagType(TD: Cls).getTypePtr());
4269 } else if (!Cls) {
4270 Cls = Qualifier.getAsRecordDecl();
4271 }
4272 // Unique pointers, to guarantee there is only one pointer of a particular
4273 // structure.
4274 llvm::FoldingSetNodeID ID;
4275 MemberPointerType::Profile(ID, Pointee: T, Qualifier, Cls);
4276
4277 llvm::FoldingSetInsertToken Token;
4278 if (MemberPointerType *PT = MemberPointerTypes.lookup(ID, Token))
4279 return QualType(PT, 0);
4280
4281 NestedNameSpecifier CanonicalQualifier = [&] {
4282 if (!Cls)
4283 return Qualifier.getCanonical();
4284 NestedNameSpecifier R(getCanonicalTagType(TD: Cls).getTypePtr());
4285 assert(R.isCanonical());
4286 return R;
4287 }();
4288 // If the pointee or class type isn't canonical, this won't be a canonical
4289 // type either, so fill in the canonical type field.
4290 QualType Canonical;
4291 if (!T.isCanonical() || Qualifier != CanonicalQualifier) {
4292 Canonical =
4293 getMemberPointerType(T: getCanonicalType(T), Qualifier: CanonicalQualifier, Cls);
4294 assert(!cast<MemberPointerType>(Canonical)->isSugared());
4295 // Get the new insert position for the node we care about.
4296 [[maybe_unused]] MemberPointerType *NewIP =
4297 MemberPointerTypes.lookup(ID, Token);
4298 assert(!NewIP && "Shouldn't be in the map!");
4299 }
4300 auto *New = new (*this, alignof(MemberPointerType))
4301 MemberPointerType(T, Qualifier, Canonical);
4302 Types.push_back(Elt: New);
4303 MemberPointerTypes.insert(N: New, Token);
4304 return QualType(New, 0);
4305}
4306
4307/// getConstantArrayType - Return the unique reference to the type for an
4308/// array of the specified element type.
4309QualType ASTContext::getConstantArrayType(QualType EltTy,
4310 const llvm::APInt &ArySizeIn,
4311 const Expr *SizeExpr,
4312 ArraySizeModifier ASM,
4313 unsigned IndexTypeQuals) const {
4314 assert((EltTy->isDependentType() ||
4315 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
4316 "Constant array of VLAs is illegal!");
4317
4318 // We only need the size as part of the type if it's instantiation-dependent.
4319 if (SizeExpr && !SizeExpr->isInstantiationDependent())
4320 SizeExpr = nullptr;
4321
4322 // Convert the array size into a canonical width matching the pointer size for
4323 // the target.
4324 llvm::APInt ArySize(ArySizeIn);
4325 ArySize = ArySize.zextOrTrunc(width: Target->getMaxPointerWidth());
4326
4327 llvm::FoldingSetNodeID ID;
4328 ConstantArrayType::Profile(ID, Ctx: *this, ET: EltTy, ArraySize: ArySize.getZExtValue(), SizeExpr,
4329 SizeMod: ASM, TypeQuals: IndexTypeQuals);
4330
4331 llvm::FoldingSetInsertToken Token;
4332 if (ConstantArrayType *ATP = ConstantArrayTypes.lookup(ID, Token))
4333 return QualType(ATP, 0);
4334
4335 // If the element type isn't canonical or has qualifiers, or the array bound
4336 // is instantiation-dependent, this won't be a canonical type either, so fill
4337 // in the canonical type field.
4338 QualType Canon;
4339 // FIXME: Check below should look for qualifiers behind sugar.
4340 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers() || SizeExpr) {
4341 SplitQualType canonSplit = getCanonicalType(T: EltTy).split();
4342 Canon = getConstantArrayType(EltTy: QualType(canonSplit.Ty, 0), ArySizeIn: ArySize, SizeExpr: nullptr,
4343 ASM, IndexTypeQuals);
4344 Canon = getQualifiedType(T: Canon, Qs: canonSplit.Quals);
4345
4346 // Get the new insert position for the node we care about.
4347 ConstantArrayType *NewIP = ConstantArrayTypes.lookup(ID, Token);
4348 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4349 }
4350
4351 auto *New = ConstantArrayType::Create(Ctx: *this, ET: EltTy, Can: Canon, Sz: ArySize, SzExpr: SizeExpr,
4352 SzMod: ASM, Qual: IndexTypeQuals);
4353 ConstantArrayTypes.insert(N: New, Token);
4354 Types.push_back(Elt: New);
4355 return QualType(New, 0);
4356}
4357
4358/// getVariableArrayDecayedType - Turns the given type, which may be
4359/// variably-modified, into the corresponding type with all the known
4360/// sizes replaced with [*].
4361QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
4362 // Vastly most common case.
4363 if (!type->isVariablyModifiedType()) return type;
4364
4365 QualType result;
4366
4367 SplitQualType split = type.getSplitDesugaredType();
4368 const Type *ty = split.Ty;
4369 switch (ty->getTypeClass()) {
4370#define TYPE(Class, Base)
4371#define ABSTRACT_TYPE(Class, Base)
4372#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4373#include "clang/AST/TypeNodes.inc"
4374 llvm_unreachable("didn't desugar past all non-canonical types?");
4375
4376 // These types should never be variably-modified.
4377 case Type::Builtin:
4378 case Type::Complex:
4379 case Type::Vector:
4380 case Type::DependentVector:
4381 case Type::ExtVector:
4382 case Type::DependentSizedExtVector:
4383 case Type::ConstantMatrix:
4384 case Type::DependentSizedMatrix:
4385 case Type::DependentAddressSpace:
4386 case Type::ObjCObject:
4387 case Type::ObjCInterface:
4388 case Type::ObjCObjectPointer:
4389 case Type::Record:
4390 case Type::Enum:
4391 case Type::UnresolvedUsing:
4392 case Type::TypeOfExpr:
4393 case Type::TypeOf:
4394 case Type::Decltype:
4395 case Type::UnaryTransform:
4396 case Type::DependentName:
4397 case Type::InjectedClassName:
4398 case Type::TemplateSpecialization:
4399 case Type::TemplateTypeParm:
4400 case Type::SubstTemplateTypeParmPack:
4401 case Type::SubstBuiltinTemplatePack:
4402 case Type::Auto:
4403 case Type::DeducedTemplateSpecialization:
4404 case Type::PackExpansion:
4405 case Type::PackIndexing:
4406 case Type::BitInt:
4407 case Type::DependentBitInt:
4408 case Type::ArrayParameter:
4409 case Type::HLSLAttributedResource:
4410 case Type::HLSLInlineSpirv:
4411 case Type::OverflowBehavior:
4412 llvm_unreachable("type should never be variably-modified");
4413
4414 // These types can be variably-modified but should never need to
4415 // further decay.
4416 case Type::FunctionNoProto:
4417 case Type::FunctionProto:
4418 case Type::BlockPointer:
4419 case Type::MemberPointer:
4420 case Type::Pipe:
4421 return type;
4422
4423 // These types can be variably-modified. All these modifications
4424 // preserve structure except as noted by comments.
4425 // TODO: if we ever care about optimizing VLAs, there are no-op
4426 // optimizations available here.
4427 case Type::Pointer:
4428 result = getPointerType(T: getVariableArrayDecayedType(
4429 type: cast<PointerType>(Val: ty)->getPointeeType()));
4430 break;
4431
4432 case Type::LValueReference: {
4433 const auto *lv = cast<LValueReferenceType>(Val: ty);
4434 result = getLValueReferenceType(
4435 T: getVariableArrayDecayedType(type: lv->getPointeeType()),
4436 SpelledAsLValue: lv->isSpelledAsLValue());
4437 break;
4438 }
4439
4440 case Type::RValueReference: {
4441 const auto *lv = cast<RValueReferenceType>(Val: ty);
4442 result = getRValueReferenceType(
4443 T: getVariableArrayDecayedType(type: lv->getPointeeType()));
4444 break;
4445 }
4446
4447 case Type::Atomic: {
4448 const auto *at = cast<AtomicType>(Val: ty);
4449 result = getAtomicType(T: getVariableArrayDecayedType(type: at->getValueType()));
4450 break;
4451 }
4452
4453 case Type::ConstantArray: {
4454 const auto *cat = cast<ConstantArrayType>(Val: ty);
4455 result = getConstantArrayType(
4456 EltTy: getVariableArrayDecayedType(type: cat->getElementType()),
4457 ArySizeIn: cat->getSize(),
4458 SizeExpr: cat->getSizeExpr(),
4459 ASM: cat->getSizeModifier(),
4460 IndexTypeQuals: cat->getIndexTypeCVRQualifiers());
4461 break;
4462 }
4463
4464 case Type::DependentSizedArray: {
4465 const auto *dat = cast<DependentSizedArrayType>(Val: ty);
4466 result = getDependentSizedArrayType(
4467 EltTy: getVariableArrayDecayedType(type: dat->getElementType()), NumElts: dat->getSizeExpr(),
4468 ASM: dat->getSizeModifier(), IndexTypeQuals: dat->getIndexTypeCVRQualifiers());
4469 break;
4470 }
4471
4472 // Turn incomplete types into [*] types.
4473 case Type::IncompleteArray: {
4474 const auto *iat = cast<IncompleteArrayType>(Val: ty);
4475 result =
4476 getVariableArrayType(EltTy: getVariableArrayDecayedType(type: iat->getElementType()),
4477 /*size*/ NumElts: nullptr, ASM: ArraySizeModifier::Normal,
4478 IndexTypeQuals: iat->getIndexTypeCVRQualifiers());
4479 break;
4480 }
4481
4482 // Turn VLA types into [*] types.
4483 case Type::VariableArray: {
4484 const auto *vat = cast<VariableArrayType>(Val: ty);
4485 result =
4486 getVariableArrayType(EltTy: getVariableArrayDecayedType(type: vat->getElementType()),
4487 /*size*/ NumElts: nullptr, ASM: ArraySizeModifier::Star,
4488 IndexTypeQuals: vat->getIndexTypeCVRQualifiers());
4489 break;
4490 }
4491 }
4492
4493 // Apply the top-level qualifiers from the original.
4494 return getQualifiedType(T: result, Qs: split.Quals);
4495}
4496
4497/// getVariableArrayType - Returns a non-unique reference to the type for a
4498/// variable array of the specified element type.
4499QualType ASTContext::getVariableArrayType(QualType EltTy, Expr *NumElts,
4500 ArraySizeModifier ASM,
4501 unsigned IndexTypeQuals) const {
4502 // Since we don't unique expressions, it isn't possible to unique VLA's
4503 // that have an expression provided for their size.
4504 QualType Canon;
4505
4506 // Be sure to pull qualifiers off the element type.
4507 // FIXME: Check below should look for qualifiers behind sugar.
4508 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
4509 SplitQualType canonSplit = getCanonicalType(T: EltTy).split();
4510 Canon = getVariableArrayType(EltTy: QualType(canonSplit.Ty, 0), NumElts, ASM,
4511 IndexTypeQuals);
4512 Canon = getQualifiedType(T: Canon, Qs: canonSplit.Quals);
4513 }
4514
4515 auto *New = new (*this, alignof(VariableArrayType))
4516 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals);
4517
4518 VariableArrayTypes.push_back(x: New);
4519 Types.push_back(Elt: New);
4520 return QualType(New, 0);
4521}
4522
4523/// getDependentSizedArrayType - Returns a non-unique reference to
4524/// the type for a dependently-sized array of the specified element
4525/// type.
4526QualType
4527ASTContext::getDependentSizedArrayType(QualType elementType, Expr *numElements,
4528 ArraySizeModifier ASM,
4529 unsigned elementTypeQuals) const {
4530 assert((!numElements || numElements->isTypeDependent() ||
4531 numElements->isValueDependent()) &&
4532 "Size must be type- or value-dependent!");
4533
4534 SplitQualType canonElementType = getCanonicalType(T: elementType).split();
4535
4536 llvm::FoldingSetInsertToken Token;
4537 llvm::FoldingSetNodeID ID;
4538 DependentSizedArrayType::Profile(
4539 ID, Context: *this, ET: numElements ? QualType(canonElementType.Ty, 0) : elementType,
4540 SizeMod: ASM, TypeQuals: elementTypeQuals, E: numElements);
4541
4542 // Look for an existing type with these properties.
4543 DependentSizedArrayType *canonTy = DependentSizedArrayTypes.lookup(ID, Token);
4544
4545 // Dependently-sized array types that do not have a specified number
4546 // of elements will have their sizes deduced from a dependent
4547 // initializer.
4548 if (!numElements) {
4549 if (canonTy)
4550 return QualType(canonTy, 0);
4551
4552 auto *newType = new (*this, alignof(DependentSizedArrayType))
4553 DependentSizedArrayType(elementType, QualType(), numElements, ASM,
4554 elementTypeQuals);
4555 DependentSizedArrayTypes.insert(N: newType, Token);
4556 Types.push_back(Elt: newType);
4557 return QualType(newType, 0);
4558 }
4559
4560 // If we don't have one, build one.
4561 if (!canonTy) {
4562 canonTy = new (*this, alignof(DependentSizedArrayType))
4563 DependentSizedArrayType(QualType(canonElementType.Ty, 0), QualType(),
4564 numElements, ASM, elementTypeQuals);
4565 DependentSizedArrayTypes.insert(N: canonTy, Token);
4566 Types.push_back(Elt: canonTy);
4567 }
4568
4569 // Apply qualifiers from the element type to the array.
4570 QualType canon = getQualifiedType(T: QualType(canonTy,0),
4571 Qs: canonElementType.Quals);
4572
4573 // If we didn't need extra canonicalization for the element type or the size
4574 // expression, then just use that as our result.
4575 if (QualType(canonElementType.Ty, 0) == elementType &&
4576 canonTy->getSizeExpr() == numElements)
4577 return canon;
4578
4579 // Otherwise, we need to build a type which follows the spelling
4580 // of the element type.
4581 auto *sugaredType = new (*this, alignof(DependentSizedArrayType))
4582 DependentSizedArrayType(elementType, canon, numElements, ASM,
4583 elementTypeQuals);
4584 Types.push_back(Elt: sugaredType);
4585 return QualType(sugaredType, 0);
4586}
4587
4588QualType ASTContext::getIncompleteArrayType(QualType elementType,
4589 ArraySizeModifier ASM,
4590 unsigned elementTypeQuals) const {
4591 llvm::FoldingSetNodeID ID;
4592 IncompleteArrayType::Profile(ID, ET: elementType, SizeMod: ASM, TypeQuals: elementTypeQuals);
4593
4594 llvm::FoldingSetInsertToken Token;
4595 if (IncompleteArrayType *iat = IncompleteArrayTypes.lookup(ID, Token))
4596 return QualType(iat, 0);
4597
4598 // If the element type isn't canonical, this won't be a canonical type
4599 // either, so fill in the canonical type field. We also have to pull
4600 // qualifiers off the element type.
4601 QualType canon;
4602
4603 // FIXME: Check below should look for qualifiers behind sugar.
4604 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
4605 SplitQualType canonSplit = getCanonicalType(T: elementType).split();
4606 canon = getIncompleteArrayType(elementType: QualType(canonSplit.Ty, 0),
4607 ASM, elementTypeQuals);
4608 canon = getQualifiedType(T: canon, Qs: canonSplit.Quals);
4609
4610 // Get the new insert position for the node we care about.
4611 IncompleteArrayType *existing = IncompleteArrayTypes.lookup(ID, Token);
4612 assert(!existing && "Shouldn't be in the map!"); (void) existing;
4613 }
4614
4615 auto *newType = new (*this, alignof(IncompleteArrayType))
4616 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
4617
4618 IncompleteArrayTypes.insert(N: newType, Token);
4619 Types.push_back(Elt: newType);
4620 return QualType(newType, 0);
4621}
4622
4623ASTContext::BuiltinVectorTypeInfo
4624ASTContext::getBuiltinVectorTypeInfo(const BuiltinType *Ty) const {
4625#define SVE_INT_ELTTY(BITS, ELTS, SIGNED, NUMVECTORS) \
4626 {getIntTypeForBitwidth(BITS, SIGNED), llvm::ElementCount::getScalable(ELTS), \
4627 NUMVECTORS};
4628
4629#define SVE_ELTTY(ELTTY, ELTS, NUMVECTORS) \
4630 {ELTTY, llvm::ElementCount::getScalable(ELTS), NUMVECTORS};
4631
4632 switch (Ty->getKind()) {
4633 default:
4634 llvm_unreachable("Unsupported builtin vector type");
4635
4636#define SVE_VECTOR_TYPE_INT(Name, MangledName, Id, SingletonId, NumEls, \
4637 ElBits, NF, IsSigned) \
4638 case BuiltinType::Id: \
4639 return {getIntTypeForBitwidth(ElBits, IsSigned), \
4640 llvm::ElementCount::getScalable(NumEls), NF};
4641#define SVE_VECTOR_TYPE_FLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4642 ElBits, NF) \
4643 case BuiltinType::Id: \
4644 return {ElBits == 16 ? HalfTy : (ElBits == 32 ? FloatTy : DoubleTy), \
4645 llvm::ElementCount::getScalable(NumEls), NF};
4646#define SVE_VECTOR_TYPE_BFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4647 ElBits, NF) \
4648 case BuiltinType::Id: \
4649 return {BFloat16Ty, llvm::ElementCount::getScalable(NumEls), NF};
4650#define SVE_VECTOR_TYPE_MFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4651 ElBits, NF) \
4652 case BuiltinType::Id: \
4653 return {MFloat8Ty, llvm::ElementCount::getScalable(NumEls), NF};
4654#define SVE_PREDICATE_TYPE_ALL(Name, MangledName, Id, SingletonId, NumEls, NF) \
4655 case BuiltinType::Id: \
4656 return {BoolTy, llvm::ElementCount::getScalable(NumEls), NF};
4657#include "clang/Basic/AArch64ACLETypes.def"
4658
4659#define RVV_VECTOR_TYPE_INT(Name, Id, SingletonId, NumEls, ElBits, NF, \
4660 IsSigned) \
4661 case BuiltinType::Id: \
4662 return {getIntTypeForBitwidth(ElBits, IsSigned), \
4663 llvm::ElementCount::getScalable(NumEls), NF};
4664#define RVV_VECTOR_TYPE_FLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \
4665 case BuiltinType::Id: \
4666 return {ElBits == 16 ? Float16Ty : (ElBits == 32 ? FloatTy : DoubleTy), \
4667 llvm::ElementCount::getScalable(NumEls), NF};
4668#define RVV_VECTOR_TYPE_BFLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \
4669 case BuiltinType::Id: \
4670 return {BFloat16Ty, llvm::ElementCount::getScalable(NumEls), NF};
4671#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
4672 case BuiltinType::Id: \
4673 return {BoolTy, llvm::ElementCount::getScalable(NumEls), 1};
4674#include "clang/Basic/RISCVVTypes.def"
4675 }
4676}
4677
4678/// getExternrefType - Return a WebAssembly externref type, which represents an
4679/// opaque reference to a host value.
4680QualType ASTContext::getWebAssemblyExternrefType() const {
4681 if (Target->getTriple().isWasm() && Target->hasFeature(Feature: "reference-types")) {
4682#define WASM_REF_TYPE(Name, MangledName, Id, SingletonId, AS) \
4683 if (BuiltinType::Id == BuiltinType::WasmExternRef) \
4684 return SingletonId;
4685#include "clang/Basic/WebAssemblyReferenceTypes.def"
4686 }
4687 llvm_unreachable(
4688 "shouldn't try to generate type externref outside WebAssembly target");
4689}
4690
4691/// getScalableVectorType - Return the unique reference to a scalable vector
4692/// type of the specified element type and size. VectorType must be a built-in
4693/// type.
4694QualType ASTContext::getScalableVectorType(QualType EltTy, unsigned NumElts,
4695 unsigned NumFields) const {
4696 auto K = llvm::ScalableVecTyKey{.EltTy: EltTy, .NumElts: NumElts, .NumFields: NumFields};
4697 if (auto It = ScalableVecTyMap.find(Val: K); It != ScalableVecTyMap.end())
4698 return It->second;
4699
4700 if (Target->hasAArch64ACLETypes()) {
4701 uint64_t EltTySize = getTypeSize(T: EltTy);
4702
4703#define SVE_VECTOR_TYPE_INT(Name, MangledName, Id, SingletonId, NumEls, \
4704 ElBits, NF, IsSigned) \
4705 if (EltTy->hasIntegerRepresentation() && !EltTy->isBooleanType() && \
4706 EltTy->hasSignedIntegerRepresentation() == IsSigned && \
4707 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4708 return ScalableVecTyMap[K] = SingletonId; \
4709 }
4710#define SVE_VECTOR_TYPE_FLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4711 ElBits, NF) \
4712 if (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \
4713 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4714 return ScalableVecTyMap[K] = SingletonId; \
4715 }
4716#define SVE_VECTOR_TYPE_BFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4717 ElBits, NF) \
4718 if (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \
4719 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4720 return ScalableVecTyMap[K] = SingletonId; \
4721 }
4722#define SVE_VECTOR_TYPE_MFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4723 ElBits, NF) \
4724 if (EltTy->isMFloat8Type() && EltTySize == ElBits && \
4725 NumElts == (NumEls * NF) && NumFields == 1) { \
4726 return ScalableVecTyMap[K] = SingletonId; \
4727 }
4728#define SVE_PREDICATE_TYPE_ALL(Name, MangledName, Id, SingletonId, NumEls, NF) \
4729 if (EltTy->isBooleanType() && NumElts == (NumEls * NF) && NumFields == 1) \
4730 return ScalableVecTyMap[K] = SingletonId;
4731#include "clang/Basic/AArch64ACLETypes.def"
4732 } else if (Target->hasRISCVVTypes()) {
4733 uint64_t EltTySize = getTypeSize(T: EltTy);
4734#define RVV_VECTOR_TYPE(Name, Id, SingletonId, NumEls, ElBits, NF, IsSigned, \
4735 IsFP, IsBF) \
4736 if (!EltTy->isBooleanType() && \
4737 ((EltTy->hasIntegerRepresentation() && \
4738 EltTy->hasSignedIntegerRepresentation() == IsSigned) || \
4739 (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \
4740 IsFP && !IsBF) || \
4741 (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \
4742 IsBF && !IsFP)) && \
4743 EltTySize == ElBits && NumElts == NumEls && NumFields == NF) \
4744 return ScalableVecTyMap[K] = SingletonId;
4745#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
4746 if (EltTy->isBooleanType() && NumElts == NumEls) \
4747 return ScalableVecTyMap[K] = SingletonId;
4748#include "clang/Basic/RISCVVTypes.def"
4749 }
4750 return QualType();
4751}
4752
4753/// getVectorType - Return the unique reference to a vector type of
4754/// the specified element type and size. VectorType must be a built-in type.
4755QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
4756 VectorKind VecKind) const {
4757 assert(vecType->isBuiltinType() ||
4758 (vecType->isBitIntType() &&
4759 // Only support _BitInt elements with byte-sized power of 2 NumBits.
4760 llvm::isPowerOf2_32(vecType->castAs<BitIntType>()->getNumBits())));
4761
4762 // Check if we've already instantiated a vector of this type.
4763 llvm::FoldingSetNodeID ID;
4764 VectorType::Profile(ID, ElementType: vecType, NumElements: NumElts, TypeClass: Type::Vector, VecKind);
4765
4766 llvm::FoldingSetInsertToken Token;
4767 if (VectorType *VTP = VectorTypes.lookup(ID, Token))
4768 return QualType(VTP, 0);
4769
4770 // If the element type isn't canonical, this won't be a canonical type either,
4771 // so fill in the canonical type field.
4772 QualType Canonical;
4773 if (!vecType.isCanonical()) {
4774 Canonical = getVectorType(vecType: getCanonicalType(T: vecType), NumElts, VecKind);
4775
4776 // Get the new insert position for the node we care about.
4777 VectorType *NewIP = VectorTypes.lookup(ID, Token);
4778 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4779 }
4780 auto *New = new (*this, alignof(VectorType))
4781 VectorType(vecType, NumElts, Canonical, VecKind);
4782 VectorTypes.insert(N: New, Token);
4783 Types.push_back(Elt: New);
4784 return QualType(New, 0);
4785}
4786
4787QualType ASTContext::getDependentVectorType(QualType VecType, Expr *SizeExpr,
4788 SourceLocation AttrLoc,
4789 VectorKind VecKind) const {
4790 llvm::FoldingSetNodeID ID;
4791 DependentVectorType::Profile(ID, Context: *this, ElementType: getCanonicalType(T: VecType), SizeExpr,
4792 VecKind);
4793 llvm::FoldingSetInsertToken Token;
4794 DependentVectorType *Canon = DependentVectorTypes.lookup(ID, Token);
4795 DependentVectorType *New;
4796
4797 if (Canon) {
4798 New = new (*this, alignof(DependentVectorType)) DependentVectorType(
4799 VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind);
4800 } else {
4801 QualType CanonVecTy = getCanonicalType(T: VecType);
4802 if (CanonVecTy == VecType) {
4803 New = new (*this, alignof(DependentVectorType))
4804 DependentVectorType(VecType, QualType(), SizeExpr, AttrLoc, VecKind);
4805
4806 DependentVectorType *CanonCheck = DependentVectorTypes.lookup(ID, Token);
4807 assert(!CanonCheck &&
4808 "Dependent-sized vector_size canonical type broken");
4809 (void)CanonCheck;
4810 DependentVectorTypes.insert(N: New, Token);
4811 } else {
4812 QualType CanonTy = getDependentVectorType(VecType: CanonVecTy, SizeExpr,
4813 AttrLoc: SourceLocation(), VecKind);
4814 New = new (*this, alignof(DependentVectorType))
4815 DependentVectorType(VecType, CanonTy, SizeExpr, AttrLoc, VecKind);
4816 }
4817 }
4818
4819 Types.push_back(Elt: New);
4820 return QualType(New, 0);
4821}
4822
4823/// getExtVectorType - Return the unique reference to an extended vector type of
4824/// the specified element type and size. VectorType must be a built-in type.
4825QualType ASTContext::getExtVectorType(QualType vecType,
4826 unsigned NumElts) const {
4827 assert(vecType->isBuiltinType() || vecType->isDependentType() ||
4828 (vecType->isBitIntType() &&
4829 // Only support _BitInt elements with byte-sized power of 2 NumBits.
4830 llvm::isPowerOf2_32(vecType->castAs<BitIntType>()->getNumBits())));
4831
4832 // Check if we've already instantiated a vector of this type.
4833 llvm::FoldingSetNodeID ID;
4834 VectorType::Profile(ID, ElementType: vecType, NumElements: NumElts, TypeClass: Type::ExtVector,
4835 VecKind: VectorKind::Generic);
4836 llvm::FoldingSetInsertToken Token;
4837 if (VectorType *VTP = VectorTypes.lookup(ID, Token))
4838 return QualType(VTP, 0);
4839
4840 // If the element type isn't canonical, this won't be a canonical type either,
4841 // so fill in the canonical type field.
4842 QualType Canonical;
4843 if (!vecType.isCanonical()) {
4844 Canonical = getExtVectorType(vecType: getCanonicalType(T: vecType), NumElts);
4845
4846 // Get the new insert position for the node we care about.
4847 VectorType *NewIP = VectorTypes.lookup(ID, Token);
4848 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4849 }
4850 auto *New = new (*this, alignof(ExtVectorType))
4851 ExtVectorType(vecType, NumElts, Canonical);
4852 VectorTypes.insert(N: New, Token);
4853 Types.push_back(Elt: New);
4854 return QualType(New, 0);
4855}
4856
4857QualType
4858ASTContext::getDependentSizedExtVectorType(QualType vecType,
4859 Expr *SizeExpr,
4860 SourceLocation AttrLoc) const {
4861 llvm::FoldingSetNodeID ID;
4862 DependentSizedExtVectorType::Profile(ID, Context: *this, ElementType: getCanonicalType(T: vecType),
4863 SizeExpr);
4864
4865 llvm::FoldingSetInsertToken Token;
4866 DependentSizedExtVectorType *Canon =
4867 DependentSizedExtVectorTypes.lookup(ID, Token);
4868 DependentSizedExtVectorType *New;
4869 if (Canon) {
4870 // We already have a canonical version of this array type; use it as
4871 // the canonical type for a newly-built type.
4872 New = new (*this, alignof(DependentSizedExtVectorType))
4873 DependentSizedExtVectorType(vecType, QualType(Canon, 0), SizeExpr,
4874 AttrLoc);
4875 } else {
4876 QualType CanonVecTy = getCanonicalType(T: vecType);
4877 if (CanonVecTy == vecType) {
4878 New = new (*this, alignof(DependentSizedExtVectorType))
4879 DependentSizedExtVectorType(vecType, QualType(), SizeExpr, AttrLoc);
4880
4881 DependentSizedExtVectorType *CanonCheck =
4882 DependentSizedExtVectorTypes.lookup(ID, Token);
4883 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
4884 (void)CanonCheck;
4885 DependentSizedExtVectorTypes.insert(N: New, Token);
4886 } else {
4887 QualType CanonExtTy = getDependentSizedExtVectorType(vecType: CanonVecTy, SizeExpr,
4888 AttrLoc: SourceLocation());
4889 New = new (*this, alignof(DependentSizedExtVectorType))
4890 DependentSizedExtVectorType(vecType, CanonExtTy, SizeExpr, AttrLoc);
4891 }
4892 }
4893
4894 Types.push_back(Elt: New);
4895 return QualType(New, 0);
4896}
4897
4898QualType ASTContext::getConstantMatrixType(
4899 QualType ElementTy, unsigned NumRows, unsigned NumColumns,
4900 std::optional<MatrixType::LayoutKind> Layout) const {
4901 llvm::FoldingSetNodeID ID;
4902 ConstantMatrixType::Profile(ID, ElementType: ElementTy, NumRows, NumColumns, Layout,
4903 TypeClass: Type::ConstantMatrix);
4904
4905 assert(MatrixType::isValidElementType(ElementTy, getLangOpts()) &&
4906 "need a valid element type");
4907 assert(NumRows > 0 && NumRows <= LangOpts.MaxMatrixDimension &&
4908 NumColumns > 0 && NumColumns <= LangOpts.MaxMatrixDimension &&
4909 "need valid matrix dimensions");
4910 llvm::FoldingSetInsertToken Token;
4911 if (ConstantMatrixType *MTP = MatrixTypes.lookup(ID, Token))
4912 return QualType(MTP, 0);
4913
4914 QualType Canonical;
4915 if (Layout || !ElementTy.isCanonical()) {
4916 Canonical = getConstantMatrixType(ElementTy: getCanonicalType(T: ElementTy), NumRows,
4917 NumColumns, Layout: std::nullopt);
4918
4919 ConstantMatrixType *NewIP = MatrixTypes.lookup(ID, Token);
4920 assert(!NewIP && "Matrix type shouldn't already exist in the map");
4921 (void)NewIP;
4922 }
4923
4924 auto *New = new (*this, alignof(ConstantMatrixType))
4925 ConstantMatrixType(ElementTy, NumRows, NumColumns, Canonical, Layout);
4926 MatrixTypes.insert(N: New, Token);
4927 Types.push_back(Elt: New);
4928 return QualType(New, 0);
4929}
4930
4931QualType ASTContext::getDependentSizedMatrixType(QualType ElementTy,
4932 Expr *RowExpr,
4933 Expr *ColumnExpr,
4934 SourceLocation AttrLoc) const {
4935 QualType CanonElementTy = getCanonicalType(T: ElementTy);
4936 llvm::FoldingSetNodeID ID;
4937 DependentSizedMatrixType::Profile(ID, Context: *this, ElementType: CanonElementTy, RowExpr,
4938 ColumnExpr);
4939
4940 llvm::FoldingSetInsertToken Token;
4941 DependentSizedMatrixType *Canon = DependentSizedMatrixTypes.lookup(ID, Token);
4942
4943 if (!Canon) {
4944 Canon = new (*this, alignof(DependentSizedMatrixType))
4945 DependentSizedMatrixType(CanonElementTy, QualType(), RowExpr,
4946 ColumnExpr, AttrLoc);
4947#ifndef NDEBUG
4948 DependentSizedMatrixType *CanonCheck =
4949 DependentSizedMatrixTypes.lookup(ID, Token);
4950 assert(!CanonCheck && "Dependent-sized matrix canonical type broken");
4951#endif
4952 DependentSizedMatrixTypes.insert(N: Canon, Token);
4953 Types.push_back(Elt: Canon);
4954 }
4955
4956 // Already have a canonical version of the matrix type
4957 //
4958 // If it exactly matches the requested type, use it directly.
4959 if (Canon->getElementType() == ElementTy && Canon->getRowExpr() == RowExpr &&
4960 Canon->getRowExpr() == ColumnExpr)
4961 return QualType(Canon, 0);
4962
4963 // Use Canon as the canonical type for newly-built type.
4964 DependentSizedMatrixType *New = new (*this, alignof(DependentSizedMatrixType))
4965 DependentSizedMatrixType(ElementTy, QualType(Canon, 0), RowExpr,
4966 ColumnExpr, AttrLoc);
4967 Types.push_back(Elt: New);
4968 return QualType(New, 0);
4969}
4970
4971QualType
4972ASTContext::getMatrixTypeWithLayout(QualType T,
4973 MatrixType::LayoutKind Layout) const {
4974 Qualifiers Quals = T.getQualifiers();
4975 const Type *Ty = T->getUnqualifiedDesugaredType();
4976
4977 if (const auto *MT = dyn_cast<ConstantMatrixType>(Val: Ty))
4978 return getQualifiedType(T: getConstantMatrixType(ElementTy: MT->getElementType(),
4979 NumRows: MT->getNumRows(),
4980 NumColumns: MT->getNumColumns(), Layout),
4981 Qs: Quals);
4982
4983 const auto *CAT = dyn_cast<ConstantArrayType>(Val: Ty);
4984 if (!CAT)
4985 return T;
4986
4987 QualType Result = getConstantArrayType(
4988 EltTy: getMatrixTypeWithLayout(T: CAT->getElementType(), Layout), ArySizeIn: CAT->getSize(),
4989 SizeExpr: CAT->getSizeExpr(), ASM: CAT->getSizeModifier(),
4990 IndexTypeQuals: CAT->getIndexTypeCVRQualifiers());
4991 if (isa<ArrayParameterType>(Val: CAT))
4992 Result = getArrayParameterType(Ty: Result);
4993
4994 return getQualifiedType(T: Result, Qs: Quals);
4995}
4996
4997QualType ASTContext::getDependentAddressSpaceType(QualType PointeeType,
4998 Expr *AddrSpaceExpr,
4999 SourceLocation AttrLoc) const {
5000 assert(AddrSpaceExpr->isInstantiationDependent());
5001
5002 QualType canonPointeeType = getCanonicalType(T: PointeeType);
5003
5004 llvm::FoldingSetInsertToken Token;
5005 llvm::FoldingSetNodeID ID;
5006 DependentAddressSpaceType::Profile(ID, Context: *this, PointeeType: canonPointeeType,
5007 AddrSpaceExpr);
5008
5009 DependentAddressSpaceType *canonTy =
5010 DependentAddressSpaceTypes.lookup(ID, Token);
5011
5012 if (!canonTy) {
5013 canonTy = new (*this, alignof(DependentAddressSpaceType))
5014 DependentAddressSpaceType(canonPointeeType, QualType(), AddrSpaceExpr,
5015 AttrLoc);
5016 DependentAddressSpaceTypes.insert(N: canonTy, Token);
5017 Types.push_back(Elt: canonTy);
5018 }
5019
5020 if (canonPointeeType == PointeeType &&
5021 canonTy->getAddrSpaceExpr() == AddrSpaceExpr)
5022 return QualType(canonTy, 0);
5023
5024 auto *sugaredType = new (*this, alignof(DependentAddressSpaceType))
5025 DependentAddressSpaceType(PointeeType, QualType(canonTy, 0),
5026 AddrSpaceExpr, AttrLoc);
5027 Types.push_back(Elt: sugaredType);
5028 return QualType(sugaredType, 0);
5029}
5030
5031/// Determine whether \p T is canonical as the result type of a function.
5032static bool isCanonicalResultType(QualType T) {
5033 return T.isCanonical() &&
5034 (T.getObjCLifetime() == Qualifiers::OCL_None ||
5035 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
5036}
5037
5038/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
5039QualType
5040ASTContext::getFunctionNoProtoType(QualType ResultTy,
5041 const FunctionType::ExtInfo &Info) const {
5042 // FIXME: This assertion cannot be enabled (yet) because the ObjC rewriter
5043 // functionality creates a function without a prototype regardless of
5044 // language mode (so it makes them even in C++). Once the rewriter has been
5045 // fixed, this assertion can be enabled again.
5046 //assert(!LangOpts.requiresStrictPrototypes() &&
5047 // "strict prototypes are disabled");
5048
5049 // Unique functions, to guarantee there is only one function of a particular
5050 // structure.
5051 llvm::FoldingSetNodeID ID;
5052 FunctionNoProtoType::Profile(ID, ResultType: ResultTy, Info);
5053
5054 llvm::FoldingSetInsertToken Token;
5055 if (FunctionNoProtoType *FT = FunctionNoProtoTypes.lookup(ID, Token))
5056 return QualType(FT, 0);
5057
5058 QualType Canonical;
5059 if (!isCanonicalResultType(T: ResultTy)) {
5060 Canonical =
5061 getFunctionNoProtoType(ResultTy: getCanonicalFunctionResultType(ResultType: ResultTy), Info);
5062
5063 // Get the new insert position for the node we care about.
5064 FunctionNoProtoType *NewIP = FunctionNoProtoTypes.lookup(ID, Token);
5065 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
5066 }
5067
5068 auto *New = new (*this, alignof(FunctionNoProtoType))
5069 FunctionNoProtoType(ResultTy, Canonical, Info);
5070 Types.push_back(Elt: New);
5071 FunctionNoProtoTypes.insert(N: New, Token);
5072 return QualType(New, 0);
5073}
5074
5075CanQualType
5076ASTContext::getCanonicalFunctionResultType(QualType ResultType) const {
5077 CanQualType CanResultType = getCanonicalType(T: ResultType);
5078
5079 // Canonical result types do not have ARC lifetime qualifiers.
5080 if (CanResultType.getQualifiers().hasObjCLifetime()) {
5081 Qualifiers Qs = CanResultType.getQualifiers();
5082 Qs.removeObjCLifetime();
5083 return CanQualType::CreateUnsafe(
5084 Other: getQualifiedType(T: CanResultType.getUnqualifiedType(), Qs));
5085 }
5086
5087 return CanResultType;
5088}
5089
5090static bool isCanonicalExceptionSpecification(
5091 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
5092 if (ESI.Type == EST_None)
5093 return true;
5094 if (!NoexceptInType)
5095 return false;
5096
5097 // C++17 onwards: exception specification is part of the type, as a simple
5098 // boolean "can this function type throw".
5099 if (ESI.Type == EST_BasicNoexcept)
5100 return true;
5101
5102 // A noexcept(expr) specification is (possibly) canonical if expr is
5103 // value-dependent.
5104 if (ESI.Type == EST_DependentNoexcept)
5105 return true;
5106
5107 // A dynamic exception specification is canonical if it only contains pack
5108 // expansions (so we can't tell whether it's non-throwing) and all its
5109 // contained types are canonical.
5110 if (ESI.Type == EST_Dynamic) {
5111 bool AnyPackExpansions = false;
5112 for (QualType ET : ESI.Exceptions) {
5113 if (!ET.isCanonical())
5114 return false;
5115 if (ET->getAs<PackExpansionType>())
5116 AnyPackExpansions = true;
5117 }
5118 return AnyPackExpansions;
5119 }
5120
5121 return false;
5122}
5123
5124QualType ASTContext::getFunctionTypeInternal(
5125 QualType ResultTy, ArrayRef<QualType> ArgArray,
5126 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
5127 size_t NumArgs = ArgArray.size();
5128
5129 // Unique functions, to guarantee there is only one function of a particular
5130 // structure.
5131 llvm::FoldingSetNodeID ID;
5132 FunctionProtoType::Profile(ID, Result: ResultTy, ArgTys: ArgArray.begin(), NumArgs, EPI,
5133 Context: *this);
5134
5135 QualType Canonical;
5136 bool Unique = false;
5137
5138 llvm::FoldingSetInsertToken Token;
5139 if (FunctionProtoType *FPT = FunctionProtoTypes.lookup(ID, Token)) {
5140 QualType Existing = QualType(FPT, 0);
5141
5142 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
5143 // it so long as our exception specification doesn't contain a dependent
5144 // noexcept expression, or we're just looking for a canonical type.
5145 // Otherwise, we're going to need to create a type
5146 // sugar node to hold the concrete expression.
5147 if (OnlyWantCanonical || !isComputedNoexcept(ESpecType: EPI.ExceptionSpec.Type) ||
5148 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
5149 return Existing;
5150
5151 // We need a new type sugar node for this one, to hold the new noexcept
5152 // expression. We do no canonicalization here, but that's OK since we don't
5153 // expect to see the same noexcept expression much more than once.
5154 Canonical = getCanonicalType(T: Existing);
5155 Unique = true;
5156 }
5157
5158 bool NoexceptInType = getLangOpts().CPlusPlus17;
5159 bool IsCanonicalExceptionSpec =
5160 isCanonicalExceptionSpecification(ESI: EPI.ExceptionSpec, NoexceptInType);
5161
5162 // Determine whether the type being created is already canonical or not.
5163 bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
5164 isCanonicalResultType(T: ResultTy) && !EPI.HasTrailingReturn;
5165 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
5166 if (!ArgArray[i].isCanonicalAsParam())
5167 isCanonical = false;
5168
5169 if (OnlyWantCanonical)
5170 assert(isCanonical &&
5171 "given non-canonical parameters constructing canonical type");
5172
5173 // If this type isn't canonical, get the canonical version of it if we don't
5174 // already have it. The exception spec is only partially part of the
5175 // canonical type, and only in C++17 onwards.
5176 if (!isCanonical && Canonical.isNull()) {
5177 SmallVector<QualType, 16> CanonicalArgs;
5178 CanonicalArgs.reserve(N: NumArgs);
5179 for (unsigned i = 0; i != NumArgs; ++i)
5180 CanonicalArgs.push_back(Elt: getCanonicalParamType(T: ArgArray[i]));
5181
5182 llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
5183 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
5184 CanonicalEPI.HasTrailingReturn = false;
5185
5186 if (IsCanonicalExceptionSpec) {
5187 // Exception spec is already OK.
5188 } else if (NoexceptInType) {
5189 switch (EPI.ExceptionSpec.Type) {
5190 case EST_Unparsed: case EST_Unevaluated: case EST_Uninstantiated:
5191 // We don't know yet. It shouldn't matter what we pick here; no-one
5192 // should ever look at this.
5193 [[fallthrough]];
5194 case EST_None: case EST_MSAny: case EST_NoexceptFalse:
5195 CanonicalEPI.ExceptionSpec.Type = EST_None;
5196 break;
5197
5198 // A dynamic exception specification is almost always "not noexcept",
5199 // with the exception that a pack expansion might expand to no types.
5200 case EST_Dynamic: {
5201 bool AnyPacks = false;
5202 for (QualType ET : EPI.ExceptionSpec.Exceptions) {
5203 if (ET->getAs<PackExpansionType>())
5204 AnyPacks = true;
5205 ExceptionTypeStorage.push_back(Elt: getCanonicalType(T: ET));
5206 }
5207 if (!AnyPacks)
5208 CanonicalEPI.ExceptionSpec.Type = EST_None;
5209 else {
5210 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
5211 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
5212 }
5213 break;
5214 }
5215
5216 case EST_DynamicNone:
5217 case EST_BasicNoexcept:
5218 case EST_NoexceptTrue:
5219 case EST_NoThrow:
5220 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
5221 break;
5222
5223 case EST_DependentNoexcept:
5224 llvm_unreachable("dependent noexcept is already canonical");
5225 }
5226 } else {
5227 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
5228 }
5229
5230 // Adjust the canonical function result type.
5231 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultType: ResultTy);
5232 Canonical =
5233 getFunctionTypeInternal(ResultTy: CanResultTy, ArgArray: CanonicalArgs, EPI: CanonicalEPI, OnlyWantCanonical: true);
5234
5235 // Get the new insert position for the node we care about.
5236 FunctionProtoType *NewIP = FunctionProtoTypes.lookup(ID, Token);
5237 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
5238 }
5239
5240 // Compute the needed size to hold this FunctionProtoType and the
5241 // various trailing objects.
5242 auto ESH = FunctionProtoType::getExceptionSpecSize(
5243 EST: EPI.ExceptionSpec.Type, NumExceptions: EPI.ExceptionSpec.Exceptions.size());
5244 size_t Size = FunctionProtoType::totalSizeToAlloc<
5245 QualType, SourceLocation, FunctionType::FunctionTypeExtraBitfields,
5246 FunctionType::FunctionTypeExtraAttributeInfo,
5247 FunctionType::FunctionTypeArmAttributes, FunctionType::ExceptionType,
5248 Expr *, FunctionDecl *, FunctionProtoType::ExtParameterInfo, Qualifiers,
5249 FunctionEffect, EffectConditionExpr>(
5250 Counts: NumArgs, Counts: EPI.Variadic, Counts: EPI.requiresFunctionProtoTypeExtraBitfields(),
5251 Counts: EPI.requiresFunctionProtoTypeExtraAttributeInfo(),
5252 Counts: EPI.requiresFunctionProtoTypeArmAttributes(), Counts: ESH.NumExceptionType,
5253 Counts: ESH.NumExprPtr, Counts: ESH.NumFunctionDeclPtr,
5254 Counts: EPI.ExtParameterInfos ? NumArgs : 0,
5255 Counts: EPI.TypeQuals.hasNonFastQualifiers() ? 1 : 0, Counts: EPI.FunctionEffects.size(),
5256 Counts: EPI.FunctionEffects.conditions().size());
5257
5258 auto *FTP = (FunctionProtoType *)Allocate(Size, Align: alignof(FunctionProtoType));
5259 FunctionProtoType::ExtProtoInfo newEPI = EPI;
5260 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
5261 Types.push_back(Elt: FTP);
5262 if (!Unique)
5263 FunctionProtoTypes.insert(N: FTP, Token);
5264 if (!EPI.FunctionEffects.empty())
5265 AnyFunctionEffects = true;
5266 return QualType(FTP, 0);
5267}
5268
5269QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
5270 llvm::FoldingSetInsertToken Token;
5271 if (PipeType *PT = PipeTypes.lookup(Key: {T, ReadOnly}, Token))
5272 return QualType(PT, 0);
5273
5274 // If the pipe element type isn't canonical, this won't be a canonical type
5275 // either, so fill in the canonical type field.
5276 QualType Canonical;
5277 if (!T.isCanonical()) {
5278 Canonical = getPipeType(T: getCanonicalType(T), ReadOnly);
5279
5280 assert(!PipeTypes.lookup({T, ReadOnly}, Token) &&
5281 "Shouldn't be in the map!");
5282 }
5283 auto *New = new (*this, alignof(PipeType)) PipeType(T, Canonical, ReadOnly);
5284 Types.push_back(Elt: New);
5285 PipeTypes.insert(N: New, Token);
5286 return QualType(New, 0);
5287}
5288
5289QualType ASTContext::adjustStringLiteralBaseType(QualType Ty) const {
5290 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
5291 return LangOpts.OpenCL ? getAddrSpaceQualType(T: Ty, AddressSpace: LangAS::opencl_constant)
5292 : Ty;
5293}
5294
5295QualType ASTContext::getReadPipeType(QualType T) const {
5296 return getPipeType(T, ReadOnly: true);
5297}
5298
5299QualType ASTContext::getWritePipeType(QualType T) const {
5300 return getPipeType(T, ReadOnly: false);
5301}
5302
5303QualType ASTContext::getBitIntType(bool IsUnsigned, unsigned NumBits) const {
5304 auto Key = std::make_pair(x: unsigned(IsUnsigned), y&: NumBits);
5305
5306 llvm::FoldingSetInsertToken Token;
5307 if (BitIntType *EIT = BitIntTypes.lookup(Key, Token))
5308 return QualType(EIT, 0);
5309
5310 auto *New = new (*this, alignof(BitIntType)) BitIntType(IsUnsigned, NumBits);
5311 BitIntTypes.insert(N: New, Token);
5312 Types.push_back(Elt: New);
5313 return QualType(New, 0);
5314}
5315
5316QualType ASTContext::getDependentBitIntType(bool IsUnsigned,
5317 Expr *NumBitsExpr) const {
5318 assert(NumBitsExpr->isInstantiationDependent() && "Only good for dependent");
5319 llvm::FoldingSetNodeID ID;
5320 DependentBitIntType::Profile(ID, Context: *this, IsUnsigned, NumBitsExpr);
5321
5322 llvm::FoldingSetInsertToken Token;
5323 if (DependentBitIntType *Existing = DependentBitIntTypes.lookup(ID, Token))
5324 return QualType(Existing, 0);
5325
5326 auto *New = new (*this, alignof(DependentBitIntType))
5327 DependentBitIntType(IsUnsigned, NumBitsExpr);
5328 DependentBitIntTypes.insert(N: New, Token);
5329
5330 Types.push_back(Elt: New);
5331 return QualType(New, 0);
5332}
5333
5334QualType
5335ASTContext::getPredefinedSugarType(PredefinedSugarType::Kind KD) const {
5336 using Kind = PredefinedSugarType::Kind;
5337
5338 if (auto *Target = PredefinedSugarTypes[llvm::to_underlying(E: KD)];
5339 Target != nullptr)
5340 return QualType(Target, 0);
5341
5342 auto getCanonicalType = [](const ASTContext &Ctx, Kind KDI) -> QualType {
5343 switch (KDI) {
5344 // size_t (C99TC3 6.5.3.4), signed size_t (C++23 5.13.2) and
5345 // ptrdiff_t (C99TC3 6.5.6) Although these types are not built-in, they
5346 // are part of the core language and are widely used. Using
5347 // PredefinedSugarType makes these types as named sugar types rather than
5348 // standard integer types, enabling better hints and diagnostics.
5349 case Kind::SizeT:
5350 return Ctx.getFromTargetType(Type: Ctx.Target->getSizeType());
5351 case Kind::SignedSizeT:
5352 return Ctx.getFromTargetType(Type: Ctx.Target->getSignedSizeType());
5353 case Kind::PtrdiffT:
5354 return Ctx.getFromTargetType(Type: Ctx.Target->getPtrDiffType(AddrSpace: LangAS::Default));
5355 }
5356 llvm_unreachable("unexpected kind");
5357 };
5358 auto *New = new (*this, alignof(PredefinedSugarType))
5359 PredefinedSugarType(KD, &Idents.get(Name: PredefinedSugarType::getName(KD)),
5360 getCanonicalType(*this, static_cast<Kind>(KD)));
5361 Types.push_back(Elt: New);
5362 PredefinedSugarTypes[llvm::to_underlying(E: KD)] = New;
5363 return QualType(New, 0);
5364}
5365
5366QualType ASTContext::getTypeDeclType(ElaboratedTypeKeyword Keyword,
5367 NestedNameSpecifier Qualifier,
5368 const TypeDecl *Decl) const {
5369 if (auto *Tag = dyn_cast<TagDecl>(Val: Decl))
5370 return getTagType(Keyword, Qualifier, TD: Tag,
5371 /*OwnsTag=*/false);
5372 if (auto *Typedef = dyn_cast<TypedefNameDecl>(Val: Decl))
5373 return getTypedefType(Keyword, Qualifier, Decl: Typedef);
5374 if (auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(Val: Decl))
5375 return getUnresolvedUsingType(Keyword, Qualifier, D: UD);
5376
5377 assert(Keyword == ElaboratedTypeKeyword::None);
5378 assert(!Qualifier);
5379 return QualType(Decl->TypeForDecl, 0);
5380}
5381
5382CanQualType ASTContext::getCanonicalTypeDeclType(const TypeDecl *TD) const {
5383 if (auto *Tag = dyn_cast<TagDecl>(Val: TD))
5384 return getCanonicalTagType(TD: Tag);
5385 if (auto *TN = dyn_cast<TypedefNameDecl>(Val: TD))
5386 return getCanonicalType(T: TN->getUnderlyingType());
5387 if (const auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(Val: TD))
5388 return getCanonicalUnresolvedUsingType(D: UD);
5389 assert(TD->TypeForDecl);
5390 return TD->TypeForDecl->getCanonicalTypeUnqualified();
5391}
5392
5393QualType ASTContext::getTypeDeclType(const TypeDecl *Decl) const {
5394 if (const auto *TD = dyn_cast<TagDecl>(Val: Decl))
5395 return getCanonicalTagType(TD);
5396 if (const auto *TD = dyn_cast<TypedefNameDecl>(Val: Decl);
5397 isa_and_nonnull<TypedefDecl, TypeAliasDecl>(Val: TD))
5398 return getTypedefType(Keyword: ElaboratedTypeKeyword::None,
5399 /*Qualifier=*/std::nullopt, Decl: TD);
5400 if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Val: Decl))
5401 return getCanonicalUnresolvedUsingType(D: Using);
5402
5403 assert(Decl->TypeForDecl);
5404 return QualType(Decl->TypeForDecl, 0);
5405}
5406
5407/// getTypedefType - Return the unique reference to the type for the
5408/// specified typedef name decl.
5409QualType
5410ASTContext::getTypedefType(ElaboratedTypeKeyword Keyword,
5411 NestedNameSpecifier Qualifier,
5412 const TypedefNameDecl *Decl, QualType UnderlyingType,
5413 std::optional<bool> TypeMatchesDeclOrNone) const {
5414 if (!TypeMatchesDeclOrNone) {
5415 QualType DeclUnderlyingType = Decl->getUnderlyingType();
5416 assert(!DeclUnderlyingType.isNull());
5417 if (UnderlyingType.isNull())
5418 UnderlyingType = DeclUnderlyingType;
5419 else
5420 assert(hasSameType(UnderlyingType, DeclUnderlyingType));
5421 TypeMatchesDeclOrNone = UnderlyingType == DeclUnderlyingType;
5422 } else {
5423 // FIXME: This is a workaround for a serialization cycle: assume the decl
5424 // underlying type is not available; don't touch it.
5425 assert(!UnderlyingType.isNull());
5426 }
5427
5428 if (Keyword == ElaboratedTypeKeyword::None && !Qualifier &&
5429 *TypeMatchesDeclOrNone) {
5430 if (Decl->TypeForDecl)
5431 return QualType(Decl->TypeForDecl, 0);
5432
5433 auto *NewType = new (*this, alignof(TypedefType))
5434 TypedefType(Type::Typedef, Keyword, Qualifier, Decl, UnderlyingType,
5435 !*TypeMatchesDeclOrNone);
5436
5437 Types.push_back(Elt: NewType);
5438 Decl->TypeForDecl = NewType;
5439 return QualType(NewType, 0);
5440 }
5441
5442 llvm::FoldingSetNodeID ID;
5443 TypedefType::Profile(ID, Keyword, Qualifier, Decl,
5444 Underlying: *TypeMatchesDeclOrNone ? QualType() : UnderlyingType);
5445
5446 llvm::FoldingSetInsertToken Token;
5447 if (FoldingSetPlaceholder<TypedefType> *Placeholder =
5448 TypedefTypes.lookup(ID, Token))
5449 return QualType(Placeholder->getType(), 0);
5450
5451 void *Mem =
5452 Allocate(Size: TypedefType::totalSizeToAlloc<FoldingSetPlaceholder<TypedefType>,
5453 NestedNameSpecifier, QualType>(
5454 Counts: 1, Counts: !!Qualifier, Counts: !*TypeMatchesDeclOrNone),
5455 Align: alignof(TypedefType));
5456 auto *NewType =
5457 new (Mem) TypedefType(Type::Typedef, Keyword, Qualifier, Decl,
5458 UnderlyingType, !*TypeMatchesDeclOrNone);
5459 auto *Placeholder = new (NewType->getFoldingSetPlaceholder())
5460 FoldingSetPlaceholder<TypedefType>();
5461 TypedefTypes.insert(N: Placeholder, Token);
5462 Types.push_back(Elt: NewType);
5463 return QualType(NewType, 0);
5464}
5465
5466QualType ASTContext::getUsingType(ElaboratedTypeKeyword Keyword,
5467 NestedNameSpecifier Qualifier,
5468 const UsingShadowDecl *D,
5469 QualType UnderlyingType) const {
5470 // FIXME: This is expensive to compute every time!
5471 if (UnderlyingType.isNull()) {
5472 const auto *UD = cast<UsingDecl>(Val: D->getIntroducer());
5473 UnderlyingType =
5474 getTypeDeclType(Keyword: UD->hasTypename() ? ElaboratedTypeKeyword::Typename
5475 : ElaboratedTypeKeyword::None,
5476 Qualifier: UD->getQualifier(), Decl: cast<TypeDecl>(Val: D->getTargetDecl()));
5477 }
5478
5479 llvm::FoldingSetNodeID ID;
5480 UsingType::Profile(ID, Keyword, Qualifier, D, UnderlyingType);
5481
5482 llvm::FoldingSetInsertToken Token;
5483 if (const UsingType *T = UsingTypes.lookup(ID, Token))
5484 return QualType(T, 0);
5485
5486 assert(!UnderlyingType.hasLocalQualifiers());
5487
5488 assert(
5489 hasSameType(getCanonicalTypeDeclType(cast<TypeDecl>(D->getTargetDecl())),
5490 UnderlyingType));
5491
5492 void *Mem =
5493 Allocate(Size: UsingType::totalSizeToAlloc<NestedNameSpecifier>(Counts: !!Qualifier),
5494 Align: alignof(UsingType));
5495 UsingType *T = new (Mem) UsingType(Keyword, Qualifier, D, UnderlyingType);
5496 Types.push_back(Elt: T);
5497 UsingTypes.insert(N: T, Token);
5498 return QualType(T, 0);
5499}
5500
5501TagType *ASTContext::getTagTypeInternal(ElaboratedTypeKeyword Keyword,
5502 NestedNameSpecifier Qualifier,
5503 const TagDecl *TD, bool OwnsTag,
5504 bool IsInjected,
5505 const Type *CanonicalType,
5506 bool WithFoldingSetNode) const {
5507 auto [TC, Size] = [&] {
5508 switch (TD->getDeclKind()) {
5509 case Decl::Enum:
5510 static_assert(alignof(EnumType) == alignof(TagType));
5511 return std::make_tuple(args: Type::Enum, args: sizeof(EnumType));
5512 case Decl::ClassTemplatePartialSpecialization:
5513 case Decl::ClassTemplateSpecialization:
5514 case Decl::CXXRecord:
5515 static_assert(alignof(RecordType) == alignof(TagType));
5516 static_assert(alignof(InjectedClassNameType) == alignof(TagType));
5517 if (cast<CXXRecordDecl>(Val: TD)->hasInjectedClassType())
5518 return std::make_tuple(args: Type::InjectedClassName,
5519 args: sizeof(InjectedClassNameType));
5520 [[fallthrough]];
5521 case Decl::Record:
5522 return std::make_tuple(args: Type::Record, args: sizeof(RecordType));
5523 default:
5524 llvm_unreachable("unexpected decl kind");
5525 }
5526 }();
5527
5528 if (Qualifier) {
5529 static_assert(alignof(NestedNameSpecifier) <= alignof(TagType));
5530 Size = llvm::alignTo(Value: Size, Align: alignof(NestedNameSpecifier)) +
5531 sizeof(NestedNameSpecifier);
5532 }
5533 void *Mem;
5534 if (WithFoldingSetNode) {
5535 // FIXME: It would be more profitable to tail allocate the folding set node
5536 // from the type, instead of the other way around, due to the greater
5537 // alignment requirements of the type. But this makes it harder to deal with
5538 // the different type node sizes. This would require either uniquing from
5539 // different folding sets, or having the folding setaccept a
5540 // contextual parameter which is not fixed at construction.
5541 Mem = Allocate(
5542 Size: sizeof(TagTypeFoldingSetPlaceholder) +
5543 TagTypeFoldingSetPlaceholder::getOffset() + Size,
5544 Align: std::max(a: alignof(TagTypeFoldingSetPlaceholder), b: alignof(TagType)));
5545 auto *T = new (Mem) TagTypeFoldingSetPlaceholder();
5546 Mem = T->getTagType();
5547 } else {
5548 Mem = Allocate(Size, Align: alignof(TagType));
5549 }
5550
5551 auto *T = [&, TC = TC]() -> TagType * {
5552 switch (TC) {
5553 case Type::Enum: {
5554 assert(isa<EnumDecl>(TD));
5555 auto *T = new (Mem) EnumType(TC, Keyword, Qualifier, TD, OwnsTag,
5556 IsInjected, CanonicalType);
5557 assert(reinterpret_cast<void *>(T) ==
5558 reinterpret_cast<void *>(static_cast<TagType *>(T)) &&
5559 "TagType must be the first base of EnumType");
5560 return T;
5561 }
5562 case Type::Record: {
5563 assert(isa<RecordDecl>(TD));
5564 auto *T = new (Mem) RecordType(TC, Keyword, Qualifier, TD, OwnsTag,
5565 IsInjected, CanonicalType);
5566 assert(reinterpret_cast<void *>(T) ==
5567 reinterpret_cast<void *>(static_cast<TagType *>(T)) &&
5568 "TagType must be the first base of RecordType");
5569 return T;
5570 }
5571 case Type::InjectedClassName: {
5572 auto *T = new (Mem) InjectedClassNameType(Keyword, Qualifier, TD,
5573 IsInjected, CanonicalType);
5574 assert(reinterpret_cast<void *>(T) ==
5575 reinterpret_cast<void *>(static_cast<TagType *>(T)) &&
5576 "TagType must be the first base of InjectedClassNameType");
5577 return T;
5578 }
5579 default:
5580 llvm_unreachable("unexpected type class");
5581 }
5582 }();
5583 assert(T->getKeyword() == Keyword);
5584 assert(T->getQualifier() == Qualifier);
5585 assert(T->getDecl() == TD);
5586 assert(T->isInjected() == IsInjected);
5587 assert(T->isTagOwned() == OwnsTag);
5588 assert((T->isCanonicalUnqualified()
5589 ? QualType()
5590 : T->getCanonicalTypeInternal()) == QualType(CanonicalType, 0));
5591 Types.push_back(Elt: T);
5592 return T;
5593}
5594
5595static const TagDecl *getNonInjectedClassName(const TagDecl *TD) {
5596 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: TD);
5597 RD && RD->isInjectedClassName())
5598 return cast<TagDecl>(Val: RD->getDeclContext());
5599 return TD;
5600}
5601
5602CanQualType ASTContext::getCanonicalTagType(const TagDecl *TD) const {
5603 TD = ::getNonInjectedClassName(TD)->getCanonicalDecl();
5604 if (TD->TypeForDecl)
5605 return TD->TypeForDecl->getCanonicalTypeUnqualified();
5606
5607 const Type *CanonicalType = getTagTypeInternal(
5608 Keyword: ElaboratedTypeKeyword::None,
5609 /*Qualifier=*/std::nullopt, TD,
5610 /*OwnsTag=*/false, /*IsInjected=*/false, /*CanonicalType=*/nullptr,
5611 /*WithFoldingSetNode=*/false);
5612 TD->TypeForDecl = CanonicalType;
5613 return CanQualType::CreateUnsafe(Other: QualType(CanonicalType, 0));
5614}
5615
5616QualType ASTContext::getTagType(ElaboratedTypeKeyword Keyword,
5617 NestedNameSpecifier Qualifier,
5618 const TagDecl *TD, bool OwnsTag) const {
5619
5620 const TagDecl *NonInjectedTD = ::getNonInjectedClassName(TD);
5621 bool IsInjected = TD != NonInjectedTD;
5622
5623 ElaboratedTypeKeyword PreferredKeyword =
5624 getLangOpts().CPlusPlus ? ElaboratedTypeKeyword::None
5625 : KeywordHelpers::getKeywordForTagTypeKind(
5626 Tag: NonInjectedTD->getTagKind());
5627
5628 if (Keyword == PreferredKeyword && !Qualifier && !OwnsTag) {
5629 if (const Type *T = TD->TypeForDecl; T && !T->isCanonicalUnqualified())
5630 return QualType(T, 0);
5631
5632 const Type *CanonicalType = getCanonicalTagType(TD: NonInjectedTD).getTypePtr();
5633 const Type *T =
5634 getTagTypeInternal(Keyword,
5635 /*Qualifier=*/std::nullopt, TD: NonInjectedTD,
5636 /*OwnsTag=*/false, IsInjected, CanonicalType,
5637 /*WithFoldingSetNode=*/false);
5638 TD->TypeForDecl = T;
5639 return QualType(T, 0);
5640 }
5641
5642 llvm::FoldingSetNodeID ID;
5643 TagTypeFoldingSetPlaceholder::Profile(ID, Keyword, Qualifier, Tag: NonInjectedTD,
5644 OwnsTag, IsInjected);
5645
5646 llvm::FoldingSetInsertToken Token;
5647 if (TagTypeFoldingSetPlaceholder *T = TagTypes.lookup(ID, Token))
5648 return QualType(T->getTagType(), 0);
5649
5650 const Type *CanonicalType = getCanonicalTagType(TD: NonInjectedTD).getTypePtr();
5651 TagType *T =
5652 getTagTypeInternal(Keyword, Qualifier, TD: NonInjectedTD, OwnsTag, IsInjected,
5653 CanonicalType, /*WithFoldingSetNode=*/true);
5654 TagTypes.insert(N: TagTypeFoldingSetPlaceholder::fromTagType(T), Token);
5655 return QualType(T, 0);
5656}
5657
5658bool ASTContext::computeBestEnumTypes(bool IsPacked, unsigned NumNegativeBits,
5659 unsigned NumPositiveBits,
5660 QualType &BestType,
5661 QualType &BestPromotionType) {
5662 unsigned IntWidth = Target->getIntWidth();
5663 unsigned CharWidth = Target->getCharWidth();
5664 unsigned ShortWidth = Target->getShortWidth();
5665 bool EnumTooLarge = false;
5666 unsigned BestWidth;
5667 if (NumNegativeBits) {
5668 // If there is a negative value, figure out the smallest integer type (of
5669 // int/long/longlong) that fits.
5670 // If it's packed, check also if it fits a char or a short.
5671 if (IsPacked && NumNegativeBits <= CharWidth &&
5672 NumPositiveBits < CharWidth) {
5673 BestType = SignedCharTy;
5674 BestWidth = CharWidth;
5675 } else if (IsPacked && NumNegativeBits <= ShortWidth &&
5676 NumPositiveBits < ShortWidth) {
5677 BestType = ShortTy;
5678 BestWidth = ShortWidth;
5679 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
5680 BestType = IntTy;
5681 BestWidth = IntWidth;
5682 } else {
5683 BestWidth = Target->getLongWidth();
5684
5685 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
5686 BestType = LongTy;
5687 } else {
5688 BestWidth = Target->getLongLongWidth();
5689
5690 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
5691 EnumTooLarge = true;
5692 BestType = LongLongTy;
5693 }
5694 }
5695 BestPromotionType = (BestWidth <= IntWidth ? IntTy : BestType);
5696 } else {
5697 // If there is no negative value, figure out the smallest type that fits
5698 // all of the enumerator values.
5699 // If it's packed, check also if it fits a char or a short.
5700 if (IsPacked && NumPositiveBits <= CharWidth) {
5701 BestType = UnsignedCharTy;
5702 BestPromotionType = IntTy;
5703 BestWidth = CharWidth;
5704 } else if (IsPacked && NumPositiveBits <= ShortWidth) {
5705 BestType = UnsignedShortTy;
5706 BestPromotionType = IntTy;
5707 BestWidth = ShortWidth;
5708 } else if (NumPositiveBits <= IntWidth) {
5709 BestType = UnsignedIntTy;
5710 BestWidth = IntWidth;
5711 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5712 ? UnsignedIntTy
5713 : IntTy;
5714 } else if (NumPositiveBits <= (BestWidth = Target->getLongWidth())) {
5715 BestType = UnsignedLongTy;
5716 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5717 ? UnsignedLongTy
5718 : LongTy;
5719 } else {
5720 BestWidth = Target->getLongLongWidth();
5721 if (NumPositiveBits > BestWidth) {
5722 // This can happen with bit-precise integer types, but those are not
5723 // allowed as the type for an enumerator per C23 6.7.2.2p4 and p12.
5724 // FIXME: GCC uses __int128_t and __uint128_t for cases that fit within
5725 // a 128-bit integer, we should consider doing the same.
5726 EnumTooLarge = true;
5727 }
5728 BestType = UnsignedLongLongTy;
5729 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5730 ? UnsignedLongLongTy
5731 : LongLongTy;
5732 }
5733 }
5734 return EnumTooLarge;
5735}
5736
5737bool ASTContext::isRepresentableIntegerValue(llvm::APSInt &Value, QualType T) {
5738 assert((T->isIntegralType(*this) || T->isEnumeralType()) &&
5739 "Integral type required!");
5740 unsigned BitWidth = getIntWidth(T);
5741
5742 if (Value.isUnsigned() || Value.isNonNegative()) {
5743 if (T->isSignedIntegerOrEnumerationType())
5744 --BitWidth;
5745 return Value.getActiveBits() <= BitWidth;
5746 }
5747 return Value.getSignificantBits() <= BitWidth;
5748}
5749
5750UnresolvedUsingType *ASTContext::getUnresolvedUsingTypeInternal(
5751 ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier,
5752 const UnresolvedUsingTypenameDecl *D, llvm::FoldingSetInsertToken Token,
5753 const Type *CanonicalType) const {
5754 void *Mem = Allocate(
5755 Size: UnresolvedUsingType::totalSizeToAlloc<
5756 FoldingSetPlaceholder<UnresolvedUsingType>, NestedNameSpecifier>(
5757 Counts: !!Token, Counts: !!Qualifier),
5758 Align: alignof(UnresolvedUsingType));
5759 auto *T = new (Mem) UnresolvedUsingType(Keyword, Qualifier, D, CanonicalType);
5760 if (Token) {
5761 auto *Placeholder = new (T->getFoldingSetPlaceholder())
5762 FoldingSetPlaceholder<UnresolvedUsingType>();
5763 UnresolvedUsingTypes.insert(N: Placeholder, Token);
5764 }
5765 Types.push_back(Elt: T);
5766 return T;
5767}
5768
5769CanQualType ASTContext::getCanonicalUnresolvedUsingType(
5770 const UnresolvedUsingTypenameDecl *D) const {
5771 D = D->getCanonicalDecl();
5772 if (D->TypeForDecl)
5773 return D->TypeForDecl->getCanonicalTypeUnqualified();
5774
5775 const Type *CanonicalType =
5776 getUnresolvedUsingTypeInternal(Keyword: ElaboratedTypeKeyword::None,
5777 /*Qualifier=*/std::nullopt, D,
5778 /*Token=*/{}, /*CanonicalType=*/nullptr);
5779 D->TypeForDecl = CanonicalType;
5780 return CanQualType::CreateUnsafe(Other: QualType(CanonicalType, 0));
5781}
5782
5783QualType
5784ASTContext::getUnresolvedUsingType(ElaboratedTypeKeyword Keyword,
5785 NestedNameSpecifier Qualifier,
5786 const UnresolvedUsingTypenameDecl *D) const {
5787 if (Keyword == ElaboratedTypeKeyword::None && !Qualifier) {
5788 if (const Type *T = D->TypeForDecl; T && !T->isCanonicalUnqualified())
5789 return QualType(T, 0);
5790
5791 const Type *CanonicalType = getCanonicalUnresolvedUsingType(D).getTypePtr();
5792 const Type *T =
5793 getUnresolvedUsingTypeInternal(Keyword: ElaboratedTypeKeyword::None,
5794 /*Qualifier=*/std::nullopt, D,
5795 /*Token=*/{}, CanonicalType);
5796 D->TypeForDecl = T;
5797 return QualType(T, 0);
5798 }
5799
5800 llvm::FoldingSetNodeID ID;
5801 UnresolvedUsingType::Profile(ID, Keyword, Qualifier, D);
5802
5803 llvm::FoldingSetInsertToken Token;
5804 if (FoldingSetPlaceholder<UnresolvedUsingType> *Placeholder =
5805 UnresolvedUsingTypes.lookup(ID, Token))
5806 return QualType(Placeholder->getType(), 0);
5807 assert(Token);
5808
5809 const Type *CanonicalType = getCanonicalUnresolvedUsingType(D).getTypePtr();
5810 const Type *T = getUnresolvedUsingTypeInternal(Keyword, Qualifier, D, Token,
5811 CanonicalType);
5812 return QualType(T, 0);
5813}
5814
5815QualType ASTContext::getAttributedType(attr::Kind attrKind,
5816 QualType modifiedType,
5817 QualType equivalentType,
5818 const Attr *attr) const {
5819 llvm::FoldingSetNodeID id;
5820 AttributedType::Profile(ID&: id, Ctx: *this, attrKind, modified: modifiedType, equivalent: equivalentType,
5821 attr);
5822
5823 llvm::FoldingSetInsertToken Token;
5824 AttributedType *type = AttributedTypes.lookup(ID: id, Token);
5825 if (type) return QualType(type, 0);
5826
5827 assert(!attr || attr->getKind() == attrKind);
5828
5829 QualType canon = getCanonicalType(T: equivalentType);
5830 type = new (*this, alignof(AttributedType))
5831 AttributedType(canon, attrKind, attr, modifiedType, equivalentType);
5832
5833 Types.push_back(Elt: type);
5834 AttributedTypes.insert(N: type, Token);
5835
5836 return QualType(type, 0);
5837}
5838
5839QualType ASTContext::getAttributedType(const Attr *attr, QualType modifiedType,
5840 QualType equivalentType) const {
5841 return getAttributedType(attrKind: attr->getKind(), modifiedType, equivalentType, attr);
5842}
5843
5844QualType ASTContext::getAttributedType(NullabilityKind nullability,
5845 QualType modifiedType,
5846 QualType equivalentType) const {
5847 switch (nullability) {
5848 case NullabilityKind::NonNull:
5849 return getAttributedType(attrKind: attr::TypeNonNull, modifiedType, equivalentType);
5850
5851 case NullabilityKind::Nullable:
5852 return getAttributedType(attrKind: attr::TypeNullable, modifiedType, equivalentType);
5853
5854 case NullabilityKind::NullableResult:
5855 return getAttributedType(attrKind: attr::TypeNullableResult, modifiedType,
5856 equivalentType);
5857
5858 case NullabilityKind::Unspecified:
5859 return getAttributedType(attrKind: attr::TypeNullUnspecified, modifiedType,
5860 equivalentType);
5861 }
5862
5863 llvm_unreachable("Unknown nullability kind");
5864}
5865
5866QualType ASTContext::getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr,
5867 QualType Wrapped) const {
5868 llvm::FoldingSetNodeID ID;
5869 BTFTagAttributedType::Profile(ID, Wrapped, BTFAttr);
5870
5871 llvm::FoldingSetInsertToken Token;
5872 BTFTagAttributedType *Ty = BTFTagAttributedTypes.lookup(ID, Token);
5873 if (Ty)
5874 return QualType(Ty, 0);
5875
5876 QualType Canon = getCanonicalType(T: Wrapped);
5877 Ty = new (*this, alignof(BTFTagAttributedType))
5878 BTFTagAttributedType(Canon, Wrapped, BTFAttr);
5879
5880 Types.push_back(Elt: Ty);
5881 BTFTagAttributedTypes.insert(N: Ty, Token);
5882
5883 return QualType(Ty, 0);
5884}
5885
5886QualType ASTContext::getOverflowBehaviorType(const OverflowBehaviorAttr *Attr,
5887 QualType Underlying) const {
5888 const IdentifierInfo *II = Attr->getBehaviorKind();
5889 StringRef IdentName = II->getName();
5890 OverflowBehaviorType::OverflowBehaviorKind Kind;
5891 if (IdentName == "wrap") {
5892 Kind = OverflowBehaviorType::OverflowBehaviorKind::Wrap;
5893 } else if (IdentName == "trap") {
5894 Kind = OverflowBehaviorType::OverflowBehaviorKind::Trap;
5895 } else {
5896 return Underlying;
5897 }
5898
5899 return getOverflowBehaviorType(Kind, Wrapped: Underlying);
5900}
5901
5902QualType ASTContext::getOverflowBehaviorType(
5903 OverflowBehaviorType::OverflowBehaviorKind Kind,
5904 QualType Underlying) const {
5905 assert(!Underlying->isOverflowBehaviorType() &&
5906 "Cannot have underlying types that are themselves OBTs");
5907
5908 llvm::FoldingSetInsertToken Token;
5909 if (OverflowBehaviorType *OBT =
5910 OverflowBehaviorTypes.lookup(Key: {Underlying, Kind}, Token)) {
5911 return QualType(OBT, 0);
5912 }
5913
5914 QualType Canonical;
5915 if (!Underlying.isCanonical() || Underlying.hasLocalQualifiers()) {
5916 SplitQualType canonSplit = getCanonicalType(T: Underlying).split();
5917 Canonical = getOverflowBehaviorType(Kind, Underlying: QualType(canonSplit.Ty, 0));
5918 Canonical = getQualifiedType(T: Canonical, Qs: canonSplit.Quals);
5919 assert(!OverflowBehaviorTypes.lookup({Underlying, Kind}, Token) &&
5920 "Shouldn't be in the map");
5921 }
5922
5923 OverflowBehaviorType *Ty = new (*this, alignof(OverflowBehaviorType))
5924 OverflowBehaviorType(*this, Canonical, Underlying, Kind);
5925
5926 Types.push_back(Elt: Ty);
5927 OverflowBehaviorTypes.insert(N: Ty, Token);
5928 return QualType(Ty, 0);
5929}
5930
5931QualType ASTContext::getHLSLAttributedResourceType(
5932 QualType Wrapped, QualType Contained,
5933 const HLSLAttributedResourceType::Attributes &Attrs) {
5934
5935 llvm::FoldingSetNodeID ID;
5936 HLSLAttributedResourceType::Profile(ID, Ctx: *this, Wrapped, Contained, Attrs);
5937
5938 llvm::FoldingSetInsertToken Token;
5939 HLSLAttributedResourceType *Ty =
5940 HLSLAttributedResourceTypes.lookup(ID, Token);
5941 if (Ty)
5942 return QualType(Ty, 0);
5943
5944 Ty = new (*this, alignof(HLSLAttributedResourceType))
5945 HLSLAttributedResourceType(Wrapped, Contained, Attrs);
5946
5947 Types.push_back(Elt: Ty);
5948 HLSLAttributedResourceTypes.insert(N: Ty, Token);
5949
5950 return QualType(Ty, 0);
5951}
5952
5953QualType ASTContext::getHLSLInlineSpirvType(uint32_t Opcode, uint32_t Size,
5954 uint32_t Alignment,
5955 ArrayRef<SpirvOperand> Operands) {
5956 llvm::FoldingSetNodeID ID;
5957 HLSLInlineSpirvType::Profile(ID, Opcode, Size, Alignment, Operands);
5958
5959 llvm::FoldingSetInsertToken Token;
5960 HLSLInlineSpirvType *Ty = HLSLInlineSpirvTypes.lookup(ID, Token);
5961 if (Ty)
5962 return QualType(Ty, 0);
5963
5964 void *Mem = Allocate(
5965 Size: HLSLInlineSpirvType::totalSizeToAlloc<SpirvOperand>(Counts: Operands.size()),
5966 Align: alignof(HLSLInlineSpirvType));
5967
5968 Ty = new (Mem) HLSLInlineSpirvType(Opcode, Size, Alignment, Operands);
5969
5970 Types.push_back(Elt: Ty);
5971 HLSLInlineSpirvTypes.insert(N: Ty, Token);
5972
5973 return QualType(Ty, 0);
5974}
5975
5976/// Retrieve a substitution-result type.
5977QualType ASTContext::getSubstTemplateTypeParmType(QualType Replacement,
5978 Decl *AssociatedDecl,
5979 unsigned Index,
5980 UnsignedOrNone PackIndex,
5981 bool Final) const {
5982 auto Key =
5983 std::make_tuple(args&: Replacement, args&: AssociatedDecl, args&: Index,
5984 args: PackIndex.toInternalRepresentation(), args: unsigned(Final));
5985 llvm::FoldingSetInsertToken Token;
5986 SubstTemplateTypeParmType *SubstParm =
5987 SubstTemplateTypeParmTypes.lookup(Key, Token);
5988
5989 if (!SubstParm) {
5990 void *Mem = Allocate(Size: SubstTemplateTypeParmType::totalSizeToAlloc<QualType>(
5991 Counts: !Replacement.isCanonical()),
5992 Align: alignof(SubstTemplateTypeParmType));
5993 SubstParm = new (Mem) SubstTemplateTypeParmType(Replacement, AssociatedDecl,
5994 Index, PackIndex, Final);
5995 Types.push_back(Elt: SubstParm);
5996 SubstTemplateTypeParmTypes.insert(N: SubstParm, Token);
5997 }
5998
5999 return QualType(SubstParm, 0);
6000}
6001
6002QualType
6003ASTContext::getSubstTemplateTypeParmPackType(Decl *AssociatedDecl,
6004 unsigned Index, bool Final,
6005 const TemplateArgument &ArgPack) {
6006#ifndef NDEBUG
6007 for (const auto &P : ArgPack.pack_elements())
6008 assert(P.getKind() == TemplateArgument::Type && "Pack contains a non-type");
6009#endif
6010
6011 llvm::FoldingSetNodeID ID;
6012 SubstTemplateTypeParmPackType::Profile(ID, AssociatedDecl, Index, Final,
6013 ArgPack);
6014 llvm::FoldingSetInsertToken Token;
6015 if (SubstTemplateTypeParmPackType *SubstParm =
6016 SubstTemplateTypeParmPackTypes.lookup(ID, Token))
6017 return QualType(SubstParm, 0);
6018
6019 QualType Canon;
6020 {
6021 TemplateArgument CanonArgPack = getCanonicalTemplateArgument(Arg: ArgPack);
6022 if (!AssociatedDecl->isCanonicalDecl() ||
6023 !CanonArgPack.structurallyEquals(Other: ArgPack)) {
6024 Canon = getSubstTemplateTypeParmPackType(
6025 AssociatedDecl: AssociatedDecl->getCanonicalDecl(), Index, Final, ArgPack: CanonArgPack);
6026 [[maybe_unused]] const auto *Nothing =
6027 SubstTemplateTypeParmPackTypes.lookup(ID, Token);
6028 assert(!Nothing);
6029 }
6030 }
6031
6032 auto *SubstParm = new (*this, alignof(SubstTemplateTypeParmPackType))
6033 SubstTemplateTypeParmPackType(Canon, AssociatedDecl, Index, Final,
6034 ArgPack);
6035 Types.push_back(Elt: SubstParm);
6036 SubstTemplateTypeParmPackTypes.insert(N: SubstParm, Token);
6037 return QualType(SubstParm, 0);
6038}
6039
6040QualType
6041ASTContext::getSubstBuiltinTemplatePack(const TemplateArgument &ArgPack) {
6042 assert(llvm::all_of(ArgPack.pack_elements(),
6043 [](const auto &P) {
6044 return P.getKind() == TemplateArgument::Type;
6045 }) &&
6046 "Pack contains a non-type");
6047
6048 llvm::FoldingSetNodeID ID;
6049 SubstBuiltinTemplatePackType::Profile(ID, ArgPack);
6050
6051 llvm::FoldingSetInsertToken Token;
6052 if (auto *T = SubstBuiltinTemplatePackTypes.lookup(ID, Token))
6053 return QualType(T, 0);
6054
6055 QualType Canon;
6056 TemplateArgument CanonArgPack = getCanonicalTemplateArgument(Arg: ArgPack);
6057 if (!CanonArgPack.structurallyEquals(Other: ArgPack)) {
6058 Canon = getSubstBuiltinTemplatePack(ArgPack: CanonArgPack);
6059 // Refresh Token, in case the recursive call above caused rehashing,
6060 // which would invalidate the bucket pointer.
6061 [[maybe_unused]] const auto *Nothing =
6062 SubstBuiltinTemplatePackTypes.lookup(ID, Token);
6063 assert(!Nothing);
6064 }
6065
6066 auto *PackType = new (*this, alignof(SubstBuiltinTemplatePackType))
6067 SubstBuiltinTemplatePackType(Canon, ArgPack);
6068 Types.push_back(Elt: PackType);
6069 SubstBuiltinTemplatePackTypes.insert(N: PackType, Token);
6070 return QualType(PackType, 0);
6071}
6072
6073/// Retrieve the template type parameter type for a template
6074/// parameter or parameter pack with the given depth, index, and (optionally)
6075/// name.
6076QualType
6077ASTContext::getTemplateTypeParmType(int Depth, int Index, bool ParameterPack,
6078 TemplateTypeParmDecl *TTPDecl) const {
6079 assert(Depth >= 0 && "Depth must be non-negative");
6080 assert(Index >= 0 && "Index must be non-negative");
6081
6082 auto Key = std::make_tuple(args: unsigned(Depth), args: unsigned(Index),
6083 args: unsigned(ParameterPack), args&: TTPDecl);
6084 llvm::FoldingSetInsertToken Token;
6085 TemplateTypeParmType *TypeParm = TemplateTypeParmTypes.lookup(Key, Token);
6086
6087 if (TypeParm)
6088 return QualType(TypeParm, 0);
6089
6090 if (TTPDecl) {
6091 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
6092 TypeParm = new (*this, alignof(TemplateTypeParmType))
6093 TemplateTypeParmType(Depth, Index, ParameterPack, TTPDecl, Canon);
6094 } else
6095 TypeParm = new (*this, alignof(TemplateTypeParmType)) TemplateTypeParmType(
6096 Depth, Index, ParameterPack, /*TTPDecl=*/nullptr, /*Canon=*/QualType());
6097
6098 Types.push_back(Elt: TypeParm);
6099 TemplateTypeParmTypes.insert(N: TypeParm, Token);
6100
6101 return QualType(TypeParm, 0);
6102}
6103
6104static ElaboratedTypeKeyword
6105getCanonicalElaboratedTypeKeyword(ElaboratedTypeKeyword Keyword) {
6106 switch (Keyword) {
6107 // These are just themselves.
6108 case ElaboratedTypeKeyword::None:
6109 case ElaboratedTypeKeyword::Struct:
6110 case ElaboratedTypeKeyword::Union:
6111 case ElaboratedTypeKeyword::Enum:
6112 case ElaboratedTypeKeyword::Interface:
6113 return Keyword;
6114
6115 // These are equivalent.
6116 case ElaboratedTypeKeyword::Typename:
6117 return ElaboratedTypeKeyword::None;
6118
6119 // These are functionally equivalent, so relying on their equivalence is
6120 // IFNDR. By making them equivalent, we disallow overloading, which at least
6121 // can produce a diagnostic.
6122 case ElaboratedTypeKeyword::Class:
6123 return ElaboratedTypeKeyword::Struct;
6124 }
6125 llvm_unreachable("unexpected keyword kind");
6126}
6127
6128TypeSourceInfo *ASTContext::getTemplateSpecializationTypeInfo(
6129 ElaboratedTypeKeyword Keyword, SourceLocation ElaboratedKeywordLoc,
6130 NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKeywordLoc,
6131 TemplateName Name, SourceLocation NameLoc,
6132 const TemplateArgumentListInfo &SpecifiedArgs,
6133 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
6134 QualType TST = getTemplateSpecializationType(
6135 Keyword, T: Name, SpecifiedArgs: SpecifiedArgs.arguments(), CanonicalArgs, Canon: Underlying);
6136
6137 TypeSourceInfo *TSI = CreateTypeSourceInfo(T: TST);
6138 TSI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>().set(
6139 ElaboratedKeywordLoc, QualifierLoc, TemplateKeywordLoc, NameLoc,
6140 TAL: SpecifiedArgs);
6141 return TSI;
6142}
6143
6144QualType ASTContext::getTemplateSpecializationType(
6145 ElaboratedTypeKeyword Keyword, TemplateName Template,
6146 ArrayRef<TemplateArgumentLoc> SpecifiedArgs,
6147 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
6148 SmallVector<TemplateArgument, 4> SpecifiedArgVec;
6149 SpecifiedArgVec.reserve(N: SpecifiedArgs.size());
6150 for (const TemplateArgumentLoc &Arg : SpecifiedArgs)
6151 SpecifiedArgVec.push_back(Elt: Arg.getArgument());
6152
6153 return getTemplateSpecializationType(Keyword, T: Template, SpecifiedArgs: SpecifiedArgVec,
6154 CanonicalArgs, Underlying);
6155}
6156
6157[[maybe_unused]] static bool
6158hasAnyPackExpansions(ArrayRef<TemplateArgument> Args) {
6159 for (const TemplateArgument &Arg : Args)
6160 if (Arg.isPackExpansion())
6161 return true;
6162 return false;
6163}
6164
6165QualType ASTContext::getCanonicalTemplateSpecializationType(
6166 ElaboratedTypeKeyword Keyword, TemplateName Template,
6167 ArrayRef<TemplateArgument> Args) const {
6168 assert(Template ==
6169 getCanonicalTemplateName(Template, /*IgnoreDeduced=*/true));
6170 assert((Keyword == ElaboratedTypeKeyword::None ||
6171 Template.getAsDependentTemplateName()));
6172#ifndef NDEBUG
6173 for (const auto &Arg : Args)
6174 assert(Arg.structurallyEquals(getCanonicalTemplateArgument(Arg)));
6175#endif
6176
6177 llvm::FoldingSetNodeID ID;
6178 TemplateSpecializationType::Profile(ID, Keyword, T: Template, Args, Underlying: QualType(),
6179 Context: *this);
6180 llvm::FoldingSetInsertToken Token;
6181 if (auto *T = TemplateSpecializationTypes.lookup(ID, Token))
6182 return QualType(T, 0);
6183
6184 void *Mem = Allocate(Size: sizeof(TemplateSpecializationType) +
6185 sizeof(TemplateArgument) * Args.size(),
6186 Align: alignof(TemplateSpecializationType));
6187 auto *Spec =
6188 new (Mem) TemplateSpecializationType(Keyword, Template,
6189 /*IsAlias=*/false, Args, QualType());
6190 assert(Spec->isDependentType() &&
6191 "canonical template specialization must be dependent");
6192 Types.push_back(Elt: Spec);
6193 TemplateSpecializationTypes.insert(N: Spec, Token);
6194 return QualType(Spec, 0);
6195}
6196
6197QualType ASTContext::getTemplateSpecializationType(
6198 ElaboratedTypeKeyword Keyword, TemplateName Template,
6199 ArrayRef<TemplateArgument> SpecifiedArgs,
6200 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
6201 const auto *TD = Template.getAsTemplateDecl(/*IgnoreDeduced=*/true);
6202 bool IsTypeAlias = TD && TD->isTypeAlias();
6203 if (Underlying.isNull()) {
6204 TemplateName CanonTemplate =
6205 getCanonicalTemplateName(Name: Template, /*IgnoreDeduced=*/true);
6206 ElaboratedTypeKeyword CanonKeyword =
6207 CanonTemplate.getAsDependentTemplateName()
6208 ? getCanonicalElaboratedTypeKeyword(Keyword)
6209 : ElaboratedTypeKeyword::None;
6210 bool NonCanonical = Template != CanonTemplate || Keyword != CanonKeyword;
6211 SmallVector<TemplateArgument, 4> CanonArgsVec;
6212 if (CanonicalArgs.empty()) {
6213 CanonArgsVec = SmallVector<TemplateArgument, 4>(SpecifiedArgs);
6214 NonCanonical |= canonicalizeTemplateArguments(Args: CanonArgsVec);
6215 CanonicalArgs = CanonArgsVec;
6216 } else {
6217 NonCanonical |= !llvm::equal(
6218 LRange&: SpecifiedArgs, RRange&: CanonicalArgs,
6219 P: [](const TemplateArgument &A, const TemplateArgument &B) {
6220 return A.structurallyEquals(Other: B);
6221 });
6222 }
6223
6224 // We can get here with an alias template when the specialization
6225 // contains a pack expansion that does not match up with a parameter
6226 // pack, or a builtin template which cannot be resolved due to dependency.
6227 assert((!isa_and_nonnull<TypeAliasTemplateDecl>(TD) ||
6228 hasAnyPackExpansions(CanonicalArgs)) &&
6229 "Caller must compute aliased type");
6230 IsTypeAlias = false;
6231
6232 Underlying = getCanonicalTemplateSpecializationType(
6233 Keyword: CanonKeyword, Template: CanonTemplate, Args: CanonicalArgs);
6234 if (!NonCanonical)
6235 return Underlying;
6236 }
6237 void *Mem = Allocate(Size: sizeof(TemplateSpecializationType) +
6238 sizeof(TemplateArgument) * SpecifiedArgs.size() +
6239 (IsTypeAlias ? sizeof(QualType) : 0),
6240 Align: alignof(TemplateSpecializationType));
6241 auto *Spec = new (Mem) TemplateSpecializationType(
6242 Keyword, Template, IsTypeAlias, SpecifiedArgs, Underlying);
6243 Types.push_back(Elt: Spec);
6244 return QualType(Spec, 0);
6245}
6246
6247QualType
6248ASTContext::getParenType(QualType InnerType) const {
6249 llvm::FoldingSetInsertToken Token;
6250 ParenType *T = ParenTypes.lookup(Key: InnerType, Token);
6251 if (T)
6252 return QualType(T, 0);
6253
6254 QualType Canon = InnerType;
6255 if (!Canon.isCanonical()) {
6256 Canon = getCanonicalType(T: InnerType);
6257 assert(!ParenTypes.lookup(InnerType, Token) &&
6258 "Paren canonical type broken");
6259 }
6260
6261 T = new (*this, alignof(ParenType)) ParenType(InnerType, Canon);
6262 Types.push_back(Elt: T);
6263 ParenTypes.insert(N: T, Token);
6264 return QualType(T, 0);
6265}
6266
6267QualType
6268ASTContext::getMacroQualifiedType(QualType UnderlyingTy,
6269 const IdentifierInfo *MacroII) const {
6270 QualType Canon = UnderlyingTy;
6271 if (!Canon.isCanonical())
6272 Canon = getCanonicalType(T: UnderlyingTy);
6273
6274 auto *newType = new (*this, alignof(MacroQualifiedType))
6275 MacroQualifiedType(UnderlyingTy, Canon, MacroII);
6276 Types.push_back(Elt: newType);
6277 return QualType(newType, 0);
6278}
6279
6280QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
6281 NestedNameSpecifier NNS,
6282 const IdentifierInfo *Name) const {
6283 llvm::FoldingSetNodeID ID;
6284 DependentNameType::Profile(ID, Keyword, NNS, Name);
6285
6286 llvm::FoldingSetInsertToken Token;
6287 if (DependentNameType *T = DependentNameTypes.lookup(ID, Token))
6288 return QualType(T, 0);
6289
6290 ElaboratedTypeKeyword CanonKeyword =
6291 getCanonicalElaboratedTypeKeyword(Keyword);
6292 NestedNameSpecifier CanonNNS = NNS.getCanonical();
6293
6294 QualType Canon;
6295 if (CanonKeyword != Keyword || CanonNNS != NNS) {
6296 Canon = getDependentNameType(Keyword: CanonKeyword, NNS: CanonNNS, Name);
6297 [[maybe_unused]] DependentNameType *T =
6298 DependentNameTypes.lookup(ID, Token);
6299 assert(!T && "broken canonicalization");
6300 assert(Canon.isCanonical());
6301 }
6302
6303 DependentNameType *T = new (*this, alignof(DependentNameType))
6304 DependentNameType(Keyword, NNS, Name, Canon);
6305 Types.push_back(Elt: T);
6306 DependentNameTypes.insert(N: T, Token);
6307 return QualType(T, 0);
6308}
6309
6310TemplateArgument ASTContext::getInjectedTemplateArg(NamedDecl *Param) const {
6311 TemplateArgument Arg;
6312 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Val: Param)) {
6313 QualType ArgType = getTypeDeclType(Decl: TTP);
6314 if (TTP->isParameterPack())
6315 ArgType = getPackExpansionType(Pattern: ArgType, NumExpansions: std::nullopt);
6316
6317 Arg = TemplateArgument(ArgType);
6318 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: Param)) {
6319 QualType T =
6320 NTTP->getType().getNonPackExpansionType().getNonLValueExprType(Context: *this);
6321 // For class NTTPs, ensure we include the 'const' so the type matches that
6322 // of a real template argument.
6323 // FIXME: It would be more faithful to model this as something like an
6324 // lvalue-to-rvalue conversion applied to a const-qualified lvalue.
6325 ExprValueKind VK;
6326 if (T->isRecordType()) {
6327 // C++ [temp.param]p8: An id-expression naming a non-type
6328 // template-parameter of class type T denotes a static storage duration
6329 // object of type const T.
6330 T.addConst();
6331 VK = VK_LValue;
6332 } else {
6333 VK = Expr::getValueKindForType(T: NTTP->getType());
6334 }
6335 Expr *E = new (*this)
6336 DeclRefExpr(*this, NTTP, /*RefersToEnclosingVariableOrCapture=*/false,
6337 T, VK, NTTP->getLocation());
6338
6339 if (NTTP->isParameterPack())
6340 E = new (*this) PackExpansionExpr(E, NTTP->getLocation(), std::nullopt);
6341 Arg = TemplateArgument(E, /*IsCanonical=*/false);
6342 } else {
6343 auto *TTP = cast<TemplateTemplateParmDecl>(Val: Param);
6344 TemplateName Name = getQualifiedTemplateName(
6345 /*Qualifier=*/std::nullopt, /*TemplateKeyword=*/false,
6346 Template: TemplateName(TTP));
6347 if (TTP->isParameterPack())
6348 Arg = TemplateArgument(Name, /*NumExpansions=*/std::nullopt);
6349 else
6350 Arg = TemplateArgument(Name);
6351 }
6352
6353 if (Param->isTemplateParameterPack())
6354 Arg =
6355 TemplateArgument::CreatePackCopy(Context&: const_cast<ASTContext &>(*this), Args: Arg);
6356
6357 return Arg;
6358}
6359
6360QualType ASTContext::getPackExpansionType(QualType Pattern,
6361 UnsignedOrNone NumExpansions,
6362 bool ExpectPackInType) const {
6363 assert((!ExpectPackInType || Pattern->containsUnexpandedParameterPack()) &&
6364 "Pack expansions must expand one or more parameter packs");
6365
6366 auto Key = std::make_pair(x&: Pattern, y: NumExpansions.toInternalRepresentation());
6367
6368 llvm::FoldingSetInsertToken Token;
6369 PackExpansionType *T = PackExpansionTypes.lookup(Key, Token);
6370 if (T)
6371 return QualType(T, 0);
6372
6373 QualType Canon;
6374 if (!Pattern.isCanonical()) {
6375 Canon = getPackExpansionType(Pattern: getCanonicalType(T: Pattern), NumExpansions,
6376 /*ExpectPackInType=*/false);
6377
6378 // Find the insert position again, in case we inserted an element into
6379 // PackExpansionTypes and invalidated our insert position.
6380 PackExpansionTypes.lookup(Key, Token);
6381 }
6382
6383 T = new (*this, alignof(PackExpansionType))
6384 PackExpansionType(Pattern, Canon, NumExpansions);
6385 Types.push_back(Elt: T);
6386 PackExpansionTypes.insert(N: T, Token);
6387 return QualType(T, 0);
6388}
6389
6390/// CmpProtocolNames - Comparison predicate for sorting protocols
6391/// alphabetically.
6392static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
6393 ObjCProtocolDecl *const *RHS) {
6394 return DeclarationName::compare(LHS: (*LHS)->getDeclName(), RHS: (*RHS)->getDeclName());
6395}
6396
6397static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) {
6398 if (Protocols.empty()) return true;
6399
6400 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
6401 return false;
6402
6403 for (unsigned i = 1; i != Protocols.size(); ++i)
6404 if (CmpProtocolNames(LHS: &Protocols[i - 1], RHS: &Protocols[i]) >= 0 ||
6405 Protocols[i]->getCanonicalDecl() != Protocols[i])
6406 return false;
6407 return true;
6408}
6409
6410static void
6411SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) {
6412 // Sort protocols, keyed by name.
6413 llvm::array_pod_sort(Start: Protocols.begin(), End: Protocols.end(), Compare: CmpProtocolNames);
6414
6415 // Canonicalize.
6416 for (ObjCProtocolDecl *&P : Protocols)
6417 P = P->getCanonicalDecl();
6418
6419 // Remove duplicates.
6420 auto ProtocolsEnd = llvm::unique(R&: Protocols);
6421 Protocols.erase(CS: ProtocolsEnd, CE: Protocols.end());
6422}
6423
6424QualType ASTContext::getObjCObjectType(QualType BaseType,
6425 ObjCProtocolDecl * const *Protocols,
6426 unsigned NumProtocols) const {
6427 return getObjCObjectType(Base: BaseType, typeArgs: {}, protocols: ArrayRef(Protocols, NumProtocols),
6428 /*isKindOf=*/false);
6429}
6430
6431QualType ASTContext::getObjCObjectType(
6432 QualType baseType,
6433 ArrayRef<QualType> typeArgs,
6434 ArrayRef<ObjCProtocolDecl *> protocols,
6435 bool isKindOf) const {
6436 // If the base type is an interface and there aren't any protocols or
6437 // type arguments to add, then the interface type will do just fine.
6438 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
6439 isa<ObjCInterfaceType>(Val: baseType))
6440 return baseType;
6441
6442 // Look in the folding set for an existing type.
6443 llvm::FoldingSetNodeID ID;
6444 ObjCObjectTypeImpl::Profile(ID, Base: baseType, typeArgs, protocols, isKindOf);
6445 llvm::FoldingSetInsertToken Token;
6446 if (ObjCObjectType *QT = ObjCObjectTypes.lookup(ID, Token))
6447 return QualType(QT, 0);
6448
6449 // Determine the type arguments to be used for canonicalization,
6450 // which may be explicitly specified here or written on the base
6451 // type.
6452 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
6453 if (effectiveTypeArgs.empty()) {
6454 if (const auto *baseObject = baseType->getAs<ObjCObjectType>())
6455 effectiveTypeArgs = baseObject->getTypeArgs();
6456 }
6457
6458 // Build the canonical type, which has the canonical base type and a
6459 // sorted-and-uniqued list of protocols and the type arguments
6460 // canonicalized.
6461 QualType canonical;
6462 bool typeArgsAreCanonical = llvm::all_of(
6463 Range&: effectiveTypeArgs, P: [&](QualType type) { return type.isCanonical(); });
6464 bool protocolsSorted = areSortedAndUniqued(Protocols: protocols);
6465 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
6466 // Determine the canonical type arguments.
6467 ArrayRef<QualType> canonTypeArgs;
6468 SmallVector<QualType, 4> canonTypeArgsVec;
6469 if (!typeArgsAreCanonical) {
6470 canonTypeArgsVec.reserve(N: effectiveTypeArgs.size());
6471 for (auto typeArg : effectiveTypeArgs)
6472 canonTypeArgsVec.push_back(Elt: getCanonicalType(T: typeArg));
6473 canonTypeArgs = canonTypeArgsVec;
6474 } else {
6475 canonTypeArgs = effectiveTypeArgs;
6476 }
6477
6478 ArrayRef<ObjCProtocolDecl *> canonProtocols;
6479 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
6480 if (!protocolsSorted) {
6481 canonProtocolsVec.append(in_start: protocols.begin(), in_end: protocols.end());
6482 SortAndUniqueProtocols(Protocols&: canonProtocolsVec);
6483 canonProtocols = canonProtocolsVec;
6484 } else {
6485 canonProtocols = protocols;
6486 }
6487
6488 canonical = getObjCObjectType(baseType: getCanonicalType(T: baseType), typeArgs: canonTypeArgs,
6489 protocols: canonProtocols, isKindOf);
6490
6491 // Regenerate Token.
6492 ObjCObjectTypes.lookup(ID, Token);
6493 }
6494
6495 unsigned size = sizeof(ObjCObjectTypeImpl);
6496 size += typeArgs.size() * sizeof(QualType);
6497 size += protocols.size() * sizeof(ObjCProtocolDecl *);
6498 void *mem = Allocate(Size: size, Align: alignof(ObjCObjectTypeImpl));
6499 auto *T =
6500 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
6501 isKindOf);
6502
6503 Types.push_back(Elt: T);
6504 ObjCObjectTypes.insert(N: T, Token);
6505 return QualType(T, 0);
6506}
6507
6508/// Apply Objective-C protocol qualifiers to the given type.
6509/// If this is for the canonical type of a type parameter, we can apply
6510/// protocol qualifiers on the ObjCObjectPointerType.
6511QualType
6512ASTContext::applyObjCProtocolQualifiers(QualType type,
6513 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
6514 bool allowOnPointerType) const {
6515 hasError = false;
6516
6517 if (const auto *objT = dyn_cast<ObjCTypeParamType>(Val: type.getTypePtr())) {
6518 return getObjCTypeParamType(Decl: objT->getDecl(), protocols);
6519 }
6520
6521 // Apply protocol qualifiers to ObjCObjectPointerType.
6522 if (allowOnPointerType) {
6523 if (const auto *objPtr =
6524 dyn_cast<ObjCObjectPointerType>(Val: type.getTypePtr())) {
6525 const ObjCObjectType *objT = objPtr->getObjectType();
6526 // Merge protocol lists and construct ObjCObjectType.
6527 SmallVector<ObjCProtocolDecl*, 8> protocolsVec;
6528 protocolsVec.append(in_start: objT->qual_begin(),
6529 in_end: objT->qual_end());
6530 protocolsVec.append(in_start: protocols.begin(), in_end: protocols.end());
6531 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
6532 type = getObjCObjectType(
6533 baseType: objT->getBaseType(),
6534 typeArgs: objT->getTypeArgsAsWritten(),
6535 protocols,
6536 isKindOf: objT->isKindOfTypeAsWritten());
6537 return getObjCObjectPointerType(OIT: type);
6538 }
6539 }
6540
6541 // Apply protocol qualifiers to ObjCObjectType.
6542 if (const auto *objT = dyn_cast<ObjCObjectType>(Val: type.getTypePtr())){
6543 // FIXME: Check for protocols to which the class type is already
6544 // known to conform.
6545
6546 return getObjCObjectType(baseType: objT->getBaseType(),
6547 typeArgs: objT->getTypeArgsAsWritten(),
6548 protocols,
6549 isKindOf: objT->isKindOfTypeAsWritten());
6550 }
6551
6552 // If the canonical type is ObjCObjectType, ...
6553 if (type->isObjCObjectType()) {
6554 // Silently overwrite any existing protocol qualifiers.
6555 // TODO: determine whether that's the right thing to do.
6556
6557 // FIXME: Check for protocols to which the class type is already
6558 // known to conform.
6559 return getObjCObjectType(baseType: type, typeArgs: {}, protocols, isKindOf: false);
6560 }
6561
6562 // id<protocol-list>
6563 if (type->isObjCIdType()) {
6564 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
6565 type = getObjCObjectType(baseType: ObjCBuiltinIdTy, typeArgs: {}, protocols,
6566 isKindOf: objPtr->isKindOfType());
6567 return getObjCObjectPointerType(OIT: type);
6568 }
6569
6570 // Class<protocol-list>
6571 if (type->isObjCClassType()) {
6572 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
6573 type = getObjCObjectType(baseType: ObjCBuiltinClassTy, typeArgs: {}, protocols,
6574 isKindOf: objPtr->isKindOfType());
6575 return getObjCObjectPointerType(OIT: type);
6576 }
6577
6578 hasError = true;
6579 return type;
6580}
6581
6582QualType
6583ASTContext::getObjCTypeParamType(const ObjCTypeParamDecl *Decl,
6584 ArrayRef<ObjCProtocolDecl *> protocols) const {
6585 // We canonicalize to the underlying type.
6586 QualType Canonical = getCanonicalType(T: Decl->getUnderlyingType());
6587 if (!protocols.empty()) {
6588 // Apply the protocol qualifers.
6589 bool hasError;
6590 Canonical = getCanonicalType(T: applyObjCProtocolQualifiers(
6591 type: Canonical, protocols, hasError, allowOnPointerType: true /*allowOnPointerType*/));
6592 assert(!hasError && "Error when apply protocol qualifier to bound type");
6593 }
6594
6595 // Key on the canonical type the node is constructed with, which is what
6596 // Profile() reports; the decl's underlying type can be updated later.
6597 auto Key = std::make_tuple(args&: Decl, args&: Canonical, args&: protocols);
6598 llvm::FoldingSetInsertToken Token;
6599 if (ObjCTypeParamType *TypeParam = ObjCTypeParamTypes.lookup(Key, Token))
6600 return QualType(TypeParam, 0);
6601
6602 unsigned size = sizeof(ObjCTypeParamType);
6603 size += protocols.size() * sizeof(ObjCProtocolDecl *);
6604 void *mem = Allocate(Size: size, Align: alignof(ObjCTypeParamType));
6605 auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols);
6606
6607 Types.push_back(Elt: newType);
6608 ObjCTypeParamTypes.insert(N: newType, Token);
6609 return QualType(newType, 0);
6610}
6611
6612void ASTContext::adjustObjCTypeParamBoundType(const ObjCTypeParamDecl *Orig,
6613 ObjCTypeParamDecl *New) const {
6614 New->setTypeSourceInfo(getTrivialTypeSourceInfo(T: Orig->getUnderlyingType()));
6615 // Update TypeForDecl after updating TypeSourceInfo.
6616 auto *NewTypeParamTy = cast<ObjCTypeParamType>(Val: New->TypeForDecl);
6617 SmallVector<ObjCProtocolDecl *, 8> protocols;
6618 protocols.append(in_start: NewTypeParamTy->qual_begin(), in_end: NewTypeParamTy->qual_end());
6619 QualType UpdatedTy = getObjCTypeParamType(Decl: New, protocols);
6620 New->TypeForDecl = UpdatedTy.getTypePtr();
6621}
6622
6623/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
6624/// protocol list adopt all protocols in QT's qualified-id protocol
6625/// list.
6626bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
6627 ObjCInterfaceDecl *IC) {
6628 if (!QT->isObjCQualifiedIdType())
6629 return false;
6630
6631 if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) {
6632 // If both the right and left sides have qualifiers.
6633 for (auto *Proto : OPT->quals()) {
6634 if (!IC->ClassImplementsProtocol(lProto: Proto, lookupCategory: false))
6635 return false;
6636 }
6637 return true;
6638 }
6639 return false;
6640}
6641
6642/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
6643/// QT's qualified-id protocol list adopt all protocols in IDecl's list
6644/// of protocols.
6645bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
6646 ObjCInterfaceDecl *IDecl) {
6647 if (!QT->isObjCQualifiedIdType())
6648 return false;
6649 const auto *OPT = QT->getAs<ObjCObjectPointerType>();
6650 if (!OPT)
6651 return false;
6652 if (!IDecl->hasDefinition())
6653 return false;
6654 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
6655 CollectInheritedProtocols(CDecl: IDecl, Protocols&: InheritedProtocols);
6656 if (InheritedProtocols.empty())
6657 return false;
6658 // Check that if every protocol in list of id<plist> conforms to a protocol
6659 // of IDecl's, then bridge casting is ok.
6660 bool Conforms = false;
6661 for (auto *Proto : OPT->quals()) {
6662 Conforms = false;
6663 for (auto *PI : InheritedProtocols) {
6664 if (ProtocolCompatibleWithProtocol(lProto: Proto, rProto: PI)) {
6665 Conforms = true;
6666 break;
6667 }
6668 }
6669 if (!Conforms)
6670 break;
6671 }
6672 if (Conforms)
6673 return true;
6674
6675 for (auto *PI : InheritedProtocols) {
6676 // If both the right and left sides have qualifiers.
6677 bool Adopts = false;
6678 for (auto *Proto : OPT->quals()) {
6679 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
6680 if ((Adopts = ProtocolCompatibleWithProtocol(lProto: PI, rProto: Proto)))
6681 break;
6682 }
6683 if (!Adopts)
6684 return false;
6685 }
6686 return true;
6687}
6688
6689/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
6690/// the given object type.
6691QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
6692 llvm::FoldingSetInsertToken Token;
6693 if (ObjCObjectPointerType *QT = ObjCObjectPointerTypes.lookup(Key: ObjectT, Token))
6694 return QualType(QT, 0);
6695
6696 // Find the canonical object type.
6697 QualType Canonical;
6698 if (!ObjectT.isCanonical())
6699 Canonical = getObjCObjectPointerType(ObjectT: getCanonicalType(T: ObjectT));
6700
6701 // No match.
6702 void *Mem =
6703 Allocate(Size: sizeof(ObjCObjectPointerType), Align: alignof(ObjCObjectPointerType));
6704 auto *QType =
6705 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
6706
6707 Types.push_back(Elt: QType);
6708 ObjCObjectPointerTypes.insert(N: QType, Token);
6709 return QualType(QType, 0);
6710}
6711
6712/// getObjCInterfaceType - Return the unique reference to the type for the
6713/// specified ObjC interface decl. The list of protocols is optional.
6714QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
6715 ObjCInterfaceDecl *PrevDecl) const {
6716 if (Decl->TypeForDecl)
6717 return QualType(Decl->TypeForDecl, 0);
6718
6719 if (PrevDecl) {
6720 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
6721 Decl->TypeForDecl = PrevDecl->TypeForDecl;
6722 return QualType(PrevDecl->TypeForDecl, 0);
6723 }
6724
6725 // Prefer the definition, if there is one.
6726 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
6727 Decl = Def;
6728
6729 void *Mem = Allocate(Size: sizeof(ObjCInterfaceType), Align: alignof(ObjCInterfaceType));
6730 auto *T = new (Mem) ObjCInterfaceType(Decl);
6731 Decl->TypeForDecl = T;
6732 Types.push_back(Elt: T);
6733 return QualType(T, 0);
6734}
6735
6736/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
6737/// TypeOfExprType AST's (since expression's are never shared). For example,
6738/// multiple declarations that refer to "typeof(x)" all contain different
6739/// DeclRefExpr's. This doesn't effect the type checker, since it operates
6740/// on canonical type's (which are always unique).
6741QualType ASTContext::getTypeOfExprType(Expr *tofExpr, TypeOfKind Kind) const {
6742 TypeOfExprType *toe;
6743 if (tofExpr->isTypeDependent()) {
6744 llvm::FoldingSetNodeID ID;
6745 DependentTypeOfExprType::Profile(ID, Context: *this, E: tofExpr,
6746 IsUnqual: Kind == TypeOfKind::Unqualified);
6747
6748 llvm::FoldingSetInsertToken Token;
6749 DependentTypeOfExprType *Canon = DependentTypeOfExprTypes.lookup(ID, Token);
6750 if (Canon) {
6751 // We already have a "canonical" version of an identical, dependent
6752 // typeof(expr) type. Use that as our canonical type.
6753 toe = new (*this, alignof(TypeOfExprType)) TypeOfExprType(
6754 *this, tofExpr, Kind, QualType((TypeOfExprType *)Canon, 0));
6755 } else {
6756 // Build a new, canonical typeof(expr) type.
6757 Canon = new (*this, alignof(DependentTypeOfExprType))
6758 DependentTypeOfExprType(*this, tofExpr, Kind);
6759 DependentTypeOfExprTypes.insert(N: Canon, Token);
6760 toe = Canon;
6761 }
6762 } else {
6763 QualType Canonical = getCanonicalType(T: tofExpr->getType());
6764 toe = new (*this, alignof(TypeOfExprType))
6765 TypeOfExprType(*this, tofExpr, Kind, Canonical);
6766 }
6767 Types.push_back(Elt: toe);
6768 return QualType(toe, 0);
6769}
6770
6771/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
6772/// TypeOfType nodes. The only motivation to unique these nodes would be
6773/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
6774/// an issue. This doesn't affect the type checker, since it operates
6775/// on canonical types (which are always unique).
6776QualType ASTContext::getTypeOfType(QualType tofType, TypeOfKind Kind) const {
6777 QualType Canonical = getCanonicalType(T: tofType);
6778 auto *tot = new (*this, alignof(TypeOfType))
6779 TypeOfType(*this, tofType, Canonical, Kind);
6780 Types.push_back(Elt: tot);
6781 return QualType(tot, 0);
6782}
6783
6784/// getReferenceQualifiedType - Given an expr, will return the type for
6785/// that expression, as in [dcl.type.simple]p4 but without taking id-expressions
6786/// and class member access into account.
6787QualType ASTContext::getReferenceQualifiedType(const Expr *E) const {
6788 // C++11 [dcl.type.simple]p4:
6789 // [...]
6790 QualType T = E->getType();
6791 switch (E->getValueKind()) {
6792 // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the
6793 // type of e;
6794 case VK_XValue:
6795 return getRValueReferenceType(T);
6796 // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the
6797 // type of e;
6798 case VK_LValue:
6799 return getLValueReferenceType(T);
6800 // - otherwise, decltype(e) is the type of e.
6801 case VK_PRValue:
6802 return T;
6803 }
6804 llvm_unreachable("Unknown value kind");
6805}
6806
6807/// Unlike many "get<Type>" functions, we don't unique DecltypeType
6808/// nodes. This would never be helpful, since each such type has its own
6809/// expression, and would not give a significant memory saving, since there
6810/// is an Expr tree under each such type.
6811QualType ASTContext::getDecltypeType(Expr *E, QualType UnderlyingType) const {
6812 // C++11 [temp.type]p2:
6813 // If an expression e involves a template parameter, decltype(e) denotes a
6814 // unique dependent type. Two such decltype-specifiers refer to the same
6815 // type only if their expressions are equivalent (14.5.6.1).
6816 QualType CanonType;
6817 if (!E->isInstantiationDependent()) {
6818 CanonType = getCanonicalType(T: UnderlyingType);
6819 } else if (!UnderlyingType.isNull()) {
6820 CanonType = getDecltypeType(E, UnderlyingType: QualType());
6821 } else {
6822 llvm::FoldingSetNodeID ID;
6823 DependentDecltypeType::Profile(ID, Context: *this, E);
6824
6825 llvm::FoldingSetInsertToken Token;
6826 if (DependentDecltypeType *Canon = DependentDecltypeTypes.lookup(ID, Token))
6827 return QualType(Canon, 0);
6828
6829 // Build a new, canonical decltype(expr) type.
6830 auto *DT =
6831 new (*this, alignof(DependentDecltypeType)) DependentDecltypeType(E);
6832 DependentDecltypeTypes.insert(N: DT, Token);
6833 Types.push_back(Elt: DT);
6834 return QualType(DT, 0);
6835 }
6836 auto *DT = new (*this, alignof(DecltypeType))
6837 DecltypeType(E, UnderlyingType, CanonType);
6838 Types.push_back(Elt: DT);
6839 return QualType(DT, 0);
6840}
6841
6842QualType ASTContext::getPackIndexingType(QualType Pattern, Expr *IndexExpr,
6843 bool FullySubstituted,
6844 ArrayRef<QualType> Expansions,
6845 UnsignedOrNone Index) const {
6846 QualType Canonical;
6847 if (FullySubstituted && Index) {
6848 Canonical = getCanonicalType(T: Expansions[*Index]);
6849 } else {
6850 llvm::FoldingSetNodeID ID;
6851 PackIndexingType::Profile(ID, Context: *this, Pattern: Pattern.getCanonicalType(), E: IndexExpr,
6852 FullySubstituted, Expansions);
6853 llvm::FoldingSetInsertToken Token;
6854 PackIndexingType *Canon = DependentPackIndexingTypes.lookup(ID, Token);
6855 if (!Canon) {
6856 void *Mem = Allocate(
6857 Size: PackIndexingType::totalSizeToAlloc<QualType>(Counts: Expansions.size()),
6858 Align: TypeAlignment);
6859 Canon =
6860 new (Mem) PackIndexingType(QualType(), Pattern.getCanonicalType(),
6861 IndexExpr, FullySubstituted, Expansions);
6862 DependentPackIndexingTypes.insert(N: Canon, Token);
6863 }
6864 Canonical = QualType(Canon, 0);
6865 }
6866
6867 void *Mem =
6868 Allocate(Size: PackIndexingType::totalSizeToAlloc<QualType>(Counts: Expansions.size()),
6869 Align: TypeAlignment);
6870 auto *T = new (Mem) PackIndexingType(Canonical, Pattern, IndexExpr,
6871 FullySubstituted, Expansions);
6872 Types.push_back(Elt: T);
6873 return QualType(T, 0);
6874}
6875
6876/// getUnaryTransformationType - We don't unique these, since the memory
6877/// savings are minimal and these are rare.
6878QualType
6879ASTContext::getUnaryTransformType(QualType BaseType, QualType UnderlyingType,
6880 UnaryTransformType::UTTKind Kind) const {
6881 // Clear UnderlyingType for a dependent base before building the ID: that is
6882 // what the node is constructed with, and what Profile() reports.
6883 if (BaseType->isDependentType()) {
6884 assert(UnderlyingType.isNull() || BaseType == UnderlyingType);
6885 UnderlyingType = QualType();
6886 }
6887
6888 auto Key = std::make_tuple(args&: BaseType, args&: UnderlyingType, args&: Kind);
6889
6890 llvm::FoldingSetInsertToken Token;
6891 if (UnaryTransformType *UT = UnaryTransformTypes.lookup(Key, Token))
6892 return QualType(UT, 0);
6893
6894 QualType CanonType;
6895 if (!BaseType->isDependentType()) {
6896 CanonType = UnderlyingType.getCanonicalType();
6897 } else {
6898 if (QualType CanonBase = BaseType.getCanonicalType();
6899 BaseType != CanonBase) {
6900 CanonType = getUnaryTransformType(BaseType: CanonBase, UnderlyingType: QualType(), Kind);
6901 assert(CanonType.isCanonical());
6902 }
6903 }
6904
6905 auto *UT = new (*this, alignof(UnaryTransformType))
6906 UnaryTransformType(BaseType, UnderlyingType, Kind, CanonType);
6907 UnaryTransformTypes.insert(N: UT, Token);
6908 Types.push_back(Elt: UT);
6909 return QualType(UT, 0);
6910}
6911
6912/// getAutoType - Return the uniqued reference to the 'auto' type which has been
6913/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
6914/// canonical deduced-but-dependent 'auto' type.
6915QualType
6916ASTContext::getAutoType(DeducedKind DK, QualType DeducedAsType,
6917 AutoTypeKeyword Keyword,
6918 TemplateName TypeConstraintConcept,
6919 ArrayRef<TemplateArgument> TypeConstraintArgs) const {
6920 if (DK == DeducedKind::Undeduced && Keyword == AutoTypeKeyword::Auto &&
6921 TypeConstraintConcept.isNull()) {
6922 assert(DeducedAsType.isNull() && "");
6923 assert(TypeConstraintArgs.empty() && "");
6924 return getAutoDeductType();
6925 }
6926
6927 // Look in the folding set for an existing type.
6928 llvm::FoldingSetNodeID ID;
6929 AutoType::Profile(ID, Context: *this, DK, Deduced: DeducedAsType, Keyword,
6930 CD: TypeConstraintConcept, Arguments: TypeConstraintArgs);
6931 if (auto const AT_iter = AutoTypes.find_as(Val: ID); AT_iter != AutoTypes.end())
6932 return QualType(AT_iter->getSecond(), 0);
6933
6934 if (DK == DeducedKind::Deduced) {
6935 assert(!DeducedAsType.isNull() && "deduced type must be provided");
6936 } else {
6937 assert(DeducedAsType.isNull() && "deduced type must not be provided");
6938 if (!TypeConstraintConcept.isNull()) {
6939 bool AnyNonCanonArgs = false;
6940 TemplateName CanonicalConcept =
6941 getCanonicalTemplateName(Name: TypeConstraintConcept);
6942 auto CanonicalConceptArgs = ::getCanonicalTemplateArguments(
6943 C: *this, Args: TypeConstraintArgs, AnyNonCanonArgs);
6944 if (TypeConstraintConcept != CanonicalConcept || AnyNonCanonArgs)
6945 DeducedAsType = getAutoType(DK, DeducedAsType: QualType(), Keyword, TypeConstraintConcept: CanonicalConcept,
6946 TypeConstraintArgs: CanonicalConceptArgs);
6947 }
6948 }
6949
6950 void *Mem = Allocate(Size: sizeof(AutoType) +
6951 sizeof(TemplateArgument) * TypeConstraintArgs.size(),
6952 Align: alignof(AutoType));
6953 auto *AT = new (Mem) AutoType(DK, DeducedAsType, Keyword,
6954 TypeConstraintConcept, TypeConstraintArgs);
6955#ifndef NDEBUG
6956 llvm::FoldingSetNodeID InsertedID;
6957 AT->Profile(InsertedID, *this);
6958 assert(InsertedID == ID && "ID does not match");
6959#endif
6960 Types.push_back(Elt: AT);
6961 AutoTypes.try_emplace(Key: ID.Intern(Allocator&: BumpAlloc), Args&: AT);
6962 return QualType(AT, 0);
6963}
6964
6965QualType ASTContext::getUnconstrainedType(QualType T) const {
6966 QualType CanonT = T.getNonPackExpansionType().getCanonicalType();
6967
6968 // Remove a type-constraint from a top-level auto or decltype(auto).
6969 if (auto *AT = CanonT->getAs<AutoType>()) {
6970 if (!AT->isConstrained())
6971 return T;
6972 return getQualifiedType(
6973 T: getAutoType(DK: AT->getDeducedKind(), DeducedAsType: QualType(), Keyword: AT->getKeyword()),
6974 Qs: T.getQualifiers());
6975 }
6976
6977 // FIXME: We only support constrained auto at the top level in the type of a
6978 // non-type template parameter at the moment. Once we lift that restriction,
6979 // we'll need to recursively build types containing auto here.
6980 assert(!CanonT->getContainedAutoType() ||
6981 !CanonT->getContainedAutoType()->isConstrained());
6982 return T;
6983}
6984
6985/// Return the uniqued reference to the deduced template specialization type
6986/// which has been deduced to the given type, or to the canonical undeduced
6987/// such type, or the canonical deduced-but-dependent such type.
6988QualType ASTContext::getDeducedTemplateSpecializationType(
6989 DeducedKind DK, QualType DeducedAsType, ElaboratedTypeKeyword Keyword,
6990 TemplateName Template) const {
6991 // Look in the folding set for an existing type.
6992 llvm::FoldingSetInsertToken Token;
6993 llvm::FoldingSetNodeID ID;
6994 DeducedTemplateSpecializationType::Profile(ID, DK, Deduced: DeducedAsType, Keyword,
6995 Template);
6996 if (DeducedTemplateSpecializationType *DTST =
6997 DeducedTemplateSpecializationTypes.lookup(ID, Token))
6998 return QualType(DTST, 0);
6999
7000 if (DK == DeducedKind::Deduced) {
7001 assert(!DeducedAsType.isNull() && "deduced type must be provided");
7002 } else {
7003 assert(DeducedAsType.isNull() && "deduced type must not be provided");
7004 TemplateName CanonTemplateName = getCanonicalTemplateName(Name: Template);
7005 // FIXME: Can this be formed from a DependentTemplateName, such that the
7006 // keyword should be part of the canonical type?
7007 if (Keyword != ElaboratedTypeKeyword::None ||
7008 Template != CanonTemplateName) {
7009 DeducedAsType = getDeducedTemplateSpecializationType(
7010 DK, DeducedAsType: QualType(), Keyword: ElaboratedTypeKeyword::None, Template: CanonTemplateName);
7011 // Find the insertion position again.
7012 [[maybe_unused]] DeducedTemplateSpecializationType *DTST =
7013 DeducedTemplateSpecializationTypes.lookup(ID, Token);
7014 assert(!DTST && "broken canonicalization");
7015 }
7016 }
7017
7018 auto *DTST = new (*this, alignof(DeducedTemplateSpecializationType))
7019 DeducedTemplateSpecializationType(DK, DeducedAsType, Keyword, Template);
7020
7021#ifndef NDEBUG
7022 llvm::FoldingSetNodeID TempID;
7023 DTST->Profile(TempID);
7024 assert(ID == TempID && "ID does not match");
7025#endif
7026 Types.push_back(Elt: DTST);
7027 DeducedTemplateSpecializationTypes.insert(N: DTST, Token);
7028 return QualType(DTST, 0);
7029}
7030
7031/// getAtomicType - Return the uniqued reference to the atomic type for
7032/// the given value type.
7033QualType ASTContext::getAtomicType(QualType T) const {
7034 // Unique pointers, to guarantee there is only one pointer of a particular
7035 // structure.
7036 llvm::FoldingSetInsertToken Token;
7037 if (AtomicType *AT = AtomicTypes.lookup(Key: T, Token))
7038 return QualType(AT, 0);
7039
7040 // If the atomic value type isn't canonical, this won't be a canonical type
7041 // either, so fill in the canonical type field.
7042 QualType Canonical;
7043 if (!T.isCanonical()) {
7044 Canonical = getAtomicType(T: getCanonicalType(T));
7045
7046 assert(!AtomicTypes.lookup(T, Token) && "Shouldn't be in the map!");
7047 }
7048 auto *New = new (*this, alignof(AtomicType)) AtomicType(T, Canonical);
7049 Types.push_back(Elt: New);
7050 AtomicTypes.insert(N: New, Token);
7051 return QualType(New, 0);
7052}
7053
7054/// getAutoDeductType - Get type pattern for deducing against 'auto'.
7055QualType ASTContext::getAutoDeductType() const {
7056 if (AutoDeductTy.isNull())
7057 AutoDeductTy = QualType(
7058 new (*this, alignof(AutoType))
7059 AutoType(DeducedKind::Undeduced, QualType(), AutoTypeKeyword::Auto,
7060 /*TypeConstraintConcept=*/TemplateName(),
7061 /*TypeConstraintArgs=*/{}),
7062 0);
7063 return AutoDeductTy;
7064}
7065
7066/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
7067QualType ASTContext::getAutoRRefDeductType() const {
7068 if (AutoRRefDeductTy.isNull())
7069 AutoRRefDeductTy = getRValueReferenceType(T: getAutoDeductType());
7070 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
7071 return AutoRRefDeductTy;
7072}
7073
7074/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
7075/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
7076/// needs to agree with the definition in <stddef.h>.
7077QualType ASTContext::getSizeType() const {
7078 return getPredefinedSugarType(KD: PredefinedSugarType::Kind::SizeT);
7079}
7080
7081CanQualType ASTContext::getCanonicalSizeType() const {
7082 return getFromTargetType(Type: Target->getSizeType());
7083}
7084
7085/// Return the unique signed counterpart of the integer type
7086/// corresponding to size_t.
7087QualType ASTContext::getSignedSizeType() const {
7088 return getPredefinedSugarType(KD: PredefinedSugarType::Kind::SignedSizeT);
7089}
7090
7091/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
7092/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
7093QualType ASTContext::getPointerDiffType() const {
7094 return getPredefinedSugarType(KD: PredefinedSugarType::Kind::PtrdiffT);
7095}
7096
7097/// Return the unique unsigned counterpart of "ptrdiff_t"
7098/// integer type. The standard (C11 7.21.6.1p7) refers to this type
7099/// in the definition of %tu format specifier.
7100QualType ASTContext::getUnsignedPointerDiffType() const {
7101 return getFromTargetType(Type: Target->getUnsignedPtrDiffType(AddrSpace: LangAS::Default));
7102}
7103
7104/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
7105CanQualType ASTContext::getIntMaxType() const {
7106 return getFromTargetType(Type: Target->getIntMaxType());
7107}
7108
7109/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
7110CanQualType ASTContext::getUIntMaxType() const {
7111 return getFromTargetType(Type: Target->getUIntMaxType());
7112}
7113
7114/// getSignedWCharType - Return the type of "signed wchar_t".
7115/// Used when in C++, as a GCC extension.
7116QualType ASTContext::getSignedWCharType() const {
7117 // FIXME: derive from "Target" ?
7118 return WCharTy;
7119}
7120
7121/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
7122/// Used when in C++, as a GCC extension.
7123QualType ASTContext::getUnsignedWCharType() const {
7124 // FIXME: derive from "Target" ?
7125 return UnsignedIntTy;
7126}
7127
7128QualType ASTContext::getIntPtrType() const {
7129 return getFromTargetType(Type: Target->getIntPtrType());
7130}
7131
7132QualType ASTContext::getUIntPtrType() const {
7133 return getCorrespondingUnsignedType(T: getIntPtrType());
7134}
7135
7136/// Return the unique type for "pid_t" defined in
7137/// <sys/types.h>. We need this to compute the correct type for vfork().
7138QualType ASTContext::getProcessIDType() const {
7139 return getFromTargetType(Type: Target->getProcessIDType());
7140}
7141
7142//===----------------------------------------------------------------------===//
7143// Type Operators
7144//===----------------------------------------------------------------------===//
7145
7146CanQualType ASTContext::getCanonicalParamType(QualType T) const {
7147 // Push qualifiers into arrays, and then discard any remaining
7148 // qualifiers.
7149 T = getCanonicalType(T);
7150 T = getVariableArrayDecayedType(type: T);
7151 const Type *Ty = T.getTypePtr();
7152 QualType Result;
7153 if (getLangOpts().HLSL && isa<ConstantArrayType>(Val: Ty)) {
7154 Result = getArrayParameterType(Ty: QualType(Ty, 0));
7155 } else if (isa<ArrayType>(Val: Ty)) {
7156 Result = getArrayDecayedType(T: QualType(Ty,0));
7157 } else if (isa<FunctionType>(Val: Ty)) {
7158 Result = getPointerType(T: QualType(Ty, 0));
7159 } else {
7160 Result = QualType(Ty, 0);
7161 }
7162
7163 return CanQualType::CreateUnsafe(Other: Result);
7164}
7165
7166QualType ASTContext::getUnqualifiedArrayType(QualType type,
7167 Qualifiers &quals) const {
7168 SplitQualType splitType = type.getSplitUnqualifiedType();
7169
7170 // FIXME: getSplitUnqualifiedType() actually walks all the way to
7171 // the unqualified desugared type and then drops it on the floor.
7172 // We then have to strip that sugar back off with
7173 // getUnqualifiedDesugaredType(), which is silly.
7174 const auto *AT =
7175 dyn_cast<ArrayType>(Val: splitType.Ty->getUnqualifiedDesugaredType());
7176
7177 // If we don't have an array, just use the results in splitType.
7178 if (!AT) {
7179 quals = splitType.Quals;
7180 return QualType(splitType.Ty, 0);
7181 }
7182
7183 // Otherwise, recurse on the array's element type.
7184 QualType elementType = AT->getElementType();
7185 QualType unqualElementType = getUnqualifiedArrayType(type: elementType, quals);
7186
7187 // If that didn't change the element type, AT has no qualifiers, so we
7188 // can just use the results in splitType.
7189 if (elementType == unqualElementType) {
7190 assert(quals.empty()); // from the recursive call
7191 quals = splitType.Quals;
7192 return QualType(splitType.Ty, 0);
7193 }
7194
7195 // Otherwise, add in the qualifiers from the outermost type, then
7196 // build the type back up.
7197 quals.addConsistentQualifiers(qs: splitType.Quals);
7198
7199 if (const auto *CAT = dyn_cast<ConstantArrayType>(Val: AT)) {
7200 return getConstantArrayType(EltTy: unqualElementType, ArySizeIn: CAT->getSize(),
7201 SizeExpr: CAT->getSizeExpr(), ASM: CAT->getSizeModifier(), IndexTypeQuals: 0);
7202 }
7203
7204 if (const auto *IAT = dyn_cast<IncompleteArrayType>(Val: AT)) {
7205 return getIncompleteArrayType(elementType: unqualElementType, ASM: IAT->getSizeModifier(), elementTypeQuals: 0);
7206 }
7207
7208 if (const auto *VAT = dyn_cast<VariableArrayType>(Val: AT)) {
7209 return getVariableArrayType(EltTy: unqualElementType, NumElts: VAT->getSizeExpr(),
7210 ASM: VAT->getSizeModifier(),
7211 IndexTypeQuals: VAT->getIndexTypeCVRQualifiers());
7212 }
7213
7214 const auto *DSAT = cast<DependentSizedArrayType>(Val: AT);
7215 return getDependentSizedArrayType(elementType: unqualElementType, numElements: DSAT->getSizeExpr(),
7216 ASM: DSAT->getSizeModifier(), elementTypeQuals: 0);
7217}
7218
7219/// Attempt to unwrap two types that may both be array types with the same bound
7220/// (or both be array types of unknown bound) for the purpose of comparing the
7221/// cv-decomposition of two types per C++ [conv.qual].
7222///
7223/// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
7224/// C++20 [conv.qual], if permitted by the current language mode.
7225void ASTContext::UnwrapSimilarArrayTypes(QualType &T1, QualType &T2,
7226 bool AllowPiMismatch) const {
7227 while (true) {
7228 auto *AT1 = getAsArrayType(T: T1);
7229 if (!AT1)
7230 return;
7231
7232 auto *AT2 = getAsArrayType(T: T2);
7233 if (!AT2)
7234 return;
7235
7236 // If we don't have two array types with the same constant bound nor two
7237 // incomplete array types, we've unwrapped everything we can.
7238 // C++20 also permits one type to be a constant array type and the other
7239 // to be an incomplete array type.
7240 // FIXME: Consider also unwrapping array of unknown bound and VLA.
7241 if (auto *CAT1 = dyn_cast<ConstantArrayType>(Val: AT1)) {
7242 auto *CAT2 = dyn_cast<ConstantArrayType>(Val: AT2);
7243 if (!((CAT2 && CAT1->getSize() == CAT2->getSize()) ||
7244 (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
7245 isa<IncompleteArrayType>(Val: AT2))))
7246 return;
7247 } else if (isa<IncompleteArrayType>(Val: AT1)) {
7248 if (!(isa<IncompleteArrayType>(Val: AT2) ||
7249 (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
7250 isa<ConstantArrayType>(Val: AT2))))
7251 return;
7252 } else {
7253 return;
7254 }
7255
7256 T1 = AT1->getElementType();
7257 T2 = AT2->getElementType();
7258 }
7259}
7260
7261/// Attempt to unwrap two types that may be similar (C++ [conv.qual]).
7262///
7263/// If T1 and T2 are both pointer types of the same kind, or both array types
7264/// with the same bound, unwraps layers from T1 and T2 until a pointer type is
7265/// unwrapped. Top-level qualifiers on T1 and T2 are ignored.
7266///
7267/// This function will typically be called in a loop that successively
7268/// "unwraps" pointer and pointer-to-member types to compare them at each
7269/// level.
7270///
7271/// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
7272/// C++20 [conv.qual], if permitted by the current language mode.
7273///
7274/// \return \c true if a pointer type was unwrapped, \c false if we reached a
7275/// pair of types that can't be unwrapped further.
7276bool ASTContext::UnwrapSimilarTypes(QualType &T1, QualType &T2,
7277 bool AllowPiMismatch) const {
7278 UnwrapSimilarArrayTypes(T1, T2, AllowPiMismatch);
7279
7280 const auto *T1PtrType = T1->getAs<PointerType>();
7281 const auto *T2PtrType = T2->getAs<PointerType>();
7282 if (T1PtrType && T2PtrType) {
7283 T1 = T1PtrType->getPointeeType();
7284 T2 = T2PtrType->getPointeeType();
7285 return true;
7286 }
7287
7288 if (const auto *T1MPType = T1->getAsCanonical<MemberPointerType>(),
7289 *T2MPType = T2->getAsCanonical<MemberPointerType>();
7290 T1MPType && T2MPType) {
7291 // Compare the qualifiers of the canonical type, as the non-canonical type
7292 // may have qualifiers pointing to a base or derived class.
7293 if (T1MPType->getQualifier() != T2MPType->getQualifier())
7294 return false;
7295 // Get the pointee types of the non-canonical type, in order to preserve
7296 // their sugar.
7297 T1 = T1->getAs<MemberPointerType>()->getPointeeType();
7298 T2 = T2->getAs<MemberPointerType>()->getPointeeType();
7299 return true;
7300 }
7301
7302 if (getLangOpts().ObjC) {
7303 const auto *T1OPType = T1->getAs<ObjCObjectPointerType>();
7304 const auto *T2OPType = T2->getAs<ObjCObjectPointerType>();
7305 if (T1OPType && T2OPType) {
7306 T1 = T1OPType->getPointeeType();
7307 T2 = T2OPType->getPointeeType();
7308 return true;
7309 }
7310 }
7311
7312 // FIXME: Block pointers, too?
7313
7314 return false;
7315}
7316
7317bool ASTContext::hasSimilarType(QualType T1, QualType T2) const {
7318 while (true) {
7319 Qualifiers Quals;
7320 T1 = getUnqualifiedArrayType(type: T1, quals&: Quals);
7321 T2 = getUnqualifiedArrayType(type: T2, quals&: Quals);
7322 if (hasSameType(T1, T2))
7323 return true;
7324 if (!UnwrapSimilarTypes(T1, T2))
7325 return false;
7326 }
7327}
7328
7329bool ASTContext::hasCvrSimilarType(QualType T1, QualType T2) {
7330 while (true) {
7331 Qualifiers Quals1, Quals2;
7332 T1 = getUnqualifiedArrayType(type: T1, quals&: Quals1);
7333 T2 = getUnqualifiedArrayType(type: T2, quals&: Quals2);
7334
7335 Quals1.removeCVRQualifiers();
7336 Quals2.removeCVRQualifiers();
7337 if (Quals1 != Quals2)
7338 return false;
7339
7340 if (hasSameType(T1, T2))
7341 return true;
7342
7343 if (!UnwrapSimilarTypes(T1, T2, /*AllowPiMismatch*/ false))
7344 return false;
7345 }
7346}
7347
7348DeclarationNameInfo
7349ASTContext::getNameForTemplate(TemplateName Name,
7350 SourceLocation NameLoc) const {
7351 switch (Name.getKind()) {
7352 case TemplateName::QualifiedTemplate:
7353 case TemplateName::Template:
7354 // DNInfo work in progress: CHECKME: what about DNLoc?
7355 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
7356 NameLoc);
7357
7358 case TemplateName::OverloadedTemplate: {
7359 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
7360 // DNInfo work in progress: CHECKME: what about DNLoc?
7361 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
7362 }
7363
7364 case TemplateName::AssumedTemplate: {
7365 AssumedTemplateStorage *Storage = Name.getAsAssumedTemplateName();
7366 return DeclarationNameInfo(Storage->getDeclName(), NameLoc);
7367 }
7368
7369 case TemplateName::DependentTemplate: {
7370 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
7371 IdentifierOrOverloadedOperator TN = DTN->getName();
7372 DeclarationName DName;
7373 if (const IdentifierInfo *II = TN.getIdentifier()) {
7374 DName = DeclarationNames.getIdentifier(ID: II);
7375 return DeclarationNameInfo(DName, NameLoc);
7376 } else {
7377 DName = DeclarationNames.getCXXOperatorName(Op: TN.getOperator());
7378 // DNInfo work in progress: FIXME: source locations?
7379 DeclarationNameLoc DNLoc =
7380 DeclarationNameLoc::makeCXXOperatorNameLoc(Range: SourceRange());
7381 return DeclarationNameInfo(DName, NameLoc, DNLoc);
7382 }
7383 }
7384
7385 case TemplateName::SubstTemplateTemplateParm: {
7386 SubstTemplateTemplateParmStorage *subst
7387 = Name.getAsSubstTemplateTemplateParm();
7388 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
7389 NameLoc);
7390 }
7391
7392 case TemplateName::SubstTemplateTemplateParmPack: {
7393 SubstTemplateTemplateParmPackStorage *subst
7394 = Name.getAsSubstTemplateTemplateParmPack();
7395 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
7396 NameLoc);
7397 }
7398 case TemplateName::UsingTemplate:
7399 return DeclarationNameInfo(Name.getAsUsingShadowDecl()->getDeclName(),
7400 NameLoc);
7401 case TemplateName::DeducedTemplate: {
7402 DeducedTemplateStorage *DTS = Name.getAsDeducedTemplateName();
7403 return getNameForTemplate(Name: DTS->getUnderlying(), NameLoc);
7404 }
7405 case TemplateName::PackIndexingTemplate: {
7406 PackIndexingTemplateStorage *PI = Name.getAsPackIndexingTemplate();
7407 return getNameForTemplate(Name: PI->getPattern(), NameLoc);
7408 }
7409 }
7410
7411 llvm_unreachable("bad template name kind!");
7412}
7413
7414const TemplateArgument *
7415ASTContext::getDefaultTemplateArgumentOrNone(const NamedDecl *P) const {
7416 auto handleParam = [](auto *TP) -> const TemplateArgument * {
7417 if (!TP->hasDefaultArgument())
7418 return nullptr;
7419 return &TP->getDefaultArgument().getArgument();
7420 };
7421 switch (P->getKind()) {
7422 case NamedDecl::TemplateTypeParm:
7423 return handleParam(cast<TemplateTypeParmDecl>(Val: P));
7424 case NamedDecl::NonTypeTemplateParm:
7425 return handleParam(cast<NonTypeTemplateParmDecl>(Val: P));
7426 case NamedDecl::TemplateTemplateParm:
7427 return handleParam(cast<TemplateTemplateParmDecl>(Val: P));
7428 default:
7429 llvm_unreachable("Unexpected template parameter kind");
7430 }
7431}
7432
7433TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name,
7434 bool IgnoreDeduced) const {
7435 while (std::optional<TemplateName> UnderlyingOrNone =
7436 Name.desugar(IgnoreDeduced))
7437 Name = *UnderlyingOrNone;
7438
7439 switch (Name.getKind()) {
7440 case TemplateName::Template: {
7441 TemplateDecl *Template = Name.getAsTemplateDecl();
7442 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Val: Template))
7443 Template = getCanonicalTemplateTemplateParmDecl(TTP);
7444
7445 // The canonical template name is the canonical template declaration.
7446 return TemplateName(cast<TemplateDecl>(Val: Template->getCanonicalDecl()));
7447 }
7448
7449 case TemplateName::AssumedTemplate:
7450 // An assumed template is just a name, so it is already canonical.
7451 return Name;
7452
7453 case TemplateName::OverloadedTemplate:
7454 llvm_unreachable("cannot canonicalize overloaded template");
7455
7456 case TemplateName::DependentTemplate: {
7457 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
7458 assert(DTN && "Non-dependent template names must refer to template decls.");
7459 NestedNameSpecifier Qualifier = DTN->getQualifier();
7460 NestedNameSpecifier CanonQualifier = Qualifier.getCanonical();
7461 if (Qualifier != CanonQualifier || !DTN->hasTemplateKeyword())
7462 return getDependentTemplateName(Name: {CanonQualifier, DTN->getName(),
7463 /*HasTemplateKeyword=*/true});
7464 return Name;
7465 }
7466
7467 case TemplateName::SubstTemplateTemplateParmPack: {
7468 SubstTemplateTemplateParmPackStorage *subst =
7469 Name.getAsSubstTemplateTemplateParmPack();
7470 TemplateArgument canonArgPack =
7471 getCanonicalTemplateArgument(Arg: subst->getArgumentPack());
7472 return getSubstTemplateTemplateParmPack(
7473 ArgPack: canonArgPack, AssociatedDecl: subst->getAssociatedDecl()->getCanonicalDecl(),
7474 Index: subst->getIndex(), Final: subst->getFinal());
7475 }
7476
7477 case TemplateName::PackIndexingTemplate: {
7478 PackIndexingTemplateStorage *PI = Name.getAsPackIndexingTemplate();
7479 SmallVector<TemplateName, 4> CanonExpansions;
7480 for (TemplateName T : PI->getExpansions())
7481 CanonExpansions.push_back(Elt: getCanonicalTemplateName(Name: T, IgnoreDeduced));
7482 return getPackIndexingTemplateName(
7483 Pattern: getCanonicalTemplateName(Name: PI->getPattern(), IgnoreDeduced),
7484 IndexExpr: PI->getIndexExpr(), FullySubstituted: PI->isFullySubstituted(), Expansions: CanonExpansions);
7485 }
7486 case TemplateName::DeducedTemplate: {
7487 assert(IgnoreDeduced == false);
7488 DeducedTemplateStorage *DTS = Name.getAsDeducedTemplateName();
7489 DefaultArguments DefArgs = DTS->getDefaultArguments();
7490 TemplateName Underlying = DTS->getUnderlying();
7491
7492 TemplateName CanonUnderlying =
7493 getCanonicalTemplateName(Name: Underlying, /*IgnoreDeduced=*/true);
7494 bool NonCanonical = CanonUnderlying != Underlying;
7495 auto CanonArgs =
7496 getCanonicalTemplateArguments(C: *this, Args: DefArgs.Args, AnyNonCanonArgs&: NonCanonical);
7497
7498 ArrayRef<NamedDecl *> Params =
7499 CanonUnderlying.getAsTemplateDecl()->getTemplateParameters()->asArray();
7500 assert(CanonArgs.size() <= Params.size());
7501 // A deduced template name which deduces the same default arguments already
7502 // declared in the underlying template is the same template as the
7503 // underlying template. We need need to note any arguments which differ from
7504 // the corresponding declaration. If any argument differs, we must build a
7505 // deduced template name.
7506 for (int I = CanonArgs.size() - 1; I >= 0; --I) {
7507 const TemplateArgument *A = getDefaultTemplateArgumentOrNone(P: Params[I]);
7508 if (!A)
7509 break;
7510 auto CanonParamDefArg = getCanonicalTemplateArgument(Arg: *A);
7511 TemplateArgument &CanonDefArg = CanonArgs[I];
7512 if (CanonDefArg.structurallyEquals(Other: CanonParamDefArg))
7513 continue;
7514 // Keep popping from the back any deault arguments which are the same.
7515 if (I == int(CanonArgs.size() - 1))
7516 CanonArgs.pop_back();
7517 NonCanonical = true;
7518 }
7519 return NonCanonical ? getDeducedTemplateName(
7520 Underlying: CanonUnderlying,
7521 /*DefaultArgs=*/{.StartPos: DefArgs.StartPos, .Args: CanonArgs})
7522 : Name;
7523 }
7524 case TemplateName::UsingTemplate:
7525 case TemplateName::QualifiedTemplate:
7526 case TemplateName::SubstTemplateTemplateParm:
7527 llvm_unreachable("always sugar node");
7528 }
7529
7530 llvm_unreachable("bad template name!");
7531}
7532
7533bool ASTContext::hasSameTemplateName(const TemplateName &X,
7534 const TemplateName &Y,
7535 bool IgnoreDeduced) const {
7536 return getCanonicalTemplateName(Name: X, IgnoreDeduced) ==
7537 getCanonicalTemplateName(Name: Y, IgnoreDeduced);
7538}
7539
7540bool ASTContext::isSameAssociatedConstraint(
7541 const AssociatedConstraint &ACX, const AssociatedConstraint &ACY) const {
7542 if (ACX.ArgPackSubstIndex != ACY.ArgPackSubstIndex)
7543 return false;
7544 if (!isSameConstraintExpr(XCE: ACX.ConstraintExpr, YCE: ACY.ConstraintExpr))
7545 return false;
7546 return true;
7547}
7548
7549bool ASTContext::isSameConstraintExpr(const Expr *XCE, const Expr *YCE) const {
7550 if (!XCE != !YCE)
7551 return false;
7552
7553 if (!XCE)
7554 return true;
7555
7556 llvm::FoldingSetNodeID XCEID, YCEID;
7557 XCE->Profile(ID&: XCEID, Context: *this, /*Canonical=*/true, /*ProfileLambdaExpr=*/true);
7558 YCE->Profile(ID&: YCEID, Context: *this, /*Canonical=*/true, /*ProfileLambdaExpr=*/true);
7559 return XCEID == YCEID;
7560}
7561
7562bool ASTContext::isSameTypeConstraint(const TypeConstraint *XTC,
7563 const TypeConstraint *YTC) const {
7564 if (!XTC != !YTC)
7565 return false;
7566
7567 if (!XTC)
7568 return true;
7569
7570 TemplateDecl *NCX = XTC->getNamedConcept().getAsTemplateDecl();
7571 TemplateDecl *NCY = YTC->getNamedConcept().getAsTemplateDecl();
7572 if (!NCX || !NCY || !isSameEntity(X: NCX, Y: NCY))
7573 return false;
7574 if (XTC->getConceptReference()->hasExplicitTemplateArgs() !=
7575 YTC->getConceptReference()->hasExplicitTemplateArgs())
7576 return false;
7577 if (XTC->getConceptReference()->hasExplicitTemplateArgs())
7578 if (XTC->getConceptReference()
7579 ->getTemplateArgsAsWritten()
7580 ->NumTemplateArgs !=
7581 YTC->getConceptReference()->getTemplateArgsAsWritten()->NumTemplateArgs)
7582 return false;
7583
7584 // Compare slowly by profiling.
7585 //
7586 // We couldn't compare the profiling result for the template
7587 // args here. Consider the following example in different modules:
7588 //
7589 // template <__integer_like _Tp, C<_Tp> Sentinel>
7590 // constexpr _Tp operator()(_Tp &&__t, Sentinel &&last) const {
7591 // return __t;
7592 // }
7593 //
7594 // When we compare the profiling result for `C<_Tp>` in different
7595 // modules, it will compare the type of `_Tp` in different modules.
7596 // However, the type of `_Tp` in different modules refer to different
7597 // types here naturally. So we couldn't compare the profiling result
7598 // for the template args directly.
7599 return isSameConstraintExpr(XCE: XTC->getImmediatelyDeclaredConstraint(),
7600 YCE: YTC->getImmediatelyDeclaredConstraint());
7601}
7602
7603bool ASTContext::isSameTemplateParameter(const NamedDecl *X,
7604 const NamedDecl *Y) const {
7605 if (X->getKind() != Y->getKind())
7606 return false;
7607
7608 if (auto *TX = dyn_cast<TemplateTypeParmDecl>(Val: X)) {
7609 auto *TY = cast<TemplateTypeParmDecl>(Val: Y);
7610 if (TX->isParameterPack() != TY->isParameterPack())
7611 return false;
7612 if (TX->hasTypeConstraint() != TY->hasTypeConstraint())
7613 return false;
7614 return isSameTypeConstraint(XTC: TX->getTypeConstraint(),
7615 YTC: TY->getTypeConstraint());
7616 }
7617
7618 if (auto *TX = dyn_cast<NonTypeTemplateParmDecl>(Val: X)) {
7619 auto *TY = cast<NonTypeTemplateParmDecl>(Val: Y);
7620 return TX->isParameterPack() == TY->isParameterPack() &&
7621 TX->getASTContext().hasSameType(T1: TX->getType(), T2: TY->getType()) &&
7622 isSameConstraintExpr(XCE: TX->getPlaceholderTypeConstraint(),
7623 YCE: TY->getPlaceholderTypeConstraint());
7624 }
7625
7626 auto *TX = cast<TemplateTemplateParmDecl>(Val: X);
7627 auto *TY = cast<TemplateTemplateParmDecl>(Val: Y);
7628 return TX->isParameterPack() == TY->isParameterPack() &&
7629 isSameTemplateParameterList(X: TX->getTemplateParameters(),
7630 Y: TY->getTemplateParameters());
7631}
7632
7633bool ASTContext::isSameTemplateParameterList(
7634 const TemplateParameterList *X, const TemplateParameterList *Y) const {
7635 if (X->size() != Y->size())
7636 return false;
7637
7638 for (unsigned I = 0, N = X->size(); I != N; ++I)
7639 if (!isSameTemplateParameter(X: X->getParam(Idx: I), Y: Y->getParam(Idx: I)))
7640 return false;
7641
7642 return isSameConstraintExpr(XCE: X->getRequiresClause(), YCE: Y->getRequiresClause());
7643}
7644
7645bool ASTContext::isSameDefaultTemplateArgument(const NamedDecl *X,
7646 const NamedDecl *Y) const {
7647 // If the type parameter isn't the same already, we don't need to check the
7648 // default argument further.
7649 if (!isSameTemplateParameter(X, Y))
7650 return false;
7651
7652 if (auto *TTPX = dyn_cast<TemplateTypeParmDecl>(Val: X)) {
7653 auto *TTPY = cast<TemplateTypeParmDecl>(Val: Y);
7654 if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument())
7655 return false;
7656
7657 return hasSameType(T1: TTPX->getDefaultArgument().getArgument().getAsType(),
7658 T2: TTPY->getDefaultArgument().getArgument().getAsType());
7659 }
7660
7661 if (auto *NTTPX = dyn_cast<NonTypeTemplateParmDecl>(Val: X)) {
7662 auto *NTTPY = cast<NonTypeTemplateParmDecl>(Val: Y);
7663 if (!NTTPX->hasDefaultArgument() || !NTTPY->hasDefaultArgument())
7664 return false;
7665
7666 Expr *DefaultArgumentX =
7667 NTTPX->getDefaultArgument().getArgument().getAsExpr()->IgnoreImpCasts();
7668 Expr *DefaultArgumentY =
7669 NTTPY->getDefaultArgument().getArgument().getAsExpr()->IgnoreImpCasts();
7670 llvm::FoldingSetNodeID XID, YID;
7671 DefaultArgumentX->Profile(ID&: XID, Context: *this, /*Canonical=*/true);
7672 DefaultArgumentY->Profile(ID&: YID, Context: *this, /*Canonical=*/true);
7673 return XID == YID;
7674 }
7675
7676 auto *TTPX = cast<TemplateTemplateParmDecl>(Val: X);
7677 auto *TTPY = cast<TemplateTemplateParmDecl>(Val: Y);
7678
7679 if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument())
7680 return false;
7681
7682 const TemplateArgument &TAX = TTPX->getDefaultArgument().getArgument();
7683 const TemplateArgument &TAY = TTPY->getDefaultArgument().getArgument();
7684 return hasSameTemplateName(X: TAX.getAsTemplate(), Y: TAY.getAsTemplate());
7685}
7686
7687static bool isSameQualifier(const NestedNameSpecifier X,
7688 const NestedNameSpecifier Y) {
7689 if (X == Y)
7690 return true;
7691 if (!X || !Y)
7692 return false;
7693
7694 auto Kind = X.getKind();
7695 if (Kind != Y.getKind())
7696 return false;
7697
7698 // FIXME: For namespaces and types, we're permitted to check that the entity
7699 // is named via the same tokens. We should probably do so.
7700 switch (Kind) {
7701 case NestedNameSpecifier::Kind::Namespace: {
7702 auto [NamespaceX, PrefixX] = X.getAsNamespaceAndPrefix();
7703 auto [NamespaceY, PrefixY] = Y.getAsNamespaceAndPrefix();
7704 if (!declaresSameEntity(D1: NamespaceX->getNamespace(),
7705 D2: NamespaceY->getNamespace()))
7706 return false;
7707 return isSameQualifier(X: PrefixX, Y: PrefixY);
7708 }
7709 case NestedNameSpecifier::Kind::Type: {
7710 const auto *TX = X.getAsType(), *TY = Y.getAsType();
7711 if (TX->getCanonicalTypeInternal() != TY->getCanonicalTypeInternal())
7712 return false;
7713 return isSameQualifier(X: TX->getPrefix(), Y: TY->getPrefix());
7714 }
7715 case NestedNameSpecifier::Kind::Null:
7716 case NestedNameSpecifier::Kind::Global:
7717 case NestedNameSpecifier::Kind::MicrosoftSuper:
7718 return true;
7719 }
7720 llvm_unreachable("unhandled qualifier kind");
7721}
7722
7723static bool hasSameCudaAttrs(const FunctionDecl *A, const FunctionDecl *B) {
7724 if (!A->getASTContext().getLangOpts().CUDA)
7725 return true; // Target attributes are overloadable in CUDA compilation only.
7726 if (A->hasAttr<CUDADeviceAttr>() != B->hasAttr<CUDADeviceAttr>())
7727 return false;
7728 if (A->hasAttr<CUDADeviceAttr>() && B->hasAttr<CUDADeviceAttr>())
7729 return A->hasAttr<CUDAHostAttr>() == B->hasAttr<CUDAHostAttr>();
7730 return true; // unattributed and __host__ functions are the same.
7731}
7732
7733/// Determine whether the attributes we can overload on are identical for A and
7734/// B. Will ignore any overloadable attrs represented in the type of A and B.
7735static bool hasSameOverloadableAttrs(const FunctionDecl *A,
7736 const FunctionDecl *B) {
7737 // Note that pass_object_size attributes are represented in the function's
7738 // ExtParameterInfo, so we don't need to check them here.
7739
7740 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
7741 auto AEnableIfAttrs = A->specific_attrs<EnableIfAttr>();
7742 auto BEnableIfAttrs = B->specific_attrs<EnableIfAttr>();
7743
7744 for (auto Pair : zip_longest(t&: AEnableIfAttrs, u&: BEnableIfAttrs)) {
7745 std::optional<EnableIfAttr *> Cand1A = std::get<0>(t&: Pair);
7746 std::optional<EnableIfAttr *> Cand2A = std::get<1>(t&: Pair);
7747
7748 // Return false if the number of enable_if attributes is different.
7749 if (!Cand1A || !Cand2A)
7750 return false;
7751
7752 Cand1ID.clear();
7753 Cand2ID.clear();
7754
7755 (*Cand1A)->getCond()->Profile(ID&: Cand1ID, Context: A->getASTContext(), Canonical: true);
7756 (*Cand2A)->getCond()->Profile(ID&: Cand2ID, Context: B->getASTContext(), Canonical: true);
7757
7758 // Return false if any of the enable_if expressions of A and B are
7759 // different.
7760 if (Cand1ID != Cand2ID)
7761 return false;
7762 }
7763 return hasSameCudaAttrs(A, B);
7764}
7765
7766bool ASTContext::isSameEntity(const NamedDecl *X, const NamedDecl *Y) const {
7767 // Caution: this function is called by the AST reader during deserialization,
7768 // so it cannot rely on AST invariants being met. Non-trivial accessors
7769 // should be avoided, along with any traversal of redeclaration chains.
7770
7771 if (X == Y)
7772 return true;
7773
7774 if (X->getDeclName() != Y->getDeclName())
7775 return false;
7776
7777 // Must be in the same context.
7778 //
7779 // Note that we can't use DeclContext::Equals here, because the DeclContexts
7780 // could be two different declarations of the same function. (We will fix the
7781 // semantic DC to refer to the primary definition after merging.)
7782 if (!declaresSameEntity(D1: cast<Decl>(Val: X->getDeclContext()->getRedeclContext()),
7783 D2: cast<Decl>(Val: Y->getDeclContext()->getRedeclContext())))
7784 return false;
7785
7786 // If either X or Y are local to the owning module, they are only possible to
7787 // be the same entity if they are in the same module.
7788 if (X->isModuleLocal() || Y->isModuleLocal())
7789 if (!isInSameModule(M1: X->getOwningModule(), M2: Y->getOwningModule()))
7790 return false;
7791
7792 // Two typedefs refer to the same entity if they have the same underlying
7793 // type.
7794 if (const auto *TypedefX = dyn_cast<TypedefNameDecl>(Val: X))
7795 if (const auto *TypedefY = dyn_cast<TypedefNameDecl>(Val: Y))
7796 return hasSameType(T1: TypedefX->getUnderlyingType(),
7797 T2: TypedefY->getUnderlyingType());
7798
7799 // Must have the same kind.
7800 if (X->getKind() != Y->getKind())
7801 return false;
7802
7803 // Objective-C classes and protocols with the same name always match.
7804 if (isa<ObjCInterfaceDecl>(Val: X) || isa<ObjCProtocolDecl>(Val: X))
7805 return true;
7806
7807 if (isa<ClassTemplateSpecializationDecl>(Val: X)) {
7808 // No need to handle these here: we merge them when adding them to the
7809 // template.
7810 return false;
7811 }
7812
7813 // Compatible tags match.
7814 if (const auto *TagX = dyn_cast<TagDecl>(Val: X)) {
7815 const auto *TagY = cast<TagDecl>(Val: Y);
7816 return (TagX->getTagKind() == TagY->getTagKind()) ||
7817 ((TagX->getTagKind() == TagTypeKind::Struct ||
7818 TagX->getTagKind() == TagTypeKind::Class ||
7819 TagX->getTagKind() == TagTypeKind::Interface) &&
7820 (TagY->getTagKind() == TagTypeKind::Struct ||
7821 TagY->getTagKind() == TagTypeKind::Class ||
7822 TagY->getTagKind() == TagTypeKind::Interface));
7823 }
7824
7825 // Functions with the same type and linkage match.
7826 // FIXME: This needs to cope with merging of prototyped/non-prototyped
7827 // functions, etc.
7828 if (const auto *FuncX = dyn_cast<FunctionDecl>(Val: X)) {
7829 const auto *FuncY = cast<FunctionDecl>(Val: Y);
7830 if (const auto *CtorX = dyn_cast<CXXConstructorDecl>(Val: X)) {
7831 const auto *CtorY = cast<CXXConstructorDecl>(Val: Y);
7832 if (CtorX->getInheritedConstructor() &&
7833 !isSameEntity(X: CtorX->getInheritedConstructor().getConstructor(),
7834 Y: CtorY->getInheritedConstructor().getConstructor()))
7835 return false;
7836 }
7837
7838 if (FuncX->isMultiVersion() != FuncY->isMultiVersion())
7839 return false;
7840
7841 // Multiversioned functions with different feature strings are represented
7842 // as separate declarations.
7843 if (FuncX->isMultiVersion()) {
7844 const auto *TAX = FuncX->getAttr<TargetAttr>();
7845 const auto *TAY = FuncY->getAttr<TargetAttr>();
7846 assert(TAX && TAY && "Multiversion Function without target attribute");
7847
7848 if (TAX->getFeaturesStr() != TAY->getFeaturesStr())
7849 return false;
7850 }
7851
7852 // Per C++20 [temp.over.link]/4, friends in different classes are sometimes
7853 // not the same entity if they are constrained.
7854 if ((FuncX->isMemberLikeConstrainedFriend() ||
7855 FuncY->isMemberLikeConstrainedFriend()) &&
7856 !FuncX->getLexicalDeclContext()->Equals(
7857 DC: FuncY->getLexicalDeclContext())) {
7858 return false;
7859 }
7860
7861 if (!isSameAssociatedConstraint(ACX: FuncX->getTrailingRequiresClause(),
7862 ACY: FuncY->getTrailingRequiresClause()))
7863 return false;
7864
7865 auto GetTypeAsWritten = [](const FunctionDecl *FD) {
7866 // Map to the first declaration that we've already merged into this one.
7867 // The TSI of redeclarations might not match (due to calling conventions
7868 // being inherited onto the type but not the TSI), but the TSI type of
7869 // the first declaration of the function should match across modules.
7870 FD = FD->getCanonicalDecl();
7871 return FD->getTypeSourceInfo() ? FD->getTypeSourceInfo()->getType()
7872 : FD->getType();
7873 };
7874 QualType XT = GetTypeAsWritten(FuncX), YT = GetTypeAsWritten(FuncY);
7875 if (!hasSameType(T1: XT, T2: YT)) {
7876 // We can get functions with different types on the redecl chain in C++17
7877 // if they have differing exception specifications and at least one of
7878 // the excpetion specs is unresolved.
7879 auto *XFPT = XT->getAs<FunctionProtoType>();
7880 auto *YFPT = YT->getAs<FunctionProtoType>();
7881 if (getLangOpts().CPlusPlus17 && XFPT && YFPT &&
7882 (isUnresolvedExceptionSpec(ESpecType: XFPT->getExceptionSpecType()) ||
7883 isUnresolvedExceptionSpec(ESpecType: YFPT->getExceptionSpecType())) &&
7884 hasSameFunctionTypeIgnoringExceptionSpec(T: XT, U: YT))
7885 return true;
7886 return false;
7887 }
7888
7889 return FuncX->getLinkageInternal() == FuncY->getLinkageInternal() &&
7890 hasSameOverloadableAttrs(A: FuncX, B: FuncY);
7891 }
7892
7893 // Variables with the same type and linkage match.
7894 if (const auto *VarX = dyn_cast<VarDecl>(Val: X)) {
7895 const auto *VarY = cast<VarDecl>(Val: Y);
7896 if (VarX->getLinkageInternal() == VarY->getLinkageInternal()) {
7897 // During deserialization, we might compare variables before we load
7898 // their types. Assume the types will end up being the same.
7899 if (VarX->getType().isNull() || VarY->getType().isNull())
7900 return true;
7901
7902 if (hasSameType(T1: VarX->getType(), T2: VarY->getType()))
7903 return true;
7904
7905 // We can get decls with different types on the redecl chain. Eg.
7906 // template <typename T> struct S { static T Var[]; }; // #1
7907 // template <typename T> T S<T>::Var[sizeof(T)]; // #2
7908 // Only? happens when completing an incomplete array type. In this case
7909 // when comparing #1 and #2 we should go through their element type.
7910 const ArrayType *VarXTy = getAsArrayType(T: VarX->getType());
7911 const ArrayType *VarYTy = getAsArrayType(T: VarY->getType());
7912 if (!VarXTy || !VarYTy)
7913 return false;
7914 if (VarXTy->isIncompleteArrayType() || VarYTy->isIncompleteArrayType())
7915 return hasSameType(T1: VarXTy->getElementType(), T2: VarYTy->getElementType());
7916 }
7917 return false;
7918 }
7919
7920 // Namespaces with the same name and inlinedness match.
7921 if (const auto *NamespaceX = dyn_cast<NamespaceDecl>(Val: X)) {
7922 const auto *NamespaceY = cast<NamespaceDecl>(Val: Y);
7923 return NamespaceX->isInline() == NamespaceY->isInline();
7924 }
7925
7926 // Identical template names and kinds match if their template parameter lists
7927 // and patterns match.
7928 if (const auto *TemplateX = dyn_cast<TemplateDecl>(Val: X)) {
7929 const auto *TemplateY = cast<TemplateDecl>(Val: Y);
7930
7931 // ConceptDecl wouldn't be the same if their constraint expression differs.
7932 if (const auto *ConceptX = dyn_cast<ConceptDecl>(Val: X)) {
7933 const auto *ConceptY = cast<ConceptDecl>(Val: Y);
7934 if (!isSameConstraintExpr(XCE: ConceptX->getConstraintExpr(),
7935 YCE: ConceptY->getConstraintExpr()))
7936 return false;
7937 }
7938
7939 return isSameEntity(X: TemplateX->getTemplatedDecl(),
7940 Y: TemplateY->getTemplatedDecl()) &&
7941 isSameTemplateParameterList(X: TemplateX->getTemplateParameters(),
7942 Y: TemplateY->getTemplateParameters());
7943 }
7944
7945 // Fields with the same name and the same type match.
7946 if (const auto *FDX = dyn_cast<FieldDecl>(Val: X)) {
7947 const auto *FDY = cast<FieldDecl>(Val: Y);
7948 // FIXME: Also check the bitwidth is odr-equivalent, if any.
7949 return hasSameType(T1: FDX->getType(), T2: FDY->getType());
7950 }
7951
7952 // Indirect fields with the same target field match.
7953 if (const auto *IFDX = dyn_cast<IndirectFieldDecl>(Val: X)) {
7954 const auto *IFDY = cast<IndirectFieldDecl>(Val: Y);
7955 return IFDX->getAnonField()->getCanonicalDecl() ==
7956 IFDY->getAnonField()->getCanonicalDecl();
7957 }
7958
7959 // Enumerators with the same name match.
7960 if (isa<EnumConstantDecl>(Val: X))
7961 // FIXME: Also check the value is odr-equivalent.
7962 return true;
7963
7964 // Using shadow declarations with the same target match.
7965 if (const auto *USX = dyn_cast<UsingShadowDecl>(Val: X)) {
7966 const auto *USY = cast<UsingShadowDecl>(Val: Y);
7967 return declaresSameEntity(D1: USX->getTargetDecl(), D2: USY->getTargetDecl());
7968 }
7969
7970 // Using declarations with the same qualifier match. (We already know that
7971 // the name matches.)
7972 if (const auto *UX = dyn_cast<UsingDecl>(Val: X)) {
7973 const auto *UY = cast<UsingDecl>(Val: Y);
7974 return isSameQualifier(X: UX->getQualifier(), Y: UY->getQualifier()) &&
7975 UX->hasTypename() == UY->hasTypename() &&
7976 UX->isAccessDeclaration() == UY->isAccessDeclaration();
7977 }
7978 if (const auto *UX = dyn_cast<UnresolvedUsingValueDecl>(Val: X)) {
7979 const auto *UY = cast<UnresolvedUsingValueDecl>(Val: Y);
7980 return isSameQualifier(X: UX->getQualifier(), Y: UY->getQualifier()) &&
7981 UX->isAccessDeclaration() == UY->isAccessDeclaration();
7982 }
7983 if (const auto *UX = dyn_cast<UnresolvedUsingTypenameDecl>(Val: X)) {
7984 return isSameQualifier(
7985 X: UX->getQualifier(),
7986 Y: cast<UnresolvedUsingTypenameDecl>(Val: Y)->getQualifier());
7987 }
7988
7989 // Using-pack declarations are only created by instantiation, and match if
7990 // they're instantiated from matching UnresolvedUsing...Decls.
7991 if (const auto *UX = dyn_cast<UsingPackDecl>(Val: X)) {
7992 return declaresSameEntity(
7993 D1: UX->getInstantiatedFromUsingDecl(),
7994 D2: cast<UsingPackDecl>(Val: Y)->getInstantiatedFromUsingDecl());
7995 }
7996
7997 // Namespace alias definitions with the same target match.
7998 if (const auto *NAX = dyn_cast<NamespaceAliasDecl>(Val: X)) {
7999 const auto *NAY = cast<NamespaceAliasDecl>(Val: Y);
8000 return NAX->getNamespace()->Equals(DC: NAY->getNamespace());
8001 }
8002
8003 if (const auto *UX = dyn_cast<UsingEnumDecl>(Val: X)) {
8004 const auto *UY = cast<UsingEnumDecl>(Val: Y);
8005 return isSameQualifier(X: UX->getQualifier(), Y: UY->getQualifier()) &&
8006 declaresSameEntity(D1: UX->getEnumDecl(), D2: UY->getEnumDecl());
8007 }
8008
8009 return false;
8010}
8011
8012TemplateArgument
8013ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
8014 switch (Arg.getKind()) {
8015 case TemplateArgument::Null:
8016 return Arg;
8017
8018 case TemplateArgument::Expression:
8019 return TemplateArgument(Arg.getAsExpr(), /*IsCanonical=*/true,
8020 Arg.getIsDefaulted());
8021
8022 case TemplateArgument::Declaration: {
8023 auto *D = cast<ValueDecl>(Val: Arg.getAsDecl()->getCanonicalDecl());
8024 return TemplateArgument(D, getCanonicalType(T: Arg.getParamTypeForDecl()),
8025 Arg.getIsDefaulted());
8026 }
8027
8028 case TemplateArgument::NullPtr:
8029 return TemplateArgument(getCanonicalType(T: Arg.getNullPtrType()),
8030 /*isNullPtr*/ true, Arg.getIsDefaulted());
8031
8032 case TemplateArgument::Template:
8033 return TemplateArgument(getCanonicalTemplateName(Name: Arg.getAsTemplate()),
8034 Arg.getIsDefaulted());
8035
8036 case TemplateArgument::TemplateExpansion:
8037 return TemplateArgument(
8038 getCanonicalTemplateName(Name: Arg.getAsTemplateOrTemplatePattern()),
8039 Arg.getNumTemplateExpansions(), Arg.getIsDefaulted());
8040
8041 case TemplateArgument::Integral:
8042 return TemplateArgument(Arg, getCanonicalType(T: Arg.getIntegralType()));
8043
8044 case TemplateArgument::StructuralValue:
8045 return TemplateArgument(*this,
8046 getCanonicalType(T: Arg.getStructuralValueType()),
8047 Arg.getAsStructuralValue(), Arg.getIsDefaulted());
8048
8049 case TemplateArgument::Type:
8050 return TemplateArgument(getCanonicalType(T: Arg.getAsType()),
8051 /*isNullPtr*/ false, Arg.getIsDefaulted());
8052
8053 case TemplateArgument::Pack: {
8054 bool AnyNonCanonArgs = false;
8055 auto CanonArgs = ::getCanonicalTemplateArguments(
8056 C: *this, Args: Arg.pack_elements(), AnyNonCanonArgs);
8057 if (!AnyNonCanonArgs)
8058 return Arg;
8059 auto NewArg = TemplateArgument::CreatePackCopy(
8060 Context&: const_cast<ASTContext &>(*this), Args: CanonArgs);
8061 NewArg.setIsDefaulted(Arg.getIsDefaulted());
8062 return NewArg;
8063 }
8064 }
8065
8066 // Silence GCC warning
8067 llvm_unreachable("Unhandled template argument kind");
8068}
8069
8070bool ASTContext::isSameTemplateArgument(const TemplateArgument &Arg1,
8071 const TemplateArgument &Arg2) const {
8072 if (Arg1.getKind() != Arg2.getKind())
8073 return false;
8074
8075 switch (Arg1.getKind()) {
8076 case TemplateArgument::Null:
8077 llvm_unreachable("Comparing NULL template argument");
8078
8079 case TemplateArgument::Type:
8080 return hasSameType(T1: Arg1.getAsType(), T2: Arg2.getAsType());
8081
8082 case TemplateArgument::Declaration:
8083 return Arg1.getAsDecl()->getUnderlyingDecl()->getCanonicalDecl() ==
8084 Arg2.getAsDecl()->getUnderlyingDecl()->getCanonicalDecl();
8085
8086 case TemplateArgument::NullPtr:
8087 return hasSameType(T1: Arg1.getNullPtrType(), T2: Arg2.getNullPtrType());
8088
8089 case TemplateArgument::Template:
8090 case TemplateArgument::TemplateExpansion:
8091 return getCanonicalTemplateName(Name: Arg1.getAsTemplateOrTemplatePattern()) ==
8092 getCanonicalTemplateName(Name: Arg2.getAsTemplateOrTemplatePattern());
8093
8094 case TemplateArgument::Integral:
8095 return llvm::APSInt::isSameValue(I1: Arg1.getAsIntegral(),
8096 I2: Arg2.getAsIntegral());
8097
8098 case TemplateArgument::StructuralValue:
8099 return Arg1.structurallyEquals(Other: Arg2);
8100
8101 case TemplateArgument::Expression: {
8102 llvm::FoldingSetNodeID ID1, ID2;
8103 Arg1.getAsExpr()->Profile(ID&: ID1, Context: *this, /*Canonical=*/true);
8104 Arg2.getAsExpr()->Profile(ID&: ID2, Context: *this, /*Canonical=*/true);
8105 return ID1 == ID2;
8106 }
8107
8108 case TemplateArgument::Pack:
8109 return llvm::equal(
8110 LRange: Arg1.getPackAsArray(), RRange: Arg2.getPackAsArray(),
8111 P: [&](const TemplateArgument &Arg1, const TemplateArgument &Arg2) {
8112 return isSameTemplateArgument(Arg1, Arg2);
8113 });
8114 }
8115
8116 llvm_unreachable("Unhandled template argument kind");
8117}
8118
8119const ArrayType *ASTContext::getAsArrayType(QualType T) const {
8120 // Handle the non-qualified case efficiently.
8121 if (!T.hasLocalQualifiers()) {
8122 // Handle the common positive case fast.
8123 if (const auto *AT = dyn_cast<ArrayType>(Val&: T))
8124 return AT;
8125 }
8126
8127 // Handle the common negative case fast.
8128 if (!isa<ArrayType>(Val: T.getCanonicalType()))
8129 return nullptr;
8130
8131 // Apply any qualifiers from the array type to the element type. This
8132 // implements C99 6.7.3p8: "If the specification of an array type includes
8133 // any type qualifiers, the element type is so qualified, not the array type."
8134
8135 // If we get here, we either have type qualifiers on the type, or we have
8136 // sugar such as a typedef in the way. If we have type qualifiers on the type
8137 // we must propagate them down into the element type.
8138
8139 SplitQualType split = T.getSplitDesugaredType();
8140 Qualifiers qs = split.Quals;
8141
8142 // If we have a simple case, just return now.
8143 const auto *ATy = dyn_cast<ArrayType>(Val: split.Ty);
8144 if (!ATy || qs.empty())
8145 return ATy;
8146
8147 // Otherwise, we have an array and we have qualifiers on it. Push the
8148 // qualifiers into the array element type and return a new array type.
8149 QualType NewEltTy = getQualifiedType(T: ATy->getElementType(), Qs: qs);
8150
8151 if (const auto *CAT = dyn_cast<ConstantArrayType>(Val: ATy))
8152 return cast<ArrayType>(Val: getConstantArrayType(EltTy: NewEltTy, ArySizeIn: CAT->getSize(),
8153 SizeExpr: CAT->getSizeExpr(),
8154 ASM: CAT->getSizeModifier(),
8155 IndexTypeQuals: CAT->getIndexTypeCVRQualifiers()));
8156 if (const auto *IAT = dyn_cast<IncompleteArrayType>(Val: ATy))
8157 return cast<ArrayType>(Val: getIncompleteArrayType(elementType: NewEltTy,
8158 ASM: IAT->getSizeModifier(),
8159 elementTypeQuals: IAT->getIndexTypeCVRQualifiers()));
8160
8161 if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(Val: ATy))
8162 return cast<ArrayType>(Val: getDependentSizedArrayType(
8163 elementType: NewEltTy, numElements: DSAT->getSizeExpr(), ASM: DSAT->getSizeModifier(),
8164 elementTypeQuals: DSAT->getIndexTypeCVRQualifiers()));
8165
8166 const auto *VAT = cast<VariableArrayType>(Val: ATy);
8167 return cast<ArrayType>(
8168 Val: getVariableArrayType(EltTy: NewEltTy, NumElts: VAT->getSizeExpr(), ASM: VAT->getSizeModifier(),
8169 IndexTypeQuals: VAT->getIndexTypeCVRQualifiers()));
8170}
8171
8172QualType ASTContext::getAdjustedParameterType(QualType T) const {
8173 if (getLangOpts().HLSL && T.getAddressSpace() == LangAS::hlsl_groupshared)
8174 return getLValueReferenceType(T);
8175 if (getLangOpts().HLSL && T->isConstantArrayType())
8176 return getArrayParameterType(Ty: T);
8177 if (T->isArrayType() || T->isFunctionType())
8178 return getDecayedType(T);
8179 return T;
8180}
8181
8182QualType ASTContext::getSignatureParameterType(QualType T) const {
8183 T = getVariableArrayDecayedType(type: T);
8184 T = getAdjustedParameterType(T);
8185 return T.getUnqualifiedType();
8186}
8187
8188QualType ASTContext::getExceptionObjectType(QualType T) const {
8189 // C++ [except.throw]p3:
8190 // A throw-expression initializes a temporary object, called the exception
8191 // object, the type of which is determined by removing any top-level
8192 // cv-qualifiers from the static type of the operand of throw and adjusting
8193 // the type from "array of T" or "function returning T" to "pointer to T"
8194 // or "pointer to function returning T", [...]
8195 T = getVariableArrayDecayedType(type: T);
8196 if (T->isArrayType() || T->isFunctionType())
8197 T = getDecayedType(T);
8198 return T.getUnqualifiedType();
8199}
8200
8201/// getArrayDecayedType - Return the properly qualified result of decaying the
8202/// specified array type to a pointer. This operation is non-trivial when
8203/// handling typedefs etc. The canonical type of "T" must be an array type,
8204/// this returns a pointer to a properly qualified element of the array.
8205///
8206/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
8207QualType ASTContext::getArrayDecayedType(QualType Ty) const {
8208 // Get the element type with 'getAsArrayType' so that we don't lose any
8209 // typedefs in the element type of the array. This also handles propagation
8210 // of type qualifiers from the array type into the element type if present
8211 // (C99 6.7.3p8).
8212 const ArrayType *PrettyArrayType = getAsArrayType(T: Ty);
8213 assert(PrettyArrayType && "Not an array type!");
8214
8215 QualType PtrTy = getPointerType(T: PrettyArrayType->getElementType());
8216
8217 // int x[restrict 4] -> int *restrict
8218 QualType Result = getQualifiedType(T: PtrTy,
8219 Qs: PrettyArrayType->getIndexTypeQualifiers());
8220
8221 // int x[_Nullable] -> int * _Nullable
8222 if (auto Nullability = Ty->getNullability()) {
8223 Result = getAttributedType(nullability: *Nullability, modifiedType: Result, equivalentType: Result);
8224 }
8225 return Result;
8226}
8227
8228QualType ASTContext::getBaseElementType(const ArrayType *array) const {
8229 return getBaseElementType(QT: array->getElementType());
8230}
8231
8232QualType ASTContext::getBaseElementType(QualType type) const {
8233 Qualifiers qs;
8234 while (true) {
8235 SplitQualType split = type.getSplitDesugaredType();
8236 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
8237 if (!array) break;
8238
8239 type = array->getElementType();
8240 qs.addConsistentQualifiers(qs: split.Quals);
8241 }
8242
8243 return getQualifiedType(T: type, Qs: qs);
8244}
8245
8246uint64_t ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) {
8247 uint64_t ElementCount = 1;
8248 do {
8249 ElementCount *= CA->getZExtSize();
8250 CA = dyn_cast_if_present<ConstantArrayType>(
8251 Val: CA->getElementType()->getAsArrayTypeUnsafe());
8252 } while (CA);
8253 return ElementCount;
8254}
8255
8256uint64_t
8257ASTContext::getArrayInitLoopExprElementCount(const ArrayInitLoopExpr *AILE) {
8258 if (!AILE)
8259 return 0;
8260
8261 uint64_t ElementCount = 1;
8262
8263 do {
8264 ElementCount *= AILE->getArraySize().getZExtValue();
8265 AILE = dyn_cast<ArrayInitLoopExpr>(Val: AILE->getSubExpr());
8266 } while (AILE);
8267
8268 return ElementCount;
8269}
8270
8271/// getFloatingRank - Return a relative rank for floating point types.
8272/// This routine will assert if passed a built-in type that isn't a float.
8273static FloatingRank getFloatingRank(QualType T) {
8274 if (const auto *CT = T->getAs<ComplexType>())
8275 return getFloatingRank(T: CT->getElementType());
8276
8277 switch (T->castAs<BuiltinType>()->getKind()) {
8278 default: llvm_unreachable("getFloatingRank(): not a floating type");
8279 case BuiltinType::Float16: return Float16Rank;
8280 case BuiltinType::Half: return HalfRank;
8281 case BuiltinType::Float: return FloatRank;
8282 case BuiltinType::Double: return DoubleRank;
8283 case BuiltinType::LongDouble: return LongDoubleRank;
8284 case BuiltinType::Float128: return Float128Rank;
8285 case BuiltinType::BFloat16: return BFloat16Rank;
8286 case BuiltinType::Ibm128: return Ibm128Rank;
8287 }
8288}
8289
8290/// getFloatingTypeOrder - Compare the rank of the two specified floating
8291/// point types, ignoring the domain of the type (i.e. 'double' ==
8292/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
8293/// LHS < RHS, return -1.
8294int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
8295 FloatingRank LHSR = getFloatingRank(T: LHS);
8296 FloatingRank RHSR = getFloatingRank(T: RHS);
8297
8298 if (LHSR == RHSR)
8299 return 0;
8300 if (LHSR > RHSR)
8301 return 1;
8302 return -1;
8303}
8304
8305int ASTContext::getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const {
8306 if (&getFloatTypeSemantics(T: LHS) == &getFloatTypeSemantics(T: RHS))
8307 return 0;
8308 return getFloatingTypeOrder(LHS, RHS);
8309}
8310
8311/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
8312/// routine will assert if passed a built-in type that isn't an integer or enum,
8313/// or if it is not canonicalized.
8314unsigned ASTContext::getIntegerRank(const Type *T) const {
8315 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
8316
8317 // Results in this 'losing' to any type of the same size, but winning if
8318 // larger.
8319 if (const auto *EIT = dyn_cast<BitIntType>(Val: T))
8320 return 0 + (EIT->getNumBits() << 3);
8321
8322 if (const auto *OBT = dyn_cast<OverflowBehaviorType>(Val: T))
8323 return getIntegerRank(T: OBT->getUnderlyingType().getTypePtr());
8324
8325 switch (cast<BuiltinType>(Val: T)->getKind()) {
8326 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
8327 case BuiltinType::Bool:
8328 return 1 + (getIntWidth(T: BoolTy) << 3);
8329 case BuiltinType::Char_S:
8330 case BuiltinType::Char_U:
8331 case BuiltinType::SChar:
8332 case BuiltinType::UChar:
8333 return 2 + (getIntWidth(T: CharTy) << 3);
8334 case BuiltinType::Short:
8335 case BuiltinType::UShort:
8336 return 3 + (getIntWidth(T: ShortTy) << 3);
8337 case BuiltinType::Int:
8338 case BuiltinType::UInt:
8339 return 4 + (getIntWidth(T: IntTy) << 3);
8340 case BuiltinType::Long:
8341 case BuiltinType::ULong:
8342 return 5 + (getIntWidth(T: LongTy) << 3);
8343 case BuiltinType::LongLong:
8344 case BuiltinType::ULongLong:
8345 return 6 + (getIntWidth(T: LongLongTy) << 3);
8346 case BuiltinType::Int128:
8347 case BuiltinType::UInt128:
8348 return 7 + (getIntWidth(T: Int128Ty) << 3);
8349
8350 // "The ranks of char8_t, char16_t, char32_t, and wchar_t equal the ranks of
8351 // their underlying types" [c++20 conv.rank]
8352 case BuiltinType::Char8:
8353 return getIntegerRank(T: UnsignedCharTy.getTypePtr());
8354 case BuiltinType::Char16:
8355 return getIntegerRank(
8356 T: getFromTargetType(Type: Target->getChar16Type()).getTypePtr());
8357 case BuiltinType::Char32:
8358 return getIntegerRank(
8359 T: getFromTargetType(Type: Target->getChar32Type()).getTypePtr());
8360 case BuiltinType::WChar_S:
8361 case BuiltinType::WChar_U:
8362 return getIntegerRank(
8363 T: getFromTargetType(Type: Target->getWCharType()).getTypePtr());
8364 }
8365}
8366
8367/// Whether this is a promotable bitfield reference according
8368/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
8369///
8370/// \returns the type this bit-field will promote to, or NULL if no
8371/// promotion occurs.
8372QualType ASTContext::isPromotableBitField(Expr *E) const {
8373 if (E->isTypeDependent() || E->isValueDependent())
8374 return {};
8375
8376 // C++ [conv.prom]p5:
8377 // If the bit-field has an enumerated type, it is treated as any other
8378 // value of that type for promotion purposes.
8379 if (getLangOpts().CPlusPlus && E->getType()->isEnumeralType())
8380 return {};
8381
8382 // FIXME: We should not do this unless E->refersToBitField() is true. This
8383 // matters in C where getSourceBitField() will find bit-fields for various
8384 // cases where the source expression is not a bit-field designator.
8385
8386 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
8387 if (!Field)
8388 return {};
8389
8390 QualType FT = Field->getType();
8391
8392 uint64_t BitWidth = Field->getBitWidthValue();
8393 uint64_t IntSize = getTypeSize(T: IntTy);
8394 // C++ [conv.prom]p5:
8395 // A prvalue for an integral bit-field can be converted to a prvalue of type
8396 // int if int can represent all the values of the bit-field; otherwise, it
8397 // can be converted to unsigned int if unsigned int can represent all the
8398 // values of the bit-field. If the bit-field is larger yet, no integral
8399 // promotion applies to it.
8400 // C11 6.3.1.1/2:
8401 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
8402 // If an int can represent all values of the original type (as restricted by
8403 // the width, for a bit-field), the value is converted to an int; otherwise,
8404 // it is converted to an unsigned int.
8405 //
8406 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
8407 // We perform that promotion here to match GCC and C++.
8408 // FIXME: C does not permit promotion of an enum bit-field whose rank is
8409 // greater than that of 'int'. We perform that promotion to match GCC.
8410 //
8411 // C23 6.3.1.1p2:
8412 // The value from a bit-field of a bit-precise integer type is converted to
8413 // the corresponding bit-precise integer type. (The rest is the same as in
8414 // C11.)
8415 if (QualType QT = Field->getType(); QT->isBitIntType())
8416 return QT;
8417
8418 if (BitWidth < IntSize)
8419 return IntTy;
8420
8421 if (BitWidth == IntSize)
8422 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
8423
8424 // Bit-fields wider than int are not subject to promotions, and therefore act
8425 // like the base type. GCC has some weird bugs in this area that we
8426 // deliberately do not follow (GCC follows a pre-standard resolution to
8427 // C's DR315 which treats bit-width as being part of the type, and this leaks
8428 // into their semantics in some cases).
8429 return {};
8430}
8431
8432/// getPromotedIntegerType - Returns the type that Promotable will
8433/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
8434/// integer type.
8435QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
8436 assert(!Promotable.isNull());
8437 assert(isPromotableIntegerType(Promotable));
8438 if (const auto *ED = Promotable->getAsEnumDecl())
8439 return ED->getPromotionType();
8440
8441 // OverflowBehaviorTypes promote their underlying type and preserve OBT
8442 // qualifier.
8443 if (const auto *OBT = Promotable->getAs<OverflowBehaviorType>()) {
8444 QualType PromotedUnderlying =
8445 getPromotedIntegerType(Promotable: OBT->getUnderlyingType());
8446 return getOverflowBehaviorType(Kind: OBT->getBehaviorKind(), Underlying: PromotedUnderlying);
8447 }
8448
8449 if (const auto *BT = Promotable->getAs<BuiltinType>()) {
8450 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
8451 // (3.9.1) can be converted to a prvalue of the first of the following
8452 // types that can represent all the values of its underlying type:
8453 // int, unsigned int, long int, unsigned long int, long long int, or
8454 // unsigned long long int [...]
8455 // FIXME: Is there some better way to compute this?
8456 if (BT->getKind() == BuiltinType::WChar_S ||
8457 BT->getKind() == BuiltinType::WChar_U ||
8458 BT->getKind() == BuiltinType::Char8 ||
8459 BT->getKind() == BuiltinType::Char16 ||
8460 BT->getKind() == BuiltinType::Char32) {
8461 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
8462 uint64_t FromSize = getTypeSize(T: BT);
8463 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
8464 LongLongTy, UnsignedLongLongTy };
8465 for (const auto &PT : PromoteTypes) {
8466 uint64_t ToSize = getTypeSize(T: PT);
8467 if (FromSize < ToSize ||
8468 (FromSize == ToSize && FromIsSigned == PT->isSignedIntegerType()))
8469 return PT;
8470 }
8471 llvm_unreachable("char type should fit into long long");
8472 }
8473 }
8474
8475 // At this point, we should have a signed or unsigned integer type.
8476 if (Promotable->isSignedIntegerType())
8477 return IntTy;
8478 uint64_t PromotableSize = getIntWidth(T: Promotable);
8479 uint64_t IntSize = getIntWidth(T: IntTy);
8480 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
8481 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
8482}
8483
8484/// Recurses in pointer/array types until it finds an objc retainable
8485/// type and returns its ownership.
8486Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
8487 while (!T.isNull()) {
8488 if (T.getObjCLifetime() != Qualifiers::OCL_None)
8489 return T.getObjCLifetime();
8490 if (T->isArrayType())
8491 T = getBaseElementType(type: T);
8492 else if (const auto *PT = T->getAs<PointerType>())
8493 T = PT->getPointeeType();
8494 else if (const auto *RT = T->getAs<ReferenceType>())
8495 T = RT->getPointeeType();
8496 else
8497 break;
8498 }
8499
8500 return Qualifiers::OCL_None;
8501}
8502
8503static const Type *getIntegerTypeForEnum(const EnumType *ET) {
8504 // Incomplete enum types are not treated as integer types.
8505 // FIXME: In C++, enum types are never integer types.
8506 const EnumDecl *ED = ET->getDecl()->getDefinitionOrSelf();
8507 if (ED->isComplete() && !ED->isScoped())
8508 return ED->getIntegerType().getTypePtr();
8509 return nullptr;
8510}
8511
8512/// getIntegerTypeOrder - Returns the highest ranked integer type:
8513/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
8514/// LHS < RHS, return -1.
8515int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
8516 const Type *LHSC = getCanonicalType(T: LHS).getTypePtr();
8517 const Type *RHSC = getCanonicalType(T: RHS).getTypePtr();
8518
8519 // Unwrap enums to their underlying type.
8520 if (const auto *ET = dyn_cast<EnumType>(Val: LHSC))
8521 LHSC = getIntegerTypeForEnum(ET);
8522 if (const auto *ET = dyn_cast<EnumType>(Val: RHSC))
8523 RHSC = getIntegerTypeForEnum(ET);
8524
8525 if (LHSC == RHSC) return 0;
8526
8527 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
8528 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
8529
8530 unsigned LHSRank = getIntegerRank(T: LHSC);
8531 unsigned RHSRank = getIntegerRank(T: RHSC);
8532
8533 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
8534 if (LHSRank == RHSRank) return 0;
8535 return LHSRank > RHSRank ? 1 : -1;
8536 }
8537
8538 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
8539 if (LHSUnsigned) {
8540 // If the unsigned [LHS] type is larger, return it.
8541 if (LHSRank >= RHSRank)
8542 return 1;
8543
8544 // If the signed type can represent all values of the unsigned type, it
8545 // wins. Because we are dealing with 2's complement and types that are
8546 // powers of two larger than each other, this is always safe.
8547 return -1;
8548 }
8549
8550 // If the unsigned [RHS] type is larger, return it.
8551 if (RHSRank >= LHSRank)
8552 return -1;
8553
8554 // If the signed type can represent all values of the unsigned type, it
8555 // wins. Because we are dealing with 2's complement and types that are
8556 // powers of two larger than each other, this is always safe.
8557 return 1;
8558}
8559
8560TypedefDecl *ASTContext::getCFConstantStringDecl() const {
8561 if (CFConstantStringTypeDecl)
8562 return CFConstantStringTypeDecl;
8563
8564 assert(!CFConstantStringTagDecl &&
8565 "tag and typedef should be initialized together");
8566 CFConstantStringTagDecl = buildImplicitRecord(Name: "__NSConstantString_tag");
8567 CFConstantStringTagDecl->startDefinition();
8568
8569 struct {
8570 QualType Type;
8571 const char *Name;
8572 } Fields[5];
8573 unsigned Count = 0;
8574
8575 /// Objective-C ABI
8576 ///
8577 /// typedef struct __NSConstantString_tag {
8578 /// const int *isa;
8579 /// int flags;
8580 /// const char *str;
8581 /// long length;
8582 /// } __NSConstantString;
8583 ///
8584 /// Swift ABI (4.1, 4.2)
8585 ///
8586 /// typedef struct __NSConstantString_tag {
8587 /// uintptr_t _cfisa;
8588 /// uintptr_t _swift_rc;
8589 /// _Atomic(uint64_t) _cfinfoa;
8590 /// const char *_ptr;
8591 /// uint32_t _length;
8592 /// } __NSConstantString;
8593 ///
8594 /// Swift ABI (5.0)
8595 ///
8596 /// typedef struct __NSConstantString_tag {
8597 /// uintptr_t _cfisa;
8598 /// uintptr_t _swift_rc;
8599 /// _Atomic(uint64_t) _cfinfoa;
8600 /// const char *_ptr;
8601 /// uintptr_t _length;
8602 /// } __NSConstantString;
8603
8604 const auto CFRuntime = getLangOpts().CFRuntime;
8605 if (static_cast<unsigned>(CFRuntime) <
8606 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) {
8607 Fields[Count++] = { .Type: getPointerType(T: IntTy.withConst()), .Name: "isa" };
8608 Fields[Count++] = { .Type: IntTy, .Name: "flags" };
8609 Fields[Count++] = { .Type: getPointerType(T: CharTy.withConst()), .Name: "str" };
8610 Fields[Count++] = { .Type: LongTy, .Name: "length" };
8611 } else {
8612 Fields[Count++] = { .Type: getUIntPtrType(), .Name: "_cfisa" };
8613 Fields[Count++] = { .Type: getUIntPtrType(), .Name: "_swift_rc" };
8614 Fields[Count++] = { .Type: getFromTargetType(Type: Target->getUInt64Type()), .Name: "_swift_rc" };
8615 Fields[Count++] = { .Type: getPointerType(T: CharTy.withConst()), .Name: "_ptr" };
8616 if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 ||
8617 CFRuntime == LangOptions::CoreFoundationABI::Swift4_2)
8618 Fields[Count++] = { .Type: IntTy, .Name: "_ptr" };
8619 else
8620 Fields[Count++] = { .Type: getUIntPtrType(), .Name: "_ptr" };
8621 }
8622
8623 // Create fields
8624 for (unsigned i = 0; i < Count; ++i) {
8625 FieldDecl *Field =
8626 FieldDecl::Create(C: *this, DC: CFConstantStringTagDecl, StartLoc: SourceLocation(),
8627 IdLoc: SourceLocation(), Id: &Idents.get(Name: Fields[i].Name),
8628 T: Fields[i].Type, /*TInfo=*/nullptr,
8629 /*BitWidth=*/BW: nullptr, /*Mutable=*/false, InitStyle: ICIS_NoInit);
8630 Field->setAccess(AS_public);
8631 CFConstantStringTagDecl->addDecl(D: Field);
8632 }
8633
8634 CFConstantStringTagDecl->completeDefinition();
8635 // This type is designed to be compatible with NSConstantString, but cannot
8636 // use the same name, since NSConstantString is an interface.
8637 CanQualType tagType = getCanonicalTagType(TD: CFConstantStringTagDecl);
8638 CFConstantStringTypeDecl =
8639 buildImplicitTypedef(T: tagType, Name: "__NSConstantString");
8640
8641 return CFConstantStringTypeDecl;
8642}
8643
8644RecordDecl *ASTContext::getCFConstantStringTagDecl() const {
8645 if (!CFConstantStringTagDecl)
8646 getCFConstantStringDecl(); // Build the tag and the typedef.
8647 return CFConstantStringTagDecl;
8648}
8649
8650// getCFConstantStringType - Return the type used for constant CFStrings.
8651QualType ASTContext::getCFConstantStringType() const {
8652 return getTypedefType(Keyword: ElaboratedTypeKeyword::None, /*Qualifier=*/std::nullopt,
8653 Decl: getCFConstantStringDecl());
8654}
8655
8656QualType ASTContext::getObjCSuperType() const {
8657 if (ObjCSuperType.isNull()) {
8658 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord(Name: "objc_super");
8659 getTranslationUnitDecl()->addDecl(D: ObjCSuperTypeDecl);
8660 ObjCSuperType = getCanonicalTagType(TD: ObjCSuperTypeDecl);
8661 }
8662 return ObjCSuperType;
8663}
8664
8665void ASTContext::setCFConstantStringType(QualType T) {
8666 const auto *TT = T->castAs<TypedefType>();
8667 CFConstantStringTypeDecl = cast<TypedefDecl>(Val: TT->getDecl());
8668 CFConstantStringTagDecl = TT->castAsRecordDecl();
8669}
8670
8671QualType ASTContext::getBlockDescriptorType() const {
8672 if (BlockDescriptorType)
8673 return getCanonicalTagType(TD: BlockDescriptorType);
8674
8675 RecordDecl *RD;
8676 // FIXME: Needs the FlagAppleBlock bit.
8677 RD = buildImplicitRecord(Name: "__block_descriptor");
8678 RD->startDefinition();
8679
8680 QualType FieldTypes[] = {
8681 UnsignedLongTy,
8682 UnsignedLongTy,
8683 };
8684
8685 static const char *const FieldNames[] = {
8686 "reserved",
8687 "Size"
8688 };
8689
8690 for (size_t i = 0; i < 2; ++i) {
8691 FieldDecl *Field = FieldDecl::Create(
8692 C: *this, DC: RD, StartLoc: SourceLocation(), IdLoc: SourceLocation(),
8693 Id: &Idents.get(Name: FieldNames[i]), T: FieldTypes[i], /*TInfo=*/nullptr,
8694 /*BitWidth=*/BW: nullptr, /*Mutable=*/false, InitStyle: ICIS_NoInit);
8695 Field->setAccess(AS_public);
8696 RD->addDecl(D: Field);
8697 }
8698
8699 RD->completeDefinition();
8700
8701 BlockDescriptorType = RD;
8702
8703 return getCanonicalTagType(TD: BlockDescriptorType);
8704}
8705
8706QualType ASTContext::getBlockDescriptorExtendedType() const {
8707 if (BlockDescriptorExtendedType)
8708 return getCanonicalTagType(TD: BlockDescriptorExtendedType);
8709
8710 RecordDecl *RD;
8711 // FIXME: Needs the FlagAppleBlock bit.
8712 RD = buildImplicitRecord(Name: "__block_descriptor_withcopydispose");
8713 RD->startDefinition();
8714
8715 QualType FieldTypes[] = {
8716 UnsignedLongTy,
8717 UnsignedLongTy,
8718 getPointerType(T: VoidPtrTy),
8719 getPointerType(T: VoidPtrTy)
8720 };
8721
8722 static const char *const FieldNames[] = {
8723 "reserved",
8724 "Size",
8725 "CopyFuncPtr",
8726 "DestroyFuncPtr"
8727 };
8728
8729 for (size_t i = 0; i < 4; ++i) {
8730 FieldDecl *Field = FieldDecl::Create(
8731 C: *this, DC: RD, StartLoc: SourceLocation(), IdLoc: SourceLocation(),
8732 Id: &Idents.get(Name: FieldNames[i]), T: FieldTypes[i], /*TInfo=*/nullptr,
8733 /*BitWidth=*/BW: nullptr,
8734 /*Mutable=*/false, InitStyle: ICIS_NoInit);
8735 Field->setAccess(AS_public);
8736 RD->addDecl(D: Field);
8737 }
8738
8739 RD->completeDefinition();
8740
8741 BlockDescriptorExtendedType = RD;
8742 return getCanonicalTagType(TD: BlockDescriptorExtendedType);
8743}
8744
8745OpenCLTypeKind ASTContext::getOpenCLTypeKind(const Type *T) const {
8746 const auto *BT = dyn_cast<BuiltinType>(Val: T);
8747
8748 if (!BT) {
8749 if (isa<PipeType>(Val: T))
8750 return OCLTK_Pipe;
8751
8752 return OCLTK_Default;
8753 }
8754
8755 switch (BT->getKind()) {
8756#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
8757 case BuiltinType::Id: \
8758 return OCLTK_Image;
8759#include "clang/Basic/OpenCLImageTypes.def"
8760
8761 case BuiltinType::OCLClkEvent:
8762 return OCLTK_ClkEvent;
8763
8764 case BuiltinType::OCLEvent:
8765 return OCLTK_Event;
8766
8767 case BuiltinType::OCLQueue:
8768 return OCLTK_Queue;
8769
8770 case BuiltinType::OCLReserveID:
8771 return OCLTK_ReserveID;
8772
8773 case BuiltinType::OCLSampler:
8774 return OCLTK_Sampler;
8775
8776 default:
8777 return OCLTK_Default;
8778 }
8779}
8780
8781LangAS ASTContext::getOpenCLTypeAddrSpace(const Type *T) const {
8782 return Target->getOpenCLTypeAddrSpace(TK: getOpenCLTypeKind(T));
8783}
8784
8785/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
8786/// requires copy/dispose. Note that this must match the logic
8787/// in buildByrefHelpers.
8788bool ASTContext::BlockRequiresCopying(QualType Ty,
8789 const VarDecl *D) {
8790 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
8791 const Expr *copyExpr = getBlockVarCopyInit(VD: D).getCopyExpr();
8792 if (!copyExpr && record->hasTrivialDestructor()) return false;
8793
8794 return true;
8795 }
8796
8797 if (Ty.hasAddressDiscriminatedPointerAuth())
8798 return true;
8799
8800 // The block needs copy/destroy helpers if Ty is non-trivial to destructively
8801 // move or destroy.
8802 if (Ty.isNonTrivialToPrimitiveDestructiveMove() || Ty.isDestructedType())
8803 return true;
8804
8805 if (!Ty->isObjCRetainableType()) return false;
8806
8807 Qualifiers qs = Ty.getQualifiers();
8808
8809 // If we have lifetime, that dominates.
8810 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
8811 switch (lifetime) {
8812 case Qualifiers::OCL_None: llvm_unreachable("impossible");
8813
8814 // These are just bits as far as the runtime is concerned.
8815 case Qualifiers::OCL_ExplicitNone:
8816 case Qualifiers::OCL_Autoreleasing:
8817 return false;
8818
8819 // These cases should have been taken care of when checking the type's
8820 // non-triviality.
8821 case Qualifiers::OCL_Weak:
8822 case Qualifiers::OCL_Strong:
8823 llvm_unreachable("impossible");
8824 }
8825 llvm_unreachable("fell out of lifetime switch!");
8826 }
8827 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
8828 Ty->isObjCObjectPointerType());
8829}
8830
8831bool ASTContext::getByrefLifetime(QualType Ty,
8832 Qualifiers::ObjCLifetime &LifeTime,
8833 bool &HasByrefExtendedLayout) const {
8834 if (!getLangOpts().ObjC ||
8835 getLangOpts().getGC() != LangOptions::NonGC)
8836 return false;
8837
8838 HasByrefExtendedLayout = false;
8839 if (Ty->isRecordType()) {
8840 HasByrefExtendedLayout = true;
8841 LifeTime = Qualifiers::OCL_None;
8842 } else if ((LifeTime = Ty.getObjCLifetime())) {
8843 // Honor the ARC qualifiers.
8844 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
8845 // The MRR rule.
8846 LifeTime = Qualifiers::OCL_ExplicitNone;
8847 } else {
8848 LifeTime = Qualifiers::OCL_None;
8849 }
8850 return true;
8851}
8852
8853CanQualType ASTContext::getNSUIntegerType() const {
8854 assert(Target && "Expected target to be initialized");
8855 const llvm::Triple &T = Target->getTriple();
8856 // Windows is LLP64 rather than LP64
8857 if (T.isOSWindows() && T.isArch64Bit())
8858 return UnsignedLongLongTy;
8859 return UnsignedLongTy;
8860}
8861
8862CanQualType ASTContext::getNSIntegerType() const {
8863 assert(Target && "Expected target to be initialized");
8864 const llvm::Triple &T = Target->getTriple();
8865 // Windows is LLP64 rather than LP64
8866 if (T.isOSWindows() && T.isArch64Bit())
8867 return LongLongTy;
8868 return LongTy;
8869}
8870
8871TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
8872 if (!ObjCInstanceTypeDecl)
8873 ObjCInstanceTypeDecl =
8874 buildImplicitTypedef(T: getObjCIdType(), Name: "instancetype");
8875 return ObjCInstanceTypeDecl;
8876}
8877
8878// This returns true if a type has been typedefed to BOOL:
8879// typedef <type> BOOL;
8880static bool isTypeTypedefedAsBOOL(QualType T) {
8881 if (const auto *TT = dyn_cast<TypedefType>(Val&: T))
8882 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
8883 return II->isStr(Str: "BOOL");
8884
8885 return false;
8886}
8887
8888/// getObjCEncodingTypeSize returns size of type for objective-c encoding
8889/// purpose.
8890CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
8891 if (!type->isIncompleteArrayType() && type->isIncompleteType())
8892 return CharUnits::Zero();
8893
8894 CharUnits sz = getTypeSizeInChars(T: type);
8895
8896 // Make all integer and enum types at least as large as an int
8897 if (sz.isPositive() && type->isIntegralOrEnumerationType())
8898 sz = std::max(a: sz, b: getTypeSizeInChars(T: IntTy));
8899 // Treat arrays as pointers, since that's how they're passed in.
8900 else if (type->isArrayType())
8901 sz = getTypeSizeInChars(T: VoidPtrTy);
8902 return sz;
8903}
8904
8905bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
8906 return getTargetInfo().getCXXABI().isMicrosoft() &&
8907 VD->isStaticDataMember() &&
8908 VD->getType()->isIntegralOrEnumerationType() &&
8909 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
8910}
8911
8912ASTContext::InlineVariableDefinitionKind
8913ASTContext::getInlineVariableDefinitionKind(const VarDecl *VD) const {
8914 if (!VD->isInline())
8915 return InlineVariableDefinitionKind::None;
8916
8917 // In almost all cases, it's a weak definition.
8918 auto *First = VD->getFirstDecl();
8919 if (First->isInlineSpecified() || !First->isStaticDataMember())
8920 return InlineVariableDefinitionKind::Weak;
8921
8922 // If there's a file-context declaration in this translation unit, it's a
8923 // non-discardable definition.
8924 for (auto *D : VD->redecls())
8925 if (D->getLexicalDeclContext()->isFileContext() &&
8926 !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr()))
8927 return InlineVariableDefinitionKind::Strong;
8928
8929 // If we've not seen one yet, we don't know.
8930 return InlineVariableDefinitionKind::WeakUnknown;
8931}
8932
8933static std::string charUnitsToString(CharUnits CU) {
8934 return llvm::itostr(X: CU.getQuantity());
8935}
8936
8937/// getObjCEncodingForBlock - Return the encoded type for this block
8938/// declaration.
8939std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
8940 std::string S;
8941
8942 const BlockDecl *Decl = Expr->getBlockDecl();
8943 QualType BlockTy =
8944 Expr->getType()->castAs<BlockPointerType>()->getPointeeType();
8945 QualType BlockReturnTy = BlockTy->castAs<FunctionType>()->getReturnType();
8946 // Encode result type.
8947 if (getLangOpts().EncodeExtendedBlockSig)
8948 getObjCEncodingForMethodParameter(QT: Decl::OBJC_TQ_None, T: BlockReturnTy, S,
8949 Extended: true /*Extended*/);
8950 else
8951 getObjCEncodingForType(T: BlockReturnTy, S);
8952 // Compute size of all parameters.
8953 // Start with computing size of a pointer in number of bytes.
8954 // FIXME: There might(should) be a better way of doing this computation!
8955 CharUnits PtrSize = getTypeSizeInChars(T: VoidPtrTy);
8956 CharUnits ParmOffset = PtrSize;
8957 for (auto *PI : Decl->parameters()) {
8958 QualType PType = PI->getType();
8959 CharUnits sz = getObjCEncodingTypeSize(type: PType);
8960 if (sz.isZero())
8961 continue;
8962 assert(sz.isPositive() && "BlockExpr - Incomplete param type");
8963 ParmOffset += sz;
8964 }
8965 // Size of the argument frame
8966 S += charUnitsToString(CU: ParmOffset);
8967 // Block pointer and offset.
8968 S += "@?0";
8969
8970 // Argument types.
8971 ParmOffset = PtrSize;
8972 for (auto *PVDecl : Decl->parameters()) {
8973 QualType PType = PVDecl->getOriginalType();
8974 if (const auto *AT =
8975 dyn_cast<ArrayType>(Val: PType->getCanonicalTypeInternal())) {
8976 // Use array's original type only if it has known number of
8977 // elements.
8978 if (!isa<ConstantArrayType>(Val: AT))
8979 PType = PVDecl->getType();
8980 } else if (PType->isFunctionType())
8981 PType = PVDecl->getType();
8982 if (getLangOpts().EncodeExtendedBlockSig)
8983 getObjCEncodingForMethodParameter(QT: Decl::OBJC_TQ_None, T: PType,
8984 S, Extended: true /*Extended*/);
8985 else
8986 getObjCEncodingForType(T: PType, S);
8987 S += charUnitsToString(CU: ParmOffset);
8988 ParmOffset += getObjCEncodingTypeSize(type: PType);
8989 }
8990
8991 return S;
8992}
8993
8994std::string
8995ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const {
8996 std::string S;
8997 // Encode result type.
8998 getObjCEncodingForType(T: Decl->getReturnType(), S);
8999 CharUnits ParmOffset;
9000 // Compute size of all parameters.
9001 for (auto *PI : Decl->parameters()) {
9002 QualType PType = PI->getType();
9003 CharUnits sz = getObjCEncodingTypeSize(type: PType);
9004 if (sz.isZero())
9005 continue;
9006
9007 assert(sz.isPositive() &&
9008 "getObjCEncodingForFunctionDecl - Incomplete param type");
9009 ParmOffset += sz;
9010 }
9011 S += charUnitsToString(CU: ParmOffset);
9012 ParmOffset = CharUnits::Zero();
9013
9014 // Argument types.
9015 for (auto *PVDecl : Decl->parameters()) {
9016 QualType PType = PVDecl->getOriginalType();
9017 if (const auto *AT =
9018 dyn_cast<ArrayType>(Val: PType->getCanonicalTypeInternal())) {
9019 // Use array's original type only if it has known number of
9020 // elements.
9021 if (!isa<ConstantArrayType>(Val: AT))
9022 PType = PVDecl->getType();
9023 } else if (PType->isFunctionType())
9024 PType = PVDecl->getType();
9025 getObjCEncodingForType(T: PType, S);
9026 S += charUnitsToString(CU: ParmOffset);
9027 ParmOffset += getObjCEncodingTypeSize(type: PType);
9028 }
9029
9030 return S;
9031}
9032
9033/// getObjCEncodingForMethodParameter - Return the encoded type for a single
9034/// method parameter or return type. If Extended, include class names and
9035/// block object types.
9036void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
9037 QualType T, std::string& S,
9038 bool Extended) const {
9039 // Encode type qualifier, 'in', 'inout', etc. for the parameter.
9040 getObjCEncodingForTypeQualifier(QT, S);
9041 // Encode parameter type.
9042 ObjCEncOptions Options = ObjCEncOptions()
9043 .setExpandPointedToStructures()
9044 .setExpandStructures()
9045 .setIsOutermostType();
9046 if (Extended)
9047 Options.setEncodeBlockParameters().setEncodeClassNames();
9048 getObjCEncodingForTypeImpl(t: T, S, Options, /*Field=*/nullptr);
9049}
9050
9051/// getObjCEncodingForMethodDecl - Return the encoded type for this method
9052/// declaration.
9053std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
9054 bool Extended) const {
9055 // FIXME: This is not very efficient.
9056 // Encode return type.
9057 std::string S;
9058 getObjCEncodingForMethodParameter(QT: Decl->getObjCDeclQualifier(),
9059 T: Decl->getReturnType(), S, Extended);
9060 // Compute size of all parameters.
9061 // Start with computing size of a pointer in number of bytes.
9062 // FIXME: There might(should) be a better way of doing this computation!
9063 CharUnits PtrSize = getTypeSizeInChars(T: VoidPtrTy);
9064 // The first two arguments (self and _cmd) are pointers; account for
9065 // their size.
9066 CharUnits ParmOffset = 2 * PtrSize;
9067 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
9068 E = Decl->sel_param_end(); PI != E; ++PI) {
9069 QualType PType = (*PI)->getType();
9070 CharUnits sz = getObjCEncodingTypeSize(type: PType);
9071 if (sz.isZero())
9072 continue;
9073
9074 assert(sz.isPositive() &&
9075 "getObjCEncodingForMethodDecl - Incomplete param type");
9076 ParmOffset += sz;
9077 }
9078 S += charUnitsToString(CU: ParmOffset);
9079 S += "@0:";
9080 S += charUnitsToString(CU: PtrSize);
9081
9082 // Argument types.
9083 ParmOffset = 2 * PtrSize;
9084 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
9085 E = Decl->sel_param_end(); PI != E; ++PI) {
9086 const ParmVarDecl *PVDecl = *PI;
9087 QualType PType = PVDecl->getOriginalType();
9088 if (const auto *AT =
9089 dyn_cast<ArrayType>(Val: PType->getCanonicalTypeInternal())) {
9090 // Use array's original type only if it has known number of
9091 // elements.
9092 if (!isa<ConstantArrayType>(Val: AT))
9093 PType = PVDecl->getType();
9094 } else if (PType->isFunctionType())
9095 PType = PVDecl->getType();
9096 getObjCEncodingForMethodParameter(QT: PVDecl->getObjCDeclQualifier(),
9097 T: PType, S, Extended);
9098 S += charUnitsToString(CU: ParmOffset);
9099 ParmOffset += getObjCEncodingTypeSize(type: PType);
9100 }
9101
9102 return S;
9103}
9104
9105ObjCPropertyImplDecl *
9106ASTContext::getObjCPropertyImplDeclForPropertyDecl(
9107 const ObjCPropertyDecl *PD,
9108 const Decl *Container) const {
9109 if (!Container)
9110 return nullptr;
9111 if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Val: Container)) {
9112 for (auto *PID : CID->property_impls())
9113 if (PID->getPropertyDecl() == PD)
9114 return PID;
9115 } else {
9116 const auto *OID = cast<ObjCImplementationDecl>(Val: Container);
9117 for (auto *PID : OID->property_impls())
9118 if (PID->getPropertyDecl() == PD)
9119 return PID;
9120 }
9121 return nullptr;
9122}
9123
9124/// getObjCEncodingForPropertyDecl - Return the encoded type for this
9125/// property declaration. If non-NULL, Container must be either an
9126/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
9127/// NULL when getting encodings for protocol properties.
9128/// Property attributes are stored as a comma-delimited C string. The simple
9129/// attributes readonly and bycopy are encoded as single characters. The
9130/// parametrized attributes, getter=name, setter=name, and ivar=name, are
9131/// encoded as single characters, followed by an identifier. Property types
9132/// are also encoded as a parametrized attribute. The characters used to encode
9133/// these attributes are defined by the following enumeration:
9134/// @code
9135/// enum PropertyAttributes {
9136/// kPropertyReadOnly = 'R', // property is read-only.
9137/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
9138/// kPropertyByref = '&', // property is a reference to the value last assigned
9139/// kPropertyDynamic = 'D', // property is dynamic
9140/// kPropertyGetter = 'G', // followed by getter selector name
9141/// kPropertySetter = 'S', // followed by setter selector name
9142/// kPropertyInstanceVariable = 'V' // followed by instance variable name
9143/// kPropertyType = 'T' // followed by old-style type encoding.
9144/// kPropertyWeak = 'W' // 'weak' property
9145/// kPropertyStrong = 'P' // property GC'able
9146/// kPropertyNonAtomic = 'N' // property non-atomic
9147/// kPropertyOptional = '?' // property optional
9148/// };
9149/// @endcode
9150std::string
9151ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
9152 const Decl *Container) const {
9153 // Collect information from the property implementation decl(s).
9154 bool Dynamic = false;
9155 ObjCPropertyImplDecl *SynthesizePID = nullptr;
9156
9157 if (ObjCPropertyImplDecl *PropertyImpDecl =
9158 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
9159 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
9160 Dynamic = true;
9161 else
9162 SynthesizePID = PropertyImpDecl;
9163 }
9164
9165 // FIXME: This is not very efficient.
9166 std::string S = "T";
9167
9168 // Encode result type.
9169 // GCC has some special rules regarding encoding of properties which
9170 // closely resembles encoding of ivars.
9171 getObjCEncodingForPropertyType(T: PD->getType(), S);
9172
9173 if (PD->isOptional())
9174 S += ",?";
9175
9176 if (PD->isReadOnly()) {
9177 S += ",R";
9178 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_copy)
9179 S += ",C";
9180 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_retain)
9181 S += ",&";
9182 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_weak)
9183 S += ",W";
9184 } else {
9185 switch (PD->getSetterKind()) {
9186 case ObjCPropertyDecl::Assign: break;
9187 case ObjCPropertyDecl::Copy: S += ",C"; break;
9188 case ObjCPropertyDecl::Retain: S += ",&"; break;
9189 case ObjCPropertyDecl::Weak: S += ",W"; break;
9190 }
9191 }
9192
9193 // It really isn't clear at all what this means, since properties
9194 // are "dynamic by default".
9195 if (Dynamic)
9196 S += ",D";
9197
9198 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_nonatomic)
9199 S += ",N";
9200
9201 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_getter) {
9202 S += ",G";
9203 S += PD->getGetterName().getAsString();
9204 }
9205
9206 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_setter) {
9207 S += ",S";
9208 S += PD->getSetterName().getAsString();
9209 }
9210
9211 if (SynthesizePID) {
9212 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
9213 S += ",V";
9214 S += OID->getNameAsString();
9215 }
9216
9217 // FIXME: OBJCGC: weak & strong
9218 return S;
9219}
9220
9221/// getLegacyIntegralTypeEncoding -
9222/// Another legacy compatibility encoding: 32-bit longs are encoded as
9223/// 'l' or 'L' , but not always. For typedefs, we need to use
9224/// 'i' or 'I' instead if encoding a struct field, or a pointer!
9225void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
9226 if (PointeeTy->getAs<TypedefType>()) {
9227 if (const auto *BT = PointeeTy->getAs<BuiltinType>()) {
9228 if (BT->getKind() == BuiltinType::ULong && getIntWidth(T: PointeeTy) == 32)
9229 PointeeTy = UnsignedIntTy;
9230 else
9231 if (BT->getKind() == BuiltinType::Long && getIntWidth(T: PointeeTy) == 32)
9232 PointeeTy = IntTy;
9233 }
9234 }
9235}
9236
9237void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
9238 const FieldDecl *Field,
9239 QualType *NotEncodedT) const {
9240 // We follow the behavior of gcc, expanding structures which are
9241 // directly pointed to, and expanding embedded structures. Note that
9242 // these rules are sufficient to prevent recursive encoding of the
9243 // same type.
9244 getObjCEncodingForTypeImpl(t: T, S,
9245 Options: ObjCEncOptions()
9246 .setExpandPointedToStructures()
9247 .setExpandStructures()
9248 .setIsOutermostType(),
9249 Field, NotEncodedT);
9250}
9251
9252void ASTContext::getObjCEncodingForPropertyType(QualType T,
9253 std::string& S) const {
9254 // Encode result type.
9255 // GCC has some special rules regarding encoding of properties which
9256 // closely resembles encoding of ivars.
9257 getObjCEncodingForTypeImpl(t: T, S,
9258 Options: ObjCEncOptions()
9259 .setExpandPointedToStructures()
9260 .setExpandStructures()
9261 .setIsOutermostType()
9262 .setEncodingProperty(),
9263 /*Field=*/nullptr);
9264}
9265
9266static char getObjCEncodingForPrimitiveType(const ASTContext *C,
9267 const BuiltinType *BT) {
9268 BuiltinType::Kind kind = BT->getKind();
9269 switch (kind) {
9270 case BuiltinType::Void: return 'v';
9271 case BuiltinType::Bool: return 'B';
9272 case BuiltinType::Char8:
9273 case BuiltinType::Char_U:
9274 case BuiltinType::UChar: return 'C';
9275 case BuiltinType::Char16:
9276 case BuiltinType::UShort: return 'S';
9277 case BuiltinType::Char32:
9278 case BuiltinType::UInt: return 'I';
9279 case BuiltinType::ULong:
9280 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
9281 case BuiltinType::UInt128: return 'T';
9282 case BuiltinType::ULongLong: return 'Q';
9283 case BuiltinType::Char_S:
9284 case BuiltinType::SChar: return 'c';
9285 case BuiltinType::Short: return 's';
9286 case BuiltinType::WChar_S:
9287 case BuiltinType::WChar_U:
9288 case BuiltinType::Int: return 'i';
9289 case BuiltinType::Long:
9290 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
9291 case BuiltinType::LongLong: return 'q';
9292 case BuiltinType::Int128: return 't';
9293 case BuiltinType::Float: return 'f';
9294 case BuiltinType::Double: return 'd';
9295 case BuiltinType::LongDouble: return 'D';
9296 case BuiltinType::NullPtr: return '*'; // like char*
9297
9298 case BuiltinType::BFloat16:
9299 case BuiltinType::Float16:
9300 case BuiltinType::Float128:
9301 case BuiltinType::Ibm128:
9302 case BuiltinType::Half:
9303 case BuiltinType::ShortAccum:
9304 case BuiltinType::Accum:
9305 case BuiltinType::LongAccum:
9306 case BuiltinType::UShortAccum:
9307 case BuiltinType::UAccum:
9308 case BuiltinType::ULongAccum:
9309 case BuiltinType::ShortFract:
9310 case BuiltinType::Fract:
9311 case BuiltinType::LongFract:
9312 case BuiltinType::UShortFract:
9313 case BuiltinType::UFract:
9314 case BuiltinType::ULongFract:
9315 case BuiltinType::SatShortAccum:
9316 case BuiltinType::SatAccum:
9317 case BuiltinType::SatLongAccum:
9318 case BuiltinType::SatUShortAccum:
9319 case BuiltinType::SatUAccum:
9320 case BuiltinType::SatULongAccum:
9321 case BuiltinType::SatShortFract:
9322 case BuiltinType::SatFract:
9323 case BuiltinType::SatLongFract:
9324 case BuiltinType::SatUShortFract:
9325 case BuiltinType::SatUFract:
9326 case BuiltinType::SatULongFract:
9327 // FIXME: potentially need @encodes for these!
9328 return ' ';
9329
9330#define SVE_TYPE(Name, Id, SingletonId) \
9331 case BuiltinType::Id:
9332#include "clang/Basic/AArch64ACLETypes.def"
9333#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9334#include "clang/Basic/RISCVVTypes.def"
9335#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9336#include "clang/Basic/WebAssemblyReferenceTypes.def"
9337#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
9338#include "clang/Basic/AMDGPUTypes.def"
9339#define SPIRV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9340#include "clang/Basic/SPIRVTypes.def"
9341 {
9342 DiagnosticsEngine &Diags = C->getDiagnostics();
9343 Diags.Report(DiagID: diag::err_unsupported_objc_primitive_encoding)
9344 << QualType(BT, 0);
9345 return ' ';
9346 }
9347
9348 case BuiltinType::ObjCId:
9349 case BuiltinType::ObjCClass:
9350 case BuiltinType::ObjCSel:
9351 llvm_unreachable("@encoding ObjC primitive type");
9352
9353 // OpenCL and placeholder types don't need @encodings.
9354#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
9355 case BuiltinType::Id:
9356#include "clang/Basic/OpenCLImageTypes.def"
9357#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
9358 case BuiltinType::Id:
9359#include "clang/Basic/OpenCLExtensionTypes.def"
9360 case BuiltinType::OCLEvent:
9361 case BuiltinType::OCLClkEvent:
9362 case BuiltinType::OCLQueue:
9363 case BuiltinType::OCLReserveID:
9364 case BuiltinType::OCLSampler:
9365 case BuiltinType::Dependent:
9366 case BuiltinType::MetaInfo:
9367#define PPC_VECTOR_TYPE(Name, Id, Size) \
9368 case BuiltinType::Id:
9369#include "clang/Basic/PPCTypes.def"
9370#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9371#include "clang/Basic/HLSLIntangibleTypes.def"
9372#define HLSL_PACKED_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9373#include "clang/Basic/HLSLPackedTypes.def"
9374#define BUILTIN_TYPE(KIND, ID)
9375#define PLACEHOLDER_TYPE(KIND, ID) \
9376 case BuiltinType::KIND:
9377#include "clang/AST/BuiltinTypes.def"
9378 llvm_unreachable("invalid builtin type for @encode");
9379 }
9380 llvm_unreachable("invalid BuiltinType::Kind value");
9381}
9382
9383static char ObjCEncodingForEnumDecl(const ASTContext *C, const EnumDecl *ED) {
9384 EnumDecl *Enum = ED->getDefinitionOrSelf();
9385
9386 // The encoding of an non-fixed enum type is always 'i', regardless of size.
9387 if (!Enum->isFixed())
9388 return 'i';
9389
9390 // The encoding of a fixed enum type matches its fixed underlying type.
9391 const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>();
9392 return getObjCEncodingForPrimitiveType(C, BT);
9393}
9394
9395static void EncodeBitField(const ASTContext *Ctx, std::string& S,
9396 QualType T, const FieldDecl *FD) {
9397 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
9398 S += 'b';
9399 // The NeXT runtime encodes bit fields as b followed by the number of bits.
9400 // The GNU runtime requires more information; bitfields are encoded as b,
9401 // then the offset (in bits) of the first element, then the type of the
9402 // bitfield, then the size in bits. For example, in this structure:
9403 //
9404 // struct
9405 // {
9406 // int integer;
9407 // int flags:2;
9408 // };
9409 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
9410 // runtime, but b32i2 for the GNU runtime. The reason for this extra
9411 // information is not especially sensible, but we're stuck with it for
9412 // compatibility with GCC, although providing it breaks anything that
9413 // actually uses runtime introspection and wants to work on both runtimes...
9414 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
9415 uint64_t Offset;
9416
9417 if (const auto *IVD = dyn_cast<ObjCIvarDecl>(Val: FD)) {
9418 Offset = Ctx->lookupFieldBitOffset(OID: IVD->getContainingInterface(), Ivar: IVD);
9419 } else {
9420 const RecordDecl *RD = FD->getParent();
9421 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(D: RD);
9422 Offset = RL.getFieldOffset(FieldNo: FD->getFieldIndex());
9423 }
9424
9425 S += llvm::utostr(X: Offset);
9426
9427 if (const auto *ET = T->getAsCanonical<EnumType>())
9428 S += ObjCEncodingForEnumDecl(C: Ctx, ED: ET->getDecl());
9429 else {
9430 const auto *BT = T->castAs<BuiltinType>();
9431 S += getObjCEncodingForPrimitiveType(C: Ctx, BT);
9432 }
9433 }
9434 S += llvm::utostr(X: FD->getBitWidthValue());
9435}
9436
9437// Helper function for determining whether the encoded type string would include
9438// a template specialization type.
9439static bool hasTemplateSpecializationInEncodedString(const Type *T,
9440 bool VisitBasesAndFields) {
9441 T = T->getBaseElementTypeUnsafe();
9442
9443 if (auto *PT = T->getAs<PointerType>())
9444 return hasTemplateSpecializationInEncodedString(
9445 T: PT->getPointeeType().getTypePtr(), VisitBasesAndFields: false);
9446
9447 auto *CXXRD = T->getAsCXXRecordDecl();
9448
9449 if (!CXXRD)
9450 return false;
9451
9452 if (isa<ClassTemplateSpecializationDecl>(Val: CXXRD))
9453 return true;
9454
9455 if (!CXXRD->hasDefinition() || !VisitBasesAndFields)
9456 return false;
9457
9458 for (const auto &B : CXXRD->bases())
9459 if (hasTemplateSpecializationInEncodedString(T: B.getType().getTypePtr(),
9460 VisitBasesAndFields: true))
9461 return true;
9462
9463 for (auto *FD : CXXRD->fields())
9464 if (hasTemplateSpecializationInEncodedString(T: FD->getType().getTypePtr(),
9465 VisitBasesAndFields: true))
9466 return true;
9467
9468 return false;
9469}
9470
9471// FIXME: Use SmallString for accumulating string.
9472void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S,
9473 const ObjCEncOptions Options,
9474 const FieldDecl *FD,
9475 QualType *NotEncodedT) const {
9476 CanQualType CT = getCanonicalType(T);
9477 switch (CT->getTypeClass()) {
9478 case Type::Builtin:
9479 case Type::Enum:
9480 if (FD && FD->isBitField())
9481 return EncodeBitField(Ctx: this, S, T, FD);
9482 if (const auto *BT = dyn_cast<BuiltinType>(Val&: CT))
9483 S += getObjCEncodingForPrimitiveType(C: this, BT);
9484 else
9485 S += ObjCEncodingForEnumDecl(C: this, ED: cast<EnumType>(Val&: CT)->getDecl());
9486 return;
9487
9488 case Type::Complex:
9489 S += 'j';
9490 getObjCEncodingForTypeImpl(T: T->castAs<ComplexType>()->getElementType(), S,
9491 Options: ObjCEncOptions(),
9492 /*Field=*/FD: nullptr);
9493 return;
9494
9495 case Type::Atomic:
9496 S += 'A';
9497 getObjCEncodingForTypeImpl(T: T->castAs<AtomicType>()->getValueType(), S,
9498 Options: ObjCEncOptions(),
9499 /*Field=*/FD: nullptr);
9500 return;
9501
9502 // encoding for pointer or reference types.
9503 case Type::Pointer:
9504 case Type::LValueReference:
9505 case Type::RValueReference: {
9506 QualType PointeeTy;
9507 if (isa<PointerType>(Val: CT)) {
9508 const auto *PT = T->castAs<PointerType>();
9509 if (PT->isObjCSelType()) {
9510 S += ':';
9511 return;
9512 }
9513 PointeeTy = PT->getPointeeType();
9514 } else {
9515 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
9516 }
9517
9518 bool isReadOnly = false;
9519 // For historical/compatibility reasons, the read-only qualifier of the
9520 // pointee gets emitted _before_ the '^'. The read-only qualifier of
9521 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
9522 // Also, do not emit the 'r' for anything but the outermost type!
9523 if (T->getAs<TypedefType>()) {
9524 if (Options.IsOutermostType() && T.isConstQualified()) {
9525 isReadOnly = true;
9526 S += 'r';
9527 }
9528 } else if (Options.IsOutermostType()) {
9529 QualType P = PointeeTy;
9530 while (auto PT = P->getAs<PointerType>())
9531 P = PT->getPointeeType();
9532 if (P.isConstQualified()) {
9533 isReadOnly = true;
9534 S += 'r';
9535 }
9536 }
9537 if (isReadOnly) {
9538 // Another legacy compatibility encoding. Some ObjC qualifier and type
9539 // combinations need to be rearranged.
9540 // Rewrite "in const" from "nr" to "rn"
9541 if (StringRef(S).ends_with(Suffix: "nr"))
9542 S.replace(i1: S.end()-2, i2: S.end(), s: "rn");
9543 }
9544
9545 if (PointeeTy->isCharType()) {
9546 // char pointer types should be encoded as '*' unless it is a
9547 // type that has been typedef'd to 'BOOL'.
9548 if (!isTypeTypedefedAsBOOL(T: PointeeTy)) {
9549 S += '*';
9550 return;
9551 }
9552 } else if (const auto *RTy = PointeeTy->getAsCanonical<RecordType>()) {
9553 const IdentifierInfo *II = RTy->getDecl()->getIdentifier();
9554 // GCC binary compat: Need to convert "struct objc_class *" to "#".
9555 if (II == &Idents.get(Name: "objc_class")) {
9556 S += '#';
9557 return;
9558 }
9559 // GCC binary compat: Need to convert "struct objc_object *" to "@".
9560 if (II == &Idents.get(Name: "objc_object")) {
9561 S += '@';
9562 return;
9563 }
9564 // If the encoded string for the class includes template names, just emit
9565 // "^v" for pointers to the class.
9566 if (getLangOpts().CPlusPlus &&
9567 (!getLangOpts().EncodeCXXClassTemplateSpec &&
9568 hasTemplateSpecializationInEncodedString(
9569 T: RTy, VisitBasesAndFields: Options.ExpandPointedToStructures()))) {
9570 S += "^v";
9571 return;
9572 }
9573 // fall through...
9574 }
9575 S += '^';
9576 getLegacyIntegralTypeEncoding(PointeeTy);
9577
9578 ObjCEncOptions NewOptions;
9579 if (Options.ExpandPointedToStructures())
9580 NewOptions.setExpandStructures();
9581 getObjCEncodingForTypeImpl(T: PointeeTy, S, Options: NewOptions,
9582 /*Field=*/FD: nullptr, NotEncodedT);
9583 return;
9584 }
9585
9586 case Type::ConstantArray:
9587 case Type::IncompleteArray:
9588 case Type::VariableArray: {
9589 const auto *AT = cast<ArrayType>(Val&: CT);
9590
9591 if (isa<IncompleteArrayType>(Val: AT) && !Options.IsStructField()) {
9592 // Incomplete arrays are encoded as a pointer to the array element.
9593 S += '^';
9594
9595 getObjCEncodingForTypeImpl(
9596 T: AT->getElementType(), S,
9597 Options: Options.keepingOnly(Mask: ObjCEncOptions().setExpandStructures()), FD);
9598 } else {
9599 S += '[';
9600
9601 if (const auto *CAT = dyn_cast<ConstantArrayType>(Val: AT))
9602 S += llvm::utostr(X: CAT->getZExtSize());
9603 else {
9604 //Variable length arrays are encoded as a regular array with 0 elements.
9605 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
9606 "Unknown array type!");
9607 S += '0';
9608 }
9609
9610 getObjCEncodingForTypeImpl(
9611 T: AT->getElementType(), S,
9612 Options: Options.keepingOnly(Mask: ObjCEncOptions().setExpandStructures()), FD,
9613 NotEncodedT);
9614 S += ']';
9615 }
9616 return;
9617 }
9618
9619 case Type::FunctionNoProto:
9620 case Type::FunctionProto:
9621 S += '?';
9622 return;
9623
9624 case Type::Record: {
9625 RecordDecl *RDecl = cast<RecordType>(Val&: CT)->getDecl();
9626 S += RDecl->isUnion() ? '(' : '{';
9627 // Anonymous structures print as '?'
9628 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
9629 S += II->getName();
9630 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(Val: RDecl)) {
9631 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
9632 llvm::raw_string_ostream OS(S);
9633 printTemplateArgumentList(OS, Args: TemplateArgs.asArray(),
9634 Policy: getPrintingPolicy());
9635 }
9636 } else {
9637 S += '?';
9638 }
9639 if (Options.ExpandStructures()) {
9640 S += '=';
9641 if (!RDecl->isUnion()) {
9642 getObjCEncodingForStructureImpl(RD: RDecl, S, Field: FD, includeVBases: true, NotEncodedT);
9643 } else {
9644 for (const auto *Field : RDecl->fields()) {
9645 if (FD) {
9646 S += '"';
9647 S += Field->getNameAsString();
9648 S += '"';
9649 }
9650
9651 // Special case bit-fields.
9652 if (Field->isBitField()) {
9653 getObjCEncodingForTypeImpl(T: Field->getType(), S,
9654 Options: ObjCEncOptions().setExpandStructures(),
9655 FD: Field);
9656 } else {
9657 QualType qt = Field->getType();
9658 getLegacyIntegralTypeEncoding(PointeeTy&: qt);
9659 getObjCEncodingForTypeImpl(
9660 T: qt, S,
9661 Options: ObjCEncOptions().setExpandStructures().setIsStructField(), FD,
9662 NotEncodedT);
9663 }
9664 }
9665 }
9666 }
9667 S += RDecl->isUnion() ? ')' : '}';
9668 return;
9669 }
9670
9671 case Type::BlockPointer: {
9672 const auto *BT = T->castAs<BlockPointerType>();
9673 S += "@?"; // Unlike a pointer-to-function, which is "^?".
9674 if (Options.EncodeBlockParameters()) {
9675 const auto *FT = BT->getPointeeType()->castAs<FunctionType>();
9676
9677 S += '<';
9678 // Block return type
9679 getObjCEncodingForTypeImpl(T: FT->getReturnType(), S,
9680 Options: Options.forComponentType(), FD, NotEncodedT);
9681 // Block self
9682 S += "@?";
9683 // Block parameters
9684 if (const auto *FPT = dyn_cast<FunctionProtoType>(Val: FT)) {
9685 for (const auto &I : FPT->param_types())
9686 getObjCEncodingForTypeImpl(T: I, S, Options: Options.forComponentType(), FD,
9687 NotEncodedT);
9688 }
9689 S += '>';
9690 }
9691 return;
9692 }
9693
9694 case Type::ObjCObject: {
9695 // hack to match legacy encoding of *id and *Class
9696 QualType Ty = getObjCObjectPointerType(ObjectT: CT);
9697 if (Ty->isObjCIdType()) {
9698 S += "{objc_object=}";
9699 return;
9700 }
9701 else if (Ty->isObjCClassType()) {
9702 S += "{objc_class=}";
9703 return;
9704 }
9705 // TODO: Double check to make sure this intentionally falls through.
9706 [[fallthrough]];
9707 }
9708
9709 case Type::ObjCInterface: {
9710 // Ignore protocol qualifiers when mangling at this level.
9711 // @encode(class_name)
9712 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
9713 S += '{';
9714 S += OI->getObjCRuntimeNameAsString();
9715 if (Options.ExpandStructures()) {
9716 S += '=';
9717 SmallVector<const ObjCIvarDecl*, 32> Ivars;
9718 DeepCollectObjCIvars(OI, leafClass: true, Ivars);
9719 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
9720 const FieldDecl *Field = Ivars[i];
9721 if (Field->isBitField())
9722 getObjCEncodingForTypeImpl(T: Field->getType(), S,
9723 Options: ObjCEncOptions().setExpandStructures(),
9724 FD: Field);
9725 else
9726 getObjCEncodingForTypeImpl(T: Field->getType(), S,
9727 Options: ObjCEncOptions().setExpandStructures(), FD,
9728 NotEncodedT);
9729 }
9730 }
9731 S += '}';
9732 return;
9733 }
9734
9735 case Type::ObjCObjectPointer: {
9736 const auto *OPT = T->castAs<ObjCObjectPointerType>();
9737 if (OPT->isObjCIdType()) {
9738 S += '@';
9739 return;
9740 }
9741
9742 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
9743 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
9744 // Since this is a binary compatibility issue, need to consult with
9745 // runtime folks. Fortunately, this is a *very* obscure construct.
9746 S += '#';
9747 return;
9748 }
9749
9750 if (OPT->isObjCQualifiedIdType()) {
9751 getObjCEncodingForTypeImpl(
9752 T: getObjCIdType(), S,
9753 Options: Options.keepingOnly(Mask: ObjCEncOptions()
9754 .setExpandPointedToStructures()
9755 .setExpandStructures()),
9756 FD);
9757 if (FD || Options.EncodingProperty() || Options.EncodeClassNames()) {
9758 // Note that we do extended encoding of protocol qualifier list
9759 // Only when doing ivar or property encoding.
9760 S += '"';
9761 for (const auto *I : OPT->quals()) {
9762 S += '<';
9763 S += I->getObjCRuntimeNameAsString();
9764 S += '>';
9765 }
9766 S += '"';
9767 }
9768 return;
9769 }
9770
9771 S += '@';
9772 if (OPT->getInterfaceDecl() &&
9773 (FD || Options.EncodingProperty() || Options.EncodeClassNames())) {
9774 S += '"';
9775 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
9776 for (const auto *I : OPT->quals()) {
9777 S += '<';
9778 S += I->getObjCRuntimeNameAsString();
9779 S += '>';
9780 }
9781 S += '"';
9782 }
9783 return;
9784 }
9785
9786 // gcc just blithely ignores member pointers.
9787 // FIXME: we should do better than that. 'M' is available.
9788 case Type::MemberPointer:
9789 // This matches gcc's encoding, even though technically it is insufficient.
9790 //FIXME. We should do a better job than gcc.
9791 case Type::Vector:
9792 case Type::ExtVector:
9793 // Until we have a coherent encoding of these three types, issue warning.
9794 if (NotEncodedT)
9795 *NotEncodedT = T;
9796 return;
9797
9798 case Type::ConstantMatrix:
9799 if (NotEncodedT)
9800 *NotEncodedT = T;
9801 return;
9802
9803 case Type::BitInt:
9804 if (NotEncodedT)
9805 *NotEncodedT = T;
9806 return;
9807
9808 // We could see an undeduced auto type here during error recovery.
9809 // Just ignore it.
9810 case Type::Auto:
9811 case Type::DeducedTemplateSpecialization:
9812 return;
9813
9814 case Type::HLSLAttributedResource:
9815 case Type::HLSLInlineSpirv:
9816 case Type::OverflowBehavior:
9817 llvm_unreachable("unexpected type");
9818
9819 case Type::ArrayParameter:
9820 case Type::Pipe:
9821#define ABSTRACT_TYPE(KIND, BASE)
9822#define TYPE(KIND, BASE)
9823#define DEPENDENT_TYPE(KIND, BASE) \
9824 case Type::KIND:
9825#define NON_CANONICAL_TYPE(KIND, BASE) \
9826 case Type::KIND:
9827#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
9828 case Type::KIND:
9829#include "clang/AST/TypeNodes.inc"
9830 llvm_unreachable("@encode for dependent type!");
9831 }
9832 llvm_unreachable("bad type kind!");
9833}
9834
9835void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
9836 std::string &S,
9837 const FieldDecl *FD,
9838 bool includeVBases,
9839 QualType *NotEncodedT) const {
9840 assert(RDecl && "Expected non-null RecordDecl");
9841 assert(!RDecl->isUnion() && "Should not be called for unions");
9842 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
9843 return;
9844
9845 const auto *CXXRec = dyn_cast<CXXRecordDecl>(Val: RDecl);
9846 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
9847 const ASTRecordLayout &layout = getASTRecordLayout(D: RDecl);
9848
9849 if (CXXRec) {
9850 for (const auto &BI : CXXRec->bases()) {
9851 if (!BI.isVirtual()) {
9852 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
9853 if (base->isEmpty())
9854 continue;
9855 uint64_t offs = toBits(CharSize: layout.getBaseClassOffset(Base: base));
9856 FieldOrBaseOffsets.insert(position: FieldOrBaseOffsets.upper_bound(x: offs),
9857 x: std::make_pair(x&: offs, y&: base));
9858 }
9859 }
9860 }
9861
9862 for (FieldDecl *Field : RDecl->fields()) {
9863 if (!Field->isZeroLengthBitField() && Field->isZeroSize(Ctx: *this))
9864 continue;
9865 uint64_t offs = layout.getFieldOffset(FieldNo: Field->getFieldIndex());
9866 FieldOrBaseOffsets.insert(position: FieldOrBaseOffsets.upper_bound(x: offs),
9867 x: std::make_pair(x&: offs, y&: Field));
9868 }
9869
9870 if (CXXRec && includeVBases) {
9871 for (const auto &BI : CXXRec->vbases()) {
9872 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
9873 if (base->isEmpty())
9874 continue;
9875 uint64_t offs = toBits(CharSize: layout.getVBaseClassOffset(VBase: base));
9876 if (offs >= uint64_t(toBits(CharSize: layout.getNonVirtualSize())) &&
9877 FieldOrBaseOffsets.find(x: offs) == FieldOrBaseOffsets.end())
9878 FieldOrBaseOffsets.insert(position: FieldOrBaseOffsets.end(),
9879 x: std::make_pair(x&: offs, y&: base));
9880 }
9881 }
9882
9883 CharUnits size;
9884 if (CXXRec) {
9885 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
9886 } else {
9887 size = layout.getSize();
9888 }
9889
9890#ifndef NDEBUG
9891 uint64_t CurOffs = 0;
9892#endif
9893 std::multimap<uint64_t, NamedDecl *>::iterator
9894 CurLayObj = FieldOrBaseOffsets.begin();
9895
9896 if (CXXRec && CXXRec->isDynamicClass() &&
9897 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
9898 if (FD) {
9899 S += "\"_vptr$";
9900 std::string recname = CXXRec->getNameAsString();
9901 if (recname.empty()) recname = "?";
9902 S += recname;
9903 S += '"';
9904 }
9905 S += "^^?";
9906#ifndef NDEBUG
9907 CurOffs += getTypeSize(VoidPtrTy);
9908#endif
9909 }
9910
9911 if (!RDecl->hasFlexibleArrayMember()) {
9912 // Mark the end of the structure.
9913 uint64_t offs = toBits(CharSize: size);
9914 FieldOrBaseOffsets.insert(position: FieldOrBaseOffsets.upper_bound(x: offs),
9915 x: std::make_pair(x&: offs, y: nullptr));
9916 }
9917
9918 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
9919#ifndef NDEBUG
9920 assert(CurOffs <= CurLayObj->first);
9921 if (CurOffs < CurLayObj->first) {
9922 uint64_t padding = CurLayObj->first - CurOffs;
9923 // FIXME: There doesn't seem to be a way to indicate in the encoding that
9924 // packing/alignment of members is different that normal, in which case
9925 // the encoding will be out-of-sync with the real layout.
9926 // If the runtime switches to just consider the size of types without
9927 // taking into account alignment, we could make padding explicit in the
9928 // encoding (e.g. using arrays of chars). The encoding strings would be
9929 // longer then though.
9930 CurOffs += padding;
9931 }
9932#endif
9933
9934 NamedDecl *dcl = CurLayObj->second;
9935 if (!dcl)
9936 break; // reached end of structure.
9937
9938 if (auto *base = dyn_cast<CXXRecordDecl>(Val: dcl)) {
9939 // We expand the bases without their virtual bases since those are going
9940 // in the initial structure. Note that this differs from gcc which
9941 // expands virtual bases each time one is encountered in the hierarchy,
9942 // making the encoding type bigger than it really is.
9943 getObjCEncodingForStructureImpl(RDecl: base, S, FD, /*includeVBases*/false,
9944 NotEncodedT);
9945 assert(!base->isEmpty());
9946#ifndef NDEBUG
9947 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
9948#endif
9949 } else {
9950 const auto *field = cast<FieldDecl>(Val: dcl);
9951 if (FD) {
9952 S += '"';
9953 S += field->getNameAsString();
9954 S += '"';
9955 }
9956
9957 if (field->isBitField()) {
9958 EncodeBitField(Ctx: this, S, T: field->getType(), FD: field);
9959#ifndef NDEBUG
9960 CurOffs += field->getBitWidthValue();
9961#endif
9962 } else {
9963 QualType qt = field->getType();
9964 getLegacyIntegralTypeEncoding(PointeeTy&: qt);
9965 getObjCEncodingForTypeImpl(
9966 T: qt, S, Options: ObjCEncOptions().setExpandStructures().setIsStructField(),
9967 FD, NotEncodedT);
9968#ifndef NDEBUG
9969 CurOffs += getTypeSize(field->getType());
9970#endif
9971 }
9972 }
9973 }
9974}
9975
9976void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
9977 std::string& S) const {
9978 if (QT & Decl::OBJC_TQ_In)
9979 S += 'n';
9980 if (QT & Decl::OBJC_TQ_Inout)
9981 S += 'N';
9982 if (QT & Decl::OBJC_TQ_Out)
9983 S += 'o';
9984 if (QT & Decl::OBJC_TQ_Bycopy)
9985 S += 'O';
9986 if (QT & Decl::OBJC_TQ_Byref)
9987 S += 'R';
9988 if (QT & Decl::OBJC_TQ_Oneway)
9989 S += 'V';
9990}
9991
9992TypedefDecl *ASTContext::getObjCIdDecl() const {
9993 if (!ObjCIdDecl) {
9994 QualType T = getObjCObjectType(BaseType: ObjCBuiltinIdTy, Protocols: {}, NumProtocols: {});
9995 T = getObjCObjectPointerType(ObjectT: T);
9996 ObjCIdDecl = buildImplicitTypedef(T, Name: "id");
9997 }
9998 return ObjCIdDecl;
9999}
10000
10001TypedefDecl *ASTContext::getObjCSelDecl() const {
10002 if (!ObjCSelDecl) {
10003 QualType T = getPointerType(T: ObjCBuiltinSelTy);
10004 ObjCSelDecl = buildImplicitTypedef(T, Name: "SEL");
10005 }
10006 return ObjCSelDecl;
10007}
10008
10009TypedefDecl *ASTContext::getObjCClassDecl() const {
10010 if (!ObjCClassDecl) {
10011 QualType T = getObjCObjectType(BaseType: ObjCBuiltinClassTy, Protocols: {}, NumProtocols: {});
10012 T = getObjCObjectPointerType(ObjectT: T);
10013 ObjCClassDecl = buildImplicitTypedef(T, Name: "Class");
10014 }
10015 return ObjCClassDecl;
10016}
10017
10018ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
10019 if (!ObjCProtocolClassDecl) {
10020 ObjCProtocolClassDecl
10021 = ObjCInterfaceDecl::Create(C: *this, DC: getTranslationUnitDecl(),
10022 atLoc: SourceLocation(),
10023 Id: &Idents.get(Name: "Protocol"),
10024 /*typeParamList=*/nullptr,
10025 /*PrevDecl=*/nullptr,
10026 ClassLoc: SourceLocation(), isInternal: true);
10027 }
10028
10029 return ObjCProtocolClassDecl;
10030}
10031
10032PointerAuthQualifier ASTContext::getObjCMemberSelTypePtrAuth() {
10033 if (!getLangOpts().PointerAuthObjcInterfaceSel)
10034 return PointerAuthQualifier();
10035 return PointerAuthQualifier::Create(
10036 Key: getLangOpts().PointerAuthObjcInterfaceSelKey,
10037 /*isAddressDiscriminated=*/IsAddressDiscriminated: true, ExtraDiscriminator: SelPointerConstantDiscriminator,
10038 AuthenticationMode: PointerAuthenticationMode::SignAndAuth,
10039 /*isIsaPointer=*/IsIsaPointer: false,
10040 /*authenticatesNullValues=*/AuthenticatesNullValues: false);
10041}
10042
10043//===----------------------------------------------------------------------===//
10044// __builtin_va_list Construction Functions
10045//===----------------------------------------------------------------------===//
10046
10047static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context,
10048 StringRef Name) {
10049 // typedef char* __builtin[_ms]_va_list;
10050 QualType T = Context->getPointerType(T: Context->CharTy);
10051 return Context->buildImplicitTypedef(T, Name);
10052}
10053
10054static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
10055 return CreateCharPtrNamedVaListDecl(Context, Name: "__builtin_ms_va_list");
10056}
10057
10058static TypedefDecl *CreateZOSVaListDecl(const ASTContext *Context) {
10059 // typedef char *__builtin_zos_va_list[2];
10060 llvm::APInt Size(Context->getTypeSize(T: Context->getSizeType()), 2);
10061 QualType T = Context->getPointerType(T: Context->CharTy);
10062 QualType ArrayType = Context->getConstantArrayType(
10063 EltTy: T, ArySizeIn: Size, SizeExpr: nullptr, ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
10064 return Context->buildImplicitTypedef(T: ArrayType, Name: "__builtin_zos_va_list");
10065}
10066
10067static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
10068 return CreateCharPtrNamedVaListDecl(Context, Name: "__builtin_va_list");
10069}
10070
10071static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
10072 // typedef void* __builtin_va_list;
10073 QualType T = Context->getPointerType(T: Context->VoidTy);
10074 return Context->buildImplicitTypedef(T, Name: "__builtin_va_list");
10075}
10076
10077static TypedefDecl *
10078CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
10079 // struct __va_list
10080 RecordDecl *VaListTagDecl = Context->buildImplicitRecord(Name: "__va_list");
10081 if (Context->getLangOpts().CPlusPlus) {
10082 // namespace std { struct __va_list {
10083 auto *NS = NamespaceDecl::Create(
10084 C&: const_cast<ASTContext &>(*Context), DC: Context->getTranslationUnitDecl(),
10085 /*Inline=*/false, StartLoc: SourceLocation(), IdLoc: SourceLocation(),
10086 Id: &Context->Idents.get(Name: "std"),
10087 /*PrevDecl=*/nullptr, /*Nested=*/false);
10088 NS->setImplicit();
10089 VaListTagDecl->setDeclContext(NS);
10090 }
10091
10092 VaListTagDecl->startDefinition();
10093
10094 const size_t NumFields = 5;
10095 QualType FieldTypes[NumFields];
10096 const char *FieldNames[NumFields];
10097
10098 // void *__stack;
10099 FieldTypes[0] = Context->getPointerType(T: Context->VoidTy);
10100 FieldNames[0] = "__stack";
10101
10102 // void *__gr_top;
10103 FieldTypes[1] = Context->getPointerType(T: Context->VoidTy);
10104 FieldNames[1] = "__gr_top";
10105
10106 // void *__vr_top;
10107 FieldTypes[2] = Context->getPointerType(T: Context->VoidTy);
10108 FieldNames[2] = "__vr_top";
10109
10110 // int __gr_offs;
10111 FieldTypes[3] = Context->IntTy;
10112 FieldNames[3] = "__gr_offs";
10113
10114 // int __vr_offs;
10115 FieldTypes[4] = Context->IntTy;
10116 FieldNames[4] = "__vr_offs";
10117
10118 // Create fields
10119 for (unsigned i = 0; i < NumFields; ++i) {
10120 FieldDecl *Field = FieldDecl::Create(C: const_cast<ASTContext &>(*Context),
10121 DC: VaListTagDecl,
10122 StartLoc: SourceLocation(),
10123 IdLoc: SourceLocation(),
10124 Id: &Context->Idents.get(Name: FieldNames[i]),
10125 T: FieldTypes[i], /*TInfo=*/nullptr,
10126 /*BitWidth=*/BW: nullptr,
10127 /*Mutable=*/false,
10128 InitStyle: ICIS_NoInit);
10129 Field->setAccess(AS_public);
10130 VaListTagDecl->addDecl(D: Field);
10131 }
10132 VaListTagDecl->completeDefinition();
10133 Context->VaListTagDecl = VaListTagDecl;
10134 CanQualType VaListTagType = Context->getCanonicalTagType(TD: VaListTagDecl);
10135
10136 // } __builtin_va_list;
10137 return Context->buildImplicitTypedef(T: VaListTagType, Name: "__builtin_va_list");
10138}
10139
10140static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
10141 // typedef struct __va_list_tag {
10142 RecordDecl *VaListTagDecl;
10143
10144 VaListTagDecl = Context->buildImplicitRecord(Name: "__va_list_tag");
10145 VaListTagDecl->startDefinition();
10146
10147 const size_t NumFields = 5;
10148 QualType FieldTypes[NumFields];
10149 const char *FieldNames[NumFields];
10150
10151 // unsigned char gpr;
10152 FieldTypes[0] = Context->UnsignedCharTy;
10153 FieldNames[0] = "gpr";
10154
10155 // unsigned char fpr;
10156 FieldTypes[1] = Context->UnsignedCharTy;
10157 FieldNames[1] = "fpr";
10158
10159 // unsigned short reserved;
10160 FieldTypes[2] = Context->UnsignedShortTy;
10161 FieldNames[2] = "reserved";
10162
10163 // void* overflow_arg_area;
10164 FieldTypes[3] = Context->getPointerType(T: Context->VoidTy);
10165 FieldNames[3] = "overflow_arg_area";
10166
10167 // void* reg_save_area;
10168 FieldTypes[4] = Context->getPointerType(T: Context->VoidTy);
10169 FieldNames[4] = "reg_save_area";
10170
10171 // Create fields
10172 for (unsigned i = 0; i < NumFields; ++i) {
10173 FieldDecl *Field = FieldDecl::Create(C: *Context, DC: VaListTagDecl,
10174 StartLoc: SourceLocation(),
10175 IdLoc: SourceLocation(),
10176 Id: &Context->Idents.get(Name: FieldNames[i]),
10177 T: FieldTypes[i], /*TInfo=*/nullptr,
10178 /*BitWidth=*/BW: nullptr,
10179 /*Mutable=*/false,
10180 InitStyle: ICIS_NoInit);
10181 Field->setAccess(AS_public);
10182 VaListTagDecl->addDecl(D: Field);
10183 }
10184 VaListTagDecl->completeDefinition();
10185 Context->VaListTagDecl = VaListTagDecl;
10186 CanQualType VaListTagType = Context->getCanonicalTagType(TD: VaListTagDecl);
10187
10188 // } __va_list_tag;
10189 TypedefDecl *VaListTagTypedefDecl =
10190 Context->buildImplicitTypedef(T: VaListTagType, Name: "__va_list_tag");
10191
10192 QualType VaListTagTypedefType =
10193 Context->getTypedefType(Keyword: ElaboratedTypeKeyword::None,
10194 /*Qualifier=*/std::nullopt, Decl: VaListTagTypedefDecl);
10195
10196 // typedef __va_list_tag __builtin_va_list[1];
10197 llvm::APInt Size(Context->getTypeSize(T: Context->getSizeType()), 1);
10198 QualType VaListTagArrayType = Context->getConstantArrayType(
10199 EltTy: VaListTagTypedefType, ArySizeIn: Size, SizeExpr: nullptr, ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
10200 return Context->buildImplicitTypedef(T: VaListTagArrayType, Name: "__builtin_va_list");
10201}
10202
10203static TypedefDecl *
10204CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
10205 // struct __va_list_tag {
10206 RecordDecl *VaListTagDecl;
10207 VaListTagDecl = Context->buildImplicitRecord(Name: "__va_list_tag");
10208 VaListTagDecl->startDefinition();
10209
10210 const size_t NumFields = 4;
10211 QualType FieldTypes[NumFields];
10212 const char *FieldNames[NumFields];
10213
10214 // unsigned gp_offset;
10215 FieldTypes[0] = Context->UnsignedIntTy;
10216 FieldNames[0] = "gp_offset";
10217
10218 // unsigned fp_offset;
10219 FieldTypes[1] = Context->UnsignedIntTy;
10220 FieldNames[1] = "fp_offset";
10221
10222 // void* overflow_arg_area;
10223 FieldTypes[2] = Context->getPointerType(T: Context->VoidTy);
10224 FieldNames[2] = "overflow_arg_area";
10225
10226 // void* reg_save_area;
10227 FieldTypes[3] = Context->getPointerType(T: Context->VoidTy);
10228 FieldNames[3] = "reg_save_area";
10229
10230 // Create fields
10231 for (unsigned i = 0; i < NumFields; ++i) {
10232 FieldDecl *Field = FieldDecl::Create(C: const_cast<ASTContext &>(*Context),
10233 DC: VaListTagDecl,
10234 StartLoc: SourceLocation(),
10235 IdLoc: SourceLocation(),
10236 Id: &Context->Idents.get(Name: FieldNames[i]),
10237 T: FieldTypes[i], /*TInfo=*/nullptr,
10238 /*BitWidth=*/BW: nullptr,
10239 /*Mutable=*/false,
10240 InitStyle: ICIS_NoInit);
10241 Field->setAccess(AS_public);
10242 VaListTagDecl->addDecl(D: Field);
10243 }
10244 VaListTagDecl->completeDefinition();
10245 Context->VaListTagDecl = VaListTagDecl;
10246 CanQualType VaListTagType = Context->getCanonicalTagType(TD: VaListTagDecl);
10247
10248 // };
10249
10250 // typedef struct __va_list_tag __builtin_va_list[1];
10251 llvm::APInt Size(Context->getTypeSize(T: Context->getSizeType()), 1);
10252 QualType VaListTagArrayType = Context->getConstantArrayType(
10253 EltTy: VaListTagType, ArySizeIn: Size, SizeExpr: nullptr, ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
10254 return Context->buildImplicitTypedef(T: VaListTagArrayType, Name: "__builtin_va_list");
10255}
10256
10257static TypedefDecl *
10258CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
10259 // struct __va_list
10260 RecordDecl *VaListDecl = Context->buildImplicitRecord(Name: "__va_list");
10261 if (Context->getLangOpts().CPlusPlus) {
10262 // namespace std { struct __va_list {
10263 NamespaceDecl *NS;
10264 NS = NamespaceDecl::Create(C&: const_cast<ASTContext &>(*Context),
10265 DC: Context->getTranslationUnitDecl(),
10266 /*Inline=*/false, StartLoc: SourceLocation(),
10267 IdLoc: SourceLocation(), Id: &Context->Idents.get(Name: "std"),
10268 /*PrevDecl=*/nullptr, /*Nested=*/false);
10269 NS->setImplicit();
10270 VaListDecl->setDeclContext(NS);
10271 }
10272
10273 VaListDecl->startDefinition();
10274
10275 // void * __ap;
10276 FieldDecl *Field = FieldDecl::Create(C: const_cast<ASTContext &>(*Context),
10277 DC: VaListDecl,
10278 StartLoc: SourceLocation(),
10279 IdLoc: SourceLocation(),
10280 Id: &Context->Idents.get(Name: "__ap"),
10281 T: Context->getPointerType(T: Context->VoidTy),
10282 /*TInfo=*/nullptr,
10283 /*BitWidth=*/BW: nullptr,
10284 /*Mutable=*/false,
10285 InitStyle: ICIS_NoInit);
10286 Field->setAccess(AS_public);
10287 VaListDecl->addDecl(D: Field);
10288
10289 // };
10290 VaListDecl->completeDefinition();
10291 Context->VaListTagDecl = VaListDecl;
10292
10293 // typedef struct __va_list __builtin_va_list;
10294 CanQualType T = Context->getCanonicalTagType(TD: VaListDecl);
10295 return Context->buildImplicitTypedef(T, Name: "__builtin_va_list");
10296}
10297
10298static TypedefDecl *
10299CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
10300 // struct __va_list_tag {
10301 RecordDecl *VaListTagDecl;
10302 VaListTagDecl = Context->buildImplicitRecord(Name: "__va_list_tag");
10303 VaListTagDecl->startDefinition();
10304
10305 const size_t NumFields = 4;
10306 QualType FieldTypes[NumFields];
10307 const char *FieldNames[NumFields];
10308
10309 // long __gpr;
10310 FieldTypes[0] = Context->LongTy;
10311 FieldNames[0] = "__gpr";
10312
10313 // long __fpr;
10314 FieldTypes[1] = Context->LongTy;
10315 FieldNames[1] = "__fpr";
10316
10317 // void *__overflow_arg_area;
10318 FieldTypes[2] = Context->getPointerType(T: Context->VoidTy);
10319 FieldNames[2] = "__overflow_arg_area";
10320
10321 // void *__reg_save_area;
10322 FieldTypes[3] = Context->getPointerType(T: Context->VoidTy);
10323 FieldNames[3] = "__reg_save_area";
10324
10325 // Create fields
10326 for (unsigned i = 0; i < NumFields; ++i) {
10327 FieldDecl *Field = FieldDecl::Create(C: const_cast<ASTContext &>(*Context),
10328 DC: VaListTagDecl,
10329 StartLoc: SourceLocation(),
10330 IdLoc: SourceLocation(),
10331 Id: &Context->Idents.get(Name: FieldNames[i]),
10332 T: FieldTypes[i], /*TInfo=*/nullptr,
10333 /*BitWidth=*/BW: nullptr,
10334 /*Mutable=*/false,
10335 InitStyle: ICIS_NoInit);
10336 Field->setAccess(AS_public);
10337 VaListTagDecl->addDecl(D: Field);
10338 }
10339 VaListTagDecl->completeDefinition();
10340 Context->VaListTagDecl = VaListTagDecl;
10341 CanQualType VaListTagType = Context->getCanonicalTagType(TD: VaListTagDecl);
10342
10343 // };
10344
10345 // typedef __va_list_tag __builtin_va_list[1];
10346 llvm::APInt Size(Context->getTypeSize(T: Context->getSizeType()), 1);
10347 QualType VaListTagArrayType = Context->getConstantArrayType(
10348 EltTy: VaListTagType, ArySizeIn: Size, SizeExpr: nullptr, ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
10349
10350 return Context->buildImplicitTypedef(T: VaListTagArrayType, Name: "__builtin_va_list");
10351}
10352
10353static TypedefDecl *CreateHexagonBuiltinVaListDecl(const ASTContext *Context) {
10354 // typedef struct __va_list_tag {
10355 RecordDecl *VaListTagDecl;
10356 VaListTagDecl = Context->buildImplicitRecord(Name: "__va_list_tag");
10357 VaListTagDecl->startDefinition();
10358
10359 const size_t NumFields = 3;
10360 QualType FieldTypes[NumFields];
10361 const char *FieldNames[NumFields];
10362
10363 // void *CurrentSavedRegisterArea;
10364 FieldTypes[0] = Context->getPointerType(T: Context->VoidTy);
10365 FieldNames[0] = "__current_saved_reg_area_pointer";
10366
10367 // void *SavedRegAreaEnd;
10368 FieldTypes[1] = Context->getPointerType(T: Context->VoidTy);
10369 FieldNames[1] = "__saved_reg_area_end_pointer";
10370
10371 // void *OverflowArea;
10372 FieldTypes[2] = Context->getPointerType(T: Context->VoidTy);
10373 FieldNames[2] = "__overflow_area_pointer";
10374
10375 // Create fields
10376 for (unsigned i = 0; i < NumFields; ++i) {
10377 FieldDecl *Field = FieldDecl::Create(
10378 C: const_cast<ASTContext &>(*Context), DC: VaListTagDecl, StartLoc: SourceLocation(),
10379 IdLoc: SourceLocation(), Id: &Context->Idents.get(Name: FieldNames[i]), T: FieldTypes[i],
10380 /*TInfo=*/nullptr,
10381 /*BitWidth=*/BW: nullptr,
10382 /*Mutable=*/false, InitStyle: ICIS_NoInit);
10383 Field->setAccess(AS_public);
10384 VaListTagDecl->addDecl(D: Field);
10385 }
10386 VaListTagDecl->completeDefinition();
10387 Context->VaListTagDecl = VaListTagDecl;
10388 CanQualType VaListTagType = Context->getCanonicalTagType(TD: VaListTagDecl);
10389
10390 // } __va_list_tag;
10391 TypedefDecl *VaListTagTypedefDecl =
10392 Context->buildImplicitTypedef(T: VaListTagType, Name: "__va_list_tag");
10393
10394 QualType VaListTagTypedefType =
10395 Context->getTypedefType(Keyword: ElaboratedTypeKeyword::None,
10396 /*Qualifier=*/std::nullopt, Decl: VaListTagTypedefDecl);
10397
10398 // typedef __va_list_tag __builtin_va_list[1];
10399 llvm::APInt Size(Context->getTypeSize(T: Context->getSizeType()), 1);
10400 QualType VaListTagArrayType = Context->getConstantArrayType(
10401 EltTy: VaListTagTypedefType, ArySizeIn: Size, SizeExpr: nullptr, ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
10402
10403 return Context->buildImplicitTypedef(T: VaListTagArrayType, Name: "__builtin_va_list");
10404}
10405
10406static TypedefDecl *
10407CreateXtensaABIBuiltinVaListDecl(const ASTContext *Context) {
10408 // typedef struct __va_list_tag {
10409 RecordDecl *VaListTagDecl = Context->buildImplicitRecord(Name: "__va_list_tag");
10410
10411 VaListTagDecl->startDefinition();
10412
10413 // int* __va_stk;
10414 // int* __va_reg;
10415 // int __va_ndx;
10416 constexpr size_t NumFields = 3;
10417 QualType FieldTypes[NumFields] = {Context->getPointerType(T: Context->IntTy),
10418 Context->getPointerType(T: Context->IntTy),
10419 Context->IntTy};
10420 const char *FieldNames[NumFields] = {"__va_stk", "__va_reg", "__va_ndx"};
10421
10422 // Create fields
10423 for (unsigned i = 0; i < NumFields; ++i) {
10424 FieldDecl *Field = FieldDecl::Create(
10425 C: *Context, DC: VaListTagDecl, StartLoc: SourceLocation(), IdLoc: SourceLocation(),
10426 Id: &Context->Idents.get(Name: FieldNames[i]), T: FieldTypes[i], /*TInfo=*/nullptr,
10427 /*BitWidth=*/BW: nullptr,
10428 /*Mutable=*/false, InitStyle: ICIS_NoInit);
10429 Field->setAccess(AS_public);
10430 VaListTagDecl->addDecl(D: Field);
10431 }
10432 VaListTagDecl->completeDefinition();
10433 Context->VaListTagDecl = VaListTagDecl;
10434 CanQualType VaListTagType = Context->getCanonicalTagType(TD: VaListTagDecl);
10435
10436 // } __va_list_tag;
10437 TypedefDecl *VaListTagTypedefDecl =
10438 Context->buildImplicitTypedef(T: VaListTagType, Name: "__builtin_va_list");
10439
10440 return VaListTagTypedefDecl;
10441}
10442
10443static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
10444 TargetInfo::BuiltinVaListKind Kind) {
10445 switch (Kind) {
10446 case TargetInfo::CharPtrBuiltinVaList:
10447 return CreateCharPtrBuiltinVaListDecl(Context);
10448 case TargetInfo::VoidPtrBuiltinVaList:
10449 return CreateVoidPtrBuiltinVaListDecl(Context);
10450 case TargetInfo::AArch64ABIBuiltinVaList:
10451 return CreateAArch64ABIBuiltinVaListDecl(Context);
10452 case TargetInfo::PowerABIBuiltinVaList:
10453 return CreatePowerABIBuiltinVaListDecl(Context);
10454 case TargetInfo::X86_64ABIBuiltinVaList:
10455 return CreateX86_64ABIBuiltinVaListDecl(Context);
10456 case TargetInfo::AAPCSABIBuiltinVaList:
10457 return CreateAAPCSABIBuiltinVaListDecl(Context);
10458 case TargetInfo::SystemZBuiltinVaList:
10459 return CreateSystemZBuiltinVaListDecl(Context);
10460 case TargetInfo::HexagonBuiltinVaList:
10461 return CreateHexagonBuiltinVaListDecl(Context);
10462 case TargetInfo::XtensaABIBuiltinVaList:
10463 return CreateXtensaABIBuiltinVaListDecl(Context);
10464 }
10465
10466 llvm_unreachable("Unhandled __builtin_va_list type kind");
10467}
10468
10469TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
10470 if (!BuiltinVaListDecl) {
10471 BuiltinVaListDecl = CreateVaListDecl(Context: this, Kind: Target->getBuiltinVaListKind());
10472 assert(BuiltinVaListDecl->isImplicit());
10473 }
10474
10475 return BuiltinVaListDecl;
10476}
10477
10478Decl *ASTContext::getVaListTagDecl() const {
10479 // Force the creation of VaListTagDecl by building the __builtin_va_list
10480 // declaration.
10481 if (!VaListTagDecl)
10482 (void)getBuiltinVaListDecl();
10483
10484 return VaListTagDecl;
10485}
10486
10487TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const {
10488 if (!BuiltinMSVaListDecl)
10489 BuiltinMSVaListDecl = CreateMSVaListDecl(Context: this);
10490
10491 return BuiltinMSVaListDecl;
10492}
10493
10494TypedefDecl *ASTContext::getBuiltinZOSVaListDecl() const {
10495 if (!BuiltinZOSVaListDecl)
10496 BuiltinZOSVaListDecl = CreateZOSVaListDecl(Context: this);
10497
10498 return BuiltinZOSVaListDecl;
10499}
10500
10501bool ASTContext::canBuiltinBeRedeclared(const FunctionDecl *FD) const {
10502 // Allow redecl custom type checking builtin for HLSL.
10503 if (LangOpts.HLSL && FD->getBuiltinID() != Builtin::NotBuiltin &&
10504 BuiltinInfo.hasCustomTypechecking(ID: FD->getBuiltinID()))
10505 return true;
10506 // Allow redecl custom type checking builtin for SPIR-V.
10507 if (getTargetInfo().getTriple().isSPIROrSPIRV() &&
10508 BuiltinInfo.isTSBuiltin(ID: FD->getBuiltinID()) &&
10509 BuiltinInfo.hasCustomTypechecking(ID: FD->getBuiltinID()))
10510 return true;
10511 return BuiltinInfo.canBeRedeclared(ID: FD->getBuiltinID());
10512}
10513
10514void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
10515 assert(ObjCConstantStringType.isNull() &&
10516 "'NSConstantString' type already set!");
10517
10518 ObjCConstantStringType = getObjCInterfaceType(Decl);
10519}
10520
10521/// Retrieve the template name that corresponds to a non-empty
10522/// lookup.
10523TemplateName
10524ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
10525 UnresolvedSetIterator End) const {
10526 unsigned size = End - Begin;
10527 assert(size > 1 && "set is not overloaded!");
10528
10529 void *memory = Allocate(Size: sizeof(OverloadedTemplateStorage) +
10530 size * sizeof(FunctionTemplateDecl*));
10531 auto *OT = new (memory) OverloadedTemplateStorage(size);
10532
10533 NamedDecl **Storage = OT->getStorage();
10534 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
10535 NamedDecl *D = *I;
10536 assert(isa<FunctionTemplateDecl>(D) ||
10537 isa<UnresolvedUsingValueDecl>(D) ||
10538 (isa<UsingShadowDecl>(D) &&
10539 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
10540 *Storage++ = D;
10541 }
10542
10543 return TemplateName(OT);
10544}
10545
10546/// Retrieve a template name representing an unqualified-id that has been
10547/// assumed to name a template for ADL purposes.
10548TemplateName ASTContext::getAssumedTemplateName(DeclarationName Name) const {
10549 auto *OT = new (*this) AssumedTemplateStorage(Name);
10550 return TemplateName(OT);
10551}
10552
10553/// Retrieve the template name that represents a qualified
10554/// template name such as \c std::vector.
10555TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier Qualifier,
10556 bool TemplateKeyword,
10557 TemplateName Template) const {
10558 assert(Template.getKind() == TemplateName::Template ||
10559 Template.getKind() == TemplateName::UsingTemplate);
10560
10561 if (Template.getAsTemplateDecl()->getKind() == Decl::TemplateTemplateParm) {
10562 assert(!Qualifier && "unexpected qualified template template parameter");
10563 assert(TemplateKeyword == false);
10564 return Template;
10565 }
10566
10567 // FIXME: Canonicalization?
10568 llvm::FoldingSetNodeID ID;
10569 QualifiedTemplateName::Profile(ID, NNS: Qualifier, TemplateKeyword, TN: Template);
10570
10571 llvm::FoldingSetInsertToken Token;
10572 QualifiedTemplateName *QTN = QualifiedTemplateNames.lookup(ID, Token);
10573 if (!QTN) {
10574 QTN = new (*this, alignof(QualifiedTemplateName))
10575 QualifiedTemplateName(Qualifier, TemplateKeyword, Template);
10576 QualifiedTemplateNames.insert(N: QTN, Token);
10577 }
10578
10579 return TemplateName(QTN);
10580}
10581
10582/// Retrieve the template name that represents a dependent
10583/// template name such as \c MetaFun::template operator+.
10584TemplateName
10585ASTContext::getDependentTemplateName(const DependentTemplateStorage &S) const {
10586 llvm::FoldingSetNodeID ID;
10587 S.Profile(ID);
10588
10589 llvm::FoldingSetInsertToken Token;
10590 if (DependentTemplateName *QTN = DependentTemplateNames.lookup(ID, Token))
10591 return TemplateName(QTN);
10592
10593 DependentTemplateName *QTN =
10594 new (*this, alignof(DependentTemplateName)) DependentTemplateName(S);
10595 DependentTemplateNames.insert(N: QTN, Token);
10596 return TemplateName(QTN);
10597}
10598
10599TemplateName ASTContext::getSubstTemplateTemplateParm(TemplateName Replacement,
10600 Decl *AssociatedDecl,
10601 unsigned Index,
10602 UnsignedOrNone PackIndex,
10603 bool Final) const {
10604 llvm::FoldingSetNodeID ID;
10605 SubstTemplateTemplateParmStorage::Profile(ID, Replacement, AssociatedDecl,
10606 Index, PackIndex, Final);
10607
10608 llvm::FoldingSetInsertToken Token;
10609 SubstTemplateTemplateParmStorage *subst =
10610 SubstTemplateTemplateParms.lookup(ID, Token);
10611
10612 if (!subst) {
10613 subst = new (*this) SubstTemplateTemplateParmStorage(
10614 Replacement, AssociatedDecl, Index, PackIndex, Final);
10615 SubstTemplateTemplateParms.insert(N: subst, Token);
10616 }
10617
10618 return TemplateName(subst);
10619}
10620
10621TemplateName
10622ASTContext::getSubstTemplateTemplateParmPack(const TemplateArgument &ArgPack,
10623 Decl *AssociatedDecl,
10624 unsigned Index, bool Final) const {
10625 auto &Self = const_cast<ASTContext &>(*this);
10626 llvm::FoldingSetNodeID ID;
10627 SubstTemplateTemplateParmPackStorage::Profile(ID, Context&: Self, ArgPack,
10628 AssociatedDecl, Index, Final);
10629
10630 llvm::FoldingSetInsertToken Token;
10631 SubstTemplateTemplateParmPackStorage *Subst =
10632 SubstTemplateTemplateParmPacks.lookup(ID, Token);
10633
10634 if (!Subst) {
10635 Subst = new (*this) SubstTemplateTemplateParmPackStorage(
10636 ArgPack.pack_elements(), AssociatedDecl, Index, Final);
10637 SubstTemplateTemplateParmPacks.insert(N: Subst, Token);
10638 }
10639
10640 return TemplateName(Subst);
10641}
10642
10643/// Retrieve the template name that represents a template name
10644/// deduced from a specialization.
10645TemplateName
10646ASTContext::getDeducedTemplateName(TemplateName Underlying,
10647 DefaultArguments DefaultArgs) const {
10648 if (!DefaultArgs)
10649 return Underlying;
10650
10651 llvm::FoldingSetNodeID ID;
10652 DeducedTemplateStorage::Profile(ID, Context: *this, Underlying, DefArgs: DefaultArgs);
10653
10654 llvm::FoldingSetInsertToken Token;
10655 DeducedTemplateStorage *DTS = DeducedTemplates.lookup(ID, Token);
10656 if (!DTS) {
10657 void *Mem = Allocate(Size: sizeof(DeducedTemplateStorage) +
10658 sizeof(TemplateArgument) * DefaultArgs.Args.size(),
10659 Align: alignof(DeducedTemplateStorage));
10660 DTS = new (Mem) DeducedTemplateStorage(Underlying, DefaultArgs);
10661 DeducedTemplates.insert(N: DTS, Token);
10662 }
10663 return TemplateName(DTS);
10664}
10665
10666TemplateName ASTContext::getPackIndexingTemplateName(
10667 TemplateName Pattern, Expr *IndexExpr, bool FullySubstituted,
10668 ArrayRef<TemplateName> Expansions) const {
10669 auto &Self = const_cast<ASTContext &>(*this);
10670 llvm::FoldingSetNodeID ID;
10671 PackIndexingTemplateStorage::Profile(ID, Context: Self, Pattern, IndexExpr,
10672 FullySubstituted, Expansions);
10673
10674 llvm::FoldingSetInsertToken Token;
10675 PackIndexingTemplateStorage *PI = PackIndexingTemplates.lookup(ID, Token);
10676 if (!PI) {
10677 void *Mem =
10678 Allocate(Size: PackIndexingTemplateStorage::totalSizeToAlloc<TemplateName>(
10679 Counts: Expansions.size()),
10680 Align: alignof(PackIndexingTemplateStorage));
10681 PI = new (Mem) PackIndexingTemplateStorage(Pattern, IndexExpr,
10682 FullySubstituted, Expansions);
10683 PackIndexingTemplates.insert(N: PI, Token);
10684 }
10685 return TemplateName(PI);
10686}
10687
10688/// getFromTargetType - Given one of the integer types provided by
10689/// TargetInfo, produce the corresponding type. The unsigned @p Type
10690/// is actually a value of type @c TargetInfo::IntType.
10691CanQualType ASTContext::getFromTargetType(unsigned Type) const {
10692 switch (Type) {
10693 case TargetInfo::NoInt: return {};
10694 case TargetInfo::SignedChar: return SignedCharTy;
10695 case TargetInfo::UnsignedChar: return UnsignedCharTy;
10696 case TargetInfo::SignedShort: return ShortTy;
10697 case TargetInfo::UnsignedShort: return UnsignedShortTy;
10698 case TargetInfo::SignedInt: return IntTy;
10699 case TargetInfo::UnsignedInt: return UnsignedIntTy;
10700 case TargetInfo::SignedLong: return LongTy;
10701 case TargetInfo::UnsignedLong: return UnsignedLongTy;
10702 case TargetInfo::SignedLongLong: return LongLongTy;
10703 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
10704 }
10705
10706 llvm_unreachable("Unhandled TargetInfo::IntType value");
10707}
10708
10709//===----------------------------------------------------------------------===//
10710// Type Predicates.
10711//===----------------------------------------------------------------------===//
10712
10713/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
10714/// garbage collection attribute.
10715///
10716Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
10717 if (getLangOpts().getGC() == LangOptions::NonGC)
10718 return Qualifiers::GCNone;
10719
10720 assert(getLangOpts().ObjC);
10721 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
10722
10723 // Default behaviour under objective-C's gc is for ObjC pointers
10724 // (or pointers to them) be treated as though they were declared
10725 // as __strong.
10726 if (GCAttrs == Qualifiers::GCNone) {
10727 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
10728 return Qualifiers::Strong;
10729 else if (Ty->isPointerType())
10730 return getObjCGCAttrKind(Ty: Ty->castAs<PointerType>()->getPointeeType());
10731 } else {
10732 // It's not valid to set GC attributes on anything that isn't a
10733 // pointer.
10734#ifndef NDEBUG
10735 QualType CT = Ty->getCanonicalTypeInternal();
10736 while (const auto *AT = dyn_cast<ArrayType>(CT))
10737 CT = AT->getElementType();
10738 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
10739#endif
10740 }
10741 return GCAttrs;
10742}
10743
10744//===----------------------------------------------------------------------===//
10745// Type Compatibility Testing
10746//===----------------------------------------------------------------------===//
10747
10748/// areCompatVectorTypes - Return true if the two specified vector types are
10749/// compatible.
10750static bool areCompatVectorTypes(const VectorType *LHS,
10751 const VectorType *RHS) {
10752 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
10753 return LHS->getElementType() == RHS->getElementType() &&
10754 LHS->getNumElements() == RHS->getNumElements();
10755}
10756
10757/// areCompatMatrixTypes - Return true if the two specified matrix types are
10758/// compatible.
10759static bool areCompatMatrixTypes(const ConstantMatrixType *LHS,
10760 const ConstantMatrixType *RHS) {
10761 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
10762 return LHS->getElementType() == RHS->getElementType() &&
10763 LHS->getNumRows() == RHS->getNumRows() &&
10764 LHS->getNumColumns() == RHS->getNumColumns();
10765}
10766
10767bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
10768 QualType SecondVec) {
10769 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
10770 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
10771
10772 if (hasSameUnqualifiedType(T1: FirstVec, T2: SecondVec))
10773 return true;
10774
10775 // Treat Neon vector types and most AltiVec vector types as if they are the
10776 // equivalent GCC vector types.
10777 const auto *First = FirstVec->castAs<VectorType>();
10778 const auto *Second = SecondVec->castAs<VectorType>();
10779 if (First->getNumElements() == Second->getNumElements() &&
10780 hasSameType(T1: First->getElementType(), T2: Second->getElementType()) &&
10781 First->getVectorKind() != VectorKind::AltiVecPixel &&
10782 First->getVectorKind() != VectorKind::AltiVecBool &&
10783 Second->getVectorKind() != VectorKind::AltiVecPixel &&
10784 Second->getVectorKind() != VectorKind::AltiVecBool &&
10785 First->getVectorKind() != VectorKind::SveFixedLengthData &&
10786 First->getVectorKind() != VectorKind::SveFixedLengthPredicate &&
10787 Second->getVectorKind() != VectorKind::SveFixedLengthData &&
10788 Second->getVectorKind() != VectorKind::SveFixedLengthPredicate &&
10789 First->getVectorKind() != VectorKind::RVVFixedLengthData &&
10790 Second->getVectorKind() != VectorKind::RVVFixedLengthData &&
10791 First->getVectorKind() != VectorKind::RVVFixedLengthMask &&
10792 Second->getVectorKind() != VectorKind::RVVFixedLengthMask &&
10793 First->getVectorKind() != VectorKind::RVVFixedLengthMask_1 &&
10794 Second->getVectorKind() != VectorKind::RVVFixedLengthMask_1 &&
10795 First->getVectorKind() != VectorKind::RVVFixedLengthMask_2 &&
10796 Second->getVectorKind() != VectorKind::RVVFixedLengthMask_2 &&
10797 First->getVectorKind() != VectorKind::RVVFixedLengthMask_4 &&
10798 Second->getVectorKind() != VectorKind::RVVFixedLengthMask_4)
10799 return true;
10800
10801 // In OpenCL, treat half and _Float16 vector types as compatible.
10802 if (getLangOpts().OpenCL &&
10803 First->getNumElements() == Second->getNumElements()) {
10804 QualType FirstElt = First->getElementType();
10805 QualType SecondElt = Second->getElementType();
10806
10807 if ((FirstElt->isFloat16Type() && SecondElt->isHalfType()) ||
10808 (FirstElt->isHalfType() && SecondElt->isFloat16Type())) {
10809 if (First->getVectorKind() != VectorKind::AltiVecPixel &&
10810 First->getVectorKind() != VectorKind::AltiVecBool &&
10811 Second->getVectorKind() != VectorKind::AltiVecPixel &&
10812 Second->getVectorKind() != VectorKind::AltiVecBool)
10813 return true;
10814 }
10815 }
10816 return false;
10817}
10818
10819bool ASTContext::areCompatibleOverflowBehaviorTypes(QualType LHS,
10820 QualType RHS) {
10821 auto Result = checkOBTAssignmentCompatibility(LHS, RHS);
10822 return Result != OBTAssignResult::IncompatibleKinds;
10823}
10824
10825ASTContext::OBTAssignResult
10826ASTContext::checkOBTAssignmentCompatibility(QualType LHS, QualType RHS) {
10827 const auto *LHSOBT = LHS->getAs<OverflowBehaviorType>();
10828 const auto *RHSOBT = RHS->getAs<OverflowBehaviorType>();
10829
10830 if (!LHSOBT && !RHSOBT)
10831 return OBTAssignResult::Compatible;
10832
10833 if (LHSOBT && RHSOBT) {
10834 if (LHSOBT->getBehaviorKind() != RHSOBT->getBehaviorKind())
10835 return OBTAssignResult::IncompatibleKinds;
10836 return OBTAssignResult::Compatible;
10837 }
10838
10839 QualType LHSUnderlying = LHSOBT ? LHSOBT->desugar() : LHS;
10840 QualType RHSUnderlying = RHSOBT ? RHSOBT->desugar() : RHS;
10841
10842 if (RHSOBT && !LHSOBT) {
10843 if (LHSUnderlying->isIntegerType() && RHSUnderlying->isIntegerType())
10844 return OBTAssignResult::Discards;
10845 }
10846
10847 return OBTAssignResult::NotApplicable;
10848}
10849
10850/// getRVVTypeSize - Return RVV vector register size.
10851static uint64_t getRVVTypeSize(ASTContext &Context, const BuiltinType *Ty) {
10852 assert(Ty->isRVVVLSBuiltinType() && "Invalid RVV Type");
10853 auto VScale = Context.getTargetInfo().getVScaleRange(
10854 LangOpts: Context.getLangOpts(), Mode: TargetInfo::ArmStreamingKind::NotStreaming);
10855 if (!VScale)
10856 return 0;
10857
10858 ASTContext::BuiltinVectorTypeInfo Info = Context.getBuiltinVectorTypeInfo(Ty);
10859
10860 uint64_t EltSize = Context.getTypeSize(T: Info.ElementType);
10861 if (Info.ElementType == Context.BoolTy)
10862 EltSize = 1;
10863
10864 uint64_t MinElts = Info.EC.getKnownMinValue();
10865 return VScale->first * MinElts * EltSize;
10866}
10867
10868bool ASTContext::areCompatibleRVVTypes(QualType FirstType,
10869 QualType SecondType) {
10870 assert(
10871 ((FirstType->isRVVSizelessBuiltinType() && SecondType->isVectorType()) ||
10872 (FirstType->isVectorType() && SecondType->isRVVSizelessBuiltinType())) &&
10873 "Expected RVV builtin type and vector type!");
10874
10875 auto IsValidCast = [this](QualType FirstType, QualType SecondType) {
10876 if (const auto *BT = FirstType->getAs<BuiltinType>()) {
10877 if (const auto *VT = SecondType->getAs<VectorType>()) {
10878 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask) {
10879 BuiltinVectorTypeInfo Info = getBuiltinVectorTypeInfo(Ty: BT);
10880 return FirstType->isRVVVLSBuiltinType() &&
10881 Info.ElementType == BoolTy &&
10882 getTypeSize(T: SecondType) == ((getRVVTypeSize(Context&: *this, Ty: BT)));
10883 }
10884 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_1) {
10885 BuiltinVectorTypeInfo Info = getBuiltinVectorTypeInfo(Ty: BT);
10886 return FirstType->isRVVVLSBuiltinType() &&
10887 Info.ElementType == BoolTy &&
10888 getTypeSize(T: SecondType) == ((getRVVTypeSize(Context&: *this, Ty: BT) * 8));
10889 }
10890 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_2) {
10891 BuiltinVectorTypeInfo Info = getBuiltinVectorTypeInfo(Ty: BT);
10892 return FirstType->isRVVVLSBuiltinType() &&
10893 Info.ElementType == BoolTy &&
10894 getTypeSize(T: SecondType) == ((getRVVTypeSize(Context&: *this, Ty: BT)) * 4);
10895 }
10896 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_4) {
10897 BuiltinVectorTypeInfo Info = getBuiltinVectorTypeInfo(Ty: BT);
10898 return FirstType->isRVVVLSBuiltinType() &&
10899 Info.ElementType == BoolTy &&
10900 getTypeSize(T: SecondType) == ((getRVVTypeSize(Context&: *this, Ty: BT)) * 2);
10901 }
10902 if (VT->getVectorKind() == VectorKind::RVVFixedLengthData ||
10903 VT->getVectorKind() == VectorKind::Generic)
10904 return FirstType->isRVVVLSBuiltinType() &&
10905 getTypeSize(T: SecondType) == getRVVTypeSize(Context&: *this, Ty: BT) &&
10906 hasSameType(T1: VT->getElementType(),
10907 T2: getBuiltinVectorTypeInfo(Ty: BT).ElementType);
10908 }
10909 }
10910 return false;
10911 };
10912
10913 return IsValidCast(FirstType, SecondType) ||
10914 IsValidCast(SecondType, FirstType);
10915}
10916
10917bool ASTContext::areLaxCompatibleRVVTypes(QualType FirstType,
10918 QualType SecondType) {
10919 assert(
10920 ((FirstType->isRVVSizelessBuiltinType() && SecondType->isVectorType()) ||
10921 (FirstType->isVectorType() && SecondType->isRVVSizelessBuiltinType())) &&
10922 "Expected RVV builtin type and vector type!");
10923
10924 auto IsLaxCompatible = [this](QualType FirstType, QualType SecondType) {
10925 const auto *BT = FirstType->getAs<BuiltinType>();
10926 if (!BT)
10927 return false;
10928
10929 if (!BT->isRVVVLSBuiltinType())
10930 return false;
10931
10932 const auto *VecTy = SecondType->getAs<VectorType>();
10933 if (VecTy && VecTy->getVectorKind() == VectorKind::Generic) {
10934 const LangOptions::LaxVectorConversionKind LVCKind =
10935 getLangOpts().getLaxVectorConversions();
10936
10937 // If __riscv_v_fixed_vlen != N do not allow vector lax conversion.
10938 if (getTypeSize(T: SecondType) != getRVVTypeSize(Context&: *this, Ty: BT))
10939 return false;
10940
10941 // If -flax-vector-conversions=all is specified, the types are
10942 // certainly compatible.
10943 if (LVCKind == LangOptions::LaxVectorConversionKind::All)
10944 return true;
10945
10946 // If -flax-vector-conversions=integer is specified, the types are
10947 // compatible if the elements are integer types.
10948 if (LVCKind == LangOptions::LaxVectorConversionKind::Integer)
10949 return VecTy->getElementType().getCanonicalType()->isIntegerType() &&
10950 FirstType->getRVVEltType(Ctx: *this)->isIntegerType();
10951 }
10952
10953 return false;
10954 };
10955
10956 return IsLaxCompatible(FirstType, SecondType) ||
10957 IsLaxCompatible(SecondType, FirstType);
10958}
10959
10960bool ASTContext::hasDirectOwnershipQualifier(QualType Ty) const {
10961 while (true) {
10962 // __strong id
10963 if (const AttributedType *Attr = dyn_cast<AttributedType>(Val&: Ty)) {
10964 if (Attr->getAttrKind() == attr::ObjCOwnership)
10965 return true;
10966
10967 Ty = Attr->getModifiedType();
10968
10969 // X *__strong (...)
10970 } else if (const ParenType *Paren = dyn_cast<ParenType>(Val&: Ty)) {
10971 Ty = Paren->getInnerType();
10972
10973 // We do not want to look through typedefs, typeof(expr),
10974 // typeof(type), or any other way that the type is somehow
10975 // abstracted.
10976 } else {
10977 return false;
10978 }
10979 }
10980}
10981
10982//===----------------------------------------------------------------------===//
10983// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
10984//===----------------------------------------------------------------------===//
10985
10986/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
10987/// inheritance hierarchy of 'rProto'.
10988bool
10989ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
10990 ObjCProtocolDecl *rProto) const {
10991 if (declaresSameEntity(D1: lProto, D2: rProto))
10992 return true;
10993 for (auto *PI : rProto->protocols())
10994 if (ProtocolCompatibleWithProtocol(lProto, rProto: PI))
10995 return true;
10996 return false;
10997}
10998
10999/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
11000/// Class<pr1, ...>.
11001bool ASTContext::ObjCQualifiedClassTypesAreCompatible(
11002 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs) {
11003 for (auto *lhsProto : lhs->quals()) {
11004 bool match = false;
11005 for (auto *rhsProto : rhs->quals()) {
11006 if (ProtocolCompatibleWithProtocol(lProto: lhsProto, rProto: rhsProto)) {
11007 match = true;
11008 break;
11009 }
11010 }
11011 if (!match)
11012 return false;
11013 }
11014 return true;
11015}
11016
11017/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
11018/// ObjCQualifiedIDType.
11019bool ASTContext::ObjCQualifiedIdTypesAreCompatible(
11020 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs,
11021 bool compare) {
11022 // Allow id<P..> and an 'id' in all cases.
11023 if (lhs->isObjCIdType() || rhs->isObjCIdType())
11024 return true;
11025
11026 // Don't allow id<P..> to convert to Class or Class<P..> in either direction.
11027 if (lhs->isObjCClassType() || lhs->isObjCQualifiedClassType() ||
11028 rhs->isObjCClassType() || rhs->isObjCQualifiedClassType())
11029 return false;
11030
11031 if (lhs->isObjCQualifiedIdType()) {
11032 if (rhs->qual_empty()) {
11033 // If the RHS is a unqualified interface pointer "NSString*",
11034 // make sure we check the class hierarchy.
11035 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
11036 for (auto *I : lhs->quals()) {
11037 // when comparing an id<P> on lhs with a static type on rhs,
11038 // see if static class implements all of id's protocols, directly or
11039 // through its super class and categories.
11040 if (!rhsID->ClassImplementsProtocol(lProto: I, lookupCategory: true))
11041 return false;
11042 }
11043 }
11044 // If there are no qualifiers and no interface, we have an 'id'.
11045 return true;
11046 }
11047 // Both the right and left sides have qualifiers.
11048 for (auto *lhsProto : lhs->quals()) {
11049 bool match = false;
11050
11051 // when comparing an id<P> on lhs with a static type on rhs,
11052 // see if static class implements all of id's protocols, directly or
11053 // through its super class and categories.
11054 for (auto *rhsProto : rhs->quals()) {
11055 if (ProtocolCompatibleWithProtocol(lProto: lhsProto, rProto: rhsProto) ||
11056 (compare && ProtocolCompatibleWithProtocol(lProto: rhsProto, rProto: lhsProto))) {
11057 match = true;
11058 break;
11059 }
11060 }
11061 // If the RHS is a qualified interface pointer "NSString<P>*",
11062 // make sure we check the class hierarchy.
11063 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
11064 for (auto *I : lhs->quals()) {
11065 // when comparing an id<P> on lhs with a static type on rhs,
11066 // see if static class implements all of id's protocols, directly or
11067 // through its super class and categories.
11068 if (rhsID->ClassImplementsProtocol(lProto: I, lookupCategory: true)) {
11069 match = true;
11070 break;
11071 }
11072 }
11073 }
11074 if (!match)
11075 return false;
11076 }
11077
11078 return true;
11079 }
11080
11081 assert(rhs->isObjCQualifiedIdType() && "One of the LHS/RHS should be id<x>");
11082
11083 if (lhs->getInterfaceType()) {
11084 // If both the right and left sides have qualifiers.
11085 for (auto *lhsProto : lhs->quals()) {
11086 bool match = false;
11087
11088 // when comparing an id<P> on rhs with a static type on lhs,
11089 // see if static class implements all of id's protocols, directly or
11090 // through its super class and categories.
11091 // First, lhs protocols in the qualifier list must be found, direct
11092 // or indirect in rhs's qualifier list or it is a mismatch.
11093 for (auto *rhsProto : rhs->quals()) {
11094 if (ProtocolCompatibleWithProtocol(lProto: lhsProto, rProto: rhsProto) ||
11095 (compare && ProtocolCompatibleWithProtocol(lProto: rhsProto, rProto: lhsProto))) {
11096 match = true;
11097 break;
11098 }
11099 }
11100 if (!match)
11101 return false;
11102 }
11103
11104 // Static class's protocols, or its super class or category protocols
11105 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
11106 if (ObjCInterfaceDecl *lhsID = lhs->getInterfaceDecl()) {
11107 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
11108 CollectInheritedProtocols(CDecl: lhsID, Protocols&: LHSInheritedProtocols);
11109 // This is rather dubious but matches gcc's behavior. If lhs has
11110 // no type qualifier and its class has no static protocol(s)
11111 // assume that it is mismatch.
11112 if (LHSInheritedProtocols.empty() && lhs->qual_empty())
11113 return false;
11114 for (auto *lhsProto : LHSInheritedProtocols) {
11115 bool match = false;
11116 for (auto *rhsProto : rhs->quals()) {
11117 if (ProtocolCompatibleWithProtocol(lProto: lhsProto, rProto: rhsProto) ||
11118 (compare && ProtocolCompatibleWithProtocol(lProto: rhsProto, rProto: lhsProto))) {
11119 match = true;
11120 break;
11121 }
11122 }
11123 if (!match)
11124 return false;
11125 }
11126 }
11127 return true;
11128 }
11129 return false;
11130}
11131
11132/// canAssignObjCInterfaces - Return true if the two interface types are
11133/// compatible for assignment from RHS to LHS. This handles validation of any
11134/// protocol qualifiers on the LHS or RHS.
11135bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
11136 const ObjCObjectPointerType *RHSOPT) {
11137 const ObjCObjectType* LHS = LHSOPT->getObjectType();
11138 const ObjCObjectType* RHS = RHSOPT->getObjectType();
11139
11140 // If either type represents the built-in 'id' type, return true.
11141 if (LHS->isObjCUnqualifiedId() || RHS->isObjCUnqualifiedId())
11142 return true;
11143
11144 // Function object that propagates a successful result or handles
11145 // __kindof types.
11146 auto finish = [&](bool succeeded) -> bool {
11147 if (succeeded)
11148 return true;
11149
11150 if (!RHS->isKindOfType())
11151 return false;
11152
11153 // Strip off __kindof and protocol qualifiers, then check whether
11154 // we can assign the other way.
11155 return canAssignObjCInterfaces(LHSOPT: RHSOPT->stripObjCKindOfTypeAndQuals(ctx: *this),
11156 RHSOPT: LHSOPT->stripObjCKindOfTypeAndQuals(ctx: *this));
11157 };
11158
11159 // Casts from or to id<P> are allowed when the other side has compatible
11160 // protocols.
11161 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
11162 return finish(ObjCQualifiedIdTypesAreCompatible(lhs: LHSOPT, rhs: RHSOPT, compare: false));
11163 }
11164
11165 // Verify protocol compatibility for casts from Class<P1> to Class<P2>.
11166 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
11167 return finish(ObjCQualifiedClassTypesAreCompatible(lhs: LHSOPT, rhs: RHSOPT));
11168 }
11169
11170 // Casts from Class to Class<Foo>, or vice-versa, are allowed.
11171 if (LHS->isObjCClass() && RHS->isObjCClass()) {
11172 return true;
11173 }
11174
11175 // If we have 2 user-defined types, fall into that path.
11176 if (LHS->getInterface() && RHS->getInterface()) {
11177 return finish(canAssignObjCInterfaces(LHS, RHS));
11178 }
11179
11180 return false;
11181}
11182
11183/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
11184/// for providing type-safety for objective-c pointers used to pass/return
11185/// arguments in block literals. When passed as arguments, passing 'A*' where
11186/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
11187/// not OK. For the return type, the opposite is not OK.
11188bool ASTContext::canAssignObjCInterfacesInBlockPointer(
11189 const ObjCObjectPointerType *LHSOPT,
11190 const ObjCObjectPointerType *RHSOPT,
11191 bool BlockReturnType) {
11192
11193 // Function object that propagates a successful result or handles
11194 // __kindof types.
11195 auto finish = [&](bool succeeded) -> bool {
11196 if (succeeded)
11197 return true;
11198
11199 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
11200 if (!Expected->isKindOfType())
11201 return false;
11202
11203 // Strip off __kindof and protocol qualifiers, then check whether
11204 // we can assign the other way.
11205 return canAssignObjCInterfacesInBlockPointer(
11206 LHSOPT: RHSOPT->stripObjCKindOfTypeAndQuals(ctx: *this),
11207 RHSOPT: LHSOPT->stripObjCKindOfTypeAndQuals(ctx: *this),
11208 BlockReturnType);
11209 };
11210
11211 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
11212 return true;
11213
11214 if (LHSOPT->isObjCBuiltinType()) {
11215 return finish(RHSOPT->isObjCBuiltinType() ||
11216 RHSOPT->isObjCQualifiedIdType());
11217 }
11218
11219 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) {
11220 if (getLangOpts().CompatibilityQualifiedIdBlockParamTypeChecking)
11221 // Use for block parameters previous type checking for compatibility.
11222 return finish(ObjCQualifiedIdTypesAreCompatible(lhs: LHSOPT, rhs: RHSOPT, compare: false) ||
11223 // Or corrected type checking as in non-compat mode.
11224 (!BlockReturnType &&
11225 ObjCQualifiedIdTypesAreCompatible(lhs: RHSOPT, rhs: LHSOPT, compare: false)));
11226 else
11227 return finish(ObjCQualifiedIdTypesAreCompatible(
11228 lhs: (BlockReturnType ? LHSOPT : RHSOPT),
11229 rhs: (BlockReturnType ? RHSOPT : LHSOPT), compare: false));
11230 }
11231
11232 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
11233 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
11234 if (LHS && RHS) { // We have 2 user-defined types.
11235 if (LHS != RHS) {
11236 if (LHS->getDecl()->isSuperClassOf(I: RHS->getDecl()))
11237 return finish(BlockReturnType);
11238 if (RHS->getDecl()->isSuperClassOf(I: LHS->getDecl()))
11239 return finish(!BlockReturnType);
11240 }
11241 else
11242 return true;
11243 }
11244 return false;
11245}
11246
11247/// Comparison routine for Objective-C protocols to be used with
11248/// llvm::array_pod_sort.
11249static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
11250 ObjCProtocolDecl * const *rhs) {
11251 return (*lhs)->getName().compare(RHS: (*rhs)->getName());
11252}
11253
11254/// getIntersectionOfProtocols - This routine finds the intersection of set
11255/// of protocols inherited from two distinct objective-c pointer objects with
11256/// the given common base.
11257/// It is used to build composite qualifier list of the composite type of
11258/// the conditional expression involving two objective-c pointer objects.
11259static
11260void getIntersectionOfProtocols(ASTContext &Context,
11261 const ObjCInterfaceDecl *CommonBase,
11262 const ObjCObjectPointerType *LHSOPT,
11263 const ObjCObjectPointerType *RHSOPT,
11264 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
11265
11266 const ObjCObjectType* LHS = LHSOPT->getObjectType();
11267 const ObjCObjectType* RHS = RHSOPT->getObjectType();
11268 assert(LHS->getInterface() && "LHS must have an interface base");
11269 assert(RHS->getInterface() && "RHS must have an interface base");
11270
11271 // Add all of the protocols for the LHS.
11272 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
11273
11274 // Start with the protocol qualifiers.
11275 for (auto *proto : LHS->quals()) {
11276 Context.CollectInheritedProtocols(CDecl: proto, Protocols&: LHSProtocolSet);
11277 }
11278
11279 // Also add the protocols associated with the LHS interface.
11280 Context.CollectInheritedProtocols(CDecl: LHS->getInterface(), Protocols&: LHSProtocolSet);
11281
11282 // Add all of the protocols for the RHS.
11283 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
11284
11285 // Start with the protocol qualifiers.
11286 for (auto *proto : RHS->quals()) {
11287 Context.CollectInheritedProtocols(CDecl: proto, Protocols&: RHSProtocolSet);
11288 }
11289
11290 // Also add the protocols associated with the RHS interface.
11291 Context.CollectInheritedProtocols(CDecl: RHS->getInterface(), Protocols&: RHSProtocolSet);
11292
11293 // Compute the intersection of the collected protocol sets.
11294 for (auto *proto : LHSProtocolSet) {
11295 if (RHSProtocolSet.count(Ptr: proto))
11296 IntersectionSet.push_back(Elt: proto);
11297 }
11298
11299 // Compute the set of protocols that is implied by either the common type or
11300 // the protocols within the intersection.
11301 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
11302 Context.CollectInheritedProtocols(CDecl: CommonBase, Protocols&: ImpliedProtocols);
11303
11304 // Remove any implied protocols from the list of inherited protocols.
11305 if (!ImpliedProtocols.empty()) {
11306 llvm::erase_if(C&: IntersectionSet, P: [&](ObjCProtocolDecl *proto) -> bool {
11307 return ImpliedProtocols.contains(Ptr: proto);
11308 });
11309 }
11310
11311 // Sort the remaining protocols by name.
11312 llvm::array_pod_sort(Start: IntersectionSet.begin(), End: IntersectionSet.end(),
11313 Compare: compareObjCProtocolsByName);
11314}
11315
11316/// Determine whether the first type is a subtype of the second.
11317static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
11318 QualType rhs) {
11319 // Common case: two object pointers.
11320 const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
11321 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
11322 if (lhsOPT && rhsOPT)
11323 return ctx.canAssignObjCInterfaces(LHSOPT: lhsOPT, RHSOPT: rhsOPT);
11324
11325 // Two block pointers.
11326 const auto *lhsBlock = lhs->getAs<BlockPointerType>();
11327 const auto *rhsBlock = rhs->getAs<BlockPointerType>();
11328 if (lhsBlock && rhsBlock)
11329 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
11330
11331 // If either is an unqualified 'id' and the other is a block, it's
11332 // acceptable.
11333 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
11334 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
11335 return true;
11336
11337 return false;
11338}
11339
11340// Check that the given Objective-C type argument lists are equivalent.
11341static bool sameObjCTypeArgs(ASTContext &ctx,
11342 const ObjCInterfaceDecl *iface,
11343 ArrayRef<QualType> lhsArgs,
11344 ArrayRef<QualType> rhsArgs,
11345 bool stripKindOf) {
11346 if (lhsArgs.size() != rhsArgs.size())
11347 return false;
11348
11349 ObjCTypeParamList *typeParams = iface->getTypeParamList();
11350 if (!typeParams)
11351 return false;
11352
11353 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
11354 if (ctx.hasSameType(T1: lhsArgs[i], T2: rhsArgs[i]))
11355 continue;
11356
11357 switch (typeParams->begin()[i]->getVariance()) {
11358 case ObjCTypeParamVariance::Invariant:
11359 if (!stripKindOf ||
11360 !ctx.hasSameType(T1: lhsArgs[i].stripObjCKindOfType(ctx),
11361 T2: rhsArgs[i].stripObjCKindOfType(ctx))) {
11362 return false;
11363 }
11364 break;
11365
11366 case ObjCTypeParamVariance::Covariant:
11367 if (!canAssignObjCObjectTypes(ctx, lhs: lhsArgs[i], rhs: rhsArgs[i]))
11368 return false;
11369 break;
11370
11371 case ObjCTypeParamVariance::Contravariant:
11372 if (!canAssignObjCObjectTypes(ctx, lhs: rhsArgs[i], rhs: lhsArgs[i]))
11373 return false;
11374 break;
11375 }
11376 }
11377
11378 return true;
11379}
11380
11381QualType ASTContext::areCommonBaseCompatible(
11382 const ObjCObjectPointerType *Lptr,
11383 const ObjCObjectPointerType *Rptr) {
11384 const ObjCObjectType *LHS = Lptr->getObjectType();
11385 const ObjCObjectType *RHS = Rptr->getObjectType();
11386 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
11387 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
11388
11389 if (!LDecl || !RDecl)
11390 return {};
11391
11392 // When either LHS or RHS is a kindof type, we should return a kindof type.
11393 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
11394 // kindof(A).
11395 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
11396
11397 // Follow the left-hand side up the class hierarchy until we either hit a
11398 // root or find the RHS. Record the ancestors in case we don't find it.
11399 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
11400 LHSAncestors;
11401 while (true) {
11402 // Record this ancestor. We'll need this if the common type isn't in the
11403 // path from the LHS to the root.
11404 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
11405
11406 if (declaresSameEntity(D1: LHS->getInterface(), D2: RDecl)) {
11407 // Get the type arguments.
11408 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
11409 bool anyChanges = false;
11410 if (LHS->isSpecialized() && RHS->isSpecialized()) {
11411 // Both have type arguments, compare them.
11412 if (!sameObjCTypeArgs(ctx&: *this, iface: LHS->getInterface(),
11413 lhsArgs: LHS->getTypeArgs(), rhsArgs: RHS->getTypeArgs(),
11414 /*stripKindOf=*/true))
11415 return {};
11416 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
11417 // If only one has type arguments, the result will not have type
11418 // arguments.
11419 LHSTypeArgs = {};
11420 anyChanges = true;
11421 }
11422
11423 // Compute the intersection of protocols.
11424 SmallVector<ObjCProtocolDecl *, 8> Protocols;
11425 getIntersectionOfProtocols(Context&: *this, CommonBase: LHS->getInterface(), LHSOPT: Lptr, RHSOPT: Rptr,
11426 IntersectionSet&: Protocols);
11427 if (!Protocols.empty())
11428 anyChanges = true;
11429
11430 // If anything in the LHS will have changed, build a new result type.
11431 // If we need to return a kindof type but LHS is not a kindof type, we
11432 // build a new result type.
11433 if (anyChanges || LHS->isKindOfType() != anyKindOf) {
11434 QualType Result = getObjCInterfaceType(Decl: LHS->getInterface());
11435 Result = getObjCObjectType(baseType: Result, typeArgs: LHSTypeArgs, protocols: Protocols,
11436 isKindOf: anyKindOf || LHS->isKindOfType());
11437 return getObjCObjectPointerType(ObjectT: Result);
11438 }
11439
11440 return getObjCObjectPointerType(ObjectT: QualType(LHS, 0));
11441 }
11442
11443 // Find the superclass.
11444 QualType LHSSuperType = LHS->getSuperClassType();
11445 if (LHSSuperType.isNull())
11446 break;
11447
11448 LHS = LHSSuperType->castAs<ObjCObjectType>();
11449 }
11450
11451 // We didn't find anything by following the LHS to its root; now check
11452 // the RHS against the cached set of ancestors.
11453 while (true) {
11454 auto KnownLHS = LHSAncestors.find(Val: RHS->getInterface()->getCanonicalDecl());
11455 if (KnownLHS != LHSAncestors.end()) {
11456 LHS = KnownLHS->second;
11457
11458 // Get the type arguments.
11459 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
11460 bool anyChanges = false;
11461 if (LHS->isSpecialized() && RHS->isSpecialized()) {
11462 // Both have type arguments, compare them.
11463 if (!sameObjCTypeArgs(ctx&: *this, iface: LHS->getInterface(),
11464 lhsArgs: LHS->getTypeArgs(), rhsArgs: RHS->getTypeArgs(),
11465 /*stripKindOf=*/true))
11466 return {};
11467 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
11468 // If only one has type arguments, the result will not have type
11469 // arguments.
11470 RHSTypeArgs = {};
11471 anyChanges = true;
11472 }
11473
11474 // Compute the intersection of protocols.
11475 SmallVector<ObjCProtocolDecl *, 8> Protocols;
11476 getIntersectionOfProtocols(Context&: *this, CommonBase: RHS->getInterface(), LHSOPT: Lptr, RHSOPT: Rptr,
11477 IntersectionSet&: Protocols);
11478 if (!Protocols.empty())
11479 anyChanges = true;
11480
11481 // If we need to return a kindof type but RHS is not a kindof type, we
11482 // build a new result type.
11483 if (anyChanges || RHS->isKindOfType() != anyKindOf) {
11484 QualType Result = getObjCInterfaceType(Decl: RHS->getInterface());
11485 Result = getObjCObjectType(baseType: Result, typeArgs: RHSTypeArgs, protocols: Protocols,
11486 isKindOf: anyKindOf || RHS->isKindOfType());
11487 return getObjCObjectPointerType(ObjectT: Result);
11488 }
11489
11490 return getObjCObjectPointerType(ObjectT: QualType(RHS, 0));
11491 }
11492
11493 // Find the superclass of the RHS.
11494 QualType RHSSuperType = RHS->getSuperClassType();
11495 if (RHSSuperType.isNull())
11496 break;
11497
11498 RHS = RHSSuperType->castAs<ObjCObjectType>();
11499 }
11500
11501 return {};
11502}
11503
11504bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
11505 const ObjCObjectType *RHS) {
11506 assert(LHS->getInterface() && "LHS is not an interface type");
11507 assert(RHS->getInterface() && "RHS is not an interface type");
11508
11509 // Verify that the base decls are compatible: the RHS must be a subclass of
11510 // the LHS.
11511 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
11512 bool IsSuperClass = LHSInterface->isSuperClassOf(I: RHS->getInterface());
11513 if (!IsSuperClass)
11514 return false;
11515
11516 // If the LHS has protocol qualifiers, determine whether all of them are
11517 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
11518 // LHS).
11519 if (LHS->getNumProtocols() > 0) {
11520 // OK if conversion of LHS to SuperClass results in narrowing of types
11521 // ; i.e., SuperClass may implement at least one of the protocols
11522 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
11523 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
11524 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
11525 CollectInheritedProtocols(CDecl: RHS->getInterface(), Protocols&: SuperClassInheritedProtocols);
11526 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
11527 // qualifiers.
11528 for (auto *RHSPI : RHS->quals())
11529 CollectInheritedProtocols(CDecl: RHSPI, Protocols&: SuperClassInheritedProtocols);
11530 // If there is no protocols associated with RHS, it is not a match.
11531 if (SuperClassInheritedProtocols.empty())
11532 return false;
11533
11534 for (const auto *LHSProto : LHS->quals()) {
11535 bool SuperImplementsProtocol = false;
11536 for (auto *SuperClassProto : SuperClassInheritedProtocols)
11537 if (SuperClassProto->lookupProtocolNamed(PName: LHSProto->getIdentifier())) {
11538 SuperImplementsProtocol = true;
11539 break;
11540 }
11541 if (!SuperImplementsProtocol)
11542 return false;
11543 }
11544 }
11545
11546 // If the LHS is specialized, we may need to check type arguments.
11547 if (LHS->isSpecialized()) {
11548 // Follow the superclass chain until we've matched the LHS class in the
11549 // hierarchy. This substitutes type arguments through.
11550 const ObjCObjectType *RHSSuper = RHS;
11551 while (!declaresSameEntity(D1: RHSSuper->getInterface(), D2: LHSInterface))
11552 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
11553
11554 // If the RHS is specializd, compare type arguments.
11555 if (RHSSuper->isSpecialized() &&
11556 !sameObjCTypeArgs(ctx&: *this, iface: LHS->getInterface(),
11557 lhsArgs: LHS->getTypeArgs(), rhsArgs: RHSSuper->getTypeArgs(),
11558 /*stripKindOf=*/true)) {
11559 return false;
11560 }
11561 }
11562
11563 return true;
11564}
11565
11566bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
11567 // get the "pointed to" types
11568 const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
11569 const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
11570
11571 if (!LHSOPT || !RHSOPT)
11572 return false;
11573
11574 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
11575 canAssignObjCInterfaces(LHSOPT: RHSOPT, RHSOPT: LHSOPT);
11576}
11577
11578bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
11579 return canAssignObjCInterfaces(
11580 LHSOPT: getObjCObjectPointerType(ObjectT: To)->castAs<ObjCObjectPointerType>(),
11581 RHSOPT: getObjCObjectPointerType(ObjectT: From)->castAs<ObjCObjectPointerType>());
11582}
11583
11584/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
11585/// both shall have the identically qualified version of a compatible type.
11586/// C99 6.2.7p1: Two types have compatible types if their types are the
11587/// same. See 6.7.[2,3,5] for additional rules.
11588bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
11589 bool CompareUnqualified) {
11590 if (getLangOpts().CPlusPlus)
11591 return hasSameType(T1: LHS, T2: RHS);
11592
11593 return !mergeTypes(LHS, RHS, OfBlockPointer: false, Unqualified: CompareUnqualified).isNull();
11594}
11595
11596bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
11597 return typesAreCompatible(LHS, RHS);
11598}
11599
11600bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
11601 return !mergeTypes(LHS, RHS, OfBlockPointer: true).isNull();
11602}
11603
11604/// mergeTransparentUnionType - if T is a transparent union type and a member
11605/// of T is compatible with SubType, return the merged type, else return
11606/// QualType()
11607QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
11608 bool OfBlockPointer,
11609 bool Unqualified) {
11610 if (const RecordType *UT = T->getAsUnionType()) {
11611 RecordDecl *UD = UT->getDecl()->getMostRecentDecl();
11612 if (UD->hasAttr<TransparentUnionAttr>()) {
11613 for (const auto *I : UD->fields()) {
11614 QualType ET = I->getType().getUnqualifiedType();
11615 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
11616 if (!MT.isNull())
11617 return MT;
11618 }
11619 }
11620 }
11621
11622 return {};
11623}
11624
11625/// mergeFunctionParameterTypes - merge two types which appear as function
11626/// parameter types
11627QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
11628 bool OfBlockPointer,
11629 bool Unqualified) {
11630 // GNU extension: two types are compatible if they appear as a function
11631 // argument, one of the types is a transparent union type and the other
11632 // type is compatible with a union member
11633 QualType lmerge = mergeTransparentUnionType(T: lhs, SubType: rhs, OfBlockPointer,
11634 Unqualified);
11635 if (!lmerge.isNull())
11636 return lmerge;
11637
11638 QualType rmerge = mergeTransparentUnionType(T: rhs, SubType: lhs, OfBlockPointer,
11639 Unqualified);
11640 if (!rmerge.isNull())
11641 return rmerge;
11642
11643 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
11644}
11645
11646QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
11647 bool OfBlockPointer, bool Unqualified,
11648 bool AllowCXX,
11649 bool IsConditionalOperator) {
11650 const auto *lbase = lhs->castAs<FunctionType>();
11651 const auto *rbase = rhs->castAs<FunctionType>();
11652 const auto *lproto = dyn_cast<FunctionProtoType>(Val: lbase);
11653 const auto *rproto = dyn_cast<FunctionProtoType>(Val: rbase);
11654 bool allLTypes = true;
11655 bool allRTypes = true;
11656
11657 // Check return type
11658 QualType retType;
11659 if (OfBlockPointer) {
11660 QualType RHS = rbase->getReturnType();
11661 QualType LHS = lbase->getReturnType();
11662 bool UnqualifiedResult = Unqualified;
11663 if (!UnqualifiedResult)
11664 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
11665 retType = mergeTypes(LHS, RHS, OfBlockPointer: true, Unqualified: UnqualifiedResult, BlockReturnType: true);
11666 }
11667 else
11668 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), OfBlockPointer: false,
11669 Unqualified);
11670 if (retType.isNull())
11671 return {};
11672
11673 if (Unqualified)
11674 retType = retType.getUnqualifiedType();
11675
11676 CanQualType LRetType = getCanonicalType(T: lbase->getReturnType());
11677 CanQualType RRetType = getCanonicalType(T: rbase->getReturnType());
11678 if (Unqualified) {
11679 LRetType = LRetType.getUnqualifiedType();
11680 RRetType = RRetType.getUnqualifiedType();
11681 }
11682
11683 if (getCanonicalType(T: retType) != LRetType)
11684 allLTypes = false;
11685 if (getCanonicalType(T: retType) != RRetType)
11686 allRTypes = false;
11687
11688 // FIXME: double check this
11689 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
11690 // rbase->getRegParmAttr() != 0 &&
11691 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
11692 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
11693 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
11694
11695 // Compatible functions must have compatible calling conventions
11696 if (lbaseInfo.getCC() != rbaseInfo.getCC())
11697 return {};
11698
11699 // Regparm is part of the calling convention.
11700 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
11701 return {};
11702 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
11703 return {};
11704
11705 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
11706 return {};
11707 if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs())
11708 return {};
11709 if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck())
11710 return {};
11711
11712 // When merging declarations, it's common for supplemental information like
11713 // attributes to only be present in one of the declarations, and we generally
11714 // want type merging to preserve the union of information. So a merged
11715 // function type should be noreturn if it was noreturn in *either* operand
11716 // type.
11717 //
11718 // But for the conditional operator, this is backwards. The result of the
11719 // operator could be either operand, and its type should conservatively
11720 // reflect that. So a function type in a composite type is noreturn only
11721 // if it's noreturn in *both* operand types.
11722 //
11723 // Arguably, noreturn is a kind of subtype, and the conditional operator
11724 // ought to produce the most specific common supertype of its operand types.
11725 // That would differ from this rule in contravariant positions. However,
11726 // neither C nor C++ generally uses this kind of subtype reasoning. Also,
11727 // as a practical matter, it would only affect C code that does abstraction of
11728 // higher-order functions (taking noreturn callbacks!), which is uncommon to
11729 // say the least. So we use the simpler rule.
11730 bool NoReturn = IsConditionalOperator
11731 ? lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn()
11732 : lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
11733 if (lbaseInfo.getNoReturn() != NoReturn)
11734 allLTypes = false;
11735 if (rbaseInfo.getNoReturn() != NoReturn)
11736 allRTypes = false;
11737
11738 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(noReturn: NoReturn);
11739
11740 std::optional<FunctionEffectSet> MergedFX;
11741
11742 if (lproto && rproto) { // two C99 style function prototypes
11743 assert((AllowCXX ||
11744 (!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec())) &&
11745 "C++ shouldn't be here");
11746 // Compatible functions must have the same number of parameters
11747 if (lproto->getNumParams() != rproto->getNumParams())
11748 return {};
11749
11750 // Variadic and non-variadic functions aren't compatible
11751 if (lproto->isVariadic() != rproto->isVariadic())
11752 return {};
11753
11754 if (lproto->getMethodQuals() != rproto->getMethodQuals())
11755 return {};
11756
11757 // Function protos with different 'cfi_salt' values aren't compatible.
11758 if (lproto->getExtraAttributeInfo().CFISalt !=
11759 rproto->getExtraAttributeInfo().CFISalt)
11760 return {};
11761
11762 // Function effects are handled similarly to noreturn, see above.
11763 FunctionEffectsRef LHSFX = lproto->getFunctionEffects();
11764 FunctionEffectsRef RHSFX = rproto->getFunctionEffects();
11765 if (LHSFX != RHSFX) {
11766 if (IsConditionalOperator)
11767 MergedFX = FunctionEffectSet::getIntersection(LHS: LHSFX, RHS: RHSFX);
11768 else {
11769 FunctionEffectSet::Conflicts Errs;
11770 MergedFX = FunctionEffectSet::getUnion(LHS: LHSFX, RHS: RHSFX, Errs);
11771 // Here we're discarding a possible error due to conflicts in the effect
11772 // sets. But we're not in a context where we can report it. The
11773 // operation does however guarantee maintenance of invariants.
11774 }
11775 if (*MergedFX != LHSFX)
11776 allLTypes = false;
11777 if (*MergedFX != RHSFX)
11778 allRTypes = false;
11779 }
11780
11781 SmallVector<FunctionProtoType::ExtParameterInfo, 4> newParamInfos;
11782 bool canUseLeft, canUseRight;
11783 if (!mergeExtParameterInfo(FirstFnType: lproto, SecondFnType: rproto, CanUseFirst&: canUseLeft, CanUseSecond&: canUseRight,
11784 NewParamInfos&: newParamInfos))
11785 return {};
11786
11787 if (!canUseLeft)
11788 allLTypes = false;
11789 if (!canUseRight)
11790 allRTypes = false;
11791
11792 // Check parameter type compatibility
11793 SmallVector<QualType, 10> types;
11794 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
11795 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
11796 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
11797 QualType paramType = mergeFunctionParameterTypes(
11798 lhs: lParamType, rhs: rParamType, OfBlockPointer, Unqualified);
11799 if (paramType.isNull())
11800 return {};
11801
11802 if (Unqualified)
11803 paramType = paramType.getUnqualifiedType();
11804
11805 types.push_back(Elt: paramType);
11806 if (Unqualified) {
11807 lParamType = lParamType.getUnqualifiedType();
11808 rParamType = rParamType.getUnqualifiedType();
11809 }
11810
11811 if (getCanonicalType(T: paramType) != getCanonicalType(T: lParamType))
11812 allLTypes = false;
11813 if (getCanonicalType(T: paramType) != getCanonicalType(T: rParamType))
11814 allRTypes = false;
11815 }
11816
11817 if (allLTypes) return lhs;
11818 if (allRTypes) return rhs;
11819
11820 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
11821 EPI.ExtInfo = einfo;
11822 EPI.ExtParameterInfos =
11823 newParamInfos.empty() ? nullptr : newParamInfos.data();
11824 if (MergedFX)
11825 EPI.FunctionEffects = *MergedFX;
11826 return getFunctionType(ResultTy: retType, Args: types, EPI);
11827 }
11828
11829 if (lproto) allRTypes = false;
11830 if (rproto) allLTypes = false;
11831
11832 const FunctionProtoType *proto = lproto ? lproto : rproto;
11833 if (proto) {
11834 assert((AllowCXX || !proto->hasExceptionSpec()) && "C++ shouldn't be here");
11835 if (proto->isVariadic())
11836 return {};
11837 // Check that the types are compatible with the types that
11838 // would result from default argument promotions (C99 6.7.5.3p15).
11839 // The only types actually affected are promotable integer
11840 // types and floats, which would be passed as a different
11841 // type depending on whether the prototype is visible.
11842 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
11843 QualType paramTy = proto->getParamType(i);
11844
11845 // Look at the converted type of enum types, since that is the type used
11846 // to pass enum values.
11847 if (const auto *ED = paramTy->getAsEnumDecl()) {
11848 paramTy = ED->getIntegerType();
11849 if (paramTy.isNull())
11850 return {};
11851 }
11852
11853 if (isPromotableIntegerType(T: paramTy) ||
11854 getCanonicalType(T: paramTy).getUnqualifiedType() == FloatTy)
11855 return {};
11856 }
11857
11858 if (allLTypes) return lhs;
11859 if (allRTypes) return rhs;
11860
11861 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
11862 EPI.ExtInfo = einfo;
11863 if (MergedFX)
11864 EPI.FunctionEffects = *MergedFX;
11865 return getFunctionType(ResultTy: retType, Args: proto->getParamTypes(), EPI);
11866 }
11867
11868 if (allLTypes) return lhs;
11869 if (allRTypes) return rhs;
11870 return getFunctionNoProtoType(ResultTy: retType, Info: einfo);
11871}
11872
11873/// Given that we have an enum type and a non-enum type, try to merge them.
11874static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
11875 QualType other, bool isBlockReturnType) {
11876 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
11877 // a signed integer type, or an unsigned integer type.
11878 // Compatibility is based on the underlying type, not the promotion
11879 // type.
11880 QualType underlyingType =
11881 ET->getDecl()->getDefinitionOrSelf()->getIntegerType();
11882 if (underlyingType.isNull())
11883 return {};
11884 if (Context.hasSameType(T1: underlyingType, T2: other))
11885 return other;
11886
11887 // In block return types, we're more permissive and accept any
11888 // integral type of the same size.
11889 if (isBlockReturnType && other->isIntegerType() &&
11890 Context.getTypeSize(T: underlyingType) == Context.getTypeSize(T: other))
11891 return other;
11892
11893 return {};
11894}
11895
11896QualType ASTContext::mergeTagDefinitions(QualType LHS, QualType RHS) {
11897 // C17 and earlier and C++ disallow two tag definitions within the same TU
11898 // from being compatible.
11899 if (LangOpts.CPlusPlus || !LangOpts.C23)
11900 return {};
11901
11902 // Nameless tags are comparable only within outer definitions. At the top
11903 // level they are not comparable.
11904 const TagDecl *LTagD = LHS->castAsTagDecl(), *RTagD = RHS->castAsTagDecl();
11905 if (!LTagD->getIdentifier() || !RTagD->getIdentifier())
11906 return {};
11907
11908 // C23, on the other hand, requires the members to be "the same enough", so
11909 // we use a structural equivalence check.
11910 StructuralEquivalenceContext::NonEquivalentDeclSet NonEquivalentDecls;
11911 StructuralEquivalenceContext Ctx(
11912 getLangOpts(), *this, *this, NonEquivalentDecls,
11913 StructuralEquivalenceKind::Default, /*StrictTypeSpelling=*/false,
11914 /*Complain=*/false, /*ErrorOnTagTypeMismatch=*/true);
11915 return Ctx.IsEquivalent(T1: LHS, T2: RHS) ? LHS : QualType{};
11916}
11917
11918std::optional<QualType> ASTContext::tryMergeOverflowBehaviorTypes(
11919 QualType LHS, QualType RHS, bool OfBlockPointer, bool Unqualified,
11920 bool BlockReturnType, bool IsConditionalOperator) {
11921 const auto *LHSOBT = LHS->getAs<OverflowBehaviorType>();
11922 const auto *RHSOBT = RHS->getAs<OverflowBehaviorType>();
11923
11924 if (!LHSOBT && !RHSOBT)
11925 return std::nullopt;
11926
11927 if (LHSOBT) {
11928 if (RHSOBT) {
11929 if (LHSOBT->getBehaviorKind() != RHSOBT->getBehaviorKind())
11930 return QualType();
11931
11932 QualType MergedUnderlying = mergeTypes(
11933 LHSOBT->getUnderlyingType(), RHSOBT->getUnderlyingType(),
11934 OfBlockPointer, Unqualified, BlockReturnType, IsConditionalOperator);
11935
11936 if (MergedUnderlying.isNull())
11937 return QualType();
11938
11939 if (getCanonicalType(T: LHSOBT) == getCanonicalType(T: RHSOBT)) {
11940 if (LHSOBT->getUnderlyingType() == RHSOBT->getUnderlyingType())
11941 return getCommonSugaredType(X: LHS, Y: RHS);
11942 return getOverflowBehaviorType(
11943 Kind: LHSOBT->getBehaviorKind(),
11944 Underlying: getCanonicalType(T: LHSOBT->getUnderlyingType()));
11945 }
11946
11947 // For different underlying types that successfully merge, wrap the
11948 // merged underlying type with the common overflow behavior
11949 return getOverflowBehaviorType(Kind: LHSOBT->getBehaviorKind(),
11950 Underlying: MergedUnderlying);
11951 }
11952 return mergeTypes(LHSOBT->getUnderlyingType(), RHS, OfBlockPointer,
11953 Unqualified, BlockReturnType, IsConditionalOperator);
11954 }
11955
11956 return mergeTypes(LHS, RHSOBT->getUnderlyingType(), OfBlockPointer,
11957 Unqualified, BlockReturnType, IsConditionalOperator);
11958}
11959
11960QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, bool OfBlockPointer,
11961 bool Unqualified, bool BlockReturnType,
11962 bool IsConditionalOperator) {
11963 // For C++ we will not reach this code with reference types (see below),
11964 // for OpenMP variant call overloading we might.
11965 //
11966 // C++ [expr]: If an expression initially has the type "reference to T", the
11967 // type is adjusted to "T" prior to any further analysis, the expression
11968 // designates the object or function denoted by the reference, and the
11969 // expression is an lvalue unless the reference is an rvalue reference and
11970 // the expression is a function call (possibly inside parentheses).
11971 auto *LHSRefTy = LHS->getAs<ReferenceType>();
11972 auto *RHSRefTy = RHS->getAs<ReferenceType>();
11973 if (LangOpts.OpenMP && LHSRefTy && RHSRefTy &&
11974 LHS->getTypeClass() == RHS->getTypeClass())
11975 return mergeTypes(LHS: LHSRefTy->getPointeeType(), RHS: RHSRefTy->getPointeeType(),
11976 OfBlockPointer, Unqualified, BlockReturnType);
11977 if (LHSRefTy || RHSRefTy)
11978 return {};
11979
11980 if (std::optional<QualType> MergedOBT =
11981 tryMergeOverflowBehaviorTypes(LHS, RHS, OfBlockPointer, Unqualified,
11982 BlockReturnType, IsConditionalOperator))
11983 return *MergedOBT;
11984
11985 if (Unqualified) {
11986 LHS = LHS.getUnqualifiedType();
11987 RHS = RHS.getUnqualifiedType();
11988 }
11989
11990 QualType LHSCan = getCanonicalType(T: LHS),
11991 RHSCan = getCanonicalType(T: RHS);
11992
11993 // If two types are identical, they are compatible.
11994 if (LHSCan == RHSCan)
11995 return LHS;
11996
11997 // If the qualifiers are different, the types aren't compatible... mostly.
11998 Qualifiers LQuals = LHSCan.getLocalQualifiers();
11999 Qualifiers RQuals = RHSCan.getLocalQualifiers();
12000 if (LQuals != RQuals) {
12001 // If any of these qualifiers are different, we have a type
12002 // mismatch.
12003 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
12004 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
12005 LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
12006 !LQuals.getPointerAuth().isEquivalent(Other: RQuals.getPointerAuth()) ||
12007 LQuals.hasUnaligned() != RQuals.hasUnaligned())
12008 return {};
12009
12010 // Exactly one GC qualifier difference is allowed: __strong is
12011 // okay if the other type has no GC qualifier but is an Objective
12012 // C object pointer (i.e. implicitly strong by default). We fix
12013 // this by pretending that the unqualified type was actually
12014 // qualified __strong.
12015 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
12016 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
12017 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
12018
12019 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
12020 return {};
12021
12022 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
12023 return mergeTypes(LHS, RHS: getObjCGCQualType(T: RHS, GCAttr: Qualifiers::Strong));
12024 }
12025 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
12026 return mergeTypes(LHS: getObjCGCQualType(T: LHS, GCAttr: Qualifiers::Strong), RHS);
12027 }
12028 return {};
12029 }
12030
12031 // Okay, qualifiers are equal.
12032
12033 Type::TypeClass LHSClass = LHSCan->getTypeClass();
12034 Type::TypeClass RHSClass = RHSCan->getTypeClass();
12035
12036 // We want to consider the two function types to be the same for these
12037 // comparisons, just force one to the other.
12038 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
12039 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
12040
12041 // Same as above for arrays
12042 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
12043 LHSClass = Type::ConstantArray;
12044 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
12045 RHSClass = Type::ConstantArray;
12046
12047 // ObjCInterfaces are just specialized ObjCObjects.
12048 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
12049 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
12050
12051 // Canonicalize ExtVector -> Vector.
12052 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
12053 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
12054
12055 // If the canonical type classes don't match.
12056 if (LHSClass != RHSClass) {
12057 // Note that we only have special rules for turning block enum
12058 // returns into block int returns, not vice-versa.
12059 if (const auto *ETy = LHS->getAsCanonical<EnumType>()) {
12060 return mergeEnumWithInteger(Context&: *this, ET: ETy, other: RHS, isBlockReturnType: false);
12061 }
12062 if (const EnumType *ETy = RHS->getAsCanonical<EnumType>()) {
12063 return mergeEnumWithInteger(Context&: *this, ET: ETy, other: LHS, isBlockReturnType: BlockReturnType);
12064 }
12065 // allow block pointer type to match an 'id' type.
12066 if (OfBlockPointer && !BlockReturnType) {
12067 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
12068 return LHS;
12069 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
12070 return RHS;
12071 }
12072 // Allow __auto_type to match anything; it merges to the type with more
12073 // information.
12074 if (const auto *AT = LHS->getAs<AutoType>()) {
12075 if (!AT->isDeduced() && AT->isGNUAutoType())
12076 return RHS;
12077 }
12078 if (const auto *AT = RHS->getAs<AutoType>()) {
12079 if (!AT->isDeduced() && AT->isGNUAutoType())
12080 return LHS;
12081 }
12082 return {};
12083 }
12084
12085 // The canonical type classes match.
12086 switch (LHSClass) {
12087#define TYPE(Class, Base)
12088#define ABSTRACT_TYPE(Class, Base)
12089#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
12090#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
12091#define DEPENDENT_TYPE(Class, Base) case Type::Class:
12092#include "clang/AST/TypeNodes.inc"
12093 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
12094
12095 case Type::Auto:
12096 case Type::DeducedTemplateSpecialization:
12097 case Type::LValueReference:
12098 case Type::RValueReference:
12099 case Type::MemberPointer:
12100 llvm_unreachable("C++ should never be in mergeTypes");
12101
12102 case Type::ObjCInterface:
12103 case Type::IncompleteArray:
12104 case Type::VariableArray:
12105 case Type::FunctionProto:
12106 case Type::ExtVector:
12107 case Type::OverflowBehavior:
12108 llvm_unreachable("Types are eliminated above");
12109
12110 case Type::Pointer:
12111 {
12112 // Merge two pointer types, while trying to preserve typedef info
12113 QualType LHSPointee = LHS->castAs<PointerType>()->getPointeeType();
12114 QualType RHSPointee = RHS->castAs<PointerType>()->getPointeeType();
12115 if (Unqualified) {
12116 LHSPointee = LHSPointee.getUnqualifiedType();
12117 RHSPointee = RHSPointee.getUnqualifiedType();
12118 }
12119 QualType ResultType = mergeTypes(LHS: LHSPointee, RHS: RHSPointee, OfBlockPointer: false,
12120 Unqualified);
12121 if (ResultType.isNull())
12122 return {};
12123 if (getCanonicalType(T: LHSPointee) == getCanonicalType(T: ResultType))
12124 return LHS;
12125 if (getCanonicalType(T: RHSPointee) == getCanonicalType(T: ResultType))
12126 return RHS;
12127 return getPointerType(T: ResultType);
12128 }
12129 case Type::BlockPointer:
12130 {
12131 // Merge two block pointer types, while trying to preserve typedef info
12132 QualType LHSPointee = LHS->castAs<BlockPointerType>()->getPointeeType();
12133 QualType RHSPointee = RHS->castAs<BlockPointerType>()->getPointeeType();
12134 if (Unqualified) {
12135 LHSPointee = LHSPointee.getUnqualifiedType();
12136 RHSPointee = RHSPointee.getUnqualifiedType();
12137 }
12138 if (getLangOpts().OpenCL) {
12139 Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
12140 Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
12141 // Blocks can't be an expression in a ternary operator (OpenCL v2.0
12142 // 6.12.5) thus the following check is asymmetric.
12143 if (!LHSPteeQual.isAddressSpaceSupersetOf(other: RHSPteeQual, Ctx: *this))
12144 return {};
12145 LHSPteeQual.removeAddressSpace();
12146 RHSPteeQual.removeAddressSpace();
12147 LHSPointee =
12148 QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
12149 RHSPointee =
12150 QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
12151 }
12152 QualType ResultType = mergeTypes(LHS: LHSPointee, RHS: RHSPointee, OfBlockPointer,
12153 Unqualified);
12154 if (ResultType.isNull())
12155 return {};
12156 if (getCanonicalType(T: LHSPointee) == getCanonicalType(T: ResultType))
12157 return LHS;
12158 if (getCanonicalType(T: RHSPointee) == getCanonicalType(T: ResultType))
12159 return RHS;
12160 return getBlockPointerType(T: ResultType);
12161 }
12162 case Type::Atomic:
12163 {
12164 // Merge two pointer types, while trying to preserve typedef info
12165 QualType LHSValue = LHS->castAs<AtomicType>()->getValueType();
12166 QualType RHSValue = RHS->castAs<AtomicType>()->getValueType();
12167 if (Unqualified) {
12168 LHSValue = LHSValue.getUnqualifiedType();
12169 RHSValue = RHSValue.getUnqualifiedType();
12170 }
12171 QualType ResultType = mergeTypes(LHS: LHSValue, RHS: RHSValue, OfBlockPointer: false,
12172 Unqualified);
12173 if (ResultType.isNull())
12174 return {};
12175 if (getCanonicalType(T: LHSValue) == getCanonicalType(T: ResultType))
12176 return LHS;
12177 if (getCanonicalType(T: RHSValue) == getCanonicalType(T: ResultType))
12178 return RHS;
12179 return getAtomicType(T: ResultType);
12180 }
12181 case Type::ConstantArray:
12182 {
12183 const ConstantArrayType* LCAT = getAsConstantArrayType(T: LHS);
12184 const ConstantArrayType* RCAT = getAsConstantArrayType(T: RHS);
12185 if (LCAT && RCAT && RCAT->getZExtSize() != LCAT->getZExtSize())
12186 return {};
12187
12188 QualType LHSElem = getAsArrayType(T: LHS)->getElementType();
12189 QualType RHSElem = getAsArrayType(T: RHS)->getElementType();
12190 if (Unqualified) {
12191 LHSElem = LHSElem.getUnqualifiedType();
12192 RHSElem = RHSElem.getUnqualifiedType();
12193 }
12194
12195 QualType ResultType = mergeTypes(LHS: LHSElem, RHS: RHSElem, OfBlockPointer: false, Unqualified);
12196 if (ResultType.isNull())
12197 return {};
12198
12199 const VariableArrayType* LVAT = getAsVariableArrayType(T: LHS);
12200 const VariableArrayType* RVAT = getAsVariableArrayType(T: RHS);
12201
12202 // If either side is a variable array, and both are complete, check whether
12203 // the current dimension is definite.
12204 if (LVAT || RVAT) {
12205 auto SizeFetch = [this](const VariableArrayType* VAT,
12206 const ConstantArrayType* CAT)
12207 -> std::pair<bool,llvm::APInt> {
12208 if (VAT) {
12209 std::optional<llvm::APSInt> TheInt;
12210 Expr *E = VAT->getSizeExpr();
12211 if (E && (TheInt = E->getIntegerConstantExpr(Ctx: *this)))
12212 return std::make_pair(x: true, y&: *TheInt);
12213 return std::make_pair(x: false, y: llvm::APSInt());
12214 }
12215 if (CAT)
12216 return std::make_pair(x: true, y: CAT->getSize());
12217 return std::make_pair(x: false, y: llvm::APInt());
12218 };
12219
12220 bool HaveLSize, HaveRSize;
12221 llvm::APInt LSize, RSize;
12222 std::tie(args&: HaveLSize, args&: LSize) = SizeFetch(LVAT, LCAT);
12223 std::tie(args&: HaveRSize, args&: RSize) = SizeFetch(RVAT, RCAT);
12224 if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(I1: LSize, I2: RSize))
12225 return {}; // Definite, but unequal, array dimension
12226 }
12227
12228 if (LCAT && getCanonicalType(T: LHSElem) == getCanonicalType(T: ResultType))
12229 return LHS;
12230 if (RCAT && getCanonicalType(T: RHSElem) == getCanonicalType(T: ResultType))
12231 return RHS;
12232 if (LCAT)
12233 return getConstantArrayType(EltTy: ResultType, ArySizeIn: LCAT->getSize(),
12234 SizeExpr: LCAT->getSizeExpr(), ASM: ArraySizeModifier(), IndexTypeQuals: 0);
12235 if (RCAT)
12236 return getConstantArrayType(EltTy: ResultType, ArySizeIn: RCAT->getSize(),
12237 SizeExpr: RCAT->getSizeExpr(), ASM: ArraySizeModifier(), IndexTypeQuals: 0);
12238 if (LVAT && getCanonicalType(T: LHSElem) == getCanonicalType(T: ResultType))
12239 return LHS;
12240 if (RVAT && getCanonicalType(T: RHSElem) == getCanonicalType(T: ResultType))
12241 return RHS;
12242 if (LVAT) {
12243 // FIXME: This isn't correct! But tricky to implement because
12244 // the array's size has to be the size of LHS, but the type
12245 // has to be different.
12246 return LHS;
12247 }
12248 if (RVAT) {
12249 // FIXME: This isn't correct! But tricky to implement because
12250 // the array's size has to be the size of RHS, but the type
12251 // has to be different.
12252 return RHS;
12253 }
12254 if (getCanonicalType(T: LHSElem) == getCanonicalType(T: ResultType)) return LHS;
12255 if (getCanonicalType(T: RHSElem) == getCanonicalType(T: ResultType)) return RHS;
12256 return getIncompleteArrayType(elementType: ResultType, ASM: ArraySizeModifier(), elementTypeQuals: 0);
12257 }
12258 case Type::FunctionNoProto:
12259 return mergeFunctionTypes(lhs: LHS, rhs: RHS, OfBlockPointer, Unqualified,
12260 /*AllowCXX=*/false, IsConditionalOperator);
12261 case Type::Record:
12262 case Type::Enum:
12263 return mergeTagDefinitions(LHS, RHS);
12264 case Type::Builtin:
12265 // Only exactly equal builtin types are compatible, which is tested above.
12266 return {};
12267 case Type::Complex:
12268 // Distinct complex types are incompatible.
12269 return {};
12270 case Type::Vector:
12271 // FIXME: The merged type should be an ExtVector!
12272 if (areCompatVectorTypes(LHS: LHSCan->castAs<VectorType>(),
12273 RHS: RHSCan->castAs<VectorType>()))
12274 return LHS;
12275 return {};
12276 case Type::ConstantMatrix:
12277 if (areCompatMatrixTypes(LHS: LHSCan->castAs<ConstantMatrixType>(),
12278 RHS: RHSCan->castAs<ConstantMatrixType>()))
12279 return LHS;
12280 return {};
12281 case Type::ObjCObject: {
12282 // Check if the types are assignment compatible.
12283 // FIXME: This should be type compatibility, e.g. whether
12284 // "LHS x; RHS x;" at global scope is legal.
12285 if (canAssignObjCInterfaces(LHS: LHS->castAs<ObjCObjectType>(),
12286 RHS: RHS->castAs<ObjCObjectType>()))
12287 return LHS;
12288 return {};
12289 }
12290 case Type::ObjCObjectPointer:
12291 if (OfBlockPointer) {
12292 if (canAssignObjCInterfacesInBlockPointer(
12293 LHSOPT: LHS->castAs<ObjCObjectPointerType>(),
12294 RHSOPT: RHS->castAs<ObjCObjectPointerType>(), BlockReturnType))
12295 return LHS;
12296 return {};
12297 }
12298 if (canAssignObjCInterfaces(LHSOPT: LHS->castAs<ObjCObjectPointerType>(),
12299 RHSOPT: RHS->castAs<ObjCObjectPointerType>()))
12300 return LHS;
12301 return {};
12302 case Type::Pipe:
12303 assert(LHS != RHS &&
12304 "Equivalent pipe types should have already been handled!");
12305 return {};
12306 case Type::ArrayParameter:
12307 assert(LHS != RHS &&
12308 "Equivalent ArrayParameter types should have already been handled!");
12309 return {};
12310 case Type::BitInt: {
12311 // Merge two bit-precise int types, while trying to preserve typedef info.
12312 bool LHSUnsigned = LHS->castAs<BitIntType>()->isUnsigned();
12313 bool RHSUnsigned = RHS->castAs<BitIntType>()->isUnsigned();
12314 unsigned LHSBits = LHS->castAs<BitIntType>()->getNumBits();
12315 unsigned RHSBits = RHS->castAs<BitIntType>()->getNumBits();
12316
12317 // Like unsigned/int, shouldn't have a type if they don't match.
12318 if (LHSUnsigned != RHSUnsigned)
12319 return {};
12320
12321 if (LHSBits != RHSBits)
12322 return {};
12323 return LHS;
12324 }
12325 case Type::HLSLAttributedResource: {
12326 const HLSLAttributedResourceType *LHSTy =
12327 LHS->castAs<HLSLAttributedResourceType>();
12328 const HLSLAttributedResourceType *RHSTy =
12329 RHS->castAs<HLSLAttributedResourceType>();
12330 assert(LHSTy->getWrappedType() == RHSTy->getWrappedType() &&
12331 LHSTy->getWrappedType()->isHLSLResourceType() &&
12332 "HLSLAttributedResourceType should always wrap __hlsl_resource_t");
12333
12334 if (LHSTy->getAttrs() == RHSTy->getAttrs() &&
12335 LHSTy->getContainedType() == RHSTy->getContainedType())
12336 return LHS;
12337 return {};
12338 }
12339 case Type::HLSLInlineSpirv:
12340 const HLSLInlineSpirvType *LHSTy = LHS->castAs<HLSLInlineSpirvType>();
12341 const HLSLInlineSpirvType *RHSTy = RHS->castAs<HLSLInlineSpirvType>();
12342
12343 if (LHSTy->getOpcode() == RHSTy->getOpcode() &&
12344 LHSTy->getSize() == RHSTy->getSize() &&
12345 LHSTy->getAlignment() == RHSTy->getAlignment()) {
12346 for (size_t I = 0; I < LHSTy->getOperands().size(); I++)
12347 if (LHSTy->getOperands()[I] != RHSTy->getOperands()[I])
12348 return {};
12349
12350 return LHS;
12351 }
12352 return {};
12353 }
12354
12355 llvm_unreachable("Invalid Type::Class!");
12356}
12357
12358bool ASTContext::mergeExtParameterInfo(
12359 const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType,
12360 bool &CanUseFirst, bool &CanUseSecond,
12361 SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &NewParamInfos) {
12362 assert(NewParamInfos.empty() && "param info list not empty");
12363 CanUseFirst = CanUseSecond = true;
12364 bool FirstHasInfo = FirstFnType->hasExtParameterInfos();
12365 bool SecondHasInfo = SecondFnType->hasExtParameterInfos();
12366
12367 // Fast path: if the first type doesn't have ext parameter infos,
12368 // we match if and only if the second type also doesn't have them.
12369 if (!FirstHasInfo && !SecondHasInfo)
12370 return true;
12371
12372 bool NeedParamInfo = false;
12373 size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size()
12374 : SecondFnType->getExtParameterInfos().size();
12375
12376 for (size_t I = 0; I < E; ++I) {
12377 FunctionProtoType::ExtParameterInfo FirstParam, SecondParam;
12378 if (FirstHasInfo)
12379 FirstParam = FirstFnType->getExtParameterInfo(I);
12380 if (SecondHasInfo)
12381 SecondParam = SecondFnType->getExtParameterInfo(I);
12382
12383 // Cannot merge unless everything except the noescape flag matches.
12384 if (FirstParam.withIsNoEscape(NoEscape: false) != SecondParam.withIsNoEscape(NoEscape: false))
12385 return false;
12386
12387 bool FirstNoEscape = FirstParam.isNoEscape();
12388 bool SecondNoEscape = SecondParam.isNoEscape();
12389 bool IsNoEscape = FirstNoEscape && SecondNoEscape;
12390 NewParamInfos.push_back(Elt: FirstParam.withIsNoEscape(NoEscape: IsNoEscape));
12391 if (NewParamInfos.back().getOpaqueValue())
12392 NeedParamInfo = true;
12393 if (FirstNoEscape != IsNoEscape)
12394 CanUseFirst = false;
12395 if (SecondNoEscape != IsNoEscape)
12396 CanUseSecond = false;
12397 }
12398
12399 if (!NeedParamInfo)
12400 NewParamInfos.clear();
12401
12402 return true;
12403}
12404
12405void ASTContext::ResetObjCLayout(const ObjCInterfaceDecl *D) {
12406 if (auto It = ObjCLayouts.find(Val: D); It != ObjCLayouts.end()) {
12407 It->second = nullptr;
12408 for (auto *SubClass : ObjCSubClasses.lookup(Val: D))
12409 ResetObjCLayout(D: SubClass);
12410 }
12411}
12412
12413/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
12414/// 'RHS' attributes and returns the merged version; including for function
12415/// return types.
12416QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
12417 QualType LHSCan = getCanonicalType(T: LHS),
12418 RHSCan = getCanonicalType(T: RHS);
12419 // If two types are identical, they are compatible.
12420 if (LHSCan == RHSCan)
12421 return LHS;
12422 if (RHSCan->isFunctionType()) {
12423 if (!LHSCan->isFunctionType())
12424 return {};
12425 QualType OldReturnType =
12426 cast<FunctionType>(Val: RHSCan.getTypePtr())->getReturnType();
12427 QualType NewReturnType =
12428 cast<FunctionType>(Val: LHSCan.getTypePtr())->getReturnType();
12429 QualType ResReturnType =
12430 mergeObjCGCQualifiers(LHS: NewReturnType, RHS: OldReturnType);
12431 if (ResReturnType.isNull())
12432 return {};
12433 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
12434 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
12435 // In either case, use OldReturnType to build the new function type.
12436 const auto *F = LHS->castAs<FunctionType>();
12437 if (const auto *FPT = cast<FunctionProtoType>(Val: F)) {
12438 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12439 EPI.ExtInfo = getFunctionExtInfo(t: LHS);
12440 QualType ResultType =
12441 getFunctionType(ResultTy: OldReturnType, Args: FPT->getParamTypes(), EPI);
12442 return ResultType;
12443 }
12444 }
12445 return {};
12446 }
12447
12448 // If the qualifiers are different, the types can still be merged.
12449 Qualifiers LQuals = LHSCan.getLocalQualifiers();
12450 Qualifiers RQuals = RHSCan.getLocalQualifiers();
12451
12452 if (LQuals.withoutObjCGCAttr() != RQuals.withoutObjCGCAttr()) {
12453 // Reject immediately, if anything but the GC qualifiers is different.
12454 return {};
12455 }
12456
12457 if (LQuals != RQuals) {
12458 // Exactly one GC qualifier difference is allowed: __strong is
12459 // okay if the other type has no GC qualifier but is an Objective
12460 // C object pointer (i.e. implicitly strong by default). We fix
12461 // this by pretending that the unqualified type was actually
12462 // qualified __strong.
12463 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
12464 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
12465 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
12466
12467 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
12468 return {};
12469
12470 if (GC_L == Qualifiers::Strong)
12471 return LHS;
12472 if (GC_R == Qualifiers::Strong)
12473 return RHS;
12474 return {};
12475 }
12476
12477 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
12478 QualType LHSBaseQT = LHS->castAs<ObjCObjectPointerType>()->getPointeeType();
12479 QualType RHSBaseQT = RHS->castAs<ObjCObjectPointerType>()->getPointeeType();
12480 QualType ResQT = mergeObjCGCQualifiers(LHS: LHSBaseQT, RHS: RHSBaseQT);
12481 if (ResQT == LHSBaseQT)
12482 return LHS;
12483 if (ResQT == RHSBaseQT)
12484 return RHS;
12485 }
12486 return {};
12487}
12488
12489//===----------------------------------------------------------------------===//
12490// Integer Predicates
12491//===----------------------------------------------------------------------===//
12492
12493unsigned ASTContext::getIntWidth(QualType T) const {
12494 if (const auto *ED = T->getAsEnumDecl())
12495 T = ED->getIntegerType();
12496 if (T->isBooleanType())
12497 return 1;
12498 if (const auto *EIT = T->getAs<BitIntType>())
12499 return EIT->getNumBits();
12500 // For builtin types, just use the standard type sizing method
12501 return (unsigned)getTypeSize(T);
12502}
12503
12504QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
12505 assert((T->hasIntegerRepresentation() || T->isEnumeralType() ||
12506 T->isFixedPointType()) &&
12507 "Unexpected type");
12508
12509 // Turn <4 x signed int> -> <4 x unsigned int>
12510 if (const auto *VTy = T->getAs<VectorType>())
12511 return getVectorType(vecType: getCorrespondingUnsignedType(T: VTy->getElementType()),
12512 NumElts: VTy->getNumElements(), VecKind: VTy->getVectorKind());
12513
12514 // For _BitInt, return an unsigned _BitInt with same width.
12515 if (const auto *EITy = T->getAs<BitIntType>())
12516 return getBitIntType(/*Unsigned=*/IsUnsigned: true, NumBits: EITy->getNumBits());
12517
12518 // For the overflow behavior types, construct a new unsigned variant
12519 if (const auto *OBT = T->getAs<OverflowBehaviorType>())
12520 return getOverflowBehaviorType(
12521 Kind: OBT->getBehaviorKind(),
12522 Underlying: getCorrespondingUnsignedType(T: OBT->getUnderlyingType()));
12523
12524 // For enums, get the underlying integer type of the enum, and let the general
12525 // integer type signchanging code handle it.
12526 if (const auto *ED = T->getAsEnumDecl())
12527 T = ED->getIntegerType();
12528
12529 switch (T->castAs<BuiltinType>()->getKind()) {
12530 case BuiltinType::Char_U:
12531 // Plain `char` is mapped to `unsigned char` even if it's already unsigned
12532 case BuiltinType::Char_S:
12533 case BuiltinType::SChar:
12534 case BuiltinType::Char8:
12535 return UnsignedCharTy;
12536 case BuiltinType::Short:
12537 return UnsignedShortTy;
12538 case BuiltinType::Int:
12539 return UnsignedIntTy;
12540 case BuiltinType::Long:
12541 return UnsignedLongTy;
12542 case BuiltinType::LongLong:
12543 return UnsignedLongLongTy;
12544 case BuiltinType::Int128:
12545 return UnsignedInt128Ty;
12546 // wchar_t is special. It is either signed or not, but when it's signed,
12547 // there's no matching "unsigned wchar_t". Therefore we return the unsigned
12548 // version of its underlying type instead.
12549 case BuiltinType::WChar_S:
12550 return getUnsignedWCharType();
12551
12552 case BuiltinType::ShortAccum:
12553 return UnsignedShortAccumTy;
12554 case BuiltinType::Accum:
12555 return UnsignedAccumTy;
12556 case BuiltinType::LongAccum:
12557 return UnsignedLongAccumTy;
12558 case BuiltinType::SatShortAccum:
12559 return SatUnsignedShortAccumTy;
12560 case BuiltinType::SatAccum:
12561 return SatUnsignedAccumTy;
12562 case BuiltinType::SatLongAccum:
12563 return SatUnsignedLongAccumTy;
12564 case BuiltinType::ShortFract:
12565 return UnsignedShortFractTy;
12566 case BuiltinType::Fract:
12567 return UnsignedFractTy;
12568 case BuiltinType::LongFract:
12569 return UnsignedLongFractTy;
12570 case BuiltinType::SatShortFract:
12571 return SatUnsignedShortFractTy;
12572 case BuiltinType::SatFract:
12573 return SatUnsignedFractTy;
12574 case BuiltinType::SatLongFract:
12575 return SatUnsignedLongFractTy;
12576 default:
12577 assert((T->hasUnsignedIntegerRepresentation() ||
12578 T->isUnsignedFixedPointType()) &&
12579 "Unexpected signed integer or fixed point type");
12580 return T;
12581 }
12582}
12583
12584QualType ASTContext::getCorrespondingSignedType(QualType T) const {
12585 assert((T->hasIntegerRepresentation() || T->isEnumeralType() ||
12586 T->isFixedPointType()) &&
12587 "Unexpected type");
12588
12589 // Turn <4 x unsigned int> -> <4 x signed int>
12590 if (const auto *VTy = T->getAs<VectorType>())
12591 return getVectorType(vecType: getCorrespondingSignedType(T: VTy->getElementType()),
12592 NumElts: VTy->getNumElements(), VecKind: VTy->getVectorKind());
12593
12594 // For _BitInt, return a signed _BitInt with same width.
12595 if (const auto *EITy = T->getAs<BitIntType>())
12596 return getBitIntType(/*Unsigned=*/IsUnsigned: false, NumBits: EITy->getNumBits());
12597
12598 // For enums, get the underlying integer type of the enum, and let the general
12599 // integer type signchanging code handle it.
12600 if (const auto *ED = T->getAsEnumDecl())
12601 T = ED->getIntegerType();
12602
12603 switch (T->castAs<BuiltinType>()->getKind()) {
12604 case BuiltinType::Char_S:
12605 // Plain `char` is mapped to `signed char` even if it's already signed
12606 case BuiltinType::Char_U:
12607 case BuiltinType::UChar:
12608 case BuiltinType::Char8:
12609 return SignedCharTy;
12610 case BuiltinType::UShort:
12611 return ShortTy;
12612 case BuiltinType::UInt:
12613 return IntTy;
12614 case BuiltinType::ULong:
12615 return LongTy;
12616 case BuiltinType::ULongLong:
12617 return LongLongTy;
12618 case BuiltinType::UInt128:
12619 return Int128Ty;
12620 // wchar_t is special. It is either unsigned or not, but when it's unsigned,
12621 // there's no matching "signed wchar_t". Therefore we return the signed
12622 // version of its underlying type instead.
12623 case BuiltinType::WChar_U:
12624 return getSignedWCharType();
12625
12626 case BuiltinType::UShortAccum:
12627 return ShortAccumTy;
12628 case BuiltinType::UAccum:
12629 return AccumTy;
12630 case BuiltinType::ULongAccum:
12631 return LongAccumTy;
12632 case BuiltinType::SatUShortAccum:
12633 return SatShortAccumTy;
12634 case BuiltinType::SatUAccum:
12635 return SatAccumTy;
12636 case BuiltinType::SatULongAccum:
12637 return SatLongAccumTy;
12638 case BuiltinType::UShortFract:
12639 return ShortFractTy;
12640 case BuiltinType::UFract:
12641 return FractTy;
12642 case BuiltinType::ULongFract:
12643 return LongFractTy;
12644 case BuiltinType::SatUShortFract:
12645 return SatShortFractTy;
12646 case BuiltinType::SatUFract:
12647 return SatFractTy;
12648 case BuiltinType::SatULongFract:
12649 return SatLongFractTy;
12650 default:
12651 assert(
12652 (T->hasSignedIntegerRepresentation() || T->isSignedFixedPointType()) &&
12653 "Unexpected signed integer or fixed point type");
12654 return T;
12655 }
12656}
12657
12658ASTMutationListener::~ASTMutationListener() = default;
12659
12660void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
12661 QualType ReturnType) {}
12662
12663//===----------------------------------------------------------------------===//
12664// Builtin Type Computation
12665//===----------------------------------------------------------------------===//
12666
12667/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
12668/// pointer over the consumed characters. This returns the resultant type. If
12669/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
12670/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
12671/// a vector of "i*".
12672///
12673/// RequiresICE is filled in on return to indicate whether the value is required
12674/// to be an Integer Constant Expression.
12675static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
12676 ASTContext::GetBuiltinTypeError &Error,
12677 bool &RequiresICE,
12678 bool AllowTypeModifiers) {
12679 // Modifiers.
12680 int HowLong = 0;
12681 bool Signed = false, Unsigned = false;
12682 bool IsChar = false, IsShort = false;
12683 RequiresICE = false;
12684
12685 // Read the prefixed modifiers first.
12686 bool Done = false;
12687 #ifndef NDEBUG
12688 bool IsSpecial = false;
12689 #endif
12690 while (!Done) {
12691 switch (*Str++) {
12692 default: Done = true; --Str; break;
12693 case 'I':
12694 RequiresICE = true;
12695 break;
12696 case 'S':
12697 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
12698 assert(!Signed && "Can't use 'S' modifier multiple times!");
12699 Signed = true;
12700 break;
12701 case 'U':
12702 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
12703 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
12704 Unsigned = true;
12705 break;
12706 case 'B':
12707 // This modifier represents int8 type (byte-width).
12708 assert(!IsSpecial &&
12709 "Can't use two 'N', 'W', 'Z', 'O', 'B', or 'T' modifiers!");
12710 assert(HowLong == 0 && "Can't use both 'L' and 'B' modifiers!");
12711#ifndef NDEBUG
12712 IsSpecial = true;
12713#endif
12714 IsChar = true;
12715 break;
12716 case 'T':
12717 // This modifier represents int16 type (short-width).
12718 assert(!IsSpecial &&
12719 "Can't use two 'N', 'W', 'Z', 'O', 'B', or 'T' modifiers!");
12720 assert(HowLong == 0 && "Can't use both 'L' and 'T' modifiers!");
12721#ifndef NDEBUG
12722 IsSpecial = true;
12723#endif
12724 IsShort = true;
12725 break;
12726 case 'L':
12727 assert(!IsSpecial &&
12728 "Can't use 'L' with 'W', 'N', 'Z', 'O', 'B', or 'T' modifiers");
12729 assert(HowLong <= 2 && "Can't have LLLL modifier");
12730 ++HowLong;
12731 break;
12732 case 'N':
12733 // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
12734 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12735 assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
12736 #ifndef NDEBUG
12737 IsSpecial = true;
12738 #endif
12739 if (Context.getTargetInfo().getLongWidth() == 32)
12740 ++HowLong;
12741 break;
12742 case 'W':
12743 // This modifier represents int64 type.
12744 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12745 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
12746 #ifndef NDEBUG
12747 IsSpecial = true;
12748 #endif
12749 switch (Context.getTargetInfo().getInt64Type()) {
12750 default:
12751 llvm_unreachable("Unexpected integer type");
12752 case TargetInfo::SignedLong:
12753 HowLong = 1;
12754 break;
12755 case TargetInfo::SignedLongLong:
12756 HowLong = 2;
12757 break;
12758 }
12759 break;
12760 case 'Z':
12761 // This modifier represents int32 type.
12762 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12763 assert(HowLong == 0 && "Can't use both 'L' and 'Z' modifiers!");
12764 #ifndef NDEBUG
12765 IsSpecial = true;
12766 #endif
12767 switch (Context.getTargetInfo().getIntTypeByWidth(BitWidth: 32, IsSigned: true)) {
12768 default:
12769 llvm_unreachable("Unexpected integer type");
12770 case TargetInfo::SignedInt:
12771 HowLong = 0;
12772 break;
12773 case TargetInfo::SignedLong:
12774 HowLong = 1;
12775 break;
12776 case TargetInfo::SignedLongLong:
12777 HowLong = 2;
12778 break;
12779 }
12780 break;
12781 case 'O':
12782 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12783 assert(HowLong == 0 && "Can't use both 'L' and 'O' modifiers!");
12784 #ifndef NDEBUG
12785 IsSpecial = true;
12786 #endif
12787 if (Context.getLangOpts().OpenCL)
12788 HowLong = 1;
12789 else
12790 HowLong = 2;
12791 break;
12792 }
12793 }
12794
12795 QualType Type;
12796
12797 // Read the base type.
12798 switch (*Str++) {
12799 default:
12800 llvm_unreachable("Unknown builtin type letter!");
12801 case 'x':
12802 assert(HowLong == 0 && !Signed && !Unsigned &&
12803 "Bad modifiers used with 'x'!");
12804 Type = Context.Float16Ty;
12805 break;
12806 case 'y':
12807 assert(HowLong == 0 && !Signed && !Unsigned &&
12808 "Bad modifiers used with 'y'!");
12809 Type = Context.BFloat16Ty;
12810 break;
12811 case 'v':
12812 assert(HowLong == 0 && !Signed && !Unsigned &&
12813 "Bad modifiers used with 'v'!");
12814 Type = Context.VoidTy;
12815 break;
12816 case 'h':
12817 assert(HowLong == 0 && !Signed && !Unsigned &&
12818 "Bad modifiers used with 'h'!");
12819 Type = Context.HalfTy;
12820 break;
12821 case 'f':
12822 assert(HowLong == 0 && !Signed && !Unsigned &&
12823 "Bad modifiers used with 'f'!");
12824 Type = Context.FloatTy;
12825 break;
12826 case 'd':
12827 assert(HowLong < 3 && !Signed && !Unsigned &&
12828 "Bad modifiers used with 'd'!");
12829 if (HowLong == 1)
12830 Type = Context.LongDoubleTy;
12831 else if (HowLong == 2)
12832 Type = Context.Float128Ty;
12833 else
12834 Type = Context.DoubleTy;
12835 break;
12836 case 's':
12837 assert(HowLong == 0 && "Bad modifiers used with 's'!");
12838 if (Unsigned)
12839 Type = Context.UnsignedShortTy;
12840 else
12841 Type = Context.ShortTy;
12842 break;
12843 case 'i':
12844 if (IsChar)
12845 Type = Unsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
12846 else if (IsShort)
12847 Type = Unsigned ? Context.UnsignedShortTy : Context.ShortTy;
12848 else if (HowLong == 3)
12849 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
12850 else if (HowLong == 2)
12851 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
12852 else if (HowLong == 1)
12853 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
12854 else
12855 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
12856 break;
12857 case 'c':
12858 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
12859 if (Signed)
12860 Type = Context.SignedCharTy;
12861 else if (Unsigned)
12862 Type = Context.UnsignedCharTy;
12863 else
12864 Type = Context.CharTy;
12865 break;
12866 case 'b': // boolean
12867 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
12868 Type = Context.BoolTy;
12869 break;
12870 case 'z': // size_t.
12871 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
12872 Type = Context.getSizeType();
12873 break;
12874 case 'w': // wchar_t.
12875 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
12876 Type = Context.getWideCharType();
12877 break;
12878 case 'F':
12879 Type = Context.getCFConstantStringType();
12880 break;
12881 case 'G':
12882 Type = Context.getObjCIdType();
12883 break;
12884 case 'H':
12885 Type = Context.getObjCSelType();
12886 break;
12887 case 'M':
12888 Type = Context.getObjCSuperType();
12889 break;
12890 case 'a':
12891 Type = Context.getBuiltinVaListType();
12892 assert(!Type.isNull() && "builtin va list type not initialized!");
12893 break;
12894 case 'A':
12895 // This is a "reference" to a va_list; however, what exactly
12896 // this means depends on how va_list is defined. There are two
12897 // different kinds of va_list: ones passed by value, and ones
12898 // passed by reference. An example of a by-value va_list is
12899 // x86, where va_list is a char*. An example of by-ref va_list
12900 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
12901 // we want this argument to be a char*&; for x86-64, we want
12902 // it to be a __va_list_tag*.
12903 Type = Context.getBuiltinVaListType();
12904 assert(!Type.isNull() && "builtin va list type not initialized!");
12905 if (Type->isArrayType())
12906 Type = Context.getArrayDecayedType(Ty: Type);
12907 else
12908 Type = Context.getLValueReferenceType(T: Type);
12909 break;
12910 case 'q': {
12911 char *End;
12912 unsigned NumElements = strtoul(nptr: Str, endptr: &End, base: 10);
12913 assert(End != Str && "Missing vector size");
12914 Str = End;
12915
12916 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
12917 RequiresICE, AllowTypeModifiers: false);
12918 assert(!RequiresICE && "Can't require vector ICE");
12919
12920 Type = Context.getScalableVectorType(EltTy: ElementType, NumElts: NumElements);
12921 break;
12922 }
12923 case 'Q': {
12924 switch (*Str++) {
12925 case 'a': {
12926 Type = Context.SveCountTy;
12927 break;
12928 }
12929 case 'b': {
12930 Type = Context.AMDGPUBufferRsrcTy;
12931 break;
12932 }
12933 case 'c': {
12934 Type = Context.AMDGPUFeaturePredicateTy;
12935 break;
12936 }
12937 case 't': {
12938 Type = Context.AMDGPUTextureTy;
12939 break;
12940 }
12941 case 'r': {
12942 Type = Context.HLSLResourceTy;
12943 break;
12944 }
12945 default:
12946 llvm_unreachable("Unexpected target builtin type");
12947 }
12948 break;
12949 }
12950 case 'V': {
12951 char *End;
12952 unsigned NumElements = strtoul(nptr: Str, endptr: &End, base: 10);
12953 assert(End != Str && "Missing vector size");
12954 Str = End;
12955
12956 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
12957 RequiresICE, AllowTypeModifiers: false);
12958 assert(!RequiresICE && "Can't require vector ICE");
12959
12960 // TODO: No way to make AltiVec vectors in builtins yet.
12961 Type = Context.getVectorType(vecType: ElementType, NumElts: NumElements, VecKind: VectorKind::Generic);
12962 break;
12963 }
12964 case 'E': {
12965 char *End;
12966
12967 unsigned NumElements = strtoul(nptr: Str, endptr: &End, base: 10);
12968 assert(End != Str && "Missing vector size");
12969
12970 Str = End;
12971
12972 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
12973 AllowTypeModifiers: false);
12974 Type = Context.getExtVectorType(vecType: ElementType, NumElts: NumElements);
12975 break;
12976 }
12977 case 'X': {
12978 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
12979 AllowTypeModifiers: false);
12980 assert(!RequiresICE && "Can't require complex ICE");
12981 Type = Context.getComplexType(T: ElementType);
12982 break;
12983 }
12984 case 'Y':
12985 Type = Context.getPointerDiffType();
12986 break;
12987 case 'P':
12988 Type = Context.getFILEType();
12989 if (Type.isNull()) {
12990 Error = ASTContext::GE_Missing_stdio;
12991 return {};
12992 }
12993 break;
12994 case 'J':
12995 if (Signed)
12996 Type = Context.getsigjmp_bufType();
12997 else
12998 Type = Context.getjmp_bufType();
12999
13000 if (Type.isNull()) {
13001 Error = ASTContext::GE_Missing_setjmp;
13002 return {};
13003 }
13004 break;
13005 case 'K':
13006 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
13007 Type = Context.getucontext_tType();
13008
13009 if (Type.isNull()) {
13010 Error = ASTContext::GE_Missing_ucontext;
13011 return {};
13012 }
13013 break;
13014 case 'p':
13015 Type = Context.getProcessIDType();
13016 break;
13017 case 'm':
13018 Type = Context.MFloat8Ty;
13019 break;
13020 }
13021
13022 // If there are modifiers and if we're allowed to parse them, go for it.
13023 Done = !AllowTypeModifiers;
13024 while (!Done) {
13025 switch (char c = *Str++) {
13026 default: Done = true; --Str; break;
13027 case '*':
13028 case '&': {
13029 // Both pointers and references can have their pointee types
13030 // qualified with an address space.
13031 char *End;
13032 unsigned AddrSpace = strtoul(nptr: Str, endptr: &End, base: 10);
13033 if (End != Str) {
13034 // Note AddrSpace == 0 is not the same as an unspecified address space.
13035 Type = Context.getAddrSpaceQualType(
13036 T: Type,
13037 AddressSpace: Context.getLangASForBuiltinAddressSpace(AS: AddrSpace));
13038 Str = End;
13039 }
13040 if (c == '*')
13041 Type = Context.getPointerType(T: Type);
13042 else
13043 Type = Context.getLValueReferenceType(T: Type);
13044 break;
13045 }
13046 // FIXME: There's no way to have a built-in with an rvalue ref arg.
13047 case 'C':
13048 Type = Type.withConst();
13049 break;
13050 case 'D':
13051 Type = Context.getVolatileType(T: Type);
13052 break;
13053 case 'R':
13054 Type = Type.withRestrict();
13055 break;
13056 }
13057 }
13058
13059 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
13060 "Integer constant 'I' type must be an integer");
13061
13062 return Type;
13063}
13064
13065// On some targets such as PowerPC, some of the builtins are defined with custom
13066// type descriptors for target-dependent types. These descriptors are decoded in
13067// other functions, but it may be useful to be able to fall back to default
13068// descriptor decoding to define builtins mixing target-dependent and target-
13069// independent types. This function allows decoding one type descriptor with
13070// default decoding.
13071QualType ASTContext::DecodeTypeStr(const char *&Str, const ASTContext &Context,
13072 GetBuiltinTypeError &Error, bool &RequireICE,
13073 bool AllowTypeModifiers) const {
13074 return DecodeTypeFromStr(Str, Context, Error, RequiresICE&: RequireICE, AllowTypeModifiers);
13075}
13076
13077/// GetBuiltinType - Return the type for the specified builtin.
13078QualType ASTContext::GetBuiltinType(unsigned Id,
13079 GetBuiltinTypeError &Error,
13080 unsigned *IntegerConstantArgs) const {
13081 const char *TypeStr = BuiltinInfo.getTypeString(ID: Id);
13082 if (TypeStr[0] == '\0') {
13083 Error = GE_Missing_type;
13084 return {};
13085 }
13086
13087 SmallVector<QualType, 8> ArgTypes;
13088
13089 bool RequiresICE = false;
13090 Error = GE_None;
13091 QualType ResType = DecodeTypeFromStr(Str&: TypeStr, Context: *this, Error,
13092 RequiresICE, AllowTypeModifiers: true);
13093 if (Error != GE_None)
13094 return {};
13095
13096 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
13097
13098 while (TypeStr[0] && TypeStr[0] != '.') {
13099 QualType Ty = DecodeTypeFromStr(Str&: TypeStr, Context: *this, Error, RequiresICE, AllowTypeModifiers: true);
13100 if (Error != GE_None)
13101 return {};
13102
13103 // If this argument is required to be an IntegerConstantExpression and the
13104 // caller cares, fill in the bitmask we return.
13105 if (RequiresICE && IntegerConstantArgs)
13106 *IntegerConstantArgs |= 1 << ArgTypes.size();
13107
13108 // Do array -> pointer decay. The builtin should use the decayed type.
13109 if (Ty->isArrayType())
13110 Ty = getArrayDecayedType(Ty);
13111
13112 ArgTypes.push_back(Elt: Ty);
13113 }
13114
13115 if (Id == Builtin::BI__GetExceptionInfo)
13116 return {};
13117
13118 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
13119 "'.' should only occur at end of builtin type list!");
13120
13121 bool Variadic = (TypeStr[0] == '.');
13122
13123 FunctionType::ExtInfo EI(Target->getDefaultCallingConv());
13124 if (BuiltinInfo.isNoReturn(ID: Id))
13125 EI = EI.withNoReturn(noReturn: true);
13126
13127 // We really shouldn't be making a no-proto type here.
13128 if (ArgTypes.empty() && Variadic && !getLangOpts().requiresStrictPrototypes())
13129 return getFunctionNoProtoType(ResultTy: ResType, Info: EI);
13130
13131 FunctionProtoType::ExtProtoInfo EPI;
13132 EPI.ExtInfo = EI;
13133 EPI.Variadic = Variadic;
13134 if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(ID: Id))
13135 EPI.ExceptionSpec.Type =
13136 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
13137
13138 return getFunctionType(ResultTy: ResType, Args: ArgTypes, EPI);
13139}
13140
13141static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
13142 const FunctionDecl *FD) {
13143 if (!FD->isExternallyVisible())
13144 return GVA_Internal;
13145
13146 // Non-user-provided functions get emitted as weak definitions with every
13147 // use, no matter whether they've been explicitly instantiated etc.
13148 if (!FD->isUserProvided())
13149 return GVA_DiscardableODR;
13150
13151 GVALinkage External;
13152 switch (FD->getTemplateSpecializationKind()) {
13153 case TSK_Undeclared:
13154 case TSK_ExplicitSpecialization:
13155 External = GVA_StrongExternal;
13156 break;
13157
13158 case TSK_ExplicitInstantiationDefinition:
13159 return GVA_StrongODR;
13160
13161 // C++11 [temp.explicit]p10:
13162 // [ Note: The intent is that an inline function that is the subject of
13163 // an explicit instantiation declaration will still be implicitly
13164 // instantiated when used so that the body can be considered for
13165 // inlining, but that no out-of-line copy of the inline function would be
13166 // generated in the translation unit. -- end note ]
13167 case TSK_ExplicitInstantiationDeclaration:
13168 return GVA_AvailableExternally;
13169
13170 case TSK_ImplicitInstantiation:
13171 External = GVA_DiscardableODR;
13172 break;
13173 }
13174
13175 if (!FD->isInlined())
13176 return External;
13177
13178 if ((!Context.getLangOpts().CPlusPlus &&
13179 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13180 !FD->hasAttr<DLLExportAttr>()) ||
13181 FD->hasAttr<GNUInlineAttr>()) {
13182 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
13183
13184 // GNU or C99 inline semantics. Determine whether this symbol should be
13185 // externally visible.
13186 if (auto *Def = FD->getDefinition();
13187 Def && Def->isInlineDefinitionExternallyVisible())
13188 return External;
13189
13190 // C99 inline semantics, where the symbol is not externally visible.
13191 return GVA_AvailableExternally;
13192 }
13193
13194 // Functions specified with extern and inline in -fms-compatibility mode
13195 // forcibly get emitted. While the body of the function cannot be later
13196 // replaced, the function definition cannot be discarded.
13197 if (FD->isMSExternInline())
13198 return GVA_StrongODR;
13199
13200 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13201 isa<CXXConstructorDecl>(Val: FD) &&
13202 cast<CXXConstructorDecl>(Val: FD)->isInheritingConstructor() &&
13203 !FD->hasAttr<DLLExportAttr>()) {
13204 // Both Clang and MSVC implement inherited constructors as forwarding
13205 // thunks that delegate to the base constructor. Keep non-dllexport
13206 // inheriting constructor thunks internal since they are not needed
13207 // outside the translation unit.
13208 //
13209 // dllexport inherited constructors are exempted so they are externally
13210 // visible, matching MSVC's export behavior. Inherited constructors
13211 // whose parameters prevent ABI-compatible forwarding (e.g. callee-
13212 // cleanup types) are excluded from export in Sema to avoid silent
13213 // runtime mismatches.
13214 return GVA_Internal;
13215 }
13216
13217 return GVA_DiscardableODR;
13218}
13219
13220static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context,
13221 const Decl *D, GVALinkage L) {
13222 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
13223 // dllexport/dllimport on inline functions.
13224 if (D->hasAttr<DLLImportAttr>()) {
13225 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
13226 return GVA_AvailableExternally;
13227 } else if (D->hasAttr<DLLExportAttr>()) {
13228 if (L == GVA_DiscardableODR)
13229 return GVA_StrongODR;
13230 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice) {
13231 // Device-side functions with __global__ attribute must always be
13232 // visible externally so they can be launched from host.
13233 if (D->hasAttr<CUDAGlobalAttr>() &&
13234 (L == GVA_DiscardableODR || L == GVA_Internal))
13235 return GVA_StrongODR;
13236 // Single source offloading languages like CUDA/HIP need to be able to
13237 // access static device variables from host code of the same compilation
13238 // unit. This is done by externalizing the static variable with a shared
13239 // name between the host and device compilation which is the same for the
13240 // same compilation unit whereas different among different compilation
13241 // units.
13242 if (Context.shouldExternalize(D))
13243 return GVA_StrongExternal;
13244 }
13245 return L;
13246}
13247
13248/// Adjust the GVALinkage for a declaration based on what an external AST source
13249/// knows about whether there can be other definitions of this declaration.
13250static GVALinkage
13251adjustGVALinkageForExternalDefinitionKind(const ASTContext &Ctx, const Decl *D,
13252 GVALinkage L) {
13253 ExternalASTSource *Source = Ctx.getExternalSource();
13254 if (!Source)
13255 return L;
13256
13257 switch (Source->hasExternalDefinitions(D)) {
13258 case ExternalASTSource::EK_Never:
13259 // Other translation units rely on us to provide the definition.
13260 if (L == GVA_DiscardableODR)
13261 return GVA_StrongODR;
13262 break;
13263
13264 case ExternalASTSource::EK_Always:
13265 return GVA_AvailableExternally;
13266
13267 case ExternalASTSource::EK_ReplyHazy:
13268 break;
13269 }
13270 return L;
13271}
13272
13273GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
13274 return adjustGVALinkageForExternalDefinitionKind(Ctx: *this, D: FD,
13275 L: adjustGVALinkageForAttributes(Context: *this, D: FD,
13276 L: basicGVALinkageForFunction(Context: *this, FD)));
13277}
13278
13279static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
13280 const VarDecl *VD) {
13281 // As an extension for interactive REPLs, make sure constant variables are
13282 // only emitted once instead of LinkageComputer::getLVForNamespaceScopeDecl
13283 // marking them as internal.
13284 if (Context.getLangOpts().CPlusPlus &&
13285 Context.getLangOpts().IncrementalExtensions &&
13286 VD->getType().isConstQualified() &&
13287 !VD->getType().isVolatileQualified() && !VD->isInline() &&
13288 !isa<VarTemplateSpecializationDecl>(Val: VD) && !VD->getDescribedVarTemplate())
13289 return GVA_DiscardableODR;
13290
13291 if (!VD->isExternallyVisible())
13292 return GVA_Internal;
13293
13294 if (VD->isStaticLocal()) {
13295 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
13296 while (LexicalContext && !isa<FunctionDecl>(Val: LexicalContext))
13297 LexicalContext = LexicalContext->getLexicalParent();
13298
13299 // ObjC Blocks can create local variables that don't have a FunctionDecl
13300 // LexicalContext.
13301 if (!LexicalContext)
13302 return GVA_DiscardableODR;
13303
13304 // Otherwise, let the static local variable inherit its linkage from the
13305 // nearest enclosing function.
13306 auto StaticLocalLinkage =
13307 Context.GetGVALinkageForFunction(FD: cast<FunctionDecl>(Val: LexicalContext));
13308
13309 // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
13310 // be emitted in any object with references to the symbol for the object it
13311 // contains, whether inline or out-of-line."
13312 // Similar behavior is observed with MSVC. An alternative ABI could use
13313 // StrongODR/AvailableExternally to match the function, but none are
13314 // known/supported currently.
13315 if (StaticLocalLinkage == GVA_StrongODR ||
13316 StaticLocalLinkage == GVA_AvailableExternally)
13317 return GVA_DiscardableODR;
13318 return StaticLocalLinkage;
13319 }
13320
13321 // MSVC treats in-class initialized static data members as definitions.
13322 // By giving them non-strong linkage, out-of-line definitions won't
13323 // cause link errors.
13324 if (Context.isMSStaticDataMemberInlineDefinition(VD))
13325 return GVA_DiscardableODR;
13326
13327 // Most non-template variables have strong linkage; inline variables are
13328 // linkonce_odr or (occasionally, for compatibility) weak_odr.
13329 GVALinkage StrongLinkage;
13330 switch (Context.getInlineVariableDefinitionKind(VD)) {
13331 case ASTContext::InlineVariableDefinitionKind::None:
13332 StrongLinkage = GVA_StrongExternal;
13333 break;
13334 case ASTContext::InlineVariableDefinitionKind::Weak:
13335 case ASTContext::InlineVariableDefinitionKind::WeakUnknown:
13336 StrongLinkage = GVA_DiscardableODR;
13337 break;
13338 case ASTContext::InlineVariableDefinitionKind::Strong:
13339 StrongLinkage = GVA_StrongODR;
13340 break;
13341 }
13342
13343 switch (VD->getTemplateSpecializationKind()) {
13344 case TSK_Undeclared:
13345 return StrongLinkage;
13346
13347 case TSK_ExplicitSpecialization:
13348 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13349 VD->isStaticDataMember()
13350 ? GVA_StrongODR
13351 : StrongLinkage;
13352
13353 case TSK_ExplicitInstantiationDefinition:
13354 return GVA_StrongODR;
13355
13356 case TSK_ExplicitInstantiationDeclaration:
13357 return GVA_AvailableExternally;
13358
13359 case TSK_ImplicitInstantiation:
13360 return GVA_DiscardableODR;
13361 }
13362
13363 llvm_unreachable("Invalid Linkage!");
13364}
13365
13366GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) const {
13367 return adjustGVALinkageForExternalDefinitionKind(Ctx: *this, D: VD,
13368 L: adjustGVALinkageForAttributes(Context: *this, D: VD,
13369 L: basicGVALinkageForVariable(Context: *this, VD)));
13370}
13371
13372bool ASTContext::DeclMustBeEmitted(const Decl *D) {
13373 if (const auto *VD = dyn_cast<VarDecl>(Val: D)) {
13374 if (!VD->isFileVarDecl())
13375 return false;
13376 // Global named register variables (GNU extension) are never emitted.
13377 if (VD->getStorageClass() == SC_Register)
13378 return false;
13379 if (VD->getDescribedVarTemplate() ||
13380 isa<VarTemplatePartialSpecializationDecl>(Val: VD))
13381 return false;
13382 } else if (const auto *FD = dyn_cast<FunctionDecl>(Val: D)) {
13383 // We never need to emit an uninstantiated function template.
13384 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
13385 return false;
13386 } else if (isa<PragmaCommentDecl>(Val: D))
13387 return true;
13388 else if (isa<PragmaDetectMismatchDecl>(Val: D))
13389 return true;
13390 else if (isa<OMPRequiresDecl>(Val: D))
13391 return true;
13392 else if (isa<OMPThreadPrivateDecl>(Val: D))
13393 return !D->getDeclContext()->isDependentContext();
13394 else if (isa<OMPAllocateDecl>(Val: D))
13395 return !D->getDeclContext()->isDependentContext();
13396 else if (isa<OMPDeclareReductionDecl>(Val: D) || isa<OMPDeclareMapperDecl>(Val: D))
13397 return !D->getDeclContext()->isDependentContext();
13398 else if (isa<ImportDecl>(Val: D))
13399 return true;
13400 else
13401 return false;
13402
13403 // If this is a member of a class template, we do not need to emit it.
13404 if (D->getDeclContext()->isDependentContext())
13405 return false;
13406
13407 // Weak references don't produce any output by themselves.
13408 if (D->hasAttr<WeakRefAttr>())
13409 return false;
13410
13411 // SYCL device compilation requires that functions defined with the
13412 // sycl_kernel_entry_point or sycl_external attributes be emitted. All
13413 // other entities are emitted only if they are used by a function
13414 // defined with one of those attributes.
13415 if (LangOpts.SYCLIsDevice)
13416 return isa<FunctionDecl>(Val: D) && (D->hasAttr<SYCLKernelEntryPointAttr>() ||
13417 D->hasAttr<SYCLExternalAttr>());
13418
13419 // Aliases and used decls are required.
13420 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
13421 return true;
13422
13423 if (const auto *FD = dyn_cast<FunctionDecl>(Val: D)) {
13424 // Forward declarations aren't required.
13425 if (!FD->doesThisDeclarationHaveABody())
13426 return FD->doesDeclarationForceExternallyVisibleDefinition();
13427
13428 // Constructors and destructors are required.
13429 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
13430 return true;
13431
13432 // The key function for a class is required. This rule only comes
13433 // into play when inline functions can be key functions, though.
13434 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
13435 if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: FD)) {
13436 const CXXRecordDecl *RD = MD->getParent();
13437 if (MD->isOutOfLine() && RD->isDynamicClass()) {
13438 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
13439 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
13440 return true;
13441 }
13442 }
13443 }
13444
13445 GVALinkage Linkage = GetGVALinkageForFunction(FD);
13446
13447 // static, static inline, always_inline, and extern inline functions can
13448 // always be deferred. Normal inline functions can be deferred in C99/C++.
13449 // Implicit template instantiations can also be deferred in C++.
13450 return !isDiscardableGVALinkage(L: Linkage);
13451 }
13452
13453 const auto *VD = cast<VarDecl>(Val: D);
13454 assert(VD->isFileVarDecl() && "Expected file scoped var");
13455
13456 // If the decl is marked as `declare target to`, it should be emitted for the
13457 // host and for the device.
13458 if (LangOpts.OpenMP &&
13459 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
13460 return true;
13461
13462 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
13463 !isMSStaticDataMemberInlineDefinition(VD))
13464 return false;
13465
13466 if (VD->shouldEmitInExternalSource())
13467 return false;
13468
13469 // Variables that can be needed in other TUs are required.
13470 auto Linkage = GetGVALinkageForVariable(VD);
13471 if (!isDiscardableGVALinkage(L: Linkage))
13472 return true;
13473
13474 // We never need to emit a variable that is available in another TU.
13475 if (Linkage == GVA_AvailableExternally)
13476 return false;
13477
13478 // Variables that have destruction with side-effects are required.
13479 if (VD->needsDestruction(Ctx: *this))
13480 return true;
13481
13482 // Variables that have initialization with side-effects are required.
13483 if (VD->hasInitWithSideEffects())
13484 return true;
13485
13486 // Likewise, variables with tuple-like bindings are required if their
13487 // bindings have side-effects.
13488 if (const auto *DD = dyn_cast<DecompositionDecl>(Val: VD)) {
13489 for (const auto *BD : DD->flat_bindings())
13490 if (const auto *BindingVD = BD->getHoldingVar())
13491 if (DeclMustBeEmitted(D: BindingVD))
13492 return true;
13493 }
13494
13495 return false;
13496}
13497
13498void ASTContext::forEachMultiversionedFunctionVersion(
13499 const FunctionDecl *FD,
13500 llvm::function_ref<void(FunctionDecl *)> Pred) const {
13501 assert(FD->isMultiVersion() && "Only valid for multiversioned functions");
13502 llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls;
13503 FD = FD->getMostRecentDecl();
13504 // FIXME: The order of traversal here matters and depends on the order of
13505 // lookup results, which happens to be (mostly) oldest-to-newest, but we
13506 // shouldn't rely on that.
13507 for (auto *CurDecl :
13508 FD->getDeclContext()->getRedeclContext()->lookup(Name: FD->getDeclName())) {
13509 FunctionDecl *CurFD = CurDecl->getAsFunction()->getMostRecentDecl();
13510 if (CurFD && hasSameType(T1: CurFD->getType(), T2: FD->getType()) &&
13511 SeenDecls.insert(V: CurFD).second) {
13512 Pred(CurFD);
13513 }
13514 }
13515}
13516
13517CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
13518 bool IsCXXMethod) const {
13519 // Pass through to the C++ ABI object
13520 if (IsCXXMethod)
13521 return ABI->getDefaultMethodCallConv(isVariadic: IsVariadic);
13522
13523 switch (LangOpts.getDefaultCallingConv()) {
13524 case LangOptions::DCC_None:
13525 break;
13526 case LangOptions::DCC_CDecl:
13527 return CC_C;
13528 case LangOptions::DCC_FastCall:
13529 if (getTargetInfo().hasFeature(Feature: "sse2") && !IsVariadic)
13530 return CC_X86FastCall;
13531 break;
13532 case LangOptions::DCC_StdCall:
13533 if (!IsVariadic)
13534 return CC_X86StdCall;
13535 break;
13536 case LangOptions::DCC_VectorCall:
13537 // __vectorcall cannot be applied to variadic functions.
13538 if (!IsVariadic)
13539 return CC_X86VectorCall;
13540 break;
13541 case LangOptions::DCC_RegCall:
13542 // __regcall cannot be applied to variadic functions.
13543 if (!IsVariadic)
13544 return CC_X86RegCall;
13545 break;
13546 case LangOptions::DCC_RtdCall:
13547 if (!IsVariadic)
13548 return CC_M68kRTD;
13549 break;
13550 }
13551 return Target->getDefaultCallingConv();
13552}
13553
13554bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
13555 // Pass through to the C++ ABI object
13556 return ABI->isNearlyEmpty(RD);
13557}
13558
13559VTableContextBase *ASTContext::getVTableContext() {
13560 if (!VTContext) {
13561 auto ABI = Target->getCXXABI();
13562 if (ABI.isMicrosoft())
13563 VTContext.reset(p: new MicrosoftVTableContext(*this));
13564 else {
13565 VTContext.reset(p: new ItaniumVTableContext(*this));
13566 }
13567 }
13568 return VTContext.get();
13569}
13570
13571MangleContext *ASTContext::createMangleContext(const TargetInfo *T) {
13572 if (!T)
13573 T = Target;
13574 switch (T->getCXXABI().getKind()) {
13575 case TargetCXXABI::AppleARM64:
13576 case TargetCXXABI::Fuchsia:
13577 case TargetCXXABI::GenericAArch64:
13578 case TargetCXXABI::GenericItanium:
13579 case TargetCXXABI::GenericARM:
13580 case TargetCXXABI::GenericMIPS:
13581 case TargetCXXABI::iOS:
13582 case TargetCXXABI::WebAssembly:
13583 case TargetCXXABI::WatchOS:
13584 case TargetCXXABI::XL:
13585 return ItaniumMangleContext::create(Context&: *this, Diags&: getDiagnostics());
13586 case TargetCXXABI::Microsoft:
13587 return MicrosoftMangleContext::create(Context&: *this, Diags&: getDiagnostics());
13588 }
13589 llvm_unreachable("Unsupported ABI");
13590}
13591
13592MangleContext *ASTContext::createDeviceMangleContext(const TargetInfo &T) {
13593 assert(T.getCXXABI().getKind() != TargetCXXABI::Microsoft &&
13594 "Device mangle context does not support Microsoft mangling.");
13595 switch (T.getCXXABI().getKind()) {
13596 case TargetCXXABI::AppleARM64:
13597 case TargetCXXABI::Fuchsia:
13598 case TargetCXXABI::GenericAArch64:
13599 case TargetCXXABI::GenericItanium:
13600 case TargetCXXABI::GenericARM:
13601 case TargetCXXABI::GenericMIPS:
13602 case TargetCXXABI::iOS:
13603 case TargetCXXABI::WebAssembly:
13604 case TargetCXXABI::WatchOS:
13605 case TargetCXXABI::XL:
13606 return ItaniumMangleContext::create(
13607 Context&: *this, Diags&: getDiagnostics(),
13608 Discriminator: [](ASTContext &, const NamedDecl *ND) -> UnsignedOrNone {
13609 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: ND))
13610 return RD->getDeviceLambdaManglingNumber();
13611 return std::nullopt;
13612 },
13613 /*IsAux=*/true);
13614 case TargetCXXABI::Microsoft:
13615 return MicrosoftMangleContext::create(Context&: *this, Diags&: getDiagnostics(),
13616 /*IsAux=*/true);
13617 }
13618 llvm_unreachable("Unsupported ABI");
13619}
13620
13621MangleContext *ASTContext::cudaNVInitDeviceMC() {
13622 // If the host and device have different C++ ABIs, mark it as the device
13623 // mangle context so that the mangling needs to retrieve the additional
13624 // device lambda mangling number instead of the regular host one.
13625 if (getAuxTargetInfo() && getTargetInfo().getCXXABI().isMicrosoft() &&
13626 getAuxTargetInfo()->getCXXABI().isItaniumFamily()) {
13627 return createDeviceMangleContext(T: *getAuxTargetInfo());
13628 }
13629
13630 return createMangleContext(T: getAuxTargetInfo());
13631}
13632
13633CXXABI::~CXXABI() = default;
13634
13635size_t ASTContext::getSideTableAllocatedMemory() const {
13636 return ASTRecordLayouts.getMemorySize() +
13637 llvm::capacity_in_bytes(X: ObjCLayouts) +
13638 llvm::capacity_in_bytes(X: KeyFunctions) +
13639 llvm::capacity_in_bytes(X: ObjCImpls) +
13640 llvm::capacity_in_bytes(X: BlockVarCopyInits) +
13641 llvm::capacity_in_bytes(X: DeclAttrs) +
13642 llvm::capacity_in_bytes(X: TemplateOrInstantiation) +
13643 llvm::capacity_in_bytes(X: InstantiatedFromUsingDecl) +
13644 llvm::capacity_in_bytes(X: InstantiatedFromUsingShadowDecl) +
13645 llvm::capacity_in_bytes(X: InstantiatedFromUnnamedFieldDecl) +
13646 llvm::capacity_in_bytes(X: OverriddenMethods) +
13647 llvm::capacity_in_bytes(X: Types) +
13648 llvm::capacity_in_bytes(x: VariableArrayTypes);
13649}
13650
13651/// getIntTypeForBitwidth -
13652/// sets integer QualTy according to specified details:
13653/// bitwidth, signed/unsigned.
13654/// Returns empty type if there is no appropriate target types.
13655QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
13656 unsigned Signed) const {
13657 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(BitWidth: DestWidth, IsSigned: Signed);
13658 CanQualType QualTy = getFromTargetType(Type: Ty);
13659 if (!QualTy && DestWidth == 128)
13660 return Signed ? Int128Ty : UnsignedInt128Ty;
13661 return QualTy;
13662}
13663
13664QualType ASTContext::getLeastIntTypeForBitwidth(unsigned DestWidth,
13665 unsigned Signed) const {
13666 return getFromTargetType(
13667 Type: getTargetInfo().getLeastIntTypeByWidth(BitWidth: DestWidth, IsSigned: Signed));
13668}
13669
13670/// getRealTypeForBitwidth -
13671/// sets floating point QualTy according to specified bitwidth.
13672/// Returns empty type if there is no appropriate target types.
13673QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth,
13674 FloatModeKind ExplicitType) const {
13675 FloatModeKind Ty =
13676 getTargetInfo().getRealTypeByWidth(BitWidth: DestWidth, ExplicitType);
13677 switch (Ty) {
13678 case FloatModeKind::Half:
13679 return HalfTy;
13680 case FloatModeKind::Float:
13681 return FloatTy;
13682 case FloatModeKind::Double:
13683 return DoubleTy;
13684 case FloatModeKind::LongDouble:
13685 return LongDoubleTy;
13686 case FloatModeKind::Float128:
13687 return Float128Ty;
13688 case FloatModeKind::Ibm128:
13689 return Ibm128Ty;
13690 case FloatModeKind::NoFloat:
13691 return {};
13692 }
13693
13694 llvm_unreachable("Unhandled TargetInfo::RealType value");
13695}
13696
13697void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
13698 if (Number <= 1)
13699 return;
13700
13701 MangleNumbers[ND] = Number;
13702
13703 if (Listener)
13704 Listener->AddedManglingNumber(D: ND, Number);
13705}
13706
13707unsigned ASTContext::getManglingNumber(const NamedDecl *ND,
13708 bool ForAuxTarget) const {
13709 auto I = MangleNumbers.find(Key: ND);
13710 unsigned Res = I != MangleNumbers.end() ? I->second : 1;
13711 // CUDA/HIP host compilation encodes host and device mangling numbers
13712 // as lower and upper half of 32 bit integer.
13713 if (LangOpts.CUDA && !LangOpts.CUDAIsDevice) {
13714 Res = ForAuxTarget ? Res >> 16 : Res & 0xFFFF;
13715 } else {
13716 assert(!ForAuxTarget && "Only CUDA/HIP host compilation supports mangling "
13717 "number for aux target");
13718 }
13719 return Res > 1 ? Res : 1;
13720}
13721
13722void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
13723 if (Number <= 1)
13724 return;
13725
13726 StaticLocalNumbers[VD] = Number;
13727
13728 if (Listener)
13729 Listener->AddedStaticLocalNumbers(D: VD, Number);
13730}
13731
13732unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
13733 auto I = StaticLocalNumbers.find(Key: VD);
13734 return I != StaticLocalNumbers.end() ? I->second : 1;
13735}
13736
13737void ASTContext::setIsDestroyingOperatorDelete(const FunctionDecl *FD,
13738 bool IsDestroying) {
13739 if (!IsDestroying) {
13740 assert(!DestroyingOperatorDeletes.contains(FD->getCanonicalDecl()));
13741 return;
13742 }
13743 DestroyingOperatorDeletes.insert(V: FD->getCanonicalDecl());
13744}
13745
13746bool ASTContext::isDestroyingOperatorDelete(const FunctionDecl *FD) const {
13747 return DestroyingOperatorDeletes.contains(V: FD->getCanonicalDecl());
13748}
13749
13750void ASTContext::setIsTypeAwareOperatorNewOrDelete(const FunctionDecl *FD,
13751 bool IsTypeAware) {
13752 if (!IsTypeAware) {
13753 assert(!TypeAwareOperatorNewAndDeletes.contains(FD->getCanonicalDecl()));
13754 return;
13755 }
13756 TypeAwareOperatorNewAndDeletes.insert(V: FD->getCanonicalDecl());
13757}
13758
13759bool ASTContext::isTypeAwareOperatorNewOrDelete(const FunctionDecl *FD) const {
13760 return TypeAwareOperatorNewAndDeletes.contains(V: FD->getCanonicalDecl());
13761}
13762
13763void ASTContext::addOperatorDeleteForVDtor(const CXXDestructorDecl *Dtor,
13764 FunctionDecl *OperatorDelete,
13765 OperatorDeleteKind K) const {
13766 switch (K) {
13767 case OperatorDeleteKind::Regular:
13768 OperatorDeletesForVirtualDtor[Dtor->getCanonicalDecl()] = OperatorDelete;
13769 break;
13770 case OperatorDeleteKind::GlobalRegular:
13771 GlobalOperatorDeletesForVirtualDtor[Dtor->getCanonicalDecl()] =
13772 OperatorDelete;
13773 break;
13774 case OperatorDeleteKind::Array:
13775 ArrayOperatorDeletesForVirtualDtor[Dtor->getCanonicalDecl()] =
13776 OperatorDelete;
13777 break;
13778 case OperatorDeleteKind::ArrayGlobal:
13779 GlobalArrayOperatorDeletesForVirtualDtor[Dtor->getCanonicalDecl()] =
13780 OperatorDelete;
13781 break;
13782 }
13783}
13784
13785bool ASTContext::dtorHasOperatorDelete(const CXXDestructorDecl *Dtor,
13786 OperatorDeleteKind K) const {
13787 switch (K) {
13788 case OperatorDeleteKind::Regular:
13789 return OperatorDeletesForVirtualDtor.contains(Val: Dtor->getCanonicalDecl());
13790 case OperatorDeleteKind::GlobalRegular:
13791 return GlobalOperatorDeletesForVirtualDtor.contains(
13792 Val: Dtor->getCanonicalDecl());
13793 case OperatorDeleteKind::Array:
13794 return ArrayOperatorDeletesForVirtualDtor.contains(
13795 Val: Dtor->getCanonicalDecl());
13796 case OperatorDeleteKind::ArrayGlobal:
13797 return GlobalArrayOperatorDeletesForVirtualDtor.contains(
13798 Val: Dtor->getCanonicalDecl());
13799 }
13800 return false;
13801}
13802
13803FunctionDecl *
13804ASTContext::getOperatorDeleteForVDtor(const CXXDestructorDecl *Dtor,
13805 OperatorDeleteKind K) const {
13806 const CXXDestructorDecl *Canon = Dtor->getCanonicalDecl();
13807 switch (K) {
13808 case OperatorDeleteKind::Regular:
13809 if (OperatorDeletesForVirtualDtor.contains(Val: Canon))
13810 return OperatorDeletesForVirtualDtor[Canon];
13811 return nullptr;
13812 case OperatorDeleteKind::GlobalRegular:
13813 if (GlobalOperatorDeletesForVirtualDtor.contains(Val: Canon))
13814 return GlobalOperatorDeletesForVirtualDtor[Canon];
13815 return nullptr;
13816 case OperatorDeleteKind::Array:
13817 if (ArrayOperatorDeletesForVirtualDtor.contains(Val: Canon))
13818 return ArrayOperatorDeletesForVirtualDtor[Canon];
13819 return nullptr;
13820 case OperatorDeleteKind::ArrayGlobal:
13821 if (GlobalArrayOperatorDeletesForVirtualDtor.contains(Val: Canon))
13822 return GlobalArrayOperatorDeletesForVirtualDtor[Canon];
13823 return nullptr;
13824 }
13825 return nullptr;
13826}
13827
13828bool ASTContext::classMaybeNeedsVectorDeletingDestructor(
13829 const CXXRecordDecl *RD) {
13830 if (!getTargetInfo().emitVectorDeletingDtors(getLangOpts()))
13831 return false;
13832
13833 return MaybeRequireVectorDeletingDtor.count(V: RD);
13834}
13835
13836void ASTContext::setClassMaybeNeedsVectorDeletingDestructor(
13837 const CXXRecordDecl *RD) {
13838 if (!getTargetInfo().emitVectorDeletingDtors(getLangOpts()))
13839 return;
13840
13841 MaybeRequireVectorDeletingDtor.insert(V: RD);
13842}
13843
13844MangleNumberingContext &
13845ASTContext::getManglingNumberContext(const DeclContext *DC) {
13846 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
13847 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
13848 if (!MCtx)
13849 MCtx = createMangleNumberingContext();
13850 return *MCtx;
13851}
13852
13853MangleNumberingContext &
13854ASTContext::getManglingNumberContext(NeedExtraManglingDecl_t, const Decl *D) {
13855 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
13856 std::unique_ptr<MangleNumberingContext> &MCtx =
13857 ExtraMangleNumberingContexts[D];
13858 if (!MCtx)
13859 MCtx = createMangleNumberingContext();
13860 return *MCtx;
13861}
13862
13863std::unique_ptr<MangleNumberingContext>
13864ASTContext::createMangleNumberingContext() const {
13865 return ABI->createMangleNumberingContext();
13866}
13867
13868const CXXConstructorDecl *
13869ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
13870 return ABI->getCopyConstructorForExceptionObject(
13871 cast<CXXRecordDecl>(Val: RD->getFirstDecl()));
13872}
13873
13874void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
13875 CXXConstructorDecl *CD) {
13876 return ABI->addCopyConstructorForExceptionObject(
13877 cast<CXXRecordDecl>(Val: RD->getFirstDecl()),
13878 cast<CXXConstructorDecl>(Val: CD->getFirstDecl()));
13879}
13880
13881void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD,
13882 TypedefNameDecl *DD) {
13883 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
13884}
13885
13886TypedefNameDecl *
13887ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) {
13888 return ABI->getTypedefNameForUnnamedTagDecl(TD);
13889}
13890
13891void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD,
13892 DeclaratorDecl *DD) {
13893 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
13894}
13895
13896DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) {
13897 return ABI->getDeclaratorForUnnamedTagDecl(TD);
13898}
13899
13900void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
13901 ParamIndices[D] = index;
13902}
13903
13904unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
13905 ParameterIndexTable::const_iterator I = ParamIndices.find(Val: D);
13906 assert(I != ParamIndices.end() &&
13907 "ParmIndices lacks entry set by ParmVarDecl");
13908 return I->second;
13909}
13910
13911QualType ASTContext::getStringLiteralArrayType(QualType EltTy,
13912 unsigned Length) const {
13913 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
13914 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
13915 EltTy = EltTy.withConst();
13916
13917 EltTy = adjustStringLiteralBaseType(Ty: EltTy);
13918
13919 // Get an array type for the string, according to C99 6.4.5. This includes
13920 // the null terminator character.
13921 return getConstantArrayType(EltTy, ArySizeIn: llvm::APInt(32, Length + 1), SizeExpr: nullptr,
13922 ASM: ArraySizeModifier::Normal, /*IndexTypeQuals*/ 0);
13923}
13924
13925StringLiteral *
13926ASTContext::getPredefinedStringLiteralFromCache(StringRef Key) const {
13927 StringLiteral *&Result = StringLiteralCache[Key];
13928 if (!Result)
13929 Result = StringLiteral::Create(
13930 Ctx: *this, Str: Key, Kind: StringLiteralKind::Ordinary,
13931 /*Pascal*/ false, Ty: getStringLiteralArrayType(EltTy: CharTy, Length: Key.size()),
13932 Locs: SourceLocation());
13933 return Result;
13934}
13935
13936MSGuidDecl *
13937ASTContext::getMSGuidDecl(MSGuidDecl::Parts Parts) const {
13938 assert(MSGuidTagDecl && "building MS GUID without MS extensions?");
13939
13940 llvm::FoldingSetNodeID ID;
13941 MSGuidDecl::Profile(ID, P: Parts);
13942
13943 llvm::FoldingSetInsertToken Token;
13944 if (MSGuidDecl *Existing = MSGuidDecls.lookup(ID, Token))
13945 return Existing;
13946
13947 QualType GUIDType = getMSGuidType().withConst();
13948 MSGuidDecl *New = MSGuidDecl::Create(C: *this, T: GUIDType, P: Parts);
13949 MSGuidDecls.insert(N: New, Token);
13950 return New;
13951}
13952
13953UnnamedGlobalConstantDecl *
13954ASTContext::getUnnamedGlobalConstantDecl(QualType Ty,
13955 const APValue &APVal) const {
13956 llvm::FoldingSetNodeID ID;
13957 UnnamedGlobalConstantDecl::Profile(ID, Ty, APVal);
13958
13959 llvm::FoldingSetInsertToken Token;
13960 if (UnnamedGlobalConstantDecl *Existing =
13961 UnnamedGlobalConstantDecls.lookup(ID, Token))
13962 return Existing;
13963
13964 UnnamedGlobalConstantDecl *New =
13965 UnnamedGlobalConstantDecl::Create(C: *this, T: Ty, APVal);
13966 UnnamedGlobalConstantDecls.insert(N: New, Token);
13967 return New;
13968}
13969
13970TemplateParamObjectDecl *
13971ASTContext::getTemplateParamObjectDecl(QualType T, const APValue &V) const {
13972 assert(T->isRecordType() && "template param object of unexpected type");
13973
13974 // C++ [temp.param]p8:
13975 // [...] a static storage duration object of type 'const T' [...]
13976 T.addConst();
13977
13978 llvm::FoldingSetNodeID ID;
13979 TemplateParamObjectDecl::Profile(ID, T, V);
13980
13981 llvm::FoldingSetInsertToken Token;
13982 if (TemplateParamObjectDecl *Existing =
13983 TemplateParamObjectDecls.lookup(ID, Token))
13984 return Existing;
13985
13986 TemplateParamObjectDecl *New = TemplateParamObjectDecl::Create(C: *this, T, V);
13987 TemplateParamObjectDecls.insert(N: New, Token);
13988 return New;
13989}
13990
13991bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
13992 const llvm::Triple &T = getTargetInfo().getTriple();
13993 if (!T.isOSDarwin())
13994 return false;
13995
13996 if (!(T.isiOS() && T.isOSVersionLT(Major: 7)) &&
13997 !(T.isMacOSX() && T.isOSVersionLT(Major: 10, Minor: 9)))
13998 return false;
13999
14000 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
14001 CharUnits sizeChars = getTypeSizeInChars(T: AtomicTy);
14002 uint64_t Size = sizeChars.getQuantity();
14003 CharUnits alignChars = getTypeAlignInChars(T: AtomicTy);
14004 unsigned Align = alignChars.getQuantity();
14005 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
14006 return (Size != Align || toBits(CharSize: sizeChars) > MaxInlineWidthInBits);
14007}
14008
14009bool
14010ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
14011 const ObjCMethodDecl *MethodImpl) {
14012 // No point trying to match an unavailable/deprecated mothod.
14013 if (MethodDecl->hasAttr<UnavailableAttr>()
14014 || MethodDecl->hasAttr<DeprecatedAttr>())
14015 return false;
14016 if (MethodDecl->getObjCDeclQualifier() !=
14017 MethodImpl->getObjCDeclQualifier())
14018 return false;
14019 if (!hasSameType(T1: MethodDecl->getReturnType(), T2: MethodImpl->getReturnType()))
14020 return false;
14021
14022 if (MethodDecl->param_size() != MethodImpl->param_size())
14023 return false;
14024
14025 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
14026 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
14027 EF = MethodDecl->param_end();
14028 IM != EM && IF != EF; ++IM, ++IF) {
14029 const ParmVarDecl *DeclVar = (*IF);
14030 const ParmVarDecl *ImplVar = (*IM);
14031 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
14032 return false;
14033 if (!hasSameType(T1: DeclVar->getType(), T2: ImplVar->getType()))
14034 return false;
14035 }
14036
14037 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
14038}
14039
14040uint64_t ASTContext::getTargetNullPointerValue(QualType QT) const {
14041 LangAS AS;
14042 if (QT->getUnqualifiedDesugaredType()->isNullPtrType())
14043 AS = LangAS::Default;
14044 else
14045 AS = QT->getPointeeType().getAddressSpace();
14046
14047 return getTargetInfo().getNullPointerValue(AddrSpace: AS);
14048}
14049
14050unsigned ASTContext::getTargetAddressSpace(LangAS AS) const {
14051 return getTargetInfo().getTargetAddressSpace(AS);
14052}
14053
14054bool ASTContext::hasSameExpr(const Expr *X, const Expr *Y) const {
14055 if (X == Y)
14056 return true;
14057 if (!X || !Y)
14058 return false;
14059 llvm::FoldingSetNodeID IDX, IDY;
14060 X->Profile(ID&: IDX, Context: *this, /*Canonical=*/true);
14061 Y->Profile(ID&: IDY, Context: *this, /*Canonical=*/true);
14062 return IDX == IDY;
14063}
14064
14065// The getCommon* helpers return, for given 'same' X and Y entities given as
14066// inputs, another entity which is also the 'same' as the inputs, but which
14067// is closer to the canonical form of the inputs, each according to a given
14068// criteria.
14069// The getCommon*Checked variants are 'null inputs not-allowed' equivalents of
14070// the regular ones.
14071
14072static Decl *getCommonDecl(Decl *X, Decl *Y) {
14073 if (!declaresSameEntity(D1: X, D2: Y))
14074 return nullptr;
14075 for (const Decl *DX : X->redecls()) {
14076 // If we reach Y before reaching the first decl, that means X is older.
14077 if (DX == Y)
14078 return X;
14079 // If we reach the first decl, then Y is older.
14080 if (DX->isFirstDecl())
14081 return Y;
14082 }
14083 llvm_unreachable("Corrupt redecls chain");
14084}
14085
14086template <class T, std::enable_if_t<std::is_base_of_v<Decl, T>, bool> = true>
14087static T *getCommonDecl(T *X, T *Y) {
14088 return cast_or_null<T>(
14089 getCommonDecl(X: const_cast<Decl *>(cast_or_null<Decl>(X)),
14090 Y: const_cast<Decl *>(cast_or_null<Decl>(Y))));
14091}
14092
14093template <class T, std::enable_if_t<std::is_base_of_v<Decl, T>, bool> = true>
14094static T *getCommonDeclChecked(T *X, T *Y) {
14095 return cast<T>(getCommonDecl(X: const_cast<Decl *>(cast<Decl>(X)),
14096 Y: const_cast<Decl *>(cast<Decl>(Y))));
14097}
14098
14099static TemplateName getCommonTemplateName(const ASTContext &Ctx, TemplateName X,
14100 TemplateName Y,
14101 bool IgnoreDeduced = false) {
14102 if (X.getAsVoidPointer() == Y.getAsVoidPointer())
14103 return X;
14104 // FIXME: There are cases here where we could find a common template name
14105 // with more sugar. For example one could be a SubstTemplateTemplate*
14106 // replacing the other.
14107 TemplateName CX = Ctx.getCanonicalTemplateName(Name: X, IgnoreDeduced);
14108 if (CX.getAsVoidPointer() !=
14109 Ctx.getCanonicalTemplateName(Name: Y).getAsVoidPointer())
14110 return TemplateName();
14111 return CX;
14112}
14113
14114static TemplateName getCommonTemplateNameChecked(const ASTContext &Ctx,
14115 TemplateName X, TemplateName Y,
14116 bool IgnoreDeduced) {
14117 TemplateName R = getCommonTemplateName(Ctx, X, Y, IgnoreDeduced);
14118 assert(R.getAsVoidPointer() != nullptr);
14119 return R;
14120}
14121
14122static auto getCommonTypes(const ASTContext &Ctx, ArrayRef<QualType> Xs,
14123 ArrayRef<QualType> Ys, bool Unqualified = false) {
14124 assert(Xs.size() == Ys.size());
14125 SmallVector<QualType, 8> Rs(Xs.size());
14126 for (size_t I = 0; I < Rs.size(); ++I)
14127 Rs[I] = Ctx.getCommonSugaredType(X: Xs[I], Y: Ys[I], Unqualified);
14128 return Rs;
14129}
14130
14131template <class T>
14132static SourceLocation getCommonAttrLoc(const T *X, const T *Y) {
14133 return X->getAttributeLoc() == Y->getAttributeLoc() ? X->getAttributeLoc()
14134 : SourceLocation();
14135}
14136
14137static TemplateArgument getCommonTemplateArgument(const ASTContext &Ctx,
14138 const TemplateArgument &X,
14139 const TemplateArgument &Y) {
14140 if (X.getKind() != Y.getKind())
14141 return TemplateArgument();
14142
14143 switch (X.getKind()) {
14144 case TemplateArgument::ArgKind::Type:
14145 if (!Ctx.hasSameType(T1: X.getAsType(), T2: Y.getAsType()))
14146 return TemplateArgument();
14147 return TemplateArgument(
14148 Ctx.getCommonSugaredType(X: X.getAsType(), Y: Y.getAsType()));
14149 case TemplateArgument::ArgKind::NullPtr:
14150 if (!Ctx.hasSameType(T1: X.getNullPtrType(), T2: Y.getNullPtrType()))
14151 return TemplateArgument();
14152 return TemplateArgument(
14153 Ctx.getCommonSugaredType(X: X.getNullPtrType(), Y: Y.getNullPtrType()),
14154 /*Unqualified=*/true);
14155 case TemplateArgument::ArgKind::Expression:
14156 if (!Ctx.hasSameType(T1: X.getAsExpr()->getType(), T2: Y.getAsExpr()->getType()))
14157 return TemplateArgument();
14158 // FIXME: Try to keep the common sugar.
14159 return X;
14160 case TemplateArgument::ArgKind::Template: {
14161 TemplateName TX = X.getAsTemplate(), TY = Y.getAsTemplate();
14162 TemplateName CTN = ::getCommonTemplateName(Ctx, X: TX, Y: TY);
14163 if (!CTN.getAsVoidPointer())
14164 return TemplateArgument();
14165 return TemplateArgument(CTN);
14166 }
14167 case TemplateArgument::ArgKind::TemplateExpansion: {
14168 TemplateName TX = X.getAsTemplateOrTemplatePattern(),
14169 TY = Y.getAsTemplateOrTemplatePattern();
14170 TemplateName CTN = ::getCommonTemplateName(Ctx, X: TX, Y: TY);
14171 if (!CTN.getAsVoidPointer())
14172 return TemplateName();
14173 auto NExpX = X.getNumTemplateExpansions();
14174 assert(NExpX == Y.getNumTemplateExpansions());
14175 return TemplateArgument(CTN, NExpX);
14176 }
14177 default:
14178 // FIXME: Handle the other argument kinds.
14179 return X;
14180 }
14181}
14182
14183static bool getCommonTemplateArguments(const ASTContext &Ctx,
14184 SmallVectorImpl<TemplateArgument> &R,
14185 ArrayRef<TemplateArgument> Xs,
14186 ArrayRef<TemplateArgument> Ys) {
14187 if (Xs.size() != Ys.size())
14188 return true;
14189 R.resize(N: Xs.size());
14190 for (size_t I = 0; I < R.size(); ++I) {
14191 R[I] = getCommonTemplateArgument(Ctx, X: Xs[I], Y: Ys[I]);
14192 if (R[I].isNull())
14193 return true;
14194 }
14195 return false;
14196}
14197
14198static auto getCommonTemplateArguments(const ASTContext &Ctx,
14199 ArrayRef<TemplateArgument> Xs,
14200 ArrayRef<TemplateArgument> Ys) {
14201 SmallVector<TemplateArgument, 8> R;
14202 bool Different = getCommonTemplateArguments(Ctx, R, Xs, Ys);
14203 assert(!Different);
14204 (void)Different;
14205 return R;
14206}
14207
14208template <class T>
14209static ElaboratedTypeKeyword getCommonTypeKeyword(const T *X, const T *Y,
14210 bool IsSame) {
14211 ElaboratedTypeKeyword KX = X->getKeyword(), KY = Y->getKeyword();
14212 if (KX == KY)
14213 return KX;
14214 KX = getCanonicalElaboratedTypeKeyword(Keyword: KX);
14215 assert(!IsSame || KX == getCanonicalElaboratedTypeKeyword(KY));
14216 return KX;
14217}
14218
14219/// Returns a NestedNameSpecifier which has only the common sugar
14220/// present in both NNS1 and NNS2.
14221static NestedNameSpecifier getCommonNNS(const ASTContext &Ctx,
14222 NestedNameSpecifier NNS1,
14223 NestedNameSpecifier NNS2, bool IsSame) {
14224 // If they are identical, all sugar is common.
14225 if (NNS1 == NNS2)
14226 return NNS1;
14227
14228 // IsSame implies both Qualifiers are equivalent.
14229 NestedNameSpecifier Canon = NNS1.getCanonical();
14230 if (Canon != NNS2.getCanonical()) {
14231 assert(!IsSame && "Should be the same NestedNameSpecifier");
14232 // If they are not the same, there is nothing to unify.
14233 return std::nullopt;
14234 }
14235
14236 NestedNameSpecifier R = std::nullopt;
14237 NestedNameSpecifier::Kind Kind = NNS1.getKind();
14238 assert(Kind == NNS2.getKind());
14239 switch (Kind) {
14240 case NestedNameSpecifier::Kind::Namespace: {
14241 auto [Namespace1, Prefix1] = NNS1.getAsNamespaceAndPrefix();
14242 auto [Namespace2, Prefix2] = NNS2.getAsNamespaceAndPrefix();
14243 auto Kind = Namespace1->getKind();
14244 if (Kind != Namespace2->getKind() ||
14245 (Kind == Decl::NamespaceAlias &&
14246 !declaresSameEntity(D1: Namespace1, D2: Namespace2))) {
14247 R = NestedNameSpecifier(
14248 Ctx,
14249 ::getCommonDeclChecked(X: Namespace1->getNamespace(),
14250 Y: Namespace2->getNamespace()),
14251 /*Prefix=*/std::nullopt);
14252 break;
14253 }
14254 // The prefixes for namespaces are not significant, its declaration
14255 // identifies it uniquely.
14256 NestedNameSpecifier Prefix = ::getCommonNNS(Ctx, NNS1: Prefix1, NNS2: Prefix2,
14257 /*IsSame=*/false);
14258 R = NestedNameSpecifier(Ctx, ::getCommonDeclChecked(X: Namespace1, Y: Namespace2),
14259 Prefix);
14260 break;
14261 }
14262 case NestedNameSpecifier::Kind::Type: {
14263 const Type *T1 = NNS1.getAsType(), *T2 = NNS2.getAsType();
14264 const Type *T = Ctx.getCommonSugaredType(X: QualType(T1, 0), Y: QualType(T2, 0),
14265 /*Unqualified=*/true)
14266 .getTypePtr();
14267 R = NestedNameSpecifier(T);
14268 break;
14269 }
14270 case NestedNameSpecifier::Kind::MicrosoftSuper: {
14271 // FIXME: Can __super even be used with data members?
14272 // If it's only usable in functions, we will never see it here,
14273 // unless we save the qualifiers used in function types.
14274 // In that case, it might be possible NNS2 is a type,
14275 // in which case we should degrade the result to
14276 // a CXXRecordType.
14277 R = NestedNameSpecifier(getCommonDeclChecked(X: NNS1.getAsMicrosoftSuper(),
14278 Y: NNS2.getAsMicrosoftSuper()));
14279 break;
14280 }
14281 case NestedNameSpecifier::Kind::Null:
14282 case NestedNameSpecifier::Kind::Global:
14283 // These are singletons.
14284 llvm_unreachable("singletons did not compare equal");
14285 }
14286 assert(R.getCanonical() == Canon);
14287 return R;
14288}
14289
14290template <class T>
14291static NestedNameSpecifier getCommonQualifier(const ASTContext &Ctx, const T *X,
14292 const T *Y, bool IsSame) {
14293 return ::getCommonNNS(Ctx, NNS1: X->getQualifier(), NNS2: Y->getQualifier(), IsSame);
14294}
14295
14296template <class T>
14297static QualType getCommonElementType(const ASTContext &Ctx, const T *X,
14298 const T *Y) {
14299 return Ctx.getCommonSugaredType(X: X->getElementType(), Y: Y->getElementType());
14300}
14301
14302static QualType getCommonTypeWithQualifierLifting(const ASTContext &Ctx,
14303 QualType X, QualType Y,
14304 Qualifiers &QX,
14305 Qualifiers &QY) {
14306 QualType R = Ctx.getCommonSugaredType(X, Y,
14307 /*Unqualified=*/true);
14308 // Qualifiers common to both element types.
14309 Qualifiers RQ = R.getQualifiers();
14310 // For each side, move to the top level any qualifiers which are not common to
14311 // both element types. The caller must assume top level qualifiers might
14312 // be different, even if they are the same type, and can be treated as sugar.
14313 QX += X.getQualifiers() - RQ;
14314 QY += Y.getQualifiers() - RQ;
14315 return R;
14316}
14317
14318template <class T>
14319static QualType getCommonArrayElementType(const ASTContext &Ctx, const T *X,
14320 Qualifiers &QX, const T *Y,
14321 Qualifiers &QY) {
14322 return getCommonTypeWithQualifierLifting(Ctx, X->getElementType(),
14323 Y->getElementType(), QX, QY);
14324}
14325
14326template <class T>
14327static QualType getCommonPointeeType(const ASTContext &Ctx, const T *X,
14328 const T *Y) {
14329 return Ctx.getCommonSugaredType(X: X->getPointeeType(), Y: Y->getPointeeType());
14330}
14331
14332template <class T>
14333static auto *getCommonSizeExpr(const ASTContext &Ctx, T *X, T *Y) {
14334 assert(Ctx.hasSameExpr(X->getSizeExpr(), Y->getSizeExpr()));
14335 return X->getSizeExpr();
14336}
14337
14338static auto getCommonSizeModifier(const ArrayType *X, const ArrayType *Y) {
14339 assert(X->getSizeModifier() == Y->getSizeModifier());
14340 return X->getSizeModifier();
14341}
14342
14343static auto getCommonIndexTypeCVRQualifiers(const ArrayType *X,
14344 const ArrayType *Y) {
14345 assert(X->getIndexTypeCVRQualifiers() == Y->getIndexTypeCVRQualifiers());
14346 return X->getIndexTypeCVRQualifiers();
14347}
14348
14349// Merges two type lists such that the resulting vector will contain
14350// each type (in a canonical sense) only once, in the order they appear
14351// from X to Y. If they occur in both X and Y, the result will contain
14352// the common sugared type between them.
14353static void mergeTypeLists(const ASTContext &Ctx,
14354 SmallVectorImpl<QualType> &Out, ArrayRef<QualType> X,
14355 ArrayRef<QualType> Y) {
14356 llvm::DenseMap<QualType, unsigned> Found;
14357 for (auto Ts : {X, Y}) {
14358 for (QualType T : Ts) {
14359 auto Res = Found.try_emplace(Key: Ctx.getCanonicalType(T), Args: Out.size());
14360 if (!Res.second) {
14361 QualType &U = Out[Res.first->second];
14362 U = Ctx.getCommonSugaredType(X: U, Y: T);
14363 } else {
14364 Out.emplace_back(Args&: T);
14365 }
14366 }
14367 }
14368}
14369
14370FunctionProtoType::ExceptionSpecInfo
14371ASTContext::mergeExceptionSpecs(FunctionProtoType::ExceptionSpecInfo ESI1,
14372 FunctionProtoType::ExceptionSpecInfo ESI2,
14373 SmallVectorImpl<QualType> &ExceptionTypeStorage,
14374 bool AcceptDependent) const {
14375 ExceptionSpecificationType EST1 = ESI1.Type, EST2 = ESI2.Type;
14376
14377 // If either of them can throw anything, that is the result.
14378 for (auto I : {EST_None, EST_MSAny, EST_NoexceptFalse}) {
14379 if (EST1 == I)
14380 return ESI1;
14381 if (EST2 == I)
14382 return ESI2;
14383 }
14384
14385 // If either of them is non-throwing, the result is the other.
14386 for (auto I :
14387 {EST_NoThrow, EST_DynamicNone, EST_BasicNoexcept, EST_NoexceptTrue}) {
14388 if (EST1 == I)
14389 return ESI2;
14390 if (EST2 == I)
14391 return ESI1;
14392 }
14393
14394 // If we're left with value-dependent computed noexcept expressions, we're
14395 // stuck. Before C++17, we can just drop the exception specification entirely,
14396 // since it's not actually part of the canonical type. And this should never
14397 // happen in C++17, because it would mean we were computing the composite
14398 // pointer type of dependent types, which should never happen.
14399 if (EST1 == EST_DependentNoexcept || EST2 == EST_DependentNoexcept) {
14400 assert(AcceptDependent &&
14401 "computing composite pointer type of dependent types");
14402 return FunctionProtoType::ExceptionSpecInfo();
14403 }
14404
14405 // Switch over the possibilities so that people adding new values know to
14406 // update this function.
14407 switch (EST1) {
14408 case EST_None:
14409 case EST_DynamicNone:
14410 case EST_MSAny:
14411 case EST_BasicNoexcept:
14412 case EST_DependentNoexcept:
14413 case EST_NoexceptFalse:
14414 case EST_NoexceptTrue:
14415 case EST_NoThrow:
14416 llvm_unreachable("These ESTs should be handled above");
14417
14418 case EST_Dynamic: {
14419 // This is the fun case: both exception specifications are dynamic. Form
14420 // the union of the two lists.
14421 assert(EST2 == EST_Dynamic && "other cases should already be handled");
14422 mergeTypeLists(Ctx: *this, Out&: ExceptionTypeStorage, X: ESI1.Exceptions,
14423 Y: ESI2.Exceptions);
14424 FunctionProtoType::ExceptionSpecInfo Result(EST_Dynamic);
14425 Result.Exceptions = ExceptionTypeStorage;
14426 return Result;
14427 }
14428
14429 case EST_Unevaluated:
14430 case EST_Uninstantiated:
14431 case EST_Unparsed:
14432 llvm_unreachable("shouldn't see unresolved exception specifications here");
14433 }
14434
14435 llvm_unreachable("invalid ExceptionSpecificationType");
14436}
14437
14438static QualType getCommonNonSugarTypeNode(const ASTContext &Ctx, const Type *X,
14439 Qualifiers &QX, const Type *Y,
14440 Qualifiers &QY) {
14441 Type::TypeClass TC = X->getTypeClass();
14442 assert(TC == Y->getTypeClass());
14443 switch (TC) {
14444#define UNEXPECTED_TYPE(Class, Kind) \
14445 case Type::Class: \
14446 llvm_unreachable("Unexpected " Kind ": " #Class);
14447
14448#define NON_CANONICAL_TYPE(Class, Base) UNEXPECTED_TYPE(Class, "non-canonical")
14449#define TYPE(Class, Base)
14450#include "clang/AST/TypeNodes.inc"
14451
14452#define SUGAR_FREE_TYPE(Class) UNEXPECTED_TYPE(Class, "sugar-free")
14453 SUGAR_FREE_TYPE(Builtin)
14454 SUGAR_FREE_TYPE(DeducedTemplateSpecialization)
14455 SUGAR_FREE_TYPE(DependentBitInt)
14456 SUGAR_FREE_TYPE(BitInt)
14457 SUGAR_FREE_TYPE(ObjCInterface)
14458 SUGAR_FREE_TYPE(SubstTemplateTypeParmPack)
14459 SUGAR_FREE_TYPE(SubstBuiltinTemplatePack)
14460 SUGAR_FREE_TYPE(UnresolvedUsing)
14461 SUGAR_FREE_TYPE(HLSLAttributedResource)
14462 SUGAR_FREE_TYPE(HLSLInlineSpirv)
14463#undef SUGAR_FREE_TYPE
14464#define NON_UNIQUE_TYPE(Class) UNEXPECTED_TYPE(Class, "non-unique")
14465 NON_UNIQUE_TYPE(TypeOfExpr)
14466 NON_UNIQUE_TYPE(VariableArray)
14467#undef NON_UNIQUE_TYPE
14468
14469 UNEXPECTED_TYPE(TypeOf, "sugar")
14470
14471#undef UNEXPECTED_TYPE
14472
14473 case Type::Auto: {
14474 const auto *AX = cast<AutoType>(Val: X), *AY = cast<AutoType>(Val: Y);
14475 assert(AX->getDeducedKind() == AY->getDeducedKind());
14476 assert(AX->getDeducedKind() != DeducedKind::Deduced);
14477 assert(AX->getKeyword() == AY->getKeyword());
14478 TemplateDecl *CD =
14479 ::getCommonDecl(X: AX->getTypeConstraintConcept().getAsTemplateDecl(),
14480 Y: AY->getTypeConstraintConcept().getAsTemplateDecl());
14481 SmallVector<TemplateArgument, 8> As;
14482 if (CD &&
14483 getCommonTemplateArguments(Ctx, R&: As, Xs: AX->getTypeConstraintArguments(),
14484 Ys: AY->getTypeConstraintArguments())) {
14485 CD = nullptr; // The arguments differ, so make it unconstrained.
14486 As.clear();
14487 }
14488 return Ctx.getAutoType(DK: AX->getDeducedKind(), DeducedAsType: QualType(), Keyword: AX->getKeyword(),
14489 TypeConstraintConcept: TemplateName(CD), TypeConstraintArgs: As);
14490 }
14491 case Type::IncompleteArray: {
14492 const auto *AX = cast<IncompleteArrayType>(Val: X),
14493 *AY = cast<IncompleteArrayType>(Val: Y);
14494 return Ctx.getIncompleteArrayType(
14495 elementType: getCommonArrayElementType(Ctx, X: AX, QX, Y: AY, QY),
14496 ASM: getCommonSizeModifier(X: AX, Y: AY), elementTypeQuals: getCommonIndexTypeCVRQualifiers(X: AX, Y: AY));
14497 }
14498 case Type::DependentSizedArray: {
14499 const auto *AX = cast<DependentSizedArrayType>(Val: X),
14500 *AY = cast<DependentSizedArrayType>(Val: Y);
14501 return Ctx.getDependentSizedArrayType(
14502 elementType: getCommonArrayElementType(Ctx, X: AX, QX, Y: AY, QY),
14503 numElements: getCommonSizeExpr(Ctx, X: AX, Y: AY), ASM: getCommonSizeModifier(X: AX, Y: AY),
14504 elementTypeQuals: getCommonIndexTypeCVRQualifiers(X: AX, Y: AY));
14505 }
14506 case Type::ConstantArray: {
14507 const auto *AX = cast<ConstantArrayType>(Val: X),
14508 *AY = cast<ConstantArrayType>(Val: Y);
14509 assert(AX->getSize() == AY->getSize());
14510 const Expr *SizeExpr = Ctx.hasSameExpr(X: AX->getSizeExpr(), Y: AY->getSizeExpr())
14511 ? AX->getSizeExpr()
14512 : nullptr;
14513 return Ctx.getConstantArrayType(
14514 EltTy: getCommonArrayElementType(Ctx, X: AX, QX, Y: AY, QY), ArySizeIn: AX->getSize(), SizeExpr,
14515 ASM: getCommonSizeModifier(X: AX, Y: AY), IndexTypeQuals: getCommonIndexTypeCVRQualifiers(X: AX, Y: AY));
14516 }
14517 case Type::ArrayParameter: {
14518 const auto *AX = cast<ArrayParameterType>(Val: X),
14519 *AY = cast<ArrayParameterType>(Val: Y);
14520 assert(AX->getSize() == AY->getSize());
14521 const Expr *SizeExpr = Ctx.hasSameExpr(X: AX->getSizeExpr(), Y: AY->getSizeExpr())
14522 ? AX->getSizeExpr()
14523 : nullptr;
14524 auto ArrayTy = Ctx.getConstantArrayType(
14525 EltTy: getCommonArrayElementType(Ctx, X: AX, QX, Y: AY, QY), ArySizeIn: AX->getSize(), SizeExpr,
14526 ASM: getCommonSizeModifier(X: AX, Y: AY), IndexTypeQuals: getCommonIndexTypeCVRQualifiers(X: AX, Y: AY));
14527 return Ctx.getArrayParameterType(Ty: ArrayTy);
14528 }
14529 case Type::Atomic: {
14530 const auto *AX = cast<AtomicType>(Val: X), *AY = cast<AtomicType>(Val: Y);
14531 return Ctx.getAtomicType(
14532 T: Ctx.getCommonSugaredType(X: AX->getValueType(), Y: AY->getValueType()));
14533 }
14534 case Type::Complex: {
14535 const auto *CX = cast<ComplexType>(Val: X), *CY = cast<ComplexType>(Val: Y);
14536 return Ctx.getComplexType(T: getCommonArrayElementType(Ctx, X: CX, QX, Y: CY, QY));
14537 }
14538 case Type::Pointer: {
14539 const auto *PX = cast<PointerType>(Val: X), *PY = cast<PointerType>(Val: Y);
14540 return Ctx.getPointerType(T: getCommonPointeeType(Ctx, X: PX, Y: PY));
14541 }
14542 case Type::BlockPointer: {
14543 const auto *PX = cast<BlockPointerType>(Val: X), *PY = cast<BlockPointerType>(Val: Y);
14544 return Ctx.getBlockPointerType(T: getCommonPointeeType(Ctx, X: PX, Y: PY));
14545 }
14546 case Type::ObjCObjectPointer: {
14547 const auto *PX = cast<ObjCObjectPointerType>(Val: X),
14548 *PY = cast<ObjCObjectPointerType>(Val: Y);
14549 return Ctx.getObjCObjectPointerType(ObjectT: getCommonPointeeType(Ctx, X: PX, Y: PY));
14550 }
14551 case Type::MemberPointer: {
14552 const auto *PX = cast<MemberPointerType>(Val: X),
14553 *PY = cast<MemberPointerType>(Val: Y);
14554 assert(declaresSameEntity(PX->getMostRecentCXXRecordDecl(),
14555 PY->getMostRecentCXXRecordDecl()));
14556 return Ctx.getMemberPointerType(
14557 T: getCommonPointeeType(Ctx, X: PX, Y: PY),
14558 Qualifier: getCommonQualifier(Ctx, X: PX, Y: PY, /*IsSame=*/true),
14559 Cls: PX->getMostRecentCXXRecordDecl());
14560 }
14561 case Type::LValueReference: {
14562 const auto *PX = cast<LValueReferenceType>(Val: X),
14563 *PY = cast<LValueReferenceType>(Val: Y);
14564 // FIXME: Preserve PointeeTypeAsWritten.
14565 return Ctx.getLValueReferenceType(T: getCommonPointeeType(Ctx, X: PX, Y: PY),
14566 SpelledAsLValue: PX->isSpelledAsLValue() ||
14567 PY->isSpelledAsLValue());
14568 }
14569 case Type::RValueReference: {
14570 const auto *PX = cast<RValueReferenceType>(Val: X),
14571 *PY = cast<RValueReferenceType>(Val: Y);
14572 // FIXME: Preserve PointeeTypeAsWritten.
14573 return Ctx.getRValueReferenceType(T: getCommonPointeeType(Ctx, X: PX, Y: PY));
14574 }
14575 case Type::DependentAddressSpace: {
14576 const auto *PX = cast<DependentAddressSpaceType>(Val: X),
14577 *PY = cast<DependentAddressSpaceType>(Val: Y);
14578 assert(Ctx.hasSameExpr(PX->getAddrSpaceExpr(), PY->getAddrSpaceExpr()));
14579 return Ctx.getDependentAddressSpaceType(PointeeType: getCommonPointeeType(Ctx, X: PX, Y: PY),
14580 AddrSpaceExpr: PX->getAddrSpaceExpr(),
14581 AttrLoc: getCommonAttrLoc(X: PX, Y: PY));
14582 }
14583 case Type::FunctionNoProto: {
14584 const auto *FX = cast<FunctionNoProtoType>(Val: X),
14585 *FY = cast<FunctionNoProtoType>(Val: Y);
14586 assert(FX->getExtInfo() == FY->getExtInfo());
14587 return Ctx.getFunctionNoProtoType(
14588 ResultTy: Ctx.getCommonSugaredType(X: FX->getReturnType(), Y: FY->getReturnType()),
14589 Info: FX->getExtInfo());
14590 }
14591 case Type::FunctionProto: {
14592 const auto *FX = cast<FunctionProtoType>(Val: X),
14593 *FY = cast<FunctionProtoType>(Val: Y);
14594 FunctionProtoType::ExtProtoInfo EPIX = FX->getExtProtoInfo(),
14595 EPIY = FY->getExtProtoInfo();
14596 assert(EPIX.ExtInfo == EPIY.ExtInfo);
14597 assert(!EPIX.ExtParameterInfos == !EPIY.ExtParameterInfos);
14598 assert(!EPIX.ExtParameterInfos ||
14599 llvm::equal(
14600 llvm::ArrayRef(EPIX.ExtParameterInfos, FX->getNumParams()),
14601 llvm::ArrayRef(EPIY.ExtParameterInfos, FY->getNumParams())));
14602 assert(EPIX.RefQualifier == EPIY.RefQualifier);
14603 assert(EPIX.TypeQuals == EPIY.TypeQuals);
14604 assert(EPIX.Variadic == EPIY.Variadic);
14605
14606 // FIXME: Can we handle an empty EllipsisLoc?
14607 // Use emtpy EllipsisLoc if X and Y differ.
14608
14609 EPIX.HasTrailingReturn = EPIX.HasTrailingReturn && EPIY.HasTrailingReturn;
14610
14611 QualType R =
14612 Ctx.getCommonSugaredType(X: FX->getReturnType(), Y: FY->getReturnType());
14613 auto P = getCommonTypes(Ctx, Xs: FX->param_types(), Ys: FY->param_types(),
14614 /*Unqualified=*/true);
14615
14616 SmallVector<QualType, 8> Exceptions;
14617 EPIX.ExceptionSpec = Ctx.mergeExceptionSpecs(
14618 ESI1: EPIX.ExceptionSpec, ESI2: EPIY.ExceptionSpec, ExceptionTypeStorage&: Exceptions, AcceptDependent: true);
14619 return Ctx.getFunctionType(ResultTy: R, Args: P, EPI: EPIX);
14620 }
14621 case Type::ObjCObject: {
14622 const auto *OX = cast<ObjCObjectType>(Val: X), *OY = cast<ObjCObjectType>(Val: Y);
14623 assert(
14624 std::equal(OX->getProtocols().begin(), OX->getProtocols().end(),
14625 OY->getProtocols().begin(), OY->getProtocols().end(),
14626 [](const ObjCProtocolDecl *P0, const ObjCProtocolDecl *P1) {
14627 return P0->getCanonicalDecl() == P1->getCanonicalDecl();
14628 }) &&
14629 "protocol lists must be the same");
14630 auto TAs = getCommonTypes(Ctx, Xs: OX->getTypeArgsAsWritten(),
14631 Ys: OY->getTypeArgsAsWritten());
14632 return Ctx.getObjCObjectType(
14633 baseType: Ctx.getCommonSugaredType(X: OX->getBaseType(), Y: OY->getBaseType()), typeArgs: TAs,
14634 protocols: OX->getProtocols(),
14635 isKindOf: OX->isKindOfTypeAsWritten() && OY->isKindOfTypeAsWritten());
14636 }
14637 case Type::ConstantMatrix: {
14638 const auto *MX = cast<ConstantMatrixType>(Val: X),
14639 *MY = cast<ConstantMatrixType>(Val: Y);
14640 assert(MX->getNumRows() == MY->getNumRows());
14641 assert(MX->getNumColumns() == MY->getNumColumns());
14642 return Ctx.getConstantMatrixType(ElementTy: getCommonElementType(Ctx, X: MX, Y: MY),
14643 NumRows: MX->getNumRows(), NumColumns: MX->getNumColumns());
14644 }
14645 case Type::DependentSizedMatrix: {
14646 const auto *MX = cast<DependentSizedMatrixType>(Val: X),
14647 *MY = cast<DependentSizedMatrixType>(Val: Y);
14648 assert(Ctx.hasSameExpr(MX->getRowExpr(), MY->getRowExpr()));
14649 assert(Ctx.hasSameExpr(MX->getColumnExpr(), MY->getColumnExpr()));
14650 return Ctx.getDependentSizedMatrixType(
14651 ElementTy: getCommonElementType(Ctx, X: MX, Y: MY), RowExpr: MX->getRowExpr(),
14652 ColumnExpr: MX->getColumnExpr(), AttrLoc: getCommonAttrLoc(X: MX, Y: MY));
14653 }
14654 case Type::Vector: {
14655 const auto *VX = cast<VectorType>(Val: X), *VY = cast<VectorType>(Val: Y);
14656 assert(VX->getNumElements() == VY->getNumElements());
14657 assert(VX->getVectorKind() == VY->getVectorKind());
14658 return Ctx.getVectorType(vecType: getCommonElementType(Ctx, X: VX, Y: VY),
14659 NumElts: VX->getNumElements(), VecKind: VX->getVectorKind());
14660 }
14661 case Type::ExtVector: {
14662 const auto *VX = cast<ExtVectorType>(Val: X), *VY = cast<ExtVectorType>(Val: Y);
14663 assert(VX->getNumElements() == VY->getNumElements());
14664 return Ctx.getExtVectorType(vecType: getCommonElementType(Ctx, X: VX, Y: VY),
14665 NumElts: VX->getNumElements());
14666 }
14667 case Type::DependentSizedExtVector: {
14668 const auto *VX = cast<DependentSizedExtVectorType>(Val: X),
14669 *VY = cast<DependentSizedExtVectorType>(Val: Y);
14670 return Ctx.getDependentSizedExtVectorType(vecType: getCommonElementType(Ctx, X: VX, Y: VY),
14671 SizeExpr: getCommonSizeExpr(Ctx, X: VX, Y: VY),
14672 AttrLoc: getCommonAttrLoc(X: VX, Y: VY));
14673 }
14674 case Type::DependentVector: {
14675 const auto *VX = cast<DependentVectorType>(Val: X),
14676 *VY = cast<DependentVectorType>(Val: Y);
14677 assert(VX->getVectorKind() == VY->getVectorKind());
14678 return Ctx.getDependentVectorType(
14679 VecType: getCommonElementType(Ctx, X: VX, Y: VY), SizeExpr: getCommonSizeExpr(Ctx, X: VX, Y: VY),
14680 AttrLoc: getCommonAttrLoc(X: VX, Y: VY), VecKind: VX->getVectorKind());
14681 }
14682 case Type::Enum:
14683 case Type::Record:
14684 case Type::InjectedClassName: {
14685 const auto *TX = cast<TagType>(Val: X), *TY = cast<TagType>(Val: Y);
14686 return Ctx.getTagType(Keyword: ::getCommonTypeKeyword(X: TX, Y: TY, /*IsSame=*/false),
14687 Qualifier: ::getCommonQualifier(Ctx, X: TX, Y: TY, /*IsSame=*/false),
14688 TD: ::getCommonDeclChecked(X: TX->getDecl(), Y: TY->getDecl()),
14689 /*OwnedTag=*/OwnsTag: false);
14690 }
14691 case Type::TemplateSpecialization: {
14692 const auto *TX = cast<TemplateSpecializationType>(Val: X),
14693 *TY = cast<TemplateSpecializationType>(Val: Y);
14694 auto As = getCommonTemplateArguments(Ctx, Xs: TX->template_arguments(),
14695 Ys: TY->template_arguments());
14696 return Ctx.getTemplateSpecializationType(
14697 Keyword: getCommonTypeKeyword(X: TX, Y: TY, /*IsSame=*/false),
14698 Template: ::getCommonTemplateNameChecked(Ctx, X: TX->getTemplateName(),
14699 Y: TY->getTemplateName(),
14700 /*IgnoreDeduced=*/true),
14701 SpecifiedArgs: As, /*CanonicalArgs=*/{}, Underlying: X->getCanonicalTypeInternal());
14702 }
14703 case Type::Decltype: {
14704 const auto *DX = cast<DecltypeType>(Val: X);
14705 [[maybe_unused]] const auto *DY = cast<DecltypeType>(Val: Y);
14706 assert(DX->isDependentType());
14707 assert(DY->isDependentType());
14708 assert(Ctx.hasSameExpr(DX->getUnderlyingExpr(), DY->getUnderlyingExpr()));
14709 // As Decltype is not uniqued, building a common type would be wasteful.
14710 return QualType(DX, 0);
14711 }
14712 case Type::PackIndexing: {
14713 const auto *DX = cast<PackIndexingType>(Val: X);
14714 [[maybe_unused]] const auto *DY = cast<PackIndexingType>(Val: Y);
14715 assert(DX->isDependentType());
14716 assert(DY->isDependentType());
14717 assert(Ctx.hasSameExpr(DX->getIndexExpr(), DY->getIndexExpr()));
14718 return QualType(DX, 0);
14719 }
14720 case Type::DependentName: {
14721 const auto *NX = cast<DependentNameType>(Val: X),
14722 *NY = cast<DependentNameType>(Val: Y);
14723 assert(NX->getIdentifier() == NY->getIdentifier());
14724 return Ctx.getDependentNameType(
14725 Keyword: getCommonTypeKeyword(X: NX, Y: NY, /*IsSame=*/true),
14726 NNS: getCommonQualifier(Ctx, X: NX, Y: NY, /*IsSame=*/true), Name: NX->getIdentifier());
14727 }
14728 case Type::OverflowBehavior: {
14729 const auto *NX = cast<OverflowBehaviorType>(Val: X),
14730 *NY = cast<OverflowBehaviorType>(Val: Y);
14731 assert(NX->getBehaviorKind() == NY->getBehaviorKind());
14732 return Ctx.getOverflowBehaviorType(
14733 Kind: NX->getBehaviorKind(),
14734 Underlying: getCommonTypeWithQualifierLifting(Ctx, X: NX->getUnderlyingType(),
14735 Y: NY->getUnderlyingType(), QX, QY));
14736 }
14737 case Type::UnaryTransform: {
14738 const auto *TX = cast<UnaryTransformType>(Val: X),
14739 *TY = cast<UnaryTransformType>(Val: Y);
14740 assert(TX->getUTTKind() == TY->getUTTKind());
14741 return Ctx.getUnaryTransformType(
14742 BaseType: Ctx.getCommonSugaredType(X: TX->getBaseType(), Y: TY->getBaseType()),
14743 UnderlyingType: Ctx.getCommonSugaredType(X: TX->getUnderlyingType(),
14744 Y: TY->getUnderlyingType()),
14745 Kind: TX->getUTTKind());
14746 }
14747 case Type::PackExpansion: {
14748 const auto *PX = cast<PackExpansionType>(Val: X),
14749 *PY = cast<PackExpansionType>(Val: Y);
14750 assert(PX->getNumExpansions() == PY->getNumExpansions());
14751 return Ctx.getPackExpansionType(
14752 Pattern: Ctx.getCommonSugaredType(X: PX->getPattern(), Y: PY->getPattern()),
14753 NumExpansions: PX->getNumExpansions(), ExpectPackInType: false);
14754 }
14755 case Type::Pipe: {
14756 const auto *PX = cast<PipeType>(Val: X), *PY = cast<PipeType>(Val: Y);
14757 assert(PX->isReadOnly() == PY->isReadOnly());
14758 auto MP = PX->isReadOnly() ? &ASTContext::getReadPipeType
14759 : &ASTContext::getWritePipeType;
14760 return (Ctx.*MP)(getCommonElementType(Ctx, X: PX, Y: PY));
14761 }
14762 case Type::TemplateTypeParm: {
14763 const auto *TX = cast<TemplateTypeParmType>(Val: X),
14764 *TY = cast<TemplateTypeParmType>(Val: Y);
14765 assert(TX->getDepth() == TY->getDepth());
14766 assert(TX->getIndex() == TY->getIndex());
14767 assert(TX->isParameterPack() == TY->isParameterPack());
14768 return Ctx.getTemplateTypeParmType(
14769 Depth: TX->getDepth(), Index: TX->getIndex(), ParameterPack: TX->isParameterPack(),
14770 TTPDecl: getCommonDecl(X: TX->getDecl(), Y: TY->getDecl()));
14771 }
14772 }
14773 llvm_unreachable("Unknown Type Class");
14774}
14775
14776static QualType getCommonSugarTypeNode(const ASTContext &Ctx, const Type *X,
14777 const Type *Y,
14778 SplitQualType Underlying) {
14779 Type::TypeClass TC = X->getTypeClass();
14780 if (TC != Y->getTypeClass())
14781 return QualType();
14782 switch (TC) {
14783#define UNEXPECTED_TYPE(Class, Kind) \
14784 case Type::Class: \
14785 llvm_unreachable("Unexpected " Kind ": " #Class);
14786#define TYPE(Class, Base)
14787#define DEPENDENT_TYPE(Class, Base) UNEXPECTED_TYPE(Class, "dependent")
14788#include "clang/AST/TypeNodes.inc"
14789
14790#define CANONICAL_TYPE(Class) UNEXPECTED_TYPE(Class, "canonical")
14791 CANONICAL_TYPE(Atomic)
14792 CANONICAL_TYPE(BitInt)
14793 CANONICAL_TYPE(BlockPointer)
14794 CANONICAL_TYPE(Builtin)
14795 CANONICAL_TYPE(Complex)
14796 CANONICAL_TYPE(ConstantArray)
14797 CANONICAL_TYPE(ArrayParameter)
14798 CANONICAL_TYPE(ConstantMatrix)
14799 CANONICAL_TYPE(Enum)
14800 CANONICAL_TYPE(ExtVector)
14801 CANONICAL_TYPE(FunctionNoProto)
14802 CANONICAL_TYPE(FunctionProto)
14803 CANONICAL_TYPE(IncompleteArray)
14804 CANONICAL_TYPE(HLSLAttributedResource)
14805 CANONICAL_TYPE(HLSLInlineSpirv)
14806 CANONICAL_TYPE(LValueReference)
14807 CANONICAL_TYPE(ObjCInterface)
14808 CANONICAL_TYPE(ObjCObject)
14809 CANONICAL_TYPE(ObjCObjectPointer)
14810 CANONICAL_TYPE(OverflowBehavior)
14811 CANONICAL_TYPE(Pipe)
14812 CANONICAL_TYPE(Pointer)
14813 CANONICAL_TYPE(Record)
14814 CANONICAL_TYPE(RValueReference)
14815 CANONICAL_TYPE(VariableArray)
14816 CANONICAL_TYPE(Vector)
14817#undef CANONICAL_TYPE
14818
14819#undef UNEXPECTED_TYPE
14820
14821 case Type::Adjusted: {
14822 const auto *AX = cast<AdjustedType>(Val: X), *AY = cast<AdjustedType>(Val: Y);
14823 QualType OX = AX->getOriginalType(), OY = AY->getOriginalType();
14824 if (!Ctx.hasSameType(T1: OX, T2: OY))
14825 return QualType();
14826 // FIXME: It's inefficient to have to unify the original types.
14827 return Ctx.getAdjustedType(Orig: Ctx.getCommonSugaredType(X: OX, Y: OY),
14828 New: Ctx.getQualifiedType(split: Underlying));
14829 }
14830 case Type::Decayed: {
14831 const auto *DX = cast<DecayedType>(Val: X), *DY = cast<DecayedType>(Val: Y);
14832 QualType OX = DX->getOriginalType(), OY = DY->getOriginalType();
14833 if (!Ctx.hasSameType(T1: OX, T2: OY))
14834 return QualType();
14835 // FIXME: It's inefficient to have to unify the original types.
14836 return Ctx.getDecayedType(Orig: Ctx.getCommonSugaredType(X: OX, Y: OY),
14837 Decayed: Ctx.getQualifiedType(split: Underlying));
14838 }
14839 case Type::Attributed: {
14840 const auto *AX = cast<AttributedType>(Val: X), *AY = cast<AttributedType>(Val: Y);
14841 AttributedType::Kind Kind = AX->getAttrKind();
14842 if (Kind != AY->getAttrKind())
14843 return QualType();
14844 QualType MX = AX->getModifiedType(), MY = AY->getModifiedType();
14845 if (!Ctx.hasSameType(T1: MX, T2: MY))
14846 return QualType();
14847 // FIXME: It's inefficient to have to unify the modified types.
14848 return Ctx.getAttributedType(attrKind: Kind, modifiedType: Ctx.getCommonSugaredType(X: MX, Y: MY),
14849 equivalentType: Ctx.getQualifiedType(split: Underlying),
14850 attr: AX->getAttr());
14851 }
14852 case Type::BTFTagAttributed: {
14853 const auto *BX = cast<BTFTagAttributedType>(Val: X);
14854 const BTFTypeTagAttr *AX = BX->getAttr();
14855 // The attribute is not uniqued, so just compare the tag.
14856 if (AX->getBTFTypeTag() !=
14857 cast<BTFTagAttributedType>(Val: Y)->getAttr()->getBTFTypeTag())
14858 return QualType();
14859 return Ctx.getBTFTagAttributedType(BTFAttr: AX, Wrapped: Ctx.getQualifiedType(split: Underlying));
14860 }
14861 case Type::Auto: {
14862 const auto *AX = cast<AutoType>(Val: X), *AY = cast<AutoType>(Val: Y);
14863 assert(AX->getDeducedKind() == DeducedKind::Deduced);
14864 assert(AY->getDeducedKind() == DeducedKind::Deduced);
14865
14866 AutoTypeKeyword KW = AX->getKeyword();
14867 if (KW != AY->getKeyword())
14868 return QualType();
14869
14870 TemplateDecl *CD =
14871 ::getCommonDecl(X: AX->getTypeConstraintConcept().getAsTemplateDecl(),
14872 Y: AY->getTypeConstraintConcept().getAsTemplateDecl());
14873 SmallVector<TemplateArgument, 8> As;
14874 if (CD &&
14875 getCommonTemplateArguments(Ctx, R&: As, Xs: AX->getTypeConstraintArguments(),
14876 Ys: AY->getTypeConstraintArguments())) {
14877 CD = nullptr; // The arguments differ, so make it unconstrained.
14878 As.clear();
14879 }
14880
14881 // Both auto types can't be dependent, otherwise they wouldn't have been
14882 // sugar. This implies they can't contain unexpanded packs either.
14883 return Ctx.getAutoType(DK: DeducedKind::Deduced,
14884 DeducedAsType: Ctx.getQualifiedType(split: Underlying), Keyword: AX->getKeyword(),
14885 TypeConstraintConcept: TemplateName(CD), TypeConstraintArgs: As);
14886 }
14887 case Type::PackIndexing:
14888 case Type::Decltype:
14889 return QualType();
14890 case Type::DeducedTemplateSpecialization:
14891 // FIXME: Try to merge these.
14892 return QualType();
14893 case Type::MacroQualified: {
14894 const auto *MX = cast<MacroQualifiedType>(Val: X),
14895 *MY = cast<MacroQualifiedType>(Val: Y);
14896 const IdentifierInfo *IX = MX->getMacroIdentifier();
14897 if (IX != MY->getMacroIdentifier())
14898 return QualType();
14899 return Ctx.getMacroQualifiedType(UnderlyingTy: Ctx.getQualifiedType(split: Underlying), MacroII: IX);
14900 }
14901 case Type::SubstTemplateTypeParm: {
14902 const auto *SX = cast<SubstTemplateTypeParmType>(Val: X),
14903 *SY = cast<SubstTemplateTypeParmType>(Val: Y);
14904 Decl *CD =
14905 ::getCommonDecl(X: SX->getAssociatedDecl(), Y: SY->getAssociatedDecl());
14906 if (!CD)
14907 return QualType();
14908 unsigned Index = SX->getIndex();
14909 if (Index != SY->getIndex())
14910 return QualType();
14911 auto PackIndex = SX->getPackIndex();
14912 if (PackIndex != SY->getPackIndex())
14913 return QualType();
14914 return Ctx.getSubstTemplateTypeParmType(Replacement: Ctx.getQualifiedType(split: Underlying),
14915 AssociatedDecl: CD, Index, PackIndex,
14916 Final: SX->getFinal() && SY->getFinal());
14917 }
14918 case Type::ObjCTypeParam:
14919 // FIXME: Try to merge these.
14920 return QualType();
14921 case Type::Paren:
14922 return Ctx.getParenType(InnerType: Ctx.getQualifiedType(split: Underlying));
14923
14924 case Type::TemplateSpecialization: {
14925 const auto *TX = cast<TemplateSpecializationType>(Val: X),
14926 *TY = cast<TemplateSpecializationType>(Val: Y);
14927 TemplateName CTN =
14928 ::getCommonTemplateName(Ctx, X: TX->getTemplateName(),
14929 Y: TY->getTemplateName(), /*IgnoreDeduced=*/true);
14930 if (!CTN.getAsVoidPointer())
14931 return QualType();
14932 SmallVector<TemplateArgument, 8> As;
14933 if (getCommonTemplateArguments(Ctx, R&: As, Xs: TX->template_arguments(),
14934 Ys: TY->template_arguments()))
14935 return QualType();
14936 return Ctx.getTemplateSpecializationType(
14937 Keyword: getCommonTypeKeyword(X: TX, Y: TY, /*IsSame=*/false), Template: CTN, SpecifiedArgs: As,
14938 /*CanonicalArgs=*/{}, Underlying: Ctx.getQualifiedType(split: Underlying));
14939 }
14940 case Type::Typedef: {
14941 const auto *TX = cast<TypedefType>(Val: X), *TY = cast<TypedefType>(Val: Y);
14942 const TypedefNameDecl *CD = ::getCommonDecl(X: TX->getDecl(), Y: TY->getDecl());
14943 if (!CD)
14944 return QualType();
14945 return Ctx.getTypedefType(
14946 Keyword: ::getCommonTypeKeyword(X: TX, Y: TY, /*IsSame=*/false),
14947 Qualifier: ::getCommonQualifier(Ctx, X: TX, Y: TY, /*IsSame=*/false), Decl: CD,
14948 UnderlyingType: Ctx.getQualifiedType(split: Underlying));
14949 }
14950 case Type::TypeOf: {
14951 // The common sugar between two typeof expressions, where one is
14952 // potentially a typeof_unqual and the other is not, we unify to the
14953 // qualified type as that retains the most information along with the type.
14954 // We only return a typeof_unqual type when both types are unqual types.
14955 TypeOfKind Kind = TypeOfKind::Qualified;
14956 if (cast<TypeOfType>(Val: X)->getKind() == cast<TypeOfType>(Val: Y)->getKind() &&
14957 cast<TypeOfType>(Val: X)->getKind() == TypeOfKind::Unqualified)
14958 Kind = TypeOfKind::Unqualified;
14959 return Ctx.getTypeOfType(tofType: Ctx.getQualifiedType(split: Underlying), Kind);
14960 }
14961 case Type::TypeOfExpr:
14962 return QualType();
14963
14964 case Type::UnaryTransform: {
14965 const auto *UX = cast<UnaryTransformType>(Val: X),
14966 *UY = cast<UnaryTransformType>(Val: Y);
14967 UnaryTransformType::UTTKind KX = UX->getUTTKind();
14968 if (KX != UY->getUTTKind())
14969 return QualType();
14970 QualType BX = UX->getBaseType(), BY = UY->getBaseType();
14971 if (!Ctx.hasSameType(T1: BX, T2: BY))
14972 return QualType();
14973 // FIXME: It's inefficient to have to unify the base types.
14974 return Ctx.getUnaryTransformType(BaseType: Ctx.getCommonSugaredType(X: BX, Y: BY),
14975 UnderlyingType: Ctx.getQualifiedType(split: Underlying), Kind: KX);
14976 }
14977 case Type::Using: {
14978 const auto *UX = cast<UsingType>(Val: X), *UY = cast<UsingType>(Val: Y);
14979 const UsingShadowDecl *CD = ::getCommonDecl(X: UX->getDecl(), Y: UY->getDecl());
14980 if (!CD)
14981 return QualType();
14982 return Ctx.getUsingType(Keyword: ::getCommonTypeKeyword(X: UX, Y: UY, /*IsSame=*/false),
14983 Qualifier: ::getCommonQualifier(Ctx, X: UX, Y: UY, /*IsSame=*/false),
14984 D: CD, UnderlyingType: Ctx.getQualifiedType(split: Underlying));
14985 }
14986 case Type::MemberPointer: {
14987 const auto *PX = cast<MemberPointerType>(Val: X),
14988 *PY = cast<MemberPointerType>(Val: Y);
14989 CXXRecordDecl *Cls = PX->getMostRecentCXXRecordDecl();
14990 assert(Cls == PY->getMostRecentCXXRecordDecl());
14991 return Ctx.getMemberPointerType(
14992 T: ::getCommonPointeeType(Ctx, X: PX, Y: PY),
14993 Qualifier: ::getCommonQualifier(Ctx, X: PX, Y: PY, /*IsSame=*/false), Cls);
14994 }
14995 case Type::CountAttributed: {
14996 const auto *DX = cast<CountAttributedType>(Val: X),
14997 *DY = cast<CountAttributedType>(Val: Y);
14998 if (DX->isCountInBytes() != DY->isCountInBytes())
14999 return QualType();
15000 if (DX->isOrNull() != DY->isOrNull())
15001 return QualType();
15002 Expr *CEX = DX->getCountExpr();
15003 Expr *CEY = DY->getCountExpr();
15004 ArrayRef<clang::TypeCoupledDeclRefInfo> CDX = DX->getCoupledDecls();
15005 if (Ctx.hasSameExpr(X: CEX, Y: CEY))
15006 return Ctx.getCountAttributedType(WrappedTy: Ctx.getQualifiedType(split: Underlying), CountExpr: CEX,
15007 CountInBytes: DX->isCountInBytes(), OrNull: DX->isOrNull(),
15008 DependentDecls: CDX);
15009 if (!CEX->isIntegerConstantExpr(Ctx) || !CEY->isIntegerConstantExpr(Ctx))
15010 return QualType();
15011 // Two declarations with the same integer constant may still differ in their
15012 // expression pointers, so we need to evaluate them.
15013 llvm::APSInt VX = *CEX->getIntegerConstantExpr(Ctx);
15014 llvm::APSInt VY = *CEY->getIntegerConstantExpr(Ctx);
15015 if (VX != VY)
15016 return QualType();
15017 return Ctx.getCountAttributedType(WrappedTy: Ctx.getQualifiedType(split: Underlying), CountExpr: CEX,
15018 CountInBytes: DX->isCountInBytes(), OrNull: DX->isOrNull(),
15019 DependentDecls: CDX);
15020 }
15021
15022 case Type::LateParsedAttr:
15023 return QualType();
15024
15025 case Type::PredefinedSugar:
15026 assert(cast<PredefinedSugarType>(X)->getKind() !=
15027 cast<PredefinedSugarType>(Y)->getKind());
15028 return QualType();
15029 }
15030 llvm_unreachable("Unhandled Type Class");
15031}
15032
15033static auto unwrapSugar(SplitQualType &T, Qualifiers &QTotal) {
15034 SmallVector<SplitQualType, 8> R;
15035 while (true) {
15036 QTotal.addConsistentQualifiers(qs: T.Quals);
15037 QualType NT = T.Ty->getLocallyUnqualifiedSingleStepDesugaredType();
15038 if (NT == QualType(T.Ty, 0))
15039 break;
15040 R.push_back(Elt: T);
15041 T = NT.split();
15042 }
15043 return R;
15044}
15045
15046QualType ASTContext::getCommonSugaredType(QualType X, QualType Y,
15047 bool Unqualified) const {
15048 assert(Unqualified ? hasSameUnqualifiedType(X, Y) : hasSameType(X, Y));
15049 if (X == Y)
15050 return X;
15051 if (!Unqualified) {
15052 if (X.isCanonical())
15053 return X;
15054 if (Y.isCanonical())
15055 return Y;
15056 }
15057
15058 SplitQualType SX = X.split(), SY = Y.split();
15059 Qualifiers QX, QY;
15060 // Desugar SX and SY, setting the sugar and qualifiers aside into Xs and Ys,
15061 // until we reach their underlying "canonical nodes". Note these are not
15062 // necessarily canonical types, as they may still have sugared properties.
15063 // QX and QY will store the sum of all qualifiers in Xs and Ys respectively.
15064 auto Xs = ::unwrapSugar(T&: SX, QTotal&: QX), Ys = ::unwrapSugar(T&: SY, QTotal&: QY);
15065
15066 // If this is an ArrayType, the element qualifiers are interchangeable with
15067 // the top level qualifiers.
15068 // * In case the canonical nodes are the same, the elements types are already
15069 // the same.
15070 // * Otherwise, the element types will be made the same, and any different
15071 // element qualifiers will be moved up to the top level qualifiers, per
15072 // 'getCommonArrayElementType'.
15073 // In both cases, this means there may be top level qualifiers which differ
15074 // between X and Y. If so, these differing qualifiers are redundant with the
15075 // element qualifiers, and can be removed without changing the canonical type.
15076 // The desired behaviour is the same as for the 'Unqualified' case here:
15077 // treat the redundant qualifiers as sugar, remove the ones which are not
15078 // common to both sides.
15079 bool KeepCommonQualifiers =
15080 Unqualified || isa<ArrayType, OverflowBehaviorType>(Val: SX.Ty);
15081
15082 if (SX.Ty != SY.Ty) {
15083 // The canonical nodes differ. Build a common canonical node out of the two,
15084 // unifying their sugar. This may recurse back here.
15085 SX.Ty =
15086 ::getCommonNonSugarTypeNode(Ctx: *this, X: SX.Ty, QX, Y: SY.Ty, QY).getTypePtr();
15087 } else {
15088 // The canonical nodes were identical: We may have desugared too much.
15089 // Add any common sugar back in.
15090 while (!Xs.empty() && !Ys.empty() && Xs.back().Ty == Ys.back().Ty) {
15091 QX -= SX.Quals;
15092 QY -= SY.Quals;
15093 SX = Xs.pop_back_val();
15094 SY = Ys.pop_back_val();
15095 }
15096 }
15097 if (KeepCommonQualifiers)
15098 QX = Qualifiers::removeCommonQualifiers(L&: QX, R&: QY);
15099 else
15100 assert(QX == QY);
15101
15102 // Even though the remaining sugar nodes in Xs and Ys differ, some may be
15103 // related. Walk up these nodes, unifying them and adding the result.
15104 while (!Xs.empty() && !Ys.empty()) {
15105 auto Underlying = SplitQualType(
15106 SX.Ty, Qualifiers::removeCommonQualifiers(L&: SX.Quals, R&: SY.Quals));
15107 SX = Xs.pop_back_val();
15108 SY = Ys.pop_back_val();
15109 SX.Ty = ::getCommonSugarTypeNode(Ctx: *this, X: SX.Ty, Y: SY.Ty, Underlying)
15110 .getTypePtrOrNull();
15111 // Stop at the first pair which is unrelated.
15112 if (!SX.Ty) {
15113 SX.Ty = Underlying.Ty;
15114 break;
15115 }
15116 QX -= Underlying.Quals;
15117 };
15118
15119 // Add back the missing accumulated qualifiers, which were stripped off
15120 // with the sugar nodes we could not unify.
15121 QualType R = getQualifiedType(T: SX.Ty, Qs: QX);
15122 assert(Unqualified ? hasSameUnqualifiedType(R, X) : hasSameType(R, X));
15123 return R;
15124}
15125
15126QualType ASTContext::getCorrespondingUnsaturatedType(QualType Ty) const {
15127 assert(Ty->isFixedPointType());
15128
15129 if (Ty->isUnsaturatedFixedPointType())
15130 return Ty;
15131
15132 switch (Ty->castAs<BuiltinType>()->getKind()) {
15133 default:
15134 llvm_unreachable("Not a saturated fixed point type!");
15135 case BuiltinType::SatShortAccum:
15136 return ShortAccumTy;
15137 case BuiltinType::SatAccum:
15138 return AccumTy;
15139 case BuiltinType::SatLongAccum:
15140 return LongAccumTy;
15141 case BuiltinType::SatUShortAccum:
15142 return UnsignedShortAccumTy;
15143 case BuiltinType::SatUAccum:
15144 return UnsignedAccumTy;
15145 case BuiltinType::SatULongAccum:
15146 return UnsignedLongAccumTy;
15147 case BuiltinType::SatShortFract:
15148 return ShortFractTy;
15149 case BuiltinType::SatFract:
15150 return FractTy;
15151 case BuiltinType::SatLongFract:
15152 return LongFractTy;
15153 case BuiltinType::SatUShortFract:
15154 return UnsignedShortFractTy;
15155 case BuiltinType::SatUFract:
15156 return UnsignedFractTy;
15157 case BuiltinType::SatULongFract:
15158 return UnsignedLongFractTy;
15159 }
15160}
15161
15162QualType ASTContext::getCorrespondingSaturatedType(QualType Ty) const {
15163 assert(Ty->isFixedPointType());
15164
15165 if (Ty->isSaturatedFixedPointType()) return Ty;
15166
15167 switch (Ty->castAs<BuiltinType>()->getKind()) {
15168 default:
15169 llvm_unreachable("Not a fixed point type!");
15170 case BuiltinType::ShortAccum:
15171 return SatShortAccumTy;
15172 case BuiltinType::Accum:
15173 return SatAccumTy;
15174 case BuiltinType::LongAccum:
15175 return SatLongAccumTy;
15176 case BuiltinType::UShortAccum:
15177 return SatUnsignedShortAccumTy;
15178 case BuiltinType::UAccum:
15179 return SatUnsignedAccumTy;
15180 case BuiltinType::ULongAccum:
15181 return SatUnsignedLongAccumTy;
15182 case BuiltinType::ShortFract:
15183 return SatShortFractTy;
15184 case BuiltinType::Fract:
15185 return SatFractTy;
15186 case BuiltinType::LongFract:
15187 return SatLongFractTy;
15188 case BuiltinType::UShortFract:
15189 return SatUnsignedShortFractTy;
15190 case BuiltinType::UFract:
15191 return SatUnsignedFractTy;
15192 case BuiltinType::ULongFract:
15193 return SatUnsignedLongFractTy;
15194 }
15195}
15196
15197LangAS ASTContext::getLangASForBuiltinAddressSpace(unsigned AS) const {
15198 if (LangOpts.OpenCL)
15199 return getTargetInfo().getOpenCLBuiltinAddressSpace(AS);
15200
15201 if (LangOpts.CUDA)
15202 return getTargetInfo().getCUDABuiltinAddressSpace(AS);
15203
15204 return getLangASFromTargetAS(TargetAS: AS);
15205}
15206
15207unsigned char ASTContext::getFixedPointScale(QualType Ty) const {
15208 assert(Ty->isFixedPointType());
15209
15210 const TargetInfo &Target = getTargetInfo();
15211 switch (Ty->castAs<BuiltinType>()->getKind()) {
15212 default:
15213 llvm_unreachable("Not a fixed point type!");
15214 case BuiltinType::ShortAccum:
15215 case BuiltinType::SatShortAccum:
15216 return Target.getShortAccumScale();
15217 case BuiltinType::Accum:
15218 case BuiltinType::SatAccum:
15219 return Target.getAccumScale();
15220 case BuiltinType::LongAccum:
15221 case BuiltinType::SatLongAccum:
15222 return Target.getLongAccumScale();
15223 case BuiltinType::UShortAccum:
15224 case BuiltinType::SatUShortAccum:
15225 return Target.getUnsignedShortAccumScale();
15226 case BuiltinType::UAccum:
15227 case BuiltinType::SatUAccum:
15228 return Target.getUnsignedAccumScale();
15229 case BuiltinType::ULongAccum:
15230 case BuiltinType::SatULongAccum:
15231 return Target.getUnsignedLongAccumScale();
15232 case BuiltinType::ShortFract:
15233 case BuiltinType::SatShortFract:
15234 return Target.getShortFractScale();
15235 case BuiltinType::Fract:
15236 case BuiltinType::SatFract:
15237 return Target.getFractScale();
15238 case BuiltinType::LongFract:
15239 case BuiltinType::SatLongFract:
15240 return Target.getLongFractScale();
15241 case BuiltinType::UShortFract:
15242 case BuiltinType::SatUShortFract:
15243 return Target.getUnsignedShortFractScale();
15244 case BuiltinType::UFract:
15245 case BuiltinType::SatUFract:
15246 return Target.getUnsignedFractScale();
15247 case BuiltinType::ULongFract:
15248 case BuiltinType::SatULongFract:
15249 return Target.getUnsignedLongFractScale();
15250 }
15251}
15252
15253unsigned char ASTContext::getFixedPointIBits(QualType Ty) const {
15254 assert(Ty->isFixedPointType());
15255
15256 const TargetInfo &Target = getTargetInfo();
15257 switch (Ty->castAs<BuiltinType>()->getKind()) {
15258 default:
15259 llvm_unreachable("Not a fixed point type!");
15260 case BuiltinType::ShortAccum:
15261 case BuiltinType::SatShortAccum:
15262 return Target.getShortAccumIBits();
15263 case BuiltinType::Accum:
15264 case BuiltinType::SatAccum:
15265 return Target.getAccumIBits();
15266 case BuiltinType::LongAccum:
15267 case BuiltinType::SatLongAccum:
15268 return Target.getLongAccumIBits();
15269 case BuiltinType::UShortAccum:
15270 case BuiltinType::SatUShortAccum:
15271 return Target.getUnsignedShortAccumIBits();
15272 case BuiltinType::UAccum:
15273 case BuiltinType::SatUAccum:
15274 return Target.getUnsignedAccumIBits();
15275 case BuiltinType::ULongAccum:
15276 case BuiltinType::SatULongAccum:
15277 return Target.getUnsignedLongAccumIBits();
15278 case BuiltinType::ShortFract:
15279 case BuiltinType::SatShortFract:
15280 case BuiltinType::Fract:
15281 case BuiltinType::SatFract:
15282 case BuiltinType::LongFract:
15283 case BuiltinType::SatLongFract:
15284 case BuiltinType::UShortFract:
15285 case BuiltinType::SatUShortFract:
15286 case BuiltinType::UFract:
15287 case BuiltinType::SatUFract:
15288 case BuiltinType::ULongFract:
15289 case BuiltinType::SatULongFract:
15290 return 0;
15291 }
15292}
15293
15294llvm::FixedPointSemantics
15295ASTContext::getFixedPointSemantics(QualType Ty) const {
15296 assert((Ty->isFixedPointType() || Ty->isIntegerType()) &&
15297 "Can only get the fixed point semantics for a "
15298 "fixed point or integer type.");
15299 if (Ty->isIntegerType())
15300 return llvm::FixedPointSemantics::GetIntegerSemantics(
15301 Width: getIntWidth(T: Ty), IsSigned: Ty->isSignedIntegerType());
15302
15303 bool isSigned = Ty->isSignedFixedPointType();
15304 return llvm::FixedPointSemantics(
15305 static_cast<unsigned>(getTypeSize(T: Ty)), getFixedPointScale(Ty), isSigned,
15306 Ty->isSaturatedFixedPointType(),
15307 !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding());
15308}
15309
15310llvm::APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const {
15311 assert(Ty->isFixedPointType());
15312 return llvm::APFixedPoint::getMax(Sema: getFixedPointSemantics(Ty));
15313}
15314
15315llvm::APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const {
15316 assert(Ty->isFixedPointType());
15317 return llvm::APFixedPoint::getMin(Sema: getFixedPointSemantics(Ty));
15318}
15319
15320QualType ASTContext::getCorrespondingSignedFixedPointType(QualType Ty) const {
15321 assert(Ty->isUnsignedFixedPointType() &&
15322 "Expected unsigned fixed point type");
15323
15324 switch (Ty->castAs<BuiltinType>()->getKind()) {
15325 case BuiltinType::UShortAccum:
15326 return ShortAccumTy;
15327 case BuiltinType::UAccum:
15328 return AccumTy;
15329 case BuiltinType::ULongAccum:
15330 return LongAccumTy;
15331 case BuiltinType::SatUShortAccum:
15332 return SatShortAccumTy;
15333 case BuiltinType::SatUAccum:
15334 return SatAccumTy;
15335 case BuiltinType::SatULongAccum:
15336 return SatLongAccumTy;
15337 case BuiltinType::UShortFract:
15338 return ShortFractTy;
15339 case BuiltinType::UFract:
15340 return FractTy;
15341 case BuiltinType::ULongFract:
15342 return LongFractTy;
15343 case BuiltinType::SatUShortFract:
15344 return SatShortFractTy;
15345 case BuiltinType::SatUFract:
15346 return SatFractTy;
15347 case BuiltinType::SatULongFract:
15348 return SatLongFractTy;
15349 default:
15350 llvm_unreachable("Unexpected unsigned fixed point type");
15351 }
15352}
15353
15354// Given a list of FMV features, return a concatenated list of the
15355// corresponding backend features (which may contain duplicates).
15356static std::vector<std::string> getFMVBackendFeaturesFor(
15357 const llvm::SmallVectorImpl<StringRef> &FMVFeatStrings) {
15358 std::vector<std::string> BackendFeats;
15359 llvm::AArch64::ExtensionSet FeatureBits;
15360 for (StringRef F : FMVFeatStrings)
15361 if (auto FMVExt = llvm::AArch64::parseFMVExtension(Extension: F))
15362 if (FMVExt->ID)
15363 FeatureBits.enable(E: *FMVExt->ID);
15364 FeatureBits.toLLVMFeatureList(Features&: BackendFeats);
15365 return BackendFeats;
15366}
15367
15368ParsedTargetAttr
15369ASTContext::filterFunctionTargetAttrs(const TargetAttr *TD) const {
15370 assert(TD != nullptr);
15371 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(Str: TD->getFeaturesStr());
15372
15373 llvm::erase_if(C&: ParsedAttr.Features, P: [&](const std::string &Feat) {
15374 return !Target->isValidFeatureName(Feature: StringRef{Feat}.substr(Start: 1));
15375 });
15376 return ParsedAttr;
15377}
15378
15379void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
15380 const FunctionDecl *FD) const {
15381 if (FD)
15382 getFunctionFeatureMap(FeatureMap, GD: GlobalDecl().getWithDecl(D: FD));
15383 else
15384 Target->initFeatureMap(Features&: FeatureMap, Diags&: getDiagnostics(),
15385 CPU: Target->getTargetOpts().CPU,
15386 FeatureVec: Target->getTargetOpts().Features);
15387}
15388
15389// Fills in the supplied string map with the set of target features for the
15390// passed in function.
15391void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
15392 GlobalDecl GD) const {
15393 StringRef TargetCPU = Target->getTargetOpts().CPU;
15394 const FunctionDecl *FD = GD.getDecl()->getAsFunction();
15395 if (const auto *TD = FD->getAttr<TargetAttr>()) {
15396 ParsedTargetAttr ParsedAttr = filterFunctionTargetAttrs(TD);
15397
15398 // Make a copy of the features as passed on the command line into the
15399 // beginning of the additional features from the function to override.
15400 // AArch64 handles command line option features in parseTargetAttr().
15401 if (!Target->getTriple().isAArch64())
15402 ParsedAttr.Features.insert(
15403 position: ParsedAttr.Features.begin(),
15404 first: Target->getTargetOpts().FeaturesAsWritten.begin(),
15405 last: Target->getTargetOpts().FeaturesAsWritten.end());
15406
15407 if (ParsedAttr.CPU != "" && Target->isValidCPUName(Name: ParsedAttr.CPU))
15408 TargetCPU = ParsedAttr.CPU;
15409
15410 // Now populate the feature map, first with the TargetCPU which is either
15411 // the default or a new one from the target attribute string. Then we'll use
15412 // the passed in features (FeaturesAsWritten) along with the new ones from
15413 // the attribute.
15414 Target->initFeatureMap(Features&: FeatureMap, Diags&: getDiagnostics(), CPU: TargetCPU,
15415 FeatureVec: ParsedAttr.Features);
15416 } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) {
15417 llvm::SmallVector<StringRef, 32> FeaturesTmp;
15418 Target->getCPUSpecificCPUDispatchFeatures(
15419 Name: SD->getCPUName(Index: GD.getMultiVersionIndex())->getName(), Features&: FeaturesTmp);
15420 std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end());
15421 Features.insert(position: Features.begin(),
15422 first: Target->getTargetOpts().FeaturesAsWritten.begin(),
15423 last: Target->getTargetOpts().FeaturesAsWritten.end());
15424 Target->initFeatureMap(Features&: FeatureMap, Diags&: getDiagnostics(), CPU: TargetCPU, FeatureVec: Features);
15425 } else if (const auto *TC = FD->getAttr<TargetClonesAttr>()) {
15426 if (Target->getTriple().isAArch64()) {
15427 llvm::SmallVector<StringRef, 8> Feats;
15428 TC->getFeatures(Out&: Feats, Index: GD.getMultiVersionIndex());
15429 std::vector<std::string> Features = getFMVBackendFeaturesFor(FMVFeatStrings: Feats);
15430 Features.insert(position: Features.begin(),
15431 first: Target->getTargetOpts().FeaturesAsWritten.begin(),
15432 last: Target->getTargetOpts().FeaturesAsWritten.end());
15433 Target->initFeatureMap(Features&: FeatureMap, Diags&: getDiagnostics(), CPU: TargetCPU, FeatureVec: Features);
15434 } else if (Target->getTriple().isRISCV()) {
15435 StringRef VersionStr = TC->getFeatureStr(Index: GD.getMultiVersionIndex());
15436 std::vector<std::string> Features;
15437 if (VersionStr != "default") {
15438 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(Str: VersionStr);
15439 Features.insert(position: Features.begin(), first: ParsedAttr.Features.begin(),
15440 last: ParsedAttr.Features.end());
15441 }
15442 Features.insert(position: Features.begin(),
15443 first: Target->getTargetOpts().FeaturesAsWritten.begin(),
15444 last: Target->getTargetOpts().FeaturesAsWritten.end());
15445 Target->initFeatureMap(Features&: FeatureMap, Diags&: getDiagnostics(), CPU: TargetCPU, FeatureVec: Features);
15446 } else if (Target->getTriple().isOSAIX()) {
15447 std::vector<std::string> Features;
15448 StringRef VersionStr = TC->getFeatureStr(Index: GD.getMultiVersionIndex());
15449 if (VersionStr.starts_with(Prefix: "cpu="))
15450 TargetCPU = VersionStr.drop_front(N: sizeof("cpu=") - 1);
15451 else if (VersionStr != "default")
15452 Features = Target->parseTargetAttr(Str: VersionStr).Features;
15453 Target->initFeatureMap(Features&: FeatureMap, Diags&: getDiagnostics(), CPU: TargetCPU, FeatureVec: Features);
15454 } else {
15455 std::vector<std::string> Features;
15456 StringRef VersionStr = TC->getFeatureStr(Index: GD.getMultiVersionIndex());
15457 if (VersionStr.starts_with(Prefix: "arch="))
15458 TargetCPU = VersionStr.drop_front(N: sizeof("arch=") - 1);
15459 else if (VersionStr != "default")
15460 Features.push_back(x: (StringRef{"+"} + VersionStr).str());
15461 Target->initFeatureMap(Features&: FeatureMap, Diags&: getDiagnostics(), CPU: TargetCPU, FeatureVec: Features);
15462 }
15463 } else if (const auto *TV = FD->getAttr<TargetVersionAttr>()) {
15464 std::vector<std::string> Features;
15465 if (Target->getTriple().isRISCV()) {
15466 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(Str: TV->getName());
15467 Features.insert(position: Features.begin(), first: ParsedAttr.Features.begin(),
15468 last: ParsedAttr.Features.end());
15469 } else {
15470 assert(Target->getTriple().isAArch64());
15471 llvm::SmallVector<StringRef, 8> Feats;
15472 TV->getFeatures(Out&: Feats);
15473 Features = getFMVBackendFeaturesFor(FMVFeatStrings: Feats);
15474 }
15475 Features.insert(position: Features.begin(),
15476 first: Target->getTargetOpts().FeaturesAsWritten.begin(),
15477 last: Target->getTargetOpts().FeaturesAsWritten.end());
15478 Target->initFeatureMap(Features&: FeatureMap, Diags&: getDiagnostics(), CPU: TargetCPU, FeatureVec: Features);
15479 } else {
15480 FeatureMap = Target->getTargetOpts().FeatureMap;
15481 }
15482}
15483
15484static SYCLKernelInfo BuildSYCLKernelInfo(ASTContext &Context,
15485 CanQualType KernelNameType,
15486 const FunctionDecl *FD) {
15487 // Host and device compilation may use different ABIs and different ABIs
15488 // may allocate name mangling discriminators differently. A discriminator
15489 // override is used to ensure consistent discriminator allocation across
15490 // host and device compilation.
15491 auto DeviceDiscriminatorOverrider =
15492 [](ASTContext &Ctx, const NamedDecl *ND) -> UnsignedOrNone {
15493 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: ND))
15494 if (RD->isLambda())
15495 return RD->getDeviceLambdaManglingNumber();
15496 return std::nullopt;
15497 };
15498 std::unique_ptr<MangleContext> MC{ItaniumMangleContext::create(
15499 Context, Diags&: Context.getDiagnostics(), Discriminator: DeviceDiscriminatorOverrider)};
15500
15501 // Construct a mangled name for the SYCL kernel caller offload entry point.
15502 // FIXME: The Itanium typeinfo mangling (_ZTS<type>) is currently used to
15503 // name the SYCL kernel caller offload entry point function. This mangling
15504 // does not suffice to clearly identify symbols that correspond to SYCL
15505 // kernel caller functions, nor is this mangling natural for targets that
15506 // use a non-Itanium ABI.
15507 std::string Buffer;
15508 Buffer.reserve(res_arg: 128);
15509 llvm::raw_string_ostream Out(Buffer);
15510 MC->mangleCanonicalTypeName(T: KernelNameType, Out);
15511 std::string KernelName = Out.str();
15512
15513 return {KernelNameType, FD, KernelName};
15514}
15515
15516void ASTContext::registerSYCLEntryPointFunction(FunctionDecl *FD) {
15517 // If the function declaration to register is invalid or dependent, the
15518 // registration attempt is ignored.
15519 if (FD->isInvalidDecl() || FD->isTemplated())
15520 return;
15521
15522 const auto *SKEPAttr = FD->getAttr<SYCLKernelEntryPointAttr>();
15523 assert(SKEPAttr && "Missing sycl_kernel_entry_point attribute");
15524
15525 // Be tolerant of multiple registration attempts so long as each attempt
15526 // is for the same entity. Callers are obligated to detect and diagnose
15527 // conflicting kernel names prior to calling this function.
15528 CanQualType KernelNameType = getCanonicalType(T: SKEPAttr->getKernelName());
15529 auto IT = SYCLKernels.find(Val: KernelNameType);
15530 assert((IT == SYCLKernels.end() ||
15531 declaresSameEntity(FD, IT->second.getKernelEntryPointDecl())) &&
15532 "SYCL kernel name conflict");
15533 (void)IT;
15534 SYCLKernels.insert(KV: std::make_pair(
15535 x&: KernelNameType, y: BuildSYCLKernelInfo(Context&: *this, KernelNameType, FD)));
15536}
15537
15538const SYCLKernelInfo &ASTContext::getSYCLKernelInfo(QualType T) const {
15539 CanQualType KernelNameType = getCanonicalType(T);
15540 return SYCLKernels.at(Val: KernelNameType);
15541}
15542
15543const SYCLKernelInfo *ASTContext::findSYCLKernelInfo(QualType T) const {
15544 CanQualType KernelNameType = getCanonicalType(T);
15545 auto IT = SYCLKernels.find(Val: KernelNameType);
15546 if (IT != SYCLKernels.end())
15547 return &IT->second;
15548 return nullptr;
15549}
15550
15551OMPTraitInfo &ASTContext::getNewOMPTraitInfo() {
15552 OMPTraitInfoVector.emplace_back(Args: new OMPTraitInfo());
15553 return *OMPTraitInfoVector.back();
15554}
15555
15556const StreamingDiagnostic &clang::
15557operator<<(const StreamingDiagnostic &DB,
15558 const ASTContext::SectionInfo &Section) {
15559 if (Section.Decl)
15560 return DB << Section.Decl;
15561 return DB << "a prior #pragma section";
15562}
15563
15564bool ASTContext::mayExternalize(const Decl *D) const {
15565 bool IsInternalVar =
15566 isa<VarDecl>(Val: D) &&
15567 basicGVALinkageForVariable(Context: *this, VD: cast<VarDecl>(Val: D)) == GVA_Internal;
15568 bool IsExplicitDeviceVar = (D->hasAttr<CUDADeviceAttr>() &&
15569 !D->getAttr<CUDADeviceAttr>()->isImplicit()) ||
15570 (D->hasAttr<CUDAConstantAttr>() &&
15571 !D->getAttr<CUDAConstantAttr>()->isImplicit());
15572 // CUDA/HIP: managed variables need to be externalized since it is
15573 // a declaration in IR, therefore cannot have internal linkage. Kernels in
15574 // anonymous name space needs to be externalized to avoid duplicate symbols.
15575 return (IsInternalVar &&
15576 (D->hasAttr<HIPManagedAttr>() || IsExplicitDeviceVar)) ||
15577 (D->hasAttr<CUDAGlobalAttr>() &&
15578 basicGVALinkageForFunction(Context: *this, FD: cast<FunctionDecl>(Val: D)) ==
15579 GVA_Internal);
15580}
15581
15582bool ASTContext::shouldExternalize(const Decl *D) const {
15583 return mayExternalize(D) &&
15584 (D->hasAttr<HIPManagedAttr>() || D->hasAttr<CUDAGlobalAttr>() ||
15585 CUDADeviceVarODRUsedByHost.count(key: cast<VarDecl>(Val: D)));
15586}
15587
15588StringRef ASTContext::getCUIDHash() const {
15589 if (!CUIDHash.empty())
15590 return CUIDHash;
15591 if (LangOpts.CUID.empty())
15592 return StringRef();
15593 CUIDHash = llvm::utohexstr(X: llvm::MD5Hash(Str: LangOpts.CUID), /*LowerCase=*/true);
15594 return CUIDHash;
15595}
15596
15597const CXXRecordDecl *
15598ASTContext::baseForVTableAuthentication(const CXXRecordDecl *ThisClass) const {
15599 assert(ThisClass);
15600 assert(ThisClass->isPolymorphic());
15601 const CXXRecordDecl *PrimaryBase = ThisClass;
15602 while (1) {
15603 assert(PrimaryBase);
15604 assert(PrimaryBase->isPolymorphic());
15605 auto &Layout = getASTRecordLayout(D: PrimaryBase);
15606 auto Base = Layout.getPrimaryBase();
15607 if (!Base || Base == PrimaryBase || !Base->isPolymorphic())
15608 break;
15609 PrimaryBase = Base;
15610 }
15611 return PrimaryBase;
15612}
15613
15614bool ASTContext::useAbbreviatedThunkName(GlobalDecl VirtualMethodDecl,
15615 StringRef MangledName) {
15616 auto *Method = cast<CXXMethodDecl>(Val: VirtualMethodDecl.getDecl());
15617 assert(Method->isVirtual());
15618 bool DefaultIncludesPointerAuth =
15619 LangOpts.PointerAuthCalls || LangOpts.PointerAuthIntrinsics;
15620
15621 if (!DefaultIncludesPointerAuth)
15622 return true;
15623
15624 auto Existing = ThunksToBeAbbreviated.find(Val: VirtualMethodDecl);
15625 if (Existing != ThunksToBeAbbreviated.end())
15626 return Existing->second.contains(key: MangledName.str());
15627
15628 std::unique_ptr<MangleContext> Mangler(createMangleContext());
15629 llvm::StringMap<llvm::SmallVector<std::string, 2>> Thunks;
15630 auto VtableContext = getVTableContext();
15631 if (const auto *ThunkInfos = VtableContext->getThunkInfo(GD: VirtualMethodDecl)) {
15632 auto *Destructor = dyn_cast<CXXDestructorDecl>(Val: Method);
15633 for (const auto &Thunk : *ThunkInfos) {
15634 SmallString<256> ElidedName;
15635 llvm::raw_svector_ostream ElidedNameStream(ElidedName);
15636 if (Destructor)
15637 Mangler->mangleCXXDtorThunk(DD: Destructor, Type: VirtualMethodDecl.getDtorType(),
15638 Thunk, /* elideOverrideInfo */ ElideOverrideInfo: true,
15639 ElidedNameStream);
15640 else
15641 Mangler->mangleThunk(MD: Method, Thunk, /* elideOverrideInfo */ ElideOverrideInfo: true,
15642 ElidedNameStream);
15643 SmallString<256> MangledName;
15644 llvm::raw_svector_ostream mangledNameStream(MangledName);
15645 if (Destructor)
15646 Mangler->mangleCXXDtorThunk(DD: Destructor, Type: VirtualMethodDecl.getDtorType(),
15647 Thunk, /* elideOverrideInfo */ ElideOverrideInfo: false,
15648 mangledNameStream);
15649 else
15650 Mangler->mangleThunk(MD: Method, Thunk, /* elideOverrideInfo */ ElideOverrideInfo: false,
15651 mangledNameStream);
15652
15653 Thunks[ElidedName].push_back(Elt: std::string(MangledName));
15654 }
15655 }
15656 llvm::StringSet<> SimplifiedThunkNames;
15657 for (auto &ThunkList : Thunks) {
15658 llvm::sort(C&: ThunkList.second);
15659 SimplifiedThunkNames.insert(key: ThunkList.second[0]);
15660 }
15661 bool Result = SimplifiedThunkNames.contains(key: MangledName);
15662 ThunksToBeAbbreviated[VirtualMethodDecl] = std::move(SimplifiedThunkNames);
15663 return Result;
15664}
15665
15666bool ASTContext::arePFPFieldsTriviallyCopyable(const RecordDecl *RD) const {
15667 // Check for trivially-destructible here because non-trivially-destructible
15668 // types will always cause the type and any types derived from it to be
15669 // considered non-trivially-copyable. The same cannot be said for
15670 // trivially-copyable because deleting special members of a type derived from
15671 // a non-trivially-copyable type can cause the derived type to be considered
15672 // trivially copyable.
15673 if (getLangOpts().PointerFieldProtectionTagged)
15674 return !isa<CXXRecordDecl>(Val: RD) ||
15675 cast<CXXRecordDecl>(Val: RD)->hasTrivialDestructor();
15676 return true;
15677}
15678
15679static void findPFPFields(const ASTContext &Ctx, QualType Ty, CharUnits Offset,
15680 std::vector<PFPField> &Fields, bool IncludeVBases) {
15681 if (auto *AT = Ctx.getAsConstantArrayType(T: Ty)) {
15682 if (auto *ElemDecl = AT->getElementType()->getAsCXXRecordDecl()) {
15683 const ASTRecordLayout &ElemRL = Ctx.getASTRecordLayout(D: ElemDecl);
15684 for (unsigned i = 0; i != AT->getSize(); ++i)
15685 findPFPFields(Ctx, Ty: AT->getElementType(), Offset: Offset + i * ElemRL.getSize(),
15686 Fields, IncludeVBases: true);
15687 }
15688 }
15689 auto *Decl = Ty->getAsCXXRecordDecl();
15690 // isPFPType() is inherited from bases and members (including via arrays), so
15691 // we can early exit if it is false. Unions are excluded per the API
15692 // documentation.
15693 if (!Decl || !Decl->isPFPType() || Decl->isUnion())
15694 return;
15695 const ASTRecordLayout &RL = Ctx.getASTRecordLayout(D: Decl);
15696 for (FieldDecl *Field : Decl->fields()) {
15697 CharUnits FieldOffset =
15698 Offset +
15699 Ctx.toCharUnitsFromBits(BitSize: RL.getFieldOffset(FieldNo: Field->getFieldIndex()));
15700 if (Ctx.isPFPField(Field))
15701 Fields.push_back(x: {.Offset: FieldOffset, .Field: Field});
15702 findPFPFields(Ctx, Ty: Field->getType(), Offset: FieldOffset, Fields,
15703 /*IncludeVBases=*/true);
15704 }
15705 // Pass false for IncludeVBases below because vbases are only included in
15706 // layout for top-level types, i.e. not bases or vbases.
15707 for (CXXBaseSpecifier &Base : Decl->bases()) {
15708 if (Base.isVirtual())
15709 continue;
15710 CharUnits BaseOffset =
15711 Offset + RL.getBaseClassOffset(Base: Base.getType()->getAsCXXRecordDecl());
15712 findPFPFields(Ctx, Ty: Base.getType(), Offset: BaseOffset, Fields,
15713 /*IncludeVBases=*/false);
15714 }
15715 if (IncludeVBases) {
15716 for (CXXBaseSpecifier &Base : Decl->vbases()) {
15717 CharUnits BaseOffset =
15718 Offset + RL.getVBaseClassOffset(VBase: Base.getType()->getAsCXXRecordDecl());
15719 findPFPFields(Ctx, Ty: Base.getType(), Offset: BaseOffset, Fields,
15720 /*IncludeVBases=*/false);
15721 }
15722 }
15723}
15724
15725std::vector<PFPField> ASTContext::findPFPFields(QualType Ty) const {
15726 std::vector<PFPField> PFPFields;
15727 ::findPFPFields(Ctx: *this, Ty, Offset: CharUnits::Zero(), Fields&: PFPFields, IncludeVBases: true);
15728 return PFPFields;
15729}
15730
15731bool ASTContext::hasPFPFields(QualType Ty) const {
15732 return !findPFPFields(Ty).empty();
15733}
15734
15735bool ASTContext::isPFPField(const FieldDecl *FD) {
15736 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: FD->getParent()))
15737 return RD->isPFPType() && FD->getType()->isPointerType() &&
15738 !FD->hasAttr<NoFieldProtectionAttr>();
15739 return false;
15740}
15741
15742void ASTContext::recordMemberDataPointerEvaluation(const ValueDecl *VD) {
15743 auto *FD = dyn_cast<FieldDecl>(Val: VD);
15744 if (!FD)
15745 FD = cast<FieldDecl>(Val: cast<IndirectFieldDecl>(Val: VD)->chain().back());
15746 if (isPFPField(FD))
15747 PFPFieldsWithEvaluatedOffset.insert(X: FD);
15748}
15749
15750void ASTContext::recordOffsetOfEvaluation(const OffsetOfExpr *E) {
15751 if (E->getNumComponents() == 0)
15752 return;
15753 OffsetOfNode Comp = E->getComponent(Idx: E->getNumComponents() - 1);
15754 if (Comp.getKind() != OffsetOfNode::Field)
15755 return;
15756 if (FieldDecl *FD = Comp.getField(); isPFPField(FD))
15757 PFPFieldsWithEvaluatedOffset.insert(X: FD);
15758}
15759
15760namespace {
15761// PaddingCalculator is a utility class that calculates the padding bits in a
15762// c/c++ type. It traverses the type recursively, collecting occupied
15763// bit intervals, and then computes the padding intervals.
15764// If a byte only contains some padding bits, it gets intervals for only those
15765// bits. This is the case for bit-fields.
15766struct PaddingCalculator {
15767 PaddingCalculator(const ASTContext &Ctx) : Ctx(Ctx) {}
15768
15769 void run(QualType Ty) {
15770 OccuppiedIntervals.clear();
15771 Stack.clear();
15772
15773 TySizeInBits = Ctx.getTypeSize(T: Ty);
15774
15775 Stack.push_back(Elt: Data{.StartBitOffset: 0, .Ty: Ty.getCanonicalType(), .VisitVirtualBase: true});
15776 while (!Stack.empty()) {
15777 Data Current = Stack.back();
15778 Stack.pop_back();
15779 Visit(D: Current);
15780 }
15781 MergeOccuppiedIntervals();
15782 }
15783
15784 llvm::SmallVector<ASTContext::BitInterval> GetPaddingIntervals() {
15785 llvm::SmallVector<ASTContext::BitInterval> Results;
15786 if (OccuppiedIntervals.size() == 1 &&
15787 OccuppiedIntervals.front().First == 0 &&
15788 OccuppiedIntervals.front().Last == TySizeInBits) {
15789 return Results;
15790 }
15791 Results.reserve(N: OccuppiedIntervals.size() + 1);
15792 uint64_t CurrentPos = 0;
15793 for (const ASTContext::BitInterval &OccupiedInterval : OccuppiedIntervals) {
15794 if (OccupiedInterval.First > CurrentPos) {
15795 Results.push_back(
15796 Elt: ASTContext::BitInterval{.First: CurrentPos, .Last: OccupiedInterval.First});
15797 }
15798 CurrentPos = OccupiedInterval.Last;
15799 }
15800 if (TySizeInBits > CurrentPos) {
15801 Results.push_back(Elt: ASTContext::BitInterval{.First: CurrentPos, .Last: TySizeInBits});
15802 }
15803 return Results;
15804 }
15805
15806private:
15807 struct Data {
15808 uint64_t StartBitOffset;
15809 QualType Ty;
15810 bool VisitVirtualBase;
15811 };
15812
15813 // Return the number of non padding bits of a scalar type.
15814 //
15815 // The property that we specifically care about here is whether the scalar
15816 // type has padding bits, i.e. are there bits in the type which are not
15817 // specified by the ABI.
15818 //
15819 // We currently don't care about this anywhere else in clang: layout cares
15820 // about the ABI size, calling convention code cares about specific types,
15821 // but nothing cares about padding specifically. And it's not something we can
15822 // easily query from LLVM due to the type system mismatches.
15823 // DL.getTypeSizeInBits(convertTypeForLoadStore(T)) is probably close, but the
15824 // DataLayout methods aren't really designed for this usage.
15825 //
15826 // Therefore, it is better to explicitly list all the scalar types
15827 // containing padding bits that we know of, namely, _BitInt(N) and x87 long
15828 // double.
15829 //
15830 // FIXME: There are likely other scalar types we need to think about here, as
15831 // brought up in review for #215823:
15832 // - bool
15833 // - enums(both with/without fixed underlying type)
15834 // - nullptr_t
15835 // - more?
15836 uint64_t getScalarOccupiedSizeInBits(QualType Ty) const {
15837 if (const auto *BIT = Ty->getAs<BitIntType>())
15838 return BIT->getNumBits();
15839
15840 if (const auto *BT = Ty->getAs<BuiltinType>()) {
15841 if (BT->getKind() == BuiltinType::LongDouble &&
15842 &Ctx.getTargetInfo().getLongDoubleFormat() ==
15843 &llvm::APFloat::x87DoubleExtended())
15844 return llvm::APFloat::getSizeInBits(
15845 Sem: Ctx.getTargetInfo().getLongDoubleFormat());
15846 }
15847
15848 return Ctx.getTypeSize(T: Ty);
15849 }
15850
15851 void Visit(const Data &D) {
15852 if (auto *AT = dyn_cast<ConstantArrayType>(Val: D.Ty)) {
15853 VisitArray(AT, StartBitOffset: D.StartBitOffset);
15854 return;
15855 }
15856
15857 if (auto *Record = D.Ty->getAsRecordDecl()) {
15858 VisitStruct(R: Record, StartBitOffset: D.StartBitOffset, VisitVirtualBase: D.VisitVirtualBase);
15859 return;
15860 }
15861
15862 if (D.Ty->isAtomicType()) {
15863 auto Unwrapped = D;
15864 Unwrapped.Ty = D.Ty.getAtomicUnqualifiedType().getCanonicalType();
15865 Stack.push_back(Elt: Unwrapped);
15866 return;
15867 }
15868
15869 if (const auto *Complex = D.Ty->getAs<ComplexType>()) {
15870 VisitComplex(CT: Complex, StartBitOffset: D.StartBitOffset);
15871 return;
15872 }
15873
15874 if (const auto *VT = D.Ty->getAs<clang::VectorType>()) {
15875 VisitVector(VT, StartBitOffset: D.StartBitOffset);
15876 return;
15877 }
15878
15879 if (const auto *BITy = D.Ty->getAs<BitIntType>()) {
15880 VisitBitInt(Ty: BITy, StartBitOffset: D.StartBitOffset);
15881 return;
15882 }
15883
15884 uint64_t SizeBit = getScalarOccupiedSizeInBits(Ty: D.Ty);
15885 OccuppiedIntervals.push_back(
15886 Elt: ASTContext::BitInterval{.First: D.StartBitOffset, .Last: D.StartBitOffset + SizeBit});
15887 }
15888
15889 void VisitArray(const ConstantArrayType *AT, uint64_t StartBitOffset) {
15890 for (uint64_t ArrIndex = 0; ArrIndex < AT->getSize().getLimitedValue();
15891 ++ArrIndex) {
15892
15893 QualType ElementQualType = AT->getElementType();
15894 auto ElementSize = Ctx.getTypeSizeInChars(T: ElementQualType);
15895 auto ElementAlign = Ctx.getTypeAlignInChars(T: ElementQualType);
15896 auto Offset = ElementSize.alignTo(Align: ElementAlign);
15897
15898 Stack.push_back(Elt: Data{
15899 .StartBitOffset: StartBitOffset + ArrIndex * Offset.getQuantity() * Ctx.getCharWidth(),
15900 .Ty: ElementQualType.getCanonicalType(), /*VisitVirtualBase*/ true});
15901 }
15902 }
15903
15904 void VisitStruct(const RecordDecl *R, uint64_t StartBitOffset,
15905 bool VisitVirtualBase) {
15906 const ASTRecordLayout &ASTLayout = Ctx.getASTRecordLayout(D: R);
15907 auto *CXXRecord = dyn_cast<CXXRecordDecl>(Val: R);
15908
15909 unsigned PointerSizeInBits = Ctx.getTypeSize(T: Ctx.NullPtrTy);
15910
15911 if (CXXRecord) {
15912 if (ASTLayout.hasOwnVFPtr()) {
15913 OccuppiedIntervals.push_back(Elt: ASTContext::BitInterval{
15914 .First: StartBitOffset, .Last: StartBitOffset + PointerSizeInBits});
15915 }
15916
15917 if (ASTLayout.hasOwnVBPtr()) {
15918 auto Offset = ASTLayout.getVBPtrOffset().getQuantity();
15919 auto StartVBPtr = StartBitOffset + Offset * Ctx.getCharWidth();
15920 OccuppiedIntervals.push_back(Elt: ASTContext::BitInterval{
15921 .First: StartVBPtr, .Last: StartVBPtr + PointerSizeInBits});
15922 }
15923
15924 const auto VisitBase = [&ASTLayout, StartBitOffset, this](
15925 const CXXBaseSpecifier &Base, auto GetOffset) {
15926 auto *BaseRecord = Base.getType()->getAsCXXRecordDecl();
15927 if (!BaseRecord) {
15928 return;
15929 }
15930 auto BaseOffset =
15931 std::invoke(GetOffset, ASTLayout, BaseRecord).getQuantity();
15932
15933 Stack.push_back(
15934 Elt: Data{StartBitOffset + BaseOffset * Ctx.getCharWidth(),
15935 Base.getType().getCanonicalType(), /*VisitVirtualBase*/
15936 false});
15937 };
15938
15939 for (auto Base : CXXRecord->bases()) {
15940 if (!Base.isVirtual()) {
15941 VisitBase(Base, &ASTRecordLayout::getBaseClassOffset);
15942 }
15943 }
15944
15945 if (VisitVirtualBase) {
15946 for (auto VBase : CXXRecord->vbases()) {
15947 VisitBase(VBase, &ASTRecordLayout::getVBaseClassOffset);
15948 }
15949 }
15950 }
15951
15952 for (auto *Field : R->fields()) {
15953 // Treat unnamed bitfields as padding.
15954 if (Field->isUnnamedBitField())
15955 continue;
15956
15957 auto FieldOffset = ASTLayout.getFieldOffset(FieldNo: Field->getFieldIndex());
15958 if (Field->isBitField()) {
15959 VisitBitfield(Field, StartBitOffset: StartBitOffset + FieldOffset);
15960 } else {
15961 Stack.push_back(Elt: Data{.StartBitOffset: StartBitOffset + FieldOffset,
15962 .Ty: Field->getType().getCanonicalType(),
15963 /*VisitVirtualBase*/ true});
15964 }
15965 }
15966 }
15967
15968 void VisitBitfield(const FieldDecl *Field, uint64_t StartBitOffset) {
15969 assert(Field->isBitField() && !Field->isUnnamedBitField());
15970 if (Field->isZeroLengthBitField())
15971 return;
15972
15973 const uint64_t DeclaredSizeInBits = Field->getBitWidthValue();
15974
15975 // Oversized bit-fields (declared width larger than the field type) occupy
15976 // only the type's width. The extra declared bits are padding and follow
15977 // the occupied bits (Itanium C++ ABI §2.4, II.1(b)).
15978 // In case where the bitfield can only have values with a range smaller than
15979 // the one declared, e.g. bool a : 5 or _BitInt(5) b : 6, the remaining bits
15980 // within the bitfield are for sign or zero extension. These are considered
15981 // occupied as well.
15982 const uint64_t OccupiedSizeInBits =
15983 std::min(a: DeclaredSizeInBits, b: Ctx.getTypeSize(T: Field->getType()));
15984
15985 if (Ctx.getTargetInfo().isLittleEndian()) {
15986 OccuppiedIntervals.push_back(
15987 Elt: {.First: StartBitOffset, .Last: StartBitOffset + OccupiedSizeInBits});
15988 return;
15989 }
15990
15991 // In big endian mode, the sequence of occupied bits traverses bytes in
15992 // increasing address order, just like in little endian. However, within
15993 // each byte, the traversal starts from the most significant bit. This is
15994 // where it differs from little endian.
15995 //
15996 // If the interval contains whole bytes in the middle, then for these
15997 // nothing changes, and they constitute a contiguous interval. However for
15998 // the partially occupied bytes in either end, if present, their bit
15999 // intervals need to be adjusted so that they count from the MSB instead.
16000 //
16001 // Occupied bits are allocated first, and any padding follows them.
16002 const uint64_t Start = StartBitOffset;
16003 const uint64_t End = Start + OccupiedSizeInBits;
16004 const uint64_t CharWidth = Ctx.getCharWidth();
16005
16006 // Special case: all the occupied bits are contained within a single byte.
16007 const uint64_t ByteStart = llvm::alignDown(Value: Start, Align: CharWidth);
16008 const uint64_t ByteEnd = llvm::alignTo(Value: End, Align: CharWidth);
16009 if (ByteStart == ByteEnd - CharWidth) {
16010 const uint64_t Length = End - Start;
16011 const uint64_t Offset = Start - ByteStart;
16012 OccuppiedIntervals.push_back(
16013 Elt: {.First: ByteEnd - Offset - Length, .Last: ByteEnd - Offset});
16014 return;
16015 }
16016
16017 // Compute the contiguous interval in the middle, comprised of whole bytes,
16018 // if any.
16019 const uint64_t MiddleIntervalStart = llvm::alignTo(Value: Start, Align: CharWidth);
16020 const uint64_t MiddleIntervalEnd = llvm::alignDown(Value: End, Align: CharWidth);
16021 if (MiddleIntervalStart != MiddleIntervalEnd)
16022 OccuppiedIntervals.push_back(Elt: {.First: MiddleIntervalStart, .Last: MiddleIntervalEnd});
16023
16024 // Compute the partially occupied first byte's interval, if any, counting
16025 // from the MSB.
16026 if (Start != MiddleIntervalStart) {
16027 const uint64_t Length = MiddleIntervalStart - Start;
16028 OccuppiedIntervals.push_back(Elt: {.First: ByteStart, .Last: ByteStart + Length});
16029 }
16030
16031 // Compute the partially occupied last byte's interval, if any, counting
16032 // from the MSB.
16033 if (End != MiddleIntervalEnd) {
16034 const uint64_t Length = End - MiddleIntervalEnd;
16035 OccuppiedIntervals.push_back(Elt: {.First: ByteEnd - Length, .Last: ByteEnd});
16036 }
16037 }
16038
16039 void VisitComplex(const ComplexType *CT, uint64_t StartBitOffset) {
16040 QualType ElementQualType = CT->getElementType().getCanonicalType();
16041 auto ElementSize = Ctx.getTypeSizeInChars(T: ElementQualType);
16042 auto ElementAlign = Ctx.getTypeAlignInChars(T: ElementQualType);
16043 auto ImgOffset = ElementSize.alignTo(Align: ElementAlign);
16044
16045 Stack.push_back(
16046 Elt: Data{.StartBitOffset: StartBitOffset, .Ty: ElementQualType, /*VisitVirtualBase*/ true});
16047 Stack.push_back(
16048 Elt: Data{.StartBitOffset: StartBitOffset + ImgOffset.getQuantity() * Ctx.getCharWidth(),
16049 .Ty: ElementQualType, /*VisitVirtualBase*/ true});
16050 }
16051
16052 void VisitVector(const clang::VectorType *VT, uint64_t StartBitOffset) {
16053 if (VT->isPackedVectorBoolType(ctx: Ctx)) {
16054 VisitPackedBooleanVector(VTy: VT, StartBitOffset);
16055 return;
16056 }
16057
16058 uint64_t SizeBit = getScalarOccupiedSizeInBits(Ty: VT->getElementType()) *
16059 VT->getNumElements();
16060 OccuppiedIntervals.push_back(
16061 Elt: ASTContext::BitInterval{.First: StartBitOffset, .Last: StartBitOffset + SizeBit});
16062 }
16063
16064 /// Compute the occupied bit intervals for a BitInt.
16065 ///
16066 /// In the case of little endian, the occupied bits are always contiguous so a
16067 /// single interval is sufficient. However in big endian, the intervals can be
16068 /// disjoint.
16069 void VisitBitInt(const BitIntType *Ty, uint64_t StartBitOffset) {
16070 const uint64_t OccupiedSizeInBits = Ty->getNumBits();
16071
16072 if (Ctx.getTargetInfo().isLittleEndian()) {
16073 OccuppiedIntervals.push_back(
16074 Elt: {.First: StartBitOffset, .Last: StartBitOffset + OccupiedSizeInBits});
16075 return;
16076 }
16077
16078 // In big endian mode, the layout of a BitInt in memory has its bytes in
16079 // reverse order, and is pictured in this order:
16080 // 1. Fully padding bytes.
16081 // 2. One partially occupied byte, with padding at the most significant
16082 // bits. ("remaining occupied bits")
16083 // 3. A sequence of fully occupied bytes up until the end of the storage.
16084 const uint64_t StorageSizeInBits = Ctx.getTypeSize(T: Ty);
16085 const uint64_t CharWidth = Ctx.getCharWidth();
16086 const uint64_t NumFullyPaddingBytes =
16087 (StorageSizeInBits - OccupiedSizeInBits) / CharWidth;
16088 const uint64_t NumFullyOccupiedBytes = OccupiedSizeInBits / CharWidth;
16089 const uint64_t NumRemainingOccupiedBits = OccupiedSizeInBits % CharWidth;
16090
16091 // Partially occupied byte
16092 if (NumRemainingOccupiedBits > 0)
16093 OccuppiedIntervals.push_back(
16094 Elt: {.First: StartBitOffset + NumFullyPaddingBytes * CharWidth,
16095 .Last: StartBitOffset + NumFullyPaddingBytes * CharWidth +
16096 NumRemainingOccupiedBits});
16097
16098 // Fully occupied bytes
16099 if (NumFullyOccupiedBytes > 0)
16100 OccuppiedIntervals.push_back(Elt: {.First: StartBitOffset + StorageSizeInBits -
16101 NumFullyOccupiedBytes * CharWidth,
16102 .Last: StartBitOffset + StorageSizeInBits});
16103 }
16104
16105 void VisitPackedBooleanVector(const VectorType *VTy,
16106 uint64_t StartBitOffset) {
16107 const uint64_t CharWidth = Ctx.getCharWidth();
16108 assert(StartBitOffset % CharWidth == 0 &&
16109 "Expected aligned packed boolean vector");
16110 assert(VTy->isPackedVectorBoolType(Ctx));
16111 const uint64_t OccupiedSizeInBits = VTy->getNumElements();
16112
16113 if (Ctx.getTargetInfo().isLittleEndian()) {
16114 OccuppiedIntervals.push_back(
16115 Elt: {.First: StartBitOffset, .Last: StartBitOffset + OccupiedSizeInBits});
16116 return;
16117 }
16118
16119 // Only the sequence of bytes containing occupied bits has its order
16120 // reversed, but the bits within each byte are still counted from the least
16121 // significant bit. So if there are fully padding bytes, they reside at the
16122 // higher addresses in both endiannesses.
16123 const uint64_t NumFullyOccupiedBytes = OccupiedSizeInBits / CharWidth;
16124 const uint64_t NumRemainingOccupiedBits = OccupiedSizeInBits % CharWidth;
16125
16126 uint64_t Start = StartBitOffset;
16127 // Partially occupied byte at the beginning
16128 if (NumRemainingOccupiedBits > 0) {
16129 const uint64_t ByteEnd = Start + CharWidth;
16130 OccuppiedIntervals.push_back(Elt: {.First: Start, .Last: Start + NumRemainingOccupiedBits});
16131 Start = ByteEnd;
16132 }
16133
16134 // The remaining fully occupied bytes form a contiguous interval
16135 if (NumFullyOccupiedBytes > 0) {
16136 OccuppiedIntervals.push_back(
16137 Elt: {.First: Start, .Last: Start + NumFullyOccupiedBytes * CharWidth});
16138 }
16139 }
16140
16141 void MergeOccuppiedIntervals() {
16142 std::sort(first: OccuppiedIntervals.begin(), last: OccuppiedIntervals.end(),
16143 comp: [](const ASTContext::BitInterval &lhs,
16144 const ASTContext::BitInterval &rhs) {
16145 return std::tie(args: lhs.First, args: lhs.Last) <
16146 std::tie(args: rhs.First, args: rhs.Last);
16147 });
16148
16149 llvm::SmallVector<ASTContext::BitInterval> Merged;
16150 Merged.reserve(N: OccuppiedIntervals.size());
16151
16152 for (const ASTContext::BitInterval &NextInterval : OccuppiedIntervals) {
16153 if (Merged.empty()) {
16154 Merged.push_back(Elt: NextInterval);
16155 continue;
16156 }
16157 auto &LastInterval = Merged.back();
16158
16159 if (NextInterval.First > LastInterval.Last) {
16160 Merged.push_back(Elt: NextInterval);
16161 } else {
16162 LastInterval.Last = std::max(a: LastInterval.Last, b: NextInterval.Last);
16163 }
16164 }
16165
16166 OccuppiedIntervals = Merged;
16167 }
16168
16169 const ASTContext &Ctx;
16170 // unsigned PointerSizeInBits;
16171 uint64_t TySizeInBits = 0;
16172 llvm::SmallVector<Data> Stack;
16173 llvm::SmallVector<ASTContext::BitInterval> OccuppiedIntervals;
16174};
16175} // namespace
16176
16177llvm::ArrayRef<ASTContext::BitInterval>
16178ASTContext::getPaddingIntervals(QualType Ty) const {
16179 Ty = Ty.getCanonicalType();
16180 auto cached = PaddingIntervalCache.find(Val: Ty);
16181 if (cached != PaddingIntervalCache.end())
16182 return cached->second;
16183
16184 PaddingCalculator pc{*this};
16185 pc.run(Ty);
16186
16187 auto [itr, res] =
16188 PaddingIntervalCache.insert_or_assign(Key: Ty, Val: pc.GetPaddingIntervals());
16189 assert(res && "Failed to insert?");
16190
16191 return itr->second;
16192}
16193