1//===- ASTContext.cpp - Context to hold long-lived AST nodes --------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the ASTContext interface.
10//
11//===----------------------------------------------------------------------===//
12
13#include "clang/AST/ASTContext.h"
14#include "ByteCode/Context.h"
15#include "CXXABI.h"
16#include "clang/AST/APValue.h"
17#include "clang/AST/ASTConcept.h"
18#include "clang/AST/ASTMutationListener.h"
19#include "clang/AST/ASTStructuralEquivalence.h"
20#include "clang/AST/ASTTypeTraits.h"
21#include "clang/AST/Attr.h"
22#include "clang/AST/AttrIterator.h"
23#include "clang/AST/CharUnits.h"
24#include "clang/AST/Comment.h"
25#include "clang/AST/Decl.h"
26#include "clang/AST/DeclBase.h"
27#include "clang/AST/DeclCXX.h"
28#include "clang/AST/DeclContextInternals.h"
29#include "clang/AST/DeclObjC.h"
30#include "clang/AST/DeclOpenMP.h"
31#include "clang/AST/DeclTemplate.h"
32#include "clang/AST/DeclarationName.h"
33#include "clang/AST/DependenceFlags.h"
34#include "clang/AST/Expr.h"
35#include "clang/AST/ExprCXX.h"
36#include "clang/AST/ExternalASTSource.h"
37#include "clang/AST/Mangle.h"
38#include "clang/AST/MangleNumberingContext.h"
39#include "clang/AST/NestedNameSpecifier.h"
40#include "clang/AST/ParentMapContext.h"
41#include "clang/AST/RawCommentList.h"
42#include "clang/AST/RecordLayout.h"
43#include "clang/AST/Stmt.h"
44#include "clang/AST/TemplateBase.h"
45#include "clang/AST/TemplateName.h"
46#include "clang/AST/Type.h"
47#include "clang/AST/TypeLoc.h"
48#include "clang/AST/UnresolvedSet.h"
49#include "clang/AST/VTableBuilder.h"
50#include "clang/Basic/AddressSpaces.h"
51#include "clang/Basic/Builtins.h"
52#include "clang/Basic/CommentOptions.h"
53#include "clang/Basic/DiagnosticAST.h"
54#include "clang/Basic/ExceptionSpecificationType.h"
55#include "clang/Basic/IdentifierTable.h"
56#include "clang/Basic/LLVM.h"
57#include "clang/Basic/LangOptions.h"
58#include "clang/Basic/Linkage.h"
59#include "clang/Basic/Module.h"
60#include "clang/Basic/NoSanitizeList.h"
61#include "clang/Basic/ObjCRuntime.h"
62#include "clang/Basic/ProfileList.h"
63#include "clang/Basic/SourceLocation.h"
64#include "clang/Basic/SourceManager.h"
65#include "clang/Basic/Specifiers.h"
66#include "clang/Basic/TargetCXXABI.h"
67#include "clang/Basic/TargetInfo.h"
68#include "clang/Basic/XRayLists.h"
69#include "clang/Lex/MacroInfo.h"
70#include "llvm/ADT/APFixedPoint.h"
71#include "llvm/ADT/APInt.h"
72#include "llvm/ADT/APSInt.h"
73#include "llvm/ADT/ArrayRef.h"
74#include "llvm/ADT/DenseMap.h"
75#include "llvm/ADT/DenseSet.h"
76#include "llvm/ADT/FoldingSet.h"
77#include "llvm/ADT/PointerUnion.h"
78#include "llvm/ADT/STLExtras.h"
79#include "llvm/ADT/SmallPtrSet.h"
80#include "llvm/ADT/SmallVector.h"
81#include "llvm/ADT/StringExtras.h"
82#include "llvm/ADT/StringRef.h"
83#include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
84#include "llvm/Support/Capacity.h"
85#include "llvm/Support/Casting.h"
86#include "llvm/Support/Compiler.h"
87#include "llvm/Support/ErrorHandling.h"
88#include "llvm/Support/MD5.h"
89#include "llvm/Support/MathExtras.h"
90#include "llvm/Support/SipHash.h"
91#include "llvm/Support/raw_ostream.h"
92#include "llvm/TargetParser/AArch64TargetParser.h"
93#include "llvm/TargetParser/Triple.h"
94#include <algorithm>
95#include <cassert>
96#include <cstddef>
97#include <cstdint>
98#include <cstdlib>
99#include <map>
100#include <memory>
101#include <optional>
102#include <string>
103#include <tuple>
104#include <utility>
105
106using namespace clang;
107
108enum FloatingRank {
109 BFloat16Rank,
110 Float16Rank,
111 HalfRank,
112 FloatRank,
113 DoubleRank,
114 LongDoubleRank,
115 Float128Rank,
116 Ibm128Rank
117};
118
119/// \returns The locations that are relevant when searching for Doc comments
120/// related to \p Key.
121static SmallVector<SourceLocation, 2>
122getLocsForCommentSearch(ASTContext::RawCommentLookupKey Key,
123 SourceManager &SourceMgr) {
124 if (const auto *MI = dyn_cast<const MacroInfo *>(Val&: Key)) {
125 SourceLocation DefLoc = MI->getDefinitionLoc();
126 if (DefLoc.isInvalid() || !DefLoc.isFileID())
127 return {};
128
129 // The macro's definition location points at its name (e.g. FOO in
130 // `#define FOO 1`). The text between a preceding documentation comment
131 // and the name contains the `#define` directive itself, which would be
132 // rejected by the preprocessor-directive guard in
133 // getRawCommentNoCacheImpl. Walk back to the leading `#` so that
134 // the guard only fires when something *else* sits between the comment
135 // and our directive.
136 FileIDAndOffset Decomposed = SourceMgr.getDecomposedLoc(Loc: DefLoc);
137 bool Invalid = false;
138 StringRef Buffer = SourceMgr.getBufferData(FID: Decomposed.first, Invalid: &Invalid);
139 if (Invalid)
140 return {};
141 unsigned Offset = Decomposed.second;
142 if (size_t Found = Buffer.find_last_of(Chars: "#\n", From: Offset);
143 Found != StringRef::npos)
144 Offset = Found;
145 return {SourceMgr.getLocForStartOfFile(FID: Decomposed.first)
146 .getLocWithOffset(Offset)};
147 }
148
149 const auto *D = cast<const Decl *>(Val&: Key);
150 assert(D);
151
152 // User can not attach documentation to implicit declarations.
153 if (D->isImplicit())
154 return {};
155
156 // User can not attach documentation to implicit instantiations.
157 if (const auto *FD = dyn_cast<FunctionDecl>(Val: D)) {
158 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
159 return {};
160 }
161
162 if (const auto *VD = dyn_cast<VarDecl>(Val: D)) {
163 if (VD->isStaticDataMember() &&
164 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
165 return {};
166 }
167
168 if (const auto *CRD = dyn_cast<CXXRecordDecl>(Val: D)) {
169 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
170 return {};
171 }
172
173 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Val: D)) {
174 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
175 if (TSK == TSK_ImplicitInstantiation ||
176 TSK == TSK_Undeclared)
177 return {};
178 }
179
180 if (const auto *ED = dyn_cast<EnumDecl>(Val: D)) {
181 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
182 return {};
183 }
184 if (const auto *TD = dyn_cast<TagDecl>(Val: D)) {
185 // When tag declaration (but not definition!) is part of the
186 // decl-specifier-seq of some other declaration, it doesn't get comment
187 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
188 return {};
189 }
190 // TODO: handle comments for function parameters properly.
191 if (isa<ParmVarDecl>(Val: D))
192 return {};
193
194 // TODO: we could look up template parameter documentation in the template
195 // documentation.
196 if (isa<TemplateTypeParmDecl>(Val: D) ||
197 isa<NonTypeTemplateParmDecl>(Val: D) ||
198 isa<TemplateTemplateParmDecl>(Val: D))
199 return {};
200
201 SmallVector<SourceLocation, 2> Locations;
202 // Find declaration location.
203 // For Objective-C declarations we generally don't expect to have multiple
204 // declarators, thus use declaration starting location as the "declaration
205 // location".
206 // For all other declarations multiple declarators are used quite frequently,
207 // so we use the location of the identifier as the "declaration location".
208 SourceLocation BaseLocation;
209 if (isa<ObjCMethodDecl>(Val: D) || isa<ObjCContainerDecl>(Val: D) ||
210 isa<ObjCPropertyDecl>(Val: D) || isa<RedeclarableTemplateDecl>(Val: D) ||
211 isa<ClassTemplateSpecializationDecl>(Val: D) ||
212 // Allow association with Y across {} in `typedef struct X {} Y`.
213 isa<TypedefDecl>(Val: D))
214 BaseLocation = D->getBeginLoc();
215 else
216 BaseLocation = D->getLocation();
217
218 if (!D->getLocation().isMacroID()) {
219 Locations.emplace_back(Args&: BaseLocation);
220 } else {
221 const auto *DeclCtx = D->getDeclContext();
222
223 // When encountering definitions generated from a macro (that are not
224 // contained by another declaration in the macro) we need to try and find
225 // the comment at the location of the expansion but if there is no comment
226 // there we should retry to see if there is a comment inside the macro as
227 // well. To this end we return first BaseLocation to first look at the
228 // expansion site, the second value is the spelling location of the
229 // beginning of the declaration defined inside the macro.
230 if (!(DeclCtx &&
231 Decl::castFromDeclContext(DeclCtx)->getLocation().isMacroID())) {
232 Locations.emplace_back(Args: SourceMgr.getExpansionLoc(Loc: BaseLocation));
233 }
234
235 // We use Decl::getBeginLoc() and not just BaseLocation here to ensure that
236 // we don't refer to the macro argument location at the expansion site (this
237 // can happen if the name's spelling is provided via macro argument), and
238 // always to the declaration itself.
239 Locations.emplace_back(Args: SourceMgr.getSpellingLoc(Loc: D->getBeginLoc()));
240 }
241
242 return Locations;
243}
244
245RawComment *ASTContext::getRawCommentNoCacheImpl(
246 RawCommentLookupKey Key, const SourceLocation RepresentativeLoc,
247 const std::map<unsigned, RawComment *> &CommentsInTheFile) const {
248 // If the declaration doesn't map directly to a location in a file, we
249 // can't find the comment.
250 if (RepresentativeLoc.isInvalid() || !RepresentativeLoc.isFileID())
251 return nullptr;
252
253 // If there are no comments anywhere, we won't find anything.
254 if (CommentsInTheFile.empty())
255 return nullptr;
256
257 const auto *D = dyn_cast<const Decl *>(Val&: Key);
258 const bool IsMacro = isa<const MacroInfo *>(Val: Key);
259
260 // Decompose the location for the declaration and find the beginning of the
261 // file buffer.
262 const FileIDAndOffset LocDecomp =
263 SourceMgr.getDecomposedLoc(Loc: RepresentativeLoc);
264
265 // Slow path.
266 auto OffsetCommentBehindDecl =
267 CommentsInTheFile.lower_bound(x: LocDecomp.second);
268
269 // First check whether we have a trailing comment.
270 if (OffsetCommentBehindDecl != CommentsInTheFile.end()) {
271 RawComment *CommentBehindDecl = OffsetCommentBehindDecl->second;
272 if ((CommentBehindDecl->isDocumentation() ||
273 LangOpts.CommentOpts.ParseAllComments) &&
274 CommentBehindDecl->isTrailingComment() &&
275 (IsMacro || (D && (isa<FieldDecl>(Val: D) || isa<EnumConstantDecl>(Val: D) ||
276 isa<VarDecl>(Val: D) || isa<ObjCMethodDecl>(Val: D) ||
277 isa<ObjCPropertyDecl>(Val: D))))) {
278
279 // Check that Doxygen trailing comment comes after the declaration, starts
280 // on the same line and in the same file as the declaration.
281 if (SourceMgr.getLineNumber(FID: LocDecomp.first, FilePos: LocDecomp.second) ==
282 Comments.getCommentBeginLine(C: CommentBehindDecl, File: LocDecomp.first,
283 Offset: OffsetCommentBehindDecl->first)) {
284 return CommentBehindDecl;
285 }
286 }
287 }
288
289 // The comment just after the declaration was not a trailing comment.
290 // Let's look at the previous comment.
291 if (OffsetCommentBehindDecl == CommentsInTheFile.begin())
292 return nullptr;
293
294 auto OffsetCommentBeforeDecl = --OffsetCommentBehindDecl;
295 RawComment *CommentBeforeDecl = OffsetCommentBeforeDecl->second;
296
297 // Check that we actually have a non-member Doxygen comment.
298 if (!(CommentBeforeDecl->isDocumentation() ||
299 LangOpts.CommentOpts.ParseAllComments) ||
300 CommentBeforeDecl->isTrailingComment())
301 return nullptr;
302
303 // Decompose the end of the comment.
304 const unsigned CommentEndOffset =
305 Comments.getCommentEndOffset(C: CommentBeforeDecl);
306
307 // Get the corresponding buffer.
308 bool Invalid = false;
309 const char *Buffer =
310 SourceMgr.getBufferData(FID: LocDecomp.first, Invalid: &Invalid).data();
311 if (Invalid)
312 return nullptr;
313
314 // Extract text between the comment and declaration.
315 StringRef Text(Buffer + CommentEndOffset,
316 LocDecomp.second - CommentEndOffset);
317
318 // There should be no other declarations or preprocessor directives between
319 // comment and declaration.
320 if (Text.find_last_of(Chars: ";{}#@") != StringRef::npos)
321 return nullptr;
322
323 return CommentBeforeDecl;
324}
325
326RawComment *ASTContext::getRawCommentNoCache(RawCommentLookupKey Key) const {
327 const auto Locs = getLocsForCommentSearch(Key, SourceMgr);
328
329 for (const auto Loc : Locs) {
330 // If the declaration or macro doesn't map directly to a location in a file,
331 // we can't find the comment.
332 if (Loc.isInvalid() || !Loc.isFileID())
333 continue;
334
335 if (ExternalSource && !CommentsLoaded) {
336 ExternalSource->ReadComments();
337 CommentsLoaded = true;
338 }
339
340 if (Comments.empty())
341 continue;
342
343 const FileID File = SourceMgr.getDecomposedLoc(Loc).first;
344 if (!File.isValid())
345 continue;
346
347 const auto CommentsInThisFile = Comments.getCommentsInFile(File);
348 if (!CommentsInThisFile || CommentsInThisFile->empty())
349 continue;
350
351 if (RawComment *Comment =
352 getRawCommentNoCacheImpl(Key, RepresentativeLoc: Loc, CommentsInTheFile: *CommentsInThisFile))
353 return Comment;
354 }
355
356 return nullptr;
357}
358
359void ASTContext::addComment(const RawComment &RC) {
360 assert(LangOpts.RetainCommentsFromSystemHeaders ||
361 !SourceMgr.isInSystemHeader(RC.getSourceRange().getBegin()));
362 Comments.addComment(RC, CommentOpts: LangOpts.CommentOpts, Allocator&: BumpAlloc);
363}
364
365const RawComment *
366ASTContext::getRawCommentForAnyRedecl(RawCommentLookupKey Key,
367 const Decl **OriginalDecl) const {
368 if (Key.isNull()) {
369 if (OriginalDecl)
370 *OriginalDecl = nullptr;
371 return nullptr;
372 }
373
374 // Macros have no redeclaration chain: look up directly, populate the cache,
375 // and return.
376 if (const auto *MI = dyn_cast<const MacroInfo *>(Val&: Key)) {
377 if (OriginalDecl)
378 *OriginalDecl = nullptr;
379 auto Existing = RawComments.find(Val: Key);
380 if (Existing != RawComments.end())
381 return Existing->second;
382 if (const RawComment *RC = getRawCommentNoCache(Key)) {
383 cacheRawComment(Original: MI, Comment: *RC);
384 return RC;
385 }
386 return nullptr;
387 }
388
389 const Decl *D = cast<const Decl *>(Val&: Key);
390 D = &adjustDeclToTemplate(D: *D);
391
392 // Any comment directly attached to D?
393 {
394 auto DeclComment = RawComments.find(Val: D);
395 if (DeclComment != RawComments.end()) {
396 if (OriginalDecl)
397 *OriginalDecl = D;
398 return DeclComment->second;
399 }
400 }
401
402 // Any comment attached to any redeclaration of D?
403 const Decl *CanonicalD = D->getCanonicalDecl();
404 if (!CanonicalD)
405 return nullptr;
406
407 {
408 auto RedeclComment = RedeclChainComments.find(Val: CanonicalD);
409 if (RedeclComment != RedeclChainComments.end()) {
410 if (OriginalDecl)
411 *OriginalDecl = RedeclComment->second;
412 auto CommentAtRedecl = RawComments.find(Val: RedeclComment->second);
413 assert(CommentAtRedecl != RawComments.end() &&
414 "This decl is supposed to have comment attached.");
415 return CommentAtRedecl->second;
416 }
417 }
418
419 // Any redeclarations of D that we haven't checked for comments yet?
420 const Decl *LastCheckedRedecl = [&]() {
421 const Decl *LastChecked = CommentlessRedeclChains.lookup(Val: CanonicalD);
422 bool CanUseCommentlessCache = false;
423 if (LastChecked) {
424 for (auto *Redecl : CanonicalD->redecls()) {
425 if (Redecl == D) {
426 CanUseCommentlessCache = true;
427 break;
428 }
429 if (Redecl == LastChecked)
430 break;
431 }
432 }
433 // FIXME: This could be improved so that even if CanUseCommentlessCache
434 // is false, once we've traversed past CanonicalD we still skip ahead
435 // LastChecked.
436 return CanUseCommentlessCache ? LastChecked : nullptr;
437 }();
438
439 for (const Decl *Redecl : D->redecls()) {
440 assert(Redecl);
441 // Skip all redeclarations that have been checked previously.
442 if (LastCheckedRedecl) {
443 if (LastCheckedRedecl == Redecl) {
444 LastCheckedRedecl = nullptr;
445 }
446 continue;
447 }
448 const RawComment *RedeclComment = getRawCommentNoCache(Key: Redecl);
449 if (RedeclComment) {
450 cacheRawComment(Original: Redecl, Comment: *RedeclComment);
451 if (OriginalDecl)
452 *OriginalDecl = Redecl;
453 return RedeclComment;
454 }
455 CommentlessRedeclChains[CanonicalD] = Redecl;
456 }
457
458 if (OriginalDecl)
459 *OriginalDecl = nullptr;
460 return nullptr;
461}
462
463void ASTContext::cacheRawComment(RawCommentLookupKey Original,
464 const RawComment &Comment) const {
465 assert(Comment.isDocumentation() || LangOpts.CommentOpts.ParseAllComments);
466 RawComments.try_emplace(Key: Original, Args: &Comment);
467 if (const auto *D = dyn_cast<const Decl *>(Val&: Original)) {
468 const Decl *const CanonicalDecl = D->getCanonicalDecl();
469 RedeclChainComments.try_emplace(Key: CanonicalDecl, Args&: D);
470 CommentlessRedeclChains.erase(Val: CanonicalDecl);
471 }
472}
473
474static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
475 SmallVectorImpl<const NamedDecl *> &Redeclared) {
476 const DeclContext *DC = ObjCMethod->getDeclContext();
477 if (const auto *IMD = dyn_cast<ObjCImplDecl>(Val: DC)) {
478 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
479 if (!ID)
480 return;
481 // Add redeclared method here.
482 for (const auto *Ext : ID->known_extensions()) {
483 if (ObjCMethodDecl *RedeclaredMethod =
484 Ext->getMethod(Sel: ObjCMethod->getSelector(),
485 isInstance: ObjCMethod->isInstanceMethod()))
486 Redeclared.push_back(Elt: RedeclaredMethod);
487 }
488 }
489}
490
491void ASTContext::attachCommentsToJustParsedDecls(ArrayRef<Decl *> Decls,
492 const Preprocessor *PP) {
493 if (Comments.empty() || Decls.empty())
494 return;
495
496 FileID File;
497 for (const Decl *D : Decls) {
498 if (D->isInvalidDecl())
499 continue;
500
501 D = &adjustDeclToTemplate(D: *D);
502 SourceLocation Loc = D->getLocation();
503 if (Loc.isValid()) {
504 // See if there are any new comments that are not attached to a decl.
505 // The location doesn't have to be precise - we care only about the file.
506 File = SourceMgr.getDecomposedLoc(Loc).first;
507 break;
508 }
509 }
510
511 if (File.isInvalid())
512 return;
513
514 auto CommentsInThisFile = Comments.getCommentsInFile(File);
515 if (!CommentsInThisFile || CommentsInThisFile->empty() ||
516 CommentsInThisFile->rbegin()->second->isAttached())
517 return;
518
519 // There is at least one comment not attached to a decl.
520 // Maybe it should be attached to one of Decls?
521 //
522 // Note that this way we pick up not only comments that precede the
523 // declaration, but also comments that *follow* the declaration -- thanks to
524 // the lookahead in the lexer: we've consumed the semicolon and looked
525 // ahead through comments.
526 for (const Decl *D : Decls) {
527 assert(D);
528 if (D->isInvalidDecl())
529 continue;
530
531 D = &adjustDeclToTemplate(D: *D);
532
533 if (RawComments.count(Val: D) > 0)
534 continue;
535
536 const auto DeclLocs = getLocsForCommentSearch(Key: D, SourceMgr);
537
538 for (const auto DeclLoc : DeclLocs) {
539 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
540 continue;
541
542 if (RawComment *const DocComment =
543 getRawCommentNoCacheImpl(Key: D, RepresentativeLoc: DeclLoc, CommentsInTheFile: *CommentsInThisFile)) {
544 cacheRawComment(Original: D, Comment: *DocComment);
545 comments::FullComment *FC = DocComment->parse(Context: *this, PP, D);
546 ParsedComments[D->getCanonicalDecl()] = FC;
547 break;
548 }
549 }
550 }
551}
552
553comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
554 const Decl *D) const {
555 auto *ThisDeclInfo = new (*this) comments::DeclInfo;
556 ThisDeclInfo->CommentDecl = D;
557 ThisDeclInfo->IsFilled = false;
558 ThisDeclInfo->fill();
559 ThisDeclInfo->CommentDecl = FC->getDecl();
560 if (!ThisDeclInfo->TemplateParameters)
561 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
562 comments::FullComment *CFC =
563 new (*this) comments::FullComment(FC->getBlocks(),
564 ThisDeclInfo);
565 return CFC;
566}
567
568comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
569 const RawComment *RC = getRawCommentNoCache(Key: D);
570 return RC ? RC->parse(Context: *this, PP: nullptr, D) : nullptr;
571}
572
573comments::FullComment *ASTContext::getCommentForDecl(
574 const Decl *D,
575 const Preprocessor *PP) const {
576 if (!D || D->isInvalidDecl())
577 return nullptr;
578 D = &adjustDeclToTemplate(D: *D);
579
580 const Decl *Canonical = D->getCanonicalDecl();
581 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
582 ParsedComments.find(Val: Canonical);
583
584 if (Pos != ParsedComments.end()) {
585 if (Canonical != D) {
586 comments::FullComment *FC = Pos->second;
587 comments::FullComment *CFC = cloneFullComment(FC, D);
588 return CFC;
589 }
590 return Pos->second;
591 }
592
593 const Decl *OriginalDecl = nullptr;
594
595 const RawComment *RC = getRawCommentForAnyRedecl(Key: D, OriginalDecl: &OriginalDecl);
596 if (!RC) {
597 if (isa<ObjCMethodDecl>(Val: D) || isa<FunctionDecl>(Val: D)) {
598 SmallVector<const NamedDecl*, 8> Overridden;
599 const auto *OMD = dyn_cast<ObjCMethodDecl>(Val: D);
600 if (OMD && OMD->isPropertyAccessor())
601 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
602 if (comments::FullComment *FC = getCommentForDecl(D: PDecl, PP))
603 return cloneFullComment(FC, D);
604 if (OMD)
605 addRedeclaredMethods(ObjCMethod: OMD, Redeclared&: Overridden);
606 getOverriddenMethods(Method: dyn_cast<NamedDecl>(Val: D), Overridden);
607 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
608 if (comments::FullComment *FC = getCommentForDecl(D: Overridden[i], PP))
609 return cloneFullComment(FC, D);
610 }
611 else if (const auto *TD = dyn_cast<TypedefNameDecl>(Val: D)) {
612 // Attach any tag type's documentation to its typedef if latter
613 // does not have one of its own.
614 QualType QT = TD->getUnderlyingType();
615 if (const auto *TT = QT->getAs<TagType>())
616 if (comments::FullComment *FC = getCommentForDecl(D: TT->getDecl(), PP))
617 return cloneFullComment(FC, D);
618 }
619 else if (const auto *IC = dyn_cast<ObjCInterfaceDecl>(Val: D)) {
620 while (IC->getSuperClass()) {
621 IC = IC->getSuperClass();
622 if (comments::FullComment *FC = getCommentForDecl(D: IC, PP))
623 return cloneFullComment(FC, D);
624 }
625 }
626 else if (const auto *CD = dyn_cast<ObjCCategoryDecl>(Val: D)) {
627 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
628 if (comments::FullComment *FC = getCommentForDecl(D: IC, PP))
629 return cloneFullComment(FC, D);
630 }
631 else if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: D)) {
632 if (!(RD = RD->getDefinition()))
633 return nullptr;
634 // Check non-virtual bases.
635 for (const auto &I : RD->bases()) {
636 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
637 continue;
638 QualType Ty = I.getType();
639 if (Ty.isNull())
640 continue;
641 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
642 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
643 continue;
644
645 if (comments::FullComment *FC = getCommentForDecl(D: (NonVirtualBase), PP))
646 return cloneFullComment(FC, D);
647 }
648 }
649 // Check virtual bases.
650 for (const auto &I : RD->vbases()) {
651 if (I.getAccessSpecifier() != AS_public)
652 continue;
653 QualType Ty = I.getType();
654 if (Ty.isNull())
655 continue;
656 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
657 if (!(VirtualBase= VirtualBase->getDefinition()))
658 continue;
659 if (comments::FullComment *FC = getCommentForDecl(D: (VirtualBase), PP))
660 return cloneFullComment(FC, D);
661 }
662 }
663 }
664 return nullptr;
665 }
666
667 // If the RawComment was attached to other redeclaration of this Decl, we
668 // should parse the comment in context of that other Decl. This is important
669 // because comments can contain references to parameter names which can be
670 // different across redeclarations.
671 if (D != OriginalDecl && OriginalDecl)
672 return getCommentForDecl(D: OriginalDecl, PP);
673
674 comments::FullComment *FC = RC->parse(Context: *this, PP, D);
675 ParsedComments[Canonical] = FC;
676 return FC;
677}
678
679void ASTContext::CanonicalTemplateTemplateParm::Profile(
680 llvm::FoldingSetNodeID &ID, const ASTContext &C,
681 TemplateTemplateParmDecl *Parm) {
682 ID.AddInteger(I: Parm->getDepth());
683 ID.AddInteger(I: Parm->getPosition());
684 ID.AddBoolean(B: Parm->isParameterPack());
685 ID.AddInteger(I: Parm->templateParameterKind());
686
687 TemplateParameterList *Params = Parm->getTemplateParameters();
688 ID.AddInteger(I: Params->size());
689 for (TemplateParameterList::const_iterator P = Params->begin(),
690 PEnd = Params->end();
691 P != PEnd; ++P) {
692 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Val: *P)) {
693 ID.AddInteger(I: 0);
694 ID.AddBoolean(B: TTP->isParameterPack());
695 ID.AddInteger(
696 I: TTP->getNumExpansionParameters().toInternalRepresentation());
697 continue;
698 }
699
700 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: *P)) {
701 ID.AddInteger(I: 1);
702 ID.AddBoolean(B: NTTP->isParameterPack());
703 ID.AddPointer(Ptr: C.getUnconstrainedType(T: C.getCanonicalType(T: NTTP->getType()))
704 .getAsOpaquePtr());
705 if (NTTP->isExpandedParameterPack()) {
706 ID.AddBoolean(B: true);
707 ID.AddInteger(I: NTTP->getNumExpansionTypes());
708 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
709 QualType T = NTTP->getExpansionType(I);
710 ID.AddPointer(Ptr: T.getCanonicalType().getAsOpaquePtr());
711 }
712 } else
713 ID.AddBoolean(B: false);
714 continue;
715 }
716
717 auto *TTP = cast<TemplateTemplateParmDecl>(Val: *P);
718 ID.AddInteger(I: 2);
719 Profile(ID, C, Parm: TTP);
720 }
721}
722
723TemplateTemplateParmDecl *
724ASTContext::getCanonicalTemplateTemplateParmDecl(
725 TemplateTemplateParmDecl *TTP) const {
726 // Check if we already have a canonical template template parameter.
727 llvm::FoldingSetNodeID ID;
728 CanonicalTemplateTemplateParm::Profile(ID, C: *this, Parm: TTP);
729 void *InsertPos = nullptr;
730 CanonicalTemplateTemplateParm *Canonical
731 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
732 if (Canonical)
733 return Canonical->getParam();
734
735 // Build a canonical template parameter list.
736 TemplateParameterList *Params = TTP->getTemplateParameters();
737 SmallVector<NamedDecl *, 4> CanonParams;
738 CanonParams.reserve(N: Params->size());
739 for (TemplateParameterList::const_iterator P = Params->begin(),
740 PEnd = Params->end();
741 P != PEnd; ++P) {
742 // Note that, per C++20 [temp.over.link]/6, when determining whether
743 // template-parameters are equivalent, constraints are ignored.
744 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Val: *P)) {
745 TemplateTypeParmDecl *NewTTP = TemplateTypeParmDecl::Create(
746 C: *this, DC: getTranslationUnitDecl(), KeyLoc: SourceLocation(), NameLoc: SourceLocation(),
747 D: TTP->getDepth(), P: TTP->getIndex(), Id: nullptr, Typename: false,
748 ParameterPack: TTP->isParameterPack(), /*HasTypeConstraint=*/false,
749 NumExpanded: TTP->getNumExpansionParameters());
750 CanonParams.push_back(Elt: NewTTP);
751 } else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: *P)) {
752 QualType T = getUnconstrainedType(T: getCanonicalType(T: NTTP->getType()));
753 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
754 NonTypeTemplateParmDecl *Param;
755 if (NTTP->isExpandedParameterPack()) {
756 SmallVector<QualType, 2> ExpandedTypes;
757 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
758 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
759 ExpandedTypes.push_back(Elt: getCanonicalType(T: NTTP->getExpansionType(I)));
760 ExpandedTInfos.push_back(
761 Elt: getTrivialTypeSourceInfo(T: ExpandedTypes.back()));
762 }
763
764 Param = NonTypeTemplateParmDecl::Create(C: *this, DC: getTranslationUnitDecl(),
765 StartLoc: SourceLocation(),
766 IdLoc: SourceLocation(),
767 D: NTTP->getDepth(),
768 P: NTTP->getPosition(), Id: nullptr,
769 T,
770 TInfo,
771 ExpandedTypes,
772 ExpandedTInfos);
773 } else {
774 Param = NonTypeTemplateParmDecl::Create(C: *this, DC: getTranslationUnitDecl(),
775 StartLoc: SourceLocation(),
776 IdLoc: SourceLocation(),
777 D: NTTP->getDepth(),
778 P: NTTP->getPosition(), Id: nullptr,
779 T,
780 ParameterPack: NTTP->isParameterPack(),
781 TInfo);
782 }
783 CanonParams.push_back(Elt: Param);
784 } else
785 CanonParams.push_back(Elt: getCanonicalTemplateTemplateParmDecl(
786 TTP: cast<TemplateTemplateParmDecl>(Val: *P)));
787 }
788
789 TemplateTemplateParmDecl *CanonTTP = TemplateTemplateParmDecl::Create(
790 C: *this, DC: getTranslationUnitDecl(), L: SourceLocation(), D: TTP->getDepth(),
791 P: TTP->getPosition(), ParameterPack: TTP->isParameterPack(), Id: nullptr,
792 ParameterKind: TTP->templateParameterKind(),
793 /*Typename=*/false,
794 Params: TemplateParameterList::Create(C: *this, TemplateLoc: SourceLocation(), LAngleLoc: SourceLocation(),
795 Params: CanonParams, RAngleLoc: SourceLocation(),
796 /*RequiresClause=*/nullptr));
797
798 // Get the new insert position for the node we care about.
799 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
800 assert(!Canonical && "Shouldn't be in the map!");
801 (void)Canonical;
802
803 // Create the canonical template template parameter entry.
804 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
805 CanonTemplateTemplateParms.InsertNode(N: Canonical, InsertPos);
806 return CanonTTP;
807}
808
809TemplateTemplateParmDecl *
810ASTContext::findCanonicalTemplateTemplateParmDeclInternal(
811 TemplateTemplateParmDecl *TTP) const {
812 llvm::FoldingSetNodeID ID;
813 CanonicalTemplateTemplateParm::Profile(ID, C: *this, Parm: TTP);
814 void *InsertPos = nullptr;
815 CanonicalTemplateTemplateParm *Canonical =
816 CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
817 return Canonical ? Canonical->getParam() : nullptr;
818}
819
820TemplateTemplateParmDecl *
821ASTContext::insertCanonicalTemplateTemplateParmDeclInternal(
822 TemplateTemplateParmDecl *CanonTTP) const {
823 llvm::FoldingSetNodeID ID;
824 CanonicalTemplateTemplateParm::Profile(ID, C: *this, Parm: CanonTTP);
825 void *InsertPos = nullptr;
826 if (auto *Existing =
827 CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos))
828 return Existing->getParam();
829 CanonTemplateTemplateParms.InsertNode(
830 N: new (*this) CanonicalTemplateTemplateParm(CanonTTP), InsertPos);
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
911ParentMapContext &ASTContext::getParentMapContext() {
912 if (!ParentMapCtx)
913 ParentMapCtx.reset(p: new ParentMapContext(*this));
914 return *ParentMapCtx;
915}
916
917static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
918 const LangOptions &LangOpts) {
919 switch (LangOpts.getAddressSpaceMapMangling()) {
920 case LangOptions::ASMM_Target:
921 return TI.useAddressSpaceMapMangling();
922 case LangOptions::ASMM_On:
923 return true;
924 case LangOptions::ASMM_Off:
925 return false;
926 }
927 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
928}
929
930ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
931 IdentifierTable &idents, SelectorTable &sels,
932 Builtin::Context &builtins, TranslationUnitKind TUKind)
933 : ConstantArrayTypes(this_(), ConstantArrayTypesLog2InitSize),
934 DependentSizedArrayTypes(this_()), DependentSizedExtVectorTypes(this_()),
935 DependentAddressSpaceTypes(this_()), DependentVectorTypes(this_()),
936 DependentSizedMatrixTypes(this_()),
937 FunctionProtoTypes(this_(), FunctionProtoTypesLog2InitSize),
938 DependentTypeOfExprTypes(this_()), DependentDecltypeTypes(this_()),
939 DependentPackIndexingTypes(this_()), TemplateSpecializationTypes(this_()),
940 AttributedTypes(this_()), DependentBitIntTypes(this_()),
941 SubstTemplateTemplateParmPacks(this_()), DeducedTemplates(this_()),
942 ArrayParameterTypes(this_()), CanonTemplateTemplateParms(this_()),
943 SourceMgr(SM), LangOpts(LOpts),
944 NoSanitizeL(new NoSanitizeList(LangOpts.NoSanitizeFiles, SM)),
945 XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles,
946 LangOpts.XRayNeverInstrumentFiles,
947 LangOpts.XRayAttrListFiles, SM)),
948 ProfList(new ProfileList(LangOpts.ProfileListFiles, SM)),
949 PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
950 BuiltinInfo(builtins), TUKind(TUKind), DeclarationNames(*this),
951 Comments(SM), CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
952 CompCategories(this_()), LastSDM(nullptr, 0) {
953 addTranslationUnitDecl();
954}
955
956void ASTContext::cleanup() {
957 // Release the DenseMaps associated with DeclContext objects.
958 // FIXME: Is this the ideal solution?
959 ReleaseDeclContextMaps();
960
961 // Call all of the deallocation functions on all of their targets.
962 for (auto &Pair : Deallocations)
963 (Pair.first)(Pair.second);
964 Deallocations.clear();
965
966 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
967 // because they can contain DenseMaps.
968 for (llvm::DenseMap<const ObjCInterfaceDecl *,
969 const ASTRecordLayout *>::iterator
970 I = ObjCLayouts.begin(),
971 E = ObjCLayouts.end();
972 I != E;)
973 // Increment in loop to prevent using deallocated memory.
974 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
975 R->Destroy(Ctx&: *this);
976 ObjCLayouts.clear();
977
978 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
979 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
980 // Increment in loop to prevent using deallocated memory.
981 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
982 R->Destroy(Ctx&: *this);
983 }
984 ASTRecordLayouts.clear();
985
986 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
987 AEnd = DeclAttrs.end();
988 A != AEnd; ++A)
989 A->second->~AttrVec();
990 DeclAttrs.clear();
991
992 for (const auto &Value : ModuleInitializers)
993 Value.second->~PerModuleInitializers();
994 ModuleInitializers.clear();
995
996 TUDecl = nullptr;
997 XRayFilter.reset();
998 NoSanitizeL.reset();
999}
1000
1001ASTContext::~ASTContext() { cleanup(); }
1002
1003void ASTContext::setTraversalScope(const std::vector<Decl *> &TopLevelDecls) {
1004 TraversalScope = TopLevelDecls;
1005 getParentMapContext().clear();
1006}
1007
1008void ASTContext::AddDeallocation(void (*Callback)(void *), void *Data) const {
1009 Deallocations.push_back(Elt: {Callback, Data});
1010}
1011
1012void
1013ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
1014 ExternalSource = std::move(Source);
1015}
1016
1017void ASTContext::PrintStats() const {
1018 llvm::errs() << "\n*** AST Context Stats:\n";
1019 llvm::errs() << " " << Types.size() << " types total.\n";
1020
1021 unsigned counts[] = {
1022#define TYPE(Name, Parent) 0,
1023#define ABSTRACT_TYPE(Name, Parent)
1024#include "clang/AST/TypeNodes.inc"
1025 0 // Extra
1026 };
1027
1028 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
1029 Type *T = Types[i];
1030 counts[(unsigned)T->getTypeClass()]++;
1031 }
1032
1033 unsigned Idx = 0;
1034 unsigned TotalBytes = 0;
1035#define TYPE(Name, Parent) \
1036 if (counts[Idx]) \
1037 llvm::errs() << " " << counts[Idx] << " " << #Name \
1038 << " types, " << sizeof(Name##Type) << " each " \
1039 << "(" << counts[Idx] * sizeof(Name##Type) \
1040 << " bytes)\n"; \
1041 TotalBytes += counts[Idx] * sizeof(Name##Type); \
1042 ++Idx;
1043#define ABSTRACT_TYPE(Name, Parent)
1044#include "clang/AST/TypeNodes.inc"
1045
1046 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
1047
1048 // Implicit special member functions.
1049 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
1050 << NumImplicitDefaultConstructors
1051 << " implicit default constructors created\n";
1052 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
1053 << NumImplicitCopyConstructors
1054 << " implicit copy constructors created\n";
1055 if (getLangOpts().CPlusPlus)
1056 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
1057 << NumImplicitMoveConstructors
1058 << " implicit move constructors created\n";
1059 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
1060 << NumImplicitCopyAssignmentOperators
1061 << " implicit copy assignment operators created\n";
1062 if (getLangOpts().CPlusPlus)
1063 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
1064 << NumImplicitMoveAssignmentOperators
1065 << " implicit move assignment operators created\n";
1066 llvm::errs() << NumImplicitDestructorsDeclared << "/"
1067 << NumImplicitDestructors
1068 << " implicit destructors created\n";
1069
1070 if (ExternalSource) {
1071 llvm::errs() << "\n";
1072 ExternalSource->PrintStats();
1073 }
1074
1075 BumpAlloc.PrintStats();
1076}
1077
1078void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
1079 bool NotifyListeners) {
1080 if (NotifyListeners)
1081 if (auto *Listener = getASTMutationListener();
1082 Listener && !ND->isUnconditionallyVisible())
1083 Listener->RedefinedHiddenDefinition(D: ND, M);
1084
1085 MergedDefModules[cast<NamedDecl>(Val: ND->getCanonicalDecl())].push_back(NewVal: M);
1086}
1087
1088void ASTContext::deduplicateMergedDefinitionsFor(NamedDecl *ND) {
1089 auto It = MergedDefModules.find(Val: cast<NamedDecl>(Val: ND->getCanonicalDecl()));
1090 if (It == MergedDefModules.end())
1091 return;
1092
1093 auto &Merged = It->second;
1094 llvm::DenseSet<Module*> Found;
1095 for (Module *&M : Merged)
1096 if (!Found.insert(V: M).second)
1097 M = nullptr;
1098 llvm::erase(C&: Merged, V: nullptr);
1099}
1100
1101ArrayRef<Module *>
1102ASTContext::getModulesWithMergedDefinition(const NamedDecl *Def) {
1103 auto MergedIt =
1104 MergedDefModules.find(Val: cast<NamedDecl>(Val: Def->getCanonicalDecl()));
1105 if (MergedIt == MergedDefModules.end())
1106 return {};
1107 return MergedIt->second;
1108}
1109
1110void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
1111 if (LazyInitializers.empty())
1112 return;
1113
1114 auto *Source = Ctx.getExternalSource();
1115 assert(Source && "lazy initializers but no external source");
1116
1117 auto LazyInits = std::move(LazyInitializers);
1118 LazyInitializers.clear();
1119
1120 for (auto ID : LazyInits)
1121 Initializers.push_back(Elt: Source->GetExternalDecl(ID));
1122
1123 assert(LazyInitializers.empty() &&
1124 "GetExternalDecl for lazy module initializer added more inits");
1125}
1126
1127void ASTContext::addModuleInitializer(Module *M, Decl *D) {
1128 // One special case: if we add a module initializer that imports another
1129 // module, and that module's only initializer is an ImportDecl, simplify.
1130 if (const auto *ID = dyn_cast<ImportDecl>(Val: D)) {
1131 auto It = ModuleInitializers.find(Val: ID->getImportedModule());
1132
1133 // Maybe the ImportDecl does nothing at all. (Common case.)
1134 if (It == ModuleInitializers.end())
1135 return;
1136
1137 // Maybe the ImportDecl only imports another ImportDecl.
1138 auto &Imported = *It->second;
1139 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
1140 Imported.resolve(Ctx&: *this);
1141 auto *OnlyDecl = Imported.Initializers.front();
1142 if (isa<ImportDecl>(Val: OnlyDecl))
1143 D = OnlyDecl;
1144 }
1145 }
1146
1147 auto *&Inits = ModuleInitializers[M];
1148 if (!Inits)
1149 Inits = new (*this) PerModuleInitializers;
1150 Inits->Initializers.push_back(Elt: D);
1151}
1152
1153void ASTContext::addLazyModuleInitializers(Module *M,
1154 ArrayRef<GlobalDeclID> IDs) {
1155 auto *&Inits = ModuleInitializers[M];
1156 if (!Inits)
1157 Inits = new (*this) PerModuleInitializers;
1158 Inits->LazyInitializers.insert(I: Inits->LazyInitializers.end(),
1159 From: IDs.begin(), To: IDs.end());
1160}
1161
1162ArrayRef<Decl *> ASTContext::getModuleInitializers(Module *M) {
1163 auto It = ModuleInitializers.find(Val: M);
1164 if (It == ModuleInitializers.end())
1165 return {};
1166
1167 auto *Inits = It->second;
1168 Inits->resolve(Ctx&: *this);
1169 return Inits->Initializers;
1170}
1171
1172void ASTContext::setCurrentNamedModule(Module *M) {
1173 assert(M->isNamedModule());
1174 assert(!CurrentCXXNamedModule &&
1175 "We should set named module for ASTContext for only once");
1176 CurrentCXXNamedModule = M;
1177}
1178
1179bool ASTContext::isInSameModule(const Module *M1, const Module *M2) const {
1180 if (!M1 != !M2)
1181 return false;
1182
1183 /// Get the representative module for M. The representative module is the
1184 /// first module unit for a specific primary module name. So that the module
1185 /// units have the same representative module belongs to the same module.
1186 ///
1187 /// The process is helpful to reduce the expensive string operations.
1188 auto GetRepresentativeModule = [this](const Module *M) {
1189 auto Iter = SameModuleLookupSet.find(Val: M);
1190 if (Iter != SameModuleLookupSet.end())
1191 return Iter->second;
1192
1193 const Module *RepresentativeModule =
1194 PrimaryModuleNameMap.try_emplace(Key: M->getPrimaryModuleInterfaceName(), Args&: M)
1195 .first->second;
1196 SameModuleLookupSet[M] = RepresentativeModule;
1197 return RepresentativeModule;
1198 };
1199
1200 assert(M1 && "Shouldn't call `isInSameModule` if both M1 and M2 are none.");
1201 return GetRepresentativeModule(M1) == GetRepresentativeModule(M2);
1202}
1203
1204ExternCContextDecl *ASTContext::getExternCContextDecl() const {
1205 if (!ExternCContext)
1206 ExternCContext = ExternCContextDecl::Create(C: *this, TU: getTranslationUnitDecl());
1207
1208 return ExternCContext;
1209}
1210
1211BuiltinTemplateDecl *
1212ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
1213 const IdentifierInfo *II) const {
1214 auto *BuiltinTemplate =
1215 BuiltinTemplateDecl::Create(C: *this, DC: getTranslationUnitDecl(), Name: II, BTK);
1216 BuiltinTemplate->setImplicit();
1217 getTranslationUnitDecl()->addDecl(D: BuiltinTemplate);
1218
1219 return BuiltinTemplate;
1220}
1221
1222#define BuiltinTemplate(BTName) \
1223 BuiltinTemplateDecl *ASTContext::get##BTName##Decl() const { \
1224 if (!Decl##BTName) \
1225 Decl##BTName = \
1226 buildBuiltinTemplateDecl(BTK##BTName, get##BTName##Name()); \
1227 return Decl##BTName; \
1228 }
1229#include "clang/Basic/BuiltinTemplates.inc"
1230
1231RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
1232 RecordDecl::TagKind TK) const {
1233 SourceLocation Loc;
1234 RecordDecl *NewDecl;
1235 if (getLangOpts().CPlusPlus)
1236 NewDecl = CXXRecordDecl::Create(C: *this, TK, DC: getTranslationUnitDecl(), StartLoc: Loc,
1237 IdLoc: Loc, Id: &Idents.get(Name));
1238 else
1239 NewDecl = RecordDecl::Create(C: *this, TK, DC: getTranslationUnitDecl(), StartLoc: Loc, IdLoc: Loc,
1240 Id: &Idents.get(Name));
1241 NewDecl->setImplicit();
1242 NewDecl->addAttr(A: TypeVisibilityAttr::CreateImplicit(
1243 Ctx&: const_cast<ASTContext &>(*this), Visibility: TypeVisibilityAttr::Default));
1244 return NewDecl;
1245}
1246
1247TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
1248 StringRef Name) const {
1249 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
1250 TypedefDecl *NewDecl = TypedefDecl::Create(
1251 C&: const_cast<ASTContext &>(*this), DC: getTranslationUnitDecl(),
1252 StartLoc: SourceLocation(), IdLoc: SourceLocation(), Id: &Idents.get(Name), TInfo);
1253 NewDecl->setImplicit();
1254 return NewDecl;
1255}
1256
1257TypedefDecl *ASTContext::getInt128Decl() const {
1258 if (!Int128Decl)
1259 Int128Decl = buildImplicitTypedef(T: Int128Ty, Name: "__int128_t");
1260 return Int128Decl;
1261}
1262
1263TypedefDecl *ASTContext::getUInt128Decl() const {
1264 if (!UInt128Decl)
1265 UInt128Decl = buildImplicitTypedef(T: UnsignedInt128Ty, Name: "__uint128_t");
1266 return UInt128Decl;
1267}
1268
1269void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
1270 auto *Ty = new (*this, alignof(BuiltinType)) BuiltinType(K);
1271 R = CanQualType::CreateUnsafe(Other: QualType(Ty, 0));
1272 Types.push_back(Elt: Ty);
1273}
1274
1275void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
1276 const TargetInfo *AuxTarget) {
1277 assert((!this->Target || this->Target == &Target) &&
1278 "Incorrect target reinitialization");
1279 assert(VoidTy.isNull() && "Context reinitialized?");
1280
1281 this->Target = &Target;
1282 this->AuxTarget = AuxTarget;
1283
1284 ABI.reset(p: createCXXABI(T: Target));
1285 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(TI: Target, LangOpts);
1286
1287 // C99 6.2.5p19.
1288 InitBuiltinType(R&: VoidTy, K: BuiltinType::Void);
1289
1290 // C99 6.2.5p2.
1291 InitBuiltinType(R&: BoolTy, K: BuiltinType::Bool);
1292 // C99 6.2.5p3.
1293 if (LangOpts.CharIsSigned)
1294 InitBuiltinType(R&: CharTy, K: BuiltinType::Char_S);
1295 else
1296 InitBuiltinType(R&: CharTy, K: BuiltinType::Char_U);
1297 // C99 6.2.5p4.
1298 InitBuiltinType(R&: SignedCharTy, K: BuiltinType::SChar);
1299 InitBuiltinType(R&: ShortTy, K: BuiltinType::Short);
1300 InitBuiltinType(R&: IntTy, K: BuiltinType::Int);
1301 InitBuiltinType(R&: LongTy, K: BuiltinType::Long);
1302 InitBuiltinType(R&: LongLongTy, K: BuiltinType::LongLong);
1303
1304 // C99 6.2.5p6.
1305 InitBuiltinType(R&: UnsignedCharTy, K: BuiltinType::UChar);
1306 InitBuiltinType(R&: UnsignedShortTy, K: BuiltinType::UShort);
1307 InitBuiltinType(R&: UnsignedIntTy, K: BuiltinType::UInt);
1308 InitBuiltinType(R&: UnsignedLongTy, K: BuiltinType::ULong);
1309 InitBuiltinType(R&: UnsignedLongLongTy, K: BuiltinType::ULongLong);
1310
1311 // C99 6.2.5p10.
1312 InitBuiltinType(R&: FloatTy, K: BuiltinType::Float);
1313 InitBuiltinType(R&: DoubleTy, K: BuiltinType::Double);
1314 InitBuiltinType(R&: LongDoubleTy, K: BuiltinType::LongDouble);
1315
1316 // GNU extension, __float128 for IEEE quadruple precision
1317 InitBuiltinType(R&: Float128Ty, K: BuiltinType::Float128);
1318
1319 // __ibm128 for IBM extended precision
1320 InitBuiltinType(R&: Ibm128Ty, K: BuiltinType::Ibm128);
1321
1322 // C11 extension ISO/IEC TS 18661-3
1323 InitBuiltinType(R&: Float16Ty, K: BuiltinType::Float16);
1324
1325 // ISO/IEC JTC1 SC22 WG14 N1169 Extension
1326 InitBuiltinType(R&: ShortAccumTy, K: BuiltinType::ShortAccum);
1327 InitBuiltinType(R&: AccumTy, K: BuiltinType::Accum);
1328 InitBuiltinType(R&: LongAccumTy, K: BuiltinType::LongAccum);
1329 InitBuiltinType(R&: UnsignedShortAccumTy, K: BuiltinType::UShortAccum);
1330 InitBuiltinType(R&: UnsignedAccumTy, K: BuiltinType::UAccum);
1331 InitBuiltinType(R&: UnsignedLongAccumTy, K: BuiltinType::ULongAccum);
1332 InitBuiltinType(R&: ShortFractTy, K: BuiltinType::ShortFract);
1333 InitBuiltinType(R&: FractTy, K: BuiltinType::Fract);
1334 InitBuiltinType(R&: LongFractTy, K: BuiltinType::LongFract);
1335 InitBuiltinType(R&: UnsignedShortFractTy, K: BuiltinType::UShortFract);
1336 InitBuiltinType(R&: UnsignedFractTy, K: BuiltinType::UFract);
1337 InitBuiltinType(R&: UnsignedLongFractTy, K: BuiltinType::ULongFract);
1338 InitBuiltinType(R&: SatShortAccumTy, K: BuiltinType::SatShortAccum);
1339 InitBuiltinType(R&: SatAccumTy, K: BuiltinType::SatAccum);
1340 InitBuiltinType(R&: SatLongAccumTy, K: BuiltinType::SatLongAccum);
1341 InitBuiltinType(R&: SatUnsignedShortAccumTy, K: BuiltinType::SatUShortAccum);
1342 InitBuiltinType(R&: SatUnsignedAccumTy, K: BuiltinType::SatUAccum);
1343 InitBuiltinType(R&: SatUnsignedLongAccumTy, K: BuiltinType::SatULongAccum);
1344 InitBuiltinType(R&: SatShortFractTy, K: BuiltinType::SatShortFract);
1345 InitBuiltinType(R&: SatFractTy, K: BuiltinType::SatFract);
1346 InitBuiltinType(R&: SatLongFractTy, K: BuiltinType::SatLongFract);
1347 InitBuiltinType(R&: SatUnsignedShortFractTy, K: BuiltinType::SatUShortFract);
1348 InitBuiltinType(R&: SatUnsignedFractTy, K: BuiltinType::SatUFract);
1349 InitBuiltinType(R&: SatUnsignedLongFractTy, K: BuiltinType::SatULongFract);
1350
1351 // GNU extension, 128-bit integers.
1352 InitBuiltinType(R&: Int128Ty, K: BuiltinType::Int128);
1353 InitBuiltinType(R&: UnsignedInt128Ty, K: BuiltinType::UInt128);
1354
1355 // C++ 3.9.1p5
1356 if (TargetInfo::isTypeSigned(T: Target.getWCharType()))
1357 InitBuiltinType(R&: WCharTy, K: BuiltinType::WChar_S);
1358 else // -fshort-wchar makes wchar_t be unsigned.
1359 InitBuiltinType(R&: WCharTy, K: BuiltinType::WChar_U);
1360 if (LangOpts.CPlusPlus && LangOpts.WChar)
1361 WideCharTy = WCharTy;
1362 else {
1363 // C99 (or C++ using -fno-wchar).
1364 WideCharTy = getFromTargetType(Type: Target.getWCharType());
1365 }
1366
1367 WIntTy = getFromTargetType(Type: Target.getWIntType());
1368
1369 // C++20 (proposed)
1370 InitBuiltinType(R&: Char8Ty, K: BuiltinType::Char8);
1371
1372 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1373 InitBuiltinType(R&: Char16Ty, K: BuiltinType::Char16);
1374 else // C99
1375 Char16Ty = getFromTargetType(Type: Target.getChar16Type());
1376
1377 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1378 InitBuiltinType(R&: Char32Ty, K: BuiltinType::Char32);
1379 else // C99
1380 Char32Ty = getFromTargetType(Type: Target.getChar32Type());
1381
1382 // Placeholder type for type-dependent expressions whose type is
1383 // completely unknown. No code should ever check a type against
1384 // DependentTy and users should never see it; however, it is here to
1385 // help diagnose failures to properly check for type-dependent
1386 // expressions.
1387 InitBuiltinType(R&: DependentTy, K: BuiltinType::Dependent);
1388
1389 // Placeholder type for functions.
1390 InitBuiltinType(R&: OverloadTy, K: BuiltinType::Overload);
1391
1392 // Placeholder type for bound members.
1393 InitBuiltinType(R&: BoundMemberTy, K: BuiltinType::BoundMember);
1394
1395 // Placeholder type for unresolved templates.
1396 InitBuiltinType(R&: UnresolvedTemplateTy, K: BuiltinType::UnresolvedTemplate);
1397
1398 // Placeholder type for pseudo-objects.
1399 InitBuiltinType(R&: PseudoObjectTy, K: BuiltinType::PseudoObject);
1400
1401 // "any" type; useful for debugger-like clients.
1402 InitBuiltinType(R&: UnknownAnyTy, K: BuiltinType::UnknownAny);
1403
1404 // Placeholder type for unbridged ARC casts.
1405 InitBuiltinType(R&: ARCUnbridgedCastTy, K: BuiltinType::ARCUnbridgedCast);
1406
1407 // Placeholder type for builtin functions.
1408 InitBuiltinType(R&: BuiltinFnTy, K: BuiltinType::BuiltinFn);
1409
1410 // Placeholder type for OMP array sections.
1411 if (LangOpts.OpenMP) {
1412 InitBuiltinType(R&: ArraySectionTy, K: BuiltinType::ArraySection);
1413 InitBuiltinType(R&: OMPArrayShapingTy, K: BuiltinType::OMPArrayShaping);
1414 InitBuiltinType(R&: OMPIteratorTy, K: BuiltinType::OMPIterator);
1415 }
1416 // Placeholder type for OpenACC array sections, if we are ALSO in OMP mode,
1417 // don't bother, as we're just using the same type as OMP.
1418 if (LangOpts.OpenACC && !LangOpts.OpenMP) {
1419 InitBuiltinType(R&: ArraySectionTy, K: BuiltinType::ArraySection);
1420 }
1421 if (LangOpts.MatrixTypes)
1422 InitBuiltinType(R&: IncompleteMatrixIdxTy, K: BuiltinType::IncompleteMatrixIdx);
1423
1424 // Builtin types for 'id', 'Class', and 'SEL'.
1425 InitBuiltinType(R&: ObjCBuiltinIdTy, K: BuiltinType::ObjCId);
1426 InitBuiltinType(R&: ObjCBuiltinClassTy, K: BuiltinType::ObjCClass);
1427 InitBuiltinType(R&: ObjCBuiltinSelTy, K: BuiltinType::ObjCSel);
1428
1429 if (LangOpts.OpenCL) {
1430#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1431 InitBuiltinType(SingletonId, BuiltinType::Id);
1432#include "clang/Basic/OpenCLImageTypes.def"
1433
1434 InitBuiltinType(R&: OCLSamplerTy, K: BuiltinType::OCLSampler);
1435 InitBuiltinType(R&: OCLEventTy, K: BuiltinType::OCLEvent);
1436 InitBuiltinType(R&: OCLClkEventTy, K: BuiltinType::OCLClkEvent);
1437 InitBuiltinType(R&: OCLQueueTy, K: BuiltinType::OCLQueue);
1438 InitBuiltinType(R&: OCLReserveIDTy, K: BuiltinType::OCLReserveID);
1439
1440#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1441 InitBuiltinType(Id##Ty, BuiltinType::Id);
1442#include "clang/Basic/OpenCLExtensionTypes.def"
1443 }
1444
1445 if (LangOpts.HLSL) {
1446#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
1447 InitBuiltinType(SingletonId, BuiltinType::Id);
1448#include "clang/Basic/HLSLIntangibleTypes.def"
1449 }
1450
1451 if (Target.hasAArch64ACLETypes() ||
1452 (AuxTarget && AuxTarget->hasAArch64ACLETypes())) {
1453#define SVE_TYPE(Name, Id, SingletonId) \
1454 InitBuiltinType(SingletonId, BuiltinType::Id);
1455#include "clang/Basic/AArch64ACLETypes.def"
1456 }
1457
1458 if (Target.getTriple().isPPC64()) {
1459#define PPC_VECTOR_MMA_TYPE(Name, Id, Size) \
1460 InitBuiltinType(Id##Ty, BuiltinType::Id);
1461#include "clang/Basic/PPCTypes.def"
1462#define PPC_VECTOR_VSX_TYPE(Name, Id, Size) \
1463 InitBuiltinType(Id##Ty, BuiltinType::Id);
1464#include "clang/Basic/PPCTypes.def"
1465 }
1466
1467 if (Target.hasRISCVVTypes()) {
1468#define RVV_TYPE(Name, Id, SingletonId) \
1469 InitBuiltinType(SingletonId, BuiltinType::Id);
1470#include "clang/Basic/RISCVVTypes.def"
1471 }
1472
1473 if (Target.getTriple().isWasm() && Target.hasFeature(Feature: "reference-types")) {
1474#define WASM_TYPE(Name, Id, SingletonId) \
1475 InitBuiltinType(SingletonId, BuiltinType::Id);
1476#include "clang/Basic/WebAssemblyReferenceTypes.def"
1477 }
1478
1479 if (Target.getTriple().isAMDGPU() ||
1480 (Target.getTriple().isSPIRV() &&
1481 Target.getTriple().getVendor() == llvm::Triple::AMD) ||
1482 (AuxTarget &&
1483 (AuxTarget->getTriple().isAMDGPU() ||
1484 ((AuxTarget->getTriple().isSPIRV() &&
1485 AuxTarget->getTriple().getVendor() == llvm::Triple::AMD))))) {
1486#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) \
1487 InitBuiltinType(SingletonId, BuiltinType::Id);
1488#include "clang/Basic/AMDGPUTypes.def"
1489 }
1490
1491 // Builtin type for __objc_yes and __objc_no
1492 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1493 SignedCharTy : BoolTy);
1494
1495 ObjCConstantStringType = QualType();
1496
1497 ObjCSuperType = QualType();
1498
1499 // void * type
1500 if (LangOpts.OpenCLGenericAddressSpace) {
1501 auto Q = VoidTy.getQualifiers();
1502 Q.setAddressSpace(LangAS::opencl_generic);
1503 VoidPtrTy = getPointerType(T: getCanonicalType(
1504 T: getQualifiedType(T: VoidTy.getUnqualifiedType(), Qs: Q)));
1505 } else {
1506 VoidPtrTy = getPointerType(T: VoidTy);
1507 }
1508
1509 // nullptr type (C++0x 2.14.7)
1510 InitBuiltinType(R&: NullPtrTy, K: BuiltinType::NullPtr);
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::getDeclAttrs(const Decl *D) {
1532 AttrVec *&Result = DeclAttrs[D];
1533 if (!Result) {
1534 void *Mem = Allocate(Size: sizeof(AttrVec));
1535 Result = new (Mem) AttrVec;
1536 }
1537
1538 return *Result;
1539}
1540
1541/// Erase the attributes corresponding to the given declaration.
1542void ASTContext::eraseDeclAttrs(const Decl *D) {
1543 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(Val: D);
1544 if (Pos != DeclAttrs.end()) {
1545 Pos->second->~AttrVec();
1546 DeclAttrs.erase(I: Pos);
1547 }
1548}
1549
1550ArrayRef<ExplicitInstantiationDecl *>
1551ASTContext::getExplicitInstantiationDecls(const NamedDecl *Spec) const {
1552 auto It =
1553 ExplicitInstantiations.find(Val: cast<NamedDecl>(Val: Spec->getCanonicalDecl()));
1554 if (It != ExplicitInstantiations.end())
1555 return It->second;
1556 return {};
1557}
1558
1559void ASTContext::addExplicitInstantiationDecl(const NamedDecl *Spec,
1560 ExplicitInstantiationDecl *EID) {
1561 ExplicitInstantiations[cast<NamedDecl>(Val: Spec->getCanonicalDecl())].push_back(
1562 NewVal: EID);
1563}
1564
1565// FIXME: Remove ?
1566MemberSpecializationInfo *
1567ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
1568 assert(Var->isStaticDataMember() && "Not a static data member");
1569 return getTemplateOrSpecializationInfo(Var)
1570 .dyn_cast<MemberSpecializationInfo *>();
1571}
1572
1573ASTContext::TemplateOrSpecializationInfo
1574ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1575 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1576 TemplateOrInstantiation.find(Val: Var);
1577 if (Pos == TemplateOrInstantiation.end())
1578 return {};
1579
1580 return Pos->second;
1581}
1582
1583void
1584ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
1585 TemplateSpecializationKind TSK,
1586 SourceLocation PointOfInstantiation) {
1587 assert(Inst->isStaticDataMember() && "Not a static data member");
1588 assert(Tmpl->isStaticDataMember() && "Not a static data member");
1589 setTemplateOrSpecializationInfo(Inst, TSI: new (*this) MemberSpecializationInfo(
1590 Tmpl, TSK, PointOfInstantiation));
1591}
1592
1593void
1594ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1595 TemplateOrSpecializationInfo TSI) {
1596 assert(!TemplateOrInstantiation[Inst] &&
1597 "Already noted what the variable was instantiated from");
1598 TemplateOrInstantiation[Inst] = TSI;
1599}
1600
1601NamedDecl *
1602ASTContext::getInstantiatedFromUsingDecl(NamedDecl *UUD) {
1603 return InstantiatedFromUsingDecl.lookup(Val: UUD);
1604}
1605
1606void
1607ASTContext::setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern) {
1608 assert((isa<UsingDecl>(Pattern) ||
1609 isa<UnresolvedUsingValueDecl>(Pattern) ||
1610 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1611 "pattern decl is not a using decl");
1612 assert((isa<UsingDecl>(Inst) ||
1613 isa<UnresolvedUsingValueDecl>(Inst) ||
1614 isa<UnresolvedUsingTypenameDecl>(Inst)) &&
1615 "instantiation did not produce a using decl");
1616 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1617 InstantiatedFromUsingDecl[Inst] = Pattern;
1618}
1619
1620UsingEnumDecl *
1621ASTContext::getInstantiatedFromUsingEnumDecl(UsingEnumDecl *UUD) {
1622 return InstantiatedFromUsingEnumDecl.lookup(Val: UUD);
1623}
1624
1625void ASTContext::setInstantiatedFromUsingEnumDecl(UsingEnumDecl *Inst,
1626 UsingEnumDecl *Pattern) {
1627 assert(!InstantiatedFromUsingEnumDecl[Inst] && "pattern already exists");
1628 InstantiatedFromUsingEnumDecl[Inst] = Pattern;
1629}
1630
1631UsingShadowDecl *
1632ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1633 return InstantiatedFromUsingShadowDecl.lookup(Val: Inst);
1634}
1635
1636void
1637ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1638 UsingShadowDecl *Pattern) {
1639 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1640 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
1641}
1642
1643FieldDecl *
1644ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) const {
1645 return InstantiatedFromUnnamedFieldDecl.lookup(Val: Field);
1646}
1647
1648void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1649 FieldDecl *Tmpl) {
1650 assert((!Inst->getDeclName() || Inst->isPlaceholderVar(getLangOpts())) &&
1651 "Instantiated field decl is not unnamed");
1652 assert((!Inst->getDeclName() || Inst->isPlaceholderVar(getLangOpts())) &&
1653 "Template field decl is not unnamed");
1654 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1655 "Already noted what unnamed field was instantiated from");
1656
1657 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1658}
1659
1660ASTContext::overridden_cxx_method_iterator
1661ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1662 return overridden_methods(Method).begin();
1663}
1664
1665ASTContext::overridden_cxx_method_iterator
1666ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1667 return overridden_methods(Method).end();
1668}
1669
1670unsigned
1671ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1672 auto Range = overridden_methods(Method);
1673 return Range.end() - Range.begin();
1674}
1675
1676ASTContext::overridden_method_range
1677ASTContext::overridden_methods(const CXXMethodDecl *Method) const {
1678 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1679 OverriddenMethods.find(Val: Method->getCanonicalDecl());
1680 if (Pos == OverriddenMethods.end())
1681 return overridden_method_range(nullptr, nullptr);
1682 return overridden_method_range(Pos->second.begin(), Pos->second.end());
1683}
1684
1685void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1686 const CXXMethodDecl *Overridden) {
1687 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
1688 OverriddenMethods[Method].push_back(NewVal: Overridden);
1689}
1690
1691void ASTContext::getOverriddenMethods(
1692 const NamedDecl *D,
1693 SmallVectorImpl<const NamedDecl *> &Overridden) const {
1694 assert(D);
1695
1696 if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(Val: D)) {
1697 Overridden.append(in_start: overridden_methods_begin(Method: CXXMethod),
1698 in_end: overridden_methods_end(Method: CXXMethod));
1699 return;
1700 }
1701
1702 const auto *Method = dyn_cast<ObjCMethodDecl>(Val: D);
1703 if (!Method)
1704 return;
1705
1706 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1707 Method->getOverriddenMethods(Overridden&: OverDecls);
1708 Overridden.append(in_start: OverDecls.begin(), in_end: OverDecls.end());
1709}
1710
1711std::optional<ASTContext::CXXRecordDeclRelocationInfo>
1712ASTContext::getRelocationInfoForCXXRecord(const CXXRecordDecl *RD) const {
1713 assert(RD);
1714 CXXRecordDecl *D = RD->getDefinition();
1715 auto it = RelocatableClasses.find(Val: D);
1716 if (it != RelocatableClasses.end())
1717 return it->getSecond();
1718 return std::nullopt;
1719}
1720
1721void ASTContext::setRelocationInfoForCXXRecord(
1722 const CXXRecordDecl *RD, CXXRecordDeclRelocationInfo Info) {
1723 assert(RD);
1724 CXXRecordDecl *D = RD->getDefinition();
1725 assert(RelocatableClasses.find(D) == RelocatableClasses.end());
1726 RelocatableClasses.insert(KV: {D, Info});
1727}
1728
1729static bool primaryBaseHaseAddressDiscriminatedVTableAuthentication(
1730 const ASTContext &Context, const CXXRecordDecl *Class) {
1731 if (!Class->isPolymorphic())
1732 return false;
1733 const CXXRecordDecl *BaseType = Context.baseForVTableAuthentication(ThisClass: Class);
1734 using AuthAttr = VTablePointerAuthenticationAttr;
1735 const AuthAttr *ExplicitAuth = BaseType->getAttr<AuthAttr>();
1736 if (!ExplicitAuth)
1737 return Context.getLangOpts().PointerAuthVTPtrAddressDiscrimination;
1738 AuthAttr::AddressDiscriminationMode AddressDiscrimination =
1739 ExplicitAuth->getAddressDiscrimination();
1740 if (AddressDiscrimination == AuthAttr::DefaultAddressDiscrimination)
1741 return Context.getLangOpts().PointerAuthVTPtrAddressDiscrimination;
1742 return AddressDiscrimination == AuthAttr::AddressDiscrimination;
1743}
1744
1745ASTContext::PointerAuthContent
1746ASTContext::findPointerAuthContent(QualType T) const {
1747 assert(isPointerAuthenticationAvailable());
1748
1749 T = T.getCanonicalType();
1750 if (T->isDependentType())
1751 return PointerAuthContent::None;
1752
1753 if (T.hasAddressDiscriminatedPointerAuth())
1754 return PointerAuthContent::AddressDiscriminatedData;
1755 const RecordDecl *RD = T->getAsRecordDecl();
1756 if (!RD)
1757 return PointerAuthContent::None;
1758
1759 if (RD->isInvalidDecl())
1760 return PointerAuthContent::None;
1761
1762 if (auto Existing = RecordContainsAddressDiscriminatedPointerAuth.find(Val: RD);
1763 Existing != RecordContainsAddressDiscriminatedPointerAuth.end())
1764 return Existing->second;
1765
1766 PointerAuthContent Result = PointerAuthContent::None;
1767
1768 auto SaveResultAndReturn = [&]() -> PointerAuthContent {
1769 auto [ResultIter, DidAdd] =
1770 RecordContainsAddressDiscriminatedPointerAuth.try_emplace(Key: RD, Args&: Result);
1771 (void)ResultIter;
1772 (void)DidAdd;
1773 assert(DidAdd);
1774 return Result;
1775 };
1776 auto ShouldContinueAfterUpdate = [&](PointerAuthContent NewResult) {
1777 static_assert(PointerAuthContent::None <
1778 PointerAuthContent::AddressDiscriminatedVTable);
1779 static_assert(PointerAuthContent::AddressDiscriminatedVTable <
1780 PointerAuthContent::AddressDiscriminatedData);
1781 if (NewResult > Result)
1782 Result = NewResult;
1783 return Result != PointerAuthContent::AddressDiscriminatedData;
1784 };
1785 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(Val: RD)) {
1786 if (primaryBaseHaseAddressDiscriminatedVTableAuthentication(Context: *this, Class: CXXRD) &&
1787 !ShouldContinueAfterUpdate(
1788 PointerAuthContent::AddressDiscriminatedVTable))
1789 return SaveResultAndReturn();
1790 for (auto Base : CXXRD->bases()) {
1791 if (!ShouldContinueAfterUpdate(findPointerAuthContent(T: Base.getType())))
1792 return SaveResultAndReturn();
1793 }
1794 }
1795 for (auto *FieldDecl : RD->fields()) {
1796 if (!ShouldContinueAfterUpdate(
1797 findPointerAuthContent(T: FieldDecl->getType())))
1798 return SaveResultAndReturn();
1799 }
1800 return SaveResultAndReturn();
1801}
1802
1803void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1804 assert(!Import->getNextLocalImport() &&
1805 "Import declaration already in the chain");
1806 assert(!Import->isFromASTFile() && "Non-local import declaration");
1807 if (!FirstLocalImport) {
1808 FirstLocalImport = Import;
1809 LastLocalImport = Import;
1810 return;
1811 }
1812
1813 LastLocalImport->setNextLocalImport(Import);
1814 LastLocalImport = Import;
1815}
1816
1817//===----------------------------------------------------------------------===//
1818// Type Sizing and Analysis
1819//===----------------------------------------------------------------------===//
1820
1821/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1822/// scalar floating point type.
1823const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
1824 switch (T->castAs<BuiltinType>()->getKind()) {
1825 default:
1826 llvm_unreachable("Not a floating point type!");
1827 case BuiltinType::BFloat16:
1828 return Target->getBFloat16Format();
1829 case BuiltinType::Float16:
1830 return Target->getHalfFormat();
1831 case BuiltinType::Half:
1832 return Target->getHalfFormat();
1833 case BuiltinType::Float: return Target->getFloatFormat();
1834 case BuiltinType::Double: return Target->getDoubleFormat();
1835 case BuiltinType::Ibm128:
1836 return Target->getIbm128Format();
1837 case BuiltinType::LongDouble:
1838 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice)
1839 return AuxTarget->getLongDoubleFormat();
1840 return Target->getLongDoubleFormat();
1841 case BuiltinType::Float128:
1842 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice)
1843 return AuxTarget->getFloat128Format();
1844 return Target->getFloat128Format();
1845 }
1846}
1847
1848CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
1849 unsigned Align = Target->getCharWidth();
1850
1851 const unsigned AlignFromAttr = D->getMaxAlignment();
1852 if (AlignFromAttr)
1853 Align = AlignFromAttr;
1854
1855 // __attribute__((aligned)) can increase or decrease alignment
1856 // *except* on a struct or struct member, where it only increases
1857 // alignment unless 'packed' is also specified.
1858 //
1859 // It is an error for alignas to decrease alignment, so we can
1860 // ignore that possibility; Sema should diagnose it.
1861 bool UseAlignAttrOnly;
1862 if (const FieldDecl *FD = dyn_cast<FieldDecl>(Val: D))
1863 UseAlignAttrOnly =
1864 FD->hasAttr<PackedAttr>() || FD->getParent()->hasAttr<PackedAttr>();
1865 else
1866 UseAlignAttrOnly = AlignFromAttr != 0;
1867 // If we're using the align attribute only, just ignore everything
1868 // else about the declaration and its type.
1869 if (UseAlignAttrOnly) {
1870 // do nothing
1871 } else if (const auto *VD = dyn_cast<ValueDecl>(Val: D)) {
1872 QualType T = VD->getType();
1873 if (const auto *RT = T->getAs<ReferenceType>()) {
1874 if (ForAlignof)
1875 T = RT->getPointeeType();
1876 else
1877 T = getPointerType(T: RT->getPointeeType());
1878 }
1879 QualType BaseT = getBaseElementType(QT: T);
1880 if (T->isFunctionType())
1881 Align = getTypeInfoImpl(T: T.getTypePtr()).Align;
1882 else if (!BaseT->isIncompleteType()) {
1883 // Adjust alignments of declarations with array type by the
1884 // large-array alignment on the target.
1885 if (const ArrayType *arrayType = getAsArrayType(T)) {
1886 unsigned MinWidth = Target->getLargeArrayMinWidth();
1887 if (!ForAlignof && MinWidth) {
1888 if (isa<VariableArrayType>(Val: arrayType))
1889 Align = std::max(a: Align, b: Target->getLargeArrayAlign());
1890 else if (isa<ConstantArrayType>(Val: arrayType) &&
1891 MinWidth <= getTypeSize(T: cast<ConstantArrayType>(Val: arrayType)))
1892 Align = std::max(a: Align, b: Target->getLargeArrayAlign());
1893 }
1894 }
1895 Align = std::max(a: Align, b: getPreferredTypeAlign(T: T.getTypePtr()));
1896 if (BaseT.getQualifiers().hasUnaligned())
1897 Align = Target->getCharWidth();
1898 }
1899
1900 // Ensure minimum alignment for global variables.
1901 if (const auto *VD = dyn_cast<VarDecl>(Val: D))
1902 if (VD->hasGlobalStorage() && !ForAlignof) {
1903 uint64_t TypeSize =
1904 !BaseT->isIncompleteType() ? getTypeSize(T: T.getTypePtr()) : 0;
1905 Align = std::max(a: Align, b: getMinGlobalAlignOfVar(Size: TypeSize, VD));
1906 }
1907
1908 // Fields can be subject to extra alignment constraints, like if
1909 // the field is packed, the struct is packed, or the struct has a
1910 // a max-field-alignment constraint (#pragma pack). So calculate
1911 // the actual alignment of the field within the struct, and then
1912 // (as we're expected to) constrain that by the alignment of the type.
1913 if (const auto *Field = dyn_cast<FieldDecl>(Val: VD)) {
1914 const RecordDecl *Parent = Field->getParent();
1915 // We can only produce a sensible answer if the record is valid.
1916 if (!Parent->isInvalidDecl()) {
1917 const ASTRecordLayout &Layout = getASTRecordLayout(D: Parent);
1918
1919 // Start with the record's overall alignment.
1920 unsigned FieldAlign = toBits(CharSize: Layout.getAlignment());
1921
1922 // Use the GCD of that and the offset within the record.
1923 uint64_t Offset = Layout.getFieldOffset(FieldNo: Field->getFieldIndex());
1924 if (Offset > 0) {
1925 // Alignment is always a power of 2, so the GCD will be a power of 2,
1926 // which means we get to do this crazy thing instead of Euclid's.
1927 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1928 if (LowBitOfOffset < FieldAlign)
1929 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1930 }
1931
1932 Align = std::min(a: Align, b: FieldAlign);
1933 }
1934 }
1935 }
1936
1937 // Some targets have hard limitation on the maximum requestable alignment in
1938 // aligned attribute for static variables.
1939 const unsigned MaxAlignedAttr = getTargetInfo().getMaxAlignedAttribute();
1940 const auto *VD = dyn_cast<VarDecl>(Val: D);
1941 if (MaxAlignedAttr && VD && VD->getStorageClass() == SC_Static)
1942 Align = std::min(a: Align, b: MaxAlignedAttr);
1943
1944 return toCharUnitsFromBits(BitSize: Align);
1945}
1946
1947CharUnits ASTContext::getExnObjectAlignment() const {
1948 return toCharUnitsFromBits(BitSize: Target->getExnObjectAlignment());
1949}
1950
1951// getTypeInfoDataSizeInChars - Return the size of a type, in
1952// chars. If the type is a record, its data size is returned. This is
1953// the size of the memcpy that's performed when assigning this type
1954// using a trivial copy/move assignment operator.
1955TypeInfoChars ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1956 TypeInfoChars Info = getTypeInfoInChars(T);
1957
1958 // In C++, objects can sometimes be allocated into the tail padding
1959 // of a base-class subobject. We decide whether that's possible
1960 // during class layout, so here we can just trust the layout results.
1961 if (getLangOpts().CPlusPlus) {
1962 if (const auto *RD = T->getAsCXXRecordDecl(); RD && !RD->isInvalidDecl()) {
1963 const ASTRecordLayout &layout = getASTRecordLayout(D: RD);
1964 Info.Width = layout.getDataSize();
1965 }
1966 }
1967
1968 return Info;
1969}
1970
1971/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1972/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1973TypeInfoChars
1974static getConstantArrayInfoInChars(const ASTContext &Context,
1975 const ConstantArrayType *CAT) {
1976 TypeInfoChars EltInfo = Context.getTypeInfoInChars(T: CAT->getElementType());
1977 uint64_t Size = CAT->getZExtSize();
1978 assert((Size == 0 || static_cast<uint64_t>(EltInfo.Width.getQuantity()) <=
1979 (uint64_t)(-1)/Size) &&
1980 "Overflow in array type char size evaluation");
1981 uint64_t Width = EltInfo.Width.getQuantity() * Size;
1982 unsigned Align = EltInfo.Align.getQuantity();
1983 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1984 Context.getTargetInfo().getPointerWidth(AddrSpace: LangAS::Default) == 64)
1985 Width = llvm::alignTo(Value: Width, Align);
1986 return TypeInfoChars(CharUnits::fromQuantity(Quantity: Width),
1987 CharUnits::fromQuantity(Quantity: Align),
1988 EltInfo.AlignRequirement);
1989}
1990
1991TypeInfoChars ASTContext::getTypeInfoInChars(const Type *T) const {
1992 if (const auto *CAT = dyn_cast<ConstantArrayType>(Val: T))
1993 return getConstantArrayInfoInChars(Context: *this, CAT);
1994 TypeInfo Info = getTypeInfo(T);
1995 return TypeInfoChars(toCharUnitsFromBits(BitSize: Info.Width),
1996 toCharUnitsFromBits(BitSize: Info.Align), Info.AlignRequirement);
1997}
1998
1999TypeInfoChars ASTContext::getTypeInfoInChars(QualType T) const {
2000 return getTypeInfoInChars(T: T.getTypePtr());
2001}
2002
2003bool ASTContext::isPromotableIntegerType(QualType T) const {
2004 // HLSL doesn't promote all small integer types to int, it
2005 // just uses the rank-based promotion rules for all types.
2006 if (getLangOpts().HLSL)
2007 return false;
2008
2009 if (const auto *BT = T->getAs<BuiltinType>())
2010 switch (BT->getKind()) {
2011 case BuiltinType::Bool:
2012 case BuiltinType::Char_S:
2013 case BuiltinType::Char_U:
2014 case BuiltinType::SChar:
2015 case BuiltinType::UChar:
2016 case BuiltinType::Short:
2017 case BuiltinType::UShort:
2018 case BuiltinType::WChar_S:
2019 case BuiltinType::WChar_U:
2020 case BuiltinType::Char8:
2021 case BuiltinType::Char16:
2022 case BuiltinType::Char32:
2023 return true;
2024 default:
2025 return false;
2026 }
2027
2028 // Enumerated types are promotable to their compatible integer types
2029 // (C99 6.3.1.1) a.k.a. its underlying type (C++ [conv.prom]p2).
2030 if (const auto *ED = T->getAsEnumDecl()) {
2031 if (T->isDependentType() || ED->getPromotionType().isNull() ||
2032 ED->isScoped())
2033 return false;
2034
2035 return true;
2036 }
2037
2038 // OverflowBehaviorTypes are promotable if their underlying type is promotable
2039 if (const auto *OBT = T->getAs<OverflowBehaviorType>()) {
2040 return isPromotableIntegerType(T: OBT->getUnderlyingType());
2041 }
2042
2043 return false;
2044}
2045
2046bool ASTContext::isAlignmentRequired(const Type *T) const {
2047 return getTypeInfo(T).AlignRequirement != AlignRequirementKind::None;
2048}
2049
2050bool ASTContext::isAlignmentRequired(QualType T) const {
2051 return isAlignmentRequired(T: T.getTypePtr());
2052}
2053
2054unsigned ASTContext::getTypeAlignIfKnown(QualType T,
2055 bool NeedsPreferredAlignment) const {
2056 // An alignment on a typedef overrides anything else.
2057 if (const auto *TT = T->getAs<TypedefType>())
2058 if (unsigned Align = TT->getDecl()->getMaxAlignment())
2059 return Align;
2060
2061 // If we have an (array of) complete type, we're done.
2062 T = getBaseElementType(QT: T);
2063 if (!T->isIncompleteType())
2064 return NeedsPreferredAlignment ? getPreferredTypeAlign(T) : getTypeAlign(T);
2065
2066 // If we had an array type, its element type might be a typedef
2067 // type with an alignment attribute.
2068 if (const auto *TT = T->getAs<TypedefType>())
2069 if (unsigned Align = TT->getDecl()->getMaxAlignment())
2070 return Align;
2071
2072 // Otherwise, see if the declaration of the type had an attribute.
2073 if (const auto *TD = T->getAsTagDecl())
2074 return TD->getMaxAlignment();
2075
2076 return 0;
2077}
2078
2079TypeInfo ASTContext::getTypeInfo(const Type *T) const {
2080 TypeInfoMap::iterator I = MemoizedTypeInfo.find(Val: T);
2081 if (I != MemoizedTypeInfo.end())
2082 return I->second;
2083
2084 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
2085 TypeInfo TI = getTypeInfoImpl(T);
2086 MemoizedTypeInfo[T] = TI;
2087 return TI;
2088}
2089
2090/// getTypeInfoImpl - Return the size of the specified type, in bits. This
2091/// method does not work on incomplete types.
2092///
2093/// FIXME: Pointers into different addr spaces could have different sizes and
2094/// alignment requirements: getPointerInfo should take an AddrSpace, this
2095/// should take a QualType, &c.
2096TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
2097 uint64_t Width = 0;
2098 unsigned Align = 8;
2099 AlignRequirementKind AlignRequirement = AlignRequirementKind::None;
2100 LangAS AS = LangAS::Default;
2101 switch (T->getTypeClass()) {
2102#define TYPE(Class, Base)
2103#define ABSTRACT_TYPE(Class, Base)
2104#define NON_CANONICAL_TYPE(Class, Base)
2105#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2106#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
2107 case Type::Class: \
2108 assert(!T->isDependentType() && "should not see dependent types here"); \
2109 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
2110#include "clang/AST/TypeNodes.inc"
2111 llvm_unreachable("Should not see dependent types");
2112
2113 case Type::FunctionNoProto:
2114 case Type::FunctionProto:
2115 // GCC extension: alignof(function) = 32 bits
2116 Width = 0;
2117 Align = 32;
2118 break;
2119
2120 case Type::IncompleteArray:
2121 case Type::VariableArray:
2122 case Type::ConstantArray:
2123 case Type::ArrayParameter: {
2124 // Model non-constant sized arrays as size zero, but track the alignment.
2125 uint64_t Size = 0;
2126 if (const auto *CAT = dyn_cast<ConstantArrayType>(Val: T))
2127 Size = CAT->getZExtSize();
2128
2129 TypeInfo EltInfo = getTypeInfo(T: cast<ArrayType>(Val: T)->getElementType());
2130 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
2131 "Overflow in array type bit size evaluation");
2132 Width = EltInfo.Width * Size;
2133 Align = EltInfo.Align;
2134 AlignRequirement = EltInfo.AlignRequirement;
2135 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
2136 getTargetInfo().getPointerWidth(AddrSpace: LangAS::Default) == 64)
2137 Width = llvm::alignTo(Value: Width, Align);
2138 break;
2139 }
2140
2141 case Type::ExtVector:
2142 case Type::Vector: {
2143 const auto *VT = cast<VectorType>(Val: T);
2144 TypeInfo EltInfo = getTypeInfo(T: VT->getElementType());
2145 Width = VT->isPackedVectorBoolType(ctx: *this)
2146 ? VT->getNumElements()
2147 : EltInfo.Width * VT->getNumElements();
2148 // Enforce at least byte size and alignment.
2149 Width = std::max<unsigned>(a: 8, b: Width);
2150 Align = std::max<unsigned>(
2151 a: 8, b: Target->vectorsAreElementAligned() ? EltInfo.Width : Width);
2152
2153 // If the alignment is not a power of 2, round up to the next power of 2.
2154 // This happens for non-power-of-2 length vectors.
2155 if (Align & (Align-1)) {
2156 Align = llvm::bit_ceil(Value: Align);
2157 Width = llvm::alignTo(Value: Width, Align);
2158 }
2159 // Adjust the alignment based on the target max.
2160 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
2161 if (TargetVectorAlign && TargetVectorAlign < Align)
2162 Align = TargetVectorAlign;
2163 if (VT->getVectorKind() == VectorKind::SveFixedLengthData)
2164 // Adjust the alignment for fixed-length SVE vectors. This is important
2165 // for non-power-of-2 vector lengths.
2166 Align = 128;
2167 else if (VT->getVectorKind() == VectorKind::SveFixedLengthPredicate)
2168 // Adjust the alignment for fixed-length SVE predicates.
2169 Align = 16;
2170 else if (VT->getVectorKind() == VectorKind::RVVFixedLengthData ||
2171 VT->getVectorKind() == VectorKind::RVVFixedLengthMask ||
2172 VT->getVectorKind() == VectorKind::RVVFixedLengthMask_1 ||
2173 VT->getVectorKind() == VectorKind::RVVFixedLengthMask_2 ||
2174 VT->getVectorKind() == VectorKind::RVVFixedLengthMask_4)
2175 // Adjust the alignment for fixed-length RVV vectors.
2176 Align = std::min<unsigned>(a: 64, b: Width);
2177 break;
2178 }
2179
2180 case Type::ConstantMatrix: {
2181 const auto *MT = cast<ConstantMatrixType>(Val: T);
2182 TypeInfo ElementInfo = getTypeInfo(T: MT->getElementType());
2183 // The internal layout of a matrix value is implementation defined.
2184 // Initially be ABI compatible with arrays with respect to alignment and
2185 // size.
2186 Width = ElementInfo.Width * MT->getNumRows() * MT->getNumColumns();
2187 Align = ElementInfo.Align;
2188 break;
2189 }
2190
2191 case Type::Builtin:
2192 switch (cast<BuiltinType>(Val: T)->getKind()) {
2193 default: llvm_unreachable("Unknown builtin type!");
2194 case BuiltinType::Void:
2195 // GCC extension: alignof(void) = 8 bits.
2196 Width = 0;
2197 Align = 8;
2198 break;
2199 case BuiltinType::Bool:
2200 Width = Target->getBoolWidth();
2201 Align = Target->getBoolAlign();
2202 break;
2203 case BuiltinType::Char_S:
2204 case BuiltinType::Char_U:
2205 case BuiltinType::UChar:
2206 case BuiltinType::SChar:
2207 case BuiltinType::Char8:
2208 Width = Target->getCharWidth();
2209 Align = Target->getCharAlign();
2210 break;
2211 case BuiltinType::WChar_S:
2212 case BuiltinType::WChar_U:
2213 Width = Target->getWCharWidth();
2214 Align = Target->getWCharAlign();
2215 break;
2216 case BuiltinType::Char16:
2217 Width = Target->getChar16Width();
2218 Align = Target->getChar16Align();
2219 break;
2220 case BuiltinType::Char32:
2221 Width = Target->getChar32Width();
2222 Align = Target->getChar32Align();
2223 break;
2224 case BuiltinType::UShort:
2225 case BuiltinType::Short:
2226 Width = Target->getShortWidth();
2227 Align = Target->getShortAlign();
2228 break;
2229 case BuiltinType::UInt:
2230 case BuiltinType::Int:
2231 Width = Target->getIntWidth();
2232 Align = Target->getIntAlign();
2233 break;
2234 case BuiltinType::ULong:
2235 case BuiltinType::Long:
2236 Width = Target->getLongWidth();
2237 Align = Target->getLongAlign();
2238 break;
2239 case BuiltinType::ULongLong:
2240 case BuiltinType::LongLong:
2241 Width = Target->getLongLongWidth();
2242 Align = Target->getLongLongAlign();
2243 break;
2244 case BuiltinType::Int128:
2245 case BuiltinType::UInt128:
2246 Width = 128;
2247 Align = Target->getInt128Align();
2248 break;
2249 case BuiltinType::ShortAccum:
2250 case BuiltinType::UShortAccum:
2251 case BuiltinType::SatShortAccum:
2252 case BuiltinType::SatUShortAccum:
2253 Width = Target->getShortAccumWidth();
2254 Align = Target->getShortAccumAlign();
2255 break;
2256 case BuiltinType::Accum:
2257 case BuiltinType::UAccum:
2258 case BuiltinType::SatAccum:
2259 case BuiltinType::SatUAccum:
2260 Width = Target->getAccumWidth();
2261 Align = Target->getAccumAlign();
2262 break;
2263 case BuiltinType::LongAccum:
2264 case BuiltinType::ULongAccum:
2265 case BuiltinType::SatLongAccum:
2266 case BuiltinType::SatULongAccum:
2267 Width = Target->getLongAccumWidth();
2268 Align = Target->getLongAccumAlign();
2269 break;
2270 case BuiltinType::ShortFract:
2271 case BuiltinType::UShortFract:
2272 case BuiltinType::SatShortFract:
2273 case BuiltinType::SatUShortFract:
2274 Width = Target->getShortFractWidth();
2275 Align = Target->getShortFractAlign();
2276 break;
2277 case BuiltinType::Fract:
2278 case BuiltinType::UFract:
2279 case BuiltinType::SatFract:
2280 case BuiltinType::SatUFract:
2281 Width = Target->getFractWidth();
2282 Align = Target->getFractAlign();
2283 break;
2284 case BuiltinType::LongFract:
2285 case BuiltinType::ULongFract:
2286 case BuiltinType::SatLongFract:
2287 case BuiltinType::SatULongFract:
2288 Width = Target->getLongFractWidth();
2289 Align = Target->getLongFractAlign();
2290 break;
2291 case BuiltinType::BFloat16:
2292 if (Target->hasBFloat16Type()) {
2293 Width = Target->getBFloat16Width();
2294 Align = Target->getBFloat16Align();
2295 } else if ((getLangOpts().SYCLIsDevice ||
2296 (getLangOpts().OpenMP &&
2297 getLangOpts().OpenMPIsTargetDevice)) &&
2298 AuxTarget->hasBFloat16Type()) {
2299 Width = AuxTarget->getBFloat16Width();
2300 Align = AuxTarget->getBFloat16Align();
2301 }
2302 break;
2303 case BuiltinType::Float16:
2304 case BuiltinType::Half:
2305 if (Target->hasFloat16Type() || !getLangOpts().OpenMP ||
2306 !getLangOpts().OpenMPIsTargetDevice) {
2307 Width = Target->getHalfWidth();
2308 Align = Target->getHalfAlign();
2309 } else {
2310 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2311 "Expected OpenMP device compilation.");
2312 Width = AuxTarget->getHalfWidth();
2313 Align = AuxTarget->getHalfAlign();
2314 }
2315 break;
2316 case BuiltinType::Float:
2317 Width = Target->getFloatWidth();
2318 Align = Target->getFloatAlign();
2319 break;
2320 case BuiltinType::Double:
2321 Width = Target->getDoubleWidth();
2322 Align = Target->getDoubleAlign();
2323 break;
2324 case BuiltinType::Ibm128:
2325 Width = Target->getIbm128Width();
2326 Align = Target->getIbm128Align();
2327 break;
2328 case BuiltinType::LongDouble:
2329 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2330 (Target->getLongDoubleWidth() != AuxTarget->getLongDoubleWidth() ||
2331 Target->getLongDoubleAlign() != AuxTarget->getLongDoubleAlign())) {
2332 Width = AuxTarget->getLongDoubleWidth();
2333 Align = AuxTarget->getLongDoubleAlign();
2334 } else {
2335 Width = Target->getLongDoubleWidth();
2336 Align = Target->getLongDoubleAlign();
2337 }
2338 break;
2339 case BuiltinType::Float128:
2340 if (Target->hasFloat128Type() || !getLangOpts().OpenMP ||
2341 !getLangOpts().OpenMPIsTargetDevice) {
2342 Width = Target->getFloat128Width();
2343 Align = Target->getFloat128Align();
2344 } else {
2345 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2346 "Expected OpenMP device compilation.");
2347 Width = AuxTarget->getFloat128Width();
2348 Align = AuxTarget->getFloat128Align();
2349 }
2350 break;
2351 case BuiltinType::NullPtr:
2352 // C++ 3.9.1p11: sizeof(nullptr_t) == sizeof(void*)
2353 Width = Target->getPointerWidth(AddrSpace: LangAS::Default);
2354 Align = Target->getPointerAlign(AddrSpace: LangAS::Default);
2355 break;
2356 case BuiltinType::ObjCId:
2357 case BuiltinType::ObjCClass:
2358 case BuiltinType::ObjCSel:
2359 Width = Target->getPointerWidth(AddrSpace: LangAS::Default);
2360 Align = Target->getPointerAlign(AddrSpace: LangAS::Default);
2361 break;
2362 case BuiltinType::OCLSampler:
2363 case BuiltinType::OCLEvent:
2364 case BuiltinType::OCLClkEvent:
2365 case BuiltinType::OCLQueue:
2366 case BuiltinType::OCLReserveID:
2367#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2368 case BuiltinType::Id:
2369#include "clang/Basic/OpenCLImageTypes.def"
2370#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2371 case BuiltinType::Id:
2372#include "clang/Basic/OpenCLExtensionTypes.def"
2373 AS = Target->getOpenCLTypeAddrSpace(TK: getOpenCLTypeKind(T));
2374 Width = Target->getPointerWidth(AddrSpace: AS);
2375 Align = Target->getPointerAlign(AddrSpace: AS);
2376 break;
2377 // The SVE types are effectively target-specific. The length of an
2378 // SVE_VECTOR_TYPE is only known at runtime, but it is always a multiple
2379 // of 128 bits. There is one predicate bit for each vector byte, so the
2380 // length of an SVE_PREDICATE_TYPE is always a multiple of 16 bits.
2381 //
2382 // Because the length is only known at runtime, we use a dummy value
2383 // of 0 for the static length. The alignment values are those defined
2384 // by the Procedure Call Standard for the Arm Architecture.
2385#define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId) \
2386 case BuiltinType::Id: \
2387 Width = 0; \
2388 Align = 128; \
2389 break;
2390#define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId) \
2391 case BuiltinType::Id: \
2392 Width = 0; \
2393 Align = 16; \
2394 break;
2395#define SVE_OPAQUE_TYPE(Name, MangledName, Id, SingletonId) \
2396 case BuiltinType::Id: \
2397 Width = 0; \
2398 Align = 16; \
2399 break;
2400#define SVE_SCALAR_TYPE(Name, MangledName, Id, SingletonId, Bits) \
2401 case BuiltinType::Id: \
2402 Width = Bits; \
2403 Align = Bits; \
2404 break;
2405#include "clang/Basic/AArch64ACLETypes.def"
2406#define PPC_VECTOR_TYPE(Name, Id, Size) \
2407 case BuiltinType::Id: \
2408 Width = Size; \
2409 Align = Size; \
2410 break;
2411#include "clang/Basic/PPCTypes.def"
2412#define RVV_VECTOR_TYPE(Name, Id, SingletonId, ElKind, ElBits, NF, IsSigned, \
2413 IsFP, IsBF) \
2414 case BuiltinType::Id: \
2415 Width = 0; \
2416 Align = ElBits; \
2417 break;
2418#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, ElKind) \
2419 case BuiltinType::Id: \
2420 Width = 0; \
2421 Align = 8; \
2422 break;
2423#include "clang/Basic/RISCVVTypes.def"
2424#define WASM_TYPE(Name, Id, SingletonId) \
2425 case BuiltinType::Id: \
2426 Width = 0; \
2427 Align = 8; \
2428 break;
2429#include "clang/Basic/WebAssemblyReferenceTypes.def"
2430#define AMDGPU_TYPE(NAME, ID, SINGLETONID, WIDTH, ALIGN) \
2431 case BuiltinType::ID: \
2432 Width = WIDTH; \
2433 Align = ALIGN; \
2434 break;
2435#include "clang/Basic/AMDGPUTypes.def"
2436#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
2437#include "clang/Basic/HLSLIntangibleTypes.def"
2438 Width = Target->getPointerWidth(AddrSpace: LangAS::Default);
2439 Align = Target->getPointerAlign(AddrSpace: LangAS::Default);
2440 break;
2441 }
2442 break;
2443 case Type::ObjCObjectPointer:
2444 Width = Target->getPointerWidth(AddrSpace: LangAS::Default);
2445 Align = Target->getPointerAlign(AddrSpace: LangAS::Default);
2446 break;
2447 case Type::BlockPointer:
2448 AS = cast<BlockPointerType>(Val: T)->getPointeeType().getAddressSpace();
2449 Width = Target->getPointerWidth(AddrSpace: AS);
2450 Align = Target->getPointerAlign(AddrSpace: AS);
2451 break;
2452 case Type::LValueReference:
2453 case Type::RValueReference:
2454 // alignof and sizeof should never enter this code path here, so we go
2455 // the pointer route.
2456 AS = cast<ReferenceType>(Val: T)->getPointeeType().getAddressSpace();
2457 Width = Target->getPointerWidth(AddrSpace: AS);
2458 Align = Target->getPointerAlign(AddrSpace: AS);
2459 break;
2460 case Type::Pointer:
2461 AS = cast<PointerType>(Val: T)->getPointeeType().getAddressSpace();
2462 Width = Target->getPointerWidth(AddrSpace: AS);
2463 Align = Target->getPointerAlign(AddrSpace: AS);
2464 break;
2465 case Type::MemberPointer: {
2466 const auto *MPT = cast<MemberPointerType>(Val: T);
2467 CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT);
2468 Width = MPI.Width;
2469 Align = MPI.Align;
2470 break;
2471 }
2472 case Type::Complex: {
2473 // Complex types have the same alignment as their elements, but twice the
2474 // size.
2475 TypeInfo EltInfo = getTypeInfo(T: cast<ComplexType>(Val: T)->getElementType());
2476 Width = EltInfo.Width * 2;
2477 Align = EltInfo.Align;
2478 break;
2479 }
2480 case Type::ObjCObject:
2481 return getTypeInfo(T: cast<ObjCObjectType>(Val: T)->getBaseType().getTypePtr());
2482 case Type::Adjusted:
2483 case Type::Decayed:
2484 return getTypeInfo(T: cast<AdjustedType>(Val: T)->getAdjustedType().getTypePtr());
2485 case Type::ObjCInterface: {
2486 const auto *ObjCI = cast<ObjCInterfaceType>(Val: T);
2487 if (ObjCI->getDecl()->isInvalidDecl()) {
2488 Width = 8;
2489 Align = 8;
2490 break;
2491 }
2492 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(D: ObjCI->getDecl());
2493 Width = toBits(CharSize: Layout.getSize());
2494 Align = toBits(CharSize: Layout.getAlignment());
2495 break;
2496 }
2497 case Type::BitInt: {
2498 const auto *EIT = cast<BitIntType>(Val: T);
2499 Align = Target->getBitIntAlign(NumBits: EIT->getNumBits());
2500 Width = Target->getBitIntWidth(NumBits: EIT->getNumBits());
2501 break;
2502 }
2503 case Type::Record:
2504 case Type::Enum: {
2505 const auto *TT = cast<TagType>(Val: T);
2506 const TagDecl *TD = TT->getDecl()->getDefinitionOrSelf();
2507
2508 if (TD->isInvalidDecl()) {
2509 Width = 8;
2510 Align = 8;
2511 break;
2512 }
2513
2514 if (isa<EnumType>(Val: TT)) {
2515 const EnumDecl *ED = cast<EnumDecl>(Val: TD);
2516 TypeInfo Info =
2517 getTypeInfo(T: ED->getIntegerType()->getUnqualifiedDesugaredType());
2518 if (unsigned AttrAlign = ED->getMaxAlignment()) {
2519 Info.Align = AttrAlign;
2520 Info.AlignRequirement = AlignRequirementKind::RequiredByEnum;
2521 }
2522 return Info;
2523 }
2524
2525 const auto *RD = cast<RecordDecl>(Val: TD);
2526 const ASTRecordLayout &Layout = getASTRecordLayout(D: RD);
2527 Width = toBits(CharSize: Layout.getSize());
2528 Align = toBits(CharSize: Layout.getAlignment());
2529 AlignRequirement = RD->hasAttr<AlignedAttr>()
2530 ? AlignRequirementKind::RequiredByRecord
2531 : AlignRequirementKind::None;
2532 break;
2533 }
2534
2535 case Type::SubstTemplateTypeParm:
2536 return getTypeInfo(T: cast<SubstTemplateTypeParmType>(Val: T)->
2537 getReplacementType().getTypePtr());
2538
2539 case Type::Auto:
2540 case Type::DeducedTemplateSpecialization: {
2541 const auto *A = cast<DeducedType>(Val: T);
2542 assert(!A->getDeducedType().isNull() &&
2543 "cannot request the size of an undeduced or dependent auto type");
2544 return getTypeInfo(T: A->getDeducedType().getTypePtr());
2545 }
2546
2547 case Type::Paren:
2548 return getTypeInfo(T: cast<ParenType>(Val: T)->getInnerType().getTypePtr());
2549
2550 case Type::MacroQualified:
2551 return getTypeInfo(
2552 T: cast<MacroQualifiedType>(Val: T)->getUnderlyingType().getTypePtr());
2553
2554 case Type::ObjCTypeParam:
2555 return getTypeInfo(T: cast<ObjCTypeParamType>(Val: T)->desugar().getTypePtr());
2556
2557 case Type::Using:
2558 return getTypeInfo(T: cast<UsingType>(Val: T)->desugar().getTypePtr());
2559
2560 case Type::Typedef: {
2561 const auto *TT = cast<TypedefType>(Val: T);
2562 TypeInfo Info = getTypeInfo(T: TT->desugar().getTypePtr());
2563 // If the typedef has an aligned attribute on it, it overrides any computed
2564 // alignment we have. This violates the GCC documentation (which says that
2565 // attribute(aligned) can only round up) but matches its implementation.
2566 if (unsigned AttrAlign = TT->getDecl()->getMaxAlignment()) {
2567 Align = AttrAlign;
2568 AlignRequirement = AlignRequirementKind::RequiredByTypedef;
2569 } else {
2570 Align = Info.Align;
2571 AlignRequirement = Info.AlignRequirement;
2572 }
2573 Width = Info.Width;
2574 break;
2575 }
2576
2577 case Type::Attributed:
2578 return getTypeInfo(
2579 T: cast<AttributedType>(Val: T)->getEquivalentType().getTypePtr());
2580
2581 case Type::CountAttributed:
2582 return getTypeInfo(T: cast<CountAttributedType>(Val: T)->desugar().getTypePtr());
2583
2584 case Type::BTFTagAttributed:
2585 return getTypeInfo(
2586 T: cast<BTFTagAttributedType>(Val: T)->getWrappedType().getTypePtr());
2587
2588 case Type::OverflowBehavior:
2589 return getTypeInfo(
2590 T: cast<OverflowBehaviorType>(Val: T)->getUnderlyingType().getTypePtr());
2591
2592 case Type::HLSLAttributedResource:
2593 return getTypeInfo(
2594 T: cast<HLSLAttributedResourceType>(Val: T)->getWrappedType().getTypePtr());
2595
2596 case Type::HLSLInlineSpirv: {
2597 const auto *ST = cast<HLSLInlineSpirvType>(Val: T);
2598 // Size is specified in bytes, convert to bits
2599 Width = ST->getSize() * 8;
2600 Align = ST->getAlignment();
2601 if (Width == 0 && Align == 0) {
2602 // We are defaulting to laying out opaque SPIR-V types as 32-bit ints.
2603 Width = 32;
2604 Align = 32;
2605 }
2606 break;
2607 }
2608
2609 case Type::Atomic: {
2610 // Start with the base type information.
2611 TypeInfo Info = getTypeInfo(T: cast<AtomicType>(Val: T)->getValueType());
2612 Width = Info.Width;
2613 Align = Info.Align;
2614
2615 if (!Width) {
2616 // An otherwise zero-sized type should still generate an
2617 // atomic operation.
2618 Width = Target->getCharWidth();
2619 assert(Align);
2620 } else if (Width <= Target->getMaxAtomicPromoteWidth()) {
2621 // If the size of the type doesn't exceed the platform's max
2622 // atomic promotion width, make the size and alignment more
2623 // favorable to atomic operations:
2624
2625 // Round the size up to a power of 2.
2626 Width = llvm::bit_ceil(Value: Width);
2627
2628 // Set the alignment equal to the size.
2629 Align = static_cast<unsigned>(Width);
2630 }
2631 }
2632 break;
2633
2634 case Type::PredefinedSugar:
2635 return getTypeInfo(T: cast<PredefinedSugarType>(Val: T)->desugar().getTypePtr());
2636
2637 case Type::Pipe:
2638 Width = Target->getPointerWidth(AddrSpace: LangAS::opencl_global);
2639 Align = Target->getPointerAlign(AddrSpace: LangAS::opencl_global);
2640 break;
2641 }
2642
2643 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
2644 return TypeInfo(Width, Align, AlignRequirement);
2645}
2646
2647unsigned ASTContext::getTypeUnadjustedAlign(const Type *T) const {
2648 UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(Val: T);
2649 if (I != MemoizedUnadjustedAlign.end())
2650 return I->second;
2651
2652 unsigned UnadjustedAlign;
2653 if (const auto *RT = T->getAsCanonical<RecordType>()) {
2654 const ASTRecordLayout &Layout = getASTRecordLayout(D: RT->getDecl());
2655 UnadjustedAlign = toBits(CharSize: Layout.getUnadjustedAlignment());
2656 } else if (const auto *ObjCI = T->getAsCanonical<ObjCInterfaceType>()) {
2657 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(D: ObjCI->getDecl());
2658 UnadjustedAlign = toBits(CharSize: Layout.getUnadjustedAlignment());
2659 } else {
2660 UnadjustedAlign = getTypeAlign(T: T->getUnqualifiedDesugaredType());
2661 }
2662
2663 MemoizedUnadjustedAlign[T] = UnadjustedAlign;
2664 return UnadjustedAlign;
2665}
2666
2667unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
2668 unsigned SimdAlign = llvm::OpenMPIRBuilder::getOpenMPDefaultSimdAlign(
2669 TargetTriple: getTargetInfo().getTriple(), Features: Target->getTargetOpts().FeatureMap);
2670 return SimdAlign;
2671}
2672
2673/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
2674CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
2675 return CharUnits::fromQuantity(Quantity: BitSize / getCharWidth());
2676}
2677
2678/// toBits - Convert a size in characters to a size in characters.
2679int64_t ASTContext::toBits(CharUnits CharSize) const {
2680 return CharSize.getQuantity() * getCharWidth();
2681}
2682
2683/// getTypeSizeInChars - Return the size of the specified type, in characters.
2684/// This method does not work on incomplete types.
2685CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
2686 return getTypeInfoInChars(T).Width;
2687}
2688CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
2689 return getTypeInfoInChars(T).Width;
2690}
2691
2692/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
2693/// characters. This method does not work on incomplete types.
2694CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
2695 return toCharUnitsFromBits(BitSize: getTypeAlign(T));
2696}
2697CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
2698 return toCharUnitsFromBits(BitSize: getTypeAlign(T));
2699}
2700
2701/// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a
2702/// type, in characters, before alignment adjustments. This method does
2703/// not work on incomplete types.
2704CharUnits ASTContext::getTypeUnadjustedAlignInChars(QualType T) const {
2705 return toCharUnitsFromBits(BitSize: getTypeUnadjustedAlign(T));
2706}
2707CharUnits ASTContext::getTypeUnadjustedAlignInChars(const Type *T) const {
2708 return toCharUnitsFromBits(BitSize: getTypeUnadjustedAlign(T));
2709}
2710
2711/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
2712/// type for the current target in bits. This can be different than the ABI
2713/// alignment in cases where it is beneficial for performance or backwards
2714/// compatibility preserving to overalign a data type. (Note: despite the name,
2715/// the preferred alignment is ABI-impacting, and not an optimization.)
2716unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
2717 TypeInfo TI = getTypeInfo(T);
2718 unsigned ABIAlign = TI.Align;
2719
2720 T = T->getBaseElementTypeUnsafe();
2721
2722 // The preferred alignment of member pointers is that of a pointer.
2723 if (T->isMemberPointerType())
2724 return getPreferredTypeAlign(T: getPointerDiffType().getTypePtr());
2725
2726 if (!Target->allowsLargerPreferedTypeAlignment())
2727 return ABIAlign;
2728
2729 if (const auto *RD = T->getAsRecordDecl()) {
2730 // When used as part of a typedef, or together with a 'packed' attribute,
2731 // the 'aligned' attribute can be used to decrease alignment. Note that the
2732 // 'packed' case is already taken into consideration when computing the
2733 // alignment, we only need to handle the typedef case here.
2734 if (TI.AlignRequirement == AlignRequirementKind::RequiredByTypedef ||
2735 RD->isInvalidDecl())
2736 return ABIAlign;
2737
2738 unsigned PreferredAlign = static_cast<unsigned>(
2739 toBits(CharSize: getASTRecordLayout(D: RD).PreferredAlignment));
2740 assert(PreferredAlign >= ABIAlign &&
2741 "PreferredAlign should be at least as large as ABIAlign.");
2742 return PreferredAlign;
2743 }
2744
2745 // Double (and, for targets supporting AIX `power` alignment, long double) and
2746 // long long should be naturally aligned (despite requiring less alignment) if
2747 // possible.
2748 if (const auto *CT = T->getAs<ComplexType>())
2749 T = CT->getElementType().getTypePtr();
2750 if (const auto *ED = T->getAsEnumDecl())
2751 T = ED->getIntegerType().getTypePtr();
2752 if (T->isSpecificBuiltinType(K: BuiltinType::Double) ||
2753 T->isSpecificBuiltinType(K: BuiltinType::LongLong) ||
2754 T->isSpecificBuiltinType(K: BuiltinType::ULongLong) ||
2755 (T->isSpecificBuiltinType(K: BuiltinType::LongDouble) &&
2756 Target->defaultsToAIXPowerAlignment()))
2757 // Don't increase the alignment if an alignment attribute was specified on a
2758 // typedef declaration.
2759 if (!TI.isAlignRequired())
2760 return std::max(a: ABIAlign, b: (unsigned)getTypeSize(T));
2761
2762 return ABIAlign;
2763}
2764
2765/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2766/// for __attribute__((aligned)) on this target, to be used if no alignment
2767/// value is specified.
2768unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const {
2769 return getTargetInfo().getDefaultAlignForAttributeAligned();
2770}
2771
2772/// getAlignOfGlobalVar - Return the alignment in bits that should be given
2773/// to a global variable of the specified type.
2774unsigned ASTContext::getAlignOfGlobalVar(QualType T, const VarDecl *VD) const {
2775 uint64_t TypeSize = getTypeSize(T: T.getTypePtr());
2776 return std::max(a: getPreferredTypeAlign(T),
2777 b: getMinGlobalAlignOfVar(Size: TypeSize, VD));
2778}
2779
2780/// getAlignOfGlobalVarInChars - Return the alignment in characters that
2781/// should be given to a global variable of the specified type.
2782CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T,
2783 const VarDecl *VD) const {
2784 return toCharUnitsFromBits(BitSize: getAlignOfGlobalVar(T, VD));
2785}
2786
2787unsigned ASTContext::getMinGlobalAlignOfVar(uint64_t Size,
2788 const VarDecl *VD) const {
2789 // Make the default handling as that of a non-weak definition in the
2790 // current translation unit.
2791 bool HasNonWeakDef = !VD || (VD->hasDefinition() && !VD->isWeak());
2792 return getTargetInfo().getMinGlobalAlign(Size, HasNonWeakDef);
2793}
2794
2795CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
2796 CharUnits Offset = CharUnits::Zero();
2797 const ASTRecordLayout *Layout = &getASTRecordLayout(D: RD);
2798 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2799 Offset += Layout->getBaseClassOffset(Base);
2800 Layout = &getASTRecordLayout(D: Base);
2801 }
2802 return Offset;
2803}
2804
2805CharUnits ASTContext::getMemberPointerPathAdjustment(const APValue &MP) const {
2806 const ValueDecl *MPD = MP.getMemberPointerDecl();
2807 CharUnits ThisAdjustment = CharUnits::Zero();
2808 ArrayRef<const CXXRecordDecl*> Path = MP.getMemberPointerPath();
2809 bool DerivedMember = MP.isMemberPointerToDerivedMember();
2810 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Val: MPD->getDeclContext());
2811 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
2812 const CXXRecordDecl *Base = RD;
2813 const CXXRecordDecl *Derived = Path[I];
2814 if (DerivedMember)
2815 std::swap(a&: Base, b&: Derived);
2816 ThisAdjustment += getASTRecordLayout(D: Derived).getBaseClassOffset(Base);
2817 RD = Path[I];
2818 }
2819 if (DerivedMember)
2820 ThisAdjustment = -ThisAdjustment;
2821 return ThisAdjustment;
2822}
2823
2824/// DeepCollectObjCIvars -
2825/// This routine first collects all declared, but not synthesized, ivars in
2826/// super class and then collects all ivars, including those synthesized for
2827/// current class. This routine is used for implementation of current class
2828/// when all ivars, declared and synthesized are known.
2829void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
2830 bool leafClass,
2831 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
2832 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2833 DeepCollectObjCIvars(OI: SuperClass, leafClass: false, Ivars);
2834 if (!leafClass) {
2835 llvm::append_range(C&: Ivars, R: OI->ivars());
2836 } else {
2837 auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
2838 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
2839 Iv= Iv->getNextIvar())
2840 Ivars.push_back(Elt: Iv);
2841 }
2842}
2843
2844/// CollectInheritedProtocols - Collect all protocols in current class and
2845/// those inherited by it.
2846void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
2847 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
2848 if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(Val: CDecl)) {
2849 // We can use protocol_iterator here instead of
2850 // all_referenced_protocol_iterator since we are walking all categories.
2851 for (auto *Proto : OI->all_referenced_protocols()) {
2852 CollectInheritedProtocols(CDecl: Proto, Protocols);
2853 }
2854
2855 // Categories of this Interface.
2856 for (const auto *Cat : OI->visible_categories())
2857 CollectInheritedProtocols(CDecl: Cat, Protocols);
2858
2859 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2860 while (SD) {
2861 CollectInheritedProtocols(CDecl: SD, Protocols);
2862 SD = SD->getSuperClass();
2863 }
2864 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(Val: CDecl)) {
2865 for (auto *Proto : OC->protocols()) {
2866 CollectInheritedProtocols(CDecl: Proto, Protocols);
2867 }
2868 } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(Val: CDecl)) {
2869 // Insert the protocol.
2870 if (!Protocols.insert(
2871 Ptr: const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2872 return;
2873
2874 for (auto *Proto : OP->protocols())
2875 CollectInheritedProtocols(CDecl: Proto, Protocols);
2876 }
2877}
2878
2879static bool unionHasUniqueObjectRepresentations(const ASTContext &Context,
2880 const RecordDecl *RD,
2881 bool CheckIfTriviallyCopyable) {
2882 assert(RD->isUnion() && "Must be union type");
2883 CharUnits UnionSize =
2884 Context.getTypeSizeInChars(T: Context.getCanonicalTagType(TD: RD));
2885
2886 for (const auto *Field : RD->fields()) {
2887 if (!Context.hasUniqueObjectRepresentations(Ty: Field->getType(),
2888 CheckIfTriviallyCopyable))
2889 return false;
2890 CharUnits FieldSize = Context.getTypeSizeInChars(T: Field->getType());
2891 if (FieldSize != UnionSize)
2892 return false;
2893 }
2894 return !RD->field_empty();
2895}
2896
2897static int64_t getSubobjectOffset(const FieldDecl *Field,
2898 const ASTContext &Context,
2899 const clang::ASTRecordLayout & /*Layout*/) {
2900 return Context.getFieldOffset(FD: Field);
2901}
2902
2903static int64_t getSubobjectOffset(const CXXRecordDecl *RD,
2904 const ASTContext &Context,
2905 const clang::ASTRecordLayout &Layout) {
2906 return Context.toBits(CharSize: Layout.getBaseClassOffset(Base: RD));
2907}
2908
2909static std::optional<int64_t>
2910structHasUniqueObjectRepresentations(const ASTContext &Context,
2911 const RecordDecl *RD,
2912 bool CheckIfTriviallyCopyable);
2913
2914static std::optional<int64_t>
2915getSubobjectSizeInBits(const FieldDecl *Field, const ASTContext &Context,
2916 bool CheckIfTriviallyCopyable) {
2917 if (const auto *RD = Field->getType()->getAsRecordDecl();
2918 RD && !RD->isUnion())
2919 return structHasUniqueObjectRepresentations(Context, RD,
2920 CheckIfTriviallyCopyable);
2921
2922 // A _BitInt type may not be unique if it has padding bits
2923 // but if it is a bitfield the padding bits are not used.
2924 bool IsBitIntType = Field->getType()->isBitIntType();
2925 if (!Field->getType()->isReferenceType() && !IsBitIntType &&
2926 !Context.hasUniqueObjectRepresentations(Ty: Field->getType(),
2927 CheckIfTriviallyCopyable))
2928 return std::nullopt;
2929
2930 int64_t FieldSizeInBits =
2931 Context.toBits(CharSize: Context.getTypeSizeInChars(T: Field->getType()));
2932 if (Field->isBitField()) {
2933 // If we have explicit padding bits, they don't contribute bits
2934 // to the actual object representation, so return 0.
2935 if (Field->isUnnamedBitField())
2936 return 0;
2937
2938 int64_t BitfieldSize = Field->getBitWidthValue();
2939 if (IsBitIntType) {
2940 if ((unsigned)BitfieldSize >
2941 cast<BitIntType>(Val: Field->getType())->getNumBits())
2942 return std::nullopt;
2943 } else if (BitfieldSize > FieldSizeInBits) {
2944 return std::nullopt;
2945 }
2946 FieldSizeInBits = BitfieldSize;
2947 } else if (IsBitIntType && !Context.hasUniqueObjectRepresentations(
2948 Ty: Field->getType(), CheckIfTriviallyCopyable)) {
2949 return std::nullopt;
2950 }
2951 return FieldSizeInBits;
2952}
2953
2954static std::optional<int64_t>
2955getSubobjectSizeInBits(const CXXRecordDecl *RD, const ASTContext &Context,
2956 bool CheckIfTriviallyCopyable) {
2957 return structHasUniqueObjectRepresentations(Context, RD,
2958 CheckIfTriviallyCopyable);
2959}
2960
2961template <typename RangeT>
2962static std::optional<int64_t> structSubobjectsHaveUniqueObjectRepresentations(
2963 const RangeT &Subobjects, int64_t CurOffsetInBits,
2964 const ASTContext &Context, const clang::ASTRecordLayout &Layout,
2965 bool CheckIfTriviallyCopyable) {
2966 for (const auto *Subobject : Subobjects) {
2967 std::optional<int64_t> SizeInBits =
2968 getSubobjectSizeInBits(Subobject, Context, CheckIfTriviallyCopyable);
2969 if (!SizeInBits)
2970 return std::nullopt;
2971 if (*SizeInBits != 0) {
2972 int64_t Offset = getSubobjectOffset(Subobject, Context, Layout);
2973 if (Offset != CurOffsetInBits)
2974 return std::nullopt;
2975 CurOffsetInBits += *SizeInBits;
2976 }
2977 }
2978 return CurOffsetInBits;
2979}
2980
2981static std::optional<int64_t>
2982structHasUniqueObjectRepresentations(const ASTContext &Context,
2983 const RecordDecl *RD,
2984 bool CheckIfTriviallyCopyable) {
2985 assert(!RD->isUnion() && "Must be struct/class type");
2986 const auto &Layout = Context.getASTRecordLayout(D: RD);
2987
2988 int64_t CurOffsetInBits = 0;
2989 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(Val: RD)) {
2990 if (ClassDecl->isDynamicClass())
2991 return std::nullopt;
2992
2993 SmallVector<CXXRecordDecl *, 4> Bases;
2994 for (const auto &Base : ClassDecl->bases()) {
2995 // Empty types can be inherited from, and non-empty types can potentially
2996 // have tail padding, so just make sure there isn't an error.
2997 Bases.emplace_back(Args: Base.getType()->getAsCXXRecordDecl());
2998 }
2999
3000 llvm::sort(C&: Bases, Comp: [&](const CXXRecordDecl *L, const CXXRecordDecl *R) {
3001 return Layout.getBaseClassOffset(Base: L) < Layout.getBaseClassOffset(Base: R);
3002 });
3003
3004 std::optional<int64_t> OffsetAfterBases =
3005 structSubobjectsHaveUniqueObjectRepresentations(
3006 Subobjects: Bases, CurOffsetInBits, Context, Layout, CheckIfTriviallyCopyable);
3007 if (!OffsetAfterBases)
3008 return std::nullopt;
3009 CurOffsetInBits = *OffsetAfterBases;
3010 }
3011
3012 std::optional<int64_t> OffsetAfterFields =
3013 structSubobjectsHaveUniqueObjectRepresentations(
3014 Subobjects: RD->fields(), CurOffsetInBits, Context, Layout,
3015 CheckIfTriviallyCopyable);
3016 if (!OffsetAfterFields)
3017 return std::nullopt;
3018 CurOffsetInBits = *OffsetAfterFields;
3019
3020 return CurOffsetInBits;
3021}
3022
3023bool ASTContext::hasUniqueObjectRepresentations(
3024 QualType Ty, bool CheckIfTriviallyCopyable) const {
3025 // C++17 [meta.unary.prop]:
3026 // The predicate condition for a template specialization
3027 // has_unique_object_representations<T> shall be satisfied if and only if:
3028 // (9.1) - T is trivially copyable, and
3029 // (9.2) - any two objects of type T with the same value have the same
3030 // object representation, where:
3031 // - two objects of array or non-union class type are considered to have
3032 // the same value if their respective sequences of direct subobjects
3033 // have the same values, and
3034 // - two objects of union type are considered to have the same value if
3035 // they have the same active member and the corresponding members have
3036 // the same value.
3037 // The set of scalar types for which this condition holds is
3038 // implementation-defined. [ Note: If a type has padding bits, the condition
3039 // does not hold; otherwise, the condition holds true for unsigned integral
3040 // types. -- end note ]
3041 assert(!Ty.isNull() && "Null QualType sent to unique object rep check");
3042
3043 // Arrays are unique only if their element type is unique.
3044 if (Ty->isArrayType())
3045 return hasUniqueObjectRepresentations(Ty: getBaseElementType(QT: Ty),
3046 CheckIfTriviallyCopyable);
3047
3048 assert((Ty->isVoidType() || !Ty->isIncompleteType()) &&
3049 "hasUniqueObjectRepresentations should not be called with an "
3050 "incomplete type");
3051
3052 // (9.1) - T is trivially copyable...
3053 if (CheckIfTriviallyCopyable && !Ty.isTriviallyCopyableType(Context: *this))
3054 return false;
3055
3056 // All integrals and enums are unique.
3057 if (Ty->isIntegralOrEnumerationType()) {
3058 // Address discriminated integer types are not unique.
3059 if (Ty.hasAddressDiscriminatedPointerAuth())
3060 return false;
3061 // Except _BitInt types that have padding bits.
3062 if (const auto *BIT = Ty->getAs<BitIntType>())
3063 return getTypeSize(T: BIT) == BIT->getNumBits();
3064
3065 return true;
3066 }
3067
3068 // All other pointers are unique.
3069 if (Ty->isPointerType())
3070 return !Ty.hasAddressDiscriminatedPointerAuth();
3071
3072 if (const auto *MPT = Ty->getAs<MemberPointerType>())
3073 return !ABI->getMemberPointerInfo(MPT).HasPadding;
3074
3075 if (const auto *Record = Ty->getAsRecordDecl()) {
3076 if (Record->isInvalidDecl())
3077 return false;
3078
3079 if (Record->isUnion())
3080 return unionHasUniqueObjectRepresentations(Context: *this, RD: Record,
3081 CheckIfTriviallyCopyable);
3082
3083 std::optional<int64_t> StructSize = structHasUniqueObjectRepresentations(
3084 Context: *this, RD: Record, CheckIfTriviallyCopyable);
3085
3086 return StructSize && *StructSize == static_cast<int64_t>(getTypeSize(T: Ty));
3087 }
3088
3089 // FIXME: More cases to handle here (list by rsmith):
3090 // vectors (careful about, eg, vector of 3 foo)
3091 // _Complex int and friends
3092 // _Atomic T
3093 // Obj-C block pointers
3094 // Obj-C object pointers
3095 // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t,
3096 // clk_event_t, queue_t, reserve_id_t)
3097 // There're also Obj-C class types and the Obj-C selector type, but I think it
3098 // makes sense for those to return false here.
3099
3100 return false;
3101}
3102
3103unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
3104 unsigned count = 0;
3105 // Count ivars declared in class extension.
3106 for (const auto *Ext : OI->known_extensions())
3107 count += Ext->ivar_size();
3108
3109 // Count ivar defined in this class's implementation. This
3110 // includes synthesized ivars.
3111 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
3112 count += ImplDecl->ivar_size();
3113
3114 return count;
3115}
3116
3117bool ASTContext::isSentinelNullExpr(const Expr *E) {
3118 if (!E)
3119 return false;
3120
3121 // nullptr_t is always treated as null.
3122 if (E->getType()->isNullPtrType()) return true;
3123
3124 if (E->getType()->isAnyPointerType() &&
3125 E->IgnoreParenCasts()->isNullPointerConstant(Ctx&: *this,
3126 NPC: Expr::NPC_ValueDependentIsNull))
3127 return true;
3128
3129 // Unfortunately, __null has type 'int'.
3130 if (isa<GNUNullExpr>(Val: E)) return true;
3131
3132 return false;
3133}
3134
3135/// Get the implementation of ObjCInterfaceDecl, or nullptr if none
3136/// exists.
3137ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
3138 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
3139 I = ObjCImpls.find(Val: D);
3140 if (I != ObjCImpls.end())
3141 return cast<ObjCImplementationDecl>(Val: I->second);
3142 return nullptr;
3143}
3144
3145/// Get the implementation of ObjCCategoryDecl, or nullptr if none
3146/// exists.
3147ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
3148 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
3149 I = ObjCImpls.find(Val: D);
3150 if (I != ObjCImpls.end())
3151 return cast<ObjCCategoryImplDecl>(Val: I->second);
3152 return nullptr;
3153}
3154
3155/// Set the implementation of ObjCInterfaceDecl.
3156void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
3157 ObjCImplementationDecl *ImplD) {
3158 assert(IFaceD && ImplD && "Passed null params");
3159 ObjCImpls[IFaceD] = ImplD;
3160}
3161
3162/// Set the implementation of ObjCCategoryDecl.
3163void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
3164 ObjCCategoryImplDecl *ImplD) {
3165 assert(CatD && ImplD && "Passed null params");
3166 ObjCImpls[CatD] = ImplD;
3167}
3168
3169const ObjCMethodDecl *
3170ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const {
3171 return ObjCMethodRedecls.lookup(Val: MD);
3172}
3173
3174void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
3175 const ObjCMethodDecl *Redecl) {
3176 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
3177 ObjCMethodRedecls[MD] = Redecl;
3178}
3179
3180const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
3181 const NamedDecl *ND) const {
3182 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(Val: ND->getDeclContext()))
3183 return ID;
3184 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(Val: ND->getDeclContext()))
3185 return CD->getClassInterface();
3186 if (const auto *IMD = dyn_cast<ObjCImplDecl>(Val: ND->getDeclContext()))
3187 return IMD->getClassInterface();
3188
3189 return nullptr;
3190}
3191
3192/// Get the copy initialization expression of VarDecl, or nullptr if
3193/// none exists.
3194BlockVarCopyInit ASTContext::getBlockVarCopyInit(const VarDecl *VD) const {
3195 assert(VD && "Passed null params");
3196 assert(VD->hasAttr<BlocksAttr>() &&
3197 "getBlockVarCopyInits - not __block var");
3198 auto I = BlockVarCopyInits.find(Val: VD);
3199 if (I != BlockVarCopyInits.end())
3200 return I->second;
3201 return {nullptr, false};
3202}
3203
3204/// Set the copy initialization expression of a block var decl.
3205void ASTContext::setBlockVarCopyInit(const VarDecl*VD, Expr *CopyExpr,
3206 bool CanThrow) {
3207 assert(VD && CopyExpr && "Passed null params");
3208 assert(VD->hasAttr<BlocksAttr>() &&
3209 "setBlockVarCopyInits - not __block var");
3210 BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow);
3211}
3212
3213TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
3214 unsigned DataSize) const {
3215 if (!DataSize)
3216 DataSize = TypeLoc::getFullDataSizeForType(Ty: T);
3217 else
3218 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
3219 "incorrect data size provided to CreateTypeSourceInfo!");
3220
3221 auto *TInfo =
3222 (TypeSourceInfo*)BumpAlloc.Allocate(Size: sizeof(TypeSourceInfo) + DataSize, Alignment: 8);
3223 new (TInfo) TypeSourceInfo(T, DataSize);
3224 return TInfo;
3225}
3226
3227TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
3228 SourceLocation L) const {
3229 TypeSourceInfo *TSI = CreateTypeSourceInfo(T);
3230 TSI->getTypeLoc().initialize(Context&: const_cast<ASTContext &>(*this), Loc: L);
3231 return TSI;
3232}
3233
3234const ASTRecordLayout &
3235ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
3236 return getObjCLayout(D);
3237}
3238
3239static auto getCanonicalTemplateArguments(const ASTContext &C,
3240 ArrayRef<TemplateArgument> Args,
3241 bool &AnyNonCanonArgs) {
3242 SmallVector<TemplateArgument, 16> CanonArgs(Args);
3243 AnyNonCanonArgs |= C.canonicalizeTemplateArguments(Args: CanonArgs);
3244 return CanonArgs;
3245}
3246
3247bool ASTContext::canonicalizeTemplateArguments(
3248 MutableArrayRef<TemplateArgument> Args) const {
3249 bool AnyNonCanonArgs = false;
3250 for (auto &Arg : Args) {
3251 TemplateArgument OrigArg = Arg;
3252 Arg = getCanonicalTemplateArgument(Arg);
3253 AnyNonCanonArgs |= !Arg.structurallyEquals(Other: OrigArg);
3254 }
3255 return AnyNonCanonArgs;
3256}
3257
3258//===----------------------------------------------------------------------===//
3259// Type creation/memoization methods
3260//===----------------------------------------------------------------------===//
3261
3262QualType
3263ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
3264 unsigned fastQuals = quals.getFastQualifiers();
3265 quals.removeFastQualifiers();
3266
3267 // Check if we've already instantiated this type.
3268 llvm::FoldingSetNodeID ID;
3269 ExtQuals::Profile(ID, BaseType: baseType, Quals: quals);
3270 void *insertPos = nullptr;
3271 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, InsertPos&: insertPos)) {
3272 assert(eq->getQualifiers() == quals);
3273 return QualType(eq, fastQuals);
3274 }
3275
3276 // If the base type is not canonical, make the appropriate canonical type.
3277 QualType canon;
3278 if (!baseType->isCanonicalUnqualified()) {
3279 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
3280 canonSplit.Quals.addConsistentQualifiers(qs: quals);
3281 canon = getExtQualType(baseType: canonSplit.Ty, quals: canonSplit.Quals);
3282
3283 // Re-find the insert position.
3284 (void) ExtQualNodes.FindNodeOrInsertPos(ID, InsertPos&: insertPos);
3285 }
3286
3287 auto *eq = new (*this, alignof(ExtQuals)) ExtQuals(baseType, canon, quals);
3288 ExtQualNodes.InsertNode(N: eq, InsertPos: insertPos);
3289 return QualType(eq, fastQuals);
3290}
3291
3292QualType ASTContext::getAddrSpaceQualType(QualType T,
3293 LangAS AddressSpace) const {
3294 QualType CanT = getCanonicalType(T);
3295 if (CanT.getAddressSpace() == AddressSpace)
3296 return T;
3297
3298 // If we are composing extended qualifiers together, merge together
3299 // into one ExtQuals node.
3300 QualifierCollector Quals;
3301 const Type *TypeNode = Quals.strip(type: T);
3302
3303 // If this type already has an address space specified, it cannot get
3304 // another one.
3305 assert(!Quals.hasAddressSpace() &&
3306 "Type cannot be in multiple addr spaces!");
3307 Quals.addAddressSpace(space: AddressSpace);
3308
3309 return getExtQualType(baseType: TypeNode, quals: Quals);
3310}
3311
3312QualType ASTContext::removeAddrSpaceQualType(QualType T) const {
3313 // If the type is not qualified with an address space, just return it
3314 // immediately.
3315 if (!T.hasAddressSpace())
3316 return T;
3317
3318 QualifierCollector Quals;
3319 const Type *TypeNode;
3320 // For arrays, strip the qualifier off the element type, then reconstruct the
3321 // array type
3322 if (T.getTypePtr()->isArrayType()) {
3323 T = getUnqualifiedArrayType(T, Quals);
3324 TypeNode = T.getTypePtr();
3325 } else {
3326 // If we are composing extended qualifiers together, merge together
3327 // into one ExtQuals node.
3328 while (T.hasAddressSpace()) {
3329 TypeNode = Quals.strip(type: T);
3330
3331 // If the type no longer has an address space after stripping qualifiers,
3332 // jump out.
3333 if (!QualType(TypeNode, 0).hasAddressSpace())
3334 break;
3335
3336 // There might be sugar in the way. Strip it and try again.
3337 T = T.getSingleStepDesugaredType(Context: *this);
3338 }
3339 }
3340
3341 Quals.removeAddressSpace();
3342
3343 // Removal of the address space can mean there are no longer any
3344 // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts)
3345 // or required.
3346 if (Quals.hasNonFastQualifiers())
3347 return getExtQualType(baseType: TypeNode, quals: Quals);
3348 else
3349 return QualType(TypeNode, Quals.getFastQualifiers());
3350}
3351
3352uint16_t
3353ASTContext::getPointerAuthVTablePointerDiscriminator(const CXXRecordDecl *RD) {
3354 assert(RD->isPolymorphic() &&
3355 "Attempted to get vtable pointer discriminator on a monomorphic type");
3356 std::unique_ptr<MangleContext> MC(createMangleContext());
3357 SmallString<256> Str;
3358 llvm::raw_svector_ostream Out(Str);
3359 MC->mangleCXXVTable(RD, Out);
3360 return llvm::getPointerAuthStableSipHash(S: Str);
3361}
3362
3363/// Encode a function type for use in the discriminator of a function pointer
3364/// type. We can't use the itanium scheme for this since C has quite permissive
3365/// rules for type compatibility that we need to be compatible with.
3366///
3367/// Formally, this function associates every function pointer type T with an
3368/// encoded string E(T). Let the equivalence relation T1 ~ T2 be defined as
3369/// E(T1) == E(T2). E(T) is part of the ABI of values of type T. C type
3370/// compatibility requires equivalent treatment under the ABI, so
3371/// CCompatible(T1, T2) must imply E(T1) == E(T2), that is, CCompatible must be
3372/// a subset of ~. Crucially, however, it must be a proper subset because
3373/// CCompatible is not an equivalence relation: for example, int[] is compatible
3374/// with both int[1] and int[2], but the latter are not compatible with each
3375/// other. Therefore this encoding function must be careful to only distinguish
3376/// types if there is no third type with which they are both required to be
3377/// compatible.
3378static void encodeTypeForFunctionPointerAuth(const ASTContext &Ctx,
3379 raw_ostream &OS, QualType QT) {
3380 // FIXME: Consider address space qualifiers.
3381 const Type *T = QT.getCanonicalType().getTypePtr();
3382
3383 // FIXME: Consider using the C++ type mangling when we encounter a construct
3384 // that is incompatible with C.
3385
3386 switch (T->getTypeClass()) {
3387 case Type::Atomic:
3388 return encodeTypeForFunctionPointerAuth(
3389 Ctx, OS, QT: cast<AtomicType>(Val: T)->getValueType());
3390
3391 case Type::LValueReference:
3392 OS << "R";
3393 encodeTypeForFunctionPointerAuth(Ctx, OS,
3394 QT: cast<ReferenceType>(Val: T)->getPointeeType());
3395 return;
3396 case Type::RValueReference:
3397 OS << "O";
3398 encodeTypeForFunctionPointerAuth(Ctx, OS,
3399 QT: cast<ReferenceType>(Val: T)->getPointeeType());
3400 return;
3401
3402 case Type::Pointer:
3403 // C11 6.7.6.1p2:
3404 // For two pointer types to be compatible, both shall be identically
3405 // qualified and both shall be pointers to compatible types.
3406 // FIXME: we should also consider pointee types.
3407 OS << "P";
3408 return;
3409
3410 case Type::ObjCObjectPointer:
3411 case Type::BlockPointer:
3412 OS << "P";
3413 return;
3414
3415 case Type::Complex:
3416 OS << "C";
3417 return encodeTypeForFunctionPointerAuth(
3418 Ctx, OS, QT: cast<ComplexType>(Val: T)->getElementType());
3419
3420 case Type::VariableArray:
3421 case Type::ConstantArray:
3422 case Type::IncompleteArray:
3423 case Type::ArrayParameter:
3424 // C11 6.7.6.2p6:
3425 // For two array types to be compatible, both shall have compatible
3426 // element types, and if both size specifiers are present, and are integer
3427 // constant expressions, then both size specifiers shall have the same
3428 // constant value [...]
3429 //
3430 // So since ElemType[N] has to be compatible ElemType[], we can't encode the
3431 // width of the array.
3432 OS << "A";
3433 return encodeTypeForFunctionPointerAuth(
3434 Ctx, OS, QT: cast<ArrayType>(Val: T)->getElementType());
3435
3436 case Type::ObjCInterface:
3437 case Type::ObjCObject:
3438 OS << "<objc_object>";
3439 return;
3440
3441 case Type::Enum: {
3442 // C11 6.7.2.2p4:
3443 // Each enumerated type shall be compatible with char, a signed integer
3444 // type, or an unsigned integer type.
3445 //
3446 // So we have to treat enum types as integers.
3447 QualType UnderlyingType = T->castAsEnumDecl()->getIntegerType();
3448 return encodeTypeForFunctionPointerAuth(
3449 Ctx, OS, QT: UnderlyingType.isNull() ? Ctx.IntTy : UnderlyingType);
3450 }
3451
3452 case Type::FunctionNoProto:
3453 case Type::FunctionProto: {
3454 // C11 6.7.6.3p15:
3455 // For two function types to be compatible, both shall specify compatible
3456 // return types. Moreover, the parameter type lists, if both are present,
3457 // shall agree in the number of parameters and in the use of the ellipsis
3458 // terminator; corresponding parameters shall have compatible types.
3459 //
3460 // That paragraph goes on to describe how unprototyped functions are to be
3461 // handled, which we ignore here. Unprototyped function pointers are hashed
3462 // as though they were prototyped nullary functions since thats probably
3463 // what the user meant. This behavior is non-conforming.
3464 // FIXME: If we add a "custom discriminator" function type attribute we
3465 // should encode functions as their discriminators.
3466 OS << "F";
3467 const auto *FuncType = cast<FunctionType>(Val: T);
3468 encodeTypeForFunctionPointerAuth(Ctx, OS, QT: FuncType->getReturnType());
3469 if (const auto *FPT = dyn_cast<FunctionProtoType>(Val: FuncType)) {
3470 for (QualType Param : FPT->param_types()) {
3471 Param = Ctx.getSignatureParameterType(T: Param);
3472 encodeTypeForFunctionPointerAuth(Ctx, OS, QT: Param);
3473 }
3474 if (FPT->isVariadic())
3475 OS << "z";
3476 }
3477 OS << "E";
3478 return;
3479 }
3480
3481 case Type::MemberPointer: {
3482 OS << "M";
3483 const auto *MPT = T->castAs<MemberPointerType>();
3484 encodeTypeForFunctionPointerAuth(
3485 Ctx, OS, QT: QualType(MPT->getQualifier().getAsType(), 0));
3486 encodeTypeForFunctionPointerAuth(Ctx, OS, QT: MPT->getPointeeType());
3487 return;
3488 }
3489 case Type::ExtVector:
3490 case Type::Vector:
3491 OS << "Dv" << Ctx.getTypeSizeInChars(T).getQuantity();
3492 break;
3493
3494 // Don't bother discriminating based on these types.
3495 case Type::Pipe:
3496 case Type::BitInt:
3497 case Type::ConstantMatrix:
3498 OS << "?";
3499 return;
3500
3501 case Type::Builtin: {
3502 const auto *BTy = T->castAs<BuiltinType>();
3503 switch (BTy->getKind()) {
3504#define SIGNED_TYPE(Id, SingletonId) \
3505 case BuiltinType::Id: \
3506 OS << "i"; \
3507 return;
3508#define UNSIGNED_TYPE(Id, SingletonId) \
3509 case BuiltinType::Id: \
3510 OS << "i"; \
3511 return;
3512#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
3513#define BUILTIN_TYPE(Id, SingletonId)
3514#include "clang/AST/BuiltinTypes.def"
3515 llvm_unreachable("placeholder types should not appear here.");
3516
3517 case BuiltinType::Half:
3518 OS << "Dh";
3519 return;
3520 case BuiltinType::Float:
3521 OS << "f";
3522 return;
3523 case BuiltinType::Double:
3524 OS << "d";
3525 return;
3526 case BuiltinType::LongDouble:
3527 OS << "e";
3528 return;
3529 case BuiltinType::Float16:
3530 OS << "DF16_";
3531 return;
3532 case BuiltinType::Float128:
3533 OS << "g";
3534 return;
3535
3536 case BuiltinType::Void:
3537 OS << "v";
3538 return;
3539
3540 case BuiltinType::ObjCId:
3541 case BuiltinType::ObjCClass:
3542 case BuiltinType::ObjCSel:
3543 case BuiltinType::NullPtr:
3544 OS << "P";
3545 return;
3546
3547 // Don't bother discriminating based on OpenCL types.
3548 case BuiltinType::OCLSampler:
3549 case BuiltinType::OCLEvent:
3550 case BuiltinType::OCLClkEvent:
3551 case BuiltinType::OCLQueue:
3552 case BuiltinType::OCLReserveID:
3553 case BuiltinType::BFloat16:
3554 case BuiltinType::VectorQuad:
3555 case BuiltinType::VectorPair:
3556 case BuiltinType::DMR1024:
3557 case BuiltinType::DMR2048:
3558 OS << "?";
3559 return;
3560
3561 // Don't bother discriminating based on these seldom-used types.
3562 case BuiltinType::Ibm128:
3563 return;
3564#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
3565 case BuiltinType::Id: \
3566 return;
3567#include "clang/Basic/OpenCLImageTypes.def"
3568#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
3569 case BuiltinType::Id: \
3570 return;
3571#include "clang/Basic/OpenCLExtensionTypes.def"
3572#define SVE_TYPE(Name, Id, SingletonId) \
3573 case BuiltinType::Id: \
3574 return;
3575#include "clang/Basic/AArch64ACLETypes.def"
3576#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
3577 case BuiltinType::Id: \
3578 return;
3579#include "clang/Basic/HLSLIntangibleTypes.def"
3580 case BuiltinType::Dependent:
3581 llvm_unreachable("should never get here");
3582#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
3583#include "clang/Basic/AMDGPUTypes.def"
3584 case BuiltinType::WasmExternRef:
3585#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
3586#include "clang/Basic/RISCVVTypes.def"
3587 llvm_unreachable("not yet implemented");
3588 }
3589 llvm_unreachable("should never get here");
3590 }
3591 case Type::Record: {
3592 const RecordDecl *RD = T->castAsCanonical<RecordType>()->getDecl();
3593 const IdentifierInfo *II = RD->getIdentifier();
3594
3595 // In C++, an immediate typedef of an anonymous struct or union
3596 // is considered to name it for ODR purposes, but C's specification
3597 // of type compatibility does not have a similar rule. Using the typedef
3598 // name in function type discriminators anyway, as we do here,
3599 // therefore technically violates the C standard: two function pointer
3600 // types defined in terms of two typedef'd anonymous structs with
3601 // different names are formally still compatible, but we are assigning
3602 // them different discriminators and therefore incompatible ABIs.
3603 //
3604 // This is a relatively minor violation that significantly improves
3605 // discrimination in some cases and has not caused problems in
3606 // practice. Regardless, it is now part of the ABI in places where
3607 // function type discrimination is used, and it can no longer be
3608 // changed except on new platforms.
3609
3610 if (!II)
3611 if (const TypedefNameDecl *Typedef = RD->getTypedefNameForAnonDecl())
3612 II = Typedef->getDeclName().getAsIdentifierInfo();
3613
3614 if (!II) {
3615 OS << "<anonymous_record>";
3616 return;
3617 }
3618 OS << II->getLength() << II->getName();
3619 return;
3620 }
3621 case Type::HLSLAttributedResource:
3622 case Type::HLSLInlineSpirv:
3623 llvm_unreachable("should never get here");
3624 break;
3625 case Type::OverflowBehavior:
3626 llvm_unreachable("should never get here");
3627 break;
3628 case Type::DeducedTemplateSpecialization:
3629 case Type::Auto:
3630#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3631#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3632#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
3633#define ABSTRACT_TYPE(Class, Base)
3634#define TYPE(Class, Base)
3635#include "clang/AST/TypeNodes.inc"
3636 llvm_unreachable("unexpected non-canonical or dependent type!");
3637 return;
3638 }
3639}
3640
3641uint16_t ASTContext::getPointerAuthTypeDiscriminator(QualType T) {
3642 assert(!T->isDependentType() &&
3643 "cannot compute type discriminator of a dependent type");
3644 SmallString<256> Str;
3645 llvm::raw_svector_ostream Out(Str);
3646
3647 if (T->isFunctionPointerType() || T->isFunctionReferenceType())
3648 T = T->getPointeeType();
3649
3650 if (T->isFunctionType()) {
3651 encodeTypeForFunctionPointerAuth(Ctx: *this, OS&: Out, QT: T);
3652 } else {
3653 T = T.getUnqualifiedType();
3654 // Calls to member function pointers don't need to worry about
3655 // language interop or the laxness of the C type compatibility rules.
3656 // We just mangle the member pointer type directly, which is
3657 // implicitly much stricter about type matching. However, we do
3658 // strip any top-level exception specification before this mangling.
3659 // C++23 requires calls to work when the function type is convertible
3660 // to the pointer type by a function pointer conversion, which can
3661 // change the exception specification. This does not technically
3662 // require the exception specification to not affect representation,
3663 // because the function pointer conversion is still always a direct
3664 // value conversion and therefore an opportunity to resign the
3665 // pointer. (This is in contrast to e.g. qualification conversions,
3666 // which can be applied in nested pointer positions, effectively
3667 // requiring qualified and unqualified representations to match.)
3668 // However, it is pragmatic to ignore exception specifications
3669 // because it allows a certain amount of `noexcept` mismatching
3670 // to not become a visible ODR problem. This also leaves some
3671 // room for the committee to add laxness to function pointer
3672 // conversions in future standards.
3673 if (auto *MPT = T->getAs<MemberPointerType>())
3674 if (MPT->isMemberFunctionPointer()) {
3675 QualType PointeeType = MPT->getPointeeType();
3676 if (PointeeType->castAs<FunctionProtoType>()->getExceptionSpecType() !=
3677 EST_None) {
3678 QualType FT = getFunctionTypeWithExceptionSpec(Orig: PointeeType, ESI: EST_None);
3679 T = getMemberPointerType(T: FT, Qualifier: MPT->getQualifier(),
3680 Cls: MPT->getMostRecentCXXRecordDecl());
3681 }
3682 }
3683 std::unique_ptr<MangleContext> MC(createMangleContext());
3684 MC->mangleCanonicalTypeName(T, Out);
3685 }
3686
3687 return llvm::getPointerAuthStableSipHash(S: Str);
3688}
3689
3690QualType ASTContext::getObjCGCQualType(QualType T,
3691 Qualifiers::GC GCAttr) const {
3692 QualType CanT = getCanonicalType(T);
3693 if (CanT.getObjCGCAttr() == GCAttr)
3694 return T;
3695
3696 if (const auto *ptr = T->getAs<PointerType>()) {
3697 QualType Pointee = ptr->getPointeeType();
3698 if (Pointee->isAnyPointerType()) {
3699 QualType ResultType = getObjCGCQualType(T: Pointee, GCAttr);
3700 return getPointerType(T: ResultType);
3701 }
3702 }
3703
3704 // If we are composing extended qualifiers together, merge together
3705 // into one ExtQuals node.
3706 QualifierCollector Quals;
3707 const Type *TypeNode = Quals.strip(type: T);
3708
3709 // If this type already has an ObjCGC specified, it cannot get
3710 // another one.
3711 assert(!Quals.hasObjCGCAttr() &&
3712 "Type cannot have multiple ObjCGCs!");
3713 Quals.addObjCGCAttr(type: GCAttr);
3714
3715 return getExtQualType(baseType: TypeNode, quals: Quals);
3716}
3717
3718QualType ASTContext::removePtrSizeAddrSpace(QualType T) const {
3719 if (const PointerType *Ptr = T->getAs<PointerType>()) {
3720 QualType Pointee = Ptr->getPointeeType();
3721 if (isPtrSizeAddressSpace(AS: Pointee.getAddressSpace())) {
3722 return getPointerType(T: removeAddrSpaceQualType(T: Pointee));
3723 }
3724 }
3725 return T;
3726}
3727
3728QualType ASTContext::getCountAttributedType(
3729 QualType WrappedTy, Expr *CountExpr, bool CountInBytes, bool OrNull,
3730 ArrayRef<TypeCoupledDeclRefInfo> DependentDecls) const {
3731 assert(WrappedTy->isPointerType() || WrappedTy->isArrayType());
3732
3733 llvm::FoldingSetNodeID ID;
3734 CountAttributedType::Profile(ID, WrappedTy, CountExpr, CountInBytes, Nullable: OrNull);
3735
3736 void *InsertPos = nullptr;
3737 CountAttributedType *CATy =
3738 CountAttributedTypes.FindNodeOrInsertPos(ID, InsertPos);
3739 if (CATy)
3740 return QualType(CATy, 0);
3741
3742 QualType CanonTy = getCanonicalType(T: WrappedTy);
3743 size_t Size = CountAttributedType::totalSizeToAlloc<TypeCoupledDeclRefInfo>(
3744 Counts: DependentDecls.size());
3745 CATy = (CountAttributedType *)Allocate(Size, Align: TypeAlignment);
3746 new (CATy) CountAttributedType(WrappedTy, CanonTy, CountExpr, CountInBytes,
3747 OrNull, DependentDecls);
3748 Types.push_back(Elt: CATy);
3749 CountAttributedTypes.InsertNode(N: CATy, InsertPos);
3750
3751 return QualType(CATy, 0);
3752}
3753
3754QualType
3755ASTContext::adjustType(QualType Orig,
3756 llvm::function_ref<QualType(QualType)> Adjust) const {
3757 switch (Orig->getTypeClass()) {
3758 case Type::Attributed: {
3759 const auto *AT = cast<AttributedType>(Val&: Orig);
3760 return getAttributedType(attrKind: AT->getAttrKind(),
3761 modifiedType: adjustType(Orig: AT->getModifiedType(), Adjust),
3762 equivalentType: adjustType(Orig: AT->getEquivalentType(), Adjust),
3763 attr: AT->getAttr());
3764 }
3765
3766 case Type::BTFTagAttributed: {
3767 const auto *BTFT = dyn_cast<BTFTagAttributedType>(Val&: Orig);
3768 return getBTFTagAttributedType(BTFAttr: BTFT->getAttr(),
3769 Wrapped: adjustType(Orig: BTFT->getWrappedType(), Adjust));
3770 }
3771
3772 case Type::OverflowBehavior: {
3773 const auto *OB = dyn_cast<OverflowBehaviorType>(Val&: Orig);
3774 return getOverflowBehaviorType(Kind: OB->getBehaviorKind(),
3775 Wrapped: adjustType(Orig: OB->getUnderlyingType(), Adjust));
3776 }
3777
3778 case Type::Paren:
3779 return getParenType(
3780 NamedType: adjustType(Orig: cast<ParenType>(Val&: Orig)->getInnerType(), Adjust));
3781
3782 case Type::Adjusted: {
3783 const auto *AT = cast<AdjustedType>(Val&: Orig);
3784 return getAdjustedType(Orig: AT->getOriginalType(),
3785 New: adjustType(Orig: AT->getAdjustedType(), Adjust));
3786 }
3787
3788 case Type::MacroQualified: {
3789 const auto *MQT = cast<MacroQualifiedType>(Val&: Orig);
3790 return getMacroQualifiedType(UnderlyingTy: adjustType(Orig: MQT->getUnderlyingType(), Adjust),
3791 MacroII: MQT->getMacroIdentifier());
3792 }
3793
3794 default:
3795 return Adjust(Orig);
3796 }
3797}
3798
3799const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
3800 FunctionType::ExtInfo Info) {
3801 if (T->getExtInfo() == Info)
3802 return T;
3803
3804 QualType Result;
3805 if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(Val: T)) {
3806 Result = getFunctionNoProtoType(ResultTy: FNPT->getReturnType(), Info);
3807 } else {
3808 const auto *FPT = cast<FunctionProtoType>(Val: T);
3809 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
3810 EPI.ExtInfo = Info;
3811 Result = getFunctionType(ResultTy: FPT->getReturnType(), Args: FPT->getParamTypes(), EPI);
3812 }
3813
3814 return cast<FunctionType>(Val: Result.getTypePtr());
3815}
3816
3817QualType ASTContext::adjustFunctionResultType(QualType FunctionType,
3818 QualType ResultType) {
3819 return adjustType(Orig: FunctionType, Adjust: [&](QualType Orig) {
3820 if (const auto *FNPT = Orig->getAs<FunctionNoProtoType>())
3821 return getFunctionNoProtoType(ResultTy: ResultType, Info: FNPT->getExtInfo());
3822
3823 const auto *FPT = Orig->castAs<FunctionProtoType>();
3824 return getFunctionType(ResultTy: ResultType, Args: FPT->getParamTypes(),
3825 EPI: FPT->getExtProtoInfo());
3826 });
3827}
3828
3829void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
3830 QualType ResultType) {
3831 FD = FD->getMostRecentDecl();
3832 while (true) {
3833 FD->setType(adjustFunctionResultType(FunctionType: FD->getType(), ResultType));
3834 if (FunctionDecl *Next = FD->getPreviousDecl())
3835 FD = Next;
3836 else
3837 break;
3838 }
3839 if (ASTMutationListener *L = getASTMutationListener())
3840 L->DeducedReturnType(FD, ReturnType: ResultType);
3841}
3842
3843/// Get a function type and produce the equivalent function type with the
3844/// specified exception specification. Type sugar that can be present on a
3845/// declaration of a function with an exception specification is permitted
3846/// and preserved. Other type sugar (for instance, typedefs) is not.
3847QualType ASTContext::getFunctionTypeWithExceptionSpec(
3848 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) const {
3849 return adjustType(Orig, Adjust: [&](QualType Ty) {
3850 const auto *Proto = Ty->castAs<FunctionProtoType>();
3851 return getFunctionType(ResultTy: Proto->getReturnType(), Args: Proto->getParamTypes(),
3852 EPI: Proto->getExtProtoInfo().withExceptionSpec(ESI));
3853 });
3854}
3855
3856bool ASTContext::hasSameFunctionTypeIgnoringExceptionSpec(QualType T,
3857 QualType U) const {
3858 return hasSameType(T1: T, T2: U) ||
3859 (getLangOpts().CPlusPlus17 &&
3860 hasSameType(T1: getFunctionTypeWithExceptionSpec(Orig: T, ESI: EST_None),
3861 T2: getFunctionTypeWithExceptionSpec(Orig: U, ESI: EST_None)));
3862}
3863
3864QualType ASTContext::getFunctionTypeWithoutPtrSizes(QualType T) {
3865 if (const auto *Proto = T->getAs<FunctionProtoType>()) {
3866 QualType RetTy = removePtrSizeAddrSpace(T: Proto->getReturnType());
3867 SmallVector<QualType, 16> Args(Proto->param_types().size());
3868 for (unsigned i = 0, n = Args.size(); i != n; ++i)
3869 Args[i] = removePtrSizeAddrSpace(T: Proto->param_types()[i]);
3870 return getFunctionType(ResultTy: RetTy, Args, EPI: Proto->getExtProtoInfo());
3871 }
3872
3873 if (const FunctionNoProtoType *Proto = T->getAs<FunctionNoProtoType>()) {
3874 QualType RetTy = removePtrSizeAddrSpace(T: Proto->getReturnType());
3875 return getFunctionNoProtoType(ResultTy: RetTy, Info: Proto->getExtInfo());
3876 }
3877
3878 return T;
3879}
3880
3881bool ASTContext::hasSameFunctionTypeIgnoringPtrSizes(QualType T, QualType U) {
3882 return hasSameType(T1: T, T2: U) ||
3883 hasSameType(T1: getFunctionTypeWithoutPtrSizes(T),
3884 T2: getFunctionTypeWithoutPtrSizes(T: U));
3885}
3886
3887QualType ASTContext::getFunctionTypeWithoutParamABIs(QualType T) const {
3888 if (const auto *Proto = T->getAs<FunctionProtoType>()) {
3889 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3890 EPI.ExtParameterInfos = nullptr;
3891 return getFunctionType(ResultTy: Proto->getReturnType(), Args: Proto->param_types(), EPI);
3892 }
3893 return T;
3894}
3895
3896bool ASTContext::hasSameFunctionTypeIgnoringParamABI(QualType T,
3897 QualType U) const {
3898 return hasSameType(T1: T, T2: U) || hasSameType(T1: getFunctionTypeWithoutParamABIs(T),
3899 T2: getFunctionTypeWithoutParamABIs(T: U));
3900}
3901
3902void ASTContext::adjustExceptionSpec(
3903 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
3904 bool AsWritten) {
3905 // Update the type.
3906 QualType Updated =
3907 getFunctionTypeWithExceptionSpec(Orig: FD->getType(), ESI);
3908 FD->setType(Updated);
3909
3910 if (!AsWritten)
3911 return;
3912
3913 // Update the type in the type source information too.
3914 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
3915 // If the type and the type-as-written differ, we may need to update
3916 // the type-as-written too.
3917 if (TSInfo->getType() != FD->getType())
3918 Updated = getFunctionTypeWithExceptionSpec(Orig: TSInfo->getType(), ESI);
3919
3920 // FIXME: When we get proper type location information for exceptions,
3921 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
3922 // up the TypeSourceInfo;
3923 assert(TypeLoc::getFullDataSizeForType(Updated) ==
3924 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
3925 "TypeLoc size mismatch from updating exception specification");
3926 TSInfo->overrideType(T: Updated);
3927 }
3928}
3929
3930/// getComplexType - Return the uniqued reference to the type for a complex
3931/// number with the specified element type.
3932QualType ASTContext::getComplexType(QualType T) const {
3933 // Unique pointers, to guarantee there is only one pointer of a particular
3934 // structure.
3935 llvm::FoldingSetNodeID ID;
3936 ComplexType::Profile(ID, Element: T);
3937
3938 void *InsertPos = nullptr;
3939 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
3940 return QualType(CT, 0);
3941
3942 // If the pointee type isn't canonical, this won't be a canonical type either,
3943 // so fill in the canonical type field.
3944 QualType Canonical;
3945 if (!T.isCanonical()) {
3946 Canonical = getComplexType(T: getCanonicalType(T));
3947
3948 // Get the new insert position for the node we care about.
3949 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
3950 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3951 }
3952 auto *New = new (*this, alignof(ComplexType)) ComplexType(T, Canonical);
3953 Types.push_back(Elt: New);
3954 ComplexTypes.InsertNode(N: New, InsertPos);
3955 return QualType(New, 0);
3956}
3957
3958/// getPointerType - Return the uniqued reference to the type for a pointer to
3959/// the specified type.
3960QualType ASTContext::getPointerType(QualType T) const {
3961 // Unique pointers, to guarantee there is only one pointer of a particular
3962 // structure.
3963 llvm::FoldingSetNodeID ID;
3964 PointerType::Profile(ID, Pointee: T);
3965
3966 void *InsertPos = nullptr;
3967 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3968 return QualType(PT, 0);
3969
3970 // If the pointee type isn't canonical, this won't be a canonical type either,
3971 // so fill in the canonical type field.
3972 QualType Canonical;
3973 if (!T.isCanonical()) {
3974 Canonical = getPointerType(T: getCanonicalType(T));
3975
3976 // Get the new insert position for the node we care about.
3977 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3978 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3979 }
3980 auto *New = new (*this, alignof(PointerType)) PointerType(T, Canonical);
3981 Types.push_back(Elt: New);
3982 PointerTypes.InsertNode(N: New, InsertPos);
3983 return QualType(New, 0);
3984}
3985
3986QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
3987 llvm::FoldingSetNodeID ID;
3988 AdjustedType::Profile(ID, Orig, New);
3989 void *InsertPos = nullptr;
3990 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3991 if (AT)
3992 return QualType(AT, 0);
3993
3994 QualType Canonical = getCanonicalType(T: New);
3995
3996 // Get the new insert position for the node we care about.
3997 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3998 assert(!AT && "Shouldn't be in the map!");
3999
4000 AT = new (*this, alignof(AdjustedType))
4001 AdjustedType(Type::Adjusted, Orig, New, Canonical);
4002 Types.push_back(Elt: AT);
4003 AdjustedTypes.InsertNode(N: AT, InsertPos);
4004 return QualType(AT, 0);
4005}
4006
4007QualType ASTContext::getDecayedType(QualType Orig, QualType Decayed) const {
4008 llvm::FoldingSetNodeID ID;
4009 AdjustedType::Profile(ID, Orig, New: Decayed);
4010 void *InsertPos = nullptr;
4011 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
4012 if (AT)
4013 return QualType(AT, 0);
4014
4015 QualType Canonical = getCanonicalType(T: Decayed);
4016
4017 // Get the new insert position for the node we care about.
4018 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
4019 assert(!AT && "Shouldn't be in the map!");
4020
4021 AT = new (*this, alignof(DecayedType)) DecayedType(Orig, Decayed, Canonical);
4022 Types.push_back(Elt: AT);
4023 AdjustedTypes.InsertNode(N: AT, InsertPos);
4024 return QualType(AT, 0);
4025}
4026
4027QualType ASTContext::getDecayedType(QualType T) const {
4028 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
4029
4030 QualType Decayed;
4031
4032 // C99 6.7.5.3p7:
4033 // A declaration of a parameter as "array of type" shall be
4034 // adjusted to "qualified pointer to type", where the type
4035 // qualifiers (if any) are those specified within the [ and ] of
4036 // the array type derivation.
4037 if (T->isArrayType())
4038 Decayed = getArrayDecayedType(T);
4039
4040 // C99 6.7.5.3p8:
4041 // A declaration of a parameter as "function returning type"
4042 // shall be adjusted to "pointer to function returning type", as
4043 // in 6.3.2.1.
4044 if (T->isFunctionType())
4045 Decayed = getPointerType(T);
4046
4047 return getDecayedType(Orig: T, Decayed);
4048}
4049
4050QualType ASTContext::getArrayParameterType(QualType Ty) const {
4051 if (Ty->isArrayParameterType())
4052 return Ty;
4053 assert(Ty->isConstantArrayType() && "Ty must be an array type.");
4054 QualType DTy = Ty.getDesugaredType(Context: *this);
4055 const auto *ATy = cast<ConstantArrayType>(Val&: DTy);
4056 llvm::FoldingSetNodeID ID;
4057 ATy->Profile(ID, Ctx: *this, ET: ATy->getElementType(), ArraySize: ATy->getZExtSize(),
4058 SizeExpr: ATy->getSizeExpr(), SizeMod: ATy->getSizeModifier(),
4059 TypeQuals: ATy->getIndexTypeQualifiers().getAsOpaqueValue());
4060 void *InsertPos = nullptr;
4061 ArrayParameterType *AT =
4062 ArrayParameterTypes.FindNodeOrInsertPos(ID, InsertPos);
4063 if (AT)
4064 return QualType(AT, 0);
4065
4066 QualType Canonical;
4067 if (!DTy.isCanonical()) {
4068 Canonical = getArrayParameterType(Ty: getCanonicalType(T: Ty));
4069
4070 // Get the new insert position for the node we care about.
4071 AT = ArrayParameterTypes.FindNodeOrInsertPos(ID, InsertPos);
4072 assert(!AT && "Shouldn't be in the map!");
4073 }
4074
4075 AT = new (*this, alignof(ArrayParameterType))
4076 ArrayParameterType(ATy, Canonical);
4077 Types.push_back(Elt: AT);
4078 ArrayParameterTypes.InsertNode(N: AT, InsertPos);
4079 return QualType(AT, 0);
4080}
4081
4082/// getBlockPointerType - Return the uniqued reference to the type for
4083/// a pointer to the specified block.
4084QualType ASTContext::getBlockPointerType(QualType T) const {
4085 assert(T->isFunctionType() && "block of function types only");
4086 // Unique pointers, to guarantee there is only one block of a particular
4087 // structure.
4088 llvm::FoldingSetNodeID ID;
4089 BlockPointerType::Profile(ID, Pointee: T);
4090
4091 void *InsertPos = nullptr;
4092 if (BlockPointerType *PT =
4093 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
4094 return QualType(PT, 0);
4095
4096 // If the block pointee type isn't canonical, this won't be a canonical
4097 // type either so fill in the canonical type field.
4098 QualType Canonical;
4099 if (!T.isCanonical()) {
4100 Canonical = getBlockPointerType(T: getCanonicalType(T));
4101
4102 // Get the new insert position for the node we care about.
4103 BlockPointerType *NewIP =
4104 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
4105 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4106 }
4107 auto *New =
4108 new (*this, alignof(BlockPointerType)) BlockPointerType(T, Canonical);
4109 Types.push_back(Elt: New);
4110 BlockPointerTypes.InsertNode(N: New, InsertPos);
4111 return QualType(New, 0);
4112}
4113
4114/// getLValueReferenceType - Return the uniqued reference to the type for an
4115/// lvalue reference to the specified type.
4116QualType
4117ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
4118 assert((!T->isPlaceholderType() ||
4119 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
4120 "Unresolved placeholder type");
4121
4122 // Unique pointers, to guarantee there is only one pointer of a particular
4123 // structure.
4124 llvm::FoldingSetNodeID ID;
4125 ReferenceType::Profile(ID, Referencee: T, SpelledAsLValue);
4126
4127 void *InsertPos = nullptr;
4128 if (LValueReferenceType *RT =
4129 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
4130 return QualType(RT, 0);
4131
4132 const auto *InnerRef = T->getAs<ReferenceType>();
4133
4134 // If the referencee type isn't canonical, this won't be a canonical type
4135 // either, so fill in the canonical type field.
4136 QualType Canonical;
4137 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
4138 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
4139 Canonical = getLValueReferenceType(T: getCanonicalType(T: PointeeType));
4140
4141 // Get the new insert position for the node we care about.
4142 LValueReferenceType *NewIP =
4143 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
4144 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4145 }
4146
4147 auto *New = new (*this, alignof(LValueReferenceType))
4148 LValueReferenceType(T, Canonical, SpelledAsLValue);
4149 Types.push_back(Elt: New);
4150 LValueReferenceTypes.InsertNode(N: New, InsertPos);
4151
4152 return QualType(New, 0);
4153}
4154
4155/// getRValueReferenceType - Return the uniqued reference to the type for an
4156/// rvalue reference to the specified type.
4157QualType ASTContext::getRValueReferenceType(QualType T) const {
4158 assert((!T->isPlaceholderType() ||
4159 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
4160 "Unresolved placeholder type");
4161
4162 // Unique pointers, to guarantee there is only one pointer of a particular
4163 // structure.
4164 llvm::FoldingSetNodeID ID;
4165 ReferenceType::Profile(ID, Referencee: T, SpelledAsLValue: false);
4166
4167 void *InsertPos = nullptr;
4168 if (RValueReferenceType *RT =
4169 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
4170 return QualType(RT, 0);
4171
4172 const auto *InnerRef = T->getAs<ReferenceType>();
4173
4174 // If the referencee type isn't canonical, this won't be a canonical type
4175 // either, so fill in the canonical type field.
4176 QualType Canonical;
4177 if (InnerRef || !T.isCanonical()) {
4178 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
4179 Canonical = getRValueReferenceType(T: getCanonicalType(T: PointeeType));
4180
4181 // Get the new insert position for the node we care about.
4182 RValueReferenceType *NewIP =
4183 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
4184 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4185 }
4186
4187 auto *New = new (*this, alignof(RValueReferenceType))
4188 RValueReferenceType(T, Canonical);
4189 Types.push_back(Elt: New);
4190 RValueReferenceTypes.InsertNode(N: New, InsertPos);
4191 return QualType(New, 0);
4192}
4193
4194QualType ASTContext::getMemberPointerType(QualType T,
4195 NestedNameSpecifier Qualifier,
4196 const CXXRecordDecl *Cls) const {
4197 if (!Qualifier) {
4198 assert(Cls && "At least one of Qualifier or Cls must be provided");
4199 Qualifier = NestedNameSpecifier(getCanonicalTagType(TD: Cls).getTypePtr());
4200 } else if (!Cls) {
4201 Cls = Qualifier.getAsRecordDecl();
4202 }
4203 // Unique pointers, to guarantee there is only one pointer of a particular
4204 // structure.
4205 llvm::FoldingSetNodeID ID;
4206 MemberPointerType::Profile(ID, Pointee: T, Qualifier, Cls);
4207
4208 void *InsertPos = nullptr;
4209 if (MemberPointerType *PT =
4210 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
4211 return QualType(PT, 0);
4212
4213 NestedNameSpecifier CanonicalQualifier = [&] {
4214 if (!Cls)
4215 return Qualifier.getCanonical();
4216 NestedNameSpecifier R(getCanonicalTagType(TD: Cls).getTypePtr());
4217 assert(R.isCanonical());
4218 return R;
4219 }();
4220 // If the pointee or class type isn't canonical, this won't be a canonical
4221 // type either, so fill in the canonical type field.
4222 QualType Canonical;
4223 if (!T.isCanonical() || Qualifier != CanonicalQualifier) {
4224 Canonical =
4225 getMemberPointerType(T: getCanonicalType(T), Qualifier: CanonicalQualifier, Cls);
4226 assert(!cast<MemberPointerType>(Canonical)->isSugared());
4227 // Get the new insert position for the node we care about.
4228 [[maybe_unused]] MemberPointerType *NewIP =
4229 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
4230 assert(!NewIP && "Shouldn't be in the map!");
4231 }
4232 auto *New = new (*this, alignof(MemberPointerType))
4233 MemberPointerType(T, Qualifier, Canonical);
4234 Types.push_back(Elt: New);
4235 MemberPointerTypes.InsertNode(N: New, InsertPos);
4236 return QualType(New, 0);
4237}
4238
4239/// getConstantArrayType - Return the unique reference to the type for an
4240/// array of the specified element type.
4241QualType ASTContext::getConstantArrayType(QualType EltTy,
4242 const llvm::APInt &ArySizeIn,
4243 const Expr *SizeExpr,
4244 ArraySizeModifier ASM,
4245 unsigned IndexTypeQuals) const {
4246 assert((EltTy->isDependentType() ||
4247 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
4248 "Constant array of VLAs is illegal!");
4249
4250 // We only need the size as part of the type if it's instantiation-dependent.
4251 if (SizeExpr && !SizeExpr->isInstantiationDependent())
4252 SizeExpr = nullptr;
4253
4254 // Convert the array size into a canonical width matching the pointer size for
4255 // the target.
4256 llvm::APInt ArySize(ArySizeIn);
4257 ArySize = ArySize.zextOrTrunc(width: Target->getMaxPointerWidth());
4258
4259 llvm::FoldingSetNodeID ID;
4260 ConstantArrayType::Profile(ID, Ctx: *this, ET: EltTy, ArraySize: ArySize.getZExtValue(), SizeExpr,
4261 SizeMod: ASM, TypeQuals: IndexTypeQuals);
4262
4263 void *InsertPos = nullptr;
4264 if (ConstantArrayType *ATP =
4265 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
4266 return QualType(ATP, 0);
4267
4268 // If the element type isn't canonical or has qualifiers, or the array bound
4269 // is instantiation-dependent, this won't be a canonical type either, so fill
4270 // in the canonical type field.
4271 QualType Canon;
4272 // FIXME: Check below should look for qualifiers behind sugar.
4273 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers() || SizeExpr) {
4274 SplitQualType canonSplit = getCanonicalType(T: EltTy).split();
4275 Canon = getConstantArrayType(EltTy: QualType(canonSplit.Ty, 0), ArySizeIn: ArySize, SizeExpr: nullptr,
4276 ASM, IndexTypeQuals);
4277 Canon = getQualifiedType(T: Canon, Qs: canonSplit.Quals);
4278
4279 // Get the new insert position for the node we care about.
4280 ConstantArrayType *NewIP =
4281 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
4282 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4283 }
4284
4285 auto *New = ConstantArrayType::Create(Ctx: *this, ET: EltTy, Can: Canon, Sz: ArySize, SzExpr: SizeExpr,
4286 SzMod: ASM, Qual: IndexTypeQuals);
4287 ConstantArrayTypes.InsertNode(N: New, InsertPos);
4288 Types.push_back(Elt: New);
4289 return QualType(New, 0);
4290}
4291
4292/// getVariableArrayDecayedType - Turns the given type, which may be
4293/// variably-modified, into the corresponding type with all the known
4294/// sizes replaced with [*].
4295QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
4296 // Vastly most common case.
4297 if (!type->isVariablyModifiedType()) return type;
4298
4299 QualType result;
4300
4301 SplitQualType split = type.getSplitDesugaredType();
4302 const Type *ty = split.Ty;
4303 switch (ty->getTypeClass()) {
4304#define TYPE(Class, Base)
4305#define ABSTRACT_TYPE(Class, Base)
4306#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4307#include "clang/AST/TypeNodes.inc"
4308 llvm_unreachable("didn't desugar past all non-canonical types?");
4309
4310 // These types should never be variably-modified.
4311 case Type::Builtin:
4312 case Type::Complex:
4313 case Type::Vector:
4314 case Type::DependentVector:
4315 case Type::ExtVector:
4316 case Type::DependentSizedExtVector:
4317 case Type::ConstantMatrix:
4318 case Type::DependentSizedMatrix:
4319 case Type::DependentAddressSpace:
4320 case Type::ObjCObject:
4321 case Type::ObjCInterface:
4322 case Type::ObjCObjectPointer:
4323 case Type::Record:
4324 case Type::Enum:
4325 case Type::UnresolvedUsing:
4326 case Type::TypeOfExpr:
4327 case Type::TypeOf:
4328 case Type::Decltype:
4329 case Type::UnaryTransform:
4330 case Type::DependentName:
4331 case Type::InjectedClassName:
4332 case Type::TemplateSpecialization:
4333 case Type::TemplateTypeParm:
4334 case Type::SubstTemplateTypeParmPack:
4335 case Type::SubstBuiltinTemplatePack:
4336 case Type::Auto:
4337 case Type::DeducedTemplateSpecialization:
4338 case Type::PackExpansion:
4339 case Type::PackIndexing:
4340 case Type::BitInt:
4341 case Type::DependentBitInt:
4342 case Type::ArrayParameter:
4343 case Type::HLSLAttributedResource:
4344 case Type::HLSLInlineSpirv:
4345 case Type::OverflowBehavior:
4346 llvm_unreachable("type should never be variably-modified");
4347
4348 // These types can be variably-modified but should never need to
4349 // further decay.
4350 case Type::FunctionNoProto:
4351 case Type::FunctionProto:
4352 case Type::BlockPointer:
4353 case Type::MemberPointer:
4354 case Type::Pipe:
4355 return type;
4356
4357 // These types can be variably-modified. All these modifications
4358 // preserve structure except as noted by comments.
4359 // TODO: if we ever care about optimizing VLAs, there are no-op
4360 // optimizations available here.
4361 case Type::Pointer:
4362 result = getPointerType(T: getVariableArrayDecayedType(
4363 type: cast<PointerType>(Val: ty)->getPointeeType()));
4364 break;
4365
4366 case Type::LValueReference: {
4367 const auto *lv = cast<LValueReferenceType>(Val: ty);
4368 result = getLValueReferenceType(
4369 T: getVariableArrayDecayedType(type: lv->getPointeeType()),
4370 SpelledAsLValue: lv->isSpelledAsLValue());
4371 break;
4372 }
4373
4374 case Type::RValueReference: {
4375 const auto *lv = cast<RValueReferenceType>(Val: ty);
4376 result = getRValueReferenceType(
4377 T: getVariableArrayDecayedType(type: lv->getPointeeType()));
4378 break;
4379 }
4380
4381 case Type::Atomic: {
4382 const auto *at = cast<AtomicType>(Val: ty);
4383 result = getAtomicType(T: getVariableArrayDecayedType(type: at->getValueType()));
4384 break;
4385 }
4386
4387 case Type::ConstantArray: {
4388 const auto *cat = cast<ConstantArrayType>(Val: ty);
4389 result = getConstantArrayType(
4390 EltTy: getVariableArrayDecayedType(type: cat->getElementType()),
4391 ArySizeIn: cat->getSize(),
4392 SizeExpr: cat->getSizeExpr(),
4393 ASM: cat->getSizeModifier(),
4394 IndexTypeQuals: cat->getIndexTypeCVRQualifiers());
4395 break;
4396 }
4397
4398 case Type::DependentSizedArray: {
4399 const auto *dat = cast<DependentSizedArrayType>(Val: ty);
4400 result = getDependentSizedArrayType(
4401 EltTy: getVariableArrayDecayedType(type: dat->getElementType()), NumElts: dat->getSizeExpr(),
4402 ASM: dat->getSizeModifier(), IndexTypeQuals: dat->getIndexTypeCVRQualifiers());
4403 break;
4404 }
4405
4406 // Turn incomplete types into [*] types.
4407 case Type::IncompleteArray: {
4408 const auto *iat = cast<IncompleteArrayType>(Val: ty);
4409 result =
4410 getVariableArrayType(EltTy: getVariableArrayDecayedType(type: iat->getElementType()),
4411 /*size*/ NumElts: nullptr, ASM: ArraySizeModifier::Normal,
4412 IndexTypeQuals: iat->getIndexTypeCVRQualifiers());
4413 break;
4414 }
4415
4416 // Turn VLA types into [*] types.
4417 case Type::VariableArray: {
4418 const auto *vat = cast<VariableArrayType>(Val: ty);
4419 result =
4420 getVariableArrayType(EltTy: getVariableArrayDecayedType(type: vat->getElementType()),
4421 /*size*/ NumElts: nullptr, ASM: ArraySizeModifier::Star,
4422 IndexTypeQuals: vat->getIndexTypeCVRQualifiers());
4423 break;
4424 }
4425 }
4426
4427 // Apply the top-level qualifiers from the original.
4428 return getQualifiedType(T: result, Qs: split.Quals);
4429}
4430
4431/// getVariableArrayType - Returns a non-unique reference to the type for a
4432/// variable array of the specified element type.
4433QualType ASTContext::getVariableArrayType(QualType EltTy, Expr *NumElts,
4434 ArraySizeModifier ASM,
4435 unsigned IndexTypeQuals) const {
4436 // Since we don't unique expressions, it isn't possible to unique VLA's
4437 // that have an expression provided for their size.
4438 QualType Canon;
4439
4440 // Be sure to pull qualifiers off the element type.
4441 // FIXME: Check below should look for qualifiers behind sugar.
4442 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
4443 SplitQualType canonSplit = getCanonicalType(T: EltTy).split();
4444 Canon = getVariableArrayType(EltTy: QualType(canonSplit.Ty, 0), NumElts, ASM,
4445 IndexTypeQuals);
4446 Canon = getQualifiedType(T: Canon, Qs: canonSplit.Quals);
4447 }
4448
4449 auto *New = new (*this, alignof(VariableArrayType))
4450 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals);
4451
4452 VariableArrayTypes.push_back(x: New);
4453 Types.push_back(Elt: New);
4454 return QualType(New, 0);
4455}
4456
4457/// getDependentSizedArrayType - Returns a non-unique reference to
4458/// the type for a dependently-sized array of the specified element
4459/// type.
4460QualType
4461ASTContext::getDependentSizedArrayType(QualType elementType, Expr *numElements,
4462 ArraySizeModifier ASM,
4463 unsigned elementTypeQuals) const {
4464 assert((!numElements || numElements->isTypeDependent() ||
4465 numElements->isValueDependent()) &&
4466 "Size must be type- or value-dependent!");
4467
4468 SplitQualType canonElementType = getCanonicalType(T: elementType).split();
4469
4470 void *insertPos = nullptr;
4471 llvm::FoldingSetNodeID ID;
4472 DependentSizedArrayType::Profile(
4473 ID, Context: *this, ET: numElements ? QualType(canonElementType.Ty, 0) : elementType,
4474 SizeMod: ASM, TypeQuals: elementTypeQuals, E: numElements);
4475
4476 // Look for an existing type with these properties.
4477 DependentSizedArrayType *canonTy =
4478 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos&: insertPos);
4479
4480 // Dependently-sized array types that do not have a specified number
4481 // of elements will have their sizes deduced from a dependent
4482 // initializer.
4483 if (!numElements) {
4484 if (canonTy)
4485 return QualType(canonTy, 0);
4486
4487 auto *newType = new (*this, alignof(DependentSizedArrayType))
4488 DependentSizedArrayType(elementType, QualType(), numElements, ASM,
4489 elementTypeQuals);
4490 DependentSizedArrayTypes.InsertNode(N: newType, InsertPos: insertPos);
4491 Types.push_back(Elt: newType);
4492 return QualType(newType, 0);
4493 }
4494
4495 // If we don't have one, build one.
4496 if (!canonTy) {
4497 canonTy = new (*this, alignof(DependentSizedArrayType))
4498 DependentSizedArrayType(QualType(canonElementType.Ty, 0), QualType(),
4499 numElements, ASM, elementTypeQuals);
4500 DependentSizedArrayTypes.InsertNode(N: canonTy, InsertPos: insertPos);
4501 Types.push_back(Elt: canonTy);
4502 }
4503
4504 // Apply qualifiers from the element type to the array.
4505 QualType canon = getQualifiedType(T: QualType(canonTy,0),
4506 Qs: canonElementType.Quals);
4507
4508 // If we didn't need extra canonicalization for the element type or the size
4509 // expression, then just use that as our result.
4510 if (QualType(canonElementType.Ty, 0) == elementType &&
4511 canonTy->getSizeExpr() == numElements)
4512 return canon;
4513
4514 // Otherwise, we need to build a type which follows the spelling
4515 // of the element type.
4516 auto *sugaredType = new (*this, alignof(DependentSizedArrayType))
4517 DependentSizedArrayType(elementType, canon, numElements, ASM,
4518 elementTypeQuals);
4519 Types.push_back(Elt: sugaredType);
4520 return QualType(sugaredType, 0);
4521}
4522
4523QualType ASTContext::getIncompleteArrayType(QualType elementType,
4524 ArraySizeModifier ASM,
4525 unsigned elementTypeQuals) const {
4526 llvm::FoldingSetNodeID ID;
4527 IncompleteArrayType::Profile(ID, ET: elementType, SizeMod: ASM, TypeQuals: elementTypeQuals);
4528
4529 void *insertPos = nullptr;
4530 if (IncompleteArrayType *iat =
4531 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos&: insertPos))
4532 return QualType(iat, 0);
4533
4534 // If the element type isn't canonical, this won't be a canonical type
4535 // either, so fill in the canonical type field. We also have to pull
4536 // qualifiers off the element type.
4537 QualType canon;
4538
4539 // FIXME: Check below should look for qualifiers behind sugar.
4540 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
4541 SplitQualType canonSplit = getCanonicalType(T: elementType).split();
4542 canon = getIncompleteArrayType(elementType: QualType(canonSplit.Ty, 0),
4543 ASM, elementTypeQuals);
4544 canon = getQualifiedType(T: canon, Qs: canonSplit.Quals);
4545
4546 // Get the new insert position for the node we care about.
4547 IncompleteArrayType *existing =
4548 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos&: insertPos);
4549 assert(!existing && "Shouldn't be in the map!"); (void) existing;
4550 }
4551
4552 auto *newType = new (*this, alignof(IncompleteArrayType))
4553 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
4554
4555 IncompleteArrayTypes.InsertNode(N: newType, InsertPos: insertPos);
4556 Types.push_back(Elt: newType);
4557 return QualType(newType, 0);
4558}
4559
4560ASTContext::BuiltinVectorTypeInfo
4561ASTContext::getBuiltinVectorTypeInfo(const BuiltinType *Ty) const {
4562#define SVE_INT_ELTTY(BITS, ELTS, SIGNED, NUMVECTORS) \
4563 {getIntTypeForBitwidth(BITS, SIGNED), llvm::ElementCount::getScalable(ELTS), \
4564 NUMVECTORS};
4565
4566#define SVE_ELTTY(ELTTY, ELTS, NUMVECTORS) \
4567 {ELTTY, llvm::ElementCount::getScalable(ELTS), NUMVECTORS};
4568
4569 switch (Ty->getKind()) {
4570 default:
4571 llvm_unreachable("Unsupported builtin vector type");
4572
4573#define SVE_VECTOR_TYPE_INT(Name, MangledName, Id, SingletonId, NumEls, \
4574 ElBits, NF, IsSigned) \
4575 case BuiltinType::Id: \
4576 return {getIntTypeForBitwidth(ElBits, IsSigned), \
4577 llvm::ElementCount::getScalable(NumEls), NF};
4578#define SVE_VECTOR_TYPE_FLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4579 ElBits, NF) \
4580 case BuiltinType::Id: \
4581 return {ElBits == 16 ? HalfTy : (ElBits == 32 ? FloatTy : DoubleTy), \
4582 llvm::ElementCount::getScalable(NumEls), NF};
4583#define SVE_VECTOR_TYPE_BFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4584 ElBits, NF) \
4585 case BuiltinType::Id: \
4586 return {BFloat16Ty, llvm::ElementCount::getScalable(NumEls), NF};
4587#define SVE_VECTOR_TYPE_MFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4588 ElBits, NF) \
4589 case BuiltinType::Id: \
4590 return {MFloat8Ty, llvm::ElementCount::getScalable(NumEls), NF};
4591#define SVE_PREDICATE_TYPE_ALL(Name, MangledName, Id, SingletonId, NumEls, NF) \
4592 case BuiltinType::Id: \
4593 return {BoolTy, llvm::ElementCount::getScalable(NumEls), NF};
4594#include "clang/Basic/AArch64ACLETypes.def"
4595
4596#define RVV_VECTOR_TYPE_INT(Name, Id, SingletonId, NumEls, ElBits, NF, \
4597 IsSigned) \
4598 case BuiltinType::Id: \
4599 return {getIntTypeForBitwidth(ElBits, IsSigned), \
4600 llvm::ElementCount::getScalable(NumEls), NF};
4601#define RVV_VECTOR_TYPE_FLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \
4602 case BuiltinType::Id: \
4603 return {ElBits == 16 ? Float16Ty : (ElBits == 32 ? FloatTy : DoubleTy), \
4604 llvm::ElementCount::getScalable(NumEls), NF};
4605#define RVV_VECTOR_TYPE_BFLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \
4606 case BuiltinType::Id: \
4607 return {BFloat16Ty, llvm::ElementCount::getScalable(NumEls), NF};
4608#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
4609 case BuiltinType::Id: \
4610 return {BoolTy, llvm::ElementCount::getScalable(NumEls), 1};
4611#include "clang/Basic/RISCVVTypes.def"
4612 }
4613}
4614
4615/// getExternrefType - Return a WebAssembly externref type, which represents an
4616/// opaque reference to a host value.
4617QualType ASTContext::getWebAssemblyExternrefType() const {
4618 if (Target->getTriple().isWasm() && Target->hasFeature(Feature: "reference-types")) {
4619#define WASM_REF_TYPE(Name, MangledName, Id, SingletonId, AS) \
4620 if (BuiltinType::Id == BuiltinType::WasmExternRef) \
4621 return SingletonId;
4622#include "clang/Basic/WebAssemblyReferenceTypes.def"
4623 }
4624 llvm_unreachable(
4625 "shouldn't try to generate type externref outside WebAssembly target");
4626}
4627
4628/// getScalableVectorType - Return the unique reference to a scalable vector
4629/// type of the specified element type and size. VectorType must be a built-in
4630/// type.
4631QualType ASTContext::getScalableVectorType(QualType EltTy, unsigned NumElts,
4632 unsigned NumFields) const {
4633 auto K = llvm::ScalableVecTyKey{.EltTy: EltTy, .NumElts: NumElts, .NumFields: NumFields};
4634 if (auto It = ScalableVecTyMap.find(Val: K); It != ScalableVecTyMap.end())
4635 return It->second;
4636
4637 if (Target->hasAArch64ACLETypes()) {
4638 uint64_t EltTySize = getTypeSize(T: EltTy);
4639
4640#define SVE_VECTOR_TYPE_INT(Name, MangledName, Id, SingletonId, NumEls, \
4641 ElBits, NF, IsSigned) \
4642 if (EltTy->hasIntegerRepresentation() && !EltTy->isBooleanType() && \
4643 EltTy->hasSignedIntegerRepresentation() == IsSigned && \
4644 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4645 return ScalableVecTyMap[K] = SingletonId; \
4646 }
4647#define SVE_VECTOR_TYPE_FLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4648 ElBits, NF) \
4649 if (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \
4650 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4651 return ScalableVecTyMap[K] = SingletonId; \
4652 }
4653#define SVE_VECTOR_TYPE_BFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4654 ElBits, NF) \
4655 if (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \
4656 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4657 return ScalableVecTyMap[K] = SingletonId; \
4658 }
4659#define SVE_VECTOR_TYPE_MFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4660 ElBits, NF) \
4661 if (EltTy->isMFloat8Type() && EltTySize == ElBits && \
4662 NumElts == (NumEls * NF) && NumFields == 1) { \
4663 return ScalableVecTyMap[K] = SingletonId; \
4664 }
4665#define SVE_PREDICATE_TYPE_ALL(Name, MangledName, Id, SingletonId, NumEls, NF) \
4666 if (EltTy->isBooleanType() && NumElts == (NumEls * NF) && NumFields == 1) \
4667 return ScalableVecTyMap[K] = SingletonId;
4668#include "clang/Basic/AArch64ACLETypes.def"
4669 } else if (Target->hasRISCVVTypes()) {
4670 uint64_t EltTySize = getTypeSize(T: EltTy);
4671#define RVV_VECTOR_TYPE(Name, Id, SingletonId, NumEls, ElBits, NF, IsSigned, \
4672 IsFP, IsBF) \
4673 if (!EltTy->isBooleanType() && \
4674 ((EltTy->hasIntegerRepresentation() && \
4675 EltTy->hasSignedIntegerRepresentation() == IsSigned) || \
4676 (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \
4677 IsFP && !IsBF) || \
4678 (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \
4679 IsBF && !IsFP)) && \
4680 EltTySize == ElBits && NumElts == NumEls && NumFields == NF) \
4681 return ScalableVecTyMap[K] = SingletonId;
4682#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
4683 if (EltTy->isBooleanType() && NumElts == NumEls) \
4684 return ScalableVecTyMap[K] = SingletonId;
4685#include "clang/Basic/RISCVVTypes.def"
4686 }
4687 return QualType();
4688}
4689
4690/// getVectorType - Return the unique reference to a vector type of
4691/// the specified element type and size. VectorType must be a built-in type.
4692QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
4693 VectorKind VecKind) const {
4694 assert(vecType->isBuiltinType() ||
4695 (vecType->isBitIntType() &&
4696 // Only support _BitInt elements with byte-sized power of 2 NumBits.
4697 llvm::isPowerOf2_32(vecType->castAs<BitIntType>()->getNumBits())));
4698
4699 // Check if we've already instantiated a vector of this type.
4700 llvm::FoldingSetNodeID ID;
4701 VectorType::Profile(ID, ElementType: vecType, NumElements: NumElts, TypeClass: Type::Vector, VecKind);
4702
4703 void *InsertPos = nullptr;
4704 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
4705 return QualType(VTP, 0);
4706
4707 // If the element type isn't canonical, this won't be a canonical type either,
4708 // so fill in the canonical type field.
4709 QualType Canonical;
4710 if (!vecType.isCanonical()) {
4711 Canonical = getVectorType(vecType: getCanonicalType(T: vecType), NumElts, VecKind);
4712
4713 // Get the new insert position for the node we care about.
4714 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4715 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4716 }
4717 auto *New = new (*this, alignof(VectorType))
4718 VectorType(vecType, NumElts, Canonical, VecKind);
4719 VectorTypes.InsertNode(N: New, InsertPos);
4720 Types.push_back(Elt: New);
4721 return QualType(New, 0);
4722}
4723
4724QualType ASTContext::getDependentVectorType(QualType VecType, Expr *SizeExpr,
4725 SourceLocation AttrLoc,
4726 VectorKind VecKind) const {
4727 llvm::FoldingSetNodeID ID;
4728 DependentVectorType::Profile(ID, Context: *this, ElementType: getCanonicalType(T: VecType), SizeExpr,
4729 VecKind);
4730 void *InsertPos = nullptr;
4731 DependentVectorType *Canon =
4732 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4733 DependentVectorType *New;
4734
4735 if (Canon) {
4736 New = new (*this, alignof(DependentVectorType)) DependentVectorType(
4737 VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind);
4738 } else {
4739 QualType CanonVecTy = getCanonicalType(T: VecType);
4740 if (CanonVecTy == VecType) {
4741 New = new (*this, alignof(DependentVectorType))
4742 DependentVectorType(VecType, QualType(), SizeExpr, AttrLoc, VecKind);
4743
4744 DependentVectorType *CanonCheck =
4745 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4746 assert(!CanonCheck &&
4747 "Dependent-sized vector_size canonical type broken");
4748 (void)CanonCheck;
4749 DependentVectorTypes.InsertNode(N: New, InsertPos);
4750 } else {
4751 QualType CanonTy = getDependentVectorType(VecType: CanonVecTy, SizeExpr,
4752 AttrLoc: SourceLocation(), VecKind);
4753 New = new (*this, alignof(DependentVectorType))
4754 DependentVectorType(VecType, CanonTy, SizeExpr, AttrLoc, VecKind);
4755 }
4756 }
4757
4758 Types.push_back(Elt: New);
4759 return QualType(New, 0);
4760}
4761
4762/// getExtVectorType - Return the unique reference to an extended vector type of
4763/// the specified element type and size. VectorType must be a built-in type.
4764QualType ASTContext::getExtVectorType(QualType vecType,
4765 unsigned NumElts) const {
4766 assert(vecType->isBuiltinType() || vecType->isDependentType() ||
4767 (vecType->isBitIntType() &&
4768 // Only support _BitInt elements with byte-sized power of 2 NumBits.
4769 llvm::isPowerOf2_32(vecType->castAs<BitIntType>()->getNumBits())));
4770
4771 // Check if we've already instantiated a vector of this type.
4772 llvm::FoldingSetNodeID ID;
4773 VectorType::Profile(ID, ElementType: vecType, NumElements: NumElts, TypeClass: Type::ExtVector,
4774 VecKind: VectorKind::Generic);
4775 void *InsertPos = nullptr;
4776 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
4777 return QualType(VTP, 0);
4778
4779 // If the element type isn't canonical, this won't be a canonical type either,
4780 // so fill in the canonical type field.
4781 QualType Canonical;
4782 if (!vecType.isCanonical()) {
4783 Canonical = getExtVectorType(vecType: getCanonicalType(T: vecType), NumElts);
4784
4785 // Get the new insert position for the node we care about.
4786 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4787 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4788 }
4789 auto *New = new (*this, alignof(ExtVectorType))
4790 ExtVectorType(vecType, NumElts, Canonical);
4791 VectorTypes.InsertNode(N: New, InsertPos);
4792 Types.push_back(Elt: New);
4793 return QualType(New, 0);
4794}
4795
4796QualType
4797ASTContext::getDependentSizedExtVectorType(QualType vecType,
4798 Expr *SizeExpr,
4799 SourceLocation AttrLoc) const {
4800 llvm::FoldingSetNodeID ID;
4801 DependentSizedExtVectorType::Profile(ID, Context: *this, ElementType: getCanonicalType(T: vecType),
4802 SizeExpr);
4803
4804 void *InsertPos = nullptr;
4805 DependentSizedExtVectorType *Canon
4806 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4807 DependentSizedExtVectorType *New;
4808 if (Canon) {
4809 // We already have a canonical version of this array type; use it as
4810 // the canonical type for a newly-built type.
4811 New = new (*this, alignof(DependentSizedExtVectorType))
4812 DependentSizedExtVectorType(vecType, QualType(Canon, 0), SizeExpr,
4813 AttrLoc);
4814 } else {
4815 QualType CanonVecTy = getCanonicalType(T: vecType);
4816 if (CanonVecTy == vecType) {
4817 New = new (*this, alignof(DependentSizedExtVectorType))
4818 DependentSizedExtVectorType(vecType, QualType(), SizeExpr, AttrLoc);
4819
4820 DependentSizedExtVectorType *CanonCheck
4821 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4822 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
4823 (void)CanonCheck;
4824 DependentSizedExtVectorTypes.InsertNode(N: New, InsertPos);
4825 } else {
4826 QualType CanonExtTy = getDependentSizedExtVectorType(vecType: CanonVecTy, SizeExpr,
4827 AttrLoc: SourceLocation());
4828 New = new (*this, alignof(DependentSizedExtVectorType))
4829 DependentSizedExtVectorType(vecType, CanonExtTy, SizeExpr, AttrLoc);
4830 }
4831 }
4832
4833 Types.push_back(Elt: New);
4834 return QualType(New, 0);
4835}
4836
4837QualType ASTContext::getConstantMatrixType(QualType ElementTy, unsigned NumRows,
4838 unsigned NumColumns) const {
4839 llvm::FoldingSetNodeID ID;
4840 ConstantMatrixType::Profile(ID, ElementType: ElementTy, NumRows, NumColumns,
4841 TypeClass: Type::ConstantMatrix);
4842
4843 assert(MatrixType::isValidElementType(ElementTy, getLangOpts()) &&
4844 "need a valid element type");
4845 assert(NumRows > 0 && NumRows <= LangOpts.MaxMatrixDimension &&
4846 NumColumns > 0 && NumColumns <= LangOpts.MaxMatrixDimension &&
4847 "need valid matrix dimensions");
4848 void *InsertPos = nullptr;
4849 if (ConstantMatrixType *MTP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos))
4850 return QualType(MTP, 0);
4851
4852 QualType Canonical;
4853 if (!ElementTy.isCanonical()) {
4854 Canonical =
4855 getConstantMatrixType(ElementTy: getCanonicalType(T: ElementTy), NumRows, NumColumns);
4856
4857 ConstantMatrixType *NewIP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4858 assert(!NewIP && "Matrix type shouldn't already exist in the map");
4859 (void)NewIP;
4860 }
4861
4862 auto *New = new (*this, alignof(ConstantMatrixType))
4863 ConstantMatrixType(ElementTy, NumRows, NumColumns, Canonical);
4864 MatrixTypes.InsertNode(N: New, InsertPos);
4865 Types.push_back(Elt: New);
4866 return QualType(New, 0);
4867}
4868
4869QualType ASTContext::getDependentSizedMatrixType(QualType ElementTy,
4870 Expr *RowExpr,
4871 Expr *ColumnExpr,
4872 SourceLocation AttrLoc) const {
4873 QualType CanonElementTy = getCanonicalType(T: ElementTy);
4874 llvm::FoldingSetNodeID ID;
4875 DependentSizedMatrixType::Profile(ID, Context: *this, ElementType: CanonElementTy, RowExpr,
4876 ColumnExpr);
4877
4878 void *InsertPos = nullptr;
4879 DependentSizedMatrixType *Canon =
4880 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4881
4882 if (!Canon) {
4883 Canon = new (*this, alignof(DependentSizedMatrixType))
4884 DependentSizedMatrixType(CanonElementTy, QualType(), RowExpr,
4885 ColumnExpr, AttrLoc);
4886#ifndef NDEBUG
4887 DependentSizedMatrixType *CanonCheck =
4888 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4889 assert(!CanonCheck && "Dependent-sized matrix canonical type broken");
4890#endif
4891 DependentSizedMatrixTypes.InsertNode(N: Canon, InsertPos);
4892 Types.push_back(Elt: Canon);
4893 }
4894
4895 // Already have a canonical version of the matrix type
4896 //
4897 // If it exactly matches the requested type, use it directly.
4898 if (Canon->getElementType() == ElementTy && Canon->getRowExpr() == RowExpr &&
4899 Canon->getRowExpr() == ColumnExpr)
4900 return QualType(Canon, 0);
4901
4902 // Use Canon as the canonical type for newly-built type.
4903 DependentSizedMatrixType *New = new (*this, alignof(DependentSizedMatrixType))
4904 DependentSizedMatrixType(ElementTy, QualType(Canon, 0), RowExpr,
4905 ColumnExpr, AttrLoc);
4906 Types.push_back(Elt: New);
4907 return QualType(New, 0);
4908}
4909
4910QualType ASTContext::getDependentAddressSpaceType(QualType PointeeType,
4911 Expr *AddrSpaceExpr,
4912 SourceLocation AttrLoc) const {
4913 assert(AddrSpaceExpr->isInstantiationDependent());
4914
4915 QualType canonPointeeType = getCanonicalType(T: PointeeType);
4916
4917 void *insertPos = nullptr;
4918 llvm::FoldingSetNodeID ID;
4919 DependentAddressSpaceType::Profile(ID, Context: *this, PointeeType: canonPointeeType,
4920 AddrSpaceExpr);
4921
4922 DependentAddressSpaceType *canonTy =
4923 DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, InsertPos&: insertPos);
4924
4925 if (!canonTy) {
4926 canonTy = new (*this, alignof(DependentAddressSpaceType))
4927 DependentAddressSpaceType(canonPointeeType, QualType(), AddrSpaceExpr,
4928 AttrLoc);
4929 DependentAddressSpaceTypes.InsertNode(N: canonTy, InsertPos: insertPos);
4930 Types.push_back(Elt: canonTy);
4931 }
4932
4933 if (canonPointeeType == PointeeType &&
4934 canonTy->getAddrSpaceExpr() == AddrSpaceExpr)
4935 return QualType(canonTy, 0);
4936
4937 auto *sugaredType = new (*this, alignof(DependentAddressSpaceType))
4938 DependentAddressSpaceType(PointeeType, QualType(canonTy, 0),
4939 AddrSpaceExpr, AttrLoc);
4940 Types.push_back(Elt: sugaredType);
4941 return QualType(sugaredType, 0);
4942}
4943
4944/// Determine whether \p T is canonical as the result type of a function.
4945static bool isCanonicalResultType(QualType T) {
4946 return T.isCanonical() &&
4947 (T.getObjCLifetime() == Qualifiers::OCL_None ||
4948 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
4949}
4950
4951/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
4952QualType
4953ASTContext::getFunctionNoProtoType(QualType ResultTy,
4954 const FunctionType::ExtInfo &Info) const {
4955 // FIXME: This assertion cannot be enabled (yet) because the ObjC rewriter
4956 // functionality creates a function without a prototype regardless of
4957 // language mode (so it makes them even in C++). Once the rewriter has been
4958 // fixed, this assertion can be enabled again.
4959 //assert(!LangOpts.requiresStrictPrototypes() &&
4960 // "strict prototypes are disabled");
4961
4962 // Unique functions, to guarantee there is only one function of a particular
4963 // structure.
4964 llvm::FoldingSetNodeID ID;
4965 FunctionNoProtoType::Profile(ID, ResultType: ResultTy, Info);
4966
4967 void *InsertPos = nullptr;
4968 if (FunctionNoProtoType *FT =
4969 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
4970 return QualType(FT, 0);
4971
4972 QualType Canonical;
4973 if (!isCanonicalResultType(T: ResultTy)) {
4974 Canonical =
4975 getFunctionNoProtoType(ResultTy: getCanonicalFunctionResultType(ResultType: ResultTy), Info);
4976
4977 // Get the new insert position for the node we care about.
4978 FunctionNoProtoType *NewIP =
4979 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
4980 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4981 }
4982
4983 auto *New = new (*this, alignof(FunctionNoProtoType))
4984 FunctionNoProtoType(ResultTy, Canonical, Info);
4985 Types.push_back(Elt: New);
4986 FunctionNoProtoTypes.InsertNode(N: New, InsertPos);
4987 return QualType(New, 0);
4988}
4989
4990CanQualType
4991ASTContext::getCanonicalFunctionResultType(QualType ResultType) const {
4992 CanQualType CanResultType = getCanonicalType(T: ResultType);
4993
4994 // Canonical result types do not have ARC lifetime qualifiers.
4995 if (CanResultType.getQualifiers().hasObjCLifetime()) {
4996 Qualifiers Qs = CanResultType.getQualifiers();
4997 Qs.removeObjCLifetime();
4998 return CanQualType::CreateUnsafe(
4999 Other: getQualifiedType(T: CanResultType.getUnqualifiedType(), Qs));
5000 }
5001
5002 return CanResultType;
5003}
5004
5005static bool isCanonicalExceptionSpecification(
5006 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
5007 if (ESI.Type == EST_None)
5008 return true;
5009 if (!NoexceptInType)
5010 return false;
5011
5012 // C++17 onwards: exception specification is part of the type, as a simple
5013 // boolean "can this function type throw".
5014 if (ESI.Type == EST_BasicNoexcept)
5015 return true;
5016
5017 // A noexcept(expr) specification is (possibly) canonical if expr is
5018 // value-dependent.
5019 if (ESI.Type == EST_DependentNoexcept)
5020 return true;
5021
5022 // A dynamic exception specification is canonical if it only contains pack
5023 // expansions (so we can't tell whether it's non-throwing) and all its
5024 // contained types are canonical.
5025 if (ESI.Type == EST_Dynamic) {
5026 bool AnyPackExpansions = false;
5027 for (QualType ET : ESI.Exceptions) {
5028 if (!ET.isCanonical())
5029 return false;
5030 if (ET->getAs<PackExpansionType>())
5031 AnyPackExpansions = true;
5032 }
5033 return AnyPackExpansions;
5034 }
5035
5036 return false;
5037}
5038
5039QualType ASTContext::getFunctionTypeInternal(
5040 QualType ResultTy, ArrayRef<QualType> ArgArray,
5041 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
5042 size_t NumArgs = ArgArray.size();
5043
5044 // Unique functions, to guarantee there is only one function of a particular
5045 // structure.
5046 llvm::FoldingSetNodeID ID;
5047 FunctionProtoType::Profile(ID, Result: ResultTy, ArgTys: ArgArray.begin(), NumArgs, EPI,
5048 Context: *this, Canonical: true);
5049
5050 QualType Canonical;
5051 bool Unique = false;
5052
5053 void *InsertPos = nullptr;
5054 if (FunctionProtoType *FPT =
5055 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
5056 QualType Existing = QualType(FPT, 0);
5057
5058 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
5059 // it so long as our exception specification doesn't contain a dependent
5060 // noexcept expression, or we're just looking for a canonical type.
5061 // Otherwise, we're going to need to create a type
5062 // sugar node to hold the concrete expression.
5063 if (OnlyWantCanonical || !isComputedNoexcept(ESpecType: EPI.ExceptionSpec.Type) ||
5064 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
5065 return Existing;
5066
5067 // We need a new type sugar node for this one, to hold the new noexcept
5068 // expression. We do no canonicalization here, but that's OK since we don't
5069 // expect to see the same noexcept expression much more than once.
5070 Canonical = getCanonicalType(T: Existing);
5071 Unique = true;
5072 }
5073
5074 bool NoexceptInType = getLangOpts().CPlusPlus17;
5075 bool IsCanonicalExceptionSpec =
5076 isCanonicalExceptionSpecification(ESI: EPI.ExceptionSpec, NoexceptInType);
5077
5078 // Determine whether the type being created is already canonical or not.
5079 bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
5080 isCanonicalResultType(T: ResultTy) && !EPI.HasTrailingReturn;
5081 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
5082 if (!ArgArray[i].isCanonicalAsParam())
5083 isCanonical = false;
5084
5085 if (OnlyWantCanonical)
5086 assert(isCanonical &&
5087 "given non-canonical parameters constructing canonical type");
5088
5089 // If this type isn't canonical, get the canonical version of it if we don't
5090 // already have it. The exception spec is only partially part of the
5091 // canonical type, and only in C++17 onwards.
5092 if (!isCanonical && Canonical.isNull()) {
5093 SmallVector<QualType, 16> CanonicalArgs;
5094 CanonicalArgs.reserve(N: NumArgs);
5095 for (unsigned i = 0; i != NumArgs; ++i)
5096 CanonicalArgs.push_back(Elt: getCanonicalParamType(T: ArgArray[i]));
5097
5098 llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
5099 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
5100 CanonicalEPI.HasTrailingReturn = false;
5101
5102 if (IsCanonicalExceptionSpec) {
5103 // Exception spec is already OK.
5104 } else if (NoexceptInType) {
5105 switch (EPI.ExceptionSpec.Type) {
5106 case EST_Unparsed: case EST_Unevaluated: case EST_Uninstantiated:
5107 // We don't know yet. It shouldn't matter what we pick here; no-one
5108 // should ever look at this.
5109 [[fallthrough]];
5110 case EST_None: case EST_MSAny: case EST_NoexceptFalse:
5111 CanonicalEPI.ExceptionSpec.Type = EST_None;
5112 break;
5113
5114 // A dynamic exception specification is almost always "not noexcept",
5115 // with the exception that a pack expansion might expand to no types.
5116 case EST_Dynamic: {
5117 bool AnyPacks = false;
5118 for (QualType ET : EPI.ExceptionSpec.Exceptions) {
5119 if (ET->getAs<PackExpansionType>())
5120 AnyPacks = true;
5121 ExceptionTypeStorage.push_back(Elt: getCanonicalType(T: ET));
5122 }
5123 if (!AnyPacks)
5124 CanonicalEPI.ExceptionSpec.Type = EST_None;
5125 else {
5126 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
5127 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
5128 }
5129 break;
5130 }
5131
5132 case EST_DynamicNone:
5133 case EST_BasicNoexcept:
5134 case EST_NoexceptTrue:
5135 case EST_NoThrow:
5136 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
5137 break;
5138
5139 case EST_DependentNoexcept:
5140 llvm_unreachable("dependent noexcept is already canonical");
5141 }
5142 } else {
5143 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
5144 }
5145
5146 // Adjust the canonical function result type.
5147 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultType: ResultTy);
5148 Canonical =
5149 getFunctionTypeInternal(ResultTy: CanResultTy, ArgArray: CanonicalArgs, EPI: CanonicalEPI, OnlyWantCanonical: true);
5150
5151 // Get the new insert position for the node we care about.
5152 FunctionProtoType *NewIP =
5153 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
5154 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
5155 }
5156
5157 // Compute the needed size to hold this FunctionProtoType and the
5158 // various trailing objects.
5159 auto ESH = FunctionProtoType::getExceptionSpecSize(
5160 EST: EPI.ExceptionSpec.Type, NumExceptions: EPI.ExceptionSpec.Exceptions.size());
5161 size_t Size = FunctionProtoType::totalSizeToAlloc<
5162 QualType, SourceLocation, FunctionType::FunctionTypeExtraBitfields,
5163 FunctionType::FunctionTypeExtraAttributeInfo,
5164 FunctionType::FunctionTypeArmAttributes, FunctionType::ExceptionType,
5165 Expr *, FunctionDecl *, FunctionProtoType::ExtParameterInfo, Qualifiers,
5166 FunctionEffect, EffectConditionExpr>(
5167 Counts: NumArgs, Counts: EPI.Variadic, Counts: EPI.requiresFunctionProtoTypeExtraBitfields(),
5168 Counts: EPI.requiresFunctionProtoTypeExtraAttributeInfo(),
5169 Counts: EPI.requiresFunctionProtoTypeArmAttributes(), Counts: ESH.NumExceptionType,
5170 Counts: ESH.NumExprPtr, Counts: ESH.NumFunctionDeclPtr,
5171 Counts: EPI.ExtParameterInfos ? NumArgs : 0,
5172 Counts: EPI.TypeQuals.hasNonFastQualifiers() ? 1 : 0, Counts: EPI.FunctionEffects.size(),
5173 Counts: EPI.FunctionEffects.conditions().size());
5174
5175 auto *FTP = (FunctionProtoType *)Allocate(Size, Align: alignof(FunctionProtoType));
5176 FunctionProtoType::ExtProtoInfo newEPI = EPI;
5177 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
5178 Types.push_back(Elt: FTP);
5179 if (!Unique)
5180 FunctionProtoTypes.InsertNode(N: FTP, InsertPos);
5181 if (!EPI.FunctionEffects.empty())
5182 AnyFunctionEffects = true;
5183 return QualType(FTP, 0);
5184}
5185
5186QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
5187 llvm::FoldingSetNodeID ID;
5188 PipeType::Profile(ID, T, isRead: ReadOnly);
5189
5190 void *InsertPos = nullptr;
5191 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
5192 return QualType(PT, 0);
5193
5194 // If the pipe element type isn't canonical, this won't be a canonical type
5195 // either, so fill in the canonical type field.
5196 QualType Canonical;
5197 if (!T.isCanonical()) {
5198 Canonical = getPipeType(T: getCanonicalType(T), ReadOnly);
5199
5200 // Get the new insert position for the node we care about.
5201 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
5202 assert(!NewIP && "Shouldn't be in the map!");
5203 (void)NewIP;
5204 }
5205 auto *New = new (*this, alignof(PipeType)) PipeType(T, Canonical, ReadOnly);
5206 Types.push_back(Elt: New);
5207 PipeTypes.InsertNode(N: New, InsertPos);
5208 return QualType(New, 0);
5209}
5210
5211QualType ASTContext::adjustStringLiteralBaseType(QualType Ty) const {
5212 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
5213 return LangOpts.OpenCL ? getAddrSpaceQualType(T: Ty, AddressSpace: LangAS::opencl_constant)
5214 : Ty;
5215}
5216
5217QualType ASTContext::getReadPipeType(QualType T) const {
5218 return getPipeType(T, ReadOnly: true);
5219}
5220
5221QualType ASTContext::getWritePipeType(QualType T) const {
5222 return getPipeType(T, ReadOnly: false);
5223}
5224
5225QualType ASTContext::getBitIntType(bool IsUnsigned, unsigned NumBits) const {
5226 llvm::FoldingSetNodeID ID;
5227 BitIntType::Profile(ID, IsUnsigned, NumBits);
5228
5229 void *InsertPos = nullptr;
5230 if (BitIntType *EIT = BitIntTypes.FindNodeOrInsertPos(ID, InsertPos))
5231 return QualType(EIT, 0);
5232
5233 auto *New = new (*this, alignof(BitIntType)) BitIntType(IsUnsigned, NumBits);
5234 BitIntTypes.InsertNode(N: New, InsertPos);
5235 Types.push_back(Elt: New);
5236 return QualType(New, 0);
5237}
5238
5239QualType ASTContext::getDependentBitIntType(bool IsUnsigned,
5240 Expr *NumBitsExpr) const {
5241 assert(NumBitsExpr->isInstantiationDependent() && "Only good for dependent");
5242 llvm::FoldingSetNodeID ID;
5243 DependentBitIntType::Profile(ID, Context: *this, IsUnsigned, NumBitsExpr);
5244
5245 void *InsertPos = nullptr;
5246 if (DependentBitIntType *Existing =
5247 DependentBitIntTypes.FindNodeOrInsertPos(ID, InsertPos))
5248 return QualType(Existing, 0);
5249
5250 auto *New = new (*this, alignof(DependentBitIntType))
5251 DependentBitIntType(IsUnsigned, NumBitsExpr);
5252 DependentBitIntTypes.InsertNode(N: New, InsertPos);
5253
5254 Types.push_back(Elt: New);
5255 return QualType(New, 0);
5256}
5257
5258QualType
5259ASTContext::getPredefinedSugarType(PredefinedSugarType::Kind KD) const {
5260 using Kind = PredefinedSugarType::Kind;
5261
5262 if (auto *Target = PredefinedSugarTypes[llvm::to_underlying(E: KD)];
5263 Target != nullptr)
5264 return QualType(Target, 0);
5265
5266 auto getCanonicalType = [](const ASTContext &Ctx, Kind KDI) -> QualType {
5267 switch (KDI) {
5268 // size_t (C99TC3 6.5.3.4), signed size_t (C++23 5.13.2) and
5269 // ptrdiff_t (C99TC3 6.5.6) Although these types are not built-in, they
5270 // are part of the core language and are widely used. Using
5271 // PredefinedSugarType makes these types as named sugar types rather than
5272 // standard integer types, enabling better hints and diagnostics.
5273 case Kind::SizeT:
5274 return Ctx.getFromTargetType(Type: Ctx.Target->getSizeType());
5275 case Kind::SignedSizeT:
5276 return Ctx.getFromTargetType(Type: Ctx.Target->getSignedSizeType());
5277 case Kind::PtrdiffT:
5278 return Ctx.getFromTargetType(Type: Ctx.Target->getPtrDiffType(AddrSpace: LangAS::Default));
5279 }
5280 llvm_unreachable("unexpected kind");
5281 };
5282 auto *New = new (*this, alignof(PredefinedSugarType))
5283 PredefinedSugarType(KD, &Idents.get(Name: PredefinedSugarType::getName(KD)),
5284 getCanonicalType(*this, static_cast<Kind>(KD)));
5285 Types.push_back(Elt: New);
5286 PredefinedSugarTypes[llvm::to_underlying(E: KD)] = New;
5287 return QualType(New, 0);
5288}
5289
5290QualType ASTContext::getTypeDeclType(ElaboratedTypeKeyword Keyword,
5291 NestedNameSpecifier Qualifier,
5292 const TypeDecl *Decl) const {
5293 if (auto *Tag = dyn_cast<TagDecl>(Val: Decl))
5294 return getTagType(Keyword, Qualifier, TD: Tag,
5295 /*OwnsTag=*/false);
5296 if (auto *Typedef = dyn_cast<TypedefNameDecl>(Val: Decl))
5297 return getTypedefType(Keyword, Qualifier, Decl: Typedef);
5298 if (auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(Val: Decl))
5299 return getUnresolvedUsingType(Keyword, Qualifier, D: UD);
5300
5301 assert(Keyword == ElaboratedTypeKeyword::None);
5302 assert(!Qualifier);
5303 return QualType(Decl->TypeForDecl, 0);
5304}
5305
5306CanQualType ASTContext::getCanonicalTypeDeclType(const TypeDecl *TD) const {
5307 if (auto *Tag = dyn_cast<TagDecl>(Val: TD))
5308 return getCanonicalTagType(TD: Tag);
5309 if (auto *TN = dyn_cast<TypedefNameDecl>(Val: TD))
5310 return getCanonicalType(T: TN->getUnderlyingType());
5311 if (const auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(Val: TD))
5312 return getCanonicalUnresolvedUsingType(D: UD);
5313 assert(TD->TypeForDecl);
5314 return TD->TypeForDecl->getCanonicalTypeUnqualified();
5315}
5316
5317QualType ASTContext::getTypeDeclType(const TypeDecl *Decl) const {
5318 if (const auto *TD = dyn_cast<TagDecl>(Val: Decl))
5319 return getCanonicalTagType(TD);
5320 if (const auto *TD = dyn_cast<TypedefNameDecl>(Val: Decl);
5321 isa_and_nonnull<TypedefDecl, TypeAliasDecl>(Val: TD))
5322 return getTypedefType(Keyword: ElaboratedTypeKeyword::None,
5323 /*Qualifier=*/std::nullopt, Decl: TD);
5324 if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Val: Decl))
5325 return getCanonicalUnresolvedUsingType(D: Using);
5326
5327 assert(Decl->TypeForDecl);
5328 return QualType(Decl->TypeForDecl, 0);
5329}
5330
5331/// getTypedefType - Return the unique reference to the type for the
5332/// specified typedef name decl.
5333QualType
5334ASTContext::getTypedefType(ElaboratedTypeKeyword Keyword,
5335 NestedNameSpecifier Qualifier,
5336 const TypedefNameDecl *Decl, QualType UnderlyingType,
5337 std::optional<bool> TypeMatchesDeclOrNone) const {
5338 if (!TypeMatchesDeclOrNone) {
5339 QualType DeclUnderlyingType = Decl->getUnderlyingType();
5340 assert(!DeclUnderlyingType.isNull());
5341 if (UnderlyingType.isNull())
5342 UnderlyingType = DeclUnderlyingType;
5343 else
5344 assert(hasSameType(UnderlyingType, DeclUnderlyingType));
5345 TypeMatchesDeclOrNone = UnderlyingType == DeclUnderlyingType;
5346 } else {
5347 // FIXME: This is a workaround for a serialization cycle: assume the decl
5348 // underlying type is not available; don't touch it.
5349 assert(!UnderlyingType.isNull());
5350 }
5351
5352 if (Keyword == ElaboratedTypeKeyword::None && !Qualifier &&
5353 *TypeMatchesDeclOrNone) {
5354 if (Decl->TypeForDecl)
5355 return QualType(Decl->TypeForDecl, 0);
5356
5357 auto *NewType = new (*this, alignof(TypedefType))
5358 TypedefType(Type::Typedef, Keyword, Qualifier, Decl, UnderlyingType,
5359 !*TypeMatchesDeclOrNone);
5360
5361 Types.push_back(Elt: NewType);
5362 Decl->TypeForDecl = NewType;
5363 return QualType(NewType, 0);
5364 }
5365
5366 llvm::FoldingSetNodeID ID;
5367 TypedefType::Profile(ID, Keyword, Qualifier, Decl,
5368 Underlying: *TypeMatchesDeclOrNone ? QualType() : UnderlyingType);
5369
5370 void *InsertPos = nullptr;
5371 if (FoldingSetPlaceholder<TypedefType> *Placeholder =
5372 TypedefTypes.FindNodeOrInsertPos(ID, InsertPos))
5373 return QualType(Placeholder->getType(), 0);
5374
5375 void *Mem =
5376 Allocate(Size: TypedefType::totalSizeToAlloc<FoldingSetPlaceholder<TypedefType>,
5377 NestedNameSpecifier, QualType>(
5378 Counts: 1, Counts: !!Qualifier, Counts: !*TypeMatchesDeclOrNone),
5379 Align: alignof(TypedefType));
5380 auto *NewType =
5381 new (Mem) TypedefType(Type::Typedef, Keyword, Qualifier, Decl,
5382 UnderlyingType, !*TypeMatchesDeclOrNone);
5383 auto *Placeholder = new (NewType->getFoldingSetPlaceholder())
5384 FoldingSetPlaceholder<TypedefType>();
5385 TypedefTypes.InsertNode(N: Placeholder, InsertPos);
5386 Types.push_back(Elt: NewType);
5387 return QualType(NewType, 0);
5388}
5389
5390QualType ASTContext::getUsingType(ElaboratedTypeKeyword Keyword,
5391 NestedNameSpecifier Qualifier,
5392 const UsingShadowDecl *D,
5393 QualType UnderlyingType) const {
5394 // FIXME: This is expensive to compute every time!
5395 if (UnderlyingType.isNull()) {
5396 const auto *UD = cast<UsingDecl>(Val: D->getIntroducer());
5397 UnderlyingType =
5398 getTypeDeclType(Keyword: UD->hasTypename() ? ElaboratedTypeKeyword::Typename
5399 : ElaboratedTypeKeyword::None,
5400 Qualifier: UD->getQualifier(), Decl: cast<TypeDecl>(Val: D->getTargetDecl()));
5401 }
5402
5403 llvm::FoldingSetNodeID ID;
5404 UsingType::Profile(ID, Keyword, Qualifier, D, UnderlyingType);
5405
5406 void *InsertPos = nullptr;
5407 if (const UsingType *T = UsingTypes.FindNodeOrInsertPos(ID, InsertPos))
5408 return QualType(T, 0);
5409
5410 assert(!UnderlyingType.hasLocalQualifiers());
5411
5412 assert(
5413 hasSameType(getCanonicalTypeDeclType(cast<TypeDecl>(D->getTargetDecl())),
5414 UnderlyingType));
5415
5416 void *Mem =
5417 Allocate(Size: UsingType::totalSizeToAlloc<NestedNameSpecifier>(Counts: !!Qualifier),
5418 Align: alignof(UsingType));
5419 UsingType *T = new (Mem) UsingType(Keyword, Qualifier, D, UnderlyingType);
5420 Types.push_back(Elt: T);
5421 UsingTypes.InsertNode(N: T, InsertPos);
5422 return QualType(T, 0);
5423}
5424
5425TagType *ASTContext::getTagTypeInternal(ElaboratedTypeKeyword Keyword,
5426 NestedNameSpecifier Qualifier,
5427 const TagDecl *TD, bool OwnsTag,
5428 bool IsInjected,
5429 const Type *CanonicalType,
5430 bool WithFoldingSetNode) const {
5431 auto [TC, Size] = [&] {
5432 switch (TD->getDeclKind()) {
5433 case Decl::Enum:
5434 static_assert(alignof(EnumType) == alignof(TagType));
5435 return std::make_tuple(args: Type::Enum, args: sizeof(EnumType));
5436 case Decl::ClassTemplatePartialSpecialization:
5437 case Decl::ClassTemplateSpecialization:
5438 case Decl::CXXRecord:
5439 static_assert(alignof(RecordType) == alignof(TagType));
5440 static_assert(alignof(InjectedClassNameType) == alignof(TagType));
5441 if (cast<CXXRecordDecl>(Val: TD)->hasInjectedClassType())
5442 return std::make_tuple(args: Type::InjectedClassName,
5443 args: sizeof(InjectedClassNameType));
5444 [[fallthrough]];
5445 case Decl::Record:
5446 return std::make_tuple(args: Type::Record, args: sizeof(RecordType));
5447 default:
5448 llvm_unreachable("unexpected decl kind");
5449 }
5450 }();
5451
5452 if (Qualifier) {
5453 static_assert(alignof(NestedNameSpecifier) <= alignof(TagType));
5454 Size = llvm::alignTo(Value: Size, Align: alignof(NestedNameSpecifier)) +
5455 sizeof(NestedNameSpecifier);
5456 }
5457 void *Mem;
5458 if (WithFoldingSetNode) {
5459 // FIXME: It would be more profitable to tail allocate the folding set node
5460 // from the type, instead of the other way around, due to the greater
5461 // alignment requirements of the type. But this makes it harder to deal with
5462 // the different type node sizes. This would require either uniquing from
5463 // different folding sets, or having the folding setaccept a
5464 // contextual parameter which is not fixed at construction.
5465 Mem = Allocate(
5466 Size: sizeof(TagTypeFoldingSetPlaceholder) +
5467 TagTypeFoldingSetPlaceholder::getOffset() + Size,
5468 Align: std::max(a: alignof(TagTypeFoldingSetPlaceholder), b: alignof(TagType)));
5469 auto *T = new (Mem) TagTypeFoldingSetPlaceholder();
5470 Mem = T->getTagType();
5471 } else {
5472 Mem = Allocate(Size, Align: alignof(TagType));
5473 }
5474
5475 auto *T = [&, TC = TC]() -> TagType * {
5476 switch (TC) {
5477 case Type::Enum: {
5478 assert(isa<EnumDecl>(TD));
5479 auto *T = new (Mem) EnumType(TC, Keyword, Qualifier, TD, OwnsTag,
5480 IsInjected, CanonicalType);
5481 assert(reinterpret_cast<void *>(T) ==
5482 reinterpret_cast<void *>(static_cast<TagType *>(T)) &&
5483 "TagType must be the first base of EnumType");
5484 return T;
5485 }
5486 case Type::Record: {
5487 assert(isa<RecordDecl>(TD));
5488 auto *T = new (Mem) RecordType(TC, Keyword, Qualifier, TD, OwnsTag,
5489 IsInjected, CanonicalType);
5490 assert(reinterpret_cast<void *>(T) ==
5491 reinterpret_cast<void *>(static_cast<TagType *>(T)) &&
5492 "TagType must be the first base of RecordType");
5493 return T;
5494 }
5495 case Type::InjectedClassName: {
5496 auto *T = new (Mem) InjectedClassNameType(Keyword, Qualifier, TD,
5497 IsInjected, CanonicalType);
5498 assert(reinterpret_cast<void *>(T) ==
5499 reinterpret_cast<void *>(static_cast<TagType *>(T)) &&
5500 "TagType must be the first base of InjectedClassNameType");
5501 return T;
5502 }
5503 default:
5504 llvm_unreachable("unexpected type class");
5505 }
5506 }();
5507 assert(T->getKeyword() == Keyword);
5508 assert(T->getQualifier() == Qualifier);
5509 assert(T->getDecl() == TD);
5510 assert(T->isInjected() == IsInjected);
5511 assert(T->isTagOwned() == OwnsTag);
5512 assert((T->isCanonicalUnqualified()
5513 ? QualType()
5514 : T->getCanonicalTypeInternal()) == QualType(CanonicalType, 0));
5515 Types.push_back(Elt: T);
5516 return T;
5517}
5518
5519static const TagDecl *getNonInjectedClassName(const TagDecl *TD) {
5520 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: TD);
5521 RD && RD->isInjectedClassName())
5522 return cast<TagDecl>(Val: RD->getDeclContext());
5523 return TD;
5524}
5525
5526CanQualType ASTContext::getCanonicalTagType(const TagDecl *TD) const {
5527 TD = ::getNonInjectedClassName(TD)->getCanonicalDecl();
5528 if (TD->TypeForDecl)
5529 return TD->TypeForDecl->getCanonicalTypeUnqualified();
5530
5531 const Type *CanonicalType = getTagTypeInternal(
5532 Keyword: ElaboratedTypeKeyword::None,
5533 /*Qualifier=*/std::nullopt, TD,
5534 /*OwnsTag=*/false, /*IsInjected=*/false, /*CanonicalType=*/nullptr,
5535 /*WithFoldingSetNode=*/false);
5536 TD->TypeForDecl = CanonicalType;
5537 return CanQualType::CreateUnsafe(Other: QualType(CanonicalType, 0));
5538}
5539
5540QualType ASTContext::getTagType(ElaboratedTypeKeyword Keyword,
5541 NestedNameSpecifier Qualifier,
5542 const TagDecl *TD, bool OwnsTag) const {
5543
5544 const TagDecl *NonInjectedTD = ::getNonInjectedClassName(TD);
5545 bool IsInjected = TD != NonInjectedTD;
5546
5547 ElaboratedTypeKeyword PreferredKeyword =
5548 getLangOpts().CPlusPlus ? ElaboratedTypeKeyword::None
5549 : KeywordHelpers::getKeywordForTagTypeKind(
5550 Tag: NonInjectedTD->getTagKind());
5551
5552 if (Keyword == PreferredKeyword && !Qualifier && !OwnsTag) {
5553 if (const Type *T = TD->TypeForDecl; T && !T->isCanonicalUnqualified())
5554 return QualType(T, 0);
5555
5556 const Type *CanonicalType = getCanonicalTagType(TD: NonInjectedTD).getTypePtr();
5557 const Type *T =
5558 getTagTypeInternal(Keyword,
5559 /*Qualifier=*/std::nullopt, TD: NonInjectedTD,
5560 /*OwnsTag=*/false, IsInjected, CanonicalType,
5561 /*WithFoldingSetNode=*/false);
5562 TD->TypeForDecl = T;
5563 return QualType(T, 0);
5564 }
5565
5566 llvm::FoldingSetNodeID ID;
5567 TagTypeFoldingSetPlaceholder::Profile(ID, Keyword, Qualifier, Tag: NonInjectedTD,
5568 OwnsTag, IsInjected);
5569
5570 void *InsertPos = nullptr;
5571 if (TagTypeFoldingSetPlaceholder *T =
5572 TagTypes.FindNodeOrInsertPos(ID, InsertPos))
5573 return QualType(T->getTagType(), 0);
5574
5575 const Type *CanonicalType = getCanonicalTagType(TD: NonInjectedTD).getTypePtr();
5576 TagType *T =
5577 getTagTypeInternal(Keyword, Qualifier, TD: NonInjectedTD, OwnsTag, IsInjected,
5578 CanonicalType, /*WithFoldingSetNode=*/true);
5579 TagTypes.InsertNode(N: TagTypeFoldingSetPlaceholder::fromTagType(T), InsertPos);
5580 return QualType(T, 0);
5581}
5582
5583bool ASTContext::computeBestEnumTypes(bool IsPacked, unsigned NumNegativeBits,
5584 unsigned NumPositiveBits,
5585 QualType &BestType,
5586 QualType &BestPromotionType) {
5587 unsigned IntWidth = Target->getIntWidth();
5588 unsigned CharWidth = Target->getCharWidth();
5589 unsigned ShortWidth = Target->getShortWidth();
5590 bool EnumTooLarge = false;
5591 unsigned BestWidth;
5592 if (NumNegativeBits) {
5593 // If there is a negative value, figure out the smallest integer type (of
5594 // int/long/longlong) that fits.
5595 // If it's packed, check also if it fits a char or a short.
5596 if (IsPacked && NumNegativeBits <= CharWidth &&
5597 NumPositiveBits < CharWidth) {
5598 BestType = SignedCharTy;
5599 BestWidth = CharWidth;
5600 } else if (IsPacked && NumNegativeBits <= ShortWidth &&
5601 NumPositiveBits < ShortWidth) {
5602 BestType = ShortTy;
5603 BestWidth = ShortWidth;
5604 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
5605 BestType = IntTy;
5606 BestWidth = IntWidth;
5607 } else {
5608 BestWidth = Target->getLongWidth();
5609
5610 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
5611 BestType = LongTy;
5612 } else {
5613 BestWidth = Target->getLongLongWidth();
5614
5615 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
5616 EnumTooLarge = true;
5617 BestType = LongLongTy;
5618 }
5619 }
5620 BestPromotionType = (BestWidth <= IntWidth ? IntTy : BestType);
5621 } else {
5622 // If there is no negative value, figure out the smallest type that fits
5623 // all of the enumerator values.
5624 // If it's packed, check also if it fits a char or a short.
5625 if (IsPacked && NumPositiveBits <= CharWidth) {
5626 BestType = UnsignedCharTy;
5627 BestPromotionType = IntTy;
5628 BestWidth = CharWidth;
5629 } else if (IsPacked && NumPositiveBits <= ShortWidth) {
5630 BestType = UnsignedShortTy;
5631 BestPromotionType = IntTy;
5632 BestWidth = ShortWidth;
5633 } else if (NumPositiveBits <= IntWidth) {
5634 BestType = UnsignedIntTy;
5635 BestWidth = IntWidth;
5636 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5637 ? UnsignedIntTy
5638 : IntTy;
5639 } else if (NumPositiveBits <= (BestWidth = Target->getLongWidth())) {
5640 BestType = UnsignedLongTy;
5641 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5642 ? UnsignedLongTy
5643 : LongTy;
5644 } else {
5645 BestWidth = Target->getLongLongWidth();
5646 if (NumPositiveBits > BestWidth) {
5647 // This can happen with bit-precise integer types, but those are not
5648 // allowed as the type for an enumerator per C23 6.7.2.2p4 and p12.
5649 // FIXME: GCC uses __int128_t and __uint128_t for cases that fit within
5650 // a 128-bit integer, we should consider doing the same.
5651 EnumTooLarge = true;
5652 }
5653 BestType = UnsignedLongLongTy;
5654 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5655 ? UnsignedLongLongTy
5656 : LongLongTy;
5657 }
5658 }
5659 return EnumTooLarge;
5660}
5661
5662bool ASTContext::isRepresentableIntegerValue(llvm::APSInt &Value, QualType T) {
5663 assert((T->isIntegralType(*this) || T->isEnumeralType()) &&
5664 "Integral type required!");
5665 unsigned BitWidth = getIntWidth(T);
5666
5667 if (Value.isUnsigned() || Value.isNonNegative()) {
5668 if (T->isSignedIntegerOrEnumerationType())
5669 --BitWidth;
5670 return Value.getActiveBits() <= BitWidth;
5671 }
5672 return Value.getSignificantBits() <= BitWidth;
5673}
5674
5675UnresolvedUsingType *ASTContext::getUnresolvedUsingTypeInternal(
5676 ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier,
5677 const UnresolvedUsingTypenameDecl *D, void *InsertPos,
5678 const Type *CanonicalType) const {
5679 void *Mem = Allocate(
5680 Size: UnresolvedUsingType::totalSizeToAlloc<
5681 FoldingSetPlaceholder<UnresolvedUsingType>, NestedNameSpecifier>(
5682 Counts: !!InsertPos, Counts: !!Qualifier),
5683 Align: alignof(UnresolvedUsingType));
5684 auto *T = new (Mem) UnresolvedUsingType(Keyword, Qualifier, D, CanonicalType);
5685 if (InsertPos) {
5686 auto *Placeholder = new (T->getFoldingSetPlaceholder())
5687 FoldingSetPlaceholder<TypedefType>();
5688 TypedefTypes.InsertNode(N: Placeholder, InsertPos);
5689 }
5690 Types.push_back(Elt: T);
5691 return T;
5692}
5693
5694CanQualType ASTContext::getCanonicalUnresolvedUsingType(
5695 const UnresolvedUsingTypenameDecl *D) const {
5696 D = D->getCanonicalDecl();
5697 if (D->TypeForDecl)
5698 return D->TypeForDecl->getCanonicalTypeUnqualified();
5699
5700 const Type *CanonicalType = getUnresolvedUsingTypeInternal(
5701 Keyword: ElaboratedTypeKeyword::None,
5702 /*Qualifier=*/std::nullopt, D,
5703 /*InsertPos=*/nullptr, /*CanonicalType=*/nullptr);
5704 D->TypeForDecl = CanonicalType;
5705 return CanQualType::CreateUnsafe(Other: QualType(CanonicalType, 0));
5706}
5707
5708QualType
5709ASTContext::getUnresolvedUsingType(ElaboratedTypeKeyword Keyword,
5710 NestedNameSpecifier Qualifier,
5711 const UnresolvedUsingTypenameDecl *D) const {
5712 if (Keyword == ElaboratedTypeKeyword::None && !Qualifier) {
5713 if (const Type *T = D->TypeForDecl; T && !T->isCanonicalUnqualified())
5714 return QualType(T, 0);
5715
5716 const Type *CanonicalType = getCanonicalUnresolvedUsingType(D).getTypePtr();
5717 const Type *T =
5718 getUnresolvedUsingTypeInternal(Keyword: ElaboratedTypeKeyword::None,
5719 /*Qualifier=*/std::nullopt, D,
5720 /*InsertPos=*/nullptr, CanonicalType);
5721 D->TypeForDecl = T;
5722 return QualType(T, 0);
5723 }
5724
5725 llvm::FoldingSetNodeID ID;
5726 UnresolvedUsingType::Profile(ID, Keyword, Qualifier, D);
5727
5728 void *InsertPos = nullptr;
5729 if (FoldingSetPlaceholder<UnresolvedUsingType> *Placeholder =
5730 UnresolvedUsingTypes.FindNodeOrInsertPos(ID, InsertPos))
5731 return QualType(Placeholder->getType(), 0);
5732 assert(InsertPos);
5733
5734 const Type *CanonicalType = getCanonicalUnresolvedUsingType(D).getTypePtr();
5735 const Type *T = getUnresolvedUsingTypeInternal(Keyword, Qualifier, D,
5736 InsertPos, CanonicalType);
5737 return QualType(T, 0);
5738}
5739
5740QualType ASTContext::getAttributedType(attr::Kind attrKind,
5741 QualType modifiedType,
5742 QualType equivalentType,
5743 const Attr *attr) const {
5744 llvm::FoldingSetNodeID id;
5745 AttributedType::Profile(ID&: id, Ctx: *this, attrKind, modified: modifiedType, equivalent: equivalentType,
5746 attr);
5747
5748 void *insertPos = nullptr;
5749 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(ID: id, InsertPos&: insertPos);
5750 if (type) return QualType(type, 0);
5751
5752 assert(!attr || attr->getKind() == attrKind);
5753
5754 QualType canon = getCanonicalType(T: equivalentType);
5755 type = new (*this, alignof(AttributedType))
5756 AttributedType(canon, attrKind, attr, modifiedType, equivalentType);
5757
5758 Types.push_back(Elt: type);
5759 AttributedTypes.InsertNode(N: type, InsertPos: insertPos);
5760
5761 return QualType(type, 0);
5762}
5763
5764QualType ASTContext::getAttributedType(const Attr *attr, QualType modifiedType,
5765 QualType equivalentType) const {
5766 return getAttributedType(attrKind: attr->getKind(), modifiedType, equivalentType, attr);
5767}
5768
5769QualType ASTContext::getAttributedType(NullabilityKind nullability,
5770 QualType modifiedType,
5771 QualType equivalentType) {
5772 switch (nullability) {
5773 case NullabilityKind::NonNull:
5774 return getAttributedType(attrKind: attr::TypeNonNull, modifiedType, equivalentType);
5775
5776 case NullabilityKind::Nullable:
5777 return getAttributedType(attrKind: attr::TypeNullable, modifiedType, equivalentType);
5778
5779 case NullabilityKind::NullableResult:
5780 return getAttributedType(attrKind: attr::TypeNullableResult, modifiedType,
5781 equivalentType);
5782
5783 case NullabilityKind::Unspecified:
5784 return getAttributedType(attrKind: attr::TypeNullUnspecified, modifiedType,
5785 equivalentType);
5786 }
5787
5788 llvm_unreachable("Unknown nullability kind");
5789}
5790
5791QualType ASTContext::getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr,
5792 QualType Wrapped) const {
5793 llvm::FoldingSetNodeID ID;
5794 BTFTagAttributedType::Profile(ID, Wrapped, BTFAttr);
5795
5796 void *InsertPos = nullptr;
5797 BTFTagAttributedType *Ty =
5798 BTFTagAttributedTypes.FindNodeOrInsertPos(ID, InsertPos);
5799 if (Ty)
5800 return QualType(Ty, 0);
5801
5802 QualType Canon = getCanonicalType(T: Wrapped);
5803 Ty = new (*this, alignof(BTFTagAttributedType))
5804 BTFTagAttributedType(Canon, Wrapped, BTFAttr);
5805
5806 Types.push_back(Elt: Ty);
5807 BTFTagAttributedTypes.InsertNode(N: Ty, InsertPos);
5808
5809 return QualType(Ty, 0);
5810}
5811
5812QualType ASTContext::getOverflowBehaviorType(const OverflowBehaviorAttr *Attr,
5813 QualType Underlying) const {
5814 const IdentifierInfo *II = Attr->getBehaviorKind();
5815 StringRef IdentName = II->getName();
5816 OverflowBehaviorType::OverflowBehaviorKind Kind;
5817 if (IdentName == "wrap") {
5818 Kind = OverflowBehaviorType::OverflowBehaviorKind::Wrap;
5819 } else if (IdentName == "trap") {
5820 Kind = OverflowBehaviorType::OverflowBehaviorKind::Trap;
5821 } else {
5822 return Underlying;
5823 }
5824
5825 return getOverflowBehaviorType(Kind, Wrapped: Underlying);
5826}
5827
5828QualType ASTContext::getOverflowBehaviorType(
5829 OverflowBehaviorType::OverflowBehaviorKind Kind,
5830 QualType Underlying) const {
5831 assert(!Underlying->isOverflowBehaviorType() &&
5832 "Cannot have underlying types that are themselves OBTs");
5833 llvm::FoldingSetNodeID ID;
5834 OverflowBehaviorType::Profile(ID, Underlying, Kind);
5835 void *InsertPos = nullptr;
5836
5837 if (OverflowBehaviorType *OBT =
5838 OverflowBehaviorTypes.FindNodeOrInsertPos(ID, InsertPos)) {
5839 return QualType(OBT, 0);
5840 }
5841
5842 QualType Canonical;
5843 if (!Underlying.isCanonical() || Underlying.hasLocalQualifiers()) {
5844 SplitQualType canonSplit = getCanonicalType(T: Underlying).split();
5845 Canonical = getOverflowBehaviorType(Kind, Underlying: QualType(canonSplit.Ty, 0));
5846 Canonical = getQualifiedType(T: Canonical, Qs: canonSplit.Quals);
5847 assert(!OverflowBehaviorTypes.FindNodeOrInsertPos(ID, InsertPos) &&
5848 "Shouldn't be in the map");
5849 }
5850
5851 OverflowBehaviorType *Ty = new (*this, alignof(OverflowBehaviorType))
5852 OverflowBehaviorType(Canonical, Underlying, Kind);
5853
5854 Types.push_back(Elt: Ty);
5855 OverflowBehaviorTypes.InsertNode(N: Ty, InsertPos);
5856 return QualType(Ty, 0);
5857}
5858
5859QualType ASTContext::getHLSLAttributedResourceType(
5860 QualType Wrapped, QualType Contained,
5861 const HLSLAttributedResourceType::Attributes &Attrs) {
5862
5863 llvm::FoldingSetNodeID ID;
5864 HLSLAttributedResourceType::Profile(ID, Wrapped, Contained, Attrs);
5865
5866 void *InsertPos = nullptr;
5867 HLSLAttributedResourceType *Ty =
5868 HLSLAttributedResourceTypes.FindNodeOrInsertPos(ID, InsertPos);
5869 if (Ty)
5870 return QualType(Ty, 0);
5871
5872 Ty = new (*this, alignof(HLSLAttributedResourceType))
5873 HLSLAttributedResourceType(Wrapped, Contained, Attrs);
5874
5875 Types.push_back(Elt: Ty);
5876 HLSLAttributedResourceTypes.InsertNode(N: Ty, InsertPos);
5877
5878 return QualType(Ty, 0);
5879}
5880
5881QualType ASTContext::getHLSLInlineSpirvType(uint32_t Opcode, uint32_t Size,
5882 uint32_t Alignment,
5883 ArrayRef<SpirvOperand> Operands) {
5884 llvm::FoldingSetNodeID ID;
5885 HLSLInlineSpirvType::Profile(ID, Opcode, Size, Alignment, Operands);
5886
5887 void *InsertPos = nullptr;
5888 HLSLInlineSpirvType *Ty =
5889 HLSLInlineSpirvTypes.FindNodeOrInsertPos(ID, InsertPos);
5890 if (Ty)
5891 return QualType(Ty, 0);
5892
5893 void *Mem = Allocate(
5894 Size: HLSLInlineSpirvType::totalSizeToAlloc<SpirvOperand>(Counts: Operands.size()),
5895 Align: alignof(HLSLInlineSpirvType));
5896
5897 Ty = new (Mem) HLSLInlineSpirvType(Opcode, Size, Alignment, Operands);
5898
5899 Types.push_back(Elt: Ty);
5900 HLSLInlineSpirvTypes.InsertNode(N: Ty, InsertPos);
5901
5902 return QualType(Ty, 0);
5903}
5904
5905/// Retrieve a substitution-result type.
5906QualType ASTContext::getSubstTemplateTypeParmType(QualType Replacement,
5907 Decl *AssociatedDecl,
5908 unsigned Index,
5909 UnsignedOrNone PackIndex,
5910 bool Final) const {
5911 llvm::FoldingSetNodeID ID;
5912 SubstTemplateTypeParmType::Profile(ID, Replacement, AssociatedDecl, Index,
5913 PackIndex, Final);
5914 void *InsertPos = nullptr;
5915 SubstTemplateTypeParmType *SubstParm =
5916 SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
5917
5918 if (!SubstParm) {
5919 void *Mem = Allocate(Size: SubstTemplateTypeParmType::totalSizeToAlloc<QualType>(
5920 Counts: !Replacement.isCanonical()),
5921 Align: alignof(SubstTemplateTypeParmType));
5922 SubstParm = new (Mem) SubstTemplateTypeParmType(Replacement, AssociatedDecl,
5923 Index, PackIndex, Final);
5924 Types.push_back(Elt: SubstParm);
5925 SubstTemplateTypeParmTypes.InsertNode(N: SubstParm, InsertPos);
5926 }
5927
5928 return QualType(SubstParm, 0);
5929}
5930
5931QualType
5932ASTContext::getSubstTemplateTypeParmPackType(Decl *AssociatedDecl,
5933 unsigned Index, bool Final,
5934 const TemplateArgument &ArgPack) {
5935#ifndef NDEBUG
5936 for (const auto &P : ArgPack.pack_elements())
5937 assert(P.getKind() == TemplateArgument::Type && "Pack contains a non-type");
5938#endif
5939
5940 llvm::FoldingSetNodeID ID;
5941 SubstTemplateTypeParmPackType::Profile(ID, AssociatedDecl, Index, Final,
5942 ArgPack);
5943 void *InsertPos = nullptr;
5944 if (SubstTemplateTypeParmPackType *SubstParm =
5945 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
5946 return QualType(SubstParm, 0);
5947
5948 QualType Canon;
5949 {
5950 TemplateArgument CanonArgPack = getCanonicalTemplateArgument(Arg: ArgPack);
5951 if (!AssociatedDecl->isCanonicalDecl() ||
5952 !CanonArgPack.structurallyEquals(Other: ArgPack)) {
5953 Canon = getSubstTemplateTypeParmPackType(
5954 AssociatedDecl: AssociatedDecl->getCanonicalDecl(), Index, Final, ArgPack: CanonArgPack);
5955 [[maybe_unused]] const auto *Nothing =
5956 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
5957 assert(!Nothing);
5958 }
5959 }
5960
5961 auto *SubstParm = new (*this, alignof(SubstTemplateTypeParmPackType))
5962 SubstTemplateTypeParmPackType(Canon, AssociatedDecl, Index, Final,
5963 ArgPack);
5964 Types.push_back(Elt: SubstParm);
5965 SubstTemplateTypeParmPackTypes.InsertNode(N: SubstParm, InsertPos);
5966 return QualType(SubstParm, 0);
5967}
5968
5969QualType
5970ASTContext::getSubstBuiltinTemplatePack(const TemplateArgument &ArgPack) {
5971 assert(llvm::all_of(ArgPack.pack_elements(),
5972 [](const auto &P) {
5973 return P.getKind() == TemplateArgument::Type;
5974 }) &&
5975 "Pack contains a non-type");
5976
5977 llvm::FoldingSetNodeID ID;
5978 SubstBuiltinTemplatePackType::Profile(ID, ArgPack);
5979
5980 void *InsertPos = nullptr;
5981 if (auto *T =
5982 SubstBuiltinTemplatePackTypes.FindNodeOrInsertPos(ID, InsertPos))
5983 return QualType(T, 0);
5984
5985 QualType Canon;
5986 TemplateArgument CanonArgPack = getCanonicalTemplateArgument(Arg: ArgPack);
5987 if (!CanonArgPack.structurallyEquals(Other: ArgPack)) {
5988 Canon = getSubstBuiltinTemplatePack(ArgPack: CanonArgPack);
5989 // Refresh InsertPos, in case the recursive call above caused rehashing,
5990 // which would invalidate the bucket pointer.
5991 [[maybe_unused]] const auto *Nothing =
5992 SubstBuiltinTemplatePackTypes.FindNodeOrInsertPos(ID, InsertPos);
5993 assert(!Nothing);
5994 }
5995
5996 auto *PackType = new (*this, alignof(SubstBuiltinTemplatePackType))
5997 SubstBuiltinTemplatePackType(Canon, ArgPack);
5998 Types.push_back(Elt: PackType);
5999 SubstBuiltinTemplatePackTypes.InsertNode(N: PackType, InsertPos);
6000 return QualType(PackType, 0);
6001}
6002
6003/// Retrieve the template type parameter type for a template
6004/// parameter or parameter pack with the given depth, index, and (optionally)
6005/// name.
6006QualType
6007ASTContext::getTemplateTypeParmType(int Depth, int Index, bool ParameterPack,
6008 TemplateTypeParmDecl *TTPDecl) const {
6009 assert(Depth >= 0 && "Depth must be non-negative");
6010 assert(Index >= 0 && "Index must be non-negative");
6011
6012 llvm::FoldingSetNodeID ID;
6013 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
6014 void *InsertPos = nullptr;
6015 TemplateTypeParmType *TypeParm
6016 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
6017
6018 if (TypeParm)
6019 return QualType(TypeParm, 0);
6020
6021 if (TTPDecl) {
6022 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
6023 TypeParm = new (*this, alignof(TemplateTypeParmType))
6024 TemplateTypeParmType(Depth, Index, ParameterPack, TTPDecl, Canon);
6025
6026 TemplateTypeParmType *TypeCheck
6027 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
6028 assert(!TypeCheck && "Template type parameter canonical type broken");
6029 (void)TypeCheck;
6030 } else
6031 TypeParm = new (*this, alignof(TemplateTypeParmType)) TemplateTypeParmType(
6032 Depth, Index, ParameterPack, /*TTPDecl=*/nullptr, /*Canon=*/QualType());
6033
6034 Types.push_back(Elt: TypeParm);
6035 TemplateTypeParmTypes.InsertNode(N: TypeParm, InsertPos);
6036
6037 return QualType(TypeParm, 0);
6038}
6039
6040static ElaboratedTypeKeyword
6041getCanonicalElaboratedTypeKeyword(ElaboratedTypeKeyword Keyword) {
6042 switch (Keyword) {
6043 // These are just themselves.
6044 case ElaboratedTypeKeyword::None:
6045 case ElaboratedTypeKeyword::Struct:
6046 case ElaboratedTypeKeyword::Union:
6047 case ElaboratedTypeKeyword::Enum:
6048 case ElaboratedTypeKeyword::Interface:
6049 return Keyword;
6050
6051 // These are equivalent.
6052 case ElaboratedTypeKeyword::Typename:
6053 return ElaboratedTypeKeyword::None;
6054
6055 // These are functionally equivalent, so relying on their equivalence is
6056 // IFNDR. By making them equivalent, we disallow overloading, which at least
6057 // can produce a diagnostic.
6058 case ElaboratedTypeKeyword::Class:
6059 return ElaboratedTypeKeyword::Struct;
6060 }
6061 llvm_unreachable("unexpected keyword kind");
6062}
6063
6064TypeSourceInfo *ASTContext::getTemplateSpecializationTypeInfo(
6065 ElaboratedTypeKeyword Keyword, SourceLocation ElaboratedKeywordLoc,
6066 NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKeywordLoc,
6067 TemplateName Name, SourceLocation NameLoc,
6068 const TemplateArgumentListInfo &SpecifiedArgs,
6069 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
6070 QualType TST = getTemplateSpecializationType(
6071 Keyword, T: Name, SpecifiedArgs: SpecifiedArgs.arguments(), CanonicalArgs, Canon: Underlying);
6072
6073 TypeSourceInfo *TSI = CreateTypeSourceInfo(T: TST);
6074 TSI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>().set(
6075 ElaboratedKeywordLoc, QualifierLoc, TemplateKeywordLoc, NameLoc,
6076 TAL: SpecifiedArgs);
6077 return TSI;
6078}
6079
6080QualType ASTContext::getTemplateSpecializationType(
6081 ElaboratedTypeKeyword Keyword, TemplateName Template,
6082 ArrayRef<TemplateArgumentLoc> SpecifiedArgs,
6083 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
6084 SmallVector<TemplateArgument, 4> SpecifiedArgVec;
6085 SpecifiedArgVec.reserve(N: SpecifiedArgs.size());
6086 for (const TemplateArgumentLoc &Arg : SpecifiedArgs)
6087 SpecifiedArgVec.push_back(Elt: Arg.getArgument());
6088
6089 return getTemplateSpecializationType(Keyword, T: Template, SpecifiedArgs: SpecifiedArgVec,
6090 CanonicalArgs, Underlying);
6091}
6092
6093[[maybe_unused]] static bool
6094hasAnyPackExpansions(ArrayRef<TemplateArgument> Args) {
6095 for (const TemplateArgument &Arg : Args)
6096 if (Arg.isPackExpansion())
6097 return true;
6098 return false;
6099}
6100
6101QualType ASTContext::getCanonicalTemplateSpecializationType(
6102 ElaboratedTypeKeyword Keyword, TemplateName Template,
6103 ArrayRef<TemplateArgument> Args) const {
6104 assert(Template ==
6105 getCanonicalTemplateName(Template, /*IgnoreDeduced=*/true));
6106 assert((Keyword == ElaboratedTypeKeyword::None ||
6107 Template.getAsDependentTemplateName()));
6108#ifndef NDEBUG
6109 for (const auto &Arg : Args)
6110 assert(Arg.structurallyEquals(getCanonicalTemplateArgument(Arg)));
6111#endif
6112
6113 llvm::FoldingSetNodeID ID;
6114 TemplateSpecializationType::Profile(ID, Keyword, T: Template, Args, Underlying: QualType(),
6115 Context: *this);
6116 void *InsertPos = nullptr;
6117 if (auto *T = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
6118 return QualType(T, 0);
6119
6120 void *Mem = Allocate(Size: sizeof(TemplateSpecializationType) +
6121 sizeof(TemplateArgument) * Args.size(),
6122 Align: alignof(TemplateSpecializationType));
6123 auto *Spec =
6124 new (Mem) TemplateSpecializationType(Keyword, Template,
6125 /*IsAlias=*/false, Args, QualType());
6126 assert(Spec->isDependentType() &&
6127 "canonical template specialization must be dependent");
6128 Types.push_back(Elt: Spec);
6129 TemplateSpecializationTypes.InsertNode(N: Spec, InsertPos);
6130 return QualType(Spec, 0);
6131}
6132
6133QualType ASTContext::getTemplateSpecializationType(
6134 ElaboratedTypeKeyword Keyword, TemplateName Template,
6135 ArrayRef<TemplateArgument> SpecifiedArgs,
6136 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
6137 const auto *TD = Template.getAsTemplateDecl(/*IgnoreDeduced=*/true);
6138 bool IsTypeAlias = TD && TD->isTypeAlias();
6139 if (Underlying.isNull()) {
6140 TemplateName CanonTemplate =
6141 getCanonicalTemplateName(Name: Template, /*IgnoreDeduced=*/true);
6142 ElaboratedTypeKeyword CanonKeyword =
6143 CanonTemplate.getAsDependentTemplateName()
6144 ? getCanonicalElaboratedTypeKeyword(Keyword)
6145 : ElaboratedTypeKeyword::None;
6146 bool NonCanonical = Template != CanonTemplate || Keyword != CanonKeyword;
6147 SmallVector<TemplateArgument, 4> CanonArgsVec;
6148 if (CanonicalArgs.empty()) {
6149 CanonArgsVec = SmallVector<TemplateArgument, 4>(SpecifiedArgs);
6150 NonCanonical |= canonicalizeTemplateArguments(Args: CanonArgsVec);
6151 CanonicalArgs = CanonArgsVec;
6152 } else {
6153 NonCanonical |= !llvm::equal(
6154 LRange&: SpecifiedArgs, RRange&: CanonicalArgs,
6155 P: [](const TemplateArgument &A, const TemplateArgument &B) {
6156 return A.structurallyEquals(Other: B);
6157 });
6158 }
6159
6160 // We can get here with an alias template when the specialization
6161 // contains a pack expansion that does not match up with a parameter
6162 // pack, or a builtin template which cannot be resolved due to dependency.
6163 assert((!isa_and_nonnull<TypeAliasTemplateDecl>(TD) ||
6164 hasAnyPackExpansions(CanonicalArgs)) &&
6165 "Caller must compute aliased type");
6166 IsTypeAlias = false;
6167
6168 Underlying = getCanonicalTemplateSpecializationType(
6169 Keyword: CanonKeyword, Template: CanonTemplate, Args: CanonicalArgs);
6170 if (!NonCanonical)
6171 return Underlying;
6172 }
6173 void *Mem = Allocate(Size: sizeof(TemplateSpecializationType) +
6174 sizeof(TemplateArgument) * SpecifiedArgs.size() +
6175 (IsTypeAlias ? sizeof(QualType) : 0),
6176 Align: alignof(TemplateSpecializationType));
6177 auto *Spec = new (Mem) TemplateSpecializationType(
6178 Keyword, Template, IsTypeAlias, SpecifiedArgs, Underlying);
6179 Types.push_back(Elt: Spec);
6180 return QualType(Spec, 0);
6181}
6182
6183QualType
6184ASTContext::getParenType(QualType InnerType) const {
6185 llvm::FoldingSetNodeID ID;
6186 ParenType::Profile(ID, Inner: InnerType);
6187
6188 void *InsertPos = nullptr;
6189 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
6190 if (T)
6191 return QualType(T, 0);
6192
6193 QualType Canon = InnerType;
6194 if (!Canon.isCanonical()) {
6195 Canon = getCanonicalType(T: InnerType);
6196 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
6197 assert(!CheckT && "Paren canonical type broken");
6198 (void)CheckT;
6199 }
6200
6201 T = new (*this, alignof(ParenType)) ParenType(InnerType, Canon);
6202 Types.push_back(Elt: T);
6203 ParenTypes.InsertNode(N: T, InsertPos);
6204 return QualType(T, 0);
6205}
6206
6207QualType
6208ASTContext::getMacroQualifiedType(QualType UnderlyingTy,
6209 const IdentifierInfo *MacroII) const {
6210 QualType Canon = UnderlyingTy;
6211 if (!Canon.isCanonical())
6212 Canon = getCanonicalType(T: UnderlyingTy);
6213
6214 auto *newType = new (*this, alignof(MacroQualifiedType))
6215 MacroQualifiedType(UnderlyingTy, Canon, MacroII);
6216 Types.push_back(Elt: newType);
6217 return QualType(newType, 0);
6218}
6219
6220QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
6221 NestedNameSpecifier NNS,
6222 const IdentifierInfo *Name) const {
6223 llvm::FoldingSetNodeID ID;
6224 DependentNameType::Profile(ID, Keyword, NNS, Name);
6225
6226 void *InsertPos = nullptr;
6227 if (DependentNameType *T =
6228 DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos))
6229 return QualType(T, 0);
6230
6231 ElaboratedTypeKeyword CanonKeyword =
6232 getCanonicalElaboratedTypeKeyword(Keyword);
6233 NestedNameSpecifier CanonNNS = NNS.getCanonical();
6234
6235 QualType Canon;
6236 if (CanonKeyword != Keyword || CanonNNS != NNS) {
6237 Canon = getDependentNameType(Keyword: CanonKeyword, NNS: CanonNNS, Name);
6238 [[maybe_unused]] DependentNameType *T =
6239 DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
6240 assert(!T && "broken canonicalization");
6241 assert(Canon.isCanonical());
6242 }
6243
6244 DependentNameType *T = new (*this, alignof(DependentNameType))
6245 DependentNameType(Keyword, NNS, Name, Canon);
6246 Types.push_back(Elt: T);
6247 DependentNameTypes.InsertNode(N: T, InsertPos);
6248 return QualType(T, 0);
6249}
6250
6251TemplateArgument ASTContext::getInjectedTemplateArg(NamedDecl *Param) const {
6252 TemplateArgument Arg;
6253 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Val: Param)) {
6254 QualType ArgType = getTypeDeclType(Decl: TTP);
6255 if (TTP->isParameterPack())
6256 ArgType = getPackExpansionType(Pattern: ArgType, NumExpansions: std::nullopt);
6257
6258 Arg = TemplateArgument(ArgType);
6259 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: Param)) {
6260 QualType T =
6261 NTTP->getType().getNonPackExpansionType().getNonLValueExprType(Context: *this);
6262 // For class NTTPs, ensure we include the 'const' so the type matches that
6263 // of a real template argument.
6264 // FIXME: It would be more faithful to model this as something like an
6265 // lvalue-to-rvalue conversion applied to a const-qualified lvalue.
6266 ExprValueKind VK;
6267 if (T->isRecordType()) {
6268 // C++ [temp.param]p8: An id-expression naming a non-type
6269 // template-parameter of class type T denotes a static storage duration
6270 // object of type const T.
6271 T.addConst();
6272 VK = VK_LValue;
6273 } else {
6274 VK = Expr::getValueKindForType(T: NTTP->getType());
6275 }
6276 Expr *E = new (*this)
6277 DeclRefExpr(*this, NTTP, /*RefersToEnclosingVariableOrCapture=*/false,
6278 T, VK, NTTP->getLocation());
6279
6280 if (NTTP->isParameterPack())
6281 E = new (*this) PackExpansionExpr(E, NTTP->getLocation(), std::nullopt);
6282 Arg = TemplateArgument(E, /*IsCanonical=*/false);
6283 } else {
6284 auto *TTP = cast<TemplateTemplateParmDecl>(Val: Param);
6285 TemplateName Name = getQualifiedTemplateName(
6286 /*Qualifier=*/std::nullopt, /*TemplateKeyword=*/false,
6287 Template: TemplateName(TTP));
6288 if (TTP->isParameterPack())
6289 Arg = TemplateArgument(Name, /*NumExpansions=*/std::nullopt);
6290 else
6291 Arg = TemplateArgument(Name);
6292 }
6293
6294 if (Param->isTemplateParameterPack())
6295 Arg =
6296 TemplateArgument::CreatePackCopy(Context&: const_cast<ASTContext &>(*this), Args: Arg);
6297
6298 return Arg;
6299}
6300
6301QualType ASTContext::getPackExpansionType(QualType Pattern,
6302 UnsignedOrNone NumExpansions,
6303 bool ExpectPackInType) const {
6304 assert((!ExpectPackInType || Pattern->containsUnexpandedParameterPack()) &&
6305 "Pack expansions must expand one or more parameter packs");
6306
6307 llvm::FoldingSetNodeID ID;
6308 PackExpansionType::Profile(ID, Pattern, NumExpansions);
6309
6310 void *InsertPos = nullptr;
6311 PackExpansionType *T = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
6312 if (T)
6313 return QualType(T, 0);
6314
6315 QualType Canon;
6316 if (!Pattern.isCanonical()) {
6317 Canon = getPackExpansionType(Pattern: getCanonicalType(T: Pattern), NumExpansions,
6318 /*ExpectPackInType=*/false);
6319
6320 // Find the insert position again, in case we inserted an element into
6321 // PackExpansionTypes and invalidated our insert position.
6322 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
6323 }
6324
6325 T = new (*this, alignof(PackExpansionType))
6326 PackExpansionType(Pattern, Canon, NumExpansions);
6327 Types.push_back(Elt: T);
6328 PackExpansionTypes.InsertNode(N: T, InsertPos);
6329 return QualType(T, 0);
6330}
6331
6332/// CmpProtocolNames - Comparison predicate for sorting protocols
6333/// alphabetically.
6334static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
6335 ObjCProtocolDecl *const *RHS) {
6336 return DeclarationName::compare(LHS: (*LHS)->getDeclName(), RHS: (*RHS)->getDeclName());
6337}
6338
6339static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) {
6340 if (Protocols.empty()) return true;
6341
6342 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
6343 return false;
6344
6345 for (unsigned i = 1; i != Protocols.size(); ++i)
6346 if (CmpProtocolNames(LHS: &Protocols[i - 1], RHS: &Protocols[i]) >= 0 ||
6347 Protocols[i]->getCanonicalDecl() != Protocols[i])
6348 return false;
6349 return true;
6350}
6351
6352static void
6353SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) {
6354 // Sort protocols, keyed by name.
6355 llvm::array_pod_sort(Start: Protocols.begin(), End: Protocols.end(), Compare: CmpProtocolNames);
6356
6357 // Canonicalize.
6358 for (ObjCProtocolDecl *&P : Protocols)
6359 P = P->getCanonicalDecl();
6360
6361 // Remove duplicates.
6362 auto ProtocolsEnd = llvm::unique(R&: Protocols);
6363 Protocols.erase(CS: ProtocolsEnd, CE: Protocols.end());
6364}
6365
6366QualType ASTContext::getObjCObjectType(QualType BaseType,
6367 ObjCProtocolDecl * const *Protocols,
6368 unsigned NumProtocols) const {
6369 return getObjCObjectType(Base: BaseType, typeArgs: {}, protocols: ArrayRef(Protocols, NumProtocols),
6370 /*isKindOf=*/false);
6371}
6372
6373QualType ASTContext::getObjCObjectType(
6374 QualType baseType,
6375 ArrayRef<QualType> typeArgs,
6376 ArrayRef<ObjCProtocolDecl *> protocols,
6377 bool isKindOf) const {
6378 // If the base type is an interface and there aren't any protocols or
6379 // type arguments to add, then the interface type will do just fine.
6380 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
6381 isa<ObjCInterfaceType>(Val: baseType))
6382 return baseType;
6383
6384 // Look in the folding set for an existing type.
6385 llvm::FoldingSetNodeID ID;
6386 ObjCObjectTypeImpl::Profile(ID, Base: baseType, typeArgs, protocols, isKindOf);
6387 void *InsertPos = nullptr;
6388 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
6389 return QualType(QT, 0);
6390
6391 // Determine the type arguments to be used for canonicalization,
6392 // which may be explicitly specified here or written on the base
6393 // type.
6394 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
6395 if (effectiveTypeArgs.empty()) {
6396 if (const auto *baseObject = baseType->getAs<ObjCObjectType>())
6397 effectiveTypeArgs = baseObject->getTypeArgs();
6398 }
6399
6400 // Build the canonical type, which has the canonical base type and a
6401 // sorted-and-uniqued list of protocols and the type arguments
6402 // canonicalized.
6403 QualType canonical;
6404 bool typeArgsAreCanonical = llvm::all_of(
6405 Range&: effectiveTypeArgs, P: [&](QualType type) { return type.isCanonical(); });
6406 bool protocolsSorted = areSortedAndUniqued(Protocols: protocols);
6407 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
6408 // Determine the canonical type arguments.
6409 ArrayRef<QualType> canonTypeArgs;
6410 SmallVector<QualType, 4> canonTypeArgsVec;
6411 if (!typeArgsAreCanonical) {
6412 canonTypeArgsVec.reserve(N: effectiveTypeArgs.size());
6413 for (auto typeArg : effectiveTypeArgs)
6414 canonTypeArgsVec.push_back(Elt: getCanonicalType(T: typeArg));
6415 canonTypeArgs = canonTypeArgsVec;
6416 } else {
6417 canonTypeArgs = effectiveTypeArgs;
6418 }
6419
6420 ArrayRef<ObjCProtocolDecl *> canonProtocols;
6421 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
6422 if (!protocolsSorted) {
6423 canonProtocolsVec.append(in_start: protocols.begin(), in_end: protocols.end());
6424 SortAndUniqueProtocols(Protocols&: canonProtocolsVec);
6425 canonProtocols = canonProtocolsVec;
6426 } else {
6427 canonProtocols = protocols;
6428 }
6429
6430 canonical = getObjCObjectType(baseType: getCanonicalType(T: baseType), typeArgs: canonTypeArgs,
6431 protocols: canonProtocols, isKindOf);
6432
6433 // Regenerate InsertPos.
6434 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
6435 }
6436
6437 unsigned size = sizeof(ObjCObjectTypeImpl);
6438 size += typeArgs.size() * sizeof(QualType);
6439 size += protocols.size() * sizeof(ObjCProtocolDecl *);
6440 void *mem = Allocate(Size: size, Align: alignof(ObjCObjectTypeImpl));
6441 auto *T =
6442 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
6443 isKindOf);
6444
6445 Types.push_back(Elt: T);
6446 ObjCObjectTypes.InsertNode(N: T, InsertPos);
6447 return QualType(T, 0);
6448}
6449
6450/// Apply Objective-C protocol qualifiers to the given type.
6451/// If this is for the canonical type of a type parameter, we can apply
6452/// protocol qualifiers on the ObjCObjectPointerType.
6453QualType
6454ASTContext::applyObjCProtocolQualifiers(QualType type,
6455 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
6456 bool allowOnPointerType) const {
6457 hasError = false;
6458
6459 if (const auto *objT = dyn_cast<ObjCTypeParamType>(Val: type.getTypePtr())) {
6460 return getObjCTypeParamType(Decl: objT->getDecl(), protocols);
6461 }
6462
6463 // Apply protocol qualifiers to ObjCObjectPointerType.
6464 if (allowOnPointerType) {
6465 if (const auto *objPtr =
6466 dyn_cast<ObjCObjectPointerType>(Val: type.getTypePtr())) {
6467 const ObjCObjectType *objT = objPtr->getObjectType();
6468 // Merge protocol lists and construct ObjCObjectType.
6469 SmallVector<ObjCProtocolDecl*, 8> protocolsVec;
6470 protocolsVec.append(in_start: objT->qual_begin(),
6471 in_end: objT->qual_end());
6472 protocolsVec.append(in_start: protocols.begin(), in_end: protocols.end());
6473 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
6474 type = getObjCObjectType(
6475 baseType: objT->getBaseType(),
6476 typeArgs: objT->getTypeArgsAsWritten(),
6477 protocols,
6478 isKindOf: objT->isKindOfTypeAsWritten());
6479 return getObjCObjectPointerType(OIT: type);
6480 }
6481 }
6482
6483 // Apply protocol qualifiers to ObjCObjectType.
6484 if (const auto *objT = dyn_cast<ObjCObjectType>(Val: type.getTypePtr())){
6485 // FIXME: Check for protocols to which the class type is already
6486 // known to conform.
6487
6488 return getObjCObjectType(baseType: objT->getBaseType(),
6489 typeArgs: objT->getTypeArgsAsWritten(),
6490 protocols,
6491 isKindOf: objT->isKindOfTypeAsWritten());
6492 }
6493
6494 // If the canonical type is ObjCObjectType, ...
6495 if (type->isObjCObjectType()) {
6496 // Silently overwrite any existing protocol qualifiers.
6497 // TODO: determine whether that's the right thing to do.
6498
6499 // FIXME: Check for protocols to which the class type is already
6500 // known to conform.
6501 return getObjCObjectType(baseType: type, typeArgs: {}, protocols, isKindOf: false);
6502 }
6503
6504 // id<protocol-list>
6505 if (type->isObjCIdType()) {
6506 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
6507 type = getObjCObjectType(baseType: ObjCBuiltinIdTy, typeArgs: {}, protocols,
6508 isKindOf: objPtr->isKindOfType());
6509 return getObjCObjectPointerType(OIT: type);
6510 }
6511
6512 // Class<protocol-list>
6513 if (type->isObjCClassType()) {
6514 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
6515 type = getObjCObjectType(baseType: ObjCBuiltinClassTy, typeArgs: {}, protocols,
6516 isKindOf: objPtr->isKindOfType());
6517 return getObjCObjectPointerType(OIT: type);
6518 }
6519
6520 hasError = true;
6521 return type;
6522}
6523
6524QualType
6525ASTContext::getObjCTypeParamType(const ObjCTypeParamDecl *Decl,
6526 ArrayRef<ObjCProtocolDecl *> protocols) const {
6527 // Look in the folding set for an existing type.
6528 llvm::FoldingSetNodeID ID;
6529 ObjCTypeParamType::Profile(ID, OTPDecl: Decl, CanonicalType: Decl->getUnderlyingType(), protocols);
6530 void *InsertPos = nullptr;
6531 if (ObjCTypeParamType *TypeParam =
6532 ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
6533 return QualType(TypeParam, 0);
6534
6535 // We canonicalize to the underlying type.
6536 QualType Canonical = getCanonicalType(T: Decl->getUnderlyingType());
6537 if (!protocols.empty()) {
6538 // Apply the protocol qualifers.
6539 bool hasError;
6540 Canonical = getCanonicalType(T: applyObjCProtocolQualifiers(
6541 type: Canonical, protocols, hasError, allowOnPointerType: true /*allowOnPointerType*/));
6542 assert(!hasError && "Error when apply protocol qualifier to bound type");
6543 }
6544
6545 unsigned size = sizeof(ObjCTypeParamType);
6546 size += protocols.size() * sizeof(ObjCProtocolDecl *);
6547 void *mem = Allocate(Size: size, Align: alignof(ObjCTypeParamType));
6548 auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols);
6549
6550 Types.push_back(Elt: newType);
6551 ObjCTypeParamTypes.InsertNode(N: newType, InsertPos);
6552 return QualType(newType, 0);
6553}
6554
6555void ASTContext::adjustObjCTypeParamBoundType(const ObjCTypeParamDecl *Orig,
6556 ObjCTypeParamDecl *New) const {
6557 New->setTypeSourceInfo(getTrivialTypeSourceInfo(T: Orig->getUnderlyingType()));
6558 // Update TypeForDecl after updating TypeSourceInfo.
6559 auto *NewTypeParamTy = cast<ObjCTypeParamType>(Val: New->TypeForDecl);
6560 SmallVector<ObjCProtocolDecl *, 8> protocols;
6561 protocols.append(in_start: NewTypeParamTy->qual_begin(), in_end: NewTypeParamTy->qual_end());
6562 QualType UpdatedTy = getObjCTypeParamType(Decl: New, protocols);
6563 New->TypeForDecl = UpdatedTy.getTypePtr();
6564}
6565
6566/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
6567/// protocol list adopt all protocols in QT's qualified-id protocol
6568/// list.
6569bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
6570 ObjCInterfaceDecl *IC) {
6571 if (!QT->isObjCQualifiedIdType())
6572 return false;
6573
6574 if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) {
6575 // If both the right and left sides have qualifiers.
6576 for (auto *Proto : OPT->quals()) {
6577 if (!IC->ClassImplementsProtocol(lProto: Proto, lookupCategory: false))
6578 return false;
6579 }
6580 return true;
6581 }
6582 return false;
6583}
6584
6585/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
6586/// QT's qualified-id protocol list adopt all protocols in IDecl's list
6587/// of protocols.
6588bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
6589 ObjCInterfaceDecl *IDecl) {
6590 if (!QT->isObjCQualifiedIdType())
6591 return false;
6592 const auto *OPT = QT->getAs<ObjCObjectPointerType>();
6593 if (!OPT)
6594 return false;
6595 if (!IDecl->hasDefinition())
6596 return false;
6597 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
6598 CollectInheritedProtocols(CDecl: IDecl, Protocols&: InheritedProtocols);
6599 if (InheritedProtocols.empty())
6600 return false;
6601 // Check that if every protocol in list of id<plist> conforms to a protocol
6602 // of IDecl's, then bridge casting is ok.
6603 bool Conforms = false;
6604 for (auto *Proto : OPT->quals()) {
6605 Conforms = false;
6606 for (auto *PI : InheritedProtocols) {
6607 if (ProtocolCompatibleWithProtocol(lProto: Proto, rProto: PI)) {
6608 Conforms = true;
6609 break;
6610 }
6611 }
6612 if (!Conforms)
6613 break;
6614 }
6615 if (Conforms)
6616 return true;
6617
6618 for (auto *PI : InheritedProtocols) {
6619 // If both the right and left sides have qualifiers.
6620 bool Adopts = false;
6621 for (auto *Proto : OPT->quals()) {
6622 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
6623 if ((Adopts = ProtocolCompatibleWithProtocol(lProto: PI, rProto: Proto)))
6624 break;
6625 }
6626 if (!Adopts)
6627 return false;
6628 }
6629 return true;
6630}
6631
6632/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
6633/// the given object type.
6634QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
6635 llvm::FoldingSetNodeID ID;
6636 ObjCObjectPointerType::Profile(ID, T: ObjectT);
6637
6638 void *InsertPos = nullptr;
6639 if (ObjCObjectPointerType *QT =
6640 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
6641 return QualType(QT, 0);
6642
6643 // Find the canonical object type.
6644 QualType Canonical;
6645 if (!ObjectT.isCanonical()) {
6646 Canonical = getObjCObjectPointerType(ObjectT: getCanonicalType(T: ObjectT));
6647
6648 // Regenerate InsertPos.
6649 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
6650 }
6651
6652 // No match.
6653 void *Mem =
6654 Allocate(Size: sizeof(ObjCObjectPointerType), Align: alignof(ObjCObjectPointerType));
6655 auto *QType =
6656 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
6657
6658 Types.push_back(Elt: QType);
6659 ObjCObjectPointerTypes.InsertNode(N: QType, InsertPos);
6660 return QualType(QType, 0);
6661}
6662
6663/// getObjCInterfaceType - Return the unique reference to the type for the
6664/// specified ObjC interface decl. The list of protocols is optional.
6665QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
6666 ObjCInterfaceDecl *PrevDecl) const {
6667 if (Decl->TypeForDecl)
6668 return QualType(Decl->TypeForDecl, 0);
6669
6670 if (PrevDecl) {
6671 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
6672 Decl->TypeForDecl = PrevDecl->TypeForDecl;
6673 return QualType(PrevDecl->TypeForDecl, 0);
6674 }
6675
6676 // Prefer the definition, if there is one.
6677 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
6678 Decl = Def;
6679
6680 void *Mem = Allocate(Size: sizeof(ObjCInterfaceType), Align: alignof(ObjCInterfaceType));
6681 auto *T = new (Mem) ObjCInterfaceType(Decl);
6682 Decl->TypeForDecl = T;
6683 Types.push_back(Elt: T);
6684 return QualType(T, 0);
6685}
6686
6687/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
6688/// TypeOfExprType AST's (since expression's are never shared). For example,
6689/// multiple declarations that refer to "typeof(x)" all contain different
6690/// DeclRefExpr's. This doesn't effect the type checker, since it operates
6691/// on canonical type's (which are always unique).
6692QualType ASTContext::getTypeOfExprType(Expr *tofExpr, TypeOfKind Kind) const {
6693 TypeOfExprType *toe;
6694 if (tofExpr->isTypeDependent()) {
6695 llvm::FoldingSetNodeID ID;
6696 DependentTypeOfExprType::Profile(ID, Context: *this, E: tofExpr,
6697 IsUnqual: Kind == TypeOfKind::Unqualified);
6698
6699 void *InsertPos = nullptr;
6700 DependentTypeOfExprType *Canon =
6701 DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
6702 if (Canon) {
6703 // We already have a "canonical" version of an identical, dependent
6704 // typeof(expr) type. Use that as our canonical type.
6705 toe = new (*this, alignof(TypeOfExprType)) TypeOfExprType(
6706 *this, tofExpr, Kind, QualType((TypeOfExprType *)Canon, 0));
6707 } else {
6708 // Build a new, canonical typeof(expr) type.
6709 Canon = new (*this, alignof(DependentTypeOfExprType))
6710 DependentTypeOfExprType(*this, tofExpr, Kind);
6711 DependentTypeOfExprTypes.InsertNode(N: Canon, InsertPos);
6712 toe = Canon;
6713 }
6714 } else {
6715 QualType Canonical = getCanonicalType(T: tofExpr->getType());
6716 toe = new (*this, alignof(TypeOfExprType))
6717 TypeOfExprType(*this, tofExpr, Kind, Canonical);
6718 }
6719 Types.push_back(Elt: toe);
6720 return QualType(toe, 0);
6721}
6722
6723/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
6724/// TypeOfType nodes. The only motivation to unique these nodes would be
6725/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
6726/// an issue. This doesn't affect the type checker, since it operates
6727/// on canonical types (which are always unique).
6728QualType ASTContext::getTypeOfType(QualType tofType, TypeOfKind Kind) const {
6729 QualType Canonical = getCanonicalType(T: tofType);
6730 auto *tot = new (*this, alignof(TypeOfType))
6731 TypeOfType(*this, tofType, Canonical, Kind);
6732 Types.push_back(Elt: tot);
6733 return QualType(tot, 0);
6734}
6735
6736/// getReferenceQualifiedType - Given an expr, will return the type for
6737/// that expression, as in [dcl.type.simple]p4 but without taking id-expressions
6738/// and class member access into account.
6739QualType ASTContext::getReferenceQualifiedType(const Expr *E) const {
6740 // C++11 [dcl.type.simple]p4:
6741 // [...]
6742 QualType T = E->getType();
6743 switch (E->getValueKind()) {
6744 // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the
6745 // type of e;
6746 case VK_XValue:
6747 return getRValueReferenceType(T);
6748 // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the
6749 // type of e;
6750 case VK_LValue:
6751 return getLValueReferenceType(T);
6752 // - otherwise, decltype(e) is the type of e.
6753 case VK_PRValue:
6754 return T;
6755 }
6756 llvm_unreachable("Unknown value kind");
6757}
6758
6759/// Unlike many "get<Type>" functions, we don't unique DecltypeType
6760/// nodes. This would never be helpful, since each such type has its own
6761/// expression, and would not give a significant memory saving, since there
6762/// is an Expr tree under each such type.
6763QualType ASTContext::getDecltypeType(Expr *E, QualType UnderlyingType) const {
6764 // C++11 [temp.type]p2:
6765 // If an expression e involves a template parameter, decltype(e) denotes a
6766 // unique dependent type. Two such decltype-specifiers refer to the same
6767 // type only if their expressions are equivalent (14.5.6.1).
6768 QualType CanonType;
6769 if (!E->isInstantiationDependent()) {
6770 CanonType = getCanonicalType(T: UnderlyingType);
6771 } else if (!UnderlyingType.isNull()) {
6772 CanonType = getDecltypeType(E, UnderlyingType: QualType());
6773 } else {
6774 llvm::FoldingSetNodeID ID;
6775 DependentDecltypeType::Profile(ID, Context: *this, E);
6776
6777 void *InsertPos = nullptr;
6778 if (DependentDecltypeType *Canon =
6779 DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos))
6780 return QualType(Canon, 0);
6781
6782 // Build a new, canonical decltype(expr) type.
6783 auto *DT =
6784 new (*this, alignof(DependentDecltypeType)) DependentDecltypeType(E);
6785 DependentDecltypeTypes.InsertNode(N: DT, InsertPos);
6786 Types.push_back(Elt: DT);
6787 return QualType(DT, 0);
6788 }
6789 auto *DT = new (*this, alignof(DecltypeType))
6790 DecltypeType(E, UnderlyingType, CanonType);
6791 Types.push_back(Elt: DT);
6792 return QualType(DT, 0);
6793}
6794
6795QualType ASTContext::getPackIndexingType(QualType Pattern, Expr *IndexExpr,
6796 bool FullySubstituted,
6797 ArrayRef<QualType> Expansions,
6798 UnsignedOrNone Index) const {
6799 QualType Canonical;
6800 if (FullySubstituted && Index) {
6801 Canonical = getCanonicalType(T: Expansions[*Index]);
6802 } else {
6803 llvm::FoldingSetNodeID ID;
6804 PackIndexingType::Profile(ID, Context: *this, Pattern: Pattern.getCanonicalType(), E: IndexExpr,
6805 FullySubstituted, Expansions);
6806 void *InsertPos = nullptr;
6807 PackIndexingType *Canon =
6808 DependentPackIndexingTypes.FindNodeOrInsertPos(ID, InsertPos);
6809 if (!Canon) {
6810 void *Mem = Allocate(
6811 Size: PackIndexingType::totalSizeToAlloc<QualType>(Counts: Expansions.size()),
6812 Align: TypeAlignment);
6813 Canon =
6814 new (Mem) PackIndexingType(QualType(), Pattern.getCanonicalType(),
6815 IndexExpr, FullySubstituted, Expansions);
6816 DependentPackIndexingTypes.InsertNode(N: Canon, InsertPos);
6817 }
6818 Canonical = QualType(Canon, 0);
6819 }
6820
6821 void *Mem =
6822 Allocate(Size: PackIndexingType::totalSizeToAlloc<QualType>(Counts: Expansions.size()),
6823 Align: TypeAlignment);
6824 auto *T = new (Mem) PackIndexingType(Canonical, Pattern, IndexExpr,
6825 FullySubstituted, Expansions);
6826 Types.push_back(Elt: T);
6827 return QualType(T, 0);
6828}
6829
6830/// getUnaryTransformationType - We don't unique these, since the memory
6831/// savings are minimal and these are rare.
6832QualType
6833ASTContext::getUnaryTransformType(QualType BaseType, QualType UnderlyingType,
6834 UnaryTransformType::UTTKind Kind) const {
6835
6836 llvm::FoldingSetNodeID ID;
6837 UnaryTransformType::Profile(ID, BaseType, UnderlyingType, UKind: Kind);
6838
6839 void *InsertPos = nullptr;
6840 if (UnaryTransformType *UT =
6841 UnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos))
6842 return QualType(UT, 0);
6843
6844 QualType CanonType;
6845 if (!BaseType->isDependentType()) {
6846 CanonType = UnderlyingType.getCanonicalType();
6847 } else {
6848 assert(UnderlyingType.isNull() || BaseType == UnderlyingType);
6849 UnderlyingType = QualType();
6850 if (QualType CanonBase = BaseType.getCanonicalType();
6851 BaseType != CanonBase) {
6852 CanonType = getUnaryTransformType(BaseType: CanonBase, UnderlyingType: QualType(), Kind);
6853 assert(CanonType.isCanonical());
6854
6855 // Find the insertion position again.
6856 [[maybe_unused]] UnaryTransformType *UT =
6857 UnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
6858 assert(!UT && "broken canonicalization");
6859 }
6860 }
6861
6862 auto *UT = new (*this, alignof(UnaryTransformType))
6863 UnaryTransformType(BaseType, UnderlyingType, Kind, CanonType);
6864 UnaryTransformTypes.InsertNode(N: UT, InsertPos);
6865 Types.push_back(Elt: UT);
6866 return QualType(UT, 0);
6867}
6868
6869/// getAutoType - Return the uniqued reference to the 'auto' type which has been
6870/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
6871/// canonical deduced-but-dependent 'auto' type.
6872QualType
6873ASTContext::getAutoType(DeducedKind DK, QualType DeducedAsType,
6874 AutoTypeKeyword Keyword,
6875 TemplateDecl *TypeConstraintConcept,
6876 ArrayRef<TemplateArgument> TypeConstraintArgs) const {
6877 if (DK == DeducedKind::Undeduced && Keyword == AutoTypeKeyword::Auto &&
6878 !TypeConstraintConcept) {
6879 assert(DeducedAsType.isNull() && "");
6880 assert(TypeConstraintArgs.empty() && "");
6881 return getAutoDeductType();
6882 }
6883
6884 // Look in the folding set for an existing type.
6885 llvm::FoldingSetNodeID ID;
6886 AutoType::Profile(ID, Context: *this, DK, Deduced: DeducedAsType, Keyword,
6887 CD: TypeConstraintConcept, Arguments: TypeConstraintArgs);
6888 if (auto const AT_iter = AutoTypes.find(Val: ID); AT_iter != AutoTypes.end())
6889 return QualType(AT_iter->getSecond(), 0);
6890
6891 if (DK == DeducedKind::Deduced) {
6892 assert(!DeducedAsType.isNull() && "deduced type must be provided");
6893 } else {
6894 assert(DeducedAsType.isNull() && "deduced type must not be provided");
6895 if (TypeConstraintConcept) {
6896 bool AnyNonCanonArgs = false;
6897 auto *CanonicalConcept =
6898 cast<TemplateDecl>(Val: TypeConstraintConcept->getCanonicalDecl());
6899 auto CanonicalConceptArgs = ::getCanonicalTemplateArguments(
6900 C: *this, Args: TypeConstraintArgs, AnyNonCanonArgs);
6901 if (TypeConstraintConcept != CanonicalConcept || AnyNonCanonArgs)
6902 DeducedAsType = getAutoType(DK, DeducedAsType: QualType(), Keyword, TypeConstraintConcept: CanonicalConcept,
6903 TypeConstraintArgs: CanonicalConceptArgs);
6904 }
6905 }
6906
6907 void *Mem = Allocate(Size: sizeof(AutoType) +
6908 sizeof(TemplateArgument) * TypeConstraintArgs.size(),
6909 Align: alignof(AutoType));
6910 auto *AT = new (Mem) AutoType(DK, DeducedAsType, Keyword,
6911 TypeConstraintConcept, TypeConstraintArgs);
6912#ifndef NDEBUG
6913 llvm::FoldingSetNodeID InsertedID;
6914 AT->Profile(InsertedID, *this);
6915 assert(InsertedID == ID && "ID does not match");
6916#endif
6917 Types.push_back(Elt: AT);
6918 AutoTypes.try_emplace(Key: ID, Args&: AT);
6919 return QualType(AT, 0);
6920}
6921
6922QualType ASTContext::getUnconstrainedType(QualType T) const {
6923 QualType CanonT = T.getNonPackExpansionType().getCanonicalType();
6924
6925 // Remove a type-constraint from a top-level auto or decltype(auto).
6926 if (auto *AT = CanonT->getAs<AutoType>()) {
6927 if (!AT->isConstrained())
6928 return T;
6929 return getQualifiedType(
6930 T: getAutoType(DK: AT->getDeducedKind(), DeducedAsType: QualType(), Keyword: AT->getKeyword()),
6931 Qs: T.getQualifiers());
6932 }
6933
6934 // FIXME: We only support constrained auto at the top level in the type of a
6935 // non-type template parameter at the moment. Once we lift that restriction,
6936 // we'll need to recursively build types containing auto here.
6937 assert(!CanonT->getContainedAutoType() ||
6938 !CanonT->getContainedAutoType()->isConstrained());
6939 return T;
6940}
6941
6942/// Return the uniqued reference to the deduced template specialization type
6943/// which has been deduced to the given type, or to the canonical undeduced
6944/// such type, or the canonical deduced-but-dependent such type.
6945QualType ASTContext::getDeducedTemplateSpecializationType(
6946 DeducedKind DK, QualType DeducedAsType, ElaboratedTypeKeyword Keyword,
6947 TemplateName Template) const {
6948 // Look in the folding set for an existing type.
6949 void *InsertPos = nullptr;
6950 llvm::FoldingSetNodeID ID;
6951 DeducedTemplateSpecializationType::Profile(ID, DK, Deduced: DeducedAsType, Keyword,
6952 Template);
6953 if (DeducedTemplateSpecializationType *DTST =
6954 DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
6955 return QualType(DTST, 0);
6956
6957 if (DK == DeducedKind::Deduced) {
6958 assert(!DeducedAsType.isNull() && "deduced type must be provided");
6959 } else {
6960 assert(DeducedAsType.isNull() && "deduced type must not be provided");
6961 TemplateName CanonTemplateName = getCanonicalTemplateName(Name: Template);
6962 // FIXME: Can this be formed from a DependentTemplateName, such that the
6963 // keyword should be part of the canonical type?
6964 if (Keyword != ElaboratedTypeKeyword::None ||
6965 Template != CanonTemplateName) {
6966 DeducedAsType = getDeducedTemplateSpecializationType(
6967 DK, DeducedAsType: QualType(), Keyword: ElaboratedTypeKeyword::None, Template: CanonTemplateName);
6968 // Find the insertion position again.
6969 [[maybe_unused]] DeducedTemplateSpecializationType *DTST =
6970 DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
6971 assert(!DTST && "broken canonicalization");
6972 }
6973 }
6974
6975 auto *DTST = new (*this, alignof(DeducedTemplateSpecializationType))
6976 DeducedTemplateSpecializationType(DK, DeducedAsType, Keyword, Template);
6977
6978#ifndef NDEBUG
6979 llvm::FoldingSetNodeID TempID;
6980 DTST->Profile(TempID);
6981 assert(ID == TempID && "ID does not match");
6982#endif
6983 Types.push_back(Elt: DTST);
6984 DeducedTemplateSpecializationTypes.InsertNode(N: DTST, InsertPos);
6985 return QualType(DTST, 0);
6986}
6987
6988/// getAtomicType - Return the uniqued reference to the atomic type for
6989/// the given value type.
6990QualType ASTContext::getAtomicType(QualType T) const {
6991 // Unique pointers, to guarantee there is only one pointer of a particular
6992 // structure.
6993 llvm::FoldingSetNodeID ID;
6994 AtomicType::Profile(ID, T);
6995
6996 void *InsertPos = nullptr;
6997 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
6998 return QualType(AT, 0);
6999
7000 // If the atomic value type isn't canonical, this won't be a canonical type
7001 // either, so fill in the canonical type field.
7002 QualType Canonical;
7003 if (!T.isCanonical()) {
7004 Canonical = getAtomicType(T: getCanonicalType(T));
7005
7006 // Get the new insert position for the node we care about.
7007 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
7008 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
7009 }
7010 auto *New = new (*this, alignof(AtomicType)) AtomicType(T, Canonical);
7011 Types.push_back(Elt: New);
7012 AtomicTypes.InsertNode(N: New, InsertPos);
7013 return QualType(New, 0);
7014}
7015
7016/// getAutoDeductType - Get type pattern for deducing against 'auto'.
7017QualType ASTContext::getAutoDeductType() const {
7018 if (AutoDeductTy.isNull())
7019 AutoDeductTy = QualType(new (*this, alignof(AutoType))
7020 AutoType(DeducedKind::Undeduced, QualType(),
7021 AutoTypeKeyword::Auto,
7022 /*TypeConstraintConcept=*/nullptr,
7023 /*TypeConstraintArgs=*/{}),
7024 0);
7025 return AutoDeductTy;
7026}
7027
7028/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
7029QualType ASTContext::getAutoRRefDeductType() const {
7030 if (AutoRRefDeductTy.isNull())
7031 AutoRRefDeductTy = getRValueReferenceType(T: getAutoDeductType());
7032 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
7033 return AutoRRefDeductTy;
7034}
7035
7036/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
7037/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
7038/// needs to agree with the definition in <stddef.h>.
7039QualType ASTContext::getSizeType() const {
7040 return getPredefinedSugarType(KD: PredefinedSugarType::Kind::SizeT);
7041}
7042
7043CanQualType ASTContext::getCanonicalSizeType() const {
7044 return getFromTargetType(Type: Target->getSizeType());
7045}
7046
7047/// Return the unique signed counterpart of the integer type
7048/// corresponding to size_t.
7049QualType ASTContext::getSignedSizeType() const {
7050 return getPredefinedSugarType(KD: PredefinedSugarType::Kind::SignedSizeT);
7051}
7052
7053/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
7054/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
7055QualType ASTContext::getPointerDiffType() const {
7056 return getPredefinedSugarType(KD: PredefinedSugarType::Kind::PtrdiffT);
7057}
7058
7059/// Return the unique unsigned counterpart of "ptrdiff_t"
7060/// integer type. The standard (C11 7.21.6.1p7) refers to this type
7061/// in the definition of %tu format specifier.
7062QualType ASTContext::getUnsignedPointerDiffType() const {
7063 return getFromTargetType(Type: Target->getUnsignedPtrDiffType(AddrSpace: LangAS::Default));
7064}
7065
7066/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
7067CanQualType ASTContext::getIntMaxType() const {
7068 return getFromTargetType(Type: Target->getIntMaxType());
7069}
7070
7071/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
7072CanQualType ASTContext::getUIntMaxType() const {
7073 return getFromTargetType(Type: Target->getUIntMaxType());
7074}
7075
7076/// getSignedWCharType - Return the type of "signed wchar_t".
7077/// Used when in C++, as a GCC extension.
7078QualType ASTContext::getSignedWCharType() const {
7079 // FIXME: derive from "Target" ?
7080 return WCharTy;
7081}
7082
7083/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
7084/// Used when in C++, as a GCC extension.
7085QualType ASTContext::getUnsignedWCharType() const {
7086 // FIXME: derive from "Target" ?
7087 return UnsignedIntTy;
7088}
7089
7090QualType ASTContext::getIntPtrType() const {
7091 return getFromTargetType(Type: Target->getIntPtrType());
7092}
7093
7094QualType ASTContext::getUIntPtrType() const {
7095 return getCorrespondingUnsignedType(T: getIntPtrType());
7096}
7097
7098/// Return the unique type for "pid_t" defined in
7099/// <sys/types.h>. We need this to compute the correct type for vfork().
7100QualType ASTContext::getProcessIDType() const {
7101 return getFromTargetType(Type: Target->getProcessIDType());
7102}
7103
7104//===----------------------------------------------------------------------===//
7105// Type Operators
7106//===----------------------------------------------------------------------===//
7107
7108CanQualType ASTContext::getCanonicalParamType(QualType T) const {
7109 // Push qualifiers into arrays, and then discard any remaining
7110 // qualifiers.
7111 T = getCanonicalType(T);
7112 T = getVariableArrayDecayedType(type: T);
7113 const Type *Ty = T.getTypePtr();
7114 QualType Result;
7115 if (getLangOpts().HLSL && isa<ConstantArrayType>(Val: Ty)) {
7116 Result = getArrayParameterType(Ty: QualType(Ty, 0));
7117 } else if (isa<ArrayType>(Val: Ty)) {
7118 Result = getArrayDecayedType(T: QualType(Ty,0));
7119 } else if (isa<FunctionType>(Val: Ty)) {
7120 Result = getPointerType(T: QualType(Ty, 0));
7121 } else {
7122 Result = QualType(Ty, 0);
7123 }
7124
7125 return CanQualType::CreateUnsafe(Other: Result);
7126}
7127
7128QualType ASTContext::getUnqualifiedArrayType(QualType type,
7129 Qualifiers &quals) const {
7130 SplitQualType splitType = type.getSplitUnqualifiedType();
7131
7132 // FIXME: getSplitUnqualifiedType() actually walks all the way to
7133 // the unqualified desugared type and then drops it on the floor.
7134 // We then have to strip that sugar back off with
7135 // getUnqualifiedDesugaredType(), which is silly.
7136 const auto *AT =
7137 dyn_cast<ArrayType>(Val: splitType.Ty->getUnqualifiedDesugaredType());
7138
7139 // If we don't have an array, just use the results in splitType.
7140 if (!AT) {
7141 quals = splitType.Quals;
7142 return QualType(splitType.Ty, 0);
7143 }
7144
7145 // Otherwise, recurse on the array's element type.
7146 QualType elementType = AT->getElementType();
7147 QualType unqualElementType = getUnqualifiedArrayType(type: elementType, quals);
7148
7149 // If that didn't change the element type, AT has no qualifiers, so we
7150 // can just use the results in splitType.
7151 if (elementType == unqualElementType) {
7152 assert(quals.empty()); // from the recursive call
7153 quals = splitType.Quals;
7154 return QualType(splitType.Ty, 0);
7155 }
7156
7157 // Otherwise, add in the qualifiers from the outermost type, then
7158 // build the type back up.
7159 quals.addConsistentQualifiers(qs: splitType.Quals);
7160
7161 if (const auto *CAT = dyn_cast<ConstantArrayType>(Val: AT)) {
7162 return getConstantArrayType(EltTy: unqualElementType, ArySizeIn: CAT->getSize(),
7163 SizeExpr: CAT->getSizeExpr(), ASM: CAT->getSizeModifier(), IndexTypeQuals: 0);
7164 }
7165
7166 if (const auto *IAT = dyn_cast<IncompleteArrayType>(Val: AT)) {
7167 return getIncompleteArrayType(elementType: unqualElementType, ASM: IAT->getSizeModifier(), elementTypeQuals: 0);
7168 }
7169
7170 if (const auto *VAT = dyn_cast<VariableArrayType>(Val: AT)) {
7171 return getVariableArrayType(EltTy: unqualElementType, NumElts: VAT->getSizeExpr(),
7172 ASM: VAT->getSizeModifier(),
7173 IndexTypeQuals: VAT->getIndexTypeCVRQualifiers());
7174 }
7175
7176 const auto *DSAT = cast<DependentSizedArrayType>(Val: AT);
7177 return getDependentSizedArrayType(elementType: unqualElementType, numElements: DSAT->getSizeExpr(),
7178 ASM: DSAT->getSizeModifier(), elementTypeQuals: 0);
7179}
7180
7181/// Attempt to unwrap two types that may both be array types with the same bound
7182/// (or both be array types of unknown bound) for the purpose of comparing the
7183/// cv-decomposition of two types per C++ [conv.qual].
7184///
7185/// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
7186/// C++20 [conv.qual], if permitted by the current language mode.
7187void ASTContext::UnwrapSimilarArrayTypes(QualType &T1, QualType &T2,
7188 bool AllowPiMismatch) const {
7189 while (true) {
7190 auto *AT1 = getAsArrayType(T: T1);
7191 if (!AT1)
7192 return;
7193
7194 auto *AT2 = getAsArrayType(T: T2);
7195 if (!AT2)
7196 return;
7197
7198 // If we don't have two array types with the same constant bound nor two
7199 // incomplete array types, we've unwrapped everything we can.
7200 // C++20 also permits one type to be a constant array type and the other
7201 // to be an incomplete array type.
7202 // FIXME: Consider also unwrapping array of unknown bound and VLA.
7203 if (auto *CAT1 = dyn_cast<ConstantArrayType>(Val: AT1)) {
7204 auto *CAT2 = dyn_cast<ConstantArrayType>(Val: AT2);
7205 if (!((CAT2 && CAT1->getSize() == CAT2->getSize()) ||
7206 (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
7207 isa<IncompleteArrayType>(Val: AT2))))
7208 return;
7209 } else if (isa<IncompleteArrayType>(Val: AT1)) {
7210 if (!(isa<IncompleteArrayType>(Val: AT2) ||
7211 (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
7212 isa<ConstantArrayType>(Val: AT2))))
7213 return;
7214 } else {
7215 return;
7216 }
7217
7218 T1 = AT1->getElementType();
7219 T2 = AT2->getElementType();
7220 }
7221}
7222
7223/// Attempt to unwrap two types that may be similar (C++ [conv.qual]).
7224///
7225/// If T1 and T2 are both pointer types of the same kind, or both array types
7226/// with the same bound, unwraps layers from T1 and T2 until a pointer type is
7227/// unwrapped. Top-level qualifiers on T1 and T2 are ignored.
7228///
7229/// This function will typically be called in a loop that successively
7230/// "unwraps" pointer and pointer-to-member types to compare them at each
7231/// level.
7232///
7233/// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
7234/// C++20 [conv.qual], if permitted by the current language mode.
7235///
7236/// \return \c true if a pointer type was unwrapped, \c false if we reached a
7237/// pair of types that can't be unwrapped further.
7238bool ASTContext::UnwrapSimilarTypes(QualType &T1, QualType &T2,
7239 bool AllowPiMismatch) const {
7240 UnwrapSimilarArrayTypes(T1, T2, AllowPiMismatch);
7241
7242 const auto *T1PtrType = T1->getAs<PointerType>();
7243 const auto *T2PtrType = T2->getAs<PointerType>();
7244 if (T1PtrType && T2PtrType) {
7245 T1 = T1PtrType->getPointeeType();
7246 T2 = T2PtrType->getPointeeType();
7247 return true;
7248 }
7249
7250 if (const auto *T1MPType = T1->getAsCanonical<MemberPointerType>(),
7251 *T2MPType = T2->getAsCanonical<MemberPointerType>();
7252 T1MPType && T2MPType) {
7253 // Compare the qualifiers of the canonical type, as the non-canonical type
7254 // may have qualifiers pointing to a base or derived class.
7255 if (T1MPType->getQualifier() != T2MPType->getQualifier())
7256 return false;
7257 // Get the pointee types of the non-canonical type, in order to preserve
7258 // their sugar.
7259 T1 = T1->getAs<MemberPointerType>()->getPointeeType();
7260 T2 = T2->getAs<MemberPointerType>()->getPointeeType();
7261 return true;
7262 }
7263
7264 if (getLangOpts().ObjC) {
7265 const auto *T1OPType = T1->getAs<ObjCObjectPointerType>();
7266 const auto *T2OPType = T2->getAs<ObjCObjectPointerType>();
7267 if (T1OPType && T2OPType) {
7268 T1 = T1OPType->getPointeeType();
7269 T2 = T2OPType->getPointeeType();
7270 return true;
7271 }
7272 }
7273
7274 // FIXME: Block pointers, too?
7275
7276 return false;
7277}
7278
7279bool ASTContext::hasSimilarType(QualType T1, QualType T2) const {
7280 while (true) {
7281 Qualifiers Quals;
7282 T1 = getUnqualifiedArrayType(type: T1, quals&: Quals);
7283 T2 = getUnqualifiedArrayType(type: T2, quals&: Quals);
7284 if (hasSameType(T1, T2))
7285 return true;
7286 if (!UnwrapSimilarTypes(T1, T2))
7287 return false;
7288 }
7289}
7290
7291bool ASTContext::hasCvrSimilarType(QualType T1, QualType T2) {
7292 while (true) {
7293 Qualifiers Quals1, Quals2;
7294 T1 = getUnqualifiedArrayType(type: T1, quals&: Quals1);
7295 T2 = getUnqualifiedArrayType(type: T2, quals&: Quals2);
7296
7297 Quals1.removeCVRQualifiers();
7298 Quals2.removeCVRQualifiers();
7299 if (Quals1 != Quals2)
7300 return false;
7301
7302 if (hasSameType(T1, T2))
7303 return true;
7304
7305 if (!UnwrapSimilarTypes(T1, T2, /*AllowPiMismatch*/ false))
7306 return false;
7307 }
7308}
7309
7310DeclarationNameInfo
7311ASTContext::getNameForTemplate(TemplateName Name,
7312 SourceLocation NameLoc) const {
7313 switch (Name.getKind()) {
7314 case TemplateName::QualifiedTemplate:
7315 case TemplateName::Template:
7316 // DNInfo work in progress: CHECKME: what about DNLoc?
7317 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
7318 NameLoc);
7319
7320 case TemplateName::OverloadedTemplate: {
7321 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
7322 // DNInfo work in progress: CHECKME: what about DNLoc?
7323 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
7324 }
7325
7326 case TemplateName::AssumedTemplate: {
7327 AssumedTemplateStorage *Storage = Name.getAsAssumedTemplateName();
7328 return DeclarationNameInfo(Storage->getDeclName(), NameLoc);
7329 }
7330
7331 case TemplateName::DependentTemplate: {
7332 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
7333 IdentifierOrOverloadedOperator TN = DTN->getName();
7334 DeclarationName DName;
7335 if (const IdentifierInfo *II = TN.getIdentifier()) {
7336 DName = DeclarationNames.getIdentifier(ID: II);
7337 return DeclarationNameInfo(DName, NameLoc);
7338 } else {
7339 DName = DeclarationNames.getCXXOperatorName(Op: TN.getOperator());
7340 // DNInfo work in progress: FIXME: source locations?
7341 DeclarationNameLoc DNLoc =
7342 DeclarationNameLoc::makeCXXOperatorNameLoc(Range: SourceRange());
7343 return DeclarationNameInfo(DName, NameLoc, DNLoc);
7344 }
7345 }
7346
7347 case TemplateName::SubstTemplateTemplateParm: {
7348 SubstTemplateTemplateParmStorage *subst
7349 = Name.getAsSubstTemplateTemplateParm();
7350 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
7351 NameLoc);
7352 }
7353
7354 case TemplateName::SubstTemplateTemplateParmPack: {
7355 SubstTemplateTemplateParmPackStorage *subst
7356 = Name.getAsSubstTemplateTemplateParmPack();
7357 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
7358 NameLoc);
7359 }
7360 case TemplateName::UsingTemplate:
7361 return DeclarationNameInfo(Name.getAsUsingShadowDecl()->getDeclName(),
7362 NameLoc);
7363 case TemplateName::DeducedTemplate: {
7364 DeducedTemplateStorage *DTS = Name.getAsDeducedTemplateName();
7365 return getNameForTemplate(Name: DTS->getUnderlying(), NameLoc);
7366 }
7367 }
7368
7369 llvm_unreachable("bad template name kind!");
7370}
7371
7372const TemplateArgument *
7373ASTContext::getDefaultTemplateArgumentOrNone(const NamedDecl *P) const {
7374 auto handleParam = [](auto *TP) -> const TemplateArgument * {
7375 if (!TP->hasDefaultArgument())
7376 return nullptr;
7377 return &TP->getDefaultArgument().getArgument();
7378 };
7379 switch (P->getKind()) {
7380 case NamedDecl::TemplateTypeParm:
7381 return handleParam(cast<TemplateTypeParmDecl>(Val: P));
7382 case NamedDecl::NonTypeTemplateParm:
7383 return handleParam(cast<NonTypeTemplateParmDecl>(Val: P));
7384 case NamedDecl::TemplateTemplateParm:
7385 return handleParam(cast<TemplateTemplateParmDecl>(Val: P));
7386 default:
7387 llvm_unreachable("Unexpected template parameter kind");
7388 }
7389}
7390
7391TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name,
7392 bool IgnoreDeduced) const {
7393 while (std::optional<TemplateName> UnderlyingOrNone =
7394 Name.desugar(IgnoreDeduced))
7395 Name = *UnderlyingOrNone;
7396
7397 switch (Name.getKind()) {
7398 case TemplateName::Template: {
7399 TemplateDecl *Template = Name.getAsTemplateDecl();
7400 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Val: Template))
7401 Template = getCanonicalTemplateTemplateParmDecl(TTP);
7402
7403 // The canonical template name is the canonical template declaration.
7404 return TemplateName(cast<TemplateDecl>(Val: Template->getCanonicalDecl()));
7405 }
7406
7407 case TemplateName::AssumedTemplate:
7408 // An assumed template is just a name, so it is already canonical.
7409 return Name;
7410
7411 case TemplateName::OverloadedTemplate:
7412 llvm_unreachable("cannot canonicalize overloaded template");
7413
7414 case TemplateName::DependentTemplate: {
7415 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
7416 assert(DTN && "Non-dependent template names must refer to template decls.");
7417 NestedNameSpecifier Qualifier = DTN->getQualifier();
7418 NestedNameSpecifier CanonQualifier = Qualifier.getCanonical();
7419 if (Qualifier != CanonQualifier || !DTN->hasTemplateKeyword())
7420 return getDependentTemplateName(Name: {CanonQualifier, DTN->getName(),
7421 /*HasTemplateKeyword=*/true});
7422 return Name;
7423 }
7424
7425 case TemplateName::SubstTemplateTemplateParmPack: {
7426 SubstTemplateTemplateParmPackStorage *subst =
7427 Name.getAsSubstTemplateTemplateParmPack();
7428 TemplateArgument canonArgPack =
7429 getCanonicalTemplateArgument(Arg: subst->getArgumentPack());
7430 return getSubstTemplateTemplateParmPack(
7431 ArgPack: canonArgPack, AssociatedDecl: subst->getAssociatedDecl()->getCanonicalDecl(),
7432 Index: subst->getIndex(), Final: subst->getFinal());
7433 }
7434 case TemplateName::DeducedTemplate: {
7435 assert(IgnoreDeduced == false);
7436 DeducedTemplateStorage *DTS = Name.getAsDeducedTemplateName();
7437 DefaultArguments DefArgs = DTS->getDefaultArguments();
7438 TemplateName Underlying = DTS->getUnderlying();
7439
7440 TemplateName CanonUnderlying =
7441 getCanonicalTemplateName(Name: Underlying, /*IgnoreDeduced=*/true);
7442 bool NonCanonical = CanonUnderlying != Underlying;
7443 auto CanonArgs =
7444 getCanonicalTemplateArguments(C: *this, Args: DefArgs.Args, AnyNonCanonArgs&: NonCanonical);
7445
7446 ArrayRef<NamedDecl *> Params =
7447 CanonUnderlying.getAsTemplateDecl()->getTemplateParameters()->asArray();
7448 assert(CanonArgs.size() <= Params.size());
7449 // A deduced template name which deduces the same default arguments already
7450 // declared in the underlying template is the same template as the
7451 // underlying template. We need need to note any arguments which differ from
7452 // the corresponding declaration. If any argument differs, we must build a
7453 // deduced template name.
7454 for (int I = CanonArgs.size() - 1; I >= 0; --I) {
7455 const TemplateArgument *A = getDefaultTemplateArgumentOrNone(P: Params[I]);
7456 if (!A)
7457 break;
7458 auto CanonParamDefArg = getCanonicalTemplateArgument(Arg: *A);
7459 TemplateArgument &CanonDefArg = CanonArgs[I];
7460 if (CanonDefArg.structurallyEquals(Other: CanonParamDefArg))
7461 continue;
7462 // Keep popping from the back any deault arguments which are the same.
7463 if (I == int(CanonArgs.size() - 1))
7464 CanonArgs.pop_back();
7465 NonCanonical = true;
7466 }
7467 return NonCanonical ? getDeducedTemplateName(
7468 Underlying: CanonUnderlying,
7469 /*DefaultArgs=*/{.StartPos: DefArgs.StartPos, .Args: CanonArgs})
7470 : Name;
7471 }
7472 case TemplateName::UsingTemplate:
7473 case TemplateName::QualifiedTemplate:
7474 case TemplateName::SubstTemplateTemplateParm:
7475 llvm_unreachable("always sugar node");
7476 }
7477
7478 llvm_unreachable("bad template name!");
7479}
7480
7481bool ASTContext::hasSameTemplateName(const TemplateName &X,
7482 const TemplateName &Y,
7483 bool IgnoreDeduced) const {
7484 return getCanonicalTemplateName(Name: X, IgnoreDeduced) ==
7485 getCanonicalTemplateName(Name: Y, IgnoreDeduced);
7486}
7487
7488bool ASTContext::isSameAssociatedConstraint(
7489 const AssociatedConstraint &ACX, const AssociatedConstraint &ACY) const {
7490 if (ACX.ArgPackSubstIndex != ACY.ArgPackSubstIndex)
7491 return false;
7492 if (!isSameConstraintExpr(XCE: ACX.ConstraintExpr, YCE: ACY.ConstraintExpr))
7493 return false;
7494 return true;
7495}
7496
7497bool ASTContext::isSameConstraintExpr(const Expr *XCE, const Expr *YCE) const {
7498 if (!XCE != !YCE)
7499 return false;
7500
7501 if (!XCE)
7502 return true;
7503
7504 llvm::FoldingSetNodeID XCEID, YCEID;
7505 XCE->Profile(ID&: XCEID, Context: *this, /*Canonical=*/true, /*ProfileLambdaExpr=*/true);
7506 YCE->Profile(ID&: YCEID, Context: *this, /*Canonical=*/true, /*ProfileLambdaExpr=*/true);
7507 return XCEID == YCEID;
7508}
7509
7510bool ASTContext::isSameTypeConstraint(const TypeConstraint *XTC,
7511 const TypeConstraint *YTC) const {
7512 if (!XTC != !YTC)
7513 return false;
7514
7515 if (!XTC)
7516 return true;
7517
7518 auto *NCX = XTC->getNamedConcept();
7519 auto *NCY = YTC->getNamedConcept();
7520 if (!NCX || !NCY || !isSameEntity(X: NCX, Y: NCY))
7521 return false;
7522 if (XTC->getConceptReference()->hasExplicitTemplateArgs() !=
7523 YTC->getConceptReference()->hasExplicitTemplateArgs())
7524 return false;
7525 if (XTC->getConceptReference()->hasExplicitTemplateArgs())
7526 if (XTC->getConceptReference()
7527 ->getTemplateArgsAsWritten()
7528 ->NumTemplateArgs !=
7529 YTC->getConceptReference()->getTemplateArgsAsWritten()->NumTemplateArgs)
7530 return false;
7531
7532 // Compare slowly by profiling.
7533 //
7534 // We couldn't compare the profiling result for the template
7535 // args here. Consider the following example in different modules:
7536 //
7537 // template <__integer_like _Tp, C<_Tp> Sentinel>
7538 // constexpr _Tp operator()(_Tp &&__t, Sentinel &&last) const {
7539 // return __t;
7540 // }
7541 //
7542 // When we compare the profiling result for `C<_Tp>` in different
7543 // modules, it will compare the type of `_Tp` in different modules.
7544 // However, the type of `_Tp` in different modules refer to different
7545 // types here naturally. So we couldn't compare the profiling result
7546 // for the template args directly.
7547 return isSameConstraintExpr(XCE: XTC->getImmediatelyDeclaredConstraint(),
7548 YCE: YTC->getImmediatelyDeclaredConstraint());
7549}
7550
7551bool ASTContext::isSameTemplateParameter(const NamedDecl *X,
7552 const NamedDecl *Y) const {
7553 if (X->getKind() != Y->getKind())
7554 return false;
7555
7556 if (auto *TX = dyn_cast<TemplateTypeParmDecl>(Val: X)) {
7557 auto *TY = cast<TemplateTypeParmDecl>(Val: Y);
7558 if (TX->isParameterPack() != TY->isParameterPack())
7559 return false;
7560 if (TX->hasTypeConstraint() != TY->hasTypeConstraint())
7561 return false;
7562 return isSameTypeConstraint(XTC: TX->getTypeConstraint(),
7563 YTC: TY->getTypeConstraint());
7564 }
7565
7566 if (auto *TX = dyn_cast<NonTypeTemplateParmDecl>(Val: X)) {
7567 auto *TY = cast<NonTypeTemplateParmDecl>(Val: Y);
7568 return TX->isParameterPack() == TY->isParameterPack() &&
7569 TX->getASTContext().hasSameType(T1: TX->getType(), T2: TY->getType()) &&
7570 isSameConstraintExpr(XCE: TX->getPlaceholderTypeConstraint(),
7571 YCE: TY->getPlaceholderTypeConstraint());
7572 }
7573
7574 auto *TX = cast<TemplateTemplateParmDecl>(Val: X);
7575 auto *TY = cast<TemplateTemplateParmDecl>(Val: Y);
7576 return TX->isParameterPack() == TY->isParameterPack() &&
7577 isSameTemplateParameterList(X: TX->getTemplateParameters(),
7578 Y: TY->getTemplateParameters());
7579}
7580
7581bool ASTContext::isSameTemplateParameterList(
7582 const TemplateParameterList *X, const TemplateParameterList *Y) const {
7583 if (X->size() != Y->size())
7584 return false;
7585
7586 for (unsigned I = 0, N = X->size(); I != N; ++I)
7587 if (!isSameTemplateParameter(X: X->getParam(Idx: I), Y: Y->getParam(Idx: I)))
7588 return false;
7589
7590 return isSameConstraintExpr(XCE: X->getRequiresClause(), YCE: Y->getRequiresClause());
7591}
7592
7593bool ASTContext::isSameDefaultTemplateArgument(const NamedDecl *X,
7594 const NamedDecl *Y) const {
7595 // If the type parameter isn't the same already, we don't need to check the
7596 // default argument further.
7597 if (!isSameTemplateParameter(X, Y))
7598 return false;
7599
7600 if (auto *TTPX = dyn_cast<TemplateTypeParmDecl>(Val: X)) {
7601 auto *TTPY = cast<TemplateTypeParmDecl>(Val: Y);
7602 if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument())
7603 return false;
7604
7605 return hasSameType(T1: TTPX->getDefaultArgument().getArgument().getAsType(),
7606 T2: TTPY->getDefaultArgument().getArgument().getAsType());
7607 }
7608
7609 if (auto *NTTPX = dyn_cast<NonTypeTemplateParmDecl>(Val: X)) {
7610 auto *NTTPY = cast<NonTypeTemplateParmDecl>(Val: Y);
7611 if (!NTTPX->hasDefaultArgument() || !NTTPY->hasDefaultArgument())
7612 return false;
7613
7614 Expr *DefaultArgumentX =
7615 NTTPX->getDefaultArgument().getArgument().getAsExpr()->IgnoreImpCasts();
7616 Expr *DefaultArgumentY =
7617 NTTPY->getDefaultArgument().getArgument().getAsExpr()->IgnoreImpCasts();
7618 llvm::FoldingSetNodeID XID, YID;
7619 DefaultArgumentX->Profile(ID&: XID, Context: *this, /*Canonical=*/true);
7620 DefaultArgumentY->Profile(ID&: YID, Context: *this, /*Canonical=*/true);
7621 return XID == YID;
7622 }
7623
7624 auto *TTPX = cast<TemplateTemplateParmDecl>(Val: X);
7625 auto *TTPY = cast<TemplateTemplateParmDecl>(Val: Y);
7626
7627 if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument())
7628 return false;
7629
7630 const TemplateArgument &TAX = TTPX->getDefaultArgument().getArgument();
7631 const TemplateArgument &TAY = TTPY->getDefaultArgument().getArgument();
7632 return hasSameTemplateName(X: TAX.getAsTemplate(), Y: TAY.getAsTemplate());
7633}
7634
7635static bool isSameQualifier(const NestedNameSpecifier X,
7636 const NestedNameSpecifier Y) {
7637 if (X == Y)
7638 return true;
7639 if (!X || !Y)
7640 return false;
7641
7642 auto Kind = X.getKind();
7643 if (Kind != Y.getKind())
7644 return false;
7645
7646 // FIXME: For namespaces and types, we're permitted to check that the entity
7647 // is named via the same tokens. We should probably do so.
7648 switch (Kind) {
7649 case NestedNameSpecifier::Kind::Namespace: {
7650 auto [NamespaceX, PrefixX] = X.getAsNamespaceAndPrefix();
7651 auto [NamespaceY, PrefixY] = Y.getAsNamespaceAndPrefix();
7652 if (!declaresSameEntity(D1: NamespaceX->getNamespace(),
7653 D2: NamespaceY->getNamespace()))
7654 return false;
7655 return isSameQualifier(X: PrefixX, Y: PrefixY);
7656 }
7657 case NestedNameSpecifier::Kind::Type: {
7658 const auto *TX = X.getAsType(), *TY = Y.getAsType();
7659 if (TX->getCanonicalTypeInternal() != TY->getCanonicalTypeInternal())
7660 return false;
7661 return isSameQualifier(X: TX->getPrefix(), Y: TY->getPrefix());
7662 }
7663 case NestedNameSpecifier::Kind::Null:
7664 case NestedNameSpecifier::Kind::Global:
7665 case NestedNameSpecifier::Kind::MicrosoftSuper:
7666 return true;
7667 }
7668 llvm_unreachable("unhandled qualifier kind");
7669}
7670
7671static bool hasSameCudaAttrs(const FunctionDecl *A, const FunctionDecl *B) {
7672 if (!A->getASTContext().getLangOpts().CUDA)
7673 return true; // Target attributes are overloadable in CUDA compilation only.
7674 if (A->hasAttr<CUDADeviceAttr>() != B->hasAttr<CUDADeviceAttr>())
7675 return false;
7676 if (A->hasAttr<CUDADeviceAttr>() && B->hasAttr<CUDADeviceAttr>())
7677 return A->hasAttr<CUDAHostAttr>() == B->hasAttr<CUDAHostAttr>();
7678 return true; // unattributed and __host__ functions are the same.
7679}
7680
7681/// Determine whether the attributes we can overload on are identical for A and
7682/// B. Will ignore any overloadable attrs represented in the type of A and B.
7683static bool hasSameOverloadableAttrs(const FunctionDecl *A,
7684 const FunctionDecl *B) {
7685 // Note that pass_object_size attributes are represented in the function's
7686 // ExtParameterInfo, so we don't need to check them here.
7687
7688 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
7689 auto AEnableIfAttrs = A->specific_attrs<EnableIfAttr>();
7690 auto BEnableIfAttrs = B->specific_attrs<EnableIfAttr>();
7691
7692 for (auto Pair : zip_longest(t&: AEnableIfAttrs, u&: BEnableIfAttrs)) {
7693 std::optional<EnableIfAttr *> Cand1A = std::get<0>(t&: Pair);
7694 std::optional<EnableIfAttr *> Cand2A = std::get<1>(t&: Pair);
7695
7696 // Return false if the number of enable_if attributes is different.
7697 if (!Cand1A || !Cand2A)
7698 return false;
7699
7700 Cand1ID.clear();
7701 Cand2ID.clear();
7702
7703 (*Cand1A)->getCond()->Profile(ID&: Cand1ID, Context: A->getASTContext(), Canonical: true);
7704 (*Cand2A)->getCond()->Profile(ID&: Cand2ID, Context: B->getASTContext(), Canonical: true);
7705
7706 // Return false if any of the enable_if expressions of A and B are
7707 // different.
7708 if (Cand1ID != Cand2ID)
7709 return false;
7710 }
7711 return hasSameCudaAttrs(A, B);
7712}
7713
7714bool ASTContext::isSameEntity(const NamedDecl *X, const NamedDecl *Y) const {
7715 // Caution: this function is called by the AST reader during deserialization,
7716 // so it cannot rely on AST invariants being met. Non-trivial accessors
7717 // should be avoided, along with any traversal of redeclaration chains.
7718
7719 if (X == Y)
7720 return true;
7721
7722 if (X->getDeclName() != Y->getDeclName())
7723 return false;
7724
7725 // Must be in the same context.
7726 //
7727 // Note that we can't use DeclContext::Equals here, because the DeclContexts
7728 // could be two different declarations of the same function. (We will fix the
7729 // semantic DC to refer to the primary definition after merging.)
7730 if (!declaresSameEntity(D1: cast<Decl>(Val: X->getDeclContext()->getRedeclContext()),
7731 D2: cast<Decl>(Val: Y->getDeclContext()->getRedeclContext())))
7732 return false;
7733
7734 // If either X or Y are local to the owning module, they are only possible to
7735 // be the same entity if they are in the same module.
7736 if (X->isModuleLocal() || Y->isModuleLocal())
7737 if (!isInSameModule(M1: X->getOwningModule(), M2: Y->getOwningModule()))
7738 return false;
7739
7740 // Two typedefs refer to the same entity if they have the same underlying
7741 // type.
7742 if (const auto *TypedefX = dyn_cast<TypedefNameDecl>(Val: X))
7743 if (const auto *TypedefY = dyn_cast<TypedefNameDecl>(Val: Y))
7744 return hasSameType(T1: TypedefX->getUnderlyingType(),
7745 T2: TypedefY->getUnderlyingType());
7746
7747 // Must have the same kind.
7748 if (X->getKind() != Y->getKind())
7749 return false;
7750
7751 // Objective-C classes and protocols with the same name always match.
7752 if (isa<ObjCInterfaceDecl>(Val: X) || isa<ObjCProtocolDecl>(Val: X))
7753 return true;
7754
7755 if (isa<ClassTemplateSpecializationDecl>(Val: X)) {
7756 // No need to handle these here: we merge them when adding them to the
7757 // template.
7758 return false;
7759 }
7760
7761 // Compatible tags match.
7762 if (const auto *TagX = dyn_cast<TagDecl>(Val: X)) {
7763 const auto *TagY = cast<TagDecl>(Val: Y);
7764 return (TagX->getTagKind() == TagY->getTagKind()) ||
7765 ((TagX->getTagKind() == TagTypeKind::Struct ||
7766 TagX->getTagKind() == TagTypeKind::Class ||
7767 TagX->getTagKind() == TagTypeKind::Interface) &&
7768 (TagY->getTagKind() == TagTypeKind::Struct ||
7769 TagY->getTagKind() == TagTypeKind::Class ||
7770 TagY->getTagKind() == TagTypeKind::Interface));
7771 }
7772
7773 // Functions with the same type and linkage match.
7774 // FIXME: This needs to cope with merging of prototyped/non-prototyped
7775 // functions, etc.
7776 if (const auto *FuncX = dyn_cast<FunctionDecl>(Val: X)) {
7777 const auto *FuncY = cast<FunctionDecl>(Val: Y);
7778 if (const auto *CtorX = dyn_cast<CXXConstructorDecl>(Val: X)) {
7779 const auto *CtorY = cast<CXXConstructorDecl>(Val: Y);
7780 if (CtorX->getInheritedConstructor() &&
7781 !isSameEntity(X: CtorX->getInheritedConstructor().getConstructor(),
7782 Y: CtorY->getInheritedConstructor().getConstructor()))
7783 return false;
7784 }
7785
7786 if (FuncX->isMultiVersion() != FuncY->isMultiVersion())
7787 return false;
7788
7789 // Multiversioned functions with different feature strings are represented
7790 // as separate declarations.
7791 if (FuncX->isMultiVersion()) {
7792 const auto *TAX = FuncX->getAttr<TargetAttr>();
7793 const auto *TAY = FuncY->getAttr<TargetAttr>();
7794 assert(TAX && TAY && "Multiversion Function without target attribute");
7795
7796 if (TAX->getFeaturesStr() != TAY->getFeaturesStr())
7797 return false;
7798 }
7799
7800 // Per C++20 [temp.over.link]/4, friends in different classes are sometimes
7801 // not the same entity if they are constrained.
7802 if ((FuncX->isMemberLikeConstrainedFriend() ||
7803 FuncY->isMemberLikeConstrainedFriend()) &&
7804 !FuncX->getLexicalDeclContext()->Equals(
7805 DC: FuncY->getLexicalDeclContext())) {
7806 return false;
7807 }
7808
7809 if (!isSameAssociatedConstraint(ACX: FuncX->getTrailingRequiresClause(),
7810 ACY: FuncY->getTrailingRequiresClause()))
7811 return false;
7812
7813 auto GetTypeAsWritten = [](const FunctionDecl *FD) {
7814 // Map to the first declaration that we've already merged into this one.
7815 // The TSI of redeclarations might not match (due to calling conventions
7816 // being inherited onto the type but not the TSI), but the TSI type of
7817 // the first declaration of the function should match across modules.
7818 FD = FD->getCanonicalDecl();
7819 return FD->getTypeSourceInfo() ? FD->getTypeSourceInfo()->getType()
7820 : FD->getType();
7821 };
7822 QualType XT = GetTypeAsWritten(FuncX), YT = GetTypeAsWritten(FuncY);
7823 if (!hasSameType(T1: XT, T2: YT)) {
7824 // We can get functions with different types on the redecl chain in C++17
7825 // if they have differing exception specifications and at least one of
7826 // the excpetion specs is unresolved.
7827 auto *XFPT = XT->getAs<FunctionProtoType>();
7828 auto *YFPT = YT->getAs<FunctionProtoType>();
7829 if (getLangOpts().CPlusPlus17 && XFPT && YFPT &&
7830 (isUnresolvedExceptionSpec(ESpecType: XFPT->getExceptionSpecType()) ||
7831 isUnresolvedExceptionSpec(ESpecType: YFPT->getExceptionSpecType())) &&
7832 hasSameFunctionTypeIgnoringExceptionSpec(T: XT, U: YT))
7833 return true;
7834 return false;
7835 }
7836
7837 return FuncX->getLinkageInternal() == FuncY->getLinkageInternal() &&
7838 hasSameOverloadableAttrs(A: FuncX, B: FuncY);
7839 }
7840
7841 // Variables with the same type and linkage match.
7842 if (const auto *VarX = dyn_cast<VarDecl>(Val: X)) {
7843 const auto *VarY = cast<VarDecl>(Val: Y);
7844 if (VarX->getLinkageInternal() == VarY->getLinkageInternal()) {
7845 // During deserialization, we might compare variables before we load
7846 // their types. Assume the types will end up being the same.
7847 if (VarX->getType().isNull() || VarY->getType().isNull())
7848 return true;
7849
7850 if (hasSameType(T1: VarX->getType(), T2: VarY->getType()))
7851 return true;
7852
7853 // We can get decls with different types on the redecl chain. Eg.
7854 // template <typename T> struct S { static T Var[]; }; // #1
7855 // template <typename T> T S<T>::Var[sizeof(T)]; // #2
7856 // Only? happens when completing an incomplete array type. In this case
7857 // when comparing #1 and #2 we should go through their element type.
7858 const ArrayType *VarXTy = getAsArrayType(T: VarX->getType());
7859 const ArrayType *VarYTy = getAsArrayType(T: VarY->getType());
7860 if (!VarXTy || !VarYTy)
7861 return false;
7862 if (VarXTy->isIncompleteArrayType() || VarYTy->isIncompleteArrayType())
7863 return hasSameType(T1: VarXTy->getElementType(), T2: VarYTy->getElementType());
7864 }
7865 return false;
7866 }
7867
7868 // Namespaces with the same name and inlinedness match.
7869 if (const auto *NamespaceX = dyn_cast<NamespaceDecl>(Val: X)) {
7870 const auto *NamespaceY = cast<NamespaceDecl>(Val: Y);
7871 return NamespaceX->isInline() == NamespaceY->isInline();
7872 }
7873
7874 // Identical template names and kinds match if their template parameter lists
7875 // and patterns match.
7876 if (const auto *TemplateX = dyn_cast<TemplateDecl>(Val: X)) {
7877 const auto *TemplateY = cast<TemplateDecl>(Val: Y);
7878
7879 // ConceptDecl wouldn't be the same if their constraint expression differs.
7880 if (const auto *ConceptX = dyn_cast<ConceptDecl>(Val: X)) {
7881 const auto *ConceptY = cast<ConceptDecl>(Val: Y);
7882 if (!isSameConstraintExpr(XCE: ConceptX->getConstraintExpr(),
7883 YCE: ConceptY->getConstraintExpr()))
7884 return false;
7885 }
7886
7887 return isSameEntity(X: TemplateX->getTemplatedDecl(),
7888 Y: TemplateY->getTemplatedDecl()) &&
7889 isSameTemplateParameterList(X: TemplateX->getTemplateParameters(),
7890 Y: TemplateY->getTemplateParameters());
7891 }
7892
7893 // Fields with the same name and the same type match.
7894 if (const auto *FDX = dyn_cast<FieldDecl>(Val: X)) {
7895 const auto *FDY = cast<FieldDecl>(Val: Y);
7896 // FIXME: Also check the bitwidth is odr-equivalent, if any.
7897 return hasSameType(T1: FDX->getType(), T2: FDY->getType());
7898 }
7899
7900 // Indirect fields with the same target field match.
7901 if (const auto *IFDX = dyn_cast<IndirectFieldDecl>(Val: X)) {
7902 const auto *IFDY = cast<IndirectFieldDecl>(Val: Y);
7903 return IFDX->getAnonField()->getCanonicalDecl() ==
7904 IFDY->getAnonField()->getCanonicalDecl();
7905 }
7906
7907 // Enumerators with the same name match.
7908 if (isa<EnumConstantDecl>(Val: X))
7909 // FIXME: Also check the value is odr-equivalent.
7910 return true;
7911
7912 // Using shadow declarations with the same target match.
7913 if (const auto *USX = dyn_cast<UsingShadowDecl>(Val: X)) {
7914 const auto *USY = cast<UsingShadowDecl>(Val: Y);
7915 return declaresSameEntity(D1: USX->getTargetDecl(), D2: USY->getTargetDecl());
7916 }
7917
7918 // Using declarations with the same qualifier match. (We already know that
7919 // the name matches.)
7920 if (const auto *UX = dyn_cast<UsingDecl>(Val: X)) {
7921 const auto *UY = cast<UsingDecl>(Val: Y);
7922 return isSameQualifier(X: UX->getQualifier(), Y: UY->getQualifier()) &&
7923 UX->hasTypename() == UY->hasTypename() &&
7924 UX->isAccessDeclaration() == UY->isAccessDeclaration();
7925 }
7926 if (const auto *UX = dyn_cast<UnresolvedUsingValueDecl>(Val: X)) {
7927 const auto *UY = cast<UnresolvedUsingValueDecl>(Val: Y);
7928 return isSameQualifier(X: UX->getQualifier(), Y: UY->getQualifier()) &&
7929 UX->isAccessDeclaration() == UY->isAccessDeclaration();
7930 }
7931 if (const auto *UX = dyn_cast<UnresolvedUsingTypenameDecl>(Val: X)) {
7932 return isSameQualifier(
7933 X: UX->getQualifier(),
7934 Y: cast<UnresolvedUsingTypenameDecl>(Val: Y)->getQualifier());
7935 }
7936
7937 // Using-pack declarations are only created by instantiation, and match if
7938 // they're instantiated from matching UnresolvedUsing...Decls.
7939 if (const auto *UX = dyn_cast<UsingPackDecl>(Val: X)) {
7940 return declaresSameEntity(
7941 D1: UX->getInstantiatedFromUsingDecl(),
7942 D2: cast<UsingPackDecl>(Val: Y)->getInstantiatedFromUsingDecl());
7943 }
7944
7945 // Namespace alias definitions with the same target match.
7946 if (const auto *NAX = dyn_cast<NamespaceAliasDecl>(Val: X)) {
7947 const auto *NAY = cast<NamespaceAliasDecl>(Val: Y);
7948 return NAX->getNamespace()->Equals(DC: NAY->getNamespace());
7949 }
7950
7951 return false;
7952}
7953
7954TemplateArgument
7955ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
7956 switch (Arg.getKind()) {
7957 case TemplateArgument::Null:
7958 return Arg;
7959
7960 case TemplateArgument::Expression:
7961 return TemplateArgument(Arg.getAsExpr(), /*IsCanonical=*/true,
7962 Arg.getIsDefaulted());
7963
7964 case TemplateArgument::Declaration: {
7965 auto *D = cast<ValueDecl>(Val: Arg.getAsDecl()->getCanonicalDecl());
7966 return TemplateArgument(D, getCanonicalType(T: Arg.getParamTypeForDecl()),
7967 Arg.getIsDefaulted());
7968 }
7969
7970 case TemplateArgument::NullPtr:
7971 return TemplateArgument(getCanonicalType(T: Arg.getNullPtrType()),
7972 /*isNullPtr*/ true, Arg.getIsDefaulted());
7973
7974 case TemplateArgument::Template:
7975 return TemplateArgument(getCanonicalTemplateName(Name: Arg.getAsTemplate()),
7976 Arg.getIsDefaulted());
7977
7978 case TemplateArgument::TemplateExpansion:
7979 return TemplateArgument(
7980 getCanonicalTemplateName(Name: Arg.getAsTemplateOrTemplatePattern()),
7981 Arg.getNumTemplateExpansions(), Arg.getIsDefaulted());
7982
7983 case TemplateArgument::Integral:
7984 return TemplateArgument(Arg, getCanonicalType(T: Arg.getIntegralType()));
7985
7986 case TemplateArgument::StructuralValue:
7987 return TemplateArgument(*this,
7988 getCanonicalType(T: Arg.getStructuralValueType()),
7989 Arg.getAsStructuralValue(), Arg.getIsDefaulted());
7990
7991 case TemplateArgument::Type:
7992 return TemplateArgument(getCanonicalType(T: Arg.getAsType()),
7993 /*isNullPtr*/ false, Arg.getIsDefaulted());
7994
7995 case TemplateArgument::Pack: {
7996 bool AnyNonCanonArgs = false;
7997 auto CanonArgs = ::getCanonicalTemplateArguments(
7998 C: *this, Args: Arg.pack_elements(), AnyNonCanonArgs);
7999 if (!AnyNonCanonArgs)
8000 return Arg;
8001 auto NewArg = TemplateArgument::CreatePackCopy(
8002 Context&: const_cast<ASTContext &>(*this), Args: CanonArgs);
8003 NewArg.setIsDefaulted(Arg.getIsDefaulted());
8004 return NewArg;
8005 }
8006 }
8007
8008 // Silence GCC warning
8009 llvm_unreachable("Unhandled template argument kind");
8010}
8011
8012bool ASTContext::isSameTemplateArgument(const TemplateArgument &Arg1,
8013 const TemplateArgument &Arg2) const {
8014 if (Arg1.getKind() != Arg2.getKind())
8015 return false;
8016
8017 switch (Arg1.getKind()) {
8018 case TemplateArgument::Null:
8019 llvm_unreachable("Comparing NULL template argument");
8020
8021 case TemplateArgument::Type:
8022 return hasSameType(T1: Arg1.getAsType(), T2: Arg2.getAsType());
8023
8024 case TemplateArgument::Declaration:
8025 return Arg1.getAsDecl()->getUnderlyingDecl()->getCanonicalDecl() ==
8026 Arg2.getAsDecl()->getUnderlyingDecl()->getCanonicalDecl();
8027
8028 case TemplateArgument::NullPtr:
8029 return hasSameType(T1: Arg1.getNullPtrType(), T2: Arg2.getNullPtrType());
8030
8031 case TemplateArgument::Template:
8032 case TemplateArgument::TemplateExpansion:
8033 return getCanonicalTemplateName(Name: Arg1.getAsTemplateOrTemplatePattern()) ==
8034 getCanonicalTemplateName(Name: Arg2.getAsTemplateOrTemplatePattern());
8035
8036 case TemplateArgument::Integral:
8037 return llvm::APSInt::isSameValue(I1: Arg1.getAsIntegral(),
8038 I2: Arg2.getAsIntegral());
8039
8040 case TemplateArgument::StructuralValue:
8041 return Arg1.structurallyEquals(Other: Arg2);
8042
8043 case TemplateArgument::Expression: {
8044 llvm::FoldingSetNodeID ID1, ID2;
8045 Arg1.getAsExpr()->Profile(ID&: ID1, Context: *this, /*Canonical=*/true);
8046 Arg2.getAsExpr()->Profile(ID&: ID2, Context: *this, /*Canonical=*/true);
8047 return ID1 == ID2;
8048 }
8049
8050 case TemplateArgument::Pack:
8051 return llvm::equal(
8052 LRange: Arg1.getPackAsArray(), RRange: Arg2.getPackAsArray(),
8053 P: [&](const TemplateArgument &Arg1, const TemplateArgument &Arg2) {
8054 return isSameTemplateArgument(Arg1, Arg2);
8055 });
8056 }
8057
8058 llvm_unreachable("Unhandled template argument kind");
8059}
8060
8061const ArrayType *ASTContext::getAsArrayType(QualType T) const {
8062 // Handle the non-qualified case efficiently.
8063 if (!T.hasLocalQualifiers()) {
8064 // Handle the common positive case fast.
8065 if (const auto *AT = dyn_cast<ArrayType>(Val&: T))
8066 return AT;
8067 }
8068
8069 // Handle the common negative case fast.
8070 if (!isa<ArrayType>(Val: T.getCanonicalType()))
8071 return nullptr;
8072
8073 // Apply any qualifiers from the array type to the element type. This
8074 // implements C99 6.7.3p8: "If the specification of an array type includes
8075 // any type qualifiers, the element type is so qualified, not the array type."
8076
8077 // If we get here, we either have type qualifiers on the type, or we have
8078 // sugar such as a typedef in the way. If we have type qualifiers on the type
8079 // we must propagate them down into the element type.
8080
8081 SplitQualType split = T.getSplitDesugaredType();
8082 Qualifiers qs = split.Quals;
8083
8084 // If we have a simple case, just return now.
8085 const auto *ATy = dyn_cast<ArrayType>(Val: split.Ty);
8086 if (!ATy || qs.empty())
8087 return ATy;
8088
8089 // Otherwise, we have an array and we have qualifiers on it. Push the
8090 // qualifiers into the array element type and return a new array type.
8091 QualType NewEltTy = getQualifiedType(T: ATy->getElementType(), Qs: qs);
8092
8093 if (const auto *CAT = dyn_cast<ConstantArrayType>(Val: ATy))
8094 return cast<ArrayType>(Val: getConstantArrayType(EltTy: NewEltTy, ArySizeIn: CAT->getSize(),
8095 SizeExpr: CAT->getSizeExpr(),
8096 ASM: CAT->getSizeModifier(),
8097 IndexTypeQuals: CAT->getIndexTypeCVRQualifiers()));
8098 if (const auto *IAT = dyn_cast<IncompleteArrayType>(Val: ATy))
8099 return cast<ArrayType>(Val: getIncompleteArrayType(elementType: NewEltTy,
8100 ASM: IAT->getSizeModifier(),
8101 elementTypeQuals: IAT->getIndexTypeCVRQualifiers()));
8102
8103 if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(Val: ATy))
8104 return cast<ArrayType>(Val: getDependentSizedArrayType(
8105 elementType: NewEltTy, numElements: DSAT->getSizeExpr(), ASM: DSAT->getSizeModifier(),
8106 elementTypeQuals: DSAT->getIndexTypeCVRQualifiers()));
8107
8108 const auto *VAT = cast<VariableArrayType>(Val: ATy);
8109 return cast<ArrayType>(
8110 Val: getVariableArrayType(EltTy: NewEltTy, NumElts: VAT->getSizeExpr(), ASM: VAT->getSizeModifier(),
8111 IndexTypeQuals: VAT->getIndexTypeCVRQualifiers()));
8112}
8113
8114QualType ASTContext::getAdjustedParameterType(QualType T) const {
8115 if (getLangOpts().HLSL && T.getAddressSpace() == LangAS::hlsl_groupshared)
8116 return getLValueReferenceType(T);
8117 if (getLangOpts().HLSL && T->isConstantArrayType())
8118 return getArrayParameterType(Ty: T);
8119 if (T->isArrayType() || T->isFunctionType())
8120 return getDecayedType(T);
8121 return T;
8122}
8123
8124QualType ASTContext::getSignatureParameterType(QualType T) const {
8125 T = getVariableArrayDecayedType(type: T);
8126 T = getAdjustedParameterType(T);
8127 return T.getUnqualifiedType();
8128}
8129
8130QualType ASTContext::getExceptionObjectType(QualType T) const {
8131 // C++ [except.throw]p3:
8132 // A throw-expression initializes a temporary object, called the exception
8133 // object, the type of which is determined by removing any top-level
8134 // cv-qualifiers from the static type of the operand of throw and adjusting
8135 // the type from "array of T" or "function returning T" to "pointer to T"
8136 // or "pointer to function returning T", [...]
8137 T = getVariableArrayDecayedType(type: T);
8138 if (T->isArrayType() || T->isFunctionType())
8139 T = getDecayedType(T);
8140 return T.getUnqualifiedType();
8141}
8142
8143/// getArrayDecayedType - Return the properly qualified result of decaying the
8144/// specified array type to a pointer. This operation is non-trivial when
8145/// handling typedefs etc. The canonical type of "T" must be an array type,
8146/// this returns a pointer to a properly qualified element of the array.
8147///
8148/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
8149QualType ASTContext::getArrayDecayedType(QualType Ty) const {
8150 // Get the element type with 'getAsArrayType' so that we don't lose any
8151 // typedefs in the element type of the array. This also handles propagation
8152 // of type qualifiers from the array type into the element type if present
8153 // (C99 6.7.3p8).
8154 const ArrayType *PrettyArrayType = getAsArrayType(T: Ty);
8155 assert(PrettyArrayType && "Not an array type!");
8156
8157 QualType PtrTy = getPointerType(T: PrettyArrayType->getElementType());
8158
8159 // int x[restrict 4] -> int *restrict
8160 QualType Result = getQualifiedType(T: PtrTy,
8161 Qs: PrettyArrayType->getIndexTypeQualifiers());
8162
8163 // int x[_Nullable] -> int * _Nullable
8164 if (auto Nullability = Ty->getNullability()) {
8165 Result = const_cast<ASTContext *>(this)->getAttributedType(nullability: *Nullability,
8166 modifiedType: Result, equivalentType: Result);
8167 }
8168 return Result;
8169}
8170
8171QualType ASTContext::getBaseElementType(const ArrayType *array) const {
8172 return getBaseElementType(QT: array->getElementType());
8173}
8174
8175QualType ASTContext::getBaseElementType(QualType type) const {
8176 Qualifiers qs;
8177 while (true) {
8178 SplitQualType split = type.getSplitDesugaredType();
8179 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
8180 if (!array) break;
8181
8182 type = array->getElementType();
8183 qs.addConsistentQualifiers(qs: split.Quals);
8184 }
8185
8186 return getQualifiedType(T: type, Qs: qs);
8187}
8188
8189/// getConstantArrayElementCount - Returns number of constant array elements.
8190uint64_t
8191ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
8192 uint64_t ElementCount = 1;
8193 do {
8194 ElementCount *= CA->getZExtSize();
8195 CA = dyn_cast_or_null<ConstantArrayType>(
8196 Val: CA->getElementType()->getAsArrayTypeUnsafe());
8197 } while (CA);
8198 return ElementCount;
8199}
8200
8201uint64_t ASTContext::getArrayInitLoopExprElementCount(
8202 const ArrayInitLoopExpr *AILE) const {
8203 if (!AILE)
8204 return 0;
8205
8206 uint64_t ElementCount = 1;
8207
8208 do {
8209 ElementCount *= AILE->getArraySize().getZExtValue();
8210 AILE = dyn_cast<ArrayInitLoopExpr>(Val: AILE->getSubExpr());
8211 } while (AILE);
8212
8213 return ElementCount;
8214}
8215
8216/// getFloatingRank - Return a relative rank for floating point types.
8217/// This routine will assert if passed a built-in type that isn't a float.
8218static FloatingRank getFloatingRank(QualType T) {
8219 if (const auto *CT = T->getAs<ComplexType>())
8220 return getFloatingRank(T: CT->getElementType());
8221
8222 switch (T->castAs<BuiltinType>()->getKind()) {
8223 default: llvm_unreachable("getFloatingRank(): not a floating type");
8224 case BuiltinType::Float16: return Float16Rank;
8225 case BuiltinType::Half: return HalfRank;
8226 case BuiltinType::Float: return FloatRank;
8227 case BuiltinType::Double: return DoubleRank;
8228 case BuiltinType::LongDouble: return LongDoubleRank;
8229 case BuiltinType::Float128: return Float128Rank;
8230 case BuiltinType::BFloat16: return BFloat16Rank;
8231 case BuiltinType::Ibm128: return Ibm128Rank;
8232 }
8233}
8234
8235/// getFloatingTypeOrder - Compare the rank of the two specified floating
8236/// point types, ignoring the domain of the type (i.e. 'double' ==
8237/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
8238/// LHS < RHS, return -1.
8239int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
8240 FloatingRank LHSR = getFloatingRank(T: LHS);
8241 FloatingRank RHSR = getFloatingRank(T: RHS);
8242
8243 if (LHSR == RHSR)
8244 return 0;
8245 if (LHSR > RHSR)
8246 return 1;
8247 return -1;
8248}
8249
8250int ASTContext::getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const {
8251 if (&getFloatTypeSemantics(T: LHS) == &getFloatTypeSemantics(T: RHS))
8252 return 0;
8253 return getFloatingTypeOrder(LHS, RHS);
8254}
8255
8256/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
8257/// routine will assert if passed a built-in type that isn't an integer or enum,
8258/// or if it is not canonicalized.
8259unsigned ASTContext::getIntegerRank(const Type *T) const {
8260 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
8261
8262 // Results in this 'losing' to any type of the same size, but winning if
8263 // larger.
8264 if (const auto *EIT = dyn_cast<BitIntType>(Val: T))
8265 return 0 + (EIT->getNumBits() << 3);
8266
8267 if (const auto *OBT = dyn_cast<OverflowBehaviorType>(Val: T))
8268 return getIntegerRank(T: OBT->getUnderlyingType().getTypePtr());
8269
8270 switch (cast<BuiltinType>(Val: T)->getKind()) {
8271 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
8272 case BuiltinType::Bool:
8273 return 1 + (getIntWidth(T: BoolTy) << 3);
8274 case BuiltinType::Char_S:
8275 case BuiltinType::Char_U:
8276 case BuiltinType::SChar:
8277 case BuiltinType::UChar:
8278 return 2 + (getIntWidth(T: CharTy) << 3);
8279 case BuiltinType::Short:
8280 case BuiltinType::UShort:
8281 return 3 + (getIntWidth(T: ShortTy) << 3);
8282 case BuiltinType::Int:
8283 case BuiltinType::UInt:
8284 return 4 + (getIntWidth(T: IntTy) << 3);
8285 case BuiltinType::Long:
8286 case BuiltinType::ULong:
8287 return 5 + (getIntWidth(T: LongTy) << 3);
8288 case BuiltinType::LongLong:
8289 case BuiltinType::ULongLong:
8290 return 6 + (getIntWidth(T: LongLongTy) << 3);
8291 case BuiltinType::Int128:
8292 case BuiltinType::UInt128:
8293 return 7 + (getIntWidth(T: Int128Ty) << 3);
8294
8295 // "The ranks of char8_t, char16_t, char32_t, and wchar_t equal the ranks of
8296 // their underlying types" [c++20 conv.rank]
8297 case BuiltinType::Char8:
8298 return getIntegerRank(T: UnsignedCharTy.getTypePtr());
8299 case BuiltinType::Char16:
8300 return getIntegerRank(
8301 T: getFromTargetType(Type: Target->getChar16Type()).getTypePtr());
8302 case BuiltinType::Char32:
8303 return getIntegerRank(
8304 T: getFromTargetType(Type: Target->getChar32Type()).getTypePtr());
8305 case BuiltinType::WChar_S:
8306 case BuiltinType::WChar_U:
8307 return getIntegerRank(
8308 T: getFromTargetType(Type: Target->getWCharType()).getTypePtr());
8309 }
8310}
8311
8312/// Whether this is a promotable bitfield reference according
8313/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
8314///
8315/// \returns the type this bit-field will promote to, or NULL if no
8316/// promotion occurs.
8317QualType ASTContext::isPromotableBitField(Expr *E) const {
8318 if (E->isTypeDependent() || E->isValueDependent())
8319 return {};
8320
8321 // C++ [conv.prom]p5:
8322 // If the bit-field has an enumerated type, it is treated as any other
8323 // value of that type for promotion purposes.
8324 if (getLangOpts().CPlusPlus && E->getType()->isEnumeralType())
8325 return {};
8326
8327 // FIXME: We should not do this unless E->refersToBitField() is true. This
8328 // matters in C where getSourceBitField() will find bit-fields for various
8329 // cases where the source expression is not a bit-field designator.
8330
8331 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
8332 if (!Field)
8333 return {};
8334
8335 QualType FT = Field->getType();
8336
8337 uint64_t BitWidth = Field->getBitWidthValue();
8338 uint64_t IntSize = getTypeSize(T: IntTy);
8339 // C++ [conv.prom]p5:
8340 // A prvalue for an integral bit-field can be converted to a prvalue of type
8341 // int if int can represent all the values of the bit-field; otherwise, it
8342 // can be converted to unsigned int if unsigned int can represent all the
8343 // values of the bit-field. If the bit-field is larger yet, no integral
8344 // promotion applies to it.
8345 // C11 6.3.1.1/2:
8346 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
8347 // If an int can represent all values of the original type (as restricted by
8348 // the width, for a bit-field), the value is converted to an int; otherwise,
8349 // it is converted to an unsigned int.
8350 //
8351 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
8352 // We perform that promotion here to match GCC and C++.
8353 // FIXME: C does not permit promotion of an enum bit-field whose rank is
8354 // greater than that of 'int'. We perform that promotion to match GCC.
8355 //
8356 // C23 6.3.1.1p2:
8357 // The value from a bit-field of a bit-precise integer type is converted to
8358 // the corresponding bit-precise integer type. (The rest is the same as in
8359 // C11.)
8360 if (QualType QT = Field->getType(); QT->isBitIntType())
8361 return QT;
8362
8363 if (BitWidth < IntSize)
8364 return IntTy;
8365
8366 if (BitWidth == IntSize)
8367 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
8368
8369 // Bit-fields wider than int are not subject to promotions, and therefore act
8370 // like the base type. GCC has some weird bugs in this area that we
8371 // deliberately do not follow (GCC follows a pre-standard resolution to
8372 // C's DR315 which treats bit-width as being part of the type, and this leaks
8373 // into their semantics in some cases).
8374 return {};
8375}
8376
8377/// getPromotedIntegerType - Returns the type that Promotable will
8378/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
8379/// integer type.
8380QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
8381 assert(!Promotable.isNull());
8382 assert(isPromotableIntegerType(Promotable));
8383 if (const auto *ED = Promotable->getAsEnumDecl())
8384 return ED->getPromotionType();
8385
8386 // OverflowBehaviorTypes promote their underlying type and preserve OBT
8387 // qualifier.
8388 if (const auto *OBT = Promotable->getAs<OverflowBehaviorType>()) {
8389 QualType PromotedUnderlying =
8390 getPromotedIntegerType(Promotable: OBT->getUnderlyingType());
8391 return getOverflowBehaviorType(Kind: OBT->getBehaviorKind(), Underlying: PromotedUnderlying);
8392 }
8393
8394 if (const auto *BT = Promotable->getAs<BuiltinType>()) {
8395 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
8396 // (3.9.1) can be converted to a prvalue of the first of the following
8397 // types that can represent all the values of its underlying type:
8398 // int, unsigned int, long int, unsigned long int, long long int, or
8399 // unsigned long long int [...]
8400 // FIXME: Is there some better way to compute this?
8401 if (BT->getKind() == BuiltinType::WChar_S ||
8402 BT->getKind() == BuiltinType::WChar_U ||
8403 BT->getKind() == BuiltinType::Char8 ||
8404 BT->getKind() == BuiltinType::Char16 ||
8405 BT->getKind() == BuiltinType::Char32) {
8406 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
8407 uint64_t FromSize = getTypeSize(T: BT);
8408 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
8409 LongLongTy, UnsignedLongLongTy };
8410 for (const auto &PT : PromoteTypes) {
8411 uint64_t ToSize = getTypeSize(T: PT);
8412 if (FromSize < ToSize ||
8413 (FromSize == ToSize && FromIsSigned == PT->isSignedIntegerType()))
8414 return PT;
8415 }
8416 llvm_unreachable("char type should fit into long long");
8417 }
8418 }
8419
8420 // At this point, we should have a signed or unsigned integer type.
8421 if (Promotable->isSignedIntegerType())
8422 return IntTy;
8423 uint64_t PromotableSize = getIntWidth(T: Promotable);
8424 uint64_t IntSize = getIntWidth(T: IntTy);
8425 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
8426 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
8427}
8428
8429/// Recurses in pointer/array types until it finds an objc retainable
8430/// type and returns its ownership.
8431Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
8432 while (!T.isNull()) {
8433 if (T.getObjCLifetime() != Qualifiers::OCL_None)
8434 return T.getObjCLifetime();
8435 if (T->isArrayType())
8436 T = getBaseElementType(type: T);
8437 else if (const auto *PT = T->getAs<PointerType>())
8438 T = PT->getPointeeType();
8439 else if (const auto *RT = T->getAs<ReferenceType>())
8440 T = RT->getPointeeType();
8441 else
8442 break;
8443 }
8444
8445 return Qualifiers::OCL_None;
8446}
8447
8448static const Type *getIntegerTypeForEnum(const EnumType *ET) {
8449 // Incomplete enum types are not treated as integer types.
8450 // FIXME: In C++, enum types are never integer types.
8451 const EnumDecl *ED = ET->getDecl()->getDefinitionOrSelf();
8452 if (ED->isComplete() && !ED->isScoped())
8453 return ED->getIntegerType().getTypePtr();
8454 return nullptr;
8455}
8456
8457/// getIntegerTypeOrder - Returns the highest ranked integer type:
8458/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
8459/// LHS < RHS, return -1.
8460int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
8461 const Type *LHSC = getCanonicalType(T: LHS).getTypePtr();
8462 const Type *RHSC = getCanonicalType(T: RHS).getTypePtr();
8463
8464 // Unwrap enums to their underlying type.
8465 if (const auto *ET = dyn_cast<EnumType>(Val: LHSC))
8466 LHSC = getIntegerTypeForEnum(ET);
8467 if (const auto *ET = dyn_cast<EnumType>(Val: RHSC))
8468 RHSC = getIntegerTypeForEnum(ET);
8469
8470 if (LHSC == RHSC) return 0;
8471
8472 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
8473 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
8474
8475 unsigned LHSRank = getIntegerRank(T: LHSC);
8476 unsigned RHSRank = getIntegerRank(T: RHSC);
8477
8478 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
8479 if (LHSRank == RHSRank) return 0;
8480 return LHSRank > RHSRank ? 1 : -1;
8481 }
8482
8483 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
8484 if (LHSUnsigned) {
8485 // If the unsigned [LHS] type is larger, return it.
8486 if (LHSRank >= RHSRank)
8487 return 1;
8488
8489 // If the signed type can represent all values of the unsigned type, it
8490 // wins. Because we are dealing with 2's complement and types that are
8491 // powers of two larger than each other, this is always safe.
8492 return -1;
8493 }
8494
8495 // If the unsigned [RHS] type is larger, return it.
8496 if (RHSRank >= LHSRank)
8497 return -1;
8498
8499 // If the signed type can represent all values of the unsigned type, it
8500 // wins. Because we are dealing with 2's complement and types that are
8501 // powers of two larger than each other, this is always safe.
8502 return 1;
8503}
8504
8505TypedefDecl *ASTContext::getCFConstantStringDecl() const {
8506 if (CFConstantStringTypeDecl)
8507 return CFConstantStringTypeDecl;
8508
8509 assert(!CFConstantStringTagDecl &&
8510 "tag and typedef should be initialized together");
8511 CFConstantStringTagDecl = buildImplicitRecord(Name: "__NSConstantString_tag");
8512 CFConstantStringTagDecl->startDefinition();
8513
8514 struct {
8515 QualType Type;
8516 const char *Name;
8517 } Fields[5];
8518 unsigned Count = 0;
8519
8520 /// Objective-C ABI
8521 ///
8522 /// typedef struct __NSConstantString_tag {
8523 /// const int *isa;
8524 /// int flags;
8525 /// const char *str;
8526 /// long length;
8527 /// } __NSConstantString;
8528 ///
8529 /// Swift ABI (4.1, 4.2)
8530 ///
8531 /// typedef struct __NSConstantString_tag {
8532 /// uintptr_t _cfisa;
8533 /// uintptr_t _swift_rc;
8534 /// _Atomic(uint64_t) _cfinfoa;
8535 /// const char *_ptr;
8536 /// uint32_t _length;
8537 /// } __NSConstantString;
8538 ///
8539 /// Swift ABI (5.0)
8540 ///
8541 /// typedef struct __NSConstantString_tag {
8542 /// uintptr_t _cfisa;
8543 /// uintptr_t _swift_rc;
8544 /// _Atomic(uint64_t) _cfinfoa;
8545 /// const char *_ptr;
8546 /// uintptr_t _length;
8547 /// } __NSConstantString;
8548
8549 const auto CFRuntime = getLangOpts().CFRuntime;
8550 if (static_cast<unsigned>(CFRuntime) <
8551 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) {
8552 Fields[Count++] = { .Type: getPointerType(T: IntTy.withConst()), .Name: "isa" };
8553 Fields[Count++] = { .Type: IntTy, .Name: "flags" };
8554 Fields[Count++] = { .Type: getPointerType(T: CharTy.withConst()), .Name: "str" };
8555 Fields[Count++] = { .Type: LongTy, .Name: "length" };
8556 } else {
8557 Fields[Count++] = { .Type: getUIntPtrType(), .Name: "_cfisa" };
8558 Fields[Count++] = { .Type: getUIntPtrType(), .Name: "_swift_rc" };
8559 Fields[Count++] = { .Type: getFromTargetType(Type: Target->getUInt64Type()), .Name: "_swift_rc" };
8560 Fields[Count++] = { .Type: getPointerType(T: CharTy.withConst()), .Name: "_ptr" };
8561 if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 ||
8562 CFRuntime == LangOptions::CoreFoundationABI::Swift4_2)
8563 Fields[Count++] = { .Type: IntTy, .Name: "_ptr" };
8564 else
8565 Fields[Count++] = { .Type: getUIntPtrType(), .Name: "_ptr" };
8566 }
8567
8568 // Create fields
8569 for (unsigned i = 0; i < Count; ++i) {
8570 FieldDecl *Field =
8571 FieldDecl::Create(C: *this, DC: CFConstantStringTagDecl, StartLoc: SourceLocation(),
8572 IdLoc: SourceLocation(), Id: &Idents.get(Name: Fields[i].Name),
8573 T: Fields[i].Type, /*TInfo=*/nullptr,
8574 /*BitWidth=*/BW: nullptr, /*Mutable=*/false, InitStyle: ICIS_NoInit);
8575 Field->setAccess(AS_public);
8576 CFConstantStringTagDecl->addDecl(D: Field);
8577 }
8578
8579 CFConstantStringTagDecl->completeDefinition();
8580 // This type is designed to be compatible with NSConstantString, but cannot
8581 // use the same name, since NSConstantString is an interface.
8582 CanQualType tagType = getCanonicalTagType(TD: CFConstantStringTagDecl);
8583 CFConstantStringTypeDecl =
8584 buildImplicitTypedef(T: tagType, Name: "__NSConstantString");
8585
8586 return CFConstantStringTypeDecl;
8587}
8588
8589RecordDecl *ASTContext::getCFConstantStringTagDecl() const {
8590 if (!CFConstantStringTagDecl)
8591 getCFConstantStringDecl(); // Build the tag and the typedef.
8592 return CFConstantStringTagDecl;
8593}
8594
8595// getCFConstantStringType - Return the type used for constant CFStrings.
8596QualType ASTContext::getCFConstantStringType() const {
8597 return getTypedefType(Keyword: ElaboratedTypeKeyword::None, /*Qualifier=*/std::nullopt,
8598 Decl: getCFConstantStringDecl());
8599}
8600
8601QualType ASTContext::getObjCSuperType() const {
8602 if (ObjCSuperType.isNull()) {
8603 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord(Name: "objc_super");
8604 getTranslationUnitDecl()->addDecl(D: ObjCSuperTypeDecl);
8605 ObjCSuperType = getCanonicalTagType(TD: ObjCSuperTypeDecl);
8606 }
8607 return ObjCSuperType;
8608}
8609
8610void ASTContext::setCFConstantStringType(QualType T) {
8611 const auto *TT = T->castAs<TypedefType>();
8612 CFConstantStringTypeDecl = cast<TypedefDecl>(Val: TT->getDecl());
8613 CFConstantStringTagDecl = TT->castAsRecordDecl();
8614}
8615
8616QualType ASTContext::getBlockDescriptorType() const {
8617 if (BlockDescriptorType)
8618 return getCanonicalTagType(TD: BlockDescriptorType);
8619
8620 RecordDecl *RD;
8621 // FIXME: Needs the FlagAppleBlock bit.
8622 RD = buildImplicitRecord(Name: "__block_descriptor");
8623 RD->startDefinition();
8624
8625 QualType FieldTypes[] = {
8626 UnsignedLongTy,
8627 UnsignedLongTy,
8628 };
8629
8630 static const char *const FieldNames[] = {
8631 "reserved",
8632 "Size"
8633 };
8634
8635 for (size_t i = 0; i < 2; ++i) {
8636 FieldDecl *Field = FieldDecl::Create(
8637 C: *this, DC: RD, StartLoc: SourceLocation(), IdLoc: SourceLocation(),
8638 Id: &Idents.get(Name: FieldNames[i]), T: FieldTypes[i], /*TInfo=*/nullptr,
8639 /*BitWidth=*/BW: nullptr, /*Mutable=*/false, InitStyle: ICIS_NoInit);
8640 Field->setAccess(AS_public);
8641 RD->addDecl(D: Field);
8642 }
8643
8644 RD->completeDefinition();
8645
8646 BlockDescriptorType = RD;
8647
8648 return getCanonicalTagType(TD: BlockDescriptorType);
8649}
8650
8651QualType ASTContext::getBlockDescriptorExtendedType() const {
8652 if (BlockDescriptorExtendedType)
8653 return getCanonicalTagType(TD: BlockDescriptorExtendedType);
8654
8655 RecordDecl *RD;
8656 // FIXME: Needs the FlagAppleBlock bit.
8657 RD = buildImplicitRecord(Name: "__block_descriptor_withcopydispose");
8658 RD->startDefinition();
8659
8660 QualType FieldTypes[] = {
8661 UnsignedLongTy,
8662 UnsignedLongTy,
8663 getPointerType(T: VoidPtrTy),
8664 getPointerType(T: VoidPtrTy)
8665 };
8666
8667 static const char *const FieldNames[] = {
8668 "reserved",
8669 "Size",
8670 "CopyFuncPtr",
8671 "DestroyFuncPtr"
8672 };
8673
8674 for (size_t i = 0; i < 4; ++i) {
8675 FieldDecl *Field = FieldDecl::Create(
8676 C: *this, DC: RD, StartLoc: SourceLocation(), IdLoc: SourceLocation(),
8677 Id: &Idents.get(Name: FieldNames[i]), T: FieldTypes[i], /*TInfo=*/nullptr,
8678 /*BitWidth=*/BW: nullptr,
8679 /*Mutable=*/false, InitStyle: ICIS_NoInit);
8680 Field->setAccess(AS_public);
8681 RD->addDecl(D: Field);
8682 }
8683
8684 RD->completeDefinition();
8685
8686 BlockDescriptorExtendedType = RD;
8687 return getCanonicalTagType(TD: BlockDescriptorExtendedType);
8688}
8689
8690OpenCLTypeKind ASTContext::getOpenCLTypeKind(const Type *T) const {
8691 const auto *BT = dyn_cast<BuiltinType>(Val: T);
8692
8693 if (!BT) {
8694 if (isa<PipeType>(Val: T))
8695 return OCLTK_Pipe;
8696
8697 return OCLTK_Default;
8698 }
8699
8700 switch (BT->getKind()) {
8701#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
8702 case BuiltinType::Id: \
8703 return OCLTK_Image;
8704#include "clang/Basic/OpenCLImageTypes.def"
8705
8706 case BuiltinType::OCLClkEvent:
8707 return OCLTK_ClkEvent;
8708
8709 case BuiltinType::OCLEvent:
8710 return OCLTK_Event;
8711
8712 case BuiltinType::OCLQueue:
8713 return OCLTK_Queue;
8714
8715 case BuiltinType::OCLReserveID:
8716 return OCLTK_ReserveID;
8717
8718 case BuiltinType::OCLSampler:
8719 return OCLTK_Sampler;
8720
8721 default:
8722 return OCLTK_Default;
8723 }
8724}
8725
8726LangAS ASTContext::getOpenCLTypeAddrSpace(const Type *T) const {
8727 return Target->getOpenCLTypeAddrSpace(TK: getOpenCLTypeKind(T));
8728}
8729
8730/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
8731/// requires copy/dispose. Note that this must match the logic
8732/// in buildByrefHelpers.
8733bool ASTContext::BlockRequiresCopying(QualType Ty,
8734 const VarDecl *D) {
8735 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
8736 const Expr *copyExpr = getBlockVarCopyInit(VD: D).getCopyExpr();
8737 if (!copyExpr && record->hasTrivialDestructor()) return false;
8738
8739 return true;
8740 }
8741
8742 if (Ty.hasAddressDiscriminatedPointerAuth())
8743 return true;
8744
8745 // The block needs copy/destroy helpers if Ty is non-trivial to destructively
8746 // move or destroy.
8747 if (Ty.isNonTrivialToPrimitiveDestructiveMove() || Ty.isDestructedType())
8748 return true;
8749
8750 if (!Ty->isObjCRetainableType()) return false;
8751
8752 Qualifiers qs = Ty.getQualifiers();
8753
8754 // If we have lifetime, that dominates.
8755 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
8756 switch (lifetime) {
8757 case Qualifiers::OCL_None: llvm_unreachable("impossible");
8758
8759 // These are just bits as far as the runtime is concerned.
8760 case Qualifiers::OCL_ExplicitNone:
8761 case Qualifiers::OCL_Autoreleasing:
8762 return false;
8763
8764 // These cases should have been taken care of when checking the type's
8765 // non-triviality.
8766 case Qualifiers::OCL_Weak:
8767 case Qualifiers::OCL_Strong:
8768 llvm_unreachable("impossible");
8769 }
8770 llvm_unreachable("fell out of lifetime switch!");
8771 }
8772 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
8773 Ty->isObjCObjectPointerType());
8774}
8775
8776bool ASTContext::getByrefLifetime(QualType Ty,
8777 Qualifiers::ObjCLifetime &LifeTime,
8778 bool &HasByrefExtendedLayout) const {
8779 if (!getLangOpts().ObjC ||
8780 getLangOpts().getGC() != LangOptions::NonGC)
8781 return false;
8782
8783 HasByrefExtendedLayout = false;
8784 if (Ty->isRecordType()) {
8785 HasByrefExtendedLayout = true;
8786 LifeTime = Qualifiers::OCL_None;
8787 } else if ((LifeTime = Ty.getObjCLifetime())) {
8788 // Honor the ARC qualifiers.
8789 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
8790 // The MRR rule.
8791 LifeTime = Qualifiers::OCL_ExplicitNone;
8792 } else {
8793 LifeTime = Qualifiers::OCL_None;
8794 }
8795 return true;
8796}
8797
8798CanQualType ASTContext::getNSUIntegerType() const {
8799 assert(Target && "Expected target to be initialized");
8800 const llvm::Triple &T = Target->getTriple();
8801 // Windows is LLP64 rather than LP64
8802 if (T.isOSWindows() && T.isArch64Bit())
8803 return UnsignedLongLongTy;
8804 return UnsignedLongTy;
8805}
8806
8807CanQualType ASTContext::getNSIntegerType() const {
8808 assert(Target && "Expected target to be initialized");
8809 const llvm::Triple &T = Target->getTriple();
8810 // Windows is LLP64 rather than LP64
8811 if (T.isOSWindows() && T.isArch64Bit())
8812 return LongLongTy;
8813 return LongTy;
8814}
8815
8816TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
8817 if (!ObjCInstanceTypeDecl)
8818 ObjCInstanceTypeDecl =
8819 buildImplicitTypedef(T: getObjCIdType(), Name: "instancetype");
8820 return ObjCInstanceTypeDecl;
8821}
8822
8823// This returns true if a type has been typedefed to BOOL:
8824// typedef <type> BOOL;
8825static bool isTypeTypedefedAsBOOL(QualType T) {
8826 if (const auto *TT = dyn_cast<TypedefType>(Val&: T))
8827 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
8828 return II->isStr(Str: "BOOL");
8829
8830 return false;
8831}
8832
8833/// getObjCEncodingTypeSize returns size of type for objective-c encoding
8834/// purpose.
8835CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
8836 if (!type->isIncompleteArrayType() && type->isIncompleteType())
8837 return CharUnits::Zero();
8838
8839 CharUnits sz = getTypeSizeInChars(T: type);
8840
8841 // Make all integer and enum types at least as large as an int
8842 if (sz.isPositive() && type->isIntegralOrEnumerationType())
8843 sz = std::max(a: sz, b: getTypeSizeInChars(T: IntTy));
8844 // Treat arrays as pointers, since that's how they're passed in.
8845 else if (type->isArrayType())
8846 sz = getTypeSizeInChars(T: VoidPtrTy);
8847 return sz;
8848}
8849
8850bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
8851 return getTargetInfo().getCXXABI().isMicrosoft() &&
8852 VD->isStaticDataMember() &&
8853 VD->getType()->isIntegralOrEnumerationType() &&
8854 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
8855}
8856
8857ASTContext::InlineVariableDefinitionKind
8858ASTContext::getInlineVariableDefinitionKind(const VarDecl *VD) const {
8859 if (!VD->isInline())
8860 return InlineVariableDefinitionKind::None;
8861
8862 // In almost all cases, it's a weak definition.
8863 auto *First = VD->getFirstDecl();
8864 if (First->isInlineSpecified() || !First->isStaticDataMember())
8865 return InlineVariableDefinitionKind::Weak;
8866
8867 // If there's a file-context declaration in this translation unit, it's a
8868 // non-discardable definition.
8869 for (auto *D : VD->redecls())
8870 if (D->getLexicalDeclContext()->isFileContext() &&
8871 !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr()))
8872 return InlineVariableDefinitionKind::Strong;
8873
8874 // If we've not seen one yet, we don't know.
8875 return InlineVariableDefinitionKind::WeakUnknown;
8876}
8877
8878static std::string charUnitsToString(const CharUnits &CU) {
8879 return llvm::itostr(X: CU.getQuantity());
8880}
8881
8882/// getObjCEncodingForBlock - Return the encoded type for this block
8883/// declaration.
8884std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
8885 std::string S;
8886
8887 const BlockDecl *Decl = Expr->getBlockDecl();
8888 QualType BlockTy =
8889 Expr->getType()->castAs<BlockPointerType>()->getPointeeType();
8890 QualType BlockReturnTy = BlockTy->castAs<FunctionType>()->getReturnType();
8891 // Encode result type.
8892 if (getLangOpts().EncodeExtendedBlockSig)
8893 getObjCEncodingForMethodParameter(QT: Decl::OBJC_TQ_None, T: BlockReturnTy, S,
8894 Extended: true /*Extended*/);
8895 else
8896 getObjCEncodingForType(T: BlockReturnTy, S);
8897 // Compute size of all parameters.
8898 // Start with computing size of a pointer in number of bytes.
8899 // FIXME: There might(should) be a better way of doing this computation!
8900 CharUnits PtrSize = getTypeSizeInChars(T: VoidPtrTy);
8901 CharUnits ParmOffset = PtrSize;
8902 for (auto *PI : Decl->parameters()) {
8903 QualType PType = PI->getType();
8904 CharUnits sz = getObjCEncodingTypeSize(type: PType);
8905 if (sz.isZero())
8906 continue;
8907 assert(sz.isPositive() && "BlockExpr - Incomplete param type");
8908 ParmOffset += sz;
8909 }
8910 // Size of the argument frame
8911 S += charUnitsToString(CU: ParmOffset);
8912 // Block pointer and offset.
8913 S += "@?0";
8914
8915 // Argument types.
8916 ParmOffset = PtrSize;
8917 for (auto *PVDecl : Decl->parameters()) {
8918 QualType PType = PVDecl->getOriginalType();
8919 if (const auto *AT =
8920 dyn_cast<ArrayType>(Val: PType->getCanonicalTypeInternal())) {
8921 // Use array's original type only if it has known number of
8922 // elements.
8923 if (!isa<ConstantArrayType>(Val: AT))
8924 PType = PVDecl->getType();
8925 } else if (PType->isFunctionType())
8926 PType = PVDecl->getType();
8927 if (getLangOpts().EncodeExtendedBlockSig)
8928 getObjCEncodingForMethodParameter(QT: Decl::OBJC_TQ_None, T: PType,
8929 S, Extended: true /*Extended*/);
8930 else
8931 getObjCEncodingForType(T: PType, S);
8932 S += charUnitsToString(CU: ParmOffset);
8933 ParmOffset += getObjCEncodingTypeSize(type: PType);
8934 }
8935
8936 return S;
8937}
8938
8939std::string
8940ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const {
8941 std::string S;
8942 // Encode result type.
8943 getObjCEncodingForType(T: Decl->getReturnType(), S);
8944 CharUnits ParmOffset;
8945 // Compute size of all parameters.
8946 for (auto *PI : Decl->parameters()) {
8947 QualType PType = PI->getType();
8948 CharUnits sz = getObjCEncodingTypeSize(type: PType);
8949 if (sz.isZero())
8950 continue;
8951
8952 assert(sz.isPositive() &&
8953 "getObjCEncodingForFunctionDecl - Incomplete param type");
8954 ParmOffset += sz;
8955 }
8956 S += charUnitsToString(CU: ParmOffset);
8957 ParmOffset = CharUnits::Zero();
8958
8959 // Argument types.
8960 for (auto *PVDecl : Decl->parameters()) {
8961 QualType PType = PVDecl->getOriginalType();
8962 if (const auto *AT =
8963 dyn_cast<ArrayType>(Val: PType->getCanonicalTypeInternal())) {
8964 // Use array's original type only if it has known number of
8965 // elements.
8966 if (!isa<ConstantArrayType>(Val: AT))
8967 PType = PVDecl->getType();
8968 } else if (PType->isFunctionType())
8969 PType = PVDecl->getType();
8970 getObjCEncodingForType(T: PType, S);
8971 S += charUnitsToString(CU: ParmOffset);
8972 ParmOffset += getObjCEncodingTypeSize(type: PType);
8973 }
8974
8975 return S;
8976}
8977
8978/// getObjCEncodingForMethodParameter - Return the encoded type for a single
8979/// method parameter or return type. If Extended, include class names and
8980/// block object types.
8981void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
8982 QualType T, std::string& S,
8983 bool Extended) const {
8984 // Encode type qualifier, 'in', 'inout', etc. for the parameter.
8985 getObjCEncodingForTypeQualifier(QT, S);
8986 // Encode parameter type.
8987 ObjCEncOptions Options = ObjCEncOptions()
8988 .setExpandPointedToStructures()
8989 .setExpandStructures()
8990 .setIsOutermostType();
8991 if (Extended)
8992 Options.setEncodeBlockParameters().setEncodeClassNames();
8993 getObjCEncodingForTypeImpl(t: T, S, Options, /*Field=*/nullptr);
8994}
8995
8996/// getObjCEncodingForMethodDecl - Return the encoded type for this method
8997/// declaration.
8998std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
8999 bool Extended) const {
9000 // FIXME: This is not very efficient.
9001 // Encode return type.
9002 std::string S;
9003 getObjCEncodingForMethodParameter(QT: Decl->getObjCDeclQualifier(),
9004 T: Decl->getReturnType(), S, Extended);
9005 // Compute size of all parameters.
9006 // Start with computing size of a pointer in number of bytes.
9007 // FIXME: There might(should) be a better way of doing this computation!
9008 CharUnits PtrSize = getTypeSizeInChars(T: VoidPtrTy);
9009 // The first two arguments (self and _cmd) are pointers; account for
9010 // their size.
9011 CharUnits ParmOffset = 2 * PtrSize;
9012 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
9013 E = Decl->sel_param_end(); PI != E; ++PI) {
9014 QualType PType = (*PI)->getType();
9015 CharUnits sz = getObjCEncodingTypeSize(type: PType);
9016 if (sz.isZero())
9017 continue;
9018
9019 assert(sz.isPositive() &&
9020 "getObjCEncodingForMethodDecl - Incomplete param type");
9021 ParmOffset += sz;
9022 }
9023 S += charUnitsToString(CU: ParmOffset);
9024 S += "@0:";
9025 S += charUnitsToString(CU: PtrSize);
9026
9027 // Argument types.
9028 ParmOffset = 2 * PtrSize;
9029 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
9030 E = Decl->sel_param_end(); PI != E; ++PI) {
9031 const ParmVarDecl *PVDecl = *PI;
9032 QualType PType = PVDecl->getOriginalType();
9033 if (const auto *AT =
9034 dyn_cast<ArrayType>(Val: PType->getCanonicalTypeInternal())) {
9035 // Use array's original type only if it has known number of
9036 // elements.
9037 if (!isa<ConstantArrayType>(Val: AT))
9038 PType = PVDecl->getType();
9039 } else if (PType->isFunctionType())
9040 PType = PVDecl->getType();
9041 getObjCEncodingForMethodParameter(QT: PVDecl->getObjCDeclQualifier(),
9042 T: PType, S, Extended);
9043 S += charUnitsToString(CU: ParmOffset);
9044 ParmOffset += getObjCEncodingTypeSize(type: PType);
9045 }
9046
9047 return S;
9048}
9049
9050ObjCPropertyImplDecl *
9051ASTContext::getObjCPropertyImplDeclForPropertyDecl(
9052 const ObjCPropertyDecl *PD,
9053 const Decl *Container) const {
9054 if (!Container)
9055 return nullptr;
9056 if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Val: Container)) {
9057 for (auto *PID : CID->property_impls())
9058 if (PID->getPropertyDecl() == PD)
9059 return PID;
9060 } else {
9061 const auto *OID = cast<ObjCImplementationDecl>(Val: Container);
9062 for (auto *PID : OID->property_impls())
9063 if (PID->getPropertyDecl() == PD)
9064 return PID;
9065 }
9066 return nullptr;
9067}
9068
9069/// getObjCEncodingForPropertyDecl - Return the encoded type for this
9070/// property declaration. If non-NULL, Container must be either an
9071/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
9072/// NULL when getting encodings for protocol properties.
9073/// Property attributes are stored as a comma-delimited C string. The simple
9074/// attributes readonly and bycopy are encoded as single characters. The
9075/// parametrized attributes, getter=name, setter=name, and ivar=name, are
9076/// encoded as single characters, followed by an identifier. Property types
9077/// are also encoded as a parametrized attribute. The characters used to encode
9078/// these attributes are defined by the following enumeration:
9079/// @code
9080/// enum PropertyAttributes {
9081/// kPropertyReadOnly = 'R', // property is read-only.
9082/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
9083/// kPropertyByref = '&', // property is a reference to the value last assigned
9084/// kPropertyDynamic = 'D', // property is dynamic
9085/// kPropertyGetter = 'G', // followed by getter selector name
9086/// kPropertySetter = 'S', // followed by setter selector name
9087/// kPropertyInstanceVariable = 'V' // followed by instance variable name
9088/// kPropertyType = 'T' // followed by old-style type encoding.
9089/// kPropertyWeak = 'W' // 'weak' property
9090/// kPropertyStrong = 'P' // property GC'able
9091/// kPropertyNonAtomic = 'N' // property non-atomic
9092/// kPropertyOptional = '?' // property optional
9093/// };
9094/// @endcode
9095std::string
9096ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
9097 const Decl *Container) const {
9098 // Collect information from the property implementation decl(s).
9099 bool Dynamic = false;
9100 ObjCPropertyImplDecl *SynthesizePID = nullptr;
9101
9102 if (ObjCPropertyImplDecl *PropertyImpDecl =
9103 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
9104 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
9105 Dynamic = true;
9106 else
9107 SynthesizePID = PropertyImpDecl;
9108 }
9109
9110 // FIXME: This is not very efficient.
9111 std::string S = "T";
9112
9113 // Encode result type.
9114 // GCC has some special rules regarding encoding of properties which
9115 // closely resembles encoding of ivars.
9116 getObjCEncodingForPropertyType(T: PD->getType(), S);
9117
9118 if (PD->isOptional())
9119 S += ",?";
9120
9121 if (PD->isReadOnly()) {
9122 S += ",R";
9123 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_copy)
9124 S += ",C";
9125 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_retain)
9126 S += ",&";
9127 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_weak)
9128 S += ",W";
9129 } else {
9130 switch (PD->getSetterKind()) {
9131 case ObjCPropertyDecl::Assign: break;
9132 case ObjCPropertyDecl::Copy: S += ",C"; break;
9133 case ObjCPropertyDecl::Retain: S += ",&"; break;
9134 case ObjCPropertyDecl::Weak: S += ",W"; break;
9135 }
9136 }
9137
9138 // It really isn't clear at all what this means, since properties
9139 // are "dynamic by default".
9140 if (Dynamic)
9141 S += ",D";
9142
9143 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_nonatomic)
9144 S += ",N";
9145
9146 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_getter) {
9147 S += ",G";
9148 S += PD->getGetterName().getAsString();
9149 }
9150
9151 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_setter) {
9152 S += ",S";
9153 S += PD->getSetterName().getAsString();
9154 }
9155
9156 if (SynthesizePID) {
9157 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
9158 S += ",V";
9159 S += OID->getNameAsString();
9160 }
9161
9162 // FIXME: OBJCGC: weak & strong
9163 return S;
9164}
9165
9166/// getLegacyIntegralTypeEncoding -
9167/// Another legacy compatibility encoding: 32-bit longs are encoded as
9168/// 'l' or 'L' , but not always. For typedefs, we need to use
9169/// 'i' or 'I' instead if encoding a struct field, or a pointer!
9170void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
9171 if (PointeeTy->getAs<TypedefType>()) {
9172 if (const auto *BT = PointeeTy->getAs<BuiltinType>()) {
9173 if (BT->getKind() == BuiltinType::ULong && getIntWidth(T: PointeeTy) == 32)
9174 PointeeTy = UnsignedIntTy;
9175 else
9176 if (BT->getKind() == BuiltinType::Long && getIntWidth(T: PointeeTy) == 32)
9177 PointeeTy = IntTy;
9178 }
9179 }
9180}
9181
9182void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
9183 const FieldDecl *Field,
9184 QualType *NotEncodedT) const {
9185 // We follow the behavior of gcc, expanding structures which are
9186 // directly pointed to, and expanding embedded structures. Note that
9187 // these rules are sufficient to prevent recursive encoding of the
9188 // same type.
9189 getObjCEncodingForTypeImpl(t: T, S,
9190 Options: ObjCEncOptions()
9191 .setExpandPointedToStructures()
9192 .setExpandStructures()
9193 .setIsOutermostType(),
9194 Field, NotEncodedT);
9195}
9196
9197void ASTContext::getObjCEncodingForPropertyType(QualType T,
9198 std::string& S) const {
9199 // Encode result type.
9200 // GCC has some special rules regarding encoding of properties which
9201 // closely resembles encoding of ivars.
9202 getObjCEncodingForTypeImpl(t: T, S,
9203 Options: ObjCEncOptions()
9204 .setExpandPointedToStructures()
9205 .setExpandStructures()
9206 .setIsOutermostType()
9207 .setEncodingProperty(),
9208 /*Field=*/nullptr);
9209}
9210
9211static char getObjCEncodingForPrimitiveType(const ASTContext *C,
9212 const BuiltinType *BT) {
9213 BuiltinType::Kind kind = BT->getKind();
9214 switch (kind) {
9215 case BuiltinType::Void: return 'v';
9216 case BuiltinType::Bool: return 'B';
9217 case BuiltinType::Char8:
9218 case BuiltinType::Char_U:
9219 case BuiltinType::UChar: return 'C';
9220 case BuiltinType::Char16:
9221 case BuiltinType::UShort: return 'S';
9222 case BuiltinType::Char32:
9223 case BuiltinType::UInt: return 'I';
9224 case BuiltinType::ULong:
9225 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
9226 case BuiltinType::UInt128: return 'T';
9227 case BuiltinType::ULongLong: return 'Q';
9228 case BuiltinType::Char_S:
9229 case BuiltinType::SChar: return 'c';
9230 case BuiltinType::Short: return 's';
9231 case BuiltinType::WChar_S:
9232 case BuiltinType::WChar_U:
9233 case BuiltinType::Int: return 'i';
9234 case BuiltinType::Long:
9235 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
9236 case BuiltinType::LongLong: return 'q';
9237 case BuiltinType::Int128: return 't';
9238 case BuiltinType::Float: return 'f';
9239 case BuiltinType::Double: return 'd';
9240 case BuiltinType::LongDouble: return 'D';
9241 case BuiltinType::NullPtr: return '*'; // like char*
9242
9243 case BuiltinType::BFloat16:
9244 case BuiltinType::Float16:
9245 case BuiltinType::Float128:
9246 case BuiltinType::Ibm128:
9247 case BuiltinType::Half:
9248 case BuiltinType::ShortAccum:
9249 case BuiltinType::Accum:
9250 case BuiltinType::LongAccum:
9251 case BuiltinType::UShortAccum:
9252 case BuiltinType::UAccum:
9253 case BuiltinType::ULongAccum:
9254 case BuiltinType::ShortFract:
9255 case BuiltinType::Fract:
9256 case BuiltinType::LongFract:
9257 case BuiltinType::UShortFract:
9258 case BuiltinType::UFract:
9259 case BuiltinType::ULongFract:
9260 case BuiltinType::SatShortAccum:
9261 case BuiltinType::SatAccum:
9262 case BuiltinType::SatLongAccum:
9263 case BuiltinType::SatUShortAccum:
9264 case BuiltinType::SatUAccum:
9265 case BuiltinType::SatULongAccum:
9266 case BuiltinType::SatShortFract:
9267 case BuiltinType::SatFract:
9268 case BuiltinType::SatLongFract:
9269 case BuiltinType::SatUShortFract:
9270 case BuiltinType::SatUFract:
9271 case BuiltinType::SatULongFract:
9272 // FIXME: potentially need @encodes for these!
9273 return ' ';
9274
9275#define SVE_TYPE(Name, Id, SingletonId) \
9276 case BuiltinType::Id:
9277#include "clang/Basic/AArch64ACLETypes.def"
9278#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9279#include "clang/Basic/RISCVVTypes.def"
9280#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9281#include "clang/Basic/WebAssemblyReferenceTypes.def"
9282#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
9283#include "clang/Basic/AMDGPUTypes.def"
9284 {
9285 DiagnosticsEngine &Diags = C->getDiagnostics();
9286 Diags.Report(DiagID: diag::err_unsupported_objc_primitive_encoding)
9287 << QualType(BT, 0);
9288 return ' ';
9289 }
9290
9291 case BuiltinType::ObjCId:
9292 case BuiltinType::ObjCClass:
9293 case BuiltinType::ObjCSel:
9294 llvm_unreachable("@encoding ObjC primitive type");
9295
9296 // OpenCL and placeholder types don't need @encodings.
9297#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
9298 case BuiltinType::Id:
9299#include "clang/Basic/OpenCLImageTypes.def"
9300#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
9301 case BuiltinType::Id:
9302#include "clang/Basic/OpenCLExtensionTypes.def"
9303 case BuiltinType::OCLEvent:
9304 case BuiltinType::OCLClkEvent:
9305 case BuiltinType::OCLQueue:
9306 case BuiltinType::OCLReserveID:
9307 case BuiltinType::OCLSampler:
9308 case BuiltinType::Dependent:
9309#define PPC_VECTOR_TYPE(Name, Id, Size) \
9310 case BuiltinType::Id:
9311#include "clang/Basic/PPCTypes.def"
9312#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9313#include "clang/Basic/HLSLIntangibleTypes.def"
9314#define BUILTIN_TYPE(KIND, ID)
9315#define PLACEHOLDER_TYPE(KIND, ID) \
9316 case BuiltinType::KIND:
9317#include "clang/AST/BuiltinTypes.def"
9318 llvm_unreachable("invalid builtin type for @encode");
9319 }
9320 llvm_unreachable("invalid BuiltinType::Kind value");
9321}
9322
9323static char ObjCEncodingForEnumDecl(const ASTContext *C, const EnumDecl *ED) {
9324 EnumDecl *Enum = ED->getDefinitionOrSelf();
9325
9326 // The encoding of an non-fixed enum type is always 'i', regardless of size.
9327 if (!Enum->isFixed())
9328 return 'i';
9329
9330 // The encoding of a fixed enum type matches its fixed underlying type.
9331 const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>();
9332 return getObjCEncodingForPrimitiveType(C, BT);
9333}
9334
9335static void EncodeBitField(const ASTContext *Ctx, std::string& S,
9336 QualType T, const FieldDecl *FD) {
9337 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
9338 S += 'b';
9339 // The NeXT runtime encodes bit fields as b followed by the number of bits.
9340 // The GNU runtime requires more information; bitfields are encoded as b,
9341 // then the offset (in bits) of the first element, then the type of the
9342 // bitfield, then the size in bits. For example, in this structure:
9343 //
9344 // struct
9345 // {
9346 // int integer;
9347 // int flags:2;
9348 // };
9349 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
9350 // runtime, but b32i2 for the GNU runtime. The reason for this extra
9351 // information is not especially sensible, but we're stuck with it for
9352 // compatibility with GCC, although providing it breaks anything that
9353 // actually uses runtime introspection and wants to work on both runtimes...
9354 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
9355 uint64_t Offset;
9356
9357 if (const auto *IVD = dyn_cast<ObjCIvarDecl>(Val: FD)) {
9358 Offset = Ctx->lookupFieldBitOffset(OID: IVD->getContainingInterface(), Ivar: IVD);
9359 } else {
9360 const RecordDecl *RD = FD->getParent();
9361 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(D: RD);
9362 Offset = RL.getFieldOffset(FieldNo: FD->getFieldIndex());
9363 }
9364
9365 S += llvm::utostr(X: Offset);
9366
9367 if (const auto *ET = T->getAsCanonical<EnumType>())
9368 S += ObjCEncodingForEnumDecl(C: Ctx, ED: ET->getDecl());
9369 else {
9370 const auto *BT = T->castAs<BuiltinType>();
9371 S += getObjCEncodingForPrimitiveType(C: Ctx, BT);
9372 }
9373 }
9374 S += llvm::utostr(X: FD->getBitWidthValue());
9375}
9376
9377// Helper function for determining whether the encoded type string would include
9378// a template specialization type.
9379static bool hasTemplateSpecializationInEncodedString(const Type *T,
9380 bool VisitBasesAndFields) {
9381 T = T->getBaseElementTypeUnsafe();
9382
9383 if (auto *PT = T->getAs<PointerType>())
9384 return hasTemplateSpecializationInEncodedString(
9385 T: PT->getPointeeType().getTypePtr(), VisitBasesAndFields: false);
9386
9387 auto *CXXRD = T->getAsCXXRecordDecl();
9388
9389 if (!CXXRD)
9390 return false;
9391
9392 if (isa<ClassTemplateSpecializationDecl>(Val: CXXRD))
9393 return true;
9394
9395 if (!CXXRD->hasDefinition() || !VisitBasesAndFields)
9396 return false;
9397
9398 for (const auto &B : CXXRD->bases())
9399 if (hasTemplateSpecializationInEncodedString(T: B.getType().getTypePtr(),
9400 VisitBasesAndFields: true))
9401 return true;
9402
9403 for (auto *FD : CXXRD->fields())
9404 if (hasTemplateSpecializationInEncodedString(T: FD->getType().getTypePtr(),
9405 VisitBasesAndFields: true))
9406 return true;
9407
9408 return false;
9409}
9410
9411// FIXME: Use SmallString for accumulating string.
9412void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S,
9413 const ObjCEncOptions Options,
9414 const FieldDecl *FD,
9415 QualType *NotEncodedT) const {
9416 CanQualType CT = getCanonicalType(T);
9417 switch (CT->getTypeClass()) {
9418 case Type::Builtin:
9419 case Type::Enum:
9420 if (FD && FD->isBitField())
9421 return EncodeBitField(Ctx: this, S, T, FD);
9422 if (const auto *BT = dyn_cast<BuiltinType>(Val&: CT))
9423 S += getObjCEncodingForPrimitiveType(C: this, BT);
9424 else
9425 S += ObjCEncodingForEnumDecl(C: this, ED: cast<EnumType>(Val&: CT)->getDecl());
9426 return;
9427
9428 case Type::Complex:
9429 S += 'j';
9430 getObjCEncodingForTypeImpl(T: T->castAs<ComplexType>()->getElementType(), S,
9431 Options: ObjCEncOptions(),
9432 /*Field=*/FD: nullptr);
9433 return;
9434
9435 case Type::Atomic:
9436 S += 'A';
9437 getObjCEncodingForTypeImpl(T: T->castAs<AtomicType>()->getValueType(), S,
9438 Options: ObjCEncOptions(),
9439 /*Field=*/FD: nullptr);
9440 return;
9441
9442 // encoding for pointer or reference types.
9443 case Type::Pointer:
9444 case Type::LValueReference:
9445 case Type::RValueReference: {
9446 QualType PointeeTy;
9447 if (isa<PointerType>(Val: CT)) {
9448 const auto *PT = T->castAs<PointerType>();
9449 if (PT->isObjCSelType()) {
9450 S += ':';
9451 return;
9452 }
9453 PointeeTy = PT->getPointeeType();
9454 } else {
9455 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
9456 }
9457
9458 bool isReadOnly = false;
9459 // For historical/compatibility reasons, the read-only qualifier of the
9460 // pointee gets emitted _before_ the '^'. The read-only qualifier of
9461 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
9462 // Also, do not emit the 'r' for anything but the outermost type!
9463 if (T->getAs<TypedefType>()) {
9464 if (Options.IsOutermostType() && T.isConstQualified()) {
9465 isReadOnly = true;
9466 S += 'r';
9467 }
9468 } else if (Options.IsOutermostType()) {
9469 QualType P = PointeeTy;
9470 while (auto PT = P->getAs<PointerType>())
9471 P = PT->getPointeeType();
9472 if (P.isConstQualified()) {
9473 isReadOnly = true;
9474 S += 'r';
9475 }
9476 }
9477 if (isReadOnly) {
9478 // Another legacy compatibility encoding. Some ObjC qualifier and type
9479 // combinations need to be rearranged.
9480 // Rewrite "in const" from "nr" to "rn"
9481 if (StringRef(S).ends_with(Suffix: "nr"))
9482 S.replace(i1: S.end()-2, i2: S.end(), s: "rn");
9483 }
9484
9485 if (PointeeTy->isCharType()) {
9486 // char pointer types should be encoded as '*' unless it is a
9487 // type that has been typedef'd to 'BOOL'.
9488 if (!isTypeTypedefedAsBOOL(T: PointeeTy)) {
9489 S += '*';
9490 return;
9491 }
9492 } else if (const auto *RTy = PointeeTy->getAsCanonical<RecordType>()) {
9493 const IdentifierInfo *II = RTy->getDecl()->getIdentifier();
9494 // GCC binary compat: Need to convert "struct objc_class *" to "#".
9495 if (II == &Idents.get(Name: "objc_class")) {
9496 S += '#';
9497 return;
9498 }
9499 // GCC binary compat: Need to convert "struct objc_object *" to "@".
9500 if (II == &Idents.get(Name: "objc_object")) {
9501 S += '@';
9502 return;
9503 }
9504 // If the encoded string for the class includes template names, just emit
9505 // "^v" for pointers to the class.
9506 if (getLangOpts().CPlusPlus &&
9507 (!getLangOpts().EncodeCXXClassTemplateSpec &&
9508 hasTemplateSpecializationInEncodedString(
9509 T: RTy, VisitBasesAndFields: Options.ExpandPointedToStructures()))) {
9510 S += "^v";
9511 return;
9512 }
9513 // fall through...
9514 }
9515 S += '^';
9516 getLegacyIntegralTypeEncoding(PointeeTy);
9517
9518 ObjCEncOptions NewOptions;
9519 if (Options.ExpandPointedToStructures())
9520 NewOptions.setExpandStructures();
9521 getObjCEncodingForTypeImpl(T: PointeeTy, S, Options: NewOptions,
9522 /*Field=*/FD: nullptr, NotEncodedT);
9523 return;
9524 }
9525
9526 case Type::ConstantArray:
9527 case Type::IncompleteArray:
9528 case Type::VariableArray: {
9529 const auto *AT = cast<ArrayType>(Val&: CT);
9530
9531 if (isa<IncompleteArrayType>(Val: AT) && !Options.IsStructField()) {
9532 // Incomplete arrays are encoded as a pointer to the array element.
9533 S += '^';
9534
9535 getObjCEncodingForTypeImpl(
9536 T: AT->getElementType(), S,
9537 Options: Options.keepingOnly(Mask: ObjCEncOptions().setExpandStructures()), FD);
9538 } else {
9539 S += '[';
9540
9541 if (const auto *CAT = dyn_cast<ConstantArrayType>(Val: AT))
9542 S += llvm::utostr(X: CAT->getZExtSize());
9543 else {
9544 //Variable length arrays are encoded as a regular array with 0 elements.
9545 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
9546 "Unknown array type!");
9547 S += '0';
9548 }
9549
9550 getObjCEncodingForTypeImpl(
9551 T: AT->getElementType(), S,
9552 Options: Options.keepingOnly(Mask: ObjCEncOptions().setExpandStructures()), FD,
9553 NotEncodedT);
9554 S += ']';
9555 }
9556 return;
9557 }
9558
9559 case Type::FunctionNoProto:
9560 case Type::FunctionProto:
9561 S += '?';
9562 return;
9563
9564 case Type::Record: {
9565 RecordDecl *RDecl = cast<RecordType>(Val&: CT)->getDecl();
9566 S += RDecl->isUnion() ? '(' : '{';
9567 // Anonymous structures print as '?'
9568 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
9569 S += II->getName();
9570 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(Val: RDecl)) {
9571 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
9572 llvm::raw_string_ostream OS(S);
9573 printTemplateArgumentList(OS, Args: TemplateArgs.asArray(),
9574 Policy: getPrintingPolicy());
9575 }
9576 } else {
9577 S += '?';
9578 }
9579 if (Options.ExpandStructures()) {
9580 S += '=';
9581 if (!RDecl->isUnion()) {
9582 getObjCEncodingForStructureImpl(RD: RDecl, S, Field: FD, includeVBases: true, NotEncodedT);
9583 } else {
9584 for (const auto *Field : RDecl->fields()) {
9585 if (FD) {
9586 S += '"';
9587 S += Field->getNameAsString();
9588 S += '"';
9589 }
9590
9591 // Special case bit-fields.
9592 if (Field->isBitField()) {
9593 getObjCEncodingForTypeImpl(T: Field->getType(), S,
9594 Options: ObjCEncOptions().setExpandStructures(),
9595 FD: Field);
9596 } else {
9597 QualType qt = Field->getType();
9598 getLegacyIntegralTypeEncoding(PointeeTy&: qt);
9599 getObjCEncodingForTypeImpl(
9600 T: qt, S,
9601 Options: ObjCEncOptions().setExpandStructures().setIsStructField(), FD,
9602 NotEncodedT);
9603 }
9604 }
9605 }
9606 }
9607 S += RDecl->isUnion() ? ')' : '}';
9608 return;
9609 }
9610
9611 case Type::BlockPointer: {
9612 const auto *BT = T->castAs<BlockPointerType>();
9613 S += "@?"; // Unlike a pointer-to-function, which is "^?".
9614 if (Options.EncodeBlockParameters()) {
9615 const auto *FT = BT->getPointeeType()->castAs<FunctionType>();
9616
9617 S += '<';
9618 // Block return type
9619 getObjCEncodingForTypeImpl(T: FT->getReturnType(), S,
9620 Options: Options.forComponentType(), FD, NotEncodedT);
9621 // Block self
9622 S += "@?";
9623 // Block parameters
9624 if (const auto *FPT = dyn_cast<FunctionProtoType>(Val: FT)) {
9625 for (const auto &I : FPT->param_types())
9626 getObjCEncodingForTypeImpl(T: I, S, Options: Options.forComponentType(), FD,
9627 NotEncodedT);
9628 }
9629 S += '>';
9630 }
9631 return;
9632 }
9633
9634 case Type::ObjCObject: {
9635 // hack to match legacy encoding of *id and *Class
9636 QualType Ty = getObjCObjectPointerType(ObjectT: CT);
9637 if (Ty->isObjCIdType()) {
9638 S += "{objc_object=}";
9639 return;
9640 }
9641 else if (Ty->isObjCClassType()) {
9642 S += "{objc_class=}";
9643 return;
9644 }
9645 // TODO: Double check to make sure this intentionally falls through.
9646 [[fallthrough]];
9647 }
9648
9649 case Type::ObjCInterface: {
9650 // Ignore protocol qualifiers when mangling at this level.
9651 // @encode(class_name)
9652 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
9653 S += '{';
9654 S += OI->getObjCRuntimeNameAsString();
9655 if (Options.ExpandStructures()) {
9656 S += '=';
9657 SmallVector<const ObjCIvarDecl*, 32> Ivars;
9658 DeepCollectObjCIvars(OI, leafClass: true, Ivars);
9659 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
9660 const FieldDecl *Field = Ivars[i];
9661 if (Field->isBitField())
9662 getObjCEncodingForTypeImpl(T: Field->getType(), S,
9663 Options: ObjCEncOptions().setExpandStructures(),
9664 FD: Field);
9665 else
9666 getObjCEncodingForTypeImpl(T: Field->getType(), S,
9667 Options: ObjCEncOptions().setExpandStructures(), FD,
9668 NotEncodedT);
9669 }
9670 }
9671 S += '}';
9672 return;
9673 }
9674
9675 case Type::ObjCObjectPointer: {
9676 const auto *OPT = T->castAs<ObjCObjectPointerType>();
9677 if (OPT->isObjCIdType()) {
9678 S += '@';
9679 return;
9680 }
9681
9682 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
9683 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
9684 // Since this is a binary compatibility issue, need to consult with
9685 // runtime folks. Fortunately, this is a *very* obscure construct.
9686 S += '#';
9687 return;
9688 }
9689
9690 if (OPT->isObjCQualifiedIdType()) {
9691 getObjCEncodingForTypeImpl(
9692 T: getObjCIdType(), S,
9693 Options: Options.keepingOnly(Mask: ObjCEncOptions()
9694 .setExpandPointedToStructures()
9695 .setExpandStructures()),
9696 FD);
9697 if (FD || Options.EncodingProperty() || Options.EncodeClassNames()) {
9698 // Note that we do extended encoding of protocol qualifier list
9699 // Only when doing ivar or property encoding.
9700 S += '"';
9701 for (const auto *I : OPT->quals()) {
9702 S += '<';
9703 S += I->getObjCRuntimeNameAsString();
9704 S += '>';
9705 }
9706 S += '"';
9707 }
9708 return;
9709 }
9710
9711 S += '@';
9712 if (OPT->getInterfaceDecl() &&
9713 (FD || Options.EncodingProperty() || Options.EncodeClassNames())) {
9714 S += '"';
9715 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
9716 for (const auto *I : OPT->quals()) {
9717 S += '<';
9718 S += I->getObjCRuntimeNameAsString();
9719 S += '>';
9720 }
9721 S += '"';
9722 }
9723 return;
9724 }
9725
9726 // gcc just blithely ignores member pointers.
9727 // FIXME: we should do better than that. 'M' is available.
9728 case Type::MemberPointer:
9729 // This matches gcc's encoding, even though technically it is insufficient.
9730 //FIXME. We should do a better job than gcc.
9731 case Type::Vector:
9732 case Type::ExtVector:
9733 // Until we have a coherent encoding of these three types, issue warning.
9734 if (NotEncodedT)
9735 *NotEncodedT = T;
9736 return;
9737
9738 case Type::ConstantMatrix:
9739 if (NotEncodedT)
9740 *NotEncodedT = T;
9741 return;
9742
9743 case Type::BitInt:
9744 if (NotEncodedT)
9745 *NotEncodedT = T;
9746 return;
9747
9748 // We could see an undeduced auto type here during error recovery.
9749 // Just ignore it.
9750 case Type::Auto:
9751 case Type::DeducedTemplateSpecialization:
9752 return;
9753
9754 case Type::HLSLAttributedResource:
9755 case Type::HLSLInlineSpirv:
9756 case Type::OverflowBehavior:
9757 llvm_unreachable("unexpected type");
9758
9759 case Type::ArrayParameter:
9760 case Type::Pipe:
9761#define ABSTRACT_TYPE(KIND, BASE)
9762#define TYPE(KIND, BASE)
9763#define DEPENDENT_TYPE(KIND, BASE) \
9764 case Type::KIND:
9765#define NON_CANONICAL_TYPE(KIND, BASE) \
9766 case Type::KIND:
9767#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
9768 case Type::KIND:
9769#include "clang/AST/TypeNodes.inc"
9770 llvm_unreachable("@encode for dependent type!");
9771 }
9772 llvm_unreachable("bad type kind!");
9773}
9774
9775void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
9776 std::string &S,
9777 const FieldDecl *FD,
9778 bool includeVBases,
9779 QualType *NotEncodedT) const {
9780 assert(RDecl && "Expected non-null RecordDecl");
9781 assert(!RDecl->isUnion() && "Should not be called for unions");
9782 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
9783 return;
9784
9785 const auto *CXXRec = dyn_cast<CXXRecordDecl>(Val: RDecl);
9786 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
9787 const ASTRecordLayout &layout = getASTRecordLayout(D: RDecl);
9788
9789 if (CXXRec) {
9790 for (const auto &BI : CXXRec->bases()) {
9791 if (!BI.isVirtual()) {
9792 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
9793 if (base->isEmpty())
9794 continue;
9795 uint64_t offs = toBits(CharSize: layout.getBaseClassOffset(Base: base));
9796 FieldOrBaseOffsets.insert(position: FieldOrBaseOffsets.upper_bound(x: offs),
9797 x: std::make_pair(x&: offs, y&: base));
9798 }
9799 }
9800 }
9801
9802 for (FieldDecl *Field : RDecl->fields()) {
9803 if (!Field->isZeroLengthBitField() && Field->isZeroSize(Ctx: *this))
9804 continue;
9805 uint64_t offs = layout.getFieldOffset(FieldNo: Field->getFieldIndex());
9806 FieldOrBaseOffsets.insert(position: FieldOrBaseOffsets.upper_bound(x: offs),
9807 x: std::make_pair(x&: offs, y&: Field));
9808 }
9809
9810 if (CXXRec && includeVBases) {
9811 for (const auto &BI : CXXRec->vbases()) {
9812 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
9813 if (base->isEmpty())
9814 continue;
9815 uint64_t offs = toBits(CharSize: layout.getVBaseClassOffset(VBase: base));
9816 if (offs >= uint64_t(toBits(CharSize: layout.getNonVirtualSize())) &&
9817 FieldOrBaseOffsets.find(x: offs) == FieldOrBaseOffsets.end())
9818 FieldOrBaseOffsets.insert(position: FieldOrBaseOffsets.end(),
9819 x: std::make_pair(x&: offs, y&: base));
9820 }
9821 }
9822
9823 CharUnits size;
9824 if (CXXRec) {
9825 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
9826 } else {
9827 size = layout.getSize();
9828 }
9829
9830#ifndef NDEBUG
9831 uint64_t CurOffs = 0;
9832#endif
9833 std::multimap<uint64_t, NamedDecl *>::iterator
9834 CurLayObj = FieldOrBaseOffsets.begin();
9835
9836 if (CXXRec && CXXRec->isDynamicClass() &&
9837 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
9838 if (FD) {
9839 S += "\"_vptr$";
9840 std::string recname = CXXRec->getNameAsString();
9841 if (recname.empty()) recname = "?";
9842 S += recname;
9843 S += '"';
9844 }
9845 S += "^^?";
9846#ifndef NDEBUG
9847 CurOffs += getTypeSize(VoidPtrTy);
9848#endif
9849 }
9850
9851 if (!RDecl->hasFlexibleArrayMember()) {
9852 // Mark the end of the structure.
9853 uint64_t offs = toBits(CharSize: size);
9854 FieldOrBaseOffsets.insert(position: FieldOrBaseOffsets.upper_bound(x: offs),
9855 x: std::make_pair(x&: offs, y: nullptr));
9856 }
9857
9858 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
9859#ifndef NDEBUG
9860 assert(CurOffs <= CurLayObj->first);
9861 if (CurOffs < CurLayObj->first) {
9862 uint64_t padding = CurLayObj->first - CurOffs;
9863 // FIXME: There doesn't seem to be a way to indicate in the encoding that
9864 // packing/alignment of members is different that normal, in which case
9865 // the encoding will be out-of-sync with the real layout.
9866 // If the runtime switches to just consider the size of types without
9867 // taking into account alignment, we could make padding explicit in the
9868 // encoding (e.g. using arrays of chars). The encoding strings would be
9869 // longer then though.
9870 CurOffs += padding;
9871 }
9872#endif
9873
9874 NamedDecl *dcl = CurLayObj->second;
9875 if (!dcl)
9876 break; // reached end of structure.
9877
9878 if (auto *base = dyn_cast<CXXRecordDecl>(Val: dcl)) {
9879 // We expand the bases without their virtual bases since those are going
9880 // in the initial structure. Note that this differs from gcc which
9881 // expands virtual bases each time one is encountered in the hierarchy,
9882 // making the encoding type bigger than it really is.
9883 getObjCEncodingForStructureImpl(RDecl: base, S, FD, /*includeVBases*/false,
9884 NotEncodedT);
9885 assert(!base->isEmpty());
9886#ifndef NDEBUG
9887 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
9888#endif
9889 } else {
9890 const auto *field = cast<FieldDecl>(Val: dcl);
9891 if (FD) {
9892 S += '"';
9893 S += field->getNameAsString();
9894 S += '"';
9895 }
9896
9897 if (field->isBitField()) {
9898 EncodeBitField(Ctx: this, S, T: field->getType(), FD: field);
9899#ifndef NDEBUG
9900 CurOffs += field->getBitWidthValue();
9901#endif
9902 } else {
9903 QualType qt = field->getType();
9904 getLegacyIntegralTypeEncoding(PointeeTy&: qt);
9905 getObjCEncodingForTypeImpl(
9906 T: qt, S, Options: ObjCEncOptions().setExpandStructures().setIsStructField(),
9907 FD, NotEncodedT);
9908#ifndef NDEBUG
9909 CurOffs += getTypeSize(field->getType());
9910#endif
9911 }
9912 }
9913 }
9914}
9915
9916void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
9917 std::string& S) const {
9918 if (QT & Decl::OBJC_TQ_In)
9919 S += 'n';
9920 if (QT & Decl::OBJC_TQ_Inout)
9921 S += 'N';
9922 if (QT & Decl::OBJC_TQ_Out)
9923 S += 'o';
9924 if (QT & Decl::OBJC_TQ_Bycopy)
9925 S += 'O';
9926 if (QT & Decl::OBJC_TQ_Byref)
9927 S += 'R';
9928 if (QT & Decl::OBJC_TQ_Oneway)
9929 S += 'V';
9930}
9931
9932TypedefDecl *ASTContext::getObjCIdDecl() const {
9933 if (!ObjCIdDecl) {
9934 QualType T = getObjCObjectType(BaseType: ObjCBuiltinIdTy, Protocols: {}, NumProtocols: {});
9935 T = getObjCObjectPointerType(ObjectT: T);
9936 ObjCIdDecl = buildImplicitTypedef(T, Name: "id");
9937 }
9938 return ObjCIdDecl;
9939}
9940
9941TypedefDecl *ASTContext::getObjCSelDecl() const {
9942 if (!ObjCSelDecl) {
9943 QualType T = getPointerType(T: ObjCBuiltinSelTy);
9944 ObjCSelDecl = buildImplicitTypedef(T, Name: "SEL");
9945 }
9946 return ObjCSelDecl;
9947}
9948
9949TypedefDecl *ASTContext::getObjCClassDecl() const {
9950 if (!ObjCClassDecl) {
9951 QualType T = getObjCObjectType(BaseType: ObjCBuiltinClassTy, Protocols: {}, NumProtocols: {});
9952 T = getObjCObjectPointerType(ObjectT: T);
9953 ObjCClassDecl = buildImplicitTypedef(T, Name: "Class");
9954 }
9955 return ObjCClassDecl;
9956}
9957
9958ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
9959 if (!ObjCProtocolClassDecl) {
9960 ObjCProtocolClassDecl
9961 = ObjCInterfaceDecl::Create(C: *this, DC: getTranslationUnitDecl(),
9962 atLoc: SourceLocation(),
9963 Id: &Idents.get(Name: "Protocol"),
9964 /*typeParamList=*/nullptr,
9965 /*PrevDecl=*/nullptr,
9966 ClassLoc: SourceLocation(), isInternal: true);
9967 }
9968
9969 return ObjCProtocolClassDecl;
9970}
9971
9972PointerAuthQualifier ASTContext::getObjCMemberSelTypePtrAuth() {
9973 if (!getLangOpts().PointerAuthObjcInterfaceSel)
9974 return PointerAuthQualifier();
9975 return PointerAuthQualifier::Create(
9976 Key: getLangOpts().PointerAuthObjcInterfaceSelKey,
9977 /*isAddressDiscriminated=*/IsAddressDiscriminated: true, ExtraDiscriminator: SelPointerConstantDiscriminator,
9978 AuthenticationMode: PointerAuthenticationMode::SignAndAuth,
9979 /*isIsaPointer=*/IsIsaPointer: false,
9980 /*authenticatesNullValues=*/AuthenticatesNullValues: false);
9981}
9982
9983//===----------------------------------------------------------------------===//
9984// __builtin_va_list Construction Functions
9985//===----------------------------------------------------------------------===//
9986
9987static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context,
9988 StringRef Name) {
9989 // typedef char* __builtin[_ms]_va_list;
9990 QualType T = Context->getPointerType(T: Context->CharTy);
9991 return Context->buildImplicitTypedef(T, Name);
9992}
9993
9994static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
9995 return CreateCharPtrNamedVaListDecl(Context, Name: "__builtin_ms_va_list");
9996}
9997
9998static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
9999 return CreateCharPtrNamedVaListDecl(Context, Name: "__builtin_va_list");
10000}
10001
10002static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
10003 // typedef void* __builtin_va_list;
10004 QualType T = Context->getPointerType(T: Context->VoidTy);
10005 return Context->buildImplicitTypedef(T, Name: "__builtin_va_list");
10006}
10007
10008static TypedefDecl *
10009CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
10010 // struct __va_list
10011 RecordDecl *VaListTagDecl = Context->buildImplicitRecord(Name: "__va_list");
10012 if (Context->getLangOpts().CPlusPlus) {
10013 // namespace std { struct __va_list {
10014 auto *NS = NamespaceDecl::Create(
10015 C&: const_cast<ASTContext &>(*Context), DC: Context->getTranslationUnitDecl(),
10016 /*Inline=*/false, StartLoc: SourceLocation(), IdLoc: SourceLocation(),
10017 Id: &Context->Idents.get(Name: "std"),
10018 /*PrevDecl=*/nullptr, /*Nested=*/false);
10019 NS->setImplicit();
10020 VaListTagDecl->setDeclContext(NS);
10021 }
10022
10023 VaListTagDecl->startDefinition();
10024
10025 const size_t NumFields = 5;
10026 QualType FieldTypes[NumFields];
10027 const char *FieldNames[NumFields];
10028
10029 // void *__stack;
10030 FieldTypes[0] = Context->getPointerType(T: Context->VoidTy);
10031 FieldNames[0] = "__stack";
10032
10033 // void *__gr_top;
10034 FieldTypes[1] = Context->getPointerType(T: Context->VoidTy);
10035 FieldNames[1] = "__gr_top";
10036
10037 // void *__vr_top;
10038 FieldTypes[2] = Context->getPointerType(T: Context->VoidTy);
10039 FieldNames[2] = "__vr_top";
10040
10041 // int __gr_offs;
10042 FieldTypes[3] = Context->IntTy;
10043 FieldNames[3] = "__gr_offs";
10044
10045 // int __vr_offs;
10046 FieldTypes[4] = Context->IntTy;
10047 FieldNames[4] = "__vr_offs";
10048
10049 // Create fields
10050 for (unsigned i = 0; i < NumFields; ++i) {
10051 FieldDecl *Field = FieldDecl::Create(C: const_cast<ASTContext &>(*Context),
10052 DC: VaListTagDecl,
10053 StartLoc: SourceLocation(),
10054 IdLoc: SourceLocation(),
10055 Id: &Context->Idents.get(Name: FieldNames[i]),
10056 T: FieldTypes[i], /*TInfo=*/nullptr,
10057 /*BitWidth=*/BW: nullptr,
10058 /*Mutable=*/false,
10059 InitStyle: ICIS_NoInit);
10060 Field->setAccess(AS_public);
10061 VaListTagDecl->addDecl(D: Field);
10062 }
10063 VaListTagDecl->completeDefinition();
10064 Context->VaListTagDecl = VaListTagDecl;
10065 CanQualType VaListTagType = Context->getCanonicalTagType(TD: VaListTagDecl);
10066
10067 // } __builtin_va_list;
10068 return Context->buildImplicitTypedef(T: VaListTagType, Name: "__builtin_va_list");
10069}
10070
10071static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
10072 // typedef struct __va_list_tag {
10073 RecordDecl *VaListTagDecl;
10074
10075 VaListTagDecl = Context->buildImplicitRecord(Name: "__va_list_tag");
10076 VaListTagDecl->startDefinition();
10077
10078 const size_t NumFields = 5;
10079 QualType FieldTypes[NumFields];
10080 const char *FieldNames[NumFields];
10081
10082 // unsigned char gpr;
10083 FieldTypes[0] = Context->UnsignedCharTy;
10084 FieldNames[0] = "gpr";
10085
10086 // unsigned char fpr;
10087 FieldTypes[1] = Context->UnsignedCharTy;
10088 FieldNames[1] = "fpr";
10089
10090 // unsigned short reserved;
10091 FieldTypes[2] = Context->UnsignedShortTy;
10092 FieldNames[2] = "reserved";
10093
10094 // void* overflow_arg_area;
10095 FieldTypes[3] = Context->getPointerType(T: Context->VoidTy);
10096 FieldNames[3] = "overflow_arg_area";
10097
10098 // void* reg_save_area;
10099 FieldTypes[4] = Context->getPointerType(T: Context->VoidTy);
10100 FieldNames[4] = "reg_save_area";
10101
10102 // Create fields
10103 for (unsigned i = 0; i < NumFields; ++i) {
10104 FieldDecl *Field = FieldDecl::Create(C: *Context, DC: VaListTagDecl,
10105 StartLoc: SourceLocation(),
10106 IdLoc: SourceLocation(),
10107 Id: &Context->Idents.get(Name: FieldNames[i]),
10108 T: FieldTypes[i], /*TInfo=*/nullptr,
10109 /*BitWidth=*/BW: nullptr,
10110 /*Mutable=*/false,
10111 InitStyle: ICIS_NoInit);
10112 Field->setAccess(AS_public);
10113 VaListTagDecl->addDecl(D: Field);
10114 }
10115 VaListTagDecl->completeDefinition();
10116 Context->VaListTagDecl = VaListTagDecl;
10117 CanQualType VaListTagType = Context->getCanonicalTagType(TD: VaListTagDecl);
10118
10119 // } __va_list_tag;
10120 TypedefDecl *VaListTagTypedefDecl =
10121 Context->buildImplicitTypedef(T: VaListTagType, Name: "__va_list_tag");
10122
10123 QualType VaListTagTypedefType =
10124 Context->getTypedefType(Keyword: ElaboratedTypeKeyword::None,
10125 /*Qualifier=*/std::nullopt, Decl: VaListTagTypedefDecl);
10126
10127 // typedef __va_list_tag __builtin_va_list[1];
10128 llvm::APInt Size(Context->getTypeSize(T: Context->getSizeType()), 1);
10129 QualType VaListTagArrayType = Context->getConstantArrayType(
10130 EltTy: VaListTagTypedefType, ArySizeIn: Size, SizeExpr: nullptr, ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
10131 return Context->buildImplicitTypedef(T: VaListTagArrayType, Name: "__builtin_va_list");
10132}
10133
10134static TypedefDecl *
10135CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
10136 // struct __va_list_tag {
10137 RecordDecl *VaListTagDecl;
10138 VaListTagDecl = Context->buildImplicitRecord(Name: "__va_list_tag");
10139 VaListTagDecl->startDefinition();
10140
10141 const size_t NumFields = 4;
10142 QualType FieldTypes[NumFields];
10143 const char *FieldNames[NumFields];
10144
10145 // unsigned gp_offset;
10146 FieldTypes[0] = Context->UnsignedIntTy;
10147 FieldNames[0] = "gp_offset";
10148
10149 // unsigned fp_offset;
10150 FieldTypes[1] = Context->UnsignedIntTy;
10151 FieldNames[1] = "fp_offset";
10152
10153 // void* overflow_arg_area;
10154 FieldTypes[2] = Context->getPointerType(T: Context->VoidTy);
10155 FieldNames[2] = "overflow_arg_area";
10156
10157 // void* reg_save_area;
10158 FieldTypes[3] = Context->getPointerType(T: Context->VoidTy);
10159 FieldNames[3] = "reg_save_area";
10160
10161 // Create fields
10162 for (unsigned i = 0; i < NumFields; ++i) {
10163 FieldDecl *Field = FieldDecl::Create(C: const_cast<ASTContext &>(*Context),
10164 DC: VaListTagDecl,
10165 StartLoc: SourceLocation(),
10166 IdLoc: SourceLocation(),
10167 Id: &Context->Idents.get(Name: FieldNames[i]),
10168 T: FieldTypes[i], /*TInfo=*/nullptr,
10169 /*BitWidth=*/BW: nullptr,
10170 /*Mutable=*/false,
10171 InitStyle: ICIS_NoInit);
10172 Field->setAccess(AS_public);
10173 VaListTagDecl->addDecl(D: Field);
10174 }
10175 VaListTagDecl->completeDefinition();
10176 Context->VaListTagDecl = VaListTagDecl;
10177 CanQualType VaListTagType = Context->getCanonicalTagType(TD: VaListTagDecl);
10178
10179 // };
10180
10181 // typedef struct __va_list_tag __builtin_va_list[1];
10182 llvm::APInt Size(Context->getTypeSize(T: Context->getSizeType()), 1);
10183 QualType VaListTagArrayType = Context->getConstantArrayType(
10184 EltTy: VaListTagType, ArySizeIn: Size, SizeExpr: nullptr, ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
10185 return Context->buildImplicitTypedef(T: VaListTagArrayType, Name: "__builtin_va_list");
10186}
10187
10188static TypedefDecl *
10189CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
10190 // struct __va_list
10191 RecordDecl *VaListDecl = Context->buildImplicitRecord(Name: "__va_list");
10192 if (Context->getLangOpts().CPlusPlus) {
10193 // namespace std { struct __va_list {
10194 NamespaceDecl *NS;
10195 NS = NamespaceDecl::Create(C&: const_cast<ASTContext &>(*Context),
10196 DC: Context->getTranslationUnitDecl(),
10197 /*Inline=*/false, StartLoc: SourceLocation(),
10198 IdLoc: SourceLocation(), Id: &Context->Idents.get(Name: "std"),
10199 /*PrevDecl=*/nullptr, /*Nested=*/false);
10200 NS->setImplicit();
10201 VaListDecl->setDeclContext(NS);
10202 }
10203
10204 VaListDecl->startDefinition();
10205
10206 // void * __ap;
10207 FieldDecl *Field = FieldDecl::Create(C: const_cast<ASTContext &>(*Context),
10208 DC: VaListDecl,
10209 StartLoc: SourceLocation(),
10210 IdLoc: SourceLocation(),
10211 Id: &Context->Idents.get(Name: "__ap"),
10212 T: Context->getPointerType(T: Context->VoidTy),
10213 /*TInfo=*/nullptr,
10214 /*BitWidth=*/BW: nullptr,
10215 /*Mutable=*/false,
10216 InitStyle: ICIS_NoInit);
10217 Field->setAccess(AS_public);
10218 VaListDecl->addDecl(D: Field);
10219
10220 // };
10221 VaListDecl->completeDefinition();
10222 Context->VaListTagDecl = VaListDecl;
10223
10224 // typedef struct __va_list __builtin_va_list;
10225 CanQualType T = Context->getCanonicalTagType(TD: VaListDecl);
10226 return Context->buildImplicitTypedef(T, Name: "__builtin_va_list");
10227}
10228
10229static TypedefDecl *
10230CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
10231 // struct __va_list_tag {
10232 RecordDecl *VaListTagDecl;
10233 VaListTagDecl = Context->buildImplicitRecord(Name: "__va_list_tag");
10234 VaListTagDecl->startDefinition();
10235
10236 const size_t NumFields = 4;
10237 QualType FieldTypes[NumFields];
10238 const char *FieldNames[NumFields];
10239
10240 // long __gpr;
10241 FieldTypes[0] = Context->LongTy;
10242 FieldNames[0] = "__gpr";
10243
10244 // long __fpr;
10245 FieldTypes[1] = Context->LongTy;
10246 FieldNames[1] = "__fpr";
10247
10248 // void *__overflow_arg_area;
10249 FieldTypes[2] = Context->getPointerType(T: Context->VoidTy);
10250 FieldNames[2] = "__overflow_arg_area";
10251
10252 // void *__reg_save_area;
10253 FieldTypes[3] = Context->getPointerType(T: Context->VoidTy);
10254 FieldNames[3] = "__reg_save_area";
10255
10256 // Create fields
10257 for (unsigned i = 0; i < NumFields; ++i) {
10258 FieldDecl *Field = FieldDecl::Create(C: const_cast<ASTContext &>(*Context),
10259 DC: VaListTagDecl,
10260 StartLoc: SourceLocation(),
10261 IdLoc: SourceLocation(),
10262 Id: &Context->Idents.get(Name: FieldNames[i]),
10263 T: FieldTypes[i], /*TInfo=*/nullptr,
10264 /*BitWidth=*/BW: nullptr,
10265 /*Mutable=*/false,
10266 InitStyle: ICIS_NoInit);
10267 Field->setAccess(AS_public);
10268 VaListTagDecl->addDecl(D: Field);
10269 }
10270 VaListTagDecl->completeDefinition();
10271 Context->VaListTagDecl = VaListTagDecl;
10272 CanQualType VaListTagType = Context->getCanonicalTagType(TD: VaListTagDecl);
10273
10274 // };
10275
10276 // typedef __va_list_tag __builtin_va_list[1];
10277 llvm::APInt Size(Context->getTypeSize(T: Context->getSizeType()), 1);
10278 QualType VaListTagArrayType = Context->getConstantArrayType(
10279 EltTy: VaListTagType, ArySizeIn: Size, SizeExpr: nullptr, ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
10280
10281 return Context->buildImplicitTypedef(T: VaListTagArrayType, Name: "__builtin_va_list");
10282}
10283
10284static TypedefDecl *CreateHexagonBuiltinVaListDecl(const ASTContext *Context) {
10285 // typedef struct __va_list_tag {
10286 RecordDecl *VaListTagDecl;
10287 VaListTagDecl = Context->buildImplicitRecord(Name: "__va_list_tag");
10288 VaListTagDecl->startDefinition();
10289
10290 const size_t NumFields = 3;
10291 QualType FieldTypes[NumFields];
10292 const char *FieldNames[NumFields];
10293
10294 // void *CurrentSavedRegisterArea;
10295 FieldTypes[0] = Context->getPointerType(T: Context->VoidTy);
10296 FieldNames[0] = "__current_saved_reg_area_pointer";
10297
10298 // void *SavedRegAreaEnd;
10299 FieldTypes[1] = Context->getPointerType(T: Context->VoidTy);
10300 FieldNames[1] = "__saved_reg_area_end_pointer";
10301
10302 // void *OverflowArea;
10303 FieldTypes[2] = Context->getPointerType(T: Context->VoidTy);
10304 FieldNames[2] = "__overflow_area_pointer";
10305
10306 // Create fields
10307 for (unsigned i = 0; i < NumFields; ++i) {
10308 FieldDecl *Field = FieldDecl::Create(
10309 C: const_cast<ASTContext &>(*Context), DC: VaListTagDecl, StartLoc: SourceLocation(),
10310 IdLoc: SourceLocation(), Id: &Context->Idents.get(Name: FieldNames[i]), T: FieldTypes[i],
10311 /*TInfo=*/nullptr,
10312 /*BitWidth=*/BW: nullptr,
10313 /*Mutable=*/false, InitStyle: ICIS_NoInit);
10314 Field->setAccess(AS_public);
10315 VaListTagDecl->addDecl(D: Field);
10316 }
10317 VaListTagDecl->completeDefinition();
10318 Context->VaListTagDecl = VaListTagDecl;
10319 CanQualType VaListTagType = Context->getCanonicalTagType(TD: VaListTagDecl);
10320
10321 // } __va_list_tag;
10322 TypedefDecl *VaListTagTypedefDecl =
10323 Context->buildImplicitTypedef(T: VaListTagType, Name: "__va_list_tag");
10324
10325 QualType VaListTagTypedefType =
10326 Context->getTypedefType(Keyword: ElaboratedTypeKeyword::None,
10327 /*Qualifier=*/std::nullopt, Decl: VaListTagTypedefDecl);
10328
10329 // typedef __va_list_tag __builtin_va_list[1];
10330 llvm::APInt Size(Context->getTypeSize(T: Context->getSizeType()), 1);
10331 QualType VaListTagArrayType = Context->getConstantArrayType(
10332 EltTy: VaListTagTypedefType, ArySizeIn: Size, SizeExpr: nullptr, ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
10333
10334 return Context->buildImplicitTypedef(T: VaListTagArrayType, Name: "__builtin_va_list");
10335}
10336
10337static TypedefDecl *
10338CreateXtensaABIBuiltinVaListDecl(const ASTContext *Context) {
10339 // typedef struct __va_list_tag {
10340 RecordDecl *VaListTagDecl = Context->buildImplicitRecord(Name: "__va_list_tag");
10341
10342 VaListTagDecl->startDefinition();
10343
10344 // int* __va_stk;
10345 // int* __va_reg;
10346 // int __va_ndx;
10347 constexpr size_t NumFields = 3;
10348 QualType FieldTypes[NumFields] = {Context->getPointerType(T: Context->IntTy),
10349 Context->getPointerType(T: Context->IntTy),
10350 Context->IntTy};
10351 const char *FieldNames[NumFields] = {"__va_stk", "__va_reg", "__va_ndx"};
10352
10353 // Create fields
10354 for (unsigned i = 0; i < NumFields; ++i) {
10355 FieldDecl *Field = FieldDecl::Create(
10356 C: *Context, DC: VaListTagDecl, StartLoc: SourceLocation(), IdLoc: SourceLocation(),
10357 Id: &Context->Idents.get(Name: FieldNames[i]), T: FieldTypes[i], /*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: "__builtin_va_list");
10370
10371 return VaListTagTypedefDecl;
10372}
10373
10374static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
10375 TargetInfo::BuiltinVaListKind Kind) {
10376 switch (Kind) {
10377 case TargetInfo::CharPtrBuiltinVaList:
10378 return CreateCharPtrBuiltinVaListDecl(Context);
10379 case TargetInfo::VoidPtrBuiltinVaList:
10380 return CreateVoidPtrBuiltinVaListDecl(Context);
10381 case TargetInfo::AArch64ABIBuiltinVaList:
10382 return CreateAArch64ABIBuiltinVaListDecl(Context);
10383 case TargetInfo::PowerABIBuiltinVaList:
10384 return CreatePowerABIBuiltinVaListDecl(Context);
10385 case TargetInfo::X86_64ABIBuiltinVaList:
10386 return CreateX86_64ABIBuiltinVaListDecl(Context);
10387 case TargetInfo::AAPCSABIBuiltinVaList:
10388 return CreateAAPCSABIBuiltinVaListDecl(Context);
10389 case TargetInfo::SystemZBuiltinVaList:
10390 return CreateSystemZBuiltinVaListDecl(Context);
10391 case TargetInfo::HexagonBuiltinVaList:
10392 return CreateHexagonBuiltinVaListDecl(Context);
10393 case TargetInfo::XtensaABIBuiltinVaList:
10394 return CreateXtensaABIBuiltinVaListDecl(Context);
10395 }
10396
10397 llvm_unreachable("Unhandled __builtin_va_list type kind");
10398}
10399
10400TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
10401 if (!BuiltinVaListDecl) {
10402 BuiltinVaListDecl = CreateVaListDecl(Context: this, Kind: Target->getBuiltinVaListKind());
10403 assert(BuiltinVaListDecl->isImplicit());
10404 }
10405
10406 return BuiltinVaListDecl;
10407}
10408
10409Decl *ASTContext::getVaListTagDecl() const {
10410 // Force the creation of VaListTagDecl by building the __builtin_va_list
10411 // declaration.
10412 if (!VaListTagDecl)
10413 (void)getBuiltinVaListDecl();
10414
10415 return VaListTagDecl;
10416}
10417
10418TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const {
10419 if (!BuiltinMSVaListDecl)
10420 BuiltinMSVaListDecl = CreateMSVaListDecl(Context: this);
10421
10422 return BuiltinMSVaListDecl;
10423}
10424
10425bool ASTContext::canBuiltinBeRedeclared(const FunctionDecl *FD) const {
10426 // Allow redecl custom type checking builtin for HLSL.
10427 if (LangOpts.HLSL && FD->getBuiltinID() != Builtin::NotBuiltin &&
10428 BuiltinInfo.hasCustomTypechecking(ID: FD->getBuiltinID()))
10429 return true;
10430 // Allow redecl custom type checking builtin for SPIR-V.
10431 if (getTargetInfo().getTriple().isSPIROrSPIRV() &&
10432 BuiltinInfo.isTSBuiltin(ID: FD->getBuiltinID()) &&
10433 BuiltinInfo.hasCustomTypechecking(ID: FD->getBuiltinID()))
10434 return true;
10435 return BuiltinInfo.canBeRedeclared(ID: FD->getBuiltinID());
10436}
10437
10438void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
10439 assert(ObjCConstantStringType.isNull() &&
10440 "'NSConstantString' type already set!");
10441
10442 ObjCConstantStringType = getObjCInterfaceType(Decl);
10443}
10444
10445/// Retrieve the template name that corresponds to a non-empty
10446/// lookup.
10447TemplateName
10448ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
10449 UnresolvedSetIterator End) const {
10450 unsigned size = End - Begin;
10451 assert(size > 1 && "set is not overloaded!");
10452
10453 void *memory = Allocate(Size: sizeof(OverloadedTemplateStorage) +
10454 size * sizeof(FunctionTemplateDecl*));
10455 auto *OT = new (memory) OverloadedTemplateStorage(size);
10456
10457 NamedDecl **Storage = OT->getStorage();
10458 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
10459 NamedDecl *D = *I;
10460 assert(isa<FunctionTemplateDecl>(D) ||
10461 isa<UnresolvedUsingValueDecl>(D) ||
10462 (isa<UsingShadowDecl>(D) &&
10463 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
10464 *Storage++ = D;
10465 }
10466
10467 return TemplateName(OT);
10468}
10469
10470/// Retrieve a template name representing an unqualified-id that has been
10471/// assumed to name a template for ADL purposes.
10472TemplateName ASTContext::getAssumedTemplateName(DeclarationName Name) const {
10473 auto *OT = new (*this) AssumedTemplateStorage(Name);
10474 return TemplateName(OT);
10475}
10476
10477/// Retrieve the template name that represents a qualified
10478/// template name such as \c std::vector.
10479TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier Qualifier,
10480 bool TemplateKeyword,
10481 TemplateName Template) const {
10482 assert(Template.getKind() == TemplateName::Template ||
10483 Template.getKind() == TemplateName::UsingTemplate);
10484
10485 if (Template.getAsTemplateDecl()->getKind() == Decl::TemplateTemplateParm) {
10486 assert(!Qualifier && "unexpected qualified template template parameter");
10487 assert(TemplateKeyword == false);
10488 return Template;
10489 }
10490
10491 // FIXME: Canonicalization?
10492 llvm::FoldingSetNodeID ID;
10493 QualifiedTemplateName::Profile(ID, NNS: Qualifier, TemplateKeyword, TN: Template);
10494
10495 void *InsertPos = nullptr;
10496 QualifiedTemplateName *QTN =
10497 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
10498 if (!QTN) {
10499 QTN = new (*this, alignof(QualifiedTemplateName))
10500 QualifiedTemplateName(Qualifier, TemplateKeyword, Template);
10501 QualifiedTemplateNames.InsertNode(N: QTN, InsertPos);
10502 }
10503
10504 return TemplateName(QTN);
10505}
10506
10507/// Retrieve the template name that represents a dependent
10508/// template name such as \c MetaFun::template operator+.
10509TemplateName
10510ASTContext::getDependentTemplateName(const DependentTemplateStorage &S) const {
10511 llvm::FoldingSetNodeID ID;
10512 S.Profile(ID);
10513
10514 void *InsertPos = nullptr;
10515 if (DependentTemplateName *QTN =
10516 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos))
10517 return TemplateName(QTN);
10518
10519 DependentTemplateName *QTN =
10520 new (*this, alignof(DependentTemplateName)) DependentTemplateName(S);
10521 DependentTemplateNames.InsertNode(N: QTN, InsertPos);
10522 return TemplateName(QTN);
10523}
10524
10525TemplateName ASTContext::getSubstTemplateTemplateParm(TemplateName Replacement,
10526 Decl *AssociatedDecl,
10527 unsigned Index,
10528 UnsignedOrNone PackIndex,
10529 bool Final) const {
10530 llvm::FoldingSetNodeID ID;
10531 SubstTemplateTemplateParmStorage::Profile(ID, Replacement, AssociatedDecl,
10532 Index, PackIndex, Final);
10533
10534 void *insertPos = nullptr;
10535 SubstTemplateTemplateParmStorage *subst
10536 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos&: insertPos);
10537
10538 if (!subst) {
10539 subst = new (*this) SubstTemplateTemplateParmStorage(
10540 Replacement, AssociatedDecl, Index, PackIndex, Final);
10541 SubstTemplateTemplateParms.InsertNode(N: subst, InsertPos: insertPos);
10542 }
10543
10544 return TemplateName(subst);
10545}
10546
10547TemplateName
10548ASTContext::getSubstTemplateTemplateParmPack(const TemplateArgument &ArgPack,
10549 Decl *AssociatedDecl,
10550 unsigned Index, bool Final) const {
10551 auto &Self = const_cast<ASTContext &>(*this);
10552 llvm::FoldingSetNodeID ID;
10553 SubstTemplateTemplateParmPackStorage::Profile(ID, Context&: Self, ArgPack,
10554 AssociatedDecl, Index, Final);
10555
10556 void *InsertPos = nullptr;
10557 SubstTemplateTemplateParmPackStorage *Subst
10558 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
10559
10560 if (!Subst) {
10561 Subst = new (*this) SubstTemplateTemplateParmPackStorage(
10562 ArgPack.pack_elements(), AssociatedDecl, Index, Final);
10563 SubstTemplateTemplateParmPacks.InsertNode(N: Subst, InsertPos);
10564 }
10565
10566 return TemplateName(Subst);
10567}
10568
10569/// Retrieve the template name that represents a template name
10570/// deduced from a specialization.
10571TemplateName
10572ASTContext::getDeducedTemplateName(TemplateName Underlying,
10573 DefaultArguments DefaultArgs) const {
10574 if (!DefaultArgs)
10575 return Underlying;
10576
10577 llvm::FoldingSetNodeID ID;
10578 DeducedTemplateStorage::Profile(ID, Context: *this, Underlying, DefArgs: DefaultArgs);
10579
10580 void *InsertPos = nullptr;
10581 DeducedTemplateStorage *DTS =
10582 DeducedTemplates.FindNodeOrInsertPos(ID, InsertPos);
10583 if (!DTS) {
10584 void *Mem = Allocate(Size: sizeof(DeducedTemplateStorage) +
10585 sizeof(TemplateArgument) * DefaultArgs.Args.size(),
10586 Align: alignof(DeducedTemplateStorage));
10587 DTS = new (Mem) DeducedTemplateStorage(Underlying, DefaultArgs);
10588 DeducedTemplates.InsertNode(N: DTS, InsertPos);
10589 }
10590 return TemplateName(DTS);
10591}
10592
10593/// getFromTargetType - Given one of the integer types provided by
10594/// TargetInfo, produce the corresponding type. The unsigned @p Type
10595/// is actually a value of type @c TargetInfo::IntType.
10596CanQualType ASTContext::getFromTargetType(unsigned Type) const {
10597 switch (Type) {
10598 case TargetInfo::NoInt: return {};
10599 case TargetInfo::SignedChar: return SignedCharTy;
10600 case TargetInfo::UnsignedChar: return UnsignedCharTy;
10601 case TargetInfo::SignedShort: return ShortTy;
10602 case TargetInfo::UnsignedShort: return UnsignedShortTy;
10603 case TargetInfo::SignedInt: return IntTy;
10604 case TargetInfo::UnsignedInt: return UnsignedIntTy;
10605 case TargetInfo::SignedLong: return LongTy;
10606 case TargetInfo::UnsignedLong: return UnsignedLongTy;
10607 case TargetInfo::SignedLongLong: return LongLongTy;
10608 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
10609 }
10610
10611 llvm_unreachable("Unhandled TargetInfo::IntType value");
10612}
10613
10614//===----------------------------------------------------------------------===//
10615// Type Predicates.
10616//===----------------------------------------------------------------------===//
10617
10618/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
10619/// garbage collection attribute.
10620///
10621Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
10622 if (getLangOpts().getGC() == LangOptions::NonGC)
10623 return Qualifiers::GCNone;
10624
10625 assert(getLangOpts().ObjC);
10626 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
10627
10628 // Default behaviour under objective-C's gc is for ObjC pointers
10629 // (or pointers to them) be treated as though they were declared
10630 // as __strong.
10631 if (GCAttrs == Qualifiers::GCNone) {
10632 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
10633 return Qualifiers::Strong;
10634 else if (Ty->isPointerType())
10635 return getObjCGCAttrKind(Ty: Ty->castAs<PointerType>()->getPointeeType());
10636 } else {
10637 // It's not valid to set GC attributes on anything that isn't a
10638 // pointer.
10639#ifndef NDEBUG
10640 QualType CT = Ty->getCanonicalTypeInternal();
10641 while (const auto *AT = dyn_cast<ArrayType>(CT))
10642 CT = AT->getElementType();
10643 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
10644#endif
10645 }
10646 return GCAttrs;
10647}
10648
10649//===----------------------------------------------------------------------===//
10650// Type Compatibility Testing
10651//===----------------------------------------------------------------------===//
10652
10653/// areCompatVectorTypes - Return true if the two specified vector types are
10654/// compatible.
10655static bool areCompatVectorTypes(const VectorType *LHS,
10656 const VectorType *RHS) {
10657 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
10658 return LHS->getElementType() == RHS->getElementType() &&
10659 LHS->getNumElements() == RHS->getNumElements();
10660}
10661
10662/// areCompatMatrixTypes - Return true if the two specified matrix types are
10663/// compatible.
10664static bool areCompatMatrixTypes(const ConstantMatrixType *LHS,
10665 const ConstantMatrixType *RHS) {
10666 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
10667 return LHS->getElementType() == RHS->getElementType() &&
10668 LHS->getNumRows() == RHS->getNumRows() &&
10669 LHS->getNumColumns() == RHS->getNumColumns();
10670}
10671
10672bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
10673 QualType SecondVec) {
10674 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
10675 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
10676
10677 if (hasSameUnqualifiedType(T1: FirstVec, T2: SecondVec))
10678 return true;
10679
10680 // Treat Neon vector types and most AltiVec vector types as if they are the
10681 // equivalent GCC vector types.
10682 const auto *First = FirstVec->castAs<VectorType>();
10683 const auto *Second = SecondVec->castAs<VectorType>();
10684 if (First->getNumElements() == Second->getNumElements() &&
10685 hasSameType(T1: First->getElementType(), T2: Second->getElementType()) &&
10686 First->getVectorKind() != VectorKind::AltiVecPixel &&
10687 First->getVectorKind() != VectorKind::AltiVecBool &&
10688 Second->getVectorKind() != VectorKind::AltiVecPixel &&
10689 Second->getVectorKind() != VectorKind::AltiVecBool &&
10690 First->getVectorKind() != VectorKind::SveFixedLengthData &&
10691 First->getVectorKind() != VectorKind::SveFixedLengthPredicate &&
10692 Second->getVectorKind() != VectorKind::SveFixedLengthData &&
10693 Second->getVectorKind() != VectorKind::SveFixedLengthPredicate &&
10694 First->getVectorKind() != VectorKind::RVVFixedLengthData &&
10695 Second->getVectorKind() != VectorKind::RVVFixedLengthData &&
10696 First->getVectorKind() != VectorKind::RVVFixedLengthMask &&
10697 Second->getVectorKind() != VectorKind::RVVFixedLengthMask &&
10698 First->getVectorKind() != VectorKind::RVVFixedLengthMask_1 &&
10699 Second->getVectorKind() != VectorKind::RVVFixedLengthMask_1 &&
10700 First->getVectorKind() != VectorKind::RVVFixedLengthMask_2 &&
10701 Second->getVectorKind() != VectorKind::RVVFixedLengthMask_2 &&
10702 First->getVectorKind() != VectorKind::RVVFixedLengthMask_4 &&
10703 Second->getVectorKind() != VectorKind::RVVFixedLengthMask_4)
10704 return true;
10705
10706 // In OpenCL, treat half and _Float16 vector types as compatible.
10707 if (getLangOpts().OpenCL &&
10708 First->getNumElements() == Second->getNumElements()) {
10709 QualType FirstElt = First->getElementType();
10710 QualType SecondElt = Second->getElementType();
10711
10712 if ((FirstElt->isFloat16Type() && SecondElt->isHalfType()) ||
10713 (FirstElt->isHalfType() && SecondElt->isFloat16Type())) {
10714 if (First->getVectorKind() != VectorKind::AltiVecPixel &&
10715 First->getVectorKind() != VectorKind::AltiVecBool &&
10716 Second->getVectorKind() != VectorKind::AltiVecPixel &&
10717 Second->getVectorKind() != VectorKind::AltiVecBool)
10718 return true;
10719 }
10720 }
10721 return false;
10722}
10723
10724bool ASTContext::areCompatibleOverflowBehaviorTypes(QualType LHS,
10725 QualType RHS) {
10726 auto Result = checkOBTAssignmentCompatibility(LHS, RHS);
10727 return Result != OBTAssignResult::IncompatibleKinds;
10728}
10729
10730ASTContext::OBTAssignResult
10731ASTContext::checkOBTAssignmentCompatibility(QualType LHS, QualType RHS) {
10732 const auto *LHSOBT = LHS->getAs<OverflowBehaviorType>();
10733 const auto *RHSOBT = RHS->getAs<OverflowBehaviorType>();
10734
10735 if (!LHSOBT && !RHSOBT)
10736 return OBTAssignResult::Compatible;
10737
10738 if (LHSOBT && RHSOBT) {
10739 if (LHSOBT->getBehaviorKind() != RHSOBT->getBehaviorKind())
10740 return OBTAssignResult::IncompatibleKinds;
10741 return OBTAssignResult::Compatible;
10742 }
10743
10744 QualType LHSUnderlying = LHSOBT ? LHSOBT->desugar() : LHS;
10745 QualType RHSUnderlying = RHSOBT ? RHSOBT->desugar() : RHS;
10746
10747 if (RHSOBT && !LHSOBT) {
10748 if (LHSUnderlying->isIntegerType() && RHSUnderlying->isIntegerType())
10749 return OBTAssignResult::Discards;
10750 }
10751
10752 return OBTAssignResult::NotApplicable;
10753}
10754
10755/// getRVVTypeSize - Return RVV vector register size.
10756static uint64_t getRVVTypeSize(ASTContext &Context, const BuiltinType *Ty) {
10757 assert(Ty->isRVVVLSBuiltinType() && "Invalid RVV Type");
10758 auto VScale = Context.getTargetInfo().getVScaleRange(
10759 LangOpts: Context.getLangOpts(), Mode: TargetInfo::ArmStreamingKind::NotStreaming);
10760 if (!VScale)
10761 return 0;
10762
10763 ASTContext::BuiltinVectorTypeInfo Info = Context.getBuiltinVectorTypeInfo(Ty);
10764
10765 uint64_t EltSize = Context.getTypeSize(T: Info.ElementType);
10766 if (Info.ElementType == Context.BoolTy)
10767 EltSize = 1;
10768
10769 uint64_t MinElts = Info.EC.getKnownMinValue();
10770 return VScale->first * MinElts * EltSize;
10771}
10772
10773bool ASTContext::areCompatibleRVVTypes(QualType FirstType,
10774 QualType SecondType) {
10775 assert(
10776 ((FirstType->isRVVSizelessBuiltinType() && SecondType->isVectorType()) ||
10777 (FirstType->isVectorType() && SecondType->isRVVSizelessBuiltinType())) &&
10778 "Expected RVV builtin type and vector type!");
10779
10780 auto IsValidCast = [this](QualType FirstType, QualType SecondType) {
10781 if (const auto *BT = FirstType->getAs<BuiltinType>()) {
10782 if (const auto *VT = SecondType->getAs<VectorType>()) {
10783 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask) {
10784 BuiltinVectorTypeInfo Info = getBuiltinVectorTypeInfo(Ty: BT);
10785 return FirstType->isRVVVLSBuiltinType() &&
10786 Info.ElementType == BoolTy &&
10787 getTypeSize(T: SecondType) == ((getRVVTypeSize(Context&: *this, Ty: BT)));
10788 }
10789 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_1) {
10790 BuiltinVectorTypeInfo Info = getBuiltinVectorTypeInfo(Ty: BT);
10791 return FirstType->isRVVVLSBuiltinType() &&
10792 Info.ElementType == BoolTy &&
10793 getTypeSize(T: SecondType) == ((getRVVTypeSize(Context&: *this, Ty: BT) * 8));
10794 }
10795 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_2) {
10796 BuiltinVectorTypeInfo Info = getBuiltinVectorTypeInfo(Ty: BT);
10797 return FirstType->isRVVVLSBuiltinType() &&
10798 Info.ElementType == BoolTy &&
10799 getTypeSize(T: SecondType) == ((getRVVTypeSize(Context&: *this, Ty: BT)) * 4);
10800 }
10801 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_4) {
10802 BuiltinVectorTypeInfo Info = getBuiltinVectorTypeInfo(Ty: BT);
10803 return FirstType->isRVVVLSBuiltinType() &&
10804 Info.ElementType == BoolTy &&
10805 getTypeSize(T: SecondType) == ((getRVVTypeSize(Context&: *this, Ty: BT)) * 2);
10806 }
10807 if (VT->getVectorKind() == VectorKind::RVVFixedLengthData ||
10808 VT->getVectorKind() == VectorKind::Generic)
10809 return FirstType->isRVVVLSBuiltinType() &&
10810 getTypeSize(T: SecondType) == getRVVTypeSize(Context&: *this, Ty: BT) &&
10811 hasSameType(T1: VT->getElementType(),
10812 T2: getBuiltinVectorTypeInfo(Ty: BT).ElementType);
10813 }
10814 }
10815 return false;
10816 };
10817
10818 return IsValidCast(FirstType, SecondType) ||
10819 IsValidCast(SecondType, FirstType);
10820}
10821
10822bool ASTContext::areLaxCompatibleRVVTypes(QualType FirstType,
10823 QualType SecondType) {
10824 assert(
10825 ((FirstType->isRVVSizelessBuiltinType() && SecondType->isVectorType()) ||
10826 (FirstType->isVectorType() && SecondType->isRVVSizelessBuiltinType())) &&
10827 "Expected RVV builtin type and vector type!");
10828
10829 auto IsLaxCompatible = [this](QualType FirstType, QualType SecondType) {
10830 const auto *BT = FirstType->getAs<BuiltinType>();
10831 if (!BT)
10832 return false;
10833
10834 if (!BT->isRVVVLSBuiltinType())
10835 return false;
10836
10837 const auto *VecTy = SecondType->getAs<VectorType>();
10838 if (VecTy && VecTy->getVectorKind() == VectorKind::Generic) {
10839 const LangOptions::LaxVectorConversionKind LVCKind =
10840 getLangOpts().getLaxVectorConversions();
10841
10842 // If __riscv_v_fixed_vlen != N do not allow vector lax conversion.
10843 if (getTypeSize(T: SecondType) != getRVVTypeSize(Context&: *this, Ty: BT))
10844 return false;
10845
10846 // If -flax-vector-conversions=all is specified, the types are
10847 // certainly compatible.
10848 if (LVCKind == LangOptions::LaxVectorConversionKind::All)
10849 return true;
10850
10851 // If -flax-vector-conversions=integer is specified, the types are
10852 // compatible if the elements are integer types.
10853 if (LVCKind == LangOptions::LaxVectorConversionKind::Integer)
10854 return VecTy->getElementType().getCanonicalType()->isIntegerType() &&
10855 FirstType->getRVVEltType(Ctx: *this)->isIntegerType();
10856 }
10857
10858 return false;
10859 };
10860
10861 return IsLaxCompatible(FirstType, SecondType) ||
10862 IsLaxCompatible(SecondType, FirstType);
10863}
10864
10865bool ASTContext::hasDirectOwnershipQualifier(QualType Ty) const {
10866 while (true) {
10867 // __strong id
10868 if (const AttributedType *Attr = dyn_cast<AttributedType>(Val&: Ty)) {
10869 if (Attr->getAttrKind() == attr::ObjCOwnership)
10870 return true;
10871
10872 Ty = Attr->getModifiedType();
10873
10874 // X *__strong (...)
10875 } else if (const ParenType *Paren = dyn_cast<ParenType>(Val&: Ty)) {
10876 Ty = Paren->getInnerType();
10877
10878 // We do not want to look through typedefs, typeof(expr),
10879 // typeof(type), or any other way that the type is somehow
10880 // abstracted.
10881 } else {
10882 return false;
10883 }
10884 }
10885}
10886
10887//===----------------------------------------------------------------------===//
10888// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
10889//===----------------------------------------------------------------------===//
10890
10891/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
10892/// inheritance hierarchy of 'rProto'.
10893bool
10894ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
10895 ObjCProtocolDecl *rProto) const {
10896 if (declaresSameEntity(D1: lProto, D2: rProto))
10897 return true;
10898 for (auto *PI : rProto->protocols())
10899 if (ProtocolCompatibleWithProtocol(lProto, rProto: PI))
10900 return true;
10901 return false;
10902}
10903
10904/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
10905/// Class<pr1, ...>.
10906bool ASTContext::ObjCQualifiedClassTypesAreCompatible(
10907 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs) {
10908 for (auto *lhsProto : lhs->quals()) {
10909 bool match = false;
10910 for (auto *rhsProto : rhs->quals()) {
10911 if (ProtocolCompatibleWithProtocol(lProto: lhsProto, rProto: rhsProto)) {
10912 match = true;
10913 break;
10914 }
10915 }
10916 if (!match)
10917 return false;
10918 }
10919 return true;
10920}
10921
10922/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
10923/// ObjCQualifiedIDType.
10924bool ASTContext::ObjCQualifiedIdTypesAreCompatible(
10925 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs,
10926 bool compare) {
10927 // Allow id<P..> and an 'id' in all cases.
10928 if (lhs->isObjCIdType() || rhs->isObjCIdType())
10929 return true;
10930
10931 // Don't allow id<P..> to convert to Class or Class<P..> in either direction.
10932 if (lhs->isObjCClassType() || lhs->isObjCQualifiedClassType() ||
10933 rhs->isObjCClassType() || rhs->isObjCQualifiedClassType())
10934 return false;
10935
10936 if (lhs->isObjCQualifiedIdType()) {
10937 if (rhs->qual_empty()) {
10938 // If the RHS is a unqualified interface pointer "NSString*",
10939 // make sure we check the class hierarchy.
10940 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
10941 for (auto *I : lhs->quals()) {
10942 // when comparing an id<P> on lhs with a static type on rhs,
10943 // see if static class implements all of id's protocols, directly or
10944 // through its super class and categories.
10945 if (!rhsID->ClassImplementsProtocol(lProto: I, lookupCategory: true))
10946 return false;
10947 }
10948 }
10949 // If there are no qualifiers and no interface, we have an 'id'.
10950 return true;
10951 }
10952 // Both the right and left sides have qualifiers.
10953 for (auto *lhsProto : lhs->quals()) {
10954 bool match = false;
10955
10956 // when comparing an id<P> on lhs with a static type on rhs,
10957 // see if static class implements all of id's protocols, directly or
10958 // through its super class and categories.
10959 for (auto *rhsProto : rhs->quals()) {
10960 if (ProtocolCompatibleWithProtocol(lProto: lhsProto, rProto: rhsProto) ||
10961 (compare && ProtocolCompatibleWithProtocol(lProto: rhsProto, rProto: lhsProto))) {
10962 match = true;
10963 break;
10964 }
10965 }
10966 // If the RHS is a qualified interface pointer "NSString<P>*",
10967 // make sure we check the class hierarchy.
10968 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
10969 for (auto *I : lhs->quals()) {
10970 // when comparing an id<P> on lhs with a static type on rhs,
10971 // see if static class implements all of id's protocols, directly or
10972 // through its super class and categories.
10973 if (rhsID->ClassImplementsProtocol(lProto: I, lookupCategory: true)) {
10974 match = true;
10975 break;
10976 }
10977 }
10978 }
10979 if (!match)
10980 return false;
10981 }
10982
10983 return true;
10984 }
10985
10986 assert(rhs->isObjCQualifiedIdType() && "One of the LHS/RHS should be id<x>");
10987
10988 if (lhs->getInterfaceType()) {
10989 // If both the right and left sides have qualifiers.
10990 for (auto *lhsProto : lhs->quals()) {
10991 bool match = false;
10992
10993 // when comparing an id<P> on rhs with a static type on lhs,
10994 // see if static class implements all of id's protocols, directly or
10995 // through its super class and categories.
10996 // First, lhs protocols in the qualifier list must be found, direct
10997 // or indirect in rhs's qualifier list or it is a mismatch.
10998 for (auto *rhsProto : rhs->quals()) {
10999 if (ProtocolCompatibleWithProtocol(lProto: lhsProto, rProto: rhsProto) ||
11000 (compare && ProtocolCompatibleWithProtocol(lProto: rhsProto, rProto: lhsProto))) {
11001 match = true;
11002 break;
11003 }
11004 }
11005 if (!match)
11006 return false;
11007 }
11008
11009 // Static class's protocols, or its super class or category protocols
11010 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
11011 if (ObjCInterfaceDecl *lhsID = lhs->getInterfaceDecl()) {
11012 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
11013 CollectInheritedProtocols(CDecl: lhsID, Protocols&: LHSInheritedProtocols);
11014 // This is rather dubious but matches gcc's behavior. If lhs has
11015 // no type qualifier and its class has no static protocol(s)
11016 // assume that it is mismatch.
11017 if (LHSInheritedProtocols.empty() && lhs->qual_empty())
11018 return false;
11019 for (auto *lhsProto : LHSInheritedProtocols) {
11020 bool match = false;
11021 for (auto *rhsProto : rhs->quals()) {
11022 if (ProtocolCompatibleWithProtocol(lProto: lhsProto, rProto: rhsProto) ||
11023 (compare && ProtocolCompatibleWithProtocol(lProto: rhsProto, rProto: lhsProto))) {
11024 match = true;
11025 break;
11026 }
11027 }
11028 if (!match)
11029 return false;
11030 }
11031 }
11032 return true;
11033 }
11034 return false;
11035}
11036
11037/// canAssignObjCInterfaces - Return true if the two interface types are
11038/// compatible for assignment from RHS to LHS. This handles validation of any
11039/// protocol qualifiers on the LHS or RHS.
11040bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
11041 const ObjCObjectPointerType *RHSOPT) {
11042 const ObjCObjectType* LHS = LHSOPT->getObjectType();
11043 const ObjCObjectType* RHS = RHSOPT->getObjectType();
11044
11045 // If either type represents the built-in 'id' type, return true.
11046 if (LHS->isObjCUnqualifiedId() || RHS->isObjCUnqualifiedId())
11047 return true;
11048
11049 // Function object that propagates a successful result or handles
11050 // __kindof types.
11051 auto finish = [&](bool succeeded) -> bool {
11052 if (succeeded)
11053 return true;
11054
11055 if (!RHS->isKindOfType())
11056 return false;
11057
11058 // Strip off __kindof and protocol qualifiers, then check whether
11059 // we can assign the other way.
11060 return canAssignObjCInterfaces(LHSOPT: RHSOPT->stripObjCKindOfTypeAndQuals(ctx: *this),
11061 RHSOPT: LHSOPT->stripObjCKindOfTypeAndQuals(ctx: *this));
11062 };
11063
11064 // Casts from or to id<P> are allowed when the other side has compatible
11065 // protocols.
11066 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
11067 return finish(ObjCQualifiedIdTypesAreCompatible(lhs: LHSOPT, rhs: RHSOPT, compare: false));
11068 }
11069
11070 // Verify protocol compatibility for casts from Class<P1> to Class<P2>.
11071 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
11072 return finish(ObjCQualifiedClassTypesAreCompatible(lhs: LHSOPT, rhs: RHSOPT));
11073 }
11074
11075 // Casts from Class to Class<Foo>, or vice-versa, are allowed.
11076 if (LHS->isObjCClass() && RHS->isObjCClass()) {
11077 return true;
11078 }
11079
11080 // If we have 2 user-defined types, fall into that path.
11081 if (LHS->getInterface() && RHS->getInterface()) {
11082 return finish(canAssignObjCInterfaces(LHS, RHS));
11083 }
11084
11085 return false;
11086}
11087
11088/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
11089/// for providing type-safety for objective-c pointers used to pass/return
11090/// arguments in block literals. When passed as arguments, passing 'A*' where
11091/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
11092/// not OK. For the return type, the opposite is not OK.
11093bool ASTContext::canAssignObjCInterfacesInBlockPointer(
11094 const ObjCObjectPointerType *LHSOPT,
11095 const ObjCObjectPointerType *RHSOPT,
11096 bool BlockReturnType) {
11097
11098 // Function object that propagates a successful result or handles
11099 // __kindof types.
11100 auto finish = [&](bool succeeded) -> bool {
11101 if (succeeded)
11102 return true;
11103
11104 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
11105 if (!Expected->isKindOfType())
11106 return false;
11107
11108 // Strip off __kindof and protocol qualifiers, then check whether
11109 // we can assign the other way.
11110 return canAssignObjCInterfacesInBlockPointer(
11111 LHSOPT: RHSOPT->stripObjCKindOfTypeAndQuals(ctx: *this),
11112 RHSOPT: LHSOPT->stripObjCKindOfTypeAndQuals(ctx: *this),
11113 BlockReturnType);
11114 };
11115
11116 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
11117 return true;
11118
11119 if (LHSOPT->isObjCBuiltinType()) {
11120 return finish(RHSOPT->isObjCBuiltinType() ||
11121 RHSOPT->isObjCQualifiedIdType());
11122 }
11123
11124 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) {
11125 if (getLangOpts().CompatibilityQualifiedIdBlockParamTypeChecking)
11126 // Use for block parameters previous type checking for compatibility.
11127 return finish(ObjCQualifiedIdTypesAreCompatible(lhs: LHSOPT, rhs: RHSOPT, compare: false) ||
11128 // Or corrected type checking as in non-compat mode.
11129 (!BlockReturnType &&
11130 ObjCQualifiedIdTypesAreCompatible(lhs: RHSOPT, rhs: LHSOPT, compare: false)));
11131 else
11132 return finish(ObjCQualifiedIdTypesAreCompatible(
11133 lhs: (BlockReturnType ? LHSOPT : RHSOPT),
11134 rhs: (BlockReturnType ? RHSOPT : LHSOPT), compare: false));
11135 }
11136
11137 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
11138 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
11139 if (LHS && RHS) { // We have 2 user-defined types.
11140 if (LHS != RHS) {
11141 if (LHS->getDecl()->isSuperClassOf(I: RHS->getDecl()))
11142 return finish(BlockReturnType);
11143 if (RHS->getDecl()->isSuperClassOf(I: LHS->getDecl()))
11144 return finish(!BlockReturnType);
11145 }
11146 else
11147 return true;
11148 }
11149 return false;
11150}
11151
11152/// Comparison routine for Objective-C protocols to be used with
11153/// llvm::array_pod_sort.
11154static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
11155 ObjCProtocolDecl * const *rhs) {
11156 return (*lhs)->getName().compare(RHS: (*rhs)->getName());
11157}
11158
11159/// getIntersectionOfProtocols - This routine finds the intersection of set
11160/// of protocols inherited from two distinct objective-c pointer objects with
11161/// the given common base.
11162/// It is used to build composite qualifier list of the composite type of
11163/// the conditional expression involving two objective-c pointer objects.
11164static
11165void getIntersectionOfProtocols(ASTContext &Context,
11166 const ObjCInterfaceDecl *CommonBase,
11167 const ObjCObjectPointerType *LHSOPT,
11168 const ObjCObjectPointerType *RHSOPT,
11169 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
11170
11171 const ObjCObjectType* LHS = LHSOPT->getObjectType();
11172 const ObjCObjectType* RHS = RHSOPT->getObjectType();
11173 assert(LHS->getInterface() && "LHS must have an interface base");
11174 assert(RHS->getInterface() && "RHS must have an interface base");
11175
11176 // Add all of the protocols for the LHS.
11177 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
11178
11179 // Start with the protocol qualifiers.
11180 for (auto *proto : LHS->quals()) {
11181 Context.CollectInheritedProtocols(CDecl: proto, Protocols&: LHSProtocolSet);
11182 }
11183
11184 // Also add the protocols associated with the LHS interface.
11185 Context.CollectInheritedProtocols(CDecl: LHS->getInterface(), Protocols&: LHSProtocolSet);
11186
11187 // Add all of the protocols for the RHS.
11188 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
11189
11190 // Start with the protocol qualifiers.
11191 for (auto *proto : RHS->quals()) {
11192 Context.CollectInheritedProtocols(CDecl: proto, Protocols&: RHSProtocolSet);
11193 }
11194
11195 // Also add the protocols associated with the RHS interface.
11196 Context.CollectInheritedProtocols(CDecl: RHS->getInterface(), Protocols&: RHSProtocolSet);
11197
11198 // Compute the intersection of the collected protocol sets.
11199 for (auto *proto : LHSProtocolSet) {
11200 if (RHSProtocolSet.count(Ptr: proto))
11201 IntersectionSet.push_back(Elt: proto);
11202 }
11203
11204 // Compute the set of protocols that is implied by either the common type or
11205 // the protocols within the intersection.
11206 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
11207 Context.CollectInheritedProtocols(CDecl: CommonBase, Protocols&: ImpliedProtocols);
11208
11209 // Remove any implied protocols from the list of inherited protocols.
11210 if (!ImpliedProtocols.empty()) {
11211 llvm::erase_if(C&: IntersectionSet, P: [&](ObjCProtocolDecl *proto) -> bool {
11212 return ImpliedProtocols.contains(Ptr: proto);
11213 });
11214 }
11215
11216 // Sort the remaining protocols by name.
11217 llvm::array_pod_sort(Start: IntersectionSet.begin(), End: IntersectionSet.end(),
11218 Compare: compareObjCProtocolsByName);
11219}
11220
11221/// Determine whether the first type is a subtype of the second.
11222static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
11223 QualType rhs) {
11224 // Common case: two object pointers.
11225 const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
11226 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
11227 if (lhsOPT && rhsOPT)
11228 return ctx.canAssignObjCInterfaces(LHSOPT: lhsOPT, RHSOPT: rhsOPT);
11229
11230 // Two block pointers.
11231 const auto *lhsBlock = lhs->getAs<BlockPointerType>();
11232 const auto *rhsBlock = rhs->getAs<BlockPointerType>();
11233 if (lhsBlock && rhsBlock)
11234 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
11235
11236 // If either is an unqualified 'id' and the other is a block, it's
11237 // acceptable.
11238 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
11239 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
11240 return true;
11241
11242 return false;
11243}
11244
11245// Check that the given Objective-C type argument lists are equivalent.
11246static bool sameObjCTypeArgs(ASTContext &ctx,
11247 const ObjCInterfaceDecl *iface,
11248 ArrayRef<QualType> lhsArgs,
11249 ArrayRef<QualType> rhsArgs,
11250 bool stripKindOf) {
11251 if (lhsArgs.size() != rhsArgs.size())
11252 return false;
11253
11254 ObjCTypeParamList *typeParams = iface->getTypeParamList();
11255 if (!typeParams)
11256 return false;
11257
11258 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
11259 if (ctx.hasSameType(T1: lhsArgs[i], T2: rhsArgs[i]))
11260 continue;
11261
11262 switch (typeParams->begin()[i]->getVariance()) {
11263 case ObjCTypeParamVariance::Invariant:
11264 if (!stripKindOf ||
11265 !ctx.hasSameType(T1: lhsArgs[i].stripObjCKindOfType(ctx),
11266 T2: rhsArgs[i].stripObjCKindOfType(ctx))) {
11267 return false;
11268 }
11269 break;
11270
11271 case ObjCTypeParamVariance::Covariant:
11272 if (!canAssignObjCObjectTypes(ctx, lhs: lhsArgs[i], rhs: rhsArgs[i]))
11273 return false;
11274 break;
11275
11276 case ObjCTypeParamVariance::Contravariant:
11277 if (!canAssignObjCObjectTypes(ctx, lhs: rhsArgs[i], rhs: lhsArgs[i]))
11278 return false;
11279 break;
11280 }
11281 }
11282
11283 return true;
11284}
11285
11286QualType ASTContext::areCommonBaseCompatible(
11287 const ObjCObjectPointerType *Lptr,
11288 const ObjCObjectPointerType *Rptr) {
11289 const ObjCObjectType *LHS = Lptr->getObjectType();
11290 const ObjCObjectType *RHS = Rptr->getObjectType();
11291 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
11292 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
11293
11294 if (!LDecl || !RDecl)
11295 return {};
11296
11297 // When either LHS or RHS is a kindof type, we should return a kindof type.
11298 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
11299 // kindof(A).
11300 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
11301
11302 // Follow the left-hand side up the class hierarchy until we either hit a
11303 // root or find the RHS. Record the ancestors in case we don't find it.
11304 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
11305 LHSAncestors;
11306 while (true) {
11307 // Record this ancestor. We'll need this if the common type isn't in the
11308 // path from the LHS to the root.
11309 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
11310
11311 if (declaresSameEntity(D1: LHS->getInterface(), D2: RDecl)) {
11312 // Get the type arguments.
11313 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
11314 bool anyChanges = false;
11315 if (LHS->isSpecialized() && RHS->isSpecialized()) {
11316 // Both have type arguments, compare them.
11317 if (!sameObjCTypeArgs(ctx&: *this, iface: LHS->getInterface(),
11318 lhsArgs: LHS->getTypeArgs(), rhsArgs: RHS->getTypeArgs(),
11319 /*stripKindOf=*/true))
11320 return {};
11321 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
11322 // If only one has type arguments, the result will not have type
11323 // arguments.
11324 LHSTypeArgs = {};
11325 anyChanges = true;
11326 }
11327
11328 // Compute the intersection of protocols.
11329 SmallVector<ObjCProtocolDecl *, 8> Protocols;
11330 getIntersectionOfProtocols(Context&: *this, CommonBase: LHS->getInterface(), LHSOPT: Lptr, RHSOPT: Rptr,
11331 IntersectionSet&: Protocols);
11332 if (!Protocols.empty())
11333 anyChanges = true;
11334
11335 // If anything in the LHS will have changed, build a new result type.
11336 // If we need to return a kindof type but LHS is not a kindof type, we
11337 // build a new result type.
11338 if (anyChanges || LHS->isKindOfType() != anyKindOf) {
11339 QualType Result = getObjCInterfaceType(Decl: LHS->getInterface());
11340 Result = getObjCObjectType(baseType: Result, typeArgs: LHSTypeArgs, protocols: Protocols,
11341 isKindOf: anyKindOf || LHS->isKindOfType());
11342 return getObjCObjectPointerType(ObjectT: Result);
11343 }
11344
11345 return getObjCObjectPointerType(ObjectT: QualType(LHS, 0));
11346 }
11347
11348 // Find the superclass.
11349 QualType LHSSuperType = LHS->getSuperClassType();
11350 if (LHSSuperType.isNull())
11351 break;
11352
11353 LHS = LHSSuperType->castAs<ObjCObjectType>();
11354 }
11355
11356 // We didn't find anything by following the LHS to its root; now check
11357 // the RHS against the cached set of ancestors.
11358 while (true) {
11359 auto KnownLHS = LHSAncestors.find(Val: RHS->getInterface()->getCanonicalDecl());
11360 if (KnownLHS != LHSAncestors.end()) {
11361 LHS = KnownLHS->second;
11362
11363 // Get the type arguments.
11364 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
11365 bool anyChanges = false;
11366 if (LHS->isSpecialized() && RHS->isSpecialized()) {
11367 // Both have type arguments, compare them.
11368 if (!sameObjCTypeArgs(ctx&: *this, iface: LHS->getInterface(),
11369 lhsArgs: LHS->getTypeArgs(), rhsArgs: RHS->getTypeArgs(),
11370 /*stripKindOf=*/true))
11371 return {};
11372 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
11373 // If only one has type arguments, the result will not have type
11374 // arguments.
11375 RHSTypeArgs = {};
11376 anyChanges = true;
11377 }
11378
11379 // Compute the intersection of protocols.
11380 SmallVector<ObjCProtocolDecl *, 8> Protocols;
11381 getIntersectionOfProtocols(Context&: *this, CommonBase: RHS->getInterface(), LHSOPT: Lptr, RHSOPT: Rptr,
11382 IntersectionSet&: Protocols);
11383 if (!Protocols.empty())
11384 anyChanges = true;
11385
11386 // If we need to return a kindof type but RHS is not a kindof type, we
11387 // build a new result type.
11388 if (anyChanges || RHS->isKindOfType() != anyKindOf) {
11389 QualType Result = getObjCInterfaceType(Decl: RHS->getInterface());
11390 Result = getObjCObjectType(baseType: Result, typeArgs: RHSTypeArgs, protocols: Protocols,
11391 isKindOf: anyKindOf || RHS->isKindOfType());
11392 return getObjCObjectPointerType(ObjectT: Result);
11393 }
11394
11395 return getObjCObjectPointerType(ObjectT: QualType(RHS, 0));
11396 }
11397
11398 // Find the superclass of the RHS.
11399 QualType RHSSuperType = RHS->getSuperClassType();
11400 if (RHSSuperType.isNull())
11401 break;
11402
11403 RHS = RHSSuperType->castAs<ObjCObjectType>();
11404 }
11405
11406 return {};
11407}
11408
11409bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
11410 const ObjCObjectType *RHS) {
11411 assert(LHS->getInterface() && "LHS is not an interface type");
11412 assert(RHS->getInterface() && "RHS is not an interface type");
11413
11414 // Verify that the base decls are compatible: the RHS must be a subclass of
11415 // the LHS.
11416 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
11417 bool IsSuperClass = LHSInterface->isSuperClassOf(I: RHS->getInterface());
11418 if (!IsSuperClass)
11419 return false;
11420
11421 // If the LHS has protocol qualifiers, determine whether all of them are
11422 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
11423 // LHS).
11424 if (LHS->getNumProtocols() > 0) {
11425 // OK if conversion of LHS to SuperClass results in narrowing of types
11426 // ; i.e., SuperClass may implement at least one of the protocols
11427 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
11428 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
11429 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
11430 CollectInheritedProtocols(CDecl: RHS->getInterface(), Protocols&: SuperClassInheritedProtocols);
11431 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
11432 // qualifiers.
11433 for (auto *RHSPI : RHS->quals())
11434 CollectInheritedProtocols(CDecl: RHSPI, Protocols&: SuperClassInheritedProtocols);
11435 // If there is no protocols associated with RHS, it is not a match.
11436 if (SuperClassInheritedProtocols.empty())
11437 return false;
11438
11439 for (const auto *LHSProto : LHS->quals()) {
11440 bool SuperImplementsProtocol = false;
11441 for (auto *SuperClassProto : SuperClassInheritedProtocols)
11442 if (SuperClassProto->lookupProtocolNamed(PName: LHSProto->getIdentifier())) {
11443 SuperImplementsProtocol = true;
11444 break;
11445 }
11446 if (!SuperImplementsProtocol)
11447 return false;
11448 }
11449 }
11450
11451 // If the LHS is specialized, we may need to check type arguments.
11452 if (LHS->isSpecialized()) {
11453 // Follow the superclass chain until we've matched the LHS class in the
11454 // hierarchy. This substitutes type arguments through.
11455 const ObjCObjectType *RHSSuper = RHS;
11456 while (!declaresSameEntity(D1: RHSSuper->getInterface(), D2: LHSInterface))
11457 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
11458
11459 // If the RHS is specializd, compare type arguments.
11460 if (RHSSuper->isSpecialized() &&
11461 !sameObjCTypeArgs(ctx&: *this, iface: LHS->getInterface(),
11462 lhsArgs: LHS->getTypeArgs(), rhsArgs: RHSSuper->getTypeArgs(),
11463 /*stripKindOf=*/true)) {
11464 return false;
11465 }
11466 }
11467
11468 return true;
11469}
11470
11471bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
11472 // get the "pointed to" types
11473 const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
11474 const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
11475
11476 if (!LHSOPT || !RHSOPT)
11477 return false;
11478
11479 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
11480 canAssignObjCInterfaces(LHSOPT: RHSOPT, RHSOPT: LHSOPT);
11481}
11482
11483bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
11484 return canAssignObjCInterfaces(
11485 LHSOPT: getObjCObjectPointerType(ObjectT: To)->castAs<ObjCObjectPointerType>(),
11486 RHSOPT: getObjCObjectPointerType(ObjectT: From)->castAs<ObjCObjectPointerType>());
11487}
11488
11489/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
11490/// both shall have the identically qualified version of a compatible type.
11491/// C99 6.2.7p1: Two types have compatible types if their types are the
11492/// same. See 6.7.[2,3,5] for additional rules.
11493bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
11494 bool CompareUnqualified) {
11495 if (getLangOpts().CPlusPlus)
11496 return hasSameType(T1: LHS, T2: RHS);
11497
11498 return !mergeTypes(LHS, RHS, OfBlockPointer: false, Unqualified: CompareUnqualified).isNull();
11499}
11500
11501bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
11502 return typesAreCompatible(LHS, RHS);
11503}
11504
11505bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
11506 return !mergeTypes(LHS, RHS, OfBlockPointer: true).isNull();
11507}
11508
11509/// mergeTransparentUnionType - if T is a transparent union type and a member
11510/// of T is compatible with SubType, return the merged type, else return
11511/// QualType()
11512QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
11513 bool OfBlockPointer,
11514 bool Unqualified) {
11515 if (const RecordType *UT = T->getAsUnionType()) {
11516 RecordDecl *UD = UT->getDecl()->getMostRecentDecl();
11517 if (UD->hasAttr<TransparentUnionAttr>()) {
11518 for (const auto *I : UD->fields()) {
11519 QualType ET = I->getType().getUnqualifiedType();
11520 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
11521 if (!MT.isNull())
11522 return MT;
11523 }
11524 }
11525 }
11526
11527 return {};
11528}
11529
11530/// mergeFunctionParameterTypes - merge two types which appear as function
11531/// parameter types
11532QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
11533 bool OfBlockPointer,
11534 bool Unqualified) {
11535 // GNU extension: two types are compatible if they appear as a function
11536 // argument, one of the types is a transparent union type and the other
11537 // type is compatible with a union member
11538 QualType lmerge = mergeTransparentUnionType(T: lhs, SubType: rhs, OfBlockPointer,
11539 Unqualified);
11540 if (!lmerge.isNull())
11541 return lmerge;
11542
11543 QualType rmerge = mergeTransparentUnionType(T: rhs, SubType: lhs, OfBlockPointer,
11544 Unqualified);
11545 if (!rmerge.isNull())
11546 return rmerge;
11547
11548 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
11549}
11550
11551QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
11552 bool OfBlockPointer, bool Unqualified,
11553 bool AllowCXX,
11554 bool IsConditionalOperator) {
11555 const auto *lbase = lhs->castAs<FunctionType>();
11556 const auto *rbase = rhs->castAs<FunctionType>();
11557 const auto *lproto = dyn_cast<FunctionProtoType>(Val: lbase);
11558 const auto *rproto = dyn_cast<FunctionProtoType>(Val: rbase);
11559 bool allLTypes = true;
11560 bool allRTypes = true;
11561
11562 // Check return type
11563 QualType retType;
11564 if (OfBlockPointer) {
11565 QualType RHS = rbase->getReturnType();
11566 QualType LHS = lbase->getReturnType();
11567 bool UnqualifiedResult = Unqualified;
11568 if (!UnqualifiedResult)
11569 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
11570 retType = mergeTypes(LHS, RHS, OfBlockPointer: true, Unqualified: UnqualifiedResult, BlockReturnType: true);
11571 }
11572 else
11573 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), OfBlockPointer: false,
11574 Unqualified);
11575 if (retType.isNull())
11576 return {};
11577
11578 if (Unqualified)
11579 retType = retType.getUnqualifiedType();
11580
11581 CanQualType LRetType = getCanonicalType(T: lbase->getReturnType());
11582 CanQualType RRetType = getCanonicalType(T: rbase->getReturnType());
11583 if (Unqualified) {
11584 LRetType = LRetType.getUnqualifiedType();
11585 RRetType = RRetType.getUnqualifiedType();
11586 }
11587
11588 if (getCanonicalType(T: retType) != LRetType)
11589 allLTypes = false;
11590 if (getCanonicalType(T: retType) != RRetType)
11591 allRTypes = false;
11592
11593 // FIXME: double check this
11594 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
11595 // rbase->getRegParmAttr() != 0 &&
11596 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
11597 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
11598 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
11599
11600 // Compatible functions must have compatible calling conventions
11601 if (lbaseInfo.getCC() != rbaseInfo.getCC())
11602 return {};
11603
11604 // Regparm is part of the calling convention.
11605 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
11606 return {};
11607 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
11608 return {};
11609
11610 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
11611 return {};
11612 if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs())
11613 return {};
11614 if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck())
11615 return {};
11616
11617 // When merging declarations, it's common for supplemental information like
11618 // attributes to only be present in one of the declarations, and we generally
11619 // want type merging to preserve the union of information. So a merged
11620 // function type should be noreturn if it was noreturn in *either* operand
11621 // type.
11622 //
11623 // But for the conditional operator, this is backwards. The result of the
11624 // operator could be either operand, and its type should conservatively
11625 // reflect that. So a function type in a composite type is noreturn only
11626 // if it's noreturn in *both* operand types.
11627 //
11628 // Arguably, noreturn is a kind of subtype, and the conditional operator
11629 // ought to produce the most specific common supertype of its operand types.
11630 // That would differ from this rule in contravariant positions. However,
11631 // neither C nor C++ generally uses this kind of subtype reasoning. Also,
11632 // as a practical matter, it would only affect C code that does abstraction of
11633 // higher-order functions (taking noreturn callbacks!), which is uncommon to
11634 // say the least. So we use the simpler rule.
11635 bool NoReturn = IsConditionalOperator
11636 ? lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn()
11637 : lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
11638 if (lbaseInfo.getNoReturn() != NoReturn)
11639 allLTypes = false;
11640 if (rbaseInfo.getNoReturn() != NoReturn)
11641 allRTypes = false;
11642
11643 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(noReturn: NoReturn);
11644
11645 std::optional<FunctionEffectSet> MergedFX;
11646
11647 if (lproto && rproto) { // two C99 style function prototypes
11648 assert((AllowCXX ||
11649 (!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec())) &&
11650 "C++ shouldn't be here");
11651 // Compatible functions must have the same number of parameters
11652 if (lproto->getNumParams() != rproto->getNumParams())
11653 return {};
11654
11655 // Variadic and non-variadic functions aren't compatible
11656 if (lproto->isVariadic() != rproto->isVariadic())
11657 return {};
11658
11659 if (lproto->getMethodQuals() != rproto->getMethodQuals())
11660 return {};
11661
11662 // Function protos with different 'cfi_salt' values aren't compatible.
11663 if (lproto->getExtraAttributeInfo().CFISalt !=
11664 rproto->getExtraAttributeInfo().CFISalt)
11665 return {};
11666
11667 // Function effects are handled similarly to noreturn, see above.
11668 FunctionEffectsRef LHSFX = lproto->getFunctionEffects();
11669 FunctionEffectsRef RHSFX = rproto->getFunctionEffects();
11670 if (LHSFX != RHSFX) {
11671 if (IsConditionalOperator)
11672 MergedFX = FunctionEffectSet::getIntersection(LHS: LHSFX, RHS: RHSFX);
11673 else {
11674 FunctionEffectSet::Conflicts Errs;
11675 MergedFX = FunctionEffectSet::getUnion(LHS: LHSFX, RHS: RHSFX, Errs);
11676 // Here we're discarding a possible error due to conflicts in the effect
11677 // sets. But we're not in a context where we can report it. The
11678 // operation does however guarantee maintenance of invariants.
11679 }
11680 if (*MergedFX != LHSFX)
11681 allLTypes = false;
11682 if (*MergedFX != RHSFX)
11683 allRTypes = false;
11684 }
11685
11686 SmallVector<FunctionProtoType::ExtParameterInfo, 4> newParamInfos;
11687 bool canUseLeft, canUseRight;
11688 if (!mergeExtParameterInfo(FirstFnType: lproto, SecondFnType: rproto, CanUseFirst&: canUseLeft, CanUseSecond&: canUseRight,
11689 NewParamInfos&: newParamInfos))
11690 return {};
11691
11692 if (!canUseLeft)
11693 allLTypes = false;
11694 if (!canUseRight)
11695 allRTypes = false;
11696
11697 // Check parameter type compatibility
11698 SmallVector<QualType, 10> types;
11699 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
11700 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
11701 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
11702 QualType paramType = mergeFunctionParameterTypes(
11703 lhs: lParamType, rhs: rParamType, OfBlockPointer, Unqualified);
11704 if (paramType.isNull())
11705 return {};
11706
11707 if (Unqualified)
11708 paramType = paramType.getUnqualifiedType();
11709
11710 types.push_back(Elt: paramType);
11711 if (Unqualified) {
11712 lParamType = lParamType.getUnqualifiedType();
11713 rParamType = rParamType.getUnqualifiedType();
11714 }
11715
11716 if (getCanonicalType(T: paramType) != getCanonicalType(T: lParamType))
11717 allLTypes = false;
11718 if (getCanonicalType(T: paramType) != getCanonicalType(T: rParamType))
11719 allRTypes = false;
11720 }
11721
11722 if (allLTypes) return lhs;
11723 if (allRTypes) return rhs;
11724
11725 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
11726 EPI.ExtInfo = einfo;
11727 EPI.ExtParameterInfos =
11728 newParamInfos.empty() ? nullptr : newParamInfos.data();
11729 if (MergedFX)
11730 EPI.FunctionEffects = *MergedFX;
11731 return getFunctionType(ResultTy: retType, Args: types, EPI);
11732 }
11733
11734 if (lproto) allRTypes = false;
11735 if (rproto) allLTypes = false;
11736
11737 const FunctionProtoType *proto = lproto ? lproto : rproto;
11738 if (proto) {
11739 assert((AllowCXX || !proto->hasExceptionSpec()) && "C++ shouldn't be here");
11740 if (proto->isVariadic())
11741 return {};
11742 // Check that the types are compatible with the types that
11743 // would result from default argument promotions (C99 6.7.5.3p15).
11744 // The only types actually affected are promotable integer
11745 // types and floats, which would be passed as a different
11746 // type depending on whether the prototype is visible.
11747 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
11748 QualType paramTy = proto->getParamType(i);
11749
11750 // Look at the converted type of enum types, since that is the type used
11751 // to pass enum values.
11752 if (const auto *ED = paramTy->getAsEnumDecl()) {
11753 paramTy = ED->getIntegerType();
11754 if (paramTy.isNull())
11755 return {};
11756 }
11757
11758 if (isPromotableIntegerType(T: paramTy) ||
11759 getCanonicalType(T: paramTy).getUnqualifiedType() == FloatTy)
11760 return {};
11761 }
11762
11763 if (allLTypes) return lhs;
11764 if (allRTypes) return rhs;
11765
11766 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
11767 EPI.ExtInfo = einfo;
11768 if (MergedFX)
11769 EPI.FunctionEffects = *MergedFX;
11770 return getFunctionType(ResultTy: retType, Args: proto->getParamTypes(), EPI);
11771 }
11772
11773 if (allLTypes) return lhs;
11774 if (allRTypes) return rhs;
11775 return getFunctionNoProtoType(ResultTy: retType, Info: einfo);
11776}
11777
11778/// Given that we have an enum type and a non-enum type, try to merge them.
11779static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
11780 QualType other, bool isBlockReturnType) {
11781 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
11782 // a signed integer type, or an unsigned integer type.
11783 // Compatibility is based on the underlying type, not the promotion
11784 // type.
11785 QualType underlyingType =
11786 ET->getDecl()->getDefinitionOrSelf()->getIntegerType();
11787 if (underlyingType.isNull())
11788 return {};
11789 if (Context.hasSameType(T1: underlyingType, T2: other))
11790 return other;
11791
11792 // In block return types, we're more permissive and accept any
11793 // integral type of the same size.
11794 if (isBlockReturnType && other->isIntegerType() &&
11795 Context.getTypeSize(T: underlyingType) == Context.getTypeSize(T: other))
11796 return other;
11797
11798 return {};
11799}
11800
11801QualType ASTContext::mergeTagDefinitions(QualType LHS, QualType RHS) {
11802 // C17 and earlier and C++ disallow two tag definitions within the same TU
11803 // from being compatible.
11804 if (LangOpts.CPlusPlus || !LangOpts.C23)
11805 return {};
11806
11807 // Nameless tags are comparable only within outer definitions. At the top
11808 // level they are not comparable.
11809 const TagDecl *LTagD = LHS->castAsTagDecl(), *RTagD = RHS->castAsTagDecl();
11810 if (!LTagD->getIdentifier() || !RTagD->getIdentifier())
11811 return {};
11812
11813 // C23, on the other hand, requires the members to be "the same enough", so
11814 // we use a structural equivalence check.
11815 StructuralEquivalenceContext::NonEquivalentDeclSet NonEquivalentDecls;
11816 StructuralEquivalenceContext Ctx(
11817 getLangOpts(), *this, *this, NonEquivalentDecls,
11818 StructuralEquivalenceKind::Default, /*StrictTypeSpelling=*/false,
11819 /*Complain=*/false, /*ErrorOnTagTypeMismatch=*/true);
11820 return Ctx.IsEquivalent(T1: LHS, T2: RHS) ? LHS : QualType{};
11821}
11822
11823std::optional<QualType> ASTContext::tryMergeOverflowBehaviorTypes(
11824 QualType LHS, QualType RHS, bool OfBlockPointer, bool Unqualified,
11825 bool BlockReturnType, bool IsConditionalOperator) {
11826 const auto *LHSOBT = LHS->getAs<OverflowBehaviorType>();
11827 const auto *RHSOBT = RHS->getAs<OverflowBehaviorType>();
11828
11829 if (!LHSOBT && !RHSOBT)
11830 return std::nullopt;
11831
11832 if (LHSOBT) {
11833 if (RHSOBT) {
11834 if (LHSOBT->getBehaviorKind() != RHSOBT->getBehaviorKind())
11835 return QualType();
11836
11837 QualType MergedUnderlying = mergeTypes(
11838 LHSOBT->getUnderlyingType(), RHSOBT->getUnderlyingType(),
11839 OfBlockPointer, Unqualified, BlockReturnType, IsConditionalOperator);
11840
11841 if (MergedUnderlying.isNull())
11842 return QualType();
11843
11844 if (getCanonicalType(T: LHSOBT) == getCanonicalType(T: RHSOBT)) {
11845 if (LHSOBT->getUnderlyingType() == RHSOBT->getUnderlyingType())
11846 return getCommonSugaredType(X: LHS, Y: RHS);
11847 return getOverflowBehaviorType(
11848 Kind: LHSOBT->getBehaviorKind(),
11849 Underlying: getCanonicalType(T: LHSOBT->getUnderlyingType()));
11850 }
11851
11852 // For different underlying types that successfully merge, wrap the
11853 // merged underlying type with the common overflow behavior
11854 return getOverflowBehaviorType(Kind: LHSOBT->getBehaviorKind(),
11855 Underlying: MergedUnderlying);
11856 }
11857 return mergeTypes(LHSOBT->getUnderlyingType(), RHS, OfBlockPointer,
11858 Unqualified, BlockReturnType, IsConditionalOperator);
11859 }
11860
11861 return mergeTypes(LHS, RHSOBT->getUnderlyingType(), OfBlockPointer,
11862 Unqualified, BlockReturnType, IsConditionalOperator);
11863}
11864
11865QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, bool OfBlockPointer,
11866 bool Unqualified, bool BlockReturnType,
11867 bool IsConditionalOperator) {
11868 // For C++ we will not reach this code with reference types (see below),
11869 // for OpenMP variant call overloading we might.
11870 //
11871 // C++ [expr]: If an expression initially has the type "reference to T", the
11872 // type is adjusted to "T" prior to any further analysis, the expression
11873 // designates the object or function denoted by the reference, and the
11874 // expression is an lvalue unless the reference is an rvalue reference and
11875 // the expression is a function call (possibly inside parentheses).
11876 auto *LHSRefTy = LHS->getAs<ReferenceType>();
11877 auto *RHSRefTy = RHS->getAs<ReferenceType>();
11878 if (LangOpts.OpenMP && LHSRefTy && RHSRefTy &&
11879 LHS->getTypeClass() == RHS->getTypeClass())
11880 return mergeTypes(LHS: LHSRefTy->getPointeeType(), RHS: RHSRefTy->getPointeeType(),
11881 OfBlockPointer, Unqualified, BlockReturnType);
11882 if (LHSRefTy || RHSRefTy)
11883 return {};
11884
11885 if (std::optional<QualType> MergedOBT =
11886 tryMergeOverflowBehaviorTypes(LHS, RHS, OfBlockPointer, Unqualified,
11887 BlockReturnType, IsConditionalOperator))
11888 return *MergedOBT;
11889
11890 if (Unqualified) {
11891 LHS = LHS.getUnqualifiedType();
11892 RHS = RHS.getUnqualifiedType();
11893 }
11894
11895 QualType LHSCan = getCanonicalType(T: LHS),
11896 RHSCan = getCanonicalType(T: RHS);
11897
11898 // If two types are identical, they are compatible.
11899 if (LHSCan == RHSCan)
11900 return LHS;
11901
11902 // If the qualifiers are different, the types aren't compatible... mostly.
11903 Qualifiers LQuals = LHSCan.getLocalQualifiers();
11904 Qualifiers RQuals = RHSCan.getLocalQualifiers();
11905 if (LQuals != RQuals) {
11906 // If any of these qualifiers are different, we have a type
11907 // mismatch.
11908 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
11909 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
11910 LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
11911 !LQuals.getPointerAuth().isEquivalent(Other: RQuals.getPointerAuth()) ||
11912 LQuals.hasUnaligned() != RQuals.hasUnaligned())
11913 return {};
11914
11915 // Exactly one GC qualifier difference is allowed: __strong is
11916 // okay if the other type has no GC qualifier but is an Objective
11917 // C object pointer (i.e. implicitly strong by default). We fix
11918 // this by pretending that the unqualified type was actually
11919 // qualified __strong.
11920 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
11921 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
11922 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
11923
11924 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
11925 return {};
11926
11927 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
11928 return mergeTypes(LHS, RHS: getObjCGCQualType(T: RHS, GCAttr: Qualifiers::Strong));
11929 }
11930 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
11931 return mergeTypes(LHS: getObjCGCQualType(T: LHS, GCAttr: Qualifiers::Strong), RHS);
11932 }
11933 return {};
11934 }
11935
11936 // Okay, qualifiers are equal.
11937
11938 Type::TypeClass LHSClass = LHSCan->getTypeClass();
11939 Type::TypeClass RHSClass = RHSCan->getTypeClass();
11940
11941 // We want to consider the two function types to be the same for these
11942 // comparisons, just force one to the other.
11943 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
11944 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
11945
11946 // Same as above for arrays
11947 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
11948 LHSClass = Type::ConstantArray;
11949 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
11950 RHSClass = Type::ConstantArray;
11951
11952 // ObjCInterfaces are just specialized ObjCObjects.
11953 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
11954 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
11955
11956 // Canonicalize ExtVector -> Vector.
11957 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
11958 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
11959
11960 // If the canonical type classes don't match.
11961 if (LHSClass != RHSClass) {
11962 // Note that we only have special rules for turning block enum
11963 // returns into block int returns, not vice-versa.
11964 if (const auto *ETy = LHS->getAsCanonical<EnumType>()) {
11965 return mergeEnumWithInteger(Context&: *this, ET: ETy, other: RHS, isBlockReturnType: false);
11966 }
11967 if (const EnumType *ETy = RHS->getAsCanonical<EnumType>()) {
11968 return mergeEnumWithInteger(Context&: *this, ET: ETy, other: LHS, isBlockReturnType: BlockReturnType);
11969 }
11970 // allow block pointer type to match an 'id' type.
11971 if (OfBlockPointer && !BlockReturnType) {
11972 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
11973 return LHS;
11974 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
11975 return RHS;
11976 }
11977 // Allow __auto_type to match anything; it merges to the type with more
11978 // information.
11979 if (const auto *AT = LHS->getAs<AutoType>()) {
11980 if (!AT->isDeduced() && AT->isGNUAutoType())
11981 return RHS;
11982 }
11983 if (const auto *AT = RHS->getAs<AutoType>()) {
11984 if (!AT->isDeduced() && AT->isGNUAutoType())
11985 return LHS;
11986 }
11987 return {};
11988 }
11989
11990 // The canonical type classes match.
11991 switch (LHSClass) {
11992#define TYPE(Class, Base)
11993#define ABSTRACT_TYPE(Class, Base)
11994#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
11995#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
11996#define DEPENDENT_TYPE(Class, Base) case Type::Class:
11997#include "clang/AST/TypeNodes.inc"
11998 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
11999
12000 case Type::Auto:
12001 case Type::DeducedTemplateSpecialization:
12002 case Type::LValueReference:
12003 case Type::RValueReference:
12004 case Type::MemberPointer:
12005 llvm_unreachable("C++ should never be in mergeTypes");
12006
12007 case Type::ObjCInterface:
12008 case Type::IncompleteArray:
12009 case Type::VariableArray:
12010 case Type::FunctionProto:
12011 case Type::ExtVector:
12012 case Type::OverflowBehavior:
12013 llvm_unreachable("Types are eliminated above");
12014
12015 case Type::Pointer:
12016 {
12017 // Merge two pointer types, while trying to preserve typedef info
12018 QualType LHSPointee = LHS->castAs<PointerType>()->getPointeeType();
12019 QualType RHSPointee = RHS->castAs<PointerType>()->getPointeeType();
12020 if (Unqualified) {
12021 LHSPointee = LHSPointee.getUnqualifiedType();
12022 RHSPointee = RHSPointee.getUnqualifiedType();
12023 }
12024 QualType ResultType = mergeTypes(LHS: LHSPointee, RHS: RHSPointee, OfBlockPointer: false,
12025 Unqualified);
12026 if (ResultType.isNull())
12027 return {};
12028 if (getCanonicalType(T: LHSPointee) == getCanonicalType(T: ResultType))
12029 return LHS;
12030 if (getCanonicalType(T: RHSPointee) == getCanonicalType(T: ResultType))
12031 return RHS;
12032 return getPointerType(T: ResultType);
12033 }
12034 case Type::BlockPointer:
12035 {
12036 // Merge two block pointer types, while trying to preserve typedef info
12037 QualType LHSPointee = LHS->castAs<BlockPointerType>()->getPointeeType();
12038 QualType RHSPointee = RHS->castAs<BlockPointerType>()->getPointeeType();
12039 if (Unqualified) {
12040 LHSPointee = LHSPointee.getUnqualifiedType();
12041 RHSPointee = RHSPointee.getUnqualifiedType();
12042 }
12043 if (getLangOpts().OpenCL) {
12044 Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
12045 Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
12046 // Blocks can't be an expression in a ternary operator (OpenCL v2.0
12047 // 6.12.5) thus the following check is asymmetric.
12048 if (!LHSPteeQual.isAddressSpaceSupersetOf(other: RHSPteeQual, Ctx: *this))
12049 return {};
12050 LHSPteeQual.removeAddressSpace();
12051 RHSPteeQual.removeAddressSpace();
12052 LHSPointee =
12053 QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
12054 RHSPointee =
12055 QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
12056 }
12057 QualType ResultType = mergeTypes(LHS: LHSPointee, RHS: RHSPointee, OfBlockPointer,
12058 Unqualified);
12059 if (ResultType.isNull())
12060 return {};
12061 if (getCanonicalType(T: LHSPointee) == getCanonicalType(T: ResultType))
12062 return LHS;
12063 if (getCanonicalType(T: RHSPointee) == getCanonicalType(T: ResultType))
12064 return RHS;
12065 return getBlockPointerType(T: ResultType);
12066 }
12067 case Type::Atomic:
12068 {
12069 // Merge two pointer types, while trying to preserve typedef info
12070 QualType LHSValue = LHS->castAs<AtomicType>()->getValueType();
12071 QualType RHSValue = RHS->castAs<AtomicType>()->getValueType();
12072 if (Unqualified) {
12073 LHSValue = LHSValue.getUnqualifiedType();
12074 RHSValue = RHSValue.getUnqualifiedType();
12075 }
12076 QualType ResultType = mergeTypes(LHS: LHSValue, RHS: RHSValue, OfBlockPointer: false,
12077 Unqualified);
12078 if (ResultType.isNull())
12079 return {};
12080 if (getCanonicalType(T: LHSValue) == getCanonicalType(T: ResultType))
12081 return LHS;
12082 if (getCanonicalType(T: RHSValue) == getCanonicalType(T: ResultType))
12083 return RHS;
12084 return getAtomicType(T: ResultType);
12085 }
12086 case Type::ConstantArray:
12087 {
12088 const ConstantArrayType* LCAT = getAsConstantArrayType(T: LHS);
12089 const ConstantArrayType* RCAT = getAsConstantArrayType(T: RHS);
12090 if (LCAT && RCAT && RCAT->getZExtSize() != LCAT->getZExtSize())
12091 return {};
12092
12093 QualType LHSElem = getAsArrayType(T: LHS)->getElementType();
12094 QualType RHSElem = getAsArrayType(T: RHS)->getElementType();
12095 if (Unqualified) {
12096 LHSElem = LHSElem.getUnqualifiedType();
12097 RHSElem = RHSElem.getUnqualifiedType();
12098 }
12099
12100 QualType ResultType = mergeTypes(LHS: LHSElem, RHS: RHSElem, OfBlockPointer: false, Unqualified);
12101 if (ResultType.isNull())
12102 return {};
12103
12104 const VariableArrayType* LVAT = getAsVariableArrayType(T: LHS);
12105 const VariableArrayType* RVAT = getAsVariableArrayType(T: RHS);
12106
12107 // If either side is a variable array, and both are complete, check whether
12108 // the current dimension is definite.
12109 if (LVAT || RVAT) {
12110 auto SizeFetch = [this](const VariableArrayType* VAT,
12111 const ConstantArrayType* CAT)
12112 -> std::pair<bool,llvm::APInt> {
12113 if (VAT) {
12114 std::optional<llvm::APSInt> TheInt;
12115 Expr *E = VAT->getSizeExpr();
12116 if (E && (TheInt = E->getIntegerConstantExpr(Ctx: *this)))
12117 return std::make_pair(x: true, y&: *TheInt);
12118 return std::make_pair(x: false, y: llvm::APSInt());
12119 }
12120 if (CAT)
12121 return std::make_pair(x: true, y: CAT->getSize());
12122 return std::make_pair(x: false, y: llvm::APInt());
12123 };
12124
12125 bool HaveLSize, HaveRSize;
12126 llvm::APInt LSize, RSize;
12127 std::tie(args&: HaveLSize, args&: LSize) = SizeFetch(LVAT, LCAT);
12128 std::tie(args&: HaveRSize, args&: RSize) = SizeFetch(RVAT, RCAT);
12129 if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(I1: LSize, I2: RSize))
12130 return {}; // Definite, but unequal, array dimension
12131 }
12132
12133 if (LCAT && getCanonicalType(T: LHSElem) == getCanonicalType(T: ResultType))
12134 return LHS;
12135 if (RCAT && getCanonicalType(T: RHSElem) == getCanonicalType(T: ResultType))
12136 return RHS;
12137 if (LCAT)
12138 return getConstantArrayType(EltTy: ResultType, ArySizeIn: LCAT->getSize(),
12139 SizeExpr: LCAT->getSizeExpr(), ASM: ArraySizeModifier(), IndexTypeQuals: 0);
12140 if (RCAT)
12141 return getConstantArrayType(EltTy: ResultType, ArySizeIn: RCAT->getSize(),
12142 SizeExpr: RCAT->getSizeExpr(), ASM: ArraySizeModifier(), IndexTypeQuals: 0);
12143 if (LVAT && getCanonicalType(T: LHSElem) == getCanonicalType(T: ResultType))
12144 return LHS;
12145 if (RVAT && getCanonicalType(T: RHSElem) == getCanonicalType(T: ResultType))
12146 return RHS;
12147 if (LVAT) {
12148 // FIXME: This isn't correct! But tricky to implement because
12149 // the array's size has to be the size of LHS, but the type
12150 // has to be different.
12151 return LHS;
12152 }
12153 if (RVAT) {
12154 // FIXME: This isn't correct! But tricky to implement because
12155 // the array's size has to be the size of RHS, but the type
12156 // has to be different.
12157 return RHS;
12158 }
12159 if (getCanonicalType(T: LHSElem) == getCanonicalType(T: ResultType)) return LHS;
12160 if (getCanonicalType(T: RHSElem) == getCanonicalType(T: ResultType)) return RHS;
12161 return getIncompleteArrayType(elementType: ResultType, ASM: ArraySizeModifier(), elementTypeQuals: 0);
12162 }
12163 case Type::FunctionNoProto:
12164 return mergeFunctionTypes(lhs: LHS, rhs: RHS, OfBlockPointer, Unqualified,
12165 /*AllowCXX=*/false, IsConditionalOperator);
12166 case Type::Record:
12167 case Type::Enum:
12168 return mergeTagDefinitions(LHS, RHS);
12169 case Type::Builtin:
12170 // Only exactly equal builtin types are compatible, which is tested above.
12171 return {};
12172 case Type::Complex:
12173 // Distinct complex types are incompatible.
12174 return {};
12175 case Type::Vector:
12176 // FIXME: The merged type should be an ExtVector!
12177 if (areCompatVectorTypes(LHS: LHSCan->castAs<VectorType>(),
12178 RHS: RHSCan->castAs<VectorType>()))
12179 return LHS;
12180 return {};
12181 case Type::ConstantMatrix:
12182 if (areCompatMatrixTypes(LHS: LHSCan->castAs<ConstantMatrixType>(),
12183 RHS: RHSCan->castAs<ConstantMatrixType>()))
12184 return LHS;
12185 return {};
12186 case Type::ObjCObject: {
12187 // Check if the types are assignment compatible.
12188 // FIXME: This should be type compatibility, e.g. whether
12189 // "LHS x; RHS x;" at global scope is legal.
12190 if (canAssignObjCInterfaces(LHS: LHS->castAs<ObjCObjectType>(),
12191 RHS: RHS->castAs<ObjCObjectType>()))
12192 return LHS;
12193 return {};
12194 }
12195 case Type::ObjCObjectPointer:
12196 if (OfBlockPointer) {
12197 if (canAssignObjCInterfacesInBlockPointer(
12198 LHSOPT: LHS->castAs<ObjCObjectPointerType>(),
12199 RHSOPT: RHS->castAs<ObjCObjectPointerType>(), BlockReturnType))
12200 return LHS;
12201 return {};
12202 }
12203 if (canAssignObjCInterfaces(LHSOPT: LHS->castAs<ObjCObjectPointerType>(),
12204 RHSOPT: RHS->castAs<ObjCObjectPointerType>()))
12205 return LHS;
12206 return {};
12207 case Type::Pipe:
12208 assert(LHS != RHS &&
12209 "Equivalent pipe types should have already been handled!");
12210 return {};
12211 case Type::ArrayParameter:
12212 assert(LHS != RHS &&
12213 "Equivalent ArrayParameter types should have already been handled!");
12214 return {};
12215 case Type::BitInt: {
12216 // Merge two bit-precise int types, while trying to preserve typedef info.
12217 bool LHSUnsigned = LHS->castAs<BitIntType>()->isUnsigned();
12218 bool RHSUnsigned = RHS->castAs<BitIntType>()->isUnsigned();
12219 unsigned LHSBits = LHS->castAs<BitIntType>()->getNumBits();
12220 unsigned RHSBits = RHS->castAs<BitIntType>()->getNumBits();
12221
12222 // Like unsigned/int, shouldn't have a type if they don't match.
12223 if (LHSUnsigned != RHSUnsigned)
12224 return {};
12225
12226 if (LHSBits != RHSBits)
12227 return {};
12228 return LHS;
12229 }
12230 case Type::HLSLAttributedResource: {
12231 const HLSLAttributedResourceType *LHSTy =
12232 LHS->castAs<HLSLAttributedResourceType>();
12233 const HLSLAttributedResourceType *RHSTy =
12234 RHS->castAs<HLSLAttributedResourceType>();
12235 assert(LHSTy->getWrappedType() == RHSTy->getWrappedType() &&
12236 LHSTy->getWrappedType()->isHLSLResourceType() &&
12237 "HLSLAttributedResourceType should always wrap __hlsl_resource_t");
12238
12239 if (LHSTy->getAttrs() == RHSTy->getAttrs() &&
12240 LHSTy->getContainedType() == RHSTy->getContainedType())
12241 return LHS;
12242 return {};
12243 }
12244 case Type::HLSLInlineSpirv:
12245 const HLSLInlineSpirvType *LHSTy = LHS->castAs<HLSLInlineSpirvType>();
12246 const HLSLInlineSpirvType *RHSTy = RHS->castAs<HLSLInlineSpirvType>();
12247
12248 if (LHSTy->getOpcode() == RHSTy->getOpcode() &&
12249 LHSTy->getSize() == RHSTy->getSize() &&
12250 LHSTy->getAlignment() == RHSTy->getAlignment()) {
12251 for (size_t I = 0; I < LHSTy->getOperands().size(); I++)
12252 if (LHSTy->getOperands()[I] != RHSTy->getOperands()[I])
12253 return {};
12254
12255 return LHS;
12256 }
12257 return {};
12258 }
12259
12260 llvm_unreachable("Invalid Type::Class!");
12261}
12262
12263bool ASTContext::mergeExtParameterInfo(
12264 const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType,
12265 bool &CanUseFirst, bool &CanUseSecond,
12266 SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &NewParamInfos) {
12267 assert(NewParamInfos.empty() && "param info list not empty");
12268 CanUseFirst = CanUseSecond = true;
12269 bool FirstHasInfo = FirstFnType->hasExtParameterInfos();
12270 bool SecondHasInfo = SecondFnType->hasExtParameterInfos();
12271
12272 // Fast path: if the first type doesn't have ext parameter infos,
12273 // we match if and only if the second type also doesn't have them.
12274 if (!FirstHasInfo && !SecondHasInfo)
12275 return true;
12276
12277 bool NeedParamInfo = false;
12278 size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size()
12279 : SecondFnType->getExtParameterInfos().size();
12280
12281 for (size_t I = 0; I < E; ++I) {
12282 FunctionProtoType::ExtParameterInfo FirstParam, SecondParam;
12283 if (FirstHasInfo)
12284 FirstParam = FirstFnType->getExtParameterInfo(I);
12285 if (SecondHasInfo)
12286 SecondParam = SecondFnType->getExtParameterInfo(I);
12287
12288 // Cannot merge unless everything except the noescape flag matches.
12289 if (FirstParam.withIsNoEscape(NoEscape: false) != SecondParam.withIsNoEscape(NoEscape: false))
12290 return false;
12291
12292 bool FirstNoEscape = FirstParam.isNoEscape();
12293 bool SecondNoEscape = SecondParam.isNoEscape();
12294 bool IsNoEscape = FirstNoEscape && SecondNoEscape;
12295 NewParamInfos.push_back(Elt: FirstParam.withIsNoEscape(NoEscape: IsNoEscape));
12296 if (NewParamInfos.back().getOpaqueValue())
12297 NeedParamInfo = true;
12298 if (FirstNoEscape != IsNoEscape)
12299 CanUseFirst = false;
12300 if (SecondNoEscape != IsNoEscape)
12301 CanUseSecond = false;
12302 }
12303
12304 if (!NeedParamInfo)
12305 NewParamInfos.clear();
12306
12307 return true;
12308}
12309
12310void ASTContext::ResetObjCLayout(const ObjCInterfaceDecl *D) {
12311 if (auto It = ObjCLayouts.find(Val: D); It != ObjCLayouts.end()) {
12312 It->second = nullptr;
12313 for (auto *SubClass : ObjCSubClasses.lookup(Val: D))
12314 ResetObjCLayout(D: SubClass);
12315 }
12316}
12317
12318/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
12319/// 'RHS' attributes and returns the merged version; including for function
12320/// return types.
12321QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
12322 QualType LHSCan = getCanonicalType(T: LHS),
12323 RHSCan = getCanonicalType(T: RHS);
12324 // If two types are identical, they are compatible.
12325 if (LHSCan == RHSCan)
12326 return LHS;
12327 if (RHSCan->isFunctionType()) {
12328 if (!LHSCan->isFunctionType())
12329 return {};
12330 QualType OldReturnType =
12331 cast<FunctionType>(Val: RHSCan.getTypePtr())->getReturnType();
12332 QualType NewReturnType =
12333 cast<FunctionType>(Val: LHSCan.getTypePtr())->getReturnType();
12334 QualType ResReturnType =
12335 mergeObjCGCQualifiers(LHS: NewReturnType, RHS: OldReturnType);
12336 if (ResReturnType.isNull())
12337 return {};
12338 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
12339 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
12340 // In either case, use OldReturnType to build the new function type.
12341 const auto *F = LHS->castAs<FunctionType>();
12342 if (const auto *FPT = cast<FunctionProtoType>(Val: F)) {
12343 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12344 EPI.ExtInfo = getFunctionExtInfo(t: LHS);
12345 QualType ResultType =
12346 getFunctionType(ResultTy: OldReturnType, Args: FPT->getParamTypes(), EPI);
12347 return ResultType;
12348 }
12349 }
12350 return {};
12351 }
12352
12353 // If the qualifiers are different, the types can still be merged.
12354 Qualifiers LQuals = LHSCan.getLocalQualifiers();
12355 Qualifiers RQuals = RHSCan.getLocalQualifiers();
12356 if (LQuals != RQuals) {
12357 // If any of these qualifiers are different, we have a type mismatch.
12358 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
12359 LQuals.getAddressSpace() != RQuals.getAddressSpace())
12360 return {};
12361
12362 // Exactly one GC qualifier difference is allowed: __strong is
12363 // okay if the other type has no GC qualifier but is an Objective
12364 // C object pointer (i.e. implicitly strong by default). We fix
12365 // this by pretending that the unqualified type was actually
12366 // qualified __strong.
12367 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
12368 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
12369 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
12370
12371 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
12372 return {};
12373
12374 if (GC_L == Qualifiers::Strong)
12375 return LHS;
12376 if (GC_R == Qualifiers::Strong)
12377 return RHS;
12378 return {};
12379 }
12380
12381 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
12382 QualType LHSBaseQT = LHS->castAs<ObjCObjectPointerType>()->getPointeeType();
12383 QualType RHSBaseQT = RHS->castAs<ObjCObjectPointerType>()->getPointeeType();
12384 QualType ResQT = mergeObjCGCQualifiers(LHS: LHSBaseQT, RHS: RHSBaseQT);
12385 if (ResQT == LHSBaseQT)
12386 return LHS;
12387 if (ResQT == RHSBaseQT)
12388 return RHS;
12389 }
12390 return {};
12391}
12392
12393//===----------------------------------------------------------------------===//
12394// Integer Predicates
12395//===----------------------------------------------------------------------===//
12396
12397unsigned ASTContext::getIntWidth(QualType T) const {
12398 if (const auto *ED = T->getAsEnumDecl())
12399 T = ED->getIntegerType();
12400 if (T->isBooleanType())
12401 return 1;
12402 if (const auto *EIT = T->getAs<BitIntType>())
12403 return EIT->getNumBits();
12404 // For builtin types, just use the standard type sizing method
12405 return (unsigned)getTypeSize(T);
12406}
12407
12408QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
12409 assert((T->hasIntegerRepresentation() || T->isEnumeralType() ||
12410 T->isFixedPointType()) &&
12411 "Unexpected type");
12412
12413 // Turn <4 x signed int> -> <4 x unsigned int>
12414 if (const auto *VTy = T->getAs<VectorType>())
12415 return getVectorType(vecType: getCorrespondingUnsignedType(T: VTy->getElementType()),
12416 NumElts: VTy->getNumElements(), VecKind: VTy->getVectorKind());
12417
12418 // For _BitInt, return an unsigned _BitInt with same width.
12419 if (const auto *EITy = T->getAs<BitIntType>())
12420 return getBitIntType(/*Unsigned=*/IsUnsigned: true, NumBits: EITy->getNumBits());
12421
12422 // For the overflow behavior types, construct a new unsigned variant
12423 if (const auto *OBT = T->getAs<OverflowBehaviorType>())
12424 return getOverflowBehaviorType(
12425 Kind: OBT->getBehaviorKind(),
12426 Underlying: getCorrespondingUnsignedType(T: OBT->getUnderlyingType()));
12427
12428 // For enums, get the underlying integer type of the enum, and let the general
12429 // integer type signchanging code handle it.
12430 if (const auto *ED = T->getAsEnumDecl())
12431 T = ED->getIntegerType();
12432
12433 switch (T->castAs<BuiltinType>()->getKind()) {
12434 case BuiltinType::Char_U:
12435 // Plain `char` is mapped to `unsigned char` even if it's already unsigned
12436 case BuiltinType::Char_S:
12437 case BuiltinType::SChar:
12438 case BuiltinType::Char8:
12439 return UnsignedCharTy;
12440 case BuiltinType::Short:
12441 return UnsignedShortTy;
12442 case BuiltinType::Int:
12443 return UnsignedIntTy;
12444 case BuiltinType::Long:
12445 return UnsignedLongTy;
12446 case BuiltinType::LongLong:
12447 return UnsignedLongLongTy;
12448 case BuiltinType::Int128:
12449 return UnsignedInt128Ty;
12450 // wchar_t is special. It is either signed or not, but when it's signed,
12451 // there's no matching "unsigned wchar_t". Therefore we return the unsigned
12452 // version of its underlying type instead.
12453 case BuiltinType::WChar_S:
12454 return getUnsignedWCharType();
12455
12456 case BuiltinType::ShortAccum:
12457 return UnsignedShortAccumTy;
12458 case BuiltinType::Accum:
12459 return UnsignedAccumTy;
12460 case BuiltinType::LongAccum:
12461 return UnsignedLongAccumTy;
12462 case BuiltinType::SatShortAccum:
12463 return SatUnsignedShortAccumTy;
12464 case BuiltinType::SatAccum:
12465 return SatUnsignedAccumTy;
12466 case BuiltinType::SatLongAccum:
12467 return SatUnsignedLongAccumTy;
12468 case BuiltinType::ShortFract:
12469 return UnsignedShortFractTy;
12470 case BuiltinType::Fract:
12471 return UnsignedFractTy;
12472 case BuiltinType::LongFract:
12473 return UnsignedLongFractTy;
12474 case BuiltinType::SatShortFract:
12475 return SatUnsignedShortFractTy;
12476 case BuiltinType::SatFract:
12477 return SatUnsignedFractTy;
12478 case BuiltinType::SatLongFract:
12479 return SatUnsignedLongFractTy;
12480 default:
12481 assert((T->hasUnsignedIntegerRepresentation() ||
12482 T->isUnsignedFixedPointType()) &&
12483 "Unexpected signed integer or fixed point type");
12484 return T;
12485 }
12486}
12487
12488QualType ASTContext::getCorrespondingSignedType(QualType T) const {
12489 assert((T->hasIntegerRepresentation() || T->isEnumeralType() ||
12490 T->isFixedPointType()) &&
12491 "Unexpected type");
12492
12493 // Turn <4 x unsigned int> -> <4 x signed int>
12494 if (const auto *VTy = T->getAs<VectorType>())
12495 return getVectorType(vecType: getCorrespondingSignedType(T: VTy->getElementType()),
12496 NumElts: VTy->getNumElements(), VecKind: VTy->getVectorKind());
12497
12498 // For _BitInt, return a signed _BitInt with same width.
12499 if (const auto *EITy = T->getAs<BitIntType>())
12500 return getBitIntType(/*Unsigned=*/IsUnsigned: false, NumBits: EITy->getNumBits());
12501
12502 // For enums, get the underlying integer type of the enum, and let the general
12503 // integer type signchanging code handle it.
12504 if (const auto *ED = T->getAsEnumDecl())
12505 T = ED->getIntegerType();
12506
12507 switch (T->castAs<BuiltinType>()->getKind()) {
12508 case BuiltinType::Char_S:
12509 // Plain `char` is mapped to `signed char` even if it's already signed
12510 case BuiltinType::Char_U:
12511 case BuiltinType::UChar:
12512 case BuiltinType::Char8:
12513 return SignedCharTy;
12514 case BuiltinType::UShort:
12515 return ShortTy;
12516 case BuiltinType::UInt:
12517 return IntTy;
12518 case BuiltinType::ULong:
12519 return LongTy;
12520 case BuiltinType::ULongLong:
12521 return LongLongTy;
12522 case BuiltinType::UInt128:
12523 return Int128Ty;
12524 // wchar_t is special. It is either unsigned or not, but when it's unsigned,
12525 // there's no matching "signed wchar_t". Therefore we return the signed
12526 // version of its underlying type instead.
12527 case BuiltinType::WChar_U:
12528 return getSignedWCharType();
12529
12530 case BuiltinType::UShortAccum:
12531 return ShortAccumTy;
12532 case BuiltinType::UAccum:
12533 return AccumTy;
12534 case BuiltinType::ULongAccum:
12535 return LongAccumTy;
12536 case BuiltinType::SatUShortAccum:
12537 return SatShortAccumTy;
12538 case BuiltinType::SatUAccum:
12539 return SatAccumTy;
12540 case BuiltinType::SatULongAccum:
12541 return SatLongAccumTy;
12542 case BuiltinType::UShortFract:
12543 return ShortFractTy;
12544 case BuiltinType::UFract:
12545 return FractTy;
12546 case BuiltinType::ULongFract:
12547 return LongFractTy;
12548 case BuiltinType::SatUShortFract:
12549 return SatShortFractTy;
12550 case BuiltinType::SatUFract:
12551 return SatFractTy;
12552 case BuiltinType::SatULongFract:
12553 return SatLongFractTy;
12554 default:
12555 assert(
12556 (T->hasSignedIntegerRepresentation() || T->isSignedFixedPointType()) &&
12557 "Unexpected signed integer or fixed point type");
12558 return T;
12559 }
12560}
12561
12562ASTMutationListener::~ASTMutationListener() = default;
12563
12564void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
12565 QualType ReturnType) {}
12566
12567//===----------------------------------------------------------------------===//
12568// Builtin Type Computation
12569//===----------------------------------------------------------------------===//
12570
12571/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
12572/// pointer over the consumed characters. This returns the resultant type. If
12573/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
12574/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
12575/// a vector of "i*".
12576///
12577/// RequiresICE is filled in on return to indicate whether the value is required
12578/// to be an Integer Constant Expression.
12579static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
12580 ASTContext::GetBuiltinTypeError &Error,
12581 bool &RequiresICE,
12582 bool AllowTypeModifiers) {
12583 // Modifiers.
12584 int HowLong = 0;
12585 bool Signed = false, Unsigned = false;
12586 bool IsChar = false, IsShort = false;
12587 RequiresICE = false;
12588
12589 // Read the prefixed modifiers first.
12590 bool Done = false;
12591 #ifndef NDEBUG
12592 bool IsSpecial = false;
12593 #endif
12594 while (!Done) {
12595 switch (*Str++) {
12596 default: Done = true; --Str; break;
12597 case 'I':
12598 RequiresICE = true;
12599 break;
12600 case 'S':
12601 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
12602 assert(!Signed && "Can't use 'S' modifier multiple times!");
12603 Signed = true;
12604 break;
12605 case 'U':
12606 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
12607 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
12608 Unsigned = true;
12609 break;
12610 case 'B':
12611 // This modifier represents int8 type (byte-width).
12612 assert(!IsSpecial &&
12613 "Can't use two 'N', 'W', 'Z', 'O', 'B', or 'T' modifiers!");
12614 assert(HowLong == 0 && "Can't use both 'L' and 'B' modifiers!");
12615#ifndef NDEBUG
12616 IsSpecial = true;
12617#endif
12618 IsChar = true;
12619 break;
12620 case 'T':
12621 // This modifier represents int16 type (short-width).
12622 assert(!IsSpecial &&
12623 "Can't use two 'N', 'W', 'Z', 'O', 'B', or 'T' modifiers!");
12624 assert(HowLong == 0 && "Can't use both 'L' and 'T' modifiers!");
12625#ifndef NDEBUG
12626 IsSpecial = true;
12627#endif
12628 IsShort = true;
12629 break;
12630 case 'L':
12631 assert(!IsSpecial &&
12632 "Can't use 'L' with 'W', 'N', 'Z', 'O', 'B', or 'T' modifiers");
12633 assert(HowLong <= 2 && "Can't have LLLL modifier");
12634 ++HowLong;
12635 break;
12636 case 'N':
12637 // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
12638 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12639 assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
12640 #ifndef NDEBUG
12641 IsSpecial = true;
12642 #endif
12643 if (Context.getTargetInfo().getLongWidth() == 32)
12644 ++HowLong;
12645 break;
12646 case 'W':
12647 // This modifier represents int64 type.
12648 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12649 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
12650 #ifndef NDEBUG
12651 IsSpecial = true;
12652 #endif
12653 switch (Context.getTargetInfo().getInt64Type()) {
12654 default:
12655 llvm_unreachable("Unexpected integer type");
12656 case TargetInfo::SignedLong:
12657 HowLong = 1;
12658 break;
12659 case TargetInfo::SignedLongLong:
12660 HowLong = 2;
12661 break;
12662 }
12663 break;
12664 case 'Z':
12665 // This modifier represents int32 type.
12666 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12667 assert(HowLong == 0 && "Can't use both 'L' and 'Z' modifiers!");
12668 #ifndef NDEBUG
12669 IsSpecial = true;
12670 #endif
12671 switch (Context.getTargetInfo().getIntTypeByWidth(BitWidth: 32, IsSigned: true)) {
12672 default:
12673 llvm_unreachable("Unexpected integer type");
12674 case TargetInfo::SignedInt:
12675 HowLong = 0;
12676 break;
12677 case TargetInfo::SignedLong:
12678 HowLong = 1;
12679 break;
12680 case TargetInfo::SignedLongLong:
12681 HowLong = 2;
12682 break;
12683 }
12684 break;
12685 case 'O':
12686 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12687 assert(HowLong == 0 && "Can't use both 'L' and 'O' modifiers!");
12688 #ifndef NDEBUG
12689 IsSpecial = true;
12690 #endif
12691 if (Context.getLangOpts().OpenCL)
12692 HowLong = 1;
12693 else
12694 HowLong = 2;
12695 break;
12696 }
12697 }
12698
12699 QualType Type;
12700
12701 // Read the base type.
12702 switch (*Str++) {
12703 default:
12704 llvm_unreachable("Unknown builtin type letter!");
12705 case 'x':
12706 assert(HowLong == 0 && !Signed && !Unsigned &&
12707 "Bad modifiers used with 'x'!");
12708 Type = Context.Float16Ty;
12709 break;
12710 case 'y':
12711 assert(HowLong == 0 && !Signed && !Unsigned &&
12712 "Bad modifiers used with 'y'!");
12713 Type = Context.BFloat16Ty;
12714 break;
12715 case 'v':
12716 assert(HowLong == 0 && !Signed && !Unsigned &&
12717 "Bad modifiers used with 'v'!");
12718 Type = Context.VoidTy;
12719 break;
12720 case 'h':
12721 assert(HowLong == 0 && !Signed && !Unsigned &&
12722 "Bad modifiers used with 'h'!");
12723 Type = Context.HalfTy;
12724 break;
12725 case 'f':
12726 assert(HowLong == 0 && !Signed && !Unsigned &&
12727 "Bad modifiers used with 'f'!");
12728 Type = Context.FloatTy;
12729 break;
12730 case 'd':
12731 assert(HowLong < 3 && !Signed && !Unsigned &&
12732 "Bad modifiers used with 'd'!");
12733 if (HowLong == 1)
12734 Type = Context.LongDoubleTy;
12735 else if (HowLong == 2)
12736 Type = Context.Float128Ty;
12737 else
12738 Type = Context.DoubleTy;
12739 break;
12740 case 's':
12741 assert(HowLong == 0 && "Bad modifiers used with 's'!");
12742 if (Unsigned)
12743 Type = Context.UnsignedShortTy;
12744 else
12745 Type = Context.ShortTy;
12746 break;
12747 case 'i':
12748 if (IsChar)
12749 Type = Unsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
12750 else if (IsShort)
12751 Type = Unsigned ? Context.UnsignedShortTy : Context.ShortTy;
12752 else if (HowLong == 3)
12753 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
12754 else if (HowLong == 2)
12755 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
12756 else if (HowLong == 1)
12757 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
12758 else
12759 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
12760 break;
12761 case 'c':
12762 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
12763 if (Signed)
12764 Type = Context.SignedCharTy;
12765 else if (Unsigned)
12766 Type = Context.UnsignedCharTy;
12767 else
12768 Type = Context.CharTy;
12769 break;
12770 case 'b': // boolean
12771 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
12772 Type = Context.BoolTy;
12773 break;
12774 case 'z': // size_t.
12775 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
12776 Type = Context.getSizeType();
12777 break;
12778 case 'w': // wchar_t.
12779 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
12780 Type = Context.getWideCharType();
12781 break;
12782 case 'F':
12783 Type = Context.getCFConstantStringType();
12784 break;
12785 case 'G':
12786 Type = Context.getObjCIdType();
12787 break;
12788 case 'H':
12789 Type = Context.getObjCSelType();
12790 break;
12791 case 'M':
12792 Type = Context.getObjCSuperType();
12793 break;
12794 case 'a':
12795 Type = Context.getBuiltinVaListType();
12796 assert(!Type.isNull() && "builtin va list type not initialized!");
12797 break;
12798 case 'A':
12799 // This is a "reference" to a va_list; however, what exactly
12800 // this means depends on how va_list is defined. There are two
12801 // different kinds of va_list: ones passed by value, and ones
12802 // passed by reference. An example of a by-value va_list is
12803 // x86, where va_list is a char*. An example of by-ref va_list
12804 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
12805 // we want this argument to be a char*&; for x86-64, we want
12806 // it to be a __va_list_tag*.
12807 Type = Context.getBuiltinVaListType();
12808 assert(!Type.isNull() && "builtin va list type not initialized!");
12809 if (Type->isArrayType())
12810 Type = Context.getArrayDecayedType(Ty: Type);
12811 else
12812 Type = Context.getLValueReferenceType(T: Type);
12813 break;
12814 case 'q': {
12815 char *End;
12816 unsigned NumElements = strtoul(nptr: Str, endptr: &End, base: 10);
12817 assert(End != Str && "Missing vector size");
12818 Str = End;
12819
12820 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
12821 RequiresICE, AllowTypeModifiers: false);
12822 assert(!RequiresICE && "Can't require vector ICE");
12823
12824 Type = Context.getScalableVectorType(EltTy: ElementType, NumElts: NumElements);
12825 break;
12826 }
12827 case 'Q': {
12828 switch (*Str++) {
12829 case 'a': {
12830 Type = Context.SveCountTy;
12831 break;
12832 }
12833 case 'b': {
12834 Type = Context.AMDGPUBufferRsrcTy;
12835 break;
12836 }
12837 case 'c': {
12838 Type = Context.AMDGPUFeaturePredicateTy;
12839 break;
12840 }
12841 case 't': {
12842 Type = Context.AMDGPUTextureTy;
12843 break;
12844 }
12845 case 'r': {
12846 Type = Context.HLSLResourceTy;
12847 break;
12848 }
12849 default:
12850 llvm_unreachable("Unexpected target builtin type");
12851 }
12852 break;
12853 }
12854 case 'V': {
12855 char *End;
12856 unsigned NumElements = strtoul(nptr: Str, endptr: &End, base: 10);
12857 assert(End != Str && "Missing vector size");
12858 Str = End;
12859
12860 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
12861 RequiresICE, AllowTypeModifiers: false);
12862 assert(!RequiresICE && "Can't require vector ICE");
12863
12864 // TODO: No way to make AltiVec vectors in builtins yet.
12865 Type = Context.getVectorType(vecType: ElementType, NumElts: NumElements, VecKind: VectorKind::Generic);
12866 break;
12867 }
12868 case 'E': {
12869 char *End;
12870
12871 unsigned NumElements = strtoul(nptr: Str, endptr: &End, base: 10);
12872 assert(End != Str && "Missing vector size");
12873
12874 Str = End;
12875
12876 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
12877 AllowTypeModifiers: false);
12878 Type = Context.getExtVectorType(vecType: ElementType, NumElts: NumElements);
12879 break;
12880 }
12881 case 'X': {
12882 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
12883 AllowTypeModifiers: false);
12884 assert(!RequiresICE && "Can't require complex ICE");
12885 Type = Context.getComplexType(T: ElementType);
12886 break;
12887 }
12888 case 'Y':
12889 Type = Context.getPointerDiffType();
12890 break;
12891 case 'P':
12892 Type = Context.getFILEType();
12893 if (Type.isNull()) {
12894 Error = ASTContext::GE_Missing_stdio;
12895 return {};
12896 }
12897 break;
12898 case 'J':
12899 if (Signed)
12900 Type = Context.getsigjmp_bufType();
12901 else
12902 Type = Context.getjmp_bufType();
12903
12904 if (Type.isNull()) {
12905 Error = ASTContext::GE_Missing_setjmp;
12906 return {};
12907 }
12908 break;
12909 case 'K':
12910 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
12911 Type = Context.getucontext_tType();
12912
12913 if (Type.isNull()) {
12914 Error = ASTContext::GE_Missing_ucontext;
12915 return {};
12916 }
12917 break;
12918 case 'p':
12919 Type = Context.getProcessIDType();
12920 break;
12921 case 'm':
12922 Type = Context.MFloat8Ty;
12923 break;
12924 }
12925
12926 // If there are modifiers and if we're allowed to parse them, go for it.
12927 Done = !AllowTypeModifiers;
12928 while (!Done) {
12929 switch (char c = *Str++) {
12930 default: Done = true; --Str; break;
12931 case '*':
12932 case '&': {
12933 // Both pointers and references can have their pointee types
12934 // qualified with an address space.
12935 char *End;
12936 unsigned AddrSpace = strtoul(nptr: Str, endptr: &End, base: 10);
12937 if (End != Str) {
12938 // Note AddrSpace == 0 is not the same as an unspecified address space.
12939 Type = Context.getAddrSpaceQualType(
12940 T: Type,
12941 AddressSpace: Context.getLangASForBuiltinAddressSpace(AS: AddrSpace));
12942 Str = End;
12943 }
12944 if (c == '*')
12945 Type = Context.getPointerType(T: Type);
12946 else
12947 Type = Context.getLValueReferenceType(T: Type);
12948 break;
12949 }
12950 // FIXME: There's no way to have a built-in with an rvalue ref arg.
12951 case 'C':
12952 Type = Type.withConst();
12953 break;
12954 case 'D':
12955 Type = Context.getVolatileType(T: Type);
12956 break;
12957 case 'R':
12958 Type = Type.withRestrict();
12959 break;
12960 }
12961 }
12962
12963 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
12964 "Integer constant 'I' type must be an integer");
12965
12966 return Type;
12967}
12968
12969// On some targets such as PowerPC, some of the builtins are defined with custom
12970// type descriptors for target-dependent types. These descriptors are decoded in
12971// other functions, but it may be useful to be able to fall back to default
12972// descriptor decoding to define builtins mixing target-dependent and target-
12973// independent types. This function allows decoding one type descriptor with
12974// default decoding.
12975QualType ASTContext::DecodeTypeStr(const char *&Str, const ASTContext &Context,
12976 GetBuiltinTypeError &Error, bool &RequireICE,
12977 bool AllowTypeModifiers) const {
12978 return DecodeTypeFromStr(Str, Context, Error, RequiresICE&: RequireICE, AllowTypeModifiers);
12979}
12980
12981/// GetBuiltinType - Return the type for the specified builtin.
12982QualType ASTContext::GetBuiltinType(unsigned Id,
12983 GetBuiltinTypeError &Error,
12984 unsigned *IntegerConstantArgs) const {
12985 const char *TypeStr = BuiltinInfo.getTypeString(ID: Id);
12986 if (TypeStr[0] == '\0') {
12987 Error = GE_Missing_type;
12988 return {};
12989 }
12990
12991 SmallVector<QualType, 8> ArgTypes;
12992
12993 bool RequiresICE = false;
12994 Error = GE_None;
12995 QualType ResType = DecodeTypeFromStr(Str&: TypeStr, Context: *this, Error,
12996 RequiresICE, AllowTypeModifiers: true);
12997 if (Error != GE_None)
12998 return {};
12999
13000 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
13001
13002 while (TypeStr[0] && TypeStr[0] != '.') {
13003 QualType Ty = DecodeTypeFromStr(Str&: TypeStr, Context: *this, Error, RequiresICE, AllowTypeModifiers: true);
13004 if (Error != GE_None)
13005 return {};
13006
13007 // If this argument is required to be an IntegerConstantExpression and the
13008 // caller cares, fill in the bitmask we return.
13009 if (RequiresICE && IntegerConstantArgs)
13010 *IntegerConstantArgs |= 1 << ArgTypes.size();
13011
13012 // Do array -> pointer decay. The builtin should use the decayed type.
13013 if (Ty->isArrayType())
13014 Ty = getArrayDecayedType(Ty);
13015
13016 ArgTypes.push_back(Elt: Ty);
13017 }
13018
13019 if (Id == Builtin::BI__GetExceptionInfo)
13020 return {};
13021
13022 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
13023 "'.' should only occur at end of builtin type list!");
13024
13025 bool Variadic = (TypeStr[0] == '.');
13026
13027 FunctionType::ExtInfo EI(Target->getDefaultCallingConv());
13028 if (BuiltinInfo.isNoReturn(ID: Id))
13029 EI = EI.withNoReturn(noReturn: true);
13030
13031 // We really shouldn't be making a no-proto type here.
13032 if (ArgTypes.empty() && Variadic && !getLangOpts().requiresStrictPrototypes())
13033 return getFunctionNoProtoType(ResultTy: ResType, Info: EI);
13034
13035 FunctionProtoType::ExtProtoInfo EPI;
13036 EPI.ExtInfo = EI;
13037 EPI.Variadic = Variadic;
13038 if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(ID: Id))
13039 EPI.ExceptionSpec.Type =
13040 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
13041
13042 return getFunctionType(ResultTy: ResType, Args: ArgTypes, EPI);
13043}
13044
13045static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
13046 const FunctionDecl *FD) {
13047 if (!FD->isExternallyVisible())
13048 return GVA_Internal;
13049
13050 // Non-user-provided functions get emitted as weak definitions with every
13051 // use, no matter whether they've been explicitly instantiated etc.
13052 if (!FD->isUserProvided())
13053 return GVA_DiscardableODR;
13054
13055 GVALinkage External;
13056 switch (FD->getTemplateSpecializationKind()) {
13057 case TSK_Undeclared:
13058 case TSK_ExplicitSpecialization:
13059 External = GVA_StrongExternal;
13060 break;
13061
13062 case TSK_ExplicitInstantiationDefinition:
13063 return GVA_StrongODR;
13064
13065 // C++11 [temp.explicit]p10:
13066 // [ Note: The intent is that an inline function that is the subject of
13067 // an explicit instantiation declaration will still be implicitly
13068 // instantiated when used so that the body can be considered for
13069 // inlining, but that no out-of-line copy of the inline function would be
13070 // generated in the translation unit. -- end note ]
13071 case TSK_ExplicitInstantiationDeclaration:
13072 return GVA_AvailableExternally;
13073
13074 case TSK_ImplicitInstantiation:
13075 External = GVA_DiscardableODR;
13076 break;
13077 }
13078
13079 if (!FD->isInlined())
13080 return External;
13081
13082 if ((!Context.getLangOpts().CPlusPlus &&
13083 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13084 !FD->hasAttr<DLLExportAttr>()) ||
13085 FD->hasAttr<GNUInlineAttr>()) {
13086 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
13087
13088 // GNU or C99 inline semantics. Determine whether this symbol should be
13089 // externally visible.
13090 if (auto *Def = FD->getDefinition();
13091 Def && Def->isInlineDefinitionExternallyVisible())
13092 return External;
13093
13094 // C99 inline semantics, where the symbol is not externally visible.
13095 return GVA_AvailableExternally;
13096 }
13097
13098 // Functions specified with extern and inline in -fms-compatibility mode
13099 // forcibly get emitted. While the body of the function cannot be later
13100 // replaced, the function definition cannot be discarded.
13101 if (FD->isMSExternInline())
13102 return GVA_StrongODR;
13103
13104 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13105 isa<CXXConstructorDecl>(Val: FD) &&
13106 cast<CXXConstructorDecl>(Val: FD)->isInheritingConstructor() &&
13107 !FD->hasAttr<DLLExportAttr>()) {
13108 // Both Clang and MSVC implement inherited constructors as forwarding
13109 // thunks that delegate to the base constructor. Keep non-dllexport
13110 // inheriting constructor thunks internal since they are not needed
13111 // outside the translation unit.
13112 //
13113 // dllexport inherited constructors are exempted so they are externally
13114 // visible, matching MSVC's export behavior. Inherited constructors
13115 // whose parameters prevent ABI-compatible forwarding (e.g. callee-
13116 // cleanup types) are excluded from export in Sema to avoid silent
13117 // runtime mismatches.
13118 return GVA_Internal;
13119 }
13120
13121 return GVA_DiscardableODR;
13122}
13123
13124static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context,
13125 const Decl *D, GVALinkage L) {
13126 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
13127 // dllexport/dllimport on inline functions.
13128 if (D->hasAttr<DLLImportAttr>()) {
13129 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
13130 return GVA_AvailableExternally;
13131 } else if (D->hasAttr<DLLExportAttr>()) {
13132 if (L == GVA_DiscardableODR)
13133 return GVA_StrongODR;
13134 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice) {
13135 // Device-side functions with __global__ attribute must always be
13136 // visible externally so they can be launched from host.
13137 if (D->hasAttr<CUDAGlobalAttr>() &&
13138 (L == GVA_DiscardableODR || L == GVA_Internal))
13139 return GVA_StrongODR;
13140 // Single source offloading languages like CUDA/HIP need to be able to
13141 // access static device variables from host code of the same compilation
13142 // unit. This is done by externalizing the static variable with a shared
13143 // name between the host and device compilation which is the same for the
13144 // same compilation unit whereas different among different compilation
13145 // units.
13146 if (Context.shouldExternalize(D))
13147 return GVA_StrongExternal;
13148 }
13149 return L;
13150}
13151
13152/// Adjust the GVALinkage for a declaration based on what an external AST source
13153/// knows about whether there can be other definitions of this declaration.
13154static GVALinkage
13155adjustGVALinkageForExternalDefinitionKind(const ASTContext &Ctx, const Decl *D,
13156 GVALinkage L) {
13157 ExternalASTSource *Source = Ctx.getExternalSource();
13158 if (!Source)
13159 return L;
13160
13161 switch (Source->hasExternalDefinitions(D)) {
13162 case ExternalASTSource::EK_Never:
13163 // Other translation units rely on us to provide the definition.
13164 if (L == GVA_DiscardableODR)
13165 return GVA_StrongODR;
13166 break;
13167
13168 case ExternalASTSource::EK_Always:
13169 return GVA_AvailableExternally;
13170
13171 case ExternalASTSource::EK_ReplyHazy:
13172 break;
13173 }
13174 return L;
13175}
13176
13177GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
13178 return adjustGVALinkageForExternalDefinitionKind(Ctx: *this, D: FD,
13179 L: adjustGVALinkageForAttributes(Context: *this, D: FD,
13180 L: basicGVALinkageForFunction(Context: *this, FD)));
13181}
13182
13183static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
13184 const VarDecl *VD) {
13185 // As an extension for interactive REPLs, make sure constant variables are
13186 // only emitted once instead of LinkageComputer::getLVForNamespaceScopeDecl
13187 // marking them as internal.
13188 if (Context.getLangOpts().CPlusPlus &&
13189 Context.getLangOpts().IncrementalExtensions &&
13190 VD->getType().isConstQualified() &&
13191 !VD->getType().isVolatileQualified() && !VD->isInline() &&
13192 !isa<VarTemplateSpecializationDecl>(Val: VD) && !VD->getDescribedVarTemplate())
13193 return GVA_DiscardableODR;
13194
13195 if (!VD->isExternallyVisible())
13196 return GVA_Internal;
13197
13198 if (VD->isStaticLocal()) {
13199 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
13200 while (LexicalContext && !isa<FunctionDecl>(Val: LexicalContext))
13201 LexicalContext = LexicalContext->getLexicalParent();
13202
13203 // ObjC Blocks can create local variables that don't have a FunctionDecl
13204 // LexicalContext.
13205 if (!LexicalContext)
13206 return GVA_DiscardableODR;
13207
13208 // Otherwise, let the static local variable inherit its linkage from the
13209 // nearest enclosing function.
13210 auto StaticLocalLinkage =
13211 Context.GetGVALinkageForFunction(FD: cast<FunctionDecl>(Val: LexicalContext));
13212
13213 // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
13214 // be emitted in any object with references to the symbol for the object it
13215 // contains, whether inline or out-of-line."
13216 // Similar behavior is observed with MSVC. An alternative ABI could use
13217 // StrongODR/AvailableExternally to match the function, but none are
13218 // known/supported currently.
13219 if (StaticLocalLinkage == GVA_StrongODR ||
13220 StaticLocalLinkage == GVA_AvailableExternally)
13221 return GVA_DiscardableODR;
13222 return StaticLocalLinkage;
13223 }
13224
13225 // MSVC treats in-class initialized static data members as definitions.
13226 // By giving them non-strong linkage, out-of-line definitions won't
13227 // cause link errors.
13228 if (Context.isMSStaticDataMemberInlineDefinition(VD))
13229 return GVA_DiscardableODR;
13230
13231 // Most non-template variables have strong linkage; inline variables are
13232 // linkonce_odr or (occasionally, for compatibility) weak_odr.
13233 GVALinkage StrongLinkage;
13234 switch (Context.getInlineVariableDefinitionKind(VD)) {
13235 case ASTContext::InlineVariableDefinitionKind::None:
13236 StrongLinkage = GVA_StrongExternal;
13237 break;
13238 case ASTContext::InlineVariableDefinitionKind::Weak:
13239 case ASTContext::InlineVariableDefinitionKind::WeakUnknown:
13240 StrongLinkage = GVA_DiscardableODR;
13241 break;
13242 case ASTContext::InlineVariableDefinitionKind::Strong:
13243 StrongLinkage = GVA_StrongODR;
13244 break;
13245 }
13246
13247 switch (VD->getTemplateSpecializationKind()) {
13248 case TSK_Undeclared:
13249 return StrongLinkage;
13250
13251 case TSK_ExplicitSpecialization:
13252 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13253 VD->isStaticDataMember()
13254 ? GVA_StrongODR
13255 : StrongLinkage;
13256
13257 case TSK_ExplicitInstantiationDefinition:
13258 return GVA_StrongODR;
13259
13260 case TSK_ExplicitInstantiationDeclaration:
13261 return GVA_AvailableExternally;
13262
13263 case TSK_ImplicitInstantiation:
13264 return GVA_DiscardableODR;
13265 }
13266
13267 llvm_unreachable("Invalid Linkage!");
13268}
13269
13270GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) const {
13271 return adjustGVALinkageForExternalDefinitionKind(Ctx: *this, D: VD,
13272 L: adjustGVALinkageForAttributes(Context: *this, D: VD,
13273 L: basicGVALinkageForVariable(Context: *this, VD)));
13274}
13275
13276bool ASTContext::DeclMustBeEmitted(const Decl *D) {
13277 if (const auto *VD = dyn_cast<VarDecl>(Val: D)) {
13278 if (!VD->isFileVarDecl())
13279 return false;
13280 // Global named register variables (GNU extension) are never emitted.
13281 if (VD->getStorageClass() == SC_Register)
13282 return false;
13283 if (VD->getDescribedVarTemplate() ||
13284 isa<VarTemplatePartialSpecializationDecl>(Val: VD))
13285 return false;
13286 } else if (const auto *FD = dyn_cast<FunctionDecl>(Val: D)) {
13287 // We never need to emit an uninstantiated function template.
13288 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
13289 return false;
13290 } else if (isa<PragmaCommentDecl>(Val: D))
13291 return true;
13292 else if (isa<PragmaDetectMismatchDecl>(Val: D))
13293 return true;
13294 else if (isa<OMPRequiresDecl>(Val: D))
13295 return true;
13296 else if (isa<OMPThreadPrivateDecl>(Val: D))
13297 return !D->getDeclContext()->isDependentContext();
13298 else if (isa<OMPAllocateDecl>(Val: D))
13299 return !D->getDeclContext()->isDependentContext();
13300 else if (isa<OMPDeclareReductionDecl>(Val: D) || isa<OMPDeclareMapperDecl>(Val: D))
13301 return !D->getDeclContext()->isDependentContext();
13302 else if (isa<ImportDecl>(Val: D))
13303 return true;
13304 else
13305 return false;
13306
13307 // If this is a member of a class template, we do not need to emit it.
13308 if (D->getDeclContext()->isDependentContext())
13309 return false;
13310
13311 // Weak references don't produce any output by themselves.
13312 if (D->hasAttr<WeakRefAttr>())
13313 return false;
13314
13315 // SYCL device compilation requires that functions defined with the
13316 // sycl_kernel_entry_point or sycl_external attributes be emitted. All
13317 // other entities are emitted only if they are used by a function
13318 // defined with one of those attributes.
13319 if (LangOpts.SYCLIsDevice)
13320 return isa<FunctionDecl>(Val: D) && (D->hasAttr<SYCLKernelEntryPointAttr>() ||
13321 D->hasAttr<SYCLExternalAttr>());
13322
13323 // Aliases and used decls are required.
13324 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
13325 return true;
13326
13327 if (const auto *FD = dyn_cast<FunctionDecl>(Val: D)) {
13328 // Forward declarations aren't required.
13329 if (!FD->doesThisDeclarationHaveABody())
13330 return FD->doesDeclarationForceExternallyVisibleDefinition();
13331
13332 // Constructors and destructors are required.
13333 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
13334 return true;
13335
13336 // The key function for a class is required. This rule only comes
13337 // into play when inline functions can be key functions, though.
13338 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
13339 if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: FD)) {
13340 const CXXRecordDecl *RD = MD->getParent();
13341 if (MD->isOutOfLine() && RD->isDynamicClass()) {
13342 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
13343 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
13344 return true;
13345 }
13346 }
13347 }
13348
13349 GVALinkage Linkage = GetGVALinkageForFunction(FD);
13350
13351 // static, static inline, always_inline, and extern inline functions can
13352 // always be deferred. Normal inline functions can be deferred in C99/C++.
13353 // Implicit template instantiations can also be deferred in C++.
13354 return !isDiscardableGVALinkage(L: Linkage);
13355 }
13356
13357 const auto *VD = cast<VarDecl>(Val: D);
13358 assert(VD->isFileVarDecl() && "Expected file scoped var");
13359
13360 // If the decl is marked as `declare target to`, it should be emitted for the
13361 // host and for the device.
13362 if (LangOpts.OpenMP &&
13363 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
13364 return true;
13365
13366 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
13367 !isMSStaticDataMemberInlineDefinition(VD))
13368 return false;
13369
13370 if (VD->shouldEmitInExternalSource())
13371 return false;
13372
13373 // Variables that can be needed in other TUs are required.
13374 auto Linkage = GetGVALinkageForVariable(VD);
13375 if (!isDiscardableGVALinkage(L: Linkage))
13376 return true;
13377
13378 // We never need to emit a variable that is available in another TU.
13379 if (Linkage == GVA_AvailableExternally)
13380 return false;
13381
13382 // Variables that have destruction with side-effects are required.
13383 if (VD->needsDestruction(Ctx: *this))
13384 return true;
13385
13386 // Variables that have initialization with side-effects are required.
13387 if (VD->hasInitWithSideEffects())
13388 return true;
13389
13390 // Likewise, variables with tuple-like bindings are required if their
13391 // bindings have side-effects.
13392 if (const auto *DD = dyn_cast<DecompositionDecl>(Val: VD)) {
13393 for (const auto *BD : DD->flat_bindings())
13394 if (const auto *BindingVD = BD->getHoldingVar())
13395 if (DeclMustBeEmitted(D: BindingVD))
13396 return true;
13397 }
13398
13399 return false;
13400}
13401
13402void ASTContext::forEachMultiversionedFunctionVersion(
13403 const FunctionDecl *FD,
13404 llvm::function_ref<void(FunctionDecl *)> Pred) const {
13405 assert(FD->isMultiVersion() && "Only valid for multiversioned functions");
13406 llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls;
13407 FD = FD->getMostRecentDecl();
13408 // FIXME: The order of traversal here matters and depends on the order of
13409 // lookup results, which happens to be (mostly) oldest-to-newest, but we
13410 // shouldn't rely on that.
13411 for (auto *CurDecl :
13412 FD->getDeclContext()->getRedeclContext()->lookup(Name: FD->getDeclName())) {
13413 FunctionDecl *CurFD = CurDecl->getAsFunction()->getMostRecentDecl();
13414 if (CurFD && hasSameType(T1: CurFD->getType(), T2: FD->getType()) &&
13415 SeenDecls.insert(V: CurFD).second) {
13416 Pred(CurFD);
13417 }
13418 }
13419}
13420
13421CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
13422 bool IsCXXMethod) const {
13423 // Pass through to the C++ ABI object
13424 if (IsCXXMethod)
13425 return ABI->getDefaultMethodCallConv(isVariadic: IsVariadic);
13426
13427 switch (LangOpts.getDefaultCallingConv()) {
13428 case LangOptions::DCC_None:
13429 break;
13430 case LangOptions::DCC_CDecl:
13431 return CC_C;
13432 case LangOptions::DCC_FastCall:
13433 if (getTargetInfo().hasFeature(Feature: "sse2") && !IsVariadic)
13434 return CC_X86FastCall;
13435 break;
13436 case LangOptions::DCC_StdCall:
13437 if (!IsVariadic)
13438 return CC_X86StdCall;
13439 break;
13440 case LangOptions::DCC_VectorCall:
13441 // __vectorcall cannot be applied to variadic functions.
13442 if (!IsVariadic)
13443 return CC_X86VectorCall;
13444 break;
13445 case LangOptions::DCC_RegCall:
13446 // __regcall cannot be applied to variadic functions.
13447 if (!IsVariadic)
13448 return CC_X86RegCall;
13449 break;
13450 case LangOptions::DCC_RtdCall:
13451 if (!IsVariadic)
13452 return CC_M68kRTD;
13453 break;
13454 }
13455 return Target->getDefaultCallingConv();
13456}
13457
13458bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
13459 // Pass through to the C++ ABI object
13460 return ABI->isNearlyEmpty(RD);
13461}
13462
13463VTableContextBase *ASTContext::getVTableContext() {
13464 if (!VTContext) {
13465 auto ABI = Target->getCXXABI();
13466 if (ABI.isMicrosoft())
13467 VTContext.reset(p: new MicrosoftVTableContext(*this));
13468 else {
13469 VTContext.reset(p: new ItaniumVTableContext(*this));
13470 }
13471 }
13472 return VTContext.get();
13473}
13474
13475MangleContext *ASTContext::createMangleContext(const TargetInfo *T) {
13476 if (!T)
13477 T = Target;
13478 switch (T->getCXXABI().getKind()) {
13479 case TargetCXXABI::AppleARM64:
13480 case TargetCXXABI::Fuchsia:
13481 case TargetCXXABI::GenericAArch64:
13482 case TargetCXXABI::GenericItanium:
13483 case TargetCXXABI::GenericARM:
13484 case TargetCXXABI::GenericMIPS:
13485 case TargetCXXABI::iOS:
13486 case TargetCXXABI::WebAssembly:
13487 case TargetCXXABI::WatchOS:
13488 case TargetCXXABI::XL:
13489 return ItaniumMangleContext::create(Context&: *this, Diags&: getDiagnostics());
13490 case TargetCXXABI::Microsoft:
13491 return MicrosoftMangleContext::create(Context&: *this, Diags&: getDiagnostics());
13492 }
13493 llvm_unreachable("Unsupported ABI");
13494}
13495
13496MangleContext *ASTContext::createDeviceMangleContext(const TargetInfo &T) {
13497 assert(T.getCXXABI().getKind() != TargetCXXABI::Microsoft &&
13498 "Device mangle context does not support Microsoft mangling.");
13499 switch (T.getCXXABI().getKind()) {
13500 case TargetCXXABI::AppleARM64:
13501 case TargetCXXABI::Fuchsia:
13502 case TargetCXXABI::GenericAArch64:
13503 case TargetCXXABI::GenericItanium:
13504 case TargetCXXABI::GenericARM:
13505 case TargetCXXABI::GenericMIPS:
13506 case TargetCXXABI::iOS:
13507 case TargetCXXABI::WebAssembly:
13508 case TargetCXXABI::WatchOS:
13509 case TargetCXXABI::XL:
13510 return ItaniumMangleContext::create(
13511 Context&: *this, Diags&: getDiagnostics(),
13512 Discriminator: [](ASTContext &, const NamedDecl *ND) -> UnsignedOrNone {
13513 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: ND))
13514 return RD->getDeviceLambdaManglingNumber();
13515 return std::nullopt;
13516 },
13517 /*IsAux=*/true);
13518 case TargetCXXABI::Microsoft:
13519 return MicrosoftMangleContext::create(Context&: *this, Diags&: getDiagnostics(),
13520 /*IsAux=*/true);
13521 }
13522 llvm_unreachable("Unsupported ABI");
13523}
13524
13525MangleContext *ASTContext::cudaNVInitDeviceMC() {
13526 // If the host and device have different C++ ABIs, mark it as the device
13527 // mangle context so that the mangling needs to retrieve the additional
13528 // device lambda mangling number instead of the regular host one.
13529 if (getAuxTargetInfo() && getTargetInfo().getCXXABI().isMicrosoft() &&
13530 getAuxTargetInfo()->getCXXABI().isItaniumFamily()) {
13531 return createDeviceMangleContext(T: *getAuxTargetInfo());
13532 }
13533
13534 return createMangleContext(T: getAuxTargetInfo());
13535}
13536
13537CXXABI::~CXXABI() = default;
13538
13539size_t ASTContext::getSideTableAllocatedMemory() const {
13540 return ASTRecordLayouts.getMemorySize() +
13541 llvm::capacity_in_bytes(X: ObjCLayouts) +
13542 llvm::capacity_in_bytes(X: KeyFunctions) +
13543 llvm::capacity_in_bytes(X: ObjCImpls) +
13544 llvm::capacity_in_bytes(X: BlockVarCopyInits) +
13545 llvm::capacity_in_bytes(X: DeclAttrs) +
13546 llvm::capacity_in_bytes(X: TemplateOrInstantiation) +
13547 llvm::capacity_in_bytes(X: InstantiatedFromUsingDecl) +
13548 llvm::capacity_in_bytes(X: InstantiatedFromUsingShadowDecl) +
13549 llvm::capacity_in_bytes(X: InstantiatedFromUnnamedFieldDecl) +
13550 llvm::capacity_in_bytes(X: OverriddenMethods) +
13551 llvm::capacity_in_bytes(X: Types) +
13552 llvm::capacity_in_bytes(x: VariableArrayTypes);
13553}
13554
13555/// getIntTypeForBitwidth -
13556/// sets integer QualTy according to specified details:
13557/// bitwidth, signed/unsigned.
13558/// Returns empty type if there is no appropriate target types.
13559QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
13560 unsigned Signed) const {
13561 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(BitWidth: DestWidth, IsSigned: Signed);
13562 CanQualType QualTy = getFromTargetType(Type: Ty);
13563 if (!QualTy && DestWidth == 128)
13564 return Signed ? Int128Ty : UnsignedInt128Ty;
13565 return QualTy;
13566}
13567
13568QualType ASTContext::getLeastIntTypeForBitwidth(unsigned DestWidth,
13569 unsigned Signed) const {
13570 return getFromTargetType(
13571 Type: getTargetInfo().getLeastIntTypeByWidth(BitWidth: DestWidth, IsSigned: Signed));
13572}
13573
13574/// getRealTypeForBitwidth -
13575/// sets floating point QualTy according to specified bitwidth.
13576/// Returns empty type if there is no appropriate target types.
13577QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth,
13578 FloatModeKind ExplicitType) const {
13579 FloatModeKind Ty =
13580 getTargetInfo().getRealTypeByWidth(BitWidth: DestWidth, ExplicitType);
13581 switch (Ty) {
13582 case FloatModeKind::Half:
13583 return HalfTy;
13584 case FloatModeKind::Float:
13585 return FloatTy;
13586 case FloatModeKind::Double:
13587 return DoubleTy;
13588 case FloatModeKind::LongDouble:
13589 return LongDoubleTy;
13590 case FloatModeKind::Float128:
13591 return Float128Ty;
13592 case FloatModeKind::Ibm128:
13593 return Ibm128Ty;
13594 case FloatModeKind::NoFloat:
13595 return {};
13596 }
13597
13598 llvm_unreachable("Unhandled TargetInfo::RealType value");
13599}
13600
13601void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
13602 if (Number <= 1)
13603 return;
13604
13605 MangleNumbers[ND] = Number;
13606
13607 if (Listener)
13608 Listener->AddedManglingNumber(D: ND, Number);
13609}
13610
13611unsigned ASTContext::getManglingNumber(const NamedDecl *ND,
13612 bool ForAuxTarget) const {
13613 auto I = MangleNumbers.find(Key: ND);
13614 unsigned Res = I != MangleNumbers.end() ? I->second : 1;
13615 // CUDA/HIP host compilation encodes host and device mangling numbers
13616 // as lower and upper half of 32 bit integer.
13617 if (LangOpts.CUDA && !LangOpts.CUDAIsDevice) {
13618 Res = ForAuxTarget ? Res >> 16 : Res & 0xFFFF;
13619 } else {
13620 assert(!ForAuxTarget && "Only CUDA/HIP host compilation supports mangling "
13621 "number for aux target");
13622 }
13623 return Res > 1 ? Res : 1;
13624}
13625
13626void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
13627 if (Number <= 1)
13628 return;
13629
13630 StaticLocalNumbers[VD] = Number;
13631
13632 if (Listener)
13633 Listener->AddedStaticLocalNumbers(D: VD, Number);
13634}
13635
13636unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
13637 auto I = StaticLocalNumbers.find(Key: VD);
13638 return I != StaticLocalNumbers.end() ? I->second : 1;
13639}
13640
13641void ASTContext::setIsDestroyingOperatorDelete(const FunctionDecl *FD,
13642 bool IsDestroying) {
13643 if (!IsDestroying) {
13644 assert(!DestroyingOperatorDeletes.contains(FD->getCanonicalDecl()));
13645 return;
13646 }
13647 DestroyingOperatorDeletes.insert(V: FD->getCanonicalDecl());
13648}
13649
13650bool ASTContext::isDestroyingOperatorDelete(const FunctionDecl *FD) const {
13651 return DestroyingOperatorDeletes.contains(V: FD->getCanonicalDecl());
13652}
13653
13654void ASTContext::setIsTypeAwareOperatorNewOrDelete(const FunctionDecl *FD,
13655 bool IsTypeAware) {
13656 if (!IsTypeAware) {
13657 assert(!TypeAwareOperatorNewAndDeletes.contains(FD->getCanonicalDecl()));
13658 return;
13659 }
13660 TypeAwareOperatorNewAndDeletes.insert(V: FD->getCanonicalDecl());
13661}
13662
13663bool ASTContext::isTypeAwareOperatorNewOrDelete(const FunctionDecl *FD) const {
13664 return TypeAwareOperatorNewAndDeletes.contains(V: FD->getCanonicalDecl());
13665}
13666
13667void ASTContext::addOperatorDeleteForVDtor(const CXXDestructorDecl *Dtor,
13668 FunctionDecl *OperatorDelete,
13669 OperatorDeleteKind K) const {
13670 switch (K) {
13671 case OperatorDeleteKind::Regular:
13672 OperatorDeletesForVirtualDtor[Dtor->getCanonicalDecl()] = OperatorDelete;
13673 break;
13674 case OperatorDeleteKind::GlobalRegular:
13675 GlobalOperatorDeletesForVirtualDtor[Dtor->getCanonicalDecl()] =
13676 OperatorDelete;
13677 break;
13678 case OperatorDeleteKind::Array:
13679 ArrayOperatorDeletesForVirtualDtor[Dtor->getCanonicalDecl()] =
13680 OperatorDelete;
13681 break;
13682 case OperatorDeleteKind::ArrayGlobal:
13683 GlobalArrayOperatorDeletesForVirtualDtor[Dtor->getCanonicalDecl()] =
13684 OperatorDelete;
13685 break;
13686 }
13687}
13688
13689bool ASTContext::dtorHasOperatorDelete(const CXXDestructorDecl *Dtor,
13690 OperatorDeleteKind K) const {
13691 switch (K) {
13692 case OperatorDeleteKind::Regular:
13693 return OperatorDeletesForVirtualDtor.contains(Val: Dtor->getCanonicalDecl());
13694 case OperatorDeleteKind::GlobalRegular:
13695 return GlobalOperatorDeletesForVirtualDtor.contains(
13696 Val: Dtor->getCanonicalDecl());
13697 case OperatorDeleteKind::Array:
13698 return ArrayOperatorDeletesForVirtualDtor.contains(
13699 Val: Dtor->getCanonicalDecl());
13700 case OperatorDeleteKind::ArrayGlobal:
13701 return GlobalArrayOperatorDeletesForVirtualDtor.contains(
13702 Val: Dtor->getCanonicalDecl());
13703 }
13704 return false;
13705}
13706
13707FunctionDecl *
13708ASTContext::getOperatorDeleteForVDtor(const CXXDestructorDecl *Dtor,
13709 OperatorDeleteKind K) const {
13710 const CXXDestructorDecl *Canon = Dtor->getCanonicalDecl();
13711 switch (K) {
13712 case OperatorDeleteKind::Regular:
13713 if (OperatorDeletesForVirtualDtor.contains(Val: Canon))
13714 return OperatorDeletesForVirtualDtor[Canon];
13715 return nullptr;
13716 case OperatorDeleteKind::GlobalRegular:
13717 if (GlobalOperatorDeletesForVirtualDtor.contains(Val: Canon))
13718 return GlobalOperatorDeletesForVirtualDtor[Canon];
13719 return nullptr;
13720 case OperatorDeleteKind::Array:
13721 if (ArrayOperatorDeletesForVirtualDtor.contains(Val: Canon))
13722 return ArrayOperatorDeletesForVirtualDtor[Canon];
13723 return nullptr;
13724 case OperatorDeleteKind::ArrayGlobal:
13725 if (GlobalArrayOperatorDeletesForVirtualDtor.contains(Val: Canon))
13726 return GlobalArrayOperatorDeletesForVirtualDtor[Canon];
13727 return nullptr;
13728 }
13729 return nullptr;
13730}
13731
13732bool ASTContext::classMaybeNeedsVectorDeletingDestructor(
13733 const CXXRecordDecl *RD) {
13734 if (!getTargetInfo().emitVectorDeletingDtors(getLangOpts()))
13735 return false;
13736
13737 return MaybeRequireVectorDeletingDtor.count(V: RD);
13738}
13739
13740void ASTContext::setClassMaybeNeedsVectorDeletingDestructor(
13741 const CXXRecordDecl *RD) {
13742 if (!getTargetInfo().emitVectorDeletingDtors(getLangOpts()))
13743 return;
13744
13745 MaybeRequireVectorDeletingDtor.insert(V: RD);
13746}
13747
13748MangleNumberingContext &
13749ASTContext::getManglingNumberContext(const DeclContext *DC) {
13750 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
13751 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
13752 if (!MCtx)
13753 MCtx = createMangleNumberingContext();
13754 return *MCtx;
13755}
13756
13757MangleNumberingContext &
13758ASTContext::getManglingNumberContext(NeedExtraManglingDecl_t, const Decl *D) {
13759 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
13760 std::unique_ptr<MangleNumberingContext> &MCtx =
13761 ExtraMangleNumberingContexts[D];
13762 if (!MCtx)
13763 MCtx = createMangleNumberingContext();
13764 return *MCtx;
13765}
13766
13767std::unique_ptr<MangleNumberingContext>
13768ASTContext::createMangleNumberingContext() const {
13769 return ABI->createMangleNumberingContext();
13770}
13771
13772const CXXConstructorDecl *
13773ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
13774 return ABI->getCopyConstructorForExceptionObject(
13775 cast<CXXRecordDecl>(Val: RD->getFirstDecl()));
13776}
13777
13778void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
13779 CXXConstructorDecl *CD) {
13780 return ABI->addCopyConstructorForExceptionObject(
13781 cast<CXXRecordDecl>(Val: RD->getFirstDecl()),
13782 cast<CXXConstructorDecl>(Val: CD->getFirstDecl()));
13783}
13784
13785void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD,
13786 TypedefNameDecl *DD) {
13787 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
13788}
13789
13790TypedefNameDecl *
13791ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) {
13792 return ABI->getTypedefNameForUnnamedTagDecl(TD);
13793}
13794
13795void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD,
13796 DeclaratorDecl *DD) {
13797 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
13798}
13799
13800DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) {
13801 return ABI->getDeclaratorForUnnamedTagDecl(TD);
13802}
13803
13804void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
13805 ParamIndices[D] = index;
13806}
13807
13808unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
13809 ParameterIndexTable::const_iterator I = ParamIndices.find(Val: D);
13810 assert(I != ParamIndices.end() &&
13811 "ParmIndices lacks entry set by ParmVarDecl");
13812 return I->second;
13813}
13814
13815QualType ASTContext::getStringLiteralArrayType(QualType EltTy,
13816 unsigned Length) const {
13817 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
13818 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
13819 EltTy = EltTy.withConst();
13820
13821 EltTy = adjustStringLiteralBaseType(Ty: EltTy);
13822
13823 // Get an array type for the string, according to C99 6.4.5. This includes
13824 // the null terminator character.
13825 return getConstantArrayType(EltTy, ArySizeIn: llvm::APInt(32, Length + 1), SizeExpr: nullptr,
13826 ASM: ArraySizeModifier::Normal, /*IndexTypeQuals*/ 0);
13827}
13828
13829StringLiteral *
13830ASTContext::getPredefinedStringLiteralFromCache(StringRef Key) const {
13831 StringLiteral *&Result = StringLiteralCache[Key];
13832 if (!Result)
13833 Result = StringLiteral::Create(
13834 Ctx: *this, Str: Key, Kind: StringLiteralKind::Ordinary,
13835 /*Pascal*/ false, Ty: getStringLiteralArrayType(EltTy: CharTy, Length: Key.size()),
13836 Locs: SourceLocation());
13837 return Result;
13838}
13839
13840MSGuidDecl *
13841ASTContext::getMSGuidDecl(MSGuidDecl::Parts Parts) const {
13842 assert(MSGuidTagDecl && "building MS GUID without MS extensions?");
13843
13844 llvm::FoldingSetNodeID ID;
13845 MSGuidDecl::Profile(ID, P: Parts);
13846
13847 void *InsertPos;
13848 if (MSGuidDecl *Existing = MSGuidDecls.FindNodeOrInsertPos(ID, InsertPos))
13849 return Existing;
13850
13851 QualType GUIDType = getMSGuidType().withConst();
13852 MSGuidDecl *New = MSGuidDecl::Create(C: *this, T: GUIDType, P: Parts);
13853 MSGuidDecls.InsertNode(N: New, InsertPos);
13854 return New;
13855}
13856
13857UnnamedGlobalConstantDecl *
13858ASTContext::getUnnamedGlobalConstantDecl(QualType Ty,
13859 const APValue &APVal) const {
13860 llvm::FoldingSetNodeID ID;
13861 UnnamedGlobalConstantDecl::Profile(ID, Ty, APVal);
13862
13863 void *InsertPos;
13864 if (UnnamedGlobalConstantDecl *Existing =
13865 UnnamedGlobalConstantDecls.FindNodeOrInsertPos(ID, InsertPos))
13866 return Existing;
13867
13868 UnnamedGlobalConstantDecl *New =
13869 UnnamedGlobalConstantDecl::Create(C: *this, T: Ty, APVal);
13870 UnnamedGlobalConstantDecls.InsertNode(N: New, InsertPos);
13871 return New;
13872}
13873
13874TemplateParamObjectDecl *
13875ASTContext::getTemplateParamObjectDecl(QualType T, const APValue &V) const {
13876 assert(T->isRecordType() && "template param object of unexpected type");
13877
13878 // C++ [temp.param]p8:
13879 // [...] a static storage duration object of type 'const T' [...]
13880 T.addConst();
13881
13882 llvm::FoldingSetNodeID ID;
13883 TemplateParamObjectDecl::Profile(ID, T, V);
13884
13885 void *InsertPos;
13886 if (TemplateParamObjectDecl *Existing =
13887 TemplateParamObjectDecls.FindNodeOrInsertPos(ID, InsertPos))
13888 return Existing;
13889
13890 TemplateParamObjectDecl *New = TemplateParamObjectDecl::Create(C: *this, T, V);
13891 TemplateParamObjectDecls.InsertNode(N: New, InsertPos);
13892 return New;
13893}
13894
13895bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
13896 const llvm::Triple &T = getTargetInfo().getTriple();
13897 if (!T.isOSDarwin())
13898 return false;
13899
13900 if (!(T.isiOS() && T.isOSVersionLT(Major: 7)) &&
13901 !(T.isMacOSX() && T.isOSVersionLT(Major: 10, Minor: 9)))
13902 return false;
13903
13904 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
13905 CharUnits sizeChars = getTypeSizeInChars(T: AtomicTy);
13906 uint64_t Size = sizeChars.getQuantity();
13907 CharUnits alignChars = getTypeAlignInChars(T: AtomicTy);
13908 unsigned Align = alignChars.getQuantity();
13909 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
13910 return (Size != Align || toBits(CharSize: sizeChars) > MaxInlineWidthInBits);
13911}
13912
13913bool
13914ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
13915 const ObjCMethodDecl *MethodImpl) {
13916 // No point trying to match an unavailable/deprecated mothod.
13917 if (MethodDecl->hasAttr<UnavailableAttr>()
13918 || MethodDecl->hasAttr<DeprecatedAttr>())
13919 return false;
13920 if (MethodDecl->getObjCDeclQualifier() !=
13921 MethodImpl->getObjCDeclQualifier())
13922 return false;
13923 if (!hasSameType(T1: MethodDecl->getReturnType(), T2: MethodImpl->getReturnType()))
13924 return false;
13925
13926 if (MethodDecl->param_size() != MethodImpl->param_size())
13927 return false;
13928
13929 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
13930 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
13931 EF = MethodDecl->param_end();
13932 IM != EM && IF != EF; ++IM, ++IF) {
13933 const ParmVarDecl *DeclVar = (*IF);
13934 const ParmVarDecl *ImplVar = (*IM);
13935 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
13936 return false;
13937 if (!hasSameType(T1: DeclVar->getType(), T2: ImplVar->getType()))
13938 return false;
13939 }
13940
13941 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
13942}
13943
13944uint64_t ASTContext::getTargetNullPointerValue(QualType QT) const {
13945 LangAS AS;
13946 if (QT->getUnqualifiedDesugaredType()->isNullPtrType())
13947 AS = LangAS::Default;
13948 else
13949 AS = QT->getPointeeType().getAddressSpace();
13950
13951 return getTargetInfo().getNullPointerValue(AddrSpace: AS);
13952}
13953
13954unsigned ASTContext::getTargetAddressSpace(LangAS AS) const {
13955 return getTargetInfo().getTargetAddressSpace(AS);
13956}
13957
13958bool ASTContext::hasSameExpr(const Expr *X, const Expr *Y) const {
13959 if (X == Y)
13960 return true;
13961 if (!X || !Y)
13962 return false;
13963 llvm::FoldingSetNodeID IDX, IDY;
13964 X->Profile(ID&: IDX, Context: *this, /*Canonical=*/true);
13965 Y->Profile(ID&: IDY, Context: *this, /*Canonical=*/true);
13966 return IDX == IDY;
13967}
13968
13969// The getCommon* helpers return, for given 'same' X and Y entities given as
13970// inputs, another entity which is also the 'same' as the inputs, but which
13971// is closer to the canonical form of the inputs, each according to a given
13972// criteria.
13973// The getCommon*Checked variants are 'null inputs not-allowed' equivalents of
13974// the regular ones.
13975
13976static Decl *getCommonDecl(Decl *X, Decl *Y) {
13977 if (!declaresSameEntity(D1: X, D2: Y))
13978 return nullptr;
13979 for (const Decl *DX : X->redecls()) {
13980 // If we reach Y before reaching the first decl, that means X is older.
13981 if (DX == Y)
13982 return X;
13983 // If we reach the first decl, then Y is older.
13984 if (DX->isFirstDecl())
13985 return Y;
13986 }
13987 llvm_unreachable("Corrupt redecls chain");
13988}
13989
13990template <class T, std::enable_if_t<std::is_base_of_v<Decl, T>, bool> = true>
13991static T *getCommonDecl(T *X, T *Y) {
13992 return cast_or_null<T>(
13993 getCommonDecl(X: const_cast<Decl *>(cast_or_null<Decl>(X)),
13994 Y: const_cast<Decl *>(cast_or_null<Decl>(Y))));
13995}
13996
13997template <class T, std::enable_if_t<std::is_base_of_v<Decl, T>, bool> = true>
13998static T *getCommonDeclChecked(T *X, T *Y) {
13999 return cast<T>(getCommonDecl(X: const_cast<Decl *>(cast<Decl>(X)),
14000 Y: const_cast<Decl *>(cast<Decl>(Y))));
14001}
14002
14003static TemplateName getCommonTemplateName(const ASTContext &Ctx, TemplateName X,
14004 TemplateName Y,
14005 bool IgnoreDeduced = false) {
14006 if (X.getAsVoidPointer() == Y.getAsVoidPointer())
14007 return X;
14008 // FIXME: There are cases here where we could find a common template name
14009 // with more sugar. For example one could be a SubstTemplateTemplate*
14010 // replacing the other.
14011 TemplateName CX = Ctx.getCanonicalTemplateName(Name: X, IgnoreDeduced);
14012 if (CX.getAsVoidPointer() !=
14013 Ctx.getCanonicalTemplateName(Name: Y).getAsVoidPointer())
14014 return TemplateName();
14015 return CX;
14016}
14017
14018static TemplateName getCommonTemplateNameChecked(const ASTContext &Ctx,
14019 TemplateName X, TemplateName Y,
14020 bool IgnoreDeduced) {
14021 TemplateName R = getCommonTemplateName(Ctx, X, Y, IgnoreDeduced);
14022 assert(R.getAsVoidPointer() != nullptr);
14023 return R;
14024}
14025
14026static auto getCommonTypes(const ASTContext &Ctx, ArrayRef<QualType> Xs,
14027 ArrayRef<QualType> Ys, bool Unqualified = false) {
14028 assert(Xs.size() == Ys.size());
14029 SmallVector<QualType, 8> Rs(Xs.size());
14030 for (size_t I = 0; I < Rs.size(); ++I)
14031 Rs[I] = Ctx.getCommonSugaredType(X: Xs[I], Y: Ys[I], Unqualified);
14032 return Rs;
14033}
14034
14035template <class T>
14036static SourceLocation getCommonAttrLoc(const T *X, const T *Y) {
14037 return X->getAttributeLoc() == Y->getAttributeLoc() ? X->getAttributeLoc()
14038 : SourceLocation();
14039}
14040
14041static TemplateArgument getCommonTemplateArgument(const ASTContext &Ctx,
14042 const TemplateArgument &X,
14043 const TemplateArgument &Y) {
14044 if (X.getKind() != Y.getKind())
14045 return TemplateArgument();
14046
14047 switch (X.getKind()) {
14048 case TemplateArgument::ArgKind::Type:
14049 if (!Ctx.hasSameType(T1: X.getAsType(), T2: Y.getAsType()))
14050 return TemplateArgument();
14051 return TemplateArgument(
14052 Ctx.getCommonSugaredType(X: X.getAsType(), Y: Y.getAsType()));
14053 case TemplateArgument::ArgKind::NullPtr:
14054 if (!Ctx.hasSameType(T1: X.getNullPtrType(), T2: Y.getNullPtrType()))
14055 return TemplateArgument();
14056 return TemplateArgument(
14057 Ctx.getCommonSugaredType(X: X.getNullPtrType(), Y: Y.getNullPtrType()),
14058 /*Unqualified=*/true);
14059 case TemplateArgument::ArgKind::Expression:
14060 if (!Ctx.hasSameType(T1: X.getAsExpr()->getType(), T2: Y.getAsExpr()->getType()))
14061 return TemplateArgument();
14062 // FIXME: Try to keep the common sugar.
14063 return X;
14064 case TemplateArgument::ArgKind::Template: {
14065 TemplateName TX = X.getAsTemplate(), TY = Y.getAsTemplate();
14066 TemplateName CTN = ::getCommonTemplateName(Ctx, X: TX, Y: TY);
14067 if (!CTN.getAsVoidPointer())
14068 return TemplateArgument();
14069 return TemplateArgument(CTN);
14070 }
14071 case TemplateArgument::ArgKind::TemplateExpansion: {
14072 TemplateName TX = X.getAsTemplateOrTemplatePattern(),
14073 TY = Y.getAsTemplateOrTemplatePattern();
14074 TemplateName CTN = ::getCommonTemplateName(Ctx, X: TX, Y: TY);
14075 if (!CTN.getAsVoidPointer())
14076 return TemplateName();
14077 auto NExpX = X.getNumTemplateExpansions();
14078 assert(NExpX == Y.getNumTemplateExpansions());
14079 return TemplateArgument(CTN, NExpX);
14080 }
14081 default:
14082 // FIXME: Handle the other argument kinds.
14083 return X;
14084 }
14085}
14086
14087static bool getCommonTemplateArguments(const ASTContext &Ctx,
14088 SmallVectorImpl<TemplateArgument> &R,
14089 ArrayRef<TemplateArgument> Xs,
14090 ArrayRef<TemplateArgument> Ys) {
14091 if (Xs.size() != Ys.size())
14092 return true;
14093 R.resize(N: Xs.size());
14094 for (size_t I = 0; I < R.size(); ++I) {
14095 R[I] = getCommonTemplateArgument(Ctx, X: Xs[I], Y: Ys[I]);
14096 if (R[I].isNull())
14097 return true;
14098 }
14099 return false;
14100}
14101
14102static auto getCommonTemplateArguments(const ASTContext &Ctx,
14103 ArrayRef<TemplateArgument> Xs,
14104 ArrayRef<TemplateArgument> Ys) {
14105 SmallVector<TemplateArgument, 8> R;
14106 bool Different = getCommonTemplateArguments(Ctx, R, Xs, Ys);
14107 assert(!Different);
14108 (void)Different;
14109 return R;
14110}
14111
14112template <class T>
14113static ElaboratedTypeKeyword getCommonTypeKeyword(const T *X, const T *Y,
14114 bool IsSame) {
14115 ElaboratedTypeKeyword KX = X->getKeyword(), KY = Y->getKeyword();
14116 if (KX == KY)
14117 return KX;
14118 KX = getCanonicalElaboratedTypeKeyword(Keyword: KX);
14119 assert(!IsSame || KX == getCanonicalElaboratedTypeKeyword(KY));
14120 return KX;
14121}
14122
14123/// Returns a NestedNameSpecifier which has only the common sugar
14124/// present in both NNS1 and NNS2.
14125static NestedNameSpecifier getCommonNNS(const ASTContext &Ctx,
14126 NestedNameSpecifier NNS1,
14127 NestedNameSpecifier NNS2, bool IsSame) {
14128 // If they are identical, all sugar is common.
14129 if (NNS1 == NNS2)
14130 return NNS1;
14131
14132 // IsSame implies both Qualifiers are equivalent.
14133 NestedNameSpecifier Canon = NNS1.getCanonical();
14134 if (Canon != NNS2.getCanonical()) {
14135 assert(!IsSame && "Should be the same NestedNameSpecifier");
14136 // If they are not the same, there is nothing to unify.
14137 return std::nullopt;
14138 }
14139
14140 NestedNameSpecifier R = std::nullopt;
14141 NestedNameSpecifier::Kind Kind = NNS1.getKind();
14142 assert(Kind == NNS2.getKind());
14143 switch (Kind) {
14144 case NestedNameSpecifier::Kind::Namespace: {
14145 auto [Namespace1, Prefix1] = NNS1.getAsNamespaceAndPrefix();
14146 auto [Namespace2, Prefix2] = NNS2.getAsNamespaceAndPrefix();
14147 auto Kind = Namespace1->getKind();
14148 if (Kind != Namespace2->getKind() ||
14149 (Kind == Decl::NamespaceAlias &&
14150 !declaresSameEntity(D1: Namespace1, D2: Namespace2))) {
14151 R = NestedNameSpecifier(
14152 Ctx,
14153 ::getCommonDeclChecked(X: Namespace1->getNamespace(),
14154 Y: Namespace2->getNamespace()),
14155 /*Prefix=*/std::nullopt);
14156 break;
14157 }
14158 // The prefixes for namespaces are not significant, its declaration
14159 // identifies it uniquely.
14160 NestedNameSpecifier Prefix = ::getCommonNNS(Ctx, NNS1: Prefix1, NNS2: Prefix2,
14161 /*IsSame=*/false);
14162 R = NestedNameSpecifier(Ctx, ::getCommonDeclChecked(X: Namespace1, Y: Namespace2),
14163 Prefix);
14164 break;
14165 }
14166 case NestedNameSpecifier::Kind::Type: {
14167 const Type *T1 = NNS1.getAsType(), *T2 = NNS2.getAsType();
14168 const Type *T = Ctx.getCommonSugaredType(X: QualType(T1, 0), Y: QualType(T2, 0),
14169 /*Unqualified=*/true)
14170 .getTypePtr();
14171 R = NestedNameSpecifier(T);
14172 break;
14173 }
14174 case NestedNameSpecifier::Kind::MicrosoftSuper: {
14175 // FIXME: Can __super even be used with data members?
14176 // If it's only usable in functions, we will never see it here,
14177 // unless we save the qualifiers used in function types.
14178 // In that case, it might be possible NNS2 is a type,
14179 // in which case we should degrade the result to
14180 // a CXXRecordType.
14181 R = NestedNameSpecifier(getCommonDeclChecked(X: NNS1.getAsMicrosoftSuper(),
14182 Y: NNS2.getAsMicrosoftSuper()));
14183 break;
14184 }
14185 case NestedNameSpecifier::Kind::Null:
14186 case NestedNameSpecifier::Kind::Global:
14187 // These are singletons.
14188 llvm_unreachable("singletons did not compare equal");
14189 }
14190 assert(R.getCanonical() == Canon);
14191 return R;
14192}
14193
14194template <class T>
14195static NestedNameSpecifier getCommonQualifier(const ASTContext &Ctx, const T *X,
14196 const T *Y, bool IsSame) {
14197 return ::getCommonNNS(Ctx, NNS1: X->getQualifier(), NNS2: Y->getQualifier(), IsSame);
14198}
14199
14200template <class T>
14201static QualType getCommonElementType(const ASTContext &Ctx, const T *X,
14202 const T *Y) {
14203 return Ctx.getCommonSugaredType(X: X->getElementType(), Y: Y->getElementType());
14204}
14205
14206static QualType getCommonTypeWithQualifierLifting(const ASTContext &Ctx,
14207 QualType X, QualType Y,
14208 Qualifiers &QX,
14209 Qualifiers &QY) {
14210 QualType R = Ctx.getCommonSugaredType(X, Y,
14211 /*Unqualified=*/true);
14212 // Qualifiers common to both element types.
14213 Qualifiers RQ = R.getQualifiers();
14214 // For each side, move to the top level any qualifiers which are not common to
14215 // both element types. The caller must assume top level qualifiers might
14216 // be different, even if they are the same type, and can be treated as sugar.
14217 QX += X.getQualifiers() - RQ;
14218 QY += Y.getQualifiers() - RQ;
14219 return R;
14220}
14221
14222template <class T>
14223static QualType getCommonArrayElementType(const ASTContext &Ctx, const T *X,
14224 Qualifiers &QX, const T *Y,
14225 Qualifiers &QY) {
14226 return getCommonTypeWithQualifierLifting(Ctx, X->getElementType(),
14227 Y->getElementType(), QX, QY);
14228}
14229
14230template <class T>
14231static QualType getCommonPointeeType(const ASTContext &Ctx, const T *X,
14232 const T *Y) {
14233 return Ctx.getCommonSugaredType(X: X->getPointeeType(), Y: Y->getPointeeType());
14234}
14235
14236template <class T>
14237static auto *getCommonSizeExpr(const ASTContext &Ctx, T *X, T *Y) {
14238 assert(Ctx.hasSameExpr(X->getSizeExpr(), Y->getSizeExpr()));
14239 return X->getSizeExpr();
14240}
14241
14242static auto getCommonSizeModifier(const ArrayType *X, const ArrayType *Y) {
14243 assert(X->getSizeModifier() == Y->getSizeModifier());
14244 return X->getSizeModifier();
14245}
14246
14247static auto getCommonIndexTypeCVRQualifiers(const ArrayType *X,
14248 const ArrayType *Y) {
14249 assert(X->getIndexTypeCVRQualifiers() == Y->getIndexTypeCVRQualifiers());
14250 return X->getIndexTypeCVRQualifiers();
14251}
14252
14253// Merges two type lists such that the resulting vector will contain
14254// each type (in a canonical sense) only once, in the order they appear
14255// from X to Y. If they occur in both X and Y, the result will contain
14256// the common sugared type between them.
14257static void mergeTypeLists(const ASTContext &Ctx,
14258 SmallVectorImpl<QualType> &Out, ArrayRef<QualType> X,
14259 ArrayRef<QualType> Y) {
14260 llvm::DenseMap<QualType, unsigned> Found;
14261 for (auto Ts : {X, Y}) {
14262 for (QualType T : Ts) {
14263 auto Res = Found.try_emplace(Key: Ctx.getCanonicalType(T), Args: Out.size());
14264 if (!Res.second) {
14265 QualType &U = Out[Res.first->second];
14266 U = Ctx.getCommonSugaredType(X: U, Y: T);
14267 } else {
14268 Out.emplace_back(Args&: T);
14269 }
14270 }
14271 }
14272}
14273
14274FunctionProtoType::ExceptionSpecInfo
14275ASTContext::mergeExceptionSpecs(FunctionProtoType::ExceptionSpecInfo ESI1,
14276 FunctionProtoType::ExceptionSpecInfo ESI2,
14277 SmallVectorImpl<QualType> &ExceptionTypeStorage,
14278 bool AcceptDependent) const {
14279 ExceptionSpecificationType EST1 = ESI1.Type, EST2 = ESI2.Type;
14280
14281 // If either of them can throw anything, that is the result.
14282 for (auto I : {EST_None, EST_MSAny, EST_NoexceptFalse}) {
14283 if (EST1 == I)
14284 return ESI1;
14285 if (EST2 == I)
14286 return ESI2;
14287 }
14288
14289 // If either of them is non-throwing, the result is the other.
14290 for (auto I :
14291 {EST_NoThrow, EST_DynamicNone, EST_BasicNoexcept, EST_NoexceptTrue}) {
14292 if (EST1 == I)
14293 return ESI2;
14294 if (EST2 == I)
14295 return ESI1;
14296 }
14297
14298 // If we're left with value-dependent computed noexcept expressions, we're
14299 // stuck. Before C++17, we can just drop the exception specification entirely,
14300 // since it's not actually part of the canonical type. And this should never
14301 // happen in C++17, because it would mean we were computing the composite
14302 // pointer type of dependent types, which should never happen.
14303 if (EST1 == EST_DependentNoexcept || EST2 == EST_DependentNoexcept) {
14304 assert(AcceptDependent &&
14305 "computing composite pointer type of dependent types");
14306 return FunctionProtoType::ExceptionSpecInfo();
14307 }
14308
14309 // Switch over the possibilities so that people adding new values know to
14310 // update this function.
14311 switch (EST1) {
14312 case EST_None:
14313 case EST_DynamicNone:
14314 case EST_MSAny:
14315 case EST_BasicNoexcept:
14316 case EST_DependentNoexcept:
14317 case EST_NoexceptFalse:
14318 case EST_NoexceptTrue:
14319 case EST_NoThrow:
14320 llvm_unreachable("These ESTs should be handled above");
14321
14322 case EST_Dynamic: {
14323 // This is the fun case: both exception specifications are dynamic. Form
14324 // the union of the two lists.
14325 assert(EST2 == EST_Dynamic && "other cases should already be handled");
14326 mergeTypeLists(Ctx: *this, Out&: ExceptionTypeStorage, X: ESI1.Exceptions,
14327 Y: ESI2.Exceptions);
14328 FunctionProtoType::ExceptionSpecInfo Result(EST_Dynamic);
14329 Result.Exceptions = ExceptionTypeStorage;
14330 return Result;
14331 }
14332
14333 case EST_Unevaluated:
14334 case EST_Uninstantiated:
14335 case EST_Unparsed:
14336 llvm_unreachable("shouldn't see unresolved exception specifications here");
14337 }
14338
14339 llvm_unreachable("invalid ExceptionSpecificationType");
14340}
14341
14342static QualType getCommonNonSugarTypeNode(const ASTContext &Ctx, const Type *X,
14343 Qualifiers &QX, const Type *Y,
14344 Qualifiers &QY) {
14345 Type::TypeClass TC = X->getTypeClass();
14346 assert(TC == Y->getTypeClass());
14347 switch (TC) {
14348#define UNEXPECTED_TYPE(Class, Kind) \
14349 case Type::Class: \
14350 llvm_unreachable("Unexpected " Kind ": " #Class);
14351
14352#define NON_CANONICAL_TYPE(Class, Base) UNEXPECTED_TYPE(Class, "non-canonical")
14353#define TYPE(Class, Base)
14354#include "clang/AST/TypeNodes.inc"
14355
14356#define SUGAR_FREE_TYPE(Class) UNEXPECTED_TYPE(Class, "sugar-free")
14357 SUGAR_FREE_TYPE(Builtin)
14358 SUGAR_FREE_TYPE(DeducedTemplateSpecialization)
14359 SUGAR_FREE_TYPE(DependentBitInt)
14360 SUGAR_FREE_TYPE(BitInt)
14361 SUGAR_FREE_TYPE(ObjCInterface)
14362 SUGAR_FREE_TYPE(SubstTemplateTypeParmPack)
14363 SUGAR_FREE_TYPE(SubstBuiltinTemplatePack)
14364 SUGAR_FREE_TYPE(UnresolvedUsing)
14365 SUGAR_FREE_TYPE(HLSLAttributedResource)
14366 SUGAR_FREE_TYPE(HLSLInlineSpirv)
14367#undef SUGAR_FREE_TYPE
14368#define NON_UNIQUE_TYPE(Class) UNEXPECTED_TYPE(Class, "non-unique")
14369 NON_UNIQUE_TYPE(TypeOfExpr)
14370 NON_UNIQUE_TYPE(VariableArray)
14371#undef NON_UNIQUE_TYPE
14372
14373 UNEXPECTED_TYPE(TypeOf, "sugar")
14374
14375#undef UNEXPECTED_TYPE
14376
14377 case Type::Auto: {
14378 const auto *AX = cast<AutoType>(Val: X), *AY = cast<AutoType>(Val: Y);
14379 assert(AX->getDeducedKind() == AY->getDeducedKind());
14380 assert(AX->getDeducedKind() != DeducedKind::Deduced);
14381 assert(AX->getKeyword() == AY->getKeyword());
14382 TemplateDecl *CD = ::getCommonDecl(X: AX->getTypeConstraintConcept(),
14383 Y: AY->getTypeConstraintConcept());
14384 SmallVector<TemplateArgument, 8> As;
14385 if (CD &&
14386 getCommonTemplateArguments(Ctx, R&: As, Xs: AX->getTypeConstraintArguments(),
14387 Ys: AY->getTypeConstraintArguments())) {
14388 CD = nullptr; // The arguments differ, so make it unconstrained.
14389 As.clear();
14390 }
14391 return Ctx.getAutoType(DK: AX->getDeducedKind(), DeducedAsType: QualType(), Keyword: AX->getKeyword(),
14392 TypeConstraintConcept: CD, TypeConstraintArgs: As);
14393 }
14394 case Type::IncompleteArray: {
14395 const auto *AX = cast<IncompleteArrayType>(Val: X),
14396 *AY = cast<IncompleteArrayType>(Val: Y);
14397 return Ctx.getIncompleteArrayType(
14398 elementType: getCommonArrayElementType(Ctx, X: AX, QX, Y: AY, QY),
14399 ASM: getCommonSizeModifier(X: AX, Y: AY), elementTypeQuals: getCommonIndexTypeCVRQualifiers(X: AX, Y: AY));
14400 }
14401 case Type::DependentSizedArray: {
14402 const auto *AX = cast<DependentSizedArrayType>(Val: X),
14403 *AY = cast<DependentSizedArrayType>(Val: Y);
14404 return Ctx.getDependentSizedArrayType(
14405 elementType: getCommonArrayElementType(Ctx, X: AX, QX, Y: AY, QY),
14406 numElements: getCommonSizeExpr(Ctx, X: AX, Y: AY), ASM: getCommonSizeModifier(X: AX, Y: AY),
14407 elementTypeQuals: getCommonIndexTypeCVRQualifiers(X: AX, Y: AY));
14408 }
14409 case Type::ConstantArray: {
14410 const auto *AX = cast<ConstantArrayType>(Val: X),
14411 *AY = cast<ConstantArrayType>(Val: Y);
14412 assert(AX->getSize() == AY->getSize());
14413 const Expr *SizeExpr = Ctx.hasSameExpr(X: AX->getSizeExpr(), Y: AY->getSizeExpr())
14414 ? AX->getSizeExpr()
14415 : nullptr;
14416 return Ctx.getConstantArrayType(
14417 EltTy: getCommonArrayElementType(Ctx, X: AX, QX, Y: AY, QY), ArySizeIn: AX->getSize(), SizeExpr,
14418 ASM: getCommonSizeModifier(X: AX, Y: AY), IndexTypeQuals: getCommonIndexTypeCVRQualifiers(X: AX, Y: AY));
14419 }
14420 case Type::ArrayParameter: {
14421 const auto *AX = cast<ArrayParameterType>(Val: X),
14422 *AY = cast<ArrayParameterType>(Val: Y);
14423 assert(AX->getSize() == AY->getSize());
14424 const Expr *SizeExpr = Ctx.hasSameExpr(X: AX->getSizeExpr(), Y: AY->getSizeExpr())
14425 ? AX->getSizeExpr()
14426 : nullptr;
14427 auto ArrayTy = Ctx.getConstantArrayType(
14428 EltTy: getCommonArrayElementType(Ctx, X: AX, QX, Y: AY, QY), ArySizeIn: AX->getSize(), SizeExpr,
14429 ASM: getCommonSizeModifier(X: AX, Y: AY), IndexTypeQuals: getCommonIndexTypeCVRQualifiers(X: AX, Y: AY));
14430 return Ctx.getArrayParameterType(Ty: ArrayTy);
14431 }
14432 case Type::Atomic: {
14433 const auto *AX = cast<AtomicType>(Val: X), *AY = cast<AtomicType>(Val: Y);
14434 return Ctx.getAtomicType(
14435 T: Ctx.getCommonSugaredType(X: AX->getValueType(), Y: AY->getValueType()));
14436 }
14437 case Type::Complex: {
14438 const auto *CX = cast<ComplexType>(Val: X), *CY = cast<ComplexType>(Val: Y);
14439 return Ctx.getComplexType(T: getCommonArrayElementType(Ctx, X: CX, QX, Y: CY, QY));
14440 }
14441 case Type::Pointer: {
14442 const auto *PX = cast<PointerType>(Val: X), *PY = cast<PointerType>(Val: Y);
14443 return Ctx.getPointerType(T: getCommonPointeeType(Ctx, X: PX, Y: PY));
14444 }
14445 case Type::BlockPointer: {
14446 const auto *PX = cast<BlockPointerType>(Val: X), *PY = cast<BlockPointerType>(Val: Y);
14447 return Ctx.getBlockPointerType(T: getCommonPointeeType(Ctx, X: PX, Y: PY));
14448 }
14449 case Type::ObjCObjectPointer: {
14450 const auto *PX = cast<ObjCObjectPointerType>(Val: X),
14451 *PY = cast<ObjCObjectPointerType>(Val: Y);
14452 return Ctx.getObjCObjectPointerType(ObjectT: getCommonPointeeType(Ctx, X: PX, Y: PY));
14453 }
14454 case Type::MemberPointer: {
14455 const auto *PX = cast<MemberPointerType>(Val: X),
14456 *PY = cast<MemberPointerType>(Val: Y);
14457 assert(declaresSameEntity(PX->getMostRecentCXXRecordDecl(),
14458 PY->getMostRecentCXXRecordDecl()));
14459 return Ctx.getMemberPointerType(
14460 T: getCommonPointeeType(Ctx, X: PX, Y: PY),
14461 Qualifier: getCommonQualifier(Ctx, X: PX, Y: PY, /*IsSame=*/true),
14462 Cls: PX->getMostRecentCXXRecordDecl());
14463 }
14464 case Type::LValueReference: {
14465 const auto *PX = cast<LValueReferenceType>(Val: X),
14466 *PY = cast<LValueReferenceType>(Val: Y);
14467 // FIXME: Preserve PointeeTypeAsWritten.
14468 return Ctx.getLValueReferenceType(T: getCommonPointeeType(Ctx, X: PX, Y: PY),
14469 SpelledAsLValue: PX->isSpelledAsLValue() ||
14470 PY->isSpelledAsLValue());
14471 }
14472 case Type::RValueReference: {
14473 const auto *PX = cast<RValueReferenceType>(Val: X),
14474 *PY = cast<RValueReferenceType>(Val: Y);
14475 // FIXME: Preserve PointeeTypeAsWritten.
14476 return Ctx.getRValueReferenceType(T: getCommonPointeeType(Ctx, X: PX, Y: PY));
14477 }
14478 case Type::DependentAddressSpace: {
14479 const auto *PX = cast<DependentAddressSpaceType>(Val: X),
14480 *PY = cast<DependentAddressSpaceType>(Val: Y);
14481 assert(Ctx.hasSameExpr(PX->getAddrSpaceExpr(), PY->getAddrSpaceExpr()));
14482 return Ctx.getDependentAddressSpaceType(PointeeType: getCommonPointeeType(Ctx, X: PX, Y: PY),
14483 AddrSpaceExpr: PX->getAddrSpaceExpr(),
14484 AttrLoc: getCommonAttrLoc(X: PX, Y: PY));
14485 }
14486 case Type::FunctionNoProto: {
14487 const auto *FX = cast<FunctionNoProtoType>(Val: X),
14488 *FY = cast<FunctionNoProtoType>(Val: Y);
14489 assert(FX->getExtInfo() == FY->getExtInfo());
14490 return Ctx.getFunctionNoProtoType(
14491 ResultTy: Ctx.getCommonSugaredType(X: FX->getReturnType(), Y: FY->getReturnType()),
14492 Info: FX->getExtInfo());
14493 }
14494 case Type::FunctionProto: {
14495 const auto *FX = cast<FunctionProtoType>(Val: X),
14496 *FY = cast<FunctionProtoType>(Val: Y);
14497 FunctionProtoType::ExtProtoInfo EPIX = FX->getExtProtoInfo(),
14498 EPIY = FY->getExtProtoInfo();
14499 assert(EPIX.ExtInfo == EPIY.ExtInfo);
14500 assert(!EPIX.ExtParameterInfos == !EPIY.ExtParameterInfos);
14501 assert(!EPIX.ExtParameterInfos ||
14502 llvm::equal(
14503 llvm::ArrayRef(EPIX.ExtParameterInfos, FX->getNumParams()),
14504 llvm::ArrayRef(EPIY.ExtParameterInfos, FY->getNumParams())));
14505 assert(EPIX.RefQualifier == EPIY.RefQualifier);
14506 assert(EPIX.TypeQuals == EPIY.TypeQuals);
14507 assert(EPIX.Variadic == EPIY.Variadic);
14508
14509 // FIXME: Can we handle an empty EllipsisLoc?
14510 // Use emtpy EllipsisLoc if X and Y differ.
14511
14512 EPIX.HasTrailingReturn = EPIX.HasTrailingReturn && EPIY.HasTrailingReturn;
14513
14514 QualType R =
14515 Ctx.getCommonSugaredType(X: FX->getReturnType(), Y: FY->getReturnType());
14516 auto P = getCommonTypes(Ctx, Xs: FX->param_types(), Ys: FY->param_types(),
14517 /*Unqualified=*/true);
14518
14519 SmallVector<QualType, 8> Exceptions;
14520 EPIX.ExceptionSpec = Ctx.mergeExceptionSpecs(
14521 ESI1: EPIX.ExceptionSpec, ESI2: EPIY.ExceptionSpec, ExceptionTypeStorage&: Exceptions, AcceptDependent: true);
14522 return Ctx.getFunctionType(ResultTy: R, Args: P, EPI: EPIX);
14523 }
14524 case Type::ObjCObject: {
14525 const auto *OX = cast<ObjCObjectType>(Val: X), *OY = cast<ObjCObjectType>(Val: Y);
14526 assert(
14527 std::equal(OX->getProtocols().begin(), OX->getProtocols().end(),
14528 OY->getProtocols().begin(), OY->getProtocols().end(),
14529 [](const ObjCProtocolDecl *P0, const ObjCProtocolDecl *P1) {
14530 return P0->getCanonicalDecl() == P1->getCanonicalDecl();
14531 }) &&
14532 "protocol lists must be the same");
14533 auto TAs = getCommonTypes(Ctx, Xs: OX->getTypeArgsAsWritten(),
14534 Ys: OY->getTypeArgsAsWritten());
14535 return Ctx.getObjCObjectType(
14536 baseType: Ctx.getCommonSugaredType(X: OX->getBaseType(), Y: OY->getBaseType()), typeArgs: TAs,
14537 protocols: OX->getProtocols(),
14538 isKindOf: OX->isKindOfTypeAsWritten() && OY->isKindOfTypeAsWritten());
14539 }
14540 case Type::ConstantMatrix: {
14541 const auto *MX = cast<ConstantMatrixType>(Val: X),
14542 *MY = cast<ConstantMatrixType>(Val: Y);
14543 assert(MX->getNumRows() == MY->getNumRows());
14544 assert(MX->getNumColumns() == MY->getNumColumns());
14545 return Ctx.getConstantMatrixType(ElementTy: getCommonElementType(Ctx, X: MX, Y: MY),
14546 NumRows: MX->getNumRows(), NumColumns: MX->getNumColumns());
14547 }
14548 case Type::DependentSizedMatrix: {
14549 const auto *MX = cast<DependentSizedMatrixType>(Val: X),
14550 *MY = cast<DependentSizedMatrixType>(Val: Y);
14551 assert(Ctx.hasSameExpr(MX->getRowExpr(), MY->getRowExpr()));
14552 assert(Ctx.hasSameExpr(MX->getColumnExpr(), MY->getColumnExpr()));
14553 return Ctx.getDependentSizedMatrixType(
14554 ElementTy: getCommonElementType(Ctx, X: MX, Y: MY), RowExpr: MX->getRowExpr(),
14555 ColumnExpr: MX->getColumnExpr(), AttrLoc: getCommonAttrLoc(X: MX, Y: MY));
14556 }
14557 case Type::Vector: {
14558 const auto *VX = cast<VectorType>(Val: X), *VY = cast<VectorType>(Val: Y);
14559 assert(VX->getNumElements() == VY->getNumElements());
14560 assert(VX->getVectorKind() == VY->getVectorKind());
14561 return Ctx.getVectorType(vecType: getCommonElementType(Ctx, X: VX, Y: VY),
14562 NumElts: VX->getNumElements(), VecKind: VX->getVectorKind());
14563 }
14564 case Type::ExtVector: {
14565 const auto *VX = cast<ExtVectorType>(Val: X), *VY = cast<ExtVectorType>(Val: Y);
14566 assert(VX->getNumElements() == VY->getNumElements());
14567 return Ctx.getExtVectorType(vecType: getCommonElementType(Ctx, X: VX, Y: VY),
14568 NumElts: VX->getNumElements());
14569 }
14570 case Type::DependentSizedExtVector: {
14571 const auto *VX = cast<DependentSizedExtVectorType>(Val: X),
14572 *VY = cast<DependentSizedExtVectorType>(Val: Y);
14573 return Ctx.getDependentSizedExtVectorType(vecType: getCommonElementType(Ctx, X: VX, Y: VY),
14574 SizeExpr: getCommonSizeExpr(Ctx, X: VX, Y: VY),
14575 AttrLoc: getCommonAttrLoc(X: VX, Y: VY));
14576 }
14577 case Type::DependentVector: {
14578 const auto *VX = cast<DependentVectorType>(Val: X),
14579 *VY = cast<DependentVectorType>(Val: Y);
14580 assert(VX->getVectorKind() == VY->getVectorKind());
14581 return Ctx.getDependentVectorType(
14582 VecType: getCommonElementType(Ctx, X: VX, Y: VY), SizeExpr: getCommonSizeExpr(Ctx, X: VX, Y: VY),
14583 AttrLoc: getCommonAttrLoc(X: VX, Y: VY), VecKind: VX->getVectorKind());
14584 }
14585 case Type::Enum:
14586 case Type::Record:
14587 case Type::InjectedClassName: {
14588 const auto *TX = cast<TagType>(Val: X), *TY = cast<TagType>(Val: Y);
14589 return Ctx.getTagType(Keyword: ::getCommonTypeKeyword(X: TX, Y: TY, /*IsSame=*/false),
14590 Qualifier: ::getCommonQualifier(Ctx, X: TX, Y: TY, /*IsSame=*/false),
14591 TD: ::getCommonDeclChecked(X: TX->getDecl(), Y: TY->getDecl()),
14592 /*OwnedTag=*/OwnsTag: false);
14593 }
14594 case Type::TemplateSpecialization: {
14595 const auto *TX = cast<TemplateSpecializationType>(Val: X),
14596 *TY = cast<TemplateSpecializationType>(Val: Y);
14597 auto As = getCommonTemplateArguments(Ctx, Xs: TX->template_arguments(),
14598 Ys: TY->template_arguments());
14599 return Ctx.getTemplateSpecializationType(
14600 Keyword: getCommonTypeKeyword(X: TX, Y: TY, /*IsSame=*/false),
14601 Template: ::getCommonTemplateNameChecked(Ctx, X: TX->getTemplateName(),
14602 Y: TY->getTemplateName(),
14603 /*IgnoreDeduced=*/true),
14604 SpecifiedArgs: As, /*CanonicalArgs=*/{}, Underlying: X->getCanonicalTypeInternal());
14605 }
14606 case Type::Decltype: {
14607 const auto *DX = cast<DecltypeType>(Val: X);
14608 [[maybe_unused]] const auto *DY = cast<DecltypeType>(Val: Y);
14609 assert(DX->isDependentType());
14610 assert(DY->isDependentType());
14611 assert(Ctx.hasSameExpr(DX->getUnderlyingExpr(), DY->getUnderlyingExpr()));
14612 // As Decltype is not uniqued, building a common type would be wasteful.
14613 return QualType(DX, 0);
14614 }
14615 case Type::PackIndexing: {
14616 const auto *DX = cast<PackIndexingType>(Val: X);
14617 [[maybe_unused]] const auto *DY = cast<PackIndexingType>(Val: Y);
14618 assert(DX->isDependentType());
14619 assert(DY->isDependentType());
14620 assert(Ctx.hasSameExpr(DX->getIndexExpr(), DY->getIndexExpr()));
14621 return QualType(DX, 0);
14622 }
14623 case Type::DependentName: {
14624 const auto *NX = cast<DependentNameType>(Val: X),
14625 *NY = cast<DependentNameType>(Val: Y);
14626 assert(NX->getIdentifier() == NY->getIdentifier());
14627 return Ctx.getDependentNameType(
14628 Keyword: getCommonTypeKeyword(X: NX, Y: NY, /*IsSame=*/true),
14629 NNS: getCommonQualifier(Ctx, X: NX, Y: NY, /*IsSame=*/true), Name: NX->getIdentifier());
14630 }
14631 case Type::OverflowBehavior: {
14632 const auto *NX = cast<OverflowBehaviorType>(Val: X),
14633 *NY = cast<OverflowBehaviorType>(Val: Y);
14634 assert(NX->getBehaviorKind() == NY->getBehaviorKind());
14635 return Ctx.getOverflowBehaviorType(
14636 Kind: NX->getBehaviorKind(),
14637 Underlying: getCommonTypeWithQualifierLifting(Ctx, X: NX->getUnderlyingType(),
14638 Y: NY->getUnderlyingType(), QX, QY));
14639 }
14640 case Type::UnaryTransform: {
14641 const auto *TX = cast<UnaryTransformType>(Val: X),
14642 *TY = cast<UnaryTransformType>(Val: Y);
14643 assert(TX->getUTTKind() == TY->getUTTKind());
14644 return Ctx.getUnaryTransformType(
14645 BaseType: Ctx.getCommonSugaredType(X: TX->getBaseType(), Y: TY->getBaseType()),
14646 UnderlyingType: Ctx.getCommonSugaredType(X: TX->getUnderlyingType(),
14647 Y: TY->getUnderlyingType()),
14648 Kind: TX->getUTTKind());
14649 }
14650 case Type::PackExpansion: {
14651 const auto *PX = cast<PackExpansionType>(Val: X),
14652 *PY = cast<PackExpansionType>(Val: Y);
14653 assert(PX->getNumExpansions() == PY->getNumExpansions());
14654 return Ctx.getPackExpansionType(
14655 Pattern: Ctx.getCommonSugaredType(X: PX->getPattern(), Y: PY->getPattern()),
14656 NumExpansions: PX->getNumExpansions(), ExpectPackInType: false);
14657 }
14658 case Type::Pipe: {
14659 const auto *PX = cast<PipeType>(Val: X), *PY = cast<PipeType>(Val: Y);
14660 assert(PX->isReadOnly() == PY->isReadOnly());
14661 auto MP = PX->isReadOnly() ? &ASTContext::getReadPipeType
14662 : &ASTContext::getWritePipeType;
14663 return (Ctx.*MP)(getCommonElementType(Ctx, X: PX, Y: PY));
14664 }
14665 case Type::TemplateTypeParm: {
14666 const auto *TX = cast<TemplateTypeParmType>(Val: X),
14667 *TY = cast<TemplateTypeParmType>(Val: Y);
14668 assert(TX->getDepth() == TY->getDepth());
14669 assert(TX->getIndex() == TY->getIndex());
14670 assert(TX->isParameterPack() == TY->isParameterPack());
14671 return Ctx.getTemplateTypeParmType(
14672 Depth: TX->getDepth(), Index: TX->getIndex(), ParameterPack: TX->isParameterPack(),
14673 TTPDecl: getCommonDecl(X: TX->getDecl(), Y: TY->getDecl()));
14674 }
14675 }
14676 llvm_unreachable("Unknown Type Class");
14677}
14678
14679static QualType getCommonSugarTypeNode(const ASTContext &Ctx, const Type *X,
14680 const Type *Y,
14681 SplitQualType Underlying) {
14682 Type::TypeClass TC = X->getTypeClass();
14683 if (TC != Y->getTypeClass())
14684 return QualType();
14685 switch (TC) {
14686#define UNEXPECTED_TYPE(Class, Kind) \
14687 case Type::Class: \
14688 llvm_unreachable("Unexpected " Kind ": " #Class);
14689#define TYPE(Class, Base)
14690#define DEPENDENT_TYPE(Class, Base) UNEXPECTED_TYPE(Class, "dependent")
14691#include "clang/AST/TypeNodes.inc"
14692
14693#define CANONICAL_TYPE(Class) UNEXPECTED_TYPE(Class, "canonical")
14694 CANONICAL_TYPE(Atomic)
14695 CANONICAL_TYPE(BitInt)
14696 CANONICAL_TYPE(BlockPointer)
14697 CANONICAL_TYPE(Builtin)
14698 CANONICAL_TYPE(Complex)
14699 CANONICAL_TYPE(ConstantArray)
14700 CANONICAL_TYPE(ArrayParameter)
14701 CANONICAL_TYPE(ConstantMatrix)
14702 CANONICAL_TYPE(Enum)
14703 CANONICAL_TYPE(ExtVector)
14704 CANONICAL_TYPE(FunctionNoProto)
14705 CANONICAL_TYPE(FunctionProto)
14706 CANONICAL_TYPE(IncompleteArray)
14707 CANONICAL_TYPE(HLSLAttributedResource)
14708 CANONICAL_TYPE(HLSLInlineSpirv)
14709 CANONICAL_TYPE(LValueReference)
14710 CANONICAL_TYPE(ObjCInterface)
14711 CANONICAL_TYPE(ObjCObject)
14712 CANONICAL_TYPE(ObjCObjectPointer)
14713 CANONICAL_TYPE(OverflowBehavior)
14714 CANONICAL_TYPE(Pipe)
14715 CANONICAL_TYPE(Pointer)
14716 CANONICAL_TYPE(Record)
14717 CANONICAL_TYPE(RValueReference)
14718 CANONICAL_TYPE(VariableArray)
14719 CANONICAL_TYPE(Vector)
14720#undef CANONICAL_TYPE
14721
14722#undef UNEXPECTED_TYPE
14723
14724 case Type::Adjusted: {
14725 const auto *AX = cast<AdjustedType>(Val: X), *AY = cast<AdjustedType>(Val: Y);
14726 QualType OX = AX->getOriginalType(), OY = AY->getOriginalType();
14727 if (!Ctx.hasSameType(T1: OX, T2: OY))
14728 return QualType();
14729 // FIXME: It's inefficient to have to unify the original types.
14730 return Ctx.getAdjustedType(Orig: Ctx.getCommonSugaredType(X: OX, Y: OY),
14731 New: Ctx.getQualifiedType(split: Underlying));
14732 }
14733 case Type::Decayed: {
14734 const auto *DX = cast<DecayedType>(Val: X), *DY = cast<DecayedType>(Val: Y);
14735 QualType OX = DX->getOriginalType(), OY = DY->getOriginalType();
14736 if (!Ctx.hasSameType(T1: OX, T2: OY))
14737 return QualType();
14738 // FIXME: It's inefficient to have to unify the original types.
14739 return Ctx.getDecayedType(Orig: Ctx.getCommonSugaredType(X: OX, Y: OY),
14740 Decayed: Ctx.getQualifiedType(split: Underlying));
14741 }
14742 case Type::Attributed: {
14743 const auto *AX = cast<AttributedType>(Val: X), *AY = cast<AttributedType>(Val: Y);
14744 AttributedType::Kind Kind = AX->getAttrKind();
14745 if (Kind != AY->getAttrKind())
14746 return QualType();
14747 QualType MX = AX->getModifiedType(), MY = AY->getModifiedType();
14748 if (!Ctx.hasSameType(T1: MX, T2: MY))
14749 return QualType();
14750 // FIXME: It's inefficient to have to unify the modified types.
14751 return Ctx.getAttributedType(attrKind: Kind, modifiedType: Ctx.getCommonSugaredType(X: MX, Y: MY),
14752 equivalentType: Ctx.getQualifiedType(split: Underlying),
14753 attr: AX->getAttr());
14754 }
14755 case Type::BTFTagAttributed: {
14756 const auto *BX = cast<BTFTagAttributedType>(Val: X);
14757 const BTFTypeTagAttr *AX = BX->getAttr();
14758 // The attribute is not uniqued, so just compare the tag.
14759 if (AX->getBTFTypeTag() !=
14760 cast<BTFTagAttributedType>(Val: Y)->getAttr()->getBTFTypeTag())
14761 return QualType();
14762 return Ctx.getBTFTagAttributedType(BTFAttr: AX, Wrapped: Ctx.getQualifiedType(split: Underlying));
14763 }
14764 case Type::Auto: {
14765 const auto *AX = cast<AutoType>(Val: X), *AY = cast<AutoType>(Val: Y);
14766 assert(AX->getDeducedKind() == DeducedKind::Deduced);
14767 assert(AY->getDeducedKind() == DeducedKind::Deduced);
14768
14769 AutoTypeKeyword KW = AX->getKeyword();
14770 if (KW != AY->getKeyword())
14771 return QualType();
14772
14773 TemplateDecl *CD = ::getCommonDecl(X: AX->getTypeConstraintConcept(),
14774 Y: AY->getTypeConstraintConcept());
14775 SmallVector<TemplateArgument, 8> As;
14776 if (CD &&
14777 getCommonTemplateArguments(Ctx, R&: As, Xs: AX->getTypeConstraintArguments(),
14778 Ys: AY->getTypeConstraintArguments())) {
14779 CD = nullptr; // The arguments differ, so make it unconstrained.
14780 As.clear();
14781 }
14782
14783 // Both auto types can't be dependent, otherwise they wouldn't have been
14784 // sugar. This implies they can't contain unexpanded packs either.
14785 return Ctx.getAutoType(DK: DeducedKind::Deduced,
14786 DeducedAsType: Ctx.getQualifiedType(split: Underlying), Keyword: AX->getKeyword(),
14787 TypeConstraintConcept: CD, TypeConstraintArgs: As);
14788 }
14789 case Type::PackIndexing:
14790 case Type::Decltype:
14791 return QualType();
14792 case Type::DeducedTemplateSpecialization:
14793 // FIXME: Try to merge these.
14794 return QualType();
14795 case Type::MacroQualified: {
14796 const auto *MX = cast<MacroQualifiedType>(Val: X),
14797 *MY = cast<MacroQualifiedType>(Val: Y);
14798 const IdentifierInfo *IX = MX->getMacroIdentifier();
14799 if (IX != MY->getMacroIdentifier())
14800 return QualType();
14801 return Ctx.getMacroQualifiedType(UnderlyingTy: Ctx.getQualifiedType(split: Underlying), MacroII: IX);
14802 }
14803 case Type::SubstTemplateTypeParm: {
14804 const auto *SX = cast<SubstTemplateTypeParmType>(Val: X),
14805 *SY = cast<SubstTemplateTypeParmType>(Val: Y);
14806 Decl *CD =
14807 ::getCommonDecl(X: SX->getAssociatedDecl(), Y: SY->getAssociatedDecl());
14808 if (!CD)
14809 return QualType();
14810 unsigned Index = SX->getIndex();
14811 if (Index != SY->getIndex())
14812 return QualType();
14813 auto PackIndex = SX->getPackIndex();
14814 if (PackIndex != SY->getPackIndex())
14815 return QualType();
14816 return Ctx.getSubstTemplateTypeParmType(Replacement: Ctx.getQualifiedType(split: Underlying),
14817 AssociatedDecl: CD, Index, PackIndex,
14818 Final: SX->getFinal() && SY->getFinal());
14819 }
14820 case Type::ObjCTypeParam:
14821 // FIXME: Try to merge these.
14822 return QualType();
14823 case Type::Paren:
14824 return Ctx.getParenType(InnerType: Ctx.getQualifiedType(split: Underlying));
14825
14826 case Type::TemplateSpecialization: {
14827 const auto *TX = cast<TemplateSpecializationType>(Val: X),
14828 *TY = cast<TemplateSpecializationType>(Val: Y);
14829 TemplateName CTN =
14830 ::getCommonTemplateName(Ctx, X: TX->getTemplateName(),
14831 Y: TY->getTemplateName(), /*IgnoreDeduced=*/true);
14832 if (!CTN.getAsVoidPointer())
14833 return QualType();
14834 SmallVector<TemplateArgument, 8> As;
14835 if (getCommonTemplateArguments(Ctx, R&: As, Xs: TX->template_arguments(),
14836 Ys: TY->template_arguments()))
14837 return QualType();
14838 return Ctx.getTemplateSpecializationType(
14839 Keyword: getCommonTypeKeyword(X: TX, Y: TY, /*IsSame=*/false), Template: CTN, SpecifiedArgs: As,
14840 /*CanonicalArgs=*/{}, Underlying: Ctx.getQualifiedType(split: Underlying));
14841 }
14842 case Type::Typedef: {
14843 const auto *TX = cast<TypedefType>(Val: X), *TY = cast<TypedefType>(Val: Y);
14844 const TypedefNameDecl *CD = ::getCommonDecl(X: TX->getDecl(), Y: TY->getDecl());
14845 if (!CD)
14846 return QualType();
14847 return Ctx.getTypedefType(
14848 Keyword: ::getCommonTypeKeyword(X: TX, Y: TY, /*IsSame=*/false),
14849 Qualifier: ::getCommonQualifier(Ctx, X: TX, Y: TY, /*IsSame=*/false), Decl: CD,
14850 UnderlyingType: Ctx.getQualifiedType(split: Underlying));
14851 }
14852 case Type::TypeOf: {
14853 // The common sugar between two typeof expressions, where one is
14854 // potentially a typeof_unqual and the other is not, we unify to the
14855 // qualified type as that retains the most information along with the type.
14856 // We only return a typeof_unqual type when both types are unqual types.
14857 TypeOfKind Kind = TypeOfKind::Qualified;
14858 if (cast<TypeOfType>(Val: X)->getKind() == cast<TypeOfType>(Val: Y)->getKind() &&
14859 cast<TypeOfType>(Val: X)->getKind() == TypeOfKind::Unqualified)
14860 Kind = TypeOfKind::Unqualified;
14861 return Ctx.getTypeOfType(tofType: Ctx.getQualifiedType(split: Underlying), Kind);
14862 }
14863 case Type::TypeOfExpr:
14864 return QualType();
14865
14866 case Type::UnaryTransform: {
14867 const auto *UX = cast<UnaryTransformType>(Val: X),
14868 *UY = cast<UnaryTransformType>(Val: Y);
14869 UnaryTransformType::UTTKind KX = UX->getUTTKind();
14870 if (KX != UY->getUTTKind())
14871 return QualType();
14872 QualType BX = UX->getBaseType(), BY = UY->getBaseType();
14873 if (!Ctx.hasSameType(T1: BX, T2: BY))
14874 return QualType();
14875 // FIXME: It's inefficient to have to unify the base types.
14876 return Ctx.getUnaryTransformType(BaseType: Ctx.getCommonSugaredType(X: BX, Y: BY),
14877 UnderlyingType: Ctx.getQualifiedType(split: Underlying), Kind: KX);
14878 }
14879 case Type::Using: {
14880 const auto *UX = cast<UsingType>(Val: X), *UY = cast<UsingType>(Val: Y);
14881 const UsingShadowDecl *CD = ::getCommonDecl(X: UX->getDecl(), Y: UY->getDecl());
14882 if (!CD)
14883 return QualType();
14884 return Ctx.getUsingType(Keyword: ::getCommonTypeKeyword(X: UX, Y: UY, /*IsSame=*/false),
14885 Qualifier: ::getCommonQualifier(Ctx, X: UX, Y: UY, /*IsSame=*/false),
14886 D: CD, UnderlyingType: Ctx.getQualifiedType(split: Underlying));
14887 }
14888 case Type::MemberPointer: {
14889 const auto *PX = cast<MemberPointerType>(Val: X),
14890 *PY = cast<MemberPointerType>(Val: Y);
14891 CXXRecordDecl *Cls = PX->getMostRecentCXXRecordDecl();
14892 assert(Cls == PY->getMostRecentCXXRecordDecl());
14893 return Ctx.getMemberPointerType(
14894 T: ::getCommonPointeeType(Ctx, X: PX, Y: PY),
14895 Qualifier: ::getCommonQualifier(Ctx, X: PX, Y: PY, /*IsSame=*/false), Cls);
14896 }
14897 case Type::CountAttributed: {
14898 const auto *DX = cast<CountAttributedType>(Val: X),
14899 *DY = cast<CountAttributedType>(Val: Y);
14900 if (DX->isCountInBytes() != DY->isCountInBytes())
14901 return QualType();
14902 if (DX->isOrNull() != DY->isOrNull())
14903 return QualType();
14904 Expr *CEX = DX->getCountExpr();
14905 Expr *CEY = DY->getCountExpr();
14906 ArrayRef<clang::TypeCoupledDeclRefInfo> CDX = DX->getCoupledDecls();
14907 if (Ctx.hasSameExpr(X: CEX, Y: CEY))
14908 return Ctx.getCountAttributedType(WrappedTy: Ctx.getQualifiedType(split: Underlying), CountExpr: CEX,
14909 CountInBytes: DX->isCountInBytes(), OrNull: DX->isOrNull(),
14910 DependentDecls: CDX);
14911 if (!CEX->isIntegerConstantExpr(Ctx) || !CEY->isIntegerConstantExpr(Ctx))
14912 return QualType();
14913 // Two declarations with the same integer constant may still differ in their
14914 // expression pointers, so we need to evaluate them.
14915 llvm::APSInt VX = *CEX->getIntegerConstantExpr(Ctx);
14916 llvm::APSInt VY = *CEY->getIntegerConstantExpr(Ctx);
14917 if (VX != VY)
14918 return QualType();
14919 return Ctx.getCountAttributedType(WrappedTy: Ctx.getQualifiedType(split: Underlying), CountExpr: CEX,
14920 CountInBytes: DX->isCountInBytes(), OrNull: DX->isOrNull(),
14921 DependentDecls: CDX);
14922 }
14923 case Type::PredefinedSugar:
14924 assert(cast<PredefinedSugarType>(X)->getKind() !=
14925 cast<PredefinedSugarType>(Y)->getKind());
14926 return QualType();
14927 }
14928 llvm_unreachable("Unhandled Type Class");
14929}
14930
14931static auto unwrapSugar(SplitQualType &T, Qualifiers &QTotal) {
14932 SmallVector<SplitQualType, 8> R;
14933 while (true) {
14934 QTotal.addConsistentQualifiers(qs: T.Quals);
14935 QualType NT = T.Ty->getLocallyUnqualifiedSingleStepDesugaredType();
14936 if (NT == QualType(T.Ty, 0))
14937 break;
14938 R.push_back(Elt: T);
14939 T = NT.split();
14940 }
14941 return R;
14942}
14943
14944QualType ASTContext::getCommonSugaredType(QualType X, QualType Y,
14945 bool Unqualified) const {
14946 assert(Unqualified ? hasSameUnqualifiedType(X, Y) : hasSameType(X, Y));
14947 if (X == Y)
14948 return X;
14949 if (!Unqualified) {
14950 if (X.isCanonical())
14951 return X;
14952 if (Y.isCanonical())
14953 return Y;
14954 }
14955
14956 SplitQualType SX = X.split(), SY = Y.split();
14957 Qualifiers QX, QY;
14958 // Desugar SX and SY, setting the sugar and qualifiers aside into Xs and Ys,
14959 // until we reach their underlying "canonical nodes". Note these are not
14960 // necessarily canonical types, as they may still have sugared properties.
14961 // QX and QY will store the sum of all qualifiers in Xs and Ys respectively.
14962 auto Xs = ::unwrapSugar(T&: SX, QTotal&: QX), Ys = ::unwrapSugar(T&: SY, QTotal&: QY);
14963
14964 // If this is an ArrayType, the element qualifiers are interchangeable with
14965 // the top level qualifiers.
14966 // * In case the canonical nodes are the same, the elements types are already
14967 // the same.
14968 // * Otherwise, the element types will be made the same, and any different
14969 // element qualifiers will be moved up to the top level qualifiers, per
14970 // 'getCommonArrayElementType'.
14971 // In both cases, this means there may be top level qualifiers which differ
14972 // between X and Y. If so, these differing qualifiers are redundant with the
14973 // element qualifiers, and can be removed without changing the canonical type.
14974 // The desired behaviour is the same as for the 'Unqualified' case here:
14975 // treat the redundant qualifiers as sugar, remove the ones which are not
14976 // common to both sides.
14977 bool KeepCommonQualifiers =
14978 Unqualified || isa<ArrayType, OverflowBehaviorType>(Val: SX.Ty);
14979
14980 if (SX.Ty != SY.Ty) {
14981 // The canonical nodes differ. Build a common canonical node out of the two,
14982 // unifying their sugar. This may recurse back here.
14983 SX.Ty =
14984 ::getCommonNonSugarTypeNode(Ctx: *this, X: SX.Ty, QX, Y: SY.Ty, QY).getTypePtr();
14985 } else {
14986 // The canonical nodes were identical: We may have desugared too much.
14987 // Add any common sugar back in.
14988 while (!Xs.empty() && !Ys.empty() && Xs.back().Ty == Ys.back().Ty) {
14989 QX -= SX.Quals;
14990 QY -= SY.Quals;
14991 SX = Xs.pop_back_val();
14992 SY = Ys.pop_back_val();
14993 }
14994 }
14995 if (KeepCommonQualifiers)
14996 QX = Qualifiers::removeCommonQualifiers(L&: QX, R&: QY);
14997 else
14998 assert(QX == QY);
14999
15000 // Even though the remaining sugar nodes in Xs and Ys differ, some may be
15001 // related. Walk up these nodes, unifying them and adding the result.
15002 while (!Xs.empty() && !Ys.empty()) {
15003 auto Underlying = SplitQualType(
15004 SX.Ty, Qualifiers::removeCommonQualifiers(L&: SX.Quals, R&: SY.Quals));
15005 SX = Xs.pop_back_val();
15006 SY = Ys.pop_back_val();
15007 SX.Ty = ::getCommonSugarTypeNode(Ctx: *this, X: SX.Ty, Y: SY.Ty, Underlying)
15008 .getTypePtrOrNull();
15009 // Stop at the first pair which is unrelated.
15010 if (!SX.Ty) {
15011 SX.Ty = Underlying.Ty;
15012 break;
15013 }
15014 QX -= Underlying.Quals;
15015 };
15016
15017 // Add back the missing accumulated qualifiers, which were stripped off
15018 // with the sugar nodes we could not unify.
15019 QualType R = getQualifiedType(T: SX.Ty, Qs: QX);
15020 assert(Unqualified ? hasSameUnqualifiedType(R, X) : hasSameType(R, X));
15021 return R;
15022}
15023
15024QualType ASTContext::getCorrespondingUnsaturatedType(QualType Ty) const {
15025 assert(Ty->isFixedPointType());
15026
15027 if (Ty->isUnsaturatedFixedPointType())
15028 return Ty;
15029
15030 switch (Ty->castAs<BuiltinType>()->getKind()) {
15031 default:
15032 llvm_unreachable("Not a saturated fixed point type!");
15033 case BuiltinType::SatShortAccum:
15034 return ShortAccumTy;
15035 case BuiltinType::SatAccum:
15036 return AccumTy;
15037 case BuiltinType::SatLongAccum:
15038 return LongAccumTy;
15039 case BuiltinType::SatUShortAccum:
15040 return UnsignedShortAccumTy;
15041 case BuiltinType::SatUAccum:
15042 return UnsignedAccumTy;
15043 case BuiltinType::SatULongAccum:
15044 return UnsignedLongAccumTy;
15045 case BuiltinType::SatShortFract:
15046 return ShortFractTy;
15047 case BuiltinType::SatFract:
15048 return FractTy;
15049 case BuiltinType::SatLongFract:
15050 return LongFractTy;
15051 case BuiltinType::SatUShortFract:
15052 return UnsignedShortFractTy;
15053 case BuiltinType::SatUFract:
15054 return UnsignedFractTy;
15055 case BuiltinType::SatULongFract:
15056 return UnsignedLongFractTy;
15057 }
15058}
15059
15060QualType ASTContext::getCorrespondingSaturatedType(QualType Ty) const {
15061 assert(Ty->isFixedPointType());
15062
15063 if (Ty->isSaturatedFixedPointType()) return Ty;
15064
15065 switch (Ty->castAs<BuiltinType>()->getKind()) {
15066 default:
15067 llvm_unreachable("Not a fixed point type!");
15068 case BuiltinType::ShortAccum:
15069 return SatShortAccumTy;
15070 case BuiltinType::Accum:
15071 return SatAccumTy;
15072 case BuiltinType::LongAccum:
15073 return SatLongAccumTy;
15074 case BuiltinType::UShortAccum:
15075 return SatUnsignedShortAccumTy;
15076 case BuiltinType::UAccum:
15077 return SatUnsignedAccumTy;
15078 case BuiltinType::ULongAccum:
15079 return SatUnsignedLongAccumTy;
15080 case BuiltinType::ShortFract:
15081 return SatShortFractTy;
15082 case BuiltinType::Fract:
15083 return SatFractTy;
15084 case BuiltinType::LongFract:
15085 return SatLongFractTy;
15086 case BuiltinType::UShortFract:
15087 return SatUnsignedShortFractTy;
15088 case BuiltinType::UFract:
15089 return SatUnsignedFractTy;
15090 case BuiltinType::ULongFract:
15091 return SatUnsignedLongFractTy;
15092 }
15093}
15094
15095LangAS ASTContext::getLangASForBuiltinAddressSpace(unsigned AS) const {
15096 if (LangOpts.OpenCL)
15097 return getTargetInfo().getOpenCLBuiltinAddressSpace(AS);
15098
15099 if (LangOpts.CUDA)
15100 return getTargetInfo().getCUDABuiltinAddressSpace(AS);
15101
15102 return getLangASFromTargetAS(TargetAS: AS);
15103}
15104
15105// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
15106// doesn't include ASTContext.h
15107template
15108clang::LazyGenerationalUpdatePtr<
15109 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
15110clang::LazyGenerationalUpdatePtr<
15111 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
15112 const clang::ASTContext &Ctx, Decl *Value);
15113
15114unsigned char ASTContext::getFixedPointScale(QualType Ty) const {
15115 assert(Ty->isFixedPointType());
15116
15117 const TargetInfo &Target = getTargetInfo();
15118 switch (Ty->castAs<BuiltinType>()->getKind()) {
15119 default:
15120 llvm_unreachable("Not a fixed point type!");
15121 case BuiltinType::ShortAccum:
15122 case BuiltinType::SatShortAccum:
15123 return Target.getShortAccumScale();
15124 case BuiltinType::Accum:
15125 case BuiltinType::SatAccum:
15126 return Target.getAccumScale();
15127 case BuiltinType::LongAccum:
15128 case BuiltinType::SatLongAccum:
15129 return Target.getLongAccumScale();
15130 case BuiltinType::UShortAccum:
15131 case BuiltinType::SatUShortAccum:
15132 return Target.getUnsignedShortAccumScale();
15133 case BuiltinType::UAccum:
15134 case BuiltinType::SatUAccum:
15135 return Target.getUnsignedAccumScale();
15136 case BuiltinType::ULongAccum:
15137 case BuiltinType::SatULongAccum:
15138 return Target.getUnsignedLongAccumScale();
15139 case BuiltinType::ShortFract:
15140 case BuiltinType::SatShortFract:
15141 return Target.getShortFractScale();
15142 case BuiltinType::Fract:
15143 case BuiltinType::SatFract:
15144 return Target.getFractScale();
15145 case BuiltinType::LongFract:
15146 case BuiltinType::SatLongFract:
15147 return Target.getLongFractScale();
15148 case BuiltinType::UShortFract:
15149 case BuiltinType::SatUShortFract:
15150 return Target.getUnsignedShortFractScale();
15151 case BuiltinType::UFract:
15152 case BuiltinType::SatUFract:
15153 return Target.getUnsignedFractScale();
15154 case BuiltinType::ULongFract:
15155 case BuiltinType::SatULongFract:
15156 return Target.getUnsignedLongFractScale();
15157 }
15158}
15159
15160unsigned char ASTContext::getFixedPointIBits(QualType Ty) const {
15161 assert(Ty->isFixedPointType());
15162
15163 const TargetInfo &Target = getTargetInfo();
15164 switch (Ty->castAs<BuiltinType>()->getKind()) {
15165 default:
15166 llvm_unreachable("Not a fixed point type!");
15167 case BuiltinType::ShortAccum:
15168 case BuiltinType::SatShortAccum:
15169 return Target.getShortAccumIBits();
15170 case BuiltinType::Accum:
15171 case BuiltinType::SatAccum:
15172 return Target.getAccumIBits();
15173 case BuiltinType::LongAccum:
15174 case BuiltinType::SatLongAccum:
15175 return Target.getLongAccumIBits();
15176 case BuiltinType::UShortAccum:
15177 case BuiltinType::SatUShortAccum:
15178 return Target.getUnsignedShortAccumIBits();
15179 case BuiltinType::UAccum:
15180 case BuiltinType::SatUAccum:
15181 return Target.getUnsignedAccumIBits();
15182 case BuiltinType::ULongAccum:
15183 case BuiltinType::SatULongAccum:
15184 return Target.getUnsignedLongAccumIBits();
15185 case BuiltinType::ShortFract:
15186 case BuiltinType::SatShortFract:
15187 case BuiltinType::Fract:
15188 case BuiltinType::SatFract:
15189 case BuiltinType::LongFract:
15190 case BuiltinType::SatLongFract:
15191 case BuiltinType::UShortFract:
15192 case BuiltinType::SatUShortFract:
15193 case BuiltinType::UFract:
15194 case BuiltinType::SatUFract:
15195 case BuiltinType::ULongFract:
15196 case BuiltinType::SatULongFract:
15197 return 0;
15198 }
15199}
15200
15201llvm::FixedPointSemantics
15202ASTContext::getFixedPointSemantics(QualType Ty) const {
15203 assert((Ty->isFixedPointType() || Ty->isIntegerType()) &&
15204 "Can only get the fixed point semantics for a "
15205 "fixed point or integer type.");
15206 if (Ty->isIntegerType())
15207 return llvm::FixedPointSemantics::GetIntegerSemantics(
15208 Width: getIntWidth(T: Ty), IsSigned: Ty->isSignedIntegerType());
15209
15210 bool isSigned = Ty->isSignedFixedPointType();
15211 return llvm::FixedPointSemantics(
15212 static_cast<unsigned>(getTypeSize(T: Ty)), getFixedPointScale(Ty), isSigned,
15213 Ty->isSaturatedFixedPointType(),
15214 !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding());
15215}
15216
15217llvm::APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const {
15218 assert(Ty->isFixedPointType());
15219 return llvm::APFixedPoint::getMax(Sema: getFixedPointSemantics(Ty));
15220}
15221
15222llvm::APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const {
15223 assert(Ty->isFixedPointType());
15224 return llvm::APFixedPoint::getMin(Sema: getFixedPointSemantics(Ty));
15225}
15226
15227QualType ASTContext::getCorrespondingSignedFixedPointType(QualType Ty) const {
15228 assert(Ty->isUnsignedFixedPointType() &&
15229 "Expected unsigned fixed point type");
15230
15231 switch (Ty->castAs<BuiltinType>()->getKind()) {
15232 case BuiltinType::UShortAccum:
15233 return ShortAccumTy;
15234 case BuiltinType::UAccum:
15235 return AccumTy;
15236 case BuiltinType::ULongAccum:
15237 return LongAccumTy;
15238 case BuiltinType::SatUShortAccum:
15239 return SatShortAccumTy;
15240 case BuiltinType::SatUAccum:
15241 return SatAccumTy;
15242 case BuiltinType::SatULongAccum:
15243 return SatLongAccumTy;
15244 case BuiltinType::UShortFract:
15245 return ShortFractTy;
15246 case BuiltinType::UFract:
15247 return FractTy;
15248 case BuiltinType::ULongFract:
15249 return LongFractTy;
15250 case BuiltinType::SatUShortFract:
15251 return SatShortFractTy;
15252 case BuiltinType::SatUFract:
15253 return SatFractTy;
15254 case BuiltinType::SatULongFract:
15255 return SatLongFractTy;
15256 default:
15257 llvm_unreachable("Unexpected unsigned fixed point type");
15258 }
15259}
15260
15261// Given a list of FMV features, return a concatenated list of the
15262// corresponding backend features (which may contain duplicates).
15263static std::vector<std::string> getFMVBackendFeaturesFor(
15264 const llvm::SmallVectorImpl<StringRef> &FMVFeatStrings) {
15265 std::vector<std::string> BackendFeats;
15266 llvm::AArch64::ExtensionSet FeatureBits;
15267 for (StringRef F : FMVFeatStrings)
15268 if (auto FMVExt = llvm::AArch64::parseFMVExtension(Extension: F))
15269 if (FMVExt->ID)
15270 FeatureBits.enable(E: *FMVExt->ID);
15271 FeatureBits.toLLVMFeatureList(Features&: BackendFeats);
15272 return BackendFeats;
15273}
15274
15275ParsedTargetAttr
15276ASTContext::filterFunctionTargetAttrs(const TargetAttr *TD) const {
15277 assert(TD != nullptr);
15278 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(Str: TD->getFeaturesStr());
15279
15280 llvm::erase_if(C&: ParsedAttr.Features, P: [&](const std::string &Feat) {
15281 return !Target->isValidFeatureName(Feature: StringRef{Feat}.substr(Start: 1));
15282 });
15283 return ParsedAttr;
15284}
15285
15286void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
15287 const FunctionDecl *FD) const {
15288 if (FD)
15289 getFunctionFeatureMap(FeatureMap, GD: GlobalDecl().getWithDecl(D: FD));
15290 else
15291 Target->initFeatureMap(Features&: FeatureMap, Diags&: getDiagnostics(),
15292 CPU: Target->getTargetOpts().CPU,
15293 FeatureVec: Target->getTargetOpts().Features);
15294}
15295
15296// Fills in the supplied string map with the set of target features for the
15297// passed in function.
15298void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
15299 GlobalDecl GD) const {
15300 StringRef TargetCPU = Target->getTargetOpts().CPU;
15301 const FunctionDecl *FD = GD.getDecl()->getAsFunction();
15302 if (const auto *TD = FD->getAttr<TargetAttr>()) {
15303 ParsedTargetAttr ParsedAttr = filterFunctionTargetAttrs(TD);
15304
15305 // Make a copy of the features as passed on the command line into the
15306 // beginning of the additional features from the function to override.
15307 // AArch64 handles command line option features in parseTargetAttr().
15308 if (!Target->getTriple().isAArch64())
15309 ParsedAttr.Features.insert(
15310 position: ParsedAttr.Features.begin(),
15311 first: Target->getTargetOpts().FeaturesAsWritten.begin(),
15312 last: Target->getTargetOpts().FeaturesAsWritten.end());
15313
15314 if (ParsedAttr.CPU != "" && Target->isValidCPUName(Name: ParsedAttr.CPU))
15315 TargetCPU = ParsedAttr.CPU;
15316
15317 // Now populate the feature map, first with the TargetCPU which is either
15318 // the default or a new one from the target attribute string. Then we'll use
15319 // the passed in features (FeaturesAsWritten) along with the new ones from
15320 // the attribute.
15321 Target->initFeatureMap(Features&: FeatureMap, Diags&: getDiagnostics(), CPU: TargetCPU,
15322 FeatureVec: ParsedAttr.Features);
15323 } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) {
15324 llvm::SmallVector<StringRef, 32> FeaturesTmp;
15325 Target->getCPUSpecificCPUDispatchFeatures(
15326 Name: SD->getCPUName(Index: GD.getMultiVersionIndex())->getName(), Features&: FeaturesTmp);
15327 std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end());
15328 Features.insert(position: Features.begin(),
15329 first: Target->getTargetOpts().FeaturesAsWritten.begin(),
15330 last: Target->getTargetOpts().FeaturesAsWritten.end());
15331 Target->initFeatureMap(Features&: FeatureMap, Diags&: getDiagnostics(), CPU: TargetCPU, FeatureVec: Features);
15332 } else if (const auto *TC = FD->getAttr<TargetClonesAttr>()) {
15333 if (Target->getTriple().isAArch64()) {
15334 llvm::SmallVector<StringRef, 8> Feats;
15335 TC->getFeatures(Out&: Feats, Index: GD.getMultiVersionIndex());
15336 std::vector<std::string> Features = getFMVBackendFeaturesFor(FMVFeatStrings: Feats);
15337 Features.insert(position: Features.begin(),
15338 first: Target->getTargetOpts().FeaturesAsWritten.begin(),
15339 last: Target->getTargetOpts().FeaturesAsWritten.end());
15340 Target->initFeatureMap(Features&: FeatureMap, Diags&: getDiagnostics(), CPU: TargetCPU, FeatureVec: Features);
15341 } else if (Target->getTriple().isRISCV()) {
15342 StringRef VersionStr = TC->getFeatureStr(Index: GD.getMultiVersionIndex());
15343 std::vector<std::string> Features;
15344 if (VersionStr != "default") {
15345 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(Str: VersionStr);
15346 Features.insert(position: Features.begin(), first: ParsedAttr.Features.begin(),
15347 last: ParsedAttr.Features.end());
15348 }
15349 Features.insert(position: Features.begin(),
15350 first: Target->getTargetOpts().FeaturesAsWritten.begin(),
15351 last: Target->getTargetOpts().FeaturesAsWritten.end());
15352 Target->initFeatureMap(Features&: FeatureMap, Diags&: getDiagnostics(), CPU: TargetCPU, FeatureVec: Features);
15353 } else if (Target->getTriple().isOSAIX()) {
15354 std::vector<std::string> Features;
15355 StringRef VersionStr = TC->getFeatureStr(Index: GD.getMultiVersionIndex());
15356 if (VersionStr.starts_with(Prefix: "cpu="))
15357 TargetCPU = VersionStr.drop_front(N: sizeof("cpu=") - 1);
15358 else
15359 assert(VersionStr == "default");
15360 Target->initFeatureMap(Features&: FeatureMap, Diags&: getDiagnostics(), CPU: TargetCPU, FeatureVec: Features);
15361 } else {
15362 std::vector<std::string> Features;
15363 StringRef VersionStr = TC->getFeatureStr(Index: GD.getMultiVersionIndex());
15364 if (VersionStr.starts_with(Prefix: "arch="))
15365 TargetCPU = VersionStr.drop_front(N: sizeof("arch=") - 1);
15366 else if (VersionStr != "default")
15367 Features.push_back(x: (StringRef{"+"} + VersionStr).str());
15368 Target->initFeatureMap(Features&: FeatureMap, Diags&: getDiagnostics(), CPU: TargetCPU, FeatureVec: Features);
15369 }
15370 } else if (const auto *TV = FD->getAttr<TargetVersionAttr>()) {
15371 std::vector<std::string> Features;
15372 if (Target->getTriple().isRISCV()) {
15373 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(Str: TV->getName());
15374 Features.insert(position: Features.begin(), first: ParsedAttr.Features.begin(),
15375 last: ParsedAttr.Features.end());
15376 } else {
15377 assert(Target->getTriple().isAArch64());
15378 llvm::SmallVector<StringRef, 8> Feats;
15379 TV->getFeatures(Out&: Feats);
15380 Features = getFMVBackendFeaturesFor(FMVFeatStrings: Feats);
15381 }
15382 Features.insert(position: Features.begin(),
15383 first: Target->getTargetOpts().FeaturesAsWritten.begin(),
15384 last: Target->getTargetOpts().FeaturesAsWritten.end());
15385 Target->initFeatureMap(Features&: FeatureMap, Diags&: getDiagnostics(), CPU: TargetCPU, FeatureVec: Features);
15386 } else {
15387 FeatureMap = Target->getTargetOpts().FeatureMap;
15388 }
15389}
15390
15391static SYCLKernelInfo BuildSYCLKernelInfo(ASTContext &Context,
15392 CanQualType KernelNameType,
15393 const FunctionDecl *FD) {
15394 // Host and device compilation may use different ABIs and different ABIs
15395 // may allocate name mangling discriminators differently. A discriminator
15396 // override is used to ensure consistent discriminator allocation across
15397 // host and device compilation.
15398 auto DeviceDiscriminatorOverrider =
15399 [](ASTContext &Ctx, const NamedDecl *ND) -> UnsignedOrNone {
15400 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: ND))
15401 if (RD->isLambda())
15402 return RD->getDeviceLambdaManglingNumber();
15403 return std::nullopt;
15404 };
15405 std::unique_ptr<MangleContext> MC{ItaniumMangleContext::create(
15406 Context, Diags&: Context.getDiagnostics(), Discriminator: DeviceDiscriminatorOverrider)};
15407
15408 // Construct a mangled name for the SYCL kernel caller offload entry point.
15409 // FIXME: The Itanium typeinfo mangling (_ZTS<type>) is currently used to
15410 // name the SYCL kernel caller offload entry point function. This mangling
15411 // does not suffice to clearly identify symbols that correspond to SYCL
15412 // kernel caller functions, nor is this mangling natural for targets that
15413 // use a non-Itanium ABI.
15414 std::string Buffer;
15415 Buffer.reserve(res_arg: 128);
15416 llvm::raw_string_ostream Out(Buffer);
15417 MC->mangleCanonicalTypeName(T: KernelNameType, Out);
15418 std::string KernelName = Out.str();
15419
15420 return {KernelNameType, FD, KernelName};
15421}
15422
15423void ASTContext::registerSYCLEntryPointFunction(FunctionDecl *FD) {
15424 // If the function declaration to register is invalid or dependent, the
15425 // registration attempt is ignored.
15426 if (FD->isInvalidDecl() || FD->isTemplated())
15427 return;
15428
15429 const auto *SKEPAttr = FD->getAttr<SYCLKernelEntryPointAttr>();
15430 assert(SKEPAttr && "Missing sycl_kernel_entry_point attribute");
15431
15432 // Be tolerant of multiple registration attempts so long as each attempt
15433 // is for the same entity. Callers are obligated to detect and diagnose
15434 // conflicting kernel names prior to calling this function.
15435 CanQualType KernelNameType = getCanonicalType(T: SKEPAttr->getKernelName());
15436 auto IT = SYCLKernels.find(Val: KernelNameType);
15437 assert((IT == SYCLKernels.end() ||
15438 declaresSameEntity(FD, IT->second.getKernelEntryPointDecl())) &&
15439 "SYCL kernel name conflict");
15440 (void)IT;
15441 SYCLKernels.insert(KV: std::make_pair(
15442 x&: KernelNameType, y: BuildSYCLKernelInfo(Context&: *this, KernelNameType, FD)));
15443}
15444
15445const SYCLKernelInfo &ASTContext::getSYCLKernelInfo(QualType T) const {
15446 CanQualType KernelNameType = getCanonicalType(T);
15447 return SYCLKernels.at(Val: KernelNameType);
15448}
15449
15450const SYCLKernelInfo *ASTContext::findSYCLKernelInfo(QualType T) const {
15451 CanQualType KernelNameType = getCanonicalType(T);
15452 auto IT = SYCLKernels.find(Val: KernelNameType);
15453 if (IT != SYCLKernels.end())
15454 return &IT->second;
15455 return nullptr;
15456}
15457
15458OMPTraitInfo &ASTContext::getNewOMPTraitInfo() {
15459 OMPTraitInfoVector.emplace_back(Args: new OMPTraitInfo());
15460 return *OMPTraitInfoVector.back();
15461}
15462
15463const StreamingDiagnostic &clang::
15464operator<<(const StreamingDiagnostic &DB,
15465 const ASTContext::SectionInfo &Section) {
15466 if (Section.Decl)
15467 return DB << Section.Decl;
15468 return DB << "a prior #pragma section";
15469}
15470
15471bool ASTContext::mayExternalize(const Decl *D) const {
15472 bool IsInternalVar =
15473 isa<VarDecl>(Val: D) &&
15474 basicGVALinkageForVariable(Context: *this, VD: cast<VarDecl>(Val: D)) == GVA_Internal;
15475 bool IsExplicitDeviceVar = (D->hasAttr<CUDADeviceAttr>() &&
15476 !D->getAttr<CUDADeviceAttr>()->isImplicit()) ||
15477 (D->hasAttr<CUDAConstantAttr>() &&
15478 !D->getAttr<CUDAConstantAttr>()->isImplicit());
15479 // CUDA/HIP: managed variables need to be externalized since it is
15480 // a declaration in IR, therefore cannot have internal linkage. Kernels in
15481 // anonymous name space needs to be externalized to avoid duplicate symbols.
15482 return (IsInternalVar &&
15483 (D->hasAttr<HIPManagedAttr>() || IsExplicitDeviceVar)) ||
15484 (D->hasAttr<CUDAGlobalAttr>() &&
15485 basicGVALinkageForFunction(Context: *this, FD: cast<FunctionDecl>(Val: D)) ==
15486 GVA_Internal);
15487}
15488
15489bool ASTContext::shouldExternalize(const Decl *D) const {
15490 return mayExternalize(D) &&
15491 (D->hasAttr<HIPManagedAttr>() || D->hasAttr<CUDAGlobalAttr>() ||
15492 CUDADeviceVarODRUsedByHost.count(key: cast<VarDecl>(Val: D)));
15493}
15494
15495StringRef ASTContext::getCUIDHash() const {
15496 if (!CUIDHash.empty())
15497 return CUIDHash;
15498 if (LangOpts.CUID.empty())
15499 return StringRef();
15500 CUIDHash = llvm::utohexstr(X: llvm::MD5Hash(Str: LangOpts.CUID), /*LowerCase=*/true);
15501 return CUIDHash;
15502}
15503
15504const CXXRecordDecl *
15505ASTContext::baseForVTableAuthentication(const CXXRecordDecl *ThisClass) const {
15506 assert(ThisClass);
15507 assert(ThisClass->isPolymorphic());
15508 const CXXRecordDecl *PrimaryBase = ThisClass;
15509 while (1) {
15510 assert(PrimaryBase);
15511 assert(PrimaryBase->isPolymorphic());
15512 auto &Layout = getASTRecordLayout(D: PrimaryBase);
15513 auto Base = Layout.getPrimaryBase();
15514 if (!Base || Base == PrimaryBase || !Base->isPolymorphic())
15515 break;
15516 PrimaryBase = Base;
15517 }
15518 return PrimaryBase;
15519}
15520
15521bool ASTContext::useAbbreviatedThunkName(GlobalDecl VirtualMethodDecl,
15522 StringRef MangledName) {
15523 auto *Method = cast<CXXMethodDecl>(Val: VirtualMethodDecl.getDecl());
15524 assert(Method->isVirtual());
15525 bool DefaultIncludesPointerAuth =
15526 LangOpts.PointerAuthCalls || LangOpts.PointerAuthIntrinsics;
15527
15528 if (!DefaultIncludesPointerAuth)
15529 return true;
15530
15531 auto Existing = ThunksToBeAbbreviated.find(Val: VirtualMethodDecl);
15532 if (Existing != ThunksToBeAbbreviated.end())
15533 return Existing->second.contains(key: MangledName.str());
15534
15535 std::unique_ptr<MangleContext> Mangler(createMangleContext());
15536 llvm::StringMap<llvm::SmallVector<std::string, 2>> Thunks;
15537 auto VtableContext = getVTableContext();
15538 if (const auto *ThunkInfos = VtableContext->getThunkInfo(GD: VirtualMethodDecl)) {
15539 auto *Destructor = dyn_cast<CXXDestructorDecl>(Val: Method);
15540 for (const auto &Thunk : *ThunkInfos) {
15541 SmallString<256> ElidedName;
15542 llvm::raw_svector_ostream ElidedNameStream(ElidedName);
15543 if (Destructor)
15544 Mangler->mangleCXXDtorThunk(DD: Destructor, Type: VirtualMethodDecl.getDtorType(),
15545 Thunk, /* elideOverrideInfo */ ElideOverrideInfo: true,
15546 ElidedNameStream);
15547 else
15548 Mangler->mangleThunk(MD: Method, Thunk, /* elideOverrideInfo */ ElideOverrideInfo: true,
15549 ElidedNameStream);
15550 SmallString<256> MangledName;
15551 llvm::raw_svector_ostream mangledNameStream(MangledName);
15552 if (Destructor)
15553 Mangler->mangleCXXDtorThunk(DD: Destructor, Type: VirtualMethodDecl.getDtorType(),
15554 Thunk, /* elideOverrideInfo */ ElideOverrideInfo: false,
15555 mangledNameStream);
15556 else
15557 Mangler->mangleThunk(MD: Method, Thunk, /* elideOverrideInfo */ ElideOverrideInfo: false,
15558 mangledNameStream);
15559
15560 Thunks[ElidedName].push_back(Elt: std::string(MangledName));
15561 }
15562 }
15563 llvm::StringSet<> SimplifiedThunkNames;
15564 for (auto &ThunkList : Thunks) {
15565 llvm::sort(C&: ThunkList.second);
15566 SimplifiedThunkNames.insert(key: ThunkList.second[0]);
15567 }
15568 bool Result = SimplifiedThunkNames.contains(key: MangledName);
15569 ThunksToBeAbbreviated[VirtualMethodDecl] = std::move(SimplifiedThunkNames);
15570 return Result;
15571}
15572
15573bool ASTContext::arePFPFieldsTriviallyCopyable(const RecordDecl *RD) const {
15574 // Check for trivially-destructible here because non-trivially-destructible
15575 // types will always cause the type and any types derived from it to be
15576 // considered non-trivially-copyable. The same cannot be said for
15577 // trivially-copyable because deleting special members of a type derived from
15578 // a non-trivially-copyable type can cause the derived type to be considered
15579 // trivially copyable.
15580 if (getLangOpts().PointerFieldProtectionTagged)
15581 return !isa<CXXRecordDecl>(Val: RD) ||
15582 cast<CXXRecordDecl>(Val: RD)->hasTrivialDestructor();
15583 return true;
15584}
15585
15586static void findPFPFields(const ASTContext &Ctx, QualType Ty, CharUnits Offset,
15587 std::vector<PFPField> &Fields, bool IncludeVBases) {
15588 if (auto *AT = Ctx.getAsConstantArrayType(T: Ty)) {
15589 if (auto *ElemDecl = AT->getElementType()->getAsCXXRecordDecl()) {
15590 const ASTRecordLayout &ElemRL = Ctx.getASTRecordLayout(D: ElemDecl);
15591 for (unsigned i = 0; i != AT->getSize(); ++i)
15592 findPFPFields(Ctx, Ty: AT->getElementType(), Offset: Offset + i * ElemRL.getSize(),
15593 Fields, IncludeVBases: true);
15594 }
15595 }
15596 auto *Decl = Ty->getAsCXXRecordDecl();
15597 // isPFPType() is inherited from bases and members (including via arrays), so
15598 // we can early exit if it is false. Unions are excluded per the API
15599 // documentation.
15600 if (!Decl || !Decl->isPFPType() || Decl->isUnion())
15601 return;
15602 const ASTRecordLayout &RL = Ctx.getASTRecordLayout(D: Decl);
15603 for (FieldDecl *Field : Decl->fields()) {
15604 CharUnits FieldOffset =
15605 Offset +
15606 Ctx.toCharUnitsFromBits(BitSize: RL.getFieldOffset(FieldNo: Field->getFieldIndex()));
15607 if (Ctx.isPFPField(Field))
15608 Fields.push_back(x: {.Offset: FieldOffset, .Field: Field});
15609 findPFPFields(Ctx, Ty: Field->getType(), Offset: FieldOffset, Fields,
15610 /*IncludeVBases=*/true);
15611 }
15612 // Pass false for IncludeVBases below because vbases are only included in
15613 // layout for top-level types, i.e. not bases or vbases.
15614 for (CXXBaseSpecifier &Base : Decl->bases()) {
15615 if (Base.isVirtual())
15616 continue;
15617 CharUnits BaseOffset =
15618 Offset + RL.getBaseClassOffset(Base: Base.getType()->getAsCXXRecordDecl());
15619 findPFPFields(Ctx, Ty: Base.getType(), Offset: BaseOffset, Fields,
15620 /*IncludeVBases=*/false);
15621 }
15622 if (IncludeVBases) {
15623 for (CXXBaseSpecifier &Base : Decl->vbases()) {
15624 CharUnits BaseOffset =
15625 Offset + RL.getVBaseClassOffset(VBase: Base.getType()->getAsCXXRecordDecl());
15626 findPFPFields(Ctx, Ty: Base.getType(), Offset: BaseOffset, Fields,
15627 /*IncludeVBases=*/false);
15628 }
15629 }
15630}
15631
15632std::vector<PFPField> ASTContext::findPFPFields(QualType Ty) const {
15633 std::vector<PFPField> PFPFields;
15634 ::findPFPFields(Ctx: *this, Ty, Offset: CharUnits::Zero(), Fields&: PFPFields, IncludeVBases: true);
15635 return PFPFields;
15636}
15637
15638bool ASTContext::hasPFPFields(QualType Ty) const {
15639 return !findPFPFields(Ty).empty();
15640}
15641
15642bool ASTContext::isPFPField(const FieldDecl *FD) const {
15643 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: FD->getParent()))
15644 return RD->isPFPType() && FD->getType()->isPointerType() &&
15645 !FD->hasAttr<NoFieldProtectionAttr>();
15646 return false;
15647}
15648
15649void ASTContext::recordMemberDataPointerEvaluation(const ValueDecl *VD) {
15650 auto *FD = dyn_cast<FieldDecl>(Val: VD);
15651 if (!FD)
15652 FD = cast<FieldDecl>(Val: cast<IndirectFieldDecl>(Val: VD)->chain().back());
15653 if (isPFPField(FD))
15654 PFPFieldsWithEvaluatedOffset.insert(X: FD);
15655}
15656
15657void ASTContext::recordOffsetOfEvaluation(const OffsetOfExpr *E) {
15658 if (E->getNumComponents() == 0)
15659 return;
15660 OffsetOfNode Comp = E->getComponent(Idx: E->getNumComponents() - 1);
15661 if (Comp.getKind() != OffsetOfNode::Field)
15662 return;
15663 if (FieldDecl *FD = Comp.getField(); isPFPField(FD))
15664 PFPFieldsWithEvaluatedOffset.insert(X: FD);
15665}
15666