Bug Summary

File:clang/lib/AST/ASTContext.cpp
Warning:line 8254, column 31
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

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