Bug Summary

File:tools/clang/lib/AST/ASTContext.cpp
Warning:line 8203, column 7
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 -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -mframe-pointer=none -relaxed-aliasing -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-10/lib/clang/10.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-10~svn373517/build-llvm/tools/clang/lib/AST -I /build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST -I /build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include -I /build/llvm-toolchain-snapshot-10~svn373517/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-10~svn373517/build-llvm/include -I /build/llvm-toolchain-snapshot-10~svn373517/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-10/lib/clang/10.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-10~svn373517/build-llvm/tools/clang/lib/AST -fdebug-prefix-map=/build/llvm-toolchain-snapshot-10~svn373517=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -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-2019-10-02-234743-9763-1 -x c++ /build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/AST/ASTContext.cpp

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