Bug Summary

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