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/ASTLambda.h"
19#include "clang/AST/ASTMutationListener.h"
20#include "clang/AST/ASTStructuralEquivalence.h"
21#include "clang/AST/ASTTypeTraits.h"
22#include "clang/AST/Attr.h"
23#include "clang/AST/AttrIterator.h"
24#include "clang/AST/CharUnits.h"
25#include "clang/AST/Comment.h"
26#include "clang/AST/Decl.h"
27#include "clang/AST/DeclBase.h"
28#include "clang/AST/DeclCXX.h"
29#include "clang/AST/DeclContextInternals.h"
30#include "clang/AST/DeclObjC.h"
31#include "clang/AST/DeclOpenMP.h"
32#include "clang/AST/DeclTemplate.h"
33#include "clang/AST/DeclarationName.h"
34#include "clang/AST/DependenceFlags.h"
35#include "clang/AST/Expr.h"
36#include "clang/AST/ExprCXX.h"
37#include "clang/AST/ExternalASTSource.h"
38#include "clang/AST/Mangle.h"
39#include "clang/AST/MangleNumberingContext.h"
40#include "clang/AST/NestedNameSpecifier.h"
41#include "clang/AST/ParentMapContext.h"
42#include "clang/AST/RawCommentList.h"
43#include "clang/AST/RecordLayout.h"
44#include "clang/AST/Stmt.h"
45#include "clang/AST/TemplateBase.h"
46#include "clang/AST/TemplateName.h"
47#include "clang/AST/Type.h"
48#include "clang/AST/TypeLoc.h"
49#include "clang/AST/UnresolvedSet.h"
50#include "clang/AST/VTableBuilder.h"
51#include "clang/Basic/AddressSpaces.h"
52#include "clang/Basic/Builtins.h"
53#include "clang/Basic/CommentOptions.h"
54#include "clang/Basic/DiagnosticAST.h"
55#include "clang/Basic/ExceptionSpecificationType.h"
56#include "clang/Basic/IdentifierTable.h"
57#include "clang/Basic/LLVM.h"
58#include "clang/Basic/LangOptions.h"
59#include "clang/Basic/Linkage.h"
60#include "clang/Basic/Module.h"
61#include "clang/Basic/NoSanitizeList.h"
62#include "clang/Basic/ObjCRuntime.h"
63#include "clang/Basic/ProfileList.h"
64#include "clang/Basic/SourceLocation.h"
65#include "clang/Basic/SourceManager.h"
66#include "clang/Basic/Specifiers.h"
67#include "clang/Basic/TargetCXXABI.h"
68#include "clang/Basic/TargetInfo.h"
69#include "clang/Basic/XRayLists.h"
70#include "clang/Lex/MacroInfo.h"
71#include "llvm/ADT/APFixedPoint.h"
72#include "llvm/ADT/APInt.h"
73#include "llvm/ADT/APSInt.h"
74#include "llvm/ADT/ArrayRef.h"
75#include "llvm/ADT/DenseMap.h"
76#include "llvm/ADT/DenseSet.h"
77#include "llvm/ADT/FoldingSet.h"
78#include "llvm/ADT/PointerUnion.h"
79#include "llvm/ADT/STLExtras.h"
80#include "llvm/ADT/SmallPtrSet.h"
81#include "llvm/ADT/SmallVector.h"
82#include "llvm/ADT/StringExtras.h"
83#include "llvm/ADT/StringRef.h"
84#include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
85#include "llvm/Support/Capacity.h"
86#include "llvm/Support/Casting.h"
87#include "llvm/Support/Compiler.h"
88#include "llvm/Support/ErrorHandling.h"
89#include "llvm/Support/MD5.h"
90#include "llvm/Support/MathExtras.h"
91#include "llvm/Support/SipHash.h"
92#include "llvm/Support/raw_ostream.h"
93#include "llvm/TargetParser/AArch64TargetParser.h"
94#include "llvm/TargetParser/Triple.h"
95#include <algorithm>
96#include <cassert>
97#include <cstddef>
98#include <cstdint>
99#include <cstdlib>
100#include <map>
101#include <memory>
102#include <optional>
103#include <string>
104#include <tuple>
105#include <utility>
106
107using namespace clang;
108
109enum FloatingRank {
110 BFloat16Rank,
111 Float16Rank,
112 HalfRank,
113 FloatRank,
114 DoubleRank,
115 LongDoubleRank,
116 Float128Rank,
117 Ibm128Rank
118};
119
120/// \returns The locations that are relevant when searching for Doc comments
121/// related to \p Key.
122static SmallVector<SourceLocation, 2>
123getLocsForCommentSearch(ASTContext::RawCommentLookupKey Key,
124 SourceManager &SourceMgr) {
125 if (const auto *MI = dyn_cast<const MacroInfo *>(Val&: Key)) {
126 SourceLocation DefLoc = MI->getDefinitionLoc();
127 if (DefLoc.isInvalid() || !DefLoc.isFileID())
128 return {};
129
130 // The macro's definition location points at its name (e.g. FOO in
131 // `#define FOO 1`). The text between a preceding documentation comment
132 // and the name contains the `#define` directive itself, which would be
133 // rejected by the preprocessor-directive guard in
134 // getRawCommentNoCacheImpl. Walk back to the leading `#` so that
135 // the guard only fires when something *else* sits between the comment
136 // and our directive.
137 FileIDAndOffset Decomposed = SourceMgr.getDecomposedLoc(Loc: DefLoc);
138 bool Invalid = false;
139 StringRef Buffer = SourceMgr.getBufferData(FID: Decomposed.first, Invalid: &Invalid);
140 if (Invalid)
141 return {};
142 unsigned Offset = Decomposed.second;
143 if (size_t Found = Buffer.find_last_of(Chars: "#\n", From: Offset);
144 Found != StringRef::npos)
145 Offset = Found;
146 return {SourceMgr.getLocForStartOfFile(FID: Decomposed.first)
147 .getLocWithOffset(Offset)};
148 }
149
150 const auto *D = cast<const Decl *>(Val&: Key);
151 assert(D);
152
153 // User can not attach documentation to implicit declarations.
154 if (D->isImplicit())
155 return {};
156
157 // User can not attach documentation to implicit instantiations.
158 if (const auto *FD = dyn_cast<FunctionDecl>(Val: D)) {
159 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
160 return {};
161 }
162
163 if (const auto *VD = dyn_cast<VarDecl>(Val: D)) {
164 if (VD->isStaticDataMember() &&
165 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
166 return {};
167 }
168
169 if (const auto *CRD = dyn_cast<CXXRecordDecl>(Val: D)) {
170 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
171 return {};
172 }
173
174 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Val: D)) {
175 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
176 if (TSK == TSK_ImplicitInstantiation ||
177 TSK == TSK_Undeclared)
178 return {};
179 }
180
181 if (const auto *ED = dyn_cast<EnumDecl>(Val: D)) {
182 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
183 return {};
184 }
185 if (const auto *TD = dyn_cast<TagDecl>(Val: D)) {
186 // When tag declaration (but not definition!) is part of the
187 // decl-specifier-seq of some other declaration, it doesn't get comment
188 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
189 return {};
190 }
191 // TODO: handle comments for function parameters properly.
192 if (isa<ParmVarDecl>(Val: D))
193 return {};
194
195 // TODO: we could look up template parameter documentation in the template
196 // documentation.
197 if (isa<TemplateTypeParmDecl>(Val: D) ||
198 isa<NonTypeTemplateParmDecl>(Val: D) ||
199 isa<TemplateTemplateParmDecl>(Val: D))
200 return {};
201
202 SmallVector<SourceLocation, 2> Locations;
203 // Find declaration location.
204 // For Objective-C declarations we generally don't expect to have multiple
205 // declarators, thus use declaration starting location as the "declaration
206 // location".
207 // For all other declarations multiple declarators are used quite frequently,
208 // so we use the location of the identifier as the "declaration location".
209 SourceLocation BaseLocation;
210 if (isa<ObjCMethodDecl>(Val: D) || isa<ObjCContainerDecl>(Val: D) ||
211 isa<ObjCPropertyDecl>(Val: D) || isa<RedeclarableTemplateDecl>(Val: D) ||
212 isa<ClassTemplateSpecializationDecl>(Val: D) ||
213 // Allow association with Y across {} in `typedef struct X {} Y`.
214 isa<TypedefDecl>(Val: D))
215 BaseLocation = D->getBeginLoc();
216 else
217 BaseLocation = D->getLocation();
218
219 if (!D->getLocation().isMacroID()) {
220 Locations.emplace_back(Args&: BaseLocation);
221 } else {
222 const auto *DeclCtx = D->getDeclContext();
223
224 // When encountering definitions generated from a macro (that are not
225 // contained by another declaration in the macro) we need to try and find
226 // the comment at the location of the expansion but if there is no comment
227 // there we should retry to see if there is a comment inside the macro as
228 // well. To this end we return first BaseLocation to first look at the
229 // expansion site, the second value is the spelling location of the
230 // beginning of the declaration defined inside the macro.
231 if (!(DeclCtx &&
232 Decl::castFromDeclContext(DeclCtx)->getLocation().isMacroID())) {
233 Locations.emplace_back(Args: SourceMgr.getExpansionLoc(Loc: BaseLocation));
234 }
235
236 // We use Decl::getBeginLoc() and not just BaseLocation here to ensure that
237 // we don't refer to the macro argument location at the expansion site (this
238 // can happen if the name's spelling is provided via macro argument), and
239 // always to the declaration itself.
240 Locations.emplace_back(Args: SourceMgr.getSpellingLoc(Loc: D->getBeginLoc()));
241 }
242
243 return Locations;
244}
245
246RawComment *ASTContext::getRawCommentNoCacheImpl(
247 RawCommentLookupKey Key, const SourceLocation RepresentativeLoc,
248 const std::map<unsigned, RawComment *> &CommentsInTheFile) const {
249 // If the declaration doesn't map directly to a location in a file, we
250 // can't find the comment.
251 if (RepresentativeLoc.isInvalid() || !RepresentativeLoc.isFileID())
252 return nullptr;
253
254 // If there are no comments anywhere, we won't find anything.
255 if (CommentsInTheFile.empty())
256 return nullptr;
257
258 const auto *D = dyn_cast<const Decl *>(Val&: Key);
259 const bool IsMacro = isa<const MacroInfo *>(Val: Key);
260
261 // Decompose the location for the declaration and find the beginning of the
262 // file buffer.
263 const FileIDAndOffset LocDecomp =
264 SourceMgr.getDecomposedLoc(Loc: RepresentativeLoc);
265
266 // Slow path.
267 auto OffsetCommentBehindDecl =
268 CommentsInTheFile.lower_bound(x: LocDecomp.second);
269
270 // First check whether we have a trailing comment.
271 if (OffsetCommentBehindDecl != CommentsInTheFile.end()) {
272 RawComment *CommentBehindDecl = OffsetCommentBehindDecl->second;
273 if ((CommentBehindDecl->isDocumentation() ||
274 LangOpts.CommentOpts.ParseAllComments) &&
275 CommentBehindDecl->isTrailingComment() &&
276 (IsMacro || (D && (isa<FieldDecl>(Val: D) || isa<EnumConstantDecl>(Val: D) ||
277 isa<VarDecl>(Val: D) || isa<ObjCMethodDecl>(Val: D) ||
278 isa<ObjCPropertyDecl>(Val: D))))) {
279
280 // Check that Doxygen trailing comment comes after the declaration, starts
281 // on the same line and in the same file as the declaration.
282 if (SourceMgr.getLineNumber(FID: LocDecomp.first, FilePos: LocDecomp.second) ==
283 Comments.getCommentBeginLine(C: CommentBehindDecl, File: LocDecomp.first,
284 Offset: OffsetCommentBehindDecl->first)) {
285 return CommentBehindDecl;
286 }
287 }
288 }
289
290 // The comment just after the declaration was not a trailing comment.
291 // Let's look at the previous comment.
292 if (OffsetCommentBehindDecl == CommentsInTheFile.begin())
293 return nullptr;
294
295 auto OffsetCommentBeforeDecl = --OffsetCommentBehindDecl;
296 RawComment *CommentBeforeDecl = OffsetCommentBeforeDecl->second;
297
298 // Check that we actually have a non-member Doxygen comment.
299 if (!(CommentBeforeDecl->isDocumentation() ||
300 LangOpts.CommentOpts.ParseAllComments) ||
301 CommentBeforeDecl->isTrailingComment())
302 return nullptr;
303
304 // Decompose the end of the comment.
305 const unsigned CommentEndOffset =
306 Comments.getCommentEndOffset(C: CommentBeforeDecl);
307
308 // Get the corresponding buffer.
309 bool Invalid = false;
310 const char *Buffer =
311 SourceMgr.getBufferData(FID: LocDecomp.first, Invalid: &Invalid).data();
312 if (Invalid)
313 return nullptr;
314
315 // Extract text between the comment and declaration.
316 StringRef Text(Buffer + CommentEndOffset,
317 LocDecomp.second - CommentEndOffset);
318
319 // There should be no other declarations or preprocessor directives between
320 // comment and declaration.
321 if (Text.find_last_of(Chars: ";{}#@") != StringRef::npos)
322 return nullptr;
323
324 return CommentBeforeDecl;
325}
326
327RawComment *ASTContext::getRawCommentNoCache(RawCommentLookupKey Key) const {
328 const auto Locs = getLocsForCommentSearch(Key, SourceMgr);
329
330 for (const auto Loc : Locs) {
331 // If the declaration or macro doesn't map directly to a location in a file,
332 // we can't find the comment.
333 if (Loc.isInvalid() || !Loc.isFileID())
334 continue;
335
336 if (ExternalSource && !CommentsLoaded) {
337 ExternalSource->ReadComments();
338 CommentsLoaded = true;
339 }
340
341 if (Comments.empty())
342 continue;
343
344 const FileID File = SourceMgr.getDecomposedLoc(Loc).first;
345 if (!File.isValid())
346 continue;
347
348 const auto CommentsInThisFile = Comments.getCommentsInFile(File);
349 if (!CommentsInThisFile || CommentsInThisFile->empty())
350 continue;
351
352 if (RawComment *Comment =
353 getRawCommentNoCacheImpl(Key, RepresentativeLoc: Loc, CommentsInTheFile: *CommentsInThisFile))
354 return Comment;
355 }
356
357 return nullptr;
358}
359
360void ASTContext::addComment(const RawComment &RC) {
361 assert(LangOpts.CommentOpts.RetainCommentsFromSystemHeaders ||
362 !SourceMgr.isInSystemHeader(RC.getSourceRange().getBegin()));
363 Comments.addComment(RC, CommentOpts: LangOpts.CommentOpts, Allocator&: BumpAlloc);
364}
365
366const RawComment *
367ASTContext::getRawCommentForAnyRedecl(RawCommentLookupKey Key,
368 const Decl **OriginalDecl) const {
369 if (Key.isNull()) {
370 if (OriginalDecl)
371 *OriginalDecl = nullptr;
372 return nullptr;
373 }
374
375 // Macros have no redeclaration chain: look up directly, populate the cache,
376 // and return.
377 if (const auto *MI = dyn_cast<const MacroInfo *>(Val&: Key)) {
378 if (OriginalDecl)
379 *OriginalDecl = nullptr;
380 auto Existing = RawComments.find(Val: Key);
381 if (Existing != RawComments.end())
382 return Existing->second;
383 if (const RawComment *RC = getRawCommentNoCache(Key)) {
384 cacheRawComment(Original: MI, Comment: *RC);
385 return RC;
386 }
387 return nullptr;
388 }
389
390 const Decl *D = cast<const Decl *>(Val&: Key);
391 D = &adjustDeclToTemplate(D: *D);
392
393 // Any comment directly attached to D?
394 {
395 auto DeclComment = RawComments.find(Val: D);
396 if (DeclComment != RawComments.end()) {
397 if (OriginalDecl)
398 *OriginalDecl = D;
399 return DeclComment->second;
400 }
401 }
402
403 // Any comment attached to any redeclaration of D?
404 const Decl *CanonicalD = D->getCanonicalDecl();
405 if (!CanonicalD)
406 return nullptr;
407
408 {
409 auto RedeclComment = RedeclChainComments.find(Val: CanonicalD);
410 if (RedeclComment != RedeclChainComments.end()) {
411 if (OriginalDecl)
412 *OriginalDecl = RedeclComment->second;
413 auto CommentAtRedecl = RawComments.find(Val: RedeclComment->second);
414 assert(CommentAtRedecl != RawComments.end() &&
415 "This decl is supposed to have comment attached.");
416 return CommentAtRedecl->second;
417 }
418 }
419
420 // Any redeclarations of D that we haven't checked for comments yet?
421 const Decl *LastCheckedRedecl = [&]() {
422 const Decl *LastChecked = CommentlessRedeclChains.lookup(Val: CanonicalD);
423 bool CanUseCommentlessCache = false;
424 if (LastChecked) {
425 for (auto *Redecl : CanonicalD->redecls()) {
426 if (Redecl == D) {
427 CanUseCommentlessCache = true;
428 break;
429 }
430 if (Redecl == LastChecked)
431 break;
432 }
433 }
434 // FIXME: This could be improved so that even if CanUseCommentlessCache
435 // is false, once we've traversed past CanonicalD we still skip ahead
436 // LastChecked.
437 return CanUseCommentlessCache ? LastChecked : nullptr;
438 }();
439
440 for (const Decl *Redecl : D->redecls()) {
441 assert(Redecl);
442 // Skip all redeclarations that have been checked previously.
443 if (LastCheckedRedecl) {
444 if (LastCheckedRedecl == Redecl) {
445 LastCheckedRedecl = nullptr;
446 }
447 continue;
448 }
449 const RawComment *RedeclComment = getRawCommentNoCache(Key: Redecl);
450 if (RedeclComment) {
451 cacheRawComment(Original: Redecl, Comment: *RedeclComment);
452 if (OriginalDecl)
453 *OriginalDecl = Redecl;
454 return RedeclComment;
455 }
456 CommentlessRedeclChains[CanonicalD] = Redecl;
457 }
458
459 if (OriginalDecl)
460 *OriginalDecl = nullptr;
461 return nullptr;
462}
463
464void ASTContext::cacheRawComment(RawCommentLookupKey Original,
465 const RawComment &Comment) const {
466 assert(Comment.isDocumentation() || LangOpts.CommentOpts.ParseAllComments);
467 RawComments.try_emplace(Key: Original, Args: &Comment);
468 if (const auto *D = dyn_cast<const Decl *>(Val&: Original)) {
469 const Decl *const CanonicalDecl = D->getCanonicalDecl();
470 RedeclChainComments.try_emplace(Key: CanonicalDecl, Args&: D);
471 CommentlessRedeclChains.erase(Val: CanonicalDecl);
472 }
473}
474
475static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
476 SmallVectorImpl<const NamedDecl *> &Redeclared) {
477 const DeclContext *DC = ObjCMethod->getDeclContext();
478 if (const auto *IMD = dyn_cast<ObjCImplDecl>(Val: DC)) {
479 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
480 if (!ID)
481 return;
482 // Add redeclared method here.
483 for (const auto *Ext : ID->known_extensions()) {
484 if (ObjCMethodDecl *RedeclaredMethod =
485 Ext->getMethod(Sel: ObjCMethod->getSelector(),
486 isInstance: ObjCMethod->isInstanceMethod()))
487 Redeclared.push_back(Elt: RedeclaredMethod);
488 }
489 }
490}
491
492void ASTContext::attachCommentsToJustParsedDecls(ArrayRef<Decl *> Decls,
493 const Preprocessor *PP) {
494 if (Comments.empty() || Decls.empty())
495 return;
496
497 FileID File;
498 for (const Decl *D : Decls) {
499 if (D->isInvalidDecl())
500 continue;
501
502 D = &adjustDeclToTemplate(D: *D);
503 SourceLocation Loc = D->getLocation();
504 if (Loc.isValid()) {
505 // See if there are any new comments that are not attached to a decl.
506 // The location doesn't have to be precise - we care only about the file.
507 File = SourceMgr.getDecomposedLoc(Loc).first;
508 break;
509 }
510 }
511
512 if (File.isInvalid())
513 return;
514
515 auto CommentsInThisFile = Comments.getCommentsInFile(File);
516 if (!CommentsInThisFile || CommentsInThisFile->empty() ||
517 CommentsInThisFile->rbegin()->second->isAttached())
518 return;
519
520 // There is at least one comment not attached to a decl.
521 // Maybe it should be attached to one of Decls?
522 //
523 // Note that this way we pick up not only comments that precede the
524 // declaration, but also comments that *follow* the declaration -- thanks to
525 // the lookahead in the lexer: we've consumed the semicolon and looked
526 // ahead through comments.
527 for (const Decl *D : Decls) {
528 assert(D);
529 if (D->isInvalidDecl())
530 continue;
531
532 D = &adjustDeclToTemplate(D: *D);
533
534 if (RawComments.count(Val: D) > 0)
535 continue;
536
537 const auto DeclLocs = getLocsForCommentSearch(Key: D, SourceMgr);
538
539 for (const auto DeclLoc : DeclLocs) {
540 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
541 continue;
542
543 if (RawComment *const DocComment =
544 getRawCommentNoCacheImpl(Key: D, RepresentativeLoc: DeclLoc, CommentsInTheFile: *CommentsInThisFile)) {
545 cacheRawComment(Original: D, Comment: *DocComment);
546 comments::FullComment *FC = DocComment->parse(Context: *this, PP, D);
547 ParsedComments[D->getCanonicalDecl()] = FC;
548 break;
549 }
550 }
551 }
552}
553
554comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
555 const Decl *D) const {
556 auto *ThisDeclInfo = new (*this) comments::DeclInfo;
557 ThisDeclInfo->CommentDecl = D;
558 ThisDeclInfo->IsFilled = false;
559 ThisDeclInfo->fill();
560 ThisDeclInfo->CommentDecl = FC->getDecl();
561 if (!ThisDeclInfo->TemplateParameters)
562 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
563 comments::FullComment *CFC =
564 new (*this) comments::FullComment(FC->getBlocks(),
565 ThisDeclInfo);
566 return CFC;
567}
568
569comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
570 const RawComment *RC = getRawCommentNoCache(Key: D);
571 return RC ? RC->parse(Context: *this, PP: nullptr, D) : nullptr;
572}
573
574comments::FullComment *ASTContext::getCommentForDecl(
575 const Decl *D,
576 const Preprocessor *PP) const {
577 if (!D || D->isInvalidDecl())
578 return nullptr;
579 D = &adjustDeclToTemplate(D: *D);
580
581 const Decl *Canonical = D->getCanonicalDecl();
582 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
583 ParsedComments.find(Val: Canonical);
584
585 if (Pos != ParsedComments.end()) {
586 if (Canonical != D) {
587 comments::FullComment *FC = Pos->second;
588 comments::FullComment *CFC = cloneFullComment(FC, D);
589 return CFC;
590 }
591 return Pos->second;
592 }
593
594 const Decl *OriginalDecl = nullptr;
595
596 const RawComment *RC = getRawCommentForAnyRedecl(Key: D, OriginalDecl: &OriginalDecl);
597 if (!RC) {
598 if (isa<ObjCMethodDecl>(Val: D) || isa<FunctionDecl>(Val: D)) {
599 SmallVector<const NamedDecl*, 8> Overridden;
600 const auto *OMD = dyn_cast<ObjCMethodDecl>(Val: D);
601 if (OMD && OMD->isPropertyAccessor())
602 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
603 if (comments::FullComment *FC = getCommentForDecl(D: PDecl, PP))
604 return cloneFullComment(FC, D);
605 if (OMD)
606 addRedeclaredMethods(ObjCMethod: OMD, Redeclared&: Overridden);
607 getOverriddenMethods(Method: dyn_cast<NamedDecl>(Val: D), Overridden);
608 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
609 if (comments::FullComment *FC = getCommentForDecl(D: Overridden[i], PP))
610 return cloneFullComment(FC, D);
611 }
612 else if (const auto *TD = dyn_cast<TypedefNameDecl>(Val: D)) {
613 // Attach any tag type's documentation to its typedef if latter
614 // does not have one of its own.
615 QualType QT = TD->getUnderlyingType();
616 if (const auto *TT = QT->getAs<TagType>())
617 if (comments::FullComment *FC = getCommentForDecl(D: TT->getDecl(), PP))
618 return cloneFullComment(FC, D);
619 }
620 else if (const auto *IC = dyn_cast<ObjCInterfaceDecl>(Val: D)) {
621 while (IC->getSuperClass()) {
622 IC = IC->getSuperClass();
623 if (comments::FullComment *FC = getCommentForDecl(D: IC, PP))
624 return cloneFullComment(FC, D);
625 }
626 }
627 else if (const auto *CD = dyn_cast<ObjCCategoryDecl>(Val: D)) {
628 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
629 if (comments::FullComment *FC = getCommentForDecl(D: IC, PP))
630 return cloneFullComment(FC, D);
631 }
632 else if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: D)) {
633 if (!(RD = RD->getDefinition()))
634 return nullptr;
635 // Check non-virtual bases.
636 for (const auto &I : RD->bases()) {
637 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
638 continue;
639 QualType Ty = I.getType();
640 if (Ty.isNull())
641 continue;
642 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
643 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
644 continue;
645
646 if (comments::FullComment *FC = getCommentForDecl(D: (NonVirtualBase), PP))
647 return cloneFullComment(FC, D);
648 }
649 }
650 // Check virtual bases.
651 for (const auto &I : RD->vbases()) {
652 if (I.getAccessSpecifier() != AS_public)
653 continue;
654 QualType Ty = I.getType();
655 if (Ty.isNull())
656 continue;
657 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
658 if (!(VirtualBase= VirtualBase->getDefinition()))
659 continue;
660 if (comments::FullComment *FC = getCommentForDecl(D: (VirtualBase), PP))
661 return cloneFullComment(FC, D);
662 }
663 }
664 }
665 return nullptr;
666 }
667
668 // If the RawComment was attached to other redeclaration of this Decl, we
669 // should parse the comment in context of that other Decl. This is important
670 // because comments can contain references to parameter names which can be
671 // different across redeclarations.
672 if (D != OriginalDecl && OriginalDecl)
673 return getCommentForDecl(D: OriginalDecl, PP);
674
675 comments::FullComment *FC = RC->parse(Context: *this, PP, D);
676 ParsedComments[Canonical] = FC;
677 return FC;
678}
679
680void ASTContext::CanonicalTemplateTemplateParm::Profile(
681 llvm::FoldingSetNodeID &ID, const ASTContext &C,
682 TemplateTemplateParmDecl *Parm) {
683 ID.AddInteger(I: Parm->getDepth());
684 ID.AddInteger(I: Parm->getPosition());
685 ID.AddBoolean(B: Parm->isParameterPack());
686 ID.AddInteger(I: Parm->templateParameterKind());
687
688 TemplateParameterList *Params = Parm->getTemplateParameters();
689 ID.AddInteger(I: Params->size());
690 for (TemplateParameterList::const_iterator P = Params->begin(),
691 PEnd = Params->end();
692 P != PEnd; ++P) {
693 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Val: *P)) {
694 ID.AddInteger(I: 0);
695 ID.AddBoolean(B: TTP->isParameterPack());
696 ID.AddInteger(
697 I: TTP->getNumExpansionParameters().toInternalRepresentation());
698 continue;
699 }
700
701 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: *P)) {
702 ID.AddInteger(I: 1);
703 ID.AddBoolean(B: NTTP->isParameterPack());
704 ID.AddPointer(Ptr: C.getUnconstrainedType(T: C.getCanonicalType(T: NTTP->getType()))
705 .getAsOpaquePtr());
706 if (NTTP->isExpandedParameterPack()) {
707 ID.AddBoolean(B: true);
708 ID.AddInteger(I: NTTP->getNumExpansionTypes());
709 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
710 QualType T = NTTP->getExpansionType(I);
711 ID.AddPointer(Ptr: T.getCanonicalType().getAsOpaquePtr());
712 }
713 } else
714 ID.AddBoolean(B: false);
715 continue;
716 }
717
718 auto *TTP = cast<TemplateTemplateParmDecl>(Val: *P);
719 ID.AddInteger(I: 2);
720 Profile(ID, C, Parm: TTP);
721 }
722}
723
724TemplateTemplateParmDecl *
725ASTContext::getCanonicalTemplateTemplateParmDecl(
726 TemplateTemplateParmDecl *TTP) const {
727 // Check if we already have a canonical template template parameter.
728 llvm::FoldingSetNodeID ID;
729 CanonicalTemplateTemplateParm::Profile(ID, C: *this, Parm: TTP);
730 llvm::FoldingSetInsertToken Token;
731 CanonicalTemplateTemplateParm *Canonical =
732 CanonTemplateTemplateParms.lookup(ID, Token);
733 if (Canonical)
734 return Canonical->getParam();
735
736 // Build a canonical template parameter list.
737 TemplateParameterList *Params = TTP->getTemplateParameters();
738 SmallVector<NamedDecl *, 4> CanonParams;
739 CanonParams.reserve(N: Params->size());
740 for (TemplateParameterList::const_iterator P = Params->begin(),
741 PEnd = Params->end();
742 P != PEnd; ++P) {
743 // Note that, per C++20 [temp.over.link]/6, when determining whether
744 // template-parameters are equivalent, constraints are ignored.
745 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Val: *P)) {
746 TemplateTypeParmDecl *NewTTP = TemplateTypeParmDecl::Create(
747 C: *this, DC: getTranslationUnitDecl(), KeyLoc: SourceLocation(), NameLoc: SourceLocation(),
748 D: TTP->getDepth(), P: TTP->getIndex(), Id: nullptr, Typename: false,
749 ParameterPack: TTP->isParameterPack(), /*HasTypeConstraint=*/false,
750 NumExpanded: TTP->getNumExpansionParameters());
751 CanonParams.push_back(Elt: NewTTP);
752 } else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: *P)) {
753 QualType T = getUnconstrainedType(T: getCanonicalType(T: NTTP->getType()));
754 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
755 NonTypeTemplateParmDecl *Param;
756 if (NTTP->isExpandedParameterPack()) {
757 SmallVector<QualType, 2> ExpandedTypes;
758 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
759 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
760 ExpandedTypes.push_back(Elt: getCanonicalType(T: NTTP->getExpansionType(I)));
761 ExpandedTInfos.push_back(
762 Elt: getTrivialTypeSourceInfo(T: ExpandedTypes.back()));
763 }
764
765 Param = NonTypeTemplateParmDecl::Create(C: *this, DC: getTranslationUnitDecl(),
766 StartLoc: SourceLocation(),
767 IdLoc: SourceLocation(),
768 D: NTTP->getDepth(),
769 P: NTTP->getPosition(), Id: nullptr,
770 T,
771 TInfo,
772 ExpandedTypes,
773 ExpandedTInfos);
774 } else {
775 Param = NonTypeTemplateParmDecl::Create(C: *this, DC: getTranslationUnitDecl(),
776 StartLoc: SourceLocation(),
777 IdLoc: SourceLocation(),
778 D: NTTP->getDepth(),
779 P: NTTP->getPosition(), Id: nullptr,
780 T,
781 ParameterPack: NTTP->isParameterPack(),
782 TInfo);
783 }
784 CanonParams.push_back(Elt: Param);
785 } else
786 CanonParams.push_back(Elt: getCanonicalTemplateTemplateParmDecl(
787 TTP: cast<TemplateTemplateParmDecl>(Val: *P)));
788 }
789
790 TemplateTemplateParmDecl *CanonTTP = TemplateTemplateParmDecl::Create(
791 C: *this, DC: getTranslationUnitDecl(), L: SourceLocation(), D: TTP->getDepth(),
792 P: TTP->getPosition(), ParameterPack: TTP->isParameterPack(), Id: nullptr,
793 ParameterKind: TTP->templateParameterKind(),
794 /*Typename=*/false,
795 Params: TemplateParameterList::Create(C: *this, TemplateLoc: SourceLocation(), LAngleLoc: SourceLocation(),
796 Params: CanonParams, RAngleLoc: SourceLocation(),
797 /*RequiresClause=*/nullptr));
798
799 // Get the new insert position for the node we care about.
800 Canonical = CanonTemplateTemplateParms.lookup(ID, Token);
801 assert(!Canonical && "Shouldn't be in the map!");
802 (void)Canonical;
803
804 // Create the canonical template template parameter entry.
805 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
806 CanonTemplateTemplateParms.insert(N: Canonical, Token);
807 return CanonTTP;
808}
809
810TemplateTemplateParmDecl *
811ASTContext::findCanonicalTemplateTemplateParmDeclInternal(
812 TemplateTemplateParmDecl *TTP) const {
813 llvm::FoldingSetNodeID ID;
814 CanonicalTemplateTemplateParm::Profile(ID, C: *this, Parm: TTP);
815 llvm::FoldingSetInsertToken Token;
816 CanonicalTemplateTemplateParm *Canonical =
817 CanonTemplateTemplateParms.lookup(ID, Token);
818 return Canonical ? Canonical->getParam() : nullptr;
819}
820
821TemplateTemplateParmDecl *
822ASTContext::insertCanonicalTemplateTemplateParmDeclInternal(
823 TemplateTemplateParmDecl *CanonTTP) const {
824 llvm::FoldingSetNodeID ID;
825 CanonicalTemplateTemplateParm::Profile(ID, C: *this, Parm: CanonTTP);
826 llvm::FoldingSetInsertToken Token;
827 if (auto *Existing = CanonTemplateTemplateParms.lookup(ID, Token))
828 return Existing->getParam();
829 CanonTemplateTemplateParms.insert(
830 N: new (*this) CanonicalTemplateTemplateParm(CanonTTP), Token);
831 return CanonTTP;
832}
833
834/// For the purposes of overflow pattern exclusion, does this match the
835/// while(i--) pattern?
836static bool matchesPostDecrInWhile(const UnaryOperator *UO, ASTContext &Ctx) {
837 if (UO->getOpcode() != UO_PostDec)
838 return false;
839
840 if (!UO->getType()->isUnsignedIntegerType())
841 return false;
842
843 // -fsanitize-undefined-ignore-overflow-pattern=unsigned-post-decr-while
844 if (!Ctx.getLangOpts().isOverflowPatternExcluded(
845 Kind: LangOptions::OverflowPatternExclusionKind::PostDecrInWhile))
846 return false;
847
848 // all Parents (usually just one) must be a WhileStmt
849 return llvm::all_of(
850 Range: Ctx.getParentMapContext().getParents(Node: *UO),
851 P: [](const DynTypedNode &P) { return P.get<WhileStmt>() != nullptr; });
852}
853
854bool ASTContext::isUnaryOverflowPatternExcluded(const UnaryOperator *UO) {
855 // -fsanitize-undefined-ignore-overflow-pattern=negated-unsigned-const
856 // ... like -1UL;
857 if (UO->getOpcode() == UO_Minus &&
858 getLangOpts().isOverflowPatternExcluded(
859 Kind: LangOptions::OverflowPatternExclusionKind::NegUnsignedConst) &&
860 UO->isIntegerConstantExpr(Ctx: *this)) {
861 return true;
862 }
863
864 if (matchesPostDecrInWhile(UO, Ctx&: *this))
865 return true;
866
867 return false;
868}
869
870/// Check if a type can have its sanitizer instrumentation elided based on its
871/// presence within an ignorelist.
872bool ASTContext::isTypeIgnoredBySanitizer(const SanitizerMask &Mask,
873 const QualType &Ty) const {
874 std::string TyName = Ty.getUnqualifiedType().getAsString(Policy: getPrintingPolicy());
875 return NoSanitizeL->containsType(Mask, MangledTypeName: TyName);
876}
877
878TargetCXXABI::Kind ASTContext::getCXXABIKind() const {
879 auto Kind = getTargetInfo().getCXXABI().getKind();
880 return getLangOpts().CXXABI.value_or(u&: Kind);
881}
882
883CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
884 if (!LangOpts.CPlusPlus) return nullptr;
885
886 switch (getCXXABIKind()) {
887 case TargetCXXABI::AppleARM64:
888 case TargetCXXABI::Fuchsia:
889 case TargetCXXABI::GenericARM: // Same as Itanium at this level
890 case TargetCXXABI::iOS:
891 case TargetCXXABI::WatchOS:
892 case TargetCXXABI::GenericAArch64:
893 case TargetCXXABI::GenericMIPS:
894 case TargetCXXABI::GenericItanium:
895 case TargetCXXABI::WebAssembly:
896 case TargetCXXABI::XL:
897 return CreateItaniumCXXABI(Ctx&: *this);
898 case TargetCXXABI::Microsoft:
899 return CreateMicrosoftCXXABI(Ctx&: *this);
900 }
901 llvm_unreachable("Invalid CXXABI type!");
902}
903
904interp::Context &ASTContext::getInterpContext() const {
905 if (!InterpContext) {
906 InterpContext.reset(p: new interp::Context(const_cast<ASTContext &>(*this)));
907 }
908 return *InterpContext;
909}
910
911static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
912 const LangOptions &LangOpts) {
913 switch (LangOpts.getAddressSpaceMapMangling()) {
914 case LangOptions::ASMM_Target:
915 return TI.useAddressSpaceMapMangling();
916 case LangOptions::ASMM_On:
917 return true;
918 case LangOptions::ASMM_Off:
919 return false;
920 }
921 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
922}
923
924ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
925 IdentifierTable &idents, SelectorTable &sels,
926 Builtin::Context &builtins, TranslationUnitKind TUKind)
927 : ConstantArrayTypes(this_(), ConstantArrayTypesLog2InitSize),
928 DependentSizedArrayTypes(this_()), DependentSizedExtVectorTypes(this_()),
929 DependentAddressSpaceTypes(this_()), DependentVectorTypes(this_()),
930 DependentSizedMatrixTypes(this_()),
931 FunctionProtoTypes(this_(), FunctionProtoTypesLog2InitSize),
932 DependentTypeOfExprTypes(this_()), DependentDecltypeTypes(this_()),
933 DependentPackIndexingTypes(this_()), TemplateSpecializationTypes(this_()),
934 AttributedTypes(this_()), DependentBitIntTypes(this_()),
935 HLSLAttributedResourceTypes(this_()),
936 SubstTemplateTemplateParmPacks(this_()), DeducedTemplates(this_()),
937 PackIndexingTemplates(this_()), ArrayParameterTypes(this_()),
938 CanonTemplateTemplateParms(this_()), SourceMgr(SM), LangOpts(LOpts),
939 NoSanitizeL(new NoSanitizeList(LangOpts.NoSanitizeFiles, SM)),
940 XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles,
941 LangOpts.XRayNeverInstrumentFiles,
942 LangOpts.XRayAttrListFiles, SM)),
943 ProfList(new ProfileList(LangOpts.ProfileListFiles, SM)),
944 PrintingPolicy(LOpts), ParentMapCtx(new ParentMapContext(*this)),
945 Idents(idents), Selectors(sels), BuiltinInfo(builtins), TUKind(TUKind),
946 DeclarationNames(*this), Comments(SM),
947 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
948 CompCategories(this_()), LastSDM(nullptr, 0) {
949 addTranslationUnitDecl();
950}
951
952void ASTContext::cleanup() {
953 // Release the DenseMaps associated with DeclContext objects.
954 // FIXME: Is this the ideal solution?
955 ReleaseDeclContextMaps();
956
957 // Call all of the deallocation functions on all of their targets.
958 for (auto &Pair : Deallocations)
959 (Pair.first)(Pair.second);
960 Deallocations.clear();
961
962 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
963 // because they can contain DenseMaps.
964 for (llvm::DenseMap<const ObjCInterfaceDecl *,
965 const ASTRecordLayout *>::iterator
966 I = ObjCLayouts.begin(),
967 E = ObjCLayouts.end();
968 I != E;)
969 // Increment in loop to prevent using deallocated memory.
970 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
971 R->Destroy(Ctx&: *this);
972 ObjCLayouts.clear();
973
974 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
975 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
976 // Increment in loop to prevent using deallocated memory.
977 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
978 R->Destroy(Ctx&: *this);
979 }
980 ASTRecordLayouts.clear();
981
982 CtorClosureDefaultArgs.clear();
983
984 for (const auto &Value : ModuleInitializers)
985 Value.second->~PerModuleInitializers();
986 ModuleInitializers.clear();
987
988 TUDecl = nullptr;
989 XRayFilter.reset();
990 NoSanitizeL.reset();
991}
992
993ASTContext::~ASTContext() { cleanup(); }
994
995void ASTContext::setTraversalScope(const std::vector<Decl *> &TopLevelDecls) {
996 TraversalScope = TopLevelDecls;
997 getParentMapContext().clear();
998}
999
1000void ASTContext::AddDeallocation(void (*Callback)(void *), void *Data) const {
1001 Deallocations.push_back(Elt: {Callback, Data});
1002}
1003
1004void
1005ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
1006 ExternalSource = std::move(Source);
1007}
1008
1009void ASTContext::PrintStats() const {
1010 llvm::errs() << "\n*** AST Context Stats:\n";
1011 llvm::errs() << " " << Types.size() << " types total.\n";
1012
1013 unsigned counts[] = {
1014#define TYPE(Name, Parent) 0,
1015#define ABSTRACT_TYPE(Name, Parent)
1016#include "clang/AST/TypeNodes.inc"
1017 0 // Extra
1018 };
1019
1020 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
1021 Type *T = Types[i];
1022 counts[(unsigned)T->getTypeClass()]++;
1023 }
1024
1025 unsigned Idx = 0;
1026 unsigned TotalBytes = 0;
1027#define TYPE(Name, Parent) \
1028 if (counts[Idx]) \
1029 llvm::errs() << " " << counts[Idx] << " " << #Name \
1030 << " types, " << sizeof(Name##Type) << " each " \
1031 << "(" << counts[Idx] * sizeof(Name##Type) \
1032 << " bytes)\n"; \
1033 TotalBytes += counts[Idx] * sizeof(Name##Type); \
1034 ++Idx;
1035#define ABSTRACT_TYPE(Name, Parent)
1036#include "clang/AST/TypeNodes.inc"
1037
1038 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
1039
1040 // Implicit special member functions.
1041 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
1042 << NumImplicitDefaultConstructors
1043 << " implicit default constructors created\n";
1044 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
1045 << NumImplicitCopyConstructors
1046 << " implicit copy constructors created\n";
1047 if (getLangOpts().CPlusPlus)
1048 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
1049 << NumImplicitMoveConstructors
1050 << " implicit move constructors created\n";
1051 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
1052 << NumImplicitCopyAssignmentOperators
1053 << " implicit copy assignment operators created\n";
1054 if (getLangOpts().CPlusPlus)
1055 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
1056 << NumImplicitMoveAssignmentOperators
1057 << " implicit move assignment operators created\n";
1058 llvm::errs() << NumImplicitDestructorsDeclared << "/"
1059 << NumImplicitDestructors
1060 << " implicit destructors created\n";
1061
1062 if (ExternalSource) {
1063 llvm::errs() << "\n";
1064 ExternalSource->PrintStats();
1065 }
1066
1067 BumpAlloc.PrintStats();
1068}
1069
1070void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
1071 bool NotifyListeners) {
1072 if (NotifyListeners)
1073 if (auto *Listener = getASTMutationListener();
1074 Listener && !ND->isUnconditionallyVisible())
1075 Listener->RedefinedHiddenDefinition(D: ND, M);
1076
1077 MergedDefModules[cast<NamedDecl>(Val: ND->getCanonicalDecl())].push_back(NewVal: M);
1078}
1079
1080void ASTContext::deduplicateMergedDefinitionsFor(NamedDecl *ND) {
1081 auto It = MergedDefModules.find(Val: cast<NamedDecl>(Val: ND->getCanonicalDecl()));
1082 if (It == MergedDefModules.end())
1083 return;
1084
1085 auto &Merged = It->second;
1086 llvm::DenseSet<Module*> Found;
1087 for (Module *&M : Merged)
1088 if (!Found.insert(V: M).second)
1089 M = nullptr;
1090 llvm::erase(C&: Merged, V: nullptr);
1091}
1092
1093ArrayRef<Module *>
1094ASTContext::getModulesWithMergedDefinition(const NamedDecl *Def) {
1095 auto MergedIt =
1096 MergedDefModules.find(Val: cast<NamedDecl>(Val: Def->getCanonicalDecl()));
1097 if (MergedIt == MergedDefModules.end())
1098 return {};
1099 return MergedIt->second;
1100}
1101
1102void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
1103 if (LazyInitializers.empty())
1104 return;
1105
1106 auto *Source = Ctx.getExternalSource();
1107 assert(Source && "lazy initializers but no external source");
1108
1109 auto LazyInits = std::move(LazyInitializers);
1110 LazyInitializers.clear();
1111
1112 for (auto ID : LazyInits)
1113 Initializers.push_back(Elt: Source->GetExternalDecl(ID));
1114
1115 assert(LazyInitializers.empty() &&
1116 "GetExternalDecl for lazy module initializer added more inits");
1117}
1118
1119void ASTContext::addModuleInitializer(Module *M, Decl *D) {
1120 // One special case: if we add a module initializer that imports another
1121 // module, and that module's only initializer is an ImportDecl, simplify.
1122 if (const auto *ID = dyn_cast<ImportDecl>(Val: D)) {
1123 auto It = ModuleInitializers.find(Val: ID->getImportedModule());
1124
1125 // Maybe the ImportDecl does nothing at all. (Common case.)
1126 if (It == ModuleInitializers.end())
1127 return;
1128
1129 // Maybe the ImportDecl only imports another ImportDecl.
1130 auto &Imported = *It->second;
1131 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
1132 Imported.resolve(Ctx&: *this);
1133 auto *OnlyDecl = Imported.Initializers.front();
1134 if (isa<ImportDecl>(Val: OnlyDecl))
1135 D = OnlyDecl;
1136 }
1137 }
1138
1139 auto *&Inits = ModuleInitializers[M];
1140 if (!Inits)
1141 Inits = new (*this) PerModuleInitializers;
1142 Inits->Initializers.push_back(Elt: D);
1143}
1144
1145void ASTContext::addLazyModuleInitializers(Module *M,
1146 ArrayRef<GlobalDeclID> IDs) {
1147 auto *&Inits = ModuleInitializers[M];
1148 if (!Inits)
1149 Inits = new (*this) PerModuleInitializers;
1150 Inits->LazyInitializers.insert(I: Inits->LazyInitializers.end(),
1151 From: IDs.begin(), To: IDs.end());
1152}
1153
1154ArrayRef<Decl *> ASTContext::getModuleInitializers(Module *M) {
1155 auto It = ModuleInitializers.find(Val: M);
1156 if (It == ModuleInitializers.end())
1157 return {};
1158
1159 auto *Inits = It->second;
1160 Inits->resolve(Ctx&: *this);
1161 return Inits->Initializers;
1162}
1163
1164void ASTContext::setCurrentNamedModule(Module *M) {
1165 assert(M->isNamedModule());
1166 assert(!CurrentCXXNamedModule &&
1167 "We should set named module for ASTContext for only once");
1168 CurrentCXXNamedModule = M;
1169}
1170
1171bool ASTContext::isInSameModule(const Module *M1, const Module *M2) const {
1172 if (!M1 != !M2)
1173 return false;
1174
1175 /// Get the representative module for M. The representative module is the
1176 /// first module unit for a specific primary module name. So that the module
1177 /// units have the same representative module belongs to the same module.
1178 ///
1179 /// The process is helpful to reduce the expensive string operations.
1180 auto GetRepresentativeModule = [this](const Module *M) {
1181 auto Iter = SameModuleLookupSet.find(Val: M);
1182 if (Iter != SameModuleLookupSet.end())
1183 return Iter->second;
1184
1185 const Module *RepresentativeModule =
1186 PrimaryModuleNameMap.try_emplace(Key: M->getPrimaryModuleInterfaceName(), Args&: M)
1187 .first->second;
1188 SameModuleLookupSet[M] = RepresentativeModule;
1189 return RepresentativeModule;
1190 };
1191
1192 assert(M1 && "Shouldn't call `isInSameModule` if both M1 and M2 are none.");
1193 return GetRepresentativeModule(M1) == GetRepresentativeModule(M2);
1194}
1195
1196ExternCContextDecl *ASTContext::getExternCContextDecl() const {
1197 if (!ExternCContext)
1198 ExternCContext = ExternCContextDecl::Create(C: *this, TU: getTranslationUnitDecl());
1199
1200 return ExternCContext;
1201}
1202
1203BuiltinTemplateDecl *
1204ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
1205 const IdentifierInfo *II) const {
1206 auto *BuiltinTemplate =
1207 BuiltinTemplateDecl::Create(C: *this, DC: getTranslationUnitDecl(), Name: II, BTK);
1208 BuiltinTemplate->setImplicit();
1209 getTranslationUnitDecl()->addDecl(D: BuiltinTemplate);
1210
1211 return BuiltinTemplate;
1212}
1213
1214#define BuiltinTemplate(BTName) \
1215 BuiltinTemplateDecl *ASTContext::get##BTName##Decl() const { \
1216 if (!Decl##BTName) \
1217 Decl##BTName = \
1218 buildBuiltinTemplateDecl(BTK##BTName, get##BTName##Name()); \
1219 return Decl##BTName; \
1220 }
1221#include "clang/Basic/BuiltinTemplates.inc"
1222
1223RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
1224 RecordDecl::TagKind TK) const {
1225 SourceLocation Loc;
1226 RecordDecl *NewDecl;
1227 if (getLangOpts().CPlusPlus)
1228 NewDecl = CXXRecordDecl::Create(C: *this, TK, DC: getTranslationUnitDecl(), StartLoc: Loc,
1229 IdLoc: Loc, Id: &Idents.get(Name));
1230 else
1231 NewDecl = RecordDecl::Create(C: *this, TK, DC: getTranslationUnitDecl(), StartLoc: Loc, IdLoc: Loc,
1232 Id: &Idents.get(Name));
1233 NewDecl->setImplicit();
1234 NewDecl->addAttr(A: TypeVisibilityAttr::CreateImplicit(
1235 Ctx&: const_cast<ASTContext &>(*this), Visibility: TypeVisibilityAttr::Default));
1236 return NewDecl;
1237}
1238
1239TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
1240 StringRef Name) const {
1241 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
1242 TypedefDecl *NewDecl = TypedefDecl::Create(
1243 C&: const_cast<ASTContext &>(*this), DC: getTranslationUnitDecl(),
1244 StartLoc: SourceLocation(), IdLoc: SourceLocation(), Id: &Idents.get(Name), TInfo);
1245 NewDecl->setImplicit();
1246 return NewDecl;
1247}
1248
1249TypedefDecl *ASTContext::getInt128Decl() const {
1250 if (!Int128Decl)
1251 Int128Decl = buildImplicitTypedef(T: Int128Ty, Name: "__int128_t");
1252 return Int128Decl;
1253}
1254
1255TypedefDecl *ASTContext::getUInt128Decl() const {
1256 if (!UInt128Decl)
1257 UInt128Decl = buildImplicitTypedef(T: UnsignedInt128Ty, Name: "__uint128_t");
1258 return UInt128Decl;
1259}
1260
1261void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
1262 auto *Ty = new (*this, alignof(BuiltinType)) BuiltinType(K);
1263 R = CanQualType::CreateUnsafe(Other: QualType(Ty, 0));
1264 Types.push_back(Elt: Ty);
1265}
1266
1267void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
1268 const TargetInfo *AuxTarget) {
1269 assert((!this->Target || this->Target == &Target) &&
1270 "Incorrect target reinitialization");
1271 assert(VoidTy.isNull() && "Context reinitialized?");
1272
1273 this->Target = &Target;
1274 this->AuxTarget = AuxTarget;
1275
1276 ABI.reset(p: createCXXABI(T: Target));
1277 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(TI: Target, LangOpts);
1278
1279 // C99 6.2.5p19.
1280 InitBuiltinType(R&: VoidTy, K: BuiltinType::Void);
1281
1282 // C99 6.2.5p2.
1283 InitBuiltinType(R&: BoolTy, K: BuiltinType::Bool);
1284 // C99 6.2.5p3.
1285 if (LangOpts.CharIsSigned)
1286 InitBuiltinType(R&: CharTy, K: BuiltinType::Char_S);
1287 else
1288 InitBuiltinType(R&: CharTy, K: BuiltinType::Char_U);
1289 // C99 6.2.5p4.
1290 InitBuiltinType(R&: SignedCharTy, K: BuiltinType::SChar);
1291 InitBuiltinType(R&: ShortTy, K: BuiltinType::Short);
1292 InitBuiltinType(R&: IntTy, K: BuiltinType::Int);
1293 InitBuiltinType(R&: LongTy, K: BuiltinType::Long);
1294 InitBuiltinType(R&: LongLongTy, K: BuiltinType::LongLong);
1295
1296 // C99 6.2.5p6.
1297 InitBuiltinType(R&: UnsignedCharTy, K: BuiltinType::UChar);
1298 InitBuiltinType(R&: UnsignedShortTy, K: BuiltinType::UShort);
1299 InitBuiltinType(R&: UnsignedIntTy, K: BuiltinType::UInt);
1300 InitBuiltinType(R&: UnsignedLongTy, K: BuiltinType::ULong);
1301 InitBuiltinType(R&: UnsignedLongLongTy, K: BuiltinType::ULongLong);
1302
1303 // C99 6.2.5p10.
1304 InitBuiltinType(R&: FloatTy, K: BuiltinType::Float);
1305 InitBuiltinType(R&: DoubleTy, K: BuiltinType::Double);
1306 InitBuiltinType(R&: LongDoubleTy, K: BuiltinType::LongDouble);
1307
1308 // GNU extension, __float128 for IEEE quadruple precision
1309 InitBuiltinType(R&: Float128Ty, K: BuiltinType::Float128);
1310
1311 // __ibm128 for IBM extended precision
1312 InitBuiltinType(R&: Ibm128Ty, K: BuiltinType::Ibm128);
1313
1314 // C11 extension ISO/IEC TS 18661-3
1315 InitBuiltinType(R&: Float16Ty, K: BuiltinType::Float16);
1316
1317 // ISO/IEC JTC1 SC22 WG14 N1169 Extension
1318 InitBuiltinType(R&: ShortAccumTy, K: BuiltinType::ShortAccum);
1319 InitBuiltinType(R&: AccumTy, K: BuiltinType::Accum);
1320 InitBuiltinType(R&: LongAccumTy, K: BuiltinType::LongAccum);
1321 InitBuiltinType(R&: UnsignedShortAccumTy, K: BuiltinType::UShortAccum);
1322 InitBuiltinType(R&: UnsignedAccumTy, K: BuiltinType::UAccum);
1323 InitBuiltinType(R&: UnsignedLongAccumTy, K: BuiltinType::ULongAccum);
1324 InitBuiltinType(R&: ShortFractTy, K: BuiltinType::ShortFract);
1325 InitBuiltinType(R&: FractTy, K: BuiltinType::Fract);
1326 InitBuiltinType(R&: LongFractTy, K: BuiltinType::LongFract);
1327 InitBuiltinType(R&: UnsignedShortFractTy, K: BuiltinType::UShortFract);
1328 InitBuiltinType(R&: UnsignedFractTy, K: BuiltinType::UFract);
1329 InitBuiltinType(R&: UnsignedLongFractTy, K: BuiltinType::ULongFract);
1330 InitBuiltinType(R&: SatShortAccumTy, K: BuiltinType::SatShortAccum);
1331 InitBuiltinType(R&: SatAccumTy, K: BuiltinType::SatAccum);
1332 InitBuiltinType(R&: SatLongAccumTy, K: BuiltinType::SatLongAccum);
1333 InitBuiltinType(R&: SatUnsignedShortAccumTy, K: BuiltinType::SatUShortAccum);
1334 InitBuiltinType(R&: SatUnsignedAccumTy, K: BuiltinType::SatUAccum);
1335 InitBuiltinType(R&: SatUnsignedLongAccumTy, K: BuiltinType::SatULongAccum);
1336 InitBuiltinType(R&: SatShortFractTy, K: BuiltinType::SatShortFract);
1337 InitBuiltinType(R&: SatFractTy, K: BuiltinType::SatFract);
1338 InitBuiltinType(R&: SatLongFractTy, K: BuiltinType::SatLongFract);
1339 InitBuiltinType(R&: SatUnsignedShortFractTy, K: BuiltinType::SatUShortFract);
1340 InitBuiltinType(R&: SatUnsignedFractTy, K: BuiltinType::SatUFract);
1341 InitBuiltinType(R&: SatUnsignedLongFractTy, K: BuiltinType::SatULongFract);
1342
1343 // GNU extension, 128-bit integers.
1344 InitBuiltinType(R&: Int128Ty, K: BuiltinType::Int128);
1345 InitBuiltinType(R&: UnsignedInt128Ty, K: BuiltinType::UInt128);
1346
1347 // C++ 3.9.1p5
1348 if (TargetInfo::isTypeSigned(T: Target.getWCharType()))
1349 InitBuiltinType(R&: WCharTy, K: BuiltinType::WChar_S);
1350 else // -fshort-wchar makes wchar_t be unsigned.
1351 InitBuiltinType(R&: WCharTy, K: BuiltinType::WChar_U);
1352 if (LangOpts.CPlusPlus && LangOpts.WChar)
1353 WideCharTy = WCharTy;
1354 else {
1355 // C99 (or C++ using -fno-wchar).
1356 WideCharTy = getFromTargetType(Type: Target.getWCharType());
1357 }
1358
1359 WIntTy = getFromTargetType(Type: Target.getWIntType());
1360
1361 // C++20 (proposed)
1362 InitBuiltinType(R&: Char8Ty, K: BuiltinType::Char8);
1363
1364 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1365 InitBuiltinType(R&: Char16Ty, K: BuiltinType::Char16);
1366 else // C99
1367 Char16Ty = getFromTargetType(Type: Target.getChar16Type());
1368
1369 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1370 InitBuiltinType(R&: Char32Ty, K: BuiltinType::Char32);
1371 else // C99
1372 Char32Ty = getFromTargetType(Type: Target.getChar32Type());
1373
1374 // Placeholder type for type-dependent expressions whose type is
1375 // completely unknown. No code should ever check a type against
1376 // DependentTy and users should never see it; however, it is here to
1377 // help diagnose failures to properly check for type-dependent
1378 // expressions.
1379 InitBuiltinType(R&: DependentTy, K: BuiltinType::Dependent);
1380
1381 // Placeholder type for functions.
1382 InitBuiltinType(R&: OverloadTy, K: BuiltinType::Overload);
1383
1384 // Placeholder type for bound members.
1385 InitBuiltinType(R&: BoundMemberTy, K: BuiltinType::BoundMember);
1386
1387 // Placeholder type for unresolved templates.
1388 InitBuiltinType(R&: UnresolvedTemplateTy, K: BuiltinType::UnresolvedTemplate);
1389
1390 // Placeholder type for pseudo-objects.
1391 InitBuiltinType(R&: PseudoObjectTy, K: BuiltinType::PseudoObject);
1392
1393 // "any" type; useful for debugger-like clients.
1394 InitBuiltinType(R&: UnknownAnyTy, K: BuiltinType::UnknownAny);
1395
1396 // Placeholder type for unbridged ARC casts.
1397 InitBuiltinType(R&: ARCUnbridgedCastTy, K: BuiltinType::ARCUnbridgedCast);
1398
1399 // Placeholder type for builtin functions.
1400 InitBuiltinType(R&: BuiltinFnTy, K: BuiltinType::BuiltinFn);
1401
1402 // Placeholder type for OMP array sections.
1403 if (LangOpts.OpenMP) {
1404 InitBuiltinType(R&: ArraySectionTy, K: BuiltinType::ArraySection);
1405 InitBuiltinType(R&: OMPArrayShapingTy, K: BuiltinType::OMPArrayShaping);
1406 InitBuiltinType(R&: OMPIteratorTy, K: BuiltinType::OMPIterator);
1407 }
1408 // Placeholder type for OpenACC array sections, if we are ALSO in OMP mode,
1409 // don't bother, as we're just using the same type as OMP.
1410 if (LangOpts.OpenACC && !LangOpts.OpenMP) {
1411 InitBuiltinType(R&: ArraySectionTy, K: BuiltinType::ArraySection);
1412 }
1413 if (LangOpts.MatrixTypes)
1414 InitBuiltinType(R&: IncompleteMatrixIdxTy, K: BuiltinType::IncompleteMatrixIdx);
1415
1416 // Builtin types for 'id', 'Class', and 'SEL'.
1417 InitBuiltinType(R&: ObjCBuiltinIdTy, K: BuiltinType::ObjCId);
1418 InitBuiltinType(R&: ObjCBuiltinClassTy, K: BuiltinType::ObjCClass);
1419 InitBuiltinType(R&: ObjCBuiltinSelTy, K: BuiltinType::ObjCSel);
1420
1421 if (LangOpts.OpenCL) {
1422#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1423 InitBuiltinType(SingletonId, BuiltinType::Id);
1424#include "clang/Basic/OpenCLImageTypes.def"
1425
1426 InitBuiltinType(R&: OCLSamplerTy, K: BuiltinType::OCLSampler);
1427 InitBuiltinType(R&: OCLEventTy, K: BuiltinType::OCLEvent);
1428 InitBuiltinType(R&: OCLClkEventTy, K: BuiltinType::OCLClkEvent);
1429 InitBuiltinType(R&: OCLQueueTy, K: BuiltinType::OCLQueue);
1430 InitBuiltinType(R&: OCLReserveIDTy, K: BuiltinType::OCLReserveID);
1431
1432#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1433 InitBuiltinType(Id##Ty, BuiltinType::Id);
1434#include "clang/Basic/OpenCLExtensionTypes.def"
1435 }
1436
1437 if (LangOpts.HLSL) {
1438#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
1439 InitBuiltinType(SingletonId, BuiltinType::Id);
1440#include "clang/Basic/HLSLIntangibleTypes.def"
1441
1442#define HLSL_PACKED_TYPE(Name, Id, SingletonId) \
1443 InitBuiltinType(SingletonId, BuiltinType::Id);
1444#include "clang/Basic/HLSLPackedTypes.def"
1445 }
1446
1447 if (Target.hasAArch64ACLETypes() ||
1448 (AuxTarget && AuxTarget->hasAArch64ACLETypes())) {
1449#define SVE_TYPE(Name, Id, SingletonId) \
1450 InitBuiltinType(SingletonId, BuiltinType::Id);
1451#include "clang/Basic/AArch64ACLETypes.def"
1452 }
1453
1454 if (Target.getTriple().isPPC64()) {
1455#define PPC_VECTOR_MMA_TYPE(Name, Id, Size) \
1456 InitBuiltinType(Id##Ty, BuiltinType::Id);
1457#include "clang/Basic/PPCTypes.def"
1458#define PPC_VECTOR_VSX_TYPE(Name, Id, Size) \
1459 InitBuiltinType(Id##Ty, BuiltinType::Id);
1460#include "clang/Basic/PPCTypes.def"
1461 }
1462
1463 if (Target.hasRISCVVTypes()) {
1464#define RVV_TYPE(Name, Id, SingletonId) \
1465 InitBuiltinType(SingletonId, BuiltinType::Id);
1466#include "clang/Basic/RISCVVTypes.def"
1467 }
1468
1469 if (Target.getTriple().isWasm() && Target.hasFeature(Feature: "reference-types")) {
1470#define WASM_TYPE(Name, Id, SingletonId) \
1471 InitBuiltinType(SingletonId, BuiltinType::Id);
1472#include "clang/Basic/WebAssemblyReferenceTypes.def"
1473 }
1474
1475 if (Target.hasAMDGPUTypes() || (AuxTarget && (AuxTarget->hasAMDGPUTypes()))) {
1476#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) \
1477 InitBuiltinType(SingletonId, BuiltinType::Id);
1478#include "clang/Basic/AMDGPUTypes.def"
1479 }
1480
1481 if (Target.getTriple().isSPIRV() ||
1482 (AuxTarget && AuxTarget->getTriple().isSPIRV())) {
1483#define SPIRV_TYPE(Name, Id, SingletonId) \
1484 InitBuiltinType(SingletonId, BuiltinType::Id);
1485#include "clang/Basic/SPIRVTypes.def"
1486 }
1487
1488 // Builtin type for __objc_yes and __objc_no
1489 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1490 SignedCharTy : BoolTy);
1491
1492 ObjCConstantStringType = QualType();
1493
1494 ObjCSuperType = QualType();
1495
1496 // void * type
1497 if (LangOpts.OpenCLGenericAddressSpace) {
1498 auto Q = VoidTy.getQualifiers();
1499 Q.setAddressSpace(LangAS::opencl_generic);
1500 VoidPtrTy = getPointerType(T: getCanonicalType(
1501 T: getQualifiedType(T: VoidTy.getUnqualifiedType(), Qs: Q)));
1502 } else {
1503 VoidPtrTy = getPointerType(T: VoidTy);
1504 }
1505
1506 // nullptr type (C++0x 2.14.7)
1507 InitBuiltinType(R&: NullPtrTy, K: BuiltinType::NullPtr);
1508
1509 // std::meta::info type (C++26 21.4.1)
1510 InitBuiltinType(R&: MetaInfoTy, K: BuiltinType::MetaInfo);
1511
1512 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1513 InitBuiltinType(R&: HalfTy, K: BuiltinType::Half);
1514
1515 InitBuiltinType(R&: BFloat16Ty, K: BuiltinType::BFloat16);
1516
1517 // Builtin type used to help define __builtin_va_list.
1518 VaListTagDecl = nullptr;
1519
1520 // MSVC predeclares struct _GUID, and we need it to create MSGuidDecls.
1521 if (LangOpts.MicrosoftExt || LangOpts.Borland) {
1522 MSGuidTagDecl = buildImplicitRecord(Name: "_GUID");
1523 getTranslationUnitDecl()->addDecl(D: MSGuidTagDecl);
1524 }
1525}
1526
1527DiagnosticsEngine &ASTContext::getDiagnostics() const {
1528 return SourceMgr.getDiagnostics();
1529}
1530
1531AttrVec *ASTContext::allocateAttrVec() {
1532 return new (DeclAttrAllocator.Allocate()) AttrVec;
1533}
1534
1535ArrayRef<CXXDefaultArgExpr *>
1536ASTContext::getCtorClosureDefaultArgs(const CXXConstructorDecl *CD) {
1537 return CtorClosureDefaultArgs.lookup(Val: CD);
1538}
1539
1540void ASTContext::setCtorClosureDefaultArgs(const CXXConstructorDecl *CD,
1541 ArrayRef<CXXDefaultArgExpr *> Args) {
1542 assert(!CtorClosureDefaultArgs.contains(CD));
1543 CtorClosureDefaultArgs[CD] = Args;
1544}
1545
1546ArrayRef<ExplicitInstantiationDecl *>
1547ASTContext::getExplicitInstantiationDecls(const NamedDecl *Spec) const {
1548 auto It =
1549 ExplicitInstantiations.find(Val: cast<NamedDecl>(Val: Spec->getCanonicalDecl()));
1550 if (It != ExplicitInstantiations.end())
1551 return It->second;
1552 return {};
1553}
1554
1555void ASTContext::addExplicitInstantiationDecl(const NamedDecl *Spec,
1556 ExplicitInstantiationDecl *EID) {
1557 ExplicitInstantiations[cast<NamedDecl>(Val: Spec->getCanonicalDecl())].push_back(
1558 NewVal: EID);
1559}
1560
1561ASTContext::TemplateOrSpecializationInfo
1562ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1563 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1564 TemplateOrInstantiation.find(Val: Var);
1565 if (Pos == TemplateOrInstantiation.end())
1566 return {};
1567
1568 return Pos->second;
1569}
1570
1571void
1572ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
1573 TemplateSpecializationKind TSK,
1574 SourceLocation PointOfInstantiation) {
1575 assert(Inst->isStaticDataMember() && "Not a static data member");
1576 assert(Tmpl->isStaticDataMember() && "Not a static data member");
1577 setTemplateOrSpecializationInfo(Inst, TSI: new (*this) MemberSpecializationInfo(
1578 Tmpl, TSK, PointOfInstantiation));
1579}
1580
1581void
1582ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1583 TemplateOrSpecializationInfo TSI) {
1584 assert(!TemplateOrInstantiation[Inst] &&
1585 "Already noted what the variable was instantiated from");
1586 TemplateOrInstantiation[Inst] = TSI;
1587}
1588
1589NamedDecl *
1590ASTContext::getInstantiatedFromUsingDecl(NamedDecl *UUD) {
1591 return InstantiatedFromUsingDecl.lookup(Val: UUD);
1592}
1593
1594void
1595ASTContext::setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern) {
1596 assert((isa<UsingDecl>(Pattern) ||
1597 isa<UnresolvedUsingValueDecl>(Pattern) ||
1598 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1599 "pattern decl is not a using decl");
1600 assert((isa<UsingDecl>(Inst) ||
1601 isa<UnresolvedUsingValueDecl>(Inst) ||
1602 isa<UnresolvedUsingTypenameDecl>(Inst)) &&
1603 "instantiation did not produce a using decl");
1604 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1605 InstantiatedFromUsingDecl[Inst] = Pattern;
1606}
1607
1608UsingEnumDecl *
1609ASTContext::getInstantiatedFromUsingEnumDecl(UsingEnumDecl *UUD) {
1610 return InstantiatedFromUsingEnumDecl.lookup(Val: UUD);
1611}
1612
1613void ASTContext::setInstantiatedFromUsingEnumDecl(UsingEnumDecl *Inst,
1614 UsingEnumDecl *Pattern) {
1615 assert(!InstantiatedFromUsingEnumDecl[Inst] && "pattern already exists");
1616 InstantiatedFromUsingEnumDecl[Inst] = Pattern;
1617}
1618
1619UsingShadowDecl *
1620ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1621 return InstantiatedFromUsingShadowDecl.lookup(Val: Inst);
1622}
1623
1624void
1625ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1626 UsingShadowDecl *Pattern) {
1627 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1628 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
1629}
1630
1631FieldDecl *
1632ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) const {
1633 return InstantiatedFromUnnamedFieldDecl.lookup(Val: Field);
1634}
1635
1636void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1637 FieldDecl *Tmpl) {
1638 assert((!Inst->getDeclName() || Inst->isPlaceholderVar(getLangOpts())) &&
1639 "Instantiated field decl is not unnamed");
1640 assert((!Inst->getDeclName() || Inst->isPlaceholderVar(getLangOpts())) &&
1641 "Template field decl is not unnamed");
1642 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1643 "Already noted what unnamed field was instantiated from");
1644
1645 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1646}
1647
1648ASTContext::overridden_cxx_method_iterator
1649ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1650 return overridden_methods(Method).begin();
1651}
1652
1653ASTContext::overridden_cxx_method_iterator
1654ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1655 return overridden_methods(Method).end();
1656}
1657
1658unsigned
1659ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1660 auto Range = overridden_methods(Method);
1661 return Range.end() - Range.begin();
1662}
1663
1664ASTContext::overridden_method_range
1665ASTContext::overridden_methods(const CXXMethodDecl *Method) const {
1666 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1667 OverriddenMethods.find(Val: Method->getCanonicalDecl());
1668 if (Pos == OverriddenMethods.end())
1669 return overridden_method_range(nullptr, nullptr);
1670 return overridden_method_range(Pos->second.begin(), Pos->second.end());
1671}
1672
1673void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1674 const CXXMethodDecl *Overridden) {
1675 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
1676 OverriddenMethods[Method].push_back(NewVal: Overridden);
1677}
1678
1679void ASTContext::getOverriddenMethods(
1680 const NamedDecl *D,
1681 SmallVectorImpl<const NamedDecl *> &Overridden) const {
1682 assert(D);
1683
1684 if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(Val: D)) {
1685 Overridden.append(in_start: overridden_methods_begin(Method: CXXMethod),
1686 in_end: overridden_methods_end(Method: CXXMethod));
1687 return;
1688 }
1689
1690 const auto *Method = dyn_cast<ObjCMethodDecl>(Val: D);
1691 if (!Method)
1692 return;
1693
1694 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1695 Method->getOverriddenMethods(Overridden&: OverDecls);
1696 Overridden.append(in_start: OverDecls.begin(), in_end: OverDecls.end());
1697}
1698
1699std::optional<ASTContext::CXXRecordDeclRelocationInfo>
1700ASTContext::getRelocationInfoForCXXRecord(const CXXRecordDecl *RD) const {
1701 assert(RD);
1702 CXXRecordDecl *D = RD->getDefinition();
1703 auto it = RelocatableClasses.find(Val: D);
1704 if (it != RelocatableClasses.end())
1705 return it->getSecond();
1706 return std::nullopt;
1707}
1708
1709void ASTContext::setRelocationInfoForCXXRecord(
1710 const CXXRecordDecl *RD, CXXRecordDeclRelocationInfo Info) {
1711 assert(RD);
1712 CXXRecordDecl *D = RD->getDefinition();
1713 assert(RelocatableClasses.find(D) == RelocatableClasses.end());
1714 RelocatableClasses.insert(KV: {D, Info});
1715}
1716
1717static bool primaryBaseHaseAddressDiscriminatedVTableAuthentication(
1718 const ASTContext &Context, const CXXRecordDecl *Class) {
1719 if (!Class->isPolymorphic())
1720 return false;
1721 const CXXRecordDecl *BaseType = Context.baseForVTableAuthentication(ThisClass: Class);
1722 using AuthAttr = VTablePointerAuthenticationAttr;
1723 const AuthAttr *ExplicitAuth = BaseType->getAttr<AuthAttr>();
1724 if (!ExplicitAuth)
1725 return Context.getLangOpts().PointerAuthVTPtrAddressDiscrimination;
1726 AuthAttr::AddressDiscriminationMode AddressDiscrimination =
1727 ExplicitAuth->getAddressDiscrimination();
1728 if (AddressDiscrimination == AuthAttr::DefaultAddressDiscrimination)
1729 return Context.getLangOpts().PointerAuthVTPtrAddressDiscrimination;
1730 return AddressDiscrimination == AuthAttr::AddressDiscrimination;
1731}
1732
1733ASTContext::PointerAuthContent
1734ASTContext::findPointerAuthContent(QualType T) const {
1735 assert(isPointerAuthenticationAvailable());
1736
1737 T = T.getCanonicalType();
1738 if (T->isDependentType())
1739 return PointerAuthContent::None;
1740
1741 if (T.hasAddressDiscriminatedPointerAuth())
1742 return PointerAuthContent::AddressDiscriminatedData;
1743 const RecordDecl *RD = T->getAsRecordDecl();
1744 if (!RD)
1745 return PointerAuthContent::None;
1746
1747 if (RD->isInvalidDecl())
1748 return PointerAuthContent::None;
1749
1750 if (auto Existing = RecordContainsAddressDiscriminatedPointerAuth.find(Val: RD);
1751 Existing != RecordContainsAddressDiscriminatedPointerAuth.end())
1752 return Existing->second;
1753
1754 PointerAuthContent Result = PointerAuthContent::None;
1755
1756 auto SaveResultAndReturn = [&]() -> PointerAuthContent {
1757 auto [ResultIter, DidAdd] =
1758 RecordContainsAddressDiscriminatedPointerAuth.try_emplace(Key: RD, Args&: Result);
1759 (void)ResultIter;
1760 (void)DidAdd;
1761 assert(DidAdd);
1762 return Result;
1763 };
1764 auto ShouldContinueAfterUpdate = [&](PointerAuthContent NewResult) {
1765 static_assert(PointerAuthContent::None <
1766 PointerAuthContent::AddressDiscriminatedVTable);
1767 static_assert(PointerAuthContent::AddressDiscriminatedVTable <
1768 PointerAuthContent::AddressDiscriminatedData);
1769 if (NewResult > Result)
1770 Result = NewResult;
1771 return Result != PointerAuthContent::AddressDiscriminatedData;
1772 };
1773 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(Val: RD)) {
1774 if (primaryBaseHaseAddressDiscriminatedVTableAuthentication(Context: *this, Class: CXXRD) &&
1775 !ShouldContinueAfterUpdate(
1776 PointerAuthContent::AddressDiscriminatedVTable))
1777 return SaveResultAndReturn();
1778 for (auto Base : CXXRD->bases()) {
1779 if (!ShouldContinueAfterUpdate(findPointerAuthContent(T: Base.getType())))
1780 return SaveResultAndReturn();
1781 }
1782 }
1783 for (auto *FieldDecl : RD->fields()) {
1784 if (!ShouldContinueAfterUpdate(
1785 findPointerAuthContent(T: FieldDecl->getType())))
1786 return SaveResultAndReturn();
1787 }
1788 return SaveResultAndReturn();
1789}
1790
1791void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1792 assert(!Import->getNextLocalImport() &&
1793 "Import declaration already in the chain");
1794 assert(!Import->isFromASTFile() && "Non-local import declaration");
1795 if (!FirstLocalImport) {
1796 FirstLocalImport = Import;
1797 LastLocalImport = Import;
1798 return;
1799 }
1800
1801 LastLocalImport->setNextLocalImport(Import);
1802 LastLocalImport = Import;
1803}
1804
1805//===----------------------------------------------------------------------===//
1806// Type Sizing and Analysis
1807//===----------------------------------------------------------------------===//
1808
1809/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1810/// scalar floating point type.
1811const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
1812 switch (T->castAs<BuiltinType>()->getKind()) {
1813 default:
1814 llvm_unreachable("Not a floating point type!");
1815 case BuiltinType::BFloat16:
1816 return Target->getBFloat16Format();
1817 case BuiltinType::Float16:
1818 return Target->getHalfFormat();
1819 case BuiltinType::Half:
1820 return Target->getHalfFormat();
1821 case BuiltinType::Float: return Target->getFloatFormat();
1822 case BuiltinType::Double: return Target->getDoubleFormat();
1823 case BuiltinType::Ibm128:
1824 return Target->getIbm128Format();
1825 case BuiltinType::LongDouble:
1826 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice)
1827 return AuxTarget->getLongDoubleFormat();
1828 return Target->getLongDoubleFormat();
1829 case BuiltinType::Float128:
1830 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice)
1831 return AuxTarget->getFloat128Format();
1832 return Target->getFloat128Format();
1833 }
1834}
1835
1836CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
1837 unsigned Align = Target->getCharWidth();
1838
1839 const unsigned AlignFromAttr = D->getMaxAlignment();
1840 if (AlignFromAttr)
1841 Align = AlignFromAttr;
1842
1843 // __attribute__((aligned)) can increase or decrease alignment
1844 // *except* on a struct or struct member, where it only increases
1845 // alignment unless 'packed' is also specified.
1846 //
1847 // It is an error for alignas to decrease alignment, so we can
1848 // ignore that possibility; Sema should diagnose it.
1849 bool UseAlignAttrOnly;
1850 if (const FieldDecl *FD = dyn_cast<FieldDecl>(Val: D))
1851 UseAlignAttrOnly =
1852 FD->hasAttr<PackedAttr>() || FD->getParent()->hasAttr<PackedAttr>();
1853 else
1854 UseAlignAttrOnly = AlignFromAttr != 0;
1855 // If we're using the align attribute only, just ignore everything
1856 // else about the declaration and its type.
1857 if (UseAlignAttrOnly) {
1858 // do nothing
1859 } else if (const auto *VD = dyn_cast<ValueDecl>(Val: D)) {
1860 QualType T = VD->getType();
1861 if (const auto *RT = T->getAs<ReferenceType>()) {
1862 if (ForAlignof)
1863 T = RT->getPointeeType();
1864 else
1865 T = getPointerType(T: RT->getPointeeType());
1866 }
1867 QualType BaseT = getBaseElementType(QT: T);
1868 if (T->isFunctionType())
1869 Align = getTypeInfoImpl(T: T.getTypePtr()).Align;
1870 else if (!BaseT->isIncompleteType()) {
1871 // Adjust alignments of declarations with array type by the
1872 // large-array alignment on the target.
1873 if (const ArrayType *arrayType = getAsArrayType(T)) {
1874 unsigned MinWidth = Target->getLargeArrayMinWidth();
1875 if (!ForAlignof && MinWidth) {
1876 if (isa<VariableArrayType>(Val: arrayType))
1877 Align = std::max(a: Align, b: Target->getLargeArrayAlign());
1878 else if (isa<ConstantArrayType>(Val: arrayType) &&
1879 MinWidth <= getTypeSize(T: cast<ConstantArrayType>(Val: arrayType)))
1880 Align = std::max(a: Align, b: Target->getLargeArrayAlign());
1881 }
1882 }
1883 Align = std::max(a: Align, b: getPreferredTypeAlign(T: T.getTypePtr()));
1884 if (BaseT.getQualifiers().hasUnaligned())
1885 Align = Target->getCharWidth();
1886 }
1887
1888 // Ensure minimum alignment for global variables.
1889 if (const auto *VD = dyn_cast<VarDecl>(Val: D))
1890 if (VD->hasGlobalStorage() && !ForAlignof) {
1891 uint64_t TypeSize =
1892 !BaseT->isIncompleteType() ? getTypeSize(T: T.getTypePtr()) : 0;
1893 Align = std::max(a: Align, b: getMinGlobalAlignOfVar(Size: TypeSize, VD));
1894 }
1895
1896 // Fields can be subject to extra alignment constraints, like if
1897 // the field is packed, the struct is packed, or the struct has a
1898 // a max-field-alignment constraint (#pragma pack). So calculate
1899 // the actual alignment of the field within the struct, and then
1900 // (as we're expected to) constrain that by the alignment of the type.
1901 if (const auto *Field = dyn_cast<FieldDecl>(Val: VD)) {
1902 const RecordDecl *Parent = Field->getParent();
1903 // We can only produce a sensible answer if the record is valid.
1904 if (!Parent->isInvalidDecl()) {
1905 const ASTRecordLayout &Layout = getASTRecordLayout(D: Parent);
1906
1907 // Start with the record's overall alignment.
1908 unsigned FieldAlign = toBits(CharSize: Layout.getAlignment());
1909
1910 // Use the GCD of that and the offset within the record.
1911 uint64_t Offset = Layout.getFieldOffset(FieldNo: Field->getFieldIndex());
1912 if (Offset > 0) {
1913 // Alignment is always a power of 2, so the GCD will be a power of 2,
1914 // which means we get to do this crazy thing instead of Euclid's.
1915 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1916 if (LowBitOfOffset < FieldAlign)
1917 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1918 }
1919
1920 Align = std::min(a: Align, b: FieldAlign);
1921 }
1922 }
1923 }
1924
1925 // Some targets have hard limitation on the maximum requestable alignment in
1926 // aligned attribute for static variables.
1927 const unsigned MaxAlignedAttr = getTargetInfo().getMaxAlignedAttribute();
1928 const auto *VD = dyn_cast<VarDecl>(Val: D);
1929 if (MaxAlignedAttr && VD && VD->getStorageClass() == SC_Static)
1930 Align = std::min(a: Align, b: MaxAlignedAttr);
1931
1932 return toCharUnitsFromBits(BitSize: Align);
1933}
1934
1935CharUnits ASTContext::getExnObjectAlignment() const {
1936 return toCharUnitsFromBits(BitSize: Target->getExnObjectAlignment());
1937}
1938
1939// getTypeInfoDataSizeInChars - Return the size of a type, in
1940// chars. If the type is a record, its data size is returned. This is
1941// the size of the memcpy that's performed when assigning this type
1942// using a trivial copy/move assignment operator.
1943TypeInfoChars ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1944 TypeInfoChars Info = getTypeInfoInChars(T);
1945
1946 // In C++, objects can sometimes be allocated into the tail padding
1947 // of a base-class subobject. We decide whether that's possible
1948 // during class layout, so here we can just trust the layout results.
1949 if (getLangOpts().CPlusPlus) {
1950 if (const auto *RD = T->getAsCXXRecordDecl(); RD && !RD->isInvalidDecl()) {
1951 const ASTRecordLayout &layout = getASTRecordLayout(D: RD);
1952 Info.Width = layout.getDataSize();
1953 }
1954 }
1955
1956 return Info;
1957}
1958
1959/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1960/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1961TypeInfoChars
1962static getConstantArrayInfoInChars(const ASTContext &Context,
1963 const ConstantArrayType *CAT) {
1964 TypeInfoChars EltInfo = Context.getTypeInfoInChars(T: CAT->getElementType());
1965 uint64_t Size = CAT->getZExtSize();
1966 assert((Size == 0 || static_cast<uint64_t>(EltInfo.Width.getQuantity()) <=
1967 (uint64_t)(-1)/Size) &&
1968 "Overflow in array type char size evaluation");
1969 uint64_t Width = EltInfo.Width.getQuantity() * Size;
1970 unsigned Align = EltInfo.Align.getQuantity();
1971 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1972 Context.getTargetInfo().getPointerWidth(AddrSpace: LangAS::Default) == 64)
1973 Width = llvm::alignTo(Value: Width, Align);
1974 return TypeInfoChars(CharUnits::fromQuantity(Quantity: Width),
1975 CharUnits::fromQuantity(Quantity: Align),
1976 EltInfo.AlignRequirement);
1977}
1978
1979TypeInfoChars ASTContext::getTypeInfoInChars(const Type *T) const {
1980 if (const auto *CAT = dyn_cast<ConstantArrayType>(Val: T))
1981 return getConstantArrayInfoInChars(Context: *this, CAT);
1982 TypeInfo Info = getTypeInfo(T);
1983 return TypeInfoChars(toCharUnitsFromBits(BitSize: Info.Width),
1984 toCharUnitsFromBits(BitSize: Info.Align), Info.AlignRequirement);
1985}
1986
1987TypeInfoChars ASTContext::getTypeInfoInChars(QualType T) const {
1988 return getTypeInfoInChars(T: T.getTypePtr());
1989}
1990
1991bool ASTContext::isPromotableIntegerType(QualType T) const {
1992 // HLSL doesn't promote all small integer types to int, it
1993 // just uses the rank-based promotion rules for all types.
1994 if (getLangOpts().HLSL)
1995 return false;
1996
1997 if (const auto *BT = T->getAs<BuiltinType>())
1998 switch (BT->getKind()) {
1999 case BuiltinType::Bool:
2000 case BuiltinType::Char_S:
2001 case BuiltinType::Char_U:
2002 case BuiltinType::SChar:
2003 case BuiltinType::UChar:
2004 case BuiltinType::Short:
2005 case BuiltinType::UShort:
2006 case BuiltinType::WChar_S:
2007 case BuiltinType::WChar_U:
2008 case BuiltinType::Char8:
2009 case BuiltinType::Char16:
2010 case BuiltinType::Char32:
2011 return true;
2012 default:
2013 return false;
2014 }
2015
2016 // Enumerated types are promotable to their compatible integer types
2017 // (C99 6.3.1.1) a.k.a. its underlying type (C++ [conv.prom]p2).
2018 if (const auto *ED = T->getAsEnumDecl()) {
2019 if (T->isDependentType() || ED->getPromotionType().isNull() ||
2020 ED->isScoped())
2021 return false;
2022
2023 return true;
2024 }
2025
2026 // OverflowBehaviorTypes are promotable if their underlying type is promotable
2027 if (const auto *OBT = T->getAs<OverflowBehaviorType>()) {
2028 return isPromotableIntegerType(T: OBT->getUnderlyingType());
2029 }
2030
2031 return false;
2032}
2033
2034bool ASTContext::isAlignmentRequired(const Type *T) const {
2035 return getTypeInfo(T).isAlignRequired();
2036}
2037
2038bool ASTContext::isAlignmentRequired(QualType T) const {
2039 return isAlignmentRequired(T: T.getTypePtr());
2040}
2041
2042unsigned ASTContext::getTypeAlignIfKnown(QualType T,
2043 bool NeedsPreferredAlignment) const {
2044 // An alignment on a typedef overrides anything else.
2045 if (const auto *TT = T->getAs<TypedefType>())
2046 if (unsigned Align = TT->getDecl()->getMaxAlignment())
2047 return Align;
2048
2049 // If we have an (array of) complete type, we're done.
2050 T = getBaseElementType(QT: T);
2051 if (!T->isIncompleteType())
2052 return NeedsPreferredAlignment ? getPreferredTypeAlign(T) : getTypeAlign(T);
2053
2054 // If we had an array type, its element type might be a typedef
2055 // type with an alignment attribute.
2056 if (const auto *TT = T->getAs<TypedefType>())
2057 if (unsigned Align = TT->getDecl()->getMaxAlignment())
2058 return Align;
2059
2060 // Otherwise, see if the declaration of the type had an attribute.
2061 if (const auto *TD = T->getAsTagDecl())
2062 return TD->getMaxAlignment();
2063
2064 return 0;
2065}
2066
2067TypeInfo ASTContext::getTypeInfo(const Type *T) const {
2068 TypeInfoMap::iterator I = MemoizedTypeInfo.find(Val: T);
2069 if (I != MemoizedTypeInfo.end())
2070 return I->second;
2071
2072 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
2073 TypeInfo TI = getTypeInfoImpl(T);
2074 MemoizedTypeInfo[T] = TI;
2075 return TI;
2076}
2077
2078/// getTypeInfoImpl - Return the size of the specified type, in bits. This
2079/// method does not work on incomplete types.
2080///
2081/// FIXME: Pointers into different addr spaces could have different sizes and
2082/// alignment requirements: getPointerInfo should take an AddrSpace, this
2083/// should take a QualType, &c.
2084TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
2085 uint64_t Width = 0;
2086 unsigned Align = 8;
2087 AlignRequirementKind AlignRequirement = AlignRequirementKind::None;
2088 LangAS AS = LangAS::Default;
2089 switch (T->getTypeClass()) {
2090#define TYPE(Class, Base)
2091#define ABSTRACT_TYPE(Class, Base)
2092#define NON_CANONICAL_TYPE(Class, Base)
2093#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2094#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
2095 case Type::Class: \
2096 assert(!T->isDependentType() && "should not see dependent types here"); \
2097 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
2098#include "clang/AST/TypeNodes.inc"
2099 llvm_unreachable("Should not see dependent types");
2100
2101 case Type::FunctionNoProto:
2102 case Type::FunctionProto:
2103 // GCC extension: alignof(function) = 32 bits
2104 Width = 0;
2105 Align = 32;
2106 break;
2107
2108 case Type::IncompleteArray:
2109 case Type::VariableArray:
2110 case Type::ConstantArray:
2111 case Type::ArrayParameter: {
2112 // Model non-constant sized arrays as size zero, but track the alignment.
2113 uint64_t Size = 0;
2114 if (const auto *CAT = dyn_cast<ConstantArrayType>(Val: T))
2115 Size = CAT->getZExtSize();
2116
2117 TypeInfo EltInfo = getTypeInfo(T: cast<ArrayType>(Val: T)->getElementType());
2118 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
2119 "Overflow in array type bit size evaluation");
2120 Width = EltInfo.Width * Size;
2121 Align = EltInfo.Align;
2122 AlignRequirement = EltInfo.AlignRequirement;
2123 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
2124 getTargetInfo().getPointerWidth(AddrSpace: LangAS::Default) == 64)
2125 Width = llvm::alignTo(Value: Width, Align);
2126 break;
2127 }
2128
2129 case Type::ExtVector:
2130 case Type::Vector: {
2131 const auto *VT = cast<VectorType>(Val: T);
2132 TypeInfo EltInfo = getTypeInfo(T: VT->getElementType());
2133 Width = VT->isPackedVectorBoolType(ctx: *this)
2134 ? VT->getNumElements()
2135 : EltInfo.Width * VT->getNumElements();
2136 // Enforce at least byte size and alignment.
2137 Width = std::max<unsigned>(a: 8, b: Width);
2138 Align = std::max<unsigned>(
2139 a: 8, b: Target->vectorsAreElementAligned() ? EltInfo.Width : Width);
2140
2141 // If the alignment is not a power of 2, round up to the next power of 2.
2142 // This happens for non-power-of-2 length vectors.
2143 if (Align & (Align-1)) {
2144 Align = llvm::bit_ceil(Value: Align);
2145 Width = llvm::alignTo(Value: Width, Align);
2146 }
2147 // Adjust the alignment based on the target max.
2148 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
2149 if (TargetVectorAlign && TargetVectorAlign < Align)
2150 Align = TargetVectorAlign;
2151 if (VT->getVectorKind() == VectorKind::SveFixedLengthData)
2152 // Adjust the alignment for fixed-length SVE vectors. This is important
2153 // for non-power-of-2 vector lengths.
2154 Align = 128;
2155 else if (VT->getVectorKind() == VectorKind::SveFixedLengthPredicate)
2156 // Adjust the alignment for fixed-length SVE predicates.
2157 Align = 16;
2158 else if (VT->getVectorKind() == VectorKind::RVVFixedLengthData ||
2159 VT->getVectorKind() == VectorKind::RVVFixedLengthMask ||
2160 VT->getVectorKind() == VectorKind::RVVFixedLengthMask_1 ||
2161 VT->getVectorKind() == VectorKind::RVVFixedLengthMask_2 ||
2162 VT->getVectorKind() == VectorKind::RVVFixedLengthMask_4)
2163 // Adjust the alignment for fixed-length RVV vectors.
2164 Align = std::min<unsigned>(a: 64, b: Width);
2165 // Vector types have their natural alignment resist reduction by
2166 // #pragma pack in MSVC record layout.
2167 AlignRequirement = AlignRequirementKind::ResistPragmaPack;
2168 break;
2169 }
2170
2171 case Type::ConstantMatrix: {
2172 const auto *MT = cast<ConstantMatrixType>(Val: T);
2173 TypeInfo ElementInfo = getTypeInfo(T: MT->getElementType());
2174 // The internal layout of a matrix value is implementation defined.
2175 // Initially be ABI compatible with arrays with respect to alignment and
2176 // size.
2177 Width = ElementInfo.Width * MT->getNumRows() * MT->getNumColumns();
2178 Align = ElementInfo.Align;
2179 break;
2180 }
2181
2182 case Type::Builtin:
2183 switch (cast<BuiltinType>(Val: T)->getKind()) {
2184 default: llvm_unreachable("Unknown builtin type!");
2185 case BuiltinType::Void:
2186 // GCC extension: alignof(void) = 8 bits.
2187 Width = 0;
2188 Align = 8;
2189 break;
2190 case BuiltinType::Bool:
2191 Width = Target->getBoolWidth();
2192 Align = Target->getBoolAlign();
2193 break;
2194 case BuiltinType::Char_S:
2195 case BuiltinType::Char_U:
2196 case BuiltinType::UChar:
2197 case BuiltinType::SChar:
2198 case BuiltinType::Char8:
2199 Width = Target->getCharWidth();
2200 Align = Target->getCharAlign();
2201 break;
2202 case BuiltinType::WChar_S:
2203 case BuiltinType::WChar_U:
2204 Width = Target->getWCharWidth();
2205 Align = Target->getWCharAlign();
2206 break;
2207 case BuiltinType::Char16:
2208 Width = Target->getChar16Width();
2209 Align = Target->getChar16Align();
2210 break;
2211 case BuiltinType::Char32:
2212 Width = Target->getChar32Width();
2213 Align = Target->getChar32Align();
2214 break;
2215 case BuiltinType::UShort:
2216 case BuiltinType::Short:
2217 Width = Target->getShortWidth();
2218 Align = Target->getShortAlign();
2219 break;
2220 case BuiltinType::UInt:
2221 case BuiltinType::Int:
2222 Width = Target->getIntWidth();
2223 Align = Target->getIntAlign();
2224 break;
2225 case BuiltinType::ULong:
2226 case BuiltinType::Long:
2227 Width = Target->getLongWidth();
2228 Align = Target->getLongAlign();
2229 break;
2230 case BuiltinType::ULongLong:
2231 case BuiltinType::LongLong:
2232 Width = Target->getLongLongWidth();
2233 Align = Target->getLongLongAlign();
2234 break;
2235 case BuiltinType::Int128:
2236 case BuiltinType::UInt128:
2237 Width = 128;
2238 Align = Target->getInt128Align();
2239 break;
2240 case BuiltinType::ShortAccum:
2241 case BuiltinType::UShortAccum:
2242 case BuiltinType::SatShortAccum:
2243 case BuiltinType::SatUShortAccum:
2244 Width = Target->getShortAccumWidth();
2245 Align = Target->getShortAccumAlign();
2246 break;
2247 case BuiltinType::Accum:
2248 case BuiltinType::UAccum:
2249 case BuiltinType::SatAccum:
2250 case BuiltinType::SatUAccum:
2251 Width = Target->getAccumWidth();
2252 Align = Target->getAccumAlign();
2253 break;
2254 case BuiltinType::LongAccum:
2255 case BuiltinType::ULongAccum:
2256 case BuiltinType::SatLongAccum:
2257 case BuiltinType::SatULongAccum:
2258 Width = Target->getLongAccumWidth();
2259 Align = Target->getLongAccumAlign();
2260 break;
2261 case BuiltinType::ShortFract:
2262 case BuiltinType::UShortFract:
2263 case BuiltinType::SatShortFract:
2264 case BuiltinType::SatUShortFract:
2265 Width = Target->getShortFractWidth();
2266 Align = Target->getShortFractAlign();
2267 break;
2268 case BuiltinType::Fract:
2269 case BuiltinType::UFract:
2270 case BuiltinType::SatFract:
2271 case BuiltinType::SatUFract:
2272 Width = Target->getFractWidth();
2273 Align = Target->getFractAlign();
2274 break;
2275 case BuiltinType::LongFract:
2276 case BuiltinType::ULongFract:
2277 case BuiltinType::SatLongFract:
2278 case BuiltinType::SatULongFract:
2279 Width = Target->getLongFractWidth();
2280 Align = Target->getLongFractAlign();
2281 break;
2282 case BuiltinType::BFloat16:
2283 if (Target->hasBFloat16Type()) {
2284 Width = Target->getBFloat16Width();
2285 Align = Target->getBFloat16Align();
2286 } else if ((getLangOpts().SYCLIsDevice ||
2287 (getLangOpts().OpenMP &&
2288 getLangOpts().OpenMPIsTargetDevice)) &&
2289 AuxTarget->hasBFloat16Type()) {
2290 Width = AuxTarget->getBFloat16Width();
2291 Align = AuxTarget->getBFloat16Align();
2292 }
2293 break;
2294 case BuiltinType::Float16:
2295 case BuiltinType::Half:
2296 if (Target->hasFloat16Type() || !getLangOpts().OpenMP ||
2297 !getLangOpts().OpenMPIsTargetDevice) {
2298 Width = Target->getHalfWidth();
2299 Align = Target->getHalfAlign();
2300 } else {
2301 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2302 "Expected OpenMP device compilation.");
2303 Width = AuxTarget->getHalfWidth();
2304 Align = AuxTarget->getHalfAlign();
2305 }
2306 break;
2307 case BuiltinType::Float:
2308 Width = Target->getFloatWidth();
2309 Align = Target->getFloatAlign();
2310 break;
2311 case BuiltinType::Double:
2312 Width = Target->getDoubleWidth();
2313 Align = Target->getDoubleAlign();
2314 break;
2315 case BuiltinType::Ibm128:
2316 Width = Target->getIbm128Width();
2317 Align = Target->getIbm128Align();
2318 break;
2319 case BuiltinType::LongDouble:
2320 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2321 (Target->getLongDoubleWidth() != AuxTarget->getLongDoubleWidth() ||
2322 Target->getLongDoubleAlign() != AuxTarget->getLongDoubleAlign())) {
2323 Width = AuxTarget->getLongDoubleWidth();
2324 Align = AuxTarget->getLongDoubleAlign();
2325 } else {
2326 Width = Target->getLongDoubleWidth();
2327 Align = Target->getLongDoubleAlign();
2328 }
2329 // x87 extended precision (fp80) has its natural alignment resist
2330 // reduction by #pragma pack in MSVC record layout.
2331 if (&Target->getLongDoubleFormat() == &llvm::APFloat::x87DoubleExtended())
2332 AlignRequirement = AlignRequirementKind::ResistPragmaPack;
2333 break;
2334 case BuiltinType::Float128:
2335 if (Target->hasFloat128Type() || !getLangOpts().OpenMP ||
2336 !getLangOpts().OpenMPIsTargetDevice) {
2337 Width = Target->getFloat128Width();
2338 Align = Target->getFloat128Align();
2339 } else {
2340 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2341 "Expected OpenMP device compilation.");
2342 Width = AuxTarget->getFloat128Width();
2343 Align = AuxTarget->getFloat128Align();
2344 }
2345 break;
2346 case BuiltinType::NullPtr:
2347 // C++ 3.9.1p11: sizeof(nullptr_t) == sizeof(void*)
2348 Width = Target->getPointerWidth(AddrSpace: LangAS::Default);
2349 Align = Target->getPointerAlign(AddrSpace: LangAS::Default);
2350 break;
2351 case BuiltinType::MetaInfo:
2352 // sizeof(std::meta::info) == sizeof(void*)
2353 Width = Target->getPointerWidth(AddrSpace: LangAS::Default);
2354 // alignof(std::meta::info) == alignof(void*)
2355 Align = Target->getPointerAlign(AddrSpace: LangAS::Default);
2356 break;
2357 case BuiltinType::ObjCId:
2358 case BuiltinType::ObjCClass:
2359 case BuiltinType::ObjCSel:
2360 Width = Target->getPointerWidth(AddrSpace: LangAS::Default);
2361 Align = Target->getPointerAlign(AddrSpace: LangAS::Default);
2362 break;
2363 case BuiltinType::OCLSampler:
2364 case BuiltinType::OCLEvent:
2365 case BuiltinType::OCLClkEvent:
2366 case BuiltinType::OCLQueue:
2367 case BuiltinType::OCLReserveID:
2368#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2369 case BuiltinType::Id:
2370#include "clang/Basic/OpenCLImageTypes.def"
2371#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2372 case BuiltinType::Id:
2373#include "clang/Basic/OpenCLExtensionTypes.def"
2374 AS = Target->getOpenCLTypeAddrSpace(TK: getOpenCLTypeKind(T));
2375 Width = Target->getPointerWidth(AddrSpace: AS);
2376 Align = Target->getPointerAlign(AddrSpace: AS);
2377 break;
2378 // The SVE types are effectively target-specific. The length of an
2379 // SVE_VECTOR_TYPE is only known at runtime, but it is always a multiple
2380 // of 128 bits. There is one predicate bit for each vector byte, so the
2381 // length of an SVE_PREDICATE_TYPE is always a multiple of 16 bits.
2382 //
2383 // Because the length is only known at runtime, we use a dummy value
2384 // of 0 for the static length. The alignment values are those defined
2385 // by the Procedure Call Standard for the Arm Architecture.
2386#define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId) \
2387 case BuiltinType::Id: \
2388 Width = 0; \
2389 Align = 128; \
2390 break;
2391#define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId) \
2392 case BuiltinType::Id: \
2393 Width = 0; \
2394 Align = 16; \
2395 break;
2396#define SVE_OPAQUE_TYPE(Name, MangledName, Id, SingletonId) \
2397 case BuiltinType::Id: \
2398 Width = 0; \
2399 Align = 16; \
2400 break;
2401#define SVE_SCALAR_TYPE(Name, MangledName, Id, SingletonId, Bits) \
2402 case BuiltinType::Id: \
2403 Width = Bits; \
2404 Align = Bits; \
2405 break;
2406#include "clang/Basic/AArch64ACLETypes.def"
2407#define PPC_VECTOR_TYPE(Name, Id, Size) \
2408 case BuiltinType::Id: \
2409 Width = Size; \
2410 Align = Size; \
2411 break;
2412#include "clang/Basic/PPCTypes.def"
2413#define RVV_VECTOR_TYPE(Name, Id, SingletonId, ElKind, ElBits, NF, IsSigned, \
2414 IsFP, IsBF) \
2415 case BuiltinType::Id: \
2416 Width = 0; \
2417 Align = ElBits; \
2418 break;
2419#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, ElKind) \
2420 case BuiltinType::Id: \
2421 Width = 0; \
2422 Align = 8; \
2423 break;
2424#include "clang/Basic/RISCVVTypes.def"
2425#define WASM_TYPE(Name, Id, SingletonId) \
2426 case BuiltinType::Id: \
2427 Width = 0; \
2428 Align = 8; \
2429 break;
2430#include "clang/Basic/WebAssemblyReferenceTypes.def"
2431#define AMDGPU_TYPE(NAME, ID, SINGLETONID, WIDTH, ALIGN) \
2432 case BuiltinType::ID: \
2433 Width = WIDTH; \
2434 Align = ALIGN; \
2435 break;
2436#include "clang/Basic/AMDGPUTypes.def"
2437#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
2438#include "clang/Basic/HLSLIntangibleTypes.def"
2439 Width = Target->getPointerWidth(AddrSpace: LangAS::Default);
2440 Align = Target->getPointerAlign(AddrSpace: LangAS::Default);
2441 break;
2442#define HLSL_PACKED_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
2443#include "clang/Basic/HLSLPackedTypes.def"
2444 Width = 32;
2445 Align = 32;
2446 break;
2447#define SPIRV_TYPE(Name, Id, SingletonId) \
2448 case BuiltinType::Id: \
2449 Width = Target->getPointerWidth(LangAS::Default); \
2450 Align = Target->getPointerAlign(LangAS::Default); \
2451 break;
2452#include "clang/Basic/SPIRVTypes.def"
2453 }
2454 break;
2455 case Type::ObjCObjectPointer:
2456 Width = Target->getPointerWidth(AddrSpace: LangAS::Default);
2457 Align = Target->getPointerAlign(AddrSpace: LangAS::Default);
2458 break;
2459 case Type::BlockPointer:
2460 AS = cast<BlockPointerType>(Val: T)->getPointeeType().getAddressSpace();
2461 Width = Target->getPointerWidth(AddrSpace: AS);
2462 Align = Target->getPointerAlign(AddrSpace: AS);
2463 break;
2464 case Type::LValueReference:
2465 case Type::RValueReference:
2466 // alignof and sizeof should never enter this code path here, so we go
2467 // the pointer route.
2468 AS = cast<ReferenceType>(Val: T)->getPointeeType().getAddressSpace();
2469 Width = Target->getPointerWidth(AddrSpace: AS);
2470 Align = Target->getPointerAlign(AddrSpace: AS);
2471 break;
2472 case Type::Pointer:
2473 AS = cast<PointerType>(Val: T)->getPointeeType().getAddressSpace();
2474 Width = Target->getPointerWidth(AddrSpace: AS);
2475 Align = Target->getPointerAlign(AddrSpace: AS);
2476 break;
2477 case Type::MemberPointer: {
2478 const auto *MPT = cast<MemberPointerType>(Val: T);
2479 CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT);
2480 Width = MPI.Width;
2481 Align = MPI.Align;
2482 break;
2483 }
2484 case Type::Complex: {
2485 // Complex types have the same alignment as their elements, but twice the
2486 // size.
2487 TypeInfo EltInfo = getTypeInfo(T: cast<ComplexType>(Val: T)->getElementType());
2488 Width = EltInfo.Width * 2;
2489 Align = EltInfo.Align;
2490 break;
2491 }
2492 case Type::ObjCObject:
2493 return getTypeInfo(T: cast<ObjCObjectType>(Val: T)->getBaseType().getTypePtr());
2494 case Type::Adjusted:
2495 case Type::Decayed:
2496 return getTypeInfo(T: cast<AdjustedType>(Val: T)->getAdjustedType().getTypePtr());
2497 case Type::ObjCInterface: {
2498 const auto *ObjCI = cast<ObjCInterfaceType>(Val: T);
2499 if (ObjCI->getDecl()->isInvalidDecl()) {
2500 Width = 8;
2501 Align = 8;
2502 break;
2503 }
2504 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(D: ObjCI->getDecl());
2505 Width = toBits(CharSize: Layout.getSize());
2506 Align = toBits(CharSize: Layout.getAlignment());
2507 break;
2508 }
2509 case Type::BitInt: {
2510 const auto *EIT = cast<BitIntType>(Val: T);
2511 Align = Target->getBitIntAlign(NumBits: EIT->getNumBits());
2512 Width = Target->getBitIntWidth(NumBits: EIT->getNumBits());
2513 break;
2514 }
2515 case Type::Record:
2516 case Type::Enum: {
2517 const auto *TT = cast<TagType>(Val: T);
2518 const TagDecl *TD = TT->getDecl()->getDefinitionOrSelf();
2519
2520 if (TD->isInvalidDecl()) {
2521 Width = 8;
2522 Align = 8;
2523 break;
2524 }
2525
2526 if (isa<EnumType>(Val: TT)) {
2527 const EnumDecl *ED = cast<EnumDecl>(Val: TD);
2528 TypeInfo Info =
2529 getTypeInfo(T: ED->getIntegerType()->getUnqualifiedDesugaredType());
2530 if (unsigned AttrAlign = ED->getMaxAlignment()) {
2531 Info.Align = AttrAlign;
2532 Info.AlignRequirement = AlignRequirementKind::RequiredByEnum;
2533 }
2534 return Info;
2535 }
2536
2537 const auto *RD = cast<RecordDecl>(Val: TD);
2538 const ASTRecordLayout &Layout = getASTRecordLayout(D: RD);
2539 Width = toBits(CharSize: Layout.getSize());
2540 Align = toBits(CharSize: Layout.getAlignment());
2541 AlignRequirement = RD->hasAttr<AlignedAttr>()
2542 ? AlignRequirementKind::RequiredByRecord
2543 : AlignRequirementKind::None;
2544 break;
2545 }
2546
2547 case Type::SubstTemplateTypeParm:
2548 return getTypeInfo(T: cast<SubstTemplateTypeParmType>(Val: T)->
2549 getReplacementType().getTypePtr());
2550
2551 case Type::Auto:
2552 case Type::DeducedTemplateSpecialization: {
2553 const auto *A = cast<DeducedType>(Val: T);
2554 assert(!A->getDeducedType().isNull() &&
2555 "cannot request the size of an undeduced or dependent auto type");
2556 return getTypeInfo(T: A->getDeducedType().getTypePtr());
2557 }
2558
2559 case Type::Paren:
2560 return getTypeInfo(T: cast<ParenType>(Val: T)->getInnerType().getTypePtr());
2561
2562 case Type::MacroQualified:
2563 return getTypeInfo(
2564 T: cast<MacroQualifiedType>(Val: T)->getUnderlyingType().getTypePtr());
2565
2566 case Type::ObjCTypeParam:
2567 return getTypeInfo(T: cast<ObjCTypeParamType>(Val: T)->desugar().getTypePtr());
2568
2569 case Type::Using:
2570 return getTypeInfo(T: cast<UsingType>(Val: T)->desugar().getTypePtr());
2571
2572 case Type::Typedef: {
2573 const auto *TT = cast<TypedefType>(Val: T);
2574 TypeInfo Info = getTypeInfo(T: TT->desugar().getTypePtr());
2575 // If the typedef has an aligned attribute on it, it overrides any computed
2576 // alignment we have. This violates the GCC documentation (which says that
2577 // attribute(aligned) can only round up) but matches its implementation.
2578 if (unsigned AttrAlign = TT->getDecl()->getMaxAlignment()) {
2579 Align = AttrAlign;
2580 AlignRequirement = AlignRequirementKind::RequiredByTypedef;
2581 } else {
2582 Align = Info.Align;
2583 AlignRequirement = Info.AlignRequirement;
2584 }
2585 Width = Info.Width;
2586 break;
2587 }
2588
2589 case Type::Attributed:
2590 return getTypeInfo(
2591 T: cast<AttributedType>(Val: T)->getEquivalentType().getTypePtr());
2592
2593 case Type::CountAttributed:
2594 return getTypeInfo(T: cast<CountAttributedType>(Val: T)->desugar().getTypePtr());
2595
2596 case Type::LateParsedAttr:
2597 return getTypeInfo(T: cast<LateParsedAttrType>(Val: T)->desugar().getTypePtr());
2598
2599 case Type::BTFTagAttributed:
2600 return getTypeInfo(
2601 T: cast<BTFTagAttributedType>(Val: T)->getWrappedType().getTypePtr());
2602
2603 case Type::OverflowBehavior:
2604 return getTypeInfo(
2605 T: cast<OverflowBehaviorType>(Val: T)->getUnderlyingType().getTypePtr());
2606
2607 case Type::HLSLAttributedResource:
2608 return getTypeInfo(
2609 T: cast<HLSLAttributedResourceType>(Val: T)->getWrappedType().getTypePtr());
2610
2611 case Type::HLSLInlineSpirv: {
2612 const auto *ST = cast<HLSLInlineSpirvType>(Val: T);
2613 // Size is specified in bytes, convert to bits
2614 Width = ST->getSize() * 8;
2615 Align = ST->getAlignment();
2616 if (Width == 0 && Align == 0) {
2617 // We are defaulting to laying out opaque SPIR-V types as 32-bit ints.
2618 Width = 32;
2619 Align = 32;
2620 }
2621 break;
2622 }
2623
2624 case Type::Atomic: {
2625 // Start with the base type information.
2626 TypeInfo Info = getTypeInfo(T: cast<AtomicType>(Val: T)->getValueType());
2627 Width = Info.Width;
2628 Align = Info.Align;
2629
2630 if (!Width) {
2631 // An otherwise zero-sized type should still generate an
2632 // atomic operation.
2633 Width = Target->getCharWidth();
2634 assert(Align);
2635 } else if (Width <= Target->getMaxAtomicPromoteWidth()) {
2636 // If the size of the type doesn't exceed the platform's max
2637 // atomic promotion width, make the size and alignment more
2638 // favorable to atomic operations:
2639
2640 // Round the size up to a power of 2.
2641 Width = llvm::bit_ceil(Value: Width);
2642
2643 // Set the alignment equal to the size.
2644 Align = static_cast<unsigned>(Width);
2645 }
2646 }
2647 break;
2648
2649 case Type::PredefinedSugar:
2650 return getTypeInfo(T: cast<PredefinedSugarType>(Val: T)->desugar().getTypePtr());
2651
2652 case Type::Pipe:
2653 Width = Target->getPointerWidth(AddrSpace: LangAS::opencl_global);
2654 Align = Target->getPointerAlign(AddrSpace: LangAS::opencl_global);
2655 break;
2656 }
2657
2658 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
2659 return TypeInfo(Width, Align, AlignRequirement);
2660}
2661
2662unsigned ASTContext::getTypeUnadjustedAlign(const Type *T) const {
2663 UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(Val: T);
2664 if (I != MemoizedUnadjustedAlign.end())
2665 return I->second;
2666
2667 unsigned UnadjustedAlign;
2668 if (const auto *RT = T->getAsCanonical<RecordType>()) {
2669 const ASTRecordLayout &Layout = getASTRecordLayout(D: RT->getDecl());
2670 UnadjustedAlign = toBits(CharSize: Layout.getUnadjustedAlignment());
2671 } else if (const auto *ObjCI = T->getAsCanonical<ObjCInterfaceType>()) {
2672 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(D: ObjCI->getDecl());
2673 UnadjustedAlign = toBits(CharSize: Layout.getUnadjustedAlignment());
2674 } else {
2675 UnadjustedAlign = getTypeAlign(T: T->getUnqualifiedDesugaredType());
2676 }
2677
2678 MemoizedUnadjustedAlign[T] = UnadjustedAlign;
2679 return UnadjustedAlign;
2680}
2681
2682unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
2683 unsigned SimdAlign = llvm::OpenMPIRBuilder::getOpenMPDefaultSimdAlign(
2684 TargetTriple: getTargetInfo().getTriple(), Features: Target->getTargetOpts().FeatureMap);
2685 return SimdAlign;
2686}
2687
2688/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
2689CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
2690 return CharUnits::fromQuantity(Quantity: BitSize / getCharWidth());
2691}
2692
2693/// toBits - Convert a size in characters to a size in characters.
2694int64_t ASTContext::toBits(CharUnits CharSize) const {
2695 return CharSize.getQuantity() * getCharWidth();
2696}
2697
2698/// getTypeSizeInChars - Return the size of the specified type, in characters.
2699/// This method does not work on incomplete types.
2700CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
2701 return getTypeInfoInChars(T).Width;
2702}
2703CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
2704 return getTypeInfoInChars(T).Width;
2705}
2706
2707/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
2708/// characters. This method does not work on incomplete types.
2709CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
2710 return toCharUnitsFromBits(BitSize: getTypeAlign(T));
2711}
2712CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
2713 return toCharUnitsFromBits(BitSize: getTypeAlign(T));
2714}
2715
2716/// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a
2717/// type, in characters, before alignment adjustments. This method does
2718/// not work on incomplete types.
2719CharUnits ASTContext::getTypeUnadjustedAlignInChars(QualType T) const {
2720 return toCharUnitsFromBits(BitSize: getTypeUnadjustedAlign(T));
2721}
2722CharUnits ASTContext::getTypeUnadjustedAlignInChars(const Type *T) const {
2723 return toCharUnitsFromBits(BitSize: getTypeUnadjustedAlign(T));
2724}
2725
2726/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
2727/// type for the current target in bits. This can be different than the ABI
2728/// alignment in cases where it is beneficial for performance or backwards
2729/// compatibility preserving to overalign a data type. (Note: despite the name,
2730/// the preferred alignment is ABI-impacting, and not an optimization.)
2731unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
2732 TypeInfo TI = getTypeInfo(T);
2733 unsigned ABIAlign = TI.Align;
2734
2735 T = T->getBaseElementTypeUnsafe();
2736
2737 // The preferred alignment of member pointers is that of a pointer.
2738 if (T->isMemberPointerType())
2739 return getPreferredTypeAlign(T: getPointerDiffType().getTypePtr());
2740
2741 if (!Target->allowsLargerPreferedTypeAlignment())
2742 return ABIAlign;
2743
2744 if (const auto *RD = T->getAsRecordDecl()) {
2745 // When used as part of a typedef, or together with a 'packed' attribute,
2746 // the 'aligned' attribute can be used to decrease alignment. Note that the
2747 // 'packed' case is already taken into consideration when computing the
2748 // alignment, we only need to handle the typedef case here.
2749 if (TI.AlignRequirement == AlignRequirementKind::RequiredByTypedef ||
2750 RD->isInvalidDecl())
2751 return ABIAlign;
2752
2753 unsigned PreferredAlign = static_cast<unsigned>(
2754 toBits(CharSize: getASTRecordLayout(D: RD).PreferredAlignment));
2755 assert(PreferredAlign >= ABIAlign &&
2756 "PreferredAlign should be at least as large as ABIAlign.");
2757 return PreferredAlign;
2758 }
2759
2760 // Double (and, for targets supporting AIX `power` alignment, long double) and
2761 // long long should be naturally aligned (despite requiring less alignment) if
2762 // possible.
2763 if (const auto *CT = T->getAs<ComplexType>())
2764 T = CT->getElementType().getTypePtr();
2765 if (const auto *ED = T->getAsEnumDecl())
2766 T = ED->getIntegerType().getTypePtr();
2767 if (T->isSpecificBuiltinType(K: BuiltinType::Double) ||
2768 T->isSpecificBuiltinType(K: BuiltinType::LongLong) ||
2769 T->isSpecificBuiltinType(K: BuiltinType::ULongLong) ||
2770 (T->isSpecificBuiltinType(K: BuiltinType::LongDouble) &&
2771 Target->defaultsToAIXPowerAlignment()))
2772 // Don't increase the alignment if an alignment attribute was specified on a
2773 // typedef declaration.
2774 if (!TI.isAlignRequired())
2775 return std::max(a: ABIAlign, b: (unsigned)getTypeSize(T));
2776
2777 return ABIAlign;
2778}
2779
2780/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2781/// for __attribute__((aligned)) on this target, to be used if no alignment
2782/// value is specified.
2783unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const {
2784 return getTargetInfo().getDefaultAlignForAttributeAligned();
2785}
2786
2787/// getAlignOfGlobalVar - Return the alignment in bits that should be given
2788/// to a global variable of the specified type.
2789unsigned ASTContext::getAlignOfGlobalVar(QualType T, const VarDecl *VD) const {
2790 uint64_t TypeSize = getTypeSize(T: T.getTypePtr());
2791 return std::max(a: getPreferredTypeAlign(T),
2792 b: getMinGlobalAlignOfVar(Size: TypeSize, VD));
2793}
2794
2795/// getAlignOfGlobalVarInChars - Return the alignment in characters that
2796/// should be given to a global variable of the specified type.
2797CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T,
2798 const VarDecl *VD) const {
2799 return toCharUnitsFromBits(BitSize: getAlignOfGlobalVar(T, VD));
2800}
2801
2802unsigned ASTContext::getMinGlobalAlignOfVar(uint64_t Size,
2803 const VarDecl *VD) const {
2804 // Make the default handling as that of a non-weak definition in the
2805 // current translation unit.
2806 bool HasNonWeakDef = !VD || (VD->hasDefinition() && !VD->isWeak());
2807 return getTargetInfo().getMinGlobalAlign(Size, HasNonWeakDef);
2808}
2809
2810CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
2811 CharUnits Offset = CharUnits::Zero();
2812 const ASTRecordLayout *Layout = &getASTRecordLayout(D: RD);
2813 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2814 Offset += Layout->getBaseClassOffset(Base);
2815 Layout = &getASTRecordLayout(D: Base);
2816 }
2817 return Offset;
2818}
2819
2820CharUnits ASTContext::getMemberPointerPathAdjustment(const APValue &MP) const {
2821 const ValueDecl *MPD = MP.getMemberPointerDecl();
2822 CharUnits ThisAdjustment = CharUnits::Zero();
2823 ArrayRef<const CXXRecordDecl*> Path = MP.getMemberPointerPath();
2824 bool DerivedMember = MP.isMemberPointerToDerivedMember();
2825 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Val: MPD->getDeclContext());
2826 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
2827 const CXXRecordDecl *Base = RD;
2828 const CXXRecordDecl *Derived = Path[I];
2829 if (DerivedMember)
2830 std::swap(a&: Base, b&: Derived);
2831 ThisAdjustment += getASTRecordLayout(D: Derived).getBaseClassOffset(Base);
2832 RD = Path[I];
2833 }
2834 if (DerivedMember)
2835 ThisAdjustment = -ThisAdjustment;
2836 return ThisAdjustment;
2837}
2838
2839/// DeepCollectObjCIvars -
2840/// This routine first collects all declared, but not synthesized, ivars in
2841/// super class and then collects all ivars, including those synthesized for
2842/// current class. This routine is used for implementation of current class
2843/// when all ivars, declared and synthesized are known.
2844void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
2845 bool leafClass,
2846 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
2847 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2848 DeepCollectObjCIvars(OI: SuperClass, leafClass: false, Ivars);
2849 if (!leafClass) {
2850 llvm::append_range(C&: Ivars, R: OI->ivars());
2851 } else {
2852 auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
2853 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
2854 Iv= Iv->getNextIvar())
2855 Ivars.push_back(Elt: Iv);
2856 }
2857}
2858
2859/// CollectInheritedProtocols - Collect all protocols in current class and
2860/// those inherited by it.
2861void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
2862 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
2863 if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(Val: CDecl)) {
2864 // We can use protocol_iterator here instead of
2865 // all_referenced_protocol_iterator since we are walking all categories.
2866 for (auto *Proto : OI->all_referenced_protocols()) {
2867 CollectInheritedProtocols(CDecl: Proto, Protocols);
2868 }
2869
2870 // Categories of this Interface.
2871 for (const auto *Cat : OI->visible_categories())
2872 CollectInheritedProtocols(CDecl: Cat, Protocols);
2873
2874 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2875 while (SD) {
2876 CollectInheritedProtocols(CDecl: SD, Protocols);
2877 SD = SD->getSuperClass();
2878 }
2879 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(Val: CDecl)) {
2880 for (auto *Proto : OC->protocols()) {
2881 CollectInheritedProtocols(CDecl: Proto, Protocols);
2882 }
2883 } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(Val: CDecl)) {
2884 // Insert the protocol.
2885 if (!Protocols.insert(
2886 Ptr: const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2887 return;
2888
2889 for (auto *Proto : OP->protocols())
2890 CollectInheritedProtocols(CDecl: Proto, Protocols);
2891 }
2892}
2893
2894static bool unionHasUniqueObjectRepresentations(const ASTContext &Context,
2895 const RecordDecl *RD,
2896 bool CheckIfTriviallyCopyable) {
2897 assert(RD->isUnion() && "Must be union type");
2898 CharUnits UnionSize =
2899 Context.getTypeSizeInChars(T: Context.getCanonicalTagType(TD: RD));
2900
2901 for (const auto *Field : RD->fields()) {
2902 if (!Context.hasUniqueObjectRepresentations(Ty: Field->getType(),
2903 CheckIfTriviallyCopyable))
2904 return false;
2905 CharUnits FieldSize = Context.getTypeSizeInChars(T: Field->getType());
2906 if (FieldSize != UnionSize)
2907 return false;
2908 }
2909 return !RD->field_empty();
2910}
2911
2912static int64_t getSubobjectOffset(const FieldDecl *Field,
2913 const ASTContext &Context,
2914 const clang::ASTRecordLayout & /*Layout*/) {
2915 return Context.getFieldOffset(FD: Field);
2916}
2917
2918static int64_t getSubobjectOffset(const CXXRecordDecl *RD,
2919 const ASTContext &Context,
2920 const clang::ASTRecordLayout &Layout) {
2921 return Context.toBits(CharSize: Layout.getBaseClassOffset(Base: RD));
2922}
2923
2924static std::optional<int64_t>
2925structHasUniqueObjectRepresentations(const ASTContext &Context,
2926 const RecordDecl *RD,
2927 bool CheckIfTriviallyCopyable);
2928
2929static std::optional<int64_t>
2930getSubobjectSizeInBits(const FieldDecl *Field, const ASTContext &Context,
2931 bool CheckIfTriviallyCopyable) {
2932 if (const auto *RD = Field->getType()->getAsRecordDecl();
2933 RD && !RD->isUnion())
2934 return structHasUniqueObjectRepresentations(Context, RD,
2935 CheckIfTriviallyCopyable);
2936
2937 // A _BitInt type may not be unique if it has padding bits
2938 // but if it is a bitfield the padding bits are not used.
2939 bool IsBitIntType = Field->getType()->isBitIntType();
2940 if (!Field->getType()->isReferenceType() && !IsBitIntType &&
2941 !Context.hasUniqueObjectRepresentations(Ty: Field->getType(),
2942 CheckIfTriviallyCopyable))
2943 return std::nullopt;
2944
2945 int64_t FieldSizeInBits =
2946 Context.toBits(CharSize: Context.getTypeSizeInChars(T: Field->getType()));
2947 if (Field->isBitField()) {
2948 // If we have explicit padding bits, they don't contribute bits
2949 // to the actual object representation, so return 0.
2950 if (Field->isUnnamedBitField())
2951 return 0;
2952
2953 int64_t BitfieldSize = Field->getBitWidthValue();
2954 if (IsBitIntType) {
2955 if ((unsigned)BitfieldSize >
2956 cast<BitIntType>(Val: Field->getType())->getNumBits())
2957 return std::nullopt;
2958 } else if (BitfieldSize > FieldSizeInBits) {
2959 return std::nullopt;
2960 }
2961 FieldSizeInBits = BitfieldSize;
2962 } else if (IsBitIntType && !Context.hasUniqueObjectRepresentations(
2963 Ty: Field->getType(), CheckIfTriviallyCopyable)) {
2964 return std::nullopt;
2965 }
2966 return FieldSizeInBits;
2967}
2968
2969static std::optional<int64_t>
2970getSubobjectSizeInBits(const CXXRecordDecl *RD, const ASTContext &Context,
2971 bool CheckIfTriviallyCopyable) {
2972 return structHasUniqueObjectRepresentations(Context, RD,
2973 CheckIfTriviallyCopyable);
2974}
2975
2976template <typename RangeT>
2977static std::optional<int64_t> structSubobjectsHaveUniqueObjectRepresentations(
2978 const RangeT &Subobjects, int64_t CurOffsetInBits,
2979 const ASTContext &Context, const clang::ASTRecordLayout &Layout,
2980 bool CheckIfTriviallyCopyable) {
2981 for (const auto *Subobject : Subobjects) {
2982 std::optional<int64_t> SizeInBits =
2983 getSubobjectSizeInBits(Subobject, Context, CheckIfTriviallyCopyable);
2984 if (!SizeInBits)
2985 return std::nullopt;
2986 if (*SizeInBits != 0) {
2987 int64_t Offset = getSubobjectOffset(Subobject, Context, Layout);
2988 if (Offset != CurOffsetInBits)
2989 return std::nullopt;
2990 CurOffsetInBits += *SizeInBits;
2991 }
2992 }
2993 return CurOffsetInBits;
2994}
2995
2996static std::optional<int64_t>
2997structHasUniqueObjectRepresentations(const ASTContext &Context,
2998 const RecordDecl *RD,
2999 bool CheckIfTriviallyCopyable) {
3000 assert(!RD->isUnion() && "Must be struct/class type");
3001 const auto &Layout = Context.getASTRecordLayout(D: RD);
3002
3003 int64_t CurOffsetInBits = 0;
3004 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(Val: RD)) {
3005 if (ClassDecl->isDynamicClass())
3006 return std::nullopt;
3007
3008 SmallVector<CXXRecordDecl *, 4> Bases;
3009 for (const auto &Base : ClassDecl->bases()) {
3010 // Empty types can be inherited from, and non-empty types can potentially
3011 // have tail padding, so just make sure there isn't an error.
3012 Bases.emplace_back(Args: Base.getType()->getAsCXXRecordDecl());
3013 }
3014
3015 llvm::sort(C&: Bases, Comp: [&](const CXXRecordDecl *L, const CXXRecordDecl *R) {
3016 return Layout.getBaseClassOffset(Base: L) < Layout.getBaseClassOffset(Base: R);
3017 });
3018
3019 std::optional<int64_t> OffsetAfterBases =
3020 structSubobjectsHaveUniqueObjectRepresentations(
3021 Subobjects: Bases, CurOffsetInBits, Context, Layout, CheckIfTriviallyCopyable);
3022 if (!OffsetAfterBases)
3023 return std::nullopt;
3024 CurOffsetInBits = *OffsetAfterBases;
3025 }
3026
3027 std::optional<int64_t> OffsetAfterFields =
3028 structSubobjectsHaveUniqueObjectRepresentations(
3029 Subobjects: RD->fields(), CurOffsetInBits, Context, Layout,
3030 CheckIfTriviallyCopyable);
3031 if (!OffsetAfterFields)
3032 return std::nullopt;
3033 CurOffsetInBits = *OffsetAfterFields;
3034
3035 return CurOffsetInBits;
3036}
3037
3038bool ASTContext::hasUniqueObjectRepresentations(
3039 QualType Ty, bool CheckIfTriviallyCopyable) const {
3040 // C++17 [meta.unary.prop]:
3041 // The predicate condition for a template specialization
3042 // has_unique_object_representations<T> shall be satisfied if and only if:
3043 // (9.1) - T is trivially copyable, and
3044 // (9.2) - any two objects of type T with the same value have the same
3045 // object representation, where:
3046 // - two objects of array or non-union class type are considered to have
3047 // the same value if their respective sequences of direct subobjects
3048 // have the same values, and
3049 // - two objects of union type are considered to have the same value if
3050 // they have the same active member and the corresponding members have
3051 // the same value.
3052 // The set of scalar types for which this condition holds is
3053 // implementation-defined. [ Note: If a type has padding bits, the condition
3054 // does not hold; otherwise, the condition holds true for unsigned integral
3055 // types. -- end note ]
3056 assert(!Ty.isNull() && "Null QualType sent to unique object rep check");
3057
3058 // Arrays are unique only if their element type is unique.
3059 if (Ty->isArrayType())
3060 return hasUniqueObjectRepresentations(Ty: getBaseElementType(QT: Ty),
3061 CheckIfTriviallyCopyable);
3062
3063 assert((Ty->isVoidType() || !Ty->isIncompleteType()) &&
3064 "hasUniqueObjectRepresentations should not be called with an "
3065 "incomplete type");
3066
3067 // _Atomic(T) shares T's object representation unless its size was rounded
3068 // up to a power of two, in which case the extra bytes are padding. Atomic
3069 // types are never trivially copyable, so (9.1) is judged on the value type.
3070 if (const auto *AT = Ty->getAs<AtomicType>())
3071 return getTypeSize(T: AT) == getTypeSize(T: AT->getValueType()) &&
3072 hasUniqueObjectRepresentations(Ty: AT->getValueType(),
3073 CheckIfTriviallyCopyable);
3074
3075 // (9.1) - T is trivially copyable...
3076 if (CheckIfTriviallyCopyable && !Ty.isTriviallyCopyableType(Context: *this))
3077 return false;
3078
3079 // All integrals and enums are unique.
3080 if (Ty->isIntegralOrEnumerationType()) {
3081 // Address discriminated integer types are not unique.
3082 if (Ty.hasAddressDiscriminatedPointerAuth())
3083 return false;
3084 // Except _BitInt types that have padding bits.
3085 if (const auto *BIT = Ty->getAs<BitIntType>())
3086 return getTypeSize(T: BIT) == BIT->getNumBits();
3087
3088 return true;
3089 }
3090
3091 // All other pointers are unique.
3092 if (Ty->isPointerType())
3093 return !Ty.hasAddressDiscriminatedPointerAuth();
3094
3095 if (const auto *MPT = Ty->getAs<MemberPointerType>())
3096 return !ABI->getMemberPointerInfo(MPT).HasPadding;
3097
3098 if (const auto *Record = Ty->getAsRecordDecl()) {
3099 if (Record->isInvalidDecl())
3100 return false;
3101
3102 if (Record->isUnion())
3103 return unionHasUniqueObjectRepresentations(Context: *this, RD: Record,
3104 CheckIfTriviallyCopyable);
3105
3106 std::optional<int64_t> StructSize = structHasUniqueObjectRepresentations(
3107 Context: *this, RD: Record, CheckIfTriviallyCopyable);
3108
3109 return StructSize && *StructSize == static_cast<int64_t>(getTypeSize(T: Ty));
3110 }
3111
3112 // FIXME: More cases to handle here (list by rsmith):
3113 // vectors (careful about, eg, vector of 3 foo)
3114 // _Complex int and friends
3115 // Obj-C block pointers
3116 // Obj-C object pointers
3117 // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t,
3118 // clk_event_t, queue_t, reserve_id_t)
3119 // There're also Obj-C class types and the Obj-C selector type, but I think it
3120 // makes sense for those to return false here.
3121
3122 return false;
3123}
3124
3125unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
3126 unsigned count = 0;
3127 // Count ivars declared in class extension.
3128 for (const auto *Ext : OI->known_extensions())
3129 count += Ext->ivar_size();
3130
3131 // Count ivar defined in this class's implementation. This
3132 // includes synthesized ivars.
3133 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
3134 count += ImplDecl->ivar_size();
3135
3136 return count;
3137}
3138
3139bool ASTContext::isSentinelNullExpr(const Expr *E) {
3140 if (!E)
3141 return false;
3142
3143 // nullptr_t is always treated as null.
3144 if (E->getType()->isNullPtrType()) return true;
3145
3146 if (E->getType()->isAnyPointerType() &&
3147 E->IgnoreParenCasts()->isNullPointerConstant(Ctx&: *this,
3148 NPC: Expr::NPC_ValueDependentIsNull))
3149 return true;
3150
3151 // Unfortunately, __null has type 'int'.
3152 if (isa<GNUNullExpr>(Val: E)) return true;
3153
3154 return false;
3155}
3156
3157/// Get the implementation of ObjCInterfaceDecl, or nullptr if none
3158/// exists.
3159ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
3160 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
3161 I = ObjCImpls.find(Val: D);
3162 if (I != ObjCImpls.end())
3163 return cast<ObjCImplementationDecl>(Val: I->second);
3164 return nullptr;
3165}
3166
3167/// Get the implementation of ObjCCategoryDecl, or nullptr if none
3168/// exists.
3169ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
3170 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
3171 I = ObjCImpls.find(Val: D);
3172 if (I != ObjCImpls.end())
3173 return cast<ObjCCategoryImplDecl>(Val: I->second);
3174 return nullptr;
3175}
3176
3177/// Set the implementation of ObjCInterfaceDecl.
3178void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
3179 ObjCImplementationDecl *ImplD) {
3180 assert(IFaceD && ImplD && "Passed null params");
3181 ObjCImpls[IFaceD] = ImplD;
3182}
3183
3184/// Set the implementation of ObjCCategoryDecl.
3185void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
3186 ObjCCategoryImplDecl *ImplD) {
3187 assert(CatD && ImplD && "Passed null params");
3188 ObjCImpls[CatD] = ImplD;
3189}
3190
3191const ObjCMethodDecl *
3192ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const {
3193 return ObjCMethodRedecls.lookup(Val: MD);
3194}
3195
3196void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
3197 const ObjCMethodDecl *Redecl) {
3198 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
3199 ObjCMethodRedecls[MD] = Redecl;
3200}
3201
3202const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
3203 const NamedDecl *ND) const {
3204 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(Val: ND->getDeclContext()))
3205 return ID;
3206 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(Val: ND->getDeclContext()))
3207 return CD->getClassInterface();
3208 if (const auto *IMD = dyn_cast<ObjCImplDecl>(Val: ND->getDeclContext()))
3209 return IMD->getClassInterface();
3210
3211 return nullptr;
3212}
3213
3214/// Get the copy initialization expression of VarDecl, or nullptr if
3215/// none exists.
3216BlockVarCopyInit ASTContext::getBlockVarCopyInit(const VarDecl *VD) const {
3217 assert(VD && "Passed null params");
3218 assert(VD->hasAttr<BlocksAttr>() &&
3219 "getBlockVarCopyInits - not __block var");
3220 auto I = BlockVarCopyInits.find(Val: VD);
3221 if (I != BlockVarCopyInits.end())
3222 return I->second;
3223 return {nullptr, false};
3224}
3225
3226/// Set the copy initialization expression of a block var decl.
3227void ASTContext::setBlockVarCopyInit(const VarDecl*VD, Expr *CopyExpr,
3228 bool CanThrow) {
3229 assert(VD && CopyExpr && "Passed null params");
3230 assert(VD->hasAttr<BlocksAttr>() &&
3231 "setBlockVarCopyInits - not __block var");
3232 BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow);
3233}
3234
3235TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
3236 unsigned DataSize) const {
3237 if (!DataSize)
3238 DataSize = TypeLoc::getFullDataSizeForType(Ty: T);
3239 else
3240 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
3241 "incorrect data size provided to CreateTypeSourceInfo!");
3242
3243 auto *TInfo =
3244 (TypeSourceInfo*)BumpAlloc.Allocate(Size: sizeof(TypeSourceInfo) + DataSize, Alignment: 8);
3245 new (TInfo) TypeSourceInfo(T, DataSize);
3246 return TInfo;
3247}
3248
3249TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
3250 SourceLocation L) const {
3251 TypeSourceInfo *TSI = CreateTypeSourceInfo(T);
3252 TSI->getTypeLoc().initialize(Context&: const_cast<ASTContext &>(*this), Loc: L);
3253 return TSI;
3254}
3255
3256const ASTRecordLayout &
3257ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
3258 return getObjCLayout(D);
3259}
3260
3261static auto getCanonicalTemplateArguments(const ASTContext &C,
3262 ArrayRef<TemplateArgument> Args,
3263 bool &AnyNonCanonArgs) {
3264 SmallVector<TemplateArgument, 16> CanonArgs(Args);
3265 AnyNonCanonArgs |= C.canonicalizeTemplateArguments(Args: CanonArgs);
3266 return CanonArgs;
3267}
3268
3269bool ASTContext::canonicalizeTemplateArguments(
3270 MutableArrayRef<TemplateArgument> Args) const {
3271 bool AnyNonCanonArgs = false;
3272 for (auto &Arg : Args) {
3273 TemplateArgument OrigArg = Arg;
3274 Arg = getCanonicalTemplateArgument(Arg);
3275 AnyNonCanonArgs |= !Arg.structurallyEquals(Other: OrigArg);
3276 }
3277 return AnyNonCanonArgs;
3278}
3279
3280//===----------------------------------------------------------------------===//
3281// Type creation/memoization methods
3282//===----------------------------------------------------------------------===//
3283
3284QualType
3285ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
3286 unsigned fastQuals = quals.getFastQualifiers();
3287 quals.removeFastQualifiers();
3288
3289 // Check if we've already instantiated this type.
3290 llvm::FoldingSetNodeID ID;
3291 ExtQuals::Profile(ID, BaseType: baseType, Quals: quals);
3292 llvm::FoldingSetInsertToken Token;
3293 if (ExtQuals *eq = ExtQualNodes.lookup(ID, Token)) {
3294 assert(eq->getQualifiers() == quals);
3295 return QualType(eq, fastQuals);
3296 }
3297
3298 // If the base type is not canonical, make the appropriate canonical type.
3299 QualType canon;
3300 if (!baseType->isCanonicalUnqualified()) {
3301 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
3302 canonSplit.Quals.addConsistentQualifiers(qs: quals);
3303 canon = getExtQualType(baseType: canonSplit.Ty, quals: canonSplit.Quals);
3304
3305 // Re-find the insert position.
3306 (void)ExtQualNodes.lookup(ID, Token);
3307 }
3308
3309 auto *eq = new (*this, alignof(ExtQuals)) ExtQuals(baseType, canon, quals);
3310 ExtQualNodes.insert(N: eq, Token);
3311 return QualType(eq, fastQuals);
3312}
3313
3314QualType ASTContext::getAddrSpaceQualType(QualType T,
3315 LangAS AddressSpace) const {
3316 QualType CanT = getCanonicalType(T);
3317 if (CanT.getAddressSpace() == AddressSpace)
3318 return T;
3319
3320 // If we are composing extended qualifiers together, merge together
3321 // into one ExtQuals node.
3322 QualifierCollector Quals;
3323 const Type *TypeNode = Quals.strip(type: T);
3324
3325 // If this type already has an address space specified, it cannot get
3326 // another one.
3327 assert(!Quals.hasAddressSpace() &&
3328 "Type cannot be in multiple addr spaces!");
3329 Quals.addAddressSpace(space: AddressSpace);
3330
3331 return getExtQualType(baseType: TypeNode, quals: Quals);
3332}
3333
3334QualType ASTContext::removeAddrSpaceQualType(QualType T) const {
3335 // If the type is not qualified with an address space, just return it
3336 // immediately.
3337 if (!T.hasAddressSpace())
3338 return T;
3339
3340 QualifierCollector Quals;
3341 const Type *TypeNode;
3342 // For arrays, strip the qualifier off the element type, then reconstruct the
3343 // array type
3344 if (T.getTypePtr()->isArrayType()) {
3345 T = getUnqualifiedArrayType(T, Quals);
3346 TypeNode = T.getTypePtr();
3347 } else {
3348 // If we are composing extended qualifiers together, merge together
3349 // into one ExtQuals node.
3350 while (T.hasAddressSpace()) {
3351 TypeNode = Quals.strip(type: T);
3352
3353 // If the type no longer has an address space after stripping qualifiers,
3354 // jump out.
3355 if (!QualType(TypeNode, 0).hasAddressSpace())
3356 break;
3357
3358 // There might be sugar in the way. Strip it and try again.
3359 T = T.getSingleStepDesugaredType(Context: *this);
3360 }
3361 }
3362
3363 Quals.removeAddressSpace();
3364
3365 // Removal of the address space can mean there are no longer any
3366 // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts)
3367 // or required.
3368 if (Quals.hasNonFastQualifiers())
3369 return getExtQualType(baseType: TypeNode, quals: Quals);
3370 else
3371 return QualType(TypeNode, Quals.getFastQualifiers());
3372}
3373
3374uint16_t
3375ASTContext::getPointerAuthVTablePointerDiscriminator(const CXXRecordDecl *RD,
3376 bool IsVTTEntry) {
3377 assert(RD->isPolymorphic() &&
3378 "Attempted to get vtable pointer discriminator on a monomorphic type");
3379
3380 std::unique_ptr<MangleContext> MC(createMangleContext());
3381 SmallString<256> Str;
3382 llvm::raw_svector_ostream Out(Str);
3383 MC->mangleCXXVTable(RD, Out);
3384 if (IsVTTEntry)
3385 Out << VTTVTablePointerDiscriminatorSuffix;
3386 return llvm::getPointerAuthStableSipHash(S: Str);
3387}
3388
3389/// Encode a function type for use in the discriminator of a function pointer
3390/// type. We can't use the itanium scheme for this since C has quite permissive
3391/// rules for type compatibility that we need to be compatible with.
3392///
3393/// Formally, this function associates every function pointer type T with an
3394/// encoded string E(T). Let the equivalence relation T1 ~ T2 be defined as
3395/// E(T1) == E(T2). E(T) is part of the ABI of values of type T. C type
3396/// compatibility requires equivalent treatment under the ABI, so
3397/// CCompatible(T1, T2) must imply E(T1) == E(T2), that is, CCompatible must be
3398/// a subset of ~. Crucially, however, it must be a proper subset because
3399/// CCompatible is not an equivalence relation: for example, int[] is compatible
3400/// with both int[1] and int[2], but the latter are not compatible with each
3401/// other. Therefore this encoding function must be careful to only distinguish
3402/// types if there is no third type with which they are both required to be
3403/// compatible.
3404static void encodeTypeForFunctionPointerAuth(const ASTContext &Ctx,
3405 raw_ostream &OS, QualType QT) {
3406 // FIXME: Consider address space qualifiers.
3407 const Type *T = QT.getCanonicalType().getTypePtr();
3408
3409 // FIXME: Consider using the C++ type mangling when we encounter a construct
3410 // that is incompatible with C.
3411
3412 switch (T->getTypeClass()) {
3413 case Type::Atomic:
3414 return encodeTypeForFunctionPointerAuth(
3415 Ctx, OS, QT: cast<AtomicType>(Val: T)->getValueType());
3416
3417 case Type::LValueReference:
3418 OS << "R";
3419 encodeTypeForFunctionPointerAuth(Ctx, OS,
3420 QT: cast<ReferenceType>(Val: T)->getPointeeType());
3421 return;
3422 case Type::RValueReference:
3423 OS << "O";
3424 encodeTypeForFunctionPointerAuth(Ctx, OS,
3425 QT: cast<ReferenceType>(Val: T)->getPointeeType());
3426 return;
3427
3428 case Type::Pointer:
3429 // C11 6.7.6.1p2:
3430 // For two pointer types to be compatible, both shall be identically
3431 // qualified and both shall be pointers to compatible types.
3432 // FIXME: we should also consider pointee types.
3433 OS << "P";
3434 return;
3435
3436 case Type::ObjCObjectPointer:
3437 case Type::BlockPointer:
3438 OS << "P";
3439 return;
3440
3441 case Type::Complex:
3442 OS << "C";
3443 return encodeTypeForFunctionPointerAuth(
3444 Ctx, OS, QT: cast<ComplexType>(Val: T)->getElementType());
3445
3446 case Type::VariableArray:
3447 case Type::ConstantArray:
3448 case Type::IncompleteArray:
3449 case Type::ArrayParameter:
3450 // C11 6.7.6.2p6:
3451 // For two array types to be compatible, both shall have compatible
3452 // element types, and if both size specifiers are present, and are integer
3453 // constant expressions, then both size specifiers shall have the same
3454 // constant value [...]
3455 //
3456 // So since ElemType[N] has to be compatible ElemType[], we can't encode the
3457 // width of the array.
3458 OS << "A";
3459 return encodeTypeForFunctionPointerAuth(
3460 Ctx, OS, QT: cast<ArrayType>(Val: T)->getElementType());
3461
3462 case Type::ObjCInterface:
3463 case Type::ObjCObject:
3464 OS << "<objc_object>";
3465 return;
3466
3467 case Type::Enum: {
3468 // C11 6.7.2.2p4:
3469 // Each enumerated type shall be compatible with char, a signed integer
3470 // type, or an unsigned integer type.
3471 //
3472 // So we have to treat enum types as integers.
3473 QualType UnderlyingType = T->castAsEnumDecl()->getIntegerType();
3474 return encodeTypeForFunctionPointerAuth(
3475 Ctx, OS, QT: UnderlyingType.isNull() ? Ctx.IntTy : UnderlyingType);
3476 }
3477
3478 case Type::FunctionNoProto:
3479 case Type::FunctionProto: {
3480 // C11 6.7.6.3p15:
3481 // For two function types to be compatible, both shall specify compatible
3482 // return types. Moreover, the parameter type lists, if both are present,
3483 // shall agree in the number of parameters and in the use of the ellipsis
3484 // terminator; corresponding parameters shall have compatible types.
3485 //
3486 // That paragraph goes on to describe how unprototyped functions are to be
3487 // handled, which we ignore here. Unprototyped function pointers are hashed
3488 // as though they were prototyped nullary functions since thats probably
3489 // what the user meant. This behavior is non-conforming.
3490 // FIXME: If we add a "custom discriminator" function type attribute we
3491 // should encode functions as their discriminators.
3492 OS << "F";
3493 const auto *FuncType = cast<FunctionType>(Val: T);
3494 encodeTypeForFunctionPointerAuth(Ctx, OS, QT: FuncType->getReturnType());
3495 if (const auto *FPT = dyn_cast<FunctionProtoType>(Val: FuncType)) {
3496 for (QualType Param : FPT->param_types()) {
3497 Param = Ctx.getSignatureParameterType(T: Param);
3498 encodeTypeForFunctionPointerAuth(Ctx, OS, QT: Param);
3499 }
3500 if (FPT->isVariadic())
3501 OS << "z";
3502 }
3503 OS << "E";
3504 return;
3505 }
3506
3507 case Type::MemberPointer: {
3508 OS << "M";
3509 const auto *MPT = T->castAs<MemberPointerType>();
3510 encodeTypeForFunctionPointerAuth(
3511 Ctx, OS, QT: QualType(MPT->getQualifier().getAsType(), 0));
3512 encodeTypeForFunctionPointerAuth(Ctx, OS, QT: MPT->getPointeeType());
3513 return;
3514 }
3515 case Type::ExtVector:
3516 case Type::Vector:
3517 OS << "Dv" << Ctx.getTypeSizeInChars(T).getQuantity();
3518 break;
3519
3520 // Don't bother discriminating based on these types.
3521 case Type::Pipe:
3522 case Type::BitInt:
3523 case Type::ConstantMatrix:
3524 OS << "?";
3525 return;
3526
3527 case Type::Builtin: {
3528 const auto *BTy = T->castAs<BuiltinType>();
3529 switch (BTy->getKind()) {
3530#define SIGNED_TYPE(Id, SingletonId) \
3531 case BuiltinType::Id: \
3532 OS << "i"; \
3533 return;
3534#define UNSIGNED_TYPE(Id, SingletonId) \
3535 case BuiltinType::Id: \
3536 OS << "i"; \
3537 return;
3538#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
3539#define BUILTIN_TYPE(Id, SingletonId)
3540#include "clang/AST/BuiltinTypes.def"
3541 llvm_unreachable("placeholder types should not appear here.");
3542
3543 case BuiltinType::Half:
3544 OS << "Dh";
3545 return;
3546 case BuiltinType::Float:
3547 OS << "f";
3548 return;
3549 case BuiltinType::Double:
3550 OS << "d";
3551 return;
3552 case BuiltinType::LongDouble:
3553 OS << "e";
3554 return;
3555 case BuiltinType::Float16:
3556 OS << "DF16_";
3557 return;
3558 case BuiltinType::Float128:
3559 OS << "g";
3560 return;
3561
3562 case BuiltinType::Void:
3563 OS << "v";
3564 return;
3565
3566 case BuiltinType::ObjCId:
3567 case BuiltinType::ObjCClass:
3568 case BuiltinType::ObjCSel:
3569 case BuiltinType::NullPtr:
3570 OS << "P";
3571 return;
3572
3573 // Don't bother discriminating based on OpenCL types.
3574 case BuiltinType::OCLSampler:
3575 case BuiltinType::OCLEvent:
3576 case BuiltinType::OCLClkEvent:
3577 case BuiltinType::OCLQueue:
3578 case BuiltinType::OCLReserveID:
3579 case BuiltinType::BFloat16:
3580 case BuiltinType::VectorQuad:
3581 case BuiltinType::VectorPair:
3582 case BuiltinType::DMR1024:
3583 case BuiltinType::DMR2048:
3584 case BuiltinType::MetaInfo:
3585 OS << "?";
3586 return;
3587
3588 // Don't bother discriminating based on these seldom-used types.
3589 case BuiltinType::Ibm128:
3590 return;
3591#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
3592 case BuiltinType::Id: \
3593 return;
3594#include "clang/Basic/OpenCLImageTypes.def"
3595#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
3596 case BuiltinType::Id: \
3597 return;
3598#include "clang/Basic/OpenCLExtensionTypes.def"
3599#define SVE_TYPE(Name, Id, SingletonId) \
3600 case BuiltinType::Id: \
3601 return;
3602#include "clang/Basic/AArch64ACLETypes.def"
3603#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
3604 case BuiltinType::Id: \
3605 return;
3606#include "clang/Basic/HLSLIntangibleTypes.def"
3607#define HLSL_PACKED_TYPE(Name, Id, SingletonId) \
3608 case BuiltinType::Id: \
3609 return;
3610#include "clang/Basic/HLSLPackedTypes.def"
3611 case BuiltinType::Dependent:
3612 llvm_unreachable("should never get here");
3613#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
3614#include "clang/Basic/AMDGPUTypes.def"
3615 case BuiltinType::WasmExternRef:
3616#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
3617#include "clang/Basic/RISCVVTypes.def"
3618#define SPIRV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
3619#include "clang/Basic/SPIRVTypes.def"
3620 llvm_unreachable("not yet implemented");
3621 }
3622 llvm_unreachable("should never get here");
3623 }
3624 case Type::Record: {
3625 const RecordDecl *RD = T->castAsCanonical<RecordType>()->getDecl();
3626 const IdentifierInfo *II = RD->getIdentifier();
3627
3628 // In C++, an immediate typedef of an anonymous struct or union
3629 // is considered to name it for ODR purposes, but C's specification
3630 // of type compatibility does not have a similar rule. Using the typedef
3631 // name in function type discriminators anyway, as we do here,
3632 // therefore technically violates the C standard: two function pointer
3633 // types defined in terms of two typedef'd anonymous structs with
3634 // different names are formally still compatible, but we are assigning
3635 // them different discriminators and therefore incompatible ABIs.
3636 //
3637 // This is a relatively minor violation that significantly improves
3638 // discrimination in some cases and has not caused problems in
3639 // practice. Regardless, it is now part of the ABI in places where
3640 // function type discrimination is used, and it can no longer be
3641 // changed except on new platforms.
3642
3643 if (!II)
3644 if (const TypedefNameDecl *Typedef = RD->getTypedefNameForAnonDecl())
3645 II = Typedef->getDeclName().getAsIdentifierInfo();
3646
3647 if (!II) {
3648 OS << "<anonymous_record>";
3649 return;
3650 }
3651 OS << II->getLength() << II->getName();
3652 return;
3653 }
3654 case Type::HLSLAttributedResource:
3655 case Type::HLSLInlineSpirv:
3656 llvm_unreachable("should never get here");
3657 break;
3658 case Type::OverflowBehavior:
3659 llvm_unreachable("should never get here");
3660 break;
3661 case Type::DeducedTemplateSpecialization:
3662 case Type::Auto:
3663#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3664#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3665#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
3666#define ABSTRACT_TYPE(Class, Base)
3667#define TYPE(Class, Base)
3668#include "clang/AST/TypeNodes.inc"
3669 llvm_unreachable("unexpected non-canonical or dependent type!");
3670 return;
3671 }
3672}
3673
3674uint16_t ASTContext::getPointerAuthTypeDiscriminator(QualType T) {
3675 assert(!T->isDependentType() &&
3676 "cannot compute type discriminator of a dependent type");
3677 SmallString<256> Str;
3678 llvm::raw_svector_ostream Out(Str);
3679
3680 if (T->isFunctionPointerType() || T->isFunctionReferenceType())
3681 T = T->getPointeeType();
3682
3683 if (T->isFunctionType()) {
3684 encodeTypeForFunctionPointerAuth(Ctx: *this, OS&: Out, QT: T);
3685 } else {
3686 T = T.getUnqualifiedType();
3687 // Calls to member function pointers don't need to worry about
3688 // language interop or the laxness of the C type compatibility rules.
3689 // We just mangle the member pointer type directly, which is
3690 // implicitly much stricter about type matching. However, we do
3691 // strip any top-level exception specification before this mangling.
3692 // C++23 requires calls to work when the function type is convertible
3693 // to the pointer type by a function pointer conversion, which can
3694 // change the exception specification. This does not technically
3695 // require the exception specification to not affect representation,
3696 // because the function pointer conversion is still always a direct
3697 // value conversion and therefore an opportunity to resign the
3698 // pointer. (This is in contrast to e.g. qualification conversions,
3699 // which can be applied in nested pointer positions, effectively
3700 // requiring qualified and unqualified representations to match.)
3701 // However, it is pragmatic to ignore exception specifications
3702 // because it allows a certain amount of `noexcept` mismatching
3703 // to not become a visible ODR problem. This also leaves some
3704 // room for the committee to add laxness to function pointer
3705 // conversions in future standards.
3706 if (auto *MPT = T->getAs<MemberPointerType>())
3707 if (MPT->isMemberFunctionPointer()) {
3708 QualType PointeeType = MPT->getPointeeType();
3709 if (PointeeType->castAs<FunctionProtoType>()->getExceptionSpecType() !=
3710 EST_None) {
3711 QualType FT = getFunctionTypeWithExceptionSpec(Orig: PointeeType, ESI: EST_None);
3712 T = getMemberPointerType(T: FT, Qualifier: MPT->getQualifier(),
3713 Cls: MPT->getMostRecentCXXRecordDecl());
3714 }
3715 }
3716 std::unique_ptr<MangleContext> MC(createMangleContext());
3717 MC->mangleCanonicalTypeName(T, Out);
3718 }
3719
3720 return llvm::getPointerAuthStableSipHash(S: Str);
3721}
3722
3723QualType ASTContext::getObjCGCQualType(QualType T,
3724 Qualifiers::GC GCAttr) const {
3725 QualType CanT = getCanonicalType(T);
3726 if (CanT.getObjCGCAttr() == GCAttr)
3727 return T;
3728
3729 if (const auto *ptr = T->getAs<PointerType>()) {
3730 QualType Pointee = ptr->getPointeeType();
3731 if (Pointee->isAnyPointerType()) {
3732 QualType ResultType = getObjCGCQualType(T: Pointee, GCAttr);
3733 return getPointerType(T: ResultType);
3734 }
3735 }
3736
3737 // If we are composing extended qualifiers together, merge together
3738 // into one ExtQuals node.
3739 QualifierCollector Quals;
3740 const Type *TypeNode = Quals.strip(type: T);
3741
3742 // If this type already has an ObjCGC specified, it cannot get
3743 // another one.
3744 assert(!Quals.hasObjCGCAttr() &&
3745 "Type cannot have multiple ObjCGCs!");
3746 Quals.addObjCGCAttr(type: GCAttr);
3747
3748 return getExtQualType(baseType: TypeNode, quals: Quals);
3749}
3750
3751QualType ASTContext::removePtrSizeAddrSpace(QualType T) const {
3752 if (const PointerType *Ptr = T->getAs<PointerType>()) {
3753 QualType Pointee = Ptr->getPointeeType();
3754 if (isPtrSizeAddressSpace(AS: Pointee.getAddressSpace())) {
3755 return getPointerType(T: removeAddrSpaceQualType(T: Pointee));
3756 }
3757 }
3758 return T;
3759}
3760
3761QualType ASTContext::getCountAttributedType(
3762 QualType WrappedTy, Expr *CountExpr, bool CountInBytes, bool OrNull,
3763 ArrayRef<TypeCoupledDeclRefInfo> DependentDecls) const {
3764 assert(WrappedTy->isPointerType() || WrappedTy->isArrayType());
3765 assert(CountExpr && "use getIncompleteCountAttributedType for a null count");
3766
3767 // Complete (non-late-parsed) path: the count expression is known up front.
3768 // This deliberately preserves the pre-existing uniquing behavior -- the
3769 // FoldingSet lookup/insert below is unchanged by late-parse support. Only
3770 // getIncompleteCountAttributedType (count filled in later) opts out of
3771 // uniquing.
3772 llvm::FoldingSetNodeID ID;
3773 CountAttributedType::Profile(ID, WrappedTy, CountExpr, CountInBytes, Nullable: OrNull);
3774
3775 llvm::FoldingSetInsertToken Token;
3776 CountAttributedType *CATy = CountAttributedTypes.lookup(ID, Token);
3777 if (CATy)
3778 return QualType(CATy, 0);
3779
3780 QualType CanonTy = getCanonicalType(T: WrappedTy);
3781 CATy = CountAttributedType::Create(Ctx: *this, Wrapped: WrappedTy, Canon: CanonTy, CountExpr,
3782 CountInBytes, OrNull, CoupledDecls: DependentDecls);
3783 Types.push_back(Elt: CATy);
3784 CountAttributedTypes.insert(N: CATy, Token);
3785
3786 return QualType(CATy, 0);
3787}
3788
3789CountAttributedType *ASTContext::getIncompleteCountAttributedType(
3790 QualType WrappedTy, bool CountInBytes, bool OrNull) const {
3791 assert(WrappedTy->isPointerType() || WrappedTy->isArrayType());
3792
3793 // Deliberately opts out of the uniquing that `getCountAttributedType` does:
3794 // `CountAttributedType::Profile` keys on the `CountExpr` pointer, which is
3795 // null here, so every incomplete node would profile identically as
3796 // `(WrappedTy, flags, nullptr)` and two fields with different counts would
3797 // collide. The node stays un-uniqued even after completion; see
3798 // `completeCountAttributedType`.
3799 //
3800 // Also deliberately not in `Types` yet. An incomplete node can be abandoned
3801 // without ever being completed (a nested counted_by, or an argument that
3802 // fails to parse), and a null-count node must not be reachable by anything
3803 // that scans `Types`. `completeCountAttributedType` registers it once the
3804 // count is in place.
3805 return CountAttributedType::Create(
3806 Ctx: *this, Wrapped: WrappedTy, Canon: getCanonicalType(T: WrappedTy),
3807 /*CountExpr=*/nullptr, CountInBytes, OrNull,
3808 /*CoupledDecls=*/{});
3809}
3810
3811void ASTContext::completeCountAttributedType(
3812 CountAttributedType *CATy, Expr *CountExpr,
3813 ArrayRef<TypeCoupledDeclRefInfo> DependentDecls) const {
3814 CATy->complete(Ctx: *this, E: CountExpr, CoupledDecls: DependentDecls);
3815 // Safe for `Types` scanners now that the count is in place; see
3816 // `getIncompleteCountAttributedType` for why it was held back.
3817 //
3818 // It stays out of the `CountAttributedTypes` FoldingSet permanently, unlike
3819 // an eagerly built node: this pointer is already embedded in the enclosing
3820 // types and handed out, so an equal node that happens to exist cannot be
3821 // merged into. The only cost is that a completed node is never
3822 // pointer-shared with an equal eager one, which does not affect semantic
3823 // type equality -- `hasSameType` compares canonical types, and this sugar's
3824 // canonical type is the wrapped type's.
3825 Types.push_back(Elt: CATy);
3826}
3827
3828QualType ASTContext::getLateParsedAttrType(
3829 QualType WrappedTy, LateParsedTypeAttribute *LateParsedAttr) const {
3830 QualType CanonTy = getCanonicalType(T: WrappedTy);
3831
3832 auto *LPATy = new (*this, alignof(LateParsedAttrType))
3833 LateParsedAttrType(WrappedTy, CanonTy, LateParsedAttr);
3834
3835 Types.push_back(Elt: LPATy);
3836 return QualType(LPATy, 0);
3837}
3838
3839QualType
3840ASTContext::adjustType(QualType Orig,
3841 llvm::function_ref<QualType(QualType)> Adjust) const {
3842 switch (Orig->getTypeClass()) {
3843 case Type::Attributed: {
3844 const auto *AT = cast<AttributedType>(Val&: Orig);
3845 return getAttributedType(attrKind: AT->getAttrKind(),
3846 modifiedType: adjustType(Orig: AT->getModifiedType(), Adjust),
3847 equivalentType: adjustType(Orig: AT->getEquivalentType(), Adjust),
3848 attr: AT->getAttr());
3849 }
3850
3851 case Type::BTFTagAttributed: {
3852 const auto *BTFT = dyn_cast<BTFTagAttributedType>(Val&: Orig);
3853 return getBTFTagAttributedType(BTFAttr: BTFT->getAttr(),
3854 Wrapped: adjustType(Orig: BTFT->getWrappedType(), Adjust));
3855 }
3856
3857 case Type::OverflowBehavior: {
3858 const auto *OB = dyn_cast<OverflowBehaviorType>(Val&: Orig);
3859 return getOverflowBehaviorType(Kind: OB->getBehaviorKind(),
3860 Wrapped: adjustType(Orig: OB->getUnderlyingType(), Adjust));
3861 }
3862
3863 case Type::Paren:
3864 return getParenType(
3865 NamedType: adjustType(Orig: cast<ParenType>(Val&: Orig)->getInnerType(), Adjust));
3866
3867 case Type::Adjusted: {
3868 const auto *AT = cast<AdjustedType>(Val&: Orig);
3869 return getAdjustedType(Orig: AT->getOriginalType(),
3870 New: adjustType(Orig: AT->getAdjustedType(), Adjust));
3871 }
3872
3873 case Type::MacroQualified: {
3874 const auto *MQT = cast<MacroQualifiedType>(Val&: Orig);
3875 return getMacroQualifiedType(UnderlyingTy: adjustType(Orig: MQT->getUnderlyingType(), Adjust),
3876 MacroII: MQT->getMacroIdentifier());
3877 }
3878
3879 default:
3880 return Adjust(Orig);
3881 }
3882}
3883
3884const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
3885 FunctionType::ExtInfo Info) {
3886 if (T->getExtInfo() == Info)
3887 return T;
3888
3889 QualType Result;
3890 if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(Val: T)) {
3891 Result = getFunctionNoProtoType(ResultTy: FNPT->getReturnType(), Info);
3892 } else {
3893 const auto *FPT = cast<FunctionProtoType>(Val: T);
3894 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
3895 EPI.ExtInfo = Info;
3896 Result = getFunctionType(ResultTy: FPT->getReturnType(), Args: FPT->getParamTypes(), EPI);
3897 }
3898
3899 return cast<FunctionType>(Val: Result.getTypePtr());
3900}
3901
3902QualType ASTContext::adjustFunctionResultType(QualType FunctionType,
3903 QualType ResultType) {
3904 return adjustType(Orig: FunctionType, Adjust: [&](QualType Orig) {
3905 if (const auto *FNPT = Orig->getAs<FunctionNoProtoType>())
3906 return getFunctionNoProtoType(ResultTy: ResultType, Info: FNPT->getExtInfo());
3907
3908 const auto *FPT = Orig->castAs<FunctionProtoType>();
3909 return getFunctionType(ResultTy: ResultType, Args: FPT->getParamTypes(),
3910 EPI: FPT->getExtProtoInfo());
3911 });
3912}
3913
3914void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
3915 QualType ResultType) {
3916 FD = FD->getMostRecentDecl();
3917 while (true) {
3918 FD->setType(adjustFunctionResultType(FunctionType: FD->getType(), ResultType));
3919 if (FunctionDecl *Next = FD->getPreviousDecl())
3920 FD = Next;
3921 else
3922 break;
3923 }
3924 if (ASTMutationListener *L = getASTMutationListener())
3925 L->DeducedReturnType(FD, ReturnType: ResultType);
3926}
3927
3928/// Get a function type and produce the equivalent function type with the
3929/// specified exception specification. Type sugar that can be present on a
3930/// declaration of a function with an exception specification is permitted
3931/// and preserved. Other type sugar (for instance, typedefs) is not.
3932QualType ASTContext::getFunctionTypeWithExceptionSpec(
3933 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) const {
3934 return adjustType(Orig, Adjust: [&](QualType Ty) {
3935 const auto *Proto = Ty->castAs<FunctionProtoType>();
3936 return getFunctionType(ResultTy: Proto->getReturnType(), Args: Proto->getParamTypes(),
3937 EPI: Proto->getExtProtoInfo().withExceptionSpec(ESI));
3938 });
3939}
3940
3941bool ASTContext::hasSameFunctionTypeIgnoringExceptionSpec(QualType T,
3942 QualType U) const {
3943 return hasSameType(T1: T, T2: U) ||
3944 (getLangOpts().CPlusPlus17 &&
3945 hasSameType(T1: getFunctionTypeWithExceptionSpec(Orig: T, ESI: EST_None),
3946 T2: getFunctionTypeWithExceptionSpec(Orig: U, ESI: EST_None)));
3947}
3948
3949QualType ASTContext::getFunctionTypeWithoutPtrSizes(QualType T) {
3950 if (const auto *Proto = T->getAs<FunctionProtoType>()) {
3951 QualType RetTy = removePtrSizeAddrSpace(T: Proto->getReturnType());
3952 SmallVector<QualType, 16> Args(Proto->param_types().size());
3953 for (unsigned i = 0, n = Args.size(); i != n; ++i)
3954 Args[i] = removePtrSizeAddrSpace(T: Proto->param_types()[i]);
3955 return getFunctionType(ResultTy: RetTy, Args, EPI: Proto->getExtProtoInfo());
3956 }
3957
3958 if (const FunctionNoProtoType *Proto = T->getAs<FunctionNoProtoType>()) {
3959 QualType RetTy = removePtrSizeAddrSpace(T: Proto->getReturnType());
3960 return getFunctionNoProtoType(ResultTy: RetTy, Info: Proto->getExtInfo());
3961 }
3962
3963 return T;
3964}
3965
3966bool ASTContext::hasSameFunctionTypeIgnoringPtrSizes(QualType T, QualType U) {
3967 return hasSameType(T1: T, T2: U) ||
3968 hasSameType(T1: getFunctionTypeWithoutPtrSizes(T),
3969 T2: getFunctionTypeWithoutPtrSizes(T: U));
3970}
3971
3972QualType ASTContext::getFunctionTypeWithoutParamABIs(QualType T) const {
3973 if (const auto *Proto = T->getAs<FunctionProtoType>()) {
3974 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3975 EPI.ExtParameterInfos = nullptr;
3976 return getFunctionType(ResultTy: Proto->getReturnType(), Args: Proto->param_types(), EPI);
3977 }
3978 return T;
3979}
3980
3981bool ASTContext::hasSameFunctionTypeIgnoringParamABI(QualType T,
3982 QualType U) const {
3983 return hasSameType(T1: T, T2: U) || hasSameType(T1: getFunctionTypeWithoutParamABIs(T),
3984 T2: getFunctionTypeWithoutParamABIs(T: U));
3985}
3986
3987void ASTContext::adjustExceptionSpec(
3988 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
3989 bool AsWritten) {
3990 // Update the type.
3991 QualType Updated =
3992 getFunctionTypeWithExceptionSpec(Orig: FD->getType(), ESI);
3993 FD->setType(Updated);
3994
3995 if (!AsWritten)
3996 return;
3997
3998 // Update the type in the type source information too.
3999 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
4000 // If the type and the type-as-written differ, we may need to update
4001 // the type-as-written too.
4002 if (TSInfo->getType() != FD->getType())
4003 Updated = getFunctionTypeWithExceptionSpec(Orig: TSInfo->getType(), ESI);
4004
4005 // FIXME: When we get proper type location information for exceptions,
4006 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
4007 // up the TypeSourceInfo;
4008 assert(TypeLoc::getFullDataSizeForType(Updated) ==
4009 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
4010 "TypeLoc size mismatch from updating exception specification");
4011 TSInfo->overrideType(T: Updated);
4012 }
4013}
4014
4015/// getComplexType - Return the uniqued reference to the type for a complex
4016/// number with the specified element type.
4017QualType ASTContext::getComplexType(QualType T) const {
4018 // Unique pointers, to guarantee there is only one pointer of a particular
4019 // structure.
4020 llvm::FoldingSetInsertToken Token;
4021 if (ComplexType *CT = ComplexTypes.lookup(Key: T, Token))
4022 return QualType(CT, 0);
4023
4024 // If the pointee type isn't canonical, this won't be a canonical type either,
4025 // so fill in the canonical type field.
4026 QualType Canonical;
4027 if (!T.isCanonical()) {
4028 Canonical = getComplexType(T: getCanonicalType(T));
4029
4030 assert(!ComplexTypes.lookup(T, Token) && "Shouldn't be in the map!");
4031 }
4032 auto *New = new (*this, alignof(ComplexType)) ComplexType(T, Canonical);
4033 Types.push_back(Elt: New);
4034 ComplexTypes.insert(N: New, Token);
4035 return QualType(New, 0);
4036}
4037
4038/// getPointerType - Return the uniqued reference to the type for a pointer to
4039/// the specified type.
4040QualType ASTContext::getPointerType(QualType T) const {
4041 // Unique pointers, to guarantee there is only one pointer of a particular
4042 // structure.
4043 llvm::FoldingSetInsertToken Token;
4044 if (PointerType *PT = PointerTypes.lookup(Key: T, Token))
4045 return QualType(PT, 0);
4046
4047 // If the pointee type isn't canonical, this won't be a canonical type either,
4048 // so fill in the canonical type field.
4049 QualType Canonical;
4050 if (!T.isCanonical()) {
4051 Canonical = getPointerType(T: getCanonicalType(T));
4052
4053 assert(!PointerTypes.lookup(T, Token) && "Shouldn't be in the map!");
4054 }
4055 auto *New = new (*this, alignof(PointerType)) PointerType(T, Canonical);
4056 Types.push_back(Elt: New);
4057 PointerTypes.insert(N: New, Token);
4058 return QualType(New, 0);
4059}
4060
4061QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
4062 llvm::FoldingSetInsertToken Token;
4063 AdjustedType *AT = AdjustedTypes.lookup(Key: {Orig, New}, Token);
4064 if (AT)
4065 return QualType(AT, 0);
4066
4067 QualType Canonical = getCanonicalType(T: New);
4068
4069 AT = new (*this, alignof(AdjustedType))
4070 AdjustedType(Type::Adjusted, Orig, New, Canonical);
4071 Types.push_back(Elt: AT);
4072 AdjustedTypes.insert(N: AT, Token);
4073 return QualType(AT, 0);
4074}
4075
4076QualType ASTContext::getDecayedType(QualType Orig, QualType Decayed) const {
4077 llvm::FoldingSetInsertToken Token;
4078 AdjustedType *AT = AdjustedTypes.lookup(Key: {Orig, Decayed}, Token);
4079 if (AT)
4080 return QualType(AT, 0);
4081
4082 QualType Canonical = getCanonicalType(T: Decayed);
4083
4084 AT = new (*this, alignof(DecayedType)) DecayedType(Orig, Decayed, Canonical);
4085 Types.push_back(Elt: AT);
4086 AdjustedTypes.insert(N: AT, Token);
4087 return QualType(AT, 0);
4088}
4089
4090QualType ASTContext::getDecayedType(QualType T) const {
4091 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
4092
4093 QualType Decayed;
4094
4095 // C99 6.7.5.3p7:
4096 // A declaration of a parameter as "array of type" shall be
4097 // adjusted to "qualified pointer to type", where the type
4098 // qualifiers (if any) are those specified within the [ and ] of
4099 // the array type derivation.
4100 if (T->isArrayType())
4101 Decayed = getArrayDecayedType(T);
4102
4103 // C99 6.7.5.3p8:
4104 // A declaration of a parameter as "function returning type"
4105 // shall be adjusted to "pointer to function returning type", as
4106 // in 6.3.2.1.
4107 if (T->isFunctionType())
4108 Decayed = getPointerType(T);
4109
4110 return getDecayedType(Orig: T, Decayed);
4111}
4112
4113QualType ASTContext::getArrayParameterType(QualType Ty) const {
4114 if (Ty->isArrayParameterType())
4115 return Ty;
4116 assert(Ty->isConstantArrayType() && "Ty must be an array type.");
4117 QualType DTy = Ty.getDesugaredType(Context: *this);
4118 const auto *ATy = cast<ConstantArrayType>(Val&: DTy);
4119 llvm::FoldingSetNodeID ID;
4120 ATy->Profile(ID, Ctx: *this, ET: ATy->getElementType(), ArraySize: ATy->getZExtSize(),
4121 SizeExpr: ATy->getSizeExpr(), SizeMod: ATy->getSizeModifier(),
4122 TypeQuals: ATy->getIndexTypeQualifiers().getAsOpaqueValue());
4123 llvm::FoldingSetInsertToken Token;
4124 ArrayParameterType *AT = ArrayParameterTypes.lookup(ID, Token);
4125 if (AT)
4126 return QualType(AT, 0);
4127
4128 QualType Canonical;
4129 if (!DTy.isCanonical()) {
4130 Canonical = getArrayParameterType(Ty: getCanonicalType(T: Ty));
4131
4132 // Get the new insert position for the node we care about.
4133 AT = ArrayParameterTypes.lookup(ID, Token);
4134 assert(!AT && "Shouldn't be in the map!");
4135 }
4136
4137 AT = new (*this, alignof(ArrayParameterType))
4138 ArrayParameterType(ATy, Canonical);
4139 Types.push_back(Elt: AT);
4140 ArrayParameterTypes.insert(N: AT, Token);
4141 return QualType(AT, 0);
4142}
4143
4144/// getBlockPointerType - Return the uniqued reference to the type for
4145/// a pointer to the specified block.
4146QualType ASTContext::getBlockPointerType(QualType T) const {
4147 assert(T->isFunctionType() && "block of function types only");
4148 // Unique pointers, to guarantee there is only one block of a particular
4149 // structure.
4150 llvm::FoldingSetInsertToken Token;
4151 if (BlockPointerType *PT = BlockPointerTypes.lookup(Key: T, Token))
4152 return QualType(PT, 0);
4153
4154 // If the block pointee type isn't canonical, this won't be a canonical
4155 // type either so fill in the canonical type field.
4156 QualType Canonical;
4157 if (!T.isCanonical()) {
4158 Canonical = getBlockPointerType(T: getCanonicalType(T));
4159
4160 assert(!BlockPointerTypes.lookup(T, Token) && "Shouldn't be in the map!");
4161 }
4162 auto *New =
4163 new (*this, alignof(BlockPointerType)) BlockPointerType(T, Canonical);
4164 Types.push_back(Elt: New);
4165 BlockPointerTypes.insert(N: New, Token);
4166 return QualType(New, 0);
4167}
4168
4169/// getLValueReferenceType - Return the uniqued reference to the type for an
4170/// lvalue reference to the specified type.
4171QualType
4172ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
4173 assert((!T->isPlaceholderType() ||
4174 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
4175 "Unresolved placeholder type");
4176
4177 // Unique pointers, to guarantee there is only one pointer of a particular
4178 // structure.
4179 llvm::FoldingSetInsertToken Token;
4180 if (LValueReferenceType *RT =
4181 LValueReferenceTypes.lookup(Key: {T, SpelledAsLValue}, Token))
4182 return QualType(RT, 0);
4183
4184 const auto *InnerRef = T->getAs<ReferenceType>();
4185
4186 // If the referencee type isn't canonical, this won't be a canonical type
4187 // either, so fill in the canonical type field.
4188 QualType Canonical;
4189 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
4190 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
4191 Canonical = getLValueReferenceType(T: getCanonicalType(T: PointeeType));
4192
4193 assert(!LValueReferenceTypes.lookup({T, SpelledAsLValue}, Token) &&
4194 "Shouldn't be in the map!");
4195 }
4196
4197 auto *New = new (*this, alignof(LValueReferenceType))
4198 LValueReferenceType(T, Canonical, SpelledAsLValue);
4199 Types.push_back(Elt: New);
4200 LValueReferenceTypes.insert(N: New, Token);
4201
4202 return QualType(New, 0);
4203}
4204
4205/// getRValueReferenceType - Return the uniqued reference to the type for an
4206/// rvalue reference to the specified type.
4207QualType ASTContext::getRValueReferenceType(QualType T) const {
4208 assert((!T->isPlaceholderType() ||
4209 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
4210 "Unresolved placeholder type");
4211
4212 // Unique pointers, to guarantee there is only one pointer of a particular
4213 // structure.
4214 llvm::FoldingSetInsertToken Token;
4215 if (RValueReferenceType *RT = RValueReferenceTypes.lookup(Key: {T, false}, Token))
4216 return QualType(RT, 0);
4217
4218 const auto *InnerRef = T->getAs<ReferenceType>();
4219
4220 // If the referencee type isn't canonical, this won't be a canonical type
4221 // either, so fill in the canonical type field.
4222 QualType Canonical;
4223 if (InnerRef || !T.isCanonical()) {
4224 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
4225 Canonical = getRValueReferenceType(T: getCanonicalType(T: PointeeType));
4226
4227 assert(!RValueReferenceTypes.lookup({T, false}, Token) &&
4228 "Shouldn't be in the map!");
4229 }
4230
4231 auto *New = new (*this, alignof(RValueReferenceType))
4232 RValueReferenceType(T, Canonical);
4233 Types.push_back(Elt: New);
4234 RValueReferenceTypes.insert(N: New, Token);
4235 return QualType(New, 0);
4236}
4237
4238QualType ASTContext::getMemberPointerType(QualType T,
4239 NestedNameSpecifier Qualifier,
4240 const CXXRecordDecl *Cls) const {
4241 if (!Qualifier) {
4242 assert(Cls && "At least one of Qualifier or Cls must be provided");
4243 Qualifier = NestedNameSpecifier(getCanonicalTagType(TD: Cls).getTypePtr());
4244 } else if (!Cls) {
4245 Cls = Qualifier.getAsRecordDecl();
4246 }
4247 // Unique pointers, to guarantee there is only one pointer of a particular
4248 // structure.
4249 llvm::FoldingSetNodeID ID;
4250 MemberPointerType::Profile(ID, Pointee: T, Qualifier, Cls);
4251
4252 llvm::FoldingSetInsertToken Token;
4253 if (MemberPointerType *PT = MemberPointerTypes.lookup(ID, Token))
4254 return QualType(PT, 0);
4255
4256 NestedNameSpecifier CanonicalQualifier = [&] {
4257 if (!Cls)
4258 return Qualifier.getCanonical();
4259 NestedNameSpecifier R(getCanonicalTagType(TD: Cls).getTypePtr());
4260 assert(R.isCanonical());
4261 return R;
4262 }();
4263 // If the pointee or class type isn't canonical, this won't be a canonical
4264 // type either, so fill in the canonical type field.
4265 QualType Canonical;
4266 if (!T.isCanonical() || Qualifier != CanonicalQualifier) {
4267 Canonical =
4268 getMemberPointerType(T: getCanonicalType(T), Qualifier: CanonicalQualifier, Cls);
4269 assert(!cast<MemberPointerType>(Canonical)->isSugared());
4270 // Get the new insert position for the node we care about.
4271 [[maybe_unused]] MemberPointerType *NewIP =
4272 MemberPointerTypes.lookup(ID, Token);
4273 assert(!NewIP && "Shouldn't be in the map!");
4274 }
4275 auto *New = new (*this, alignof(MemberPointerType))
4276 MemberPointerType(T, Qualifier, Canonical);
4277 Types.push_back(Elt: New);
4278 MemberPointerTypes.insert(N: New, Token);
4279 return QualType(New, 0);
4280}
4281
4282/// getConstantArrayType - Return the unique reference to the type for an
4283/// array of the specified element type.
4284QualType ASTContext::getConstantArrayType(QualType EltTy,
4285 const llvm::APInt &ArySizeIn,
4286 const Expr *SizeExpr,
4287 ArraySizeModifier ASM,
4288 unsigned IndexTypeQuals) const {
4289 assert((EltTy->isDependentType() ||
4290 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
4291 "Constant array of VLAs is illegal!");
4292
4293 // We only need the size as part of the type if it's instantiation-dependent.
4294 if (SizeExpr && !SizeExpr->isInstantiationDependent())
4295 SizeExpr = nullptr;
4296
4297 // Convert the array size into a canonical width matching the pointer size for
4298 // the target.
4299 llvm::APInt ArySize(ArySizeIn);
4300 ArySize = ArySize.zextOrTrunc(width: Target->getMaxPointerWidth());
4301
4302 llvm::FoldingSetNodeID ID;
4303 ConstantArrayType::Profile(ID, Ctx: *this, ET: EltTy, ArraySize: ArySize.getZExtValue(), SizeExpr,
4304 SizeMod: ASM, TypeQuals: IndexTypeQuals);
4305
4306 llvm::FoldingSetInsertToken Token;
4307 if (ConstantArrayType *ATP = ConstantArrayTypes.lookup(ID, Token))
4308 return QualType(ATP, 0);
4309
4310 // If the element type isn't canonical or has qualifiers, or the array bound
4311 // is instantiation-dependent, this won't be a canonical type either, so fill
4312 // in the canonical type field.
4313 QualType Canon;
4314 // FIXME: Check below should look for qualifiers behind sugar.
4315 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers() || SizeExpr) {
4316 SplitQualType canonSplit = getCanonicalType(T: EltTy).split();
4317 Canon = getConstantArrayType(EltTy: QualType(canonSplit.Ty, 0), ArySizeIn: ArySize, SizeExpr: nullptr,
4318 ASM, IndexTypeQuals);
4319 Canon = getQualifiedType(T: Canon, Qs: canonSplit.Quals);
4320
4321 // Get the new insert position for the node we care about.
4322 ConstantArrayType *NewIP = ConstantArrayTypes.lookup(ID, Token);
4323 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4324 }
4325
4326 auto *New = ConstantArrayType::Create(Ctx: *this, ET: EltTy, Can: Canon, Sz: ArySize, SzExpr: SizeExpr,
4327 SzMod: ASM, Qual: IndexTypeQuals);
4328 ConstantArrayTypes.insert(N: New, Token);
4329 Types.push_back(Elt: New);
4330 return QualType(New, 0);
4331}
4332
4333/// getVariableArrayDecayedType - Turns the given type, which may be
4334/// variably-modified, into the corresponding type with all the known
4335/// sizes replaced with [*].
4336QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
4337 // Vastly most common case.
4338 if (!type->isVariablyModifiedType()) return type;
4339
4340 QualType result;
4341
4342 SplitQualType split = type.getSplitDesugaredType();
4343 const Type *ty = split.Ty;
4344 switch (ty->getTypeClass()) {
4345#define TYPE(Class, Base)
4346#define ABSTRACT_TYPE(Class, Base)
4347#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4348#include "clang/AST/TypeNodes.inc"
4349 llvm_unreachable("didn't desugar past all non-canonical types?");
4350
4351 // These types should never be variably-modified.
4352 case Type::Builtin:
4353 case Type::Complex:
4354 case Type::Vector:
4355 case Type::DependentVector:
4356 case Type::ExtVector:
4357 case Type::DependentSizedExtVector:
4358 case Type::ConstantMatrix:
4359 case Type::DependentSizedMatrix:
4360 case Type::DependentAddressSpace:
4361 case Type::ObjCObject:
4362 case Type::ObjCInterface:
4363 case Type::ObjCObjectPointer:
4364 case Type::Record:
4365 case Type::Enum:
4366 case Type::UnresolvedUsing:
4367 case Type::TypeOfExpr:
4368 case Type::TypeOf:
4369 case Type::Decltype:
4370 case Type::UnaryTransform:
4371 case Type::DependentName:
4372 case Type::InjectedClassName:
4373 case Type::TemplateSpecialization:
4374 case Type::TemplateTypeParm:
4375 case Type::SubstTemplateTypeParmPack:
4376 case Type::SubstBuiltinTemplatePack:
4377 case Type::Auto:
4378 case Type::DeducedTemplateSpecialization:
4379 case Type::PackExpansion:
4380 case Type::PackIndexing:
4381 case Type::BitInt:
4382 case Type::DependentBitInt:
4383 case Type::ArrayParameter:
4384 case Type::HLSLAttributedResource:
4385 case Type::HLSLInlineSpirv:
4386 case Type::OverflowBehavior:
4387 llvm_unreachable("type should never be variably-modified");
4388
4389 // These types can be variably-modified but should never need to
4390 // further decay.
4391 case Type::FunctionNoProto:
4392 case Type::FunctionProto:
4393 case Type::BlockPointer:
4394 case Type::MemberPointer:
4395 case Type::Pipe:
4396 return type;
4397
4398 // These types can be variably-modified. All these modifications
4399 // preserve structure except as noted by comments.
4400 // TODO: if we ever care about optimizing VLAs, there are no-op
4401 // optimizations available here.
4402 case Type::Pointer:
4403 result = getPointerType(T: getVariableArrayDecayedType(
4404 type: cast<PointerType>(Val: ty)->getPointeeType()));
4405 break;
4406
4407 case Type::LValueReference: {
4408 const auto *lv = cast<LValueReferenceType>(Val: ty);
4409 result = getLValueReferenceType(
4410 T: getVariableArrayDecayedType(type: lv->getPointeeType()),
4411 SpelledAsLValue: lv->isSpelledAsLValue());
4412 break;
4413 }
4414
4415 case Type::RValueReference: {
4416 const auto *lv = cast<RValueReferenceType>(Val: ty);
4417 result = getRValueReferenceType(
4418 T: getVariableArrayDecayedType(type: lv->getPointeeType()));
4419 break;
4420 }
4421
4422 case Type::Atomic: {
4423 const auto *at = cast<AtomicType>(Val: ty);
4424 result = getAtomicType(T: getVariableArrayDecayedType(type: at->getValueType()));
4425 break;
4426 }
4427
4428 case Type::ConstantArray: {
4429 const auto *cat = cast<ConstantArrayType>(Val: ty);
4430 result = getConstantArrayType(
4431 EltTy: getVariableArrayDecayedType(type: cat->getElementType()),
4432 ArySizeIn: cat->getSize(),
4433 SizeExpr: cat->getSizeExpr(),
4434 ASM: cat->getSizeModifier(),
4435 IndexTypeQuals: cat->getIndexTypeCVRQualifiers());
4436 break;
4437 }
4438
4439 case Type::DependentSizedArray: {
4440 const auto *dat = cast<DependentSizedArrayType>(Val: ty);
4441 result = getDependentSizedArrayType(
4442 EltTy: getVariableArrayDecayedType(type: dat->getElementType()), NumElts: dat->getSizeExpr(),
4443 ASM: dat->getSizeModifier(), IndexTypeQuals: dat->getIndexTypeCVRQualifiers());
4444 break;
4445 }
4446
4447 // Turn incomplete types into [*] types.
4448 case Type::IncompleteArray: {
4449 const auto *iat = cast<IncompleteArrayType>(Val: ty);
4450 result =
4451 getVariableArrayType(EltTy: getVariableArrayDecayedType(type: iat->getElementType()),
4452 /*size*/ NumElts: nullptr, ASM: ArraySizeModifier::Normal,
4453 IndexTypeQuals: iat->getIndexTypeCVRQualifiers());
4454 break;
4455 }
4456
4457 // Turn VLA types into [*] types.
4458 case Type::VariableArray: {
4459 const auto *vat = cast<VariableArrayType>(Val: ty);
4460 result =
4461 getVariableArrayType(EltTy: getVariableArrayDecayedType(type: vat->getElementType()),
4462 /*size*/ NumElts: nullptr, ASM: ArraySizeModifier::Star,
4463 IndexTypeQuals: vat->getIndexTypeCVRQualifiers());
4464 break;
4465 }
4466 }
4467
4468 // Apply the top-level qualifiers from the original.
4469 return getQualifiedType(T: result, Qs: split.Quals);
4470}
4471
4472/// getVariableArrayType - Returns a non-unique reference to the type for a
4473/// variable array of the specified element type.
4474QualType ASTContext::getVariableArrayType(QualType EltTy, Expr *NumElts,
4475 ArraySizeModifier ASM,
4476 unsigned IndexTypeQuals) const {
4477 // Since we don't unique expressions, it isn't possible to unique VLA's
4478 // that have an expression provided for their size.
4479 QualType Canon;
4480
4481 // Be sure to pull qualifiers off the element type.
4482 // FIXME: Check below should look for qualifiers behind sugar.
4483 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
4484 SplitQualType canonSplit = getCanonicalType(T: EltTy).split();
4485 Canon = getVariableArrayType(EltTy: QualType(canonSplit.Ty, 0), NumElts, ASM,
4486 IndexTypeQuals);
4487 Canon = getQualifiedType(T: Canon, Qs: canonSplit.Quals);
4488 }
4489
4490 auto *New = new (*this, alignof(VariableArrayType))
4491 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals);
4492
4493 VariableArrayTypes.push_back(x: New);
4494 Types.push_back(Elt: New);
4495 return QualType(New, 0);
4496}
4497
4498/// getDependentSizedArrayType - Returns a non-unique reference to
4499/// the type for a dependently-sized array of the specified element
4500/// type.
4501QualType
4502ASTContext::getDependentSizedArrayType(QualType elementType, Expr *numElements,
4503 ArraySizeModifier ASM,
4504 unsigned elementTypeQuals) const {
4505 assert((!numElements || numElements->isTypeDependent() ||
4506 numElements->isValueDependent()) &&
4507 "Size must be type- or value-dependent!");
4508
4509 SplitQualType canonElementType = getCanonicalType(T: elementType).split();
4510
4511 llvm::FoldingSetInsertToken Token;
4512 llvm::FoldingSetNodeID ID;
4513 DependentSizedArrayType::Profile(
4514 ID, Context: *this, ET: numElements ? QualType(canonElementType.Ty, 0) : elementType,
4515 SizeMod: ASM, TypeQuals: elementTypeQuals, E: numElements);
4516
4517 // Look for an existing type with these properties.
4518 DependentSizedArrayType *canonTy = DependentSizedArrayTypes.lookup(ID, Token);
4519
4520 // Dependently-sized array types that do not have a specified number
4521 // of elements will have their sizes deduced from a dependent
4522 // initializer.
4523 if (!numElements) {
4524 if (canonTy)
4525 return QualType(canonTy, 0);
4526
4527 auto *newType = new (*this, alignof(DependentSizedArrayType))
4528 DependentSizedArrayType(elementType, QualType(), numElements, ASM,
4529 elementTypeQuals);
4530 DependentSizedArrayTypes.insert(N: newType, Token);
4531 Types.push_back(Elt: newType);
4532 return QualType(newType, 0);
4533 }
4534
4535 // If we don't have one, build one.
4536 if (!canonTy) {
4537 canonTy = new (*this, alignof(DependentSizedArrayType))
4538 DependentSizedArrayType(QualType(canonElementType.Ty, 0), QualType(),
4539 numElements, ASM, elementTypeQuals);
4540 DependentSizedArrayTypes.insert(N: canonTy, Token);
4541 Types.push_back(Elt: canonTy);
4542 }
4543
4544 // Apply qualifiers from the element type to the array.
4545 QualType canon = getQualifiedType(T: QualType(canonTy,0),
4546 Qs: canonElementType.Quals);
4547
4548 // If we didn't need extra canonicalization for the element type or the size
4549 // expression, then just use that as our result.
4550 if (QualType(canonElementType.Ty, 0) == elementType &&
4551 canonTy->getSizeExpr() == numElements)
4552 return canon;
4553
4554 // Otherwise, we need to build a type which follows the spelling
4555 // of the element type.
4556 auto *sugaredType = new (*this, alignof(DependentSizedArrayType))
4557 DependentSizedArrayType(elementType, canon, numElements, ASM,
4558 elementTypeQuals);
4559 Types.push_back(Elt: sugaredType);
4560 return QualType(sugaredType, 0);
4561}
4562
4563QualType ASTContext::getIncompleteArrayType(QualType elementType,
4564 ArraySizeModifier ASM,
4565 unsigned elementTypeQuals) const {
4566 llvm::FoldingSetNodeID ID;
4567 IncompleteArrayType::Profile(ID, ET: elementType, SizeMod: ASM, TypeQuals: elementTypeQuals);
4568
4569 llvm::FoldingSetInsertToken Token;
4570 if (IncompleteArrayType *iat = IncompleteArrayTypes.lookup(ID, Token))
4571 return QualType(iat, 0);
4572
4573 // If the element type isn't canonical, this won't be a canonical type
4574 // either, so fill in the canonical type field. We also have to pull
4575 // qualifiers off the element type.
4576 QualType canon;
4577
4578 // FIXME: Check below should look for qualifiers behind sugar.
4579 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
4580 SplitQualType canonSplit = getCanonicalType(T: elementType).split();
4581 canon = getIncompleteArrayType(elementType: QualType(canonSplit.Ty, 0),
4582 ASM, elementTypeQuals);
4583 canon = getQualifiedType(T: canon, Qs: canonSplit.Quals);
4584
4585 // Get the new insert position for the node we care about.
4586 IncompleteArrayType *existing = IncompleteArrayTypes.lookup(ID, Token);
4587 assert(!existing && "Shouldn't be in the map!"); (void) existing;
4588 }
4589
4590 auto *newType = new (*this, alignof(IncompleteArrayType))
4591 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
4592
4593 IncompleteArrayTypes.insert(N: newType, Token);
4594 Types.push_back(Elt: newType);
4595 return QualType(newType, 0);
4596}
4597
4598ASTContext::BuiltinVectorTypeInfo
4599ASTContext::getBuiltinVectorTypeInfo(const BuiltinType *Ty) const {
4600#define SVE_INT_ELTTY(BITS, ELTS, SIGNED, NUMVECTORS) \
4601 {getIntTypeForBitwidth(BITS, SIGNED), llvm::ElementCount::getScalable(ELTS), \
4602 NUMVECTORS};
4603
4604#define SVE_ELTTY(ELTTY, ELTS, NUMVECTORS) \
4605 {ELTTY, llvm::ElementCount::getScalable(ELTS), NUMVECTORS};
4606
4607 switch (Ty->getKind()) {
4608 default:
4609 llvm_unreachable("Unsupported builtin vector type");
4610
4611#define SVE_VECTOR_TYPE_INT(Name, MangledName, Id, SingletonId, NumEls, \
4612 ElBits, NF, IsSigned) \
4613 case BuiltinType::Id: \
4614 return {getIntTypeForBitwidth(ElBits, IsSigned), \
4615 llvm::ElementCount::getScalable(NumEls), NF};
4616#define SVE_VECTOR_TYPE_FLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4617 ElBits, NF) \
4618 case BuiltinType::Id: \
4619 return {ElBits == 16 ? HalfTy : (ElBits == 32 ? FloatTy : DoubleTy), \
4620 llvm::ElementCount::getScalable(NumEls), NF};
4621#define SVE_VECTOR_TYPE_BFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4622 ElBits, NF) \
4623 case BuiltinType::Id: \
4624 return {BFloat16Ty, llvm::ElementCount::getScalable(NumEls), NF};
4625#define SVE_VECTOR_TYPE_MFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4626 ElBits, NF) \
4627 case BuiltinType::Id: \
4628 return {MFloat8Ty, llvm::ElementCount::getScalable(NumEls), NF};
4629#define SVE_PREDICATE_TYPE_ALL(Name, MangledName, Id, SingletonId, NumEls, NF) \
4630 case BuiltinType::Id: \
4631 return {BoolTy, llvm::ElementCount::getScalable(NumEls), NF};
4632#include "clang/Basic/AArch64ACLETypes.def"
4633
4634#define RVV_VECTOR_TYPE_INT(Name, Id, SingletonId, NumEls, ElBits, NF, \
4635 IsSigned) \
4636 case BuiltinType::Id: \
4637 return {getIntTypeForBitwidth(ElBits, IsSigned), \
4638 llvm::ElementCount::getScalable(NumEls), NF};
4639#define RVV_VECTOR_TYPE_FLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \
4640 case BuiltinType::Id: \
4641 return {ElBits == 16 ? Float16Ty : (ElBits == 32 ? FloatTy : DoubleTy), \
4642 llvm::ElementCount::getScalable(NumEls), NF};
4643#define RVV_VECTOR_TYPE_BFLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \
4644 case BuiltinType::Id: \
4645 return {BFloat16Ty, llvm::ElementCount::getScalable(NumEls), NF};
4646#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
4647 case BuiltinType::Id: \
4648 return {BoolTy, llvm::ElementCount::getScalable(NumEls), 1};
4649#include "clang/Basic/RISCVVTypes.def"
4650 }
4651}
4652
4653/// getExternrefType - Return a WebAssembly externref type, which represents an
4654/// opaque reference to a host value.
4655QualType ASTContext::getWebAssemblyExternrefType() const {
4656 if (Target->getTriple().isWasm() && Target->hasFeature(Feature: "reference-types")) {
4657#define WASM_REF_TYPE(Name, MangledName, Id, SingletonId, AS) \
4658 if (BuiltinType::Id == BuiltinType::WasmExternRef) \
4659 return SingletonId;
4660#include "clang/Basic/WebAssemblyReferenceTypes.def"
4661 }
4662 llvm_unreachable(
4663 "shouldn't try to generate type externref outside WebAssembly target");
4664}
4665
4666/// getScalableVectorType - Return the unique reference to a scalable vector
4667/// type of the specified element type and size. VectorType must be a built-in
4668/// type.
4669QualType ASTContext::getScalableVectorType(QualType EltTy, unsigned NumElts,
4670 unsigned NumFields) const {
4671 auto K = llvm::ScalableVecTyKey{.EltTy: EltTy, .NumElts: NumElts, .NumFields: NumFields};
4672 if (auto It = ScalableVecTyMap.find(Val: K); It != ScalableVecTyMap.end())
4673 return It->second;
4674
4675 if (Target->hasAArch64ACLETypes()) {
4676 uint64_t EltTySize = getTypeSize(T: EltTy);
4677
4678#define SVE_VECTOR_TYPE_INT(Name, MangledName, Id, SingletonId, NumEls, \
4679 ElBits, NF, IsSigned) \
4680 if (EltTy->hasIntegerRepresentation() && !EltTy->isBooleanType() && \
4681 EltTy->hasSignedIntegerRepresentation() == IsSigned && \
4682 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4683 return ScalableVecTyMap[K] = SingletonId; \
4684 }
4685#define SVE_VECTOR_TYPE_FLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4686 ElBits, NF) \
4687 if (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \
4688 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4689 return ScalableVecTyMap[K] = SingletonId; \
4690 }
4691#define SVE_VECTOR_TYPE_BFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4692 ElBits, NF) \
4693 if (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \
4694 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4695 return ScalableVecTyMap[K] = SingletonId; \
4696 }
4697#define SVE_VECTOR_TYPE_MFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4698 ElBits, NF) \
4699 if (EltTy->isMFloat8Type() && EltTySize == ElBits && \
4700 NumElts == (NumEls * NF) && NumFields == 1) { \
4701 return ScalableVecTyMap[K] = SingletonId; \
4702 }
4703#define SVE_PREDICATE_TYPE_ALL(Name, MangledName, Id, SingletonId, NumEls, NF) \
4704 if (EltTy->isBooleanType() && NumElts == (NumEls * NF) && NumFields == 1) \
4705 return ScalableVecTyMap[K] = SingletonId;
4706#include "clang/Basic/AArch64ACLETypes.def"
4707 } else if (Target->hasRISCVVTypes()) {
4708 uint64_t EltTySize = getTypeSize(T: EltTy);
4709#define RVV_VECTOR_TYPE(Name, Id, SingletonId, NumEls, ElBits, NF, IsSigned, \
4710 IsFP, IsBF) \
4711 if (!EltTy->isBooleanType() && \
4712 ((EltTy->hasIntegerRepresentation() && \
4713 EltTy->hasSignedIntegerRepresentation() == IsSigned) || \
4714 (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \
4715 IsFP && !IsBF) || \
4716 (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \
4717 IsBF && !IsFP)) && \
4718 EltTySize == ElBits && NumElts == NumEls && NumFields == NF) \
4719 return ScalableVecTyMap[K] = SingletonId;
4720#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
4721 if (EltTy->isBooleanType() && NumElts == NumEls) \
4722 return ScalableVecTyMap[K] = SingletonId;
4723#include "clang/Basic/RISCVVTypes.def"
4724 }
4725 return QualType();
4726}
4727
4728/// getVectorType - Return the unique reference to a vector type of
4729/// the specified element type and size. VectorType must be a built-in type.
4730QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
4731 VectorKind VecKind) const {
4732 assert(vecType->isBuiltinType() ||
4733 (vecType->isBitIntType() &&
4734 // Only support _BitInt elements with byte-sized power of 2 NumBits.
4735 llvm::isPowerOf2_32(vecType->castAs<BitIntType>()->getNumBits())));
4736
4737 // Check if we've already instantiated a vector of this type.
4738 llvm::FoldingSetNodeID ID;
4739 VectorType::Profile(ID, ElementType: vecType, NumElements: NumElts, TypeClass: Type::Vector, VecKind);
4740
4741 llvm::FoldingSetInsertToken Token;
4742 if (VectorType *VTP = VectorTypes.lookup(ID, Token))
4743 return QualType(VTP, 0);
4744
4745 // If the element type isn't canonical, this won't be a canonical type either,
4746 // so fill in the canonical type field.
4747 QualType Canonical;
4748 if (!vecType.isCanonical()) {
4749 Canonical = getVectorType(vecType: getCanonicalType(T: vecType), NumElts, VecKind);
4750
4751 // Get the new insert position for the node we care about.
4752 VectorType *NewIP = VectorTypes.lookup(ID, Token);
4753 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4754 }
4755 auto *New = new (*this, alignof(VectorType))
4756 VectorType(vecType, NumElts, Canonical, VecKind);
4757 VectorTypes.insert(N: New, Token);
4758 Types.push_back(Elt: New);
4759 return QualType(New, 0);
4760}
4761
4762QualType ASTContext::getDependentVectorType(QualType VecType, Expr *SizeExpr,
4763 SourceLocation AttrLoc,
4764 VectorKind VecKind) const {
4765 llvm::FoldingSetNodeID ID;
4766 DependentVectorType::Profile(ID, Context: *this, ElementType: getCanonicalType(T: VecType), SizeExpr,
4767 VecKind);
4768 llvm::FoldingSetInsertToken Token;
4769 DependentVectorType *Canon = DependentVectorTypes.lookup(ID, Token);
4770 DependentVectorType *New;
4771
4772 if (Canon) {
4773 New = new (*this, alignof(DependentVectorType)) DependentVectorType(
4774 VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind);
4775 } else {
4776 QualType CanonVecTy = getCanonicalType(T: VecType);
4777 if (CanonVecTy == VecType) {
4778 New = new (*this, alignof(DependentVectorType))
4779 DependentVectorType(VecType, QualType(), SizeExpr, AttrLoc, VecKind);
4780
4781 DependentVectorType *CanonCheck = DependentVectorTypes.lookup(ID, Token);
4782 assert(!CanonCheck &&
4783 "Dependent-sized vector_size canonical type broken");
4784 (void)CanonCheck;
4785 DependentVectorTypes.insert(N: New, Token);
4786 } else {
4787 QualType CanonTy = getDependentVectorType(VecType: CanonVecTy, SizeExpr,
4788 AttrLoc: SourceLocation(), VecKind);
4789 New = new (*this, alignof(DependentVectorType))
4790 DependentVectorType(VecType, CanonTy, SizeExpr, AttrLoc, VecKind);
4791 }
4792 }
4793
4794 Types.push_back(Elt: New);
4795 return QualType(New, 0);
4796}
4797
4798/// getExtVectorType - Return the unique reference to an extended vector type of
4799/// the specified element type and size. VectorType must be a built-in type.
4800QualType ASTContext::getExtVectorType(QualType vecType,
4801 unsigned NumElts) const {
4802 assert(vecType->isBuiltinType() || vecType->isDependentType() ||
4803 (vecType->isBitIntType() &&
4804 // Only support _BitInt elements with byte-sized power of 2 NumBits.
4805 llvm::isPowerOf2_32(vecType->castAs<BitIntType>()->getNumBits())));
4806
4807 // Check if we've already instantiated a vector of this type.
4808 llvm::FoldingSetNodeID ID;
4809 VectorType::Profile(ID, ElementType: vecType, NumElements: NumElts, TypeClass: Type::ExtVector,
4810 VecKind: VectorKind::Generic);
4811 llvm::FoldingSetInsertToken Token;
4812 if (VectorType *VTP = VectorTypes.lookup(ID, Token))
4813 return QualType(VTP, 0);
4814
4815 // If the element type isn't canonical, this won't be a canonical type either,
4816 // so fill in the canonical type field.
4817 QualType Canonical;
4818 if (!vecType.isCanonical()) {
4819 Canonical = getExtVectorType(vecType: getCanonicalType(T: vecType), NumElts);
4820
4821 // Get the new insert position for the node we care about.
4822 VectorType *NewIP = VectorTypes.lookup(ID, Token);
4823 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4824 }
4825 auto *New = new (*this, alignof(ExtVectorType))
4826 ExtVectorType(vecType, NumElts, Canonical);
4827 VectorTypes.insert(N: New, Token);
4828 Types.push_back(Elt: New);
4829 return QualType(New, 0);
4830}
4831
4832QualType
4833ASTContext::getDependentSizedExtVectorType(QualType vecType,
4834 Expr *SizeExpr,
4835 SourceLocation AttrLoc) const {
4836 llvm::FoldingSetNodeID ID;
4837 DependentSizedExtVectorType::Profile(ID, Context: *this, ElementType: getCanonicalType(T: vecType),
4838 SizeExpr);
4839
4840 llvm::FoldingSetInsertToken Token;
4841 DependentSizedExtVectorType *Canon =
4842 DependentSizedExtVectorTypes.lookup(ID, Token);
4843 DependentSizedExtVectorType *New;
4844 if (Canon) {
4845 // We already have a canonical version of this array type; use it as
4846 // the canonical type for a newly-built type.
4847 New = new (*this, alignof(DependentSizedExtVectorType))
4848 DependentSizedExtVectorType(vecType, QualType(Canon, 0), SizeExpr,
4849 AttrLoc);
4850 } else {
4851 QualType CanonVecTy = getCanonicalType(T: vecType);
4852 if (CanonVecTy == vecType) {
4853 New = new (*this, alignof(DependentSizedExtVectorType))
4854 DependentSizedExtVectorType(vecType, QualType(), SizeExpr, AttrLoc);
4855
4856 DependentSizedExtVectorType *CanonCheck =
4857 DependentSizedExtVectorTypes.lookup(ID, Token);
4858 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
4859 (void)CanonCheck;
4860 DependentSizedExtVectorTypes.insert(N: New, Token);
4861 } else {
4862 QualType CanonExtTy = getDependentSizedExtVectorType(vecType: CanonVecTy, SizeExpr,
4863 AttrLoc: SourceLocation());
4864 New = new (*this, alignof(DependentSizedExtVectorType))
4865 DependentSizedExtVectorType(vecType, CanonExtTy, SizeExpr, AttrLoc);
4866 }
4867 }
4868
4869 Types.push_back(Elt: New);
4870 return QualType(New, 0);
4871}
4872
4873QualType ASTContext::getConstantMatrixType(
4874 QualType ElementTy, unsigned NumRows, unsigned NumColumns,
4875 std::optional<MatrixType::LayoutKind> Layout) const {
4876 llvm::FoldingSetNodeID ID;
4877 ConstantMatrixType::Profile(ID, ElementType: ElementTy, NumRows, NumColumns, Layout,
4878 TypeClass: Type::ConstantMatrix);
4879
4880 assert(MatrixType::isValidElementType(ElementTy, getLangOpts()) &&
4881 "need a valid element type");
4882 assert(NumRows > 0 && NumRows <= LangOpts.MaxMatrixDimension &&
4883 NumColumns > 0 && NumColumns <= LangOpts.MaxMatrixDimension &&
4884 "need valid matrix dimensions");
4885 llvm::FoldingSetInsertToken Token;
4886 if (ConstantMatrixType *MTP = MatrixTypes.lookup(ID, Token))
4887 return QualType(MTP, 0);
4888
4889 QualType Canonical;
4890 if (Layout || !ElementTy.isCanonical()) {
4891 Canonical = getConstantMatrixType(ElementTy: getCanonicalType(T: ElementTy), NumRows,
4892 NumColumns, Layout: std::nullopt);
4893
4894 ConstantMatrixType *NewIP = MatrixTypes.lookup(ID, Token);
4895 assert(!NewIP && "Matrix type shouldn't already exist in the map");
4896 (void)NewIP;
4897 }
4898
4899 auto *New = new (*this, alignof(ConstantMatrixType))
4900 ConstantMatrixType(ElementTy, NumRows, NumColumns, Canonical, Layout);
4901 MatrixTypes.insert(N: New, Token);
4902 Types.push_back(Elt: New);
4903 return QualType(New, 0);
4904}
4905
4906QualType ASTContext::getDependentSizedMatrixType(QualType ElementTy,
4907 Expr *RowExpr,
4908 Expr *ColumnExpr,
4909 SourceLocation AttrLoc) const {
4910 QualType CanonElementTy = getCanonicalType(T: ElementTy);
4911 llvm::FoldingSetNodeID ID;
4912 DependentSizedMatrixType::Profile(ID, Context: *this, ElementType: CanonElementTy, RowExpr,
4913 ColumnExpr);
4914
4915 llvm::FoldingSetInsertToken Token;
4916 DependentSizedMatrixType *Canon = DependentSizedMatrixTypes.lookup(ID, Token);
4917
4918 if (!Canon) {
4919 Canon = new (*this, alignof(DependentSizedMatrixType))
4920 DependentSizedMatrixType(CanonElementTy, QualType(), RowExpr,
4921 ColumnExpr, AttrLoc);
4922#ifndef NDEBUG
4923 DependentSizedMatrixType *CanonCheck =
4924 DependentSizedMatrixTypes.lookup(ID, Token);
4925 assert(!CanonCheck && "Dependent-sized matrix canonical type broken");
4926#endif
4927 DependentSizedMatrixTypes.insert(N: Canon, Token);
4928 Types.push_back(Elt: Canon);
4929 }
4930
4931 // Already have a canonical version of the matrix type
4932 //
4933 // If it exactly matches the requested type, use it directly.
4934 if (Canon->getElementType() == ElementTy && Canon->getRowExpr() == RowExpr &&
4935 Canon->getRowExpr() == ColumnExpr)
4936 return QualType(Canon, 0);
4937
4938 // Use Canon as the canonical type for newly-built type.
4939 DependentSizedMatrixType *New = new (*this, alignof(DependentSizedMatrixType))
4940 DependentSizedMatrixType(ElementTy, QualType(Canon, 0), RowExpr,
4941 ColumnExpr, AttrLoc);
4942 Types.push_back(Elt: New);
4943 return QualType(New, 0);
4944}
4945
4946QualType
4947ASTContext::getMatrixTypeWithLayout(QualType T,
4948 MatrixType::LayoutKind Layout) const {
4949 Qualifiers Quals = T.getQualifiers();
4950 const Type *Ty = T->getUnqualifiedDesugaredType();
4951
4952 if (const auto *MT = dyn_cast<ConstantMatrixType>(Val: Ty))
4953 return getQualifiedType(T: getConstantMatrixType(ElementTy: MT->getElementType(),
4954 NumRows: MT->getNumRows(),
4955 NumColumns: MT->getNumColumns(), Layout),
4956 Qs: Quals);
4957
4958 const auto *CAT = dyn_cast<ConstantArrayType>(Val: Ty);
4959 if (!CAT)
4960 return T;
4961
4962 QualType Result = getConstantArrayType(
4963 EltTy: getMatrixTypeWithLayout(T: CAT->getElementType(), Layout), ArySizeIn: CAT->getSize(),
4964 SizeExpr: CAT->getSizeExpr(), ASM: CAT->getSizeModifier(),
4965 IndexTypeQuals: CAT->getIndexTypeCVRQualifiers());
4966 if (isa<ArrayParameterType>(Val: CAT))
4967 Result = getArrayParameterType(Ty: Result);
4968
4969 return getQualifiedType(T: Result, Qs: Quals);
4970}
4971
4972QualType ASTContext::getDependentAddressSpaceType(QualType PointeeType,
4973 Expr *AddrSpaceExpr,
4974 SourceLocation AttrLoc) const {
4975 assert(AddrSpaceExpr->isInstantiationDependent());
4976
4977 QualType canonPointeeType = getCanonicalType(T: PointeeType);
4978
4979 llvm::FoldingSetInsertToken Token;
4980 llvm::FoldingSetNodeID ID;
4981 DependentAddressSpaceType::Profile(ID, Context: *this, PointeeType: canonPointeeType,
4982 AddrSpaceExpr);
4983
4984 DependentAddressSpaceType *canonTy =
4985 DependentAddressSpaceTypes.lookup(ID, Token);
4986
4987 if (!canonTy) {
4988 canonTy = new (*this, alignof(DependentAddressSpaceType))
4989 DependentAddressSpaceType(canonPointeeType, QualType(), AddrSpaceExpr,
4990 AttrLoc);
4991 DependentAddressSpaceTypes.insert(N: canonTy, Token);
4992 Types.push_back(Elt: canonTy);
4993 }
4994
4995 if (canonPointeeType == PointeeType &&
4996 canonTy->getAddrSpaceExpr() == AddrSpaceExpr)
4997 return QualType(canonTy, 0);
4998
4999 auto *sugaredType = new (*this, alignof(DependentAddressSpaceType))
5000 DependentAddressSpaceType(PointeeType, QualType(canonTy, 0),
5001 AddrSpaceExpr, AttrLoc);
5002 Types.push_back(Elt: sugaredType);
5003 return QualType(sugaredType, 0);
5004}
5005
5006/// Determine whether \p T is canonical as the result type of a function.
5007static bool isCanonicalResultType(QualType T) {
5008 return T.isCanonical() &&
5009 (T.getObjCLifetime() == Qualifiers::OCL_None ||
5010 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
5011}
5012
5013/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
5014QualType
5015ASTContext::getFunctionNoProtoType(QualType ResultTy,
5016 const FunctionType::ExtInfo &Info) const {
5017 // FIXME: This assertion cannot be enabled (yet) because the ObjC rewriter
5018 // functionality creates a function without a prototype regardless of
5019 // language mode (so it makes them even in C++). Once the rewriter has been
5020 // fixed, this assertion can be enabled again.
5021 //assert(!LangOpts.requiresStrictPrototypes() &&
5022 // "strict prototypes are disabled");
5023
5024 // Unique functions, to guarantee there is only one function of a particular
5025 // structure.
5026 llvm::FoldingSetNodeID ID;
5027 FunctionNoProtoType::Profile(ID, ResultType: ResultTy, Info);
5028
5029 llvm::FoldingSetInsertToken Token;
5030 if (FunctionNoProtoType *FT = FunctionNoProtoTypes.lookup(ID, Token))
5031 return QualType(FT, 0);
5032
5033 QualType Canonical;
5034 if (!isCanonicalResultType(T: ResultTy)) {
5035 Canonical =
5036 getFunctionNoProtoType(ResultTy: getCanonicalFunctionResultType(ResultType: ResultTy), Info);
5037
5038 // Get the new insert position for the node we care about.
5039 FunctionNoProtoType *NewIP = FunctionNoProtoTypes.lookup(ID, Token);
5040 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
5041 }
5042
5043 auto *New = new (*this, alignof(FunctionNoProtoType))
5044 FunctionNoProtoType(ResultTy, Canonical, Info);
5045 Types.push_back(Elt: New);
5046 FunctionNoProtoTypes.insert(N: New, Token);
5047 return QualType(New, 0);
5048}
5049
5050CanQualType
5051ASTContext::getCanonicalFunctionResultType(QualType ResultType) const {
5052 CanQualType CanResultType = getCanonicalType(T: ResultType);
5053
5054 // Canonical result types do not have ARC lifetime qualifiers.
5055 if (CanResultType.getQualifiers().hasObjCLifetime()) {
5056 Qualifiers Qs = CanResultType.getQualifiers();
5057 Qs.removeObjCLifetime();
5058 return CanQualType::CreateUnsafe(
5059 Other: getQualifiedType(T: CanResultType.getUnqualifiedType(), Qs));
5060 }
5061
5062 return CanResultType;
5063}
5064
5065static bool isCanonicalExceptionSpecification(
5066 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
5067 if (ESI.Type == EST_None)
5068 return true;
5069 if (!NoexceptInType)
5070 return false;
5071
5072 // C++17 onwards: exception specification is part of the type, as a simple
5073 // boolean "can this function type throw".
5074 if (ESI.Type == EST_BasicNoexcept)
5075 return true;
5076
5077 // A noexcept(expr) specification is (possibly) canonical if expr is
5078 // value-dependent.
5079 if (ESI.Type == EST_DependentNoexcept)
5080 return true;
5081
5082 // A dynamic exception specification is canonical if it only contains pack
5083 // expansions (so we can't tell whether it's non-throwing) and all its
5084 // contained types are canonical.
5085 if (ESI.Type == EST_Dynamic) {
5086 bool AnyPackExpansions = false;
5087 for (QualType ET : ESI.Exceptions) {
5088 if (!ET.isCanonical())
5089 return false;
5090 if (ET->getAs<PackExpansionType>())
5091 AnyPackExpansions = true;
5092 }
5093 return AnyPackExpansions;
5094 }
5095
5096 return false;
5097}
5098
5099QualType ASTContext::getFunctionTypeInternal(
5100 QualType ResultTy, ArrayRef<QualType> ArgArray,
5101 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
5102 size_t NumArgs = ArgArray.size();
5103
5104 // Unique functions, to guarantee there is only one function of a particular
5105 // structure.
5106 llvm::FoldingSetNodeID ID;
5107 FunctionProtoType::Profile(ID, Result: ResultTy, ArgTys: ArgArray.begin(), NumArgs, EPI,
5108 Context: *this);
5109
5110 QualType Canonical;
5111 bool Unique = false;
5112
5113 llvm::FoldingSetInsertToken Token;
5114 if (FunctionProtoType *FPT = FunctionProtoTypes.lookup(ID, Token)) {
5115 QualType Existing = QualType(FPT, 0);
5116
5117 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
5118 // it so long as our exception specification doesn't contain a dependent
5119 // noexcept expression, or we're just looking for a canonical type.
5120 // Otherwise, we're going to need to create a type
5121 // sugar node to hold the concrete expression.
5122 if (OnlyWantCanonical || !isComputedNoexcept(ESpecType: EPI.ExceptionSpec.Type) ||
5123 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
5124 return Existing;
5125
5126 // We need a new type sugar node for this one, to hold the new noexcept
5127 // expression. We do no canonicalization here, but that's OK since we don't
5128 // expect to see the same noexcept expression much more than once.
5129 Canonical = getCanonicalType(T: Existing);
5130 Unique = true;
5131 }
5132
5133 bool NoexceptInType = getLangOpts().CPlusPlus17;
5134 bool IsCanonicalExceptionSpec =
5135 isCanonicalExceptionSpecification(ESI: EPI.ExceptionSpec, NoexceptInType);
5136
5137 // Determine whether the type being created is already canonical or not.
5138 bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
5139 isCanonicalResultType(T: ResultTy) && !EPI.HasTrailingReturn;
5140 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
5141 if (!ArgArray[i].isCanonicalAsParam())
5142 isCanonical = false;
5143
5144 if (OnlyWantCanonical)
5145 assert(isCanonical &&
5146 "given non-canonical parameters constructing canonical type");
5147
5148 // If this type isn't canonical, get the canonical version of it if we don't
5149 // already have it. The exception spec is only partially part of the
5150 // canonical type, and only in C++17 onwards.
5151 if (!isCanonical && Canonical.isNull()) {
5152 SmallVector<QualType, 16> CanonicalArgs;
5153 CanonicalArgs.reserve(N: NumArgs);
5154 for (unsigned i = 0; i != NumArgs; ++i)
5155 CanonicalArgs.push_back(Elt: getCanonicalParamType(T: ArgArray[i]));
5156
5157 llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
5158 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
5159 CanonicalEPI.HasTrailingReturn = false;
5160
5161 if (IsCanonicalExceptionSpec) {
5162 // Exception spec is already OK.
5163 } else if (NoexceptInType) {
5164 switch (EPI.ExceptionSpec.Type) {
5165 case EST_Unparsed: case EST_Unevaluated: case EST_Uninstantiated:
5166 // We don't know yet. It shouldn't matter what we pick here; no-one
5167 // should ever look at this.
5168 [[fallthrough]];
5169 case EST_None: case EST_MSAny: case EST_NoexceptFalse:
5170 CanonicalEPI.ExceptionSpec.Type = EST_None;
5171 break;
5172
5173 // A dynamic exception specification is almost always "not noexcept",
5174 // with the exception that a pack expansion might expand to no types.
5175 case EST_Dynamic: {
5176 bool AnyPacks = false;
5177 for (QualType ET : EPI.ExceptionSpec.Exceptions) {
5178 if (ET->getAs<PackExpansionType>())
5179 AnyPacks = true;
5180 ExceptionTypeStorage.push_back(Elt: getCanonicalType(T: ET));
5181 }
5182 if (!AnyPacks)
5183 CanonicalEPI.ExceptionSpec.Type = EST_None;
5184 else {
5185 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
5186 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
5187 }
5188 break;
5189 }
5190
5191 case EST_DynamicNone:
5192 case EST_BasicNoexcept:
5193 case EST_NoexceptTrue:
5194 case EST_NoThrow:
5195 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
5196 break;
5197
5198 case EST_DependentNoexcept:
5199 llvm_unreachable("dependent noexcept is already canonical");
5200 }
5201 } else {
5202 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
5203 }
5204
5205 // Adjust the canonical function result type.
5206 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultType: ResultTy);
5207 Canonical =
5208 getFunctionTypeInternal(ResultTy: CanResultTy, ArgArray: CanonicalArgs, EPI: CanonicalEPI, OnlyWantCanonical: true);
5209
5210 // Get the new insert position for the node we care about.
5211 FunctionProtoType *NewIP = FunctionProtoTypes.lookup(ID, Token);
5212 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
5213 }
5214
5215 // Compute the needed size to hold this FunctionProtoType and the
5216 // various trailing objects.
5217 auto ESH = FunctionProtoType::getExceptionSpecSize(
5218 EST: EPI.ExceptionSpec.Type, NumExceptions: EPI.ExceptionSpec.Exceptions.size());
5219 size_t Size = FunctionProtoType::totalSizeToAlloc<
5220 QualType, SourceLocation, FunctionType::FunctionTypeExtraBitfields,
5221 FunctionType::FunctionTypeExtraAttributeInfo,
5222 FunctionType::FunctionTypeArmAttributes, FunctionType::ExceptionType,
5223 Expr *, FunctionDecl *, FunctionProtoType::ExtParameterInfo, Qualifiers,
5224 FunctionEffect, EffectConditionExpr>(
5225 Counts: NumArgs, Counts: EPI.Variadic, Counts: EPI.requiresFunctionProtoTypeExtraBitfields(),
5226 Counts: EPI.requiresFunctionProtoTypeExtraAttributeInfo(),
5227 Counts: EPI.requiresFunctionProtoTypeArmAttributes(), Counts: ESH.NumExceptionType,
5228 Counts: ESH.NumExprPtr, Counts: ESH.NumFunctionDeclPtr,
5229 Counts: EPI.ExtParameterInfos ? NumArgs : 0,
5230 Counts: EPI.TypeQuals.hasNonFastQualifiers() ? 1 : 0, Counts: EPI.FunctionEffects.size(),
5231 Counts: EPI.FunctionEffects.conditions().size());
5232
5233 auto *FTP = (FunctionProtoType *)Allocate(Size, Align: alignof(FunctionProtoType));
5234 FunctionProtoType::ExtProtoInfo newEPI = EPI;
5235 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
5236 Types.push_back(Elt: FTP);
5237 if (!Unique)
5238 FunctionProtoTypes.insert(N: FTP, Token);
5239 if (!EPI.FunctionEffects.empty())
5240 AnyFunctionEffects = true;
5241 return QualType(FTP, 0);
5242}
5243
5244QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
5245 llvm::FoldingSetInsertToken Token;
5246 if (PipeType *PT = PipeTypes.lookup(Key: {T, ReadOnly}, Token))
5247 return QualType(PT, 0);
5248
5249 // If the pipe element type isn't canonical, this won't be a canonical type
5250 // either, so fill in the canonical type field.
5251 QualType Canonical;
5252 if (!T.isCanonical()) {
5253 Canonical = getPipeType(T: getCanonicalType(T), ReadOnly);
5254
5255 assert(!PipeTypes.lookup({T, ReadOnly}, Token) &&
5256 "Shouldn't be in the map!");
5257 }
5258 auto *New = new (*this, alignof(PipeType)) PipeType(T, Canonical, ReadOnly);
5259 Types.push_back(Elt: New);
5260 PipeTypes.insert(N: New, Token);
5261 return QualType(New, 0);
5262}
5263
5264QualType ASTContext::adjustStringLiteralBaseType(QualType Ty) const {
5265 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
5266 return LangOpts.OpenCL ? getAddrSpaceQualType(T: Ty, AddressSpace: LangAS::opencl_constant)
5267 : Ty;
5268}
5269
5270QualType ASTContext::getReadPipeType(QualType T) const {
5271 return getPipeType(T, ReadOnly: true);
5272}
5273
5274QualType ASTContext::getWritePipeType(QualType T) const {
5275 return getPipeType(T, ReadOnly: false);
5276}
5277
5278QualType ASTContext::getBitIntType(bool IsUnsigned, unsigned NumBits) const {
5279 auto Key = std::make_pair(x: unsigned(IsUnsigned), y&: NumBits);
5280
5281 llvm::FoldingSetInsertToken Token;
5282 if (BitIntType *EIT = BitIntTypes.lookup(Key, Token))
5283 return QualType(EIT, 0);
5284
5285 auto *New = new (*this, alignof(BitIntType)) BitIntType(IsUnsigned, NumBits);
5286 BitIntTypes.insert(N: New, Token);
5287 Types.push_back(Elt: New);
5288 return QualType(New, 0);
5289}
5290
5291QualType ASTContext::getDependentBitIntType(bool IsUnsigned,
5292 Expr *NumBitsExpr) const {
5293 assert(NumBitsExpr->isInstantiationDependent() && "Only good for dependent");
5294 llvm::FoldingSetNodeID ID;
5295 DependentBitIntType::Profile(ID, Context: *this, IsUnsigned, NumBitsExpr);
5296
5297 llvm::FoldingSetInsertToken Token;
5298 if (DependentBitIntType *Existing = DependentBitIntTypes.lookup(ID, Token))
5299 return QualType(Existing, 0);
5300
5301 auto *New = new (*this, alignof(DependentBitIntType))
5302 DependentBitIntType(IsUnsigned, NumBitsExpr);
5303 DependentBitIntTypes.insert(N: New, Token);
5304
5305 Types.push_back(Elt: New);
5306 return QualType(New, 0);
5307}
5308
5309QualType
5310ASTContext::getPredefinedSugarType(PredefinedSugarType::Kind KD) const {
5311 using Kind = PredefinedSugarType::Kind;
5312
5313 if (auto *Target = PredefinedSugarTypes[llvm::to_underlying(E: KD)];
5314 Target != nullptr)
5315 return QualType(Target, 0);
5316
5317 auto getCanonicalType = [](const ASTContext &Ctx, Kind KDI) -> QualType {
5318 switch (KDI) {
5319 // size_t (C99TC3 6.5.3.4), signed size_t (C++23 5.13.2) and
5320 // ptrdiff_t (C99TC3 6.5.6) Although these types are not built-in, they
5321 // are part of the core language and are widely used. Using
5322 // PredefinedSugarType makes these types as named sugar types rather than
5323 // standard integer types, enabling better hints and diagnostics.
5324 case Kind::SizeT:
5325 return Ctx.getFromTargetType(Type: Ctx.Target->getSizeType());
5326 case Kind::SignedSizeT:
5327 return Ctx.getFromTargetType(Type: Ctx.Target->getSignedSizeType());
5328 case Kind::PtrdiffT:
5329 return Ctx.getFromTargetType(Type: Ctx.Target->getPtrDiffType(AddrSpace: LangAS::Default));
5330 }
5331 llvm_unreachable("unexpected kind");
5332 };
5333 auto *New = new (*this, alignof(PredefinedSugarType))
5334 PredefinedSugarType(KD, &Idents.get(Name: PredefinedSugarType::getName(KD)),
5335 getCanonicalType(*this, static_cast<Kind>(KD)));
5336 Types.push_back(Elt: New);
5337 PredefinedSugarTypes[llvm::to_underlying(E: KD)] = New;
5338 return QualType(New, 0);
5339}
5340
5341QualType ASTContext::getTypeDeclType(ElaboratedTypeKeyword Keyword,
5342 NestedNameSpecifier Qualifier,
5343 const TypeDecl *Decl) const {
5344 if (auto *Tag = dyn_cast<TagDecl>(Val: Decl))
5345 return getTagType(Keyword, Qualifier, TD: Tag,
5346 /*OwnsTag=*/false);
5347 if (auto *Typedef = dyn_cast<TypedefNameDecl>(Val: Decl))
5348 return getTypedefType(Keyword, Qualifier, Decl: Typedef);
5349 if (auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(Val: Decl))
5350 return getUnresolvedUsingType(Keyword, Qualifier, D: UD);
5351
5352 assert(Keyword == ElaboratedTypeKeyword::None);
5353 assert(!Qualifier);
5354 return QualType(Decl->TypeForDecl, 0);
5355}
5356
5357CanQualType ASTContext::getCanonicalTypeDeclType(const TypeDecl *TD) const {
5358 if (auto *Tag = dyn_cast<TagDecl>(Val: TD))
5359 return getCanonicalTagType(TD: Tag);
5360 if (auto *TN = dyn_cast<TypedefNameDecl>(Val: TD))
5361 return getCanonicalType(T: TN->getUnderlyingType());
5362 if (const auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(Val: TD))
5363 return getCanonicalUnresolvedUsingType(D: UD);
5364 assert(TD->TypeForDecl);
5365 return TD->TypeForDecl->getCanonicalTypeUnqualified();
5366}
5367
5368QualType ASTContext::getTypeDeclType(const TypeDecl *Decl) const {
5369 if (const auto *TD = dyn_cast<TagDecl>(Val: Decl))
5370 return getCanonicalTagType(TD);
5371 if (const auto *TD = dyn_cast<TypedefNameDecl>(Val: Decl);
5372 isa_and_nonnull<TypedefDecl, TypeAliasDecl>(Val: TD))
5373 return getTypedefType(Keyword: ElaboratedTypeKeyword::None,
5374 /*Qualifier=*/std::nullopt, Decl: TD);
5375 if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Val: Decl))
5376 return getCanonicalUnresolvedUsingType(D: Using);
5377
5378 assert(Decl->TypeForDecl);
5379 return QualType(Decl->TypeForDecl, 0);
5380}
5381
5382/// getTypedefType - Return the unique reference to the type for the
5383/// specified typedef name decl.
5384QualType
5385ASTContext::getTypedefType(ElaboratedTypeKeyword Keyword,
5386 NestedNameSpecifier Qualifier,
5387 const TypedefNameDecl *Decl, QualType UnderlyingType,
5388 std::optional<bool> TypeMatchesDeclOrNone) const {
5389 if (!TypeMatchesDeclOrNone) {
5390 QualType DeclUnderlyingType = Decl->getUnderlyingType();
5391 assert(!DeclUnderlyingType.isNull());
5392 if (UnderlyingType.isNull())
5393 UnderlyingType = DeclUnderlyingType;
5394 else
5395 assert(hasSameType(UnderlyingType, DeclUnderlyingType));
5396 TypeMatchesDeclOrNone = UnderlyingType == DeclUnderlyingType;
5397 } else {
5398 // FIXME: This is a workaround for a serialization cycle: assume the decl
5399 // underlying type is not available; don't touch it.
5400 assert(!UnderlyingType.isNull());
5401 }
5402
5403 if (Keyword == ElaboratedTypeKeyword::None && !Qualifier &&
5404 *TypeMatchesDeclOrNone) {
5405 if (Decl->TypeForDecl)
5406 return QualType(Decl->TypeForDecl, 0);
5407
5408 auto *NewType = new (*this, alignof(TypedefType))
5409 TypedefType(Type::Typedef, Keyword, Qualifier, Decl, UnderlyingType,
5410 !*TypeMatchesDeclOrNone);
5411
5412 Types.push_back(Elt: NewType);
5413 Decl->TypeForDecl = NewType;
5414 return QualType(NewType, 0);
5415 }
5416
5417 llvm::FoldingSetNodeID ID;
5418 TypedefType::Profile(ID, Keyword, Qualifier, Decl,
5419 Underlying: *TypeMatchesDeclOrNone ? QualType() : UnderlyingType);
5420
5421 llvm::FoldingSetInsertToken Token;
5422 if (FoldingSetPlaceholder<TypedefType> *Placeholder =
5423 TypedefTypes.lookup(ID, Token))
5424 return QualType(Placeholder->getType(), 0);
5425
5426 void *Mem =
5427 Allocate(Size: TypedefType::totalSizeToAlloc<FoldingSetPlaceholder<TypedefType>,
5428 NestedNameSpecifier, QualType>(
5429 Counts: 1, Counts: !!Qualifier, Counts: !*TypeMatchesDeclOrNone),
5430 Align: alignof(TypedefType));
5431 auto *NewType =
5432 new (Mem) TypedefType(Type::Typedef, Keyword, Qualifier, Decl,
5433 UnderlyingType, !*TypeMatchesDeclOrNone);
5434 auto *Placeholder = new (NewType->getFoldingSetPlaceholder())
5435 FoldingSetPlaceholder<TypedefType>();
5436 TypedefTypes.insert(N: Placeholder, Token);
5437 Types.push_back(Elt: NewType);
5438 return QualType(NewType, 0);
5439}
5440
5441QualType ASTContext::getUsingType(ElaboratedTypeKeyword Keyword,
5442 NestedNameSpecifier Qualifier,
5443 const UsingShadowDecl *D,
5444 QualType UnderlyingType) const {
5445 // FIXME: This is expensive to compute every time!
5446 if (UnderlyingType.isNull()) {
5447 const auto *UD = cast<UsingDecl>(Val: D->getIntroducer());
5448 UnderlyingType =
5449 getTypeDeclType(Keyword: UD->hasTypename() ? ElaboratedTypeKeyword::Typename
5450 : ElaboratedTypeKeyword::None,
5451 Qualifier: UD->getQualifier(), Decl: cast<TypeDecl>(Val: D->getTargetDecl()));
5452 }
5453
5454 llvm::FoldingSetNodeID ID;
5455 UsingType::Profile(ID, Keyword, Qualifier, D, UnderlyingType);
5456
5457 llvm::FoldingSetInsertToken Token;
5458 if (const UsingType *T = UsingTypes.lookup(ID, Token))
5459 return QualType(T, 0);
5460
5461 assert(!UnderlyingType.hasLocalQualifiers());
5462
5463 assert(
5464 hasSameType(getCanonicalTypeDeclType(cast<TypeDecl>(D->getTargetDecl())),
5465 UnderlyingType));
5466
5467 void *Mem =
5468 Allocate(Size: UsingType::totalSizeToAlloc<NestedNameSpecifier>(Counts: !!Qualifier),
5469 Align: alignof(UsingType));
5470 UsingType *T = new (Mem) UsingType(Keyword, Qualifier, D, UnderlyingType);
5471 Types.push_back(Elt: T);
5472 UsingTypes.insert(N: T, Token);
5473 return QualType(T, 0);
5474}
5475
5476TagType *ASTContext::getTagTypeInternal(ElaboratedTypeKeyword Keyword,
5477 NestedNameSpecifier Qualifier,
5478 const TagDecl *TD, bool OwnsTag,
5479 bool IsInjected,
5480 const Type *CanonicalType,
5481 bool WithFoldingSetNode) const {
5482 auto [TC, Size] = [&] {
5483 switch (TD->getDeclKind()) {
5484 case Decl::Enum:
5485 static_assert(alignof(EnumType) == alignof(TagType));
5486 return std::make_tuple(args: Type::Enum, args: sizeof(EnumType));
5487 case Decl::ClassTemplatePartialSpecialization:
5488 case Decl::ClassTemplateSpecialization:
5489 case Decl::CXXRecord:
5490 static_assert(alignof(RecordType) == alignof(TagType));
5491 static_assert(alignof(InjectedClassNameType) == alignof(TagType));
5492 if (cast<CXXRecordDecl>(Val: TD)->hasInjectedClassType())
5493 return std::make_tuple(args: Type::InjectedClassName,
5494 args: sizeof(InjectedClassNameType));
5495 [[fallthrough]];
5496 case Decl::Record:
5497 return std::make_tuple(args: Type::Record, args: sizeof(RecordType));
5498 default:
5499 llvm_unreachable("unexpected decl kind");
5500 }
5501 }();
5502
5503 if (Qualifier) {
5504 static_assert(alignof(NestedNameSpecifier) <= alignof(TagType));
5505 Size = llvm::alignTo(Value: Size, Align: alignof(NestedNameSpecifier)) +
5506 sizeof(NestedNameSpecifier);
5507 }
5508 void *Mem;
5509 if (WithFoldingSetNode) {
5510 // FIXME: It would be more profitable to tail allocate the folding set node
5511 // from the type, instead of the other way around, due to the greater
5512 // alignment requirements of the type. But this makes it harder to deal with
5513 // the different type node sizes. This would require either uniquing from
5514 // different folding sets, or having the folding setaccept a
5515 // contextual parameter which is not fixed at construction.
5516 Mem = Allocate(
5517 Size: sizeof(TagTypeFoldingSetPlaceholder) +
5518 TagTypeFoldingSetPlaceholder::getOffset() + Size,
5519 Align: std::max(a: alignof(TagTypeFoldingSetPlaceholder), b: alignof(TagType)));
5520 auto *T = new (Mem) TagTypeFoldingSetPlaceholder();
5521 Mem = T->getTagType();
5522 } else {
5523 Mem = Allocate(Size, Align: alignof(TagType));
5524 }
5525
5526 auto *T = [&, TC = TC]() -> TagType * {
5527 switch (TC) {
5528 case Type::Enum: {
5529 assert(isa<EnumDecl>(TD));
5530 auto *T = new (Mem) EnumType(TC, Keyword, Qualifier, TD, OwnsTag,
5531 IsInjected, CanonicalType);
5532 assert(reinterpret_cast<void *>(T) ==
5533 reinterpret_cast<void *>(static_cast<TagType *>(T)) &&
5534 "TagType must be the first base of EnumType");
5535 return T;
5536 }
5537 case Type::Record: {
5538 assert(isa<RecordDecl>(TD));
5539 auto *T = new (Mem) RecordType(TC, Keyword, Qualifier, TD, OwnsTag,
5540 IsInjected, CanonicalType);
5541 assert(reinterpret_cast<void *>(T) ==
5542 reinterpret_cast<void *>(static_cast<TagType *>(T)) &&
5543 "TagType must be the first base of RecordType");
5544 return T;
5545 }
5546 case Type::InjectedClassName: {
5547 auto *T = new (Mem) InjectedClassNameType(Keyword, Qualifier, TD,
5548 IsInjected, CanonicalType);
5549 assert(reinterpret_cast<void *>(T) ==
5550 reinterpret_cast<void *>(static_cast<TagType *>(T)) &&
5551 "TagType must be the first base of InjectedClassNameType");
5552 return T;
5553 }
5554 default:
5555 llvm_unreachable("unexpected type class");
5556 }
5557 }();
5558 assert(T->getKeyword() == Keyword);
5559 assert(T->getQualifier() == Qualifier);
5560 assert(T->getDecl() == TD);
5561 assert(T->isInjected() == IsInjected);
5562 assert(T->isTagOwned() == OwnsTag);
5563 assert((T->isCanonicalUnqualified()
5564 ? QualType()
5565 : T->getCanonicalTypeInternal()) == QualType(CanonicalType, 0));
5566 Types.push_back(Elt: T);
5567 return T;
5568}
5569
5570static const TagDecl *getNonInjectedClassName(const TagDecl *TD) {
5571 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: TD);
5572 RD && RD->isInjectedClassName())
5573 return cast<TagDecl>(Val: RD->getDeclContext());
5574 return TD;
5575}
5576
5577CanQualType ASTContext::getCanonicalTagType(const TagDecl *TD) const {
5578 TD = ::getNonInjectedClassName(TD)->getCanonicalDecl();
5579 if (TD->TypeForDecl)
5580 return TD->TypeForDecl->getCanonicalTypeUnqualified();
5581
5582 const Type *CanonicalType = getTagTypeInternal(
5583 Keyword: ElaboratedTypeKeyword::None,
5584 /*Qualifier=*/std::nullopt, TD,
5585 /*OwnsTag=*/false, /*IsInjected=*/false, /*CanonicalType=*/nullptr,
5586 /*WithFoldingSetNode=*/false);
5587 TD->TypeForDecl = CanonicalType;
5588 return CanQualType::CreateUnsafe(Other: QualType(CanonicalType, 0));
5589}
5590
5591QualType ASTContext::getTagType(ElaboratedTypeKeyword Keyword,
5592 NestedNameSpecifier Qualifier,
5593 const TagDecl *TD, bool OwnsTag) const {
5594
5595 const TagDecl *NonInjectedTD = ::getNonInjectedClassName(TD);
5596 bool IsInjected = TD != NonInjectedTD;
5597
5598 ElaboratedTypeKeyword PreferredKeyword =
5599 getLangOpts().CPlusPlus ? ElaboratedTypeKeyword::None
5600 : KeywordHelpers::getKeywordForTagTypeKind(
5601 Tag: NonInjectedTD->getTagKind());
5602
5603 if (Keyword == PreferredKeyword && !Qualifier && !OwnsTag) {
5604 if (const Type *T = TD->TypeForDecl; T && !T->isCanonicalUnqualified())
5605 return QualType(T, 0);
5606
5607 const Type *CanonicalType = getCanonicalTagType(TD: NonInjectedTD).getTypePtr();
5608 const Type *T =
5609 getTagTypeInternal(Keyword,
5610 /*Qualifier=*/std::nullopt, TD: NonInjectedTD,
5611 /*OwnsTag=*/false, IsInjected, CanonicalType,
5612 /*WithFoldingSetNode=*/false);
5613 TD->TypeForDecl = T;
5614 return QualType(T, 0);
5615 }
5616
5617 llvm::FoldingSetNodeID ID;
5618 TagTypeFoldingSetPlaceholder::Profile(ID, Keyword, Qualifier, Tag: NonInjectedTD,
5619 OwnsTag, IsInjected);
5620
5621 llvm::FoldingSetInsertToken Token;
5622 if (TagTypeFoldingSetPlaceholder *T = TagTypes.lookup(ID, Token))
5623 return QualType(T->getTagType(), 0);
5624
5625 const Type *CanonicalType = getCanonicalTagType(TD: NonInjectedTD).getTypePtr();
5626 TagType *T =
5627 getTagTypeInternal(Keyword, Qualifier, TD: NonInjectedTD, OwnsTag, IsInjected,
5628 CanonicalType, /*WithFoldingSetNode=*/true);
5629 TagTypes.insert(N: TagTypeFoldingSetPlaceholder::fromTagType(T), Token);
5630 return QualType(T, 0);
5631}
5632
5633bool ASTContext::computeBestEnumTypes(bool IsPacked, unsigned NumNegativeBits,
5634 unsigned NumPositiveBits,
5635 QualType &BestType,
5636 QualType &BestPromotionType) {
5637 unsigned IntWidth = Target->getIntWidth();
5638 unsigned CharWidth = Target->getCharWidth();
5639 unsigned ShortWidth = Target->getShortWidth();
5640 bool EnumTooLarge = false;
5641 unsigned BestWidth;
5642 if (NumNegativeBits) {
5643 // If there is a negative value, figure out the smallest integer type (of
5644 // int/long/longlong) that fits.
5645 // If it's packed, check also if it fits a char or a short.
5646 if (IsPacked && NumNegativeBits <= CharWidth &&
5647 NumPositiveBits < CharWidth) {
5648 BestType = SignedCharTy;
5649 BestWidth = CharWidth;
5650 } else if (IsPacked && NumNegativeBits <= ShortWidth &&
5651 NumPositiveBits < ShortWidth) {
5652 BestType = ShortTy;
5653 BestWidth = ShortWidth;
5654 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
5655 BestType = IntTy;
5656 BestWidth = IntWidth;
5657 } else {
5658 BestWidth = Target->getLongWidth();
5659
5660 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
5661 BestType = LongTy;
5662 } else {
5663 BestWidth = Target->getLongLongWidth();
5664
5665 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
5666 EnumTooLarge = true;
5667 BestType = LongLongTy;
5668 }
5669 }
5670 BestPromotionType = (BestWidth <= IntWidth ? IntTy : BestType);
5671 } else {
5672 // If there is no negative value, figure out the smallest type that fits
5673 // all of the enumerator values.
5674 // If it's packed, check also if it fits a char or a short.
5675 if (IsPacked && NumPositiveBits <= CharWidth) {
5676 BestType = UnsignedCharTy;
5677 BestPromotionType = IntTy;
5678 BestWidth = CharWidth;
5679 } else if (IsPacked && NumPositiveBits <= ShortWidth) {
5680 BestType = UnsignedShortTy;
5681 BestPromotionType = IntTy;
5682 BestWidth = ShortWidth;
5683 } else if (NumPositiveBits <= IntWidth) {
5684 BestType = UnsignedIntTy;
5685 BestWidth = IntWidth;
5686 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5687 ? UnsignedIntTy
5688 : IntTy;
5689 } else if (NumPositiveBits <= (BestWidth = Target->getLongWidth())) {
5690 BestType = UnsignedLongTy;
5691 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5692 ? UnsignedLongTy
5693 : LongTy;
5694 } else {
5695 BestWidth = Target->getLongLongWidth();
5696 if (NumPositiveBits > BestWidth) {
5697 // This can happen with bit-precise integer types, but those are not
5698 // allowed as the type for an enumerator per C23 6.7.2.2p4 and p12.
5699 // FIXME: GCC uses __int128_t and __uint128_t for cases that fit within
5700 // a 128-bit integer, we should consider doing the same.
5701 EnumTooLarge = true;
5702 }
5703 BestType = UnsignedLongLongTy;
5704 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5705 ? UnsignedLongLongTy
5706 : LongLongTy;
5707 }
5708 }
5709 return EnumTooLarge;
5710}
5711
5712bool ASTContext::isRepresentableIntegerValue(llvm::APSInt &Value, QualType T) {
5713 assert((T->isIntegralType(*this) || T->isEnumeralType()) &&
5714 "Integral type required!");
5715 unsigned BitWidth = getIntWidth(T);
5716
5717 if (Value.isUnsigned() || Value.isNonNegative()) {
5718 if (T->isSignedIntegerOrEnumerationType())
5719 --BitWidth;
5720 return Value.getActiveBits() <= BitWidth;
5721 }
5722 return Value.getSignificantBits() <= BitWidth;
5723}
5724
5725UnresolvedUsingType *ASTContext::getUnresolvedUsingTypeInternal(
5726 ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier,
5727 const UnresolvedUsingTypenameDecl *D, llvm::FoldingSetInsertToken Token,
5728 const Type *CanonicalType) const {
5729 void *Mem = Allocate(
5730 Size: UnresolvedUsingType::totalSizeToAlloc<
5731 FoldingSetPlaceholder<UnresolvedUsingType>, NestedNameSpecifier>(
5732 Counts: !!Token, Counts: !!Qualifier),
5733 Align: alignof(UnresolvedUsingType));
5734 auto *T = new (Mem) UnresolvedUsingType(Keyword, Qualifier, D, CanonicalType);
5735 if (Token) {
5736 auto *Placeholder = new (T->getFoldingSetPlaceholder())
5737 FoldingSetPlaceholder<UnresolvedUsingType>();
5738 UnresolvedUsingTypes.insert(N: Placeholder, Token);
5739 }
5740 Types.push_back(Elt: T);
5741 return T;
5742}
5743
5744CanQualType ASTContext::getCanonicalUnresolvedUsingType(
5745 const UnresolvedUsingTypenameDecl *D) const {
5746 D = D->getCanonicalDecl();
5747 if (D->TypeForDecl)
5748 return D->TypeForDecl->getCanonicalTypeUnqualified();
5749
5750 const Type *CanonicalType =
5751 getUnresolvedUsingTypeInternal(Keyword: ElaboratedTypeKeyword::None,
5752 /*Qualifier=*/std::nullopt, D,
5753 /*Token=*/{}, /*CanonicalType=*/nullptr);
5754 D->TypeForDecl = CanonicalType;
5755 return CanQualType::CreateUnsafe(Other: QualType(CanonicalType, 0));
5756}
5757
5758QualType
5759ASTContext::getUnresolvedUsingType(ElaboratedTypeKeyword Keyword,
5760 NestedNameSpecifier Qualifier,
5761 const UnresolvedUsingTypenameDecl *D) const {
5762 if (Keyword == ElaboratedTypeKeyword::None && !Qualifier) {
5763 if (const Type *T = D->TypeForDecl; T && !T->isCanonicalUnqualified())
5764 return QualType(T, 0);
5765
5766 const Type *CanonicalType = getCanonicalUnresolvedUsingType(D).getTypePtr();
5767 const Type *T =
5768 getUnresolvedUsingTypeInternal(Keyword: ElaboratedTypeKeyword::None,
5769 /*Qualifier=*/std::nullopt, D,
5770 /*Token=*/{}, CanonicalType);
5771 D->TypeForDecl = T;
5772 return QualType(T, 0);
5773 }
5774
5775 llvm::FoldingSetNodeID ID;
5776 UnresolvedUsingType::Profile(ID, Keyword, Qualifier, D);
5777
5778 llvm::FoldingSetInsertToken Token;
5779 if (FoldingSetPlaceholder<UnresolvedUsingType> *Placeholder =
5780 UnresolvedUsingTypes.lookup(ID, Token))
5781 return QualType(Placeholder->getType(), 0);
5782 assert(Token);
5783
5784 const Type *CanonicalType = getCanonicalUnresolvedUsingType(D).getTypePtr();
5785 const Type *T = getUnresolvedUsingTypeInternal(Keyword, Qualifier, D, Token,
5786 CanonicalType);
5787 return QualType(T, 0);
5788}
5789
5790QualType ASTContext::getAttributedType(attr::Kind attrKind,
5791 QualType modifiedType,
5792 QualType equivalentType,
5793 const Attr *attr) const {
5794 llvm::FoldingSetNodeID id;
5795 AttributedType::Profile(ID&: id, Ctx: *this, attrKind, modified: modifiedType, equivalent: equivalentType,
5796 attr);
5797
5798 llvm::FoldingSetInsertToken Token;
5799 AttributedType *type = AttributedTypes.lookup(ID: id, Token);
5800 if (type) return QualType(type, 0);
5801
5802 assert(!attr || attr->getKind() == attrKind);
5803
5804 QualType canon = getCanonicalType(T: equivalentType);
5805 type = new (*this, alignof(AttributedType))
5806 AttributedType(canon, attrKind, attr, modifiedType, equivalentType);
5807
5808 Types.push_back(Elt: type);
5809 AttributedTypes.insert(N: type, Token);
5810
5811 return QualType(type, 0);
5812}
5813
5814QualType ASTContext::getAttributedType(const Attr *attr, QualType modifiedType,
5815 QualType equivalentType) const {
5816 return getAttributedType(attrKind: attr->getKind(), modifiedType, equivalentType, attr);
5817}
5818
5819QualType ASTContext::getAttributedType(NullabilityKind nullability,
5820 QualType modifiedType,
5821 QualType equivalentType) const {
5822 switch (nullability) {
5823 case NullabilityKind::NonNull:
5824 return getAttributedType(attrKind: attr::TypeNonNull, modifiedType, equivalentType);
5825
5826 case NullabilityKind::Nullable:
5827 return getAttributedType(attrKind: attr::TypeNullable, modifiedType, equivalentType);
5828
5829 case NullabilityKind::NullableResult:
5830 return getAttributedType(attrKind: attr::TypeNullableResult, modifiedType,
5831 equivalentType);
5832
5833 case NullabilityKind::Unspecified:
5834 return getAttributedType(attrKind: attr::TypeNullUnspecified, modifiedType,
5835 equivalentType);
5836 }
5837
5838 llvm_unreachable("Unknown nullability kind");
5839}
5840
5841QualType ASTContext::getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr,
5842 QualType Wrapped) const {
5843 llvm::FoldingSetNodeID ID;
5844 BTFTagAttributedType::Profile(ID, Wrapped, BTFAttr);
5845
5846 llvm::FoldingSetInsertToken Token;
5847 BTFTagAttributedType *Ty = BTFTagAttributedTypes.lookup(ID, Token);
5848 if (Ty)
5849 return QualType(Ty, 0);
5850
5851 QualType Canon = getCanonicalType(T: Wrapped);
5852 Ty = new (*this, alignof(BTFTagAttributedType))
5853 BTFTagAttributedType(Canon, Wrapped, BTFAttr);
5854
5855 Types.push_back(Elt: Ty);
5856 BTFTagAttributedTypes.insert(N: Ty, Token);
5857
5858 return QualType(Ty, 0);
5859}
5860
5861QualType ASTContext::getOverflowBehaviorType(const OverflowBehaviorAttr *Attr,
5862 QualType Underlying) const {
5863 const IdentifierInfo *II = Attr->getBehaviorKind();
5864 StringRef IdentName = II->getName();
5865 OverflowBehaviorType::OverflowBehaviorKind Kind;
5866 if (IdentName == "wrap") {
5867 Kind = OverflowBehaviorType::OverflowBehaviorKind::Wrap;
5868 } else if (IdentName == "trap") {
5869 Kind = OverflowBehaviorType::OverflowBehaviorKind::Trap;
5870 } else {
5871 return Underlying;
5872 }
5873
5874 return getOverflowBehaviorType(Kind, Wrapped: Underlying);
5875}
5876
5877QualType ASTContext::getOverflowBehaviorType(
5878 OverflowBehaviorType::OverflowBehaviorKind Kind,
5879 QualType Underlying) const {
5880 assert(!Underlying->isOverflowBehaviorType() &&
5881 "Cannot have underlying types that are themselves OBTs");
5882
5883 llvm::FoldingSetInsertToken Token;
5884 if (OverflowBehaviorType *OBT =
5885 OverflowBehaviorTypes.lookup(Key: {Underlying, Kind}, Token)) {
5886 return QualType(OBT, 0);
5887 }
5888
5889 QualType Canonical;
5890 if (!Underlying.isCanonical() || Underlying.hasLocalQualifiers()) {
5891 SplitQualType canonSplit = getCanonicalType(T: Underlying).split();
5892 Canonical = getOverflowBehaviorType(Kind, Underlying: QualType(canonSplit.Ty, 0));
5893 Canonical = getQualifiedType(T: Canonical, Qs: canonSplit.Quals);
5894 assert(!OverflowBehaviorTypes.lookup({Underlying, Kind}, Token) &&
5895 "Shouldn't be in the map");
5896 }
5897
5898 OverflowBehaviorType *Ty = new (*this, alignof(OverflowBehaviorType))
5899 OverflowBehaviorType(*this, Canonical, Underlying, Kind);
5900
5901 Types.push_back(Elt: Ty);
5902 OverflowBehaviorTypes.insert(N: Ty, Token);
5903 return QualType(Ty, 0);
5904}
5905
5906QualType ASTContext::getHLSLAttributedResourceType(
5907 QualType Wrapped, QualType Contained,
5908 const HLSLAttributedResourceType::Attributes &Attrs) {
5909
5910 llvm::FoldingSetNodeID ID;
5911 HLSLAttributedResourceType::Profile(ID, Ctx: *this, Wrapped, Contained, Attrs);
5912
5913 llvm::FoldingSetInsertToken Token;
5914 HLSLAttributedResourceType *Ty =
5915 HLSLAttributedResourceTypes.lookup(ID, Token);
5916 if (Ty)
5917 return QualType(Ty, 0);
5918
5919 Ty = new (*this, alignof(HLSLAttributedResourceType))
5920 HLSLAttributedResourceType(Wrapped, Contained, Attrs);
5921
5922 Types.push_back(Elt: Ty);
5923 HLSLAttributedResourceTypes.insert(N: Ty, Token);
5924
5925 return QualType(Ty, 0);
5926}
5927
5928QualType ASTContext::getHLSLInlineSpirvType(uint32_t Opcode, uint32_t Size,
5929 uint32_t Alignment,
5930 ArrayRef<SpirvOperand> Operands) {
5931 llvm::FoldingSetNodeID ID;
5932 HLSLInlineSpirvType::Profile(ID, Opcode, Size, Alignment, Operands);
5933
5934 llvm::FoldingSetInsertToken Token;
5935 HLSLInlineSpirvType *Ty = HLSLInlineSpirvTypes.lookup(ID, Token);
5936 if (Ty)
5937 return QualType(Ty, 0);
5938
5939 void *Mem = Allocate(
5940 Size: HLSLInlineSpirvType::totalSizeToAlloc<SpirvOperand>(Counts: Operands.size()),
5941 Align: alignof(HLSLInlineSpirvType));
5942
5943 Ty = new (Mem) HLSLInlineSpirvType(Opcode, Size, Alignment, Operands);
5944
5945 Types.push_back(Elt: Ty);
5946 HLSLInlineSpirvTypes.insert(N: Ty, Token);
5947
5948 return QualType(Ty, 0);
5949}
5950
5951/// Retrieve a substitution-result type.
5952QualType ASTContext::getSubstTemplateTypeParmType(QualType Replacement,
5953 Decl *AssociatedDecl,
5954 unsigned Index,
5955 UnsignedOrNone PackIndex,
5956 bool Final) const {
5957 auto Key =
5958 std::make_tuple(args&: Replacement, args&: AssociatedDecl, args&: Index,
5959 args: PackIndex.toInternalRepresentation(), args: unsigned(Final));
5960 llvm::FoldingSetInsertToken Token;
5961 SubstTemplateTypeParmType *SubstParm =
5962 SubstTemplateTypeParmTypes.lookup(Key, Token);
5963
5964 if (!SubstParm) {
5965 void *Mem = Allocate(Size: SubstTemplateTypeParmType::totalSizeToAlloc<QualType>(
5966 Counts: !Replacement.isCanonical()),
5967 Align: alignof(SubstTemplateTypeParmType));
5968 SubstParm = new (Mem) SubstTemplateTypeParmType(Replacement, AssociatedDecl,
5969 Index, PackIndex, Final);
5970 Types.push_back(Elt: SubstParm);
5971 SubstTemplateTypeParmTypes.insert(N: SubstParm, Token);
5972 }
5973
5974 return QualType(SubstParm, 0);
5975}
5976
5977QualType
5978ASTContext::getSubstTemplateTypeParmPackType(Decl *AssociatedDecl,
5979 unsigned Index, bool Final,
5980 const TemplateArgument &ArgPack) {
5981#ifndef NDEBUG
5982 for (const auto &P : ArgPack.pack_elements())
5983 assert(P.getKind() == TemplateArgument::Type && "Pack contains a non-type");
5984#endif
5985
5986 llvm::FoldingSetNodeID ID;
5987 SubstTemplateTypeParmPackType::Profile(ID, AssociatedDecl, Index, Final,
5988 ArgPack);
5989 llvm::FoldingSetInsertToken Token;
5990 if (SubstTemplateTypeParmPackType *SubstParm =
5991 SubstTemplateTypeParmPackTypes.lookup(ID, Token))
5992 return QualType(SubstParm, 0);
5993
5994 QualType Canon;
5995 {
5996 TemplateArgument CanonArgPack = getCanonicalTemplateArgument(Arg: ArgPack);
5997 if (!AssociatedDecl->isCanonicalDecl() ||
5998 !CanonArgPack.structurallyEquals(Other: ArgPack)) {
5999 Canon = getSubstTemplateTypeParmPackType(
6000 AssociatedDecl: AssociatedDecl->getCanonicalDecl(), Index, Final, ArgPack: CanonArgPack);
6001 [[maybe_unused]] const auto *Nothing =
6002 SubstTemplateTypeParmPackTypes.lookup(ID, Token);
6003 assert(!Nothing);
6004 }
6005 }
6006
6007 auto *SubstParm = new (*this, alignof(SubstTemplateTypeParmPackType))
6008 SubstTemplateTypeParmPackType(Canon, AssociatedDecl, Index, Final,
6009 ArgPack);
6010 Types.push_back(Elt: SubstParm);
6011 SubstTemplateTypeParmPackTypes.insert(N: SubstParm, Token);
6012 return QualType(SubstParm, 0);
6013}
6014
6015QualType
6016ASTContext::getSubstBuiltinTemplatePack(const TemplateArgument &ArgPack) {
6017 assert(llvm::all_of(ArgPack.pack_elements(),
6018 [](const auto &P) {
6019 return P.getKind() == TemplateArgument::Type;
6020 }) &&
6021 "Pack contains a non-type");
6022
6023 llvm::FoldingSetNodeID ID;
6024 SubstBuiltinTemplatePackType::Profile(ID, ArgPack);
6025
6026 llvm::FoldingSetInsertToken Token;
6027 if (auto *T = SubstBuiltinTemplatePackTypes.lookup(ID, Token))
6028 return QualType(T, 0);
6029
6030 QualType Canon;
6031 TemplateArgument CanonArgPack = getCanonicalTemplateArgument(Arg: ArgPack);
6032 if (!CanonArgPack.structurallyEquals(Other: ArgPack)) {
6033 Canon = getSubstBuiltinTemplatePack(ArgPack: CanonArgPack);
6034 // Refresh Token, in case the recursive call above caused rehashing,
6035 // which would invalidate the bucket pointer.
6036 [[maybe_unused]] const auto *Nothing =
6037 SubstBuiltinTemplatePackTypes.lookup(ID, Token);
6038 assert(!Nothing);
6039 }
6040
6041 auto *PackType = new (*this, alignof(SubstBuiltinTemplatePackType))
6042 SubstBuiltinTemplatePackType(Canon, ArgPack);
6043 Types.push_back(Elt: PackType);
6044 SubstBuiltinTemplatePackTypes.insert(N: PackType, Token);
6045 return QualType(PackType, 0);
6046}
6047
6048/// Retrieve the template type parameter type for a template
6049/// parameter or parameter pack with the given depth, index, and (optionally)
6050/// name.
6051QualType
6052ASTContext::getTemplateTypeParmType(int Depth, int Index, bool ParameterPack,
6053 TemplateTypeParmDecl *TTPDecl) const {
6054 assert(Depth >= 0 && "Depth must be non-negative");
6055 assert(Index >= 0 && "Index must be non-negative");
6056
6057 auto Key = std::make_tuple(args: unsigned(Depth), args: unsigned(Index),
6058 args: unsigned(ParameterPack), args&: TTPDecl);
6059 llvm::FoldingSetInsertToken Token;
6060 TemplateTypeParmType *TypeParm = TemplateTypeParmTypes.lookup(Key, Token);
6061
6062 if (TypeParm)
6063 return QualType(TypeParm, 0);
6064
6065 if (TTPDecl) {
6066 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
6067 TypeParm = new (*this, alignof(TemplateTypeParmType))
6068 TemplateTypeParmType(Depth, Index, ParameterPack, TTPDecl, Canon);
6069 } else
6070 TypeParm = new (*this, alignof(TemplateTypeParmType)) TemplateTypeParmType(
6071 Depth, Index, ParameterPack, /*TTPDecl=*/nullptr, /*Canon=*/QualType());
6072
6073 Types.push_back(Elt: TypeParm);
6074 TemplateTypeParmTypes.insert(N: TypeParm, Token);
6075
6076 return QualType(TypeParm, 0);
6077}
6078
6079static ElaboratedTypeKeyword
6080getCanonicalElaboratedTypeKeyword(ElaboratedTypeKeyword Keyword) {
6081 switch (Keyword) {
6082 // These are just themselves.
6083 case ElaboratedTypeKeyword::None:
6084 case ElaboratedTypeKeyword::Struct:
6085 case ElaboratedTypeKeyword::Union:
6086 case ElaboratedTypeKeyword::Enum:
6087 case ElaboratedTypeKeyword::Interface:
6088 return Keyword;
6089
6090 // These are equivalent.
6091 case ElaboratedTypeKeyword::Typename:
6092 return ElaboratedTypeKeyword::None;
6093
6094 // These are functionally equivalent, so relying on their equivalence is
6095 // IFNDR. By making them equivalent, we disallow overloading, which at least
6096 // can produce a diagnostic.
6097 case ElaboratedTypeKeyword::Class:
6098 return ElaboratedTypeKeyword::Struct;
6099 }
6100 llvm_unreachable("unexpected keyword kind");
6101}
6102
6103TypeSourceInfo *ASTContext::getTemplateSpecializationTypeInfo(
6104 ElaboratedTypeKeyword Keyword, SourceLocation ElaboratedKeywordLoc,
6105 NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKeywordLoc,
6106 TemplateName Name, SourceLocation NameLoc,
6107 const TemplateArgumentListInfo &SpecifiedArgs,
6108 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
6109 QualType TST = getTemplateSpecializationType(
6110 Keyword, T: Name, SpecifiedArgs: SpecifiedArgs.arguments(), CanonicalArgs, Canon: Underlying);
6111
6112 TypeSourceInfo *TSI = CreateTypeSourceInfo(T: TST);
6113 TSI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>().set(
6114 ElaboratedKeywordLoc, QualifierLoc, TemplateKeywordLoc, NameLoc,
6115 TAL: SpecifiedArgs);
6116 return TSI;
6117}
6118
6119QualType ASTContext::getTemplateSpecializationType(
6120 ElaboratedTypeKeyword Keyword, TemplateName Template,
6121 ArrayRef<TemplateArgumentLoc> SpecifiedArgs,
6122 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
6123 SmallVector<TemplateArgument, 4> SpecifiedArgVec;
6124 SpecifiedArgVec.reserve(N: SpecifiedArgs.size());
6125 for (const TemplateArgumentLoc &Arg : SpecifiedArgs)
6126 SpecifiedArgVec.push_back(Elt: Arg.getArgument());
6127
6128 return getTemplateSpecializationType(Keyword, T: Template, SpecifiedArgs: SpecifiedArgVec,
6129 CanonicalArgs, Underlying);
6130}
6131
6132[[maybe_unused]] static bool
6133hasAnyPackExpansions(ArrayRef<TemplateArgument> Args) {
6134 for (const TemplateArgument &Arg : Args)
6135 if (Arg.isPackExpansion())
6136 return true;
6137 return false;
6138}
6139
6140QualType ASTContext::getCanonicalTemplateSpecializationType(
6141 ElaboratedTypeKeyword Keyword, TemplateName Template,
6142 ArrayRef<TemplateArgument> Args) const {
6143 assert(Template ==
6144 getCanonicalTemplateName(Template, /*IgnoreDeduced=*/true));
6145 assert((Keyword == ElaboratedTypeKeyword::None ||
6146 Template.getAsDependentTemplateName()));
6147#ifndef NDEBUG
6148 for (const auto &Arg : Args)
6149 assert(Arg.structurallyEquals(getCanonicalTemplateArgument(Arg)));
6150#endif
6151
6152 llvm::FoldingSetNodeID ID;
6153 TemplateSpecializationType::Profile(ID, Keyword, T: Template, Args, Underlying: QualType(),
6154 Context: *this);
6155 llvm::FoldingSetInsertToken Token;
6156 if (auto *T = TemplateSpecializationTypes.lookup(ID, Token))
6157 return QualType(T, 0);
6158
6159 void *Mem = Allocate(Size: sizeof(TemplateSpecializationType) +
6160 sizeof(TemplateArgument) * Args.size(),
6161 Align: alignof(TemplateSpecializationType));
6162 auto *Spec =
6163 new (Mem) TemplateSpecializationType(Keyword, Template,
6164 /*IsAlias=*/false, Args, QualType());
6165 assert(Spec->isDependentType() &&
6166 "canonical template specialization must be dependent");
6167 Types.push_back(Elt: Spec);
6168 TemplateSpecializationTypes.insert(N: Spec, Token);
6169 return QualType(Spec, 0);
6170}
6171
6172QualType ASTContext::getTemplateSpecializationType(
6173 ElaboratedTypeKeyword Keyword, TemplateName Template,
6174 ArrayRef<TemplateArgument> SpecifiedArgs,
6175 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
6176 const auto *TD = Template.getAsTemplateDecl(/*IgnoreDeduced=*/true);
6177 bool IsTypeAlias = TD && TD->isTypeAlias();
6178 if (Underlying.isNull()) {
6179 TemplateName CanonTemplate =
6180 getCanonicalTemplateName(Name: Template, /*IgnoreDeduced=*/true);
6181 ElaboratedTypeKeyword CanonKeyword =
6182 CanonTemplate.getAsDependentTemplateName()
6183 ? getCanonicalElaboratedTypeKeyword(Keyword)
6184 : ElaboratedTypeKeyword::None;
6185 bool NonCanonical = Template != CanonTemplate || Keyword != CanonKeyword;
6186 SmallVector<TemplateArgument, 4> CanonArgsVec;
6187 if (CanonicalArgs.empty()) {
6188 CanonArgsVec = SmallVector<TemplateArgument, 4>(SpecifiedArgs);
6189 NonCanonical |= canonicalizeTemplateArguments(Args: CanonArgsVec);
6190 CanonicalArgs = CanonArgsVec;
6191 } else {
6192 NonCanonical |= !llvm::equal(
6193 LRange&: SpecifiedArgs, RRange&: CanonicalArgs,
6194 P: [](const TemplateArgument &A, const TemplateArgument &B) {
6195 return A.structurallyEquals(Other: B);
6196 });
6197 }
6198
6199 // We can get here with an alias template when the specialization
6200 // contains a pack expansion that does not match up with a parameter
6201 // pack, or a builtin template which cannot be resolved due to dependency.
6202 assert((!isa_and_nonnull<TypeAliasTemplateDecl>(TD) ||
6203 hasAnyPackExpansions(CanonicalArgs)) &&
6204 "Caller must compute aliased type");
6205 IsTypeAlias = false;
6206
6207 Underlying = getCanonicalTemplateSpecializationType(
6208 Keyword: CanonKeyword, Template: CanonTemplate, Args: CanonicalArgs);
6209 if (!NonCanonical)
6210 return Underlying;
6211 }
6212 void *Mem = Allocate(Size: sizeof(TemplateSpecializationType) +
6213 sizeof(TemplateArgument) * SpecifiedArgs.size() +
6214 (IsTypeAlias ? sizeof(QualType) : 0),
6215 Align: alignof(TemplateSpecializationType));
6216 auto *Spec = new (Mem) TemplateSpecializationType(
6217 Keyword, Template, IsTypeAlias, SpecifiedArgs, Underlying);
6218 Types.push_back(Elt: Spec);
6219 return QualType(Spec, 0);
6220}
6221
6222QualType
6223ASTContext::getParenType(QualType InnerType) const {
6224 llvm::FoldingSetInsertToken Token;
6225 ParenType *T = ParenTypes.lookup(Key: InnerType, Token);
6226 if (T)
6227 return QualType(T, 0);
6228
6229 QualType Canon = InnerType;
6230 if (!Canon.isCanonical()) {
6231 Canon = getCanonicalType(T: InnerType);
6232 assert(!ParenTypes.lookup(InnerType, Token) &&
6233 "Paren canonical type broken");
6234 }
6235
6236 T = new (*this, alignof(ParenType)) ParenType(InnerType, Canon);
6237 Types.push_back(Elt: T);
6238 ParenTypes.insert(N: T, Token);
6239 return QualType(T, 0);
6240}
6241
6242QualType
6243ASTContext::getMacroQualifiedType(QualType UnderlyingTy,
6244 const IdentifierInfo *MacroII) const {
6245 QualType Canon = UnderlyingTy;
6246 if (!Canon.isCanonical())
6247 Canon = getCanonicalType(T: UnderlyingTy);
6248
6249 auto *newType = new (*this, alignof(MacroQualifiedType))
6250 MacroQualifiedType(UnderlyingTy, Canon, MacroII);
6251 Types.push_back(Elt: newType);
6252 return QualType(newType, 0);
6253}
6254
6255QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
6256 NestedNameSpecifier NNS,
6257 const IdentifierInfo *Name) const {
6258 llvm::FoldingSetNodeID ID;
6259 DependentNameType::Profile(ID, Keyword, NNS, Name);
6260
6261 llvm::FoldingSetInsertToken Token;
6262 if (DependentNameType *T = DependentNameTypes.lookup(ID, Token))
6263 return QualType(T, 0);
6264
6265 ElaboratedTypeKeyword CanonKeyword =
6266 getCanonicalElaboratedTypeKeyword(Keyword);
6267 NestedNameSpecifier CanonNNS = NNS.getCanonical();
6268
6269 QualType Canon;
6270 if (CanonKeyword != Keyword || CanonNNS != NNS) {
6271 Canon = getDependentNameType(Keyword: CanonKeyword, NNS: CanonNNS, Name);
6272 [[maybe_unused]] DependentNameType *T =
6273 DependentNameTypes.lookup(ID, Token);
6274 assert(!T && "broken canonicalization");
6275 assert(Canon.isCanonical());
6276 }
6277
6278 DependentNameType *T = new (*this, alignof(DependentNameType))
6279 DependentNameType(Keyword, NNS, Name, Canon);
6280 Types.push_back(Elt: T);
6281 DependentNameTypes.insert(N: T, Token);
6282 return QualType(T, 0);
6283}
6284
6285TemplateArgument ASTContext::getInjectedTemplateArg(NamedDecl *Param) const {
6286 TemplateArgument Arg;
6287 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Val: Param)) {
6288 QualType ArgType = getTypeDeclType(Decl: TTP);
6289 if (TTP->isParameterPack())
6290 ArgType = getPackExpansionType(Pattern: ArgType, NumExpansions: std::nullopt);
6291
6292 Arg = TemplateArgument(ArgType);
6293 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: Param)) {
6294 QualType T =
6295 NTTP->getType().getNonPackExpansionType().getNonLValueExprType(Context: *this);
6296 // For class NTTPs, ensure we include the 'const' so the type matches that
6297 // of a real template argument.
6298 // FIXME: It would be more faithful to model this as something like an
6299 // lvalue-to-rvalue conversion applied to a const-qualified lvalue.
6300 ExprValueKind VK = VK_PRValue;
6301 if (NTTP->getType()->isReferenceType()) {
6302 // As in Sema::BuildDeclarationNameExpr, a parameter of reference
6303 // type, even an rvalue reference, is an lvalue.
6304 VK = VK_LValue;
6305 } else if (T->isRecordType()) {
6306 // C++ [temp.param]p8: An id-expression naming a non-type
6307 // template-parameter of class type T denotes a static storage duration
6308 // object of type const T.
6309 T.addConst();
6310 VK = VK_LValue;
6311 }
6312 Expr *E = new (*this)
6313 DeclRefExpr(*this, NTTP, /*RefersToEnclosingVariableOrCapture=*/false,
6314 T, VK, NTTP->getLocation());
6315
6316 if (NTTP->isParameterPack())
6317 E = new (*this) PackExpansionExpr(E, NTTP->getLocation(), std::nullopt);
6318 Arg = TemplateArgument(E, /*IsCanonical=*/false);
6319 } else {
6320 auto *TTP = cast<TemplateTemplateParmDecl>(Val: Param);
6321 TemplateName Name = getQualifiedTemplateName(
6322 /*Qualifier=*/std::nullopt, /*TemplateKeyword=*/false,
6323 Template: TemplateName(TTP));
6324 if (TTP->isParameterPack())
6325 Arg = TemplateArgument(Name, /*NumExpansions=*/std::nullopt);
6326 else
6327 Arg = TemplateArgument(Name);
6328 }
6329
6330 if (Param->isTemplateParameterPack())
6331 Arg =
6332 TemplateArgument::CreatePackCopy(Context&: const_cast<ASTContext &>(*this), Args: Arg);
6333
6334 return Arg;
6335}
6336
6337QualType ASTContext::getPackExpansionType(QualType Pattern,
6338 UnsignedOrNone NumExpansions,
6339 bool ExpectPackInType) const {
6340 assert((!ExpectPackInType || Pattern->containsUnexpandedParameterPack()) &&
6341 "Pack expansions must expand one or more parameter packs");
6342
6343 auto Key = std::make_pair(x&: Pattern, y: NumExpansions.toInternalRepresentation());
6344
6345 llvm::FoldingSetInsertToken Token;
6346 PackExpansionType *T = PackExpansionTypes.lookup(Key, Token);
6347 if (T)
6348 return QualType(T, 0);
6349
6350 QualType Canon;
6351 if (!Pattern.isCanonical()) {
6352 Canon = getPackExpansionType(Pattern: getCanonicalType(T: Pattern), NumExpansions,
6353 /*ExpectPackInType=*/false);
6354
6355 // Find the insert position again, in case we inserted an element into
6356 // PackExpansionTypes and invalidated our insert position.
6357 PackExpansionTypes.lookup(Key, Token);
6358 }
6359
6360 T = new (*this, alignof(PackExpansionType))
6361 PackExpansionType(Pattern, Canon, NumExpansions);
6362 Types.push_back(Elt: T);
6363 PackExpansionTypes.insert(N: T, Token);
6364 return QualType(T, 0);
6365}
6366
6367/// CmpProtocolNames - Comparison predicate for sorting protocols
6368/// alphabetically.
6369static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
6370 ObjCProtocolDecl *const *RHS) {
6371 return DeclarationName::compare(LHS: (*LHS)->getDeclName(), RHS: (*RHS)->getDeclName());
6372}
6373
6374static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) {
6375 if (Protocols.empty()) return true;
6376
6377 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
6378 return false;
6379
6380 for (unsigned i = 1; i != Protocols.size(); ++i)
6381 if (CmpProtocolNames(LHS: &Protocols[i - 1], RHS: &Protocols[i]) >= 0 ||
6382 Protocols[i]->getCanonicalDecl() != Protocols[i])
6383 return false;
6384 return true;
6385}
6386
6387static void
6388SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) {
6389 // Sort protocols, keyed by name.
6390 llvm::array_pod_sort(Start: Protocols.begin(), End: Protocols.end(), Compare: CmpProtocolNames);
6391
6392 // Canonicalize.
6393 for (ObjCProtocolDecl *&P : Protocols)
6394 P = P->getCanonicalDecl();
6395
6396 // Remove duplicates.
6397 auto ProtocolsEnd = llvm::unique(R&: Protocols);
6398 Protocols.erase(CS: ProtocolsEnd, CE: Protocols.end());
6399}
6400
6401QualType ASTContext::getObjCObjectType(QualType BaseType,
6402 ObjCProtocolDecl * const *Protocols,
6403 unsigned NumProtocols) const {
6404 return getObjCObjectType(Base: BaseType, typeArgs: {}, protocols: ArrayRef(Protocols, NumProtocols),
6405 /*isKindOf=*/false);
6406}
6407
6408QualType ASTContext::getObjCObjectType(
6409 QualType baseType,
6410 ArrayRef<QualType> typeArgs,
6411 ArrayRef<ObjCProtocolDecl *> protocols,
6412 bool isKindOf) const {
6413 // If the base type is an interface and there aren't any protocols or
6414 // type arguments to add, then the interface type will do just fine.
6415 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
6416 isa<ObjCInterfaceType>(Val: baseType))
6417 return baseType;
6418
6419 // Look in the folding set for an existing type.
6420 llvm::FoldingSetNodeID ID;
6421 ObjCObjectTypeImpl::Profile(ID, Base: baseType, typeArgs, protocols, isKindOf);
6422 llvm::FoldingSetInsertToken Token;
6423 if (ObjCObjectType *QT = ObjCObjectTypes.lookup(ID, Token))
6424 return QualType(QT, 0);
6425
6426 // Determine the type arguments to be used for canonicalization,
6427 // which may be explicitly specified here or written on the base
6428 // type.
6429 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
6430 if (effectiveTypeArgs.empty()) {
6431 if (const auto *baseObject = baseType->getAs<ObjCObjectType>())
6432 effectiveTypeArgs = baseObject->getTypeArgs();
6433 }
6434
6435 // Build the canonical type, which has the canonical base type and a
6436 // sorted-and-uniqued list of protocols and the type arguments
6437 // canonicalized.
6438 QualType canonical;
6439 bool typeArgsAreCanonical = llvm::all_of(
6440 Range&: effectiveTypeArgs, P: [&](QualType type) { return type.isCanonical(); });
6441 bool protocolsSorted = areSortedAndUniqued(Protocols: protocols);
6442 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
6443 // Determine the canonical type arguments.
6444 ArrayRef<QualType> canonTypeArgs;
6445 SmallVector<QualType, 4> canonTypeArgsVec;
6446 if (!typeArgsAreCanonical) {
6447 canonTypeArgsVec.reserve(N: effectiveTypeArgs.size());
6448 for (auto typeArg : effectiveTypeArgs)
6449 canonTypeArgsVec.push_back(Elt: getCanonicalType(T: typeArg));
6450 canonTypeArgs = canonTypeArgsVec;
6451 } else {
6452 canonTypeArgs = effectiveTypeArgs;
6453 }
6454
6455 ArrayRef<ObjCProtocolDecl *> canonProtocols;
6456 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
6457 if (!protocolsSorted) {
6458 canonProtocolsVec.append(in_start: protocols.begin(), in_end: protocols.end());
6459 SortAndUniqueProtocols(Protocols&: canonProtocolsVec);
6460 canonProtocols = canonProtocolsVec;
6461 } else {
6462 canonProtocols = protocols;
6463 }
6464
6465 canonical = getObjCObjectType(baseType: getCanonicalType(T: baseType), typeArgs: canonTypeArgs,
6466 protocols: canonProtocols, isKindOf);
6467
6468 // Regenerate Token.
6469 ObjCObjectTypes.lookup(ID, Token);
6470 }
6471
6472 unsigned size = sizeof(ObjCObjectTypeImpl);
6473 size += typeArgs.size() * sizeof(QualType);
6474 size += protocols.size() * sizeof(ObjCProtocolDecl *);
6475 void *mem = Allocate(Size: size, Align: alignof(ObjCObjectTypeImpl));
6476 auto *T =
6477 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
6478 isKindOf);
6479
6480 Types.push_back(Elt: T);
6481 ObjCObjectTypes.insert(N: T, Token);
6482 return QualType(T, 0);
6483}
6484
6485/// Apply Objective-C protocol qualifiers to the given type.
6486/// If this is for the canonical type of a type parameter, we can apply
6487/// protocol qualifiers on the ObjCObjectPointerType.
6488QualType
6489ASTContext::applyObjCProtocolQualifiers(QualType type,
6490 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
6491 bool allowOnPointerType) const {
6492 hasError = false;
6493
6494 if (const auto *objT = dyn_cast<ObjCTypeParamType>(Val: type.getTypePtr())) {
6495 return getObjCTypeParamType(Decl: objT->getDecl(), protocols);
6496 }
6497
6498 // Apply protocol qualifiers to ObjCObjectPointerType.
6499 if (allowOnPointerType) {
6500 if (const auto *objPtr =
6501 dyn_cast<ObjCObjectPointerType>(Val: type.getTypePtr())) {
6502 const ObjCObjectType *objT = objPtr->getObjectType();
6503 // Merge protocol lists and construct ObjCObjectType.
6504 SmallVector<ObjCProtocolDecl*, 8> protocolsVec;
6505 protocolsVec.append(in_start: objT->qual_begin(),
6506 in_end: objT->qual_end());
6507 protocolsVec.append(in_start: protocols.begin(), in_end: protocols.end());
6508 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
6509 type = getObjCObjectType(
6510 baseType: objT->getBaseType(),
6511 typeArgs: objT->getTypeArgsAsWritten(),
6512 protocols,
6513 isKindOf: objT->isKindOfTypeAsWritten());
6514 return getObjCObjectPointerType(OIT: type);
6515 }
6516 }
6517
6518 // Apply protocol qualifiers to ObjCObjectType.
6519 if (const auto *objT = dyn_cast<ObjCObjectType>(Val: type.getTypePtr())){
6520 // FIXME: Check for protocols to which the class type is already
6521 // known to conform.
6522
6523 return getObjCObjectType(baseType: objT->getBaseType(),
6524 typeArgs: objT->getTypeArgsAsWritten(),
6525 protocols,
6526 isKindOf: objT->isKindOfTypeAsWritten());
6527 }
6528
6529 // If the canonical type is ObjCObjectType, ...
6530 if (type->isObjCObjectType()) {
6531 // Silently overwrite any existing protocol qualifiers.
6532 // TODO: determine whether that's the right thing to do.
6533
6534 // FIXME: Check for protocols to which the class type is already
6535 // known to conform.
6536 return getObjCObjectType(baseType: type, typeArgs: {}, protocols, isKindOf: false);
6537 }
6538
6539 // id<protocol-list>
6540 if (type->isObjCIdType()) {
6541 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
6542 type = getObjCObjectType(baseType: ObjCBuiltinIdTy, typeArgs: {}, protocols,
6543 isKindOf: objPtr->isKindOfType());
6544 return getObjCObjectPointerType(OIT: type);
6545 }
6546
6547 // Class<protocol-list>
6548 if (type->isObjCClassType()) {
6549 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
6550 type = getObjCObjectType(baseType: ObjCBuiltinClassTy, typeArgs: {}, protocols,
6551 isKindOf: objPtr->isKindOfType());
6552 return getObjCObjectPointerType(OIT: type);
6553 }
6554
6555 hasError = true;
6556 return type;
6557}
6558
6559QualType
6560ASTContext::getObjCTypeParamType(const ObjCTypeParamDecl *Decl,
6561 ArrayRef<ObjCProtocolDecl *> protocols) const {
6562 // We canonicalize to the underlying type.
6563 QualType Canonical = getCanonicalType(T: Decl->getUnderlyingType());
6564 if (!protocols.empty()) {
6565 // Apply the protocol qualifers.
6566 bool hasError;
6567 Canonical = getCanonicalType(T: applyObjCProtocolQualifiers(
6568 type: Canonical, protocols, hasError, allowOnPointerType: true /*allowOnPointerType*/));
6569 assert(!hasError && "Error when apply protocol qualifier to bound type");
6570 }
6571
6572 // Key on the canonical type the node is constructed with, which is what
6573 // Profile() reports; the decl's underlying type can be updated later.
6574 auto Key = std::make_tuple(args&: Decl, args&: Canonical, args&: protocols);
6575 llvm::FoldingSetInsertToken Token;
6576 if (ObjCTypeParamType *TypeParam = ObjCTypeParamTypes.lookup(Key, Token))
6577 return QualType(TypeParam, 0);
6578
6579 unsigned size = sizeof(ObjCTypeParamType);
6580 size += protocols.size() * sizeof(ObjCProtocolDecl *);
6581 void *mem = Allocate(Size: size, Align: alignof(ObjCTypeParamType));
6582 auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols);
6583
6584 Types.push_back(Elt: newType);
6585 ObjCTypeParamTypes.insert(N: newType, Token);
6586 return QualType(newType, 0);
6587}
6588
6589void ASTContext::adjustObjCTypeParamBoundType(const ObjCTypeParamDecl *Orig,
6590 ObjCTypeParamDecl *New) const {
6591 New->setTypeSourceInfo(getTrivialTypeSourceInfo(T: Orig->getUnderlyingType()));
6592 // Update TypeForDecl after updating TypeSourceInfo.
6593 auto *NewTypeParamTy = cast<ObjCTypeParamType>(Val: New->TypeForDecl);
6594 SmallVector<ObjCProtocolDecl *, 8> protocols;
6595 protocols.append(in_start: NewTypeParamTy->qual_begin(), in_end: NewTypeParamTy->qual_end());
6596 QualType UpdatedTy = getObjCTypeParamType(Decl: New, protocols);
6597 New->TypeForDecl = UpdatedTy.getTypePtr();
6598}
6599
6600/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
6601/// protocol list adopt all protocols in QT's qualified-id protocol
6602/// list.
6603bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
6604 ObjCInterfaceDecl *IC) {
6605 if (!QT->isObjCQualifiedIdType())
6606 return false;
6607
6608 if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) {
6609 // If both the right and left sides have qualifiers.
6610 for (auto *Proto : OPT->quals()) {
6611 if (!IC->ClassImplementsProtocol(lProto: Proto, lookupCategory: false))
6612 return false;
6613 }
6614 return true;
6615 }
6616 return false;
6617}
6618
6619/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
6620/// QT's qualified-id protocol list adopt all protocols in IDecl's list
6621/// of protocols.
6622bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
6623 ObjCInterfaceDecl *IDecl) {
6624 if (!QT->isObjCQualifiedIdType())
6625 return false;
6626 const auto *OPT = QT->getAs<ObjCObjectPointerType>();
6627 if (!OPT)
6628 return false;
6629 if (!IDecl->hasDefinition())
6630 return false;
6631 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
6632 CollectInheritedProtocols(CDecl: IDecl, Protocols&: InheritedProtocols);
6633 if (InheritedProtocols.empty())
6634 return false;
6635 // Check that if every protocol in list of id<plist> conforms to a protocol
6636 // of IDecl's, then bridge casting is ok.
6637 bool Conforms = false;
6638 for (auto *Proto : OPT->quals()) {
6639 Conforms = false;
6640 for (auto *PI : InheritedProtocols) {
6641 if (ProtocolCompatibleWithProtocol(lProto: Proto, rProto: PI)) {
6642 Conforms = true;
6643 break;
6644 }
6645 }
6646 if (!Conforms)
6647 break;
6648 }
6649 if (Conforms)
6650 return true;
6651
6652 for (auto *PI : InheritedProtocols) {
6653 // If both the right and left sides have qualifiers.
6654 bool Adopts = false;
6655 for (auto *Proto : OPT->quals()) {
6656 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
6657 if ((Adopts = ProtocolCompatibleWithProtocol(lProto: PI, rProto: Proto)))
6658 break;
6659 }
6660 if (!Adopts)
6661 return false;
6662 }
6663 return true;
6664}
6665
6666/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
6667/// the given object type.
6668QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
6669 llvm::FoldingSetInsertToken Token;
6670 if (ObjCObjectPointerType *QT = ObjCObjectPointerTypes.lookup(Key: ObjectT, Token))
6671 return QualType(QT, 0);
6672
6673 // Find the canonical object type.
6674 QualType Canonical;
6675 if (!ObjectT.isCanonical())
6676 Canonical = getObjCObjectPointerType(ObjectT: getCanonicalType(T: ObjectT));
6677
6678 // No match.
6679 void *Mem =
6680 Allocate(Size: sizeof(ObjCObjectPointerType), Align: alignof(ObjCObjectPointerType));
6681 auto *QType =
6682 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
6683
6684 Types.push_back(Elt: QType);
6685 ObjCObjectPointerTypes.insert(N: QType, Token);
6686 return QualType(QType, 0);
6687}
6688
6689/// getObjCInterfaceType - Return the unique reference to the type for the
6690/// specified ObjC interface decl. The list of protocols is optional.
6691QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
6692 ObjCInterfaceDecl *PrevDecl) const {
6693 if (Decl->TypeForDecl)
6694 return QualType(Decl->TypeForDecl, 0);
6695
6696 if (PrevDecl) {
6697 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
6698 Decl->TypeForDecl = PrevDecl->TypeForDecl;
6699 return QualType(PrevDecl->TypeForDecl, 0);
6700 }
6701
6702 // Prefer the definition, if there is one.
6703 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
6704 Decl = Def;
6705
6706 void *Mem = Allocate(Size: sizeof(ObjCInterfaceType), Align: alignof(ObjCInterfaceType));
6707 auto *T = new (Mem) ObjCInterfaceType(Decl);
6708 Decl->TypeForDecl = T;
6709 Types.push_back(Elt: T);
6710 return QualType(T, 0);
6711}
6712
6713/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
6714/// TypeOfExprType AST's (since expression's are never shared). For example,
6715/// multiple declarations that refer to "typeof(x)" all contain different
6716/// DeclRefExpr's. This doesn't effect the type checker, since it operates
6717/// on canonical type's (which are always unique).
6718QualType ASTContext::getTypeOfExprType(Expr *tofExpr, TypeOfKind Kind) const {
6719 TypeOfExprType *toe;
6720 if (tofExpr->isTypeDependent()) {
6721 llvm::FoldingSetNodeID ID;
6722 DependentTypeOfExprType::Profile(ID, Context: *this, E: tofExpr,
6723 IsUnqual: Kind == TypeOfKind::Unqualified);
6724
6725 llvm::FoldingSetInsertToken Token;
6726 DependentTypeOfExprType *Canon = DependentTypeOfExprTypes.lookup(ID, Token);
6727 if (Canon) {
6728 // We already have a "canonical" version of an identical, dependent
6729 // typeof(expr) type. Use that as our canonical type.
6730 toe = new (*this, alignof(TypeOfExprType)) TypeOfExprType(
6731 *this, tofExpr, Kind, QualType((TypeOfExprType *)Canon, 0));
6732 } else {
6733 // Build a new, canonical typeof(expr) type.
6734 Canon = new (*this, alignof(DependentTypeOfExprType))
6735 DependentTypeOfExprType(*this, tofExpr, Kind);
6736 DependentTypeOfExprTypes.insert(N: Canon, Token);
6737 toe = Canon;
6738 }
6739 } else {
6740 QualType Canonical = getCanonicalType(T: tofExpr->getType());
6741 toe = new (*this, alignof(TypeOfExprType))
6742 TypeOfExprType(*this, tofExpr, Kind, Canonical);
6743 }
6744 Types.push_back(Elt: toe);
6745 return QualType(toe, 0);
6746}
6747
6748/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
6749/// TypeOfType nodes. The only motivation to unique these nodes would be
6750/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
6751/// an issue. This doesn't affect the type checker, since it operates
6752/// on canonical types (which are always unique).
6753QualType ASTContext::getTypeOfType(QualType tofType, TypeOfKind Kind) const {
6754 QualType Canonical = getCanonicalType(T: tofType);
6755 auto *tot = new (*this, alignof(TypeOfType))
6756 TypeOfType(*this, tofType, Canonical, Kind);
6757 Types.push_back(Elt: tot);
6758 return QualType(tot, 0);
6759}
6760
6761/// getReferenceQualifiedType - Given an expr, will return the type for
6762/// that expression, as in [dcl.type.simple]p4 but without taking id-expressions
6763/// and class member access into account.
6764QualType ASTContext::getReferenceQualifiedType(const Expr *E) const {
6765 // C++11 [dcl.type.simple]p4:
6766 // [...]
6767 QualType T = E->getType();
6768 switch (E->getValueKind()) {
6769 // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the
6770 // type of e;
6771 case VK_XValue:
6772 return getRValueReferenceType(T);
6773 // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the
6774 // type of e;
6775 case VK_LValue:
6776 return getLValueReferenceType(T);
6777 // - otherwise, decltype(e) is the type of e.
6778 case VK_PRValue:
6779 return T;
6780 }
6781 llvm_unreachable("Unknown value kind");
6782}
6783
6784/// Unlike many "get<Type>" functions, we don't unique DecltypeType
6785/// nodes. This would never be helpful, since each such type has its own
6786/// expression, and would not give a significant memory saving, since there
6787/// is an Expr tree under each such type.
6788QualType ASTContext::getDecltypeType(Expr *E, QualType UnderlyingType) const {
6789 // C++11 [temp.type]p2:
6790 // If an expression e involves a template parameter, decltype(e) denotes a
6791 // unique dependent type. Two such decltype-specifiers refer to the same
6792 // type only if their expressions are equivalent (14.5.6.1).
6793 QualType CanonType;
6794 if (!E->isInstantiationDependent()) {
6795 CanonType = getCanonicalType(T: UnderlyingType);
6796 } else if (!UnderlyingType.isNull()) {
6797 CanonType = getDecltypeType(E, UnderlyingType: QualType());
6798 } else {
6799 llvm::FoldingSetNodeID ID;
6800 DependentDecltypeType::Profile(ID, Context: *this, E);
6801
6802 llvm::FoldingSetInsertToken Token;
6803 if (DependentDecltypeType *Canon = DependentDecltypeTypes.lookup(ID, Token))
6804 return QualType(Canon, 0);
6805
6806 // Build a new, canonical decltype(expr) type.
6807 auto *DT =
6808 new (*this, alignof(DependentDecltypeType)) DependentDecltypeType(E);
6809 DependentDecltypeTypes.insert(N: DT, Token);
6810 Types.push_back(Elt: DT);
6811 return QualType(DT, 0);
6812 }
6813 auto *DT = new (*this, alignof(DecltypeType))
6814 DecltypeType(E, UnderlyingType, CanonType);
6815 Types.push_back(Elt: DT);
6816 return QualType(DT, 0);
6817}
6818
6819QualType ASTContext::getPackIndexingType(QualType Pattern, Expr *IndexExpr,
6820 bool FullySubstituted,
6821 ArrayRef<QualType> Expansions,
6822 UnsignedOrNone Index) const {
6823 QualType Canonical;
6824 if (FullySubstituted && Index) {
6825 Canonical = getCanonicalType(T: Expansions[*Index]);
6826 } else {
6827 llvm::FoldingSetNodeID ID;
6828 PackIndexingType::Profile(ID, Context: *this, Pattern: Pattern.getCanonicalType(), E: IndexExpr,
6829 FullySubstituted, Expansions);
6830 llvm::FoldingSetInsertToken Token;
6831 PackIndexingType *Canon = DependentPackIndexingTypes.lookup(ID, Token);
6832 if (!Canon) {
6833 void *Mem = Allocate(
6834 Size: PackIndexingType::totalSizeToAlloc<QualType>(Counts: Expansions.size()),
6835 Align: TypeAlignment);
6836 Canon =
6837 new (Mem) PackIndexingType(QualType(), Pattern.getCanonicalType(),
6838 IndexExpr, FullySubstituted, Expansions);
6839 DependentPackIndexingTypes.insert(N: Canon, Token);
6840 }
6841 Canonical = QualType(Canon, 0);
6842 }
6843
6844 void *Mem =
6845 Allocate(Size: PackIndexingType::totalSizeToAlloc<QualType>(Counts: Expansions.size()),
6846 Align: TypeAlignment);
6847 auto *T = new (Mem) PackIndexingType(Canonical, Pattern, IndexExpr,
6848 FullySubstituted, Expansions);
6849 Types.push_back(Elt: T);
6850 return QualType(T, 0);
6851}
6852
6853/// getUnaryTransformationType - We don't unique these, since the memory
6854/// savings are minimal and these are rare.
6855QualType
6856ASTContext::getUnaryTransformType(QualType BaseType, QualType UnderlyingType,
6857 UnaryTransformType::UTTKind Kind) const {
6858 // Clear UnderlyingType for a dependent base before building the ID: that is
6859 // what the node is constructed with, and what Profile() reports.
6860 if (BaseType->isDependentType()) {
6861 assert(UnderlyingType.isNull() || BaseType == UnderlyingType);
6862 UnderlyingType = QualType();
6863 }
6864
6865 auto Key = std::make_tuple(args&: BaseType, args&: UnderlyingType, args&: Kind);
6866
6867 llvm::FoldingSetInsertToken Token;
6868 if (UnaryTransformType *UT = UnaryTransformTypes.lookup(Key, Token))
6869 return QualType(UT, 0);
6870
6871 QualType CanonType;
6872 if (!BaseType->isDependentType()) {
6873 CanonType = UnderlyingType.getCanonicalType();
6874 } else {
6875 if (QualType CanonBase = BaseType.getCanonicalType();
6876 BaseType != CanonBase) {
6877 CanonType = getUnaryTransformType(BaseType: CanonBase, UnderlyingType: QualType(), Kind);
6878 assert(CanonType.isCanonical());
6879 }
6880 }
6881
6882 auto *UT = new (*this, alignof(UnaryTransformType))
6883 UnaryTransformType(BaseType, UnderlyingType, Kind, CanonType);
6884 UnaryTransformTypes.insert(N: UT, Token);
6885 Types.push_back(Elt: UT);
6886 return QualType(UT, 0);
6887}
6888
6889/// getAutoType - Return the uniqued reference to the 'auto' type which has been
6890/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
6891/// canonical deduced-but-dependent 'auto' type.
6892QualType
6893ASTContext::getAutoType(DeducedKind DK, QualType DeducedAsType,
6894 AutoTypeKeyword Keyword,
6895 TemplateName TypeConstraintConcept,
6896 ArrayRef<TemplateArgument> TypeConstraintArgs) const {
6897 if (DK == DeducedKind::Undeduced && Keyword == AutoTypeKeyword::Auto &&
6898 TypeConstraintConcept.isNull()) {
6899 assert(DeducedAsType.isNull() && "");
6900 assert(TypeConstraintArgs.empty() && "");
6901 return getAutoDeductType();
6902 }
6903
6904 // Look in the folding set for an existing type.
6905 llvm::FoldingSetNodeID ID;
6906 AutoType::Profile(ID, Context: *this, DK, Deduced: DeducedAsType, Keyword,
6907 CD: TypeConstraintConcept, Arguments: TypeConstraintArgs);
6908 if (auto const AT_iter = AutoTypes.find_as(Val: ID); AT_iter != AutoTypes.end())
6909 return QualType(AT_iter->getSecond(), 0);
6910
6911 if (DK == DeducedKind::Deduced) {
6912 assert(!DeducedAsType.isNull() && "deduced type must be provided");
6913 } else {
6914 assert(DeducedAsType.isNull() && "deduced type must not be provided");
6915 if (!TypeConstraintConcept.isNull()) {
6916 bool AnyNonCanonArgs = false;
6917 TemplateName CanonicalConcept =
6918 getCanonicalTemplateName(Name: TypeConstraintConcept);
6919 auto CanonicalConceptArgs = ::getCanonicalTemplateArguments(
6920 C: *this, Args: TypeConstraintArgs, AnyNonCanonArgs);
6921 if (TypeConstraintConcept != CanonicalConcept || AnyNonCanonArgs)
6922 DeducedAsType = getAutoType(DK, DeducedAsType: QualType(), Keyword, TypeConstraintConcept: CanonicalConcept,
6923 TypeConstraintArgs: CanonicalConceptArgs);
6924 }
6925 }
6926
6927 void *Mem = Allocate(Size: sizeof(AutoType) +
6928 sizeof(TemplateArgument) * TypeConstraintArgs.size(),
6929 Align: alignof(AutoType));
6930 auto *AT = new (Mem) AutoType(DK, DeducedAsType, Keyword,
6931 TypeConstraintConcept, TypeConstraintArgs);
6932#ifndef NDEBUG
6933 llvm::FoldingSetNodeID InsertedID;
6934 AT->Profile(InsertedID, *this);
6935 assert(InsertedID == ID && "ID does not match");
6936#endif
6937 Types.push_back(Elt: AT);
6938 AutoTypes.try_emplace(Key: ID.Intern(Allocator&: BumpAlloc), Args&: AT);
6939 return QualType(AT, 0);
6940}
6941
6942QualType ASTContext::getUnconstrainedType(QualType T) const {
6943 QualType CanonT = T.getNonPackExpansionType().getCanonicalType();
6944
6945 // Remove a type-constraint from a top-level auto or decltype(auto).
6946 if (auto *AT = CanonT->getAs<AutoType>()) {
6947 if (!AT->isConstrained())
6948 return T;
6949 return getQualifiedType(
6950 T: getAutoType(DK: AT->getDeducedKind(), DeducedAsType: QualType(), Keyword: AT->getKeyword()),
6951 Qs: T.getQualifiers());
6952 }
6953
6954 // FIXME: We only support constrained auto at the top level in the type of a
6955 // non-type template parameter at the moment. Once we lift that restriction,
6956 // we'll need to recursively build types containing auto here.
6957 assert(!CanonT->getContainedAutoType() ||
6958 !CanonT->getContainedAutoType()->isConstrained());
6959 return T;
6960}
6961
6962/// Return the uniqued reference to the deduced template specialization type
6963/// which has been deduced to the given type, or to the canonical undeduced
6964/// such type, or the canonical deduced-but-dependent such type.
6965QualType ASTContext::getDeducedTemplateSpecializationType(
6966 DeducedKind DK, QualType DeducedAsType, ElaboratedTypeKeyword Keyword,
6967 TemplateName Template) const {
6968 // Look in the folding set for an existing type.
6969 llvm::FoldingSetInsertToken Token;
6970 llvm::FoldingSetNodeID ID;
6971 DeducedTemplateSpecializationType::Profile(ID, DK, Deduced: DeducedAsType, Keyword,
6972 Template);
6973 if (DeducedTemplateSpecializationType *DTST =
6974 DeducedTemplateSpecializationTypes.lookup(ID, Token))
6975 return QualType(DTST, 0);
6976
6977 if (DK == DeducedKind::Deduced) {
6978 assert(!DeducedAsType.isNull() && "deduced type must be provided");
6979 } else {
6980 assert(DeducedAsType.isNull() && "deduced type must not be provided");
6981 TemplateName CanonTemplateName = getCanonicalTemplateName(Name: Template);
6982 // FIXME: Can this be formed from a DependentTemplateName, such that the
6983 // keyword should be part of the canonical type?
6984 if (Keyword != ElaboratedTypeKeyword::None ||
6985 Template != CanonTemplateName) {
6986 DeducedAsType = getDeducedTemplateSpecializationType(
6987 DK, DeducedAsType: QualType(), Keyword: ElaboratedTypeKeyword::None, Template: CanonTemplateName);
6988 // Find the insertion position again.
6989 [[maybe_unused]] DeducedTemplateSpecializationType *DTST =
6990 DeducedTemplateSpecializationTypes.lookup(ID, Token);
6991 assert(!DTST && "broken canonicalization");
6992 }
6993 }
6994
6995 auto *DTST = new (*this, alignof(DeducedTemplateSpecializationType))
6996 DeducedTemplateSpecializationType(DK, DeducedAsType, Keyword, Template);
6997
6998#ifndef NDEBUG
6999 llvm::FoldingSetNodeID TempID;
7000 DTST->Profile(TempID);
7001 assert(ID == TempID && "ID does not match");
7002#endif
7003 Types.push_back(Elt: DTST);
7004 DeducedTemplateSpecializationTypes.insert(N: DTST, Token);
7005 return QualType(DTST, 0);
7006}
7007
7008/// getAtomicType - Return the uniqued reference to the atomic type for
7009/// the given value type.
7010QualType ASTContext::getAtomicType(QualType T) const {
7011 // Unique pointers, to guarantee there is only one pointer of a particular
7012 // structure.
7013 llvm::FoldingSetInsertToken Token;
7014 if (AtomicType *AT = AtomicTypes.lookup(Key: T, Token))
7015 return QualType(AT, 0);
7016
7017 // If the atomic value type isn't canonical, this won't be a canonical type
7018 // either, so fill in the canonical type field.
7019 QualType Canonical;
7020 if (!T.isCanonical()) {
7021 Canonical = getAtomicType(T: getCanonicalType(T));
7022
7023 assert(!AtomicTypes.lookup(T, Token) && "Shouldn't be in the map!");
7024 }
7025 auto *New = new (*this, alignof(AtomicType)) AtomicType(T, Canonical);
7026 Types.push_back(Elt: New);
7027 AtomicTypes.insert(N: New, Token);
7028 return QualType(New, 0);
7029}
7030
7031/// getAutoDeductType - Get type pattern for deducing against 'auto'.
7032QualType ASTContext::getAutoDeductType() const {
7033 if (AutoDeductTy.isNull())
7034 AutoDeductTy = QualType(
7035 new (*this, alignof(AutoType))
7036 AutoType(DeducedKind::Undeduced, QualType(), AutoTypeKeyword::Auto,
7037 /*TypeConstraintConcept=*/TemplateName(),
7038 /*TypeConstraintArgs=*/{}),
7039 0);
7040 return AutoDeductTy;
7041}
7042
7043/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
7044QualType ASTContext::getAutoRRefDeductType() const {
7045 if (AutoRRefDeductTy.isNull())
7046 AutoRRefDeductTy = getRValueReferenceType(T: getAutoDeductType());
7047 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
7048 return AutoRRefDeductTy;
7049}
7050
7051/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
7052/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
7053/// needs to agree with the definition in <stddef.h>.
7054QualType ASTContext::getSizeType() const {
7055 return getPredefinedSugarType(KD: PredefinedSugarType::Kind::SizeT);
7056}
7057
7058CanQualType ASTContext::getCanonicalSizeType() const {
7059 return getFromTargetType(Type: Target->getSizeType());
7060}
7061
7062/// Return the unique signed counterpart of the integer type
7063/// corresponding to size_t.
7064QualType ASTContext::getSignedSizeType() const {
7065 return getPredefinedSugarType(KD: PredefinedSugarType::Kind::SignedSizeT);
7066}
7067
7068/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
7069/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
7070QualType ASTContext::getPointerDiffType() const {
7071 return getPredefinedSugarType(KD: PredefinedSugarType::Kind::PtrdiffT);
7072}
7073
7074/// Return the unique unsigned counterpart of "ptrdiff_t"
7075/// integer type. The standard (C11 7.21.6.1p7) refers to this type
7076/// in the definition of %tu format specifier.
7077QualType ASTContext::getUnsignedPointerDiffType() const {
7078 return getFromTargetType(Type: Target->getUnsignedPtrDiffType(AddrSpace: LangAS::Default));
7079}
7080
7081/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
7082CanQualType ASTContext::getIntMaxType() const {
7083 return getFromTargetType(Type: Target->getIntMaxType());
7084}
7085
7086/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
7087CanQualType ASTContext::getUIntMaxType() const {
7088 return getFromTargetType(Type: Target->getUIntMaxType());
7089}
7090
7091/// getSignedWCharType - Return the type of "signed wchar_t".
7092/// Used when in C++, as a GCC extension.
7093QualType ASTContext::getSignedWCharType() const {
7094 // FIXME: derive from "Target" ?
7095 return WCharTy;
7096}
7097
7098/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
7099/// Used when in C++, as a GCC extension.
7100QualType ASTContext::getUnsignedWCharType() const {
7101 // FIXME: derive from "Target" ?
7102 return UnsignedIntTy;
7103}
7104
7105QualType ASTContext::getIntPtrType() const {
7106 return getFromTargetType(Type: Target->getIntPtrType());
7107}
7108
7109QualType ASTContext::getUIntPtrType() const {
7110 return getCorrespondingUnsignedType(T: getIntPtrType());
7111}
7112
7113/// Return the unique type for "pid_t" defined in
7114/// <sys/types.h>. We need this to compute the correct type for vfork().
7115QualType ASTContext::getProcessIDType() const {
7116 return getFromTargetType(Type: Target->getProcessIDType());
7117}
7118
7119//===----------------------------------------------------------------------===//
7120// Type Operators
7121//===----------------------------------------------------------------------===//
7122
7123CanQualType ASTContext::getCanonicalParamType(QualType T) const {
7124 // Push qualifiers into arrays, and then discard any remaining
7125 // qualifiers.
7126 T = getCanonicalType(T);
7127 T = getVariableArrayDecayedType(type: T);
7128 const Type *Ty = T.getTypePtr();
7129 QualType Result;
7130 if (getLangOpts().HLSL && isa<ConstantArrayType>(Val: Ty)) {
7131 Result = getArrayParameterType(Ty: QualType(Ty, 0));
7132 } else if (isa<ArrayType>(Val: Ty)) {
7133 Result = getArrayDecayedType(T: QualType(Ty,0));
7134 } else if (isa<FunctionType>(Val: Ty)) {
7135 Result = getPointerType(T: QualType(Ty, 0));
7136 } else {
7137 Result = QualType(Ty, 0);
7138 }
7139
7140 return CanQualType::CreateUnsafe(Other: Result);
7141}
7142
7143QualType ASTContext::getUnqualifiedArrayType(QualType type,
7144 Qualifiers &quals) const {
7145 SplitQualType splitType = type.getSplitUnqualifiedType();
7146
7147 // FIXME: getSplitUnqualifiedType() actually walks all the way to
7148 // the unqualified desugared type and then drops it on the floor.
7149 // We then have to strip that sugar back off with
7150 // getUnqualifiedDesugaredType(), which is silly.
7151 const auto *AT =
7152 dyn_cast<ArrayType>(Val: splitType.Ty->getUnqualifiedDesugaredType());
7153
7154 // If we don't have an array, just use the results in splitType.
7155 if (!AT) {
7156 quals = splitType.Quals;
7157 return QualType(splitType.Ty, 0);
7158 }
7159
7160 // Otherwise, recurse on the array's element type.
7161 QualType elementType = AT->getElementType();
7162 QualType unqualElementType = getUnqualifiedArrayType(type: elementType, quals);
7163
7164 // If that didn't change the element type, AT has no qualifiers, so we
7165 // can just use the results in splitType.
7166 if (elementType == unqualElementType) {
7167 assert(quals.empty()); // from the recursive call
7168 quals = splitType.Quals;
7169 return QualType(splitType.Ty, 0);
7170 }
7171
7172 // Otherwise, add in the qualifiers from the outermost type, then
7173 // build the type back up.
7174 quals.addConsistentQualifiers(qs: splitType.Quals);
7175
7176 if (const auto *CAT = dyn_cast<ConstantArrayType>(Val: AT)) {
7177 return getConstantArrayType(EltTy: unqualElementType, ArySizeIn: CAT->getSize(),
7178 SizeExpr: CAT->getSizeExpr(), ASM: CAT->getSizeModifier(), IndexTypeQuals: 0);
7179 }
7180
7181 if (const auto *IAT = dyn_cast<IncompleteArrayType>(Val: AT)) {
7182 return getIncompleteArrayType(elementType: unqualElementType, ASM: IAT->getSizeModifier(), elementTypeQuals: 0);
7183 }
7184
7185 if (const auto *VAT = dyn_cast<VariableArrayType>(Val: AT)) {
7186 return getVariableArrayType(EltTy: unqualElementType, NumElts: VAT->getSizeExpr(),
7187 ASM: VAT->getSizeModifier(),
7188 IndexTypeQuals: VAT->getIndexTypeCVRQualifiers());
7189 }
7190
7191 const auto *DSAT = cast<DependentSizedArrayType>(Val: AT);
7192 return getDependentSizedArrayType(elementType: unqualElementType, numElements: DSAT->getSizeExpr(),
7193 ASM: DSAT->getSizeModifier(), elementTypeQuals: 0);
7194}
7195
7196/// Attempt to unwrap two types that may both be array types with the same bound
7197/// (or both be array types of unknown bound) for the purpose of comparing the
7198/// cv-decomposition of two types per C++ [conv.qual].
7199///
7200/// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
7201/// C++20 [conv.qual], if permitted by the current language mode.
7202void ASTContext::UnwrapSimilarArrayTypes(QualType &T1, QualType &T2,
7203 bool AllowPiMismatch) const {
7204 while (true) {
7205 auto *AT1 = getAsArrayType(T: T1);
7206 if (!AT1)
7207 return;
7208
7209 auto *AT2 = getAsArrayType(T: T2);
7210 if (!AT2)
7211 return;
7212
7213 // If we don't have two array types with the same constant bound nor two
7214 // incomplete array types, we've unwrapped everything we can.
7215 // C++20 also permits one type to be a constant array type and the other
7216 // to be an incomplete array type.
7217 // FIXME: Consider also unwrapping array of unknown bound and VLA.
7218 if (auto *CAT1 = dyn_cast<ConstantArrayType>(Val: AT1)) {
7219 auto *CAT2 = dyn_cast<ConstantArrayType>(Val: AT2);
7220 if (!((CAT2 && CAT1->getSize() == CAT2->getSize()) ||
7221 (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
7222 isa<IncompleteArrayType>(Val: AT2))))
7223 return;
7224 } else if (isa<IncompleteArrayType>(Val: AT1)) {
7225 if (!(isa<IncompleteArrayType>(Val: AT2) ||
7226 (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
7227 isa<ConstantArrayType>(Val: AT2))))
7228 return;
7229 } else {
7230 return;
7231 }
7232
7233 T1 = AT1->getElementType();
7234 T2 = AT2->getElementType();
7235 }
7236}
7237
7238/// Attempt to unwrap two types that may be similar (C++ [conv.qual]).
7239///
7240/// If T1 and T2 are both pointer types of the same kind, or both array types
7241/// with the same bound, unwraps layers from T1 and T2 until a pointer type is
7242/// unwrapped. Top-level qualifiers on T1 and T2 are ignored.
7243///
7244/// This function will typically be called in a loop that successively
7245/// "unwraps" pointer and pointer-to-member types to compare them at each
7246/// level.
7247///
7248/// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
7249/// C++20 [conv.qual], if permitted by the current language mode.
7250///
7251/// \return \c true if a pointer type was unwrapped, \c false if we reached a
7252/// pair of types that can't be unwrapped further.
7253bool ASTContext::UnwrapSimilarTypes(QualType &T1, QualType &T2,
7254 bool AllowPiMismatch) const {
7255 UnwrapSimilarArrayTypes(T1, T2, AllowPiMismatch);
7256
7257 const auto *T1PtrType = T1->getAs<PointerType>();
7258 const auto *T2PtrType = T2->getAs<PointerType>();
7259 if (T1PtrType && T2PtrType) {
7260 T1 = T1PtrType->getPointeeType();
7261 T2 = T2PtrType->getPointeeType();
7262 return true;
7263 }
7264
7265 if (const auto *T1MPType = T1->getAsCanonical<MemberPointerType>(),
7266 *T2MPType = T2->getAsCanonical<MemberPointerType>();
7267 T1MPType && T2MPType) {
7268 // Compare the qualifiers of the canonical type, as the non-canonical type
7269 // may have qualifiers pointing to a base or derived class.
7270 if (T1MPType->getQualifier() != T2MPType->getQualifier())
7271 return false;
7272 // Get the pointee types of the non-canonical type, in order to preserve
7273 // their sugar.
7274 T1 = T1->getAs<MemberPointerType>()->getPointeeType();
7275 T2 = T2->getAs<MemberPointerType>()->getPointeeType();
7276 return true;
7277 }
7278
7279 if (getLangOpts().ObjC) {
7280 const auto *T1OPType = T1->getAs<ObjCObjectPointerType>();
7281 const auto *T2OPType = T2->getAs<ObjCObjectPointerType>();
7282 if (T1OPType && T2OPType) {
7283 T1 = T1OPType->getPointeeType();
7284 T2 = T2OPType->getPointeeType();
7285 return true;
7286 }
7287 }
7288
7289 // FIXME: Block pointers, too?
7290
7291 return false;
7292}
7293
7294bool ASTContext::hasSimilarType(QualType T1, QualType T2) const {
7295 while (true) {
7296 Qualifiers Quals;
7297 T1 = getUnqualifiedArrayType(type: T1, quals&: Quals);
7298 T2 = getUnqualifiedArrayType(type: T2, quals&: Quals);
7299 if (hasSameType(T1, T2))
7300 return true;
7301 if (!UnwrapSimilarTypes(T1, T2))
7302 return false;
7303 }
7304}
7305
7306bool ASTContext::hasCvrSimilarType(QualType T1, QualType T2) {
7307 while (true) {
7308 Qualifiers Quals1, Quals2;
7309 T1 = getUnqualifiedArrayType(type: T1, quals&: Quals1);
7310 T2 = getUnqualifiedArrayType(type: T2, quals&: Quals2);
7311
7312 Quals1.removeCVRQualifiers();
7313 Quals2.removeCVRQualifiers();
7314 if (Quals1 != Quals2)
7315 return false;
7316
7317 if (hasSameType(T1, T2))
7318 return true;
7319
7320 if (!UnwrapSimilarTypes(T1, T2, /*AllowPiMismatch*/ false))
7321 return false;
7322 }
7323}
7324
7325DeclarationNameInfo
7326ASTContext::getNameForTemplate(TemplateName Name,
7327 SourceLocation NameLoc) const {
7328 switch (Name.getKind()) {
7329 case TemplateName::QualifiedTemplate:
7330 case TemplateName::Template:
7331 // DNInfo work in progress: CHECKME: what about DNLoc?
7332 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
7333 NameLoc);
7334
7335 case TemplateName::OverloadedTemplate: {
7336 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
7337 // DNInfo work in progress: CHECKME: what about DNLoc?
7338 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
7339 }
7340
7341 case TemplateName::AssumedTemplate: {
7342 AssumedTemplateStorage *Storage = Name.getAsAssumedTemplateName();
7343 return DeclarationNameInfo(Storage->getDeclName(), NameLoc);
7344 }
7345
7346 case TemplateName::DependentTemplate: {
7347 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
7348 IdentifierOrOverloadedOperator TN = DTN->getName();
7349 DeclarationName DName;
7350 if (const IdentifierInfo *II = TN.getIdentifier()) {
7351 DName = DeclarationNames.getIdentifier(ID: II);
7352 return DeclarationNameInfo(DName, NameLoc);
7353 } else {
7354 DName = DeclarationNames.getCXXOperatorName(Op: TN.getOperator());
7355 // DNInfo work in progress: FIXME: source locations?
7356 DeclarationNameLoc DNLoc =
7357 DeclarationNameLoc::makeCXXOperatorNameLoc(Range: SourceRange());
7358 return DeclarationNameInfo(DName, NameLoc, DNLoc);
7359 }
7360 }
7361
7362 case TemplateName::SubstTemplateTemplateParm: {
7363 SubstTemplateTemplateParmStorage *subst
7364 = Name.getAsSubstTemplateTemplateParm();
7365 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
7366 NameLoc);
7367 }
7368
7369 case TemplateName::SubstTemplateTemplateParmPack: {
7370 SubstTemplateTemplateParmPackStorage *subst
7371 = Name.getAsSubstTemplateTemplateParmPack();
7372 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
7373 NameLoc);
7374 }
7375 case TemplateName::UsingTemplate:
7376 return DeclarationNameInfo(Name.getAsUsingShadowDecl()->getDeclName(),
7377 NameLoc);
7378 case TemplateName::DeducedTemplate: {
7379 DeducedTemplateStorage *DTS = Name.getAsDeducedTemplateName();
7380 return getNameForTemplate(Name: DTS->getUnderlying(), NameLoc);
7381 }
7382 case TemplateName::PackIndexingTemplate: {
7383 PackIndexingTemplateStorage *PI = Name.getAsPackIndexingTemplate();
7384 return getNameForTemplate(Name: PI->getPattern(), NameLoc);
7385 }
7386 }
7387
7388 llvm_unreachable("bad template name kind!");
7389}
7390
7391const TemplateArgument *
7392ASTContext::getDefaultTemplateArgumentOrNone(const NamedDecl *P) const {
7393 auto handleParam = [](auto *TP) -> const TemplateArgument * {
7394 if (!TP->hasDefaultArgument())
7395 return nullptr;
7396 return &TP->getDefaultArgument().getArgument();
7397 };
7398 switch (P->getKind()) {
7399 case NamedDecl::TemplateTypeParm:
7400 return handleParam(cast<TemplateTypeParmDecl>(Val: P));
7401 case NamedDecl::NonTypeTemplateParm:
7402 return handleParam(cast<NonTypeTemplateParmDecl>(Val: P));
7403 case NamedDecl::TemplateTemplateParm:
7404 return handleParam(cast<TemplateTemplateParmDecl>(Val: P));
7405 default:
7406 llvm_unreachable("Unexpected template parameter kind");
7407 }
7408}
7409
7410TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name,
7411 bool IgnoreDeduced) const {
7412 while (std::optional<TemplateName> UnderlyingOrNone =
7413 Name.desugar(IgnoreDeduced))
7414 Name = *UnderlyingOrNone;
7415
7416 switch (Name.getKind()) {
7417 case TemplateName::Template: {
7418 TemplateDecl *Template = Name.getAsTemplateDecl();
7419 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Val: Template))
7420 Template = getCanonicalTemplateTemplateParmDecl(TTP);
7421
7422 // The canonical template name is the canonical template declaration.
7423 return TemplateName(cast<TemplateDecl>(Val: Template->getCanonicalDecl()));
7424 }
7425
7426 case TemplateName::AssumedTemplate:
7427 // An assumed template is just a name, so it is already canonical.
7428 return Name;
7429
7430 case TemplateName::OverloadedTemplate:
7431 llvm_unreachable("cannot canonicalize overloaded template");
7432
7433 case TemplateName::DependentTemplate: {
7434 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
7435 assert(DTN && "Non-dependent template names must refer to template decls.");
7436 NestedNameSpecifier Qualifier = DTN->getQualifier();
7437 NestedNameSpecifier CanonQualifier = Qualifier.getCanonical();
7438 if (Qualifier != CanonQualifier || !DTN->hasTemplateKeyword())
7439 return getDependentTemplateName(Name: {CanonQualifier, DTN->getName(),
7440 /*HasTemplateKeyword=*/true});
7441 return Name;
7442 }
7443
7444 case TemplateName::SubstTemplateTemplateParmPack: {
7445 SubstTemplateTemplateParmPackStorage *subst =
7446 Name.getAsSubstTemplateTemplateParmPack();
7447 TemplateArgument canonArgPack =
7448 getCanonicalTemplateArgument(Arg: subst->getArgumentPack());
7449 return getSubstTemplateTemplateParmPack(
7450 ArgPack: canonArgPack, AssociatedDecl: subst->getAssociatedDecl()->getCanonicalDecl(),
7451 Index: subst->getIndex(), Final: subst->getFinal());
7452 }
7453
7454 case TemplateName::PackIndexingTemplate: {
7455 PackIndexingTemplateStorage *PI = Name.getAsPackIndexingTemplate();
7456 SmallVector<TemplateName, 4> CanonExpansions;
7457 for (TemplateName T : PI->getExpansions())
7458 CanonExpansions.push_back(Elt: getCanonicalTemplateName(Name: T, IgnoreDeduced));
7459 return getPackIndexingTemplateName(
7460 Pattern: getCanonicalTemplateName(Name: PI->getPattern(), IgnoreDeduced),
7461 IndexExpr: PI->getIndexExpr(), FullySubstituted: PI->isFullySubstituted(), Expansions: CanonExpansions);
7462 }
7463 case TemplateName::DeducedTemplate: {
7464 assert(IgnoreDeduced == false);
7465 DeducedTemplateStorage *DTS = Name.getAsDeducedTemplateName();
7466 DefaultArguments DefArgs = DTS->getDefaultArguments();
7467 TemplateName Underlying = DTS->getUnderlying();
7468
7469 TemplateName CanonUnderlying =
7470 getCanonicalTemplateName(Name: Underlying, /*IgnoreDeduced=*/true);
7471 bool NonCanonical = CanonUnderlying != Underlying;
7472 auto CanonArgs =
7473 getCanonicalTemplateArguments(C: *this, Args: DefArgs.Args, AnyNonCanonArgs&: NonCanonical);
7474
7475 ArrayRef<NamedDecl *> Params =
7476 CanonUnderlying.getAsTemplateDecl()->getTemplateParameters()->asArray();
7477 assert(CanonArgs.size() <= Params.size());
7478 // A deduced template name which deduces the same default arguments already
7479 // declared in the underlying template is the same template as the
7480 // underlying template. We need need to note any arguments which differ from
7481 // the corresponding declaration. If any argument differs, we must build a
7482 // deduced template name.
7483 for (int I = CanonArgs.size() - 1; I >= 0; --I) {
7484 const TemplateArgument *A = getDefaultTemplateArgumentOrNone(P: Params[I]);
7485 if (!A)
7486 break;
7487 auto CanonParamDefArg = getCanonicalTemplateArgument(Arg: *A);
7488 TemplateArgument &CanonDefArg = CanonArgs[I];
7489 if (CanonDefArg.structurallyEquals(Other: CanonParamDefArg))
7490 continue;
7491 // Keep popping from the back any deault arguments which are the same.
7492 if (I == int(CanonArgs.size() - 1))
7493 CanonArgs.pop_back();
7494 NonCanonical = true;
7495 }
7496 return NonCanonical ? getDeducedTemplateName(
7497 Underlying: CanonUnderlying,
7498 /*DefaultArgs=*/{.StartPos: DefArgs.StartPos, .Args: CanonArgs})
7499 : Name;
7500 }
7501 case TemplateName::UsingTemplate:
7502 case TemplateName::QualifiedTemplate:
7503 case TemplateName::SubstTemplateTemplateParm:
7504 llvm_unreachable("always sugar node");
7505 }
7506
7507 llvm_unreachable("bad template name!");
7508}
7509
7510bool ASTContext::hasSameTemplateName(const TemplateName &X,
7511 const TemplateName &Y,
7512 bool IgnoreDeduced) const {
7513 return getCanonicalTemplateName(Name: X, IgnoreDeduced) ==
7514 getCanonicalTemplateName(Name: Y, IgnoreDeduced);
7515}
7516
7517bool ASTContext::isSameAssociatedConstraint(
7518 const AssociatedConstraint &ACX, const AssociatedConstraint &ACY) const {
7519 if (ACX.ArgPackSubstIndex != ACY.ArgPackSubstIndex)
7520 return false;
7521 if (!isSameConstraintExpr(XCE: ACX.ConstraintExpr, YCE: ACY.ConstraintExpr))
7522 return false;
7523 return true;
7524}
7525
7526bool ASTContext::isSameConstraintExpr(const Expr *XCE, const Expr *YCE) const {
7527 if (!XCE != !YCE)
7528 return false;
7529
7530 if (!XCE)
7531 return true;
7532
7533 llvm::FoldingSetNodeID XCEID, YCEID;
7534 XCE->Profile(ID&: XCEID, Context: *this, /*Canonical=*/true, /*ProfileLambdaExpr=*/true);
7535 YCE->Profile(ID&: YCEID, Context: *this, /*Canonical=*/true, /*ProfileLambdaExpr=*/true);
7536 return XCEID == YCEID;
7537}
7538
7539bool ASTContext::isSameTypeConstraint(const TypeConstraint *XTC,
7540 const TypeConstraint *YTC) const {
7541 if (!XTC != !YTC)
7542 return false;
7543
7544 if (!XTC)
7545 return true;
7546
7547 TemplateDecl *NCX = XTC->getNamedConcept().getAsTemplateDecl();
7548 TemplateDecl *NCY = YTC->getNamedConcept().getAsTemplateDecl();
7549 if (!NCX || !NCY || !isSameEntity(X: NCX, Y: NCY))
7550 return false;
7551 if (XTC->getConceptReference()->hasExplicitTemplateArgs() !=
7552 YTC->getConceptReference()->hasExplicitTemplateArgs())
7553 return false;
7554 if (XTC->getConceptReference()->hasExplicitTemplateArgs())
7555 if (XTC->getConceptReference()
7556 ->getTemplateArgsAsWritten()
7557 ->NumTemplateArgs !=
7558 YTC->getConceptReference()->getTemplateArgsAsWritten()->NumTemplateArgs)
7559 return false;
7560
7561 // Compare slowly by profiling.
7562 //
7563 // We couldn't compare the profiling result for the template
7564 // args here. Consider the following example in different modules:
7565 //
7566 // template <__integer_like _Tp, C<_Tp> Sentinel>
7567 // constexpr _Tp operator()(_Tp &&__t, Sentinel &&last) const {
7568 // return __t;
7569 // }
7570 //
7571 // When we compare the profiling result for `C<_Tp>` in different
7572 // modules, it will compare the type of `_Tp` in different modules.
7573 // However, the type of `_Tp` in different modules refer to different
7574 // types here naturally. So we couldn't compare the profiling result
7575 // for the template args directly.
7576 return isSameConstraintExpr(XCE: XTC->getImmediatelyDeclaredConstraint(),
7577 YCE: YTC->getImmediatelyDeclaredConstraint());
7578}
7579
7580bool ASTContext::isSameTemplateParameter(const NamedDecl *X,
7581 const NamedDecl *Y) const {
7582 if (X->getKind() != Y->getKind())
7583 return false;
7584
7585 if (auto *TX = dyn_cast<TemplateTypeParmDecl>(Val: X)) {
7586 auto *TY = cast<TemplateTypeParmDecl>(Val: Y);
7587 if (TX->isParameterPack() != TY->isParameterPack())
7588 return false;
7589 if (TX->hasTypeConstraint() != TY->hasTypeConstraint())
7590 return false;
7591 return isSameTypeConstraint(XTC: TX->getTypeConstraint(),
7592 YTC: TY->getTypeConstraint());
7593 }
7594
7595 if (auto *TX = dyn_cast<NonTypeTemplateParmDecl>(Val: X)) {
7596 auto *TY = cast<NonTypeTemplateParmDecl>(Val: Y);
7597 return TX->isParameterPack() == TY->isParameterPack() &&
7598 TX->getASTContext().hasSameType(T1: TX->getType(), T2: TY->getType()) &&
7599 isSameConstraintExpr(XCE: TX->getPlaceholderTypeConstraint(),
7600 YCE: TY->getPlaceholderTypeConstraint());
7601 }
7602
7603 auto *TX = cast<TemplateTemplateParmDecl>(Val: X);
7604 auto *TY = cast<TemplateTemplateParmDecl>(Val: Y);
7605 return TX->isParameterPack() == TY->isParameterPack() &&
7606 isSameTemplateParameterList(X: TX->getTemplateParameters(),
7607 Y: TY->getTemplateParameters());
7608}
7609
7610bool ASTContext::isSameTemplateParameterList(
7611 const TemplateParameterList *X, const TemplateParameterList *Y) const {
7612 if (X->size() != Y->size())
7613 return false;
7614
7615 for (unsigned I = 0, N = X->size(); I != N; ++I)
7616 if (!isSameTemplateParameter(X: X->getParam(Idx: I), Y: Y->getParam(Idx: I)))
7617 return false;
7618
7619 return isSameConstraintExpr(XCE: X->getRequiresClause(), YCE: Y->getRequiresClause());
7620}
7621
7622bool ASTContext::isSameDefaultTemplateArgument(const NamedDecl *X,
7623 const NamedDecl *Y) const {
7624 // If the type parameter isn't the same already, we don't need to check the
7625 // default argument further.
7626 if (!isSameTemplateParameter(X, Y))
7627 return false;
7628
7629 if (auto *TTPX = dyn_cast<TemplateTypeParmDecl>(Val: X)) {
7630 auto *TTPY = cast<TemplateTypeParmDecl>(Val: Y);
7631 if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument())
7632 return false;
7633
7634 return hasSameType(T1: TTPX->getDefaultArgument().getArgument().getAsType(),
7635 T2: TTPY->getDefaultArgument().getArgument().getAsType());
7636 }
7637
7638 if (auto *NTTPX = dyn_cast<NonTypeTemplateParmDecl>(Val: X)) {
7639 auto *NTTPY = cast<NonTypeTemplateParmDecl>(Val: Y);
7640 if (!NTTPX->hasDefaultArgument() || !NTTPY->hasDefaultArgument())
7641 return false;
7642
7643 Expr *DefaultArgumentX =
7644 NTTPX->getDefaultArgument().getArgument().getAsExpr()->IgnoreImpCasts();
7645 Expr *DefaultArgumentY =
7646 NTTPY->getDefaultArgument().getArgument().getAsExpr()->IgnoreImpCasts();
7647 llvm::FoldingSetNodeID XID, YID;
7648 DefaultArgumentX->Profile(ID&: XID, Context: *this, /*Canonical=*/true);
7649 DefaultArgumentY->Profile(ID&: YID, Context: *this, /*Canonical=*/true);
7650 return XID == YID;
7651 }
7652
7653 auto *TTPX = cast<TemplateTemplateParmDecl>(Val: X);
7654 auto *TTPY = cast<TemplateTemplateParmDecl>(Val: Y);
7655
7656 if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument())
7657 return false;
7658
7659 const TemplateArgument &TAX = TTPX->getDefaultArgument().getArgument();
7660 const TemplateArgument &TAY = TTPY->getDefaultArgument().getArgument();
7661 return hasSameTemplateName(X: TAX.getAsTemplate(), Y: TAY.getAsTemplate());
7662}
7663
7664static bool isSameQualifier(const NestedNameSpecifier X,
7665 const NestedNameSpecifier Y) {
7666 if (X == Y)
7667 return true;
7668 if (!X || !Y)
7669 return false;
7670
7671 auto Kind = X.getKind();
7672 if (Kind != Y.getKind())
7673 return false;
7674
7675 // FIXME: For namespaces and types, we're permitted to check that the entity
7676 // is named via the same tokens. We should probably do so.
7677 switch (Kind) {
7678 case NestedNameSpecifier::Kind::Namespace: {
7679 auto [NamespaceX, PrefixX] = X.getAsNamespaceAndPrefix();
7680 auto [NamespaceY, PrefixY] = Y.getAsNamespaceAndPrefix();
7681 if (!declaresSameEntity(D1: NamespaceX->getNamespace(),
7682 D2: NamespaceY->getNamespace()))
7683 return false;
7684 return isSameQualifier(X: PrefixX, Y: PrefixY);
7685 }
7686 case NestedNameSpecifier::Kind::Type: {
7687 const auto *TX = X.getAsType(), *TY = Y.getAsType();
7688 if (TX->getCanonicalTypeInternal() != TY->getCanonicalTypeInternal())
7689 return false;
7690 return isSameQualifier(X: TX->getPrefix(), Y: TY->getPrefix());
7691 }
7692 case NestedNameSpecifier::Kind::Null:
7693 case NestedNameSpecifier::Kind::Global:
7694 case NestedNameSpecifier::Kind::MicrosoftSuper:
7695 return true;
7696 }
7697 llvm_unreachable("unhandled qualifier kind");
7698}
7699
7700static bool hasSameCudaAttrs(const FunctionDecl *A, const FunctionDecl *B) {
7701 if (!A->getASTContext().getLangOpts().CUDA)
7702 return true; // Target attributes are overloadable in CUDA compilation only.
7703 if (A->hasAttr<CUDADeviceAttr>() != B->hasAttr<CUDADeviceAttr>())
7704 return false;
7705 if (A->hasAttr<CUDADeviceAttr>() && B->hasAttr<CUDADeviceAttr>())
7706 return A->hasAttr<CUDAHostAttr>() == B->hasAttr<CUDAHostAttr>();
7707 return true; // unattributed and __host__ functions are the same.
7708}
7709
7710/// Determine whether the attributes we can overload on are identical for A and
7711/// B. Will ignore any overloadable attrs represented in the type of A and B.
7712static bool hasSameOverloadableAttrs(const FunctionDecl *A,
7713 const FunctionDecl *B) {
7714 // Note that pass_object_size attributes are represented in the function's
7715 // ExtParameterInfo, so we don't need to check them here.
7716
7717 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
7718 auto AEnableIfAttrs = A->specific_attrs<EnableIfAttr>();
7719 auto BEnableIfAttrs = B->specific_attrs<EnableIfAttr>();
7720
7721 for (auto Pair : zip_longest(t&: AEnableIfAttrs, u&: BEnableIfAttrs)) {
7722 std::optional<EnableIfAttr *> Cand1A = std::get<0>(t&: Pair);
7723 std::optional<EnableIfAttr *> Cand2A = std::get<1>(t&: Pair);
7724
7725 // Return false if the number of enable_if attributes is different.
7726 if (!Cand1A || !Cand2A)
7727 return false;
7728
7729 Cand1ID.clear();
7730 Cand2ID.clear();
7731
7732 (*Cand1A)->getCond()->Profile(ID&: Cand1ID, Context: A->getASTContext(), Canonical: true);
7733 (*Cand2A)->getCond()->Profile(ID&: Cand2ID, Context: B->getASTContext(), Canonical: true);
7734
7735 // Return false if any of the enable_if expressions of A and B are
7736 // different.
7737 if (Cand1ID != Cand2ID)
7738 return false;
7739 }
7740 return hasSameCudaAttrs(A, B);
7741}
7742
7743bool ASTContext::isSameEntity(const NamedDecl *X, const NamedDecl *Y) const {
7744 // Caution: this function is called by the AST reader during deserialization,
7745 // so it cannot rely on AST invariants being met. Non-trivial accessors
7746 // should be avoided, along with any traversal of redeclaration chains.
7747
7748 if (X == Y)
7749 return true;
7750
7751 if (X->getDeclName() != Y->getDeclName())
7752 return false;
7753
7754 // Must be in the same context.
7755 //
7756 // Note that we can't use DeclContext::Equals here, because the DeclContexts
7757 // could be two different declarations of the same function. (We will fix the
7758 // semantic DC to refer to the primary definition after merging.)
7759 if (!declaresSameEntity(D1: cast<Decl>(Val: X->getDeclContext()->getRedeclContext()),
7760 D2: cast<Decl>(Val: Y->getDeclContext()->getRedeclContext())))
7761 return false;
7762
7763 // If either X or Y are local to the owning module, they are only possible to
7764 // be the same entity if they are in the same module.
7765 if (X->isModuleLocal() || Y->isModuleLocal())
7766 if (!isInSameModule(M1: X->getOwningModule(), M2: Y->getOwningModule()))
7767 return false;
7768
7769 // Two typedefs refer to the same entity if they have the same underlying
7770 // type.
7771 if (const auto *TypedefX = dyn_cast<TypedefNameDecl>(Val: X))
7772 if (const auto *TypedefY = dyn_cast<TypedefNameDecl>(Val: Y))
7773 return hasSameType(T1: TypedefX->getUnderlyingType(),
7774 T2: TypedefY->getUnderlyingType());
7775
7776 // Must have the same kind.
7777 if (X->getKind() != Y->getKind())
7778 return false;
7779
7780 // Objective-C classes and protocols with the same name always match.
7781 if (isa<ObjCInterfaceDecl>(Val: X) || isa<ObjCProtocolDecl>(Val: X))
7782 return true;
7783
7784 if (isa<ClassTemplateSpecializationDecl>(Val: X)) {
7785 // No need to handle these here: we merge them when adding them to the
7786 // template.
7787 return false;
7788 }
7789
7790 // Compatible tags match.
7791 if (const auto *TagX = dyn_cast<TagDecl>(Val: X)) {
7792 const auto *TagY = cast<TagDecl>(Val: Y);
7793 return (TagX->getTagKind() == TagY->getTagKind()) ||
7794 ((TagX->getTagKind() == TagTypeKind::Struct ||
7795 TagX->getTagKind() == TagTypeKind::Class ||
7796 TagX->getTagKind() == TagTypeKind::Interface) &&
7797 (TagY->getTagKind() == TagTypeKind::Struct ||
7798 TagY->getTagKind() == TagTypeKind::Class ||
7799 TagY->getTagKind() == TagTypeKind::Interface));
7800 }
7801
7802 // Functions with the same type and linkage match.
7803 // FIXME: This needs to cope with merging of prototyped/non-prototyped
7804 // functions, etc.
7805 if (const auto *FuncX = dyn_cast<FunctionDecl>(Val: X)) {
7806 const auto *FuncY = cast<FunctionDecl>(Val: Y);
7807 if (const auto *CtorX = dyn_cast<CXXConstructorDecl>(Val: X)) {
7808 const auto *CtorY = cast<CXXConstructorDecl>(Val: Y);
7809 if (CtorX->getInheritedConstructor() &&
7810 !isSameEntity(X: CtorX->getInheritedConstructor().getConstructor(),
7811 Y: CtorY->getInheritedConstructor().getConstructor()))
7812 return false;
7813 }
7814
7815 if (FuncX->isMultiVersion() != FuncY->isMultiVersion())
7816 return false;
7817
7818 // Multiversioned functions with different feature strings are represented
7819 // as separate declarations.
7820 if (FuncX->isMultiVersion()) {
7821 const auto *TAX = FuncX->getAttr<TargetAttr>();
7822 const auto *TAY = FuncY->getAttr<TargetAttr>();
7823 assert(TAX && TAY && "Multiversion Function without target attribute");
7824
7825 if (TAX->getFeaturesStr() != TAY->getFeaturesStr())
7826 return false;
7827 }
7828
7829 // Per C++20 [temp.over.link]/4, friends in different classes are sometimes
7830 // not the same entity if they are constrained.
7831 if ((FuncX->isMemberLikeConstrainedFriend() ||
7832 FuncY->isMemberLikeConstrainedFriend()) &&
7833 !FuncX->getLexicalDeclContext()->Equals(
7834 DC: FuncY->getLexicalDeclContext())) {
7835 return false;
7836 }
7837
7838 if (!isSameAssociatedConstraint(ACX: FuncX->getTrailingRequiresClause(),
7839 ACY: FuncY->getTrailingRequiresClause()))
7840 return false;
7841
7842 auto GetTypeAsWritten = [](const FunctionDecl *FD) {
7843 // Map to the first declaration that we've already merged into this one.
7844 // The TSI of redeclarations might not match (due to calling conventions
7845 // being inherited onto the type but not the TSI), but the TSI type of
7846 // the first declaration of the function should match across modules.
7847 FD = FD->getCanonicalDecl();
7848 return FD->getTypeSourceInfo() ? FD->getTypeSourceInfo()->getType()
7849 : FD->getType();
7850 };
7851 QualType XT = GetTypeAsWritten(FuncX), YT = GetTypeAsWritten(FuncY);
7852 if (!hasSameType(T1: XT, T2: YT)) {
7853 // We can get functions with different types on the redecl chain in C++17
7854 // if they have differing exception specifications and at least one of
7855 // the excpetion specs is unresolved.
7856 auto *XFPT = XT->getAs<FunctionProtoType>();
7857 auto *YFPT = YT->getAs<FunctionProtoType>();
7858 if (getLangOpts().CPlusPlus17 && XFPT && YFPT &&
7859 (isUnresolvedExceptionSpec(ESpecType: XFPT->getExceptionSpecType()) ||
7860 isUnresolvedExceptionSpec(ESpecType: YFPT->getExceptionSpecType())) &&
7861 hasSameFunctionTypeIgnoringExceptionSpec(T: XT, U: YT))
7862 return true;
7863 return false;
7864 }
7865
7866 return FuncX->getLinkageInternal() == FuncY->getLinkageInternal() &&
7867 hasSameOverloadableAttrs(A: FuncX, B: FuncY);
7868 }
7869
7870 // Variables with the same type and linkage match.
7871 if (const auto *VarX = dyn_cast<VarDecl>(Val: X)) {
7872 const auto *VarY = cast<VarDecl>(Val: Y);
7873 if (VarX->getLinkageInternal() == VarY->getLinkageInternal()) {
7874 // During deserialization, we might compare variables before we load
7875 // their types. Assume the types will end up being the same.
7876 if (VarX->getType().isNull() || VarY->getType().isNull())
7877 return true;
7878
7879 if (hasSameType(T1: VarX->getType(), T2: VarY->getType()))
7880 return true;
7881
7882 // We can get decls with different types on the redecl chain. Eg.
7883 // template <typename T> struct S { static T Var[]; }; // #1
7884 // template <typename T> T S<T>::Var[sizeof(T)]; // #2
7885 // Only? happens when completing an incomplete array type. In this case
7886 // when comparing #1 and #2 we should go through their element type.
7887 const ArrayType *VarXTy = getAsArrayType(T: VarX->getType());
7888 const ArrayType *VarYTy = getAsArrayType(T: VarY->getType());
7889 if (!VarXTy || !VarYTy)
7890 return false;
7891 if (VarXTy->isIncompleteArrayType() || VarYTy->isIncompleteArrayType())
7892 return hasSameType(T1: VarXTy->getElementType(), T2: VarYTy->getElementType());
7893 }
7894 return false;
7895 }
7896
7897 // Namespaces with the same name and inlinedness match.
7898 if (const auto *NamespaceX = dyn_cast<NamespaceDecl>(Val: X)) {
7899 const auto *NamespaceY = cast<NamespaceDecl>(Val: Y);
7900 return NamespaceX->isInline() == NamespaceY->isInline();
7901 }
7902
7903 // Identical template names and kinds match if their template parameter lists
7904 // and patterns match.
7905 if (const auto *TemplateX = dyn_cast<TemplateDecl>(Val: X)) {
7906 const auto *TemplateY = cast<TemplateDecl>(Val: Y);
7907
7908 // ConceptDecl wouldn't be the same if their constraint expression differs.
7909 if (const auto *ConceptX = dyn_cast<ConceptDecl>(Val: X)) {
7910 const auto *ConceptY = cast<ConceptDecl>(Val: Y);
7911 if (!isSameConstraintExpr(XCE: ConceptX->getConstraintExpr(),
7912 YCE: ConceptY->getConstraintExpr()))
7913 return false;
7914 }
7915
7916 return isSameEntity(X: TemplateX->getTemplatedDecl(),
7917 Y: TemplateY->getTemplatedDecl()) &&
7918 isSameTemplateParameterList(X: TemplateX->getTemplateParameters(),
7919 Y: TemplateY->getTemplateParameters());
7920 }
7921
7922 // Fields with the same name and the same type match.
7923 if (const auto *FDX = dyn_cast<FieldDecl>(Val: X)) {
7924 const auto *FDY = cast<FieldDecl>(Val: Y);
7925 // FIXME: Also check the bitwidth is odr-equivalent, if any.
7926 return hasSameType(T1: FDX->getType(), T2: FDY->getType());
7927 }
7928
7929 // Indirect fields with the same target field match.
7930 if (const auto *IFDX = dyn_cast<IndirectFieldDecl>(Val: X)) {
7931 const auto *IFDY = cast<IndirectFieldDecl>(Val: Y);
7932 return IFDX->getAnonField()->getCanonicalDecl() ==
7933 IFDY->getAnonField()->getCanonicalDecl();
7934 }
7935
7936 // Enumerators with the same name match.
7937 if (isa<EnumConstantDecl>(Val: X))
7938 // FIXME: Also check the value is odr-equivalent.
7939 return true;
7940
7941 // Using shadow declarations with the same target match.
7942 if (const auto *USX = dyn_cast<UsingShadowDecl>(Val: X)) {
7943 const auto *USY = cast<UsingShadowDecl>(Val: Y);
7944 return declaresSameEntity(D1: USX->getTargetDecl(), D2: USY->getTargetDecl());
7945 }
7946
7947 // Using declarations with the same qualifier match. (We already know that
7948 // the name matches.)
7949 if (const auto *UX = dyn_cast<UsingDecl>(Val: X)) {
7950 const auto *UY = cast<UsingDecl>(Val: Y);
7951 return isSameQualifier(X: UX->getQualifier(), Y: UY->getQualifier()) &&
7952 UX->hasTypename() == UY->hasTypename() &&
7953 UX->isAccessDeclaration() == UY->isAccessDeclaration();
7954 }
7955 if (const auto *UX = dyn_cast<UnresolvedUsingValueDecl>(Val: X)) {
7956 const auto *UY = cast<UnresolvedUsingValueDecl>(Val: Y);
7957 return isSameQualifier(X: UX->getQualifier(), Y: UY->getQualifier()) &&
7958 UX->isAccessDeclaration() == UY->isAccessDeclaration();
7959 }
7960 if (const auto *UX = dyn_cast<UnresolvedUsingTypenameDecl>(Val: X)) {
7961 return isSameQualifier(
7962 X: UX->getQualifier(),
7963 Y: cast<UnresolvedUsingTypenameDecl>(Val: Y)->getQualifier());
7964 }
7965
7966 // Using-pack declarations are only created by instantiation, and match if
7967 // they're instantiated from matching UnresolvedUsing...Decls.
7968 if (const auto *UX = dyn_cast<UsingPackDecl>(Val: X)) {
7969 return declaresSameEntity(
7970 D1: UX->getInstantiatedFromUsingDecl(),
7971 D2: cast<UsingPackDecl>(Val: Y)->getInstantiatedFromUsingDecl());
7972 }
7973
7974 // Namespace alias definitions with the same target match.
7975 if (const auto *NAX = dyn_cast<NamespaceAliasDecl>(Val: X)) {
7976 const auto *NAY = cast<NamespaceAliasDecl>(Val: Y);
7977 return NAX->getNamespace()->Equals(DC: NAY->getNamespace());
7978 }
7979
7980 if (const auto *UX = dyn_cast<UsingEnumDecl>(Val: X)) {
7981 const auto *UY = cast<UsingEnumDecl>(Val: Y);
7982 return isSameQualifier(X: UX->getQualifier(), Y: UY->getQualifier()) &&
7983 declaresSameEntity(D1: UX->getEnumDecl(), D2: UY->getEnumDecl());
7984 }
7985
7986 return false;
7987}
7988
7989TemplateArgument
7990ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
7991 switch (Arg.getKind()) {
7992 case TemplateArgument::Null:
7993 return Arg;
7994
7995 case TemplateArgument::Expression:
7996 return TemplateArgument(Arg.getAsExpr(), /*IsCanonical=*/true,
7997 Arg.getIsDefaulted());
7998
7999 case TemplateArgument::Declaration: {
8000 auto *D = cast<ValueDecl>(Val: Arg.getAsDecl()->getCanonicalDecl());
8001 return TemplateArgument(D, getCanonicalType(T: Arg.getParamTypeForDecl()),
8002 Arg.getIsDefaulted());
8003 }
8004
8005 case TemplateArgument::NullPtr:
8006 return TemplateArgument(getCanonicalType(T: Arg.getNullPtrType()),
8007 /*isNullPtr*/ true, Arg.getIsDefaulted());
8008
8009 case TemplateArgument::Template:
8010 return TemplateArgument(getCanonicalTemplateName(Name: Arg.getAsTemplate()),
8011 Arg.getIsDefaulted());
8012
8013 case TemplateArgument::TemplateExpansion:
8014 return TemplateArgument(
8015 getCanonicalTemplateName(Name: Arg.getAsTemplateOrTemplatePattern()),
8016 Arg.getNumTemplateExpansions(), Arg.getIsDefaulted());
8017
8018 case TemplateArgument::Integral:
8019 return TemplateArgument(Arg, getCanonicalType(T: Arg.getIntegralType()));
8020
8021 case TemplateArgument::StructuralValue:
8022 return TemplateArgument(*this,
8023 getCanonicalType(T: Arg.getStructuralValueType()),
8024 Arg.getAsStructuralValue(), Arg.getIsDefaulted());
8025
8026 case TemplateArgument::Type:
8027 return TemplateArgument(getCanonicalType(T: Arg.getAsType()),
8028 /*isNullPtr*/ false, Arg.getIsDefaulted());
8029
8030 case TemplateArgument::Pack: {
8031 bool AnyNonCanonArgs = false;
8032 auto CanonArgs = ::getCanonicalTemplateArguments(
8033 C: *this, Args: Arg.pack_elements(), AnyNonCanonArgs);
8034 if (!AnyNonCanonArgs)
8035 return Arg;
8036 auto NewArg = TemplateArgument::CreatePackCopy(
8037 Context&: const_cast<ASTContext &>(*this), Args: CanonArgs);
8038 NewArg.setIsDefaulted(Arg.getIsDefaulted());
8039 return NewArg;
8040 }
8041 }
8042
8043 // Silence GCC warning
8044 llvm_unreachable("Unhandled template argument kind");
8045}
8046
8047bool ASTContext::isSameTemplateArgument(const TemplateArgument &Arg1,
8048 const TemplateArgument &Arg2) const {
8049 if (Arg1.getKind() != Arg2.getKind())
8050 return false;
8051
8052 switch (Arg1.getKind()) {
8053 case TemplateArgument::Null:
8054 llvm_unreachable("Comparing NULL template argument");
8055
8056 case TemplateArgument::Type:
8057 return hasSameType(T1: Arg1.getAsType(), T2: Arg2.getAsType());
8058
8059 case TemplateArgument::Declaration:
8060 return Arg1.getAsDecl()->getUnderlyingDecl()->getCanonicalDecl() ==
8061 Arg2.getAsDecl()->getUnderlyingDecl()->getCanonicalDecl();
8062
8063 case TemplateArgument::NullPtr:
8064 return hasSameType(T1: Arg1.getNullPtrType(), T2: Arg2.getNullPtrType());
8065
8066 case TemplateArgument::Template:
8067 case TemplateArgument::TemplateExpansion:
8068 return getCanonicalTemplateName(Name: Arg1.getAsTemplateOrTemplatePattern()) ==
8069 getCanonicalTemplateName(Name: Arg2.getAsTemplateOrTemplatePattern());
8070
8071 case TemplateArgument::Integral:
8072 return llvm::APSInt::isSameValue(I1: Arg1.getAsIntegral(),
8073 I2: Arg2.getAsIntegral());
8074
8075 case TemplateArgument::StructuralValue:
8076 return Arg1.structurallyEquals(Other: Arg2);
8077
8078 case TemplateArgument::Expression: {
8079 llvm::FoldingSetNodeID ID1, ID2;
8080 Arg1.getAsExpr()->Profile(ID&: ID1, Context: *this, /*Canonical=*/true);
8081 Arg2.getAsExpr()->Profile(ID&: ID2, Context: *this, /*Canonical=*/true);
8082 return ID1 == ID2;
8083 }
8084
8085 case TemplateArgument::Pack:
8086 return llvm::equal(
8087 LRange: Arg1.getPackAsArray(), RRange: Arg2.getPackAsArray(),
8088 P: [&](const TemplateArgument &Arg1, const TemplateArgument &Arg2) {
8089 return isSameTemplateArgument(Arg1, Arg2);
8090 });
8091 }
8092
8093 llvm_unreachable("Unhandled template argument kind");
8094}
8095
8096const ArrayType *ASTContext::getAsArrayType(QualType T) const {
8097 // Handle the non-qualified case efficiently.
8098 if (!T.hasLocalQualifiers()) {
8099 // Handle the common positive case fast.
8100 if (const auto *AT = dyn_cast<ArrayType>(Val&: T))
8101 return AT;
8102 }
8103
8104 // Handle the common negative case fast.
8105 if (!isa<ArrayType>(Val: T.getCanonicalType()))
8106 return nullptr;
8107
8108 // Apply any qualifiers from the array type to the element type. This
8109 // implements C99 6.7.3p8: "If the specification of an array type includes
8110 // any type qualifiers, the element type is so qualified, not the array type."
8111
8112 // If we get here, we either have type qualifiers on the type, or we have
8113 // sugar such as a typedef in the way. If we have type qualifiers on the type
8114 // we must propagate them down into the element type.
8115
8116 SplitQualType split = T.getSplitDesugaredType();
8117 Qualifiers qs = split.Quals;
8118
8119 // If we have a simple case, just return now.
8120 const auto *ATy = dyn_cast<ArrayType>(Val: split.Ty);
8121 if (!ATy || qs.empty())
8122 return ATy;
8123
8124 // Otherwise, we have an array and we have qualifiers on it. Push the
8125 // qualifiers into the array element type and return a new array type.
8126 QualType NewEltTy = getQualifiedType(T: ATy->getElementType(), Qs: qs);
8127
8128 if (const auto *CAT = dyn_cast<ConstantArrayType>(Val: ATy))
8129 return cast<ArrayType>(Val: getConstantArrayType(EltTy: NewEltTy, ArySizeIn: CAT->getSize(),
8130 SizeExpr: CAT->getSizeExpr(),
8131 ASM: CAT->getSizeModifier(),
8132 IndexTypeQuals: CAT->getIndexTypeCVRQualifiers()));
8133 if (const auto *IAT = dyn_cast<IncompleteArrayType>(Val: ATy))
8134 return cast<ArrayType>(Val: getIncompleteArrayType(elementType: NewEltTy,
8135 ASM: IAT->getSizeModifier(),
8136 elementTypeQuals: IAT->getIndexTypeCVRQualifiers()));
8137
8138 if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(Val: ATy))
8139 return cast<ArrayType>(Val: getDependentSizedArrayType(
8140 elementType: NewEltTy, numElements: DSAT->getSizeExpr(), ASM: DSAT->getSizeModifier(),
8141 elementTypeQuals: DSAT->getIndexTypeCVRQualifiers()));
8142
8143 const auto *VAT = cast<VariableArrayType>(Val: ATy);
8144 return cast<ArrayType>(
8145 Val: getVariableArrayType(EltTy: NewEltTy, NumElts: VAT->getSizeExpr(), ASM: VAT->getSizeModifier(),
8146 IndexTypeQuals: VAT->getIndexTypeCVRQualifiers()));
8147}
8148
8149QualType ASTContext::getAdjustedParameterType(QualType T) const {
8150 if (getLangOpts().HLSL && T.getAddressSpace() == LangAS::hlsl_groupshared)
8151 return getLValueReferenceType(T);
8152 if (getLangOpts().HLSL && T->isConstantArrayType())
8153 return getArrayParameterType(Ty: T);
8154 if (T->isArrayType() || T->isFunctionType())
8155 return getDecayedType(T);
8156 return T;
8157}
8158
8159QualType ASTContext::getSignatureParameterType(QualType T) const {
8160 T = getVariableArrayDecayedType(type: T);
8161 T = getAdjustedParameterType(T);
8162 return T.getUnqualifiedType();
8163}
8164
8165QualType ASTContext::getExceptionObjectType(QualType T) const {
8166 // C++ [except.throw]p3:
8167 // A throw-expression initializes a temporary object, called the exception
8168 // object, the type of which is determined by removing any top-level
8169 // cv-qualifiers from the static type of the operand of throw and adjusting
8170 // the type from "array of T" or "function returning T" to "pointer to T"
8171 // or "pointer to function returning T", [...]
8172 T = getVariableArrayDecayedType(type: T);
8173 if (T->isArrayType() || T->isFunctionType())
8174 T = getDecayedType(T);
8175 return T.getUnqualifiedType();
8176}
8177
8178/// getArrayDecayedType - Return the properly qualified result of decaying the
8179/// specified array type to a pointer. This operation is non-trivial when
8180/// handling typedefs etc. The canonical type of "T" must be an array type,
8181/// this returns a pointer to a properly qualified element of the array.
8182///
8183/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
8184QualType ASTContext::getArrayDecayedType(QualType Ty) const {
8185 // Get the element type with 'getAsArrayType' so that we don't lose any
8186 // typedefs in the element type of the array. This also handles propagation
8187 // of type qualifiers from the array type into the element type if present
8188 // (C99 6.7.3p8).
8189 const ArrayType *PrettyArrayType = getAsArrayType(T: Ty);
8190 assert(PrettyArrayType && "Not an array type!");
8191
8192 QualType PtrTy = getPointerType(T: PrettyArrayType->getElementType());
8193
8194 // int x[restrict 4] -> int *restrict
8195 QualType Result = getQualifiedType(T: PtrTy,
8196 Qs: PrettyArrayType->getIndexTypeQualifiers());
8197
8198 // int x[_Nullable] -> int * _Nullable
8199 if (auto Nullability = Ty->getNullability()) {
8200 Result = getAttributedType(nullability: *Nullability, modifiedType: Result, equivalentType: Result);
8201 }
8202 return Result;
8203}
8204
8205QualType ASTContext::getBaseElementType(const ArrayType *array) const {
8206 return getBaseElementType(QT: array->getElementType());
8207}
8208
8209QualType ASTContext::getBaseElementType(QualType type) const {
8210 Qualifiers qs;
8211 while (true) {
8212 SplitQualType split = type.getSplitDesugaredType();
8213 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
8214 if (!array) break;
8215
8216 type = array->getElementType();
8217 qs.addConsistentQualifiers(qs: split.Quals);
8218 }
8219
8220 return getQualifiedType(T: type, Qs: qs);
8221}
8222
8223uint64_t ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) {
8224 uint64_t ElementCount = 1;
8225 do {
8226 ElementCount *= CA->getZExtSize();
8227 CA = dyn_cast_if_present<ConstantArrayType>(
8228 Val: CA->getElementType()->getAsArrayTypeUnsafe());
8229 } while (CA);
8230 return ElementCount;
8231}
8232
8233uint64_t
8234ASTContext::getArrayInitLoopExprElementCount(const ArrayInitLoopExpr *AILE) {
8235 if (!AILE)
8236 return 0;
8237
8238 uint64_t ElementCount = 1;
8239
8240 do {
8241 ElementCount *= AILE->getArraySize().getZExtValue();
8242 AILE = dyn_cast<ArrayInitLoopExpr>(Val: AILE->getSubExpr());
8243 } while (AILE);
8244
8245 return ElementCount;
8246}
8247
8248/// getFloatingRank - Return a relative rank for floating point types.
8249/// This routine will assert if passed a built-in type that isn't a float.
8250static FloatingRank getFloatingRank(QualType T) {
8251 if (const auto *CT = T->getAs<ComplexType>())
8252 return getFloatingRank(T: CT->getElementType());
8253
8254 switch (T->castAs<BuiltinType>()->getKind()) {
8255 default: llvm_unreachable("getFloatingRank(): not a floating type");
8256 case BuiltinType::Float16: return Float16Rank;
8257 case BuiltinType::Half: return HalfRank;
8258 case BuiltinType::Float: return FloatRank;
8259 case BuiltinType::Double: return DoubleRank;
8260 case BuiltinType::LongDouble: return LongDoubleRank;
8261 case BuiltinType::Float128: return Float128Rank;
8262 case BuiltinType::BFloat16: return BFloat16Rank;
8263 case BuiltinType::Ibm128: return Ibm128Rank;
8264 }
8265}
8266
8267/// getFloatingTypeOrder - Compare the rank of the two specified floating
8268/// point types, ignoring the domain of the type (i.e. 'double' ==
8269/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
8270/// LHS < RHS, return -1.
8271int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
8272 FloatingRank LHSR = getFloatingRank(T: LHS);
8273 FloatingRank RHSR = getFloatingRank(T: RHS);
8274
8275 if (LHSR == RHSR)
8276 return 0;
8277 if (LHSR > RHSR)
8278 return 1;
8279 return -1;
8280}
8281
8282int ASTContext::getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const {
8283 if (&getFloatTypeSemantics(T: LHS) == &getFloatTypeSemantics(T: RHS))
8284 return 0;
8285 return getFloatingTypeOrder(LHS, RHS);
8286}
8287
8288/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
8289/// routine will assert if passed a built-in type that isn't an integer or enum,
8290/// or if it is not canonicalized.
8291unsigned ASTContext::getIntegerRank(const Type *T) const {
8292 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
8293
8294 // Results in this 'losing' to any type of the same size, but winning if
8295 // larger.
8296 if (const auto *EIT = dyn_cast<BitIntType>(Val: T))
8297 return 0 + (EIT->getNumBits() << 3);
8298
8299 if (const auto *OBT = dyn_cast<OverflowBehaviorType>(Val: T))
8300 return getIntegerRank(T: OBT->getUnderlyingType().getTypePtr());
8301
8302 switch (cast<BuiltinType>(Val: T)->getKind()) {
8303 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
8304 case BuiltinType::Bool:
8305 return 1 + (getIntWidth(T: BoolTy) << 3);
8306 case BuiltinType::Char_S:
8307 case BuiltinType::Char_U:
8308 case BuiltinType::SChar:
8309 case BuiltinType::UChar:
8310 return 2 + (getIntWidth(T: CharTy) << 3);
8311 case BuiltinType::Short:
8312 case BuiltinType::UShort:
8313 return 3 + (getIntWidth(T: ShortTy) << 3);
8314 case BuiltinType::Int:
8315 case BuiltinType::UInt:
8316 return 4 + (getIntWidth(T: IntTy) << 3);
8317 case BuiltinType::Long:
8318 case BuiltinType::ULong:
8319 return 5 + (getIntWidth(T: LongTy) << 3);
8320 case BuiltinType::LongLong:
8321 case BuiltinType::ULongLong:
8322 return 6 + (getIntWidth(T: LongLongTy) << 3);
8323 case BuiltinType::Int128:
8324 case BuiltinType::UInt128:
8325 return 7 + (getIntWidth(T: Int128Ty) << 3);
8326
8327 // "The ranks of char8_t, char16_t, char32_t, and wchar_t equal the ranks of
8328 // their underlying types" [c++20 conv.rank]
8329 case BuiltinType::Char8:
8330 return getIntegerRank(T: UnsignedCharTy.getTypePtr());
8331 case BuiltinType::Char16:
8332 return getIntegerRank(
8333 T: getFromTargetType(Type: Target->getChar16Type()).getTypePtr());
8334 case BuiltinType::Char32:
8335 return getIntegerRank(
8336 T: getFromTargetType(Type: Target->getChar32Type()).getTypePtr());
8337 case BuiltinType::WChar_S:
8338 case BuiltinType::WChar_U:
8339 return getIntegerRank(
8340 T: getFromTargetType(Type: Target->getWCharType()).getTypePtr());
8341 }
8342}
8343
8344/// Whether this is a promotable bitfield reference according
8345/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
8346///
8347/// \returns the type this bit-field will promote to, or NULL if no
8348/// promotion occurs.
8349QualType ASTContext::isPromotableBitField(Expr *E) const {
8350 if (E->isTypeDependent() || E->isValueDependent())
8351 return {};
8352
8353 // C++ [conv.prom]p5:
8354 // If the bit-field has an enumerated type, it is treated as any other
8355 // value of that type for promotion purposes.
8356 if (getLangOpts().CPlusPlus && E->getType()->isEnumeralType())
8357 return {};
8358
8359 // FIXME: We should not do this unless E->refersToBitField() is true. This
8360 // matters in C where getSourceBitField() will find bit-fields for various
8361 // cases where the source expression is not a bit-field designator.
8362
8363 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
8364 if (!Field)
8365 return {};
8366
8367 QualType FT = Field->getType();
8368
8369 uint64_t BitWidth = Field->getBitWidthValue();
8370 uint64_t IntSize = getTypeSize(T: IntTy);
8371 // C++ [conv.prom]p5:
8372 // A prvalue for an integral bit-field can be converted to a prvalue of type
8373 // int if int can represent all the values of the bit-field; otherwise, it
8374 // can be converted to unsigned int if unsigned int can represent all the
8375 // values of the bit-field. If the bit-field is larger yet, no integral
8376 // promotion applies to it.
8377 // C11 6.3.1.1/2:
8378 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
8379 // If an int can represent all values of the original type (as restricted by
8380 // the width, for a bit-field), the value is converted to an int; otherwise,
8381 // it is converted to an unsigned int.
8382 //
8383 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
8384 // We perform that promotion here to match GCC and C++.
8385 // FIXME: C does not permit promotion of an enum bit-field whose rank is
8386 // greater than that of 'int'. We perform that promotion to match GCC.
8387 //
8388 // C23 6.3.1.1p2:
8389 // The value from a bit-field of a bit-precise integer type is converted to
8390 // the corresponding bit-precise integer type. (The rest is the same as in
8391 // C11.)
8392 if (QualType QT = Field->getType(); QT->isBitIntType())
8393 return QT;
8394
8395 if (BitWidth < IntSize)
8396 return IntTy;
8397
8398 if (BitWidth == IntSize)
8399 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
8400
8401 // Bit-fields wider than int are not subject to promotions, and therefore act
8402 // like the base type. GCC has some weird bugs in this area that we
8403 // deliberately do not follow (GCC follows a pre-standard resolution to
8404 // C's DR315 which treats bit-width as being part of the type, and this leaks
8405 // into their semantics in some cases).
8406 return {};
8407}
8408
8409/// getPromotedIntegerType - Returns the type that Promotable will
8410/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
8411/// integer type.
8412QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
8413 assert(!Promotable.isNull());
8414 assert(isPromotableIntegerType(Promotable));
8415 if (const auto *ED = Promotable->getAsEnumDecl())
8416 return ED->getPromotionType();
8417
8418 // OverflowBehaviorTypes promote their underlying type and preserve OBT
8419 // qualifier.
8420 if (const auto *OBT = Promotable->getAs<OverflowBehaviorType>()) {
8421 QualType PromotedUnderlying =
8422 getPromotedIntegerType(Promotable: OBT->getUnderlyingType());
8423 return getOverflowBehaviorType(Kind: OBT->getBehaviorKind(), Underlying: PromotedUnderlying);
8424 }
8425
8426 if (const auto *BT = Promotable->getAs<BuiltinType>()) {
8427 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
8428 // (3.9.1) can be converted to a prvalue of the first of the following
8429 // types that can represent all the values of its underlying type:
8430 // int, unsigned int, long int, unsigned long int, long long int, or
8431 // unsigned long long int [...]
8432 // FIXME: Is there some better way to compute this?
8433 if (BT->getKind() == BuiltinType::WChar_S ||
8434 BT->getKind() == BuiltinType::WChar_U ||
8435 BT->getKind() == BuiltinType::Char8 ||
8436 BT->getKind() == BuiltinType::Char16 ||
8437 BT->getKind() == BuiltinType::Char32) {
8438 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
8439 uint64_t FromSize = getTypeSize(T: BT);
8440 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
8441 LongLongTy, UnsignedLongLongTy };
8442 for (const auto &PT : PromoteTypes) {
8443 uint64_t ToSize = getTypeSize(T: PT);
8444 if (FromSize < ToSize ||
8445 (FromSize == ToSize && FromIsSigned == PT->isSignedIntegerType()))
8446 return PT;
8447 }
8448 llvm_unreachable("char type should fit into long long");
8449 }
8450 }
8451
8452 // At this point, we should have a signed or unsigned integer type.
8453 if (Promotable->isSignedIntegerType())
8454 return IntTy;
8455 uint64_t PromotableSize = getIntWidth(T: Promotable);
8456 uint64_t IntSize = getIntWidth(T: IntTy);
8457 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
8458 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
8459}
8460
8461/// Recurses in pointer/array types until it finds an objc retainable
8462/// type and returns its ownership.
8463Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
8464 while (!T.isNull()) {
8465 if (T.getObjCLifetime() != Qualifiers::OCL_None)
8466 return T.getObjCLifetime();
8467 if (T->isArrayType())
8468 T = getBaseElementType(type: T);
8469 else if (const auto *PT = T->getAs<PointerType>())
8470 T = PT->getPointeeType();
8471 else if (const auto *RT = T->getAs<ReferenceType>())
8472 T = RT->getPointeeType();
8473 else
8474 break;
8475 }
8476
8477 return Qualifiers::OCL_None;
8478}
8479
8480static const Type *getIntegerTypeForEnum(const EnumType *ET) {
8481 // Incomplete enum types are not treated as integer types.
8482 // FIXME: In C++, enum types are never integer types.
8483 const EnumDecl *ED = ET->getDecl()->getDefinitionOrSelf();
8484 if (ED->isComplete() && !ED->isScoped())
8485 return ED->getIntegerType().getTypePtr();
8486 return nullptr;
8487}
8488
8489/// getIntegerTypeOrder - Returns the highest ranked integer type:
8490/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
8491/// LHS < RHS, return -1.
8492int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
8493 const Type *LHSC = getCanonicalType(T: LHS).getTypePtr();
8494 const Type *RHSC = getCanonicalType(T: RHS).getTypePtr();
8495
8496 // Unwrap enums to their underlying type.
8497 if (const auto *ET = dyn_cast<EnumType>(Val: LHSC))
8498 LHSC = getIntegerTypeForEnum(ET);
8499 if (const auto *ET = dyn_cast<EnumType>(Val: RHSC))
8500 RHSC = getIntegerTypeForEnum(ET);
8501
8502 if (LHSC == RHSC) return 0;
8503
8504 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
8505 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
8506
8507 unsigned LHSRank = getIntegerRank(T: LHSC);
8508 unsigned RHSRank = getIntegerRank(T: RHSC);
8509
8510 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
8511 if (LHSRank == RHSRank) return 0;
8512 return LHSRank > RHSRank ? 1 : -1;
8513 }
8514
8515 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
8516 if (LHSUnsigned) {
8517 // If the unsigned [LHS] type is larger, return it.
8518 if (LHSRank >= RHSRank)
8519 return 1;
8520
8521 // If the signed type can represent all values of the unsigned type, it
8522 // wins. Because we are dealing with 2's complement and types that are
8523 // powers of two larger than each other, this is always safe.
8524 return -1;
8525 }
8526
8527 // If the unsigned [RHS] type is larger, return it.
8528 if (RHSRank >= LHSRank)
8529 return -1;
8530
8531 // If the signed type can represent all values of the unsigned type, it
8532 // wins. Because we are dealing with 2's complement and types that are
8533 // powers of two larger than each other, this is always safe.
8534 return 1;
8535}
8536
8537TypedefDecl *ASTContext::getCFConstantStringDecl() const {
8538 if (CFConstantStringTypeDecl)
8539 return CFConstantStringTypeDecl;
8540
8541 assert(!CFConstantStringTagDecl &&
8542 "tag and typedef should be initialized together");
8543 CFConstantStringTagDecl = buildImplicitRecord(Name: "__NSConstantString_tag");
8544 CFConstantStringTagDecl->startDefinition();
8545
8546 struct {
8547 QualType Type;
8548 const char *Name;
8549 } Fields[5];
8550 unsigned Count = 0;
8551
8552 /// Objective-C ABI
8553 ///
8554 /// typedef struct __NSConstantString_tag {
8555 /// const int *isa;
8556 /// int flags;
8557 /// const char *str;
8558 /// long length;
8559 /// } __NSConstantString;
8560 ///
8561 /// Swift ABI (4.1, 4.2)
8562 ///
8563 /// typedef struct __NSConstantString_tag {
8564 /// uintptr_t _cfisa;
8565 /// uintptr_t _swift_rc;
8566 /// _Atomic(uint64_t) _cfinfoa;
8567 /// const char *_ptr;
8568 /// uint32_t _length;
8569 /// } __NSConstantString;
8570 ///
8571 /// Swift ABI (5.0)
8572 ///
8573 /// typedef struct __NSConstantString_tag {
8574 /// uintptr_t _cfisa;
8575 /// uintptr_t _swift_rc;
8576 /// _Atomic(uint64_t) _cfinfoa;
8577 /// const char *_ptr;
8578 /// uintptr_t _length;
8579 /// } __NSConstantString;
8580
8581 const auto CFRuntime = getLangOpts().CFRuntime;
8582 if (static_cast<unsigned>(CFRuntime) <
8583 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) {
8584 Fields[Count++] = { .Type: getPointerType(T: IntTy.withConst()), .Name: "isa" };
8585 Fields[Count++] = { .Type: IntTy, .Name: "flags" };
8586 Fields[Count++] = { .Type: getPointerType(T: CharTy.withConst()), .Name: "str" };
8587 Fields[Count++] = { .Type: LongTy, .Name: "length" };
8588 } else {
8589 Fields[Count++] = { .Type: getUIntPtrType(), .Name: "_cfisa" };
8590 Fields[Count++] = { .Type: getUIntPtrType(), .Name: "_swift_rc" };
8591 Fields[Count++] = { .Type: getFromTargetType(Type: Target->getUInt64Type()), .Name: "_swift_rc" };
8592 Fields[Count++] = { .Type: getPointerType(T: CharTy.withConst()), .Name: "_ptr" };
8593 if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 ||
8594 CFRuntime == LangOptions::CoreFoundationABI::Swift4_2)
8595 Fields[Count++] = { .Type: IntTy, .Name: "_ptr" };
8596 else
8597 Fields[Count++] = { .Type: getUIntPtrType(), .Name: "_ptr" };
8598 }
8599
8600 // Create fields
8601 for (unsigned i = 0; i < Count; ++i) {
8602 FieldDecl *Field =
8603 FieldDecl::Create(C: *this, DC: CFConstantStringTagDecl, StartLoc: SourceLocation(),
8604 IdLoc: SourceLocation(), Id: &Idents.get(Name: Fields[i].Name),
8605 T: Fields[i].Type, /*TInfo=*/nullptr,
8606 /*BitWidth=*/BW: nullptr, /*Mutable=*/false, InitStyle: ICIS_NoInit);
8607 Field->setAccess(AS_public);
8608 CFConstantStringTagDecl->addDecl(D: Field);
8609 }
8610
8611 CFConstantStringTagDecl->completeDefinition();
8612 // This type is designed to be compatible with NSConstantString, but cannot
8613 // use the same name, since NSConstantString is an interface.
8614 CanQualType tagType = getCanonicalTagType(TD: CFConstantStringTagDecl);
8615 CFConstantStringTypeDecl =
8616 buildImplicitTypedef(T: tagType, Name: "__NSConstantString");
8617
8618 return CFConstantStringTypeDecl;
8619}
8620
8621RecordDecl *ASTContext::getCFConstantStringTagDecl() const {
8622 if (!CFConstantStringTagDecl)
8623 getCFConstantStringDecl(); // Build the tag and the typedef.
8624 return CFConstantStringTagDecl;
8625}
8626
8627// getCFConstantStringType - Return the type used for constant CFStrings.
8628QualType ASTContext::getCFConstantStringType() const {
8629 return getTypedefType(Keyword: ElaboratedTypeKeyword::None, /*Qualifier=*/std::nullopt,
8630 Decl: getCFConstantStringDecl());
8631}
8632
8633QualType ASTContext::getObjCSuperType() const {
8634 if (ObjCSuperType.isNull()) {
8635 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord(Name: "objc_super");
8636 getTranslationUnitDecl()->addDecl(D: ObjCSuperTypeDecl);
8637 ObjCSuperType = getCanonicalTagType(TD: ObjCSuperTypeDecl);
8638 }
8639 return ObjCSuperType;
8640}
8641
8642void ASTContext::setCFConstantStringType(QualType T) {
8643 const auto *TT = T->castAs<TypedefType>();
8644 CFConstantStringTypeDecl = cast<TypedefDecl>(Val: TT->getDecl());
8645 CFConstantStringTagDecl = TT->castAsRecordDecl();
8646}
8647
8648QualType ASTContext::getBlockDescriptorType() const {
8649 if (BlockDescriptorType)
8650 return getCanonicalTagType(TD: BlockDescriptorType);
8651
8652 RecordDecl *RD;
8653 // FIXME: Needs the FlagAppleBlock bit.
8654 RD = buildImplicitRecord(Name: "__block_descriptor");
8655 RD->startDefinition();
8656
8657 QualType FieldTypes[] = {
8658 UnsignedLongTy,
8659 UnsignedLongTy,
8660 };
8661
8662 static const char *const FieldNames[] = {
8663 "reserved",
8664 "Size"
8665 };
8666
8667 for (size_t i = 0; i < 2; ++i) {
8668 FieldDecl *Field = FieldDecl::Create(
8669 C: *this, DC: RD, StartLoc: SourceLocation(), IdLoc: SourceLocation(),
8670 Id: &Idents.get(Name: FieldNames[i]), T: FieldTypes[i], /*TInfo=*/nullptr,
8671 /*BitWidth=*/BW: nullptr, /*Mutable=*/false, InitStyle: ICIS_NoInit);
8672 Field->setAccess(AS_public);
8673 RD->addDecl(D: Field);
8674 }
8675
8676 RD->completeDefinition();
8677
8678 BlockDescriptorType = RD;
8679
8680 return getCanonicalTagType(TD: BlockDescriptorType);
8681}
8682
8683QualType ASTContext::getBlockDescriptorExtendedType() const {
8684 if (BlockDescriptorExtendedType)
8685 return getCanonicalTagType(TD: BlockDescriptorExtendedType);
8686
8687 RecordDecl *RD;
8688 // FIXME: Needs the FlagAppleBlock bit.
8689 RD = buildImplicitRecord(Name: "__block_descriptor_withcopydispose");
8690 RD->startDefinition();
8691
8692 QualType FieldTypes[] = {
8693 UnsignedLongTy,
8694 UnsignedLongTy,
8695 getPointerType(T: VoidPtrTy),
8696 getPointerType(T: VoidPtrTy)
8697 };
8698
8699 static const char *const FieldNames[] = {
8700 "reserved",
8701 "Size",
8702 "CopyFuncPtr",
8703 "DestroyFuncPtr"
8704 };
8705
8706 for (size_t i = 0; i < 4; ++i) {
8707 FieldDecl *Field = FieldDecl::Create(
8708 C: *this, DC: RD, StartLoc: SourceLocation(), IdLoc: SourceLocation(),
8709 Id: &Idents.get(Name: FieldNames[i]), T: FieldTypes[i], /*TInfo=*/nullptr,
8710 /*BitWidth=*/BW: nullptr,
8711 /*Mutable=*/false, InitStyle: ICIS_NoInit);
8712 Field->setAccess(AS_public);
8713 RD->addDecl(D: Field);
8714 }
8715
8716 RD->completeDefinition();
8717
8718 BlockDescriptorExtendedType = RD;
8719 return getCanonicalTagType(TD: BlockDescriptorExtendedType);
8720}
8721
8722OpenCLTypeKind ASTContext::getOpenCLTypeKind(const Type *T) const {
8723 const auto *BT = dyn_cast<BuiltinType>(Val: T);
8724
8725 if (!BT) {
8726 if (isa<PipeType>(Val: T))
8727 return OCLTK_Pipe;
8728
8729 return OCLTK_Default;
8730 }
8731
8732 switch (BT->getKind()) {
8733#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
8734 case BuiltinType::Id: \
8735 return OCLTK_Image;
8736#include "clang/Basic/OpenCLImageTypes.def"
8737
8738 case BuiltinType::OCLClkEvent:
8739 return OCLTK_ClkEvent;
8740
8741 case BuiltinType::OCLEvent:
8742 return OCLTK_Event;
8743
8744 case BuiltinType::OCLQueue:
8745 return OCLTK_Queue;
8746
8747 case BuiltinType::OCLReserveID:
8748 return OCLTK_ReserveID;
8749
8750 case BuiltinType::OCLSampler:
8751 return OCLTK_Sampler;
8752
8753 default:
8754 return OCLTK_Default;
8755 }
8756}
8757
8758LangAS ASTContext::getOpenCLTypeAddrSpace(const Type *T) const {
8759 return Target->getOpenCLTypeAddrSpace(TK: getOpenCLTypeKind(T));
8760}
8761
8762/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
8763/// requires copy/dispose. Note that this must match the logic
8764/// in buildByrefHelpers.
8765bool ASTContext::BlockRequiresCopying(QualType Ty,
8766 const VarDecl *D) {
8767 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
8768 const Expr *copyExpr = getBlockVarCopyInit(VD: D).getCopyExpr();
8769 if (!copyExpr && record->hasTrivialDestructor()) return false;
8770
8771 return true;
8772 }
8773
8774 if (Ty.hasAddressDiscriminatedPointerAuth())
8775 return true;
8776
8777 // The block needs copy/destroy helpers if Ty is non-trivial to destructively
8778 // move or destroy.
8779 if (Ty.isNonTrivialToPrimitiveDestructiveMove() || Ty.isDestructedType())
8780 return true;
8781
8782 if (!Ty->isObjCRetainableType()) return false;
8783
8784 Qualifiers qs = Ty.getQualifiers();
8785
8786 // If we have lifetime, that dominates.
8787 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
8788 switch (lifetime) {
8789 case Qualifiers::OCL_None: llvm_unreachable("impossible");
8790
8791 // These are just bits as far as the runtime is concerned.
8792 case Qualifiers::OCL_ExplicitNone:
8793 case Qualifiers::OCL_Autoreleasing:
8794 return false;
8795
8796 // These cases should have been taken care of when checking the type's
8797 // non-triviality.
8798 case Qualifiers::OCL_Weak:
8799 case Qualifiers::OCL_Strong:
8800 llvm_unreachable("impossible");
8801 }
8802 llvm_unreachable("fell out of lifetime switch!");
8803 }
8804 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
8805 Ty->isObjCObjectPointerType());
8806}
8807
8808bool ASTContext::getByrefLifetime(QualType Ty,
8809 Qualifiers::ObjCLifetime &LifeTime,
8810 bool &HasByrefExtendedLayout) const {
8811 if (!getLangOpts().ObjC ||
8812 getLangOpts().getGC() != LangOptions::NonGC)
8813 return false;
8814
8815 HasByrefExtendedLayout = false;
8816 if (Ty->isRecordType()) {
8817 HasByrefExtendedLayout = true;
8818 LifeTime = Qualifiers::OCL_None;
8819 } else if ((LifeTime = Ty.getObjCLifetime())) {
8820 // Honor the ARC qualifiers.
8821 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
8822 // The MRR rule.
8823 LifeTime = Qualifiers::OCL_ExplicitNone;
8824 } else {
8825 LifeTime = Qualifiers::OCL_None;
8826 }
8827 return true;
8828}
8829
8830CanQualType ASTContext::getNSUIntegerType() const {
8831 assert(Target && "Expected target to be initialized");
8832 const llvm::Triple &T = Target->getTriple();
8833 // Windows is LLP64 rather than LP64
8834 if (T.isOSWindows() && T.isArch64Bit())
8835 return UnsignedLongLongTy;
8836 return UnsignedLongTy;
8837}
8838
8839CanQualType ASTContext::getNSIntegerType() const {
8840 assert(Target && "Expected target to be initialized");
8841 const llvm::Triple &T = Target->getTriple();
8842 // Windows is LLP64 rather than LP64
8843 if (T.isOSWindows() && T.isArch64Bit())
8844 return LongLongTy;
8845 return LongTy;
8846}
8847
8848TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
8849 if (!ObjCInstanceTypeDecl)
8850 ObjCInstanceTypeDecl =
8851 buildImplicitTypedef(T: getObjCIdType(), Name: "instancetype");
8852 return ObjCInstanceTypeDecl;
8853}
8854
8855// This returns true if a type has been typedefed to BOOL:
8856// typedef <type> BOOL;
8857static bool isTypeTypedefedAsBOOL(QualType T) {
8858 if (const auto *TT = dyn_cast<TypedefType>(Val&: T))
8859 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
8860 return II->isStr(Str: "BOOL");
8861
8862 return false;
8863}
8864
8865/// getObjCEncodingTypeSize returns size of type for objective-c encoding
8866/// purpose.
8867CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
8868 if (!type->isIncompleteArrayType() && type->isIncompleteType())
8869 return CharUnits::Zero();
8870
8871 CharUnits sz = getTypeSizeInChars(T: type);
8872
8873 // Make all integer and enum types at least as large as an int
8874 if (sz.isPositive() && type->isIntegralOrEnumerationType())
8875 sz = std::max(a: sz, b: getTypeSizeInChars(T: IntTy));
8876 // Treat arrays as pointers, since that's how they're passed in.
8877 else if (type->isArrayType())
8878 sz = getTypeSizeInChars(T: VoidPtrTy);
8879 return sz;
8880}
8881
8882bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
8883 return getTargetInfo().getCXXABI().isMicrosoft() &&
8884 VD->isStaticDataMember() &&
8885 VD->getType()->isIntegralOrEnumerationType() &&
8886 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
8887}
8888
8889ASTContext::InlineVariableDefinitionKind
8890ASTContext::getInlineVariableDefinitionKind(const VarDecl *VD) const {
8891 if (!VD->isInline())
8892 return InlineVariableDefinitionKind::None;
8893
8894 // In almost all cases, it's a weak definition.
8895 auto *First = VD->getFirstDecl();
8896 if (First->isInlineSpecified() || !First->isStaticDataMember())
8897 return InlineVariableDefinitionKind::Weak;
8898
8899 // If there's a file-context declaration in this translation unit, it's a
8900 // non-discardable definition.
8901 for (auto *D : VD->redecls())
8902 if (D->getLexicalDeclContext()->isFileContext() &&
8903 !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr()))
8904 return InlineVariableDefinitionKind::Strong;
8905
8906 // If we've not seen one yet, we don't know.
8907 return InlineVariableDefinitionKind::WeakUnknown;
8908}
8909
8910static std::string charUnitsToString(CharUnits CU) {
8911 return llvm::itostr(X: CU.getQuantity());
8912}
8913
8914/// getObjCEncodingForBlock - Return the encoded type for this block
8915/// declaration.
8916std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
8917 std::string S;
8918
8919 const BlockDecl *Decl = Expr->getBlockDecl();
8920 QualType BlockTy =
8921 Expr->getType()->castAs<BlockPointerType>()->getPointeeType();
8922 QualType BlockReturnTy = BlockTy->castAs<FunctionType>()->getReturnType();
8923 // Encode result type.
8924 if (getLangOpts().EncodeExtendedBlockSig)
8925 getObjCEncodingForMethodParameter(QT: Decl::OBJC_TQ_None, T: BlockReturnTy, S,
8926 Extended: true /*Extended*/);
8927 else
8928 getObjCEncodingForType(T: BlockReturnTy, S);
8929 // Compute size of all parameters.
8930 // Start with computing size of a pointer in number of bytes.
8931 // FIXME: There might(should) be a better way of doing this computation!
8932 CharUnits PtrSize = getTypeSizeInChars(T: VoidPtrTy);
8933 CharUnits ParmOffset = PtrSize;
8934 for (auto *PI : Decl->parameters()) {
8935 QualType PType = PI->getType();
8936 CharUnits sz = getObjCEncodingTypeSize(type: PType);
8937 if (sz.isZero())
8938 continue;
8939 assert(sz.isPositive() && "BlockExpr - Incomplete param type");
8940 ParmOffset += sz;
8941 }
8942 // Size of the argument frame
8943 S += charUnitsToString(CU: ParmOffset);
8944 // Block pointer and offset.
8945 S += "@?0";
8946
8947 // Argument types.
8948 ParmOffset = PtrSize;
8949 for (auto *PVDecl : Decl->parameters()) {
8950 QualType PType = PVDecl->getOriginalType();
8951 if (const auto *AT =
8952 dyn_cast<ArrayType>(Val: PType->getCanonicalTypeInternal())) {
8953 // Use array's original type only if it has known number of
8954 // elements.
8955 if (!isa<ConstantArrayType>(Val: AT))
8956 PType = PVDecl->getType();
8957 } else if (PType->isFunctionType())
8958 PType = PVDecl->getType();
8959 if (getLangOpts().EncodeExtendedBlockSig)
8960 getObjCEncodingForMethodParameter(QT: Decl::OBJC_TQ_None, T: PType,
8961 S, Extended: true /*Extended*/);
8962 else
8963 getObjCEncodingForType(T: PType, S);
8964 S += charUnitsToString(CU: ParmOffset);
8965 ParmOffset += getObjCEncodingTypeSize(type: PType);
8966 }
8967
8968 return S;
8969}
8970
8971std::string
8972ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const {
8973 std::string S;
8974 // Encode result type.
8975 getObjCEncodingForType(T: Decl->getReturnType(), S);
8976 CharUnits ParmOffset;
8977 // Compute size of all parameters.
8978 for (auto *PI : Decl->parameters()) {
8979 QualType PType = PI->getType();
8980 CharUnits sz = getObjCEncodingTypeSize(type: PType);
8981 if (sz.isZero())
8982 continue;
8983
8984 assert(sz.isPositive() &&
8985 "getObjCEncodingForFunctionDecl - Incomplete param type");
8986 ParmOffset += sz;
8987 }
8988 S += charUnitsToString(CU: ParmOffset);
8989 ParmOffset = CharUnits::Zero();
8990
8991 // Argument types.
8992 for (auto *PVDecl : Decl->parameters()) {
8993 QualType PType = PVDecl->getOriginalType();
8994 if (const auto *AT =
8995 dyn_cast<ArrayType>(Val: PType->getCanonicalTypeInternal())) {
8996 // Use array's original type only if it has known number of
8997 // elements.
8998 if (!isa<ConstantArrayType>(Val: AT))
8999 PType = PVDecl->getType();
9000 } else if (PType->isFunctionType())
9001 PType = PVDecl->getType();
9002 getObjCEncodingForType(T: PType, S);
9003 S += charUnitsToString(CU: ParmOffset);
9004 ParmOffset += getObjCEncodingTypeSize(type: PType);
9005 }
9006
9007 return S;
9008}
9009
9010/// getObjCEncodingForMethodParameter - Return the encoded type for a single
9011/// method parameter or return type. If Extended, include class names and
9012/// block object types.
9013void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
9014 QualType T, std::string& S,
9015 bool Extended) const {
9016 // Encode type qualifier, 'in', 'inout', etc. for the parameter.
9017 getObjCEncodingForTypeQualifier(QT, S);
9018 // Encode parameter type.
9019 ObjCEncOptions Options = ObjCEncOptions()
9020 .setExpandPointedToStructures()
9021 .setExpandStructures()
9022 .setIsOutermostType();
9023 if (Extended)
9024 Options.setEncodeBlockParameters().setEncodeClassNames();
9025 getObjCEncodingForTypeImpl(t: T, S, Options, /*Field=*/nullptr);
9026}
9027
9028/// getObjCEncodingForMethodDecl - Return the encoded type for this method
9029/// declaration.
9030std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
9031 bool Extended) const {
9032 // FIXME: This is not very efficient.
9033 // Encode return type.
9034 std::string S;
9035 getObjCEncodingForMethodParameter(QT: Decl->getObjCDeclQualifier(),
9036 T: Decl->getReturnType(), S, Extended);
9037 // Compute size of all parameters.
9038 // Start with computing size of a pointer in number of bytes.
9039 // FIXME: There might(should) be a better way of doing this computation!
9040 CharUnits PtrSize = getTypeSizeInChars(T: VoidPtrTy);
9041 // The first two arguments (self and _cmd) are pointers; account for
9042 // their size.
9043 CharUnits ParmOffset = 2 * PtrSize;
9044 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
9045 E = Decl->sel_param_end(); PI != E; ++PI) {
9046 QualType PType = (*PI)->getType();
9047 CharUnits sz = getObjCEncodingTypeSize(type: PType);
9048 if (sz.isZero())
9049 continue;
9050
9051 assert(sz.isPositive() &&
9052 "getObjCEncodingForMethodDecl - Incomplete param type");
9053 ParmOffset += sz;
9054 }
9055 S += charUnitsToString(CU: ParmOffset);
9056 S += "@0:";
9057 S += charUnitsToString(CU: PtrSize);
9058
9059 // Argument types.
9060 ParmOffset = 2 * PtrSize;
9061 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
9062 E = Decl->sel_param_end(); PI != E; ++PI) {
9063 const ParmVarDecl *PVDecl = *PI;
9064 QualType PType = PVDecl->getOriginalType();
9065 if (const auto *AT =
9066 dyn_cast<ArrayType>(Val: PType->getCanonicalTypeInternal())) {
9067 // Use array's original type only if it has known number of
9068 // elements.
9069 if (!isa<ConstantArrayType>(Val: AT))
9070 PType = PVDecl->getType();
9071 } else if (PType->isFunctionType())
9072 PType = PVDecl->getType();
9073 getObjCEncodingForMethodParameter(QT: PVDecl->getObjCDeclQualifier(),
9074 T: PType, S, Extended);
9075 S += charUnitsToString(CU: ParmOffset);
9076 ParmOffset += getObjCEncodingTypeSize(type: PType);
9077 }
9078
9079 return S;
9080}
9081
9082ObjCPropertyImplDecl *
9083ASTContext::getObjCPropertyImplDeclForPropertyDecl(
9084 const ObjCPropertyDecl *PD,
9085 const Decl *Container) const {
9086 if (!Container)
9087 return nullptr;
9088 if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Val: Container)) {
9089 for (auto *PID : CID->property_impls())
9090 if (PID->getPropertyDecl() == PD)
9091 return PID;
9092 } else {
9093 const auto *OID = cast<ObjCImplementationDecl>(Val: Container);
9094 for (auto *PID : OID->property_impls())
9095 if (PID->getPropertyDecl() == PD)
9096 return PID;
9097 }
9098 return nullptr;
9099}
9100
9101/// getObjCEncodingForPropertyDecl - Return the encoded type for this
9102/// property declaration. If non-NULL, Container must be either an
9103/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
9104/// NULL when getting encodings for protocol properties.
9105/// Property attributes are stored as a comma-delimited C string. The simple
9106/// attributes readonly and bycopy are encoded as single characters. The
9107/// parametrized attributes, getter=name, setter=name, and ivar=name, are
9108/// encoded as single characters, followed by an identifier. Property types
9109/// are also encoded as a parametrized attribute. The characters used to encode
9110/// these attributes are defined by the following enumeration:
9111/// @code
9112/// enum PropertyAttributes {
9113/// kPropertyReadOnly = 'R', // property is read-only.
9114/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
9115/// kPropertyByref = '&', // property is a reference to the value last assigned
9116/// kPropertyDynamic = 'D', // property is dynamic
9117/// kPropertyGetter = 'G', // followed by getter selector name
9118/// kPropertySetter = 'S', // followed by setter selector name
9119/// kPropertyInstanceVariable = 'V' // followed by instance variable name
9120/// kPropertyType = 'T' // followed by old-style type encoding.
9121/// kPropertyWeak = 'W' // 'weak' property
9122/// kPropertyStrong = 'P' // property GC'able
9123/// kPropertyNonAtomic = 'N' // property non-atomic
9124/// kPropertyOptional = '?' // property optional
9125/// };
9126/// @endcode
9127std::string
9128ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
9129 const Decl *Container) const {
9130 // Collect information from the property implementation decl(s).
9131 bool Dynamic = false;
9132 ObjCPropertyImplDecl *SynthesizePID = nullptr;
9133
9134 if (ObjCPropertyImplDecl *PropertyImpDecl =
9135 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
9136 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
9137 Dynamic = true;
9138 else
9139 SynthesizePID = PropertyImpDecl;
9140 }
9141
9142 // FIXME: This is not very efficient.
9143 std::string S = "T";
9144
9145 // Encode result type.
9146 // GCC has some special rules regarding encoding of properties which
9147 // closely resembles encoding of ivars.
9148 getObjCEncodingForPropertyType(T: PD->getType(), S);
9149
9150 if (PD->isOptional())
9151 S += ",?";
9152
9153 if (PD->isReadOnly()) {
9154 S += ",R";
9155 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_copy)
9156 S += ",C";
9157 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_retain)
9158 S += ",&";
9159 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_weak)
9160 S += ",W";
9161 } else {
9162 switch (PD->getSetterKind()) {
9163 case ObjCPropertyDecl::Assign: break;
9164 case ObjCPropertyDecl::Copy: S += ",C"; break;
9165 case ObjCPropertyDecl::Retain: S += ",&"; break;
9166 case ObjCPropertyDecl::Weak: S += ",W"; break;
9167 }
9168 }
9169
9170 // It really isn't clear at all what this means, since properties
9171 // are "dynamic by default".
9172 if (Dynamic)
9173 S += ",D";
9174
9175 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_nonatomic)
9176 S += ",N";
9177
9178 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_getter) {
9179 S += ",G";
9180 S += PD->getGetterName().getAsString();
9181 }
9182
9183 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_setter) {
9184 S += ",S";
9185 S += PD->getSetterName().getAsString();
9186 }
9187
9188 if (SynthesizePID) {
9189 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
9190 S += ",V";
9191 S += OID->getNameAsString();
9192 }
9193
9194 // FIXME: OBJCGC: weak & strong
9195 return S;
9196}
9197
9198/// getLegacyIntegralTypeEncoding -
9199/// Another legacy compatibility encoding: 32-bit longs are encoded as
9200/// 'l' or 'L' , but not always. For typedefs, we need to use
9201/// 'i' or 'I' instead if encoding a struct field, or a pointer!
9202void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
9203 if (PointeeTy->getAs<TypedefType>()) {
9204 if (const auto *BT = PointeeTy->getAs<BuiltinType>()) {
9205 if (BT->getKind() == BuiltinType::ULong && getIntWidth(T: PointeeTy) == 32)
9206 PointeeTy = UnsignedIntTy;
9207 else
9208 if (BT->getKind() == BuiltinType::Long && getIntWidth(T: PointeeTy) == 32)
9209 PointeeTy = IntTy;
9210 }
9211 }
9212}
9213
9214void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
9215 const FieldDecl *Field,
9216 QualType *NotEncodedT) const {
9217 // We follow the behavior of gcc, expanding structures which are
9218 // directly pointed to, and expanding embedded structures. Note that
9219 // these rules are sufficient to prevent recursive encoding of the
9220 // same type.
9221 getObjCEncodingForTypeImpl(t: T, S,
9222 Options: ObjCEncOptions()
9223 .setExpandPointedToStructures()
9224 .setExpandStructures()
9225 .setIsOutermostType(),
9226 Field, NotEncodedT);
9227}
9228
9229void ASTContext::getObjCEncodingForPropertyType(QualType T,
9230 std::string& S) const {
9231 // Encode result type.
9232 // GCC has some special rules regarding encoding of properties which
9233 // closely resembles encoding of ivars.
9234 getObjCEncodingForTypeImpl(t: T, S,
9235 Options: ObjCEncOptions()
9236 .setExpandPointedToStructures()
9237 .setExpandStructures()
9238 .setIsOutermostType()
9239 .setEncodingProperty(),
9240 /*Field=*/nullptr);
9241}
9242
9243static char getObjCEncodingForPrimitiveType(const ASTContext *C,
9244 const BuiltinType *BT) {
9245 BuiltinType::Kind kind = BT->getKind();
9246 switch (kind) {
9247 case BuiltinType::Void: return 'v';
9248 case BuiltinType::Bool: return 'B';
9249 case BuiltinType::Char8:
9250 case BuiltinType::Char_U:
9251 case BuiltinType::UChar: return 'C';
9252 case BuiltinType::Char16:
9253 case BuiltinType::UShort: return 'S';
9254 case BuiltinType::Char32:
9255 case BuiltinType::UInt: return 'I';
9256 case BuiltinType::ULong:
9257 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
9258 case BuiltinType::UInt128: return 'T';
9259 case BuiltinType::ULongLong: return 'Q';
9260 case BuiltinType::Char_S:
9261 case BuiltinType::SChar: return 'c';
9262 case BuiltinType::Short: return 's';
9263 case BuiltinType::WChar_S:
9264 case BuiltinType::WChar_U:
9265 case BuiltinType::Int: return 'i';
9266 case BuiltinType::Long:
9267 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
9268 case BuiltinType::LongLong: return 'q';
9269 case BuiltinType::Int128: return 't';
9270 case BuiltinType::Float: return 'f';
9271 case BuiltinType::Double: return 'd';
9272 case BuiltinType::LongDouble: return 'D';
9273 case BuiltinType::NullPtr: return '*'; // like char*
9274
9275 case BuiltinType::BFloat16:
9276 case BuiltinType::Float16:
9277 case BuiltinType::Float128:
9278 case BuiltinType::Ibm128:
9279 case BuiltinType::Half:
9280 case BuiltinType::ShortAccum:
9281 case BuiltinType::Accum:
9282 case BuiltinType::LongAccum:
9283 case BuiltinType::UShortAccum:
9284 case BuiltinType::UAccum:
9285 case BuiltinType::ULongAccum:
9286 case BuiltinType::ShortFract:
9287 case BuiltinType::Fract:
9288 case BuiltinType::LongFract:
9289 case BuiltinType::UShortFract:
9290 case BuiltinType::UFract:
9291 case BuiltinType::ULongFract:
9292 case BuiltinType::SatShortAccum:
9293 case BuiltinType::SatAccum:
9294 case BuiltinType::SatLongAccum:
9295 case BuiltinType::SatUShortAccum:
9296 case BuiltinType::SatUAccum:
9297 case BuiltinType::SatULongAccum:
9298 case BuiltinType::SatShortFract:
9299 case BuiltinType::SatFract:
9300 case BuiltinType::SatLongFract:
9301 case BuiltinType::SatUShortFract:
9302 case BuiltinType::SatUFract:
9303 case BuiltinType::SatULongFract:
9304 // FIXME: potentially need @encodes for these!
9305 return ' ';
9306
9307#define SVE_TYPE(Name, Id, SingletonId) \
9308 case BuiltinType::Id:
9309#include "clang/Basic/AArch64ACLETypes.def"
9310#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9311#include "clang/Basic/RISCVVTypes.def"
9312#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9313#include "clang/Basic/WebAssemblyReferenceTypes.def"
9314#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
9315#include "clang/Basic/AMDGPUTypes.def"
9316#define SPIRV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9317#include "clang/Basic/SPIRVTypes.def"
9318 {
9319 DiagnosticsEngine &Diags = C->getDiagnostics();
9320 Diags.Report(DiagID: diag::err_unsupported_objc_primitive_encoding)
9321 << QualType(BT, 0);
9322 return ' ';
9323 }
9324
9325 case BuiltinType::ObjCId:
9326 case BuiltinType::ObjCClass:
9327 case BuiltinType::ObjCSel:
9328 llvm_unreachable("@encoding ObjC primitive type");
9329
9330 // OpenCL and placeholder types don't need @encodings.
9331#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
9332 case BuiltinType::Id:
9333#include "clang/Basic/OpenCLImageTypes.def"
9334#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
9335 case BuiltinType::Id:
9336#include "clang/Basic/OpenCLExtensionTypes.def"
9337 case BuiltinType::OCLEvent:
9338 case BuiltinType::OCLClkEvent:
9339 case BuiltinType::OCLQueue:
9340 case BuiltinType::OCLReserveID:
9341 case BuiltinType::OCLSampler:
9342 case BuiltinType::Dependent:
9343 case BuiltinType::MetaInfo:
9344#define PPC_VECTOR_TYPE(Name, Id, Size) \
9345 case BuiltinType::Id:
9346#include "clang/Basic/PPCTypes.def"
9347#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9348#include "clang/Basic/HLSLIntangibleTypes.def"
9349#define HLSL_PACKED_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9350#include "clang/Basic/HLSLPackedTypes.def"
9351#define BUILTIN_TYPE(KIND, ID)
9352#define PLACEHOLDER_TYPE(KIND, ID) \
9353 case BuiltinType::KIND:
9354#include "clang/AST/BuiltinTypes.def"
9355 llvm_unreachable("invalid builtin type for @encode");
9356 }
9357 llvm_unreachable("invalid BuiltinType::Kind value");
9358}
9359
9360static char ObjCEncodingForEnumDecl(const ASTContext *C, const EnumDecl *ED) {
9361 EnumDecl *Enum = ED->getDefinitionOrSelf();
9362
9363 // The encoding of an non-fixed enum type is always 'i', regardless of size.
9364 if (!Enum->isFixed())
9365 return 'i';
9366
9367 // The encoding of a fixed enum type matches its fixed underlying type.
9368 const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>();
9369 return getObjCEncodingForPrimitiveType(C, BT);
9370}
9371
9372static void EncodeBitField(const ASTContext *Ctx, std::string& S,
9373 QualType T, const FieldDecl *FD) {
9374 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
9375 S += 'b';
9376 // The NeXT runtime encodes bit fields as b followed by the number of bits.
9377 // The GNU runtime requires more information; bitfields are encoded as b,
9378 // then the offset (in bits) of the first element, then the type of the
9379 // bitfield, then the size in bits. For example, in this structure:
9380 //
9381 // struct
9382 // {
9383 // int integer;
9384 // int flags:2;
9385 // };
9386 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
9387 // runtime, but b32i2 for the GNU runtime. The reason for this extra
9388 // information is not especially sensible, but we're stuck with it for
9389 // compatibility with GCC, although providing it breaks anything that
9390 // actually uses runtime introspection and wants to work on both runtimes...
9391 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
9392 uint64_t Offset;
9393
9394 if (const auto *IVD = dyn_cast<ObjCIvarDecl>(Val: FD)) {
9395 Offset = Ctx->lookupFieldBitOffset(OID: IVD->getContainingInterface(), Ivar: IVD);
9396 } else {
9397 const RecordDecl *RD = FD->getParent();
9398 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(D: RD);
9399 Offset = RL.getFieldOffset(FieldNo: FD->getFieldIndex());
9400 }
9401
9402 S += llvm::utostr(X: Offset);
9403
9404 if (const auto *ET = T->getAsCanonical<EnumType>())
9405 S += ObjCEncodingForEnumDecl(C: Ctx, ED: ET->getDecl());
9406 else {
9407 const auto *BT = T->castAs<BuiltinType>();
9408 S += getObjCEncodingForPrimitiveType(C: Ctx, BT);
9409 }
9410 }
9411 S += llvm::utostr(X: FD->getBitWidthValue());
9412}
9413
9414// Helper function for determining whether the encoded type string would include
9415// a template specialization type.
9416static bool hasTemplateSpecializationInEncodedString(const Type *T,
9417 bool VisitBasesAndFields) {
9418 T = T->getBaseElementTypeUnsafe();
9419
9420 if (auto *PT = T->getAs<PointerType>())
9421 return hasTemplateSpecializationInEncodedString(
9422 T: PT->getPointeeType().getTypePtr(), VisitBasesAndFields: false);
9423
9424 auto *CXXRD = T->getAsCXXRecordDecl();
9425
9426 if (!CXXRD)
9427 return false;
9428
9429 if (isa<ClassTemplateSpecializationDecl>(Val: CXXRD))
9430 return true;
9431
9432 if (!CXXRD->hasDefinition() || !VisitBasesAndFields)
9433 return false;
9434
9435 for (const auto &B : CXXRD->bases())
9436 if (hasTemplateSpecializationInEncodedString(T: B.getType().getTypePtr(),
9437 VisitBasesAndFields: true))
9438 return true;
9439
9440 for (auto *FD : CXXRD->fields())
9441 if (hasTemplateSpecializationInEncodedString(T: FD->getType().getTypePtr(),
9442 VisitBasesAndFields: true))
9443 return true;
9444
9445 return false;
9446}
9447
9448// FIXME: Use SmallString for accumulating string.
9449void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S,
9450 const ObjCEncOptions Options,
9451 const FieldDecl *FD,
9452 QualType *NotEncodedT) const {
9453 CanQualType CT = getCanonicalType(T);
9454 switch (CT->getTypeClass()) {
9455 case Type::Builtin:
9456 case Type::Enum:
9457 if (FD && FD->isBitField())
9458 return EncodeBitField(Ctx: this, S, T, FD);
9459 if (const auto *BT = dyn_cast<BuiltinType>(Val&: CT))
9460 S += getObjCEncodingForPrimitiveType(C: this, BT);
9461 else
9462 S += ObjCEncodingForEnumDecl(C: this, ED: cast<EnumType>(Val&: CT)->getDecl());
9463 return;
9464
9465 case Type::Complex:
9466 S += 'j';
9467 getObjCEncodingForTypeImpl(T: T->castAs<ComplexType>()->getElementType(), S,
9468 Options: ObjCEncOptions(),
9469 /*Field=*/FD: nullptr);
9470 return;
9471
9472 case Type::Atomic:
9473 S += 'A';
9474 getObjCEncodingForTypeImpl(T: T->castAs<AtomicType>()->getValueType(), S,
9475 Options: ObjCEncOptions(),
9476 /*Field=*/FD: nullptr);
9477 return;
9478
9479 // encoding for pointer or reference types.
9480 case Type::Pointer:
9481 case Type::LValueReference:
9482 case Type::RValueReference: {
9483 QualType PointeeTy;
9484 if (isa<PointerType>(Val: CT)) {
9485 const auto *PT = T->castAs<PointerType>();
9486 if (PT->isObjCSelType()) {
9487 S += ':';
9488 return;
9489 }
9490 PointeeTy = PT->getPointeeType();
9491 } else {
9492 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
9493 }
9494
9495 bool isReadOnly = false;
9496 // For historical/compatibility reasons, the read-only qualifier of the
9497 // pointee gets emitted _before_ the '^'. The read-only qualifier of
9498 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
9499 // Also, do not emit the 'r' for anything but the outermost type!
9500 if (T->getAs<TypedefType>()) {
9501 if (Options.IsOutermostType() && T.isConstQualified()) {
9502 isReadOnly = true;
9503 S += 'r';
9504 }
9505 } else if (Options.IsOutermostType()) {
9506 QualType P = PointeeTy;
9507 while (auto PT = P->getAs<PointerType>())
9508 P = PT->getPointeeType();
9509 if (P.isConstQualified()) {
9510 isReadOnly = true;
9511 S += 'r';
9512 }
9513 }
9514 if (isReadOnly) {
9515 // Another legacy compatibility encoding. Some ObjC qualifier and type
9516 // combinations need to be rearranged.
9517 // Rewrite "in const" from "nr" to "rn"
9518 if (StringRef(S).ends_with(Suffix: "nr"))
9519 S.replace(i1: S.end()-2, i2: S.end(), s: "rn");
9520 }
9521
9522 if (PointeeTy->isCharType()) {
9523 // char pointer types should be encoded as '*' unless it is a
9524 // type that has been typedef'd to 'BOOL'.
9525 if (!isTypeTypedefedAsBOOL(T: PointeeTy)) {
9526 S += '*';
9527 return;
9528 }
9529 } else if (const auto *RTy = PointeeTy->getAsCanonical<RecordType>()) {
9530 const IdentifierInfo *II = RTy->getDecl()->getIdentifier();
9531 // GCC binary compat: Need to convert "struct objc_class *" to "#".
9532 if (II == &Idents.get(Name: "objc_class")) {
9533 S += '#';
9534 return;
9535 }
9536 // GCC binary compat: Need to convert "struct objc_object *" to "@".
9537 if (II == &Idents.get(Name: "objc_object")) {
9538 S += '@';
9539 return;
9540 }
9541 // If the encoded string for the class includes template names, just emit
9542 // "^v" for pointers to the class.
9543 if (getLangOpts().CPlusPlus &&
9544 (!getLangOpts().EncodeCXXClassTemplateSpec &&
9545 hasTemplateSpecializationInEncodedString(
9546 T: RTy, VisitBasesAndFields: Options.ExpandPointedToStructures()))) {
9547 S += "^v";
9548 return;
9549 }
9550 // fall through...
9551 }
9552 S += '^';
9553 getLegacyIntegralTypeEncoding(PointeeTy);
9554
9555 ObjCEncOptions NewOptions;
9556 if (Options.ExpandPointedToStructures())
9557 NewOptions.setExpandStructures();
9558 getObjCEncodingForTypeImpl(T: PointeeTy, S, Options: NewOptions,
9559 /*Field=*/FD: nullptr, NotEncodedT);
9560 return;
9561 }
9562
9563 case Type::ConstantArray:
9564 case Type::IncompleteArray:
9565 case Type::VariableArray: {
9566 const auto *AT = cast<ArrayType>(Val&: CT);
9567
9568 if (isa<IncompleteArrayType>(Val: AT) && !Options.IsStructField()) {
9569 // Incomplete arrays are encoded as a pointer to the array element.
9570 S += '^';
9571
9572 getObjCEncodingForTypeImpl(
9573 T: AT->getElementType(), S,
9574 Options: Options.keepingOnly(Mask: ObjCEncOptions().setExpandStructures()), FD);
9575 } else {
9576 S += '[';
9577
9578 if (const auto *CAT = dyn_cast<ConstantArrayType>(Val: AT))
9579 S += llvm::utostr(X: CAT->getZExtSize());
9580 else {
9581 //Variable length arrays are encoded as a regular array with 0 elements.
9582 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
9583 "Unknown array type!");
9584 S += '0';
9585 }
9586
9587 getObjCEncodingForTypeImpl(
9588 T: AT->getElementType(), S,
9589 Options: Options.keepingOnly(Mask: ObjCEncOptions().setExpandStructures()), FD,
9590 NotEncodedT);
9591 S += ']';
9592 }
9593 return;
9594 }
9595
9596 case Type::FunctionNoProto:
9597 case Type::FunctionProto:
9598 S += '?';
9599 return;
9600
9601 case Type::Record: {
9602 RecordDecl *RDecl = cast<RecordType>(Val&: CT)->getDecl();
9603 S += RDecl->isUnion() ? '(' : '{';
9604 // Anonymous structures print as '?'
9605 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
9606 S += II->getName();
9607 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(Val: RDecl)) {
9608 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
9609 llvm::raw_string_ostream OS(S);
9610 printTemplateArgumentList(OS, Args: TemplateArgs.asArray(),
9611 Policy: getPrintingPolicy());
9612 }
9613 } else {
9614 S += '?';
9615 }
9616 if (Options.ExpandStructures()) {
9617 S += '=';
9618 if (!RDecl->isUnion()) {
9619 getObjCEncodingForStructureImpl(RD: RDecl, S, Field: FD, includeVBases: true, NotEncodedT);
9620 } else {
9621 for (const auto *Field : RDecl->fields()) {
9622 if (FD) {
9623 S += '"';
9624 S += Field->getNameAsString();
9625 S += '"';
9626 }
9627
9628 // Special case bit-fields.
9629 if (Field->isBitField()) {
9630 getObjCEncodingForTypeImpl(T: Field->getType(), S,
9631 Options: ObjCEncOptions().setExpandStructures(),
9632 FD: Field);
9633 } else {
9634 QualType qt = Field->getType();
9635 getLegacyIntegralTypeEncoding(PointeeTy&: qt);
9636 getObjCEncodingForTypeImpl(
9637 T: qt, S,
9638 Options: ObjCEncOptions().setExpandStructures().setIsStructField(), FD,
9639 NotEncodedT);
9640 }
9641 }
9642 }
9643 }
9644 S += RDecl->isUnion() ? ')' : '}';
9645 return;
9646 }
9647
9648 case Type::BlockPointer: {
9649 const auto *BT = T->castAs<BlockPointerType>();
9650 S += "@?"; // Unlike a pointer-to-function, which is "^?".
9651 if (Options.EncodeBlockParameters()) {
9652 const auto *FT = BT->getPointeeType()->castAs<FunctionType>();
9653
9654 S += '<';
9655 // Block return type
9656 getObjCEncodingForTypeImpl(T: FT->getReturnType(), S,
9657 Options: Options.forComponentType(), FD, NotEncodedT);
9658 // Block self
9659 S += "@?";
9660 // Block parameters
9661 if (const auto *FPT = dyn_cast<FunctionProtoType>(Val: FT)) {
9662 for (const auto &I : FPT->param_types())
9663 getObjCEncodingForTypeImpl(T: I, S, Options: Options.forComponentType(), FD,
9664 NotEncodedT);
9665 }
9666 S += '>';
9667 }
9668 return;
9669 }
9670
9671 case Type::ObjCObject: {
9672 // hack to match legacy encoding of *id and *Class
9673 QualType Ty = getObjCObjectPointerType(ObjectT: CT);
9674 if (Ty->isObjCIdType()) {
9675 S += "{objc_object=}";
9676 return;
9677 }
9678 else if (Ty->isObjCClassType()) {
9679 S += "{objc_class=}";
9680 return;
9681 }
9682 // TODO: Double check to make sure this intentionally falls through.
9683 [[fallthrough]];
9684 }
9685
9686 case Type::ObjCInterface: {
9687 // Ignore protocol qualifiers when mangling at this level.
9688 // @encode(class_name)
9689 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
9690 S += '{';
9691 S += OI->getObjCRuntimeNameAsString();
9692 if (Options.ExpandStructures()) {
9693 S += '=';
9694 SmallVector<const ObjCIvarDecl*, 32> Ivars;
9695 DeepCollectObjCIvars(OI, leafClass: true, Ivars);
9696 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
9697 const FieldDecl *Field = Ivars[i];
9698 if (Field->isBitField())
9699 getObjCEncodingForTypeImpl(T: Field->getType(), S,
9700 Options: ObjCEncOptions().setExpandStructures(),
9701 FD: Field);
9702 else
9703 getObjCEncodingForTypeImpl(T: Field->getType(), S,
9704 Options: ObjCEncOptions().setExpandStructures(), FD,
9705 NotEncodedT);
9706 }
9707 }
9708 S += '}';
9709 return;
9710 }
9711
9712 case Type::ObjCObjectPointer: {
9713 const auto *OPT = T->castAs<ObjCObjectPointerType>();
9714 if (OPT->isObjCIdType()) {
9715 S += '@';
9716 return;
9717 }
9718
9719 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
9720 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
9721 // Since this is a binary compatibility issue, need to consult with
9722 // runtime folks. Fortunately, this is a *very* obscure construct.
9723 S += '#';
9724 return;
9725 }
9726
9727 if (OPT->isObjCQualifiedIdType()) {
9728 getObjCEncodingForTypeImpl(
9729 T: getObjCIdType(), S,
9730 Options: Options.keepingOnly(Mask: ObjCEncOptions()
9731 .setExpandPointedToStructures()
9732 .setExpandStructures()),
9733 FD);
9734 if (FD || Options.EncodingProperty() || Options.EncodeClassNames()) {
9735 // Note that we do extended encoding of protocol qualifier list
9736 // Only when doing ivar or property encoding.
9737 S += '"';
9738 for (const auto *I : OPT->quals()) {
9739 S += '<';
9740 S += I->getObjCRuntimeNameAsString();
9741 S += '>';
9742 }
9743 S += '"';
9744 }
9745 return;
9746 }
9747
9748 S += '@';
9749 if (OPT->getInterfaceDecl() &&
9750 (FD || Options.EncodingProperty() || Options.EncodeClassNames())) {
9751 S += '"';
9752 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
9753 for (const auto *I : OPT->quals()) {
9754 S += '<';
9755 S += I->getObjCRuntimeNameAsString();
9756 S += '>';
9757 }
9758 S += '"';
9759 }
9760 return;
9761 }
9762
9763 // gcc just blithely ignores member pointers.
9764 // FIXME: we should do better than that. 'M' is available.
9765 case Type::MemberPointer:
9766 // This matches gcc's encoding, even though technically it is insufficient.
9767 //FIXME. We should do a better job than gcc.
9768 case Type::Vector:
9769 case Type::ExtVector:
9770 // Until we have a coherent encoding of these three types, issue warning.
9771 if (NotEncodedT)
9772 *NotEncodedT = T;
9773 return;
9774
9775 case Type::ConstantMatrix:
9776 if (NotEncodedT)
9777 *NotEncodedT = T;
9778 return;
9779
9780 case Type::BitInt:
9781 if (NotEncodedT)
9782 *NotEncodedT = T;
9783 return;
9784
9785 // We could see an undeduced auto type here during error recovery.
9786 // Just ignore it.
9787 case Type::Auto:
9788 case Type::DeducedTemplateSpecialization:
9789 return;
9790
9791 case Type::HLSLAttributedResource:
9792 case Type::HLSLInlineSpirv:
9793 case Type::OverflowBehavior:
9794 llvm_unreachable("unexpected type");
9795
9796 case Type::ArrayParameter:
9797 case Type::Pipe:
9798#define ABSTRACT_TYPE(KIND, BASE)
9799#define TYPE(KIND, BASE)
9800#define DEPENDENT_TYPE(KIND, BASE) \
9801 case Type::KIND:
9802#define NON_CANONICAL_TYPE(KIND, BASE) \
9803 case Type::KIND:
9804#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
9805 case Type::KIND:
9806#include "clang/AST/TypeNodes.inc"
9807 llvm_unreachable("@encode for dependent type!");
9808 }
9809 llvm_unreachable("bad type kind!");
9810}
9811
9812void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
9813 std::string &S,
9814 const FieldDecl *FD,
9815 bool includeVBases,
9816 QualType *NotEncodedT) const {
9817 assert(RDecl && "Expected non-null RecordDecl");
9818 assert(!RDecl->isUnion() && "Should not be called for unions");
9819 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
9820 return;
9821
9822 const auto *CXXRec = dyn_cast<CXXRecordDecl>(Val: RDecl);
9823 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
9824 const ASTRecordLayout &layout = getASTRecordLayout(D: RDecl);
9825
9826 if (CXXRec) {
9827 for (const auto &BI : CXXRec->bases()) {
9828 if (!BI.isVirtual()) {
9829 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
9830 if (base->isEmpty())
9831 continue;
9832 uint64_t offs = toBits(CharSize: layout.getBaseClassOffset(Base: base));
9833 FieldOrBaseOffsets.insert(position: FieldOrBaseOffsets.upper_bound(x: offs),
9834 x: std::make_pair(x&: offs, y&: base));
9835 }
9836 }
9837 }
9838
9839 for (FieldDecl *Field : RDecl->fields()) {
9840 if (!Field->isZeroLengthBitField() && Field->isZeroSize(Ctx: *this))
9841 continue;
9842 uint64_t offs = layout.getFieldOffset(FieldNo: Field->getFieldIndex());
9843 FieldOrBaseOffsets.insert(position: FieldOrBaseOffsets.upper_bound(x: offs),
9844 x: std::make_pair(x&: offs, y&: Field));
9845 }
9846
9847 if (CXXRec && includeVBases) {
9848 for (const auto &BI : CXXRec->vbases()) {
9849 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
9850 if (base->isEmpty())
9851 continue;
9852 uint64_t offs = toBits(CharSize: layout.getVBaseClassOffset(VBase: base));
9853 if (offs >= uint64_t(toBits(CharSize: layout.getNonVirtualSize())) &&
9854 FieldOrBaseOffsets.find(x: offs) == FieldOrBaseOffsets.end())
9855 FieldOrBaseOffsets.insert(position: FieldOrBaseOffsets.end(),
9856 x: std::make_pair(x&: offs, y&: base));
9857 }
9858 }
9859
9860 CharUnits size;
9861 if (CXXRec) {
9862 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
9863 } else {
9864 size = layout.getSize();
9865 }
9866
9867#ifndef NDEBUG
9868 uint64_t CurOffs = 0;
9869#endif
9870 std::multimap<uint64_t, NamedDecl *>::iterator
9871 CurLayObj = FieldOrBaseOffsets.begin();
9872
9873 if (CXXRec && CXXRec->isDynamicClass() &&
9874 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
9875 if (FD) {
9876 S += "\"_vptr$";
9877 std::string recname = CXXRec->getNameAsString();
9878 if (recname.empty()) recname = "?";
9879 S += recname;
9880 S += '"';
9881 }
9882 S += "^^?";
9883#ifndef NDEBUG
9884 CurOffs += getTypeSize(VoidPtrTy);
9885#endif
9886 }
9887
9888 if (!RDecl->hasFlexibleArrayMember()) {
9889 // Mark the end of the structure.
9890 uint64_t offs = toBits(CharSize: size);
9891 FieldOrBaseOffsets.insert(position: FieldOrBaseOffsets.upper_bound(x: offs),
9892 x: std::make_pair(x&: offs, y: nullptr));
9893 }
9894
9895 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
9896#ifndef NDEBUG
9897 assert(CurOffs <= CurLayObj->first);
9898 if (CurOffs < CurLayObj->first) {
9899 uint64_t padding = CurLayObj->first - CurOffs;
9900 // FIXME: There doesn't seem to be a way to indicate in the encoding that
9901 // packing/alignment of members is different that normal, in which case
9902 // the encoding will be out-of-sync with the real layout.
9903 // If the runtime switches to just consider the size of types without
9904 // taking into account alignment, we could make padding explicit in the
9905 // encoding (e.g. using arrays of chars). The encoding strings would be
9906 // longer then though.
9907 CurOffs += padding;
9908 }
9909#endif
9910
9911 NamedDecl *dcl = CurLayObj->second;
9912 if (!dcl)
9913 break; // reached end of structure.
9914
9915 if (auto *base = dyn_cast<CXXRecordDecl>(Val: dcl)) {
9916 // We expand the bases without their virtual bases since those are going
9917 // in the initial structure. Note that this differs from gcc which
9918 // expands virtual bases each time one is encountered in the hierarchy,
9919 // making the encoding type bigger than it really is.
9920 getObjCEncodingForStructureImpl(RDecl: base, S, FD, /*includeVBases*/false,
9921 NotEncodedT);
9922 assert(!base->isEmpty());
9923#ifndef NDEBUG
9924 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
9925#endif
9926 } else {
9927 const auto *field = cast<FieldDecl>(Val: dcl);
9928 if (FD) {
9929 S += '"';
9930 S += field->getNameAsString();
9931 S += '"';
9932 }
9933
9934 if (field->isBitField()) {
9935 EncodeBitField(Ctx: this, S, T: field->getType(), FD: field);
9936#ifndef NDEBUG
9937 CurOffs += field->getBitWidthValue();
9938#endif
9939 } else {
9940 QualType qt = field->getType();
9941 getLegacyIntegralTypeEncoding(PointeeTy&: qt);
9942 getObjCEncodingForTypeImpl(
9943 T: qt, S, Options: ObjCEncOptions().setExpandStructures().setIsStructField(),
9944 FD, NotEncodedT);
9945#ifndef NDEBUG
9946 CurOffs += getTypeSize(field->getType());
9947#endif
9948 }
9949 }
9950 }
9951}
9952
9953void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
9954 std::string& S) const {
9955 if (QT & Decl::OBJC_TQ_In)
9956 S += 'n';
9957 if (QT & Decl::OBJC_TQ_Inout)
9958 S += 'N';
9959 if (QT & Decl::OBJC_TQ_Out)
9960 S += 'o';
9961 if (QT & Decl::OBJC_TQ_Bycopy)
9962 S += 'O';
9963 if (QT & Decl::OBJC_TQ_Byref)
9964 S += 'R';
9965 if (QT & Decl::OBJC_TQ_Oneway)
9966 S += 'V';
9967}
9968
9969TypedefDecl *ASTContext::getObjCIdDecl() const {
9970 if (!ObjCIdDecl) {
9971 QualType T = getObjCObjectType(BaseType: ObjCBuiltinIdTy, Protocols: {}, NumProtocols: {});
9972 T = getObjCObjectPointerType(ObjectT: T);
9973 ObjCIdDecl = buildImplicitTypedef(T, Name: "id");
9974 }
9975 return ObjCIdDecl;
9976}
9977
9978TypedefDecl *ASTContext::getObjCSelDecl() const {
9979 if (!ObjCSelDecl) {
9980 QualType T = getPointerType(T: ObjCBuiltinSelTy);
9981 ObjCSelDecl = buildImplicitTypedef(T, Name: "SEL");
9982 }
9983 return ObjCSelDecl;
9984}
9985
9986TypedefDecl *ASTContext::getObjCClassDecl() const {
9987 if (!ObjCClassDecl) {
9988 QualType T = getObjCObjectType(BaseType: ObjCBuiltinClassTy, Protocols: {}, NumProtocols: {});
9989 T = getObjCObjectPointerType(ObjectT: T);
9990 ObjCClassDecl = buildImplicitTypedef(T, Name: "Class");
9991 }
9992 return ObjCClassDecl;
9993}
9994
9995ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
9996 if (!ObjCProtocolClassDecl) {
9997 ObjCProtocolClassDecl
9998 = ObjCInterfaceDecl::Create(C: *this, DC: getTranslationUnitDecl(),
9999 atLoc: SourceLocation(),
10000 Id: &Idents.get(Name: "Protocol"),
10001 /*typeParamList=*/nullptr,
10002 /*PrevDecl=*/nullptr,
10003 ClassLoc: SourceLocation(), isInternal: true);
10004 }
10005
10006 return ObjCProtocolClassDecl;
10007}
10008
10009PointerAuthQualifier ASTContext::getObjCMemberSelTypePtrAuth() {
10010 if (!getLangOpts().PointerAuthObjcInterfaceSel)
10011 return PointerAuthQualifier();
10012 return PointerAuthQualifier::Create(
10013 Key: getLangOpts().PointerAuthObjcInterfaceSelKey,
10014 /*isAddressDiscriminated=*/IsAddressDiscriminated: true, ExtraDiscriminator: SelPointerConstantDiscriminator,
10015 AuthenticationMode: PointerAuthenticationMode::SignAndAuth,
10016 /*isIsaPointer=*/IsIsaPointer: false,
10017 /*authenticatesNullValues=*/AuthenticatesNullValues: false);
10018}
10019
10020//===----------------------------------------------------------------------===//
10021// __builtin_va_list Construction Functions
10022//===----------------------------------------------------------------------===//
10023
10024static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context,
10025 StringRef Name) {
10026 // typedef char* __builtin[_ms]_va_list;
10027 QualType T = Context->getPointerType(T: Context->CharTy);
10028 return Context->buildImplicitTypedef(T, Name);
10029}
10030
10031static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
10032 return CreateCharPtrNamedVaListDecl(Context, Name: "__builtin_ms_va_list");
10033}
10034
10035static TypedefDecl *CreateZOSVaListDecl(const ASTContext *Context) {
10036 // typedef char *__builtin_zos_va_list[2];
10037 llvm::APInt Size(Context->getTypeSize(T: Context->getSizeType()), 2);
10038 QualType T = Context->getPointerType(T: Context->CharTy);
10039 QualType ArrayType = Context->getConstantArrayType(
10040 EltTy: T, ArySizeIn: Size, SizeExpr: nullptr, ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
10041 return Context->buildImplicitTypedef(T: ArrayType, Name: "__builtin_zos_va_list");
10042}
10043
10044static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
10045 return CreateCharPtrNamedVaListDecl(Context, Name: "__builtin_va_list");
10046}
10047
10048static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
10049 // typedef void* __builtin_va_list;
10050 QualType T = Context->getPointerType(T: Context->VoidTy);
10051 return Context->buildImplicitTypedef(T, Name: "__builtin_va_list");
10052}
10053
10054static TypedefDecl *
10055CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
10056 // struct __va_list
10057 RecordDecl *VaListTagDecl = Context->buildImplicitRecord(Name: "__va_list");
10058 if (Context->getLangOpts().CPlusPlus) {
10059 // namespace std { struct __va_list {
10060 auto *NS = NamespaceDecl::Create(
10061 C&: const_cast<ASTContext &>(*Context), DC: Context->getTranslationUnitDecl(),
10062 /*Inline=*/false, StartLoc: SourceLocation(), IdLoc: SourceLocation(),
10063 Id: &Context->Idents.get(Name: "std"),
10064 /*PrevDecl=*/nullptr, /*Nested=*/false);
10065 NS->setImplicit();
10066 VaListTagDecl->setDeclContext(NS);
10067 }
10068
10069 VaListTagDecl->startDefinition();
10070
10071 const size_t NumFields = 5;
10072 QualType FieldTypes[NumFields];
10073 const char *FieldNames[NumFields];
10074
10075 // void *__stack;
10076 FieldTypes[0] = Context->getPointerType(T: Context->VoidTy);
10077 FieldNames[0] = "__stack";
10078
10079 // void *__gr_top;
10080 FieldTypes[1] = Context->getPointerType(T: Context->VoidTy);
10081 FieldNames[1] = "__gr_top";
10082
10083 // void *__vr_top;
10084 FieldTypes[2] = Context->getPointerType(T: Context->VoidTy);
10085 FieldNames[2] = "__vr_top";
10086
10087 // int __gr_offs;
10088 FieldTypes[3] = Context->IntTy;
10089 FieldNames[3] = "__gr_offs";
10090
10091 // int __vr_offs;
10092 FieldTypes[4] = Context->IntTy;
10093 FieldNames[4] = "__vr_offs";
10094
10095 // Create fields
10096 for (unsigned i = 0; i < NumFields; ++i) {
10097 FieldDecl *Field = FieldDecl::Create(C: const_cast<ASTContext &>(*Context),
10098 DC: VaListTagDecl,
10099 StartLoc: SourceLocation(),
10100 IdLoc: SourceLocation(),
10101 Id: &Context->Idents.get(Name: FieldNames[i]),
10102 T: FieldTypes[i], /*TInfo=*/nullptr,
10103 /*BitWidth=*/BW: nullptr,
10104 /*Mutable=*/false,
10105 InitStyle: ICIS_NoInit);
10106 Field->setAccess(AS_public);
10107 VaListTagDecl->addDecl(D: Field);
10108 }
10109 VaListTagDecl->completeDefinition();
10110 Context->VaListTagDecl = VaListTagDecl;
10111 CanQualType VaListTagType = Context->getCanonicalTagType(TD: VaListTagDecl);
10112
10113 // } __builtin_va_list;
10114 return Context->buildImplicitTypedef(T: VaListTagType, Name: "__builtin_va_list");
10115}
10116
10117static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
10118 // typedef struct __va_list_tag {
10119 RecordDecl *VaListTagDecl;
10120
10121 VaListTagDecl = Context->buildImplicitRecord(Name: "__va_list_tag");
10122 VaListTagDecl->startDefinition();
10123
10124 const size_t NumFields = 5;
10125 QualType FieldTypes[NumFields];
10126 const char *FieldNames[NumFields];
10127
10128 // unsigned char gpr;
10129 FieldTypes[0] = Context->UnsignedCharTy;
10130 FieldNames[0] = "gpr";
10131
10132 // unsigned char fpr;
10133 FieldTypes[1] = Context->UnsignedCharTy;
10134 FieldNames[1] = "fpr";
10135
10136 // unsigned short reserved;
10137 FieldTypes[2] = Context->UnsignedShortTy;
10138 FieldNames[2] = "reserved";
10139
10140 // void* overflow_arg_area;
10141 FieldTypes[3] = Context->getPointerType(T: Context->VoidTy);
10142 FieldNames[3] = "overflow_arg_area";
10143
10144 // void* reg_save_area;
10145 FieldTypes[4] = Context->getPointerType(T: Context->VoidTy);
10146 FieldNames[4] = "reg_save_area";
10147
10148 // Create fields
10149 for (unsigned i = 0; i < NumFields; ++i) {
10150 FieldDecl *Field = FieldDecl::Create(C: *Context, DC: VaListTagDecl,
10151 StartLoc: SourceLocation(),
10152 IdLoc: SourceLocation(),
10153 Id: &Context->Idents.get(Name: FieldNames[i]),
10154 T: FieldTypes[i], /*TInfo=*/nullptr,
10155 /*BitWidth=*/BW: nullptr,
10156 /*Mutable=*/false,
10157 InitStyle: ICIS_NoInit);
10158 Field->setAccess(AS_public);
10159 VaListTagDecl->addDecl(D: Field);
10160 }
10161 VaListTagDecl->completeDefinition();
10162 Context->VaListTagDecl = VaListTagDecl;
10163 CanQualType VaListTagType = Context->getCanonicalTagType(TD: VaListTagDecl);
10164
10165 // } __va_list_tag;
10166 TypedefDecl *VaListTagTypedefDecl =
10167 Context->buildImplicitTypedef(T: VaListTagType, Name: "__va_list_tag");
10168
10169 QualType VaListTagTypedefType =
10170 Context->getTypedefType(Keyword: ElaboratedTypeKeyword::None,
10171 /*Qualifier=*/std::nullopt, Decl: VaListTagTypedefDecl);
10172
10173 // typedef __va_list_tag __builtin_va_list[1];
10174 llvm::APInt Size(Context->getTypeSize(T: Context->getSizeType()), 1);
10175 QualType VaListTagArrayType = Context->getConstantArrayType(
10176 EltTy: VaListTagTypedefType, ArySizeIn: Size, SizeExpr: nullptr, ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
10177 return Context->buildImplicitTypedef(T: VaListTagArrayType, Name: "__builtin_va_list");
10178}
10179
10180static TypedefDecl *
10181CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
10182 // struct __va_list_tag {
10183 RecordDecl *VaListTagDecl;
10184 VaListTagDecl = Context->buildImplicitRecord(Name: "__va_list_tag");
10185 VaListTagDecl->startDefinition();
10186
10187 const size_t NumFields = 4;
10188 QualType FieldTypes[NumFields];
10189 const char *FieldNames[NumFields];
10190
10191 // unsigned gp_offset;
10192 FieldTypes[0] = Context->UnsignedIntTy;
10193 FieldNames[0] = "gp_offset";
10194
10195 // unsigned fp_offset;
10196 FieldTypes[1] = Context->UnsignedIntTy;
10197 FieldNames[1] = "fp_offset";
10198
10199 // void* overflow_arg_area;
10200 FieldTypes[2] = Context->getPointerType(T: Context->VoidTy);
10201 FieldNames[2] = "overflow_arg_area";
10202
10203 // void* reg_save_area;
10204 FieldTypes[3] = Context->getPointerType(T: Context->VoidTy);
10205 FieldNames[3] = "reg_save_area";
10206
10207 // Create fields
10208 for (unsigned i = 0; i < NumFields; ++i) {
10209 FieldDecl *Field = FieldDecl::Create(C: const_cast<ASTContext &>(*Context),
10210 DC: VaListTagDecl,
10211 StartLoc: SourceLocation(),
10212 IdLoc: SourceLocation(),
10213 Id: &Context->Idents.get(Name: FieldNames[i]),
10214 T: FieldTypes[i], /*TInfo=*/nullptr,
10215 /*BitWidth=*/BW: nullptr,
10216 /*Mutable=*/false,
10217 InitStyle: ICIS_NoInit);
10218 Field->setAccess(AS_public);
10219 VaListTagDecl->addDecl(D: Field);
10220 }
10221 VaListTagDecl->completeDefinition();
10222 Context->VaListTagDecl = VaListTagDecl;
10223 CanQualType VaListTagType = Context->getCanonicalTagType(TD: VaListTagDecl);
10224
10225 // };
10226
10227 // typedef struct __va_list_tag __builtin_va_list[1];
10228 llvm::APInt Size(Context->getTypeSize(T: Context->getSizeType()), 1);
10229 QualType VaListTagArrayType = Context->getConstantArrayType(
10230 EltTy: VaListTagType, ArySizeIn: Size, SizeExpr: nullptr, ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
10231 return Context->buildImplicitTypedef(T: VaListTagArrayType, Name: "__builtin_va_list");
10232}
10233
10234static TypedefDecl *
10235CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
10236 // struct __va_list
10237 RecordDecl *VaListDecl = Context->buildImplicitRecord(Name: "__va_list");
10238 if (Context->getLangOpts().CPlusPlus) {
10239 // namespace std { struct __va_list {
10240 NamespaceDecl *NS;
10241 NS = NamespaceDecl::Create(C&: const_cast<ASTContext &>(*Context),
10242 DC: Context->getTranslationUnitDecl(),
10243 /*Inline=*/false, StartLoc: SourceLocation(),
10244 IdLoc: SourceLocation(), Id: &Context->Idents.get(Name: "std"),
10245 /*PrevDecl=*/nullptr, /*Nested=*/false);
10246 NS->setImplicit();
10247 VaListDecl->setDeclContext(NS);
10248 }
10249
10250 VaListDecl->startDefinition();
10251
10252 // void * __ap;
10253 FieldDecl *Field = FieldDecl::Create(C: const_cast<ASTContext &>(*Context),
10254 DC: VaListDecl,
10255 StartLoc: SourceLocation(),
10256 IdLoc: SourceLocation(),
10257 Id: &Context->Idents.get(Name: "__ap"),
10258 T: Context->getPointerType(T: Context->VoidTy),
10259 /*TInfo=*/nullptr,
10260 /*BitWidth=*/BW: nullptr,
10261 /*Mutable=*/false,
10262 InitStyle: ICIS_NoInit);
10263 Field->setAccess(AS_public);
10264 VaListDecl->addDecl(D: Field);
10265
10266 // };
10267 VaListDecl->completeDefinition();
10268 Context->VaListTagDecl = VaListDecl;
10269
10270 // typedef struct __va_list __builtin_va_list;
10271 CanQualType T = Context->getCanonicalTagType(TD: VaListDecl);
10272 return Context->buildImplicitTypedef(T, Name: "__builtin_va_list");
10273}
10274
10275static TypedefDecl *
10276CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
10277 // struct __va_list_tag {
10278 RecordDecl *VaListTagDecl;
10279 VaListTagDecl = Context->buildImplicitRecord(Name: "__va_list_tag");
10280 VaListTagDecl->startDefinition();
10281
10282 const size_t NumFields = 4;
10283 QualType FieldTypes[NumFields];
10284 const char *FieldNames[NumFields];
10285
10286 // long __gpr;
10287 FieldTypes[0] = Context->LongTy;
10288 FieldNames[0] = "__gpr";
10289
10290 // long __fpr;
10291 FieldTypes[1] = Context->LongTy;
10292 FieldNames[1] = "__fpr";
10293
10294 // void *__overflow_arg_area;
10295 FieldTypes[2] = Context->getPointerType(T: Context->VoidTy);
10296 FieldNames[2] = "__overflow_arg_area";
10297
10298 // void *__reg_save_area;
10299 FieldTypes[3] = Context->getPointerType(T: Context->VoidTy);
10300 FieldNames[3] = "__reg_save_area";
10301
10302 // Create fields
10303 for (unsigned i = 0; i < NumFields; ++i) {
10304 FieldDecl *Field = FieldDecl::Create(C: const_cast<ASTContext &>(*Context),
10305 DC: VaListTagDecl,
10306 StartLoc: SourceLocation(),
10307 IdLoc: SourceLocation(),
10308 Id: &Context->Idents.get(Name: FieldNames[i]),
10309 T: FieldTypes[i], /*TInfo=*/nullptr,
10310 /*BitWidth=*/BW: nullptr,
10311 /*Mutable=*/false,
10312 InitStyle: ICIS_NoInit);
10313 Field->setAccess(AS_public);
10314 VaListTagDecl->addDecl(D: Field);
10315 }
10316 VaListTagDecl->completeDefinition();
10317 Context->VaListTagDecl = VaListTagDecl;
10318 CanQualType VaListTagType = Context->getCanonicalTagType(TD: VaListTagDecl);
10319
10320 // };
10321
10322 // typedef __va_list_tag __builtin_va_list[1];
10323 llvm::APInt Size(Context->getTypeSize(T: Context->getSizeType()), 1);
10324 QualType VaListTagArrayType = Context->getConstantArrayType(
10325 EltTy: VaListTagType, ArySizeIn: Size, SizeExpr: nullptr, ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
10326
10327 return Context->buildImplicitTypedef(T: VaListTagArrayType, Name: "__builtin_va_list");
10328}
10329
10330static TypedefDecl *CreateHexagonBuiltinVaListDecl(const ASTContext *Context) {
10331 // typedef struct __va_list_tag {
10332 RecordDecl *VaListTagDecl;
10333 VaListTagDecl = Context->buildImplicitRecord(Name: "__va_list_tag");
10334 VaListTagDecl->startDefinition();
10335
10336 const size_t NumFields = 3;
10337 QualType FieldTypes[NumFields];
10338 const char *FieldNames[NumFields];
10339
10340 // void *CurrentSavedRegisterArea;
10341 FieldTypes[0] = Context->getPointerType(T: Context->VoidTy);
10342 FieldNames[0] = "__current_saved_reg_area_pointer";
10343
10344 // void *SavedRegAreaEnd;
10345 FieldTypes[1] = Context->getPointerType(T: Context->VoidTy);
10346 FieldNames[1] = "__saved_reg_area_end_pointer";
10347
10348 // void *OverflowArea;
10349 FieldTypes[2] = Context->getPointerType(T: Context->VoidTy);
10350 FieldNames[2] = "__overflow_area_pointer";
10351
10352 // Create fields
10353 for (unsigned i = 0; i < NumFields; ++i) {
10354 FieldDecl *Field = FieldDecl::Create(
10355 C: const_cast<ASTContext &>(*Context), DC: VaListTagDecl, StartLoc: SourceLocation(),
10356 IdLoc: SourceLocation(), Id: &Context->Idents.get(Name: FieldNames[i]), T: FieldTypes[i],
10357 /*TInfo=*/nullptr,
10358 /*BitWidth=*/BW: nullptr,
10359 /*Mutable=*/false, InitStyle: ICIS_NoInit);
10360 Field->setAccess(AS_public);
10361 VaListTagDecl->addDecl(D: Field);
10362 }
10363 VaListTagDecl->completeDefinition();
10364 Context->VaListTagDecl = VaListTagDecl;
10365 CanQualType VaListTagType = Context->getCanonicalTagType(TD: VaListTagDecl);
10366
10367 // } __va_list_tag;
10368 TypedefDecl *VaListTagTypedefDecl =
10369 Context->buildImplicitTypedef(T: VaListTagType, Name: "__va_list_tag");
10370
10371 QualType VaListTagTypedefType =
10372 Context->getTypedefType(Keyword: ElaboratedTypeKeyword::None,
10373 /*Qualifier=*/std::nullopt, Decl: VaListTagTypedefDecl);
10374
10375 // typedef __va_list_tag __builtin_va_list[1];
10376 llvm::APInt Size(Context->getTypeSize(T: Context->getSizeType()), 1);
10377 QualType VaListTagArrayType = Context->getConstantArrayType(
10378 EltTy: VaListTagTypedefType, ArySizeIn: Size, SizeExpr: nullptr, ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
10379
10380 return Context->buildImplicitTypedef(T: VaListTagArrayType, Name: "__builtin_va_list");
10381}
10382
10383static TypedefDecl *
10384CreateXtensaABIBuiltinVaListDecl(const ASTContext *Context) {
10385 // typedef struct __va_list_tag {
10386 RecordDecl *VaListTagDecl = Context->buildImplicitRecord(Name: "__va_list_tag");
10387
10388 VaListTagDecl->startDefinition();
10389
10390 // int* __va_stk;
10391 // int* __va_reg;
10392 // int __va_ndx;
10393 constexpr size_t NumFields = 3;
10394 QualType FieldTypes[NumFields] = {Context->getPointerType(T: Context->IntTy),
10395 Context->getPointerType(T: Context->IntTy),
10396 Context->IntTy};
10397 const char *FieldNames[NumFields] = {"__va_stk", "__va_reg", "__va_ndx"};
10398
10399 // Create fields
10400 for (unsigned i = 0; i < NumFields; ++i) {
10401 FieldDecl *Field = FieldDecl::Create(
10402 C: *Context, DC: VaListTagDecl, StartLoc: SourceLocation(), IdLoc: SourceLocation(),
10403 Id: &Context->Idents.get(Name: FieldNames[i]), T: FieldTypes[i], /*TInfo=*/nullptr,
10404 /*BitWidth=*/BW: nullptr,
10405 /*Mutable=*/false, InitStyle: ICIS_NoInit);
10406 Field->setAccess(AS_public);
10407 VaListTagDecl->addDecl(D: Field);
10408 }
10409 VaListTagDecl->completeDefinition();
10410 Context->VaListTagDecl = VaListTagDecl;
10411 CanQualType VaListTagType = Context->getCanonicalTagType(TD: VaListTagDecl);
10412
10413 // } __va_list_tag;
10414 TypedefDecl *VaListTagTypedefDecl =
10415 Context->buildImplicitTypedef(T: VaListTagType, Name: "__builtin_va_list");
10416
10417 return VaListTagTypedefDecl;
10418}
10419
10420static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
10421 TargetInfo::BuiltinVaListKind Kind) {
10422 switch (Kind) {
10423 case TargetInfo::CharPtrBuiltinVaList:
10424 return CreateCharPtrBuiltinVaListDecl(Context);
10425 case TargetInfo::VoidPtrBuiltinVaList:
10426 return CreateVoidPtrBuiltinVaListDecl(Context);
10427 case TargetInfo::AArch64ABIBuiltinVaList:
10428 return CreateAArch64ABIBuiltinVaListDecl(Context);
10429 case TargetInfo::PowerABIBuiltinVaList:
10430 return CreatePowerABIBuiltinVaListDecl(Context);
10431 case TargetInfo::X86_64ABIBuiltinVaList:
10432 return CreateX86_64ABIBuiltinVaListDecl(Context);
10433 case TargetInfo::AAPCSABIBuiltinVaList:
10434 return CreateAAPCSABIBuiltinVaListDecl(Context);
10435 case TargetInfo::SystemZBuiltinVaList:
10436 return CreateSystemZBuiltinVaListDecl(Context);
10437 case TargetInfo::HexagonBuiltinVaList:
10438 return CreateHexagonBuiltinVaListDecl(Context);
10439 case TargetInfo::XtensaABIBuiltinVaList:
10440 return CreateXtensaABIBuiltinVaListDecl(Context);
10441 }
10442
10443 llvm_unreachable("Unhandled __builtin_va_list type kind");
10444}
10445
10446TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
10447 if (!BuiltinVaListDecl) {
10448 BuiltinVaListDecl = CreateVaListDecl(Context: this, Kind: Target->getBuiltinVaListKind());
10449 assert(BuiltinVaListDecl->isImplicit());
10450 }
10451
10452 return BuiltinVaListDecl;
10453}
10454
10455Decl *ASTContext::getVaListTagDecl() const {
10456 // Force the creation of VaListTagDecl by building the __builtin_va_list
10457 // declaration.
10458 if (!VaListTagDecl)
10459 (void)getBuiltinVaListDecl();
10460
10461 return VaListTagDecl;
10462}
10463
10464TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const {
10465 if (!BuiltinMSVaListDecl)
10466 BuiltinMSVaListDecl = CreateMSVaListDecl(Context: this);
10467
10468 return BuiltinMSVaListDecl;
10469}
10470
10471TypedefDecl *ASTContext::getBuiltinZOSVaListDecl() const {
10472 if (!BuiltinZOSVaListDecl)
10473 BuiltinZOSVaListDecl = CreateZOSVaListDecl(Context: this);
10474
10475 return BuiltinZOSVaListDecl;
10476}
10477
10478bool ASTContext::canBuiltinBeRedeclared(const FunctionDecl *FD) const {
10479 // Allow redecl custom type checking builtin for HLSL.
10480 if (LangOpts.HLSL && FD->getBuiltinID() != Builtin::NotBuiltin &&
10481 BuiltinInfo.hasCustomTypechecking(ID: FD->getBuiltinID()))
10482 return true;
10483 // Allow redecl custom type checking builtin for SPIR-V.
10484 if (getTargetInfo().getTriple().isSPIROrSPIRV() &&
10485 BuiltinInfo.isTSBuiltin(ID: FD->getBuiltinID()) &&
10486 BuiltinInfo.hasCustomTypechecking(ID: FD->getBuiltinID()))
10487 return true;
10488 return BuiltinInfo.canBeRedeclared(ID: FD->getBuiltinID());
10489}
10490
10491void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
10492 assert(ObjCConstantStringType.isNull() &&
10493 "'NSConstantString' type already set!");
10494
10495 ObjCConstantStringType = getObjCInterfaceType(Decl);
10496}
10497
10498/// Retrieve the template name that corresponds to a non-empty
10499/// lookup.
10500TemplateName
10501ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
10502 UnresolvedSetIterator End) const {
10503 unsigned size = End - Begin;
10504 assert(size > 1 && "set is not overloaded!");
10505
10506 void *memory = Allocate(Size: sizeof(OverloadedTemplateStorage) +
10507 size * sizeof(FunctionTemplateDecl*));
10508 auto *OT = new (memory) OverloadedTemplateStorage(size);
10509
10510 NamedDecl **Storage = OT->getStorage();
10511 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
10512 NamedDecl *D = *I;
10513 assert(isa<FunctionTemplateDecl>(D) ||
10514 isa<UnresolvedUsingValueDecl>(D) ||
10515 (isa<UsingShadowDecl>(D) &&
10516 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
10517 *Storage++ = D;
10518 }
10519
10520 return TemplateName(OT);
10521}
10522
10523/// Retrieve a template name representing an unqualified-id that has been
10524/// assumed to name a template for ADL purposes.
10525TemplateName ASTContext::getAssumedTemplateName(DeclarationName Name) const {
10526 auto *OT = new (*this) AssumedTemplateStorage(Name);
10527 return TemplateName(OT);
10528}
10529
10530/// Retrieve the template name that represents a qualified
10531/// template name such as \c std::vector.
10532TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier Qualifier,
10533 bool TemplateKeyword,
10534 TemplateName Template) const {
10535 assert(Template.getKind() == TemplateName::Template ||
10536 Template.getKind() == TemplateName::UsingTemplate);
10537
10538 if (Template.getAsTemplateDecl()->getKind() == Decl::TemplateTemplateParm) {
10539 assert(!Qualifier && "unexpected qualified template template parameter");
10540 assert(TemplateKeyword == false);
10541 return Template;
10542 }
10543
10544 // FIXME: Canonicalization?
10545 llvm::FoldingSetNodeID ID;
10546 QualifiedTemplateName::Profile(ID, NNS: Qualifier, TemplateKeyword, TN: Template);
10547
10548 llvm::FoldingSetInsertToken Token;
10549 QualifiedTemplateName *QTN = QualifiedTemplateNames.lookup(ID, Token);
10550 if (!QTN) {
10551 QTN = new (*this, alignof(QualifiedTemplateName))
10552 QualifiedTemplateName(Qualifier, TemplateKeyword, Template);
10553 QualifiedTemplateNames.insert(N: QTN, Token);
10554 }
10555
10556 return TemplateName(QTN);
10557}
10558
10559/// Retrieve the template name that represents a dependent
10560/// template name such as \c MetaFun::template operator+.
10561TemplateName
10562ASTContext::getDependentTemplateName(const DependentTemplateStorage &S) const {
10563 llvm::FoldingSetNodeID ID;
10564 S.Profile(ID);
10565
10566 llvm::FoldingSetInsertToken Token;
10567 if (DependentTemplateName *QTN = DependentTemplateNames.lookup(ID, Token))
10568 return TemplateName(QTN);
10569
10570 DependentTemplateName *QTN =
10571 new (*this, alignof(DependentTemplateName)) DependentTemplateName(S);
10572 DependentTemplateNames.insert(N: QTN, Token);
10573 return TemplateName(QTN);
10574}
10575
10576TemplateName ASTContext::getSubstTemplateTemplateParm(TemplateName Replacement,
10577 Decl *AssociatedDecl,
10578 unsigned Index,
10579 UnsignedOrNone PackIndex,
10580 bool Final) const {
10581 llvm::FoldingSetNodeID ID;
10582 SubstTemplateTemplateParmStorage::Profile(ID, Replacement, AssociatedDecl,
10583 Index, PackIndex, Final);
10584
10585 llvm::FoldingSetInsertToken Token;
10586 SubstTemplateTemplateParmStorage *subst =
10587 SubstTemplateTemplateParms.lookup(ID, Token);
10588
10589 if (!subst) {
10590 subst = new (*this) SubstTemplateTemplateParmStorage(
10591 Replacement, AssociatedDecl, Index, PackIndex, Final);
10592 SubstTemplateTemplateParms.insert(N: subst, Token);
10593 }
10594
10595 return TemplateName(subst);
10596}
10597
10598TemplateName
10599ASTContext::getSubstTemplateTemplateParmPack(const TemplateArgument &ArgPack,
10600 Decl *AssociatedDecl,
10601 unsigned Index, bool Final) const {
10602 auto &Self = const_cast<ASTContext &>(*this);
10603 llvm::FoldingSetNodeID ID;
10604 SubstTemplateTemplateParmPackStorage::Profile(ID, Context&: Self, ArgPack,
10605 AssociatedDecl, Index, Final);
10606
10607 llvm::FoldingSetInsertToken Token;
10608 SubstTemplateTemplateParmPackStorage *Subst =
10609 SubstTemplateTemplateParmPacks.lookup(ID, Token);
10610
10611 if (!Subst) {
10612 Subst = new (*this) SubstTemplateTemplateParmPackStorage(
10613 ArgPack.pack_elements(), AssociatedDecl, Index, Final);
10614 SubstTemplateTemplateParmPacks.insert(N: Subst, Token);
10615 }
10616
10617 return TemplateName(Subst);
10618}
10619
10620/// Retrieve the template name that represents a template name
10621/// deduced from a specialization.
10622TemplateName
10623ASTContext::getDeducedTemplateName(TemplateName Underlying,
10624 DefaultArguments DefaultArgs) const {
10625 if (!DefaultArgs)
10626 return Underlying;
10627
10628 llvm::FoldingSetNodeID ID;
10629 DeducedTemplateStorage::Profile(ID, Context: *this, Underlying, DefArgs: DefaultArgs);
10630
10631 llvm::FoldingSetInsertToken Token;
10632 DeducedTemplateStorage *DTS = DeducedTemplates.lookup(ID, Token);
10633 if (!DTS) {
10634 void *Mem = Allocate(Size: sizeof(DeducedTemplateStorage) +
10635 sizeof(TemplateArgument) * DefaultArgs.Args.size(),
10636 Align: alignof(DeducedTemplateStorage));
10637 DTS = new (Mem) DeducedTemplateStorage(Underlying, DefaultArgs);
10638 DeducedTemplates.insert(N: DTS, Token);
10639 }
10640 return TemplateName(DTS);
10641}
10642
10643TemplateName ASTContext::getPackIndexingTemplateName(
10644 TemplateName Pattern, Expr *IndexExpr, bool FullySubstituted,
10645 ArrayRef<TemplateName> Expansions) const {
10646 auto &Self = const_cast<ASTContext &>(*this);
10647 llvm::FoldingSetNodeID ID;
10648 PackIndexingTemplateStorage::Profile(ID, Context: Self, Pattern, IndexExpr,
10649 FullySubstituted, Expansions);
10650
10651 llvm::FoldingSetInsertToken Token;
10652 PackIndexingTemplateStorage *PI = PackIndexingTemplates.lookup(ID, Token);
10653 if (!PI) {
10654 void *Mem =
10655 Allocate(Size: PackIndexingTemplateStorage::totalSizeToAlloc<TemplateName>(
10656 Counts: Expansions.size()),
10657 Align: alignof(PackIndexingTemplateStorage));
10658 PI = new (Mem) PackIndexingTemplateStorage(Pattern, IndexExpr,
10659 FullySubstituted, Expansions);
10660 PackIndexingTemplates.insert(N: PI, Token);
10661 }
10662 return TemplateName(PI);
10663}
10664
10665/// getFromTargetType - Given one of the integer types provided by
10666/// TargetInfo, produce the corresponding type. The unsigned @p Type
10667/// is actually a value of type @c TargetInfo::IntType.
10668CanQualType ASTContext::getFromTargetType(unsigned Type) const {
10669 switch (Type) {
10670 case TargetInfo::NoInt: return {};
10671 case TargetInfo::SignedChar: return SignedCharTy;
10672 case TargetInfo::UnsignedChar: return UnsignedCharTy;
10673 case TargetInfo::SignedShort: return ShortTy;
10674 case TargetInfo::UnsignedShort: return UnsignedShortTy;
10675 case TargetInfo::SignedInt: return IntTy;
10676 case TargetInfo::UnsignedInt: return UnsignedIntTy;
10677 case TargetInfo::SignedLong: return LongTy;
10678 case TargetInfo::UnsignedLong: return UnsignedLongTy;
10679 case TargetInfo::SignedLongLong: return LongLongTy;
10680 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
10681 }
10682
10683 llvm_unreachable("Unhandled TargetInfo::IntType value");
10684}
10685
10686//===----------------------------------------------------------------------===//
10687// Type Predicates.
10688//===----------------------------------------------------------------------===//
10689
10690/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
10691/// garbage collection attribute.
10692///
10693Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
10694 if (getLangOpts().getGC() == LangOptions::NonGC)
10695 return Qualifiers::GCNone;
10696
10697 assert(getLangOpts().ObjC);
10698 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
10699
10700 // Default behaviour under objective-C's gc is for ObjC pointers
10701 // (or pointers to them) be treated as though they were declared
10702 // as __strong.
10703 if (GCAttrs == Qualifiers::GCNone) {
10704 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
10705 return Qualifiers::Strong;
10706 else if (Ty->isPointerType())
10707 return getObjCGCAttrKind(Ty: Ty->castAs<PointerType>()->getPointeeType());
10708 } else {
10709 // It's not valid to set GC attributes on anything that isn't a
10710 // pointer.
10711#ifndef NDEBUG
10712 QualType CT = Ty->getCanonicalTypeInternal();
10713 while (const auto *AT = dyn_cast<ArrayType>(CT))
10714 CT = AT->getElementType();
10715 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
10716#endif
10717 }
10718 return GCAttrs;
10719}
10720
10721//===----------------------------------------------------------------------===//
10722// Type Compatibility Testing
10723//===----------------------------------------------------------------------===//
10724
10725/// areCompatVectorTypes - Return true if the two specified vector types are
10726/// compatible.
10727static bool areCompatVectorTypes(const VectorType *LHS,
10728 const VectorType *RHS) {
10729 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
10730 return LHS->getElementType() == RHS->getElementType() &&
10731 LHS->getNumElements() == RHS->getNumElements();
10732}
10733
10734/// areCompatMatrixTypes - Return true if the two specified matrix types are
10735/// compatible.
10736static bool areCompatMatrixTypes(const ConstantMatrixType *LHS,
10737 const ConstantMatrixType *RHS) {
10738 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
10739 return LHS->getElementType() == RHS->getElementType() &&
10740 LHS->getNumRows() == RHS->getNumRows() &&
10741 LHS->getNumColumns() == RHS->getNumColumns();
10742}
10743
10744bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
10745 QualType SecondVec) {
10746 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
10747 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
10748
10749 if (hasSameUnqualifiedType(T1: FirstVec, T2: SecondVec))
10750 return true;
10751
10752 // Treat Neon vector types and most AltiVec vector types as if they are the
10753 // equivalent GCC vector types.
10754 const auto *First = FirstVec->castAs<VectorType>();
10755 const auto *Second = SecondVec->castAs<VectorType>();
10756 if (First->getNumElements() == Second->getNumElements() &&
10757 hasSameType(T1: First->getElementType(), T2: Second->getElementType()) &&
10758 First->getVectorKind() != VectorKind::AltiVecPixel &&
10759 First->getVectorKind() != VectorKind::AltiVecBool &&
10760 Second->getVectorKind() != VectorKind::AltiVecPixel &&
10761 Second->getVectorKind() != VectorKind::AltiVecBool &&
10762 First->getVectorKind() != VectorKind::SveFixedLengthData &&
10763 First->getVectorKind() != VectorKind::SveFixedLengthPredicate &&
10764 Second->getVectorKind() != VectorKind::SveFixedLengthData &&
10765 Second->getVectorKind() != VectorKind::SveFixedLengthPredicate &&
10766 First->getVectorKind() != VectorKind::RVVFixedLengthData &&
10767 Second->getVectorKind() != VectorKind::RVVFixedLengthData &&
10768 First->getVectorKind() != VectorKind::RVVFixedLengthMask &&
10769 Second->getVectorKind() != VectorKind::RVVFixedLengthMask &&
10770 First->getVectorKind() != VectorKind::RVVFixedLengthMask_1 &&
10771 Second->getVectorKind() != VectorKind::RVVFixedLengthMask_1 &&
10772 First->getVectorKind() != VectorKind::RVVFixedLengthMask_2 &&
10773 Second->getVectorKind() != VectorKind::RVVFixedLengthMask_2 &&
10774 First->getVectorKind() != VectorKind::RVVFixedLengthMask_4 &&
10775 Second->getVectorKind() != VectorKind::RVVFixedLengthMask_4)
10776 return true;
10777
10778 // In OpenCL, treat half and _Float16 vector types as compatible.
10779 if (getLangOpts().OpenCL &&
10780 First->getNumElements() == Second->getNumElements()) {
10781 QualType FirstElt = First->getElementType();
10782 QualType SecondElt = Second->getElementType();
10783
10784 if ((FirstElt->isFloat16Type() && SecondElt->isHalfType()) ||
10785 (FirstElt->isHalfType() && SecondElt->isFloat16Type())) {
10786 if (First->getVectorKind() != VectorKind::AltiVecPixel &&
10787 First->getVectorKind() != VectorKind::AltiVecBool &&
10788 Second->getVectorKind() != VectorKind::AltiVecPixel &&
10789 Second->getVectorKind() != VectorKind::AltiVecBool)
10790 return true;
10791 }
10792 }
10793 return false;
10794}
10795
10796bool ASTContext::areCompatibleOverflowBehaviorTypes(QualType LHS,
10797 QualType RHS) {
10798 auto Result = checkOBTAssignmentCompatibility(LHS, RHS);
10799 return Result != OBTAssignResult::IncompatibleKinds;
10800}
10801
10802ASTContext::OBTAssignResult
10803ASTContext::checkOBTAssignmentCompatibility(QualType LHS, QualType RHS) {
10804 const auto *LHSOBT = LHS->getAs<OverflowBehaviorType>();
10805 const auto *RHSOBT = RHS->getAs<OverflowBehaviorType>();
10806
10807 if (!LHSOBT && !RHSOBT)
10808 return OBTAssignResult::Compatible;
10809
10810 if (LHSOBT && RHSOBT) {
10811 if (LHSOBT->getBehaviorKind() != RHSOBT->getBehaviorKind())
10812 return OBTAssignResult::IncompatibleKinds;
10813 return OBTAssignResult::Compatible;
10814 }
10815
10816 QualType LHSUnderlying = LHSOBT ? LHSOBT->desugar() : LHS;
10817 QualType RHSUnderlying = RHSOBT ? RHSOBT->desugar() : RHS;
10818
10819 if (RHSOBT && !LHSOBT) {
10820 if (LHSUnderlying->isIntegerType() && RHSUnderlying->isIntegerType())
10821 return OBTAssignResult::Discards;
10822 }
10823
10824 return OBTAssignResult::NotApplicable;
10825}
10826
10827/// getRVVTypeSize - Return RVV vector register size.
10828static uint64_t getRVVTypeSize(ASTContext &Context, const BuiltinType *Ty) {
10829 assert(Ty->isRVVVLSBuiltinType() && "Invalid RVV Type");
10830 auto VScale = Context.getTargetInfo().getVScaleRange(
10831 LangOpts: Context.getLangOpts(), Mode: TargetInfo::ArmStreamingKind::NotStreaming);
10832 if (!VScale)
10833 return 0;
10834
10835 ASTContext::BuiltinVectorTypeInfo Info = Context.getBuiltinVectorTypeInfo(Ty);
10836
10837 uint64_t EltSize = Context.getTypeSize(T: Info.ElementType);
10838 if (Info.ElementType == Context.BoolTy)
10839 EltSize = 1;
10840
10841 uint64_t MinElts = Info.EC.getKnownMinValue();
10842 return VScale->first * MinElts * EltSize;
10843}
10844
10845bool ASTContext::areCompatibleRVVTypes(QualType FirstType,
10846 QualType SecondType) {
10847 assert(
10848 ((FirstType->isRVVSizelessBuiltinType() && SecondType->isVectorType()) ||
10849 (FirstType->isVectorType() && SecondType->isRVVSizelessBuiltinType())) &&
10850 "Expected RVV builtin type and vector type!");
10851
10852 auto IsValidCast = [this](QualType FirstType, QualType SecondType) {
10853 if (const auto *BT = FirstType->getAs<BuiltinType>()) {
10854 if (const auto *VT = SecondType->getAs<VectorType>()) {
10855 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask) {
10856 BuiltinVectorTypeInfo Info = getBuiltinVectorTypeInfo(Ty: BT);
10857 return FirstType->isRVVVLSBuiltinType() &&
10858 Info.ElementType == BoolTy &&
10859 getTypeSize(T: SecondType) == ((getRVVTypeSize(Context&: *this, Ty: BT)));
10860 }
10861 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_1) {
10862 BuiltinVectorTypeInfo Info = getBuiltinVectorTypeInfo(Ty: BT);
10863 return FirstType->isRVVVLSBuiltinType() &&
10864 Info.ElementType == BoolTy &&
10865 getTypeSize(T: SecondType) == ((getRVVTypeSize(Context&: *this, Ty: BT) * 8));
10866 }
10867 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_2) {
10868 BuiltinVectorTypeInfo Info = getBuiltinVectorTypeInfo(Ty: BT);
10869 return FirstType->isRVVVLSBuiltinType() &&
10870 Info.ElementType == BoolTy &&
10871 getTypeSize(T: SecondType) == ((getRVVTypeSize(Context&: *this, Ty: BT)) * 4);
10872 }
10873 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_4) {
10874 BuiltinVectorTypeInfo Info = getBuiltinVectorTypeInfo(Ty: BT);
10875 return FirstType->isRVVVLSBuiltinType() &&
10876 Info.ElementType == BoolTy &&
10877 getTypeSize(T: SecondType) == ((getRVVTypeSize(Context&: *this, Ty: BT)) * 2);
10878 }
10879 if (VT->getVectorKind() == VectorKind::RVVFixedLengthData ||
10880 VT->getVectorKind() == VectorKind::Generic)
10881 return FirstType->isRVVVLSBuiltinType() &&
10882 getTypeSize(T: SecondType) == getRVVTypeSize(Context&: *this, Ty: BT) &&
10883 hasSameType(T1: VT->getElementType(),
10884 T2: getBuiltinVectorTypeInfo(Ty: BT).ElementType);
10885 }
10886 }
10887 return false;
10888 };
10889
10890 return IsValidCast(FirstType, SecondType) ||
10891 IsValidCast(SecondType, FirstType);
10892}
10893
10894bool ASTContext::areLaxCompatibleRVVTypes(QualType FirstType,
10895 QualType SecondType) {
10896 assert(
10897 ((FirstType->isRVVSizelessBuiltinType() && SecondType->isVectorType()) ||
10898 (FirstType->isVectorType() && SecondType->isRVVSizelessBuiltinType())) &&
10899 "Expected RVV builtin type and vector type!");
10900
10901 auto IsLaxCompatible = [this](QualType FirstType, QualType SecondType) {
10902 const auto *BT = FirstType->getAs<BuiltinType>();
10903 if (!BT)
10904 return false;
10905
10906 if (!BT->isRVVVLSBuiltinType())
10907 return false;
10908
10909 const auto *VecTy = SecondType->getAs<VectorType>();
10910 if (VecTy && VecTy->getVectorKind() == VectorKind::Generic) {
10911 const LangOptions::LaxVectorConversionKind LVCKind =
10912 getLangOpts().getLaxVectorConversions();
10913
10914 // If __riscv_v_fixed_vlen != N do not allow vector lax conversion.
10915 if (getTypeSize(T: SecondType) != getRVVTypeSize(Context&: *this, Ty: BT))
10916 return false;
10917
10918 // If -flax-vector-conversions=all is specified, the types are
10919 // certainly compatible.
10920 if (LVCKind == LangOptions::LaxVectorConversionKind::All)
10921 return true;
10922
10923 // If -flax-vector-conversions=integer is specified, the types are
10924 // compatible if the elements are integer types.
10925 if (LVCKind == LangOptions::LaxVectorConversionKind::Integer)
10926 return VecTy->getElementType().getCanonicalType()->isIntegerType() &&
10927 FirstType->getRVVEltType(Ctx: *this)->isIntegerType();
10928 }
10929
10930 return false;
10931 };
10932
10933 return IsLaxCompatible(FirstType, SecondType) ||
10934 IsLaxCompatible(SecondType, FirstType);
10935}
10936
10937bool ASTContext::hasDirectOwnershipQualifier(QualType Ty) const {
10938 while (true) {
10939 // __strong id
10940 if (const AttributedType *Attr = dyn_cast<AttributedType>(Val&: Ty)) {
10941 if (Attr->getAttrKind() == attr::ObjCOwnership)
10942 return true;
10943
10944 Ty = Attr->getModifiedType();
10945
10946 // X *__strong (...)
10947 } else if (const ParenType *Paren = dyn_cast<ParenType>(Val&: Ty)) {
10948 Ty = Paren->getInnerType();
10949
10950 // We do not want to look through typedefs, typeof(expr),
10951 // typeof(type), or any other way that the type is somehow
10952 // abstracted.
10953 } else {
10954 return false;
10955 }
10956 }
10957}
10958
10959//===----------------------------------------------------------------------===//
10960// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
10961//===----------------------------------------------------------------------===//
10962
10963/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
10964/// inheritance hierarchy of 'rProto'.
10965bool
10966ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
10967 ObjCProtocolDecl *rProto) const {
10968 if (declaresSameEntity(D1: lProto, D2: rProto))
10969 return true;
10970 for (auto *PI : rProto->protocols())
10971 if (ProtocolCompatibleWithProtocol(lProto, rProto: PI))
10972 return true;
10973 return false;
10974}
10975
10976/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
10977/// Class<pr1, ...>.
10978bool ASTContext::ObjCQualifiedClassTypesAreCompatible(
10979 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs) {
10980 for (auto *lhsProto : lhs->quals()) {
10981 bool match = false;
10982 for (auto *rhsProto : rhs->quals()) {
10983 if (ProtocolCompatibleWithProtocol(lProto: lhsProto, rProto: rhsProto)) {
10984 match = true;
10985 break;
10986 }
10987 }
10988 if (!match)
10989 return false;
10990 }
10991 return true;
10992}
10993
10994/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
10995/// ObjCQualifiedIDType.
10996bool ASTContext::ObjCQualifiedIdTypesAreCompatible(
10997 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs,
10998 bool compare) {
10999 // Allow id<P..> and an 'id' in all cases.
11000 if (lhs->isObjCIdType() || rhs->isObjCIdType())
11001 return true;
11002
11003 // Don't allow id<P..> to convert to Class or Class<P..> in either direction.
11004 if (lhs->isObjCClassType() || lhs->isObjCQualifiedClassType() ||
11005 rhs->isObjCClassType() || rhs->isObjCQualifiedClassType())
11006 return false;
11007
11008 if (lhs->isObjCQualifiedIdType()) {
11009 if (rhs->qual_empty()) {
11010 // If the RHS is a unqualified interface pointer "NSString*",
11011 // make sure we check the class hierarchy.
11012 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
11013 for (auto *I : lhs->quals()) {
11014 // when comparing an id<P> on lhs with a static type on rhs,
11015 // see if static class implements all of id's protocols, directly or
11016 // through its super class and categories.
11017 if (!rhsID->ClassImplementsProtocol(lProto: I, lookupCategory: true))
11018 return false;
11019 }
11020 }
11021 // If there are no qualifiers and no interface, we have an 'id'.
11022 return true;
11023 }
11024 // Both the right and left sides have qualifiers.
11025 for (auto *lhsProto : lhs->quals()) {
11026 bool match = false;
11027
11028 // when comparing an id<P> on lhs with a static type on rhs,
11029 // see if static class implements all of id's protocols, directly or
11030 // through its super class and categories.
11031 for (auto *rhsProto : rhs->quals()) {
11032 if (ProtocolCompatibleWithProtocol(lProto: lhsProto, rProto: rhsProto) ||
11033 (compare && ProtocolCompatibleWithProtocol(lProto: rhsProto, rProto: lhsProto))) {
11034 match = true;
11035 break;
11036 }
11037 }
11038 // If the RHS is a qualified interface pointer "NSString<P>*",
11039 // make sure we check the class hierarchy.
11040 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
11041 for (auto *I : lhs->quals()) {
11042 // when comparing an id<P> on lhs with a static type on rhs,
11043 // see if static class implements all of id's protocols, directly or
11044 // through its super class and categories.
11045 if (rhsID->ClassImplementsProtocol(lProto: I, lookupCategory: true)) {
11046 match = true;
11047 break;
11048 }
11049 }
11050 }
11051 if (!match)
11052 return false;
11053 }
11054
11055 return true;
11056 }
11057
11058 assert(rhs->isObjCQualifiedIdType() && "One of the LHS/RHS should be id<x>");
11059
11060 if (lhs->getInterfaceType()) {
11061 // If both the right and left sides have qualifiers.
11062 for (auto *lhsProto : lhs->quals()) {
11063 bool match = false;
11064
11065 // when comparing an id<P> on rhs with a static type on lhs,
11066 // see if static class implements all of id's protocols, directly or
11067 // through its super class and categories.
11068 // First, lhs protocols in the qualifier list must be found, direct
11069 // or indirect in rhs's qualifier list or it is a mismatch.
11070 for (auto *rhsProto : rhs->quals()) {
11071 if (ProtocolCompatibleWithProtocol(lProto: lhsProto, rProto: rhsProto) ||
11072 (compare && ProtocolCompatibleWithProtocol(lProto: rhsProto, rProto: lhsProto))) {
11073 match = true;
11074 break;
11075 }
11076 }
11077 if (!match)
11078 return false;
11079 }
11080
11081 // Static class's protocols, or its super class or category protocols
11082 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
11083 if (ObjCInterfaceDecl *lhsID = lhs->getInterfaceDecl()) {
11084 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
11085 CollectInheritedProtocols(CDecl: lhsID, Protocols&: LHSInheritedProtocols);
11086 // This is rather dubious but matches gcc's behavior. If lhs has
11087 // no type qualifier and its class has no static protocol(s)
11088 // assume that it is mismatch.
11089 if (LHSInheritedProtocols.empty() && lhs->qual_empty())
11090 return false;
11091 for (auto *lhsProto : LHSInheritedProtocols) {
11092 bool match = false;
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 return true;
11105 }
11106 return false;
11107}
11108
11109/// canAssignObjCInterfaces - Return true if the two interface types are
11110/// compatible for assignment from RHS to LHS. This handles validation of any
11111/// protocol qualifiers on the LHS or RHS.
11112bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
11113 const ObjCObjectPointerType *RHSOPT) {
11114 const ObjCObjectType* LHS = LHSOPT->getObjectType();
11115 const ObjCObjectType* RHS = RHSOPT->getObjectType();
11116
11117 // If either type represents the built-in 'id' type, return true.
11118 if (LHS->isObjCUnqualifiedId() || RHS->isObjCUnqualifiedId())
11119 return true;
11120
11121 // Function object that propagates a successful result or handles
11122 // __kindof types.
11123 auto finish = [&](bool succeeded) -> bool {
11124 if (succeeded)
11125 return true;
11126
11127 if (!RHS->isKindOfType())
11128 return false;
11129
11130 // Strip off __kindof and protocol qualifiers, then check whether
11131 // we can assign the other way.
11132 return canAssignObjCInterfaces(LHSOPT: RHSOPT->stripObjCKindOfTypeAndQuals(ctx: *this),
11133 RHSOPT: LHSOPT->stripObjCKindOfTypeAndQuals(ctx: *this));
11134 };
11135
11136 // Casts from or to id<P> are allowed when the other side has compatible
11137 // protocols.
11138 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
11139 return finish(ObjCQualifiedIdTypesAreCompatible(lhs: LHSOPT, rhs: RHSOPT, compare: false));
11140 }
11141
11142 // Verify protocol compatibility for casts from Class<P1> to Class<P2>.
11143 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
11144 return finish(ObjCQualifiedClassTypesAreCompatible(lhs: LHSOPT, rhs: RHSOPT));
11145 }
11146
11147 // Casts from Class to Class<Foo>, or vice-versa, are allowed.
11148 if (LHS->isObjCClass() && RHS->isObjCClass()) {
11149 return true;
11150 }
11151
11152 // If we have 2 user-defined types, fall into that path.
11153 if (LHS->getInterface() && RHS->getInterface()) {
11154 return finish(canAssignObjCInterfaces(LHS, RHS));
11155 }
11156
11157 return false;
11158}
11159
11160/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
11161/// for providing type-safety for objective-c pointers used to pass/return
11162/// arguments in block literals. When passed as arguments, passing 'A*' where
11163/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
11164/// not OK. For the return type, the opposite is not OK.
11165bool ASTContext::canAssignObjCInterfacesInBlockPointer(
11166 const ObjCObjectPointerType *LHSOPT,
11167 const ObjCObjectPointerType *RHSOPT,
11168 bool BlockReturnType) {
11169
11170 // Function object that propagates a successful result or handles
11171 // __kindof types.
11172 auto finish = [&](bool succeeded) -> bool {
11173 if (succeeded)
11174 return true;
11175
11176 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
11177 if (!Expected->isKindOfType())
11178 return false;
11179
11180 // Strip off __kindof and protocol qualifiers, then check whether
11181 // we can assign the other way.
11182 return canAssignObjCInterfacesInBlockPointer(
11183 LHSOPT: RHSOPT->stripObjCKindOfTypeAndQuals(ctx: *this),
11184 RHSOPT: LHSOPT->stripObjCKindOfTypeAndQuals(ctx: *this),
11185 BlockReturnType);
11186 };
11187
11188 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
11189 return true;
11190
11191 if (LHSOPT->isObjCBuiltinType()) {
11192 return finish(RHSOPT->isObjCBuiltinType() ||
11193 RHSOPT->isObjCQualifiedIdType());
11194 }
11195
11196 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) {
11197 if (getLangOpts().CompatibilityQualifiedIdBlockParamTypeChecking)
11198 // Use for block parameters previous type checking for compatibility.
11199 return finish(ObjCQualifiedIdTypesAreCompatible(lhs: LHSOPT, rhs: RHSOPT, compare: false) ||
11200 // Or corrected type checking as in non-compat mode.
11201 (!BlockReturnType &&
11202 ObjCQualifiedIdTypesAreCompatible(lhs: RHSOPT, rhs: LHSOPT, compare: false)));
11203 else
11204 return finish(ObjCQualifiedIdTypesAreCompatible(
11205 lhs: (BlockReturnType ? LHSOPT : RHSOPT),
11206 rhs: (BlockReturnType ? RHSOPT : LHSOPT), compare: false));
11207 }
11208
11209 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
11210 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
11211 if (LHS && RHS) { // We have 2 user-defined types.
11212 if (LHS != RHS) {
11213 if (LHS->getDecl()->isSuperClassOf(I: RHS->getDecl()))
11214 return finish(BlockReturnType);
11215 if (RHS->getDecl()->isSuperClassOf(I: LHS->getDecl()))
11216 return finish(!BlockReturnType);
11217 }
11218 else
11219 return true;
11220 }
11221 return false;
11222}
11223
11224/// Comparison routine for Objective-C protocols to be used with
11225/// llvm::array_pod_sort.
11226static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
11227 ObjCProtocolDecl * const *rhs) {
11228 return (*lhs)->getName().compare(RHS: (*rhs)->getName());
11229}
11230
11231/// getIntersectionOfProtocols - This routine finds the intersection of set
11232/// of protocols inherited from two distinct objective-c pointer objects with
11233/// the given common base.
11234/// It is used to build composite qualifier list of the composite type of
11235/// the conditional expression involving two objective-c pointer objects.
11236static
11237void getIntersectionOfProtocols(ASTContext &Context,
11238 const ObjCInterfaceDecl *CommonBase,
11239 const ObjCObjectPointerType *LHSOPT,
11240 const ObjCObjectPointerType *RHSOPT,
11241 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
11242
11243 const ObjCObjectType* LHS = LHSOPT->getObjectType();
11244 const ObjCObjectType* RHS = RHSOPT->getObjectType();
11245 assert(LHS->getInterface() && "LHS must have an interface base");
11246 assert(RHS->getInterface() && "RHS must have an interface base");
11247
11248 // Add all of the protocols for the LHS.
11249 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
11250
11251 // Start with the protocol qualifiers.
11252 for (auto *proto : LHS->quals()) {
11253 Context.CollectInheritedProtocols(CDecl: proto, Protocols&: LHSProtocolSet);
11254 }
11255
11256 // Also add the protocols associated with the LHS interface.
11257 Context.CollectInheritedProtocols(CDecl: LHS->getInterface(), Protocols&: LHSProtocolSet);
11258
11259 // Add all of the protocols for the RHS.
11260 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
11261
11262 // Start with the protocol qualifiers.
11263 for (auto *proto : RHS->quals()) {
11264 Context.CollectInheritedProtocols(CDecl: proto, Protocols&: RHSProtocolSet);
11265 }
11266
11267 // Also add the protocols associated with the RHS interface.
11268 Context.CollectInheritedProtocols(CDecl: RHS->getInterface(), Protocols&: RHSProtocolSet);
11269
11270 // Compute the intersection of the collected protocol sets.
11271 for (auto *proto : LHSProtocolSet) {
11272 if (RHSProtocolSet.count(Ptr: proto))
11273 IntersectionSet.push_back(Elt: proto);
11274 }
11275
11276 // Compute the set of protocols that is implied by either the common type or
11277 // the protocols within the intersection.
11278 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
11279 Context.CollectInheritedProtocols(CDecl: CommonBase, Protocols&: ImpliedProtocols);
11280
11281 // Remove any implied protocols from the list of inherited protocols.
11282 if (!ImpliedProtocols.empty()) {
11283 llvm::erase_if(C&: IntersectionSet, P: [&](ObjCProtocolDecl *proto) -> bool {
11284 return ImpliedProtocols.contains(Ptr: proto);
11285 });
11286 }
11287
11288 // Sort the remaining protocols by name.
11289 llvm::array_pod_sort(Start: IntersectionSet.begin(), End: IntersectionSet.end(),
11290 Compare: compareObjCProtocolsByName);
11291}
11292
11293/// Determine whether the first type is a subtype of the second.
11294static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
11295 QualType rhs) {
11296 // Common case: two object pointers.
11297 const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
11298 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
11299 if (lhsOPT && rhsOPT)
11300 return ctx.canAssignObjCInterfaces(LHSOPT: lhsOPT, RHSOPT: rhsOPT);
11301
11302 // Two block pointers.
11303 const auto *lhsBlock = lhs->getAs<BlockPointerType>();
11304 const auto *rhsBlock = rhs->getAs<BlockPointerType>();
11305 if (lhsBlock && rhsBlock)
11306 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
11307
11308 // If either is an unqualified 'id' and the other is a block, it's
11309 // acceptable.
11310 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
11311 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
11312 return true;
11313
11314 return false;
11315}
11316
11317// Check that the given Objective-C type argument lists are equivalent.
11318static bool sameObjCTypeArgs(ASTContext &ctx,
11319 const ObjCInterfaceDecl *iface,
11320 ArrayRef<QualType> lhsArgs,
11321 ArrayRef<QualType> rhsArgs,
11322 bool stripKindOf) {
11323 if (lhsArgs.size() != rhsArgs.size())
11324 return false;
11325
11326 ObjCTypeParamList *typeParams = iface->getTypeParamList();
11327 if (!typeParams)
11328 return false;
11329
11330 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
11331 if (ctx.hasSameType(T1: lhsArgs[i], T2: rhsArgs[i]))
11332 continue;
11333
11334 switch (typeParams->begin()[i]->getVariance()) {
11335 case ObjCTypeParamVariance::Invariant:
11336 if (!stripKindOf ||
11337 !ctx.hasSameType(T1: lhsArgs[i].stripObjCKindOfType(ctx),
11338 T2: rhsArgs[i].stripObjCKindOfType(ctx))) {
11339 return false;
11340 }
11341 break;
11342
11343 case ObjCTypeParamVariance::Covariant:
11344 if (!canAssignObjCObjectTypes(ctx, lhs: lhsArgs[i], rhs: rhsArgs[i]))
11345 return false;
11346 break;
11347
11348 case ObjCTypeParamVariance::Contravariant:
11349 if (!canAssignObjCObjectTypes(ctx, lhs: rhsArgs[i], rhs: lhsArgs[i]))
11350 return false;
11351 break;
11352 }
11353 }
11354
11355 return true;
11356}
11357
11358QualType ASTContext::areCommonBaseCompatible(
11359 const ObjCObjectPointerType *Lptr,
11360 const ObjCObjectPointerType *Rptr) {
11361 const ObjCObjectType *LHS = Lptr->getObjectType();
11362 const ObjCObjectType *RHS = Rptr->getObjectType();
11363 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
11364 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
11365
11366 if (!LDecl || !RDecl)
11367 return {};
11368
11369 // When either LHS or RHS is a kindof type, we should return a kindof type.
11370 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
11371 // kindof(A).
11372 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
11373
11374 // Follow the left-hand side up the class hierarchy until we either hit a
11375 // root or find the RHS. Record the ancestors in case we don't find it.
11376 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
11377 LHSAncestors;
11378 while (true) {
11379 // Record this ancestor. We'll need this if the common type isn't in the
11380 // path from the LHS to the root.
11381 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
11382
11383 if (declaresSameEntity(D1: LHS->getInterface(), D2: RDecl)) {
11384 // Get the type arguments.
11385 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
11386 bool anyChanges = false;
11387 if (LHS->isSpecialized() && RHS->isSpecialized()) {
11388 // Both have type arguments, compare them.
11389 if (!sameObjCTypeArgs(ctx&: *this, iface: LHS->getInterface(),
11390 lhsArgs: LHS->getTypeArgs(), rhsArgs: RHS->getTypeArgs(),
11391 /*stripKindOf=*/true))
11392 return {};
11393 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
11394 // If only one has type arguments, the result will not have type
11395 // arguments.
11396 LHSTypeArgs = {};
11397 anyChanges = true;
11398 }
11399
11400 // Compute the intersection of protocols.
11401 SmallVector<ObjCProtocolDecl *, 8> Protocols;
11402 getIntersectionOfProtocols(Context&: *this, CommonBase: LHS->getInterface(), LHSOPT: Lptr, RHSOPT: Rptr,
11403 IntersectionSet&: Protocols);
11404 if (!Protocols.empty())
11405 anyChanges = true;
11406
11407 // If anything in the LHS will have changed, build a new result type.
11408 // If we need to return a kindof type but LHS is not a kindof type, we
11409 // build a new result type.
11410 if (anyChanges || LHS->isKindOfType() != anyKindOf) {
11411 QualType Result = getObjCInterfaceType(Decl: LHS->getInterface());
11412 Result = getObjCObjectType(baseType: Result, typeArgs: LHSTypeArgs, protocols: Protocols,
11413 isKindOf: anyKindOf || LHS->isKindOfType());
11414 return getObjCObjectPointerType(ObjectT: Result);
11415 }
11416
11417 return getObjCObjectPointerType(ObjectT: QualType(LHS, 0));
11418 }
11419
11420 // Find the superclass.
11421 QualType LHSSuperType = LHS->getSuperClassType();
11422 if (LHSSuperType.isNull())
11423 break;
11424
11425 LHS = LHSSuperType->castAs<ObjCObjectType>();
11426 }
11427
11428 // We didn't find anything by following the LHS to its root; now check
11429 // the RHS against the cached set of ancestors.
11430 while (true) {
11431 auto KnownLHS = LHSAncestors.find(Val: RHS->getInterface()->getCanonicalDecl());
11432 if (KnownLHS != LHSAncestors.end()) {
11433 LHS = KnownLHS->second;
11434
11435 // Get the type arguments.
11436 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
11437 bool anyChanges = false;
11438 if (LHS->isSpecialized() && RHS->isSpecialized()) {
11439 // Both have type arguments, compare them.
11440 if (!sameObjCTypeArgs(ctx&: *this, iface: LHS->getInterface(),
11441 lhsArgs: LHS->getTypeArgs(), rhsArgs: RHS->getTypeArgs(),
11442 /*stripKindOf=*/true))
11443 return {};
11444 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
11445 // If only one has type arguments, the result will not have type
11446 // arguments.
11447 RHSTypeArgs = {};
11448 anyChanges = true;
11449 }
11450
11451 // Compute the intersection of protocols.
11452 SmallVector<ObjCProtocolDecl *, 8> Protocols;
11453 getIntersectionOfProtocols(Context&: *this, CommonBase: RHS->getInterface(), LHSOPT: Lptr, RHSOPT: Rptr,
11454 IntersectionSet&: Protocols);
11455 if (!Protocols.empty())
11456 anyChanges = true;
11457
11458 // If we need to return a kindof type but RHS is not a kindof type, we
11459 // build a new result type.
11460 if (anyChanges || RHS->isKindOfType() != anyKindOf) {
11461 QualType Result = getObjCInterfaceType(Decl: RHS->getInterface());
11462 Result = getObjCObjectType(baseType: Result, typeArgs: RHSTypeArgs, protocols: Protocols,
11463 isKindOf: anyKindOf || RHS->isKindOfType());
11464 return getObjCObjectPointerType(ObjectT: Result);
11465 }
11466
11467 return getObjCObjectPointerType(ObjectT: QualType(RHS, 0));
11468 }
11469
11470 // Find the superclass of the RHS.
11471 QualType RHSSuperType = RHS->getSuperClassType();
11472 if (RHSSuperType.isNull())
11473 break;
11474
11475 RHS = RHSSuperType->castAs<ObjCObjectType>();
11476 }
11477
11478 return {};
11479}
11480
11481bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
11482 const ObjCObjectType *RHS) {
11483 assert(LHS->getInterface() && "LHS is not an interface type");
11484 assert(RHS->getInterface() && "RHS is not an interface type");
11485
11486 // Verify that the base decls are compatible: the RHS must be a subclass of
11487 // the LHS.
11488 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
11489 bool IsSuperClass = LHSInterface->isSuperClassOf(I: RHS->getInterface());
11490 if (!IsSuperClass)
11491 return false;
11492
11493 // If the LHS has protocol qualifiers, determine whether all of them are
11494 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
11495 // LHS).
11496 if (LHS->getNumProtocols() > 0) {
11497 // OK if conversion of LHS to SuperClass results in narrowing of types
11498 // ; i.e., SuperClass may implement at least one of the protocols
11499 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
11500 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
11501 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
11502 CollectInheritedProtocols(CDecl: RHS->getInterface(), Protocols&: SuperClassInheritedProtocols);
11503 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
11504 // qualifiers.
11505 for (auto *RHSPI : RHS->quals())
11506 CollectInheritedProtocols(CDecl: RHSPI, Protocols&: SuperClassInheritedProtocols);
11507 // If there is no protocols associated with RHS, it is not a match.
11508 if (SuperClassInheritedProtocols.empty())
11509 return false;
11510
11511 for (const auto *LHSProto : LHS->quals()) {
11512 bool SuperImplementsProtocol = false;
11513 for (auto *SuperClassProto : SuperClassInheritedProtocols)
11514 if (SuperClassProto->lookupProtocolNamed(PName: LHSProto->getIdentifier())) {
11515 SuperImplementsProtocol = true;
11516 break;
11517 }
11518 if (!SuperImplementsProtocol)
11519 return false;
11520 }
11521 }
11522
11523 // If the LHS is specialized, we may need to check type arguments.
11524 if (LHS->isSpecialized()) {
11525 // Follow the superclass chain until we've matched the LHS class in the
11526 // hierarchy. This substitutes type arguments through.
11527 const ObjCObjectType *RHSSuper = RHS;
11528 while (!declaresSameEntity(D1: RHSSuper->getInterface(), D2: LHSInterface))
11529 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
11530
11531 // If the RHS is specializd, compare type arguments.
11532 if (RHSSuper->isSpecialized() &&
11533 !sameObjCTypeArgs(ctx&: *this, iface: LHS->getInterface(),
11534 lhsArgs: LHS->getTypeArgs(), rhsArgs: RHSSuper->getTypeArgs(),
11535 /*stripKindOf=*/true)) {
11536 return false;
11537 }
11538 }
11539
11540 return true;
11541}
11542
11543bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
11544 // get the "pointed to" types
11545 const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
11546 const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
11547
11548 if (!LHSOPT || !RHSOPT)
11549 return false;
11550
11551 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
11552 canAssignObjCInterfaces(LHSOPT: RHSOPT, RHSOPT: LHSOPT);
11553}
11554
11555bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
11556 return canAssignObjCInterfaces(
11557 LHSOPT: getObjCObjectPointerType(ObjectT: To)->castAs<ObjCObjectPointerType>(),
11558 RHSOPT: getObjCObjectPointerType(ObjectT: From)->castAs<ObjCObjectPointerType>());
11559}
11560
11561/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
11562/// both shall have the identically qualified version of a compatible type.
11563/// C99 6.2.7p1: Two types have compatible types if their types are the
11564/// same. See 6.7.[2,3,5] for additional rules.
11565bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
11566 bool CompareUnqualified) {
11567 if (getLangOpts().CPlusPlus)
11568 return hasSameType(T1: LHS, T2: RHS);
11569
11570 return !mergeTypes(LHS, RHS, OfBlockPointer: false, Unqualified: CompareUnqualified).isNull();
11571}
11572
11573bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
11574 return typesAreCompatible(LHS, RHS);
11575}
11576
11577bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
11578 return !mergeTypes(LHS, RHS, OfBlockPointer: true).isNull();
11579}
11580
11581/// mergeTransparentUnionType - if T is a transparent union type and a member
11582/// of T is compatible with SubType, return the merged type, else return
11583/// QualType()
11584QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
11585 bool OfBlockPointer,
11586 bool Unqualified) {
11587 if (const RecordType *UT = T->getAsUnionType()) {
11588 RecordDecl *UD = UT->getDecl()->getMostRecentDecl();
11589 if (UD->hasAttr<TransparentUnionAttr>()) {
11590 for (const auto *I : UD->fields()) {
11591 QualType ET = I->getType().getUnqualifiedType();
11592 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
11593 if (!MT.isNull())
11594 return MT;
11595 }
11596 }
11597 }
11598
11599 return {};
11600}
11601
11602/// mergeFunctionParameterTypes - merge two types which appear as function
11603/// parameter types
11604QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
11605 bool OfBlockPointer,
11606 bool Unqualified) {
11607 // GNU extension: two types are compatible if they appear as a function
11608 // argument, one of the types is a transparent union type and the other
11609 // type is compatible with a union member
11610 QualType lmerge = mergeTransparentUnionType(T: lhs, SubType: rhs, OfBlockPointer,
11611 Unqualified);
11612 if (!lmerge.isNull())
11613 return lmerge;
11614
11615 QualType rmerge = mergeTransparentUnionType(T: rhs, SubType: lhs, OfBlockPointer,
11616 Unqualified);
11617 if (!rmerge.isNull())
11618 return rmerge;
11619
11620 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
11621}
11622
11623QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
11624 bool OfBlockPointer, bool Unqualified,
11625 bool AllowCXX,
11626 bool IsConditionalOperator) {
11627 const auto *lbase = lhs->castAs<FunctionType>();
11628 const auto *rbase = rhs->castAs<FunctionType>();
11629 const auto *lproto = dyn_cast<FunctionProtoType>(Val: lbase);
11630 const auto *rproto = dyn_cast<FunctionProtoType>(Val: rbase);
11631 bool allLTypes = true;
11632 bool allRTypes = true;
11633
11634 // Check return type
11635 QualType retType;
11636 if (OfBlockPointer) {
11637 QualType RHS = rbase->getReturnType();
11638 QualType LHS = lbase->getReturnType();
11639 bool UnqualifiedResult = Unqualified;
11640 if (!UnqualifiedResult)
11641 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
11642 retType = mergeTypes(LHS, RHS, OfBlockPointer: true, Unqualified: UnqualifiedResult, BlockReturnType: true);
11643 }
11644 else
11645 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), OfBlockPointer: false,
11646 Unqualified);
11647 if (retType.isNull())
11648 return {};
11649
11650 if (Unqualified)
11651 retType = retType.getUnqualifiedType();
11652
11653 CanQualType LRetType = getCanonicalType(T: lbase->getReturnType());
11654 CanQualType RRetType = getCanonicalType(T: rbase->getReturnType());
11655 if (Unqualified) {
11656 LRetType = LRetType.getUnqualifiedType();
11657 RRetType = RRetType.getUnqualifiedType();
11658 }
11659
11660 if (getCanonicalType(T: retType) != LRetType)
11661 allLTypes = false;
11662 if (getCanonicalType(T: retType) != RRetType)
11663 allRTypes = false;
11664
11665 // FIXME: double check this
11666 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
11667 // rbase->getRegParmAttr() != 0 &&
11668 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
11669 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
11670 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
11671
11672 // Compatible functions must have compatible calling conventions
11673 if (lbaseInfo.getCC() != rbaseInfo.getCC())
11674 return {};
11675
11676 // Regparm is part of the calling convention.
11677 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
11678 return {};
11679 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
11680 return {};
11681
11682 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
11683 return {};
11684 if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs())
11685 return {};
11686 if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck())
11687 return {};
11688
11689 // When merging declarations, it's common for supplemental information like
11690 // attributes to only be present in one of the declarations, and we generally
11691 // want type merging to preserve the union of information. So a merged
11692 // function type should be noreturn if it was noreturn in *either* operand
11693 // type.
11694 //
11695 // But for the conditional operator, this is backwards. The result of the
11696 // operator could be either operand, and its type should conservatively
11697 // reflect that. So a function type in a composite type is noreturn only
11698 // if it's noreturn in *both* operand types.
11699 //
11700 // Arguably, noreturn is a kind of subtype, and the conditional operator
11701 // ought to produce the most specific common supertype of its operand types.
11702 // That would differ from this rule in contravariant positions. However,
11703 // neither C nor C++ generally uses this kind of subtype reasoning. Also,
11704 // as a practical matter, it would only affect C code that does abstraction of
11705 // higher-order functions (taking noreturn callbacks!), which is uncommon to
11706 // say the least. So we use the simpler rule.
11707 bool NoReturn = IsConditionalOperator
11708 ? lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn()
11709 : lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
11710 if (lbaseInfo.getNoReturn() != NoReturn)
11711 allLTypes = false;
11712 if (rbaseInfo.getNoReturn() != NoReturn)
11713 allRTypes = false;
11714
11715 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(noReturn: NoReturn);
11716
11717 std::optional<FunctionEffectSet> MergedFX;
11718
11719 if (lproto && rproto) { // two C99 style function prototypes
11720 assert((AllowCXX ||
11721 (!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec())) &&
11722 "C++ shouldn't be here");
11723 // Compatible functions must have the same number of parameters
11724 if (lproto->getNumParams() != rproto->getNumParams())
11725 return {};
11726
11727 // Variadic and non-variadic functions aren't compatible
11728 if (lproto->isVariadic() != rproto->isVariadic())
11729 return {};
11730
11731 if (lproto->getMethodQuals() != rproto->getMethodQuals())
11732 return {};
11733
11734 // Function protos with different 'cfi_salt' values aren't compatible.
11735 if (lproto->getExtraAttributeInfo().CFISalt !=
11736 rproto->getExtraAttributeInfo().CFISalt)
11737 return {};
11738
11739 // Function effects are handled similarly to noreturn, see above.
11740 FunctionEffectsRef LHSFX = lproto->getFunctionEffects();
11741 FunctionEffectsRef RHSFX = rproto->getFunctionEffects();
11742 if (LHSFX != RHSFX) {
11743 if (IsConditionalOperator)
11744 MergedFX = FunctionEffectSet::getIntersection(LHS: LHSFX, RHS: RHSFX);
11745 else {
11746 FunctionEffectSet::Conflicts Errs;
11747 MergedFX = FunctionEffectSet::getUnion(LHS: LHSFX, RHS: RHSFX, Errs);
11748 // Here we're discarding a possible error due to conflicts in the effect
11749 // sets. But we're not in a context where we can report it. The
11750 // operation does however guarantee maintenance of invariants.
11751 }
11752 if (*MergedFX != LHSFX)
11753 allLTypes = false;
11754 if (*MergedFX != RHSFX)
11755 allRTypes = false;
11756 }
11757
11758 SmallVector<FunctionProtoType::ExtParameterInfo, 4> newParamInfos;
11759 bool canUseLeft, canUseRight;
11760 if (!mergeExtParameterInfo(FirstFnType: lproto, SecondFnType: rproto, CanUseFirst&: canUseLeft, CanUseSecond&: canUseRight,
11761 NewParamInfos&: newParamInfos))
11762 return {};
11763
11764 if (!canUseLeft)
11765 allLTypes = false;
11766 if (!canUseRight)
11767 allRTypes = false;
11768
11769 // Check parameter type compatibility
11770 SmallVector<QualType, 10> types;
11771 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
11772 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
11773 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
11774 QualType paramType = mergeFunctionParameterTypes(
11775 lhs: lParamType, rhs: rParamType, OfBlockPointer, Unqualified);
11776 if (paramType.isNull())
11777 return {};
11778
11779 if (Unqualified)
11780 paramType = paramType.getUnqualifiedType();
11781
11782 types.push_back(Elt: paramType);
11783 if (Unqualified) {
11784 lParamType = lParamType.getUnqualifiedType();
11785 rParamType = rParamType.getUnqualifiedType();
11786 }
11787
11788 if (getCanonicalType(T: paramType) != getCanonicalType(T: lParamType))
11789 allLTypes = false;
11790 if (getCanonicalType(T: paramType) != getCanonicalType(T: rParamType))
11791 allRTypes = false;
11792 }
11793
11794 if (allLTypes) return lhs;
11795 if (allRTypes) return rhs;
11796
11797 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
11798 EPI.ExtInfo = einfo;
11799 EPI.ExtParameterInfos =
11800 newParamInfos.empty() ? nullptr : newParamInfos.data();
11801 if (MergedFX)
11802 EPI.FunctionEffects = *MergedFX;
11803 return getFunctionType(ResultTy: retType, Args: types, EPI);
11804 }
11805
11806 if (lproto) allRTypes = false;
11807 if (rproto) allLTypes = false;
11808
11809 const FunctionProtoType *proto = lproto ? lproto : rproto;
11810 if (proto) {
11811 assert((AllowCXX || !proto->hasExceptionSpec()) && "C++ shouldn't be here");
11812 if (proto->isVariadic())
11813 return {};
11814 // Check that the types are compatible with the types that
11815 // would result from default argument promotions (C99 6.7.5.3p15).
11816 // The only types actually affected are promotable integer
11817 // types and floats, which would be passed as a different
11818 // type depending on whether the prototype is visible.
11819 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
11820 QualType paramTy = proto->getParamType(i);
11821
11822 // Look at the converted type of enum types, since that is the type used
11823 // to pass enum values.
11824 if (const auto *ED = paramTy->getAsEnumDecl()) {
11825 paramTy = ED->getIntegerType();
11826 if (paramTy.isNull())
11827 return {};
11828 }
11829
11830 if (isPromotableIntegerType(T: paramTy) ||
11831 getCanonicalType(T: paramTy).getUnqualifiedType() == FloatTy)
11832 return {};
11833 }
11834
11835 if (allLTypes) return lhs;
11836 if (allRTypes) return rhs;
11837
11838 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
11839 EPI.ExtInfo = einfo;
11840 if (MergedFX)
11841 EPI.FunctionEffects = *MergedFX;
11842 return getFunctionType(ResultTy: retType, Args: proto->getParamTypes(), EPI);
11843 }
11844
11845 if (allLTypes) return lhs;
11846 if (allRTypes) return rhs;
11847 return getFunctionNoProtoType(ResultTy: retType, Info: einfo);
11848}
11849
11850/// Given that we have an enum type and a non-enum type, try to merge them.
11851static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
11852 QualType other, bool isBlockReturnType) {
11853 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
11854 // a signed integer type, or an unsigned integer type.
11855 // Compatibility is based on the underlying type, not the promotion
11856 // type.
11857 QualType underlyingType =
11858 ET->getDecl()->getDefinitionOrSelf()->getIntegerType();
11859 if (underlyingType.isNull())
11860 return {};
11861 if (Context.hasSameType(T1: underlyingType, T2: other))
11862 return other;
11863
11864 // In block return types, we're more permissive and accept any
11865 // integral type of the same size.
11866 if (isBlockReturnType && other->isIntegerType() &&
11867 Context.getTypeSize(T: underlyingType) == Context.getTypeSize(T: other))
11868 return other;
11869
11870 return {};
11871}
11872
11873QualType ASTContext::mergeTagDefinitions(QualType LHS, QualType RHS) {
11874 // C17 and earlier and C++ disallow two tag definitions within the same TU
11875 // from being compatible.
11876 if (LangOpts.CPlusPlus || !LangOpts.C23)
11877 return {};
11878
11879 // Nameless tags are comparable only within outer definitions. At the top
11880 // level they are not comparable.
11881 const TagDecl *LTagD = LHS->castAsTagDecl(), *RTagD = RHS->castAsTagDecl();
11882 if (!LTagD->getIdentifier() || !RTagD->getIdentifier())
11883 return {};
11884
11885 // C23, on the other hand, requires the members to be "the same enough", so
11886 // we use a structural equivalence check.
11887 StructuralEquivalenceContext::NonEquivalentDeclSet NonEquivalentDecls;
11888 StructuralEquivalenceContext Ctx(
11889 getLangOpts(), *this, *this, NonEquivalentDecls,
11890 StructuralEquivalenceKind::Default, /*StrictTypeSpelling=*/false,
11891 /*Complain=*/false, /*ErrorOnTagTypeMismatch=*/true);
11892 return Ctx.IsEquivalent(T1: LHS, T2: RHS) ? LHS : QualType{};
11893}
11894
11895std::optional<QualType> ASTContext::tryMergeOverflowBehaviorTypes(
11896 QualType LHS, QualType RHS, bool OfBlockPointer, bool Unqualified,
11897 bool BlockReturnType, bool IsConditionalOperator) {
11898 const auto *LHSOBT = LHS->getAs<OverflowBehaviorType>();
11899 const auto *RHSOBT = RHS->getAs<OverflowBehaviorType>();
11900
11901 if (!LHSOBT && !RHSOBT)
11902 return std::nullopt;
11903
11904 if (LHSOBT) {
11905 if (RHSOBT) {
11906 if (LHSOBT->getBehaviorKind() != RHSOBT->getBehaviorKind())
11907 return QualType();
11908
11909 QualType MergedUnderlying = mergeTypes(
11910 LHSOBT->getUnderlyingType(), RHSOBT->getUnderlyingType(),
11911 OfBlockPointer, Unqualified, BlockReturnType, IsConditionalOperator);
11912
11913 if (MergedUnderlying.isNull())
11914 return QualType();
11915
11916 if (getCanonicalType(T: LHSOBT) == getCanonicalType(T: RHSOBT)) {
11917 if (LHSOBT->getUnderlyingType() == RHSOBT->getUnderlyingType())
11918 return getCommonSugaredType(X: LHS, Y: RHS);
11919 return getOverflowBehaviorType(
11920 Kind: LHSOBT->getBehaviorKind(),
11921 Underlying: getCanonicalType(T: LHSOBT->getUnderlyingType()));
11922 }
11923
11924 // For different underlying types that successfully merge, wrap the
11925 // merged underlying type with the common overflow behavior
11926 return getOverflowBehaviorType(Kind: LHSOBT->getBehaviorKind(),
11927 Underlying: MergedUnderlying);
11928 }
11929 return mergeTypes(LHSOBT->getUnderlyingType(), RHS, OfBlockPointer,
11930 Unqualified, BlockReturnType, IsConditionalOperator);
11931 }
11932
11933 return mergeTypes(LHS, RHSOBT->getUnderlyingType(), OfBlockPointer,
11934 Unqualified, BlockReturnType, IsConditionalOperator);
11935}
11936
11937QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, bool OfBlockPointer,
11938 bool Unqualified, bool BlockReturnType,
11939 bool IsConditionalOperator) {
11940 // For C++ we will not reach this code with reference types (see below),
11941 // for OpenMP variant call overloading we might.
11942 //
11943 // C++ [expr]: If an expression initially has the type "reference to T", the
11944 // type is adjusted to "T" prior to any further analysis, the expression
11945 // designates the object or function denoted by the reference, and the
11946 // expression is an lvalue unless the reference is an rvalue reference and
11947 // the expression is a function call (possibly inside parentheses).
11948 auto *LHSRefTy = LHS->getAs<ReferenceType>();
11949 auto *RHSRefTy = RHS->getAs<ReferenceType>();
11950 if (LangOpts.OpenMP && LHSRefTy && RHSRefTy &&
11951 LHS->getTypeClass() == RHS->getTypeClass())
11952 return mergeTypes(LHS: LHSRefTy->getPointeeType(), RHS: RHSRefTy->getPointeeType(),
11953 OfBlockPointer, Unqualified, BlockReturnType);
11954 if (LHSRefTy || RHSRefTy)
11955 return {};
11956
11957 if (std::optional<QualType> MergedOBT =
11958 tryMergeOverflowBehaviorTypes(LHS, RHS, OfBlockPointer, Unqualified,
11959 BlockReturnType, IsConditionalOperator))
11960 return *MergedOBT;
11961
11962 if (Unqualified) {
11963 LHS = LHS.getUnqualifiedType();
11964 RHS = RHS.getUnqualifiedType();
11965 }
11966
11967 QualType LHSCan = getCanonicalType(T: LHS),
11968 RHSCan = getCanonicalType(T: RHS);
11969
11970 // If two types are identical, they are compatible.
11971 if (LHSCan == RHSCan)
11972 return LHS;
11973
11974 // If the qualifiers are different, the types aren't compatible... mostly.
11975 Qualifiers LQuals = LHSCan.getLocalQualifiers();
11976 Qualifiers RQuals = RHSCan.getLocalQualifiers();
11977 if (LQuals != RQuals) {
11978 // If any of these qualifiers are different, we have a type
11979 // mismatch.
11980 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
11981 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
11982 LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
11983 !LQuals.getPointerAuth().isEquivalent(Other: RQuals.getPointerAuth()) ||
11984 LQuals.hasUnaligned() != RQuals.hasUnaligned())
11985 return {};
11986
11987 // Exactly one GC qualifier difference is allowed: __strong is
11988 // okay if the other type has no GC qualifier but is an Objective
11989 // C object pointer (i.e. implicitly strong by default). We fix
11990 // this by pretending that the unqualified type was actually
11991 // qualified __strong.
11992 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
11993 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
11994 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
11995
11996 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
11997 return {};
11998
11999 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
12000 return mergeTypes(LHS, RHS: getObjCGCQualType(T: RHS, GCAttr: Qualifiers::Strong));
12001 }
12002 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
12003 return mergeTypes(LHS: getObjCGCQualType(T: LHS, GCAttr: Qualifiers::Strong), RHS);
12004 }
12005 return {};
12006 }
12007
12008 // Okay, qualifiers are equal.
12009
12010 Type::TypeClass LHSClass = LHSCan->getTypeClass();
12011 Type::TypeClass RHSClass = RHSCan->getTypeClass();
12012
12013 // We want to consider the two function types to be the same for these
12014 // comparisons, just force one to the other.
12015 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
12016 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
12017
12018 // Same as above for arrays
12019 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
12020 LHSClass = Type::ConstantArray;
12021 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
12022 RHSClass = Type::ConstantArray;
12023
12024 // ObjCInterfaces are just specialized ObjCObjects.
12025 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
12026 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
12027
12028 // Canonicalize ExtVector -> Vector.
12029 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
12030 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
12031
12032 // If the canonical type classes don't match.
12033 if (LHSClass != RHSClass) {
12034 // Note that we only have special rules for turning block enum
12035 // returns into block int returns, not vice-versa.
12036 if (const auto *ETy = LHS->getAsCanonical<EnumType>()) {
12037 return mergeEnumWithInteger(Context&: *this, ET: ETy, other: RHS, isBlockReturnType: false);
12038 }
12039 if (const EnumType *ETy = RHS->getAsCanonical<EnumType>()) {
12040 return mergeEnumWithInteger(Context&: *this, ET: ETy, other: LHS, isBlockReturnType: BlockReturnType);
12041 }
12042 // allow block pointer type to match an 'id' type.
12043 if (OfBlockPointer && !BlockReturnType) {
12044 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
12045 return LHS;
12046 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
12047 return RHS;
12048 }
12049 // Allow __auto_type to match anything; it merges to the type with more
12050 // information.
12051 if (const auto *AT = LHS->getAs<AutoType>()) {
12052 if (!AT->isDeduced() && AT->isGNUAutoType())
12053 return RHS;
12054 }
12055 if (const auto *AT = RHS->getAs<AutoType>()) {
12056 if (!AT->isDeduced() && AT->isGNUAutoType())
12057 return LHS;
12058 }
12059 return {};
12060 }
12061
12062 // The canonical type classes match.
12063 switch (LHSClass) {
12064#define TYPE(Class, Base)
12065#define ABSTRACT_TYPE(Class, Base)
12066#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
12067#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
12068#define DEPENDENT_TYPE(Class, Base) case Type::Class:
12069#include "clang/AST/TypeNodes.inc"
12070 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
12071
12072 case Type::Auto:
12073 case Type::DeducedTemplateSpecialization:
12074 case Type::LValueReference:
12075 case Type::RValueReference:
12076 case Type::MemberPointer:
12077 llvm_unreachable("C++ should never be in mergeTypes");
12078
12079 case Type::ObjCInterface:
12080 case Type::IncompleteArray:
12081 case Type::VariableArray:
12082 case Type::FunctionProto:
12083 case Type::ExtVector:
12084 case Type::OverflowBehavior:
12085 llvm_unreachable("Types are eliminated above");
12086
12087 case Type::Pointer:
12088 {
12089 // Merge two pointer types, while trying to preserve typedef info
12090 QualType LHSPointee = LHS->castAs<PointerType>()->getPointeeType();
12091 QualType RHSPointee = RHS->castAs<PointerType>()->getPointeeType();
12092 if (Unqualified) {
12093 LHSPointee = LHSPointee.getUnqualifiedType();
12094 RHSPointee = RHSPointee.getUnqualifiedType();
12095 }
12096 QualType ResultType = mergeTypes(LHS: LHSPointee, RHS: RHSPointee, OfBlockPointer: false,
12097 Unqualified);
12098 if (ResultType.isNull())
12099 return {};
12100 if (getCanonicalType(T: LHSPointee) == getCanonicalType(T: ResultType))
12101 return LHS;
12102 if (getCanonicalType(T: RHSPointee) == getCanonicalType(T: ResultType))
12103 return RHS;
12104 return getPointerType(T: ResultType);
12105 }
12106 case Type::BlockPointer:
12107 {
12108 // Merge two block pointer types, while trying to preserve typedef info
12109 QualType LHSPointee = LHS->castAs<BlockPointerType>()->getPointeeType();
12110 QualType RHSPointee = RHS->castAs<BlockPointerType>()->getPointeeType();
12111 if (Unqualified) {
12112 LHSPointee = LHSPointee.getUnqualifiedType();
12113 RHSPointee = RHSPointee.getUnqualifiedType();
12114 }
12115 if (getLangOpts().OpenCL) {
12116 Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
12117 Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
12118 // Blocks can't be an expression in a ternary operator (OpenCL v2.0
12119 // 6.12.5) thus the following check is asymmetric.
12120 if (!LHSPteeQual.isAddressSpaceSupersetOf(other: RHSPteeQual, Ctx: *this))
12121 return {};
12122 LHSPteeQual.removeAddressSpace();
12123 RHSPteeQual.removeAddressSpace();
12124 LHSPointee =
12125 QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
12126 RHSPointee =
12127 QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
12128 }
12129 QualType ResultType = mergeTypes(LHS: LHSPointee, RHS: RHSPointee, OfBlockPointer,
12130 Unqualified);
12131 if (ResultType.isNull())
12132 return {};
12133 if (getCanonicalType(T: LHSPointee) == getCanonicalType(T: ResultType))
12134 return LHS;
12135 if (getCanonicalType(T: RHSPointee) == getCanonicalType(T: ResultType))
12136 return RHS;
12137 return getBlockPointerType(T: ResultType);
12138 }
12139 case Type::Atomic:
12140 {
12141 // Merge two pointer types, while trying to preserve typedef info
12142 QualType LHSValue = LHS->castAs<AtomicType>()->getValueType();
12143 QualType RHSValue = RHS->castAs<AtomicType>()->getValueType();
12144 if (Unqualified) {
12145 LHSValue = LHSValue.getUnqualifiedType();
12146 RHSValue = RHSValue.getUnqualifiedType();
12147 }
12148 QualType ResultType = mergeTypes(LHS: LHSValue, RHS: RHSValue, OfBlockPointer: false,
12149 Unqualified);
12150 if (ResultType.isNull())
12151 return {};
12152 if (getCanonicalType(T: LHSValue) == getCanonicalType(T: ResultType))
12153 return LHS;
12154 if (getCanonicalType(T: RHSValue) == getCanonicalType(T: ResultType))
12155 return RHS;
12156 return getAtomicType(T: ResultType);
12157 }
12158 case Type::ConstantArray:
12159 {
12160 const ConstantArrayType* LCAT = getAsConstantArrayType(T: LHS);
12161 const ConstantArrayType* RCAT = getAsConstantArrayType(T: RHS);
12162 if (LCAT && RCAT && RCAT->getZExtSize() != LCAT->getZExtSize())
12163 return {};
12164
12165 QualType LHSElem = getAsArrayType(T: LHS)->getElementType();
12166 QualType RHSElem = getAsArrayType(T: RHS)->getElementType();
12167 if (Unqualified) {
12168 LHSElem = LHSElem.getUnqualifiedType();
12169 RHSElem = RHSElem.getUnqualifiedType();
12170 }
12171
12172 QualType ResultType = mergeTypes(LHS: LHSElem, RHS: RHSElem, OfBlockPointer: false, Unqualified);
12173 if (ResultType.isNull())
12174 return {};
12175
12176 const VariableArrayType* LVAT = getAsVariableArrayType(T: LHS);
12177 const VariableArrayType* RVAT = getAsVariableArrayType(T: RHS);
12178
12179 // If either side is a variable array, and both are complete, check whether
12180 // the current dimension is definite.
12181 if (LVAT || RVAT) {
12182 auto SizeFetch = [this](const VariableArrayType* VAT,
12183 const ConstantArrayType* CAT)
12184 -> std::pair<bool,llvm::APInt> {
12185 if (VAT) {
12186 std::optional<llvm::APSInt> TheInt;
12187 Expr *E = VAT->getSizeExpr();
12188 if (E && (TheInt = E->getIntegerConstantExpr(Ctx: *this)))
12189 return std::make_pair(x: true, y&: *TheInt);
12190 return std::make_pair(x: false, y: llvm::APSInt());
12191 }
12192 if (CAT)
12193 return std::make_pair(x: true, y: CAT->getSize());
12194 return std::make_pair(x: false, y: llvm::APInt());
12195 };
12196
12197 bool HaveLSize, HaveRSize;
12198 llvm::APInt LSize, RSize;
12199 std::tie(args&: HaveLSize, args&: LSize) = SizeFetch(LVAT, LCAT);
12200 std::tie(args&: HaveRSize, args&: RSize) = SizeFetch(RVAT, RCAT);
12201 if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(I1: LSize, I2: RSize))
12202 return {}; // Definite, but unequal, array dimension
12203 }
12204
12205 if (LCAT && getCanonicalType(T: LHSElem) == getCanonicalType(T: ResultType))
12206 return LHS;
12207 if (RCAT && getCanonicalType(T: RHSElem) == getCanonicalType(T: ResultType))
12208 return RHS;
12209 if (LCAT)
12210 return getConstantArrayType(EltTy: ResultType, ArySizeIn: LCAT->getSize(),
12211 SizeExpr: LCAT->getSizeExpr(), ASM: ArraySizeModifier(), IndexTypeQuals: 0);
12212 if (RCAT)
12213 return getConstantArrayType(EltTy: ResultType, ArySizeIn: RCAT->getSize(),
12214 SizeExpr: RCAT->getSizeExpr(), ASM: ArraySizeModifier(), IndexTypeQuals: 0);
12215 if (LVAT && getCanonicalType(T: LHSElem) == getCanonicalType(T: ResultType))
12216 return LHS;
12217 if (RVAT && getCanonicalType(T: RHSElem) == getCanonicalType(T: ResultType))
12218 return RHS;
12219 if (LVAT) {
12220 // FIXME: This isn't correct! But tricky to implement because
12221 // the array's size has to be the size of LHS, but the type
12222 // has to be different.
12223 return LHS;
12224 }
12225 if (RVAT) {
12226 // FIXME: This isn't correct! But tricky to implement because
12227 // the array's size has to be the size of RHS, but the type
12228 // has to be different.
12229 return RHS;
12230 }
12231 if (getCanonicalType(T: LHSElem) == getCanonicalType(T: ResultType)) return LHS;
12232 if (getCanonicalType(T: RHSElem) == getCanonicalType(T: ResultType)) return RHS;
12233 return getIncompleteArrayType(elementType: ResultType, ASM: ArraySizeModifier(), elementTypeQuals: 0);
12234 }
12235 case Type::FunctionNoProto:
12236 return mergeFunctionTypes(lhs: LHS, rhs: RHS, OfBlockPointer, Unqualified,
12237 /*AllowCXX=*/false, IsConditionalOperator);
12238 case Type::Record:
12239 case Type::Enum:
12240 return mergeTagDefinitions(LHS, RHS);
12241 case Type::Builtin:
12242 // Only exactly equal builtin types are compatible, which is tested above.
12243 return {};
12244 case Type::Complex:
12245 // Distinct complex types are incompatible.
12246 return {};
12247 case Type::Vector:
12248 // FIXME: The merged type should be an ExtVector!
12249 if (areCompatVectorTypes(LHS: LHSCan->castAs<VectorType>(),
12250 RHS: RHSCan->castAs<VectorType>()))
12251 return LHS;
12252 return {};
12253 case Type::ConstantMatrix:
12254 if (areCompatMatrixTypes(LHS: LHSCan->castAs<ConstantMatrixType>(),
12255 RHS: RHSCan->castAs<ConstantMatrixType>()))
12256 return LHS;
12257 return {};
12258 case Type::ObjCObject: {
12259 // Check if the types are assignment compatible.
12260 // FIXME: This should be type compatibility, e.g. whether
12261 // "LHS x; RHS x;" at global scope is legal.
12262 if (canAssignObjCInterfaces(LHS: LHS->castAs<ObjCObjectType>(),
12263 RHS: RHS->castAs<ObjCObjectType>()))
12264 return LHS;
12265 return {};
12266 }
12267 case Type::ObjCObjectPointer:
12268 if (OfBlockPointer) {
12269 if (canAssignObjCInterfacesInBlockPointer(
12270 LHSOPT: LHS->castAs<ObjCObjectPointerType>(),
12271 RHSOPT: RHS->castAs<ObjCObjectPointerType>(), BlockReturnType))
12272 return LHS;
12273 return {};
12274 }
12275 if (canAssignObjCInterfaces(LHSOPT: LHS->castAs<ObjCObjectPointerType>(),
12276 RHSOPT: RHS->castAs<ObjCObjectPointerType>()))
12277 return LHS;
12278 return {};
12279 case Type::Pipe:
12280 assert(LHS != RHS &&
12281 "Equivalent pipe types should have already been handled!");
12282 return {};
12283 case Type::ArrayParameter:
12284 assert(LHS != RHS &&
12285 "Equivalent ArrayParameter types should have already been handled!");
12286 return {};
12287 case Type::BitInt: {
12288 // Merge two bit-precise int types, while trying to preserve typedef info.
12289 bool LHSUnsigned = LHS->castAs<BitIntType>()->isUnsigned();
12290 bool RHSUnsigned = RHS->castAs<BitIntType>()->isUnsigned();
12291 unsigned LHSBits = LHS->castAs<BitIntType>()->getNumBits();
12292 unsigned RHSBits = RHS->castAs<BitIntType>()->getNumBits();
12293
12294 // Like unsigned/int, shouldn't have a type if they don't match.
12295 if (LHSUnsigned != RHSUnsigned)
12296 return {};
12297
12298 if (LHSBits != RHSBits)
12299 return {};
12300 return LHS;
12301 }
12302 case Type::HLSLAttributedResource: {
12303 const HLSLAttributedResourceType *LHSTy =
12304 LHS->castAs<HLSLAttributedResourceType>();
12305 const HLSLAttributedResourceType *RHSTy =
12306 RHS->castAs<HLSLAttributedResourceType>();
12307 assert(LHSTy->getWrappedType() == RHSTy->getWrappedType() &&
12308 LHSTy->getWrappedType()->isHLSLResourceType() &&
12309 "HLSLAttributedResourceType should always wrap __hlsl_resource_t");
12310
12311 if (LHSTy->getAttrs() == RHSTy->getAttrs() &&
12312 LHSTy->getContainedType() == RHSTy->getContainedType())
12313 return LHS;
12314 return {};
12315 }
12316 case Type::HLSLInlineSpirv:
12317 const HLSLInlineSpirvType *LHSTy = LHS->castAs<HLSLInlineSpirvType>();
12318 const HLSLInlineSpirvType *RHSTy = RHS->castAs<HLSLInlineSpirvType>();
12319
12320 if (LHSTy->getOpcode() == RHSTy->getOpcode() &&
12321 LHSTy->getSize() == RHSTy->getSize() &&
12322 LHSTy->getAlignment() == RHSTy->getAlignment()) {
12323 for (size_t I = 0; I < LHSTy->getOperands().size(); I++)
12324 if (LHSTy->getOperands()[I] != RHSTy->getOperands()[I])
12325 return {};
12326
12327 return LHS;
12328 }
12329 return {};
12330 }
12331
12332 llvm_unreachable("Invalid Type::Class!");
12333}
12334
12335bool ASTContext::mergeExtParameterInfo(
12336 const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType,
12337 bool &CanUseFirst, bool &CanUseSecond,
12338 SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &NewParamInfos) {
12339 assert(NewParamInfos.empty() && "param info list not empty");
12340 CanUseFirst = CanUseSecond = true;
12341 bool FirstHasInfo = FirstFnType->hasExtParameterInfos();
12342 bool SecondHasInfo = SecondFnType->hasExtParameterInfos();
12343
12344 // Fast path: if the first type doesn't have ext parameter infos,
12345 // we match if and only if the second type also doesn't have them.
12346 if (!FirstHasInfo && !SecondHasInfo)
12347 return true;
12348
12349 bool NeedParamInfo = false;
12350 size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size()
12351 : SecondFnType->getExtParameterInfos().size();
12352
12353 for (size_t I = 0; I < E; ++I) {
12354 FunctionProtoType::ExtParameterInfo FirstParam, SecondParam;
12355 if (FirstHasInfo)
12356 FirstParam = FirstFnType->getExtParameterInfo(I);
12357 if (SecondHasInfo)
12358 SecondParam = SecondFnType->getExtParameterInfo(I);
12359
12360 // Cannot merge unless everything except the noescape flag matches.
12361 if (FirstParam.withIsNoEscape(NoEscape: false) != SecondParam.withIsNoEscape(NoEscape: false))
12362 return false;
12363
12364 bool FirstNoEscape = FirstParam.isNoEscape();
12365 bool SecondNoEscape = SecondParam.isNoEscape();
12366 bool IsNoEscape = FirstNoEscape && SecondNoEscape;
12367 NewParamInfos.push_back(Elt: FirstParam.withIsNoEscape(NoEscape: IsNoEscape));
12368 if (NewParamInfos.back().getOpaqueValue())
12369 NeedParamInfo = true;
12370 if (FirstNoEscape != IsNoEscape)
12371 CanUseFirst = false;
12372 if (SecondNoEscape != IsNoEscape)
12373 CanUseSecond = false;
12374 }
12375
12376 if (!NeedParamInfo)
12377 NewParamInfos.clear();
12378
12379 return true;
12380}
12381
12382void ASTContext::ResetObjCLayout(const ObjCInterfaceDecl *D) {
12383 if (auto It = ObjCLayouts.find(Val: D); It != ObjCLayouts.end()) {
12384 It->second = nullptr;
12385 for (auto *SubClass : ObjCSubClasses.lookup(Val: D))
12386 ResetObjCLayout(D: SubClass);
12387 }
12388}
12389
12390/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
12391/// 'RHS' attributes and returns the merged version; including for function
12392/// return types.
12393QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
12394 QualType LHSCan = getCanonicalType(T: LHS),
12395 RHSCan = getCanonicalType(T: RHS);
12396 // If two types are identical, they are compatible.
12397 if (LHSCan == RHSCan)
12398 return LHS;
12399 if (RHSCan->isFunctionType()) {
12400 if (!LHSCan->isFunctionType())
12401 return {};
12402 QualType OldReturnType =
12403 cast<FunctionType>(Val: RHSCan.getTypePtr())->getReturnType();
12404 QualType NewReturnType =
12405 cast<FunctionType>(Val: LHSCan.getTypePtr())->getReturnType();
12406 QualType ResReturnType =
12407 mergeObjCGCQualifiers(LHS: NewReturnType, RHS: OldReturnType);
12408 if (ResReturnType.isNull())
12409 return {};
12410 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
12411 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
12412 // In either case, use OldReturnType to build the new function type.
12413 const auto *F = LHS->castAs<FunctionType>();
12414 if (const auto *FPT = cast<FunctionProtoType>(Val: F)) {
12415 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12416 EPI.ExtInfo = getFunctionExtInfo(t: LHS);
12417 QualType ResultType =
12418 getFunctionType(ResultTy: OldReturnType, Args: FPT->getParamTypes(), EPI);
12419 return ResultType;
12420 }
12421 }
12422 return {};
12423 }
12424
12425 // If the qualifiers are different, the types can still be merged.
12426 Qualifiers LQuals = LHSCan.getLocalQualifiers();
12427 Qualifiers RQuals = RHSCan.getLocalQualifiers();
12428
12429 if (LQuals.withoutObjCGCAttr() != RQuals.withoutObjCGCAttr()) {
12430 // Reject immediately, if anything but the GC qualifiers is different.
12431 return {};
12432 }
12433
12434 if (LQuals != RQuals) {
12435 // Exactly one GC qualifier difference is allowed: __strong is
12436 // okay if the other type has no GC qualifier but is an Objective
12437 // C object pointer (i.e. implicitly strong by default). We fix
12438 // this by pretending that the unqualified type was actually
12439 // qualified __strong.
12440 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
12441 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
12442 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
12443
12444 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
12445 return {};
12446
12447 if (GC_L == Qualifiers::Strong)
12448 return LHS;
12449 if (GC_R == Qualifiers::Strong)
12450 return RHS;
12451 return {};
12452 }
12453
12454 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
12455 QualType LHSBaseQT = LHS->castAs<ObjCObjectPointerType>()->getPointeeType();
12456 QualType RHSBaseQT = RHS->castAs<ObjCObjectPointerType>()->getPointeeType();
12457 QualType ResQT = mergeObjCGCQualifiers(LHS: LHSBaseQT, RHS: RHSBaseQT);
12458 if (ResQT == LHSBaseQT)
12459 return LHS;
12460 if (ResQT == RHSBaseQT)
12461 return RHS;
12462 }
12463 return {};
12464}
12465
12466//===----------------------------------------------------------------------===//
12467// Integer Predicates
12468//===----------------------------------------------------------------------===//
12469
12470unsigned ASTContext::getIntWidth(QualType T) const {
12471 if (const auto *ED = T->getAsEnumDecl())
12472 T = ED->getIntegerType();
12473 if (T->isBooleanType())
12474 return 1;
12475 if (const auto *EIT = T->getAs<BitIntType>())
12476 return EIT->getNumBits();
12477 // For builtin types, just use the standard type sizing method
12478 return (unsigned)getTypeSize(T);
12479}
12480
12481QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
12482 assert((T->hasIntegerRepresentation() || T->isEnumeralType() ||
12483 T->isFixedPointType()) &&
12484 "Unexpected type");
12485
12486 // Turn <4 x signed int> -> <4 x unsigned int>
12487 if (const auto *VTy = T->getAs<VectorType>())
12488 return getVectorType(vecType: getCorrespondingUnsignedType(T: VTy->getElementType()),
12489 NumElts: VTy->getNumElements(), VecKind: VTy->getVectorKind());
12490
12491 // For _BitInt, return an unsigned _BitInt with same width.
12492 if (const auto *EITy = T->getAs<BitIntType>())
12493 return getBitIntType(/*Unsigned=*/IsUnsigned: true, NumBits: EITy->getNumBits());
12494
12495 // For the overflow behavior types, construct a new unsigned variant
12496 if (const auto *OBT = T->getAs<OverflowBehaviorType>())
12497 return getOverflowBehaviorType(
12498 Kind: OBT->getBehaviorKind(),
12499 Underlying: getCorrespondingUnsignedType(T: OBT->getUnderlyingType()));
12500
12501 // For enums, get the underlying integer type of the enum, and let the general
12502 // integer type signchanging code handle it.
12503 if (const auto *ED = T->getAsEnumDecl())
12504 T = ED->getIntegerType();
12505
12506 switch (T->castAs<BuiltinType>()->getKind()) {
12507 case BuiltinType::Char_U:
12508 // Plain `char` is mapped to `unsigned char` even if it's already unsigned
12509 case BuiltinType::Char_S:
12510 case BuiltinType::SChar:
12511 case BuiltinType::Char8:
12512 return UnsignedCharTy;
12513 case BuiltinType::Short:
12514 return UnsignedShortTy;
12515 case BuiltinType::Int:
12516 return UnsignedIntTy;
12517 case BuiltinType::Long:
12518 return UnsignedLongTy;
12519 case BuiltinType::LongLong:
12520 return UnsignedLongLongTy;
12521 case BuiltinType::Int128:
12522 return UnsignedInt128Ty;
12523 // wchar_t is special. It is either signed or not, but when it's signed,
12524 // there's no matching "unsigned wchar_t". Therefore we return the unsigned
12525 // version of its underlying type instead.
12526 case BuiltinType::WChar_S:
12527 return getUnsignedWCharType();
12528
12529 case BuiltinType::ShortAccum:
12530 return UnsignedShortAccumTy;
12531 case BuiltinType::Accum:
12532 return UnsignedAccumTy;
12533 case BuiltinType::LongAccum:
12534 return UnsignedLongAccumTy;
12535 case BuiltinType::SatShortAccum:
12536 return SatUnsignedShortAccumTy;
12537 case BuiltinType::SatAccum:
12538 return SatUnsignedAccumTy;
12539 case BuiltinType::SatLongAccum:
12540 return SatUnsignedLongAccumTy;
12541 case BuiltinType::ShortFract:
12542 return UnsignedShortFractTy;
12543 case BuiltinType::Fract:
12544 return UnsignedFractTy;
12545 case BuiltinType::LongFract:
12546 return UnsignedLongFractTy;
12547 case BuiltinType::SatShortFract:
12548 return SatUnsignedShortFractTy;
12549 case BuiltinType::SatFract:
12550 return SatUnsignedFractTy;
12551 case BuiltinType::SatLongFract:
12552 return SatUnsignedLongFractTy;
12553 default:
12554 assert((T->hasUnsignedIntegerRepresentation() ||
12555 T->isUnsignedFixedPointType()) &&
12556 "Unexpected signed integer or fixed point type");
12557 return T;
12558 }
12559}
12560
12561QualType ASTContext::getCorrespondingSignedType(QualType T) const {
12562 assert((T->hasIntegerRepresentation() || T->isEnumeralType() ||
12563 T->isFixedPointType()) &&
12564 "Unexpected type");
12565
12566 // Turn <4 x unsigned int> -> <4 x signed int>
12567 if (const auto *VTy = T->getAs<VectorType>())
12568 return getVectorType(vecType: getCorrespondingSignedType(T: VTy->getElementType()),
12569 NumElts: VTy->getNumElements(), VecKind: VTy->getVectorKind());
12570
12571 // For _BitInt, return a signed _BitInt with same width.
12572 if (const auto *EITy = T->getAs<BitIntType>())
12573 return getBitIntType(/*Unsigned=*/IsUnsigned: false, NumBits: EITy->getNumBits());
12574
12575 // For enums, get the underlying integer type of the enum, and let the general
12576 // integer type signchanging code handle it.
12577 if (const auto *ED = T->getAsEnumDecl())
12578 T = ED->getIntegerType();
12579
12580 switch (T->castAs<BuiltinType>()->getKind()) {
12581 case BuiltinType::Char_S:
12582 // Plain `char` is mapped to `signed char` even if it's already signed
12583 case BuiltinType::Char_U:
12584 case BuiltinType::UChar:
12585 case BuiltinType::Char8:
12586 return SignedCharTy;
12587 case BuiltinType::UShort:
12588 return ShortTy;
12589 case BuiltinType::UInt:
12590 return IntTy;
12591 case BuiltinType::ULong:
12592 return LongTy;
12593 case BuiltinType::ULongLong:
12594 return LongLongTy;
12595 case BuiltinType::UInt128:
12596 return Int128Ty;
12597 // wchar_t is special. It is either unsigned or not, but when it's unsigned,
12598 // there's no matching "signed wchar_t". Therefore we return the signed
12599 // version of its underlying type instead.
12600 case BuiltinType::WChar_U:
12601 return getSignedWCharType();
12602
12603 case BuiltinType::UShortAccum:
12604 return ShortAccumTy;
12605 case BuiltinType::UAccum:
12606 return AccumTy;
12607 case BuiltinType::ULongAccum:
12608 return LongAccumTy;
12609 case BuiltinType::SatUShortAccum:
12610 return SatShortAccumTy;
12611 case BuiltinType::SatUAccum:
12612 return SatAccumTy;
12613 case BuiltinType::SatULongAccum:
12614 return SatLongAccumTy;
12615 case BuiltinType::UShortFract:
12616 return ShortFractTy;
12617 case BuiltinType::UFract:
12618 return FractTy;
12619 case BuiltinType::ULongFract:
12620 return LongFractTy;
12621 case BuiltinType::SatUShortFract:
12622 return SatShortFractTy;
12623 case BuiltinType::SatUFract:
12624 return SatFractTy;
12625 case BuiltinType::SatULongFract:
12626 return SatLongFractTy;
12627 default:
12628 assert(
12629 (T->hasSignedIntegerRepresentation() || T->isSignedFixedPointType()) &&
12630 "Unexpected signed integer or fixed point type");
12631 return T;
12632 }
12633}
12634
12635ASTMutationListener::~ASTMutationListener() = default;
12636
12637void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
12638 QualType ReturnType) {}
12639
12640//===----------------------------------------------------------------------===//
12641// Builtin Type Computation
12642//===----------------------------------------------------------------------===//
12643
12644/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
12645/// pointer over the consumed characters. This returns the resultant type. If
12646/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
12647/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
12648/// a vector of "i*".
12649///
12650/// RequiresICE is filled in on return to indicate whether the value is required
12651/// to be an Integer Constant Expression.
12652static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
12653 ASTContext::GetBuiltinTypeError &Error,
12654 bool &RequiresICE,
12655 bool AllowTypeModifiers) {
12656 // Modifiers.
12657 int HowLong = 0;
12658 bool Signed = false, Unsigned = false;
12659 bool IsChar = false, IsShort = false;
12660 bool IsLeast = false;
12661 RequiresICE = false;
12662
12663 // Read the prefixed modifiers first.
12664 bool Done = false;
12665 #ifndef NDEBUG
12666 bool IsSpecial = false;
12667 #endif
12668 while (!Done) {
12669 switch (*Str++) {
12670 default: Done = true; --Str; break;
12671 case 'I':
12672 RequiresICE = true;
12673 break;
12674 case 'S':
12675 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
12676 assert(!Signed && "Can't use 'S' modifier multiple times!");
12677 Signed = true;
12678 break;
12679 case 'U':
12680 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
12681 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
12682 Unsigned = true;
12683 break;
12684 case 'l':
12685 // This modifier represents the least-width type (e.g. uint_least8_t).
12686 assert(!IsLeast && "Can't use 'l' modifier multiple times!");
12687 IsLeast = true;
12688 break;
12689 case 'B':
12690 // This modifier represents int8 type (byte-width).
12691 assert(!IsSpecial &&
12692 "Can't use two 'N', 'W', 'Z', 'O', 'B', or 'T' modifiers!");
12693 assert(HowLong == 0 && "Can't use both 'L' and 'B' modifiers!");
12694#ifndef NDEBUG
12695 IsSpecial = true;
12696#endif
12697 IsChar = true;
12698 break;
12699 case 'T':
12700 // This modifier represents int16 type (short-width).
12701 assert(!IsSpecial &&
12702 "Can't use two 'N', 'W', 'Z', 'O', 'B', or 'T' modifiers!");
12703 assert(HowLong == 0 && "Can't use both 'L' and 'T' modifiers!");
12704#ifndef NDEBUG
12705 IsSpecial = true;
12706#endif
12707 IsShort = true;
12708 break;
12709 case 'L':
12710 assert(!IsSpecial &&
12711 "Can't use 'L' with 'W', 'N', 'Z', 'O', 'B', or 'T' modifiers");
12712 assert(HowLong <= 2 && "Can't have LLLL modifier");
12713 ++HowLong;
12714 break;
12715 case 'N':
12716 // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
12717 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12718 assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
12719 #ifndef NDEBUG
12720 IsSpecial = true;
12721 #endif
12722 if (Context.getTargetInfo().getLongWidth() == 32)
12723 ++HowLong;
12724 break;
12725 case 'W':
12726 // This modifier represents int64 type.
12727 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12728 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
12729 #ifndef NDEBUG
12730 IsSpecial = true;
12731 #endif
12732 switch (Context.getTargetInfo().getInt64Type()) {
12733 default:
12734 llvm_unreachable("Unexpected integer type");
12735 case TargetInfo::SignedLong:
12736 HowLong = 1;
12737 break;
12738 case TargetInfo::SignedLongLong:
12739 HowLong = 2;
12740 break;
12741 }
12742 break;
12743 case 'Z':
12744 // This modifier represents int32 type.
12745 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12746 assert(HowLong == 0 && "Can't use both 'L' and 'Z' modifiers!");
12747 #ifndef NDEBUG
12748 IsSpecial = true;
12749 #endif
12750 switch (Context.getTargetInfo().getIntTypeByWidth(BitWidth: 32, IsSigned: true)) {
12751 default:
12752 llvm_unreachable("Unexpected integer type");
12753 case TargetInfo::SignedInt:
12754 HowLong = 0;
12755 break;
12756 case TargetInfo::SignedLong:
12757 HowLong = 1;
12758 break;
12759 case TargetInfo::SignedLongLong:
12760 HowLong = 2;
12761 break;
12762 }
12763 break;
12764 case 'O':
12765 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12766 assert(HowLong == 0 && "Can't use both 'L' and 'O' modifiers!");
12767 #ifndef NDEBUG
12768 IsSpecial = true;
12769 #endif
12770 if (Context.getLangOpts().OpenCL)
12771 HowLong = 1;
12772 else
12773 HowLong = 2;
12774 break;
12775 }
12776 }
12777
12778 QualType Type;
12779
12780 // Read the base type.
12781 switch (*Str++) {
12782 default:
12783 llvm_unreachable("Unknown builtin type letter!");
12784 case 'x':
12785 assert(HowLong == 0 && !Signed && !Unsigned &&
12786 "Bad modifiers used with 'x'!");
12787 Type = Context.Float16Ty;
12788 break;
12789 case 'y':
12790 assert(HowLong == 0 && !Signed && !Unsigned &&
12791 "Bad modifiers used with 'y'!");
12792 Type = Context.BFloat16Ty;
12793 break;
12794 case 'v':
12795 assert(HowLong == 0 && !Signed && !Unsigned &&
12796 "Bad modifiers used with 'v'!");
12797 Type = Context.VoidTy;
12798 break;
12799 case 'h':
12800 assert(HowLong == 0 && !Signed && !Unsigned &&
12801 "Bad modifiers used with 'h'!");
12802 Type = Context.HalfTy;
12803 break;
12804 case 'f':
12805 assert(HowLong == 0 && !Signed && !Unsigned &&
12806 "Bad modifiers used with 'f'!");
12807 Type = Context.FloatTy;
12808 break;
12809 case 'd':
12810 assert(HowLong < 3 && !Signed && !Unsigned &&
12811 "Bad modifiers used with 'd'!");
12812 if (HowLong == 1)
12813 Type = Context.LongDoubleTy;
12814 else if (HowLong == 2)
12815 Type = Context.Float128Ty;
12816 else
12817 Type = Context.DoubleTy;
12818 break;
12819 case 's':
12820 assert(HowLong == 0 && "Bad modifiers used with 's'!");
12821 if (Unsigned)
12822 Type = Context.UnsignedShortTy;
12823 else
12824 Type = Context.ShortTy;
12825 break;
12826 case 'i':
12827 if (IsChar)
12828 Type = Unsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
12829 else if (IsShort)
12830 Type = Unsigned ? Context.UnsignedShortTy : Context.ShortTy;
12831 else if (HowLong == 3)
12832 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
12833 else if (HowLong == 2)
12834 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
12835 else if (HowLong == 1)
12836 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
12837 else
12838 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
12839 if (IsLeast)
12840 Type = Context.getLeastIntTypeForBitwidth(DestWidth: Context.getIntWidth(T: Type),
12841 /*Signed=*/!Unsigned);
12842 break;
12843 case 'c':
12844 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
12845 if (Signed)
12846 Type = Context.SignedCharTy;
12847 else if (Unsigned)
12848 Type = Context.UnsignedCharTy;
12849 else
12850 Type = Context.CharTy;
12851 break;
12852 case 'b': // boolean
12853 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
12854 Type = Context.BoolTy;
12855 break;
12856 case 'z': // size_t.
12857 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
12858 Type = Context.getSizeType();
12859 break;
12860 case 'w': // wchar_t.
12861 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
12862 Type = Context.getWideCharType();
12863 break;
12864 case 'F':
12865 Type = Context.getCFConstantStringType();
12866 break;
12867 case 'G':
12868 Type = Context.getObjCIdType();
12869 break;
12870 case 'H':
12871 Type = Context.getObjCSelType();
12872 break;
12873 case 'M':
12874 Type = Context.getObjCSuperType();
12875 break;
12876 case 'a':
12877 Type = Context.getBuiltinVaListType();
12878 assert(!Type.isNull() && "builtin va list type not initialized!");
12879 break;
12880 case 'A':
12881 // This is a "reference" to a va_list; however, what exactly
12882 // this means depends on how va_list is defined. There are two
12883 // different kinds of va_list: ones passed by value, and ones
12884 // passed by reference. An example of a by-value va_list is
12885 // x86, where va_list is a char*. An example of by-ref va_list
12886 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
12887 // we want this argument to be a char*&; for x86-64, we want
12888 // it to be a __va_list_tag*.
12889 Type = Context.getBuiltinVaListType();
12890 assert(!Type.isNull() && "builtin va list type not initialized!");
12891 if (Type->isArrayType())
12892 Type = Context.getArrayDecayedType(Ty: Type);
12893 else
12894 Type = Context.getLValueReferenceType(T: Type);
12895 break;
12896 case 'q': {
12897 char *End;
12898 unsigned NumElements = strtoul(nptr: Str, endptr: &End, base: 10);
12899 assert(End != Str && "Missing vector size");
12900 Str = End;
12901
12902 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
12903 RequiresICE, AllowTypeModifiers: false);
12904 assert(!RequiresICE && "Can't require vector ICE");
12905
12906 Type = Context.getScalableVectorType(EltTy: ElementType, NumElts: NumElements);
12907 break;
12908 }
12909 case 'Q': {
12910 switch (*Str++) {
12911 case 'a': {
12912 Type = Context.SveCountTy;
12913 break;
12914 }
12915 case 'b': {
12916 Type = Context.AMDGPUBufferRsrcTy;
12917 break;
12918 }
12919 case 'c': {
12920 Type = Context.AMDGPUFeaturePredicateTy;
12921 break;
12922 }
12923 case 't': {
12924 Type = Context.AMDGPUTextureTy;
12925 break;
12926 }
12927 case 'r': {
12928 Type = Context.HLSLResourceTy;
12929 break;
12930 }
12931 default:
12932 llvm_unreachable("Unexpected target builtin type");
12933 }
12934 break;
12935 }
12936 case 'V': {
12937 char *End;
12938 unsigned NumElements = strtoul(nptr: Str, endptr: &End, base: 10);
12939 assert(End != Str && "Missing vector size");
12940 Str = End;
12941
12942 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
12943 RequiresICE, AllowTypeModifiers: false);
12944 assert(!RequiresICE && "Can't require vector ICE");
12945
12946 // TODO: No way to make AltiVec vectors in builtins yet.
12947 Type = Context.getVectorType(vecType: ElementType, NumElts: NumElements, VecKind: VectorKind::Generic);
12948 break;
12949 }
12950 case 'E': {
12951 char *End;
12952
12953 unsigned NumElements = strtoul(nptr: Str, endptr: &End, base: 10);
12954 assert(End != Str && "Missing vector size");
12955
12956 Str = End;
12957
12958 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
12959 AllowTypeModifiers: false);
12960 Type = Context.getExtVectorType(vecType: ElementType, NumElts: NumElements);
12961 break;
12962 }
12963 case 'X': {
12964 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
12965 AllowTypeModifiers: false);
12966 assert(!RequiresICE && "Can't require complex ICE");
12967 Type = Context.getComplexType(T: ElementType);
12968 break;
12969 }
12970 case 'Y':
12971 Type = Context.getPointerDiffType();
12972 break;
12973 case 'P':
12974 Type = Context.getFILEType();
12975 if (Type.isNull()) {
12976 Error = ASTContext::GE_Missing_stdio;
12977 return {};
12978 }
12979 break;
12980 case 'J':
12981 if (Signed)
12982 Type = Context.getsigjmp_bufType();
12983 else
12984 Type = Context.getjmp_bufType();
12985
12986 if (Type.isNull()) {
12987 Error = ASTContext::GE_Missing_setjmp;
12988 return {};
12989 }
12990 break;
12991 case 'K':
12992 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
12993 Type = Context.getucontext_tType();
12994
12995 if (Type.isNull()) {
12996 Error = ASTContext::GE_Missing_ucontext;
12997 return {};
12998 }
12999 break;
13000 case 'p':
13001 Type = Context.getProcessIDType();
13002 break;
13003 case 'm':
13004 Type = Context.MFloat8Ty;
13005 break;
13006 }
13007
13008 // If there are modifiers and if we're allowed to parse them, go for it.
13009 Done = !AllowTypeModifiers;
13010 while (!Done) {
13011 switch (char c = *Str++) {
13012 default: Done = true; --Str; break;
13013 case '*':
13014 case '&': {
13015 // Both pointers and references can have their pointee types
13016 // qualified with an address space.
13017 char *End;
13018 unsigned AddrSpace = strtoul(nptr: Str, endptr: &End, base: 10);
13019 if (End != Str) {
13020 // Note AddrSpace == 0 is not the same as an unspecified address space.
13021 Type = Context.getAddrSpaceQualType(
13022 T: Type,
13023 AddressSpace: Context.getLangASForBuiltinAddressSpace(AS: AddrSpace));
13024 Str = End;
13025 }
13026 if (c == '*')
13027 Type = Context.getPointerType(T: Type);
13028 else
13029 Type = Context.getLValueReferenceType(T: Type);
13030 break;
13031 }
13032 // FIXME: There's no way to have a built-in with an rvalue ref arg.
13033 case 'C':
13034 Type = Type.withConst();
13035 break;
13036 case 'D':
13037 Type = Context.getVolatileType(T: Type);
13038 break;
13039 case 'R':
13040 Type = Type.withRestrict();
13041 break;
13042 }
13043 }
13044
13045 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
13046 "Integer constant 'I' type must be an integer");
13047
13048 return Type;
13049}
13050
13051// On some targets such as PowerPC, some of the builtins are defined with custom
13052// type descriptors for target-dependent types. These descriptors are decoded in
13053// other functions, but it may be useful to be able to fall back to default
13054// descriptor decoding to define builtins mixing target-dependent and target-
13055// independent types. This function allows decoding one type descriptor with
13056// default decoding.
13057QualType ASTContext::DecodeTypeStr(const char *&Str, const ASTContext &Context,
13058 GetBuiltinTypeError &Error, bool &RequireICE,
13059 bool AllowTypeModifiers) const {
13060 return DecodeTypeFromStr(Str, Context, Error, RequiresICE&: RequireICE, AllowTypeModifiers);
13061}
13062
13063/// GetBuiltinType - Return the type for the specified builtin.
13064QualType ASTContext::GetBuiltinType(unsigned Id,
13065 GetBuiltinTypeError &Error,
13066 unsigned *IntegerConstantArgs) const {
13067 const char *TypeStr = BuiltinInfo.getTypeString(ID: Id);
13068 if (TypeStr[0] == '\0') {
13069 Error = GE_Missing_type;
13070 return {};
13071 }
13072
13073 SmallVector<QualType, 8> ArgTypes;
13074
13075 bool RequiresICE = false;
13076 Error = GE_None;
13077 QualType ResType = DecodeTypeFromStr(Str&: TypeStr, Context: *this, Error,
13078 RequiresICE, AllowTypeModifiers: true);
13079 if (Error != GE_None)
13080 return {};
13081
13082 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
13083
13084 while (TypeStr[0] && TypeStr[0] != '.') {
13085 QualType Ty = DecodeTypeFromStr(Str&: TypeStr, Context: *this, Error, RequiresICE, AllowTypeModifiers: true);
13086 if (Error != GE_None)
13087 return {};
13088
13089 // If this argument is required to be an IntegerConstantExpression and the
13090 // caller cares, fill in the bitmask we return.
13091 if (RequiresICE && IntegerConstantArgs)
13092 *IntegerConstantArgs |= 1 << ArgTypes.size();
13093
13094 // Do array -> pointer decay. The builtin should use the decayed type.
13095 if (Ty->isArrayType())
13096 Ty = getArrayDecayedType(Ty);
13097
13098 ArgTypes.push_back(Elt: Ty);
13099 }
13100
13101 if (Id == Builtin::BI__GetExceptionInfo)
13102 return {};
13103
13104 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
13105 "'.' should only occur at end of builtin type list!");
13106
13107 bool Variadic = (TypeStr[0] == '.');
13108
13109 FunctionType::ExtInfo EI(Target->getDefaultCallingConv());
13110 if (BuiltinInfo.isNoReturn(ID: Id))
13111 EI = EI.withNoReturn(noReturn: true);
13112
13113 // We really shouldn't be making a no-proto type here.
13114 if (ArgTypes.empty() && Variadic && !getLangOpts().requiresStrictPrototypes())
13115 return getFunctionNoProtoType(ResultTy: ResType, Info: EI);
13116
13117 FunctionProtoType::ExtProtoInfo EPI;
13118 EPI.ExtInfo = EI;
13119 EPI.Variadic = Variadic;
13120 if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(ID: Id))
13121 EPI.ExceptionSpec.Type =
13122 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
13123
13124 return getFunctionType(ResultTy: ResType, Args: ArgTypes, EPI);
13125}
13126
13127static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
13128 const FunctionDecl *FD) {
13129 if (!FD->isExternallyVisible())
13130 return GVA_Internal;
13131
13132 // Non-user-provided functions get emitted as weak definitions with every
13133 // use, no matter whether they've been explicitly instantiated etc.
13134 if (!FD->isUserProvided())
13135 return GVA_DiscardableODR;
13136
13137 GVALinkage External;
13138 switch (FD->getTemplateSpecializationKind()) {
13139 case TSK_Undeclared:
13140 case TSK_ExplicitSpecialization:
13141 External = GVA_StrongExternal;
13142 break;
13143
13144 case TSK_ExplicitInstantiationDefinition:
13145 return GVA_StrongODR;
13146
13147 // C++11 [temp.explicit]p10:
13148 // [ Note: The intent is that an inline function that is the subject of
13149 // an explicit instantiation declaration will still be implicitly
13150 // instantiated when used so that the body can be considered for
13151 // inlining, but that no out-of-line copy of the inline function would be
13152 // generated in the translation unit. -- end note ]
13153 case TSK_ExplicitInstantiationDeclaration:
13154 return GVA_AvailableExternally;
13155
13156 case TSK_ImplicitInstantiation:
13157 External = GVA_DiscardableODR;
13158 break;
13159 }
13160
13161 if (!FD->isInlined())
13162 return External;
13163
13164 if ((!Context.getLangOpts().CPlusPlus &&
13165 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13166 !FD->hasAttr<DLLExportAttr>()) ||
13167 FD->hasAttr<GNUInlineAttr>()) {
13168 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
13169
13170 // GNU or C99 inline semantics. Determine whether this symbol should be
13171 // externally visible.
13172 if (auto *Def = FD->getDefinition();
13173 Def && Def->isInlineDefinitionExternallyVisible())
13174 return External;
13175
13176 // C99 inline semantics, where the symbol is not externally visible.
13177 return GVA_AvailableExternally;
13178 }
13179
13180 // Functions specified with extern and inline in -fms-compatibility mode
13181 // forcibly get emitted. While the body of the function cannot be later
13182 // replaced, the function definition cannot be discarded.
13183 if (FD->isMSExternInline())
13184 return GVA_StrongODR;
13185
13186 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13187 isa<CXXConstructorDecl>(Val: FD) &&
13188 cast<CXXConstructorDecl>(Val: FD)->isInheritingConstructor() &&
13189 !FD->hasAttr<DLLExportAttr>()) {
13190 // Both Clang and MSVC implement inherited constructors as forwarding
13191 // thunks that delegate to the base constructor. Keep non-dllexport
13192 // inheriting constructor thunks internal since they are not needed
13193 // outside the translation unit.
13194 //
13195 // dllexport inherited constructors are exempted so they are externally
13196 // visible, matching MSVC's export behavior. Inherited constructors
13197 // whose parameters prevent ABI-compatible forwarding (e.g. callee-
13198 // cleanup types) are excluded from export in Sema to avoid silent
13199 // runtime mismatches.
13200 return GVA_Internal;
13201 }
13202
13203 return GVA_DiscardableODR;
13204}
13205
13206static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context,
13207 const Decl *D, GVALinkage L) {
13208 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
13209 // dllexport/dllimport on inline functions.
13210 if (D->hasAttr<DLLImportAttr>()) {
13211 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
13212 return GVA_AvailableExternally;
13213 } else if (D->hasAttr<DLLExportAttr>()) {
13214 if (L == GVA_DiscardableODR)
13215 return GVA_StrongODR;
13216 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice) {
13217 // Device-side functions with __global__ attribute must always be
13218 // visible externally so they can be launched from host.
13219 if (D->hasAttr<CUDAGlobalAttr>() &&
13220 (L == GVA_DiscardableODR || L == GVA_Internal))
13221 return GVA_StrongODR;
13222 // Single source offloading languages like CUDA/HIP need to be able to
13223 // access static device variables from host code of the same compilation
13224 // unit. This is done by externalizing the static variable with a shared
13225 // name between the host and device compilation which is the same for the
13226 // same compilation unit whereas different among different compilation
13227 // units.
13228 if (Context.shouldExternalize(D))
13229 return GVA_StrongExternal;
13230 }
13231 return L;
13232}
13233
13234/// Adjust the GVALinkage for a declaration based on what an external AST source
13235/// knows about whether there can be other definitions of this declaration.
13236static GVALinkage
13237adjustGVALinkageForExternalDefinitionKind(const ASTContext &Ctx, const Decl *D,
13238 GVALinkage L) {
13239 ExternalASTSource *Source = Ctx.getExternalSource();
13240 if (!Source)
13241 return L;
13242
13243 switch (Source->hasExternalDefinitions(D)) {
13244 case ExternalASTSource::EK_Never:
13245 // Other translation units rely on us to provide the definition.
13246 if (L == GVA_DiscardableODR)
13247 return GVA_StrongODR;
13248 break;
13249
13250 case ExternalASTSource::EK_Always:
13251 return GVA_AvailableExternally;
13252
13253 case ExternalASTSource::EK_ReplyHazy:
13254 break;
13255 }
13256 return L;
13257}
13258
13259GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
13260 return adjustGVALinkageForExternalDefinitionKind(Ctx: *this, D: FD,
13261 L: adjustGVALinkageForAttributes(Context: *this, D: FD,
13262 L: basicGVALinkageForFunction(Context: *this, FD)));
13263}
13264
13265static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
13266 const VarDecl *VD) {
13267 // As an extension for interactive REPLs, make sure constant variables are
13268 // only emitted once instead of LinkageComputer::getLVForNamespaceScopeDecl
13269 // marking them as internal.
13270 if (Context.getLangOpts().CPlusPlus &&
13271 Context.getLangOpts().IncrementalExtensions &&
13272 VD->getType().isConstQualified() &&
13273 !VD->getType().isVolatileQualified() && !VD->isInline() &&
13274 !isa<VarTemplateSpecializationDecl>(Val: VD) && !VD->getDescribedVarTemplate())
13275 return GVA_DiscardableODR;
13276
13277 if (!VD->isExternallyVisible())
13278 return GVA_Internal;
13279
13280 if (VD->isStaticLocal()) {
13281 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
13282 while (LexicalContext && !isa<FunctionDecl>(Val: LexicalContext))
13283 LexicalContext = LexicalContext->getLexicalParent();
13284
13285 // ObjC Blocks can create local variables that don't have a FunctionDecl
13286 // LexicalContext.
13287 if (!LexicalContext)
13288 return GVA_DiscardableODR;
13289
13290 // Otherwise, let the static local variable inherit its linkage from the
13291 // nearest enclosing function.
13292 auto StaticLocalLinkage =
13293 Context.GetGVALinkageForFunction(FD: cast<FunctionDecl>(Val: LexicalContext));
13294
13295 // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
13296 // be emitted in any object with references to the symbol for the object it
13297 // contains, whether inline or out-of-line."
13298 // Similar behavior is observed with MSVC. An alternative ABI could use
13299 // StrongODR/AvailableExternally to match the function, but none are
13300 // known/supported currently.
13301 if (StaticLocalLinkage == GVA_StrongODR ||
13302 StaticLocalLinkage == GVA_AvailableExternally)
13303 return GVA_DiscardableODR;
13304 return StaticLocalLinkage;
13305 }
13306
13307 // MSVC treats in-class initialized static data members as definitions.
13308 // By giving them non-strong linkage, out-of-line definitions won't
13309 // cause link errors.
13310 if (Context.isMSStaticDataMemberInlineDefinition(VD))
13311 return GVA_DiscardableODR;
13312
13313 // Most non-template variables have strong linkage; inline variables are
13314 // linkonce_odr or (occasionally, for compatibility) weak_odr.
13315 GVALinkage StrongLinkage;
13316 switch (Context.getInlineVariableDefinitionKind(VD)) {
13317 case ASTContext::InlineVariableDefinitionKind::None:
13318 StrongLinkage = GVA_StrongExternal;
13319 break;
13320 case ASTContext::InlineVariableDefinitionKind::Weak:
13321 case ASTContext::InlineVariableDefinitionKind::WeakUnknown:
13322 StrongLinkage = GVA_DiscardableODR;
13323 break;
13324 case ASTContext::InlineVariableDefinitionKind::Strong:
13325 StrongLinkage = GVA_StrongODR;
13326 break;
13327 }
13328
13329 switch (VD->getTemplateSpecializationKind()) {
13330 case TSK_Undeclared:
13331 return StrongLinkage;
13332
13333 case TSK_ExplicitSpecialization:
13334 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13335 VD->isStaticDataMember()
13336 ? GVA_StrongODR
13337 : StrongLinkage;
13338
13339 case TSK_ExplicitInstantiationDefinition:
13340 return GVA_StrongODR;
13341
13342 case TSK_ExplicitInstantiationDeclaration:
13343 return GVA_AvailableExternally;
13344
13345 case TSK_ImplicitInstantiation:
13346 return GVA_DiscardableODR;
13347 }
13348
13349 llvm_unreachable("Invalid Linkage!");
13350}
13351
13352GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) const {
13353 return adjustGVALinkageForExternalDefinitionKind(Ctx: *this, D: VD,
13354 L: adjustGVALinkageForAttributes(Context: *this, D: VD,
13355 L: basicGVALinkageForVariable(Context: *this, VD)));
13356}
13357
13358bool ASTContext::DeclMustBeEmitted(const Decl *D) {
13359 if (const auto *VD = dyn_cast<VarDecl>(Val: D)) {
13360 if (!VD->isFileVarDecl())
13361 return false;
13362 // Global named register variables (GNU extension) are never emitted.
13363 if (VD->getStorageClass() == SC_Register)
13364 return false;
13365 if (VD->getDescribedVarTemplate() ||
13366 isa<VarTemplatePartialSpecializationDecl>(Val: VD))
13367 return false;
13368 } else if (const auto *FD = dyn_cast<FunctionDecl>(Val: D)) {
13369 // We never need to emit an uninstantiated function template.
13370 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
13371 return false;
13372 } else if (isa<PragmaCommentDecl>(Val: D))
13373 return true;
13374 else if (isa<PragmaDetectMismatchDecl>(Val: D))
13375 return true;
13376 else if (isa<OMPRequiresDecl>(Val: D))
13377 return true;
13378 else if (isa<OMPThreadPrivateDecl>(Val: D))
13379 return !D->getDeclContext()->isDependentContext();
13380 else if (isa<OMPAllocateDecl>(Val: D))
13381 return !D->getDeclContext()->isDependentContext();
13382 else if (isa<OMPDeclareReductionDecl>(Val: D) || isa<OMPDeclareMapperDecl>(Val: D))
13383 return !D->getDeclContext()->isDependentContext();
13384 else if (isa<ImportDecl>(Val: D))
13385 return true;
13386 else
13387 return false;
13388
13389 // If this is a member of a class template, we do not need to emit it.
13390 if (D->getDeclContext()->isDependentContext())
13391 return false;
13392
13393 // Weak references don't produce any output by themselves.
13394 if (D->hasAttr<WeakRefAttr>())
13395 return false;
13396
13397 // SYCL device compilation requires that functions defined with the
13398 // sycl_kernel_entry_point or sycl_external attributes be emitted. All
13399 // other entities are emitted only if they are used by a function
13400 // defined with one of those attributes.
13401 if (LangOpts.SYCLIsDevice)
13402 return isa<FunctionDecl>(Val: D) && (D->hasAttr<SYCLKernelEntryPointAttr>() ||
13403 D->hasAttr<SYCLExternalAttr>());
13404
13405 // Aliases and used decls are required.
13406 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
13407 return true;
13408
13409 if (const auto *FD = dyn_cast<FunctionDecl>(Val: D)) {
13410 // Forward declarations aren't required.
13411 if (!FD->doesThisDeclarationHaveABody())
13412 return FD->doesDeclarationForceExternallyVisibleDefinition();
13413
13414 // Constructors and destructors are required.
13415 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
13416 return true;
13417
13418 // The key function for a class is required. This rule only comes
13419 // into play when inline functions can be key functions, though.
13420 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
13421 if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: FD)) {
13422 const CXXRecordDecl *RD = MD->getParent();
13423 if (MD->isOutOfLine() && RD->isDynamicClass()) {
13424 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
13425 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
13426 return true;
13427 }
13428 }
13429 }
13430
13431 GVALinkage Linkage = GetGVALinkageForFunction(FD);
13432
13433 // static, static inline, always_inline, and extern inline functions can
13434 // always be deferred. Normal inline functions can be deferred in C99/C++.
13435 // Implicit template instantiations can also be deferred in C++.
13436 return !isDiscardableGVALinkage(L: Linkage);
13437 }
13438
13439 const auto *VD = cast<VarDecl>(Val: D);
13440 assert(VD->isFileVarDecl() && "Expected file scoped var");
13441
13442 // If the decl is marked as `declare target to`, it should be emitted for the
13443 // host and for the device.
13444 if (LangOpts.OpenMP &&
13445 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
13446 return true;
13447
13448 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
13449 !isMSStaticDataMemberInlineDefinition(VD))
13450 return false;
13451
13452 if (VD->shouldEmitInExternalSource())
13453 return false;
13454
13455 // Variables that can be needed in other TUs are required.
13456 auto Linkage = GetGVALinkageForVariable(VD);
13457 if (!isDiscardableGVALinkage(L: Linkage))
13458 return true;
13459
13460 // We never need to emit a variable that is available in another TU.
13461 if (Linkage == GVA_AvailableExternally)
13462 return false;
13463
13464 // Variables that have destruction with side-effects are required.
13465 if (VD->needsDestruction(Ctx: *this))
13466 return true;
13467
13468 // Variables that have initialization with side-effects are required.
13469 if (VD->hasInitWithSideEffects())
13470 return true;
13471
13472 // Likewise, variables with tuple-like bindings are required if their
13473 // bindings have side-effects.
13474 if (const auto *DD = dyn_cast<DecompositionDecl>(Val: VD)) {
13475 for (const auto *BD : DD->flat_bindings())
13476 if (const auto *BindingVD = BD->getHoldingVar())
13477 if (DeclMustBeEmitted(D: BindingVD))
13478 return true;
13479 }
13480
13481 return false;
13482}
13483
13484template <typename AttrT> static bool hasImplicitAttr(const ValueDecl *D) {
13485 if (auto *A = D->getAttr<AttrT>())
13486 return A->isImplicit();
13487 return D->isImplicit();
13488}
13489
13490bool ASTContext::shouldEmitCUDADecl(const ValueDecl *D) const {
13491 assert(LangOpts.CUDA && "Should not be called by non-CUDA languages");
13492 assert((isa<FunctionDecl>(D) || isa<VarDecl>(D)) &&
13493 "Expected Variable or Function");
13494
13495 if (const auto *VD = dyn_cast<VarDecl>(Val: D)) {
13496 // We need to emit host-side 'shadows' for all global device-side variables
13497 // because the CUDA runtime needs their size and host-side address in order
13498 // to provide access to their device-side incarnations.
13499 return !LangOpts.CUDAIsDevice || VD->hasAttr<CUDADeviceAttr>() ||
13500 VD->hasAttr<CUDAConstantAttr>() || VD->hasAttr<CUDASharedAttr>() ||
13501 VD->getType()->isCUDADeviceBuiltinSurfaceType() ||
13502 VD->getType()->isCUDADeviceBuiltinTextureType();
13503 }
13504
13505 const auto *FD = cast<FunctionDecl>(Val: D);
13506 // Device-only functions are the only things we skip on the host.
13507 if (!LangOpts.CUDAIsDevice)
13508 return FD->hasAttr<CUDAHostAttr>() || !FD->hasAttr<CUDADeviceAttr>();
13509
13510 // Non-constexpr non-lambda implicit host device functions are not emitted
13511 // unless they are used on device side.
13512 return (FD->hasAttr<CUDADeviceAttr>() &&
13513 !(LangOpts.OffloadImplicitHostDeviceTemplates &&
13514 hasImplicitAttr<CUDAHostAttr>(D: FD) &&
13515 hasImplicitAttr<CUDADeviceAttr>(D: FD) && !FD->isConstexpr() &&
13516 !isLambdaCallOperator(DC: FD) &&
13517 !CUDAImplicitHostDeviceFunUsedByDevice.count(V: FD))) ||
13518 FD->hasAttr<CUDAGlobalAttr>() ||
13519 (LangOpts.HIPStdPar && !FD->hasAttr<CUDAHostAttr>());
13520}
13521
13522void ASTContext::forEachMultiversionedFunctionVersion(
13523 const FunctionDecl *FD,
13524 llvm::function_ref<void(FunctionDecl *)> Pred) const {
13525 assert(FD->isMultiVersion() && "Only valid for multiversioned functions");
13526 llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls;
13527 FD = FD->getMostRecentDecl();
13528 // FIXME: The order of traversal here matters and depends on the order of
13529 // lookup results, which happens to be (mostly) oldest-to-newest, but we
13530 // shouldn't rely on that.
13531 for (auto *CurDecl :
13532 FD->getDeclContext()->getRedeclContext()->lookup(Name: FD->getDeclName())) {
13533 FunctionDecl *CurFD = CurDecl->getAsFunction()->getMostRecentDecl();
13534 if (CurFD && hasSameType(T1: CurFD->getType(), T2: FD->getType()) &&
13535 SeenDecls.insert(V: CurFD).second) {
13536 Pred(CurFD);
13537 }
13538 }
13539}
13540
13541CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
13542 bool IsCXXMethod) const {
13543 // Pass through to the C++ ABI object
13544 if (IsCXXMethod)
13545 return ABI->getDefaultMethodCallConv(isVariadic: IsVariadic);
13546
13547 switch (LangOpts.getDefaultCallingConv()) {
13548 case LangOptions::DCC_None:
13549 break;
13550 case LangOptions::DCC_CDecl:
13551 return CC_C;
13552 case LangOptions::DCC_FastCall:
13553 if (getTargetInfo().hasFeature(Feature: "sse2") && !IsVariadic)
13554 return CC_X86FastCall;
13555 break;
13556 case LangOptions::DCC_StdCall:
13557 if (!IsVariadic)
13558 return CC_X86StdCall;
13559 break;
13560 case LangOptions::DCC_VectorCall:
13561 // __vectorcall cannot be applied to variadic functions.
13562 if (!IsVariadic)
13563 return CC_X86VectorCall;
13564 break;
13565 case LangOptions::DCC_RegCall:
13566 // __regcall cannot be applied to variadic functions.
13567 if (!IsVariadic)
13568 return CC_X86RegCall;
13569 break;
13570 case LangOptions::DCC_RtdCall:
13571 if (!IsVariadic)
13572 return CC_M68kRTD;
13573 break;
13574 }
13575 return Target->getDefaultCallingConv();
13576}
13577
13578bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
13579 // Pass through to the C++ ABI object
13580 return ABI->isNearlyEmpty(RD);
13581}
13582
13583VTableContextBase *ASTContext::getVTableContext() {
13584 if (!VTContext) {
13585 auto ABI = Target->getCXXABI();
13586 if (ABI.isMicrosoft())
13587 VTContext.reset(p: new MicrosoftVTableContext(*this));
13588 else {
13589 VTContext.reset(p: new ItaniumVTableContext(*this));
13590 }
13591 }
13592 return VTContext.get();
13593}
13594
13595MangleContext *ASTContext::createMangleContext(const TargetInfo *T) {
13596 if (!T)
13597 T = Target;
13598 switch (T->getCXXABI().getKind()) {
13599 case TargetCXXABI::AppleARM64:
13600 case TargetCXXABI::Fuchsia:
13601 case TargetCXXABI::GenericAArch64:
13602 case TargetCXXABI::GenericItanium:
13603 case TargetCXXABI::GenericARM:
13604 case TargetCXXABI::GenericMIPS:
13605 case TargetCXXABI::iOS:
13606 case TargetCXXABI::WebAssembly:
13607 case TargetCXXABI::WatchOS:
13608 case TargetCXXABI::XL:
13609 return ItaniumMangleContext::create(Context&: *this, Diags&: getDiagnostics());
13610 case TargetCXXABI::Microsoft:
13611 return MicrosoftMangleContext::create(Context&: *this, Diags&: getDiagnostics());
13612 }
13613 llvm_unreachable("Unsupported ABI");
13614}
13615
13616MangleContext *ASTContext::createDeviceMangleContext(const TargetInfo &T) {
13617 assert(T.getCXXABI().getKind() != TargetCXXABI::Microsoft &&
13618 "Device mangle context does not support Microsoft mangling.");
13619 switch (T.getCXXABI().getKind()) {
13620 case TargetCXXABI::AppleARM64:
13621 case TargetCXXABI::Fuchsia:
13622 case TargetCXXABI::GenericAArch64:
13623 case TargetCXXABI::GenericItanium:
13624 case TargetCXXABI::GenericARM:
13625 case TargetCXXABI::GenericMIPS:
13626 case TargetCXXABI::iOS:
13627 case TargetCXXABI::WebAssembly:
13628 case TargetCXXABI::WatchOS:
13629 case TargetCXXABI::XL:
13630 return ItaniumMangleContext::create(
13631 Context&: *this, Diags&: getDiagnostics(),
13632 Discriminator: [](ASTContext &, const NamedDecl *ND) -> UnsignedOrNone {
13633 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: ND))
13634 return RD->getDeviceLambdaManglingNumber();
13635 return std::nullopt;
13636 },
13637 /*IsAux=*/true);
13638 case TargetCXXABI::Microsoft:
13639 return MicrosoftMangleContext::create(Context&: *this, Diags&: getDiagnostics(),
13640 /*IsAux=*/true);
13641 }
13642 llvm_unreachable("Unsupported ABI");
13643}
13644
13645MangleContext *ASTContext::cudaNVInitDeviceMC() {
13646 // If the host and device have different C++ ABIs, mark it as the device
13647 // mangle context so that the mangling needs to retrieve the additional
13648 // device lambda mangling number instead of the regular host one.
13649 if (getAuxTargetInfo() && getTargetInfo().getCXXABI().isMicrosoft() &&
13650 getAuxTargetInfo()->getCXXABI().isItaniumFamily()) {
13651 return createDeviceMangleContext(T: *getAuxTargetInfo());
13652 }
13653
13654 return createMangleContext(T: getAuxTargetInfo());
13655}
13656
13657CXXABI::~CXXABI() = default;
13658
13659size_t ASTContext::getSideTableAllocatedMemory() const {
13660 return ASTRecordLayouts.getMemorySize() +
13661 llvm::capacity_in_bytes(X: ObjCLayouts) +
13662 llvm::capacity_in_bytes(X: KeyFunctions) +
13663 llvm::capacity_in_bytes(X: ObjCImpls) +
13664 llvm::capacity_in_bytes(X: BlockVarCopyInits) +
13665 DeclAttrAllocator.getTotalMemory() +
13666 llvm::capacity_in_bytes(X: TemplateOrInstantiation) +
13667 llvm::capacity_in_bytes(X: InstantiatedFromUsingDecl) +
13668 llvm::capacity_in_bytes(X: InstantiatedFromUsingShadowDecl) +
13669 llvm::capacity_in_bytes(X: InstantiatedFromUnnamedFieldDecl) +
13670 llvm::capacity_in_bytes(X: OverriddenMethods) +
13671 llvm::capacity_in_bytes(X: Types) +
13672 llvm::capacity_in_bytes(x: VariableArrayTypes);
13673}
13674
13675/// getIntTypeForBitwidth -
13676/// sets integer QualTy according to specified details:
13677/// bitwidth, signed/unsigned.
13678/// Returns empty type if there is no appropriate target types.
13679QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
13680 unsigned Signed) const {
13681 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(BitWidth: DestWidth, IsSigned: Signed);
13682 CanQualType QualTy = getFromTargetType(Type: Ty);
13683 if (!QualTy && DestWidth == 128)
13684 return Signed ? Int128Ty : UnsignedInt128Ty;
13685 return QualTy;
13686}
13687
13688QualType ASTContext::getLeastIntTypeForBitwidth(unsigned DestWidth,
13689 unsigned Signed) const {
13690 return getFromTargetType(
13691 Type: getTargetInfo().getLeastIntTypeByWidth(BitWidth: DestWidth, IsSigned: Signed));
13692}
13693
13694/// getRealTypeForBitwidth -
13695/// sets floating point QualTy according to specified bitwidth.
13696/// Returns empty type if there is no appropriate target types.
13697QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth,
13698 FloatModeKind ExplicitType) const {
13699 FloatModeKind Ty =
13700 getTargetInfo().getRealTypeByWidth(BitWidth: DestWidth, ExplicitType);
13701 switch (Ty) {
13702 case FloatModeKind::Half:
13703 return HalfTy;
13704 case FloatModeKind::Float:
13705 return FloatTy;
13706 case FloatModeKind::Double:
13707 return DoubleTy;
13708 case FloatModeKind::LongDouble:
13709 return LongDoubleTy;
13710 case FloatModeKind::Float128:
13711 return Float128Ty;
13712 case FloatModeKind::Ibm128:
13713 return Ibm128Ty;
13714 case FloatModeKind::NoFloat:
13715 return {};
13716 }
13717
13718 llvm_unreachable("Unhandled TargetInfo::RealType value");
13719}
13720
13721void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
13722 if (Number <= 1)
13723 return;
13724
13725 MangleNumbers[ND] = Number;
13726
13727 if (Listener)
13728 Listener->AddedManglingNumber(D: ND, Number);
13729}
13730
13731unsigned ASTContext::getManglingNumber(const NamedDecl *ND,
13732 bool ForAuxTarget) const {
13733 auto I = MangleNumbers.find(Key: ND);
13734 unsigned Res = I != MangleNumbers.end() ? I->second : 1;
13735 // CUDA/HIP host compilation encodes host and device mangling numbers
13736 // as lower and upper half of 32 bit integer.
13737 if (LangOpts.CUDA && !LangOpts.CUDAIsDevice) {
13738 Res = ForAuxTarget ? Res >> 16 : Res & 0xFFFF;
13739 } else {
13740 assert(!ForAuxTarget && "Only CUDA/HIP host compilation supports mangling "
13741 "number for aux target");
13742 }
13743 return Res > 1 ? Res : 1;
13744}
13745
13746void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
13747 if (Number <= 1)
13748 return;
13749
13750 StaticLocalNumbers[VD] = Number;
13751
13752 if (Listener)
13753 Listener->AddedStaticLocalNumbers(D: VD, Number);
13754}
13755
13756unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
13757 auto I = StaticLocalNumbers.find(Key: VD);
13758 return I != StaticLocalNumbers.end() ? I->second : 1;
13759}
13760
13761void ASTContext::setIsDestroyingOperatorDelete(const FunctionDecl *FD,
13762 bool IsDestroying) {
13763 if (!IsDestroying) {
13764 assert(!DestroyingOperatorDeletes.contains(FD->getCanonicalDecl()));
13765 return;
13766 }
13767 DestroyingOperatorDeletes.insert(V: FD->getCanonicalDecl());
13768}
13769
13770bool ASTContext::isDestroyingOperatorDelete(const FunctionDecl *FD) const {
13771 return DestroyingOperatorDeletes.contains(V: FD->getCanonicalDecl());
13772}
13773
13774void ASTContext::setIsTypeAwareOperatorNewOrDelete(const FunctionDecl *FD,
13775 bool IsTypeAware) {
13776 if (!IsTypeAware) {
13777 assert(!TypeAwareOperatorNewAndDeletes.contains(FD->getCanonicalDecl()));
13778 return;
13779 }
13780 TypeAwareOperatorNewAndDeletes.insert(V: FD->getCanonicalDecl());
13781}
13782
13783bool ASTContext::isTypeAwareOperatorNewOrDelete(const FunctionDecl *FD) const {
13784 return TypeAwareOperatorNewAndDeletes.contains(V: FD->getCanonicalDecl());
13785}
13786
13787void ASTContext::addOperatorDeleteForVDtor(const CXXDestructorDecl *Dtor,
13788 FunctionDecl *OperatorDelete,
13789 OperatorDeleteKind K) const {
13790 switch (K) {
13791 case OperatorDeleteKind::Regular:
13792 OperatorDeletesForVirtualDtor[Dtor->getCanonicalDecl()] = OperatorDelete;
13793 break;
13794 case OperatorDeleteKind::GlobalRegular:
13795 GlobalOperatorDeletesForVirtualDtor[Dtor->getCanonicalDecl()] =
13796 OperatorDelete;
13797 break;
13798 case OperatorDeleteKind::Array:
13799 ArrayOperatorDeletesForVirtualDtor[Dtor->getCanonicalDecl()] =
13800 OperatorDelete;
13801 break;
13802 case OperatorDeleteKind::ArrayGlobal:
13803 GlobalArrayOperatorDeletesForVirtualDtor[Dtor->getCanonicalDecl()] =
13804 OperatorDelete;
13805 break;
13806 }
13807}
13808
13809bool ASTContext::dtorHasOperatorDelete(const CXXDestructorDecl *Dtor,
13810 OperatorDeleteKind K) const {
13811 switch (K) {
13812 case OperatorDeleteKind::Regular:
13813 return OperatorDeletesForVirtualDtor.contains(Val: Dtor->getCanonicalDecl());
13814 case OperatorDeleteKind::GlobalRegular:
13815 return GlobalOperatorDeletesForVirtualDtor.contains(
13816 Val: Dtor->getCanonicalDecl());
13817 case OperatorDeleteKind::Array:
13818 return ArrayOperatorDeletesForVirtualDtor.contains(
13819 Val: Dtor->getCanonicalDecl());
13820 case OperatorDeleteKind::ArrayGlobal:
13821 return GlobalArrayOperatorDeletesForVirtualDtor.contains(
13822 Val: Dtor->getCanonicalDecl());
13823 }
13824 return false;
13825}
13826
13827FunctionDecl *
13828ASTContext::getOperatorDeleteForVDtor(const CXXDestructorDecl *Dtor,
13829 OperatorDeleteKind K) const {
13830 const CXXDestructorDecl *Canon = Dtor->getCanonicalDecl();
13831 switch (K) {
13832 case OperatorDeleteKind::Regular:
13833 if (OperatorDeletesForVirtualDtor.contains(Val: Canon))
13834 return OperatorDeletesForVirtualDtor[Canon];
13835 return nullptr;
13836 case OperatorDeleteKind::GlobalRegular:
13837 if (GlobalOperatorDeletesForVirtualDtor.contains(Val: Canon))
13838 return GlobalOperatorDeletesForVirtualDtor[Canon];
13839 return nullptr;
13840 case OperatorDeleteKind::Array:
13841 if (ArrayOperatorDeletesForVirtualDtor.contains(Val: Canon))
13842 return ArrayOperatorDeletesForVirtualDtor[Canon];
13843 return nullptr;
13844 case OperatorDeleteKind::ArrayGlobal:
13845 if (GlobalArrayOperatorDeletesForVirtualDtor.contains(Val: Canon))
13846 return GlobalArrayOperatorDeletesForVirtualDtor[Canon];
13847 return nullptr;
13848 }
13849 return nullptr;
13850}
13851
13852bool ASTContext::classMaybeNeedsVectorDeletingDestructor(
13853 const CXXRecordDecl *RD) {
13854 if (!getTargetInfo().emitVectorDeletingDtors(getLangOpts()))
13855 return false;
13856
13857 return MaybeRequireVectorDeletingDtor.count(V: RD);
13858}
13859
13860void ASTContext::setClassMaybeNeedsVectorDeletingDestructor(
13861 const CXXRecordDecl *RD) {
13862 if (!getTargetInfo().emitVectorDeletingDtors(getLangOpts()))
13863 return;
13864
13865 MaybeRequireVectorDeletingDtor.insert(V: RD);
13866}
13867
13868MangleNumberingContext &
13869ASTContext::getManglingNumberContext(const DeclContext *DC) {
13870 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
13871 // Reopened namespaces share a mangling context so that declarations in
13872 // different namespace blocks do not receive duplicate mangling numbers.
13873 DC = DC->getPrimaryContext();
13874 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
13875 if (!MCtx)
13876 MCtx = createMangleNumberingContext();
13877 return *MCtx;
13878}
13879
13880MangleNumberingContext &
13881ASTContext::getManglingNumberContext(NeedExtraManglingDecl_t, const Decl *D) {
13882 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
13883 std::unique_ptr<MangleNumberingContext> &MCtx =
13884 ExtraMangleNumberingContexts[D];
13885 if (!MCtx)
13886 MCtx = createMangleNumberingContext();
13887 return *MCtx;
13888}
13889
13890std::unique_ptr<MangleNumberingContext>
13891ASTContext::createMangleNumberingContext() const {
13892 return ABI->createMangleNumberingContext();
13893}
13894
13895const CXXConstructorDecl *
13896ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
13897 return ABI->getCopyConstructorForExceptionObject(
13898 cast<CXXRecordDecl>(Val: RD->getFirstDecl()));
13899}
13900
13901void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
13902 CXXConstructorDecl *CD) {
13903 return ABI->addCopyConstructorForExceptionObject(
13904 cast<CXXRecordDecl>(Val: RD->getFirstDecl()),
13905 cast<CXXConstructorDecl>(Val: CD->getFirstDecl()));
13906}
13907
13908void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD,
13909 TypedefNameDecl *DD) {
13910 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
13911}
13912
13913TypedefNameDecl *
13914ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) {
13915 return ABI->getTypedefNameForUnnamedTagDecl(TD);
13916}
13917
13918void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD,
13919 DeclaratorDecl *DD) {
13920 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
13921}
13922
13923DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) {
13924 return ABI->getDeclaratorForUnnamedTagDecl(TD);
13925}
13926
13927void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
13928 ParamIndices[D] = index;
13929}
13930
13931unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
13932 ParameterIndexTable::const_iterator I = ParamIndices.find(Val: D);
13933 assert(I != ParamIndices.end() &&
13934 "ParmIndices lacks entry set by ParmVarDecl");
13935 return I->second;
13936}
13937
13938QualType ASTContext::getStringLiteralArrayType(QualType EltTy,
13939 unsigned Length) const {
13940 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
13941 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
13942 EltTy = EltTy.withConst();
13943
13944 EltTy = adjustStringLiteralBaseType(Ty: EltTy);
13945
13946 // Get an array type for the string, according to C99 6.4.5. This includes
13947 // the null terminator character.
13948 return getConstantArrayType(EltTy, ArySizeIn: llvm::APInt(32, Length + 1), SizeExpr: nullptr,
13949 ASM: ArraySizeModifier::Normal, /*IndexTypeQuals*/ 0);
13950}
13951
13952StringLiteral *
13953ASTContext::getPredefinedStringLiteralFromCache(StringRef Key) const {
13954 StringLiteral *&Result = StringLiteralCache[Key];
13955 if (!Result)
13956 Result = StringLiteral::Create(
13957 Ctx: *this, Str: Key, Kind: StringLiteralKind::Ordinary,
13958 /*Pascal*/ false, Ty: getStringLiteralArrayType(EltTy: CharTy, Length: Key.size()),
13959 Locs: SourceLocation());
13960 return Result;
13961}
13962
13963MSGuidDecl *
13964ASTContext::getMSGuidDecl(MSGuidDecl::Parts Parts) const {
13965 assert(MSGuidTagDecl && "building MS GUID without MS extensions?");
13966
13967 llvm::FoldingSetNodeID ID;
13968 MSGuidDecl::Profile(ID, P: Parts);
13969
13970 llvm::FoldingSetInsertToken Token;
13971 if (MSGuidDecl *Existing = MSGuidDecls.lookup(ID, Token))
13972 return Existing;
13973
13974 QualType GUIDType = getMSGuidType().withConst();
13975 MSGuidDecl *New = MSGuidDecl::Create(C: *this, T: GUIDType, P: Parts);
13976 MSGuidDecls.insert(N: New, Token);
13977 return New;
13978}
13979
13980UnnamedGlobalConstantDecl *
13981ASTContext::getUnnamedGlobalConstantDecl(QualType Ty,
13982 const APValue &APVal) const {
13983 llvm::FoldingSetNodeID ID;
13984 UnnamedGlobalConstantDecl::Profile(ID, Ty, APVal);
13985
13986 llvm::FoldingSetInsertToken Token;
13987 if (UnnamedGlobalConstantDecl *Existing =
13988 UnnamedGlobalConstantDecls.lookup(ID, Token))
13989 return Existing;
13990
13991 UnnamedGlobalConstantDecl *New =
13992 UnnamedGlobalConstantDecl::Create(C: *this, T: Ty, APVal);
13993 UnnamedGlobalConstantDecls.insert(N: New, Token);
13994 return New;
13995}
13996
13997TemplateParamObjectDecl *
13998ASTContext::getTemplateParamObjectDecl(QualType T, const APValue &V) const {
13999 assert(T->isRecordType() && "template param object of unexpected type");
14000
14001 // C++ [temp.param]p8:
14002 // [...] a static storage duration object of type 'const T' [...]
14003 T.addConst();
14004
14005 llvm::FoldingSetNodeID ID;
14006 TemplateParamObjectDecl::Profile(ID, T, V);
14007
14008 llvm::FoldingSetInsertToken Token;
14009 if (TemplateParamObjectDecl *Existing =
14010 TemplateParamObjectDecls.lookup(ID, Token))
14011 return Existing;
14012
14013 TemplateParamObjectDecl *New = TemplateParamObjectDecl::Create(C: *this, T, V);
14014 TemplateParamObjectDecls.insert(N: New, Token);
14015 return New;
14016}
14017
14018bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
14019 const llvm::Triple &T = getTargetInfo().getTriple();
14020 if (!T.isOSDarwin())
14021 return false;
14022
14023 if (!(T.isiOS() && T.isOSVersionLT(Major: 7)) &&
14024 !(T.isMacOSX() && T.isOSVersionLT(Major: 10, Minor: 9)))
14025 return false;
14026
14027 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
14028 CharUnits sizeChars = getTypeSizeInChars(T: AtomicTy);
14029 uint64_t Size = sizeChars.getQuantity();
14030 CharUnits alignChars = getTypeAlignInChars(T: AtomicTy);
14031 unsigned Align = alignChars.getQuantity();
14032 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
14033 return (Size != Align || toBits(CharSize: sizeChars) > MaxInlineWidthInBits);
14034}
14035
14036bool
14037ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
14038 const ObjCMethodDecl *MethodImpl) {
14039 // No point trying to match an unavailable/deprecated mothod.
14040 if (MethodDecl->hasAttr<UnavailableAttr>()
14041 || MethodDecl->hasAttr<DeprecatedAttr>())
14042 return false;
14043 if (MethodDecl->getObjCDeclQualifier() !=
14044 MethodImpl->getObjCDeclQualifier())
14045 return false;
14046 if (!hasSameType(T1: MethodDecl->getReturnType(), T2: MethodImpl->getReturnType()))
14047 return false;
14048
14049 if (MethodDecl->param_size() != MethodImpl->param_size())
14050 return false;
14051
14052 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
14053 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
14054 EF = MethodDecl->param_end();
14055 IM != EM && IF != EF; ++IM, ++IF) {
14056 const ParmVarDecl *DeclVar = (*IF);
14057 const ParmVarDecl *ImplVar = (*IM);
14058 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
14059 return false;
14060 if (!hasSameType(T1: DeclVar->getType(), T2: ImplVar->getType()))
14061 return false;
14062 }
14063
14064 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
14065}
14066
14067uint64_t ASTContext::getTargetNullPointerValue(QualType QT) const {
14068 LangAS AS;
14069 if (QT->getUnqualifiedDesugaredType()->isNullPtrType())
14070 AS = LangAS::Default;
14071 else
14072 AS = QT->getPointeeType().getAddressSpace();
14073
14074 return getTargetInfo().getNullPointerValue(AddrSpace: AS);
14075}
14076
14077unsigned ASTContext::getTargetAddressSpace(LangAS AS) const {
14078 return getTargetInfo().getTargetAddressSpace(AS);
14079}
14080
14081bool ASTContext::hasSameExpr(const Expr *X, const Expr *Y) const {
14082 if (X == Y)
14083 return true;
14084 if (!X || !Y)
14085 return false;
14086 llvm::FoldingSetNodeID IDX, IDY;
14087 X->Profile(ID&: IDX, Context: *this, /*Canonical=*/true);
14088 Y->Profile(ID&: IDY, Context: *this, /*Canonical=*/true);
14089 return IDX == IDY;
14090}
14091
14092// The getCommon* helpers return, for given 'same' X and Y entities given as
14093// inputs, another entity which is also the 'same' as the inputs, but which
14094// is closer to the canonical form of the inputs, each according to a given
14095// criteria.
14096// The getCommon*Checked variants are 'null inputs not-allowed' equivalents of
14097// the regular ones.
14098
14099static Decl *getCommonDecl(Decl *X, Decl *Y) {
14100 if (!declaresSameEntity(D1: X, D2: Y))
14101 return nullptr;
14102 for (const Decl *DX : X->redecls()) {
14103 // If we reach Y before reaching the first decl, that means X is older.
14104 if (DX == Y)
14105 return X;
14106 // If we reach the first decl, then Y is older.
14107 if (DX->isFirstDecl())
14108 return Y;
14109 }
14110 llvm_unreachable("Corrupt redecls chain");
14111}
14112
14113template <class T, std::enable_if_t<std::is_base_of_v<Decl, T>, bool> = true>
14114static T *getCommonDecl(T *X, T *Y) {
14115 return cast_or_null<T>(
14116 getCommonDecl(X: const_cast<Decl *>(cast_or_null<Decl>(X)),
14117 Y: const_cast<Decl *>(cast_or_null<Decl>(Y))));
14118}
14119
14120template <class T, std::enable_if_t<std::is_base_of_v<Decl, T>, bool> = true>
14121static T *getCommonDeclChecked(T *X, T *Y) {
14122 return cast<T>(getCommonDecl(X: const_cast<Decl *>(cast<Decl>(X)),
14123 Y: const_cast<Decl *>(cast<Decl>(Y))));
14124}
14125
14126static TemplateName getCommonTemplateName(const ASTContext &Ctx, TemplateName X,
14127 TemplateName Y,
14128 bool IgnoreDeduced = false) {
14129 if (X.getAsVoidPointer() == Y.getAsVoidPointer())
14130 return X;
14131 // FIXME: There are cases here where we could find a common template name
14132 // with more sugar. For example one could be a SubstTemplateTemplate*
14133 // replacing the other.
14134 TemplateName CX = Ctx.getCanonicalTemplateName(Name: X, IgnoreDeduced);
14135 if (CX.getAsVoidPointer() !=
14136 Ctx.getCanonicalTemplateName(Name: Y).getAsVoidPointer())
14137 return TemplateName();
14138 return CX;
14139}
14140
14141static TemplateName getCommonTemplateNameChecked(const ASTContext &Ctx,
14142 TemplateName X, TemplateName Y,
14143 bool IgnoreDeduced) {
14144 TemplateName R = getCommonTemplateName(Ctx, X, Y, IgnoreDeduced);
14145 assert(R.getAsVoidPointer() != nullptr);
14146 return R;
14147}
14148
14149static auto getCommonTypes(const ASTContext &Ctx, ArrayRef<QualType> Xs,
14150 ArrayRef<QualType> Ys, bool Unqualified = false) {
14151 assert(Xs.size() == Ys.size());
14152 SmallVector<QualType, 8> Rs(Xs.size());
14153 for (size_t I = 0; I < Rs.size(); ++I)
14154 Rs[I] = Ctx.getCommonSugaredType(X: Xs[I], Y: Ys[I], Unqualified);
14155 return Rs;
14156}
14157
14158template <class T>
14159static SourceLocation getCommonAttrLoc(const T *X, const T *Y) {
14160 return X->getAttributeLoc() == Y->getAttributeLoc() ? X->getAttributeLoc()
14161 : SourceLocation();
14162}
14163
14164static TemplateArgument getCommonTemplateArgument(const ASTContext &Ctx,
14165 const TemplateArgument &X,
14166 const TemplateArgument &Y) {
14167 if (X.getKind() != Y.getKind())
14168 return TemplateArgument();
14169
14170 switch (X.getKind()) {
14171 case TemplateArgument::ArgKind::Type:
14172 if (!Ctx.hasSameType(T1: X.getAsType(), T2: Y.getAsType()))
14173 return TemplateArgument();
14174 return TemplateArgument(
14175 Ctx.getCommonSugaredType(X: X.getAsType(), Y: Y.getAsType()));
14176 case TemplateArgument::ArgKind::NullPtr:
14177 if (!Ctx.hasSameType(T1: X.getNullPtrType(), T2: Y.getNullPtrType()))
14178 return TemplateArgument();
14179 return TemplateArgument(
14180 Ctx.getCommonSugaredType(X: X.getNullPtrType(), Y: Y.getNullPtrType()),
14181 /*Unqualified=*/true);
14182 case TemplateArgument::ArgKind::Expression:
14183 if (!Ctx.hasSameType(T1: X.getAsExpr()->getType(), T2: Y.getAsExpr()->getType()))
14184 return TemplateArgument();
14185 // FIXME: Try to keep the common sugar.
14186 return X;
14187 case TemplateArgument::ArgKind::Template: {
14188 TemplateName TX = X.getAsTemplate(), TY = Y.getAsTemplate();
14189 TemplateName CTN = ::getCommonTemplateName(Ctx, X: TX, Y: TY);
14190 if (!CTN.getAsVoidPointer())
14191 return TemplateArgument();
14192 return TemplateArgument(CTN);
14193 }
14194 case TemplateArgument::ArgKind::TemplateExpansion: {
14195 TemplateName TX = X.getAsTemplateOrTemplatePattern(),
14196 TY = Y.getAsTemplateOrTemplatePattern();
14197 TemplateName CTN = ::getCommonTemplateName(Ctx, X: TX, Y: TY);
14198 if (!CTN.getAsVoidPointer())
14199 return TemplateName();
14200 auto NExpX = X.getNumTemplateExpansions();
14201 assert(NExpX == Y.getNumTemplateExpansions());
14202 return TemplateArgument(CTN, NExpX);
14203 }
14204 default:
14205 // FIXME: Handle the other argument kinds.
14206 return X;
14207 }
14208}
14209
14210static bool getCommonTemplateArguments(const ASTContext &Ctx,
14211 SmallVectorImpl<TemplateArgument> &R,
14212 ArrayRef<TemplateArgument> Xs,
14213 ArrayRef<TemplateArgument> Ys) {
14214 if (Xs.size() != Ys.size())
14215 return true;
14216 R.resize(N: Xs.size());
14217 for (size_t I = 0; I < R.size(); ++I) {
14218 R[I] = getCommonTemplateArgument(Ctx, X: Xs[I], Y: Ys[I]);
14219 if (R[I].isNull())
14220 return true;
14221 }
14222 return false;
14223}
14224
14225static auto getCommonTemplateArguments(const ASTContext &Ctx,
14226 ArrayRef<TemplateArgument> Xs,
14227 ArrayRef<TemplateArgument> Ys) {
14228 SmallVector<TemplateArgument, 8> R;
14229 bool Different = getCommonTemplateArguments(Ctx, R, Xs, Ys);
14230 assert(!Different);
14231 (void)Different;
14232 return R;
14233}
14234
14235template <class T>
14236static ElaboratedTypeKeyword getCommonTypeKeyword(const T *X, const T *Y,
14237 bool IsSame) {
14238 ElaboratedTypeKeyword KX = X->getKeyword(), KY = Y->getKeyword();
14239 if (KX == KY)
14240 return KX;
14241 KX = getCanonicalElaboratedTypeKeyword(Keyword: KX);
14242 assert(!IsSame || KX == getCanonicalElaboratedTypeKeyword(KY));
14243 return KX;
14244}
14245
14246/// Returns a NestedNameSpecifier which has only the common sugar
14247/// present in both NNS1 and NNS2.
14248static NestedNameSpecifier getCommonNNS(const ASTContext &Ctx,
14249 NestedNameSpecifier NNS1,
14250 NestedNameSpecifier NNS2, bool IsSame) {
14251 // If they are identical, all sugar is common.
14252 if (NNS1 == NNS2)
14253 return NNS1;
14254
14255 // IsSame implies both Qualifiers are equivalent.
14256 NestedNameSpecifier Canon = NNS1.getCanonical();
14257 if (Canon != NNS2.getCanonical()) {
14258 assert(!IsSame && "Should be the same NestedNameSpecifier");
14259 // If they are not the same, there is nothing to unify.
14260 return std::nullopt;
14261 }
14262
14263 NestedNameSpecifier R = std::nullopt;
14264 NestedNameSpecifier::Kind Kind = NNS1.getKind();
14265 assert(Kind == NNS2.getKind());
14266 switch (Kind) {
14267 case NestedNameSpecifier::Kind::Namespace: {
14268 auto [Namespace1, Prefix1] = NNS1.getAsNamespaceAndPrefix();
14269 auto [Namespace2, Prefix2] = NNS2.getAsNamespaceAndPrefix();
14270 auto Kind = Namespace1->getKind();
14271 if (Kind != Namespace2->getKind() ||
14272 (Kind == Decl::NamespaceAlias &&
14273 !declaresSameEntity(D1: Namespace1, D2: Namespace2))) {
14274 R = NestedNameSpecifier(
14275 Ctx,
14276 ::getCommonDeclChecked(X: Namespace1->getNamespace(),
14277 Y: Namespace2->getNamespace()),
14278 /*Prefix=*/std::nullopt);
14279 break;
14280 }
14281 // The prefixes for namespaces are not significant, its declaration
14282 // identifies it uniquely.
14283 NestedNameSpecifier Prefix = ::getCommonNNS(Ctx, NNS1: Prefix1, NNS2: Prefix2,
14284 /*IsSame=*/false);
14285 R = NestedNameSpecifier(Ctx, ::getCommonDeclChecked(X: Namespace1, Y: Namespace2),
14286 Prefix);
14287 break;
14288 }
14289 case NestedNameSpecifier::Kind::Type: {
14290 const Type *T1 = NNS1.getAsType(), *T2 = NNS2.getAsType();
14291 const Type *T = Ctx.getCommonSugaredType(X: QualType(T1, 0), Y: QualType(T2, 0),
14292 /*Unqualified=*/true)
14293 .getTypePtr();
14294 R = NestedNameSpecifier(T);
14295 break;
14296 }
14297 case NestedNameSpecifier::Kind::MicrosoftSuper: {
14298 // FIXME: Can __super even be used with data members?
14299 // If it's only usable in functions, we will never see it here,
14300 // unless we save the qualifiers used in function types.
14301 // In that case, it might be possible NNS2 is a type,
14302 // in which case we should degrade the result to
14303 // a CXXRecordType.
14304 R = NestedNameSpecifier(getCommonDeclChecked(X: NNS1.getAsMicrosoftSuper(),
14305 Y: NNS2.getAsMicrosoftSuper()));
14306 break;
14307 }
14308 case NestedNameSpecifier::Kind::Null:
14309 case NestedNameSpecifier::Kind::Global:
14310 // These are singletons.
14311 llvm_unreachable("singletons did not compare equal");
14312 }
14313 assert(R.getCanonical() == Canon);
14314 return R;
14315}
14316
14317template <class T>
14318static NestedNameSpecifier getCommonQualifier(const ASTContext &Ctx, const T *X,
14319 const T *Y, bool IsSame) {
14320 return ::getCommonNNS(Ctx, NNS1: X->getQualifier(), NNS2: Y->getQualifier(), IsSame);
14321}
14322
14323template <class T>
14324static QualType getCommonElementType(const ASTContext &Ctx, const T *X,
14325 const T *Y) {
14326 return Ctx.getCommonSugaredType(X: X->getElementType(), Y: Y->getElementType());
14327}
14328
14329static QualType getCommonTypeWithQualifierLifting(const ASTContext &Ctx,
14330 QualType X, QualType Y,
14331 Qualifiers &QX,
14332 Qualifiers &QY) {
14333 QualType R = Ctx.getCommonSugaredType(X, Y,
14334 /*Unqualified=*/true);
14335 // Qualifiers common to both element types.
14336 Qualifiers RQ = R.getQualifiers();
14337 // For each side, move to the top level any qualifiers which are not common to
14338 // both element types. The caller must assume top level qualifiers might
14339 // be different, even if they are the same type, and can be treated as sugar.
14340 QX += X.getQualifiers() - RQ;
14341 QY += Y.getQualifiers() - RQ;
14342 return R;
14343}
14344
14345template <class T>
14346static QualType getCommonArrayElementType(const ASTContext &Ctx, const T *X,
14347 Qualifiers &QX, const T *Y,
14348 Qualifiers &QY) {
14349 return getCommonTypeWithQualifierLifting(Ctx, X->getElementType(),
14350 Y->getElementType(), QX, QY);
14351}
14352
14353template <class T>
14354static QualType getCommonPointeeType(const ASTContext &Ctx, const T *X,
14355 const T *Y) {
14356 return Ctx.getCommonSugaredType(X: X->getPointeeType(), Y: Y->getPointeeType());
14357}
14358
14359template <class T>
14360static auto *getCommonSizeExpr(const ASTContext &Ctx, T *X, T *Y) {
14361 assert(Ctx.hasSameExpr(X->getSizeExpr(), Y->getSizeExpr()));
14362 return X->getSizeExpr();
14363}
14364
14365static auto getCommonSizeModifier(const ArrayType *X, const ArrayType *Y) {
14366 assert(X->getSizeModifier() == Y->getSizeModifier());
14367 return X->getSizeModifier();
14368}
14369
14370static auto getCommonIndexTypeCVRQualifiers(const ArrayType *X,
14371 const ArrayType *Y) {
14372 assert(X->getIndexTypeCVRQualifiers() == Y->getIndexTypeCVRQualifiers());
14373 return X->getIndexTypeCVRQualifiers();
14374}
14375
14376// Merges two type lists such that the resulting vector will contain
14377// each type (in a canonical sense) only once, in the order they appear
14378// from X to Y. If they occur in both X and Y, the result will contain
14379// the common sugared type between them.
14380static void mergeTypeLists(const ASTContext &Ctx,
14381 SmallVectorImpl<QualType> &Out, ArrayRef<QualType> X,
14382 ArrayRef<QualType> Y) {
14383 llvm::DenseMap<QualType, unsigned> Found;
14384 for (auto Ts : {X, Y}) {
14385 for (QualType T : Ts) {
14386 auto Res = Found.try_emplace(Key: Ctx.getCanonicalType(T), Args: Out.size());
14387 if (!Res.second) {
14388 QualType &U = Out[Res.first->second];
14389 U = Ctx.getCommonSugaredType(X: U, Y: T);
14390 } else {
14391 Out.emplace_back(Args&: T);
14392 }
14393 }
14394 }
14395}
14396
14397FunctionProtoType::ExceptionSpecInfo
14398ASTContext::mergeExceptionSpecs(FunctionProtoType::ExceptionSpecInfo ESI1,
14399 FunctionProtoType::ExceptionSpecInfo ESI2,
14400 SmallVectorImpl<QualType> &ExceptionTypeStorage,
14401 bool AcceptDependent) const {
14402 ExceptionSpecificationType EST1 = ESI1.Type, EST2 = ESI2.Type;
14403
14404 // If either of them can throw anything, that is the result.
14405 for (auto I : {EST_None, EST_MSAny, EST_NoexceptFalse}) {
14406 if (EST1 == I)
14407 return ESI1;
14408 if (EST2 == I)
14409 return ESI2;
14410 }
14411
14412 // If either of them is non-throwing, the result is the other.
14413 for (auto I :
14414 {EST_NoThrow, EST_DynamicNone, EST_BasicNoexcept, EST_NoexceptTrue}) {
14415 if (EST1 == I)
14416 return ESI2;
14417 if (EST2 == I)
14418 return ESI1;
14419 }
14420
14421 // If we're left with value-dependent computed noexcept expressions, we're
14422 // stuck. Before C++17, we can just drop the exception specification entirely,
14423 // since it's not actually part of the canonical type. And this should never
14424 // happen in C++17, because it would mean we were computing the composite
14425 // pointer type of dependent types, which should never happen.
14426 if (EST1 == EST_DependentNoexcept || EST2 == EST_DependentNoexcept) {
14427 assert(AcceptDependent &&
14428 "computing composite pointer type of dependent types");
14429 return FunctionProtoType::ExceptionSpecInfo();
14430 }
14431
14432 // Switch over the possibilities so that people adding new values know to
14433 // update this function.
14434 switch (EST1) {
14435 case EST_None:
14436 case EST_DynamicNone:
14437 case EST_MSAny:
14438 case EST_BasicNoexcept:
14439 case EST_DependentNoexcept:
14440 case EST_NoexceptFalse:
14441 case EST_NoexceptTrue:
14442 case EST_NoThrow:
14443 llvm_unreachable("These ESTs should be handled above");
14444
14445 case EST_Dynamic: {
14446 // This is the fun case: both exception specifications are dynamic. Form
14447 // the union of the two lists.
14448 assert(EST2 == EST_Dynamic && "other cases should already be handled");
14449 mergeTypeLists(Ctx: *this, Out&: ExceptionTypeStorage, X: ESI1.Exceptions,
14450 Y: ESI2.Exceptions);
14451 FunctionProtoType::ExceptionSpecInfo Result(EST_Dynamic);
14452 Result.Exceptions = ExceptionTypeStorage;
14453 return Result;
14454 }
14455
14456 case EST_Unevaluated:
14457 case EST_Uninstantiated:
14458 case EST_Unparsed:
14459 llvm_unreachable("shouldn't see unresolved exception specifications here");
14460 }
14461
14462 llvm_unreachable("invalid ExceptionSpecificationType");
14463}
14464
14465static QualType getCommonNonSugarTypeNode(const ASTContext &Ctx, const Type *X,
14466 Qualifiers &QX, const Type *Y,
14467 Qualifiers &QY) {
14468 Type::TypeClass TC = X->getTypeClass();
14469 assert(TC == Y->getTypeClass());
14470 switch (TC) {
14471#define UNEXPECTED_TYPE(Class, Kind) \
14472 case Type::Class: \
14473 llvm_unreachable("Unexpected " Kind ": " #Class);
14474
14475#define NON_CANONICAL_TYPE(Class, Base) UNEXPECTED_TYPE(Class, "non-canonical")
14476#define TYPE(Class, Base)
14477#include "clang/AST/TypeNodes.inc"
14478
14479#define SUGAR_FREE_TYPE(Class) UNEXPECTED_TYPE(Class, "sugar-free")
14480 SUGAR_FREE_TYPE(Builtin)
14481 SUGAR_FREE_TYPE(DeducedTemplateSpecialization)
14482 SUGAR_FREE_TYPE(DependentBitInt)
14483 SUGAR_FREE_TYPE(BitInt)
14484 SUGAR_FREE_TYPE(ObjCInterface)
14485 SUGAR_FREE_TYPE(SubstTemplateTypeParmPack)
14486 SUGAR_FREE_TYPE(SubstBuiltinTemplatePack)
14487 SUGAR_FREE_TYPE(UnresolvedUsing)
14488 SUGAR_FREE_TYPE(HLSLAttributedResource)
14489 SUGAR_FREE_TYPE(HLSLInlineSpirv)
14490#undef SUGAR_FREE_TYPE
14491#define NON_UNIQUE_TYPE(Class) UNEXPECTED_TYPE(Class, "non-unique")
14492 NON_UNIQUE_TYPE(TypeOfExpr)
14493 NON_UNIQUE_TYPE(VariableArray)
14494#undef NON_UNIQUE_TYPE
14495
14496 UNEXPECTED_TYPE(TypeOf, "sugar")
14497
14498#undef UNEXPECTED_TYPE
14499
14500 case Type::Auto: {
14501 const auto *AX = cast<AutoType>(Val: X), *AY = cast<AutoType>(Val: Y);
14502 assert(AX->getDeducedKind() == AY->getDeducedKind());
14503 assert(AX->getDeducedKind() != DeducedKind::Deduced);
14504 assert(AX->getKeyword() == AY->getKeyword());
14505 TemplateDecl *CD =
14506 ::getCommonDecl(X: AX->getTypeConstraintConcept().getAsTemplateDecl(),
14507 Y: AY->getTypeConstraintConcept().getAsTemplateDecl());
14508 SmallVector<TemplateArgument, 8> As;
14509 if (CD &&
14510 getCommonTemplateArguments(Ctx, R&: As, Xs: AX->getTypeConstraintArguments(),
14511 Ys: AY->getTypeConstraintArguments())) {
14512 CD = nullptr; // The arguments differ, so make it unconstrained.
14513 As.clear();
14514 }
14515 return Ctx.getAutoType(DK: AX->getDeducedKind(), DeducedAsType: QualType(), Keyword: AX->getKeyword(),
14516 TypeConstraintConcept: TemplateName(CD), TypeConstraintArgs: As);
14517 }
14518 case Type::IncompleteArray: {
14519 const auto *AX = cast<IncompleteArrayType>(Val: X),
14520 *AY = cast<IncompleteArrayType>(Val: Y);
14521 return Ctx.getIncompleteArrayType(
14522 elementType: getCommonArrayElementType(Ctx, X: AX, QX, Y: AY, QY),
14523 ASM: getCommonSizeModifier(X: AX, Y: AY), elementTypeQuals: getCommonIndexTypeCVRQualifiers(X: AX, Y: AY));
14524 }
14525 case Type::DependentSizedArray: {
14526 const auto *AX = cast<DependentSizedArrayType>(Val: X),
14527 *AY = cast<DependentSizedArrayType>(Val: Y);
14528 return Ctx.getDependentSizedArrayType(
14529 elementType: getCommonArrayElementType(Ctx, X: AX, QX, Y: AY, QY),
14530 numElements: getCommonSizeExpr(Ctx, X: AX, Y: AY), ASM: getCommonSizeModifier(X: AX, Y: AY),
14531 elementTypeQuals: getCommonIndexTypeCVRQualifiers(X: AX, Y: AY));
14532 }
14533 case Type::ConstantArray: {
14534 const auto *AX = cast<ConstantArrayType>(Val: X),
14535 *AY = cast<ConstantArrayType>(Val: Y);
14536 assert(AX->getSize() == AY->getSize());
14537 const Expr *SizeExpr = Ctx.hasSameExpr(X: AX->getSizeExpr(), Y: AY->getSizeExpr())
14538 ? AX->getSizeExpr()
14539 : nullptr;
14540 return Ctx.getConstantArrayType(
14541 EltTy: getCommonArrayElementType(Ctx, X: AX, QX, Y: AY, QY), ArySizeIn: AX->getSize(), SizeExpr,
14542 ASM: getCommonSizeModifier(X: AX, Y: AY), IndexTypeQuals: getCommonIndexTypeCVRQualifiers(X: AX, Y: AY));
14543 }
14544 case Type::ArrayParameter: {
14545 const auto *AX = cast<ArrayParameterType>(Val: X),
14546 *AY = cast<ArrayParameterType>(Val: Y);
14547 assert(AX->getSize() == AY->getSize());
14548 const Expr *SizeExpr = Ctx.hasSameExpr(X: AX->getSizeExpr(), Y: AY->getSizeExpr())
14549 ? AX->getSizeExpr()
14550 : nullptr;
14551 auto ArrayTy = Ctx.getConstantArrayType(
14552 EltTy: getCommonArrayElementType(Ctx, X: AX, QX, Y: AY, QY), ArySizeIn: AX->getSize(), SizeExpr,
14553 ASM: getCommonSizeModifier(X: AX, Y: AY), IndexTypeQuals: getCommonIndexTypeCVRQualifiers(X: AX, Y: AY));
14554 return Ctx.getArrayParameterType(Ty: ArrayTy);
14555 }
14556 case Type::Atomic: {
14557 const auto *AX = cast<AtomicType>(Val: X), *AY = cast<AtomicType>(Val: Y);
14558 return Ctx.getAtomicType(
14559 T: Ctx.getCommonSugaredType(X: AX->getValueType(), Y: AY->getValueType()));
14560 }
14561 case Type::Complex: {
14562 const auto *CX = cast<ComplexType>(Val: X), *CY = cast<ComplexType>(Val: Y);
14563 return Ctx.getComplexType(T: getCommonArrayElementType(Ctx, X: CX, QX, Y: CY, QY));
14564 }
14565 case Type::Pointer: {
14566 const auto *PX = cast<PointerType>(Val: X), *PY = cast<PointerType>(Val: Y);
14567 return Ctx.getPointerType(T: getCommonPointeeType(Ctx, X: PX, Y: PY));
14568 }
14569 case Type::BlockPointer: {
14570 const auto *PX = cast<BlockPointerType>(Val: X), *PY = cast<BlockPointerType>(Val: Y);
14571 return Ctx.getBlockPointerType(T: getCommonPointeeType(Ctx, X: PX, Y: PY));
14572 }
14573 case Type::ObjCObjectPointer: {
14574 const auto *PX = cast<ObjCObjectPointerType>(Val: X),
14575 *PY = cast<ObjCObjectPointerType>(Val: Y);
14576 return Ctx.getObjCObjectPointerType(ObjectT: getCommonPointeeType(Ctx, X: PX, Y: PY));
14577 }
14578 case Type::MemberPointer: {
14579 const auto *PX = cast<MemberPointerType>(Val: X),
14580 *PY = cast<MemberPointerType>(Val: Y);
14581 assert(declaresSameEntity(PX->getMostRecentCXXRecordDecl(),
14582 PY->getMostRecentCXXRecordDecl()));
14583 return Ctx.getMemberPointerType(
14584 T: getCommonPointeeType(Ctx, X: PX, Y: PY),
14585 Qualifier: getCommonQualifier(Ctx, X: PX, Y: PY, /*IsSame=*/true),
14586 Cls: PX->getMostRecentCXXRecordDecl());
14587 }
14588 case Type::LValueReference: {
14589 const auto *PX = cast<LValueReferenceType>(Val: X),
14590 *PY = cast<LValueReferenceType>(Val: Y);
14591 // FIXME: Preserve PointeeTypeAsWritten.
14592 return Ctx.getLValueReferenceType(T: getCommonPointeeType(Ctx, X: PX, Y: PY),
14593 SpelledAsLValue: PX->isSpelledAsLValue() ||
14594 PY->isSpelledAsLValue());
14595 }
14596 case Type::RValueReference: {
14597 const auto *PX = cast<RValueReferenceType>(Val: X),
14598 *PY = cast<RValueReferenceType>(Val: Y);
14599 // FIXME: Preserve PointeeTypeAsWritten.
14600 return Ctx.getRValueReferenceType(T: getCommonPointeeType(Ctx, X: PX, Y: PY));
14601 }
14602 case Type::DependentAddressSpace: {
14603 const auto *PX = cast<DependentAddressSpaceType>(Val: X),
14604 *PY = cast<DependentAddressSpaceType>(Val: Y);
14605 assert(Ctx.hasSameExpr(PX->getAddrSpaceExpr(), PY->getAddrSpaceExpr()));
14606 return Ctx.getDependentAddressSpaceType(PointeeType: getCommonPointeeType(Ctx, X: PX, Y: PY),
14607 AddrSpaceExpr: PX->getAddrSpaceExpr(),
14608 AttrLoc: getCommonAttrLoc(X: PX, Y: PY));
14609 }
14610 case Type::FunctionNoProto: {
14611 const auto *FX = cast<FunctionNoProtoType>(Val: X),
14612 *FY = cast<FunctionNoProtoType>(Val: Y);
14613 assert(FX->getExtInfo() == FY->getExtInfo());
14614 return Ctx.getFunctionNoProtoType(
14615 ResultTy: Ctx.getCommonSugaredType(X: FX->getReturnType(), Y: FY->getReturnType()),
14616 Info: FX->getExtInfo());
14617 }
14618 case Type::FunctionProto: {
14619 const auto *FX = cast<FunctionProtoType>(Val: X),
14620 *FY = cast<FunctionProtoType>(Val: Y);
14621 FunctionProtoType::ExtProtoInfo EPIX = FX->getExtProtoInfo(),
14622 EPIY = FY->getExtProtoInfo();
14623 assert(EPIX.ExtInfo == EPIY.ExtInfo);
14624 assert(!EPIX.ExtParameterInfos == !EPIY.ExtParameterInfos);
14625 assert(!EPIX.ExtParameterInfos ||
14626 llvm::equal(
14627 llvm::ArrayRef(EPIX.ExtParameterInfos, FX->getNumParams()),
14628 llvm::ArrayRef(EPIY.ExtParameterInfos, FY->getNumParams())));
14629 assert(EPIX.RefQualifier == EPIY.RefQualifier);
14630 assert(EPIX.TypeQuals == EPIY.TypeQuals);
14631 assert(EPIX.Variadic == EPIY.Variadic);
14632
14633 // FIXME: Can we handle an empty EllipsisLoc?
14634 // Use emtpy EllipsisLoc if X and Y differ.
14635
14636 EPIX.HasTrailingReturn = EPIX.HasTrailingReturn && EPIY.HasTrailingReturn;
14637
14638 QualType R =
14639 Ctx.getCommonSugaredType(X: FX->getReturnType(), Y: FY->getReturnType());
14640 auto P = getCommonTypes(Ctx, Xs: FX->param_types(), Ys: FY->param_types(),
14641 /*Unqualified=*/true);
14642
14643 SmallVector<QualType, 8> Exceptions;
14644 EPIX.ExceptionSpec = Ctx.mergeExceptionSpecs(
14645 ESI1: EPIX.ExceptionSpec, ESI2: EPIY.ExceptionSpec, ExceptionTypeStorage&: Exceptions, AcceptDependent: true);
14646 return Ctx.getFunctionType(ResultTy: R, Args: P, EPI: EPIX);
14647 }
14648 case Type::ObjCObject: {
14649 const auto *OX = cast<ObjCObjectType>(Val: X), *OY = cast<ObjCObjectType>(Val: Y);
14650 assert(
14651 std::equal(OX->getProtocols().begin(), OX->getProtocols().end(),
14652 OY->getProtocols().begin(), OY->getProtocols().end(),
14653 [](const ObjCProtocolDecl *P0, const ObjCProtocolDecl *P1) {
14654 return P0->getCanonicalDecl() == P1->getCanonicalDecl();
14655 }) &&
14656 "protocol lists must be the same");
14657 auto TAs = getCommonTypes(Ctx, Xs: OX->getTypeArgsAsWritten(),
14658 Ys: OY->getTypeArgsAsWritten());
14659 return Ctx.getObjCObjectType(
14660 baseType: Ctx.getCommonSugaredType(X: OX->getBaseType(), Y: OY->getBaseType()), typeArgs: TAs,
14661 protocols: OX->getProtocols(),
14662 isKindOf: OX->isKindOfTypeAsWritten() && OY->isKindOfTypeAsWritten());
14663 }
14664 case Type::ConstantMatrix: {
14665 const auto *MX = cast<ConstantMatrixType>(Val: X),
14666 *MY = cast<ConstantMatrixType>(Val: Y);
14667 assert(MX->getNumRows() == MY->getNumRows());
14668 assert(MX->getNumColumns() == MY->getNumColumns());
14669 return Ctx.getConstantMatrixType(ElementTy: getCommonElementType(Ctx, X: MX, Y: MY),
14670 NumRows: MX->getNumRows(), NumColumns: MX->getNumColumns());
14671 }
14672 case Type::DependentSizedMatrix: {
14673 const auto *MX = cast<DependentSizedMatrixType>(Val: X),
14674 *MY = cast<DependentSizedMatrixType>(Val: Y);
14675 assert(Ctx.hasSameExpr(MX->getRowExpr(), MY->getRowExpr()));
14676 assert(Ctx.hasSameExpr(MX->getColumnExpr(), MY->getColumnExpr()));
14677 return Ctx.getDependentSizedMatrixType(
14678 ElementTy: getCommonElementType(Ctx, X: MX, Y: MY), RowExpr: MX->getRowExpr(),
14679 ColumnExpr: MX->getColumnExpr(), AttrLoc: getCommonAttrLoc(X: MX, Y: MY));
14680 }
14681 case Type::Vector: {
14682 const auto *VX = cast<VectorType>(Val: X), *VY = cast<VectorType>(Val: Y);
14683 assert(VX->getNumElements() == VY->getNumElements());
14684 assert(VX->getVectorKind() == VY->getVectorKind());
14685 return Ctx.getVectorType(vecType: getCommonElementType(Ctx, X: VX, Y: VY),
14686 NumElts: VX->getNumElements(), VecKind: VX->getVectorKind());
14687 }
14688 case Type::ExtVector: {
14689 const auto *VX = cast<ExtVectorType>(Val: X), *VY = cast<ExtVectorType>(Val: Y);
14690 assert(VX->getNumElements() == VY->getNumElements());
14691 return Ctx.getExtVectorType(vecType: getCommonElementType(Ctx, X: VX, Y: VY),
14692 NumElts: VX->getNumElements());
14693 }
14694 case Type::DependentSizedExtVector: {
14695 const auto *VX = cast<DependentSizedExtVectorType>(Val: X),
14696 *VY = cast<DependentSizedExtVectorType>(Val: Y);
14697 return Ctx.getDependentSizedExtVectorType(vecType: getCommonElementType(Ctx, X: VX, Y: VY),
14698 SizeExpr: getCommonSizeExpr(Ctx, X: VX, Y: VY),
14699 AttrLoc: getCommonAttrLoc(X: VX, Y: VY));
14700 }
14701 case Type::DependentVector: {
14702 const auto *VX = cast<DependentVectorType>(Val: X),
14703 *VY = cast<DependentVectorType>(Val: Y);
14704 assert(VX->getVectorKind() == VY->getVectorKind());
14705 return Ctx.getDependentVectorType(
14706 VecType: getCommonElementType(Ctx, X: VX, Y: VY), SizeExpr: getCommonSizeExpr(Ctx, X: VX, Y: VY),
14707 AttrLoc: getCommonAttrLoc(X: VX, Y: VY), VecKind: VX->getVectorKind());
14708 }
14709 case Type::Enum:
14710 case Type::Record:
14711 case Type::InjectedClassName: {
14712 const auto *TX = cast<TagType>(Val: X), *TY = cast<TagType>(Val: Y);
14713 return Ctx.getTagType(Keyword: ::getCommonTypeKeyword(X: TX, Y: TY, /*IsSame=*/false),
14714 Qualifier: ::getCommonQualifier(Ctx, X: TX, Y: TY, /*IsSame=*/false),
14715 TD: ::getCommonDeclChecked(X: TX->getDecl(), Y: TY->getDecl()),
14716 /*OwnedTag=*/OwnsTag: false);
14717 }
14718 case Type::TemplateSpecialization: {
14719 const auto *TX = cast<TemplateSpecializationType>(Val: X),
14720 *TY = cast<TemplateSpecializationType>(Val: Y);
14721 auto As = getCommonTemplateArguments(Ctx, Xs: TX->template_arguments(),
14722 Ys: TY->template_arguments());
14723 return Ctx.getTemplateSpecializationType(
14724 Keyword: getCommonTypeKeyword(X: TX, Y: TY, /*IsSame=*/false),
14725 Template: ::getCommonTemplateNameChecked(Ctx, X: TX->getTemplateName(),
14726 Y: TY->getTemplateName(),
14727 /*IgnoreDeduced=*/true),
14728 SpecifiedArgs: As, /*CanonicalArgs=*/{}, Underlying: X->getCanonicalTypeInternal());
14729 }
14730 case Type::Decltype: {
14731 const auto *DX = cast<DecltypeType>(Val: X);
14732 [[maybe_unused]] const auto *DY = cast<DecltypeType>(Val: Y);
14733 assert(DX->isDependentType());
14734 assert(DY->isDependentType());
14735 assert(Ctx.hasSameExpr(DX->getUnderlyingExpr(), DY->getUnderlyingExpr()));
14736 // As Decltype is not uniqued, building a common type would be wasteful.
14737 return QualType(DX, 0);
14738 }
14739 case Type::PackIndexing: {
14740 const auto *DX = cast<PackIndexingType>(Val: X);
14741 [[maybe_unused]] const auto *DY = cast<PackIndexingType>(Val: Y);
14742 assert(DX->isDependentType());
14743 assert(DY->isDependentType());
14744 assert(Ctx.hasSameExpr(DX->getIndexExpr(), DY->getIndexExpr()));
14745 return QualType(DX, 0);
14746 }
14747 case Type::DependentName: {
14748 const auto *NX = cast<DependentNameType>(Val: X),
14749 *NY = cast<DependentNameType>(Val: Y);
14750 assert(NX->getIdentifier() == NY->getIdentifier());
14751 return Ctx.getDependentNameType(
14752 Keyword: getCommonTypeKeyword(X: NX, Y: NY, /*IsSame=*/true),
14753 NNS: getCommonQualifier(Ctx, X: NX, Y: NY, /*IsSame=*/true), Name: NX->getIdentifier());
14754 }
14755 case Type::OverflowBehavior: {
14756 const auto *NX = cast<OverflowBehaviorType>(Val: X),
14757 *NY = cast<OverflowBehaviorType>(Val: Y);
14758 assert(NX->getBehaviorKind() == NY->getBehaviorKind());
14759 return Ctx.getOverflowBehaviorType(
14760 Kind: NX->getBehaviorKind(),
14761 Underlying: getCommonTypeWithQualifierLifting(Ctx, X: NX->getUnderlyingType(),
14762 Y: NY->getUnderlyingType(), QX, QY));
14763 }
14764 case Type::UnaryTransform: {
14765 const auto *TX = cast<UnaryTransformType>(Val: X),
14766 *TY = cast<UnaryTransformType>(Val: Y);
14767 assert(TX->getUTTKind() == TY->getUTTKind());
14768 return Ctx.getUnaryTransformType(
14769 BaseType: Ctx.getCommonSugaredType(X: TX->getBaseType(), Y: TY->getBaseType()),
14770 UnderlyingType: Ctx.getCommonSugaredType(X: TX->getUnderlyingType(),
14771 Y: TY->getUnderlyingType()),
14772 Kind: TX->getUTTKind());
14773 }
14774 case Type::PackExpansion: {
14775 const auto *PX = cast<PackExpansionType>(Val: X),
14776 *PY = cast<PackExpansionType>(Val: Y);
14777 assert(PX->getNumExpansions() == PY->getNumExpansions());
14778 return Ctx.getPackExpansionType(
14779 Pattern: Ctx.getCommonSugaredType(X: PX->getPattern(), Y: PY->getPattern()),
14780 NumExpansions: PX->getNumExpansions(), ExpectPackInType: false);
14781 }
14782 case Type::Pipe: {
14783 const auto *PX = cast<PipeType>(Val: X), *PY = cast<PipeType>(Val: Y);
14784 assert(PX->isReadOnly() == PY->isReadOnly());
14785 auto MP = PX->isReadOnly() ? &ASTContext::getReadPipeType
14786 : &ASTContext::getWritePipeType;
14787 return (Ctx.*MP)(getCommonElementType(Ctx, X: PX, Y: PY));
14788 }
14789 case Type::TemplateTypeParm: {
14790 const auto *TX = cast<TemplateTypeParmType>(Val: X),
14791 *TY = cast<TemplateTypeParmType>(Val: Y);
14792 assert(TX->getDepth() == TY->getDepth());
14793 assert(TX->getIndex() == TY->getIndex());
14794 assert(TX->isParameterPack() == TY->isParameterPack());
14795 return Ctx.getTemplateTypeParmType(
14796 Depth: TX->getDepth(), Index: TX->getIndex(), ParameterPack: TX->isParameterPack(),
14797 TTPDecl: getCommonDecl(X: TX->getDecl(), Y: TY->getDecl()));
14798 }
14799 }
14800 llvm_unreachable("Unknown Type Class");
14801}
14802
14803static QualType getCommonSugarTypeNode(const ASTContext &Ctx, const Type *X,
14804 const Type *Y,
14805 SplitQualType Underlying) {
14806 Type::TypeClass TC = X->getTypeClass();
14807 if (TC != Y->getTypeClass())
14808 return QualType();
14809 switch (TC) {
14810#define UNEXPECTED_TYPE(Class, Kind) \
14811 case Type::Class: \
14812 llvm_unreachable("Unexpected " Kind ": " #Class);
14813#define TYPE(Class, Base)
14814#define DEPENDENT_TYPE(Class, Base) UNEXPECTED_TYPE(Class, "dependent")
14815#include "clang/AST/TypeNodes.inc"
14816
14817#define CANONICAL_TYPE(Class) UNEXPECTED_TYPE(Class, "canonical")
14818 CANONICAL_TYPE(Atomic)
14819 CANONICAL_TYPE(BitInt)
14820 CANONICAL_TYPE(BlockPointer)
14821 CANONICAL_TYPE(Builtin)
14822 CANONICAL_TYPE(Complex)
14823 CANONICAL_TYPE(ConstantArray)
14824 CANONICAL_TYPE(ArrayParameter)
14825 CANONICAL_TYPE(ConstantMatrix)
14826 CANONICAL_TYPE(Enum)
14827 CANONICAL_TYPE(ExtVector)
14828 CANONICAL_TYPE(FunctionNoProto)
14829 CANONICAL_TYPE(FunctionProto)
14830 CANONICAL_TYPE(IncompleteArray)
14831 CANONICAL_TYPE(HLSLAttributedResource)
14832 CANONICAL_TYPE(HLSLInlineSpirv)
14833 CANONICAL_TYPE(LValueReference)
14834 CANONICAL_TYPE(ObjCInterface)
14835 CANONICAL_TYPE(ObjCObject)
14836 CANONICAL_TYPE(ObjCObjectPointer)
14837 CANONICAL_TYPE(OverflowBehavior)
14838 CANONICAL_TYPE(Pipe)
14839 CANONICAL_TYPE(Pointer)
14840 CANONICAL_TYPE(Record)
14841 CANONICAL_TYPE(RValueReference)
14842 CANONICAL_TYPE(VariableArray)
14843 CANONICAL_TYPE(Vector)
14844#undef CANONICAL_TYPE
14845
14846#undef UNEXPECTED_TYPE
14847
14848 case Type::Adjusted: {
14849 const auto *AX = cast<AdjustedType>(Val: X), *AY = cast<AdjustedType>(Val: Y);
14850 QualType OX = AX->getOriginalType(), OY = AY->getOriginalType();
14851 if (!Ctx.hasSameType(T1: OX, T2: OY))
14852 return QualType();
14853 // FIXME: It's inefficient to have to unify the original types.
14854 return Ctx.getAdjustedType(Orig: Ctx.getCommonSugaredType(X: OX, Y: OY),
14855 New: Ctx.getQualifiedType(split: Underlying));
14856 }
14857 case Type::Decayed: {
14858 const auto *DX = cast<DecayedType>(Val: X), *DY = cast<DecayedType>(Val: Y);
14859 QualType OX = DX->getOriginalType(), OY = DY->getOriginalType();
14860 if (!Ctx.hasSameType(T1: OX, T2: OY))
14861 return QualType();
14862 // FIXME: It's inefficient to have to unify the original types.
14863 return Ctx.getDecayedType(Orig: Ctx.getCommonSugaredType(X: OX, Y: OY),
14864 Decayed: Ctx.getQualifiedType(split: Underlying));
14865 }
14866 case Type::Attributed: {
14867 const auto *AX = cast<AttributedType>(Val: X), *AY = cast<AttributedType>(Val: Y);
14868 AttributedType::Kind Kind = AX->getAttrKind();
14869 if (Kind != AY->getAttrKind())
14870 return QualType();
14871 QualType MX = AX->getModifiedType(), MY = AY->getModifiedType();
14872 if (!Ctx.hasSameType(T1: MX, T2: MY))
14873 return QualType();
14874 // FIXME: It's inefficient to have to unify the modified types.
14875 return Ctx.getAttributedType(attrKind: Kind, modifiedType: Ctx.getCommonSugaredType(X: MX, Y: MY),
14876 equivalentType: Ctx.getQualifiedType(split: Underlying),
14877 attr: AX->getAttr());
14878 }
14879 case Type::BTFTagAttributed: {
14880 const auto *BX = cast<BTFTagAttributedType>(Val: X);
14881 const BTFTypeTagAttr *AX = BX->getAttr();
14882 // The attribute is not uniqued, so just compare the tag.
14883 if (AX->getBTFTypeTag() !=
14884 cast<BTFTagAttributedType>(Val: Y)->getAttr()->getBTFTypeTag())
14885 return QualType();
14886 return Ctx.getBTFTagAttributedType(BTFAttr: AX, Wrapped: Ctx.getQualifiedType(split: Underlying));
14887 }
14888 case Type::Auto: {
14889 const auto *AX = cast<AutoType>(Val: X), *AY = cast<AutoType>(Val: Y);
14890 assert(AX->getDeducedKind() == DeducedKind::Deduced);
14891 assert(AY->getDeducedKind() == DeducedKind::Deduced);
14892
14893 AutoTypeKeyword KW = AX->getKeyword();
14894 if (KW != AY->getKeyword())
14895 return QualType();
14896
14897 TemplateDecl *CD =
14898 ::getCommonDecl(X: AX->getTypeConstraintConcept().getAsTemplateDecl(),
14899 Y: AY->getTypeConstraintConcept().getAsTemplateDecl());
14900 SmallVector<TemplateArgument, 8> As;
14901 if (CD &&
14902 getCommonTemplateArguments(Ctx, R&: As, Xs: AX->getTypeConstraintArguments(),
14903 Ys: AY->getTypeConstraintArguments())) {
14904 CD = nullptr; // The arguments differ, so make it unconstrained.
14905 As.clear();
14906 }
14907
14908 // Both auto types can't be dependent, otherwise they wouldn't have been
14909 // sugar. This implies they can't contain unexpanded packs either.
14910 return Ctx.getAutoType(DK: DeducedKind::Deduced,
14911 DeducedAsType: Ctx.getQualifiedType(split: Underlying), Keyword: AX->getKeyword(),
14912 TypeConstraintConcept: TemplateName(CD), TypeConstraintArgs: As);
14913 }
14914 case Type::PackIndexing:
14915 case Type::Decltype:
14916 return QualType();
14917 case Type::DeducedTemplateSpecialization:
14918 // FIXME: Try to merge these.
14919 return QualType();
14920 case Type::MacroQualified: {
14921 const auto *MX = cast<MacroQualifiedType>(Val: X),
14922 *MY = cast<MacroQualifiedType>(Val: Y);
14923 const IdentifierInfo *IX = MX->getMacroIdentifier();
14924 if (IX != MY->getMacroIdentifier())
14925 return QualType();
14926 return Ctx.getMacroQualifiedType(UnderlyingTy: Ctx.getQualifiedType(split: Underlying), MacroII: IX);
14927 }
14928 case Type::SubstTemplateTypeParm: {
14929 const auto *SX = cast<SubstTemplateTypeParmType>(Val: X),
14930 *SY = cast<SubstTemplateTypeParmType>(Val: Y);
14931 Decl *CD =
14932 ::getCommonDecl(X: SX->getAssociatedDecl(), Y: SY->getAssociatedDecl());
14933 if (!CD)
14934 return QualType();
14935 unsigned Index = SX->getIndex();
14936 if (Index != SY->getIndex())
14937 return QualType();
14938 auto PackIndex = SX->getPackIndex();
14939 if (PackIndex != SY->getPackIndex())
14940 return QualType();
14941 return Ctx.getSubstTemplateTypeParmType(Replacement: Ctx.getQualifiedType(split: Underlying),
14942 AssociatedDecl: CD, Index, PackIndex,
14943 Final: SX->getFinal() && SY->getFinal());
14944 }
14945 case Type::ObjCTypeParam:
14946 // FIXME: Try to merge these.
14947 return QualType();
14948 case Type::Paren:
14949 return Ctx.getParenType(InnerType: Ctx.getQualifiedType(split: Underlying));
14950
14951 case Type::TemplateSpecialization: {
14952 const auto *TX = cast<TemplateSpecializationType>(Val: X),
14953 *TY = cast<TemplateSpecializationType>(Val: Y);
14954 TemplateName CTN =
14955 ::getCommonTemplateName(Ctx, X: TX->getTemplateName(),
14956 Y: TY->getTemplateName(), /*IgnoreDeduced=*/true);
14957 if (!CTN.getAsVoidPointer())
14958 return QualType();
14959 SmallVector<TemplateArgument, 8> As;
14960 if (getCommonTemplateArguments(Ctx, R&: As, Xs: TX->template_arguments(),
14961 Ys: TY->template_arguments()))
14962 return QualType();
14963 return Ctx.getTemplateSpecializationType(
14964 Keyword: getCommonTypeKeyword(X: TX, Y: TY, /*IsSame=*/false), Template: CTN, SpecifiedArgs: As,
14965 /*CanonicalArgs=*/{}, Underlying: Ctx.getQualifiedType(split: Underlying));
14966 }
14967 case Type::Typedef: {
14968 const auto *TX = cast<TypedefType>(Val: X), *TY = cast<TypedefType>(Val: Y);
14969 const TypedefNameDecl *CD = ::getCommonDecl(X: TX->getDecl(), Y: TY->getDecl());
14970 if (!CD)
14971 return QualType();
14972 return Ctx.getTypedefType(
14973 Keyword: ::getCommonTypeKeyword(X: TX, Y: TY, /*IsSame=*/false),
14974 Qualifier: ::getCommonQualifier(Ctx, X: TX, Y: TY, /*IsSame=*/false), Decl: CD,
14975 UnderlyingType: Ctx.getQualifiedType(split: Underlying));
14976 }
14977 case Type::TypeOf: {
14978 // The common sugar between two typeof expressions, where one is
14979 // potentially a typeof_unqual and the other is not, we unify to the
14980 // qualified type as that retains the most information along with the type.
14981 // We only return a typeof_unqual type when both types are unqual types.
14982 TypeOfKind Kind = TypeOfKind::Qualified;
14983 if (cast<TypeOfType>(Val: X)->getKind() == cast<TypeOfType>(Val: Y)->getKind() &&
14984 cast<TypeOfType>(Val: X)->getKind() == TypeOfKind::Unqualified)
14985 Kind = TypeOfKind::Unqualified;
14986 return Ctx.getTypeOfType(tofType: Ctx.getQualifiedType(split: Underlying), Kind);
14987 }
14988 case Type::TypeOfExpr:
14989 return QualType();
14990
14991 case Type::UnaryTransform: {
14992 const auto *UX = cast<UnaryTransformType>(Val: X),
14993 *UY = cast<UnaryTransformType>(Val: Y);
14994 UnaryTransformType::UTTKind KX = UX->getUTTKind();
14995 if (KX != UY->getUTTKind())
14996 return QualType();
14997 QualType BX = UX->getBaseType(), BY = UY->getBaseType();
14998 if (!Ctx.hasSameType(T1: BX, T2: BY))
14999 return QualType();
15000 // FIXME: It's inefficient to have to unify the base types.
15001 return Ctx.getUnaryTransformType(BaseType: Ctx.getCommonSugaredType(X: BX, Y: BY),
15002 UnderlyingType: Ctx.getQualifiedType(split: Underlying), Kind: KX);
15003 }
15004 case Type::Using: {
15005 const auto *UX = cast<UsingType>(Val: X), *UY = cast<UsingType>(Val: Y);
15006 const UsingShadowDecl *CD = ::getCommonDecl(X: UX->getDecl(), Y: UY->getDecl());
15007 if (!CD)
15008 return QualType();
15009 return Ctx.getUsingType(Keyword: ::getCommonTypeKeyword(X: UX, Y: UY, /*IsSame=*/false),
15010 Qualifier: ::getCommonQualifier(Ctx, X: UX, Y: UY, /*IsSame=*/false),
15011 D: CD, UnderlyingType: Ctx.getQualifiedType(split: Underlying));
15012 }
15013 case Type::MemberPointer: {
15014 const auto *PX = cast<MemberPointerType>(Val: X),
15015 *PY = cast<MemberPointerType>(Val: Y);
15016 CXXRecordDecl *Cls = PX->getMostRecentCXXRecordDecl();
15017 assert(Cls == PY->getMostRecentCXXRecordDecl());
15018 return Ctx.getMemberPointerType(
15019 T: ::getCommonPointeeType(Ctx, X: PX, Y: PY),
15020 Qualifier: ::getCommonQualifier(Ctx, X: PX, Y: PY, /*IsSame=*/false), Cls);
15021 }
15022 case Type::CountAttributed: {
15023 const auto *DX = cast<CountAttributedType>(Val: X),
15024 *DY = cast<CountAttributedType>(Val: Y);
15025 if (DX->isCountInBytes() != DY->isCountInBytes())
15026 return QualType();
15027 if (DX->isOrNull() != DY->isOrNull())
15028 return QualType();
15029 Expr *CEX = DX->getCountExpr();
15030 Expr *CEY = DY->getCountExpr();
15031 ArrayRef<clang::TypeCoupledDeclRefInfo> CDX = DX->getCoupledDecls();
15032 if (Ctx.hasSameExpr(X: CEX, Y: CEY))
15033 return Ctx.getCountAttributedType(WrappedTy: Ctx.getQualifiedType(split: Underlying), CountExpr: CEX,
15034 CountInBytes: DX->isCountInBytes(), OrNull: DX->isOrNull(),
15035 DependentDecls: CDX);
15036 if (!CEX->isIntegerConstantExpr(Ctx) || !CEY->isIntegerConstantExpr(Ctx))
15037 return QualType();
15038 // Two declarations with the same integer constant may still differ in their
15039 // expression pointers, so we need to evaluate them.
15040 llvm::APSInt VX = *CEX->getIntegerConstantExpr(Ctx);
15041 llvm::APSInt VY = *CEY->getIntegerConstantExpr(Ctx);
15042 if (VX != VY)
15043 return QualType();
15044 return Ctx.getCountAttributedType(WrappedTy: Ctx.getQualifiedType(split: Underlying), CountExpr: CEX,
15045 CountInBytes: DX->isCountInBytes(), OrNull: DX->isOrNull(),
15046 DependentDecls: CDX);
15047 }
15048
15049 case Type::LateParsedAttr:
15050 return QualType();
15051
15052 case Type::PredefinedSugar:
15053 assert(cast<PredefinedSugarType>(X)->getKind() !=
15054 cast<PredefinedSugarType>(Y)->getKind());
15055 return QualType();
15056 }
15057 llvm_unreachable("Unhandled Type Class");
15058}
15059
15060static auto unwrapSugar(SplitQualType &T, Qualifiers &QTotal) {
15061 SmallVector<SplitQualType, 8> R;
15062 while (true) {
15063 QTotal.addConsistentQualifiers(qs: T.Quals);
15064 QualType NT = T.Ty->getLocallyUnqualifiedSingleStepDesugaredType();
15065 if (NT == QualType(T.Ty, 0))
15066 break;
15067 R.push_back(Elt: T);
15068 T = NT.split();
15069 }
15070 return R;
15071}
15072
15073QualType ASTContext::getCommonSugaredType(QualType X, QualType Y,
15074 bool Unqualified) const {
15075 assert(Unqualified ? hasSameUnqualifiedType(X, Y) : hasSameType(X, Y));
15076 if (X == Y)
15077 return X;
15078 if (!Unqualified) {
15079 if (X.isCanonical())
15080 return X;
15081 if (Y.isCanonical())
15082 return Y;
15083 }
15084
15085 SplitQualType SX = X.split(), SY = Y.split();
15086 Qualifiers QX, QY;
15087 // Desugar SX and SY, setting the sugar and qualifiers aside into Xs and Ys,
15088 // until we reach their underlying "canonical nodes". Note these are not
15089 // necessarily canonical types, as they may still have sugared properties.
15090 // QX and QY will store the sum of all qualifiers in Xs and Ys respectively.
15091 auto Xs = ::unwrapSugar(T&: SX, QTotal&: QX), Ys = ::unwrapSugar(T&: SY, QTotal&: QY);
15092
15093 // If this is an ArrayType, the element qualifiers are interchangeable with
15094 // the top level qualifiers.
15095 // * In case the canonical nodes are the same, the elements types are already
15096 // the same.
15097 // * Otherwise, the element types will be made the same, and any different
15098 // element qualifiers will be moved up to the top level qualifiers, per
15099 // 'getCommonArrayElementType'.
15100 // In both cases, this means there may be top level qualifiers which differ
15101 // between X and Y. If so, these differing qualifiers are redundant with the
15102 // element qualifiers, and can be removed without changing the canonical type.
15103 // The desired behaviour is the same as for the 'Unqualified' case here:
15104 // treat the redundant qualifiers as sugar, remove the ones which are not
15105 // common to both sides.
15106 bool KeepCommonQualifiers =
15107 Unqualified || isa<ArrayType, OverflowBehaviorType>(Val: SX.Ty);
15108
15109 if (SX.Ty != SY.Ty) {
15110 // The canonical nodes differ. Build a common canonical node out of the two,
15111 // unifying their sugar. This may recurse back here.
15112 SX.Ty =
15113 ::getCommonNonSugarTypeNode(Ctx: *this, X: SX.Ty, QX, Y: SY.Ty, QY).getTypePtr();
15114 } else {
15115 // The canonical nodes were identical: We may have desugared too much.
15116 // Add any common sugar back in.
15117 while (!Xs.empty() && !Ys.empty() && Xs.back().Ty == Ys.back().Ty) {
15118 QX -= SX.Quals;
15119 QY -= SY.Quals;
15120 SX = Xs.pop_back_val();
15121 SY = Ys.pop_back_val();
15122 }
15123 }
15124 if (KeepCommonQualifiers)
15125 QX = Qualifiers::removeCommonQualifiers(L&: QX, R&: QY);
15126 else
15127 assert(QX == QY);
15128
15129 // Even though the remaining sugar nodes in Xs and Ys differ, some may be
15130 // related. Walk up these nodes, unifying them and adding the result.
15131 while (!Xs.empty() && !Ys.empty()) {
15132 auto Underlying = SplitQualType(
15133 SX.Ty, Qualifiers::removeCommonQualifiers(L&: SX.Quals, R&: SY.Quals));
15134 SX = Xs.pop_back_val();
15135 SY = Ys.pop_back_val();
15136 SX.Ty = ::getCommonSugarTypeNode(Ctx: *this, X: SX.Ty, Y: SY.Ty, Underlying)
15137 .getTypePtrOrNull();
15138 // Stop at the first pair which is unrelated.
15139 if (!SX.Ty) {
15140 SX.Ty = Underlying.Ty;
15141 break;
15142 }
15143 QX -= Underlying.Quals;
15144 };
15145
15146 // Add back the missing accumulated qualifiers, which were stripped off
15147 // with the sugar nodes we could not unify.
15148 QualType R = getQualifiedType(T: SX.Ty, Qs: QX);
15149 assert(Unqualified ? hasSameUnqualifiedType(R, X) : hasSameType(R, X));
15150 return R;
15151}
15152
15153QualType ASTContext::getCorrespondingUnsaturatedType(QualType Ty) const {
15154 assert(Ty->isFixedPointType());
15155
15156 if (Ty->isUnsaturatedFixedPointType())
15157 return Ty;
15158
15159 switch (Ty->castAs<BuiltinType>()->getKind()) {
15160 default:
15161 llvm_unreachable("Not a saturated fixed point type!");
15162 case BuiltinType::SatShortAccum:
15163 return ShortAccumTy;
15164 case BuiltinType::SatAccum:
15165 return AccumTy;
15166 case BuiltinType::SatLongAccum:
15167 return LongAccumTy;
15168 case BuiltinType::SatUShortAccum:
15169 return UnsignedShortAccumTy;
15170 case BuiltinType::SatUAccum:
15171 return UnsignedAccumTy;
15172 case BuiltinType::SatULongAccum:
15173 return UnsignedLongAccumTy;
15174 case BuiltinType::SatShortFract:
15175 return ShortFractTy;
15176 case BuiltinType::SatFract:
15177 return FractTy;
15178 case BuiltinType::SatLongFract:
15179 return LongFractTy;
15180 case BuiltinType::SatUShortFract:
15181 return UnsignedShortFractTy;
15182 case BuiltinType::SatUFract:
15183 return UnsignedFractTy;
15184 case BuiltinType::SatULongFract:
15185 return UnsignedLongFractTy;
15186 }
15187}
15188
15189QualType ASTContext::getCorrespondingSaturatedType(QualType Ty) const {
15190 assert(Ty->isFixedPointType());
15191
15192 if (Ty->isSaturatedFixedPointType()) return Ty;
15193
15194 switch (Ty->castAs<BuiltinType>()->getKind()) {
15195 default:
15196 llvm_unreachable("Not a fixed point type!");
15197 case BuiltinType::ShortAccum:
15198 return SatShortAccumTy;
15199 case BuiltinType::Accum:
15200 return SatAccumTy;
15201 case BuiltinType::LongAccum:
15202 return SatLongAccumTy;
15203 case BuiltinType::UShortAccum:
15204 return SatUnsignedShortAccumTy;
15205 case BuiltinType::UAccum:
15206 return SatUnsignedAccumTy;
15207 case BuiltinType::ULongAccum:
15208 return SatUnsignedLongAccumTy;
15209 case BuiltinType::ShortFract:
15210 return SatShortFractTy;
15211 case BuiltinType::Fract:
15212 return SatFractTy;
15213 case BuiltinType::LongFract:
15214 return SatLongFractTy;
15215 case BuiltinType::UShortFract:
15216 return SatUnsignedShortFractTy;
15217 case BuiltinType::UFract:
15218 return SatUnsignedFractTy;
15219 case BuiltinType::ULongFract:
15220 return SatUnsignedLongFractTy;
15221 }
15222}
15223
15224LangAS ASTContext::getLangASForBuiltinAddressSpace(unsigned AS) const {
15225 if (LangOpts.OpenCL)
15226 return getTargetInfo().getOpenCLBuiltinAddressSpace(AS);
15227
15228 if (LangOpts.CUDA)
15229 return getTargetInfo().getCUDABuiltinAddressSpace(AS);
15230
15231 return getLangASFromTargetAS(TargetAS: AS);
15232}
15233
15234unsigned char ASTContext::getFixedPointScale(QualType Ty) const {
15235 assert(Ty->isFixedPointType());
15236
15237 const TargetInfo &Target = getTargetInfo();
15238 switch (Ty->castAs<BuiltinType>()->getKind()) {
15239 default:
15240 llvm_unreachable("Not a fixed point type!");
15241 case BuiltinType::ShortAccum:
15242 case BuiltinType::SatShortAccum:
15243 return Target.getShortAccumScale();
15244 case BuiltinType::Accum:
15245 case BuiltinType::SatAccum:
15246 return Target.getAccumScale();
15247 case BuiltinType::LongAccum:
15248 case BuiltinType::SatLongAccum:
15249 return Target.getLongAccumScale();
15250 case BuiltinType::UShortAccum:
15251 case BuiltinType::SatUShortAccum:
15252 return Target.getUnsignedShortAccumScale();
15253 case BuiltinType::UAccum:
15254 case BuiltinType::SatUAccum:
15255 return Target.getUnsignedAccumScale();
15256 case BuiltinType::ULongAccum:
15257 case BuiltinType::SatULongAccum:
15258 return Target.getUnsignedLongAccumScale();
15259 case BuiltinType::ShortFract:
15260 case BuiltinType::SatShortFract:
15261 return Target.getShortFractScale();
15262 case BuiltinType::Fract:
15263 case BuiltinType::SatFract:
15264 return Target.getFractScale();
15265 case BuiltinType::LongFract:
15266 case BuiltinType::SatLongFract:
15267 return Target.getLongFractScale();
15268 case BuiltinType::UShortFract:
15269 case BuiltinType::SatUShortFract:
15270 return Target.getUnsignedShortFractScale();
15271 case BuiltinType::UFract:
15272 case BuiltinType::SatUFract:
15273 return Target.getUnsignedFractScale();
15274 case BuiltinType::ULongFract:
15275 case BuiltinType::SatULongFract:
15276 return Target.getUnsignedLongFractScale();
15277 }
15278}
15279
15280unsigned char ASTContext::getFixedPointIBits(QualType Ty) const {
15281 assert(Ty->isFixedPointType());
15282
15283 const TargetInfo &Target = getTargetInfo();
15284 switch (Ty->castAs<BuiltinType>()->getKind()) {
15285 default:
15286 llvm_unreachable("Not a fixed point type!");
15287 case BuiltinType::ShortAccum:
15288 case BuiltinType::SatShortAccum:
15289 return Target.getShortAccumIBits();
15290 case BuiltinType::Accum:
15291 case BuiltinType::SatAccum:
15292 return Target.getAccumIBits();
15293 case BuiltinType::LongAccum:
15294 case BuiltinType::SatLongAccum:
15295 return Target.getLongAccumIBits();
15296 case BuiltinType::UShortAccum:
15297 case BuiltinType::SatUShortAccum:
15298 return Target.getUnsignedShortAccumIBits();
15299 case BuiltinType::UAccum:
15300 case BuiltinType::SatUAccum:
15301 return Target.getUnsignedAccumIBits();
15302 case BuiltinType::ULongAccum:
15303 case BuiltinType::SatULongAccum:
15304 return Target.getUnsignedLongAccumIBits();
15305 case BuiltinType::ShortFract:
15306 case BuiltinType::SatShortFract:
15307 case BuiltinType::Fract:
15308 case BuiltinType::SatFract:
15309 case BuiltinType::LongFract:
15310 case BuiltinType::SatLongFract:
15311 case BuiltinType::UShortFract:
15312 case BuiltinType::SatUShortFract:
15313 case BuiltinType::UFract:
15314 case BuiltinType::SatUFract:
15315 case BuiltinType::ULongFract:
15316 case BuiltinType::SatULongFract:
15317 return 0;
15318 }
15319}
15320
15321llvm::FixedPointSemantics
15322ASTContext::getFixedPointSemantics(QualType Ty) const {
15323 assert((Ty->isFixedPointType() || Ty->isIntegerType()) &&
15324 "Can only get the fixed point semantics for a "
15325 "fixed point or integer type.");
15326 if (Ty->isIntegerType())
15327 return llvm::FixedPointSemantics::GetIntegerSemantics(
15328 Width: getIntWidth(T: Ty), IsSigned: Ty->isSignedIntegerType());
15329
15330 bool isSigned = Ty->isSignedFixedPointType();
15331 return llvm::FixedPointSemantics(
15332 static_cast<unsigned>(getTypeSize(T: Ty)), getFixedPointScale(Ty), isSigned,
15333 Ty->isSaturatedFixedPointType(),
15334 !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding());
15335}
15336
15337llvm::APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const {
15338 assert(Ty->isFixedPointType());
15339 return llvm::APFixedPoint::getMax(Sema: getFixedPointSemantics(Ty));
15340}
15341
15342llvm::APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const {
15343 assert(Ty->isFixedPointType());
15344 return llvm::APFixedPoint::getMin(Sema: getFixedPointSemantics(Ty));
15345}
15346
15347QualType ASTContext::getCorrespondingSignedFixedPointType(QualType Ty) const {
15348 assert(Ty->isUnsignedFixedPointType() &&
15349 "Expected unsigned fixed point type");
15350
15351 switch (Ty->castAs<BuiltinType>()->getKind()) {
15352 case BuiltinType::UShortAccum:
15353 return ShortAccumTy;
15354 case BuiltinType::UAccum:
15355 return AccumTy;
15356 case BuiltinType::ULongAccum:
15357 return LongAccumTy;
15358 case BuiltinType::SatUShortAccum:
15359 return SatShortAccumTy;
15360 case BuiltinType::SatUAccum:
15361 return SatAccumTy;
15362 case BuiltinType::SatULongAccum:
15363 return SatLongAccumTy;
15364 case BuiltinType::UShortFract:
15365 return ShortFractTy;
15366 case BuiltinType::UFract:
15367 return FractTy;
15368 case BuiltinType::ULongFract:
15369 return LongFractTy;
15370 case BuiltinType::SatUShortFract:
15371 return SatShortFractTy;
15372 case BuiltinType::SatUFract:
15373 return SatFractTy;
15374 case BuiltinType::SatULongFract:
15375 return SatLongFractTy;
15376 default:
15377 llvm_unreachable("Unexpected unsigned fixed point type");
15378 }
15379}
15380
15381// Given a list of FMV features, return a concatenated list of the
15382// corresponding backend features (which may contain duplicates).
15383static std::vector<std::string> getFMVBackendFeaturesFor(
15384 const llvm::SmallVectorImpl<StringRef> &FMVFeatStrings) {
15385 std::vector<std::string> BackendFeats;
15386 llvm::AArch64::ExtensionSet FeatureBits;
15387 for (StringRef F : FMVFeatStrings)
15388 if (auto FMVExt = llvm::AArch64::parseFMVExtension(Extension: F))
15389 if (FMVExt->ID)
15390 FeatureBits.enable(E: *FMVExt->ID);
15391 FeatureBits.toLLVMFeatureList(Features&: BackendFeats);
15392 return BackendFeats;
15393}
15394
15395ParsedTargetAttr
15396ASTContext::filterFunctionTargetAttrs(const TargetAttr *TD) const {
15397 assert(TD != nullptr);
15398 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(Str: TD->getFeaturesStr());
15399
15400 llvm::erase_if(C&: ParsedAttr.Features, P: [&](const std::string &Feat) {
15401 return !Target->isValidFeatureName(Feature: StringRef{Feat}.substr(Start: 1));
15402 });
15403 return ParsedAttr;
15404}
15405
15406void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
15407 const FunctionDecl *FD) const {
15408 if (FD)
15409 getFunctionFeatureMap(FeatureMap, GD: GlobalDecl().getWithDecl(D: FD));
15410 else
15411 Target->initFeatureMap(Features&: FeatureMap, Diags&: getDiagnostics(),
15412 CPU: Target->getTargetOpts().CPU,
15413 FeatureVec: Target->getTargetOpts().Features);
15414}
15415
15416// Fills in the supplied string map with the set of target features for the
15417// passed in function.
15418void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
15419 GlobalDecl GD) const {
15420 StringRef TargetCPU = Target->getTargetOpts().CPU;
15421 const FunctionDecl *FD = GD.getDecl()->getAsFunction();
15422 if (const auto *TD = FD->getAttr<TargetAttr>()) {
15423 ParsedTargetAttr ParsedAttr = filterFunctionTargetAttrs(TD);
15424
15425 // Make a copy of the features as passed on the command line into the
15426 // beginning of the additional features from the function to override.
15427 // AArch64 handles command line option features in parseTargetAttr().
15428 if (!Target->getTriple().isAArch64())
15429 ParsedAttr.Features.insert(
15430 position: ParsedAttr.Features.begin(),
15431 first: Target->getTargetOpts().FeaturesAsWritten.begin(),
15432 last: Target->getTargetOpts().FeaturesAsWritten.end());
15433
15434 if (ParsedAttr.CPU != "" && Target->isValidCPUName(Name: ParsedAttr.CPU))
15435 TargetCPU = ParsedAttr.CPU;
15436
15437 // Now populate the feature map, first with the TargetCPU which is either
15438 // the default or a new one from the target attribute string. Then we'll use
15439 // the passed in features (FeaturesAsWritten) along with the new ones from
15440 // the attribute.
15441 Target->initFeatureMap(Features&: FeatureMap, Diags&: getDiagnostics(), CPU: TargetCPU,
15442 FeatureVec: ParsedAttr.Features);
15443 } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) {
15444 llvm::SmallVector<StringRef, 32> FeaturesTmp;
15445 Target->getCPUSpecificCPUDispatchFeatures(
15446 Name: SD->getCPUName(Index: GD.getMultiVersionIndex())->getName(), Features&: FeaturesTmp);
15447 std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end());
15448 Features.insert(position: Features.begin(),
15449 first: Target->getTargetOpts().FeaturesAsWritten.begin(),
15450 last: Target->getTargetOpts().FeaturesAsWritten.end());
15451 Target->initFeatureMap(Features&: FeatureMap, Diags&: getDiagnostics(), CPU: TargetCPU, FeatureVec: Features);
15452 } else if (const auto *TC = FD->getAttr<TargetClonesAttr>()) {
15453 if (Target->getTriple().isAArch64()) {
15454 llvm::SmallVector<StringRef, 8> Feats;
15455 TC->getFeatures(Out&: Feats, Index: GD.getMultiVersionIndex());
15456 std::vector<std::string> Features = getFMVBackendFeaturesFor(FMVFeatStrings: Feats);
15457 Features.insert(position: Features.begin(),
15458 first: Target->getTargetOpts().FeaturesAsWritten.begin(),
15459 last: Target->getTargetOpts().FeaturesAsWritten.end());
15460 Target->initFeatureMap(Features&: FeatureMap, Diags&: getDiagnostics(), CPU: TargetCPU, FeatureVec: Features);
15461 } else if (Target->getTriple().isRISCV()) {
15462 StringRef VersionStr = TC->getFeatureStr(Index: GD.getMultiVersionIndex());
15463 std::vector<std::string> Features;
15464 if (VersionStr != "default") {
15465 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(Str: VersionStr);
15466 Features.insert(position: Features.begin(), first: ParsedAttr.Features.begin(),
15467 last: ParsedAttr.Features.end());
15468 }
15469 Features.insert(position: Features.begin(),
15470 first: Target->getTargetOpts().FeaturesAsWritten.begin(),
15471 last: Target->getTargetOpts().FeaturesAsWritten.end());
15472 Target->initFeatureMap(Features&: FeatureMap, Diags&: getDiagnostics(), CPU: TargetCPU, FeatureVec: Features);
15473 } else if (Target->getTriple().isOSAIX()) {
15474 std::vector<std::string> Features;
15475 StringRef VersionStr = TC->getFeatureStr(Index: GD.getMultiVersionIndex());
15476 if (VersionStr.starts_with(Prefix: "cpu="))
15477 TargetCPU = VersionStr.drop_front(N: sizeof("cpu=") - 1);
15478 else if (VersionStr != "default")
15479 Features = Target->parseTargetAttr(Str: VersionStr).Features;
15480 Target->initFeatureMap(Features&: FeatureMap, Diags&: getDiagnostics(), CPU: TargetCPU, FeatureVec: Features);
15481 } else {
15482 std::vector<std::string> Features;
15483 StringRef VersionStr = TC->getFeatureStr(Index: GD.getMultiVersionIndex());
15484 if (VersionStr.starts_with(Prefix: "arch="))
15485 TargetCPU = VersionStr.drop_front(N: sizeof("arch=") - 1);
15486 else if (VersionStr != "default")
15487 Features.push_back(x: (StringRef{"+"} + VersionStr).str());
15488 Target->initFeatureMap(Features&: FeatureMap, Diags&: getDiagnostics(), CPU: TargetCPU, FeatureVec: Features);
15489 }
15490 } else if (const auto *TV = FD->getAttr<TargetVersionAttr>()) {
15491 std::vector<std::string> Features;
15492 if (Target->getTriple().isRISCV()) {
15493 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(Str: TV->getName());
15494 Features.insert(position: Features.begin(), first: ParsedAttr.Features.begin(),
15495 last: ParsedAttr.Features.end());
15496 } else {
15497 assert(Target->getTriple().isAArch64());
15498 llvm::SmallVector<StringRef, 8> Feats;
15499 TV->getFeatures(Out&: Feats);
15500 Features = getFMVBackendFeaturesFor(FMVFeatStrings: Feats);
15501 }
15502 Features.insert(position: Features.begin(),
15503 first: Target->getTargetOpts().FeaturesAsWritten.begin(),
15504 last: Target->getTargetOpts().FeaturesAsWritten.end());
15505 Target->initFeatureMap(Features&: FeatureMap, Diags&: getDiagnostics(), CPU: TargetCPU, FeatureVec: Features);
15506 } else {
15507 FeatureMap = Target->getTargetOpts().FeatureMap;
15508 }
15509}
15510
15511static SYCLKernelInfo BuildSYCLKernelInfo(ASTContext &Context,
15512 CanQualType KernelNameType,
15513 const FunctionDecl *FD) {
15514 // Host and device compilation may use different ABIs and different ABIs
15515 // may allocate name mangling discriminators differently. A discriminator
15516 // override is used to ensure consistent discriminator allocation across
15517 // host and device compilation.
15518 auto DeviceDiscriminatorOverrider =
15519 [](ASTContext &Ctx, const NamedDecl *ND) -> UnsignedOrNone {
15520 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: ND))
15521 if (RD->isLambda())
15522 return RD->getDeviceLambdaManglingNumber();
15523 return std::nullopt;
15524 };
15525 std::unique_ptr<MangleContext> MC{ItaniumMangleContext::create(
15526 Context, Diags&: Context.getDiagnostics(), Discriminator: DeviceDiscriminatorOverrider)};
15527
15528 // Construct a mangled name for the SYCL kernel caller offload entry point.
15529 // FIXME: The Itanium typeinfo mangling (_ZTS<type>) is currently used to
15530 // name the SYCL kernel caller offload entry point function. This mangling
15531 // does not suffice to clearly identify symbols that correspond to SYCL
15532 // kernel caller functions, nor is this mangling natural for targets that
15533 // use a non-Itanium ABI.
15534 std::string Buffer;
15535 Buffer.reserve(res_arg: 128);
15536 llvm::raw_string_ostream Out(Buffer);
15537 MC->mangleCanonicalTypeName(T: KernelNameType, Out);
15538 std::string KernelName = Out.str();
15539
15540 return {KernelNameType, FD, KernelName};
15541}
15542
15543void ASTContext::registerSYCLEntryPointFunction(FunctionDecl *FD) {
15544 // If the function declaration to register is invalid or dependent, the
15545 // registration attempt is ignored.
15546 if (FD->isInvalidDecl() || FD->isTemplated())
15547 return;
15548
15549 const auto *SKEPAttr = FD->getAttr<SYCLKernelEntryPointAttr>();
15550 assert(SKEPAttr && "Missing sycl_kernel_entry_point attribute");
15551
15552 // Be tolerant of multiple registration attempts so long as each attempt
15553 // is for the same entity. Callers are obligated to detect and diagnose
15554 // conflicting kernel names prior to calling this function.
15555 CanQualType KernelNameType = getCanonicalType(T: SKEPAttr->getKernelName());
15556 auto IT = SYCLKernels.find(Val: KernelNameType);
15557 assert((IT == SYCLKernels.end() ||
15558 declaresSameEntity(FD, IT->second.getKernelEntryPointDecl())) &&
15559 "SYCL kernel name conflict");
15560 (void)IT;
15561 SYCLKernels.insert(KV: std::make_pair(
15562 x&: KernelNameType, y: BuildSYCLKernelInfo(Context&: *this, KernelNameType, FD)));
15563}
15564
15565const SYCLKernelInfo &ASTContext::getSYCLKernelInfo(QualType T) const {
15566 CanQualType KernelNameType = getCanonicalType(T);
15567 return SYCLKernels.at(Val: KernelNameType);
15568}
15569
15570const SYCLKernelInfo *ASTContext::findSYCLKernelInfo(QualType T) const {
15571 CanQualType KernelNameType = getCanonicalType(T);
15572 auto IT = SYCLKernels.find(Val: KernelNameType);
15573 if (IT != SYCLKernels.end())
15574 return &IT->second;
15575 return nullptr;
15576}
15577
15578OMPTraitInfo &ASTContext::getNewOMPTraitInfo() {
15579 OMPTraitInfoVector.emplace_back(Args: new OMPTraitInfo());
15580 return *OMPTraitInfoVector.back();
15581}
15582
15583const StreamingDiagnostic &clang::
15584operator<<(const StreamingDiagnostic &DB,
15585 const ASTContext::SectionInfo &Section) {
15586 if (Section.Decl)
15587 return DB << Section.Decl;
15588 return DB << "a prior #pragma section";
15589}
15590
15591bool ASTContext::mayExternalize(const Decl *D) const {
15592 bool IsInternalVar =
15593 isa<VarDecl>(Val: D) &&
15594 basicGVALinkageForVariable(Context: *this, VD: cast<VarDecl>(Val: D)) == GVA_Internal;
15595 bool IsExplicitDeviceVar = (D->hasAttr<CUDADeviceAttr>() &&
15596 !D->getAttr<CUDADeviceAttr>()->isImplicit()) ||
15597 (D->hasAttr<CUDAConstantAttr>() &&
15598 !D->getAttr<CUDAConstantAttr>()->isImplicit());
15599 // CUDA/HIP: managed variables need to be externalized since it is
15600 // a declaration in IR, therefore cannot have internal linkage. Kernels in
15601 // anonymous name space needs to be externalized to avoid duplicate symbols.
15602 return (IsInternalVar &&
15603 (D->hasAttr<HIPManagedAttr>() || IsExplicitDeviceVar)) ||
15604 (D->hasAttr<CUDAGlobalAttr>() &&
15605 basicGVALinkageForFunction(Context: *this, FD: cast<FunctionDecl>(Val: D)) ==
15606 GVA_Internal);
15607}
15608
15609bool ASTContext::shouldExternalize(const Decl *D) const {
15610 return mayExternalize(D) &&
15611 (D->hasAttr<HIPManagedAttr>() || D->hasAttr<CUDAGlobalAttr>() ||
15612 CUDADeviceVarODRUsedByHost.count(key: cast<VarDecl>(Val: D)));
15613}
15614
15615StringRef ASTContext::getCUIDHash() const {
15616 if (!CUIDHash.empty())
15617 return CUIDHash;
15618 if (LangOpts.CUID.empty())
15619 return StringRef();
15620 CUIDHash = llvm::utohexstr(X: llvm::MD5Hash(Str: LangOpts.CUID), /*LowerCase=*/true);
15621 return CUIDHash;
15622}
15623
15624const CXXRecordDecl *
15625ASTContext::baseForVTableAuthentication(const CXXRecordDecl *ThisClass) const {
15626 assert(ThisClass);
15627 assert(ThisClass->isPolymorphic());
15628 const CXXRecordDecl *PrimaryBase = ThisClass;
15629 while (1) {
15630 assert(PrimaryBase);
15631 assert(PrimaryBase->isPolymorphic());
15632 auto &Layout = getASTRecordLayout(D: PrimaryBase);
15633 auto Base = Layout.getPrimaryBase();
15634 if (!Base || Base == PrimaryBase || !Base->isPolymorphic())
15635 break;
15636 PrimaryBase = Base;
15637 }
15638 return PrimaryBase;
15639}
15640
15641bool ASTContext::useAbbreviatedThunkName(GlobalDecl VirtualMethodDecl,
15642 StringRef MangledName) {
15643 auto *Method = cast<CXXMethodDecl>(Val: VirtualMethodDecl.getDecl());
15644 assert(Method->isVirtual());
15645 bool DefaultIncludesPointerAuth =
15646 LangOpts.PointerAuthCalls || LangOpts.PointerAuthIntrinsics;
15647
15648 if (!DefaultIncludesPointerAuth)
15649 return true;
15650
15651 auto Existing = ThunksToBeAbbreviated.find(Val: VirtualMethodDecl);
15652 if (Existing != ThunksToBeAbbreviated.end())
15653 return Existing->second.contains(key: MangledName.str());
15654
15655 std::unique_ptr<MangleContext> Mangler(createMangleContext());
15656 llvm::StringMap<llvm::SmallVector<std::string, 2>> Thunks;
15657 auto VtableContext = getVTableContext();
15658 if (const auto *ThunkInfos = VtableContext->getThunkInfo(GD: VirtualMethodDecl)) {
15659 auto *Destructor = dyn_cast<CXXDestructorDecl>(Val: Method);
15660 for (const auto &Thunk : *ThunkInfos) {
15661 SmallString<256> ElidedName;
15662 llvm::raw_svector_ostream ElidedNameStream(ElidedName);
15663 if (Destructor)
15664 Mangler->mangleCXXDtorThunk(DD: Destructor, Type: VirtualMethodDecl.getDtorType(),
15665 Thunk, /* elideOverrideInfo */ ElideOverrideInfo: true,
15666 ElidedNameStream);
15667 else
15668 Mangler->mangleThunk(MD: Method, Thunk, /* elideOverrideInfo */ ElideOverrideInfo: true,
15669 ElidedNameStream);
15670 SmallString<256> MangledName;
15671 llvm::raw_svector_ostream mangledNameStream(MangledName);
15672 if (Destructor)
15673 Mangler->mangleCXXDtorThunk(DD: Destructor, Type: VirtualMethodDecl.getDtorType(),
15674 Thunk, /* elideOverrideInfo */ ElideOverrideInfo: false,
15675 mangledNameStream);
15676 else
15677 Mangler->mangleThunk(MD: Method, Thunk, /* elideOverrideInfo */ ElideOverrideInfo: false,
15678 mangledNameStream);
15679
15680 Thunks[ElidedName].push_back(Elt: std::string(MangledName));
15681 }
15682 }
15683 llvm::StringSet<> SimplifiedThunkNames;
15684 for (auto &ThunkList : Thunks) {
15685 llvm::sort(C&: ThunkList.second);
15686 SimplifiedThunkNames.insert(key: ThunkList.second[0]);
15687 }
15688 bool Result = SimplifiedThunkNames.contains(key: MangledName);
15689 ThunksToBeAbbreviated[VirtualMethodDecl] = std::move(SimplifiedThunkNames);
15690 return Result;
15691}
15692
15693bool ASTContext::arePFPFieldsTriviallyCopyable(const RecordDecl *RD) const {
15694 // Check for trivially-destructible here because non-trivially-destructible
15695 // types will always cause the type and any types derived from it to be
15696 // considered non-trivially-copyable. The same cannot be said for
15697 // trivially-copyable because deleting special members of a type derived from
15698 // a non-trivially-copyable type can cause the derived type to be considered
15699 // trivially copyable.
15700 if (getLangOpts().PointerFieldProtectionTagged)
15701 return !isa<CXXRecordDecl>(Val: RD) ||
15702 cast<CXXRecordDecl>(Val: RD)->hasTrivialDestructor();
15703 return true;
15704}
15705
15706static void findPFPFields(const ASTContext &Ctx, QualType Ty, CharUnits Offset,
15707 std::vector<PFPField> &Fields, bool IncludeVBases) {
15708 if (auto *AT = Ctx.getAsConstantArrayType(T: Ty)) {
15709 if (auto *ElemDecl = AT->getElementType()->getAsCXXRecordDecl()) {
15710 const ASTRecordLayout &ElemRL = Ctx.getASTRecordLayout(D: ElemDecl);
15711 for (unsigned i = 0; i != AT->getSize(); ++i)
15712 findPFPFields(Ctx, Ty: AT->getElementType(), Offset: Offset + i * ElemRL.getSize(),
15713 Fields, IncludeVBases: true);
15714 }
15715 }
15716 auto *Decl = Ty->getAsCXXRecordDecl();
15717 // isPFPType() is inherited from bases and members (including via arrays), so
15718 // we can early exit if it is false. Unions are excluded per the API
15719 // documentation.
15720 if (!Decl || !Decl->isPFPType() || Decl->isUnion())
15721 return;
15722 const ASTRecordLayout &RL = Ctx.getASTRecordLayout(D: Decl);
15723 for (FieldDecl *Field : Decl->fields()) {
15724 CharUnits FieldOffset =
15725 Offset +
15726 Ctx.toCharUnitsFromBits(BitSize: RL.getFieldOffset(FieldNo: Field->getFieldIndex()));
15727 if (Ctx.isPFPField(Field))
15728 Fields.push_back(x: {.Offset: FieldOffset, .Field: Field});
15729 findPFPFields(Ctx, Ty: Field->getType(), Offset: FieldOffset, Fields,
15730 /*IncludeVBases=*/true);
15731 }
15732 // Pass false for IncludeVBases below because vbases are only included in
15733 // layout for top-level types, i.e. not bases or vbases.
15734 for (CXXBaseSpecifier &Base : Decl->bases()) {
15735 if (Base.isVirtual())
15736 continue;
15737 CharUnits BaseOffset =
15738 Offset + RL.getBaseClassOffset(Base: Base.getType()->getAsCXXRecordDecl());
15739 findPFPFields(Ctx, Ty: Base.getType(), Offset: BaseOffset, Fields,
15740 /*IncludeVBases=*/false);
15741 }
15742 if (IncludeVBases) {
15743 for (CXXBaseSpecifier &Base : Decl->vbases()) {
15744 CharUnits BaseOffset =
15745 Offset + RL.getVBaseClassOffset(VBase: Base.getType()->getAsCXXRecordDecl());
15746 findPFPFields(Ctx, Ty: Base.getType(), Offset: BaseOffset, Fields,
15747 /*IncludeVBases=*/false);
15748 }
15749 }
15750}
15751
15752std::vector<PFPField> ASTContext::findPFPFields(QualType Ty) const {
15753 std::vector<PFPField> PFPFields;
15754 ::findPFPFields(Ctx: *this, Ty, Offset: CharUnits::Zero(), Fields&: PFPFields, IncludeVBases: true);
15755 return PFPFields;
15756}
15757
15758bool ASTContext::hasPFPFields(QualType Ty) const {
15759 return !findPFPFields(Ty).empty();
15760}
15761
15762bool ASTContext::isPFPField(const FieldDecl *FD) {
15763 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: FD->getParent()))
15764 return RD->isPFPType() && FD->getType()->isPointerType() &&
15765 !FD->hasAttr<NoFieldProtectionAttr>();
15766 return false;
15767}
15768
15769void ASTContext::recordMemberDataPointerEvaluation(const ValueDecl *VD) {
15770 auto *FD = dyn_cast<FieldDecl>(Val: VD);
15771 if (!FD)
15772 FD = cast<FieldDecl>(Val: cast<IndirectFieldDecl>(Val: VD)->chain().back());
15773 if (isPFPField(FD))
15774 PFPFieldsWithEvaluatedOffset.insert(X: FD);
15775}
15776
15777void ASTContext::recordOffsetOfEvaluation(const OffsetOfExpr *E) {
15778 if (E->getNumComponents() == 0)
15779 return;
15780 OffsetOfNode Comp = E->getComponent(Idx: E->getNumComponents() - 1);
15781 if (Comp.getKind() != OffsetOfNode::Field)
15782 return;
15783 if (FieldDecl *FD = Comp.getField(); isPFPField(FD))
15784 PFPFieldsWithEvaluatedOffset.insert(X: FD);
15785}
15786
15787namespace {
15788// PaddingCalculator is a utility class that calculates the padding bits in a
15789// c/c++ type. It traverses the type recursively, collecting occupied
15790// bit intervals, and then computes the padding intervals.
15791// If a byte only contains some padding bits, it gets intervals for only those
15792// bits. This is the case for bit-fields.
15793struct PaddingCalculator {
15794 PaddingCalculator(const ASTContext &Ctx) : Ctx(Ctx) {}
15795
15796 void run(QualType Ty) {
15797 OccuppiedIntervals.clear();
15798 Stack.clear();
15799
15800 TySizeInBits = Ctx.getTypeSize(T: Ty);
15801
15802 Stack.push_back(Elt: Data{.StartBitOffset: 0, .Ty: Ty.getCanonicalType(), .VisitVirtualBase: true});
15803 while (!Stack.empty()) {
15804 Data Current = Stack.back();
15805 Stack.pop_back();
15806 Visit(D: Current);
15807 }
15808 MergeOccuppiedIntervals();
15809 }
15810
15811 llvm::SmallVector<ASTContext::BitInterval> GetPaddingIntervals() {
15812 llvm::SmallVector<ASTContext::BitInterval> Results;
15813 if (OccuppiedIntervals.size() == 1 &&
15814 OccuppiedIntervals.front().First == 0 &&
15815 OccuppiedIntervals.front().Last == TySizeInBits) {
15816 return Results;
15817 }
15818 Results.reserve(N: OccuppiedIntervals.size() + 1);
15819 uint64_t CurrentPos = 0;
15820 for (const ASTContext::BitInterval &OccupiedInterval : OccuppiedIntervals) {
15821 if (OccupiedInterval.First > CurrentPos) {
15822 Results.push_back(
15823 Elt: ASTContext::BitInterval{.First: CurrentPos, .Last: OccupiedInterval.First});
15824 }
15825 CurrentPos = OccupiedInterval.Last;
15826 }
15827 if (TySizeInBits > CurrentPos) {
15828 Results.push_back(Elt: ASTContext::BitInterval{.First: CurrentPos, .Last: TySizeInBits});
15829 }
15830 return Results;
15831 }
15832
15833private:
15834 struct Data {
15835 uint64_t StartBitOffset;
15836 QualType Ty;
15837 bool VisitVirtualBase;
15838 };
15839
15840 // Return the number of non padding bits of a scalar type.
15841 //
15842 // The property that we specifically care about here is whether the scalar
15843 // type has padding bits, i.e. are there bits in the type which are not
15844 // specified by the ABI.
15845 //
15846 // We currently don't care about this anywhere else in clang: layout cares
15847 // about the ABI size, calling convention code cares about specific types,
15848 // but nothing cares about padding specifically. And it's not something we can
15849 // easily query from LLVM due to the type system mismatches.
15850 // DL.getTypeSizeInBits(convertTypeForLoadStore(T)) is probably close, but the
15851 // DataLayout methods aren't really designed for this usage.
15852 //
15853 // Therefore, it is better to explicitly list all the scalar types
15854 // containing padding bits that we know of, namely, _BitInt(N) and x87 long
15855 // double.
15856 //
15857 // FIXME: There are likely other scalar types we need to think about here, as
15858 // brought up in review for #215823:
15859 // - bool
15860 // - enums(both with/without fixed underlying type)
15861 // - nullptr_t
15862 // - more?
15863 uint64_t getScalarOccupiedSizeInBits(QualType Ty) const {
15864 if (const auto *BIT = Ty->getAs<BitIntType>())
15865 return BIT->getNumBits();
15866
15867 if (const auto *BT = Ty->getAs<BuiltinType>()) {
15868 if (BT->getKind() == BuiltinType::LongDouble &&
15869 &Ctx.getTargetInfo().getLongDoubleFormat() ==
15870 &llvm::APFloat::x87DoubleExtended())
15871 return llvm::APFloat::getSizeInBits(
15872 Sem: Ctx.getTargetInfo().getLongDoubleFormat());
15873 }
15874
15875 return Ctx.getTypeSize(T: Ty);
15876 }
15877
15878 void Visit(const Data &D) {
15879 if (auto *AT = dyn_cast<ConstantArrayType>(Val: D.Ty)) {
15880 VisitArray(AT, StartBitOffset: D.StartBitOffset);
15881 return;
15882 }
15883
15884 if (auto *Record = D.Ty->getAsRecordDecl()) {
15885 VisitStruct(R: Record, StartBitOffset: D.StartBitOffset, VisitVirtualBase: D.VisitVirtualBase);
15886 return;
15887 }
15888
15889 if (D.Ty->isAtomicType()) {
15890 auto Unwrapped = D;
15891 Unwrapped.Ty = D.Ty.getAtomicUnqualifiedType().getCanonicalType();
15892 Stack.push_back(Elt: Unwrapped);
15893 return;
15894 }
15895
15896 if (const auto *Complex = D.Ty->getAs<ComplexType>()) {
15897 VisitComplex(CT: Complex, StartBitOffset: D.StartBitOffset);
15898 return;
15899 }
15900
15901 if (const auto *VT = D.Ty->getAs<clang::VectorType>()) {
15902 VisitVector(VT, StartBitOffset: D.StartBitOffset);
15903 return;
15904 }
15905
15906 if (const auto *BITy = D.Ty->getAs<BitIntType>()) {
15907 VisitBitInt(Ty: BITy, StartBitOffset: D.StartBitOffset);
15908 return;
15909 }
15910
15911 uint64_t SizeBit = getScalarOccupiedSizeInBits(Ty: D.Ty);
15912 OccuppiedIntervals.push_back(
15913 Elt: ASTContext::BitInterval{.First: D.StartBitOffset, .Last: D.StartBitOffset + SizeBit});
15914 }
15915
15916 void VisitArray(const ConstantArrayType *AT, uint64_t StartBitOffset) {
15917 for (uint64_t ArrIndex = 0; ArrIndex < AT->getSize().getLimitedValue();
15918 ++ArrIndex) {
15919
15920 QualType ElementQualType = AT->getElementType();
15921 auto ElementSize = Ctx.getTypeSizeInChars(T: ElementQualType);
15922 auto ElementAlign = Ctx.getTypeAlignInChars(T: ElementQualType);
15923 auto Offset = ElementSize.alignTo(Align: ElementAlign);
15924
15925 Stack.push_back(Elt: Data{
15926 .StartBitOffset: StartBitOffset + ArrIndex * Offset.getQuantity() * Ctx.getCharWidth(),
15927 .Ty: ElementQualType.getCanonicalType(), /*VisitVirtualBase*/ true});
15928 }
15929 }
15930
15931 void VisitStruct(const RecordDecl *R, uint64_t StartBitOffset,
15932 bool VisitVirtualBase) {
15933 const ASTRecordLayout &ASTLayout = Ctx.getASTRecordLayout(D: R);
15934 auto *CXXRecord = dyn_cast<CXXRecordDecl>(Val: R);
15935
15936 unsigned PointerSizeInBits = Ctx.getTypeSize(T: Ctx.NullPtrTy);
15937
15938 if (CXXRecord) {
15939 if (ASTLayout.hasOwnVFPtr()) {
15940 OccuppiedIntervals.push_back(Elt: ASTContext::BitInterval{
15941 .First: StartBitOffset, .Last: StartBitOffset + PointerSizeInBits});
15942 }
15943
15944 if (ASTLayout.hasOwnVBPtr()) {
15945 auto Offset = ASTLayout.getVBPtrOffset().getQuantity();
15946 auto StartVBPtr = StartBitOffset + Offset * Ctx.getCharWidth();
15947 OccuppiedIntervals.push_back(Elt: ASTContext::BitInterval{
15948 .First: StartVBPtr, .Last: StartVBPtr + PointerSizeInBits});
15949 }
15950
15951 const auto VisitBase = [&ASTLayout, StartBitOffset, this](
15952 const CXXBaseSpecifier &Base, auto GetOffset) {
15953 auto *BaseRecord = Base.getType()->getAsCXXRecordDecl();
15954 if (!BaseRecord) {
15955 return;
15956 }
15957 auto BaseOffset =
15958 std::invoke(GetOffset, ASTLayout, BaseRecord).getQuantity();
15959
15960 Stack.push_back(
15961 Elt: Data{StartBitOffset + BaseOffset * Ctx.getCharWidth(),
15962 Base.getType().getCanonicalType(), /*VisitVirtualBase*/
15963 false});
15964 };
15965
15966 for (auto Base : CXXRecord->bases()) {
15967 if (!Base.isVirtual()) {
15968 VisitBase(Base, &ASTRecordLayout::getBaseClassOffset);
15969 }
15970 }
15971
15972 if (VisitVirtualBase) {
15973 for (auto VBase : CXXRecord->vbases()) {
15974 VisitBase(VBase, &ASTRecordLayout::getVBaseClassOffset);
15975 }
15976 }
15977 }
15978
15979 for (auto *Field : R->fields()) {
15980 // Treat unnamed bitfields as padding.
15981 if (Field->isUnnamedBitField())
15982 continue;
15983
15984 auto FieldOffset = ASTLayout.getFieldOffset(FieldNo: Field->getFieldIndex());
15985 if (Field->isBitField()) {
15986 VisitBitfield(Field, StartBitOffset: StartBitOffset + FieldOffset);
15987 } else {
15988 Stack.push_back(Elt: Data{.StartBitOffset: StartBitOffset + FieldOffset,
15989 .Ty: Field->getType().getCanonicalType(),
15990 /*VisitVirtualBase*/ true});
15991 }
15992 }
15993 }
15994
15995 void VisitBitfield(const FieldDecl *Field, uint64_t StartBitOffset) {
15996 assert(Field->isBitField() && !Field->isUnnamedBitField());
15997 if (Field->isZeroLengthBitField())
15998 return;
15999
16000 const uint64_t DeclaredSizeInBits = Field->getBitWidthValue();
16001
16002 // Oversized bit-fields (declared width larger than the field type) occupy
16003 // only the type's width. The extra declared bits are padding and follow
16004 // the occupied bits (Itanium C++ ABI §2.4, II.1(b)).
16005 // In case where the bitfield can only have values with a range smaller than
16006 // the one declared, e.g. bool a : 5 or _BitInt(5) b : 6, the remaining bits
16007 // within the bitfield are for sign or zero extension. These are considered
16008 // occupied as well.
16009 const uint64_t OccupiedSizeInBits =
16010 std::min(a: DeclaredSizeInBits, b: Ctx.getTypeSize(T: Field->getType()));
16011
16012 if (Ctx.getTargetInfo().isLittleEndian()) {
16013 OccuppiedIntervals.push_back(
16014 Elt: {.First: StartBitOffset, .Last: StartBitOffset + OccupiedSizeInBits});
16015 return;
16016 }
16017
16018 // In big endian mode, the sequence of occupied bits traverses bytes in
16019 // increasing address order, just like in little endian. However, within
16020 // each byte, the traversal starts from the most significant bit. This is
16021 // where it differs from little endian.
16022 //
16023 // If the interval contains whole bytes in the middle, then for these
16024 // nothing changes, and they constitute a contiguous interval. However for
16025 // the partially occupied bytes in either end, if present, their bit
16026 // intervals need to be adjusted so that they count from the MSB instead.
16027 //
16028 // Occupied bits are allocated first, and any padding follows them.
16029 const uint64_t Start = StartBitOffset;
16030 const uint64_t End = Start + OccupiedSizeInBits;
16031 const uint64_t CharWidth = Ctx.getCharWidth();
16032
16033 // Special case: all the occupied bits are contained within a single byte.
16034 const uint64_t ByteStart = llvm::alignDown(Value: Start, Align: CharWidth);
16035 const uint64_t ByteEnd = llvm::alignTo(Value: End, Align: CharWidth);
16036 if (ByteStart == ByteEnd - CharWidth) {
16037 const uint64_t Length = End - Start;
16038 const uint64_t Offset = Start - ByteStart;
16039 OccuppiedIntervals.push_back(
16040 Elt: {.First: ByteEnd - Offset - Length, .Last: ByteEnd - Offset});
16041 return;
16042 }
16043
16044 // Compute the contiguous interval in the middle, comprised of whole bytes,
16045 // if any.
16046 const uint64_t MiddleIntervalStart = llvm::alignTo(Value: Start, Align: CharWidth);
16047 const uint64_t MiddleIntervalEnd = llvm::alignDown(Value: End, Align: CharWidth);
16048 if (MiddleIntervalStart != MiddleIntervalEnd)
16049 OccuppiedIntervals.push_back(Elt: {.First: MiddleIntervalStart, .Last: MiddleIntervalEnd});
16050
16051 // Compute the partially occupied first byte's interval, if any, counting
16052 // from the MSB.
16053 if (Start != MiddleIntervalStart) {
16054 const uint64_t Length = MiddleIntervalStart - Start;
16055 OccuppiedIntervals.push_back(Elt: {.First: ByteStart, .Last: ByteStart + Length});
16056 }
16057
16058 // Compute the partially occupied last byte's interval, if any, counting
16059 // from the MSB.
16060 if (End != MiddleIntervalEnd) {
16061 const uint64_t Length = End - MiddleIntervalEnd;
16062 OccuppiedIntervals.push_back(Elt: {.First: ByteEnd - Length, .Last: ByteEnd});
16063 }
16064 }
16065
16066 void VisitComplex(const ComplexType *CT, uint64_t StartBitOffset) {
16067 QualType ElementQualType = CT->getElementType().getCanonicalType();
16068 auto ElementSize = Ctx.getTypeSizeInChars(T: ElementQualType);
16069 auto ElementAlign = Ctx.getTypeAlignInChars(T: ElementQualType);
16070 auto ImgOffset = ElementSize.alignTo(Align: ElementAlign);
16071
16072 Stack.push_back(
16073 Elt: Data{.StartBitOffset: StartBitOffset, .Ty: ElementQualType, /*VisitVirtualBase*/ true});
16074 Stack.push_back(
16075 Elt: Data{.StartBitOffset: StartBitOffset + ImgOffset.getQuantity() * Ctx.getCharWidth(),
16076 .Ty: ElementQualType, /*VisitVirtualBase*/ true});
16077 }
16078
16079 void VisitVector(const clang::VectorType *VT, uint64_t StartBitOffset) {
16080 if (VT->isPackedVectorBoolType(ctx: Ctx)) {
16081 VisitPackedBooleanVector(VTy: VT, StartBitOffset);
16082 return;
16083 }
16084
16085 uint64_t SizeBit = getScalarOccupiedSizeInBits(Ty: VT->getElementType()) *
16086 VT->getNumElements();
16087 OccuppiedIntervals.push_back(
16088 Elt: ASTContext::BitInterval{.First: StartBitOffset, .Last: StartBitOffset + SizeBit});
16089 }
16090
16091 /// Compute the occupied bit intervals for a BitInt.
16092 ///
16093 /// In the case of little endian, the occupied bits are always contiguous so a
16094 /// single interval is sufficient. However in big endian, the intervals can be
16095 /// disjoint.
16096 void VisitBitInt(const BitIntType *Ty, uint64_t StartBitOffset) {
16097 const uint64_t OccupiedSizeInBits = Ty->getNumBits();
16098
16099 if (Ctx.getTargetInfo().isLittleEndian()) {
16100 OccuppiedIntervals.push_back(
16101 Elt: {.First: StartBitOffset, .Last: StartBitOffset + OccupiedSizeInBits});
16102 return;
16103 }
16104
16105 // In big endian mode, the layout of a BitInt in memory has its bytes in
16106 // reverse order, and is pictured in this order:
16107 // 1. Fully padding bytes.
16108 // 2. One partially occupied byte, with padding at the most significant
16109 // bits. ("remaining occupied bits")
16110 // 3. A sequence of fully occupied bytes up until the end of the storage.
16111 const uint64_t StorageSizeInBits = Ctx.getTypeSize(T: Ty);
16112 const uint64_t CharWidth = Ctx.getCharWidth();
16113 const uint64_t NumFullyPaddingBytes =
16114 (StorageSizeInBits - OccupiedSizeInBits) / CharWidth;
16115 const uint64_t NumFullyOccupiedBytes = OccupiedSizeInBits / CharWidth;
16116 const uint64_t NumRemainingOccupiedBits = OccupiedSizeInBits % CharWidth;
16117
16118 // Partially occupied byte
16119 if (NumRemainingOccupiedBits > 0)
16120 OccuppiedIntervals.push_back(
16121 Elt: {.First: StartBitOffset + NumFullyPaddingBytes * CharWidth,
16122 .Last: StartBitOffset + NumFullyPaddingBytes * CharWidth +
16123 NumRemainingOccupiedBits});
16124
16125 // Fully occupied bytes
16126 if (NumFullyOccupiedBytes > 0)
16127 OccuppiedIntervals.push_back(Elt: {.First: StartBitOffset + StorageSizeInBits -
16128 NumFullyOccupiedBytes * CharWidth,
16129 .Last: StartBitOffset + StorageSizeInBits});
16130 }
16131
16132 void VisitPackedBooleanVector(const VectorType *VTy,
16133 uint64_t StartBitOffset) {
16134 const uint64_t CharWidth = Ctx.getCharWidth();
16135 assert(StartBitOffset % CharWidth == 0 &&
16136 "Expected aligned packed boolean vector");
16137 assert(VTy->isPackedVectorBoolType(Ctx));
16138 const uint64_t OccupiedSizeInBits = VTy->getNumElements();
16139
16140 if (Ctx.getTargetInfo().isLittleEndian()) {
16141 OccuppiedIntervals.push_back(
16142 Elt: {.First: StartBitOffset, .Last: StartBitOffset + OccupiedSizeInBits});
16143 return;
16144 }
16145
16146 // Only the sequence of bytes containing occupied bits has its order
16147 // reversed, but the bits within each byte are still counted from the least
16148 // significant bit. So if there are fully padding bytes, they reside at the
16149 // higher addresses in both endiannesses.
16150 const uint64_t NumFullyOccupiedBytes = OccupiedSizeInBits / CharWidth;
16151 const uint64_t NumRemainingOccupiedBits = OccupiedSizeInBits % CharWidth;
16152
16153 uint64_t Start = StartBitOffset;
16154 // Partially occupied byte at the beginning
16155 if (NumRemainingOccupiedBits > 0) {
16156 const uint64_t ByteEnd = Start + CharWidth;
16157 OccuppiedIntervals.push_back(Elt: {.First: Start, .Last: Start + NumRemainingOccupiedBits});
16158 Start = ByteEnd;
16159 }
16160
16161 // The remaining fully occupied bytes form a contiguous interval
16162 if (NumFullyOccupiedBytes > 0) {
16163 OccuppiedIntervals.push_back(
16164 Elt: {.First: Start, .Last: Start + NumFullyOccupiedBytes * CharWidth});
16165 }
16166 }
16167
16168 void MergeOccuppiedIntervals() {
16169 std::sort(first: OccuppiedIntervals.begin(), last: OccuppiedIntervals.end(),
16170 comp: [](const ASTContext::BitInterval &lhs,
16171 const ASTContext::BitInterval &rhs) {
16172 return std::tie(args: lhs.First, args: lhs.Last) <
16173 std::tie(args: rhs.First, args: rhs.Last);
16174 });
16175
16176 llvm::SmallVector<ASTContext::BitInterval> Merged;
16177 Merged.reserve(N: OccuppiedIntervals.size());
16178
16179 for (const ASTContext::BitInterval &NextInterval : OccuppiedIntervals) {
16180 if (Merged.empty()) {
16181 Merged.push_back(Elt: NextInterval);
16182 continue;
16183 }
16184 auto &LastInterval = Merged.back();
16185
16186 if (NextInterval.First > LastInterval.Last) {
16187 Merged.push_back(Elt: NextInterval);
16188 } else {
16189 LastInterval.Last = std::max(a: LastInterval.Last, b: NextInterval.Last);
16190 }
16191 }
16192
16193 OccuppiedIntervals = Merged;
16194 }
16195
16196 const ASTContext &Ctx;
16197 // unsigned PointerSizeInBits;
16198 uint64_t TySizeInBits = 0;
16199 llvm::SmallVector<Data> Stack;
16200 llvm::SmallVector<ASTContext::BitInterval> OccuppiedIntervals;
16201};
16202} // namespace
16203
16204llvm::ArrayRef<ASTContext::BitInterval>
16205ASTContext::getPaddingIntervals(QualType Ty) const {
16206 Ty = Ty.getCanonicalType();
16207 auto cached = PaddingIntervalCache.find(Val: Ty);
16208 if (cached != PaddingIntervalCache.end())
16209 return cached->second;
16210
16211 PaddingCalculator pc{*this};
16212 pc.run(Ty);
16213
16214 auto [itr, res] =
16215 PaddingIntervalCache.insert_or_assign(Key: Ty, Val: pc.GetPaddingIntervals());
16216 assert(res && "Failed to insert?");
16217
16218 return itr->second;
16219}
16220