Bug Summary

File:clang/lib/AST/ASTContext.cpp
Warning:line 2981, column 12
1st function call argument is an uninitialized value

Annotated Source Code

Press '?' to see keyboard shortcuts

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