Bug Summary

File:build/source/clang/lib/AST/ASTContext.cpp
Warning:line 4076, column 3
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name ASTContext.cpp -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/source/build-llvm -resource-dir /usr/lib/llvm-16/lib/clang/16 -I tools/clang/lib/AST -I /build/source/clang/lib/AST -I /build/source/clang/include -I tools/clang/include -I include -I /build/source/llvm/include -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-16/lib/clang/16/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/source/build-llvm=build-llvm -fmacro-prefix-map=/build/source/= -fcoverage-prefix-map=/build/source/build-llvm=build-llvm -fcoverage-prefix-map=/build/source/= -source-date-epoch 1670191760 -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -Wno-misleading-indentation -std=c++17 -fdeprecated-macro -fdebug-compilation-dir=/build/source/build-llvm -fdebug-prefix-map=/build/source/build-llvm=build-llvm -fdebug-prefix-map=/build/source/= -fdebug-prefix-map=/build/source/build-llvm=build-llvm -fdebug-prefix-map=/build/source/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2022-12-05-012027-15999-1 -x c++ /build/source/clang/lib/AST/ASTContext.cpp
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 "CXXABI.h"
15#include "Interp/Context.h"
16#include "clang/AST/APValue.h"
17#include "clang/AST/ASTConcept.h"
18#include "clang/AST/ASTMutationListener.h"
19#include "clang/AST/ASTTypeTraits.h"
20#include "clang/AST/Attr.h"
21#include "clang/AST/AttrIterator.h"
22#include "clang/AST/CharUnits.h"
23#include "clang/AST/Comment.h"
24#include "clang/AST/Decl.h"
25#include "clang/AST/DeclBase.h"
26#include "clang/AST/DeclCXX.h"
27#include "clang/AST/DeclContextInternals.h"
28#include "clang/AST/DeclObjC.h"
29#include "clang/AST/DeclOpenMP.h"
30#include "clang/AST/DeclTemplate.h"
31#include "clang/AST/DeclarationName.h"
32#include "clang/AST/DependenceFlags.h"
33#include "clang/AST/Expr.h"
34#include "clang/AST/ExprCXX.h"
35#include "clang/AST/ExprConcepts.h"
36#include "clang/AST/ExternalASTSource.h"
37#include "clang/AST/Mangle.h"
38#include "clang/AST/MangleNumberingContext.h"
39#include "clang/AST/NestedNameSpecifier.h"
40#include "clang/AST/ParentMapContext.h"
41#include "clang/AST/RawCommentList.h"
42#include "clang/AST/RecordLayout.h"
43#include "clang/AST/Stmt.h"
44#include "clang/AST/TemplateBase.h"
45#include "clang/AST/TemplateName.h"
46#include "clang/AST/Type.h"
47#include "clang/AST/TypeLoc.h"
48#include "clang/AST/UnresolvedSet.h"
49#include "clang/AST/VTableBuilder.h"
50#include "clang/Basic/AddressSpaces.h"
51#include "clang/Basic/Builtins.h"
52#include "clang/Basic/CommentOptions.h"
53#include "clang/Basic/ExceptionSpecificationType.h"
54#include "clang/Basic/IdentifierTable.h"
55#include "clang/Basic/LLVM.h"
56#include "clang/Basic/LangOptions.h"
57#include "clang/Basic/Linkage.h"
58#include "clang/Basic/Module.h"
59#include "clang/Basic/NoSanitizeList.h"
60#include "clang/Basic/ObjCRuntime.h"
61#include "clang/Basic/SourceLocation.h"
62#include "clang/Basic/SourceManager.h"
63#include "clang/Basic/Specifiers.h"
64#include "clang/Basic/TargetCXXABI.h"
65#include "clang/Basic/TargetInfo.h"
66#include "clang/Basic/XRayLists.h"
67#include "llvm/ADT/APFixedPoint.h"
68#include "llvm/ADT/APInt.h"
69#include "llvm/ADT/APSInt.h"
70#include "llvm/ADT/ArrayRef.h"
71#include "llvm/ADT/DenseMap.h"
72#include "llvm/ADT/DenseSet.h"
73#include "llvm/ADT/FoldingSet.h"
74#include "llvm/ADT/None.h"
75#include "llvm/ADT/Optional.h"
76#include "llvm/ADT/PointerUnion.h"
77#include "llvm/ADT/STLExtras.h"
78#include "llvm/ADT/SmallPtrSet.h"
79#include "llvm/ADT/SmallVector.h"
80#include "llvm/ADT/StringExtras.h"
81#include "llvm/ADT/StringRef.h"
82#include "llvm/ADT/Triple.h"
83#include "llvm/Support/Capacity.h"
84#include "llvm/Support/Casting.h"
85#include "llvm/Support/Compiler.h"
86#include "llvm/Support/ErrorHandling.h"
87#include "llvm/Support/MD5.h"
88#include "llvm/Support/MathExtras.h"
89#include "llvm/Support/raw_ostream.h"
90#include <algorithm>
91#include <cassert>
92#include <cstddef>
93#include <cstdint>
94#include <cstdlib>
95#include <map>
96#include <memory>
97#include <string>
98#include <tuple>
99#include <utility>
100
101using namespace clang;
102
103enum FloatingRank {
104 BFloat16Rank,
105 Float16Rank,
106 HalfRank,
107 FloatRank,
108 DoubleRank,
109 LongDoubleRank,
110 Float128Rank,
111 Ibm128Rank
112};
113
114/// \returns location that is relevant when searching for Doc comments related
115/// to \p D.
116static SourceLocation getDeclLocForCommentSearch(const Decl *D,
117 SourceManager &SourceMgr) {
118 assert(D)(static_cast <bool> (D) ? void (0) : __assert_fail ("D"
, "clang/lib/AST/ASTContext.cpp", 118, __extension__ __PRETTY_FUNCTION__
))
;
119
120 // User can not attach documentation to implicit declarations.
121 if (D->isImplicit())
122 return {};
123
124 // User can not attach documentation to implicit instantiations.
125 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
126 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
127 return {};
128 }
129
130 if (const auto *VD = dyn_cast<VarDecl>(D)) {
131 if (VD->isStaticDataMember() &&
132 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
133 return {};
134 }
135
136 if (const auto *CRD = dyn_cast<CXXRecordDecl>(D)) {
137 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
138 return {};
139 }
140
141 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
142 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
143 if (TSK == TSK_ImplicitInstantiation ||
144 TSK == TSK_Undeclared)
145 return {};
146 }
147
148 if (const auto *ED = dyn_cast<EnumDecl>(D)) {
149 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
150 return {};
151 }
152 if (const auto *TD = dyn_cast<TagDecl>(D)) {
153 // When tag declaration (but not definition!) is part of the
154 // decl-specifier-seq of some other declaration, it doesn't get comment
155 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
156 return {};
157 }
158 // TODO: handle comments for function parameters properly.
159 if (isa<ParmVarDecl>(D))
160 return {};
161
162 // TODO: we could look up template parameter documentation in the template
163 // documentation.
164 if (isa<TemplateTypeParmDecl>(D) ||
165 isa<NonTypeTemplateParmDecl>(D) ||
166 isa<TemplateTemplateParmDecl>(D))
167 return {};
168
169 // Find declaration location.
170 // For Objective-C declarations we generally don't expect to have multiple
171 // declarators, thus use declaration starting location as the "declaration
172 // location".
173 // For all other declarations multiple declarators are used quite frequently,
174 // so we use the location of the identifier as the "declaration location".
175 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
176 isa<ObjCPropertyDecl>(D) ||
177 isa<RedeclarableTemplateDecl>(D) ||
178 isa<ClassTemplateSpecializationDecl>(D) ||
179 // Allow association with Y across {} in `typedef struct X {} Y`.
180 isa<TypedefDecl>(D))
181 return D->getBeginLoc();
182
183 const SourceLocation DeclLoc = D->getLocation();
184 if (DeclLoc.isMacroID()) {
185 if (isa<TypedefDecl>(D)) {
186 // If location of the typedef name is in a macro, it is because being
187 // declared via a macro. Try using declaration's starting location as
188 // the "declaration location".
189 return D->getBeginLoc();
190 }
191
192 if (const auto *TD = dyn_cast<TagDecl>(D)) {
193 // If location of the tag decl is inside a macro, but the spelling of
194 // the tag name comes from a macro argument, it looks like a special
195 // macro like NS_ENUM is being used to define the tag decl. In that
196 // case, adjust the source location to the expansion loc so that we can
197 // attach the comment to the tag decl.
198 if (SourceMgr.isMacroArgExpansion(DeclLoc) && TD->isCompleteDefinition())
199 return SourceMgr.getExpansionLoc(DeclLoc);
200 }
201 }
202
203 return DeclLoc;
204}
205
206RawComment *ASTContext::getRawCommentForDeclNoCacheImpl(
207 const Decl *D, const SourceLocation RepresentativeLocForDecl,
208 const std::map<unsigned, RawComment *> &CommentsInTheFile) const {
209 // If the declaration doesn't map directly to a location in a file, we
210 // can't find the comment.
211 if (RepresentativeLocForDecl.isInvalid() ||
212 !RepresentativeLocForDecl.isFileID())
213 return nullptr;
214
215 // If there are no comments anywhere, we won't find anything.
216 if (CommentsInTheFile.empty())
217 return nullptr;
218
219 // Decompose the location for the declaration and find the beginning of the
220 // file buffer.
221 const std::pair<FileID, unsigned> DeclLocDecomp =
222 SourceMgr.getDecomposedLoc(RepresentativeLocForDecl);
223
224 // Slow path.
225 auto OffsetCommentBehindDecl =
226 CommentsInTheFile.lower_bound(DeclLocDecomp.second);
227
228 // First check whether we have a trailing comment.
229 if (OffsetCommentBehindDecl != CommentsInTheFile.end()) {
230 RawComment *CommentBehindDecl = OffsetCommentBehindDecl->second;
231 if ((CommentBehindDecl->isDocumentation() ||
232 LangOpts.CommentOpts.ParseAllComments) &&
233 CommentBehindDecl->isTrailingComment() &&
234 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
235 isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
236
237 // Check that Doxygen trailing comment comes after the declaration, starts
238 // on the same line and in the same file as the declaration.
239 if (SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second) ==
240 Comments.getCommentBeginLine(CommentBehindDecl, DeclLocDecomp.first,
241 OffsetCommentBehindDecl->first)) {
242 return CommentBehindDecl;
243 }
244 }
245 }
246
247 // The comment just after the declaration was not a trailing comment.
248 // Let's look at the previous comment.
249 if (OffsetCommentBehindDecl == CommentsInTheFile.begin())
250 return nullptr;
251
252 auto OffsetCommentBeforeDecl = --OffsetCommentBehindDecl;
253 RawComment *CommentBeforeDecl = OffsetCommentBeforeDecl->second;
254
255 // Check that we actually have a non-member Doxygen comment.
256 if (!(CommentBeforeDecl->isDocumentation() ||
257 LangOpts.CommentOpts.ParseAllComments) ||
258 CommentBeforeDecl->isTrailingComment())
259 return nullptr;
260
261 // Decompose the end of the comment.
262 const unsigned CommentEndOffset =
263 Comments.getCommentEndOffset(CommentBeforeDecl);
264
265 // Get the corresponding buffer.
266 bool Invalid = false;
267 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
268 &Invalid).data();
269 if (Invalid)
270 return nullptr;
271
272 // Extract text between the comment and declaration.
273 StringRef Text(Buffer + CommentEndOffset,
274 DeclLocDecomp.second - CommentEndOffset);
275
276 // There should be no other declarations or preprocessor directives between
277 // comment and declaration.
278 if (Text.find_first_of(";{}#@") != StringRef::npos)
279 return nullptr;
280
281 return CommentBeforeDecl;
282}
283
284RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
285 const SourceLocation DeclLoc = getDeclLocForCommentSearch(D, SourceMgr);
286
287 // If the declaration doesn't map directly to a location in a file, we
288 // can't find the comment.
289 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
290 return nullptr;
291
292 if (ExternalSource && !CommentsLoaded) {
293 ExternalSource->ReadComments();
294 CommentsLoaded = true;
295 }
296
297 if (Comments.empty())
298 return nullptr;
299
300 const FileID File = SourceMgr.getDecomposedLoc(DeclLoc).first;
301 if (!File.isValid()) {
302 return nullptr;
303 }
304 const auto CommentsInThisFile = Comments.getCommentsInFile(File);
305 if (!CommentsInThisFile || CommentsInThisFile->empty())
306 return nullptr;
307
308 return getRawCommentForDeclNoCacheImpl(D, DeclLoc, *CommentsInThisFile);
309}
310
311void ASTContext::addComment(const RawComment &RC) {
312 assert(LangOpts.RetainCommentsFromSystemHeaders ||(static_cast <bool> (LangOpts.RetainCommentsFromSystemHeaders
|| !SourceMgr.isInSystemHeader(RC.getSourceRange().getBegin(
))) ? void (0) : __assert_fail ("LangOpts.RetainCommentsFromSystemHeaders || !SourceMgr.isInSystemHeader(RC.getSourceRange().getBegin())"
, "clang/lib/AST/ASTContext.cpp", 313, __extension__ __PRETTY_FUNCTION__
))
313 !SourceMgr.isInSystemHeader(RC.getSourceRange().getBegin()))(static_cast <bool> (LangOpts.RetainCommentsFromSystemHeaders
|| !SourceMgr.isInSystemHeader(RC.getSourceRange().getBegin(
))) ? void (0) : __assert_fail ("LangOpts.RetainCommentsFromSystemHeaders || !SourceMgr.isInSystemHeader(RC.getSourceRange().getBegin())"
, "clang/lib/AST/ASTContext.cpp", 313, __extension__ __PRETTY_FUNCTION__
))
;
314 Comments.addComment(RC, LangOpts.CommentOpts, BumpAlloc);
315}
316
317/// If we have a 'templated' declaration for a template, adjust 'D' to
318/// refer to the actual template.
319/// If we have an implicit instantiation, adjust 'D' to refer to template.
320static const Decl &adjustDeclToTemplate(const Decl &D) {
321 if (const auto *FD = dyn_cast<FunctionDecl>(&D)) {
322 // Is this function declaration part of a function template?
323 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
324 return *FTD;
325
326 // Nothing to do if function is not an implicit instantiation.
327 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
328 return D;
329
330 // Function is an implicit instantiation of a function template?
331 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
332 return *FTD;
333
334 // Function is instantiated from a member definition of a class template?
335 if (const FunctionDecl *MemberDecl =
336 FD->getInstantiatedFromMemberFunction())
337 return *MemberDecl;
338
339 return D;
340 }
341 if (const auto *VD = dyn_cast<VarDecl>(&D)) {
342 // Static data member is instantiated from a member definition of a class
343 // template?
344 if (VD->isStaticDataMember())
345 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
346 return *MemberDecl;
347
348 return D;
349 }
350 if (const auto *CRD = dyn_cast<CXXRecordDecl>(&D)) {
351 // Is this class declaration part of a class template?
352 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
353 return *CTD;
354
355 // Class is an implicit instantiation of a class template or partial
356 // specialization?
357 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
358 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
359 return D;
360 llvm::PointerUnion<ClassTemplateDecl *,
361 ClassTemplatePartialSpecializationDecl *>
362 PU = CTSD->getSpecializedTemplateOrPartial();
363 return PU.is<ClassTemplateDecl *>()
364 ? *static_cast<const Decl *>(PU.get<ClassTemplateDecl *>())
365 : *static_cast<const Decl *>(
366 PU.get<ClassTemplatePartialSpecializationDecl *>());
367 }
368
369 // Class is instantiated from a member definition of a class template?
370 if (const MemberSpecializationInfo *Info =
371 CRD->getMemberSpecializationInfo())
372 return *Info->getInstantiatedFrom();
373
374 return D;
375 }
376 if (const auto *ED = dyn_cast<EnumDecl>(&D)) {
377 // Enum is instantiated from a member definition of a class template?
378 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
379 return *MemberDecl;
380
381 return D;
382 }
383 // FIXME: Adjust alias templates?
384 return D;
385}
386
387const RawComment *ASTContext::getRawCommentForAnyRedecl(
388 const Decl *D,
389 const Decl **OriginalDecl) const {
390 if (!D) {
391 if (OriginalDecl)
392 OriginalDecl = nullptr;
393 return nullptr;
394 }
395
396 D = &adjustDeclToTemplate(*D);
397
398 // Any comment directly attached to D?
399 {
400 auto DeclComment = DeclRawComments.find(D);
401 if (DeclComment != DeclRawComments.end()) {
402 if (OriginalDecl)
403 *OriginalDecl = D;
404 return DeclComment->second;
405 }
406 }
407
408 // Any comment attached to any redeclaration of D?
409 const Decl *CanonicalD = D->getCanonicalDecl();
410 if (!CanonicalD)
411 return nullptr;
412
413 {
414 auto RedeclComment = RedeclChainComments.find(CanonicalD);
415 if (RedeclComment != RedeclChainComments.end()) {
416 if (OriginalDecl)
417 *OriginalDecl = RedeclComment->second;
418 auto CommentAtRedecl = DeclRawComments.find(RedeclComment->second);
419 assert(CommentAtRedecl != DeclRawComments.end() &&(static_cast <bool> (CommentAtRedecl != DeclRawComments
.end() && "This decl is supposed to have comment attached."
) ? void (0) : __assert_fail ("CommentAtRedecl != DeclRawComments.end() && \"This decl is supposed to have comment attached.\""
, "clang/lib/AST/ASTContext.cpp", 420, __extension__ __PRETTY_FUNCTION__
))
420 "This decl is supposed to have comment attached.")(static_cast <bool> (CommentAtRedecl != DeclRawComments
.end() && "This decl is supposed to have comment attached."
) ? void (0) : __assert_fail ("CommentAtRedecl != DeclRawComments.end() && \"This decl is supposed to have comment attached.\""
, "clang/lib/AST/ASTContext.cpp", 420, __extension__ __PRETTY_FUNCTION__
))
;
421 return CommentAtRedecl->second;
422 }
423 }
424
425 // Any redeclarations of D that we haven't checked for comments yet?
426 // We can't use DenseMap::iterator directly since it'd get invalid.
427 auto LastCheckedRedecl = [this, CanonicalD]() -> const Decl * {
428 auto LookupRes = CommentlessRedeclChains.find(CanonicalD);
429 if (LookupRes != CommentlessRedeclChains.end())
430 return LookupRes->second;
431 return nullptr;
432 }();
433
434 for (const auto Redecl : D->redecls()) {
435 assert(Redecl)(static_cast <bool> (Redecl) ? void (0) : __assert_fail
("Redecl", "clang/lib/AST/ASTContext.cpp", 435, __extension__
__PRETTY_FUNCTION__))
;
436 // Skip all redeclarations that have been checked previously.
437 if (LastCheckedRedecl) {
438 if (LastCheckedRedecl == Redecl) {
439 LastCheckedRedecl = nullptr;
440 }
441 continue;
442 }
443 const RawComment *RedeclComment = getRawCommentForDeclNoCache(Redecl);
444 if (RedeclComment) {
445 cacheRawCommentForDecl(*Redecl, *RedeclComment);
446 if (OriginalDecl)
447 *OriginalDecl = Redecl;
448 return RedeclComment;
449 }
450 CommentlessRedeclChains[CanonicalD] = Redecl;
451 }
452
453 if (OriginalDecl)
454 *OriginalDecl = nullptr;
455 return nullptr;
456}
457
458void ASTContext::cacheRawCommentForDecl(const Decl &OriginalD,
459 const RawComment &Comment) const {
460 assert(Comment.isDocumentation() || LangOpts.CommentOpts.ParseAllComments)(static_cast <bool> (Comment.isDocumentation() || LangOpts
.CommentOpts.ParseAllComments) ? void (0) : __assert_fail ("Comment.isDocumentation() || LangOpts.CommentOpts.ParseAllComments"
, "clang/lib/AST/ASTContext.cpp", 460, __extension__ __PRETTY_FUNCTION__
))
;
461 DeclRawComments.try_emplace(&OriginalD, &Comment);
462 const Decl *const CanonicalDecl = OriginalD.getCanonicalDecl();
463 RedeclChainComments.try_emplace(CanonicalDecl, &OriginalD);
464 CommentlessRedeclChains.erase(CanonicalDecl);
465}
466
467static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
468 SmallVectorImpl<const NamedDecl *> &Redeclared) {
469 const DeclContext *DC = ObjCMethod->getDeclContext();
470 if (const auto *IMD = dyn_cast<ObjCImplDecl>(DC)) {
471 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
472 if (!ID)
473 return;
474 // Add redeclared method here.
475 for (const auto *Ext : ID->known_extensions()) {
476 if (ObjCMethodDecl *RedeclaredMethod =
477 Ext->getMethod(ObjCMethod->getSelector(),
478 ObjCMethod->isInstanceMethod()))
479 Redeclared.push_back(RedeclaredMethod);
480 }
481 }
482}
483
484void ASTContext::attachCommentsToJustParsedDecls(ArrayRef<Decl *> Decls,
485 const Preprocessor *PP) {
486 if (Comments.empty() || Decls.empty())
487 return;
488
489 FileID File;
490 for (Decl *D : Decls) {
491 SourceLocation Loc = D->getLocation();
492 if (Loc.isValid()) {
493 // See if there are any new comments that are not attached to a decl.
494 // The location doesn't have to be precise - we care only about the file.
495 File = SourceMgr.getDecomposedLoc(Loc).first;
496 break;
497 }
498 }
499
500 if (File.isInvalid())
501 return;
502
503 auto CommentsInThisFile = Comments.getCommentsInFile(File);
504 if (!CommentsInThisFile || CommentsInThisFile->empty() ||
505 CommentsInThisFile->rbegin()->second->isAttached())
506 return;
507
508 // There is at least one comment not attached to a decl.
509 // Maybe it should be attached to one of Decls?
510 //
511 // Note that this way we pick up not only comments that precede the
512 // declaration, but also comments that *follow* the declaration -- thanks to
513 // the lookahead in the lexer: we've consumed the semicolon and looked
514 // ahead through comments.
515
516 for (const Decl *D : Decls) {
517 assert(D)(static_cast <bool> (D) ? void (0) : __assert_fail ("D"
, "clang/lib/AST/ASTContext.cpp", 517, __extension__ __PRETTY_FUNCTION__
))
;
518 if (D->isInvalidDecl())
519 continue;
520
521 D = &adjustDeclToTemplate(*D);
522
523 const SourceLocation DeclLoc = getDeclLocForCommentSearch(D, SourceMgr);
524
525 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
526 continue;
527
528 if (DeclRawComments.count(D) > 0)
529 continue;
530
531 if (RawComment *const DocComment =
532 getRawCommentForDeclNoCacheImpl(D, DeclLoc, *CommentsInThisFile)) {
533 cacheRawCommentForDecl(*D, *DocComment);
534 comments::FullComment *FC = DocComment->parse(*this, PP, D);
535 ParsedComments[D->getCanonicalDecl()] = FC;
536 }
537 }
538}
539
540comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
541 const Decl *D) const {
542 auto *ThisDeclInfo = new (*this) comments::DeclInfo;
543 ThisDeclInfo->CommentDecl = D;
544 ThisDeclInfo->IsFilled = false;
545 ThisDeclInfo->fill();
546 ThisDeclInfo->CommentDecl = FC->getDecl();
547 if (!ThisDeclInfo->TemplateParameters)
548 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
549 comments::FullComment *CFC =
550 new (*this) comments::FullComment(FC->getBlocks(),
551 ThisDeclInfo);
552 return CFC;
553}
554
555comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
556 const RawComment *RC = getRawCommentForDeclNoCache(D);
557 return RC ? RC->parse(*this, nullptr, D) : nullptr;
558}
559
560comments::FullComment *ASTContext::getCommentForDecl(
561 const Decl *D,
562 const Preprocessor *PP) const {
563 if (!D || D->isInvalidDecl())
564 return nullptr;
565 D = &adjustDeclToTemplate(*D);
566
567 const Decl *Canonical = D->getCanonicalDecl();
568 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
569 ParsedComments.find(Canonical);
570
571 if (Pos != ParsedComments.end()) {
572 if (Canonical != D) {
573 comments::FullComment *FC = Pos->second;
574 comments::FullComment *CFC = cloneFullComment(FC, D);
575 return CFC;
576 }
577 return Pos->second;
578 }
579
580 const Decl *OriginalDecl = nullptr;
581
582 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
583 if (!RC) {
584 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
585 SmallVector<const NamedDecl*, 8> Overridden;
586 const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
587 if (OMD && OMD->isPropertyAccessor())
588 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
589 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
590 return cloneFullComment(FC, D);
591 if (OMD)
592 addRedeclaredMethods(OMD, Overridden);
593 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
594 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
595 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
596 return cloneFullComment(FC, D);
597 }
598 else if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
599 // Attach any tag type's documentation to its typedef if latter
600 // does not have one of its own.
601 QualType QT = TD->getUnderlyingType();
602 if (const auto *TT = QT->getAs<TagType>())
603 if (const Decl *TD = TT->getDecl())
604 if (comments::FullComment *FC = getCommentForDecl(TD, PP))
605 return cloneFullComment(FC, D);
606 }
607 else if (const auto *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
608 while (IC->getSuperClass()) {
609 IC = IC->getSuperClass();
610 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
611 return cloneFullComment(FC, D);
612 }
613 }
614 else if (const auto *CD = dyn_cast<ObjCCategoryDecl>(D)) {
615 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
616 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
617 return cloneFullComment(FC, D);
618 }
619 else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
620 if (!(RD = RD->getDefinition()))
621 return nullptr;
622 // Check non-virtual bases.
623 for (const auto &I : RD->bases()) {
624 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
625 continue;
626 QualType Ty = I.getType();
627 if (Ty.isNull())
628 continue;
629 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
630 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
631 continue;
632
633 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
634 return cloneFullComment(FC, D);
635 }
636 }
637 // Check virtual bases.
638 for (const auto &I : RD->vbases()) {
639 if (I.getAccessSpecifier() != AS_public)
640 continue;
641 QualType Ty = I.getType();
642 if (Ty.isNull())
643 continue;
644 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
645 if (!(VirtualBase= VirtualBase->getDefinition()))
646 continue;
647 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
648 return cloneFullComment(FC, D);
649 }
650 }
651 }
652 return nullptr;
653 }
654
655 // If the RawComment was attached to other redeclaration of this Decl, we
656 // should parse the comment in context of that other Decl. This is important
657 // because comments can contain references to parameter names which can be
658 // different across redeclarations.
659 if (D != OriginalDecl && OriginalDecl)
660 return getCommentForDecl(OriginalDecl, PP);
661
662 comments::FullComment *FC = RC->parse(*this, PP, D);
663 ParsedComments[Canonical] = FC;
664 return FC;
665}
666
667void
668ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
669 const ASTContext &C,
670 TemplateTemplateParmDecl *Parm) {
671 ID.AddInteger(Parm->getDepth());
672 ID.AddInteger(Parm->getPosition());
673 ID.AddBoolean(Parm->isParameterPack());
674
675 TemplateParameterList *Params = Parm->getTemplateParameters();
676 ID.AddInteger(Params->size());
677 for (TemplateParameterList::const_iterator P = Params->begin(),
678 PEnd = Params->end();
679 P != PEnd; ++P) {
680 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
681 ID.AddInteger(0);
682 ID.AddBoolean(TTP->isParameterPack());
683 const TypeConstraint *TC = TTP->getTypeConstraint();
684 ID.AddBoolean(TC != nullptr);
685 if (TC)
686 TC->getImmediatelyDeclaredConstraint()->Profile(ID, C,
687 /*Canonical=*/true);
688 if (TTP->isExpandedParameterPack()) {
689 ID.AddBoolean(true);
690 ID.AddInteger(TTP->getNumExpansionParameters());
691 } else
692 ID.AddBoolean(false);
693 continue;
694 }
695
696 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
697 ID.AddInteger(1);
698 ID.AddBoolean(NTTP->isParameterPack());
699 const Expr *TC = NTTP->getPlaceholderTypeConstraint();
700 ID.AddBoolean(TC != nullptr);
701 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
702 if (TC)
703 TC->Profile(ID, C, /*Canonical=*/true);
704 if (NTTP->isExpandedParameterPack()) {
705 ID.AddBoolean(true);
706 ID.AddInteger(NTTP->getNumExpansionTypes());
707 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
708 QualType T = NTTP->getExpansionType(I);
709 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
710 }
711 } else
712 ID.AddBoolean(false);
713 continue;
714 }
715
716 auto *TTP = cast<TemplateTemplateParmDecl>(*P);
717 ID.AddInteger(2);
718 Profile(ID, C, TTP);
719 }
720 Expr *RequiresClause = Parm->getTemplateParameters()->getRequiresClause();
721 ID.AddBoolean(RequiresClause != nullptr);
722 if (RequiresClause)
723 RequiresClause->Profile(ID, C, /*Canonical=*/true);
724}
725
726static Expr *
727canonicalizeImmediatelyDeclaredConstraint(const ASTContext &C, Expr *IDC,
728 QualType ConstrainedType) {
729 // This is a bit ugly - we need to form a new immediately-declared
730 // constraint that references the new parameter; this would ideally
731 // require semantic analysis (e.g. template<C T> struct S {}; - the
732 // converted arguments of C<T> could be an argument pack if C is
733 // declared as template<typename... T> concept C = ...).
734 // We don't have semantic analysis here so we dig deep into the
735 // ready-made constraint expr and change the thing manually.
736 ConceptSpecializationExpr *CSE;
737 if (const auto *Fold = dyn_cast<CXXFoldExpr>(IDC))
738 CSE = cast<ConceptSpecializationExpr>(Fold->getLHS());
739 else
740 CSE = cast<ConceptSpecializationExpr>(IDC);
741 ArrayRef<TemplateArgument> OldConverted = CSE->getTemplateArguments();
742 SmallVector<TemplateArgument, 3> NewConverted;
743 NewConverted.reserve(OldConverted.size());
744 if (OldConverted.front().getKind() == TemplateArgument::Pack) {
745 // The case:
746 // template<typename... T> concept C = true;
747 // template<C<int> T> struct S; -> constraint is C<{T, int}>
748 NewConverted.push_back(ConstrainedType);
749 llvm::append_range(NewConverted,
750 OldConverted.front().pack_elements().drop_front(1));
751 TemplateArgument NewPack(NewConverted);
752
753 NewConverted.clear();
754 NewConverted.push_back(NewPack);
755 assert(OldConverted.size() == 1 &&(static_cast <bool> (OldConverted.size() == 1 &&
"Template parameter pack should be the last parameter") ? void
(0) : __assert_fail ("OldConverted.size() == 1 && \"Template parameter pack should be the last parameter\""
, "clang/lib/AST/ASTContext.cpp", 756, __extension__ __PRETTY_FUNCTION__
))
756 "Template parameter pack should be the last parameter")(static_cast <bool> (OldConverted.size() == 1 &&
"Template parameter pack should be the last parameter") ? void
(0) : __assert_fail ("OldConverted.size() == 1 && \"Template parameter pack should be the last parameter\""
, "clang/lib/AST/ASTContext.cpp", 756, __extension__ __PRETTY_FUNCTION__
))
;
757 } else {
758 assert(OldConverted.front().getKind() == TemplateArgument::Type &&(static_cast <bool> (OldConverted.front().getKind() == TemplateArgument
::Type && "Unexpected first argument kind for immediately-declared "
"constraint") ? void (0) : __assert_fail ("OldConverted.front().getKind() == TemplateArgument::Type && \"Unexpected first argument kind for immediately-declared \" \"constraint\""
, "clang/lib/AST/ASTContext.cpp", 760, __extension__ __PRETTY_FUNCTION__
))
759 "Unexpected first argument kind for immediately-declared "(static_cast <bool> (OldConverted.front().getKind() == TemplateArgument
::Type && "Unexpected first argument kind for immediately-declared "
"constraint") ? void (0) : __assert_fail ("OldConverted.front().getKind() == TemplateArgument::Type && \"Unexpected first argument kind for immediately-declared \" \"constraint\""
, "clang/lib/AST/ASTContext.cpp", 760, __extension__ __PRETTY_FUNCTION__
))
760 "constraint")(static_cast <bool> (OldConverted.front().getKind() == TemplateArgument
::Type && "Unexpected first argument kind for immediately-declared "
"constraint") ? void (0) : __assert_fail ("OldConverted.front().getKind() == TemplateArgument::Type && \"Unexpected first argument kind for immediately-declared \" \"constraint\""
, "clang/lib/AST/ASTContext.cpp", 760, __extension__ __PRETTY_FUNCTION__
))
;
761 NewConverted.push_back(ConstrainedType);
762 llvm::append_range(NewConverted, OldConverted.drop_front(1));
763 }
764 auto *CSD = ImplicitConceptSpecializationDecl::Create(
765 C, CSE->getNamedConcept()->getDeclContext(),
766 CSE->getNamedConcept()->getLocation(), NewConverted);
767
768 Expr *NewIDC = ConceptSpecializationExpr::Create(
769 C, CSE->getNamedConcept(), CSD, nullptr, CSE->isInstantiationDependent(),
770 CSE->containsUnexpandedParameterPack());
771
772 if (auto *OrigFold = dyn_cast<CXXFoldExpr>(IDC))
773 NewIDC = new (C) CXXFoldExpr(
774 OrigFold->getType(), /*Callee*/ nullptr, SourceLocation(), NewIDC,
775 BinaryOperatorKind::BO_LAnd, SourceLocation(), /*RHS=*/nullptr,
776 SourceLocation(), /*NumExpansions=*/std::nullopt);
777 return NewIDC;
778}
779
780TemplateTemplateParmDecl *
781ASTContext::getCanonicalTemplateTemplateParmDecl(
782 TemplateTemplateParmDecl *TTP) const {
783 // Check if we already have a canonical template template parameter.
784 llvm::FoldingSetNodeID ID;
785 CanonicalTemplateTemplateParm::Profile(ID, *this, TTP);
786 void *InsertPos = nullptr;
787 CanonicalTemplateTemplateParm *Canonical
788 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
789 if (Canonical)
790 return Canonical->getParam();
791
792 // Build a canonical template parameter list.
793 TemplateParameterList *Params = TTP->getTemplateParameters();
794 SmallVector<NamedDecl *, 4> CanonParams;
795 CanonParams.reserve(Params->size());
796 for (TemplateParameterList::const_iterator P = Params->begin(),
797 PEnd = Params->end();
798 P != PEnd; ++P) {
799 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
800 TemplateTypeParmDecl *NewTTP = TemplateTypeParmDecl::Create(
801 *this, getTranslationUnitDecl(), SourceLocation(), SourceLocation(),
802 TTP->getDepth(), TTP->getIndex(), nullptr, false,
803 TTP->isParameterPack(), TTP->hasTypeConstraint(),
804 TTP->isExpandedParameterPack()
805 ? llvm::Optional<unsigned>(TTP->getNumExpansionParameters())
806 : std::nullopt);
807 if (const auto *TC = TTP->getTypeConstraint()) {
808 QualType ParamAsArgument(NewTTP->getTypeForDecl(), 0);
809 Expr *NewIDC = canonicalizeImmediatelyDeclaredConstraint(
810 *this, TC->getImmediatelyDeclaredConstraint(),
811 ParamAsArgument);
812 NewTTP->setTypeConstraint(
813 NestedNameSpecifierLoc(),
814 DeclarationNameInfo(TC->getNamedConcept()->getDeclName(),
815 SourceLocation()), /*FoundDecl=*/nullptr,
816 // Actually canonicalizing a TemplateArgumentLoc is difficult so we
817 // simply omit the ArgsAsWritten
818 TC->getNamedConcept(), /*ArgsAsWritten=*/nullptr, NewIDC);
819 }
820 CanonParams.push_back(NewTTP);
821 } else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
822 QualType T = getCanonicalType(NTTP->getType());
823 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
824 NonTypeTemplateParmDecl *Param;
825 if (NTTP->isExpandedParameterPack()) {
826 SmallVector<QualType, 2> ExpandedTypes;
827 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
828 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
829 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
830 ExpandedTInfos.push_back(
831 getTrivialTypeSourceInfo(ExpandedTypes.back()));
832 }
833
834 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
835 SourceLocation(),
836 SourceLocation(),
837 NTTP->getDepth(),
838 NTTP->getPosition(), nullptr,
839 T,
840 TInfo,
841 ExpandedTypes,
842 ExpandedTInfos);
843 } else {
844 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
845 SourceLocation(),
846 SourceLocation(),
847 NTTP->getDepth(),
848 NTTP->getPosition(), nullptr,
849 T,
850 NTTP->isParameterPack(),
851 TInfo);
852 }
853 if (AutoType *AT = T->getContainedAutoType()) {
854 if (AT->isConstrained()) {
855 Param->setPlaceholderTypeConstraint(
856 canonicalizeImmediatelyDeclaredConstraint(
857 *this, NTTP->getPlaceholderTypeConstraint(), T));
858 }
859 }
860 CanonParams.push_back(Param);
861
862 } else
863 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
864 cast<TemplateTemplateParmDecl>(*P)));
865 }
866
867 Expr *CanonRequiresClause = nullptr;
868 if (Expr *RequiresClause = TTP->getTemplateParameters()->getRequiresClause())
869 CanonRequiresClause = RequiresClause;
870
871 TemplateTemplateParmDecl *CanonTTP
872 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
873 SourceLocation(), TTP->getDepth(),
874 TTP->getPosition(),
875 TTP->isParameterPack(),
876 nullptr,
877 TemplateParameterList::Create(*this, SourceLocation(),
878 SourceLocation(),
879 CanonParams,
880 SourceLocation(),
881 CanonRequiresClause));
882
883 // Get the new insert position for the node we care about.
884 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
885 assert(!Canonical && "Shouldn't be in the map!")(static_cast <bool> (!Canonical && "Shouldn't be in the map!"
) ? void (0) : __assert_fail ("!Canonical && \"Shouldn't be in the map!\""
, "clang/lib/AST/ASTContext.cpp", 885, __extension__ __PRETTY_FUNCTION__
))
;
886 (void)Canonical;
887
888 // Create the canonical template template parameter entry.
889 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
890 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
891 return CanonTTP;
892}
893
894TargetCXXABI::Kind ASTContext::getCXXABIKind() const {
895 auto Kind = getTargetInfo().getCXXABI().getKind();
896 return getLangOpts().CXXABI.value_or(Kind);
897}
898
899CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
900 if (!LangOpts.CPlusPlus) return nullptr;
901
902 switch (getCXXABIKind()) {
903 case TargetCXXABI::AppleARM64:
904 case TargetCXXABI::Fuchsia:
905 case TargetCXXABI::GenericARM: // Same as Itanium at this level
906 case TargetCXXABI::iOS:
907 case TargetCXXABI::WatchOS:
908 case TargetCXXABI::GenericAArch64:
909 case TargetCXXABI::GenericMIPS:
910 case TargetCXXABI::GenericItanium:
911 case TargetCXXABI::WebAssembly:
912 case TargetCXXABI::XL:
913 return CreateItaniumCXXABI(*this);
914 case TargetCXXABI::Microsoft:
915 return CreateMicrosoftCXXABI(*this);
916 }
917 llvm_unreachable("Invalid CXXABI type!")::llvm::llvm_unreachable_internal("Invalid CXXABI type!", "clang/lib/AST/ASTContext.cpp"
, 917)
;
918}
919
920interp::Context &ASTContext::getInterpContext() {
921 if (!InterpContext) {
922 InterpContext.reset(new interp::Context(*this));
923 }
924 return *InterpContext.get();
925}
926
927ParentMapContext &ASTContext::getParentMapContext() {
928 if (!ParentMapCtx)
929 ParentMapCtx.reset(new ParentMapContext(*this));
930 return *ParentMapCtx.get();
931}
932
933static const LangASMap *getAddressSpaceMap(const TargetInfo &T,
934 const LangOptions &LOpts) {
935 if (LOpts.FakeAddressSpaceMap) {
936 // The fake address space map must have a distinct entry for each
937 // language-specific address space.
938 static const unsigned FakeAddrSpaceMap[] = {
939 0, // Default
940 1, // opencl_global
941 3, // opencl_local
942 2, // opencl_constant
943 0, // opencl_private
944 4, // opencl_generic
945 5, // opencl_global_device
946 6, // opencl_global_host
947 7, // cuda_device
948 8, // cuda_constant
949 9, // cuda_shared
950 1, // sycl_global
951 5, // sycl_global_device
952 6, // sycl_global_host
953 3, // sycl_local
954 0, // sycl_private
955 10, // ptr32_sptr
956 11, // ptr32_uptr
957 12, // ptr64
958 13, // hlsl_groupshared
959 };
960 return &FakeAddrSpaceMap;
961 } else {
962 return &T.getAddressSpaceMap();
963 }
964}
965
966static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
967 const LangOptions &LangOpts) {
968 switch (LangOpts.getAddressSpaceMapMangling()) {
969 case LangOptions::ASMM_Target:
970 return TI.useAddressSpaceMapMangling();
971 case LangOptions::ASMM_On:
972 return true;
973 case LangOptions::ASMM_Off:
974 return false;
975 }
976 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.")::llvm::llvm_unreachable_internal("getAddressSpaceMapMangling() doesn't cover anything."
, "clang/lib/AST/ASTContext.cpp", 976)
;
977}
978
979ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
980 IdentifierTable &idents, SelectorTable &sels,
981 Builtin::Context &builtins, TranslationUnitKind TUKind)
982 : ConstantArrayTypes(this_(), ConstantArrayTypesLog2InitSize),
983 FunctionProtoTypes(this_(), FunctionProtoTypesLog2InitSize),
984 TemplateSpecializationTypes(this_()),
985 DependentTemplateSpecializationTypes(this_()), AutoTypes(this_()),
986 SubstTemplateTemplateParmPacks(this_()),
987 CanonTemplateTemplateParms(this_()), SourceMgr(SM), LangOpts(LOpts),
988 NoSanitizeL(new NoSanitizeList(LangOpts.NoSanitizeFiles, SM)),
989 XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles,
990 LangOpts.XRayNeverInstrumentFiles,
991 LangOpts.XRayAttrListFiles, SM)),
992 ProfList(new ProfileList(LangOpts.ProfileListFiles, SM)),
993 PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
994 BuiltinInfo(builtins), TUKind(TUKind), DeclarationNames(*this),
995 Comments(SM), CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
996 CompCategories(this_()), LastSDM(nullptr, 0) {
997 addTranslationUnitDecl();
998}
999
1000void ASTContext::cleanup() {
1001 // Release the DenseMaps associated with DeclContext objects.
1002 // FIXME: Is this the ideal solution?
1003 ReleaseDeclContextMaps();
1004
1005 // Call all of the deallocation functions on all of their targets.
1006 for (auto &Pair : Deallocations)
1007 (Pair.first)(Pair.second);
1008 Deallocations.clear();
1009
1010 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
1011 // because they can contain DenseMaps.
1012 for (llvm::DenseMap<const ObjCContainerDecl*,
1013 const ASTRecordLayout*>::iterator
1014 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
1015 // Increment in loop to prevent using deallocated memory.
1016 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
1017 R->Destroy(*this);
1018 ObjCLayouts.clear();
1019
1020 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
1021 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
1022 // Increment in loop to prevent using deallocated memory.
1023 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
1024 R->Destroy(*this);
1025 }
1026 ASTRecordLayouts.clear();
1027
1028 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
1029 AEnd = DeclAttrs.end();
1030 A != AEnd; ++A)
1031 A->second->~AttrVec();
1032 DeclAttrs.clear();
1033
1034 for (const auto &Value : ModuleInitializers)
1035 Value.second->~PerModuleInitializers();
1036 ModuleInitializers.clear();
1037}
1038
1039ASTContext::~ASTContext() { cleanup(); }
1040
1041void ASTContext::setTraversalScope(const std::vector<Decl *> &TopLevelDecls) {
1042 TraversalScope = TopLevelDecls;
1043 getParentMapContext().clear();
1044}
1045
1046void ASTContext::AddDeallocation(void (*Callback)(void *), void *Data) const {
1047 Deallocations.push_back({Callback, Data});
1048}
1049
1050void
1051ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
1052 ExternalSource = std::move(Source);
1053}
1054
1055void ASTContext::PrintStats() const {
1056 llvm::errs() << "\n*** AST Context Stats:\n";
1057 llvm::errs() << " " << Types.size() << " types total.\n";
1058
1059 unsigned counts[] = {
1060#define TYPE(Name, Parent) 0,
1061#define ABSTRACT_TYPE(Name, Parent)
1062#include "clang/AST/TypeNodes.inc"
1063 0 // Extra
1064 };
1065
1066 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
1067 Type *T = Types[i];
1068 counts[(unsigned)T->getTypeClass()]++;
1069 }
1070
1071 unsigned Idx = 0;
1072 unsigned TotalBytes = 0;
1073#define TYPE(Name, Parent) \
1074 if (counts[Idx]) \
1075 llvm::errs() << " " << counts[Idx] << " " << #Name \
1076 << " types, " << sizeof(Name##Type) << " each " \
1077 << "(" << counts[Idx] * sizeof(Name##Type) \
1078 << " bytes)\n"; \
1079 TotalBytes += counts[Idx] * sizeof(Name##Type); \
1080 ++Idx;
1081#define ABSTRACT_TYPE(Name, Parent)
1082#include "clang/AST/TypeNodes.inc"
1083
1084 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
1085
1086 // Implicit special member functions.
1087 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
1088 << NumImplicitDefaultConstructors
1089 << " implicit default constructors created\n";
1090 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
1091 << NumImplicitCopyConstructors
1092 << " implicit copy constructors created\n";
1093 if (getLangOpts().CPlusPlus)
1094 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
1095 << NumImplicitMoveConstructors
1096 << " implicit move constructors created\n";
1097 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
1098 << NumImplicitCopyAssignmentOperators
1099 << " implicit copy assignment operators created\n";
1100 if (getLangOpts().CPlusPlus)
1101 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
1102 << NumImplicitMoveAssignmentOperators
1103 << " implicit move assignment operators created\n";
1104 llvm::errs() << NumImplicitDestructorsDeclared << "/"
1105 << NumImplicitDestructors
1106 << " implicit destructors created\n";
1107
1108 if (ExternalSource) {
1109 llvm::errs() << "\n";
1110 ExternalSource->PrintStats();
1111 }
1112
1113 BumpAlloc.PrintStats();
1114}
1115
1116void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
1117 bool NotifyListeners) {
1118 if (NotifyListeners)
1119 if (auto *Listener = getASTMutationListener())
1120 Listener->RedefinedHiddenDefinition(ND, M);
1121
1122 MergedDefModules[cast<NamedDecl>(ND->getCanonicalDecl())].push_back(M);
1123}
1124
1125void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) {
1126 auto It = MergedDefModules.find(cast<NamedDecl>(ND->getCanonicalDecl()));
1127 if (It == MergedDefModules.end())
1128 return;
1129
1130 auto &Merged = It->second;
1131 llvm::DenseSet<Module*> Found;
1132 for (Module *&M : Merged)
1133 if (!Found.insert(M).second)
1134 M = nullptr;
1135 llvm::erase_value(Merged, nullptr);
1136}
1137
1138ArrayRef<Module *>
1139ASTContext::getModulesWithMergedDefinition(const NamedDecl *Def) {
1140 auto MergedIt =
1141 MergedDefModules.find(cast<NamedDecl>(Def->getCanonicalDecl()));
1142 if (MergedIt == MergedDefModules.end())
1143 return std::nullopt;
1144 return MergedIt->second;
1145}
1146
1147void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
1148 if (LazyInitializers.empty())
1149 return;
1150
1151 auto *Source = Ctx.getExternalSource();
1152 assert(Source && "lazy initializers but no external source")(static_cast <bool> (Source && "lazy initializers but no external source"
) ? void (0) : __assert_fail ("Source && \"lazy initializers but no external source\""
, "clang/lib/AST/ASTContext.cpp", 1152, __extension__ __PRETTY_FUNCTION__
))
;
1153
1154 auto LazyInits = std::move(LazyInitializers);
1155 LazyInitializers.clear();
1156
1157 for (auto ID : LazyInits)
1158 Initializers.push_back(Source->GetExternalDecl(ID));
1159
1160 assert(LazyInitializers.empty() &&(static_cast <bool> (LazyInitializers.empty() &&
"GetExternalDecl for lazy module initializer added more inits"
) ? void (0) : __assert_fail ("LazyInitializers.empty() && \"GetExternalDecl for lazy module initializer added more inits\""
, "clang/lib/AST/ASTContext.cpp", 1161, __extension__ __PRETTY_FUNCTION__
))
1161 "GetExternalDecl for lazy module initializer added more inits")(static_cast <bool> (LazyInitializers.empty() &&
"GetExternalDecl for lazy module initializer added more inits"
) ? void (0) : __assert_fail ("LazyInitializers.empty() && \"GetExternalDecl for lazy module initializer added more inits\""
, "clang/lib/AST/ASTContext.cpp", 1161, __extension__ __PRETTY_FUNCTION__
))
;
1162}
1163
1164void ASTContext::addModuleInitializer(Module *M, Decl *D) {
1165 // One special case: if we add a module initializer that imports another
1166 // module, and that module's only initializer is an ImportDecl, simplify.
1167 if (const auto *ID = dyn_cast<ImportDecl>(D)) {
1168 auto It = ModuleInitializers.find(ID->getImportedModule());
1169
1170 // Maybe the ImportDecl does nothing at all. (Common case.)
1171 if (It == ModuleInitializers.end())
1172 return;
1173
1174 // Maybe the ImportDecl only imports another ImportDecl.
1175 auto &Imported = *It->second;
1176 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
1177 Imported.resolve(*this);
1178 auto *OnlyDecl = Imported.Initializers.front();
1179 if (isa<ImportDecl>(OnlyDecl))
1180 D = OnlyDecl;
1181 }
1182 }
1183
1184 auto *&Inits = ModuleInitializers[M];
1185 if (!Inits)
1186 Inits = new (*this) PerModuleInitializers;
1187 Inits->Initializers.push_back(D);
1188}
1189
1190void ASTContext::addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs) {
1191 auto *&Inits = ModuleInitializers[M];
1192 if (!Inits)
1193 Inits = new (*this) PerModuleInitializers;
1194 Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
1195 IDs.begin(), IDs.end());
1196}
1197
1198ArrayRef<Decl *> ASTContext::getModuleInitializers(Module *M) {
1199 auto It = ModuleInitializers.find(M);
1200 if (It == ModuleInitializers.end())
1201 return std::nullopt;
1202
1203 auto *Inits = It->second;
1204 Inits->resolve(*this);
1205 return Inits->Initializers;
1206}
1207
1208ExternCContextDecl *ASTContext::getExternCContextDecl() const {
1209 if (!ExternCContext)
1210 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
1211
1212 return ExternCContext;
1213}
1214
1215BuiltinTemplateDecl *
1216ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
1217 const IdentifierInfo *II) const {
1218 auto *BuiltinTemplate =
1219 BuiltinTemplateDecl::Create(*this, getTranslationUnitDecl(), II, BTK);
1220 BuiltinTemplate->setImplicit();
1221 getTranslationUnitDecl()->addDecl(BuiltinTemplate);
1222
1223 return BuiltinTemplate;
1224}
1225
1226BuiltinTemplateDecl *
1227ASTContext::getMakeIntegerSeqDecl() const {
1228 if (!MakeIntegerSeqDecl)
1229 MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq,
1230 getMakeIntegerSeqName());
1231 return MakeIntegerSeqDecl;
1232}
1233
1234BuiltinTemplateDecl *
1235ASTContext::getTypePackElementDecl() const {
1236 if (!TypePackElementDecl)
1237 TypePackElementDecl = buildBuiltinTemplateDecl(BTK__type_pack_element,
1238 getTypePackElementName());
1239 return TypePackElementDecl;
1240}
1241
1242RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
1243 RecordDecl::TagKind TK) const {
1244 SourceLocation Loc;
1245 RecordDecl *NewDecl;
1246 if (getLangOpts().CPlusPlus)
1247 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
1248 Loc, &Idents.get(Name));
1249 else
1250 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
1251 &Idents.get(Name));
1252 NewDecl->setImplicit();
1253 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
1254 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
1255 return NewDecl;
1256}
1257
1258TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
1259 StringRef Name) const {
1260 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
1261 TypedefDecl *NewDecl = TypedefDecl::Create(
1262 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
1263 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
1264 NewDecl->setImplicit();
1265 return NewDecl;
1266}
1267
1268TypedefDecl *ASTContext::getInt128Decl() const {
1269 if (!Int128Decl)
1270 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
1271 return Int128Decl;
1272}
1273
1274TypedefDecl *ASTContext::getUInt128Decl() const {
1275 if (!UInt128Decl)
1276 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
1277 return UInt128Decl;
1278}
1279
1280void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
1281 auto *Ty = new (*this, TypeAlignment) BuiltinType(K);
1282 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
1283 Types.push_back(Ty);
1284}
1285
1286void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
1287 const TargetInfo *AuxTarget) {
1288 assert((!this->Target || this->Target == &Target) &&(static_cast <bool> ((!this->Target || this->Target
== &Target) && "Incorrect target reinitialization"
) ? void (0) : __assert_fail ("(!this->Target || this->Target == &Target) && \"Incorrect target reinitialization\""
, "clang/lib/AST/ASTContext.cpp", 1289, __extension__ __PRETTY_FUNCTION__
))
1289 "Incorrect target reinitialization")(static_cast <bool> ((!this->Target || this->Target
== &Target) && "Incorrect target reinitialization"
) ? void (0) : __assert_fail ("(!this->Target || this->Target == &Target) && \"Incorrect target reinitialization\""
, "clang/lib/AST/ASTContext.cpp", 1289, __extension__ __PRETTY_FUNCTION__
))
;
1290 assert(VoidTy.isNull() && "Context reinitialized?")(static_cast <bool> (VoidTy.isNull() && "Context reinitialized?"
) ? void (0) : __assert_fail ("VoidTy.isNull() && \"Context reinitialized?\""
, "clang/lib/AST/ASTContext.cpp", 1290, __extension__ __PRETTY_FUNCTION__
))
;
1291
1292 this->Target = &Target;
1293 this->AuxTarget = AuxTarget;
1294
1295 ABI.reset(createCXXABI(Target));
1296 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
1297 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
1298
1299 // C99 6.2.5p19.
1300 InitBuiltinType(VoidTy, BuiltinType::Void);
1301
1302 // C99 6.2.5p2.
1303 InitBuiltinType(BoolTy, BuiltinType::Bool);
1304 // C99 6.2.5p3.
1305 if (LangOpts.CharIsSigned)
1306 InitBuiltinType(CharTy, BuiltinType::Char_S);
1307 else
1308 InitBuiltinType(CharTy, BuiltinType::Char_U);
1309 // C99 6.2.5p4.
1310 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
1311 InitBuiltinType(ShortTy, BuiltinType::Short);
1312 InitBuiltinType(IntTy, BuiltinType::Int);
1313 InitBuiltinType(LongTy, BuiltinType::Long);
1314 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
1315
1316 // C99 6.2.5p6.
1317 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
1318 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
1319 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
1320 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
1321 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
1322
1323 // C99 6.2.5p10.
1324 InitBuiltinType(FloatTy, BuiltinType::Float);
1325 InitBuiltinType(DoubleTy, BuiltinType::Double);
1326 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
1327
1328 // GNU extension, __float128 for IEEE quadruple precision
1329 InitBuiltinType(Float128Ty, BuiltinType::Float128);
1330
1331 // __ibm128 for IBM extended precision
1332 InitBuiltinType(Ibm128Ty, BuiltinType::Ibm128);
1333
1334 // C11 extension ISO/IEC TS 18661-3
1335 InitBuiltinType(Float16Ty, BuiltinType::Float16);
1336
1337 // ISO/IEC JTC1 SC22 WG14 N1169 Extension
1338 InitBuiltinType(ShortAccumTy, BuiltinType::ShortAccum);
1339 InitBuiltinType(AccumTy, BuiltinType::Accum);
1340 InitBuiltinType(LongAccumTy, BuiltinType::LongAccum);
1341 InitBuiltinType(UnsignedShortAccumTy, BuiltinType::UShortAccum);
1342 InitBuiltinType(UnsignedAccumTy, BuiltinType::UAccum);
1343 InitBuiltinType(UnsignedLongAccumTy, BuiltinType::ULongAccum);
1344 InitBuiltinType(ShortFractTy, BuiltinType::ShortFract);
1345 InitBuiltinType(FractTy, BuiltinType::Fract);
1346 InitBuiltinType(LongFractTy, BuiltinType::LongFract);
1347 InitBuiltinType(UnsignedShortFractTy, BuiltinType::UShortFract);
1348 InitBuiltinType(UnsignedFractTy, BuiltinType::UFract);
1349 InitBuiltinType(UnsignedLongFractTy, BuiltinType::ULongFract);
1350 InitBuiltinType(SatShortAccumTy, BuiltinType::SatShortAccum);
1351 InitBuiltinType(SatAccumTy, BuiltinType::SatAccum);
1352 InitBuiltinType(SatLongAccumTy, BuiltinType::SatLongAccum);
1353 InitBuiltinType(SatUnsignedShortAccumTy, BuiltinType::SatUShortAccum);
1354 InitBuiltinType(SatUnsignedAccumTy, BuiltinType::SatUAccum);
1355 InitBuiltinType(SatUnsignedLongAccumTy, BuiltinType::SatULongAccum);
1356 InitBuiltinType(SatShortFractTy, BuiltinType::SatShortFract);
1357 InitBuiltinType(SatFractTy, BuiltinType::SatFract);
1358 InitBuiltinType(SatLongFractTy, BuiltinType::SatLongFract);
1359 InitBuiltinType(SatUnsignedShortFractTy, BuiltinType::SatUShortFract);
1360 InitBuiltinType(SatUnsignedFractTy, BuiltinType::SatUFract);
1361 InitBuiltinType(SatUnsignedLongFractTy, BuiltinType::SatULongFract);
1362
1363 // GNU extension, 128-bit integers.
1364 InitBuiltinType(Int128Ty, BuiltinType::Int128);
1365 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
1366
1367 // C++ 3.9.1p5
1368 if (TargetInfo::isTypeSigned(Target.getWCharType()))
1369 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1370 else // -fshort-wchar makes wchar_t be unsigned.
1371 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1372 if (LangOpts.CPlusPlus && LangOpts.WChar)
1373 WideCharTy = WCharTy;
1374 else {
1375 // C99 (or C++ using -fno-wchar).
1376 WideCharTy = getFromTargetType(Target.getWCharType());
1377 }
1378
1379 WIntTy = getFromTargetType(Target.getWIntType());
1380
1381 // C++20 (proposed)
1382 InitBuiltinType(Char8Ty, BuiltinType::Char8);
1383
1384 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1385 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1386 else // C99
1387 Char16Ty = getFromTargetType(Target.getChar16Type());
1388
1389 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1390 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1391 else // C99
1392 Char32Ty = getFromTargetType(Target.getChar32Type());
1393
1394 // Placeholder type for type-dependent expressions whose type is
1395 // completely unknown. No code should ever check a type against
1396 // DependentTy and users should never see it; however, it is here to
1397 // help diagnose failures to properly check for type-dependent
1398 // expressions.
1399 InitBuiltinType(DependentTy, BuiltinType::Dependent);
1400
1401 // Placeholder type for functions.
1402 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1403
1404 // Placeholder type for bound members.
1405 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1406
1407 // Placeholder type for pseudo-objects.
1408 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1409
1410 // "any" type; useful for debugger-like clients.
1411 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1412
1413 // Placeholder type for unbridged ARC casts.
1414 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1415
1416 // Placeholder type for builtin functions.
1417 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1418
1419 // Placeholder type for OMP array sections.
1420 if (LangOpts.OpenMP) {
1421 InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection);
1422 InitBuiltinType(OMPArrayShapingTy, BuiltinType::OMPArrayShaping);
1423 InitBuiltinType(OMPIteratorTy, BuiltinType::OMPIterator);
1424 }
1425 if (LangOpts.MatrixTypes)
1426 InitBuiltinType(IncompleteMatrixIdxTy, BuiltinType::IncompleteMatrixIdx);
1427
1428 // Builtin types for 'id', 'Class', and 'SEL'.
1429 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1430 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
1431 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
1432
1433 if (LangOpts.OpenCL) {
1434#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1435 InitBuiltinType(SingletonId, BuiltinType::Id);
1436#include "clang/Basic/OpenCLImageTypes.def"
1437
1438 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
1439 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
1440 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1441 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
1442 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
1443
1444#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1445 InitBuiltinType(Id##Ty, BuiltinType::Id);
1446#include "clang/Basic/OpenCLExtensionTypes.def"
1447 }
1448
1449 if (Target.hasAArch64SVETypes()) {
1450#define SVE_TYPE(Name, Id, SingletonId) \
1451 InitBuiltinType(SingletonId, BuiltinType::Id);
1452#include "clang/Basic/AArch64SVEACLETypes.def"
1453 }
1454
1455 if (Target.getTriple().isPPC64()) {
1456#define PPC_VECTOR_MMA_TYPE(Name, Id, Size) \
1457 InitBuiltinType(Id##Ty, BuiltinType::Id);
1458#include "clang/Basic/PPCTypes.def"
1459#define PPC_VECTOR_VSX_TYPE(Name, Id, Size) \
1460 InitBuiltinType(Id##Ty, BuiltinType::Id);
1461#include "clang/Basic/PPCTypes.def"
1462 }
1463
1464 if (Target.hasRISCVVTypes()) {
1465#define RVV_TYPE(Name, Id, SingletonId) \
1466 InitBuiltinType(SingletonId, BuiltinType::Id);
1467#include "clang/Basic/RISCVVTypes.def"
1468 }
1469
1470 // Builtin type for __objc_yes and __objc_no
1471 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1472 SignedCharTy : BoolTy);
1473
1474 ObjCConstantStringType = QualType();
1475
1476 ObjCSuperType = QualType();
1477
1478 // void * type
1479 if (LangOpts.OpenCLGenericAddressSpace) {
1480 auto Q = VoidTy.getQualifiers();
1481 Q.setAddressSpace(LangAS::opencl_generic);
1482 VoidPtrTy = getPointerType(getCanonicalType(
1483 getQualifiedType(VoidTy.getUnqualifiedType(), Q)));
1484 } else {
1485 VoidPtrTy = getPointerType(VoidTy);
1486 }
1487
1488 // nullptr type (C++0x 2.14.7)
1489 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
1490
1491 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1492 InitBuiltinType(HalfTy, BuiltinType::Half);
1493
1494 InitBuiltinType(BFloat16Ty, BuiltinType::BFloat16);
1495
1496 // Builtin type used to help define __builtin_va_list.
1497 VaListTagDecl = nullptr;
1498
1499 // MSVC predeclares struct _GUID, and we need it to create MSGuidDecls.
1500 if (LangOpts.MicrosoftExt || LangOpts.Borland) {
1501 MSGuidTagDecl = buildImplicitRecord("_GUID");
1502 getTranslationUnitDecl()->addDecl(MSGuidTagDecl);
1503 }
1504}
1505
1506DiagnosticsEngine &ASTContext::getDiagnostics() const {
1507 return SourceMgr.getDiagnostics();
1508}
1509
1510AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1511 AttrVec *&Result = DeclAttrs[D];
1512 if (!Result) {
1513 void *Mem = Allocate(sizeof(AttrVec));
1514 Result = new (Mem) AttrVec;
1515 }
1516
1517 return *Result;
1518}
1519
1520/// Erase the attributes corresponding to the given declaration.
1521void ASTContext::eraseDeclAttrs(const Decl *D) {
1522 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1523 if (Pos != DeclAttrs.end()) {
1524 Pos->second->~AttrVec();
1525 DeclAttrs.erase(Pos);
1526 }
1527}
1528
1529// FIXME: Remove ?
1530MemberSpecializationInfo *
1531ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
1532 assert(Var->isStaticDataMember() && "Not a static data member")(static_cast <bool> (Var->isStaticDataMember() &&
"Not a static data member") ? void (0) : __assert_fail ("Var->isStaticDataMember() && \"Not a static data member\""
, "clang/lib/AST/ASTContext.cpp", 1532, __extension__ __PRETTY_FUNCTION__
))
;
1533 return getTemplateOrSpecializationInfo(Var)
1534 .dyn_cast<MemberSpecializationInfo *>();
1535}
1536
1537ASTContext::TemplateOrSpecializationInfo
1538ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1539 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1540 TemplateOrInstantiation.find(Var);
1541 if (Pos == TemplateOrInstantiation.end())
1542 return {};
1543
1544 return Pos->second;
1545}
1546
1547void
1548ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
1549 TemplateSpecializationKind TSK,
1550 SourceLocation PointOfInstantiation) {
1551 assert(Inst->isStaticDataMember() && "Not a static data member")(static_cast <bool> (Inst->isStaticDataMember() &&
"Not a static data member") ? void (0) : __assert_fail ("Inst->isStaticDataMember() && \"Not a static data member\""
, "clang/lib/AST/ASTContext.cpp", 1551, __extension__ __PRETTY_FUNCTION__
))
;
1552 assert(Tmpl->isStaticDataMember() && "Not a static data member")(static_cast <bool> (Tmpl->isStaticDataMember() &&
"Not a static data member") ? void (0) : __assert_fail ("Tmpl->isStaticDataMember() && \"Not a static data member\""
, "clang/lib/AST/ASTContext.cpp", 1552, __extension__ __PRETTY_FUNCTION__
))
;
1553 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1554 Tmpl, TSK, PointOfInstantiation));
1555}
1556
1557void
1558ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1559 TemplateOrSpecializationInfo TSI) {
1560 assert(!TemplateOrInstantiation[Inst] &&(static_cast <bool> (!TemplateOrInstantiation[Inst] &&
"Already noted what the variable was instantiated from") ? void
(0) : __assert_fail ("!TemplateOrInstantiation[Inst] && \"Already noted what the variable was instantiated from\""
, "clang/lib/AST/ASTContext.cpp", 1561, __extension__ __PRETTY_FUNCTION__
))
1561 "Already noted what the variable was instantiated from")(static_cast <bool> (!TemplateOrInstantiation[Inst] &&
"Already noted what the variable was instantiated from") ? void
(0) : __assert_fail ("!TemplateOrInstantiation[Inst] && \"Already noted what the variable was instantiated from\""
, "clang/lib/AST/ASTContext.cpp", 1561, __extension__ __PRETTY_FUNCTION__
))
;
1562 TemplateOrInstantiation[Inst] = TSI;
1563}
1564
1565NamedDecl *
1566ASTContext::getInstantiatedFromUsingDecl(NamedDecl *UUD) {
1567 auto Pos = InstantiatedFromUsingDecl.find(UUD);
1568 if (Pos == InstantiatedFromUsingDecl.end())
1569 return nullptr;
1570
1571 return Pos->second;
1572}
1573
1574void
1575ASTContext::setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern) {
1576 assert((isa<UsingDecl>(Pattern) ||(static_cast <bool> ((isa<UsingDecl>(Pattern) || isa
<UnresolvedUsingValueDecl>(Pattern) || isa<UnresolvedUsingTypenameDecl
>(Pattern)) && "pattern decl is not a using decl")
? void (0) : __assert_fail ("(isa<UsingDecl>(Pattern) || isa<UnresolvedUsingValueDecl>(Pattern) || isa<UnresolvedUsingTypenameDecl>(Pattern)) && \"pattern decl is not a using decl\""
, "clang/lib/AST/ASTContext.cpp", 1579, __extension__ __PRETTY_FUNCTION__
))
1577 isa<UnresolvedUsingValueDecl>(Pattern) ||(static_cast <bool> ((isa<UsingDecl>(Pattern) || isa
<UnresolvedUsingValueDecl>(Pattern) || isa<UnresolvedUsingTypenameDecl
>(Pattern)) && "pattern decl is not a using decl")
? void (0) : __assert_fail ("(isa<UsingDecl>(Pattern) || isa<UnresolvedUsingValueDecl>(Pattern) || isa<UnresolvedUsingTypenameDecl>(Pattern)) && \"pattern decl is not a using decl\""
, "clang/lib/AST/ASTContext.cpp", 1579, __extension__ __PRETTY_FUNCTION__
))
1578 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&(static_cast <bool> ((isa<UsingDecl>(Pattern) || isa
<UnresolvedUsingValueDecl>(Pattern) || isa<UnresolvedUsingTypenameDecl
>(Pattern)) && "pattern decl is not a using decl")
? void (0) : __assert_fail ("(isa<UsingDecl>(Pattern) || isa<UnresolvedUsingValueDecl>(Pattern) || isa<UnresolvedUsingTypenameDecl>(Pattern)) && \"pattern decl is not a using decl\""
, "clang/lib/AST/ASTContext.cpp", 1579, __extension__ __PRETTY_FUNCTION__
))
1579 "pattern decl is not a using decl")(static_cast <bool> ((isa<UsingDecl>(Pattern) || isa
<UnresolvedUsingValueDecl>(Pattern) || isa<UnresolvedUsingTypenameDecl
>(Pattern)) && "pattern decl is not a using decl")
? void (0) : __assert_fail ("(isa<UsingDecl>(Pattern) || isa<UnresolvedUsingValueDecl>(Pattern) || isa<UnresolvedUsingTypenameDecl>(Pattern)) && \"pattern decl is not a using decl\""
, "clang/lib/AST/ASTContext.cpp", 1579, __extension__ __PRETTY_FUNCTION__
))
;
1580 assert((isa<UsingDecl>(Inst) ||(static_cast <bool> ((isa<UsingDecl>(Inst) || isa
<UnresolvedUsingValueDecl>(Inst) || isa<UnresolvedUsingTypenameDecl
>(Inst)) && "instantiation did not produce a using decl"
) ? void (0) : __assert_fail ("(isa<UsingDecl>(Inst) || isa<UnresolvedUsingValueDecl>(Inst) || isa<UnresolvedUsingTypenameDecl>(Inst)) && \"instantiation did not produce a using decl\""
, "clang/lib/AST/ASTContext.cpp", 1583, __extension__ __PRETTY_FUNCTION__
))
1581 isa<UnresolvedUsingValueDecl>(Inst) ||(static_cast <bool> ((isa<UsingDecl>(Inst) || isa
<UnresolvedUsingValueDecl>(Inst) || isa<UnresolvedUsingTypenameDecl
>(Inst)) && "instantiation did not produce a using decl"
) ? void (0) : __assert_fail ("(isa<UsingDecl>(Inst) || isa<UnresolvedUsingValueDecl>(Inst) || isa<UnresolvedUsingTypenameDecl>(Inst)) && \"instantiation did not produce a using decl\""
, "clang/lib/AST/ASTContext.cpp", 1583, __extension__ __PRETTY_FUNCTION__
))
1582 isa<UnresolvedUsingTypenameDecl>(Inst)) &&(static_cast <bool> ((isa<UsingDecl>(Inst) || isa
<UnresolvedUsingValueDecl>(Inst) || isa<UnresolvedUsingTypenameDecl
>(Inst)) && "instantiation did not produce a using decl"
) ? void (0) : __assert_fail ("(isa<UsingDecl>(Inst) || isa<UnresolvedUsingValueDecl>(Inst) || isa<UnresolvedUsingTypenameDecl>(Inst)) && \"instantiation did not produce a using decl\""
, "clang/lib/AST/ASTContext.cpp", 1583, __extension__ __PRETTY_FUNCTION__
))
1583 "instantiation did not produce a using decl")(static_cast <bool> ((isa<UsingDecl>(Inst) || isa
<UnresolvedUsingValueDecl>(Inst) || isa<UnresolvedUsingTypenameDecl
>(Inst)) && "instantiation did not produce a using decl"
) ? void (0) : __assert_fail ("(isa<UsingDecl>(Inst) || isa<UnresolvedUsingValueDecl>(Inst) || isa<UnresolvedUsingTypenameDecl>(Inst)) && \"instantiation did not produce a using decl\""
, "clang/lib/AST/ASTContext.cpp", 1583, __extension__ __PRETTY_FUNCTION__
))
;
1584 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists")(static_cast <bool> (!InstantiatedFromUsingDecl[Inst] &&
"pattern already exists") ? void (0) : __assert_fail ("!InstantiatedFromUsingDecl[Inst] && \"pattern already exists\""
, "clang/lib/AST/ASTContext.cpp", 1584, __extension__ __PRETTY_FUNCTION__
))
;
1585 InstantiatedFromUsingDecl[Inst] = Pattern;
1586}
1587
1588UsingEnumDecl *
1589ASTContext::getInstantiatedFromUsingEnumDecl(UsingEnumDecl *UUD) {
1590 auto Pos = InstantiatedFromUsingEnumDecl.find(UUD);
1591 if (Pos == InstantiatedFromUsingEnumDecl.end())
1592 return nullptr;
1593
1594 return Pos->second;
1595}
1596
1597void ASTContext::setInstantiatedFromUsingEnumDecl(UsingEnumDecl *Inst,
1598 UsingEnumDecl *Pattern) {
1599 assert(!InstantiatedFromUsingEnumDecl[Inst] && "pattern already exists")(static_cast <bool> (!InstantiatedFromUsingEnumDecl[Inst
] && "pattern already exists") ? void (0) : __assert_fail
("!InstantiatedFromUsingEnumDecl[Inst] && \"pattern already exists\""
, "clang/lib/AST/ASTContext.cpp", 1599, __extension__ __PRETTY_FUNCTION__
))
;
1600 InstantiatedFromUsingEnumDecl[Inst] = Pattern;
1601}
1602
1603UsingShadowDecl *
1604ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1605 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1606 = InstantiatedFromUsingShadowDecl.find(Inst);
1607 if (Pos == InstantiatedFromUsingShadowDecl.end())
1608 return nullptr;
1609
1610 return Pos->second;
1611}
1612
1613void
1614ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1615 UsingShadowDecl *Pattern) {
1616 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists")(static_cast <bool> (!InstantiatedFromUsingShadowDecl[Inst
] && "pattern already exists") ? void (0) : __assert_fail
("!InstantiatedFromUsingShadowDecl[Inst] && \"pattern already exists\""
, "clang/lib/AST/ASTContext.cpp", 1616, __extension__ __PRETTY_FUNCTION__
))
;
1617 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
1618}
1619
1620FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1621 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1622 = InstantiatedFromUnnamedFieldDecl.find(Field);
1623 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
1624 return nullptr;
1625
1626 return Pos->second;
1627}
1628
1629void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1630 FieldDecl *Tmpl) {
1631 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed")(static_cast <bool> (!Inst->getDeclName() &&
"Instantiated field decl is not unnamed") ? void (0) : __assert_fail
("!Inst->getDeclName() && \"Instantiated field decl is not unnamed\""
, "clang/lib/AST/ASTContext.cpp", 1631, __extension__ __PRETTY_FUNCTION__
))
;
1632 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed")(static_cast <bool> (!Tmpl->getDeclName() &&
"Template field decl is not unnamed") ? void (0) : __assert_fail
("!Tmpl->getDeclName() && \"Template field decl is not unnamed\""
, "clang/lib/AST/ASTContext.cpp", 1632, __extension__ __PRETTY_FUNCTION__
))
;
1633 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&(static_cast <bool> (!InstantiatedFromUnnamedFieldDecl[
Inst] && "Already noted what unnamed field was instantiated from"
) ? void (0) : __assert_fail ("!InstantiatedFromUnnamedFieldDecl[Inst] && \"Already noted what unnamed field was instantiated from\""
, "clang/lib/AST/ASTContext.cpp", 1634, __extension__ __PRETTY_FUNCTION__
))
1634 "Already noted what unnamed field was instantiated from")(static_cast <bool> (!InstantiatedFromUnnamedFieldDecl[
Inst] && "Already noted what unnamed field was instantiated from"
) ? void (0) : __assert_fail ("!InstantiatedFromUnnamedFieldDecl[Inst] && \"Already noted what unnamed field was instantiated from\""
, "clang/lib/AST/ASTContext.cpp", 1634, __extension__ __PRETTY_FUNCTION__
))
;
1635
1636 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1637}
1638
1639ASTContext::overridden_cxx_method_iterator
1640ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1641 return overridden_methods(Method).begin();
1642}
1643
1644ASTContext::overridden_cxx_method_iterator
1645ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1646 return overridden_methods(Method).end();
1647}
1648
1649unsigned
1650ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1651 auto Range = overridden_methods(Method);
1652 return Range.end() - Range.begin();
1653}
1654
1655ASTContext::overridden_method_range
1656ASTContext::overridden_methods(const CXXMethodDecl *Method) const {
1657 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1658 OverriddenMethods.find(Method->getCanonicalDecl());
1659 if (Pos == OverriddenMethods.end())
1660 return overridden_method_range(nullptr, nullptr);
1661 return overridden_method_range(Pos->second.begin(), Pos->second.end());
1662}
1663
1664void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1665 const CXXMethodDecl *Overridden) {
1666 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl())(static_cast <bool> (Method->isCanonicalDecl() &&
Overridden->isCanonicalDecl()) ? void (0) : __assert_fail
("Method->isCanonicalDecl() && Overridden->isCanonicalDecl()"
, "clang/lib/AST/ASTContext.cpp", 1666, __extension__ __PRETTY_FUNCTION__
))
;
1667 OverriddenMethods[Method].push_back(Overridden);
1668}
1669
1670void ASTContext::getOverriddenMethods(
1671 const NamedDecl *D,
1672 SmallVectorImpl<const NamedDecl *> &Overridden) const {
1673 assert(D)(static_cast <bool> (D) ? void (0) : __assert_fail ("D"
, "clang/lib/AST/ASTContext.cpp", 1673, __extension__ __PRETTY_FUNCTION__
))
;
1674
1675 if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
1676 Overridden.append(overridden_methods_begin(CXXMethod),
1677 overridden_methods_end(CXXMethod));
1678 return;
1679 }
1680
1681 const auto *Method = dyn_cast<ObjCMethodDecl>(D);
1682 if (!Method)
1683 return;
1684
1685 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1686 Method->getOverriddenMethods(OverDecls);
1687 Overridden.append(OverDecls.begin(), OverDecls.end());
1688}
1689
1690void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1691 assert(!Import->getNextLocalImport() &&(static_cast <bool> (!Import->getNextLocalImport() &&
"Import declaration already in the chain") ? void (0) : __assert_fail
("!Import->getNextLocalImport() && \"Import declaration already in the chain\""
, "clang/lib/AST/ASTContext.cpp", 1692, __extension__ __PRETTY_FUNCTION__
))
1692 "Import declaration already in the chain")(static_cast <bool> (!Import->getNextLocalImport() &&
"Import declaration already in the chain") ? void (0) : __assert_fail
("!Import->getNextLocalImport() && \"Import declaration already in the chain\""
, "clang/lib/AST/ASTContext.cpp", 1692, __extension__ __PRETTY_FUNCTION__
))
;
1693 assert(!Import->isFromASTFile() && "Non-local import declaration")(static_cast <bool> (!Import->isFromASTFile() &&
"Non-local import declaration") ? void (0) : __assert_fail (
"!Import->isFromASTFile() && \"Non-local import declaration\""
, "clang/lib/AST/ASTContext.cpp", 1693, __extension__ __PRETTY_FUNCTION__
))
;
1694 if (!FirstLocalImport) {
1695 FirstLocalImport = Import;
1696 LastLocalImport = Import;
1697 return;
1698 }
1699
1700 LastLocalImport->setNextLocalImport(Import);
1701 LastLocalImport = Import;
1702}
1703
1704//===----------------------------------------------------------------------===//
1705// Type Sizing and Analysis
1706//===----------------------------------------------------------------------===//
1707
1708/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1709/// scalar floating point type.
1710const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
1711 switch (T->castAs<BuiltinType>()->getKind()) {
1712 default:
1713 llvm_unreachable("Not a floating point type!")::llvm::llvm_unreachable_internal("Not a floating point type!"
, "clang/lib/AST/ASTContext.cpp", 1713)
;
1714 case BuiltinType::BFloat16:
1715 return Target->getBFloat16Format();
1716 case BuiltinType::Float16:
1717 return Target->getHalfFormat();
1718 case BuiltinType::Half:
1719 // For HLSL, when the native half type is disabled, half will be treat as
1720 // float.
1721 if (getLangOpts().HLSL)
1722 if (getLangOpts().NativeHalfType)
1723 return Target->getHalfFormat();
1724 else
1725 return Target->getFloatFormat();
1726 else
1727 return Target->getHalfFormat();
1728 case BuiltinType::Float: return Target->getFloatFormat();
1729 case BuiltinType::Double: return Target->getDoubleFormat();
1730 case BuiltinType::Ibm128:
1731 return Target->getIbm128Format();
1732 case BuiltinType::LongDouble:
1733 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice)
1734 return AuxTarget->getLongDoubleFormat();
1735 return Target->getLongDoubleFormat();
1736 case BuiltinType::Float128:
1737 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice)
1738 return AuxTarget->getFloat128Format();
1739 return Target->getFloat128Format();
1740 }
1741}
1742
1743CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
1744 unsigned Align = Target->getCharWidth();
1745
1746 bool UseAlignAttrOnly = false;
1747 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1748 Align = AlignFromAttr;
1749
1750 // __attribute__((aligned)) can increase or decrease alignment
1751 // *except* on a struct or struct member, where it only increases
1752 // alignment unless 'packed' is also specified.
1753 //
1754 // It is an error for alignas to decrease alignment, so we can
1755 // ignore that possibility; Sema should diagnose it.
1756 if (isa<FieldDecl>(D)) {
1757 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1758 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1759 } else {
1760 UseAlignAttrOnly = true;
1761 }
1762 }
1763 else if (isa<FieldDecl>(D))
1764 UseAlignAttrOnly =
1765 D->hasAttr<PackedAttr>() ||
1766 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1767
1768 // If we're using the align attribute only, just ignore everything
1769 // else about the declaration and its type.
1770 if (UseAlignAttrOnly) {
1771 // do nothing
1772 } else if (const auto *VD = dyn_cast<ValueDecl>(D)) {
1773 QualType T = VD->getType();
1774 if (const auto *RT = T->getAs<ReferenceType>()) {
1775 if (ForAlignof)
1776 T = RT->getPointeeType();
1777 else
1778 T = getPointerType(RT->getPointeeType());
1779 }
1780 QualType BaseT = getBaseElementType(T);
1781 if (T->isFunctionType())
1782 Align = getTypeInfoImpl(T.getTypePtr()).Align;
1783 else if (!BaseT->isIncompleteType()) {
1784 // Adjust alignments of declarations with array type by the
1785 // large-array alignment on the target.
1786 if (const ArrayType *arrayType = getAsArrayType(T)) {
1787 unsigned MinWidth = Target->getLargeArrayMinWidth();
1788 if (!ForAlignof && MinWidth) {
1789 if (isa<VariableArrayType>(arrayType))
1790 Align = std::max(Align, Target->getLargeArrayAlign());
1791 else if (isa<ConstantArrayType>(arrayType) &&
1792 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1793 Align = std::max(Align, Target->getLargeArrayAlign());
1794 }
1795 }
1796 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
1797 if (BaseT.getQualifiers().hasUnaligned())
1798 Align = Target->getCharWidth();
1799 if (const auto *VD = dyn_cast<VarDecl>(D)) {
1800 if (VD->hasGlobalStorage() && !ForAlignof) {
1801 uint64_t TypeSize = getTypeSize(T.getTypePtr());
1802 Align = std::max(Align, getTargetInfo().getMinGlobalAlign(TypeSize));
1803 }
1804 }
1805 }
1806
1807 // Fields can be subject to extra alignment constraints, like if
1808 // the field is packed, the struct is packed, or the struct has a
1809 // a max-field-alignment constraint (#pragma pack). So calculate
1810 // the actual alignment of the field within the struct, and then
1811 // (as we're expected to) constrain that by the alignment of the type.
1812 if (const auto *Field = dyn_cast<FieldDecl>(VD)) {
1813 const RecordDecl *Parent = Field->getParent();
1814 // We can only produce a sensible answer if the record is valid.
1815 if (!Parent->isInvalidDecl()) {
1816 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
1817
1818 // Start with the record's overall alignment.
1819 unsigned FieldAlign = toBits(Layout.getAlignment());
1820
1821 // Use the GCD of that and the offset within the record.
1822 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1823 if (Offset > 0) {
1824 // Alignment is always a power of 2, so the GCD will be a power of 2,
1825 // which means we get to do this crazy thing instead of Euclid's.
1826 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1827 if (LowBitOfOffset < FieldAlign)
1828 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1829 }
1830
1831 Align = std::min(Align, FieldAlign);
1832 }
1833 }
1834 }
1835
1836 // Some targets have hard limitation on the maximum requestable alignment in
1837 // aligned attribute for static variables.
1838 const unsigned MaxAlignedAttr = getTargetInfo().getMaxAlignedAttribute();
1839 const auto *VD = dyn_cast<VarDecl>(D);
1840 if (MaxAlignedAttr && VD && VD->getStorageClass() == SC_Static)
1841 Align = std::min(Align, MaxAlignedAttr);
1842
1843 return toCharUnitsFromBits(Align);
1844}
1845
1846CharUnits ASTContext::getExnObjectAlignment() const {
1847 return toCharUnitsFromBits(Target->getExnObjectAlignment());
1848}
1849
1850// getTypeInfoDataSizeInChars - Return the size of a type, in
1851// chars. If the type is a record, its data size is returned. This is
1852// the size of the memcpy that's performed when assigning this type
1853// using a trivial copy/move assignment operator.
1854TypeInfoChars ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1855 TypeInfoChars Info = getTypeInfoInChars(T);
1856
1857 // In C++, objects can sometimes be allocated into the tail padding
1858 // of a base-class subobject. We decide whether that's possible
1859 // during class layout, so here we can just trust the layout results.
1860 if (getLangOpts().CPlusPlus) {
1861 if (const auto *RT = T->getAs<RecordType>()) {
1862 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1863 Info.Width = layout.getDataSize();
1864 }
1865 }
1866
1867 return Info;
1868}
1869
1870/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1871/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1872TypeInfoChars
1873static getConstantArrayInfoInChars(const ASTContext &Context,
1874 const ConstantArrayType *CAT) {
1875 TypeInfoChars EltInfo = Context.getTypeInfoInChars(CAT->getElementType());
1876 uint64_t Size = CAT->getSize().getZExtValue();
1877 assert((Size == 0 || static_cast<uint64_t>(EltInfo.Width.getQuantity()) <=(static_cast <bool> ((Size == 0 || static_cast<uint64_t
>(EltInfo.Width.getQuantity()) <= (uint64_t)(-1)/Size) &&
"Overflow in array type char size evaluation") ? void (0) : __assert_fail
("(Size == 0 || static_cast<uint64_t>(EltInfo.Width.getQuantity()) <= (uint64_t)(-1)/Size) && \"Overflow in array type char size evaluation\""
, "clang/lib/AST/ASTContext.cpp", 1879, __extension__ __PRETTY_FUNCTION__
))
1878 (uint64_t)(-1)/Size) &&(static_cast <bool> ((Size == 0 || static_cast<uint64_t
>(EltInfo.Width.getQuantity()) <= (uint64_t)(-1)/Size) &&
"Overflow in array type char size evaluation") ? void (0) : __assert_fail
("(Size == 0 || static_cast<uint64_t>(EltInfo.Width.getQuantity()) <= (uint64_t)(-1)/Size) && \"Overflow in array type char size evaluation\""
, "clang/lib/AST/ASTContext.cpp", 1879, __extension__ __PRETTY_FUNCTION__
))
1879 "Overflow in array type char size evaluation")(static_cast <bool> ((Size == 0 || static_cast<uint64_t
>(EltInfo.Width.getQuantity()) <= (uint64_t)(-1)/Size) &&
"Overflow in array type char size evaluation") ? void (0) : __assert_fail
("(Size == 0 || static_cast<uint64_t>(EltInfo.Width.getQuantity()) <= (uint64_t)(-1)/Size) && \"Overflow in array type char size evaluation\""
, "clang/lib/AST/ASTContext.cpp", 1879, __extension__ __PRETTY_FUNCTION__
))
;
1880 uint64_t Width = EltInfo.Width.getQuantity() * Size;
1881 unsigned Align = EltInfo.Align.getQuantity();
1882 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1883 Context.getTargetInfo().getPointerWidth(LangAS::Default) == 64)
1884 Width = llvm::alignTo(Width, Align);
1885 return TypeInfoChars(CharUnits::fromQuantity(Width),
1886 CharUnits::fromQuantity(Align),
1887 EltInfo.AlignRequirement);
1888}
1889
1890TypeInfoChars ASTContext::getTypeInfoInChars(const Type *T) const {
1891 if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
1892 return getConstantArrayInfoInChars(*this, CAT);
1893 TypeInfo Info = getTypeInfo(T);
1894 return TypeInfoChars(toCharUnitsFromBits(Info.Width),
1895 toCharUnitsFromBits(Info.Align), Info.AlignRequirement);
1896}
1897
1898TypeInfoChars ASTContext::getTypeInfoInChars(QualType T) const {
1899 return getTypeInfoInChars(T.getTypePtr());
1900}
1901
1902bool ASTContext::isPromotableIntegerType(QualType T) const {
1903 // HLSL doesn't promote all small integer types to int, it
1904 // just uses the rank-based promotion rules for all types.
1905 if (getLangOpts().HLSL)
1906 return false;
1907
1908 if (const auto *BT = T->getAs<BuiltinType>())
1909 switch (BT->getKind()) {
1910 case BuiltinType::Bool:
1911 case BuiltinType::Char_S:
1912 case BuiltinType::Char_U:
1913 case BuiltinType::SChar:
1914 case BuiltinType::UChar:
1915 case BuiltinType::Short:
1916 case BuiltinType::UShort:
1917 case BuiltinType::WChar_S:
1918 case BuiltinType::WChar_U:
1919 case BuiltinType::Char8:
1920 case BuiltinType::Char16:
1921 case BuiltinType::Char32:
1922 return true;
1923 default:
1924 return false;
1925 }
1926
1927 // Enumerated types are promotable to their compatible integer types
1928 // (C99 6.3.1.1) a.k.a. its underlying type (C++ [conv.prom]p2).
1929 if (const auto *ET = T->getAs<EnumType>()) {
1930 if (T->isDependentType() || ET->getDecl()->getPromotionType().isNull() ||
1931 ET->getDecl()->isScoped())
1932 return false;
1933
1934 return true;
1935 }
1936
1937 return false;
1938}
1939
1940bool ASTContext::isAlignmentRequired(const Type *T) const {
1941 return getTypeInfo(T).AlignRequirement != AlignRequirementKind::None;
1942}
1943
1944bool ASTContext::isAlignmentRequired(QualType T) const {
1945 return isAlignmentRequired(T.getTypePtr());
1946}
1947
1948unsigned ASTContext::getTypeAlignIfKnown(QualType T,
1949 bool NeedsPreferredAlignment) const {
1950 // An alignment on a typedef overrides anything else.
1951 if (const auto *TT = T->getAs<TypedefType>())
1952 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1953 return Align;
1954
1955 // If we have an (array of) complete type, we're done.
1956 T = getBaseElementType(T);
1957 if (!T->isIncompleteType())
1958 return NeedsPreferredAlignment ? getPreferredTypeAlign(T) : getTypeAlign(T);
1959
1960 // If we had an array type, its element type might be a typedef
1961 // type with an alignment attribute.
1962 if (const auto *TT = T->getAs<TypedefType>())
1963 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1964 return Align;
1965
1966 // Otherwise, see if the declaration of the type had an attribute.
1967 if (const auto *TT = T->getAs<TagType>())
1968 return TT->getDecl()->getMaxAlignment();
1969
1970 return 0;
1971}
1972
1973TypeInfo ASTContext::getTypeInfo(const Type *T) const {
1974 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1975 if (I != MemoizedTypeInfo.end())
1976 return I->second;
1977
1978 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1979 TypeInfo TI = getTypeInfoImpl(T);
1980 MemoizedTypeInfo[T] = TI;
1981 return TI;
1982}
1983
1984/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1985/// method does not work on incomplete types.
1986///
1987/// FIXME: Pointers into different addr spaces could have different sizes and
1988/// alignment requirements: getPointerInfo should take an AddrSpace, this
1989/// should take a QualType, &c.
1990TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1991 uint64_t Width = 0;
1992 unsigned Align = 8;
1993 AlignRequirementKind AlignRequirement = AlignRequirementKind::None;
1994 LangAS AS = LangAS::Default;
1995 switch (T->getTypeClass()) {
1996#define TYPE(Class, Base)
1997#define ABSTRACT_TYPE(Class, Base)
1998#define NON_CANONICAL_TYPE(Class, Base)
1999#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2000#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
2001 case Type::Class: \
2002 assert(!T->isDependentType() && "should not see dependent types here")(static_cast <bool> (!T->isDependentType() &&
"should not see dependent types here") ? void (0) : __assert_fail
("!T->isDependentType() && \"should not see dependent types here\""
, "clang/lib/AST/ASTContext.cpp", 2002, __extension__ __PRETTY_FUNCTION__
))
; \
2003 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
2004#include "clang/AST/TypeNodes.inc"
2005 llvm_unreachable("Should not see dependent types")::llvm::llvm_unreachable_internal("Should not see dependent types"
, "clang/lib/AST/ASTContext.cpp", 2005)
;
2006
2007 case Type::FunctionNoProto:
2008 case Type::FunctionProto:
2009 // GCC extension: alignof(function) = 32 bits
2010 Width = 0;
2011 Align = 32;
2012 break;
2013
2014 case Type::IncompleteArray:
2015 case Type::VariableArray:
2016 case Type::ConstantArray: {
2017 // Model non-constant sized arrays as size zero, but track the alignment.
2018 uint64_t Size = 0;
2019 if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
2020 Size = CAT->getSize().getZExtValue();
2021
2022 TypeInfo EltInfo = getTypeInfo(cast<ArrayType>(T)->getElementType());
2023 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&(static_cast <bool> ((Size == 0 || EltInfo.Width <= (
uint64_t)(-1) / Size) && "Overflow in array type bit size evaluation"
) ? void (0) : __assert_fail ("(Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) && \"Overflow in array type bit size evaluation\""
, "clang/lib/AST/ASTContext.cpp", 2024, __extension__ __PRETTY_FUNCTION__
))
2024 "Overflow in array type bit size evaluation")(static_cast <bool> ((Size == 0 || EltInfo.Width <= (
uint64_t)(-1) / Size) && "Overflow in array type bit size evaluation"
) ? void (0) : __assert_fail ("(Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) && \"Overflow in array type bit size evaluation\""
, "clang/lib/AST/ASTContext.cpp", 2024, __extension__ __PRETTY_FUNCTION__
))
;
2025 Width = EltInfo.Width * Size;
2026 Align = EltInfo.Align;
2027 AlignRequirement = EltInfo.AlignRequirement;
2028 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
2029 getTargetInfo().getPointerWidth(LangAS::Default) == 64)
2030 Width = llvm::alignTo(Width, Align);
2031 break;
2032 }
2033
2034 case Type::ExtVector:
2035 case Type::Vector: {
2036 const auto *VT = cast<VectorType>(T);
2037 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
2038 Width = VT->isExtVectorBoolType() ? VT->getNumElements()
2039 : EltInfo.Width * VT->getNumElements();
2040 // Enforce at least byte alignment.
2041 Align = std::max<unsigned>(8, Width);
2042
2043 // If the alignment is not a power of 2, round up to the next power of 2.
2044 // This happens for non-power-of-2 length vectors.
2045 if (Align & (Align-1)) {
2046 Align = llvm::NextPowerOf2(Align);
2047 Width = llvm::alignTo(Width, Align);
2048 }
2049 // Adjust the alignment based on the target max.
2050 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
2051 if (TargetVectorAlign && TargetVectorAlign < Align)
2052 Align = TargetVectorAlign;
2053 if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector)
2054 // Adjust the alignment for fixed-length SVE vectors. This is important
2055 // for non-power-of-2 vector lengths.
2056 Align = 128;
2057 else if (VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector)
2058 // Adjust the alignment for fixed-length SVE predicates.
2059 Align = 16;
2060 break;
2061 }
2062
2063 case Type::ConstantMatrix: {
2064 const auto *MT = cast<ConstantMatrixType>(T);
2065 TypeInfo ElementInfo = getTypeInfo(MT->getElementType());
2066 // The internal layout of a matrix value is implementation defined.
2067 // Initially be ABI compatible with arrays with respect to alignment and
2068 // size.
2069 Width = ElementInfo.Width * MT->getNumRows() * MT->getNumColumns();
2070 Align = ElementInfo.Align;
2071 break;
2072 }
2073
2074 case Type::Builtin:
2075 switch (cast<BuiltinType>(T)->getKind()) {
2076 default: llvm_unreachable("Unknown builtin type!")::llvm::llvm_unreachable_internal("Unknown builtin type!", "clang/lib/AST/ASTContext.cpp"
, 2076)
;
2077 case BuiltinType::Void:
2078 // GCC extension: alignof(void) = 8 bits.
2079 Width = 0;
2080 Align = 8;
2081 break;
2082 case BuiltinType::Bool:
2083 Width = Target->getBoolWidth();
2084 Align = Target->getBoolAlign();
2085 break;
2086 case BuiltinType::Char_S:
2087 case BuiltinType::Char_U:
2088 case BuiltinType::UChar:
2089 case BuiltinType::SChar:
2090 case BuiltinType::Char8:
2091 Width = Target->getCharWidth();
2092 Align = Target->getCharAlign();
2093 break;
2094 case BuiltinType::WChar_S:
2095 case BuiltinType::WChar_U:
2096 Width = Target->getWCharWidth();
2097 Align = Target->getWCharAlign();
2098 break;
2099 case BuiltinType::Char16:
2100 Width = Target->getChar16Width();
2101 Align = Target->getChar16Align();
2102 break;
2103 case BuiltinType::Char32:
2104 Width = Target->getChar32Width();
2105 Align = Target->getChar32Align();
2106 break;
2107 case BuiltinType::UShort:
2108 case BuiltinType::Short:
2109 Width = Target->getShortWidth();
2110 Align = Target->getShortAlign();
2111 break;
2112 case BuiltinType::UInt:
2113 case BuiltinType::Int:
2114 Width = Target->getIntWidth();
2115 Align = Target->getIntAlign();
2116 break;
2117 case BuiltinType::ULong:
2118 case BuiltinType::Long:
2119 Width = Target->getLongWidth();
2120 Align = Target->getLongAlign();
2121 break;
2122 case BuiltinType::ULongLong:
2123 case BuiltinType::LongLong:
2124 Width = Target->getLongLongWidth();
2125 Align = Target->getLongLongAlign();
2126 break;
2127 case BuiltinType::Int128:
2128 case BuiltinType::UInt128:
2129 Width = 128;
2130 Align = Target->getInt128Align();
2131 break;
2132 case BuiltinType::ShortAccum:
2133 case BuiltinType::UShortAccum:
2134 case BuiltinType::SatShortAccum:
2135 case BuiltinType::SatUShortAccum:
2136 Width = Target->getShortAccumWidth();
2137 Align = Target->getShortAccumAlign();
2138 break;
2139 case BuiltinType::Accum:
2140 case BuiltinType::UAccum:
2141 case BuiltinType::SatAccum:
2142 case BuiltinType::SatUAccum:
2143 Width = Target->getAccumWidth();
2144 Align = Target->getAccumAlign();
2145 break;
2146 case BuiltinType::LongAccum:
2147 case BuiltinType::ULongAccum:
2148 case BuiltinType::SatLongAccum:
2149 case BuiltinType::SatULongAccum:
2150 Width = Target->getLongAccumWidth();
2151 Align = Target->getLongAccumAlign();
2152 break;
2153 case BuiltinType::ShortFract:
2154 case BuiltinType::UShortFract:
2155 case BuiltinType::SatShortFract:
2156 case BuiltinType::SatUShortFract:
2157 Width = Target->getShortFractWidth();
2158 Align = Target->getShortFractAlign();
2159 break;
2160 case BuiltinType::Fract:
2161 case BuiltinType::UFract:
2162 case BuiltinType::SatFract:
2163 case BuiltinType::SatUFract:
2164 Width = Target->getFractWidth();
2165 Align = Target->getFractAlign();
2166 break;
2167 case BuiltinType::LongFract:
2168 case BuiltinType::ULongFract:
2169 case BuiltinType::SatLongFract:
2170 case BuiltinType::SatULongFract:
2171 Width = Target->getLongFractWidth();
2172 Align = Target->getLongFractAlign();
2173 break;
2174 case BuiltinType::BFloat16:
2175 if (Target->hasBFloat16Type()) {
2176 Width = Target->getBFloat16Width();
2177 Align = Target->getBFloat16Align();
2178 }
2179 break;
2180 case BuiltinType::Float16:
2181 case BuiltinType::Half:
2182 if (Target->hasFloat16Type() || !getLangOpts().OpenMP ||
2183 !getLangOpts().OpenMPIsDevice) {
2184 Width = Target->getHalfWidth();
2185 Align = Target->getHalfAlign();
2186 } else {
2187 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&(static_cast <bool> (getLangOpts().OpenMP && getLangOpts
().OpenMPIsDevice && "Expected OpenMP device compilation."
) ? void (0) : __assert_fail ("getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && \"Expected OpenMP device compilation.\""
, "clang/lib/AST/ASTContext.cpp", 2188, __extension__ __PRETTY_FUNCTION__
))
2188 "Expected OpenMP device compilation.")(static_cast <bool> (getLangOpts().OpenMP && getLangOpts
().OpenMPIsDevice && "Expected OpenMP device compilation."
) ? void (0) : __assert_fail ("getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && \"Expected OpenMP device compilation.\""
, "clang/lib/AST/ASTContext.cpp", 2188, __extension__ __PRETTY_FUNCTION__
))
;
2189 Width = AuxTarget->getHalfWidth();
2190 Align = AuxTarget->getHalfAlign();
2191 }
2192 break;
2193 case BuiltinType::Float:
2194 Width = Target->getFloatWidth();
2195 Align = Target->getFloatAlign();
2196 break;
2197 case BuiltinType::Double:
2198 Width = Target->getDoubleWidth();
2199 Align = Target->getDoubleAlign();
2200 break;
2201 case BuiltinType::Ibm128:
2202 Width = Target->getIbm128Width();
2203 Align = Target->getIbm128Align();
2204 break;
2205 case BuiltinType::LongDouble:
2206 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
2207 (Target->getLongDoubleWidth() != AuxTarget->getLongDoubleWidth() ||
2208 Target->getLongDoubleAlign() != AuxTarget->getLongDoubleAlign())) {
2209 Width = AuxTarget->getLongDoubleWidth();
2210 Align = AuxTarget->getLongDoubleAlign();
2211 } else {
2212 Width = Target->getLongDoubleWidth();
2213 Align = Target->getLongDoubleAlign();
2214 }
2215 break;
2216 case BuiltinType::Float128:
2217 if (Target->hasFloat128Type() || !getLangOpts().OpenMP ||
2218 !getLangOpts().OpenMPIsDevice) {
2219 Width = Target->getFloat128Width();
2220 Align = Target->getFloat128Align();
2221 } else {
2222 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&(static_cast <bool> (getLangOpts().OpenMP && getLangOpts
().OpenMPIsDevice && "Expected OpenMP device compilation."
) ? void (0) : __assert_fail ("getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && \"Expected OpenMP device compilation.\""
, "clang/lib/AST/ASTContext.cpp", 2223, __extension__ __PRETTY_FUNCTION__
))
2223 "Expected OpenMP device compilation.")(static_cast <bool> (getLangOpts().OpenMP && getLangOpts
().OpenMPIsDevice && "Expected OpenMP device compilation."
) ? void (0) : __assert_fail ("getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && \"Expected OpenMP device compilation.\""
, "clang/lib/AST/ASTContext.cpp", 2223, __extension__ __PRETTY_FUNCTION__
))
;
2224 Width = AuxTarget->getFloat128Width();
2225 Align = AuxTarget->getFloat128Align();
2226 }
2227 break;
2228 case BuiltinType::NullPtr:
2229 // C++ 3.9.1p11: sizeof(nullptr_t) == sizeof(void*)
2230 Width = Target->getPointerWidth(LangAS::Default);
2231 Align = Target->getPointerAlign(LangAS::Default);
2232 break;
2233 case BuiltinType::ObjCId:
2234 case BuiltinType::ObjCClass:
2235 case BuiltinType::ObjCSel:
2236 Width = Target->getPointerWidth(LangAS::Default);
2237 Align = Target->getPointerAlign(LangAS::Default);
2238 break;
2239 case BuiltinType::OCLSampler:
2240 case BuiltinType::OCLEvent:
2241 case BuiltinType::OCLClkEvent:
2242 case BuiltinType::OCLQueue:
2243 case BuiltinType::OCLReserveID:
2244#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2245 case BuiltinType::Id:
2246#include "clang/Basic/OpenCLImageTypes.def"
2247#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2248 case BuiltinType::Id:
2249#include "clang/Basic/OpenCLExtensionTypes.def"
2250 AS = Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
2251 Width = Target->getPointerWidth(AS);
2252 Align = Target->getPointerAlign(AS);
2253 break;
2254 // The SVE types are effectively target-specific. The length of an
2255 // SVE_VECTOR_TYPE is only known at runtime, but it is always a multiple
2256 // of 128 bits. There is one predicate bit for each vector byte, so the
2257 // length of an SVE_PREDICATE_TYPE is always a multiple of 16 bits.
2258 //
2259 // Because the length is only known at runtime, we use a dummy value
2260 // of 0 for the static length. The alignment values are those defined
2261 // by the Procedure Call Standard for the Arm Architecture.
2262#define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId, NumEls, ElBits, \
2263 IsSigned, IsFP, IsBF) \
2264 case BuiltinType::Id: \
2265 Width = 0; \
2266 Align = 128; \
2267 break;
2268#define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId, NumEls) \
2269 case BuiltinType::Id: \
2270 Width = 0; \
2271 Align = 16; \
2272 break;
2273#include "clang/Basic/AArch64SVEACLETypes.def"
2274#define PPC_VECTOR_TYPE(Name, Id, Size) \
2275 case BuiltinType::Id: \
2276 Width = Size; \
2277 Align = Size; \
2278 break;
2279#include "clang/Basic/PPCTypes.def"
2280#define RVV_VECTOR_TYPE(Name, Id, SingletonId, ElKind, ElBits, NF, IsSigned, \
2281 IsFP) \
2282 case BuiltinType::Id: \
2283 Width = 0; \
2284 Align = ElBits; \
2285 break;
2286#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, ElKind) \
2287 case BuiltinType::Id: \
2288 Width = 0; \
2289 Align = 8; \
2290 break;
2291#include "clang/Basic/RISCVVTypes.def"
2292 }
2293 break;
2294 case Type::ObjCObjectPointer:
2295 Width = Target->getPointerWidth(LangAS::Default);
2296 Align = Target->getPointerAlign(LangAS::Default);
2297 break;
2298 case Type::BlockPointer:
2299 AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
2300 Width = Target->getPointerWidth(AS);
2301 Align = Target->getPointerAlign(AS);
2302 break;
2303 case Type::LValueReference:
2304 case Type::RValueReference:
2305 // alignof and sizeof should never enter this code path here, so we go
2306 // the pointer route.
2307 AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
2308 Width = Target->getPointerWidth(AS);
2309 Align = Target->getPointerAlign(AS);
2310 break;
2311 case Type::Pointer:
2312 AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
2313 Width = Target->getPointerWidth(AS);
2314 Align = Target->getPointerAlign(AS);
2315 break;
2316 case Type::MemberPointer: {
2317 const auto *MPT = cast<MemberPointerType>(T);
2318 CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT);
2319 Width = MPI.Width;
2320 Align = MPI.Align;
2321 break;
2322 }
2323 case Type::Complex: {
2324 // Complex types have the same alignment as their elements, but twice the
2325 // size.
2326 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
2327 Width = EltInfo.Width * 2;
2328 Align = EltInfo.Align;
2329 break;
2330 }
2331 case Type::ObjCObject:
2332 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
2333 case Type::Adjusted:
2334 case Type::Decayed:
2335 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
2336 case Type::ObjCInterface: {
2337 const auto *ObjCI = cast<ObjCInterfaceType>(T);
2338 if (ObjCI->getDecl()->isInvalidDecl()) {
2339 Width = 8;
2340 Align = 8;
2341 break;
2342 }
2343 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2344 Width = toBits(Layout.getSize());
2345 Align = toBits(Layout.getAlignment());
2346 break;
2347 }
2348 case Type::BitInt: {
2349 const auto *EIT = cast<BitIntType>(T);
2350 Align =
2351 std::min(static_cast<unsigned>(std::max(
2352 getCharWidth(), llvm::PowerOf2Ceil(EIT->getNumBits()))),
2353 Target->getLongLongAlign());
2354 Width = llvm::alignTo(EIT->getNumBits(), Align);
2355 break;
2356 }
2357 case Type::Record:
2358 case Type::Enum: {
2359 const auto *TT = cast<TagType>(T);
2360
2361 if (TT->getDecl()->isInvalidDecl()) {
2362 Width = 8;
2363 Align = 8;
2364 break;
2365 }
2366
2367 if (const auto *ET = dyn_cast<EnumType>(TT)) {
2368 const EnumDecl *ED = ET->getDecl();
2369 TypeInfo Info =
2370 getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType());
2371 if (unsigned AttrAlign = ED->getMaxAlignment()) {
2372 Info.Align = AttrAlign;
2373 Info.AlignRequirement = AlignRequirementKind::RequiredByEnum;
2374 }
2375 return Info;
2376 }
2377
2378 const auto *RT = cast<RecordType>(TT);
2379 const RecordDecl *RD = RT->getDecl();
2380 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2381 Width = toBits(Layout.getSize());
2382 Align = toBits(Layout.getAlignment());
2383 AlignRequirement = RD->hasAttr<AlignedAttr>()
2384 ? AlignRequirementKind::RequiredByRecord
2385 : AlignRequirementKind::None;
2386 break;
2387 }
2388
2389 case Type::SubstTemplateTypeParm:
2390 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
2391 getReplacementType().getTypePtr());
2392
2393 case Type::Auto:
2394 case Type::DeducedTemplateSpecialization: {
2395 const auto *A = cast<DeducedType>(T);
2396 assert(!A->getDeducedType().isNull() &&(static_cast <bool> (!A->getDeducedType().isNull() &&
"cannot request the size of an undeduced or dependent auto type"
) ? void (0) : __assert_fail ("!A->getDeducedType().isNull() && \"cannot request the size of an undeduced or dependent auto type\""
, "clang/lib/AST/ASTContext.cpp", 2397, __extension__ __PRETTY_FUNCTION__
))
2397 "cannot request the size of an undeduced or dependent auto type")(static_cast <bool> (!A->getDeducedType().isNull() &&
"cannot request the size of an undeduced or dependent auto type"
) ? void (0) : __assert_fail ("!A->getDeducedType().isNull() && \"cannot request the size of an undeduced or dependent auto type\""
, "clang/lib/AST/ASTContext.cpp", 2397, __extension__ __PRETTY_FUNCTION__
))
;
2398 return getTypeInfo(A->getDeducedType().getTypePtr());
2399 }
2400
2401 case Type::Paren:
2402 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
2403
2404 case Type::MacroQualified:
2405 return getTypeInfo(
2406 cast<MacroQualifiedType>(T)->getUnderlyingType().getTypePtr());
2407
2408 case Type::ObjCTypeParam:
2409 return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr());
2410
2411 case Type::Using:
2412 return getTypeInfo(cast<UsingType>(T)->desugar().getTypePtr());
2413
2414 case Type::Typedef: {
2415 const auto *TT = cast<TypedefType>(T);
2416 TypeInfo Info = getTypeInfo(TT->desugar().getTypePtr());
2417 // If the typedef has an aligned attribute on it, it overrides any computed
2418 // alignment we have. This violates the GCC documentation (which says that
2419 // attribute(aligned) can only round up) but matches its implementation.
2420 if (unsigned AttrAlign = TT->getDecl()->getMaxAlignment()) {
2421 Align = AttrAlign;
2422 AlignRequirement = AlignRequirementKind::RequiredByTypedef;
2423 } else {
2424 Align = Info.Align;
2425 AlignRequirement = Info.AlignRequirement;
2426 }
2427 Width = Info.Width;
2428 break;
2429 }
2430
2431 case Type::Elaborated:
2432 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
2433
2434 case Type::Attributed:
2435 return getTypeInfo(
2436 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
2437
2438 case Type::BTFTagAttributed:
2439 return getTypeInfo(
2440 cast<BTFTagAttributedType>(T)->getWrappedType().getTypePtr());
2441
2442 case Type::Atomic: {
2443 // Start with the base type information.
2444 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
2445 Width = Info.Width;
2446 Align = Info.Align;
2447
2448 if (!Width) {
2449 // An otherwise zero-sized type should still generate an
2450 // atomic operation.
2451 Width = Target->getCharWidth();
2452 assert(Align)(static_cast <bool> (Align) ? void (0) : __assert_fail (
"Align", "clang/lib/AST/ASTContext.cpp", 2452, __extension__ __PRETTY_FUNCTION__
))
;
2453 } else if (Width <= Target->getMaxAtomicPromoteWidth()) {
2454 // If the size of the type doesn't exceed the platform's max
2455 // atomic promotion width, make the size and alignment more
2456 // favorable to atomic operations:
2457
2458 // Round the size up to a power of 2.
2459 if (!llvm::isPowerOf2_64(Width))
2460 Width = llvm::NextPowerOf2(Width);
2461
2462 // Set the alignment equal to the size.
2463 Align = static_cast<unsigned>(Width);
2464 }
2465 }
2466 break;
2467
2468 case Type::Pipe:
2469 Width = Target->getPointerWidth(LangAS::opencl_global);
2470 Align = Target->getPointerAlign(LangAS::opencl_global);
2471 break;
2472 }
2473
2474 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2")(static_cast <bool> (llvm::isPowerOf2_32(Align) &&
"Alignment must be power of 2") ? void (0) : __assert_fail (
"llvm::isPowerOf2_32(Align) && \"Alignment must be power of 2\""
, "clang/lib/AST/ASTContext.cpp", 2474, __extension__ __PRETTY_FUNCTION__
))
;
2475 return TypeInfo(Width, Align, AlignRequirement);
2476}
2477
2478unsigned ASTContext::getTypeUnadjustedAlign(const Type *T) const {
2479 UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(T);
2480 if (I != MemoizedUnadjustedAlign.end())
2481 return I->second;
2482
2483 unsigned UnadjustedAlign;
2484 if (const auto *RT = T->getAs<RecordType>()) {
2485 const RecordDecl *RD = RT->getDecl();
2486 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2487 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2488 } else if (const auto *ObjCI = T->getAs<ObjCInterfaceType>()) {
2489 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2490 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2491 } else {
2492 UnadjustedAlign = getTypeAlign(T->getUnqualifiedDesugaredType());
2493 }
2494
2495 MemoizedUnadjustedAlign[T] = UnadjustedAlign;
2496 return UnadjustedAlign;
2497}
2498
2499unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
2500 unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign();
2501 return SimdAlign;
2502}
2503
2504/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
2505CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
2506 return CharUnits::fromQuantity(BitSize / getCharWidth());
2507}
2508
2509/// toBits - Convert a size in characters to a size in characters.
2510int64_t ASTContext::toBits(CharUnits CharSize) const {
2511 return CharSize.getQuantity() * getCharWidth();
2512}
2513
2514/// getTypeSizeInChars - Return the size of the specified type, in characters.
2515/// This method does not work on incomplete types.
2516CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
2517 return getTypeInfoInChars(T).Width;
2518}
2519CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
2520 return getTypeInfoInChars(T).Width;
2521}
2522
2523/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
2524/// characters. This method does not work on incomplete types.
2525CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
2526 return toCharUnitsFromBits(getTypeAlign(T));
2527}
2528CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
2529 return toCharUnitsFromBits(getTypeAlign(T));
2530}
2531
2532/// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a
2533/// type, in characters, before alignment adjustments. This method does
2534/// not work on incomplete types.
2535CharUnits ASTContext::getTypeUnadjustedAlignInChars(QualType T) const {
2536 return toCharUnitsFromBits(getTypeUnadjustedAlign(T));
2537}
2538CharUnits ASTContext::getTypeUnadjustedAlignInChars(const Type *T) const {
2539 return toCharUnitsFromBits(getTypeUnadjustedAlign(T));
2540}
2541
2542/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
2543/// type for the current target in bits. This can be different than the ABI
2544/// alignment in cases where it is beneficial for performance or backwards
2545/// compatibility preserving to overalign a data type. (Note: despite the name,
2546/// the preferred alignment is ABI-impacting, and not an optimization.)
2547unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
2548 TypeInfo TI = getTypeInfo(T);
2549 unsigned ABIAlign = TI.Align;
2550
2551 T = T->getBaseElementTypeUnsafe();
2552
2553 // The preferred alignment of member pointers is that of a pointer.
2554 if (T->isMemberPointerType())
2555 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
2556
2557 if (!Target->allowsLargerPreferedTypeAlignment())
2558 return ABIAlign;
2559
2560 if (const auto *RT = T->getAs<RecordType>()) {
2561 const RecordDecl *RD = RT->getDecl();
2562
2563 // When used as part of a typedef, or together with a 'packed' attribute,
2564 // the 'aligned' attribute can be used to decrease alignment. Note that the
2565 // 'packed' case is already taken into consideration when computing the
2566 // alignment, we only need to handle the typedef case here.
2567 if (TI.AlignRequirement == AlignRequirementKind::RequiredByTypedef ||
2568 RD->isInvalidDecl())
2569 return ABIAlign;
2570
2571 unsigned PreferredAlign = static_cast<unsigned>(
2572 toBits(getASTRecordLayout(RD).PreferredAlignment));
2573 assert(PreferredAlign >= ABIAlign &&(static_cast <bool> (PreferredAlign >= ABIAlign &&
"PreferredAlign should be at least as large as ABIAlign.") ?
void (0) : __assert_fail ("PreferredAlign >= ABIAlign && \"PreferredAlign should be at least as large as ABIAlign.\""
, "clang/lib/AST/ASTContext.cpp", 2574, __extension__ __PRETTY_FUNCTION__
))
2574 "PreferredAlign should be at least as large as ABIAlign.")(static_cast <bool> (PreferredAlign >= ABIAlign &&
"PreferredAlign should be at least as large as ABIAlign.") ?
void (0) : __assert_fail ("PreferredAlign >= ABIAlign && \"PreferredAlign should be at least as large as ABIAlign.\""
, "clang/lib/AST/ASTContext.cpp", 2574, __extension__ __PRETTY_FUNCTION__
))
;
2575 return PreferredAlign;
2576 }
2577
2578 // Double (and, for targets supporting AIX `power` alignment, long double) and
2579 // long long should be naturally aligned (despite requiring less alignment) if
2580 // possible.
2581 if (const auto *CT = T->getAs<ComplexType>())
2582 T = CT->getElementType().getTypePtr();
2583 if (const auto *ET = T->getAs<EnumType>())
2584 T = ET->getDecl()->getIntegerType().getTypePtr();
2585 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
2586 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
2587 T->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2588 (T->isSpecificBuiltinType(BuiltinType::LongDouble) &&
2589 Target->defaultsToAIXPowerAlignment()))
2590 // Don't increase the alignment if an alignment attribute was specified on a
2591 // typedef declaration.
2592 if (!TI.isAlignRequired())
2593 return std::max(ABIAlign, (unsigned)getTypeSize(T));
2594
2595 return ABIAlign;
2596}
2597
2598/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2599/// for __attribute__((aligned)) on this target, to be used if no alignment
2600/// value is specified.
2601unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const {
2602 return getTargetInfo().getDefaultAlignForAttributeAligned();
2603}
2604
2605/// getAlignOfGlobalVar - Return the alignment in bits that should be given
2606/// to a global variable of the specified type.
2607unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
2608 uint64_t TypeSize = getTypeSize(T.getTypePtr());
2609 return std::max(getPreferredTypeAlign(T),
2610 getTargetInfo().getMinGlobalAlign(TypeSize));
2611}
2612
2613/// getAlignOfGlobalVarInChars - Return the alignment in characters that
2614/// should be given to a global variable of the specified type.
2615CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
2616 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
2617}
2618
2619CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
2620 CharUnits Offset = CharUnits::Zero();
2621 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
2622 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2623 Offset += Layout->getBaseClassOffset(Base);
2624 Layout = &getASTRecordLayout(Base);
2625 }
2626 return Offset;
2627}
2628
2629CharUnits ASTContext::getMemberPointerPathAdjustment(const APValue &MP) const {
2630 const ValueDecl *MPD = MP.getMemberPointerDecl();
2631 CharUnits ThisAdjustment = CharUnits::Zero();
2632 ArrayRef<const CXXRecordDecl*> Path = MP.getMemberPointerPath();
2633 bool DerivedMember = MP.isMemberPointerToDerivedMember();
2634 const CXXRecordDecl *RD = cast<CXXRecordDecl>(MPD->getDeclContext());
2635 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
2636 const CXXRecordDecl *Base = RD;
2637 const CXXRecordDecl *Derived = Path[I];
2638 if (DerivedMember)
2639 std::swap(Base, Derived);
2640 ThisAdjustment += getASTRecordLayout(Derived).getBaseClassOffset(Base);
2641 RD = Path[I];
2642 }
2643 if (DerivedMember)
2644 ThisAdjustment = -ThisAdjustment;
2645 return ThisAdjustment;
2646}
2647
2648/// DeepCollectObjCIvars -
2649/// This routine first collects all declared, but not synthesized, ivars in
2650/// super class and then collects all ivars, including those synthesized for
2651/// current class. This routine is used for implementation of current class
2652/// when all ivars, declared and synthesized are known.
2653void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
2654 bool leafClass,
2655 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
2656 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2657 DeepCollectObjCIvars(SuperClass, false, Ivars);
2658 if (!leafClass) {
2659 llvm::append_range(Ivars, OI->ivars());
2660 } else {
2661 auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
2662 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
2663 Iv= Iv->getNextIvar())
2664 Ivars.push_back(Iv);
2665 }
2666}
2667
2668/// CollectInheritedProtocols - Collect all protocols in current class and
2669/// those inherited by it.
2670void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
2671 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
2672 if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
2673 // We can use protocol_iterator here instead of
2674 // all_referenced_protocol_iterator since we are walking all categories.
2675 for (auto *Proto : OI->all_referenced_protocols()) {
2676 CollectInheritedProtocols(Proto, Protocols);
2677 }
2678
2679 // Categories of this Interface.
2680 for (const auto *Cat : OI->visible_categories())
2681 CollectInheritedProtocols(Cat, Protocols);
2682
2683 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2684 while (SD) {
2685 CollectInheritedProtocols(SD, Protocols);
2686 SD = SD->getSuperClass();
2687 }
2688 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
2689 for (auto *Proto : OC->protocols()) {
2690 CollectInheritedProtocols(Proto, Protocols);
2691 }
2692 } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
2693 // Insert the protocol.
2694 if (!Protocols.insert(
2695 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2696 return;
2697
2698 for (auto *Proto : OP->protocols())
2699 CollectInheritedProtocols(Proto, Protocols);
2700 }
2701}
2702
2703static bool unionHasUniqueObjectRepresentations(const ASTContext &Context,
2704 const RecordDecl *RD) {
2705 assert(RD->isUnion() && "Must be union type")(static_cast <bool> (RD->isUnion() && "Must be union type"
) ? void (0) : __assert_fail ("RD->isUnion() && \"Must be union type\""
, "clang/lib/AST/ASTContext.cpp", 2705, __extension__ __PRETTY_FUNCTION__
))
;
2706 CharUnits UnionSize = Context.getTypeSizeInChars(RD->getTypeForDecl());
2707
2708 for (const auto *Field : RD->fields()) {
2709 if (!Context.hasUniqueObjectRepresentations(Field->getType()))
2710 return false;
2711 CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType());
2712 if (FieldSize != UnionSize)
2713 return false;
2714 }
2715 return !RD->field_empty();
2716}
2717
2718static int64_t getSubobjectOffset(const FieldDecl *Field,
2719 const ASTContext &Context,
2720 const clang::ASTRecordLayout & /*Layout*/) {
2721 return Context.getFieldOffset(Field);
2722}
2723
2724static int64_t getSubobjectOffset(const CXXRecordDecl *RD,
2725 const ASTContext &Context,
2726 const clang::ASTRecordLayout &Layout) {
2727 return Context.toBits(Layout.getBaseClassOffset(RD));
2728}
2729
2730static llvm::Optional<int64_t>
2731structHasUniqueObjectRepresentations(const ASTContext &Context,
2732 const RecordDecl *RD);
2733
2734static llvm::Optional<int64_t>
2735getSubobjectSizeInBits(const FieldDecl *Field, const ASTContext &Context) {
2736 if (Field->getType()->isRecordType()) {
2737 const RecordDecl *RD = Field->getType()->getAsRecordDecl();
2738 if (!RD->isUnion())
2739 return structHasUniqueObjectRepresentations(Context, RD);
2740 }
2741
2742 // A _BitInt type may not be unique if it has padding bits
2743 // but if it is a bitfield the padding bits are not used.
2744 bool IsBitIntType = Field->getType()->isBitIntType();
2745 if (!Field->getType()->isReferenceType() && !IsBitIntType &&
2746 !Context.hasUniqueObjectRepresentations(Field->getType()))
2747 return std::nullopt;
2748
2749 int64_t FieldSizeInBits =
2750 Context.toBits(Context.getTypeSizeInChars(Field->getType()));
2751 if (Field->isBitField()) {
2752 int64_t BitfieldSize = Field->getBitWidthValue(Context);
2753 if (IsBitIntType) {
2754 if ((unsigned)BitfieldSize >
2755 cast<BitIntType>(Field->getType())->getNumBits())
2756 return std::nullopt;
2757 } else if (BitfieldSize > FieldSizeInBits) {
2758 return std::nullopt;
2759 }
2760 FieldSizeInBits = BitfieldSize;
2761 } else if (IsBitIntType &&
2762 !Context.hasUniqueObjectRepresentations(Field->getType())) {
2763 return std::nullopt;
2764 }
2765 return FieldSizeInBits;
2766}
2767
2768static llvm::Optional<int64_t>
2769getSubobjectSizeInBits(const CXXRecordDecl *RD, const ASTContext &Context) {
2770 return structHasUniqueObjectRepresentations(Context, RD);
2771}
2772
2773template <typename RangeT>
2774static llvm::Optional<int64_t> structSubobjectsHaveUniqueObjectRepresentations(
2775 const RangeT &Subobjects, int64_t CurOffsetInBits,
2776 const ASTContext &Context, const clang::ASTRecordLayout &Layout) {
2777 for (const auto *Subobject : Subobjects) {
2778 llvm::Optional<int64_t> SizeInBits =
2779 getSubobjectSizeInBits(Subobject, Context);
2780 if (!SizeInBits)
2781 return std::nullopt;
2782 if (*SizeInBits != 0) {
2783 int64_t Offset = getSubobjectOffset(Subobject, Context, Layout);
2784 if (Offset != CurOffsetInBits)
2785 return std::nullopt;
2786 CurOffsetInBits += *SizeInBits;
2787 }
2788 }
2789 return CurOffsetInBits;
2790}
2791
2792static llvm::Optional<int64_t>
2793structHasUniqueObjectRepresentations(const ASTContext &Context,
2794 const RecordDecl *RD) {
2795 assert(!RD->isUnion() && "Must be struct/class type")(static_cast <bool> (!RD->isUnion() && "Must be struct/class type"
) ? void (0) : __assert_fail ("!RD->isUnion() && \"Must be struct/class type\""
, "clang/lib/AST/ASTContext.cpp", 2795, __extension__ __PRETTY_FUNCTION__
))
;
2796 const auto &Layout = Context.getASTRecordLayout(RD);
2797
2798 int64_t CurOffsetInBits = 0;
2799 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) {
2800 if (ClassDecl->isDynamicClass())
2801 return std::nullopt;
2802
2803 SmallVector<CXXRecordDecl *, 4> Bases;
2804 for (const auto &Base : ClassDecl->bases()) {
2805 // Empty types can be inherited from, and non-empty types can potentially
2806 // have tail padding, so just make sure there isn't an error.
2807 Bases.emplace_back(Base.getType()->getAsCXXRecordDecl());
2808 }
2809
2810 llvm::sort(Bases, [&](const CXXRecordDecl *L, const CXXRecordDecl *R) {
2811 return Layout.getBaseClassOffset(L) < Layout.getBaseClassOffset(R);
2812 });
2813
2814 llvm::Optional<int64_t> OffsetAfterBases =
2815 structSubobjectsHaveUniqueObjectRepresentations(Bases, CurOffsetInBits,
2816 Context, Layout);
2817 if (!OffsetAfterBases)
2818 return std::nullopt;
2819 CurOffsetInBits = *OffsetAfterBases;
2820 }
2821
2822 llvm::Optional<int64_t> OffsetAfterFields =
2823 structSubobjectsHaveUniqueObjectRepresentations(
2824 RD->fields(), CurOffsetInBits, Context, Layout);
2825 if (!OffsetAfterFields)
2826 return std::nullopt;
2827 CurOffsetInBits = *OffsetAfterFields;
2828
2829 return CurOffsetInBits;
2830}
2831
2832bool ASTContext::hasUniqueObjectRepresentations(QualType Ty) const {
2833 // C++17 [meta.unary.prop]:
2834 // The predicate condition for a template specialization
2835 // has_unique_object_representations<T> shall be
2836 // satisfied if and only if:
2837 // (9.1) - T is trivially copyable, and
2838 // (9.2) - any two objects of type T with the same value have the same
2839 // object representation, where two objects
2840 // of array or non-union class type are considered to have the same value
2841 // if their respective sequences of
2842 // direct subobjects have the same values, and two objects of union type
2843 // are considered to have the same
2844 // value if they have the same active member and the corresponding members
2845 // have the same value.
2846 // The set of scalar types for which this condition holds is
2847 // implementation-defined. [ Note: If a type has padding
2848 // bits, the condition does not hold; otherwise, the condition holds true
2849 // for unsigned integral types. -- end note ]
2850 assert(!Ty.isNull() && "Null QualType sent to unique object rep check")(static_cast <bool> (!Ty.isNull() && "Null QualType sent to unique object rep check"
) ? void (0) : __assert_fail ("!Ty.isNull() && \"Null QualType sent to unique object rep check\""
, "clang/lib/AST/ASTContext.cpp", 2850, __extension__ __PRETTY_FUNCTION__
))
;
2851
2852 // Arrays are unique only if their element type is unique.
2853 if (Ty->isArrayType())
2854 return hasUniqueObjectRepresentations(getBaseElementType(Ty));
2855
2856 // (9.1) - T is trivially copyable...
2857 if (!Ty.isTriviallyCopyableType(*this))
2858 return false;
2859
2860 // All integrals and enums are unique.
2861 if (Ty->isIntegralOrEnumerationType()) {
2862 // Except _BitInt types that have padding bits.
2863 if (const auto *BIT = dyn_cast<BitIntType>(Ty))
2864 return getTypeSize(BIT) == BIT->getNumBits();
2865
2866 return true;
2867 }
2868
2869 // All other pointers are unique.
2870 if (Ty->isPointerType())
2871 return true;
2872
2873 if (Ty->isMemberPointerType()) {
2874 const auto *MPT = Ty->getAs<MemberPointerType>();
2875 return !ABI->getMemberPointerInfo(MPT).HasPadding;
2876 }
2877
2878 if (Ty->isRecordType()) {
2879 const RecordDecl *Record = Ty->castAs<RecordType>()->getDecl();
2880
2881 if (Record->isInvalidDecl())
2882 return false;
2883
2884 if (Record->isUnion())
2885 return unionHasUniqueObjectRepresentations(*this, Record);
2886
2887 Optional<int64_t> StructSize =
2888 structHasUniqueObjectRepresentations(*this, Record);
2889
2890 return StructSize && *StructSize == static_cast<int64_t>(getTypeSize(Ty));
2891 }
2892
2893 // FIXME: More cases to handle here (list by rsmith):
2894 // vectors (careful about, eg, vector of 3 foo)
2895 // _Complex int and friends
2896 // _Atomic T
2897 // Obj-C block pointers
2898 // Obj-C object pointers
2899 // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t,
2900 // clk_event_t, queue_t, reserve_id_t)
2901 // There're also Obj-C class types and the Obj-C selector type, but I think it
2902 // makes sense for those to return false here.
2903
2904 return false;
2905}
2906
2907unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
2908 unsigned count = 0;
2909 // Count ivars declared in class extension.
2910 for (const auto *Ext : OI->known_extensions())
2911 count += Ext->ivar_size();
2912
2913 // Count ivar defined in this class's implementation. This
2914 // includes synthesized ivars.
2915 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
2916 count += ImplDecl->ivar_size();
2917
2918 return count;
2919}
2920
2921bool ASTContext::isSentinelNullExpr(const Expr *E) {
2922 if (!E)
2923 return false;
2924
2925 // nullptr_t is always treated as null.
2926 if (E->getType()->isNullPtrType()) return true;
2927
2928 if (E->getType()->isAnyPointerType() &&
2929 E->IgnoreParenCasts()->isNullPointerConstant(*this,
2930 Expr::NPC_ValueDependentIsNull))
2931 return true;
2932
2933 // Unfortunately, __null has type 'int'.
2934 if (isa<GNUNullExpr>(E)) return true;
2935
2936 return false;
2937}
2938
2939/// Get the implementation of ObjCInterfaceDecl, or nullptr if none
2940/// exists.
2941ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
2942 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2943 I = ObjCImpls.find(D);
2944 if (I != ObjCImpls.end())
2945 return cast<ObjCImplementationDecl>(I->second);
2946 return nullptr;
2947}
2948
2949/// Get the implementation of ObjCCategoryDecl, or nullptr if none
2950/// exists.
2951ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
2952 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2953 I = ObjCImpls.find(D);
2954 if (I != ObjCImpls.end())
2955 return cast<ObjCCategoryImplDecl>(I->second);
2956 return nullptr;
2957}
2958
2959/// Set the implementation of ObjCInterfaceDecl.
2960void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2961 ObjCImplementationDecl *ImplD) {
2962 assert(IFaceD && ImplD && "Passed null params")(static_cast <bool> (IFaceD && ImplD &&
"Passed null params") ? void (0) : __assert_fail ("IFaceD && ImplD && \"Passed null params\""
, "clang/lib/AST/ASTContext.cpp", 2962, __extension__ __PRETTY_FUNCTION__
))
;
2963 ObjCImpls[IFaceD] = ImplD;
2964}
2965
2966/// Set the implementation of ObjCCategoryDecl.
2967void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
2968 ObjCCategoryImplDecl *ImplD) {
2969 assert(CatD && ImplD && "Passed null params")(static_cast <bool> (CatD && ImplD && "Passed null params"
) ? void (0) : __assert_fail ("CatD && ImplD && \"Passed null params\""
, "clang/lib/AST/ASTContext.cpp", 2969, __extension__ __PRETTY_FUNCTION__
))
;
2970 ObjCImpls[CatD] = ImplD;
2971}
2972
2973const ObjCMethodDecl *
2974ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const {
2975 return ObjCMethodRedecls.lookup(MD);
2976}
2977
2978void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
2979 const ObjCMethodDecl *Redecl) {
2980 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration")(static_cast <bool> (!getObjCMethodRedeclaration(MD) &&
"MD already has a redeclaration") ? void (0) : __assert_fail
("!getObjCMethodRedeclaration(MD) && \"MD already has a redeclaration\""
, "clang/lib/AST/ASTContext.cpp", 2980, __extension__ __PRETTY_FUNCTION__
))
;
2981 ObjCMethodRedecls[MD] = Redecl;
2982}
2983
2984const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
2985 const NamedDecl *ND) const {
2986 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
2987 return ID;
2988 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
2989 return CD->getClassInterface();
2990 if (const auto *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
2991 return IMD->getClassInterface();
2992
2993 return nullptr;
2994}
2995
2996/// Get the copy initialization expression of VarDecl, or nullptr if
2997/// none exists.
2998BlockVarCopyInit ASTContext::getBlockVarCopyInit(const VarDecl *VD) const {
2999 assert(VD && "Passed null params")(static_cast <bool> (VD && "Passed null params"
) ? void (0) : __assert_fail ("VD && \"Passed null params\""
, "clang/lib/AST/ASTContext.cpp", 2999, __extension__ __PRETTY_FUNCTION__
))
;
3000 assert(VD->hasAttr<BlocksAttr>() &&(static_cast <bool> (VD->hasAttr<BlocksAttr>()
&& "getBlockVarCopyInits - not __block var") ? void (
0) : __assert_fail ("VD->hasAttr<BlocksAttr>() && \"getBlockVarCopyInits - not __block var\""
, "clang/lib/AST/ASTContext.cpp", 3001, __extension__ __PRETTY_FUNCTION__
))
3001 "getBlockVarCopyInits - not __block var")(static_cast <bool> (VD->hasAttr<BlocksAttr>()
&& "getBlockVarCopyInits - not __block var") ? void (
0) : __assert_fail ("VD->hasAttr<BlocksAttr>() && \"getBlockVarCopyInits - not __block var\""
, "clang/lib/AST/ASTContext.cpp", 3001, __extension__ __PRETTY_FUNCTION__
))
;
3002 auto I = BlockVarCopyInits.find(VD);
3003 if (I != BlockVarCopyInits.end())
3004 return I->second;
3005 return {nullptr, false};
3006}
3007
3008/// Set the copy initialization expression of a block var decl.
3009void ASTContext::setBlockVarCopyInit(const VarDecl*VD, Expr *CopyExpr,
3010 bool CanThrow) {
3011 assert(VD && CopyExpr && "Passed null params")(static_cast <bool> (VD && CopyExpr && "Passed null params"
) ? void (0) : __assert_fail ("VD && CopyExpr && \"Passed null params\""
, "clang/lib/AST/ASTContext.cpp", 3011, __extension__ __PRETTY_FUNCTION__
))
;
3012 assert(VD->hasAttr<BlocksAttr>() &&(static_cast <bool> (VD->hasAttr<BlocksAttr>()
&& "setBlockVarCopyInits - not __block var") ? void (
0) : __assert_fail ("VD->hasAttr<BlocksAttr>() && \"setBlockVarCopyInits - not __block var\""
, "clang/lib/AST/ASTContext.cpp", 3013, __extension__ __PRETTY_FUNCTION__
))
3013 "setBlockVarCopyInits - not __block var")(static_cast <bool> (VD->hasAttr<BlocksAttr>()
&& "setBlockVarCopyInits - not __block var") ? void (
0) : __assert_fail ("VD->hasAttr<BlocksAttr>() && \"setBlockVarCopyInits - not __block var\""
, "clang/lib/AST/ASTContext.cpp", 3013, __extension__ __PRETTY_FUNCTION__
))
;
3014 BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow);
3015}
3016
3017TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
3018 unsigned DataSize) const {
3019 if (!DataSize)
3020 DataSize = TypeLoc::getFullDataSizeForType(T);
3021 else
3022 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&(static_cast <bool> (DataSize == TypeLoc::getFullDataSizeForType
(T) && "incorrect data size provided to CreateTypeSourceInfo!"
) ? void (0) : __assert_fail ("DataSize == TypeLoc::getFullDataSizeForType(T) && \"incorrect data size provided to CreateTypeSourceInfo!\""
, "clang/lib/AST/ASTContext.cpp", 3023, __extension__ __PRETTY_FUNCTION__
))
3023 "incorrect data size provided to CreateTypeSourceInfo!")(static_cast <bool> (DataSize == TypeLoc::getFullDataSizeForType
(T) && "incorrect data size provided to CreateTypeSourceInfo!"
) ? void (0) : __assert_fail ("DataSize == TypeLoc::getFullDataSizeForType(T) && \"incorrect data size provided to CreateTypeSourceInfo!\""
, "clang/lib/AST/ASTContext.cpp", 3023, __extension__ __PRETTY_FUNCTION__
))
;
3024
3025 auto *TInfo =
3026 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
3027 new (TInfo) TypeSourceInfo(T);
3028 return TInfo;
3029}
3030
3031TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
3032 SourceLocation L) const {
3033 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
3034 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
3035 return DI;
3036}
3037
3038const ASTRecordLayout &
3039ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
3040 return getObjCLayout(D, nullptr);
3041}
3042
3043const ASTRecordLayout &
3044ASTContext::getASTObjCImplementationLayout(
3045 const ObjCImplementationDecl *D) const {
3046 return getObjCLayout(D->getClassInterface(), D);
3047}
3048
3049static auto getCanonicalTemplateArguments(const ASTContext &C,
3050 ArrayRef<TemplateArgument> Args,
3051 bool &AnyNonCanonArgs) {
3052 SmallVector<TemplateArgument, 16> CanonArgs(Args);
3053 for (auto &Arg : CanonArgs) {
3054 TemplateArgument OrigArg = Arg;
3055 Arg = C.getCanonicalTemplateArgument(Arg);
3056 AnyNonCanonArgs |= !Arg.structurallyEquals(OrigArg);
3057 }
3058 return CanonArgs;
3059}
3060
3061//===----------------------------------------------------------------------===//
3062// Type creation/memoization methods
3063//===----------------------------------------------------------------------===//
3064
3065QualType
3066ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
3067 unsigned fastQuals = quals.getFastQualifiers();
3068 quals.removeFastQualifiers();
3069
3070 // Check if we've already instantiated this type.
3071 llvm::FoldingSetNodeID ID;
3072 ExtQuals::Profile(ID, baseType, quals);
3073 void *insertPos = nullptr;
3074 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
3075 assert(eq->getQualifiers() == quals)(static_cast <bool> (eq->getQualifiers() == quals) ?
void (0) : __assert_fail ("eq->getQualifiers() == quals",
"clang/lib/AST/ASTContext.cpp", 3075, __extension__ __PRETTY_FUNCTION__
))
;
3076 return QualType(eq, fastQuals);
3077 }
3078
3079 // If the base type is not canonical, make the appropriate canonical type.
3080 QualType canon;
3081 if (!baseType->isCanonicalUnqualified()) {
3082 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
3083 canonSplit.Quals.addConsistentQualifiers(quals);
3084 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
3085
3086 // Re-find the insert position.
3087 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
3088 }
3089
3090 auto *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
3091 ExtQualNodes.InsertNode(eq, insertPos);
3092 return QualType(eq, fastQuals);
3093}
3094
3095QualType ASTContext::getAddrSpaceQualType(QualType T,
3096 LangAS AddressSpace) const {
3097 QualType CanT = getCanonicalType(T);
3098 if (CanT.getAddressSpace() == AddressSpace)
3099 return T;
3100
3101 // If we are composing extended qualifiers together, merge together
3102 // into one ExtQuals node.
3103 QualifierCollector Quals;
3104 const Type *TypeNode = Quals.strip(T);
3105
3106 // If this type already has an address space specified, it cannot get
3107 // another one.
3108 assert(!Quals.hasAddressSpace() &&(static_cast <bool> (!Quals.hasAddressSpace() &&
"Type cannot be in multiple addr spaces!") ? void (0) : __assert_fail
("!Quals.hasAddressSpace() && \"Type cannot be in multiple addr spaces!\""
, "clang/lib/AST/ASTContext.cpp", 3109, __extension__ __PRETTY_FUNCTION__
))
3109 "Type cannot be in multiple addr spaces!")(static_cast <bool> (!Quals.hasAddressSpace() &&
"Type cannot be in multiple addr spaces!") ? void (0) : __assert_fail
("!Quals.hasAddressSpace() && \"Type cannot be in multiple addr spaces!\""
, "clang/lib/AST/ASTContext.cpp", 3109, __extension__ __PRETTY_FUNCTION__
))
;
3110 Quals.addAddressSpace(AddressSpace);
3111
3112 return getExtQualType(TypeNode, Quals);
3113}
3114
3115QualType ASTContext::removeAddrSpaceQualType(QualType T) const {
3116 // If the type is not qualified with an address space, just return it
3117 // immediately.
3118 if (!T.hasAddressSpace())
3119 return T;
3120
3121 // If we are composing extended qualifiers together, merge together
3122 // into one ExtQuals node.
3123 QualifierCollector Quals;
3124 const Type *TypeNode;
3125
3126 while (T.hasAddressSpace()) {
3127 TypeNode = Quals.strip(T);
3128
3129 // If the type no longer has an address space after stripping qualifiers,
3130 // jump out.
3131 if (!QualType(TypeNode, 0).hasAddressSpace())
3132 break;
3133
3134 // There might be sugar in the way. Strip it and try again.
3135 T = T.getSingleStepDesugaredType(*this);
3136 }
3137
3138 Quals.removeAddressSpace();
3139
3140 // Removal of the address space can mean there are no longer any
3141 // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts)
3142 // or required.
3143 if (Quals.hasNonFastQualifiers())
3144 return getExtQualType(TypeNode, Quals);
3145 else
3146 return QualType(TypeNode, Quals.getFastQualifiers());
3147}
3148
3149QualType ASTContext::getObjCGCQualType(QualType T,
3150 Qualifiers::GC GCAttr) const {
3151 QualType CanT = getCanonicalType(T);
3152 if (CanT.getObjCGCAttr() == GCAttr)
3153 return T;
3154
3155 if (const auto *ptr = T->getAs<PointerType>()) {
3156 QualType Pointee = ptr->getPointeeType();
3157 if (Pointee->isAnyPointerType()) {
3158 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
3159 return getPointerType(ResultType);
3160 }
3161 }
3162
3163 // If we are composing extended qualifiers together, merge together
3164 // into one ExtQuals node.
3165 QualifierCollector Quals;
3166 const Type *TypeNode = Quals.strip(T);
3167
3168 // If this type already has an ObjCGC specified, it cannot get
3169 // another one.
3170 assert(!Quals.hasObjCGCAttr() &&(static_cast <bool> (!Quals.hasObjCGCAttr() && "Type cannot have multiple ObjCGCs!"
) ? void (0) : __assert_fail ("!Quals.hasObjCGCAttr() && \"Type cannot have multiple ObjCGCs!\""
, "clang/lib/AST/ASTContext.cpp", 3171, __extension__ __PRETTY_FUNCTION__
))
3171 "Type cannot have multiple ObjCGCs!")(static_cast <bool> (!Quals.hasObjCGCAttr() && "Type cannot have multiple ObjCGCs!"
) ? void (0) : __assert_fail ("!Quals.hasObjCGCAttr() && \"Type cannot have multiple ObjCGCs!\""
, "clang/lib/AST/ASTContext.cpp", 3171, __extension__ __PRETTY_FUNCTION__
))
;
3172 Quals.addObjCGCAttr(GCAttr);
3173
3174 return getExtQualType(TypeNode, Quals);
3175}
3176
3177QualType ASTContext::removePtrSizeAddrSpace(QualType T) const {
3178 if (const PointerType *Ptr = T->getAs<PointerType>()) {
3179 QualType Pointee = Ptr->getPointeeType();
3180 if (isPtrSizeAddressSpace(Pointee.getAddressSpace())) {
3181 return getPointerType(removeAddrSpaceQualType(Pointee));
3182 }
3183 }
3184 return T;
3185}
3186
3187const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
3188 FunctionType::ExtInfo Info) {
3189 if (T->getExtInfo() == Info)
3190 return T;
3191
3192 QualType Result;
3193 if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
3194 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
3195 } else {
3196 const auto *FPT = cast<FunctionProtoType>(T);
3197 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
3198 EPI.ExtInfo = Info;
3199 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
3200 }
3201
3202 return cast<FunctionType>(Result.getTypePtr());
3203}
3204
3205void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
3206 QualType ResultType) {
3207 FD = FD->getMostRecentDecl();
3208 while (true) {
3209 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
3210 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
3211 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
3212 if (FunctionDecl *Next = FD->getPreviousDecl())
3213 FD = Next;
3214 else
3215 break;
3216 }
3217 if (ASTMutationListener *L = getASTMutationListener())
3218 L->DeducedReturnType(FD, ResultType);
3219}
3220
3221/// Get a function type and produce the equivalent function type with the
3222/// specified exception specification. Type sugar that can be present on a
3223/// declaration of a function with an exception specification is permitted
3224/// and preserved. Other type sugar (for instance, typedefs) is not.
3225QualType ASTContext::getFunctionTypeWithExceptionSpec(
3226 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) const {
3227 // Might have some parens.
3228 if (const auto *PT = dyn_cast<ParenType>(Orig))
3229 return getParenType(
3230 getFunctionTypeWithExceptionSpec(PT->getInnerType(), ESI));
3231
3232 // Might be wrapped in a macro qualified type.
3233 if (const auto *MQT = dyn_cast<MacroQualifiedType>(Orig))
3234 return getMacroQualifiedType(
3235 getFunctionTypeWithExceptionSpec(MQT->getUnderlyingType(), ESI),
3236 MQT->getMacroIdentifier());
3237
3238 // Might have a calling-convention attribute.
3239 if (const auto *AT = dyn_cast<AttributedType>(Orig))
3240 return getAttributedType(
3241 AT->getAttrKind(),
3242 getFunctionTypeWithExceptionSpec(AT->getModifiedType(), ESI),
3243 getFunctionTypeWithExceptionSpec(AT->getEquivalentType(), ESI));
3244
3245 // Anything else must be a function type. Rebuild it with the new exception
3246 // specification.
3247 const auto *Proto = Orig->castAs<FunctionProtoType>();
3248 return getFunctionType(
3249 Proto->getReturnType(), Proto->getParamTypes(),
3250 Proto->getExtProtoInfo().withExceptionSpec(ESI));
3251}
3252
3253bool ASTContext::hasSameFunctionTypeIgnoringExceptionSpec(QualType T,
3254 QualType U) const {
3255 return hasSameType(T, U) ||
3256 (getLangOpts().CPlusPlus17 &&
3257 hasSameType(getFunctionTypeWithExceptionSpec(T, EST_None),
3258 getFunctionTypeWithExceptionSpec(U, EST_None)));
3259}
3260
3261QualType ASTContext::getFunctionTypeWithoutPtrSizes(QualType T) {
3262 if (const auto *Proto = T->getAs<FunctionProtoType>()) {
3263 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3264 SmallVector<QualType, 16> Args(Proto->param_types().size());
3265 for (unsigned i = 0, n = Args.size(); i != n; ++i)
3266 Args[i] = removePtrSizeAddrSpace(Proto->param_types()[i]);
3267 return getFunctionType(RetTy, Args, Proto->getExtProtoInfo());
3268 }
3269
3270 if (const FunctionNoProtoType *Proto = T->getAs<FunctionNoProtoType>()) {
3271 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3272 return getFunctionNoProtoType(RetTy, Proto->getExtInfo());
3273 }
3274
3275 return T;
3276}
3277
3278bool ASTContext::hasSameFunctionTypeIgnoringPtrSizes(QualType T, QualType U) {
3279 return hasSameType(T, U) ||
3280 hasSameType(getFunctionTypeWithoutPtrSizes(T),
3281 getFunctionTypeWithoutPtrSizes(U));
3282}
3283
3284void ASTContext::adjustExceptionSpec(
3285 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
3286 bool AsWritten) {
3287 // Update the type.
3288 QualType Updated =
3289 getFunctionTypeWithExceptionSpec(FD->getType(), ESI);
3290 FD->setType(Updated);
3291
3292 if (!AsWritten)
3293 return;
3294
3295 // Update the type in the type source information too.
3296 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
3297 // If the type and the type-as-written differ, we may need to update
3298 // the type-as-written too.
3299 if (TSInfo->getType() != FD->getType())
3300 Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI);
3301
3302 // FIXME: When we get proper type location information for exceptions,
3303 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
3304 // up the TypeSourceInfo;
3305 assert(TypeLoc::getFullDataSizeForType(Updated) ==(static_cast <bool> (TypeLoc::getFullDataSizeForType(Updated
) == TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
"TypeLoc size mismatch from updating exception specification"
) ? void (0) : __assert_fail ("TypeLoc::getFullDataSizeForType(Updated) == TypeLoc::getFullDataSizeForType(TSInfo->getType()) && \"TypeLoc size mismatch from updating exception specification\""
, "clang/lib/AST/ASTContext.cpp", 3307, __extension__ __PRETTY_FUNCTION__
))
3306 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&(static_cast <bool> (TypeLoc::getFullDataSizeForType(Updated
) == TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
"TypeLoc size mismatch from updating exception specification"
) ? void (0) : __assert_fail ("TypeLoc::getFullDataSizeForType(Updated) == TypeLoc::getFullDataSizeForType(TSInfo->getType()) && \"TypeLoc size mismatch from updating exception specification\""
, "clang/lib/AST/ASTContext.cpp", 3307, __extension__ __PRETTY_FUNCTION__
))
3307 "TypeLoc size mismatch from updating exception specification")(static_cast <bool> (TypeLoc::getFullDataSizeForType(Updated
) == TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
"TypeLoc size mismatch from updating exception specification"
) ? void (0) : __assert_fail ("TypeLoc::getFullDataSizeForType(Updated) == TypeLoc::getFullDataSizeForType(TSInfo->getType()) && \"TypeLoc size mismatch from updating exception specification\""
, "clang/lib/AST/ASTContext.cpp", 3307, __extension__ __PRETTY_FUNCTION__
))
;
3308 TSInfo->overrideType(Updated);
3309 }
3310}
3311
3312/// getComplexType - Return the uniqued reference to the type for a complex
3313/// number with the specified element type.
3314QualType ASTContext::getComplexType(QualType T) const {
3315 // Unique pointers, to guarantee there is only one pointer of a particular
3316 // structure.
3317 llvm::FoldingSetNodeID ID;
3318 ComplexType::Profile(ID, T);
3319
3320 void *InsertPos = nullptr;
3321 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
3322 return QualType(CT, 0);
3323
3324 // If the pointee type isn't canonical, this won't be a canonical type either,
3325 // so fill in the canonical type field.
3326 QualType Canonical;
3327 if (!T.isCanonical()) {
3328 Canonical = getComplexType(getCanonicalType(T));
3329
3330 // Get the new insert position for the node we care about.
3331 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
3332 assert(!NewIP && "Shouldn't be in the map!")(static_cast <bool> (!NewIP && "Shouldn't be in the map!"
) ? void (0) : __assert_fail ("!NewIP && \"Shouldn't be in the map!\""
, "clang/lib/AST/ASTContext.cpp", 3332, __extension__ __PRETTY_FUNCTION__
))
; (void)NewIP;
3333 }
3334 auto *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
3335 Types.push_back(New);
3336 ComplexTypes.InsertNode(New, InsertPos);
3337 return QualType(New, 0);
3338}
3339
3340/// getPointerType - Return the uniqued reference to the type for a pointer to
3341/// the specified type.
3342QualType ASTContext::getPointerType(QualType T) const {
3343 // Unique pointers, to guarantee there is only one pointer of a particular
3344 // structure.
3345 llvm::FoldingSetNodeID ID;
3346 PointerType::Profile(ID, T);
3347
3348 void *InsertPos = nullptr;
3349 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3350 return QualType(PT, 0);
3351
3352 // If the pointee type isn't canonical, this won't be a canonical type either,
3353 // so fill in the canonical type field.
3354 QualType Canonical;
3355 if (!T.isCanonical()) {
3356 Canonical = getPointerType(getCanonicalType(T));
3357
3358 // Get the new insert position for the node we care about.
3359 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3360 assert(!NewIP && "Shouldn't be in the map!")(static_cast <bool> (!NewIP && "Shouldn't be in the map!"
) ? void (0) : __assert_fail ("!NewIP && \"Shouldn't be in the map!\""
, "clang/lib/AST/ASTContext.cpp", 3360, __extension__ __PRETTY_FUNCTION__
))
; (void)NewIP;
3361 }
3362 auto *New = new (*this, TypeAlignment) PointerType(T, Canonical);
3363 Types.push_back(New);
3364 PointerTypes.InsertNode(New, InsertPos);
3365 return QualType(New, 0);
3366}
3367
3368QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
3369 llvm::FoldingSetNodeID ID;
3370 AdjustedType::Profile(ID, Orig, New);
3371 void *InsertPos = nullptr;
3372 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3373 if (AT)
3374 return QualType(AT, 0);
3375
3376 QualType Canonical = getCanonicalType(New);
3377
3378 // Get the new insert position for the node we care about.
3379 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3380 assert(!AT && "Shouldn't be in the map!")(static_cast <bool> (!AT && "Shouldn't be in the map!"
) ? void (0) : __assert_fail ("!AT && \"Shouldn't be in the map!\""
, "clang/lib/AST/ASTContext.cpp", 3380, __extension__ __PRETTY_FUNCTION__
))
;
3381
3382 AT = new (*this, TypeAlignment)
3383 AdjustedType(Type::Adjusted, Orig, New, Canonical);
3384 Types.push_back(AT);
3385 AdjustedTypes.InsertNode(AT, InsertPos);
3386 return QualType(AT, 0);
3387}
3388
3389QualType ASTContext::getDecayedType(QualType Orig, QualType Decayed) const {
3390 llvm::FoldingSetNodeID ID;
3391 AdjustedType::Profile(ID, Orig, Decayed);
3392 void *InsertPos = nullptr;
3393 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3394 if (AT)
3395 return QualType(AT, 0);
3396
3397 QualType Canonical = getCanonicalType(Decayed);
3398
3399 // Get the new insert position for the node we care about.
3400 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3401 assert(!AT && "Shouldn't be in the map!")(static_cast <bool> (!AT && "Shouldn't be in the map!"
) ? void (0) : __assert_fail ("!AT && \"Shouldn't be in the map!\""
, "clang/lib/AST/ASTContext.cpp", 3401, __extension__ __PRETTY_FUNCTION__
))
;
3402
3403 AT = new (*this, TypeAlignment) DecayedType(Orig, Decayed, Canonical);
3404 Types.push_back(AT);
3405 AdjustedTypes.InsertNode(AT, InsertPos);
3406 return QualType(AT, 0);
3407}
3408
3409QualType ASTContext::getDecayedType(QualType T) const {
3410 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay")(static_cast <bool> ((T->isArrayType() || T->isFunctionType
()) && "T does not decay") ? void (0) : __assert_fail
("(T->isArrayType() || T->isFunctionType()) && \"T does not decay\""
, "clang/lib/AST/ASTContext.cpp", 3410, __extension__ __PRETTY_FUNCTION__
))
;
3411
3412 QualType Decayed;
3413
3414 // C99 6.7.5.3p7:
3415 // A declaration of a parameter as "array of type" shall be
3416 // adjusted to "qualified pointer to type", where the type
3417 // qualifiers (if any) are those specified within the [ and ] of
3418 // the array type derivation.
3419 if (T->isArrayType())
3420 Decayed = getArrayDecayedType(T);
3421
3422 // C99 6.7.5.3p8:
3423 // A declaration of a parameter as "function returning type"
3424 // shall be adjusted to "pointer to function returning type", as
3425 // in 6.3.2.1.
3426 if (T->isFunctionType())
3427 Decayed = getPointerType(T);
3428
3429 return getDecayedType(T, Decayed);
3430}
3431
3432/// getBlockPointerType - Return the uniqued reference to the type for
3433/// a pointer to the specified block.
3434QualType ASTContext::getBlockPointerType(QualType T) const {
3435 assert(T->isFunctionType() && "block of function types only")(static_cast <bool> (T->isFunctionType() && "block of function types only"
) ? void (0) : __assert_fail ("T->isFunctionType() && \"block of function types only\""
, "clang/lib/AST/ASTContext.cpp", 3435, __extension__ __PRETTY_FUNCTION__
))
;
3436 // Unique pointers, to guarantee there is only one block of a particular
3437 // structure.
3438 llvm::FoldingSetNodeID ID;
3439 BlockPointerType::Profile(ID, T);
3440
3441 void *InsertPos = nullptr;
3442 if (BlockPointerType *PT =
3443 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3444 return QualType(PT, 0);
3445
3446 // If the block pointee type isn't canonical, this won't be a canonical
3447 // type either so fill in the canonical type field.
3448 QualType Canonical;
3449 if (!T.isCanonical()) {
3450 Canonical = getBlockPointerType(getCanonicalType(T));
3451
3452 // Get the new insert position for the node we care about.
3453 BlockPointerType *NewIP =
3454 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3455 assert(!NewIP && "Shouldn't be in the map!")(static_cast <bool> (!NewIP && "Shouldn't be in the map!"
) ? void (0) : __assert_fail ("!NewIP && \"Shouldn't be in the map!\""
, "clang/lib/AST/ASTContext.cpp", 3455, __extension__ __PRETTY_FUNCTION__
))
; (void)NewIP;
3456 }
3457 auto *New = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
3458 Types.push_back(New);
3459 BlockPointerTypes.InsertNode(New, InsertPos);
3460 return QualType(New, 0);
3461}
3462
3463/// getLValueReferenceType - Return the uniqued reference to the type for an
3464/// lvalue reference to the specified type.
3465QualType
3466ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
3467 assert((!T->isPlaceholderType() ||(static_cast <bool> ((!T->isPlaceholderType() || T->
isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
"Unresolved placeholder type") ? void (0) : __assert_fail ("(!T->isPlaceholderType() || T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) && \"Unresolved placeholder type\""
, "clang/lib/AST/ASTContext.cpp", 3469, __extension__ __PRETTY_FUNCTION__
))
3468 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&(static_cast <bool> ((!T->isPlaceholderType() || T->
isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
"Unresolved placeholder type") ? void (0) : __assert_fail ("(!T->isPlaceholderType() || T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) && \"Unresolved placeholder type\""
, "clang/lib/AST/ASTContext.cpp", 3469, __extension__ __PRETTY_FUNCTION__
))
3469 "Unresolved placeholder type")(static_cast <bool> ((!T->isPlaceholderType() || T->
isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
"Unresolved placeholder type") ? void (0) : __assert_fail ("(!T->isPlaceholderType() || T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) && \"Unresolved placeholder type\""
, "clang/lib/AST/ASTContext.cpp", 3469, __extension__ __PRETTY_FUNCTION__
))
;
3470
3471 // Unique pointers, to guarantee there is only one pointer of a particular
3472 // structure.
3473 llvm::FoldingSetNodeID ID;
3474 ReferenceType::Profile(ID, T, SpelledAsLValue);
3475
3476 void *InsertPos = nullptr;
3477 if (LValueReferenceType *RT =
3478 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
3479 return QualType(RT, 0);
3480
3481 const auto *InnerRef = T->getAs<ReferenceType>();
3482
3483 // If the referencee type isn't canonical, this won't be a canonical type
3484 // either, so fill in the canonical type field.
3485 QualType Canonical;
3486 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
3487 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
3488 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
3489
3490 // Get the new insert position for the node we care about.
3491 LValueReferenceType *NewIP =
3492 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
3493 assert(!NewIP && "Shouldn't be in the map!")(static_cast <bool> (!NewIP && "Shouldn't be in the map!"
) ? void (0) : __assert_fail ("!NewIP && \"Shouldn't be in the map!\""
, "clang/lib/AST/ASTContext.cpp", 3493, __extension__ __PRETTY_FUNCTION__
))
; (void)NewIP;
3494 }
3495
3496 auto *New = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
3497 SpelledAsLValue);
3498 Types.push_back(New);
3499 LValueReferenceTypes.InsertNode(New, InsertPos);
3500
3501 return QualType(New, 0);
3502}
3503
3504/// getRValueReferenceType - Return the uniqued reference to the type for an
3505/// rvalue reference to the specified type.
3506QualType ASTContext::getRValueReferenceType(QualType T) const {
3507 assert((!T->isPlaceholderType() ||(static_cast <bool> ((!T->isPlaceholderType() || T->
isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
"Unresolved placeholder type") ? void (0) : __assert_fail ("(!T->isPlaceholderType() || T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) && \"Unresolved placeholder type\""
, "clang/lib/AST/ASTContext.cpp", 3509, __extension__ __PRETTY_FUNCTION__
))
3508 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&(static_cast <bool> ((!T->isPlaceholderType() || T->
isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
"Unresolved placeholder type") ? void (0) : __assert_fail ("(!T->isPlaceholderType() || T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) && \"Unresolved placeholder type\""
, "clang/lib/AST/ASTContext.cpp", 3509, __extension__ __PRETTY_FUNCTION__
))
3509 "Unresolved placeholder type")(static_cast <bool> ((!T->isPlaceholderType() || T->
isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
"Unresolved placeholder type") ? void (0) : __assert_fail ("(!T->isPlaceholderType() || T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) && \"Unresolved placeholder type\""
, "clang/lib/AST/ASTContext.cpp", 3509, __extension__ __PRETTY_FUNCTION__
))
;
3510
3511 // Unique pointers, to guarantee there is only one pointer of a particular
3512 // structure.
3513 llvm::FoldingSetNodeID ID;
3514 ReferenceType::Profile(ID, T, false);
3515
3516 void *InsertPos = nullptr;
3517 if (RValueReferenceType *RT =
3518 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
3519 return QualType(RT, 0);
3520
3521 const auto *InnerRef = T->getAs<ReferenceType>();
3522
3523 // If the referencee type isn't canonical, this won't be a canonical type
3524 // either, so fill in the canonical type field.
3525 QualType Canonical;
3526 if (InnerRef || !T.isCanonical()) {
3527 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
3528 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
3529
3530 // Get the new insert position for the node we care about.
3531 RValueReferenceType *NewIP =
3532 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
3533 assert(!NewIP && "Shouldn't be in the map!")(static_cast <bool> (!NewIP && "Shouldn't be in the map!"
) ? void (0) : __assert_fail ("!NewIP && \"Shouldn't be in the map!\""
, "clang/lib/AST/ASTContext.cpp", 3533, __extension__ __PRETTY_FUNCTION__
))
; (void)NewIP;
3534 }
3535
3536 auto *New = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
3537 Types.push_back(New);
3538 RValueReferenceTypes.InsertNode(New, InsertPos);
3539 return QualType(New, 0);
3540}
3541
3542/// getMemberPointerType - Return the uniqued reference to the type for a
3543/// member pointer to the specified type, in the specified class.
3544QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
3545 // Unique pointers, to guarantee there is only one pointer of a particular
3546 // structure.
3547 llvm::FoldingSetNodeID ID;
3548 MemberPointerType::Profile(ID, T, Cls);
3549
3550 void *InsertPos = nullptr;
3551 if (MemberPointerType *PT =
3552 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3553 return QualType(PT, 0);
3554
3555 // If the pointee or class type isn't canonical, this won't be a canonical
3556 // type either, so fill in the canonical type field.
3557 QualType Canonical;
3558 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
3559 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
3560
3561 // Get the new insert position for the node we care about.
3562 MemberPointerType *NewIP =
3563 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3564 assert(!NewIP && "Shouldn't be in the map!")(static_cast <bool> (!NewIP && "Shouldn't be in the map!"
) ? void (0) : __assert_fail ("!NewIP && \"Shouldn't be in the map!\""
, "clang/lib/AST/ASTContext.cpp", 3564, __extension__ __PRETTY_FUNCTION__
))
; (void)NewIP;
3565 }
3566 auto *New = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
3567 Types.push_back(New);
3568 MemberPointerTypes.InsertNode(New, InsertPos);
3569 return QualType(New, 0);
3570}
3571
3572/// getConstantArrayType - Return the unique reference to the type for an
3573/// array of the specified element type.
3574QualType ASTContext::getConstantArrayType(QualType EltTy,
3575 const llvm::APInt &ArySizeIn,
3576 const Expr *SizeExpr,
3577 ArrayType::ArraySizeModifier ASM,
3578 unsigned IndexTypeQuals) const {
3579 assert((EltTy->isDependentType() ||(static_cast <bool> ((EltTy->isDependentType() || EltTy
->isIncompleteType() || EltTy->isConstantSizeType()) &&
"Constant array of VLAs is illegal!") ? void (0) : __assert_fail
("(EltTy->isDependentType() || EltTy->isIncompleteType() || EltTy->isConstantSizeType()) && \"Constant array of VLAs is illegal!\""
, "clang/lib/AST/ASTContext.cpp", 3581, __extension__ __PRETTY_FUNCTION__
))
3580 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&(static_cast <bool> ((EltTy->isDependentType() || EltTy
->isIncompleteType() || EltTy->isConstantSizeType()) &&
"Constant array of VLAs is illegal!") ? void (0) : __assert_fail
("(EltTy->isDependentType() || EltTy->isIncompleteType() || EltTy->isConstantSizeType()) && \"Constant array of VLAs is illegal!\""
, "clang/lib/AST/ASTContext.cpp", 3581, __extension__ __PRETTY_FUNCTION__
))
3581 "Constant array of VLAs is illegal!")(static_cast <bool> ((EltTy->isDependentType() || EltTy
->isIncompleteType() || EltTy->isConstantSizeType()) &&
"Constant array of VLAs is illegal!") ? void (0) : __assert_fail
("(EltTy->isDependentType() || EltTy->isIncompleteType() || EltTy->isConstantSizeType()) && \"Constant array of VLAs is illegal!\""
, "clang/lib/AST/ASTContext.cpp", 3581, __extension__ __PRETTY_FUNCTION__
))
;
3582
3583 // We only need the size as part of the type if it's instantiation-dependent.
3584 if (SizeExpr && !SizeExpr->isInstantiationDependent())
3585 SizeExpr = nullptr;
3586
3587 // Convert the array size into a canonical width matching the pointer size for
3588 // the target.
3589 llvm::APInt ArySize(ArySizeIn);
3590 ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth());
3591
3592 llvm::FoldingSetNodeID ID;
3593 ConstantArrayType::Profile(ID, *this, EltTy, ArySize, SizeExpr, ASM,
3594 IndexTypeQuals);
3595
3596 void *InsertPos = nullptr;
3597 if (ConstantArrayType *ATP =
3598 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
3599 return QualType(ATP, 0);
3600
3601 // If the element type isn't canonical or has qualifiers, or the array bound
3602 // is instantiation-dependent, this won't be a canonical type either, so fill
3603 // in the canonical type field.
3604 QualType Canon;
3605 // FIXME: Check below should look for qualifiers behind sugar.
3606 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers() || SizeExpr) {
3607 SplitQualType canonSplit = getCanonicalType(EltTy).split();
3608 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize, nullptr,
3609 ASM, IndexTypeQuals);
3610 Canon = getQualifiedType(Canon, canonSplit.Quals);
3611
3612 // Get the new insert position for the node we care about.
3613 ConstantArrayType *NewIP =
3614 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
3615 assert(!NewIP && "Shouldn't be in the map!")(static_cast <bool> (!NewIP && "Shouldn't be in the map!"
) ? void (0) : __assert_fail ("!NewIP && \"Shouldn't be in the map!\""
, "clang/lib/AST/ASTContext.cpp", 3615, __extension__ __PRETTY_FUNCTION__
))
; (void)NewIP;
3616 }
3617
3618 void *Mem = Allocate(
3619 ConstantArrayType::totalSizeToAlloc<const Expr *>(SizeExpr ? 1 : 0),
3620 TypeAlignment);
3621 auto *New = new (Mem)
3622 ConstantArrayType(EltTy, Canon, ArySize, SizeExpr, ASM, IndexTypeQuals);
3623 ConstantArrayTypes.InsertNode(New, InsertPos);
3624 Types.push_back(New);
3625 return QualType(New, 0);
3626}
3627
3628/// getVariableArrayDecayedType - Turns the given type, which may be
3629/// variably-modified, into the corresponding type with all the known
3630/// sizes replaced with [*].
3631QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
3632 // Vastly most common case.
3633 if (!type->isVariablyModifiedType()) return type;
3634
3635 QualType result;
3636
3637 SplitQualType split = type.getSplitDesugaredType();
3638 const Type *ty = split.Ty;
3639 switch (ty->getTypeClass()) {
3640#define TYPE(Class, Base)
3641#define ABSTRACT_TYPE(Class, Base)
3642#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3643#include "clang/AST/TypeNodes.inc"
3644 llvm_unreachable("didn't desugar past all non-canonical types?")::llvm::llvm_unreachable_internal("didn't desugar past all non-canonical types?"
, "clang/lib/AST/ASTContext.cpp", 3644)
;
3645
3646 // These types should never be variably-modified.
3647 case Type::Builtin:
3648 case Type::Complex:
3649 case Type::Vector:
3650 case Type::DependentVector:
3651 case Type::ExtVector:
3652 case Type::DependentSizedExtVector:
3653 case Type::ConstantMatrix:
3654 case Type::DependentSizedMatrix:
3655 case Type::DependentAddressSpace:
3656 case Type::ObjCObject:
3657 case Type::ObjCInterface:
3658 case Type::ObjCObjectPointer:
3659 case Type::Record:
3660 case Type::Enum:
3661 case Type::UnresolvedUsing:
3662 case Type::TypeOfExpr:
3663 case Type::TypeOf:
3664 case Type::Decltype:
3665 case Type::UnaryTransform:
3666 case Type::DependentName:
3667 case Type::InjectedClassName:
3668 case Type::TemplateSpecialization:
3669 case Type::DependentTemplateSpecialization:
3670 case Type::TemplateTypeParm:
3671 case Type::SubstTemplateTypeParmPack:
3672 case Type::Auto:
3673 case Type::DeducedTemplateSpecialization:
3674 case Type::PackExpansion:
3675 case Type::BitInt:
3676 case Type::DependentBitInt:
3677 llvm_unreachable("type should never be variably-modified")::llvm::llvm_unreachable_internal("type should never be variably-modified"
, "clang/lib/AST/ASTContext.cpp", 3677)
;
3678
3679 // These types can be variably-modified but should never need to
3680 // further decay.
3681 case Type::FunctionNoProto:
3682 case Type::FunctionProto:
3683 case Type::BlockPointer:
3684 case Type::MemberPointer:
3685 case Type::Pipe:
3686 return type;
3687
3688 // These types can be variably-modified. All these modifications
3689 // preserve structure except as noted by comments.
3690 // TODO: if we ever care about optimizing VLAs, there are no-op
3691 // optimizations available here.
3692 case Type::Pointer:
3693 result = getPointerType(getVariableArrayDecayedType(
3694 cast<PointerType>(ty)->getPointeeType()));
3695 break;
3696
3697 case Type::LValueReference: {
3698 const auto *lv = cast<LValueReferenceType>(ty);
3699 result = getLValueReferenceType(
3700 getVariableArrayDecayedType(lv->getPointeeType()),
3701 lv->isSpelledAsLValue());
3702 break;
3703 }
3704
3705 case Type::RValueReference: {
3706 const auto *lv = cast<RValueReferenceType>(ty);
3707 result = getRValueReferenceType(
3708 getVariableArrayDecayedType(lv->getPointeeType()));
3709 break;
3710 }
3711
3712 case Type::Atomic: {
3713 const auto *at = cast<AtomicType>(ty);
3714 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
3715 break;
3716 }
3717
3718 case Type::ConstantArray: {
3719 const auto *cat = cast<ConstantArrayType>(ty);
3720 result = getConstantArrayType(
3721 getVariableArrayDecayedType(cat->getElementType()),
3722 cat->getSize(),
3723 cat->getSizeExpr(),
3724 cat->getSizeModifier(),
3725 cat->getIndexTypeCVRQualifiers());
3726 break;
3727 }
3728
3729 case Type::DependentSizedArray: {
3730 const auto *dat = cast<DependentSizedArrayType>(ty);
3731 result = getDependentSizedArrayType(
3732 getVariableArrayDecayedType(dat->getElementType()),
3733 dat->getSizeExpr(),
3734 dat->getSizeModifier(),
3735 dat->getIndexTypeCVRQualifiers(),
3736 dat->getBracketsRange());
3737 break;
3738 }
3739
3740 // Turn incomplete types into [*] types.
3741 case Type::IncompleteArray: {
3742 const auto *iat = cast<IncompleteArrayType>(ty);
3743 result = getVariableArrayType(
3744 getVariableArrayDecayedType(iat->getElementType()),
3745 /*size*/ nullptr,
3746 ArrayType::Normal,
3747 iat->getIndexTypeCVRQualifiers(),
3748 SourceRange());
3749 break;
3750 }
3751
3752 // Turn VLA types into [*] types.
3753 case Type::VariableArray: {
3754 const auto *vat = cast<VariableArrayType>(ty);
3755 result = getVariableArrayType(
3756 getVariableArrayDecayedType(vat->getElementType()),
3757 /*size*/ nullptr,
3758 ArrayType::Star,
3759 vat->getIndexTypeCVRQualifiers(),
3760 vat->getBracketsRange());
3761 break;
3762 }
3763 }
3764
3765 // Apply the top-level qualifiers from the original.
3766 return getQualifiedType(result, split.Quals);
3767}
3768
3769/// getVariableArrayType - Returns a non-unique reference to the type for a
3770/// variable array of the specified element type.
3771QualType ASTContext::getVariableArrayType(QualType EltTy,
3772 Expr *NumElts,
3773 ArrayType::ArraySizeModifier ASM,
3774 unsigned IndexTypeQuals,
3775 SourceRange Brackets) const {
3776 // Since we don't unique expressions, it isn't possible to unique VLA's
3777 // that have an expression provided for their size.
3778 QualType Canon;
3779
3780 // Be sure to pull qualifiers off the element type.
3781 // FIXME: Check below should look for qualifiers behind sugar.
3782 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
3783 SplitQualType canonSplit = getCanonicalType(EltTy).split();
3784 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
3785 IndexTypeQuals, Brackets);
3786 Canon = getQualifiedType(Canon, canonSplit.Quals);
3787 }
3788
3789 auto *New = new (*this, TypeAlignment)
3790 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
3791
3792 VariableArrayTypes.push_back(New);
3793 Types.push_back(New);
3794 return QualType(New, 0);
3795}
3796
3797/// getDependentSizedArrayType - Returns a non-unique reference to
3798/// the type for a dependently-sized array of the specified element
3799/// type.
3800QualType ASTContext::getDependentSizedArrayType(QualType elementType,
3801 Expr *numElements,
3802 ArrayType::ArraySizeModifier ASM,
3803 unsigned elementTypeQuals,
3804 SourceRange brackets) const {
3805 assert((!numElements || numElements->isTypeDependent() ||(static_cast <bool> ((!numElements || numElements->isTypeDependent
() || numElements->isValueDependent()) && "Size must be type- or value-dependent!"
) ? void (0) : __assert_fail ("(!numElements || numElements->isTypeDependent() || numElements->isValueDependent()) && \"Size must be type- or value-dependent!\""
, "clang/lib/AST/ASTContext.cpp", 3807, __extension__ __PRETTY_FUNCTION__
))
3806 numElements->isValueDependent()) &&(static_cast <bool> ((!numElements || numElements->isTypeDependent
() || numElements->isValueDependent()) && "Size must be type- or value-dependent!"
) ? void (0) : __assert_fail ("(!numElements || numElements->isTypeDependent() || numElements->isValueDependent()) && \"Size must be type- or value-dependent!\""
, "clang/lib/AST/ASTContext.cpp", 3807, __extension__ __PRETTY_FUNCTION__
))
3807 "Size must be type- or value-dependent!")(static_cast <bool> ((!numElements || numElements->isTypeDependent
() || numElements->isValueDependent()) && "Size must be type- or value-dependent!"
) ? void (0) : __assert_fail ("(!numElements || numElements->isTypeDependent() || numElements->isValueDependent()) && \"Size must be type- or value-dependent!\""
, "clang/lib/AST/ASTContext.cpp", 3807, __extension__ __PRETTY_FUNCTION__
))
;
3808
3809 // Dependently-sized array types that do not have a specified number
3810 // of elements will have their sizes deduced from a dependent
3811 // initializer. We do no canonicalization here at all, which is okay
3812 // because they can't be used in most locations.
3813 if (!numElements) {
3814 auto *newType
3815 = new (*this, TypeAlignment)
3816 DependentSizedArrayType(*this, elementType, QualType(),
3817 numElements, ASM, elementTypeQuals,
3818 brackets);
3819 Types.push_back(newType);
3820 return QualType(newType, 0);
3821 }
3822
3823 // Otherwise, we actually build a new type every time, but we
3824 // also build a canonical type.
3825
3826 SplitQualType canonElementType = getCanonicalType(elementType).split();
3827
3828 void *insertPos = nullptr;
3829 llvm::FoldingSetNodeID ID;
3830 DependentSizedArrayType::Profile(ID, *this,
3831 QualType(canonElementType.Ty, 0),
3832 ASM, elementTypeQuals, numElements);
3833
3834 // Look for an existing type with these properties.
3835 DependentSizedArrayType *canonTy =
3836 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
3837
3838 // If we don't have one, build one.
3839 if (!canonTy) {
3840 canonTy = new (*this, TypeAlignment)
3841 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
3842 QualType(), numElements, ASM, elementTypeQuals,
3843 brackets);
3844 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
3845 Types.push_back(canonTy);
3846 }
3847
3848 // Apply qualifiers from the element type to the array.
3849 QualType canon = getQualifiedType(QualType(canonTy,0),
3850 canonElementType.Quals);
3851
3852 // If we didn't need extra canonicalization for the element type or the size
3853 // expression, then just use that as our result.
3854 if (QualType(canonElementType.Ty, 0) == elementType &&
3855 canonTy->getSizeExpr() == numElements)
3856 return canon;
3857
3858 // Otherwise, we need to build a type which follows the spelling
3859 // of the element type.
3860 auto *sugaredType
3861 = new (*this, TypeAlignment)
3862 DependentSizedArrayType(*this, elementType, canon, numElements,
3863 ASM, elementTypeQuals, brackets);
3864 Types.push_back(sugaredType);
3865 return QualType(sugaredType, 0);
3866}
3867
3868QualType ASTContext::getIncompleteArrayType(QualType elementType,
3869 ArrayType::ArraySizeModifier ASM,
3870 unsigned elementTypeQuals) const {
3871 llvm::FoldingSetNodeID ID;
3872 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
3873
3874 void *insertPos = nullptr;
3875 if (IncompleteArrayType *iat =
3876 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
3877 return QualType(iat, 0);
3878
3879 // If the element type isn't canonical, this won't be a canonical type
3880 // either, so fill in the canonical type field. We also have to pull
3881 // qualifiers off the element type.
3882 QualType canon;
3883
3884 // FIXME: Check below should look for qualifiers behind sugar.
3885 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
3886 SplitQualType canonSplit = getCanonicalType(elementType).split();
3887 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
3888 ASM, elementTypeQuals);
3889 canon = getQualifiedType(canon, canonSplit.Quals);
3890
3891 // Get the new insert position for the node we care about.
3892 IncompleteArrayType *existing =
3893 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
3894 assert(!existing && "Shouldn't be in the map!")(static_cast <bool> (!existing && "Shouldn't be in the map!"
) ? void (0) : __assert_fail ("!existing && \"Shouldn't be in the map!\""
, "clang/lib/AST/ASTContext.cpp", 3894, __extension__ __PRETTY_FUNCTION__
))
; (void) existing;
3895 }
3896
3897 auto *newType = new (*this, TypeAlignment)
3898 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
3899
3900 IncompleteArrayTypes.InsertNode(newType, insertPos);
3901 Types.push_back(newType);
3902 return QualType(newType, 0);
3903}
3904
3905ASTContext::BuiltinVectorTypeInfo
3906ASTContext::getBuiltinVectorTypeInfo(const BuiltinType *Ty) const {
3907#define SVE_INT_ELTTY(BITS, ELTS, SIGNED, NUMVECTORS){getIntTypeForBitwidth(BITS, SIGNED), llvm::ElementCount::getScalable
(ELTS), NUMVECTORS};
\
3908 {getIntTypeForBitwidth(BITS, SIGNED), llvm::ElementCount::getScalable(ELTS), \
3909 NUMVECTORS};
3910
3911#define SVE_ELTTY(ELTTY, ELTS, NUMVECTORS){ELTTY, llvm::ElementCount::getScalable(ELTS), NUMVECTORS}; \
3912 {ELTTY, llvm::ElementCount::getScalable(ELTS), NUMVECTORS};
3913
3914 switch (Ty->getKind()) {
3915 default:
3916 llvm_unreachable("Unsupported builtin vector type")::llvm::llvm_unreachable_internal("Unsupported builtin vector type"
, "clang/lib/AST/ASTContext.cpp", 3916)
;
3917 case BuiltinType::SveInt8:
3918 return SVE_INT_ELTTY(8, 16, true, 1){getIntTypeForBitwidth(8, true), llvm::ElementCount::getScalable
(16), 1};
;
3919 case BuiltinType::SveUint8:
3920 return SVE_INT_ELTTY(8, 16, false, 1){getIntTypeForBitwidth(8, false), llvm::ElementCount::getScalable
(16), 1};
;
3921 case BuiltinType::SveInt8x2:
3922 return SVE_INT_ELTTY(8, 16, true, 2){getIntTypeForBitwidth(8, true), llvm::ElementCount::getScalable
(16), 2};
;
3923 case BuiltinType::SveUint8x2:
3924 return SVE_INT_ELTTY(8, 16, false, 2){getIntTypeForBitwidth(8, false), llvm::ElementCount::getScalable
(16), 2};
;
3925 case BuiltinType::SveInt8x3:
3926 return SVE_INT_ELTTY(8, 16, true, 3){getIntTypeForBitwidth(8, true), llvm::ElementCount::getScalable
(16), 3};
;
3927 case BuiltinType::SveUint8x3:
3928 return SVE_INT_ELTTY(8, 16, false, 3){getIntTypeForBitwidth(8, false), llvm::ElementCount::getScalable
(16), 3};
;
3929 case BuiltinType::SveInt8x4:
3930 return SVE_INT_ELTTY(8, 16, true, 4){getIntTypeForBitwidth(8, true), llvm::ElementCount::getScalable
(16), 4};
;
3931 case BuiltinType::SveUint8x4:
3932 return SVE_INT_ELTTY(8, 16, false, 4){getIntTypeForBitwidth(8, false), llvm::ElementCount::getScalable
(16), 4};
;
3933 case BuiltinType::SveInt16:
3934 return SVE_INT_ELTTY(16, 8, true, 1){getIntTypeForBitwidth(16, true), llvm::ElementCount::getScalable
(8), 1};
;
3935 case BuiltinType::SveUint16:
3936 return SVE_INT_ELTTY(16, 8, false, 1){getIntTypeForBitwidth(16, false), llvm::ElementCount::getScalable
(8), 1};
;
3937 case BuiltinType::SveInt16x2:
3938 return SVE_INT_ELTTY(16, 8, true, 2){getIntTypeForBitwidth(16, true), llvm::ElementCount::getScalable
(8), 2};
;
3939 case BuiltinType::SveUint16x2:
3940 return SVE_INT_ELTTY(16, 8, false, 2){getIntTypeForBitwidth(16, false), llvm::ElementCount::getScalable
(8), 2};
;
3941 case BuiltinType::SveInt16x3:
3942 return SVE_INT_ELTTY(16, 8, true, 3){getIntTypeForBitwidth(16, true), llvm::ElementCount::getScalable
(8), 3};
;
3943 case BuiltinType::SveUint16x3:
3944 return SVE_INT_ELTTY(16, 8, false, 3){getIntTypeForBitwidth(16, false), llvm::ElementCount::getScalable
(8), 3};
;
3945 case BuiltinType::SveInt16x4:
3946 return SVE_INT_ELTTY(16, 8, true, 4){getIntTypeForBitwidth(16, true), llvm::ElementCount::getScalable
(8), 4};
;
3947 case BuiltinType::SveUint16x4:
3948 return SVE_INT_ELTTY(16, 8, false, 4){getIntTypeForBitwidth(16, false), llvm::ElementCount::getScalable
(8), 4};
;
3949 case BuiltinType::SveInt32:
3950 return SVE_INT_ELTTY(32, 4, true, 1){getIntTypeForBitwidth(32, true), llvm::ElementCount::getScalable
(4), 1};
;
3951 case BuiltinType::SveUint32:
3952 return SVE_INT_ELTTY(32, 4, false, 1){getIntTypeForBitwidth(32, false), llvm::ElementCount::getScalable
(4), 1};
;
3953 case BuiltinType::SveInt32x2:
3954 return SVE_INT_ELTTY(32, 4, true, 2){getIntTypeForBitwidth(32, true), llvm::ElementCount::getScalable
(4), 2};
;
3955 case BuiltinType::SveUint32x2:
3956 return SVE_INT_ELTTY(32, 4, false, 2){getIntTypeForBitwidth(32, false), llvm::ElementCount::getScalable
(4), 2};
;
3957 case BuiltinType::SveInt32x3:
3958 return SVE_INT_ELTTY(32, 4, true, 3){getIntTypeForBitwidth(32, true), llvm::ElementCount::getScalable
(4), 3};
;
3959 case BuiltinType::SveUint32x3:
3960 return SVE_INT_ELTTY(32, 4, false, 3){getIntTypeForBitwidth(32, false), llvm::ElementCount::getScalable
(4), 3};
;
3961 case BuiltinType::SveInt32x4:
3962 return SVE_INT_ELTTY(32, 4, true, 4){getIntTypeForBitwidth(32, true), llvm::ElementCount::getScalable
(4), 4};
;
3963 case BuiltinType::SveUint32x4:
3964 return SVE_INT_ELTTY(32, 4, false, 4){getIntTypeForBitwidth(32, false), llvm::ElementCount::getScalable
(4), 4};
;
3965 case BuiltinType::SveInt64:
3966 return SVE_INT_ELTTY(64, 2, true, 1){getIntTypeForBitwidth(64, true), llvm::ElementCount::getScalable
(2), 1};
;
3967 case BuiltinType::SveUint64:
3968 return SVE_INT_ELTTY(64, 2, false, 1){getIntTypeForBitwidth(64, false), llvm::ElementCount::getScalable
(2), 1};
;
3969 case BuiltinType::SveInt64x2:
3970 return SVE_INT_ELTTY(64, 2, true, 2){getIntTypeForBitwidth(64, true), llvm::ElementCount::getScalable
(2), 2};
;
3971 case BuiltinType::SveUint64x2:
3972 return SVE_INT_ELTTY(64, 2, false, 2){getIntTypeForBitwidth(64, false), llvm::ElementCount::getScalable
(2), 2};
;
3973 case BuiltinType::SveInt64x3:
3974 return SVE_INT_ELTTY(64, 2, true, 3){getIntTypeForBitwidth(64, true), llvm::ElementCount::getScalable
(2), 3};
;
3975 case BuiltinType::SveUint64x3:
3976 return SVE_INT_ELTTY(64, 2, false, 3){getIntTypeForBitwidth(64, false), llvm::ElementCount::getScalable
(2), 3};
;
3977 case BuiltinType::SveInt64x4:
3978 return SVE_INT_ELTTY(64, 2, true, 4){getIntTypeForBitwidth(64, true), llvm::ElementCount::getScalable
(2), 4};
;
3979 case BuiltinType::SveUint64x4:
3980 return SVE_INT_ELTTY(64, 2, false, 4){getIntTypeForBitwidth(64, false), llvm::ElementCount::getScalable
(2), 4};
;
3981 case BuiltinType::SveBool:
3982 return SVE_ELTTY(BoolTy, 16, 1){BoolTy, llvm::ElementCount::getScalable(16), 1};;
3983 case BuiltinType::SveFloat16:
3984 return SVE_ELTTY(HalfTy, 8, 1){HalfTy, llvm::ElementCount::getScalable(8), 1};;
3985 case BuiltinType::SveFloat16x2:
3986 return SVE_ELTTY(HalfTy, 8, 2){HalfTy, llvm::ElementCount::getScalable(8), 2};;
3987 case BuiltinType::SveFloat16x3:
3988 return SVE_ELTTY(HalfTy, 8, 3){HalfTy, llvm::ElementCount::getScalable(8), 3};;
3989 case BuiltinType::SveFloat16x4:
3990 return SVE_ELTTY(HalfTy, 8, 4){HalfTy, llvm::ElementCount::getScalable(8), 4};;
3991 case BuiltinType::SveFloat32:
3992 return SVE_ELTTY(FloatTy, 4, 1){FloatTy, llvm::ElementCount::getScalable(4), 1};;
3993 case BuiltinType::SveFloat32x2:
3994 return SVE_ELTTY(FloatTy, 4, 2){FloatTy, llvm::ElementCount::getScalable(4), 2};;
3995 case BuiltinType::SveFloat32x3:
3996 return SVE_ELTTY(FloatTy, 4, 3){FloatTy, llvm::ElementCount::getScalable(4), 3};;
3997 case BuiltinType::SveFloat32x4:
3998 return SVE_ELTTY(FloatTy, 4, 4){FloatTy, llvm::ElementCount::getScalable(4), 4};;
3999 case BuiltinType::SveFloat64:
4000 return SVE_ELTTY(DoubleTy, 2, 1){DoubleTy, llvm::ElementCount::getScalable(2), 1};;
4001 case BuiltinType::SveFloat64x2:
4002 return SVE_ELTTY(DoubleTy, 2, 2){DoubleTy, llvm::ElementCount::getScalable(2), 2};;
4003 case BuiltinType::SveFloat64x3:
4004 return SVE_ELTTY(DoubleTy, 2, 3){DoubleTy, llvm::ElementCount::getScalable(2), 3};;
4005 case BuiltinType::SveFloat64x4:
4006 return SVE_ELTTY(DoubleTy, 2, 4){DoubleTy, llvm::ElementCount::getScalable(2), 4};;
4007 case BuiltinType::SveBFloat16:
4008 return SVE_ELTTY(BFloat16Ty, 8, 1){BFloat16Ty, llvm::ElementCount::getScalable(8), 1};;
4009 case BuiltinType::SveBFloat16x2:
4010 return SVE_ELTTY(BFloat16Ty, 8, 2){BFloat16Ty, llvm::ElementCount::getScalable(8), 2};;
4011 case BuiltinType::SveBFloat16x3:
4012 return SVE_ELTTY(BFloat16Ty, 8, 3){BFloat16Ty, llvm::ElementCount::getScalable(8), 3};;
4013 case BuiltinType::SveBFloat16x4:
4014 return SVE_ELTTY(BFloat16Ty, 8, 4){BFloat16Ty, llvm::ElementCount::getScalable(8), 4};;
4015#define RVV_VECTOR_TYPE_INT(Name, Id, SingletonId, NumEls, ElBits, NF, \
4016 IsSigned) \
4017 case BuiltinType::Id: \
4018 return {getIntTypeForBitwidth(ElBits, IsSigned), \
4019 llvm::ElementCount::getScalable(NumEls), NF};
4020#define RVV_VECTOR_TYPE_FLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \
4021 case BuiltinType::Id: \
4022 return {ElBits == 16 ? Float16Ty : (ElBits == 32 ? FloatTy : DoubleTy), \
4023 llvm::ElementCount::getScalable(NumEls), NF};
4024#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
4025 case BuiltinType::Id: \
4026 return {BoolTy, llvm::ElementCount::getScalable(NumEls), 1};
4027#include "clang/Basic/RISCVVTypes.def"
4028 }
4029}
4030
4031/// getScalableVectorType - Return the unique reference to a scalable vector
4032/// type of the specified element type and size. VectorType must be a built-in
4033/// type.
4034QualType ASTContext::getScalableVectorType(QualType EltTy,
4035 unsigned NumElts) const {
4036 if (Target->hasAArch64SVETypes()) {
4037 uint64_t EltTySize = getTypeSize(EltTy);
4038#define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId, NumEls, ElBits, \
4039 IsSigned, IsFP, IsBF) \
4040 if (!EltTy->isBooleanType() && \
4041 ((EltTy->hasIntegerRepresentation() && \
4042 EltTy->hasSignedIntegerRepresentation() == IsSigned) || \
4043 (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \
4044 IsFP && !IsBF) || \
4045 (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \
4046 IsBF && !IsFP)) && \
4047 EltTySize == ElBits && NumElts == NumEls) { \
4048 return SingletonId; \
4049 }
4050#define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId, NumEls) \
4051 if (EltTy->isBooleanType() && NumElts == NumEls) \
4052 return SingletonId;
4053#include "clang/Basic/AArch64SVEACLETypes.def"
4054 } else if (Target->hasRISCVVTypes()) {
4055 uint64_t EltTySize = getTypeSize(EltTy);
4056#define RVV_VECTOR_TYPE(Name, Id, SingletonId, NumEls, ElBits, NF, IsSigned, \
4057 IsFP) \
4058 if (!EltTy->isBooleanType() && \
4059 ((EltTy->hasIntegerRepresentation() && \
4060 EltTy->hasSignedIntegerRepresentation() == IsSigned) || \
4061 (EltTy->hasFloatingRepresentation() && IsFP)) && \
4062 EltTySize == ElBits && NumElts == NumEls) \
4063 return SingletonId;
4064#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
4065 if (EltTy->isBooleanType() && NumElts == NumEls) \
4066 return SingletonId;
4067#include "clang/Basic/RISCVVTypes.def"
4068 }
4069 return QualType();
4070}
4071
4072/// getVectorType - Return the unique reference to a vector type of
4073/// the specified element type and size. VectorType must be a built-in type.
4074QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
4075 VectorType::VectorKind VecKind) const {
4076 assert(vecType->isBuiltinType() ||(static_cast <bool> (vecType->isBuiltinType() || (vecType
->isBitIntType() && llvm::isPowerOf2_32(vecType->
getAs<BitIntType>()->getNumBits()) && vecType
->getAs<BitIntType>()->getNumBits() >= 8)) ? void
(0) : __assert_fail ("vecType->isBuiltinType() || (vecType->isBitIntType() && llvm::isPowerOf2_32(vecType->getAs<BitIntType>()->getNumBits()) && vecType->getAs<BitIntType>()->getNumBits() >= 8)"
, "clang/lib/AST/ASTContext.cpp", 4080, __extension__ __PRETTY_FUNCTION__
))
7
Assuming the object is not a 'const class clang::BitIntType *'
8
Called C++ object pointer is null
4077 (vecType->isBitIntType() &&(static_cast <bool> (vecType->isBuiltinType() || (vecType
->isBitIntType() && llvm::isPowerOf2_32(vecType->
getAs<BitIntType>()->getNumBits()) && vecType
->getAs<BitIntType>()->getNumBits() >= 8)) ? void
(0) : __assert_fail ("vecType->isBuiltinType() || (vecType->isBitIntType() && llvm::isPowerOf2_32(vecType->getAs<BitIntType>()->getNumBits()) && vecType->getAs<BitIntType>()->getNumBits() >= 8)"
, "clang/lib/AST/ASTContext.cpp", 4080, __extension__ __PRETTY_FUNCTION__
))
4078 // Only support _BitInt elements with byte-sized power of 2 NumBits.(static_cast <bool> (vecType->isBuiltinType() || (vecType
->isBitIntType() && llvm::isPowerOf2_32(vecType->
getAs<BitIntType>()->getNumBits()) && vecType
->getAs<BitIntType>()->getNumBits() >= 8)) ? void
(0) : __assert_fail ("vecType->isBuiltinType() || (vecType->isBitIntType() && llvm::isPowerOf2_32(vecType->getAs<BitIntType>()->getNumBits()) && vecType->getAs<BitIntType>()->getNumBits() >= 8)"
, "clang/lib/AST/ASTContext.cpp", 4080, __extension__ __PRETTY_FUNCTION__
))
4079 llvm::isPowerOf2_32(vecType->getAs<BitIntType>()->getNumBits()) &&(static_cast <bool> (vecType->isBuiltinType() || (vecType
->isBitIntType() && llvm::isPowerOf2_32(vecType->
getAs<BitIntType>()->getNumBits()) && vecType
->getAs<BitIntType>()->getNumBits() >= 8)) ? void
(0) : __assert_fail ("vecType->isBuiltinType() || (vecType->isBitIntType() && llvm::isPowerOf2_32(vecType->getAs<BitIntType>()->getNumBits()) && vecType->getAs<BitIntType>()->getNumBits() >= 8)"
, "clang/lib/AST/ASTContext.cpp", 4080, __extension__ __PRETTY_FUNCTION__
))
4080 vecType->getAs<BitIntType>()->getNumBits() >= 8))(static_cast <bool> (vecType->isBuiltinType() || (vecType
->isBitIntType() && llvm::isPowerOf2_32(vecType->
getAs<BitIntType>()->getNumBits()) && vecType
->getAs<BitIntType>()->getNumBits() >= 8)) ? void
(0) : __assert_fail ("vecType->isBuiltinType() || (vecType->isBitIntType() && llvm::isPowerOf2_32(vecType->getAs<BitIntType>()->getNumBits()) && vecType->getAs<BitIntType>()->getNumBits() >= 8)"
, "clang/lib/AST/ASTContext.cpp", 4080, __extension__ __PRETTY_FUNCTION__
))
;
4081
4082 // Check if we've already instantiated a vector of this type.
4083 llvm::FoldingSetNodeID ID;
4084 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
4085
4086 void *InsertPos = nullptr;
4087 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
4088 return QualType(VTP, 0);
4089
4090 // If the element type isn't canonical, this won't be a canonical type either,
4091 // so fill in the canonical type field.
4092 QualType Canonical;
4093 if (!vecType.isCanonical()) {
4094 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
4095
4096 // Get the new insert position for the node we care about.
4097 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4098 assert(!NewIP && "Shouldn't be in the map!")(static_cast <bool> (!NewIP && "Shouldn't be in the map!"
) ? void (0) : __assert_fail ("!NewIP && \"Shouldn't be in the map!\""
, "clang/lib/AST/ASTContext.cpp", 4098, __extension__ __PRETTY_FUNCTION__
))
; (void)NewIP;
4099 }
4100 auto *New = new (*this, TypeAlignment)
4101 VectorType(vecType, NumElts, Canonical, VecKind);
4102 VectorTypes.InsertNode(New, InsertPos);
4103 Types.push_back(New);
4104 return QualType(New, 0);
4105}
4106
4107QualType
4108ASTContext::getDependentVectorType(QualType VecType, Expr *SizeExpr,
4109 SourceLocation AttrLoc,
4110 VectorType::VectorKind VecKind) const {
4111 llvm::FoldingSetNodeID ID;
4112 DependentVectorType::Profile(ID, *this, getCanonicalType(VecType), SizeExpr,
4113 VecKind);
4114 void *InsertPos = nullptr;
4115 DependentVectorType *Canon =
4116 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4117 DependentVectorType *New;
4118
4119 if (Canon) {
4120 New = new (*this, TypeAlignment) DependentVectorType(
4121 *this, VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind);
4122 } else {
4123 QualType CanonVecTy = getCanonicalType(VecType);
4124 if (CanonVecTy == VecType) {
4125 New = new (*this, TypeAlignment) DependentVectorType(
4126 *this, VecType, QualType(), SizeExpr, AttrLoc, VecKind);
4127
4128 DependentVectorType *CanonCheck =
4129 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4130 assert(!CanonCheck &&(static_cast <bool> (!CanonCheck && "Dependent-sized vector_size canonical type broken"
) ? void (0) : __assert_fail ("!CanonCheck && \"Dependent-sized vector_size canonical type broken\""
, "clang/lib/AST/ASTContext.cpp", 4131, __extension__ __PRETTY_FUNCTION__
))
4131 "Dependent-sized vector_size canonical type broken")(static_cast <bool> (!CanonCheck && "Dependent-sized vector_size canonical type broken"
) ? void (0) : __assert_fail ("!CanonCheck && \"Dependent-sized vector_size canonical type broken\""
, "clang/lib/AST/ASTContext.cpp", 4131, __extension__ __PRETTY_FUNCTION__
))
;
4132 (void)CanonCheck;
4133 DependentVectorTypes.InsertNode(New, InsertPos);
4134 } else {
4135 QualType CanonTy = getDependentVectorType(CanonVecTy, SizeExpr,
4136 SourceLocation(), VecKind);
4137 New = new (*this, TypeAlignment) DependentVectorType(
4138 *this, VecType, CanonTy, SizeExpr, AttrLoc, VecKind);
4139 }
4140 }
4141
4142 Types.push_back(New);
4143 return QualType(New, 0);
4144}
4145
4146/// getExtVectorType - Return the unique reference to an extended vector type of
4147/// the specified element type and size. VectorType must be a built-in type.
4148QualType ASTContext::getExtVectorType(QualType vecType,
4149 unsigned NumElts) const {
4150 assert(vecType->isBuiltinType() || vecType->isDependentType() ||(static_cast <bool> (vecType->isBuiltinType() || vecType
->isDependentType() || (vecType->isBitIntType() &&
llvm::isPowerOf2_32(vecType->getAs<BitIntType>()->
getNumBits()) && vecType->getAs<BitIntType>(
)->getNumBits() >= 8)) ? void (0) : __assert_fail ("vecType->isBuiltinType() || vecType->isDependentType() || (vecType->isBitIntType() && llvm::isPowerOf2_32(vecType->getAs<BitIntType>()->getNumBits()) && vecType->getAs<BitIntType>()->getNumBits() >= 8)"
, "clang/lib/AST/ASTContext.cpp", 4154, __extension__ __PRETTY_FUNCTION__
))
4151 (vecType->isBitIntType() &&(static_cast <bool> (vecType->isBuiltinType() || vecType
->isDependentType() || (vecType->isBitIntType() &&
llvm::isPowerOf2_32(vecType->getAs<BitIntType>()->
getNumBits()) && vecType->getAs<BitIntType>(
)->getNumBits() >= 8)) ? void (0) : __assert_fail ("vecType->isBuiltinType() || vecType->isDependentType() || (vecType->isBitIntType() && llvm::isPowerOf2_32(vecType->getAs<BitIntType>()->getNumBits()) && vecType->getAs<BitIntType>()->getNumBits() >= 8)"
, "clang/lib/AST/ASTContext.cpp", 4154, __extension__ __PRETTY_FUNCTION__
))
4152 // Only support _BitInt elements with byte-sized power of 2 NumBits.(static_cast <bool> (vecType->isBuiltinType() || vecType
->isDependentType() || (vecType->isBitIntType() &&
llvm::isPowerOf2_32(vecType->getAs<BitIntType>()->
getNumBits()) && vecType->getAs<BitIntType>(
)->getNumBits() >= 8)) ? void (0) : __assert_fail ("vecType->isBuiltinType() || vecType->isDependentType() || (vecType->isBitIntType() && llvm::isPowerOf2_32(vecType->getAs<BitIntType>()->getNumBits()) && vecType->getAs<BitIntType>()->getNumBits() >= 8)"
, "clang/lib/AST/ASTContext.cpp", 4154, __extension__ __PRETTY_FUNCTION__
))
4153 llvm::isPowerOf2_32(vecType->getAs<BitIntType>()->getNumBits()) &&(static_cast <bool> (vecType->isBuiltinType() || vecType
->isDependentType() || (vecType->isBitIntType() &&
llvm::isPowerOf2_32(vecType->getAs<BitIntType>()->
getNumBits()) && vecType->getAs<BitIntType>(
)->getNumBits() >= 8)) ? void (0) : __assert_fail ("vecType->isBuiltinType() || vecType->isDependentType() || (vecType->isBitIntType() && llvm::isPowerOf2_32(vecType->getAs<BitIntType>()->getNumBits()) && vecType->getAs<BitIntType>()->getNumBits() >= 8)"
, "clang/lib/AST/ASTContext.cpp", 4154, __extension__ __PRETTY_FUNCTION__
))
4154 vecType->getAs<BitIntType>()->getNumBits() >= 8))(static_cast <bool> (vecType->isBuiltinType() || vecType
->isDependentType() || (vecType->isBitIntType() &&
llvm::isPowerOf2_32(vecType->getAs<BitIntType>()->
getNumBits()) && vecType->getAs<BitIntType>(
)->getNumBits() >= 8)) ? void (0) : __assert_fail ("vecType->isBuiltinType() || vecType->isDependentType() || (vecType->isBitIntType() && llvm::isPowerOf2_32(vecType->getAs<BitIntType>()->getNumBits()) && vecType->getAs<BitIntType>()->getNumBits() >= 8)"
, "clang/lib/AST/ASTContext.cpp", 4154, __extension__ __PRETTY_FUNCTION__
))
;
4155
4156 // Check if we've already instantiated a vector of this type.
4157 llvm::FoldingSetNodeID ID;
4158 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
4159 VectorType::GenericVector);
4160 void *InsertPos = nullptr;
4161 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
4162 return QualType(VTP, 0);
4163
4164 // If the element type isn't canonical, this won't be a canonical type either,
4165 // so fill in the canonical type field.
4166 QualType Canonical;
4167 if (!vecType.isCanonical()) {
4168 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
4169
4170 // Get the new insert position for the node we care about.
4171 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4172 assert(!NewIP && "Shouldn't be in the map!")(static_cast <bool> (!NewIP && "Shouldn't be in the map!"
) ? void (0) : __assert_fail ("!NewIP && \"Shouldn't be in the map!\""
, "clang/lib/AST/ASTContext.cpp", 4172, __extension__ __PRETTY_FUNCTION__
))
; (void)NewIP;
4173 }
4174 auto *New = new (*this, TypeAlignment)
4175 ExtVectorType(vecType, NumElts, Canonical);
4176 VectorTypes.InsertNode(New, InsertPos);
4177 Types.push_back(New);
4178 return QualType(New, 0);
4179}
4180
4181QualType
4182ASTContext::getDependentSizedExtVectorType(QualType vecType,
4183 Expr *SizeExpr,
4184 SourceLocation AttrLoc) const {
4185 llvm::FoldingSetNodeID ID;
4186 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
4187 SizeExpr);
4188
4189 void *InsertPos = nullptr;
4190 DependentSizedExtVectorType *Canon
4191 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4192 DependentSizedExtVectorType *New;
4193 if (Canon) {
4194 // We already have a canonical version of this array type; use it as
4195 // the canonical type for a newly-built type.
4196 New = new (*this, TypeAlignment)
4197 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
4198 SizeExpr, AttrLoc);
4199 } else {
4200 QualType CanonVecTy = getCanonicalType(vecType);
4201 if (CanonVecTy == vecType) {
4202 New = new (*this, TypeAlignment)
4203 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
4204 AttrLoc);
4205
4206 DependentSizedExtVectorType *CanonCheck
4207 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4208 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken")(static_cast <bool> (!CanonCheck && "Dependent-sized ext_vector canonical type broken"
) ? void (0) : __assert_fail ("!CanonCheck && \"Dependent-sized ext_vector canonical type broken\""
, "clang/lib/AST/ASTContext.cpp", 4208, __extension__ __PRETTY_FUNCTION__
))
;
4209 (void)CanonCheck;
4210 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
4211 } else {
4212 QualType CanonExtTy = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
4213 SourceLocation());
4214 New = new (*this, TypeAlignment) DependentSizedExtVectorType(
4215 *this, vecType, CanonExtTy, SizeExpr, AttrLoc);
4216 }
4217 }
4218
4219 Types.push_back(New);
4220 return QualType(New, 0);
4221}
4222
4223QualType ASTContext::getConstantMatrixType(QualType ElementTy, unsigned NumRows,
4224 unsigned NumColumns) const {
4225 llvm::FoldingSetNodeID ID;
4226 ConstantMatrixType::Profile(ID, ElementTy, NumRows, NumColumns,
4227 Type::ConstantMatrix);
4228
4229 assert(MatrixType::isValidElementType(ElementTy) &&(static_cast <bool> (MatrixType::isValidElementType(ElementTy
) && "need a valid element type") ? void (0) : __assert_fail
("MatrixType::isValidElementType(ElementTy) && \"need a valid element type\""
, "clang/lib/AST/ASTContext.cpp", 4230, __extension__ __PRETTY_FUNCTION__
))
4230 "need a valid element type")(static_cast <bool> (MatrixType::isValidElementType(ElementTy
) && "need a valid element type") ? void (0) : __assert_fail
("MatrixType::isValidElementType(ElementTy) && \"need a valid element type\""
, "clang/lib/AST/ASTContext.cpp", 4230, __extension__ __PRETTY_FUNCTION__
))
;
4231 assert(ConstantMatrixType::isDimensionValid(NumRows) &&(static_cast <bool> (ConstantMatrixType::isDimensionValid
(NumRows) && ConstantMatrixType::isDimensionValid(NumColumns
) && "need valid matrix dimensions") ? void (0) : __assert_fail
("ConstantMatrixType::isDimensionValid(NumRows) && ConstantMatrixType::isDimensionValid(NumColumns) && \"need valid matrix dimensions\""
, "clang/lib/AST/ASTContext.cpp", 4233, __extension__ __PRETTY_FUNCTION__
))
4232 ConstantMatrixType::isDimensionValid(NumColumns) &&(static_cast <bool> (ConstantMatrixType::isDimensionValid
(NumRows) && ConstantMatrixType::isDimensionValid(NumColumns
) && "need valid matrix dimensions") ? void (0) : __assert_fail
("ConstantMatrixType::isDimensionValid(NumRows) && ConstantMatrixType::isDimensionValid(NumColumns) && \"need valid matrix dimensions\""
, "clang/lib/AST/ASTContext.cpp", 4233, __extension__ __PRETTY_FUNCTION__
))
4233 "need valid matrix dimensions")(static_cast <bool> (ConstantMatrixType::isDimensionValid
(NumRows) && ConstantMatrixType::isDimensionValid(NumColumns
) && "need valid matrix dimensions") ? void (0) : __assert_fail
("ConstantMatrixType::isDimensionValid(NumRows) && ConstantMatrixType::isDimensionValid(NumColumns) && \"need valid matrix dimensions\""
, "clang/lib/AST/ASTContext.cpp", 4233, __extension__ __PRETTY_FUNCTION__
))
;
4234 void *InsertPos = nullptr;
4235 if (ConstantMatrixType *MTP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos))
4236 return QualType(MTP, 0);
4237
4238 QualType Canonical;
4239 if (!ElementTy.isCanonical()) {
4240 Canonical =
4241 getConstantMatrixType(getCanonicalType(ElementTy), NumRows, NumColumns);
4242
4243 ConstantMatrixType *NewIP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4244 assert(!NewIP && "Matrix type shouldn't already exist in the map")(static_cast <bool> (!NewIP && "Matrix type shouldn't already exist in the map"
) ? void (0) : __assert_fail ("!NewIP && \"Matrix type shouldn't already exist in the map\""
, "clang/lib/AST/ASTContext.cpp", 4244, __extension__ __PRETTY_FUNCTION__
))
;
4245 (void)NewIP;
4246 }
4247
4248 auto *New = new (*this, TypeAlignment)
4249 ConstantMatrixType(ElementTy, NumRows, NumColumns, Canonical);
4250 MatrixTypes.InsertNode(New, InsertPos);
4251 Types.push_back(New);
4252 return QualType(New, 0);
4253}
4254
4255QualType ASTContext::getDependentSizedMatrixType(QualType ElementTy,
4256 Expr *RowExpr,
4257 Expr *ColumnExpr,
4258 SourceLocation AttrLoc) const {
4259 QualType CanonElementTy = getCanonicalType(ElementTy);
4260 llvm::FoldingSetNodeID ID;
4261 DependentSizedMatrixType::Profile(ID, *this, CanonElementTy, RowExpr,
4262 ColumnExpr);
4263
4264 void *InsertPos = nullptr;
4265 DependentSizedMatrixType *Canon =
4266 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4267
4268 if (!Canon) {
4269 Canon = new (*this, TypeAlignment) DependentSizedMatrixType(
4270 *this, CanonElementTy, QualType(), RowExpr, ColumnExpr, AttrLoc);
4271#ifndef NDEBUG
4272 DependentSizedMatrixType *CanonCheck =
4273 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4274 assert(!CanonCheck && "Dependent-sized matrix canonical type broken")(static_cast <bool> (!CanonCheck && "Dependent-sized matrix canonical type broken"
) ? void (0) : __assert_fail ("!CanonCheck && \"Dependent-sized matrix canonical type broken\""
, "clang/lib/AST/ASTContext.cpp", 4274, __extension__ __PRETTY_FUNCTION__
))
;
4275#endif
4276 DependentSizedMatrixTypes.InsertNode(Canon, InsertPos);
4277 Types.push_back(Canon);
4278 }
4279
4280 // Already have a canonical version of the matrix type
4281 //
4282 // If it exactly matches the requested type, use it directly.
4283 if (Canon->getElementType() == ElementTy && Canon->getRowExpr() == RowExpr &&
4284 Canon->getRowExpr() == ColumnExpr)
4285 return QualType(Canon, 0);
4286
4287 // Use Canon as the canonical type for newly-built type.
4288 DependentSizedMatrixType *New = new (*this, TypeAlignment)
4289 DependentSizedMatrixType(*this, ElementTy, QualType(Canon, 0), RowExpr,
4290 ColumnExpr, AttrLoc);
4291 Types.push_back(New);
4292 return QualType(New, 0);
4293}
4294
4295QualType ASTContext::getDependentAddressSpaceType(QualType PointeeType,
4296 Expr *AddrSpaceExpr,
4297 SourceLocation AttrLoc) const {
4298 assert(AddrSpaceExpr->isInstantiationDependent())(static_cast <bool> (AddrSpaceExpr->isInstantiationDependent
()) ? void (0) : __assert_fail ("AddrSpaceExpr->isInstantiationDependent()"
, "clang/lib/AST/ASTContext.cpp", 4298, __extension__ __PRETTY_FUNCTION__
))
;
4299
4300 QualType canonPointeeType = getCanonicalType(PointeeType);
4301
4302 void *insertPos = nullptr;
4303 llvm::FoldingSetNodeID ID;
4304 DependentAddressSpaceType::Profile(ID, *this, canonPointeeType,
4305 AddrSpaceExpr);
4306
4307 DependentAddressSpaceType *canonTy =
4308 DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos);
4309
4310 if (!canonTy) {
4311 canonTy = new (*this, TypeAlignment)
4312 DependentAddressSpaceType(*this, canonPointeeType,
4313 QualType(), AddrSpaceExpr, AttrLoc);
4314 DependentAddressSpaceTypes.InsertNode(canonTy, insertPos);
4315 Types.push_back(canonTy);
4316 }
4317
4318 if (canonPointeeType == PointeeType &&
4319 canonTy->getAddrSpaceExpr() == AddrSpaceExpr)
4320 return QualType(canonTy, 0);
4321
4322 auto *sugaredType
4323 = new (*this, TypeAlignment)
4324 DependentAddressSpaceType(*this, PointeeType, QualType(canonTy, 0),
4325 AddrSpaceExpr, AttrLoc);
4326 Types.push_back(sugaredType);
4327 return QualType(sugaredType, 0);
4328}
4329
4330/// Determine whether \p T is canonical as the result type of a function.
4331static bool isCanonicalResultType(QualType T) {
4332 return T.isCanonical() &&
4333 (T.getObjCLifetime() == Qualifiers::OCL_None ||
4334 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
4335}
4336
4337/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
4338QualType
4339ASTContext::getFunctionNoProtoType(QualType ResultTy,
4340 const FunctionType::ExtInfo &Info) const {
4341 // FIXME: This assertion cannot be enabled (yet) because the ObjC rewriter
4342 // functionality creates a function without a prototype regardless of
4343 // language mode (so it makes them even in C++). Once the rewriter has been
4344 // fixed, this assertion can be enabled again.
4345 //assert(!LangOpts.requiresStrictPrototypes() &&
4346 // "strict prototypes are disabled");
4347
4348 // Unique functions, to guarantee there is only one function of a particular
4349 // structure.
4350 llvm::FoldingSetNodeID ID;
4351 FunctionNoProtoType::Profile(ID, ResultTy, Info);
4352
4353 void *InsertPos = nullptr;
4354 if (FunctionNoProtoType *FT =
4355 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
4356 return QualType(FT, 0);
4357
4358 QualType Canonical;
4359 if (!isCanonicalResultType(ResultTy)) {
4360 Canonical =
4361 getFunctionNoProtoType(getCanonicalFunctionResultType(ResultTy), Info);
4362
4363 // Get the new insert position for the node we care about.
4364 FunctionNoProtoType *NewIP =
4365 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
4366 assert(!NewIP && "Shouldn't be in the map!")(static_cast <bool> (!NewIP && "Shouldn't be in the map!"
) ? void (0) : __assert_fail ("!NewIP && \"Shouldn't be in the map!\""
, "clang/lib/AST/ASTContext.cpp", 4366, __extension__ __PRETTY_FUNCTION__
))
; (void)NewIP;
4367 }
4368
4369 auto *New = new (*this, TypeAlignment)
4370 FunctionNoProtoType(ResultTy, Canonical, Info);
4371 Types.push_back(New);
4372 FunctionNoProtoTypes.InsertNode(New, InsertPos);
4373 return QualType(New, 0);
4374}
4375
4376CanQualType
4377ASTContext::getCanonicalFunctionResultType(QualType ResultType) const {
4378 CanQualType CanResultType = getCanonicalType(ResultType);
4379
4380 // Canonical result types do not have ARC lifetime qualifiers.
4381 if (CanResultType.getQualifiers().hasObjCLifetime()) {
4382 Qualifiers Qs = CanResultType.getQualifiers();
4383 Qs.removeObjCLifetime();
4384 return CanQualType::CreateUnsafe(
4385 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
4386 }
4387
4388 return CanResultType;
4389}
4390
4391static bool isCanonicalExceptionSpecification(
4392 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
4393 if (ESI.Type == EST_None)
4394 return true;
4395 if (!NoexceptInType)
4396 return false;
4397
4398 // C++17 onwards: exception specification is part of the type, as a simple
4399 // boolean "can this function type throw".
4400 if (ESI.Type == EST_BasicNoexcept)
4401 return true;
4402
4403 // A noexcept(expr) specification is (possibly) canonical if expr is
4404 // value-dependent.
4405 if (ESI.Type == EST_DependentNoexcept)
4406 return true;
4407
4408 // A dynamic exception specification is canonical if it only contains pack
4409 // expansions (so we can't tell whether it's non-throwing) and all its
4410 // contained types are canonical.
4411 if (ESI.Type == EST_Dynamic) {
4412 bool AnyPackExpansions = false;
4413 for (QualType ET : ESI.Exceptions) {
4414 if (!ET.isCanonical())
4415 return false;
4416 if (ET->getAs<PackExpansionType>())
4417 AnyPackExpansions = true;
4418 }
4419 return AnyPackExpansions;
4420 }
4421
4422 return false;
4423}
4424
4425QualType ASTContext::getFunctionTypeInternal(
4426 QualType ResultTy, ArrayRef<QualType> ArgArray,
4427 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
4428 size_t NumArgs = ArgArray.size();
4429
4430 // Unique functions, to guarantee there is only one function of a particular
4431 // structure.
4432 llvm::FoldingSetNodeID ID;
4433 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
4434 *this, true);
4435
4436 QualType Canonical;
4437 bool Unique = false;
4438
4439 void *InsertPos = nullptr;
4440 if (FunctionProtoType *FPT =
4441 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
4442 QualType Existing = QualType(FPT, 0);
4443
4444 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
4445 // it so long as our exception specification doesn't contain a dependent
4446 // noexcept expression, or we're just looking for a canonical type.
4447 // Otherwise, we're going to need to create a type
4448 // sugar node to hold the concrete expression.
4449 if (OnlyWantCanonical || !isComputedNoexcept(EPI.ExceptionSpec.Type) ||
4450 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
4451 return Existing;
4452
4453 // We need a new type sugar node for this one, to hold the new noexcept
4454 // expression. We do no canonicalization here, but that's OK since we don't
4455 // expect to see the same noexcept expression much more than once.
4456 Canonical = getCanonicalType(Existing);
4457 Unique = true;
4458 }
4459
4460 bool NoexceptInType = getLangOpts().CPlusPlus17;
4461 bool IsCanonicalExceptionSpec =
4462 isCanonicalExceptionSpecification(EPI.ExceptionSpec, NoexceptInType);
4463
4464 // Determine whether the type being created is already canonical or not.
4465 bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
4466 isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
4467 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
4468 if (!ArgArray[i].isCanonicalAsParam())
4469 isCanonical = false;
4470
4471 if (OnlyWantCanonical)
4472 assert(isCanonical &&(static_cast <bool> (isCanonical && "given non-canonical parameters constructing canonical type"
) ? void (0) : __assert_fail ("isCanonical && \"given non-canonical parameters constructing canonical type\""
, "clang/lib/AST/ASTContext.cpp", 4473, __extension__ __PRETTY_FUNCTION__
))
4473 "given non-canonical parameters constructing canonical type")(static_cast <bool> (isCanonical && "given non-canonical parameters constructing canonical type"
) ? void (0) : __assert_fail ("isCanonical && \"given non-canonical parameters constructing canonical type\""
, "clang/lib/AST/ASTContext.cpp", 4473, __extension__ __PRETTY_FUNCTION__
))
;
4474
4475 // If this type isn't canonical, get the canonical version of it if we don't
4476 // already have it. The exception spec is only partially part of the
4477 // canonical type, and only in C++17 onwards.
4478 if (!isCanonical && Canonical.isNull()) {
4479 SmallVector<QualType, 16> CanonicalArgs;
4480 CanonicalArgs.reserve(NumArgs);
4481 for (unsigned i = 0; i != NumArgs; ++i)
4482 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
4483
4484 llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
4485 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
4486 CanonicalEPI.HasTrailingReturn = false;
4487
4488 if (IsCanonicalExceptionSpec) {
4489 // Exception spec is already OK.
4490 } else if (NoexceptInType) {
4491 switch (EPI.ExceptionSpec.Type) {
4492 case EST_Unparsed: case EST_Unevaluated: case EST_Uninstantiated:
4493 // We don't know yet. It shouldn't matter what we pick here; no-one
4494 // should ever look at this.
4495 [[fallthrough]];
4496 case EST_None: case EST_MSAny: case EST_NoexceptFalse:
4497 CanonicalEPI.ExceptionSpec.Type = EST_None;
4498 break;
4499
4500 // A dynamic exception specification is almost always "not noexcept",
4501 // with the exception that a pack expansion might expand to no types.
4502 case EST_Dynamic: {
4503 bool AnyPacks = false;
4504 for (QualType ET : EPI.ExceptionSpec.Exceptions) {
4505 if (ET->getAs<PackExpansionType>())
4506 AnyPacks = true;
4507 ExceptionTypeStorage.push_back(getCanonicalType(ET));
4508 }
4509 if (!AnyPacks)
4510 CanonicalEPI.ExceptionSpec.Type = EST_None;
4511 else {
4512 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
4513 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
4514 }
4515 break;
4516 }
4517
4518 case EST_DynamicNone:
4519 case EST_BasicNoexcept:
4520 case EST_NoexceptTrue:
4521 case EST_NoThrow:
4522 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
4523 break;
4524
4525 case EST_DependentNoexcept:
4526 llvm_unreachable("dependent noexcept is already canonical")::llvm::llvm_unreachable_internal("dependent noexcept is already canonical"
, "clang/lib/AST/ASTContext.cpp", 4526)
;
4527 }
4528 } else {
4529 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
4530 }
4531
4532 // Adjust the canonical function result type.
4533 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
4534 Canonical =
4535 getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
4536
4537 // Get the new insert position for the node we care about.
4538 FunctionProtoType *NewIP =
4539 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
4540 assert(!NewIP && "Shouldn't be in the map!")(static_cast <bool> (!NewIP && "Shouldn't be in the map!"
) ? void (0) : __assert_fail ("!NewIP && \"Shouldn't be in the map!\""
, "clang/lib/AST/ASTContext.cpp", 4540, __extension__ __PRETTY_FUNCTION__
))
; (void)NewIP;
4541 }
4542
4543 // Compute the needed size to hold this FunctionProtoType and the
4544 // various trailing objects.
4545 auto ESH = FunctionProtoType::getExceptionSpecSize(
4546 EPI.ExceptionSpec.Type, EPI.ExceptionSpec.Exceptions.size());
4547 size_t Size = FunctionProtoType::totalSizeToAlloc<
4548 QualType, SourceLocation, FunctionType::FunctionTypeExtraBitfields,
4549 FunctionType::ExceptionType, Expr *, FunctionDecl *,
4550 FunctionProtoType::ExtParameterInfo, Qualifiers>(
4551 NumArgs, EPI.Variadic, EPI.requiresFunctionProtoTypeExtraBitfields(),
4552 ESH.NumExceptionType, ESH.NumExprPtr, ESH.NumFunctionDeclPtr,
4553 EPI.ExtParameterInfos ? NumArgs : 0,
4554 EPI.TypeQuals.hasNonFastQualifiers() ? 1 : 0);
4555
4556 auto *FTP = (FunctionProtoType *)Allocate(Size, TypeAlignment);
4557 FunctionProtoType::ExtProtoInfo newEPI = EPI;
4558 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
4559 Types.push_back(FTP);
4560 if (!Unique)
4561 FunctionProtoTypes.InsertNode(FTP, InsertPos);
4562 return QualType(FTP, 0);
4563}
4564
4565QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
4566 llvm::FoldingSetNodeID ID;
4567 PipeType::Profile(ID, T, ReadOnly);
4568
4569 void *InsertPos = nullptr;
4570 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
4571 return QualType(PT, 0);
4572
4573 // If the pipe element type isn't canonical, this won't be a canonical type
4574 // either, so fill in the canonical type field.
4575 QualType Canonical;
4576 if (!T.isCanonical()) {
4577 Canonical = getPipeType(getCanonicalType(T), ReadOnly);
4578
4579 // Get the new insert position for the node we care about.
4580 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
4581 assert(!NewIP && "Shouldn't be in the map!")(static_cast <bool> (!NewIP && "Shouldn't be in the map!"
) ? void (0) : __assert_fail ("!NewIP && \"Shouldn't be in the map!\""
, "clang/lib/AST/ASTContext.cpp", 4581, __extension__ __PRETTY_FUNCTION__
))
;
4582 (void)NewIP;
4583 }
4584 auto *New = new (*this, TypeAlignment) PipeType(T, Canonical, ReadOnly);
4585 Types.push_back(New);
4586 PipeTypes.InsertNode(New, InsertPos);
4587 return QualType(New, 0);
4588}
4589
4590QualType ASTContext::adjustStringLiteralBaseType(QualType Ty) const {
4591 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
4592 return LangOpts.OpenCL ? getAddrSpaceQualType(Ty, LangAS::opencl_constant)
4593 : Ty;
4594}
4595
4596QualType ASTContext::getReadPipeType(QualType T) const {
4597 return getPipeType(T, true);
4598}
4599
4600QualType ASTContext::getWritePipeType(QualType T) const {
4601 return getPipeType(T, false);
4602}
4603
4604QualType ASTContext::getBitIntType(bool IsUnsigned, unsigned NumBits) const {
4605 llvm::FoldingSetNodeID ID;
4606 BitIntType::Profile(ID, IsUnsigned, NumBits);
4607
4608 void *InsertPos = nullptr;
4609 if (BitIntType *EIT = BitIntTypes.FindNodeOrInsertPos(ID, InsertPos))
4610 return QualType(EIT, 0);
4611
4612 auto *New = new (*this, TypeAlignment) BitIntType(IsUnsigned, NumBits);
4613 BitIntTypes.InsertNode(New, InsertPos);
4614 Types.push_back(New);
4615 return QualType(New, 0);
4616}
4617
4618QualType ASTContext::getDependentBitIntType(bool IsUnsigned,
4619 Expr *NumBitsExpr) const {
4620 assert(NumBitsExpr->isInstantiationDependent() && "Only good for dependent")(static_cast <bool> (NumBitsExpr->isInstantiationDependent
() && "Only good for dependent") ? void (0) : __assert_fail
("NumBitsExpr->isInstantiationDependent() && \"Only good for dependent\""
, "clang/lib/AST/ASTContext.cpp", 4620, __extension__ __PRETTY_FUNCTION__
))
;
4621 llvm::FoldingSetNodeID ID;
4622 DependentBitIntType::Profile(ID, *this, IsUnsigned, NumBitsExpr);
4623
4624 void *InsertPos = nullptr;
4625 if (DependentBitIntType *Existing =
4626 DependentBitIntTypes.FindNodeOrInsertPos(ID, InsertPos))
4627 return QualType(Existing, 0);
4628
4629 auto *New = new (*this, TypeAlignment)
4630 DependentBitIntType(*this, IsUnsigned, NumBitsExpr);
4631 DependentBitIntTypes.InsertNode(New, InsertPos);
4632
4633 Types.push_back(New);
4634 return QualType(New, 0);
4635}
4636
4637#ifndef NDEBUG
4638static bool NeedsInjectedClassNameType(const RecordDecl *D) {
4639 if (!isa<CXXRecordDecl>(D)) return false;
4640 const auto *RD = cast<CXXRecordDecl>(D);
4641 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
4642 return true;
4643 if (RD->getDescribedClassTemplate() &&
4644 !isa<ClassTemplateSpecializationDecl>(RD))
4645 return true;
4646 return false;
4647}
4648#endif
4649
4650/// getInjectedClassNameType - Return the unique reference to the
4651/// injected class name type for the specified templated declaration.
4652QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
4653 QualType TST) const {
4654 assert(NeedsInjectedClassNameType(Decl))(static_cast <bool> (NeedsInjectedClassNameType(Decl)) ?
void (0) : __assert_fail ("NeedsInjectedClassNameType(Decl)"
, "clang/lib/AST/ASTContext.cpp", 4654, __extension__ __PRETTY_FUNCTION__
))
;
4655 if (Decl->TypeForDecl) {
4656 assert(isa<InjectedClassNameType>(Decl->TypeForDecl))(static_cast <bool> (isa<InjectedClassNameType>(Decl
->TypeForDecl)) ? void (0) : __assert_fail ("isa<InjectedClassNameType>(Decl->TypeForDecl)"
, "clang/lib/AST/ASTContext.cpp", 4656, __extension__ __PRETTY_FUNCTION__
))
;
4657 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
4658 assert(PrevDecl->TypeForDecl && "previous declaration has no type")(static_cast <bool> (PrevDecl->TypeForDecl &&
"previous declaration has no type") ? void (0) : __assert_fail
("PrevDecl->TypeForDecl && \"previous declaration has no type\""
, "clang/lib/AST/ASTContext.cpp", 4658, __extension__ __PRETTY_FUNCTION__
))
;
4659 Decl->TypeForDecl = PrevDecl->TypeForDecl;
4660 assert(isa<InjectedClassNameType>(Decl->TypeForDecl))(static_cast <bool> (isa<InjectedClassNameType>(Decl
->TypeForDecl)) ? void (0) : __assert_fail ("isa<InjectedClassNameType>(Decl->TypeForDecl)"
, "clang/lib/AST/ASTContext.cpp", 4660, __extension__ __PRETTY_FUNCTION__
))
;
4661 } else {
4662 Type *newType =
4663 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
4664 Decl->TypeForDecl = newType;
4665 Types.push_back(newType);
4666 }
4667 return QualType(Decl->TypeForDecl, 0);
4668}
4669
4670/// getTypeDeclType - Return the unique reference to the type for the
4671/// specified type declaration.
4672QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
4673 assert(Decl && "Passed null for Decl param")(static_cast <bool> (Decl && "Passed null for Decl param"
) ? void (0) : __assert_fail ("Decl && \"Passed null for Decl param\""
, "clang/lib/AST/ASTContext.cpp", 4673, __extension__ __PRETTY_FUNCTION__
))
;
4674 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case")(static_cast <bool> (!Decl->TypeForDecl && "TypeForDecl present in slow case"
) ? void (0) : __assert_fail ("!Decl->TypeForDecl && \"TypeForDecl present in slow case\""
, "clang/lib/AST/ASTContext.cpp", 4674, __extension__ __PRETTY_FUNCTION__
))
;
4675
4676 if (const auto *Typedef = dyn_cast<TypedefNameDecl>(Decl))
4677 return getTypedefType(Typedef);
4678
4679 assert(!isa<TemplateTypeParmDecl>(Decl) &&(static_cast <bool> (!isa<TemplateTypeParmDecl>(Decl
) && "Template type parameter types are always available."
) ? void (0) : __assert_fail ("!isa<TemplateTypeParmDecl>(Decl) && \"Template type parameter types are always available.\""
, "clang/lib/AST/ASTContext.cpp", 4680, __extension__ __PRETTY_FUNCTION__
))
4680 "Template type parameter types are always available.")(static_cast <bool> (!isa<TemplateTypeParmDecl>(Decl
) && "Template type parameter types are always available."
) ? void (0) : __assert_fail ("!isa<TemplateTypeParmDecl>(Decl) && \"Template type parameter types are always available.\""
, "clang/lib/AST/ASTContext.cpp", 4680, __extension__ __PRETTY_FUNCTION__
))
;
4681
4682 if (const auto *Record = dyn_cast<RecordDecl>(Decl)) {
4683 assert(Record->isFirstDecl() && "struct/union has previous declaration")(static_cast <bool> (Record->isFirstDecl() &&
"struct/union has previous declaration") ? void (0) : __assert_fail
("Record->isFirstDecl() && \"struct/union has previous declaration\""
, "clang/lib/AST/ASTContext.cpp", 4683, __extension__ __PRETTY_FUNCTION__
))
;
4684 assert(!NeedsInjectedClassNameType(Record))(static_cast <bool> (!NeedsInjectedClassNameType(Record
)) ? void (0) : __assert_fail ("!NeedsInjectedClassNameType(Record)"
, "clang/lib/AST/ASTContext.cpp", 4684, __extension__ __PRETTY_FUNCTION__
))
;
4685 return getRecordType(Record);
4686 } else if (const auto *Enum = dyn_cast<EnumDecl>(Decl)) {
4687 assert(Enum->isFirstDecl() && "enum has previous declaration")(static_cast <bool> (Enum->isFirstDecl() && "enum has previous declaration"
) ? void (0) : __assert_fail ("Enum->isFirstDecl() && \"enum has previous declaration\""
, "clang/lib/AST/ASTContext.cpp", 4687, __extension__ __PRETTY_FUNCTION__
))
;
4688 return getEnumType(Enum);
4689 } else if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
4690 return getUnresolvedUsingType(Using);
4691 } else
4692 llvm_unreachable("TypeDecl without a type?")::llvm::llvm_unreachable_internal("TypeDecl without a type?",
"clang/lib/AST/ASTContext.cpp", 4692)
;
4693
4694 return QualType(Decl->TypeForDecl, 0);
4695}
4696
4697/// getTypedefType - Return the unique reference to the type for the
4698/// specified typedef name decl.
4699QualType ASTContext::getTypedefType(const TypedefNameDecl *Decl,
4700 QualType Underlying) const {
4701 if (!Decl->TypeForDecl) {
4702 if (Underlying.isNull())
4703 Underlying = Decl->getUnderlyingType();
4704 auto *NewType = new (*this, TypeAlignment) TypedefType(
4705 Type::Typedef, Decl, QualType(), getCanonicalType(Underlying));
4706 Decl->TypeForDecl = NewType;
4707 Types.push_back(NewType);
4708 return QualType(NewType, 0);
4709 }
4710 if (Underlying.isNull() || Decl->getUnderlyingType() == Underlying)
4711 return QualType(Decl->TypeForDecl, 0);
4712 assert(hasSameType(Decl->getUnderlyingType(), Underlying))(static_cast <bool> (hasSameType(Decl->getUnderlyingType
(), Underlying)) ? void (0) : __assert_fail ("hasSameType(Decl->getUnderlyingType(), Underlying)"
, "clang/lib/AST/ASTContext.cpp", 4712, __extension__ __PRETTY_FUNCTION__
))
;
4713
4714 llvm::FoldingSetNodeID ID;
4715 TypedefType::Profile(ID, Decl, Underlying);
4716
4717 void *InsertPos = nullptr;
4718 if (TypedefType *T = TypedefTypes.FindNodeOrInsertPos(ID, InsertPos)) {
4719 assert(!T->typeMatchesDecl() &&(static_cast <bool> (!T->typeMatchesDecl() &&
"non-divergent case should be handled with TypeDecl") ? void
(0) : __assert_fail ("!T->typeMatchesDecl() && \"non-divergent case should be handled with TypeDecl\""
, "clang/lib/AST/ASTContext.cpp", 4720, __extension__ __PRETTY_FUNCTION__
))
4720 "non-divergent case should be handled with TypeDecl")(static_cast <bool> (!T->typeMatchesDecl() &&
"non-divergent case should be handled with TypeDecl") ? void
(0) : __assert_fail ("!T->typeMatchesDecl() && \"non-divergent case should be handled with TypeDecl\""
, "clang/lib/AST/ASTContext.cpp", 4720, __extension__ __PRETTY_FUNCTION__
))
;
4721 return QualType(T, 0);
4722 }
4723
4724 void *Mem =
4725 Allocate(TypedefType::totalSizeToAlloc<QualType>(true), TypeAlignment);
4726 auto *NewType = new (Mem) TypedefType(Type::Typedef, Decl, Underlying,
4727 getCanonicalType(Underlying));
4728 TypedefTypes.InsertNode(NewType, InsertPos);
4729 Types.push_back(NewType);
4730 return QualType(NewType, 0);
4731}
4732
4733QualType ASTContext::getUsingType(const UsingShadowDecl *Found,
4734 QualType Underlying) const {
4735 llvm::FoldingSetNodeID ID;
4736 UsingType::Profile(ID, Found, Underlying);
4737
4738 void *InsertPos = nullptr;
4739 if (UsingType *T = UsingTypes.FindNodeOrInsertPos(ID, InsertPos))
4740 return QualType(T, 0);
4741
4742 const Type *TypeForDecl =
4743 cast<TypeDecl>(Found->getTargetDecl())->getTypeForDecl();
4744
4745 assert(!Underlying.hasLocalQualifiers())(static_cast <bool> (!Underlying.hasLocalQualifiers()) ?
void (0) : __assert_fail ("!Underlying.hasLocalQualifiers()"
, "clang/lib/AST/ASTContext.cpp", 4745, __extension__ __PRETTY_FUNCTION__
))
;
4746 QualType Canon = Underlying->getCanonicalTypeInternal();
4747 assert(TypeForDecl->getCanonicalTypeInternal() == Canon)(static_cast <bool> (TypeForDecl->getCanonicalTypeInternal
() == Canon) ? void (0) : __assert_fail ("TypeForDecl->getCanonicalTypeInternal() == Canon"
, "clang/lib/AST/ASTContext.cpp", 4747, __extension__ __PRETTY_FUNCTION__
))
;
4748
4749 if (Underlying.getTypePtr() == TypeForDecl)
4750 Underlying = QualType();
4751 void *Mem =
4752 Allocate(UsingType::totalSizeToAlloc<QualType>(!Underlying.isNull()),
4753 TypeAlignment);
4754 UsingType *NewType = new (Mem) UsingType(Found, Underlying, Canon);
4755 Types.push_back(NewType);
4756 UsingTypes.InsertNode(NewType, InsertPos);
4757 return QualType(NewType, 0);
4758}
4759
4760QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
4761 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
4762
4763 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
4764 if (PrevDecl->TypeForDecl)
4765 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
4766
4767 auto *newType = new (*this, TypeAlignment) RecordType(Decl);
4768 Decl->TypeForDecl = newType;
4769 Types.push_back(newType);
4770 return QualType(newType, 0);
4771}
4772
4773QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
4774 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
4775
4776 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
4777 if (PrevDecl->TypeForDecl)
4778 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
4779
4780 auto *newType = new (*this, TypeAlignment) EnumType(Decl);
4781 Decl->TypeForDecl = newType;
4782 Types.push_back(newType);
4783 return QualType(newType, 0);
4784}
4785
4786QualType ASTContext::getUnresolvedUsingType(
4787 const UnresolvedUsingTypenameDecl *Decl) const {
4788 if (Decl->TypeForDecl)
4789 return QualType(Decl->TypeForDecl, 0);
4790
4791 if (const UnresolvedUsingTypenameDecl *CanonicalDecl =
4792 Decl->getCanonicalDecl())
4793 if (CanonicalDecl->TypeForDecl)
4794 return QualType(Decl->TypeForDecl = CanonicalDecl->TypeForDecl, 0);
4795
4796 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Decl);
4797 Decl->TypeForDecl = newType;
4798 Types.push_back(newType);
4799 return QualType(newType, 0);
4800}
4801
4802QualType ASTContext::getAttributedType(attr::Kind attrKind,
4803 QualType modifiedType,
4804 QualType equivalentType) const {
4805 llvm::FoldingSetNodeID id;
4806 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
4807
4808 void *insertPos = nullptr;
4809 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
4810 if (type) return QualType(type, 0);
4811
4812 QualType canon = getCanonicalType(equivalentType);
4813 type = new (*this, TypeAlignment)
4814 AttributedType(canon, attrKind, modifiedType, equivalentType);
4815
4816 Types.push_back(type);
4817 AttributedTypes.InsertNode(type, insertPos);
4818
4819 return QualType(type, 0);
4820}
4821
4822QualType ASTContext::getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr,
4823 QualType Wrapped) {
4824 llvm::FoldingSetNodeID ID;
4825 BTFTagAttributedType::Profile(ID, Wrapped, BTFAttr);
4826
4827 void *InsertPos = nullptr;
4828 BTFTagAttributedType *Ty =
4829 BTFTagAttributedTypes.FindNodeOrInsertPos(ID, InsertPos);
4830 if (Ty)
4831 return QualType(Ty, 0);
4832
4833 QualType Canon = getCanonicalType(Wrapped);
4834 Ty = new (*this, TypeAlignment) BTFTagAttributedType(Canon, Wrapped, BTFAttr);
4835
4836 Types.push_back(Ty);
4837 BTFTagAttributedTypes.InsertNode(Ty, InsertPos);
4838
4839 return QualType(Ty, 0);
4840}
4841
4842/// Retrieve a substitution-result type.
4843QualType
4844ASTContext::getSubstTemplateTypeParmType(QualType Replacement,
4845 Decl *AssociatedDecl, unsigned Index,
4846 Optional<unsigned> PackIndex) const {
4847 llvm::FoldingSetNodeID ID;
4848 SubstTemplateTypeParmType::Profile(ID, Replacement, AssociatedDecl, Index,
4849 PackIndex);
4850 void *InsertPos = nullptr;
4851 SubstTemplateTypeParmType *SubstParm =
4852 SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4853
4854 if (!SubstParm) {
4855 void *Mem = Allocate(SubstTemplateTypeParmType::totalSizeToAlloc<QualType>(
4856 !Replacement.isCanonical()),
4857 TypeAlignment);
4858 SubstParm = new (Mem) SubstTemplateTypeParmType(Replacement, AssociatedDecl,
4859 Index, PackIndex);
4860 Types.push_back(SubstParm);
4861 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
4862 }
4863
4864 return QualType(SubstParm, 0);
4865}
4866
4867/// Retrieve a
4868QualType
4869ASTContext::getSubstTemplateTypeParmPackType(Decl *AssociatedDecl,
4870 unsigned Index, bool Final,
4871 const TemplateArgument &ArgPack) {
4872#ifndef NDEBUG
4873 for (const auto &P : ArgPack.pack_elements())
4874 assert(P.getKind() == TemplateArgument::Type && "Pack contains a non-type")(static_cast <bool> (P.getKind() == TemplateArgument::Type
&& "Pack contains a non-type") ? void (0) : __assert_fail
("P.getKind() == TemplateArgument::Type && \"Pack contains a non-type\""
, "clang/lib/AST/ASTContext.cpp", 4874, __extension__ __PRETTY_FUNCTION__
))
;
4875#endif
4876
4877 llvm::FoldingSetNodeID ID;
4878 SubstTemplateTypeParmPackType::Profile(ID, AssociatedDecl, Index, Final,
4879 ArgPack);
4880 void *InsertPos = nullptr;
4881 if (SubstTemplateTypeParmPackType *SubstParm =
4882 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
4883 return QualType(SubstParm, 0);
4884
4885 QualType Canon;
4886 {
4887 TemplateArgument CanonArgPack = getCanonicalTemplateArgument(ArgPack);
4888 if (!AssociatedDecl->isCanonicalDecl() ||
4889 !CanonArgPack.structurallyEquals(ArgPack)) {
4890 Canon = getSubstTemplateTypeParmPackType(
4891 AssociatedDecl->getCanonicalDecl(), Index, Final, CanonArgPack);
4892 [[maybe_unused]] const auto *Nothing =
4893 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
4894 assert(!Nothing)(static_cast <bool> (!Nothing) ? void (0) : __assert_fail
("!Nothing", "clang/lib/AST/ASTContext.cpp", 4894, __extension__
__PRETTY_FUNCTION__))
;
4895 }
4896 }
4897
4898 auto *SubstParm = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(
4899 Canon, AssociatedDecl, Index, Final, ArgPack);
4900 Types.push_back(SubstParm);
4901 SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos);
4902 return QualType(SubstParm, 0);
4903}
4904
4905/// Retrieve the template type parameter type for a template
4906/// parameter or parameter pack with the given depth, index, and (optionally)
4907/// name.
4908QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
4909 bool ParameterPack,
4910 TemplateTypeParmDecl *TTPDecl) const {
4911 llvm::FoldingSetNodeID ID;
4912 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
4913 void *InsertPos = nullptr;
4914 TemplateTypeParmType *TypeParm
4915 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4916
4917 if (TypeParm)
4918 return QualType(TypeParm, 0);
4919
4920 if (TTPDecl) {
4921 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
4922 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
4923
4924 TemplateTypeParmType *TypeCheck
4925 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4926 assert(!TypeCheck && "Template type parameter canonical type broken")(static_cast <bool> (!TypeCheck && "Template type parameter canonical type broken"
) ? void (0) : __assert_fail ("!TypeCheck && \"Template type parameter canonical type broken\""
, "clang/lib/AST/ASTContext.cpp", 4926, __extension__ __PRETTY_FUNCTION__
))
;
4927 (void)TypeCheck;
4928 } else
4929 TypeParm = new (*this, TypeAlignment)
4930 TemplateTypeParmType(Depth, Index, ParameterPack);
4931
4932 Types.push_back(TypeParm);
4933 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
4934
4935 return QualType(TypeParm, 0);
4936}
4937
4938TypeSourceInfo *
4939ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
4940 SourceLocation NameLoc,
4941 const TemplateArgumentListInfo &Args,
4942 QualType Underlying) const {
4943 assert(!Name.getAsDependentTemplateName() &&(static_cast <bool> (!Name.getAsDependentTemplateName()
&& "No dependent template names here!") ? void (0) :
__assert_fail ("!Name.getAsDependentTemplateName() && \"No dependent template names here!\""
, "clang/lib/AST/ASTContext.cpp", 4944, __extension__ __PRETTY_FUNCTION__
))
4944 "No dependent template names here!")(static_cast <bool> (!Name.getAsDependentTemplateName()
&& "No dependent template names here!") ? void (0) :
__assert_fail ("!Name.getAsDependentTemplateName() && \"No dependent template names here!\""
, "clang/lib/AST/ASTContext.cpp", 4944, __extension__ __PRETTY_FUNCTION__
))
;
4945 QualType TST =
4946 getTemplateSpecializationType(Name, Args.arguments(), Underlying);
4947
4948 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
4949 TemplateSpecializationTypeLoc TL =
4950 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
4951 TL.setTemplateKeywordLoc(SourceLocation());
4952 TL.setTemplateNameLoc(NameLoc);
4953 TL.setLAngleLoc(Args.getLAngleLoc());
4954 TL.setRAngleLoc(Args.getRAngleLoc());
4955 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
4956 TL.setArgLocInfo(i, Args[i].getLocInfo());
4957 return DI;
4958}
4959
4960QualType
4961ASTContext::getTemplateSpecializationType(TemplateName Template,
4962 ArrayRef<TemplateArgumentLoc> Args,
4963 QualType Underlying) const {
4964 assert(!Template.getAsDependentTemplateName() &&(static_cast <bool> (!Template.getAsDependentTemplateName
() && "No dependent template names here!") ? void (0)
: __assert_fail ("!Template.getAsDependentTemplateName() && \"No dependent template names here!\""
, "clang/lib/AST/ASTContext.cpp", 4965, __extension__ __PRETTY_FUNCTION__
))
4965 "No dependent template names here!")(static_cast <bool> (!Template.getAsDependentTemplateName
() && "No dependent template names here!") ? void (0)
: __assert_fail ("!Template.getAsDependentTemplateName() && \"No dependent template names here!\""
, "clang/lib/AST/ASTContext.cpp", 4965, __extension__ __PRETTY_FUNCTION__
))
;
4966
4967 SmallVector<TemplateArgument, 4> ArgVec;
4968 ArgVec.reserve(Args.size());
4969 for (const TemplateArgumentLoc &Arg : Args)
4970 ArgVec.push_back(Arg.getArgument());
4971
4972 return getTemplateSpecializationType(Template, ArgVec, Underlying);
4973}
4974
4975#ifndef NDEBUG
4976static bool hasAnyPackExpansions(ArrayRef<TemplateArgument> Args) {
4977 for (const TemplateArgument &Arg : Args)
4978 if (Arg.isPackExpansion())
4979 return true;
4980
4981 return true;
4982}
4983#endif
4984
4985QualType
4986ASTContext::getTemplateSpecializationType(TemplateName Template,
4987 ArrayRef<TemplateArgument> Args,
4988 QualType Underlying) const {
4989 assert(!Template.getAsDependentTemplateName() &&(static_cast <bool> (!Template.getAsDependentTemplateName
() && "No dependent template names here!") ? void (0)
: __assert_fail ("!Template.getAsDependentTemplateName() && \"No dependent template names here!\""
, "clang/lib/AST/ASTContext.cpp", 4990, __extension__ __PRETTY_FUNCTION__
))
4990 "No dependent template names here!")(static_cast <bool> (!Template.getAsDependentTemplateName
() && "No dependent template names here!") ? void (0)
: __assert_fail ("!Template.getAsDependentTemplateName() && \"No dependent template names here!\""
, "clang/lib/AST/ASTContext.cpp", 4990, __extension__ __PRETTY_FUNCTION__
))
;
4991 // Look through qualified template names.
4992 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
4993 Template = QTN->getUnderlyingTemplate();
4994
4995 const auto *TD = Template.getAsTemplateDecl();
4996 bool IsTypeAlias = TD && TD->isTypeAlias();
4997 QualType CanonType;
4998 if (!Underlying.isNull())
4999 CanonType = getCanonicalType(Underlying);
5000 else {
5001 // We can get here with an alias template when the specialization contains
5002 // a pack expansion that does not match up with a parameter pack.
5003 assert((!IsTypeAlias || hasAnyPackExpansions(Args)) &&(static_cast <bool> ((!IsTypeAlias || hasAnyPackExpansions
(Args)) && "Caller must compute aliased type") ? void
(0) : __assert_fail ("(!IsTypeAlias || hasAnyPackExpansions(Args)) && \"Caller must compute aliased type\""
, "clang/lib/AST/ASTContext.cpp", 5004, __extension__ __PRETTY_FUNCTION__
))
5004 "Caller must compute aliased type")(static_cast <bool> ((!IsTypeAlias || hasAnyPackExpansions
(Args)) && "Caller must compute aliased type") ? void
(0) : __assert_fail ("(!IsTypeAlias || hasAnyPackExpansions(Args)) && \"Caller must compute aliased type\""
, "clang/lib/AST/ASTContext.cpp", 5004, __extension__ __PRETTY_FUNCTION__
))
;
5005 IsTypeAlias = false;
5006 CanonType = getCanonicalTemplateSpecializationType(Template, Args);
5007 }
5008
5009 // Allocate the (non-canonical) template specialization type, but don't
5010 // try to unique it: these types typically have location information that
5011 // we don't unique and don't want to lose.
5012 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
5013 sizeof(TemplateArgument) * Args.size() +
5014 (IsTypeAlias? sizeof(QualType) : 0),
5015 TypeAlignment);
5016 auto *Spec
5017 = new (Mem) TemplateSpecializationType(Template, Args, CanonType,
5018 IsTypeAlias ? Underlying : QualType());
5019
5020 Types.push_back(Spec);
5021 return QualType(Spec, 0);
5022}
5023
5024QualType ASTContext::getCanonicalTemplateSpecializationType(
5025 TemplateName Template, ArrayRef<TemplateArgument> Args) const {
5026 assert(!Template.getAsDependentTemplateName() &&(static_cast <bool> (!Template.getAsDependentTemplateName
() && "No dependent template names here!") ? void (0)
: __assert_fail ("!Template.getAsDependentTemplateName() && \"No dependent template names here!\""
, "clang/lib/AST/ASTContext.cpp", 5027, __extension__ __PRETTY_FUNCTION__
))
5027 "No dependent template names here!")(static_cast <bool> (!Template.getAsDependentTemplateName
() && "No dependent template names here!") ? void (0)
: __assert_fail ("!Template.getAsDependentTemplateName() && \"No dependent template names here!\""
, "clang/lib/AST/ASTContext.cpp", 5027, __extension__ __PRETTY_FUNCTION__
))
;
5028
5029 // Look through qualified template names.
5030 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
5031 Template = TemplateName(QTN->getUnderlyingTemplate());
5032
5033 // Build the canonical template specialization type.
5034 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
5035 bool AnyNonCanonArgs = false;
5036 auto CanonArgs =
5037 ::getCanonicalTemplateArguments(*this, Args, AnyNonCanonArgs);
5038
5039 // Determine whether this canonical template specialization type already
5040 // exists.
5041 llvm::FoldingSetNodeID ID;
5042 TemplateSpecializationType::Profile(ID, CanonTemplate,
5043 CanonArgs, *this);
5044
5045 void *InsertPos = nullptr;
5046 TemplateSpecializationType *Spec
5047 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
5048
5049 if (!Spec) {
5050 // Allocate a new canonical template specialization type.
5051 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
5052 sizeof(TemplateArgument) * CanonArgs.size()),
5053 TypeAlignment);
5054 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
5055 CanonArgs,
5056 QualType(), QualType());
5057 Types.push_back(Spec);
5058 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
5059 }
5060
5061 assert(Spec->isDependentType() &&(static_cast <bool> (Spec->isDependentType() &&
"Non-dependent template-id type must have a canonical type")
? void (0) : __assert_fail ("Spec->isDependentType() && \"Non-dependent template-id type must have a canonical type\""
, "clang/lib/AST/ASTContext.cpp", 5062, __extension__ __PRETTY_FUNCTION__
))
5062 "Non-dependent template-id type must have a canonical type")(static_cast <bool> (Spec->isDependentType() &&
"Non-dependent template-id type must have a canonical type")
? void (0) : __assert_fail ("Spec->isDependentType() && \"Non-dependent template-id type must have a canonical type\""
, "clang/lib/AST/ASTContext.cpp", 5062, __extension__ __PRETTY_FUNCTION__
))
;
5063 return QualType(Spec, 0);
5064}
5065
5066QualType ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
5067 NestedNameSpecifier *NNS,
5068 QualType NamedType,
5069 TagDecl *OwnedTagDecl) const {
5070 llvm::FoldingSetNodeID ID;
5071 ElaboratedType::Profile(ID, Keyword, NNS, NamedType, OwnedTagDecl);
5072
5073 void *InsertPos = nullptr;
5074 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
5075 if (T)
5076 return QualType(T, 0);
5077
5078 QualType Canon = NamedType;
5079 if (!Canon.isCanonical()) {
5080 Canon = getCanonicalType(NamedType);
5081 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
5082 assert(!CheckT && "Elaborated canonical type broken")(static_cast <bool> (!CheckT && "Elaborated canonical type broken"
) ? void (0) : __assert_fail ("!CheckT && \"Elaborated canonical type broken\""
, "clang/lib/AST/ASTContext.cpp", 5082, __extension__ __PRETTY_FUNCTION__
))
;
5083 (void)CheckT;
5084 }
5085
5086 void *Mem = Allocate(ElaboratedType::totalSizeToAlloc<TagDecl *>(!!OwnedTagDecl),
5087 TypeAlignment);
5088 T = new (Mem) ElaboratedType(Keyword, NNS, NamedType, Canon, OwnedTagDecl);
5089
5090 Types.push_back(T);
5091 ElaboratedTypes.InsertNode(T, InsertPos);
5092 return QualType(T, 0);
5093}
5094
5095QualType
5096ASTContext::getParenType(QualType InnerType) const {
5097 llvm::FoldingSetNodeID ID;
5098 ParenType::Profile(ID, InnerType);
5099
5100 void *InsertPos = nullptr;
5101 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
5102 if (T)
5103 return QualType(T, 0);
5104
5105 QualType Canon = InnerType;
5106 if (!Canon.isCanonical()) {
5107 Canon = getCanonicalType(InnerType);
5108 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
5109 assert(!CheckT && "Paren canonical type broken")(static_cast <bool> (!CheckT && "Paren canonical type broken"
) ? void (0) : __assert_fail ("!CheckT && \"Paren canonical type broken\""
, "clang/lib/AST/ASTContext.cpp", 5109, __extension__ __PRETTY_FUNCTION__
))
;
5110 (void)CheckT;
5111 }
5112
5113 T = new (*this, TypeAlignment) ParenType(InnerType, Canon);
5114 Types.push_back(T);
5115 ParenTypes.InsertNode(T, InsertPos);
5116 return QualType(T, 0);
5117}
5118
5119QualType
5120ASTContext::getMacroQualifiedType(QualType UnderlyingTy,
5121 const IdentifierInfo *MacroII) const {
5122 QualType Canon = UnderlyingTy;
5123 if (!Canon.isCanonical())
5124 Canon = getCanonicalType(UnderlyingTy);
5125
5126 auto *newType = new (*this, TypeAlignment)
5127 MacroQualifiedType(UnderlyingTy, Canon, MacroII);
5128 Types.push_back(newType);
5129 return QualType(newType, 0);
5130}
5131
5132QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
5133 NestedNameSpecifier *NNS,
5134 const IdentifierInfo *Name,
5135 QualType Canon) const {
5136 if (Canon.isNull()) {
5137 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5138 if (CanonNNS != NNS)
5139 Canon = getDependentNameType(Keyword, CanonNNS, Name);
5140 }
5141
5142 llvm::FoldingSetNodeID ID;
5143 DependentNameType::Profile(ID, Keyword, NNS, Name);
5144
5145 void *InsertPos = nullptr;
5146 DependentNameType *T
5147 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
5148 if (T)
5149 return QualType(T, 0);
5150
5151 T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon);
5152 Types.push_back(T);
5153 DependentNameTypes.InsertNode(T, InsertPos);
5154 return QualType(T, 0);
5155}
5156
5157QualType ASTContext::getDependentTemplateSpecializationType(
5158 ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
5159 const IdentifierInfo *Name, ArrayRef<TemplateArgumentLoc> Args) const {
5160 // TODO: avoid this copy
5161 SmallVector<TemplateArgument, 16> ArgCopy;
5162 for (unsigned I = 0, E = Args.size(); I != E; ++I)
5163 ArgCopy.push_back(Args[I].getArgument());
5164 return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy);
5165}
5166
5167QualType
5168ASTContext::getDependentTemplateSpecializationType(
5169 ElaboratedTypeKeyword Keyword,
5170 NestedNameSpecifier *NNS,
5171 const IdentifierInfo *Name,
5172 ArrayRef<TemplateArgument> Args) const {
5173 assert((!NNS || NNS->isDependent()) &&(static_cast <bool> ((!NNS || NNS->isDependent()) &&
"nested-name-specifier must be dependent") ? void (0) : __assert_fail
("(!NNS || NNS->isDependent()) && \"nested-name-specifier must be dependent\""
, "clang/lib/AST/ASTContext.cpp", 5174, __extension__ __PRETTY_FUNCTION__
))
5174 "nested-name-specifier must be dependent")(static_cast <bool> ((!NNS || NNS->isDependent()) &&
"nested-name-specifier must be dependent") ? void (0) : __assert_fail
("(!NNS || NNS->isDependent()) && \"nested-name-specifier must be dependent\""
, "clang/lib/AST/ASTContext.cpp", 5174, __extension__ __PRETTY_FUNCTION__
))
;
5175
5176 llvm::FoldingSetNodeID ID;
5177 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
5178 Name, Args);
5179
5180 void *InsertPos = nullptr;
5181 DependentTemplateSpecializationType *T
5182 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
5183 if (T)
5184 return QualType(T, 0);
5185
5186 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5187
5188 ElaboratedTypeKeyword CanonKeyword = Keyword;
5189 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
5190
5191 bool AnyNonCanonArgs = false;
5192 auto CanonArgs =
5193 ::getCanonicalTemplateArguments(*this, Args, AnyNonCanonArgs);
5194
5195 QualType Canon;
5196 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
5197 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
5198 Name,
5199 CanonArgs);
5200
5201 // Find the insert position again.
5202 [[maybe_unused]] auto *Nothing =
5203 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
5204 assert(!Nothing && "canonical type broken")(static_cast <bool> (!Nothing && "canonical type broken"
) ? void (0) : __assert_fail ("!Nothing && \"canonical type broken\""
, "clang/lib/AST/ASTContext.cpp", 5204, __extension__ __PRETTY_FUNCTION__
))
;
5205 }
5206
5207 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
5208 sizeof(TemplateArgument) * Args.size()),
5209 TypeAlignment);
5210 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
5211 Name, Args, Canon);
5212 Types.push_back(T);
5213 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
5214 return QualType(T, 0);
5215}
5216
5217TemplateArgument ASTContext::getInjectedTemplateArg(NamedDecl *Param) {
5218 TemplateArgument Arg;
5219 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
5220 QualType ArgType = getTypeDeclType(TTP);
5221 if (TTP->isParameterPack())
5222 ArgType = getPackExpansionType(ArgType, std::nullopt);
5223
5224 Arg = TemplateArgument(ArgType);
5225 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5226 QualType T =
5227 NTTP->getType().getNonPackExpansionType().getNonLValueExprType(*this);
5228 // For class NTTPs, ensure we include the 'const' so the type matches that
5229 // of a real template argument.
5230 // FIXME: It would be more faithful to model this as something like an
5231 // lvalue-to-rvalue conversion applied to a const-qualified lvalue.
5232 if (T->isRecordType())
5233 T.addConst();
5234 Expr *E = new (*this) DeclRefExpr(
5235 *this, NTTP, /*RefersToEnclosingVariableOrCapture*/ false, T,
5236 Expr::getValueKindForType(NTTP->getType()), NTTP->getLocation());
5237
5238 if (NTTP->isParameterPack())
5239 E = new (*this)
5240 PackExpansionExpr(DependentTy, E, NTTP->getLocation(), std::nullopt);
5241 Arg = TemplateArgument(E);
5242 } else {
5243 auto *TTP = cast<TemplateTemplateParmDecl>(Param);
5244 if (TTP->isParameterPack())
5245 Arg = TemplateArgument(TemplateName(TTP), Optional<unsigned>());
5246 else
5247 Arg = TemplateArgument(TemplateName(TTP));
5248 }
5249
5250 if (Param->isTemplateParameterPack())
5251 Arg = TemplateArgument::CreatePackCopy(*this, Arg);
5252
5253 return Arg;
5254}
5255
5256void
5257ASTContext::getInjectedTemplateArgs(const TemplateParameterList *Params,
5258 SmallVectorImpl<TemplateArgument> &Args) {
5259 Args.reserve(Args.size() + Params->size());
5260
5261 for (NamedDecl *Param : *Params)
5262 Args.push_back(getInjectedTemplateArg(Param));
5263}
5264
5265QualType ASTContext::getPackExpansionType(QualType Pattern,
5266 Optional<unsigned> NumExpansions,
5267 bool ExpectPackInType) {
5268 assert((!ExpectPackInType || Pattern->containsUnexpandedParameterPack()) &&(static_cast <bool> ((!ExpectPackInType || Pattern->
containsUnexpandedParameterPack()) && "Pack expansions must expand one or more parameter packs"
) ? void (0) : __assert_fail ("(!ExpectPackInType || Pattern->containsUnexpandedParameterPack()) && \"Pack expansions must expand one or more parameter packs\""
, "clang/lib/AST/ASTContext.cpp", 5269, __extension__ __PRETTY_FUNCTION__
))
5269 "Pack expansions must expand one or more parameter packs")(static_cast <bool> ((!ExpectPackInType || Pattern->
containsUnexpandedParameterPack()) && "Pack expansions must expand one or more parameter packs"
) ? void (0) : __assert_fail ("(!ExpectPackInType || Pattern->containsUnexpandedParameterPack()) && \"Pack expansions must expand one or more parameter packs\""
, "clang/lib/AST/ASTContext.cpp", 5269, __extension__ __PRETTY_FUNCTION__
))
;
5270
5271 llvm::FoldingSetNodeID ID;
5272 PackExpansionType::Profile(ID, Pattern, NumExpansions);
5273
5274 void *InsertPos = nullptr;
5275 PackExpansionType *T = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
5276 if (T)
5277 return QualType(T, 0);
5278
5279 QualType Canon;
5280 if (!Pattern.isCanonical()) {
5281 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions,
5282 /*ExpectPackInType=*/false);
5283
5284 // Find the insert position again, in case we inserted an element into
5285 // PackExpansionTypes and invalidated our insert position.
5286 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
5287 }
5288
5289 T = new (*this, TypeAlignment)
5290 PackExpansionType(Pattern, Canon, NumExpansions);
5291 Types.push_back(T);
5292 PackExpansionTypes.InsertNode(T, InsertPos);
5293 return QualType(T, 0);
5294}
5295
5296/// CmpProtocolNames - Comparison predicate for sorting protocols
5297/// alphabetically.
5298static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
5299 ObjCProtocolDecl *const *RHS) {
5300 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
5301}
5302
5303static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) {
5304 if (Protocols.empty()) return true;
5305
5306 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
5307 return false;
5308
5309 for (unsigned i = 1; i != Protocols.size(); ++i)
5310 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
5311 Protocols[i]->getCanonicalDecl() != Protocols[i])
5312 return false;
5313 return true;
5314}
5315
5316static void
5317SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) {
5318 // Sort protocols, keyed by name.
5319 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
5320
5321 // Canonicalize.
5322 for (ObjCProtocolDecl *&P : Protocols)
5323 P = P->getCanonicalDecl();
5324
5325 // Remove duplicates.
5326 auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end());
5327 Protocols.erase(ProtocolsEnd, Protocols.end());
5328}
5329
5330QualType ASTContext::getObjCObjectType(QualType BaseType,
5331 ObjCProtocolDecl * const *Protocols,
5332 unsigned NumProtocols) const {
5333 return getObjCObjectType(BaseType, {},
5334 llvm::makeArrayRef(Protocols, NumProtocols),
5335 /*isKindOf=*/false);
5336}
5337
5338QualType ASTContext::getObjCObjectType(
5339 QualType baseType,
5340 ArrayRef<QualType> typeArgs,
5341 ArrayRef<ObjCProtocolDecl *> protocols,
5342 bool isKindOf) const {
5343 // If the base type is an interface and there aren't any protocols or
5344 // type arguments to add, then the interface type will do just fine.
5345 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
5346 isa<ObjCInterfaceType>(baseType))
5347 return baseType;
5348
5349 // Look in the folding set for an existing type.
5350 llvm::FoldingSetNodeID ID;
5351 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
5352 void *InsertPos = nullptr;
5353 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
5354 return QualType(QT, 0);
5355
5356 // Determine the type arguments to be used for canonicalization,
5357 // which may be explicitly specified here or written on the base
5358 // type.
5359 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
5360 if (effectiveTypeArgs.empty()) {
5361 if (const auto *baseObject = baseType->getAs<ObjCObjectType>())
5362 effectiveTypeArgs = baseObject->getTypeArgs();
5363 }
5364
5365 // Build the canonical type, which has the canonical base type and a
5366 // sorted-and-uniqued list of protocols and the type arguments
5367 // canonicalized.
5368 QualType canonical;
5369 bool typeArgsAreCanonical = llvm::all_of(
5370 effectiveTypeArgs, [&](QualType type) { return type.isCanonical(); });
5371 bool protocolsSorted = areSortedAndUniqued(protocols);
5372 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
5373 // Determine the canonical type arguments.
5374 ArrayRef<QualType> canonTypeArgs;
5375 SmallVector<QualType, 4> canonTypeArgsVec;
5376 if (!typeArgsAreCanonical) {
5377 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
5378 for (auto typeArg : effectiveTypeArgs)
5379 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
5380 canonTypeArgs = canonTypeArgsVec;
5381 } else {
5382 canonTypeArgs = effectiveTypeArgs;
5383 }
5384
5385 ArrayRef<ObjCProtocolDecl *> canonProtocols;
5386 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
5387 if (!protocolsSorted) {
5388 canonProtocolsVec.append(protocols.begin(), protocols.end());
5389 SortAndUniqueProtocols(canonProtocolsVec);
5390 canonProtocols = canonProtocolsVec;
5391 } else {
5392 canonProtocols = protocols;
5393 }
5394
5395 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
5396 canonProtocols, isKindOf);
5397
5398 // Regenerate InsertPos.
5399 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
5400 }
5401
5402 unsigned size = sizeof(ObjCObjectTypeImpl);
5403 size += typeArgs.size() * sizeof(QualType);
5404 size += protocols.size() * sizeof(ObjCProtocolDecl *);
5405 void *mem = Allocate(size, TypeAlignment);
5406 auto *T =
5407 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
5408 isKindOf);
5409
5410 Types.push_back(T);
5411 ObjCObjectTypes.InsertNode(T, InsertPos);
5412 return QualType(T, 0);
5413}
5414
5415/// Apply Objective-C protocol qualifiers to the given type.
5416/// If this is for the canonical type of a type parameter, we can apply
5417/// protocol qualifiers on the ObjCObjectPointerType.
5418QualType
5419ASTContext::applyObjCProtocolQualifiers(QualType type,
5420 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
5421 bool allowOnPointerType) const {
5422 hasError = false;
5423
5424 if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
5425 return getObjCTypeParamType(objT->getDecl(), protocols);
5426 }
5427
5428 // Apply protocol qualifiers to ObjCObjectPointerType.
5429 if (allowOnPointerType) {
5430 if (const auto *objPtr =
5431 dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
5432 const ObjCObjectType *objT = objPtr->getObjectType();
5433 // Merge protocol lists and construct ObjCObjectType.
5434 SmallVector<ObjCProtocolDecl*, 8> protocolsVec;
5435 protocolsVec.append(objT->qual_begin(),
5436 objT->qual_end());
5437 protocolsVec.append(protocols.begin(), protocols.end());
5438 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
5439 type = getObjCObjectType(
5440 objT->getBaseType(),
5441 objT->getTypeArgsAsWritten(),
5442 protocols,
5443 objT->isKindOfTypeAsWritten());
5444 return getObjCObjectPointerType(type);
5445 }
5446 }
5447
5448 // Apply protocol qualifiers to ObjCObjectType.
5449 if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
5450 // FIXME: Check for protocols to which the class type is already
5451 // known to conform.
5452
5453 return getObjCObjectType(objT->getBaseType(),
5454 objT->getTypeArgsAsWritten(),
5455 protocols,
5456 objT->isKindOfTypeAsWritten());
5457 }
5458
5459 // If the canonical type is ObjCObjectType, ...
5460 if (type->isObjCObjectType()) {
5461 // Silently overwrite any existing protocol qualifiers.
5462 // TODO: determine whether that's the right thing to do.
5463
5464 // FIXME: Check for protocols to which the class type is already
5465 // known to conform.
5466 return getObjCObjectType(type, {}, protocols, false);
5467 }
5468
5469 // id<protocol-list>
5470 if (type->isObjCIdType()) {
5471 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
5472 type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols,
5473 objPtr->isKindOfType());
5474 return getObjCObjectPointerType(type);
5475 }
5476
5477 // Class<protocol-list>
5478 if (type->isObjCClassType()) {
5479 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
5480 type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols,
5481 objPtr->isKindOfType());
5482 return getObjCObjectPointerType(type);
5483 }
5484
5485 hasError = true;
5486 return type;
5487}
5488
5489QualType
5490ASTContext::getObjCTypeParamType(const ObjCTypeParamDecl *Decl,
5491 ArrayRef<ObjCProtocolDecl *> protocols) const {
5492 // Look in the folding set for an existing type.
5493 llvm::FoldingSetNodeID ID;
5494 ObjCTypeParamType::Profile(ID, Decl, Decl->getUnderlyingType(), protocols);
5495 void *InsertPos = nullptr;
5496 if (ObjCTypeParamType *TypeParam =
5497 ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
5498 return QualType(TypeParam, 0);
5499
5500 // We canonicalize to the underlying type.
5501 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
5502 if (!protocols.empty()) {
5503 // Apply the protocol qualifers.
5504 bool hasError;
5505 Canonical = getCanonicalType(applyObjCProtocolQualifiers(
5506 Canonical, protocols, hasError, true /*allowOnPointerType*/));
5507 assert(!hasError && "Error when apply protocol qualifier to bound type")(static_cast <bool> (!hasError && "Error when apply protocol qualifier to bound type"
) ? void (0) : __assert_fail ("!hasError && \"Error when apply protocol qualifier to bound type\""
, "clang/lib/AST/ASTContext.cpp", 5507, __extension__ __PRETTY_FUNCTION__
))
;
5508 }
5509
5510 unsigned size = sizeof(ObjCTypeParamType);
5511 size += protocols.size() * sizeof(ObjCProtocolDecl *);
5512 void *mem = Allocate(size, TypeAlignment);
5513 auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols);
5514
5515 Types.push_back(newType);
5516 ObjCTypeParamTypes.InsertNode(newType, InsertPos);
5517 return QualType(newType, 0);
5518}
5519
5520void ASTContext::adjustObjCTypeParamBoundType(const ObjCTypeParamDecl *Orig,
5521 ObjCTypeParamDecl *New) const {
5522 New->setTypeSourceInfo(getTrivialTypeSourceInfo(Orig->getUnderlyingType()));
5523 // Update TypeForDecl after updating TypeSourceInfo.
5524 auto NewTypeParamTy = cast<ObjCTypeParamType>(New->getTypeForDecl());
5525 SmallVector<ObjCProtocolDecl *, 8> protocols;
5526 protocols.append(NewTypeParamTy->qual_begin(), NewTypeParamTy->qual_end());
5527 QualType UpdatedTy = getObjCTypeParamType(New, protocols);
5528 New->setTypeForDecl(UpdatedTy.getTypePtr());
5529}
5530
5531/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
5532/// protocol list adopt all protocols in QT's qualified-id protocol
5533/// list.
5534bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
5535 ObjCInterfaceDecl *IC) {
5536 if (!QT->isObjCQualifiedIdType())
5537 return false;
5538
5539 if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) {
5540 // If both the right and left sides have qualifiers.
5541 for (auto *Proto : OPT->quals()) {
5542 if (!IC->ClassImplementsProtocol(Proto, false))
5543 return false;
5544 }
5545 return true;
5546 }
5547 return false;
5548}
5549
5550/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
5551/// QT's qualified-id protocol list adopt all protocols in IDecl's list
5552/// of protocols.
5553bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
5554 ObjCInterfaceDecl *IDecl) {
5555 if (!QT->isObjCQualifiedIdType())
5556 return false;
5557 const auto *OPT = QT->getAs<ObjCObjectPointerType>();
5558 if (!OPT)
5559 return false;
5560 if (!IDecl->hasDefinition())
5561 return false;
5562 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
5563 CollectInheritedProtocols(IDecl, InheritedProtocols);
5564 if (InheritedProtocols.empty())
5565 return false;
5566 // Check that if every protocol in list of id<plist> conforms to a protocol
5567 // of IDecl's, then bridge casting is ok.
5568 bool Conforms = false;
5569 for (auto *Proto : OPT->quals()) {
5570 Conforms = false;
5571 for (auto *PI : InheritedProtocols) {
5572 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
5573 Conforms = true;
5574 break;
5575 }
5576 }
5577 if (!Conforms)
5578 break;
5579 }
5580 if (Conforms)
5581 return true;
5582
5583 for (auto *PI : InheritedProtocols) {
5584 // If both the right and left sides have qualifiers.
5585 bool Adopts = false;
5586 for (auto *Proto : OPT->quals()) {
5587 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
5588 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
5589 break;
5590 }
5591 if (!Adopts)
5592 return false;
5593 }
5594 return true;
5595}
5596
5597/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
5598/// the given object type.
5599QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
5600 llvm::FoldingSetNodeID ID;
5601 ObjCObjectPointerType::Profile(ID, ObjectT);
5602
5603 void *InsertPos = nullptr;
5604 if (ObjCObjectPointerType *QT =
5605 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
5606 return QualType(QT, 0);
5607
5608 // Find the canonical object type.
5609 QualType Canonical;
5610 if (!ObjectT.isCanonical()) {
5611 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
5612
5613 // Regenerate InsertPos.
5614 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
5615 }
5616
5617 // No match.
5618 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
5619 auto *QType =
5620 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
5621
5622 Types.push_back(QType);
5623 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
5624 return QualType(QType, 0);
5625}
5626
5627/// getObjCInterfaceType - Return the unique reference to the type for the
5628/// specified ObjC interface decl. The list of protocols is optional.
5629QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
5630 ObjCInterfaceDecl *PrevDecl) const {
5631 if (Decl->TypeForDecl)
5632 return QualType(Decl->TypeForDecl, 0);
5633
5634 if (PrevDecl) {
5635 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl")(static_cast <bool> (PrevDecl->TypeForDecl &&
"previous decl has no TypeForDecl") ? void (0) : __assert_fail
("PrevDecl->TypeForDecl && \"previous decl has no TypeForDecl\""
, "clang/lib/AST/ASTContext.cpp", 5635, __extension__ __PRETTY_FUNCTION__
))
;
5636 Decl->TypeForDecl = PrevDecl->TypeForDecl;
5637 return QualType(PrevDecl->TypeForDecl, 0);
5638 }
5639
5640 // Prefer the definition, if there is one.
5641 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
5642 Decl = Def;
5643
5644 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
5645 auto *T = new (Mem) ObjCInterfaceType(Decl);
5646 Decl->TypeForDecl = T;
5647 Types.push_back(T);
5648 return QualType(T, 0);
5649}
5650
5651/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
5652/// TypeOfExprType AST's (since expression's are never shared). For example,
5653/// multiple declarations that refer to "typeof(x)" all contain different
5654/// DeclRefExpr's. This doesn't effect the type checker, since it operates
5655/// on canonical type's (which are always unique).
5656QualType ASTContext::getTypeOfExprType(Expr *tofExpr, TypeOfKind Kind) const {
5657 TypeOfExprType *toe;
5658 if (tofExpr->isTypeDependent()) {
5659 llvm::FoldingSetNodeID ID;
5660 DependentTypeOfExprType::Profile(ID, *this, tofExpr,
5661 Kind == TypeOfKind::Unqualified);
5662
5663 void *InsertPos = nullptr;
5664 DependentTypeOfExprType *Canon =
5665 DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
5666 if (Canon) {
5667 // We already have a "canonical" version of an identical, dependent
5668 // typeof(expr) type. Use that as our canonical type.
5669 toe = new (*this, TypeAlignment)
5670 TypeOfExprType(tofExpr, Kind, QualType((TypeOfExprType *)Canon, 0));
5671 } else {
5672 // Build a new, canonical typeof(expr) type.
5673 Canon = new (*this, TypeAlignment)
5674 DependentTypeOfExprType(*this, tofExpr, Kind);
5675 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
5676 toe = Canon;
5677 }
5678 } else {