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