clang  10.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"
32 #include "clang/AST/Expr.h"
33 #include "clang/AST/ExprCXX.h"
35 #include "clang/AST/Mangle.h"
39 #include "clang/AST/RecordLayout.h"
41 #include "clang/AST/Stmt.h"
42 #include "clang/AST/TemplateBase.h"
43 #include "clang/AST/TemplateName.h"
44 #include "clang/AST/Type.h"
45 #include "clang/AST/TypeLoc.h"
49 #include "clang/Basic/Builtins.h"
52 #include "clang/Basic/FixedPoint.h"
54 #include "clang/Basic/LLVM.h"
56 #include "clang/Basic/Linkage.h"
61 #include "clang/Basic/Specifiers.h"
63 #include "clang/Basic/TargetInfo.h"
64 #include "clang/Basic/XRayLists.h"
65 #include "llvm/ADT/APInt.h"
66 #include "llvm/ADT/APSInt.h"
67 #include "llvm/ADT/ArrayRef.h"
68 #include "llvm/ADT/DenseMap.h"
69 #include "llvm/ADT/DenseSet.h"
70 #include "llvm/ADT/FoldingSet.h"
71 #include "llvm/ADT/None.h"
72 #include "llvm/ADT/Optional.h"
73 #include "llvm/ADT/PointerUnion.h"
74 #include "llvm/ADT/STLExtras.h"
75 #include "llvm/ADT/SmallPtrSet.h"
76 #include "llvm/ADT/SmallVector.h"
77 #include "llvm/ADT/StringExtras.h"
78 #include "llvm/ADT/StringRef.h"
79 #include "llvm/ADT/Triple.h"
80 #include "llvm/Support/Capacity.h"
81 #include "llvm/Support/Casting.h"
82 #include "llvm/Support/Compiler.h"
83 #include "llvm/Support/ErrorHandling.h"
84 #include "llvm/Support/MathExtras.h"
85 #include "llvm/Support/raw_ostream.h"
86 #include <algorithm>
87 #include <cassert>
88 #include <cstddef>
89 #include <cstdint>
90 #include <cstdlib>
91 #include <map>
92 #include <memory>
93 #include <string>
94 #include <tuple>
95 #include <utility>
96 
97 using namespace clang;
98 
101 };
102 const Expr *ASTContext::traverseIgnored(const Expr *E) const {
103  return traverseIgnored(const_cast<Expr *>(E));
104 }
105 
107  if (!E)
108  return nullptr;
109 
110  switch (Traversal) {
112  return E;
114  return E->IgnoreParenImpCasts();
116  return E->IgnoreUnlessSpelledInSource();
117  }
118  llvm_unreachable("Invalid Traversal type!");
119 }
120 
123  if (const auto *E = N.get<Expr>()) {
125  }
126  return N;
127 }
128 
129 /// \returns location that is relevant when searching for Doc comments related
130 /// to \p D.
132  SourceManager &SourceMgr) {
133  assert(D);
134 
135  // User can not attach documentation to implicit declarations.
136  if (D->isImplicit())
137  return {};
138 
139  // User can not attach documentation to implicit instantiations.
140  if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
141  if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
142  return {};
143  }
144 
145  if (const auto *VD = dyn_cast<VarDecl>(D)) {
146  if (VD->isStaticDataMember() &&
147  VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
148  return {};
149  }
150 
151  if (const auto *CRD = dyn_cast<CXXRecordDecl>(D)) {
152  if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
153  return {};
154  }
155 
156  if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
157  TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
158  if (TSK == TSK_ImplicitInstantiation ||
159  TSK == TSK_Undeclared)
160  return {};
161  }
162 
163  if (const auto *ED = dyn_cast<EnumDecl>(D)) {
164  if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
165  return {};
166  }
167  if (const auto *TD = dyn_cast<TagDecl>(D)) {
168  // When tag declaration (but not definition!) is part of the
169  // decl-specifier-seq of some other declaration, it doesn't get comment
170  if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
171  return {};
172  }
173  // TODO: handle comments for function parameters properly.
174  if (isa<ParmVarDecl>(D))
175  return {};
176 
177  // TODO: we could look up template parameter documentation in the template
178  // documentation.
179  if (isa<TemplateTypeParmDecl>(D) ||
180  isa<NonTypeTemplateParmDecl>(D) ||
181  isa<TemplateTemplateParmDecl>(D))
182  return {};
183 
184  // Find declaration location.
185  // For Objective-C declarations we generally don't expect to have multiple
186  // declarators, thus use declaration starting location as the "declaration
187  // location".
188  // For all other declarations multiple declarators are used quite frequently,
189  // so we use the location of the identifier as the "declaration location".
190  if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
191  isa<ObjCPropertyDecl>(D) ||
192  isa<RedeclarableTemplateDecl>(D) ||
193  isa<ClassTemplateSpecializationDecl>(D) ||
194  // Allow association with Y across {} in `typedef struct X {} Y`.
195  isa<TypedefDecl>(D))
196  return D->getBeginLoc();
197  else {
198  const SourceLocation DeclLoc = D->getLocation();
199  if (DeclLoc.isMacroID()) {
200  if (isa<TypedefDecl>(D)) {
201  // If location of the typedef name is in a macro, it is because being
202  // declared via a macro. Try using declaration's starting location as
203  // the "declaration location".
204  return D->getBeginLoc();
205  } else if (const auto *TD = dyn_cast<TagDecl>(D)) {
206  // If location of the tag decl is inside a macro, but the spelling of
207  // the tag name comes from a macro argument, it looks like a special
208  // macro like NS_ENUM is being used to define the tag decl. In that
209  // case, adjust the source location to the expansion loc so that we can
210  // attach the comment to the tag decl.
211  if (SourceMgr.isMacroArgExpansion(DeclLoc) &&
212  TD->isCompleteDefinition())
213  return SourceMgr.getExpansionLoc(DeclLoc);
214  }
215  }
216  return DeclLoc;
217  }
218 
219  return {};
220 }
221 
223  const Decl *D, const SourceLocation RepresentativeLocForDecl,
224  const std::map<unsigned, RawComment *> &CommentsInTheFile) const {
225  // If the declaration doesn't map directly to a location in a file, we
226  // can't find the comment.
227  if (RepresentativeLocForDecl.isInvalid() ||
228  !RepresentativeLocForDecl.isFileID())
229  return nullptr;
230 
231  // If there are no comments anywhere, we won't find anything.
232  if (CommentsInTheFile.empty())
233  return nullptr;
234 
235  // Decompose the location for the declaration and find the beginning of the
236  // file buffer.
237  const std::pair<FileID, unsigned> DeclLocDecomp =
238  SourceMgr.getDecomposedLoc(RepresentativeLocForDecl);
239 
240  // Slow path.
241  auto OffsetCommentBehindDecl =
242  CommentsInTheFile.lower_bound(DeclLocDecomp.second);
243 
244  // First check whether we have a trailing comment.
245  if (OffsetCommentBehindDecl != CommentsInTheFile.end()) {
246  RawComment *CommentBehindDecl = OffsetCommentBehindDecl->second;
247  if ((CommentBehindDecl->isDocumentation() ||
248  LangOpts.CommentOpts.ParseAllComments) &&
249  CommentBehindDecl->isTrailingComment() &&
250  (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
251  isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
252 
253  // Check that Doxygen trailing comment comes after the declaration, starts
254  // on the same line and in the same file as the declaration.
255  if (SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second) ==
256  Comments.getCommentBeginLine(CommentBehindDecl, DeclLocDecomp.first,
257  OffsetCommentBehindDecl->first)) {
258  return CommentBehindDecl;
259  }
260  }
261  }
262 
263  // The comment just after the declaration was not a trailing comment.
264  // Let's look at the previous comment.
265  if (OffsetCommentBehindDecl == CommentsInTheFile.begin())
266  return nullptr;
267 
268  auto OffsetCommentBeforeDecl = --OffsetCommentBehindDecl;
269  RawComment *CommentBeforeDecl = OffsetCommentBeforeDecl->second;
270 
271  // Check that we actually have a non-member Doxygen comment.
272  if (!(CommentBeforeDecl->isDocumentation() ||
273  LangOpts.CommentOpts.ParseAllComments) ||
274  CommentBeforeDecl->isTrailingComment())
275  return nullptr;
276 
277  // Decompose the end of the comment.
278  const unsigned CommentEndOffset =
279  Comments.getCommentEndOffset(CommentBeforeDecl);
280 
281  // Get the corresponding buffer.
282  bool Invalid = false;
283  const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
284  &Invalid).data();
285  if (Invalid)
286  return nullptr;
287 
288  // Extract text between the comment and declaration.
289  StringRef Text(Buffer + CommentEndOffset,
290  DeclLocDecomp.second - CommentEndOffset);
291 
292  // There should be no other declarations or preprocessor directives between
293  // comment and declaration.
294  if (Text.find_first_of(";{}#@") != StringRef::npos)
295  return nullptr;
296 
297  return CommentBeforeDecl;
298 }
299 
301  const SourceLocation DeclLoc = getDeclLocForCommentSearch(D, SourceMgr);
302 
303  // If the declaration doesn't map directly to a location in a file, we
304  // can't find the comment.
305  if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
306  return nullptr;
307 
308  if (ExternalSource && !CommentsLoaded) {
309  ExternalSource->ReadComments();
310  CommentsLoaded = true;
311  }
312 
313  if (Comments.empty())
314  return nullptr;
315 
316  const FileID File = SourceMgr.getDecomposedLoc(DeclLoc).first;
317  const auto CommentsInThisFile = Comments.getCommentsInFile(File);
318  if (!CommentsInThisFile || CommentsInThisFile->empty())
319  return nullptr;
320 
321  return getRawCommentForDeclNoCacheImpl(D, DeclLoc, *CommentsInThisFile);
322 }
323 
324 /// If we have a 'templated' declaration for a template, adjust 'D' to
325 /// refer to the actual template.
326 /// If we have an implicit instantiation, adjust 'D' to refer to template.
327 static const Decl &adjustDeclToTemplate(const Decl &D) {
328  if (const auto *FD = dyn_cast<FunctionDecl>(&D)) {
329  // Is this function declaration part of a function template?
330  if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
331  return *FTD;
332 
333  // Nothing to do if function is not an implicit instantiation.
334  if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
335  return D;
336 
337  // Function is an implicit instantiation of a function template?
338  if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
339  return *FTD;
340 
341  // Function is instantiated from a member definition of a class template?
342  if (const FunctionDecl *MemberDecl =
344  return *MemberDecl;
345 
346  return D;
347  }
348  if (const auto *VD = dyn_cast<VarDecl>(&D)) {
349  // Static data member is instantiated from a member definition of a class
350  // template?
351  if (VD->isStaticDataMember())
352  if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
353  return *MemberDecl;
354 
355  return D;
356  }
357  if (const auto *CRD = dyn_cast<CXXRecordDecl>(&D)) {
358  // Is this class declaration part of a class template?
359  if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
360  return *CTD;
361 
362  // Class is an implicit instantiation of a class template or partial
363  // specialization?
364  if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
365  if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
366  return D;
367  llvm::PointerUnion<ClassTemplateDecl *,
369  PU = CTSD->getSpecializedTemplateOrPartial();
370  return PU.is<ClassTemplateDecl *>()
371  ? *static_cast<const Decl *>(PU.get<ClassTemplateDecl *>())
372  : *static_cast<const Decl *>(
374  }
375 
376  // Class is instantiated from a member definition of a class template?
377  if (const MemberSpecializationInfo *Info =
378  CRD->getMemberSpecializationInfo())
379  return *Info->getInstantiatedFrom();
380 
381  return D;
382  }
383  if (const auto *ED = dyn_cast<EnumDecl>(&D)) {
384  // Enum is instantiated from a member definition of a class template?
385  if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
386  return *MemberDecl;
387 
388  return D;
389  }
390  // FIXME: Adjust alias templates?
391  return D;
392 }
393 
395  const Decl *D,
396  const Decl **OriginalDecl) const {
397  if (!D) {
398  if (OriginalDecl)
399  OriginalDecl = nullptr;
400  return nullptr;
401  }
402 
403  D = &adjustDeclToTemplate(*D);
404 
405  // Any comment directly attached to D?
406  {
407  auto DeclComment = DeclRawComments.find(D);
408  if (DeclComment != DeclRawComments.end()) {
409  if (OriginalDecl)
410  *OriginalDecl = D;
411  return DeclComment->second;
412  }
413  }
414 
415  // Any comment attached to any redeclaration of D?
416  const Decl *CanonicalD = D->getCanonicalDecl();
417  if (!CanonicalD)
418  return nullptr;
419 
420  {
421  auto RedeclComment = RedeclChainComments.find(CanonicalD);
422  if (RedeclComment != RedeclChainComments.end()) {
423  if (OriginalDecl)
424  *OriginalDecl = RedeclComment->second;
425  auto CommentAtRedecl = DeclRawComments.find(RedeclComment->second);
426  assert(CommentAtRedecl != DeclRawComments.end() &&
427  "This decl is supposed to have comment attached.");
428  return CommentAtRedecl->second;
429  }
430  }
431 
432  // Any redeclarations of D that we haven't checked for comments yet?
433  // We can't use DenseMap::iterator directly since it'd get invalid.
434  auto LastCheckedRedecl = [this, CanonicalD]() -> const Decl * {
435  auto LookupRes = CommentlessRedeclChains.find(CanonicalD);
436  if (LookupRes != CommentlessRedeclChains.end())
437  return LookupRes->second;
438  return nullptr;
439  }();
440 
441  for (const auto Redecl : D->redecls()) {
442  assert(Redecl);
443  // Skip all redeclarations that have been checked previously.
444  if (LastCheckedRedecl) {
445  if (LastCheckedRedecl == Redecl) {
446  LastCheckedRedecl = nullptr;
447  }
448  continue;
449  }
450  const RawComment *RedeclComment = getRawCommentForDeclNoCache(Redecl);
451  if (RedeclComment) {
452  cacheRawCommentForDecl(*Redecl, *RedeclComment);
453  if (OriginalDecl)
454  *OriginalDecl = Redecl;
455  return RedeclComment;
456  }
457  CommentlessRedeclChains[CanonicalD] = Redecl;
458  }
459 
460  if (OriginalDecl)
461  *OriginalDecl = nullptr;
462  return nullptr;
463 }
464 
466  const RawComment &Comment) const {
467  assert(Comment.isDocumentation() || LangOpts.CommentOpts.ParseAllComments);
468  DeclRawComments.try_emplace(&OriginalD, &Comment);
469  const Decl *const CanonicalDecl = OriginalD.getCanonicalDecl();
470  RedeclChainComments.try_emplace(CanonicalDecl, &OriginalD);
471  CommentlessRedeclChains.erase(CanonicalDecl);
472 }
473 
474 static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
476  const DeclContext *DC = ObjCMethod->getDeclContext();
477  if (const auto *IMD = dyn_cast<ObjCImplDecl>(DC)) {
478  const ObjCInterfaceDecl *ID = IMD->getClassInterface();
479  if (!ID)
480  return;
481  // Add redeclared method here.
482  for (const auto *Ext : ID->known_extensions()) {
483  if (ObjCMethodDecl *RedeclaredMethod =
484  Ext->getMethod(ObjCMethod->getSelector(),
485  ObjCMethod->isInstanceMethod()))
486  Redeclared.push_back(RedeclaredMethod);
487  }
488  }
489 }
490 
492  const Preprocessor *PP) {
493  if (Comments.empty() || Decls.empty())
494  return;
495 
496  // See if there are any new comments that are not attached to a decl.
497  // The location doesn't have to be precise - we care only about the file.
498  const FileID File =
499  SourceMgr.getDecomposedLoc((*Decls.begin())->getLocation()).first;
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)) {
530  cacheRawCommentForDecl(*D, *DocComment);
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  for (auto &Arg : OldConverted.front().pack_elements().drop_front(1))
743  NewConverted.push_back(Arg);
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  for (auto &Arg : OldConverted.drop_front(1))
756  NewConverted.push_back(Arg);
757  }
759  C, CSE->getNamedConcept(), NewConverted, nullptr,
760  CSE->isInstantiationDependent(), CSE->containsUnexpandedParameterPack());
761 
762  if (auto *OrigFold = dyn_cast<CXXFoldExpr>(IDC))
763  NewIDC = new (C) CXXFoldExpr(OrigFold->getType(), SourceLocation(), NewIDC,
764  BinaryOperatorKind::BO_LAnd,
765  SourceLocation(), /*RHS=*/nullptr,
766  SourceLocation(), /*NumExpansions=*/None);
767  return NewIDC;
768 }
769 
771 ASTContext::getCanonicalTemplateTemplateParmDecl(
772  TemplateTemplateParmDecl *TTP) const {
773  // Check if we already have a canonical template template parameter.
774  llvm::FoldingSetNodeID ID;
775  CanonicalTemplateTemplateParm::Profile(ID, *this, TTP);
776  void *InsertPos = nullptr;
777  CanonicalTemplateTemplateParm *Canonical
778  = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
779  if (Canonical)
780  return Canonical->getParam();
781 
782  // Build a canonical template parameter list.
784  SmallVector<NamedDecl *, 4> CanonParams;
785  CanonParams.reserve(Params->size());
787  PEnd = Params->end();
788  P != PEnd; ++P) {
789  if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
792  TTP->getDepth(), TTP->getIndex(), nullptr, false,
793  TTP->isParameterPack(), TTP->hasTypeConstraint(),
794  TTP->isExpandedParameterPack() ?
795  llvm::Optional<unsigned>(TTP->getNumExpansionParameters()) : None);
796  if (const auto *TC = TTP->getTypeConstraint()) {
797  QualType ParamAsArgument(NewTTP->getTypeForDecl(), 0);
799  *this, TC->getImmediatelyDeclaredConstraint(),
800  ParamAsArgument);
801  TemplateArgumentListInfo CanonArgsAsWritten;
802  if (auto *Args = TC->getTemplateArgsAsWritten())
803  for (const auto &ArgLoc : Args->arguments())
804  CanonArgsAsWritten.addArgument(
805  TemplateArgumentLoc(ArgLoc.getArgument(),
807  NewTTP->setTypeConstraint(
809  DeclarationNameInfo(TC->getNamedConcept()->getDeclName(),
810  SourceLocation()), /*FoundDecl=*/nullptr,
811  // Actually canonicalizing a TemplateArgumentLoc is difficult so we
812  // simply omit the ArgsAsWritten
813  TC->getNamedConcept(), /*ArgsAsWritten=*/nullptr, NewIDC);
814  }
815  CanonParams.push_back(NewTTP);
816  } else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
817  QualType T = getCanonicalType(NTTP->getType());
820  if (NTTP->isExpandedParameterPack()) {
821  SmallVector<QualType, 2> ExpandedTypes;
822  SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
823  for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
824  ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
825  ExpandedTInfos.push_back(
826  getTrivialTypeSourceInfo(ExpandedTypes.back()));
827  }
828 
830  SourceLocation(),
831  SourceLocation(),
832  NTTP->getDepth(),
833  NTTP->getPosition(), nullptr,
834  T,
835  TInfo,
836  ExpandedTypes,
837  ExpandedTInfos);
838  } else {
840  SourceLocation(),
841  SourceLocation(),
842  NTTP->getDepth(),
843  NTTP->getPosition(), nullptr,
844  T,
845  NTTP->isParameterPack(),
846  TInfo);
847  }
848  if (AutoType *AT = T->getContainedAutoType()) {
849  if (AT->isConstrained()) {
852  *this, NTTP->getPlaceholderTypeConstraint(), T));
853  }
854  }
855  CanonParams.push_back(Param);
856 
857  } else
858  CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
859  cast<TemplateTemplateParmDecl>(*P)));
860  }
861 
862  Expr *CanonRequiresClause = nullptr;
863  if (Expr *RequiresClause = TTP->getTemplateParameters()->getRequiresClause())
864  CanonRequiresClause = RequiresClause;
865 
866  TemplateTemplateParmDecl *CanonTTP
868  SourceLocation(), TTP->getDepth(),
869  TTP->getPosition(),
870  TTP->isParameterPack(),
871  nullptr,
873  SourceLocation(),
874  CanonParams,
875  SourceLocation(),
876  CanonRequiresClause));
877 
878  // Get the new insert position for the node we care about.
879  Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
880  assert(!Canonical && "Shouldn't be in the map!");
881  (void)Canonical;
882 
883  // Create the canonical template template parameter entry.
884  Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
885  CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
886  return CanonTTP;
887 }
888 
889 CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
890  if (!LangOpts.CPlusPlus) return nullptr;
891 
892  switch (T.getCXXABI().getKind()) {
894  case TargetCXXABI::GenericARM: // Same as Itanium at this level
895  case TargetCXXABI::iOS:
896  case TargetCXXABI::iOS64:
902  return CreateItaniumCXXABI(*this);
904  return CreateMicrosoftCXXABI(*this);
905  }
906  llvm_unreachable("Invalid CXXABI type!");
907 }
908 
910  if (!InterpContext) {
911  InterpContext.reset(new interp::Context(*this));
912  }
913  return *InterpContext.get();
914 }
915 
916 static const LangASMap *getAddressSpaceMap(const TargetInfo &T,
917  const LangOptions &LOpts) {
918  if (LOpts.FakeAddressSpaceMap) {
919  // The fake address space map must have a distinct entry for each
920  // language-specific address space.
921  static const unsigned FakeAddrSpaceMap[] = {
922  0, // Default
923  1, // opencl_global
924  3, // opencl_local
925  2, // opencl_constant
926  0, // opencl_private
927  4, // opencl_generic
928  5, // cuda_device
929  6, // cuda_constant
930  7, // cuda_shared
931  8, // ptr32_sptr
932  9, // ptr32_uptr
933  10 // ptr64
934  };
935  return &FakeAddrSpaceMap;
936  } else {
937  return &T.getAddressSpaceMap();
938  }
939 }
940 
942  const LangOptions &LangOpts) {
943  switch (LangOpts.getAddressSpaceMapMangling()) {
945  return TI.useAddressSpaceMapMangling();
947  return true;
949  return false;
950  }
951  llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
952 }
953 
955  IdentifierTable &idents, SelectorTable &sels,
956  Builtin::Context &builtins)
957  : ConstantArrayTypes(this_()), FunctionProtoTypes(this_()),
958  TemplateSpecializationTypes(this_()),
959  DependentTemplateSpecializationTypes(this_()), AutoTypes(this_()),
960  SubstTemplateTemplateParmPacks(this_()),
961  CanonTemplateTemplateParms(this_()), SourceMgr(SM), LangOpts(LOpts),
962  SanitizerBL(new SanitizerBlacklist(LangOpts.SanitizerBlacklistFiles, SM)),
963  XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles,
964  LangOpts.XRayNeverInstrumentFiles,
965  LangOpts.XRayAttrListFiles, SM)),
966  PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
967  BuiltinInfo(builtins), DeclarationNames(*this), Comments(SM),
968  CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
969  CompCategories(this_()), LastSDM(nullptr, 0) {
970  TUDecl = TranslationUnitDecl::Create(*this);
971  TraversalScope = {TUDecl};
972 }
973 
975  // Release the DenseMaps associated with DeclContext objects.
976  // FIXME: Is this the ideal solution?
977  ReleaseDeclContextMaps();
978 
979  // Call all of the deallocation functions on all of their targets.
980  for (auto &Pair : Deallocations)
981  (Pair.first)(Pair.second);
982 
983  // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
984  // because they can contain DenseMaps.
985  for (llvm::DenseMap<const ObjCContainerDecl*,
986  const ASTRecordLayout*>::iterator
987  I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
988  // Increment in loop to prevent using deallocated memory.
989  if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
990  R->Destroy(*this);
991 
992  for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
993  I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
994  // Increment in loop to prevent using deallocated memory.
995  if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
996  R->Destroy(*this);
997  }
998 
999  for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
1000  AEnd = DeclAttrs.end();
1001  A != AEnd; ++A)
1002  A->second->~AttrVec();
1003 
1004  for (const auto &Value : ModuleInitializers)
1005  Value.second->~PerModuleInitializers();
1006 
1007  for (APValue *Value : APValueCleanups)
1008  Value->~APValue();
1009 }
1010 
1012  /// Contains parents of a node.
1014 
1015  /// Maps from a node to its parents. This is used for nodes that have
1016  /// pointer identity only, which are more common and we can save space by
1017  /// only storing a unique pointer to them.
1018  using ParentMapPointers = llvm::DenseMap<
1019  const void *,
1020  llvm::PointerUnion<const Decl *, const Stmt *,
1022 
1023  /// Parent map for nodes without pointer identity. We store a full
1024  /// DynTypedNode for all keys.
1025  using ParentMapOtherNodes = llvm::DenseMap<
1027  llvm::PointerUnion<const Decl *, const Stmt *,
1028  ast_type_traits::DynTypedNode *, ParentVector *>>;
1029 
1030  ParentMapPointers PointerParents;
1031  ParentMapOtherNodes OtherParents;
1032  class ASTVisitor;
1033 
1034  static ast_type_traits::DynTypedNode
1035  getSingleDynTypedNodeFromParentMap(ParentMapPointers::mapped_type U) {
1036  if (const auto *D = U.dyn_cast<const Decl *>())
1038  if (const auto *S = U.dyn_cast<const Stmt *>())
1040  return *U.get<ast_type_traits::DynTypedNode *>();
1041  }
1042 
1043  template <typename NodeTy, typename MapTy>
1044  static ASTContext::DynTypedNodeList getDynNodeFromMap(const NodeTy &Node,
1045  const MapTy &Map) {
1046  auto I = Map.find(Node);
1047  if (I == Map.end()) {
1049  }
1050  if (const auto *V = I->second.template dyn_cast<ParentVector *>()) {
1051  return llvm::makeArrayRef(*V);
1052  }
1053  return getSingleDynTypedNodeFromParentMap(I->second);
1054  }
1055 
1056 public:
1057  ParentMap(ASTContext &Ctx);
1059  for (const auto &Entry : PointerParents) {
1060  if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
1061  delete Entry.second.get<ast_type_traits::DynTypedNode *>();
1062  } else if (Entry.second.is<ParentVector *>()) {
1063  delete Entry.second.get<ParentVector *>();
1064  }
1065  }
1066  for (const auto &Entry : OtherParents) {
1067  if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
1068  delete Entry.second.get<ast_type_traits::DynTypedNode *>();
1069  } else if (Entry.second.is<ParentVector *>()) {
1070  delete Entry.second.get<ParentVector *>();
1071  }
1072  }
1073  }
1074 
1075  DynTypedNodeList getParents(const ast_type_traits::DynTypedNode &Node) {
1076  if (Node.getNodeKind().hasPointerIdentity())
1077  return getDynNodeFromMap(Node.getMemoizationData(), PointerParents);
1078  return getDynNodeFromMap(Node, OtherParents);
1079  }
1080 };
1081 
1082 void ASTContext::setTraversalScope(const std::vector<Decl *> &TopLevelDecls) {
1083  TraversalScope = TopLevelDecls;
1084  Parents.clear();
1085 }
1086 
1087 void ASTContext::AddDeallocation(void (*Callback)(void *), void *Data) const {
1088  Deallocations.push_back({Callback, Data});
1089 }
1090 
1091 void
1093  ExternalSource = std::move(Source);
1094 }
1095 
1097  llvm::errs() << "\n*** AST Context Stats:\n";
1098  llvm::errs() << " " << Types.size() << " types total.\n";
1099 
1100  unsigned counts[] = {
1101 #define TYPE(Name, Parent) 0,
1102 #define ABSTRACT_TYPE(Name, Parent)
1103 #include "clang/AST/TypeNodes.inc"
1104  0 // Extra
1105  };
1106 
1107  for (unsigned i = 0, e = Types.size(); i != e; ++i) {
1108  Type *T = Types[i];
1109  counts[(unsigned)T->getTypeClass()]++;
1110  }
1111 
1112  unsigned Idx = 0;
1113  unsigned TotalBytes = 0;
1114 #define TYPE(Name, Parent) \
1115  if (counts[Idx]) \
1116  llvm::errs() << " " << counts[Idx] << " " << #Name \
1117  << " types, " << sizeof(Name##Type) << " each " \
1118  << "(" << counts[Idx] * sizeof(Name##Type) \
1119  << " bytes)\n"; \
1120  TotalBytes += counts[Idx] * sizeof(Name##Type); \
1121  ++Idx;
1122 #define ABSTRACT_TYPE(Name, Parent)
1123 #include "clang/AST/TypeNodes.inc"
1124 
1125  llvm::errs() << "Total bytes = " << TotalBytes << "\n";
1126 
1127  // Implicit special member functions.
1128  llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
1130  << " implicit default constructors created\n";
1131  llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
1133  << " implicit copy constructors created\n";
1134  if (getLangOpts().CPlusPlus)
1135  llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
1137  << " implicit move constructors created\n";
1138  llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
1140  << " implicit copy assignment operators created\n";
1141  if (getLangOpts().CPlusPlus)
1142  llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
1144  << " implicit move assignment operators created\n";
1145  llvm::errs() << NumImplicitDestructorsDeclared << "/"
1147  << " implicit destructors created\n";
1148 
1149  if (ExternalSource) {
1150  llvm::errs() << "\n";
1151  ExternalSource->PrintStats();
1152  }
1153 
1154  BumpAlloc.PrintStats();
1155 }
1156 
1158  bool NotifyListeners) {
1159  if (NotifyListeners)
1160  if (auto *Listener = getASTMutationListener())
1162 
1163  MergedDefModules[cast<NamedDecl>(ND->getCanonicalDecl())].push_back(M);
1164 }
1165 
1167  auto It = MergedDefModules.find(cast<NamedDecl>(ND->getCanonicalDecl()));
1168  if (It == MergedDefModules.end())
1169  return;
1170 
1171  auto &Merged = It->second;
1173  for (Module *&M : Merged)
1174  if (!Found.insert(M).second)
1175  M = nullptr;
1176  Merged.erase(std::remove(Merged.begin(), Merged.end(), nullptr), Merged.end());
1177 }
1178 
1179 void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
1180  if (LazyInitializers.empty())
1181  return;
1182 
1183  auto *Source = Ctx.getExternalSource();
1184  assert(Source && "lazy initializers but no external source");
1185 
1186  auto LazyInits = std::move(LazyInitializers);
1187  LazyInitializers.clear();
1188 
1189  for (auto ID : LazyInits)
1190  Initializers.push_back(Source->GetExternalDecl(ID));
1191 
1192  assert(LazyInitializers.empty() &&
1193  "GetExternalDecl for lazy module initializer added more inits");
1194 }
1195 
1197  // One special case: if we add a module initializer that imports another
1198  // module, and that module's only initializer is an ImportDecl, simplify.
1199  if (const auto *ID = dyn_cast<ImportDecl>(D)) {
1200  auto It = ModuleInitializers.find(ID->getImportedModule());
1201 
1202  // Maybe the ImportDecl does nothing at all. (Common case.)
1203  if (It == ModuleInitializers.end())
1204  return;
1205 
1206  // Maybe the ImportDecl only imports another ImportDecl.
1207  auto &Imported = *It->second;
1208  if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
1209  Imported.resolve(*this);
1210  auto *OnlyDecl = Imported.Initializers.front();
1211  if (isa<ImportDecl>(OnlyDecl))
1212  D = OnlyDecl;
1213  }
1214  }
1215 
1216  auto *&Inits = ModuleInitializers[M];
1217  if (!Inits)
1218  Inits = new (*this) PerModuleInitializers;
1219  Inits->Initializers.push_back(D);
1220 }
1221 
1223  auto *&Inits = ModuleInitializers[M];
1224  if (!Inits)
1225  Inits = new (*this) PerModuleInitializers;
1226  Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
1227  IDs.begin(), IDs.end());
1228 }
1229 
1231  auto It = ModuleInitializers.find(M);
1232  if (It == ModuleInitializers.end())
1233  return None;
1234 
1235  auto *Inits = It->second;
1236  Inits->resolve(*this);
1237  return Inits->Initializers;
1238 }
1239 
1241  if (!ExternCContext)
1242  ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
1243 
1244  return ExternCContext;
1245 }
1246 
1249  const IdentifierInfo *II) const {
1250  auto *BuiltinTemplate = BuiltinTemplateDecl::Create(*this, TUDecl, II, BTK);
1251  BuiltinTemplate->setImplicit();
1252  TUDecl->addDecl(BuiltinTemplate);
1253 
1254  return BuiltinTemplate;
1255 }
1256 
1259  if (!MakeIntegerSeqDecl)
1260  MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq,
1262  return MakeIntegerSeqDecl;
1263 }
1264 
1267  if (!TypePackElementDecl)
1268  TypePackElementDecl = buildBuiltinTemplateDecl(BTK__type_pack_element,
1270  return TypePackElementDecl;
1271 }
1272 
1274  RecordDecl::TagKind TK) const {
1275  SourceLocation Loc;
1276  RecordDecl *NewDecl;
1277  if (getLangOpts().CPlusPlus)
1278  NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
1279  Loc, &Idents.get(Name));
1280  else
1281  NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
1282  &Idents.get(Name));
1283  NewDecl->setImplicit();
1284  NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
1285  const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
1286  return NewDecl;
1287 }
1288 
1290  StringRef Name) const {
1292  TypedefDecl *NewDecl = TypedefDecl::Create(
1293  const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
1294  SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
1295  NewDecl->setImplicit();
1296  return NewDecl;
1297 }
1298 
1300  if (!Int128Decl)
1301  Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
1302  return Int128Decl;
1303 }
1304 
1306  if (!UInt128Decl)
1307  UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
1308  return UInt128Decl;
1309 }
1310 
1311 void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
1312  auto *Ty = new (*this, TypeAlignment) BuiltinType(K);
1313  R = CanQualType::CreateUnsafe(QualType(Ty, 0));
1314  Types.push_back(Ty);
1315 }
1316 
1318  const TargetInfo *AuxTarget) {
1319  assert((!this->Target || this->Target == &Target) &&
1320  "Incorrect target reinitialization");
1321  assert(VoidTy.isNull() && "Context reinitialized?");
1322 
1323  this->Target = &Target;
1324  this->AuxTarget = AuxTarget;
1325 
1326  ABI.reset(createCXXABI(Target));
1327  AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
1328  AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
1329 
1330  // C99 6.2.5p19.
1331  InitBuiltinType(VoidTy, BuiltinType::Void);
1332 
1333  // C99 6.2.5p2.
1334  InitBuiltinType(BoolTy, BuiltinType::Bool);
1335  // C99 6.2.5p3.
1336  if (LangOpts.CharIsSigned)
1337  InitBuiltinType(CharTy, BuiltinType::Char_S);
1338  else
1339  InitBuiltinType(CharTy, BuiltinType::Char_U);
1340  // C99 6.2.5p4.
1341  InitBuiltinType(SignedCharTy, BuiltinType::SChar);
1342  InitBuiltinType(ShortTy, BuiltinType::Short);
1343  InitBuiltinType(IntTy, BuiltinType::Int);
1344  InitBuiltinType(LongTy, BuiltinType::Long);
1345  InitBuiltinType(LongLongTy, BuiltinType::LongLong);
1346 
1347  // C99 6.2.5p6.
1348  InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
1349  InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
1350  InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
1351  InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
1352  InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
1353 
1354  // C99 6.2.5p10.
1355  InitBuiltinType(FloatTy, BuiltinType::Float);
1356  InitBuiltinType(DoubleTy, BuiltinType::Double);
1357  InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
1358 
1359  // GNU extension, __float128 for IEEE quadruple precision
1360  InitBuiltinType(Float128Ty, BuiltinType::Float128);
1361 
1362  // C11 extension ISO/IEC TS 18661-3
1363  InitBuiltinType(Float16Ty, BuiltinType::Float16);
1364 
1365  // ISO/IEC JTC1 SC22 WG14 N1169 Extension
1366  InitBuiltinType(ShortAccumTy, BuiltinType::ShortAccum);
1367  InitBuiltinType(AccumTy, BuiltinType::Accum);
1368  InitBuiltinType(LongAccumTy, BuiltinType::LongAccum);
1369  InitBuiltinType(UnsignedShortAccumTy, BuiltinType::UShortAccum);
1370  InitBuiltinType(UnsignedAccumTy, BuiltinType::UAccum);
1371  InitBuiltinType(UnsignedLongAccumTy, BuiltinType::ULongAccum);
1372  InitBuiltinType(ShortFractTy, BuiltinType::ShortFract);
1373  InitBuiltinType(FractTy, BuiltinType::Fract);
1374  InitBuiltinType(LongFractTy, BuiltinType::LongFract);
1375  InitBuiltinType(UnsignedShortFractTy, BuiltinType::UShortFract);
1376  InitBuiltinType(UnsignedFractTy, BuiltinType::UFract);
1377  InitBuiltinType(UnsignedLongFractTy, BuiltinType::ULongFract);
1378  InitBuiltinType(SatShortAccumTy, BuiltinType::SatShortAccum);
1379  InitBuiltinType(SatAccumTy, BuiltinType::SatAccum);
1380  InitBuiltinType(SatLongAccumTy, BuiltinType::SatLongAccum);
1381  InitBuiltinType(SatUnsignedShortAccumTy, BuiltinType::SatUShortAccum);
1382  InitBuiltinType(SatUnsignedAccumTy, BuiltinType::SatUAccum);
1383  InitBuiltinType(SatUnsignedLongAccumTy, BuiltinType::SatULongAccum);
1384  InitBuiltinType(SatShortFractTy, BuiltinType::SatShortFract);
1385  InitBuiltinType(SatFractTy, BuiltinType::SatFract);
1386  InitBuiltinType(SatLongFractTy, BuiltinType::SatLongFract);
1387  InitBuiltinType(SatUnsignedShortFractTy, BuiltinType::SatUShortFract);
1388  InitBuiltinType(SatUnsignedFractTy, BuiltinType::SatUFract);
1389  InitBuiltinType(SatUnsignedLongFractTy, BuiltinType::SatULongFract);
1390 
1391  // GNU extension, 128-bit integers.
1392  InitBuiltinType(Int128Ty, BuiltinType::Int128);
1393  InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
1394 
1395  // C++ 3.9.1p5
1396  if (TargetInfo::isTypeSigned(Target.getWCharType()))
1397  InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1398  else // -fshort-wchar makes wchar_t be unsigned.
1399  InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1400  if (LangOpts.CPlusPlus && LangOpts.WChar)
1401  WideCharTy = WCharTy;
1402  else {
1403  // C99 (or C++ using -fno-wchar).
1404  WideCharTy = getFromTargetType(Target.getWCharType());
1405  }
1406 
1407  WIntTy = getFromTargetType(Target.getWIntType());
1408 
1409  // C++20 (proposed)
1410  InitBuiltinType(Char8Ty, BuiltinType::Char8);
1411 
1412  if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1413  InitBuiltinType(Char16Ty, BuiltinType::Char16);
1414  else // C99
1415  Char16Ty = getFromTargetType(Target.getChar16Type());
1416 
1417  if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1418  InitBuiltinType(Char32Ty, BuiltinType::Char32);
1419  else // C99
1420  Char32Ty = getFromTargetType(Target.getChar32Type());
1421 
1422  // Placeholder type for type-dependent expressions whose type is
1423  // completely unknown. No code should ever check a type against
1424  // DependentTy and users should never see it; however, it is here to
1425  // help diagnose failures to properly check for type-dependent
1426  // expressions.
1427  InitBuiltinType(DependentTy, BuiltinType::Dependent);
1428 
1429  // Placeholder type for functions.
1430  InitBuiltinType(OverloadTy, BuiltinType::Overload);
1431 
1432  // Placeholder type for bound members.
1433  InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1434 
1435  // Placeholder type for pseudo-objects.
1436  InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1437 
1438  // "any" type; useful for debugger-like clients.
1439  InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1440 
1441  // Placeholder type for unbridged ARC casts.
1442  InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1443 
1444  // Placeholder type for builtin functions.
1445  InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1446 
1447  // Placeholder type for OMP array sections.
1448  if (LangOpts.OpenMP)
1449  InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection);
1450 
1451  // C99 6.2.5p11.
1456 
1457  // Builtin types for 'id', 'Class', and 'SEL'.
1458  InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1459  InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
1460  InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
1461 
1462  if (LangOpts.OpenCL) {
1463 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1464  InitBuiltinType(SingletonId, BuiltinType::Id);
1465 #include "clang/Basic/OpenCLImageTypes.def"
1466 
1467  InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
1468  InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
1469  InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1470  InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
1471  InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
1472 
1473 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1474  InitBuiltinType(Id##Ty, BuiltinType::Id);
1475 #include "clang/Basic/OpenCLExtensionTypes.def"
1476  }
1477 
1478  if (Target.hasAArch64SVETypes()) {
1479 #define SVE_TYPE(Name, Id, SingletonId) \
1480  InitBuiltinType(SingletonId, BuiltinType::Id);
1481 #include "clang/Basic/AArch64SVEACLETypes.def"
1482  }
1483 
1484  // Builtin type for __objc_yes and __objc_no
1485  ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1486  SignedCharTy : BoolTy);
1487 
1488  ObjCConstantStringType = QualType();
1489 
1490  ObjCSuperType = QualType();
1491 
1492  // void * type
1493  if (LangOpts.OpenCLVersion >= 200) {
1494  auto Q = VoidTy.getQualifiers();
1498  } else {
1500  }
1501 
1502  // nullptr type (C++0x 2.14.7)
1503  InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
1504 
1505  // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1506  InitBuiltinType(HalfTy, BuiltinType::Half);
1507 
1508  // Builtin type used to help define __builtin_va_list.
1509  VaListTagDecl = nullptr;
1510 }
1511 
1513  return SourceMgr.getDiagnostics();
1514 }
1515 
1517  AttrVec *&Result = DeclAttrs[D];
1518  if (!Result) {
1519  void *Mem = Allocate(sizeof(AttrVec));
1520  Result = new (Mem) AttrVec;
1521  }
1522 
1523  return *Result;
1524 }
1525 
1526 /// Erase the attributes corresponding to the given declaration.
1528  llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1529  if (Pos != DeclAttrs.end()) {
1530  Pos->second->~AttrVec();
1531  DeclAttrs.erase(Pos);
1532  }
1533 }
1534 
1535 // FIXME: Remove ?
1538  assert(Var->isStaticDataMember() && "Not a static data member");
1540  .dyn_cast<MemberSpecializationInfo *>();
1541 }
1542 
1545  llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1546  TemplateOrInstantiation.find(Var);
1547  if (Pos == TemplateOrInstantiation.end())
1548  return {};
1549 
1550  return Pos->second;
1551 }
1552 
1553 void
1556  SourceLocation PointOfInstantiation) {
1557  assert(Inst->isStaticDataMember() && "Not a static data member");
1558  assert(Tmpl->isStaticDataMember() && "Not a static data member");
1560  Tmpl, TSK, PointOfInstantiation));
1561 }
1562 
1563 void
1566  assert(!TemplateOrInstantiation[Inst] &&
1567  "Already noted what the variable was instantiated from");
1568  TemplateOrInstantiation[Inst] = TSI;
1569 }
1570 
1571 NamedDecl *
1573  auto Pos = InstantiatedFromUsingDecl.find(UUD);
1574  if (Pos == InstantiatedFromUsingDecl.end())
1575  return nullptr;
1576 
1577  return Pos->second;
1578 }
1579 
1580 void
1582  assert((isa<UsingDecl>(Pattern) ||
1583  isa<UnresolvedUsingValueDecl>(Pattern) ||
1584  isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1585  "pattern decl is not a using decl");
1586  assert((isa<UsingDecl>(Inst) ||
1587  isa<UnresolvedUsingValueDecl>(Inst) ||
1588  isa<UnresolvedUsingTypenameDecl>(Inst)) &&
1589  "instantiation did not produce a using decl");
1590  assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1591  InstantiatedFromUsingDecl[Inst] = Pattern;
1592 }
1593 
1596  llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1597  = InstantiatedFromUsingShadowDecl.find(Inst);
1598  if (Pos == InstantiatedFromUsingShadowDecl.end())
1599  return nullptr;
1600 
1601  return Pos->second;
1602 }
1603 
1604 void
1606  UsingShadowDecl *Pattern) {
1607  assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1608  InstantiatedFromUsingShadowDecl[Inst] = Pattern;
1609 }
1610 
1612  llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1613  = InstantiatedFromUnnamedFieldDecl.find(Field);
1614  if (Pos == InstantiatedFromUnnamedFieldDecl.end())
1615  return nullptr;
1616 
1617  return Pos->second;
1618 }
1619 
1621  FieldDecl *Tmpl) {
1622  assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1623  assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1624  assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1625  "Already noted what unnamed field was instantiated from");
1626 
1627  InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1628 }
1629 
1632  return overridden_methods(Method).begin();
1633 }
1634 
1637  return overridden_methods(Method).end();
1638 }
1639 
1640 unsigned
1642  auto Range = overridden_methods(Method);
1643  return Range.end() - Range.begin();
1644 }
1645 
1648  llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1649  OverriddenMethods.find(Method->getCanonicalDecl());
1650  if (Pos == OverriddenMethods.end())
1651  return overridden_method_range(nullptr, nullptr);
1652  return overridden_method_range(Pos->second.begin(), Pos->second.end());
1653 }
1654 
1656  const CXXMethodDecl *Overridden) {
1657  assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
1658  OverriddenMethods[Method].push_back(Overridden);
1659 }
1660 
1662  const NamedDecl *D,
1663  SmallVectorImpl<const NamedDecl *> &Overridden) const {
1664  assert(D);
1665 
1666  if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
1667  Overridden.append(overridden_methods_begin(CXXMethod),
1668  overridden_methods_end(CXXMethod));
1669  return;
1670  }
1671 
1672  const auto *Method = dyn_cast<ObjCMethodDecl>(D);
1673  if (!Method)
1674  return;
1675 
1677  Method->getOverriddenMethods(OverDecls);
1678  Overridden.append(OverDecls.begin(), OverDecls.end());
1679 }
1680 
1682  assert(!Import->NextLocalImport && "Import declaration already in the chain");
1683  assert(!Import->isFromASTFile() && "Non-local import declaration");
1684  if (!FirstLocalImport) {
1685  FirstLocalImport = Import;
1686  LastLocalImport = Import;
1687  return;
1688  }
1689 
1690  LastLocalImport->NextLocalImport = Import;
1691  LastLocalImport = Import;
1692 }
1693 
1694 //===----------------------------------------------------------------------===//
1695 // Type Sizing and Analysis
1696 //===----------------------------------------------------------------------===//
1697 
1698 /// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1699 /// scalar floating point type.
1700 const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
1701  switch (T->castAs<BuiltinType>()->getKind()) {
1702  default:
1703  llvm_unreachable("Not a floating point type!");
1704  case BuiltinType::Float16:
1705  case BuiltinType::Half:
1706  return Target->getHalfFormat();
1707  case BuiltinType::Float: return Target->getFloatFormat();
1708  case BuiltinType::Double: return Target->getDoubleFormat();
1709  case BuiltinType::LongDouble:
1710  if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice)
1711  return AuxTarget->getLongDoubleFormat();
1712  return Target->getLongDoubleFormat();
1713  case BuiltinType::Float128:
1714  if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice)
1715  return AuxTarget->getFloat128Format();
1716  return Target->getFloat128Format();
1717  }
1718 }
1719 
1720 CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
1721  unsigned Align = Target->getCharWidth();
1722 
1723  bool UseAlignAttrOnly = false;
1724  if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1725  Align = AlignFromAttr;
1726 
1727  // __attribute__((aligned)) can increase or decrease alignment
1728  // *except* on a struct or struct member, where it only increases
1729  // alignment unless 'packed' is also specified.
1730  //
1731  // It is an error for alignas to decrease alignment, so we can
1732  // ignore that possibility; Sema should diagnose it.
1733  if (isa<FieldDecl>(D)) {
1734  UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1735  cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1736  } else {
1737  UseAlignAttrOnly = true;
1738  }
1739  }
1740  else if (isa<FieldDecl>(D))
1741  UseAlignAttrOnly =
1742  D->hasAttr<PackedAttr>() ||
1743  cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1744 
1745  // If we're using the align attribute only, just ignore everything
1746  // else about the declaration and its type.
1747  if (UseAlignAttrOnly) {
1748  // do nothing
1749  } else if (const auto *VD = dyn_cast<ValueDecl>(D)) {
1750  QualType T = VD->getType();
1751  if (const auto *RT = T->getAs<ReferenceType>()) {
1752  if (ForAlignof)
1753  T = RT->getPointeeType();
1754  else
1755  T = getPointerType(RT->getPointeeType());
1756  }
1757  QualType BaseT = getBaseElementType(T);
1758  if (T->isFunctionType())
1759  Align = getTypeInfoImpl(T.getTypePtr()).Align;
1760  else if (!BaseT->isIncompleteType()) {
1761  // Adjust alignments of declarations with array type by the
1762  // large-array alignment on the target.
1763  if (const ArrayType *arrayType = getAsArrayType(T)) {
1764  unsigned MinWidth = Target->getLargeArrayMinWidth();
1765  if (!ForAlignof && MinWidth) {
1766  if (isa<VariableArrayType>(arrayType))
1767  Align = std::max(Align, Target->getLargeArrayAlign());
1768  else if (isa<ConstantArrayType>(arrayType) &&
1769  MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1770  Align = std::max(Align, Target->getLargeArrayAlign());
1771  }
1772  }
1773  Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
1774  if (BaseT.getQualifiers().hasUnaligned())
1775  Align = Target->getCharWidth();
1776  if (const auto *VD = dyn_cast<VarDecl>(D)) {
1777  if (VD->hasGlobalStorage() && !ForAlignof) {
1778  uint64_t TypeSize = getTypeSize(T.getTypePtr());
1779  Align = std::max(Align, getTargetInfo().getMinGlobalAlign(TypeSize));
1780  }
1781  }
1782  }
1783 
1784  // Fields can be subject to extra alignment constraints, like if
1785  // the field is packed, the struct is packed, or the struct has a
1786  // a max-field-alignment constraint (#pragma pack). So calculate
1787  // the actual alignment of the field within the struct, and then
1788  // (as we're expected to) constrain that by the alignment of the type.
1789  if (const auto *Field = dyn_cast<FieldDecl>(VD)) {
1790  const RecordDecl *Parent = Field->getParent();
1791  // We can only produce a sensible answer if the record is valid.
1792  if (!Parent->isInvalidDecl()) {
1793  const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
1794 
1795  // Start with the record's overall alignment.
1796  unsigned FieldAlign = toBits(Layout.getAlignment());
1797 
1798  // Use the GCD of that and the offset within the record.
1799  uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1800  if (Offset > 0) {
1801  // Alignment is always a power of 2, so the GCD will be a power of 2,
1802  // which means we get to do this crazy thing instead of Euclid's.
1803  uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1804  if (LowBitOfOffset < FieldAlign)
1805  FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1806  }
1807 
1808  Align = std::min(Align, FieldAlign);
1809  }
1810  }
1811  }
1812 
1813  return toCharUnitsFromBits(Align);
1814 }
1815 
1816 // getTypeInfoDataSizeInChars - Return the size of a type, in
1817 // chars. If the type is a record, its data size is returned. This is
1818 // the size of the memcpy that's performed when assigning this type
1819 // using a trivial copy/move assignment operator.
1820 std::pair<CharUnits, CharUnits>
1822  std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1823 
1824  // In C++, objects can sometimes be allocated into the tail padding
1825  // of a base-class subobject. We decide whether that's possible
1826  // during class layout, so here we can just trust the layout results.
1827  if (getLangOpts().CPlusPlus) {
1828  if (const auto *RT = T->getAs<RecordType>()) {
1829  const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1830  sizeAndAlign.first = layout.getDataSize();
1831  }
1832  }
1833 
1834  return sizeAndAlign;
1835 }
1836 
1837 /// getConstantArrayInfoInChars - Performing the computation in CharUnits
1838 /// instead of in bits prevents overflowing the uint64_t for some large arrays.
1839 std::pair<CharUnits, CharUnits>
1841  const ConstantArrayType *CAT) {
1842  std::pair<CharUnits, CharUnits> EltInfo =
1843  Context.getTypeInfoInChars(CAT->getElementType());
1844  uint64_t Size = CAT->getSize().getZExtValue();
1845  assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1846  (uint64_t)(-1)/Size) &&
1847  "Overflow in array type char size evaluation");
1848  uint64_t Width = EltInfo.first.getQuantity() * Size;
1849  unsigned Align = EltInfo.second.getQuantity();
1850  if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1851  Context.getTargetInfo().getPointerWidth(0) == 64)
1852  Width = llvm::alignTo(Width, Align);
1853  return std::make_pair(CharUnits::fromQuantity(Width),
1854  CharUnits::fromQuantity(Align));
1855 }
1856 
1857 std::pair<CharUnits, CharUnits>
1859  if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
1860  return getConstantArrayInfoInChars(*this, CAT);
1861  TypeInfo Info = getTypeInfo(T);
1862  return std::make_pair(toCharUnitsFromBits(Info.Width),
1863  toCharUnitsFromBits(Info.Align));
1864 }
1865 
1866 std::pair<CharUnits, CharUnits>
1868  return getTypeInfoInChars(T.getTypePtr());
1869 }
1870 
1872  return getTypeInfo(T).AlignIsRequired;
1873 }
1874 
1876  return isAlignmentRequired(T.getTypePtr());
1877 }
1878 
1880  // An alignment on a typedef overrides anything else.
1881  if (const auto *TT = T->getAs<TypedefType>())
1882  if (unsigned Align = TT->getDecl()->getMaxAlignment())
1883  return Align;
1884 
1885  // If we have an (array of) complete type, we're done.
1886  T = getBaseElementType(T);
1887  if (!T->isIncompleteType())
1888  return getTypeAlign(T);
1889 
1890  // If we had an array type, its element type might be a typedef
1891  // type with an alignment attribute.
1892  if (const auto *TT = T->getAs<TypedefType>())
1893  if (unsigned Align = TT->getDecl()->getMaxAlignment())
1894  return Align;
1895 
1896  // Otherwise, see if the declaration of the type had an attribute.
1897  if (const auto *TT = T->getAs<TagType>())
1898  return TT->getDecl()->getMaxAlignment();
1899 
1900  return 0;
1901 }
1902 
1904  TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1905  if (I != MemoizedTypeInfo.end())
1906  return I->second;
1907 
1908  // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1909  TypeInfo TI = getTypeInfoImpl(T);
1910  MemoizedTypeInfo[T] = TI;
1911  return TI;
1912 }
1913 
1914 /// getTypeInfoImpl - Return the size of the specified type, in bits. This
1915 /// method does not work on incomplete types.
1916 ///
1917 /// FIXME: Pointers into different addr spaces could have different sizes and
1918 /// alignment requirements: getPointerInfo should take an AddrSpace, this
1919 /// should take a QualType, &c.
1920 TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1921  uint64_t Width = 0;
1922  unsigned Align = 8;
1923  bool AlignIsRequired = false;
1924  unsigned AS = 0;
1925  switch (T->getTypeClass()) {
1926 #define TYPE(Class, Base)
1927 #define ABSTRACT_TYPE(Class, Base)
1928 #define NON_CANONICAL_TYPE(Class, Base)
1929 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
1930 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1931  case Type::Class: \
1932  assert(!T->isDependentType() && "should not see dependent types here"); \
1933  return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
1934 #include "clang/AST/TypeNodes.inc"
1935  llvm_unreachable("Should not see dependent types");
1936 
1937  case Type::FunctionNoProto:
1938  case Type::FunctionProto:
1939  // GCC extension: alignof(function) = 32 bits
1940  Width = 0;
1941  Align = 32;
1942  break;
1943 
1944  case Type::IncompleteArray:
1945  case Type::VariableArray:
1946  Width = 0;
1947  Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1948  break;
1949 
1950  case Type::ConstantArray: {
1951  const auto *CAT = cast<ConstantArrayType>(T);
1952 
1953  TypeInfo EltInfo = getTypeInfo(CAT->getElementType());
1954  uint64_t Size = CAT->getSize().getZExtValue();
1955  assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
1956  "Overflow in array type bit size evaluation");
1957  Width = EltInfo.Width * Size;
1958  Align = EltInfo.Align;
1959  if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1960  getTargetInfo().getPointerWidth(0) == 64)
1961  Width = llvm::alignTo(Width, Align);
1962  break;
1963  }
1964  case Type::ExtVector:
1965  case Type::Vector: {
1966  const auto *VT = cast<VectorType>(T);
1967  TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1968  Width = EltInfo.Width * VT->getNumElements();
1969  Align = Width;
1970  // If the alignment is not a power of 2, round up to the next power of 2.
1971  // This happens for non-power-of-2 length vectors.
1972  if (Align & (Align-1)) {
1973  Align = llvm::NextPowerOf2(Align);
1974  Width = llvm::alignTo(Width, Align);
1975  }
1976  // Adjust the alignment based on the target max.
1977  uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1978  if (TargetVectorAlign && TargetVectorAlign < Align)
1979  Align = TargetVectorAlign;
1980  break;
1981  }
1982 
1983  case Type::Builtin:
1984  switch (cast<BuiltinType>(T)->getKind()) {
1985  default: llvm_unreachable("Unknown builtin type!");
1986  case BuiltinType::Void:
1987  // GCC extension: alignof(void) = 8 bits.
1988  Width = 0;
1989  Align = 8;
1990  break;
1991  case BuiltinType::Bool:
1992  Width = Target->getBoolWidth();
1993  Align = Target->getBoolAlign();
1994  break;
1995  case BuiltinType::Char_S:
1996  case BuiltinType::Char_U:
1997  case BuiltinType::UChar:
1998  case BuiltinType::SChar:
1999  case BuiltinType::Char8:
2000  Width = Target->getCharWidth();
2001  Align = Target->getCharAlign();
2002  break;
2003  case BuiltinType::WChar_S:
2004  case BuiltinType::WChar_U:
2005  Width = Target->getWCharWidth();
2006  Align = Target->getWCharAlign();
2007  break;
2008  case BuiltinType::Char16:
2009  Width = Target->getChar16Width();
2010  Align = Target->getChar16Align();
2011  break;
2012  case BuiltinType::Char32:
2013  Width = Target->getChar32Width();
2014  Align = Target->getChar32Align();
2015  break;
2016  case BuiltinType::UShort:
2017  case BuiltinType::Short:
2018  Width = Target->getShortWidth();
2019  Align = Target->getShortAlign();
2020  break;
2021  case BuiltinType::UInt:
2022  case BuiltinType::Int:
2023  Width = Target->getIntWidth();
2024  Align = Target->getIntAlign();
2025  break;
2026  case BuiltinType::ULong:
2027  case BuiltinType::Long:
2028  Width = Target->getLongWidth();
2029  Align = Target->getLongAlign();
2030  break;
2031  case BuiltinType::ULongLong:
2032  case BuiltinType::LongLong:
2033  Width = Target->getLongLongWidth();
2034  Align = Target->getLongLongAlign();
2035  break;
2036  case BuiltinType::Int128:
2037  case BuiltinType::UInt128:
2038  Width = 128;
2039  Align = 128; // int128_t is 128-bit aligned on all targets.
2040  break;
2041  case BuiltinType::ShortAccum:
2042  case BuiltinType::UShortAccum:
2043  case BuiltinType::SatShortAccum:
2044  case BuiltinType::SatUShortAccum:
2045  Width = Target->getShortAccumWidth();
2046  Align = Target->getShortAccumAlign();
2047  break;
2048  case BuiltinType::Accum:
2049  case BuiltinType::UAccum:
2050  case BuiltinType::SatAccum:
2051  case BuiltinType::SatUAccum:
2052  Width = Target->getAccumWidth();
2053  Align = Target->getAccumAlign();
2054  break;
2055  case BuiltinType::LongAccum:
2056  case BuiltinType::ULongAccum:
2057  case BuiltinType::SatLongAccum:
2058  case BuiltinType::SatULongAccum:
2059  Width = Target->getLongAccumWidth();
2060  Align = Target->getLongAccumAlign();
2061  break;
2062  case BuiltinType::ShortFract:
2063  case BuiltinType::UShortFract:
2064  case BuiltinType::SatShortFract:
2065  case BuiltinType::SatUShortFract:
2066  Width = Target->getShortFractWidth();
2067  Align = Target->getShortFractAlign();
2068  break;
2069  case BuiltinType::Fract:
2070  case BuiltinType::UFract:
2071  case BuiltinType::SatFract:
2072  case BuiltinType::SatUFract:
2073  Width = Target->getFractWidth();
2074  Align = Target->getFractAlign();
2075  break;
2076  case BuiltinType::LongFract:
2077  case BuiltinType::ULongFract:
2078  case BuiltinType::SatLongFract:
2079  case BuiltinType::SatULongFract:
2080  Width = Target->getLongFractWidth();
2081  Align = Target->getLongFractAlign();
2082  break;
2083  case BuiltinType::Float16:
2084  case BuiltinType::Half:
2085  if (Target->hasFloat16Type() || !getLangOpts().OpenMP ||
2086  !getLangOpts().OpenMPIsDevice) {
2087  Width = Target->getHalfWidth();
2088  Align = Target->getHalfAlign();
2089  } else {
2090  assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
2091  "Expected OpenMP device compilation.");
2092  Width = AuxTarget->getHalfWidth();
2093  Align = AuxTarget->getHalfAlign();
2094  }
2095  break;
2096  case BuiltinType::Float:
2097  Width = Target->getFloatWidth();
2098  Align = Target->getFloatAlign();
2099  break;
2100  case BuiltinType::Double:
2101  Width = Target->getDoubleWidth();
2102  Align = Target->getDoubleAlign();
2103  break;
2104  case BuiltinType::LongDouble:
2105  if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
2106  (Target->getLongDoubleWidth() != AuxTarget->getLongDoubleWidth() ||
2107  Target->getLongDoubleAlign() != AuxTarget->getLongDoubleAlign())) {
2108  Width = AuxTarget->getLongDoubleWidth();
2109  Align = AuxTarget->getLongDoubleAlign();
2110  } else {
2111  Width = Target->getLongDoubleWidth();
2112  Align = Target->getLongDoubleAlign();
2113  }
2114  break;
2115  case BuiltinType::Float128:
2116  if (Target->hasFloat128Type() || !getLangOpts().OpenMP ||
2117  !getLangOpts().OpenMPIsDevice) {
2118  Width = Target->getFloat128Width();
2119  Align = Target->getFloat128Align();
2120  } else {
2121  assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
2122  "Expected OpenMP device compilation.");
2123  Width = AuxTarget->getFloat128Width();
2124  Align = AuxTarget->getFloat128Align();
2125  }
2126  break;
2127  case BuiltinType::NullPtr:
2128  Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
2129  Align = Target->getPointerAlign(0); // == sizeof(void*)
2130  break;
2131  case BuiltinType::ObjCId:
2132  case BuiltinType::ObjCClass:
2133  case BuiltinType::ObjCSel:
2134  Width = Target->getPointerWidth(0);
2135  Align = Target->getPointerAlign(0);
2136  break;
2137  case BuiltinType::OCLSampler:
2138  case BuiltinType::OCLEvent:
2139  case BuiltinType::OCLClkEvent:
2140  case BuiltinType::OCLQueue:
2141  case BuiltinType::OCLReserveID:
2142 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2143  case BuiltinType::Id:
2144 #include "clang/Basic/OpenCLImageTypes.def"
2145 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2146  case BuiltinType::Id:
2147 #include "clang/Basic/OpenCLExtensionTypes.def"
2148  AS = getTargetAddressSpace(
2149  Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T)));
2150  Width = Target->getPointerWidth(AS);
2151  Align = Target->getPointerAlign(AS);
2152  break;
2153  // The SVE types are effectively target-specific. The length of an
2154  // SVE_VECTOR_TYPE is only known at runtime, but it is always a multiple
2155  // of 128 bits. There is one predicate bit for each vector byte, so the
2156  // length of an SVE_PREDICATE_TYPE is always a multiple of 16 bits.
2157  //
2158  // Because the length is only known at runtime, we use a dummy value
2159  // of 0 for the static length. The alignment values are those defined
2160  // by the Procedure Call Standard for the Arm Architecture.
2161 #define SVE_VECTOR_TYPE(Name, Id, SingletonId, ElKind, ElBits, IsSigned, IsFP)\
2162  case BuiltinType::Id: \
2163  Width = 0; \
2164  Align = 128; \
2165  break;
2166 #define SVE_PREDICATE_TYPE(Name, Id, SingletonId, ElKind) \
2167  case BuiltinType::Id: \
2168  Width = 0; \
2169  Align = 16; \
2170  break;
2171 #include "clang/Basic/AArch64SVEACLETypes.def"
2172  }
2173  break;
2174  case Type::ObjCObjectPointer:
2175  Width = Target->getPointerWidth(0);
2176  Align = Target->getPointerAlign(0);
2177  break;
2178  case Type::BlockPointer:
2179  AS = getTargetAddressSpace(cast<BlockPointerType>(T)->getPointeeType());
2180  Width = Target->getPointerWidth(AS);
2181  Align = Target->getPointerAlign(AS);
2182  break;
2183  case Type::LValueReference:
2184  case Type::RValueReference:
2185  // alignof and sizeof should never enter this code path here, so we go
2186  // the pointer route.
2187  AS = getTargetAddressSpace(cast<ReferenceType>(T)->getPointeeType());
2188  Width = Target->getPointerWidth(AS);
2189  Align = Target->getPointerAlign(AS);
2190  break;
2191  case Type::Pointer:
2192  AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
2193  Width = Target->getPointerWidth(AS);
2194  Align = Target->getPointerAlign(AS);
2195  break;
2196  case Type::MemberPointer: {
2197  const auto *MPT = cast<MemberPointerType>(T);
2198  CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT);
2199  Width = MPI.Width;
2200  Align = MPI.Align;
2201  break;
2202  }
2203  case Type::Complex: {
2204  // Complex types have the same alignment as their elements, but twice the
2205  // size.
2206  TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
2207  Width = EltInfo.Width * 2;
2208  Align = EltInfo.Align;
2209  break;
2210  }
2211  case Type::ObjCObject:
2212  return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
2213  case Type::Adjusted:
2214  case Type::Decayed:
2215  return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
2216  case Type::ObjCInterface: {
2217  const auto *ObjCI = cast<ObjCInterfaceType>(T);
2218  const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2219  Width = toBits(Layout.getSize());
2220  Align = toBits(Layout.getAlignment());
2221  break;
2222  }
2223  case Type::Record:
2224  case Type::Enum: {
2225  const auto *TT = cast<TagType>(T);
2226 
2227  if (TT->getDecl()->isInvalidDecl()) {
2228  Width = 8;
2229  Align = 8;
2230  break;
2231  }
2232 
2233  if (const auto *ET = dyn_cast<EnumType>(TT)) {
2234  const EnumDecl *ED = ET->getDecl();
2235  TypeInfo Info =
2237  if (unsigned AttrAlign = ED->getMaxAlignment()) {
2238  Info.Align = AttrAlign;
2239  Info.AlignIsRequired = true;
2240  }
2241  return Info;
2242  }
2243 
2244  const auto *RT = cast<RecordType>(TT);
2245  const RecordDecl *RD = RT->getDecl();
2246  const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2247  Width = toBits(Layout.getSize());
2248  Align = toBits(Layout.getAlignment());
2249  AlignIsRequired = RD->hasAttr<AlignedAttr>();
2250  break;
2251  }
2252 
2253  case Type::SubstTemplateTypeParm:
2254  return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
2255  getReplacementType().getTypePtr());
2256 
2257  case Type::Auto:
2258  case Type::DeducedTemplateSpecialization: {
2259  const auto *A = cast<DeducedType>(T);
2260  assert(!A->getDeducedType().isNull() &&
2261  "cannot request the size of an undeduced or dependent auto type");
2262  return getTypeInfo(A->getDeducedType().getTypePtr());
2263  }
2264 
2265  case Type::Paren:
2266  return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
2267 
2268  case Type::MacroQualified:
2269  return getTypeInfo(
2270  cast<MacroQualifiedType>(T)->getUnderlyingType().getTypePtr());
2271 
2272  case Type::ObjCTypeParam:
2273  return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr());
2274 
2275  case Type::Typedef: {
2276  const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
2277  TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
2278  // If the typedef has an aligned attribute on it, it overrides any computed
2279  // alignment we have. This violates the GCC documentation (which says that
2280  // attribute(aligned) can only round up) but matches its implementation.
2281  if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
2282  Align = AttrAlign;
2283  AlignIsRequired = true;
2284  } else {
2285  Align = Info.Align;
2286  AlignIsRequired = Info.AlignIsRequired;
2287  }
2288  Width = Info.Width;
2289  break;
2290  }
2291 
2292  case Type::Elaborated:
2293  return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
2294 
2295  case Type::Attributed:
2296  return getTypeInfo(
2297  cast<AttributedType>(T)->getEquivalentType().getTypePtr());
2298 
2299  case Type::Atomic: {
2300  // Start with the base type information.
2301  TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
2302  Width = Info.Width;
2303  Align = Info.Align;
2304 
2305  if (!Width) {
2306  // An otherwise zero-sized type should still generate an
2307  // atomic operation.
2308  Width = Target->getCharWidth();
2309  assert(Align);
2310  } else if (Width <= Target->getMaxAtomicPromoteWidth()) {
2311  // If the size of the type doesn't exceed the platform's max
2312  // atomic promotion width, make the size and alignment more
2313  // favorable to atomic operations:
2314 
2315  // Round the size up to a power of 2.
2316  if (!llvm::isPowerOf2_64(Width))
2317  Width = llvm::NextPowerOf2(Width);
2318 
2319  // Set the alignment equal to the size.
2320  Align = static_cast<unsigned>(Width);
2321  }
2322  }
2323  break;
2324 
2325  case Type::Pipe:
2326  Width = Target->getPointerWidth(getTargetAddressSpace(LangAS::opencl_global));
2327  Align = Target->getPointerAlign(getTargetAddressSpace(LangAS::opencl_global));
2328  break;
2329  }
2330 
2331  assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
2332  return TypeInfo(Width, Align, AlignIsRequired);
2333 }
2334 
2335 unsigned ASTContext::getTypeUnadjustedAlign(const Type *T) const {
2336  UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(T);
2337  if (I != MemoizedUnadjustedAlign.end())
2338  return I->second;
2339 
2340  unsigned UnadjustedAlign;
2341  if (const auto *RT = T->getAs<RecordType>()) {
2342  const RecordDecl *RD = RT->getDecl();
2343  const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2344  UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2345  } else if (const auto *ObjCI = T->getAs<ObjCInterfaceType>()) {
2346  const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2347  UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2348  } else {
2349  UnadjustedAlign = getTypeAlign(T->getUnqualifiedDesugaredType());
2350  }
2351 
2352  MemoizedUnadjustedAlign[T] = UnadjustedAlign;
2353  return UnadjustedAlign;
2354 }
2355 
2357  unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign();
2358  // Target ppc64 with QPX: simd default alignment for pointer to double is 32.
2359  if ((getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64 ||
2360  getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64le) &&
2361  getTargetInfo().getABI() == "elfv1-qpx" &&
2362  T->isSpecificBuiltinType(BuiltinType::Double))
2363  SimdAlign = 256;
2364  return SimdAlign;
2365 }
2366 
2367 /// toCharUnitsFromBits - Convert a size in bits to a size in characters.
2369  return CharUnits::fromQuantity(BitSize / getCharWidth());
2370 }
2371 
2372 /// toBits - Convert a size in characters to a size in characters.
2373 int64_t ASTContext::toBits(CharUnits CharSize) const {
2374  return CharSize.getQuantity() * getCharWidth();
2375 }
2376 
2377 /// getTypeSizeInChars - Return the size of the specified type, in characters.
2378 /// This method does not work on incomplete types.
2380  return getTypeInfoInChars(T).first;
2381 }
2383  return getTypeInfoInChars(T).first;
2384 }
2385 
2386 /// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
2387 /// characters. This method does not work on incomplete types.
2389  return toCharUnitsFromBits(getTypeAlign(T));
2390 }
2392  return toCharUnitsFromBits(getTypeAlign(T));
2393 }
2394 
2395 /// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a
2396 /// type, in characters, before alignment adustments. This method does
2397 /// not work on incomplete types.
2400 }
2403 }
2404 
2405 /// getPreferredTypeAlign - Return the "preferred" alignment of the specified
2406 /// type for the current target in bits. This can be different than the ABI
2407 /// alignment in cases where it is beneficial for performance to overalign
2408 /// a data type.
2409 unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
2410  TypeInfo TI = getTypeInfo(T);
2411  unsigned ABIAlign = TI.Align;
2412 
2413  T = T->getBaseElementTypeUnsafe();
2414 
2415  // The preferred alignment of member pointers is that of a pointer.
2416  if (T->isMemberPointerType())
2418 
2419  if (!Target->allowsLargerPreferedTypeAlignment())
2420  return ABIAlign;
2421 
2422  // Double and long long should be naturally aligned if possible.
2423  if (const auto *CT = T->getAs<ComplexType>())
2424  T = CT->getElementType().getTypePtr();
2425  if (const auto *ET = T->getAs<EnumType>())
2426  T = ET->getDecl()->getIntegerType().getTypePtr();
2427  if (T->isSpecificBuiltinType(BuiltinType::Double) ||
2428  T->isSpecificBuiltinType(BuiltinType::LongLong) ||
2429  T->isSpecificBuiltinType(BuiltinType::ULongLong))
2430  // Don't increase the alignment if an alignment attribute was specified on a
2431  // typedef declaration.
2432  if (!TI.AlignIsRequired)
2433  return std::max(ABIAlign, (unsigned)getTypeSize(T));
2434 
2435  return ABIAlign;
2436 }
2437 
2438 /// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2439 /// for __attribute__((aligned)) on this target, to be used if no alignment
2440 /// value is specified.
2443 }
2444 
2445 /// getAlignOfGlobalVar - Return the alignment in bits that should be given
2446 /// to a global variable of the specified type.
2448  uint64_t TypeSize = getTypeSize(T.getTypePtr());
2449  return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign(TypeSize));
2450 }
2451 
2452 /// getAlignOfGlobalVarInChars - Return the alignment in characters that
2453 /// should be given to a global variable of the specified type.
2456 }
2457 
2460  const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
2461  while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2462  Offset += Layout->getBaseClassOffset(Base);
2463  Layout = &getASTRecordLayout(Base);
2464  }
2465  return Offset;
2466 }
2467 
2468 /// DeepCollectObjCIvars -
2469 /// This routine first collects all declared, but not synthesized, ivars in
2470 /// super class and then collects all ivars, including those synthesized for
2471 /// current class. This routine is used for implementation of current class
2472 /// when all ivars, declared and synthesized are known.
2474  bool leafClass,
2475  SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
2476  if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2477  DeepCollectObjCIvars(SuperClass, false, Ivars);
2478  if (!leafClass) {
2479  for (const auto *I : OI->ivars())
2480  Ivars.push_back(I);
2481  } else {
2482  auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
2483  for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
2484  Iv= Iv->getNextIvar())
2485  Ivars.push_back(Iv);
2486  }
2487 }
2488 
2489 /// CollectInheritedProtocols - Collect all protocols in current class and
2490 /// those inherited by it.
2492  llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
2493  if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
2494  // We can use protocol_iterator here instead of
2495  // all_referenced_protocol_iterator since we are walking all categories.
2496  for (auto *Proto : OI->all_referenced_protocols()) {
2497  CollectInheritedProtocols(Proto, Protocols);
2498  }
2499 
2500  // Categories of this Interface.
2501  for (const auto *Cat : OI->visible_categories())
2502  CollectInheritedProtocols(Cat, Protocols);
2503 
2504  if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2505  while (SD) {
2506  CollectInheritedProtocols(SD, Protocols);
2507  SD = SD->getSuperClass();
2508  }
2509  } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
2510  for (auto *Proto : OC->protocols()) {
2511  CollectInheritedProtocols(Proto, Protocols);
2512  }
2513  } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
2514  // Insert the protocol.
2515  if (!Protocols.insert(
2516  const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2517  return;
2518 
2519  for (auto *Proto : OP->protocols())
2520  CollectInheritedProtocols(Proto, Protocols);
2521  }
2522 }
2523 
2525  const RecordDecl *RD) {
2526  assert(RD->isUnion() && "Must be union type");
2527  CharUnits UnionSize = Context.getTypeSizeInChars(RD->getTypeForDecl());
2528 
2529  for (const auto *Field : RD->fields()) {
2530  if (!Context.hasUniqueObjectRepresentations(Field->getType()))
2531  return false;
2532  CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType());
2533  if (FieldSize != UnionSize)
2534  return false;
2535  }
2536  return !RD->field_empty();
2537 }
2538 
2539 static bool isStructEmpty(QualType Ty) {
2540  const RecordDecl *RD = Ty->castAs<RecordType>()->getDecl();
2541 
2542  if (!RD->field_empty())
2543  return false;
2544 
2545  if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD))
2546  return ClassDecl->isEmpty();
2547 
2548  return true;
2549 }
2550 
2553  const RecordDecl *RD) {
2554  assert(!RD->isUnion() && "Must be struct/class type");
2555  const auto &Layout = Context.getASTRecordLayout(RD);
2556 
2557  int64_t CurOffsetInBits = 0;
2558  if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) {
2559  if (ClassDecl->isDynamicClass())
2560  return llvm::None;
2561 
2563  for (const auto &Base : ClassDecl->bases()) {
2564  // Empty types can be inherited from, and non-empty types can potentially
2565  // have tail padding, so just make sure there isn't an error.
2566  if (!isStructEmpty(Base.getType())) {
2568  Context, Base.getType()->castAs<RecordType>()->getDecl());
2569  if (!Size)
2570  return llvm::None;
2571  Bases.emplace_back(Base.getType(), Size.getValue());
2572  }
2573  }
2574 
2575  llvm::sort(Bases, [&](const std::pair<QualType, int64_t> &L,
2576  const std::pair<QualType, int64_t> &R) {
2577  return Layout.getBaseClassOffset(L.first->getAsCXXRecordDecl()) <
2578  Layout.getBaseClassOffset(R.first->getAsCXXRecordDecl());
2579  });
2580 
2581  for (const auto &Base : Bases) {
2582  int64_t BaseOffset = Context.toBits(
2583  Layout.getBaseClassOffset(Base.first->getAsCXXRecordDecl()));
2584  int64_t BaseSize = Base.second;
2585  if (BaseOffset != CurOffsetInBits)
2586  return llvm::None;
2587  CurOffsetInBits = BaseOffset + BaseSize;
2588  }
2589  }
2590 
2591  for (const auto *Field : RD->fields()) {
2592  if (!Field->getType()->isReferenceType() &&
2593  !Context.hasUniqueObjectRepresentations(Field->getType()))
2594  return llvm::None;
2595 
2596  int64_t FieldSizeInBits =
2597  Context.toBits(Context.getTypeSizeInChars(Field->getType()));
2598  if (Field->isBitField()) {
2599  int64_t BitfieldSize = Field->getBitWidthValue(Context);
2600 
2601  if (BitfieldSize > FieldSizeInBits)
2602  return llvm::None;
2603  FieldSizeInBits = BitfieldSize;
2604  }
2605 
2606  int64_t FieldOffsetInBits = Context.getFieldOffset(Field);
2607 
2608  if (FieldOffsetInBits != CurOffsetInBits)
2609  return llvm::None;
2610 
2611  CurOffsetInBits = FieldSizeInBits + FieldOffsetInBits;
2612  }
2613 
2614  return CurOffsetInBits;
2615 }
2616 
2618  // C++17 [meta.unary.prop]:
2619  // The predicate condition for a template specialization
2620  // has_unique_object_representations<T> shall be
2621  // satisfied if and only if:
2622  // (9.1) - T is trivially copyable, and
2623  // (9.2) - any two objects of type T with the same value have the same
2624  // object representation, where two objects
2625  // of array or non-union class type are considered to have the same value
2626  // if their respective sequences of
2627  // direct subobjects have the same values, and two objects of union type
2628  // are considered to have the same
2629  // value if they have the same active member and the corresponding members
2630  // have the same value.
2631  // The set of scalar types for which this condition holds is
2632  // implementation-defined. [ Note: If a type has padding
2633  // bits, the condition does not hold; otherwise, the condition holds true
2634  // for unsigned integral types. -- end note ]
2635  assert(!Ty.isNull() && "Null QualType sent to unique object rep check");
2636 
2637  // Arrays are unique only if their element type is unique.
2638  if (Ty->isArrayType())
2640 
2641  // (9.1) - T is trivially copyable...
2642  if (!Ty.isTriviallyCopyableType(*this))
2643  return false;
2644 
2645  // All integrals and enums are unique.
2646  if (Ty->isIntegralOrEnumerationType())
2647  return true;
2648 
2649  // All other pointers are unique.
2650  if (Ty->isPointerType())
2651  return true;
2652 
2653  if (Ty->isMemberPointerType()) {
2654  const auto *MPT = Ty->getAs<MemberPointerType>();
2655  return !ABI->getMemberPointerInfo(MPT).HasPadding;
2656  }
2657 
2658  if (Ty->isRecordType()) {
2659  const RecordDecl *Record = Ty->castAs<RecordType>()->getDecl();
2660 
2661  if (Record->isInvalidDecl())
2662  return false;
2663 
2664  if (Record->isUnion())
2665  return unionHasUniqueObjectRepresentations(*this, Record);
2666 
2667  Optional<int64_t> StructSize =
2668  structHasUniqueObjectRepresentations(*this, Record);
2669 
2670  return StructSize &&
2671  StructSize.getValue() == static_cast<int64_t>(getTypeSize(Ty));
2672  }
2673 
2674  // FIXME: More cases to handle here (list by rsmith):
2675  // vectors (careful about, eg, vector of 3 foo)
2676  // _Complex int and friends
2677  // _Atomic T
2678  // Obj-C block pointers
2679  // Obj-C object pointers
2680  // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t,
2681  // clk_event_t, queue_t, reserve_id_t)
2682  // There're also Obj-C class types and the Obj-C selector type, but I think it
2683  // makes sense for those to return false here.
2684 
2685  return false;
2686 }
2687 
2689  unsigned count = 0;
2690  // Count ivars declared in class extension.
2691  for (const auto *Ext : OI->known_extensions())
2692  count += Ext->ivar_size();
2693 
2694  // Count ivar defined in this class's implementation. This
2695  // includes synthesized ivars.
2696  if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
2697  count += ImplDecl->ivar_size();
2698 
2699  return count;
2700 }
2701 
2703  if (!E)
2704  return false;
2705 
2706  // nullptr_t is always treated as null.
2707  if (E->getType()->isNullPtrType()) return true;
2708 
2709  if (E->getType()->isAnyPointerType() &&
2712  return true;
2713 
2714  // Unfortunately, __null has type 'int'.
2715  if (isa<GNUNullExpr>(E)) return true;
2716 
2717  return false;
2718 }
2719 
2720 /// Get the implementation of ObjCInterfaceDecl, or nullptr if none
2721 /// exists.
2723  llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2724  I = ObjCImpls.find(D);
2725  if (I != ObjCImpls.end())
2726  return cast<ObjCImplementationDecl>(I->second);
2727  return nullptr;
2728 }
2729 
2730 /// Get the implementation of ObjCCategoryDecl, or nullptr if none
2731 /// exists.
2733  llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2734  I = ObjCImpls.find(D);
2735  if (I != ObjCImpls.end())
2736  return cast<ObjCCategoryImplDecl>(I->second);
2737  return nullptr;
2738 }
2739 
2740 /// Set the implementation of ObjCInterfaceDecl.
2742  ObjCImplementationDecl *ImplD) {
2743  assert(IFaceD && ImplD && "Passed null params");
2744  ObjCImpls[IFaceD] = ImplD;
2745 }
2746 
2747 /// Set the implementation of ObjCCategoryDecl.
2749  ObjCCategoryImplDecl *ImplD) {
2750  assert(CatD && ImplD && "Passed null params");
2751  ObjCImpls[CatD] = ImplD;
2752 }
2753 
2754 const ObjCMethodDecl *
2756  return ObjCMethodRedecls.lookup(MD);
2757 }
2758 
2760  const ObjCMethodDecl *Redecl) {
2761  assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
2762  ObjCMethodRedecls[MD] = Redecl;
2763 }
2764 
2766  const NamedDecl *ND) const {
2767  if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
2768  return ID;
2769  if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
2770  return CD->getClassInterface();
2771  if (const auto *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
2772  return IMD->getClassInterface();
2773 
2774  return nullptr;
2775 }
2776 
2777 /// Get the copy initialization expression of VarDecl, or nullptr if
2778 /// none exists.
2780  assert(VD && "Passed null params");
2781  assert(VD->hasAttr<BlocksAttr>() &&
2782  "getBlockVarCopyInits - not __block var");
2783  auto I = BlockVarCopyInits.find(VD);
2784  if (I != BlockVarCopyInits.end())
2785  return I->second;
2786  return {nullptr, false};
2787 }
2788 
2789 /// Set the copy initialization expression of a block var decl.
2791  bool CanThrow) {
2792  assert(VD && CopyExpr && "Passed null params");
2793  assert(VD->hasAttr<BlocksAttr>() &&
2794  "setBlockVarCopyInits - not __block var");
2795  BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow);
2796 }
2797 
2799  unsigned DataSize) const {
2800  if (!DataSize)
2801  DataSize = TypeLoc::getFullDataSizeForType(T);
2802  else
2803  assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
2804  "incorrect data size provided to CreateTypeSourceInfo!");
2805 
2806  auto *TInfo =
2807  (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
2808  new (TInfo) TypeSourceInfo(T);
2809  return TInfo;
2810 }
2811 
2813  SourceLocation L) const {
2815  DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
2816  return DI;
2817 }
2818 
2819 const ASTRecordLayout &
2821  return getObjCLayout(D, nullptr);
2822 }
2823 
2824 const ASTRecordLayout &
2826  const ObjCImplementationDecl *D) const {
2827  return getObjCLayout(D->getClassInterface(), D);
2828 }
2829 
2830 //===----------------------------------------------------------------------===//
2831 // Type creation/memoization methods
2832 //===----------------------------------------------------------------------===//
2833 
2834 QualType
2835 ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2836  unsigned fastQuals = quals.getFastQualifiers();
2837  quals.removeFastQualifiers();
2838 
2839  // Check if we've already instantiated this type.
2840  llvm::FoldingSetNodeID ID;
2841  ExtQuals::Profile(ID, baseType, quals);
2842  void *insertPos = nullptr;
2843  if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2844  assert(eq->getQualifiers() == quals);
2845  return QualType(eq, fastQuals);
2846  }
2847 
2848  // If the base type is not canonical, make the appropriate canonical type.
2849  QualType canon;
2850  if (!baseType->isCanonicalUnqualified()) {
2851  SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
2852  canonSplit.Quals.addConsistentQualifiers(quals);
2853  canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
2854 
2855  // Re-find the insert position.
2856  (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2857  }
2858 
2859  auto *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2860  ExtQualNodes.InsertNode(eq, insertPos);
2861  return QualType(eq, fastQuals);
2862 }
2863 
2865  LangAS AddressSpace) const {
2866  QualType CanT = getCanonicalType(T);
2867  if (CanT.getAddressSpace() == AddressSpace)
2868  return T;
2869 
2870  // If we are composing extended qualifiers together, merge together
2871  // into one ExtQuals node.
2872  QualifierCollector Quals;
2873  const Type *TypeNode = Quals.strip(T);
2874 
2875  // If this type already has an address space specified, it cannot get
2876  // another one.
2877  assert(!Quals.hasAddressSpace() &&
2878  "Type cannot be in multiple addr spaces!");
2879  Quals.addAddressSpace(AddressSpace);
2880 
2881  return getExtQualType(TypeNode, Quals);
2882 }
2883 
2885  // If we are composing extended qualifiers together, merge together
2886  // into one ExtQuals node.
2887  QualifierCollector Quals;
2888  const Type *TypeNode = Quals.strip(T);
2889 
2890  // If the qualifier doesn't have an address space just return it.
2891  if (!Quals.hasAddressSpace())
2892  return T;
2893 
2894  Quals.removeAddressSpace();
2895 
2896  // Removal of the address space can mean there are no longer any
2897  // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts)
2898  // or required.
2899  if (Quals.hasNonFastQualifiers())
2900  return getExtQualType(TypeNode, Quals);
2901  else
2902  return QualType(TypeNode, Quals.getFastQualifiers());
2903 }
2904 
2906  Qualifiers::GC GCAttr) const {
2907  QualType CanT = getCanonicalType(T);
2908  if (CanT.getObjCGCAttr() == GCAttr)
2909  return T;
2910 
2911  if (const auto *ptr = T->getAs<PointerType>()) {
2912  QualType Pointee = ptr->getPointeeType();
2913  if (Pointee->isAnyPointerType()) {
2914  QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2915  return getPointerType(ResultType);
2916  }
2917  }
2918 
2919  // If we are composing extended qualifiers together, merge together
2920  // into one ExtQuals node.
2921  QualifierCollector Quals;
2922  const Type *TypeNode = Quals.strip(T);
2923 
2924  // If this type already has an ObjCGC specified, it cannot get
2925  // another one.
2926  assert(!Quals.hasObjCGCAttr() &&
2927  "Type cannot have multiple ObjCGCs!");
2928  Quals.addObjCGCAttr(GCAttr);
2929 
2930  return getExtQualType(TypeNode, Quals);
2931 }
2932 
2934  if (const PointerType *Ptr = T->getAs<PointerType>()) {
2935  QualType Pointee = Ptr->getPointeeType();
2936  if (isPtrSizeAddressSpace(Pointee.getAddressSpace())) {
2937  return getPointerType(removeAddrSpaceQualType(Pointee));
2938  }
2939  }
2940  return T;
2941 }
2942 
2944  FunctionType::ExtInfo Info) {
2945  if (T->getExtInfo() == Info)
2946  return T;
2947 
2948  QualType Result;
2949  if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
2950  Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
2951  } else {
2952  const auto *FPT = cast<FunctionProtoType>(T);
2953  FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2954  EPI.ExtInfo = Info;
2955  Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
2956  }
2957 
2958  return cast<FunctionType>(Result.getTypePtr());
2959 }
2960 
2962  QualType ResultType) {
2963  FD = FD->getMostRecentDecl();
2964  while (true) {
2965  const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
2966  FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2967  FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
2968  if (FunctionDecl *Next = FD->getPreviousDecl())
2969  FD = Next;
2970  else
2971  break;
2972  }
2974  L->DeducedReturnType(FD, ResultType);
2975 }
2976 
2977 /// Get a function type and produce the equivalent function type with the
2978 /// specified exception specification. Type sugar that can be present on a
2979 /// declaration of a function with an exception specification is permitted
2980 /// and preserved. Other type sugar (for instance, typedefs) is not.
2983  // Might have some parens.
2984  if (const auto *PT = dyn_cast<ParenType>(Orig))
2985  return getParenType(
2986  getFunctionTypeWithExceptionSpec(PT->getInnerType(), ESI));
2987 
2988  // Might be wrapped in a macro qualified type.
2989  if (const auto *MQT = dyn_cast<MacroQualifiedType>(Orig))
2990  return getMacroQualifiedType(
2991  getFunctionTypeWithExceptionSpec(MQT->getUnderlyingType(), ESI),
2992  MQT->getMacroIdentifier());
2993 
2994  // Might have a calling-convention attribute.
2995  if (const auto *AT = dyn_cast<AttributedType>(Orig))
2996  return getAttributedType(
2997  AT->getAttrKind(),
2998  getFunctionTypeWithExceptionSpec(AT->getModifiedType(), ESI),
2999  getFunctionTypeWithExceptionSpec(AT->getEquivalentType(), ESI));
3000 
3001  // Anything else must be a function type. Rebuild it with the new exception
3002  // specification.
3003  const auto *Proto = Orig->castAs<FunctionProtoType>();
3004  return getFunctionType(
3005  Proto->getReturnType(), Proto->getParamTypes(),
3006  Proto->getExtProtoInfo().withExceptionSpec(ESI));
3007 }
3008 
3010  QualType U) {
3011  return hasSameType(T, U) ||
3012  (getLangOpts().CPlusPlus17 &&
3015 }
3016 
3018  if (const auto *Proto = T->getAs<FunctionProtoType>()) {
3019  QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3020  SmallVector<QualType, 16> Args(Proto->param_types());
3021  for (unsigned i = 0, n = Args.size(); i != n; ++i)
3022  Args[i] = removePtrSizeAddrSpace(Args[i]);
3023  return getFunctionType(RetTy, Args, Proto->getExtProtoInfo());
3024  }
3025 
3026  if (const FunctionNoProtoType *Proto = T->getAs<FunctionNoProtoType>()) {
3027  QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3028  return getFunctionNoProtoType(RetTy, Proto->getExtInfo());
3029  }
3030 
3031  return T;
3032 }
3033 
3035  return hasSameType(T, U) ||
3038 }
3039 
3042  bool AsWritten) {
3043  // Update the type.
3044  QualType Updated =
3046  FD->setType(Updated);
3047 
3048  if (!AsWritten)
3049  return;
3050 
3051  // Update the type in the type source information too.
3052  if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
3053  // If the type and the type-as-written differ, we may need to update
3054  // the type-as-written too.
3055  if (TSInfo->getType() != FD->getType())
3056  Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI);
3057 
3058  // FIXME: When we get proper type location information for exceptions,
3059  // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
3060  // up the TypeSourceInfo;
3061  assert(TypeLoc::getFullDataSizeForType(Updated) ==
3062  TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
3063  "TypeLoc size mismatch from updating exception specification");
3064  TSInfo->overrideType(Updated);
3065  }
3066 }
3067 
3068 /// getComplexType - Return the uniqued reference to the type for a complex
3069 /// number with the specified element type.
3071  // Unique pointers, to guarantee there is only one pointer of a particular
3072  // structure.
3073  llvm::FoldingSetNodeID ID;
3074  ComplexType::Profile(ID, T);
3075 
3076  void *InsertPos = nullptr;
3077  if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
3078  return QualType(CT, 0);
3079 
3080  // If the pointee type isn't canonical, this won't be a canonical type either,
3081  // so fill in the canonical type field.
3082  QualType Canonical;
3083  if (!T.isCanonical()) {
3084  Canonical = getComplexType(getCanonicalType(T));
3085 
3086  // Get the new insert position for the node we care about.
3087  ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
3088  assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3089  }
3090  auto *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
3091  Types.push_back(New);
3092  ComplexTypes.InsertNode(New, InsertPos);
3093  return QualType(New, 0);
3094 }
3095 
3096 /// getPointerType - Return the uniqued reference to the type for a pointer to
3097 /// the specified type.
3099  // Unique pointers, to guarantee there is only one pointer of a particular
3100  // structure.
3101  llvm::FoldingSetNodeID ID;
3102  PointerType::Profile(ID, T);
3103 
3104  void *InsertPos = nullptr;
3105  if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3106  return QualType(PT, 0);
3107 
3108  // If the pointee type isn't canonical, this won't be a canonical type either,
3109  // so fill in the canonical type field.
3110  QualType Canonical;
3111  if (!T.isCanonical()) {
3112  Canonical = getPointerType(getCanonicalType(T));
3113 
3114  // Get the new insert position for the node we care about.
3115  PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3116  assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3117  }
3118  auto *New = new (*this, TypeAlignment) PointerType(T, Canonical);
3119  Types.push_back(New);
3120  PointerTypes.InsertNode(New, InsertPos);
3121  return QualType(New, 0);
3122 }
3123 
3125  llvm::FoldingSetNodeID ID;
3126  AdjustedType::Profile(ID, Orig, New);
3127  void *InsertPos = nullptr;
3128  AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3129  if (AT)
3130  return QualType(AT, 0);
3131 
3132  QualType Canonical = getCanonicalType(New);
3133 
3134  // Get the new insert position for the node we care about.
3135  AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3136  assert(!AT && "Shouldn't be in the map!");
3137 
3138  AT = new (*this, TypeAlignment)
3139  AdjustedType(Type::Adjusted, Orig, New, Canonical);
3140  Types.push_back(AT);
3141  AdjustedTypes.InsertNode(AT, InsertPos);
3142  return QualType(AT, 0);
3143 }
3144 
3146  assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
3147 
3148  QualType Decayed;
3149 
3150  // C99 6.7.5.3p7:
3151  // A declaration of a parameter as "array of type" shall be
3152  // adjusted to "qualified pointer to type", where the type
3153  // qualifiers (if any) are those specified within the [ and ] of
3154  // the array type derivation.
3155  if (T->isArrayType())
3156  Decayed = getArrayDecayedType(T);
3157 
3158  // C99 6.7.5.3p8:
3159  // A declaration of a parameter as "function returning type"
3160  // shall be adjusted to "pointer to function returning type", as
3161  // in 6.3.2.1.
3162  if (T->isFunctionType())
3163  Decayed = getPointerType(T);
3164 
3165  llvm::FoldingSetNodeID ID;
3166  AdjustedType::Profile(ID, T, Decayed);
3167  void *InsertPos = nullptr;
3168  AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3169  if (AT)
3170  return QualType(AT, 0);
3171 
3172  QualType Canonical = getCanonicalType(Decayed);
3173 
3174  // Get the new insert position for the node we care about.
3175  AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3176  assert(!AT && "Shouldn't be in the map!");
3177 
3178  AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
3179  Types.push_back(AT);
3180  AdjustedTypes.InsertNode(AT, InsertPos);
3181  return QualType(AT, 0);
3182 }
3183 
3184 /// getBlockPointerType - Return the uniqued reference to the type for
3185 /// a pointer to the specified block.
3187  assert(T->isFunctionType() && "block of function types only");
3188  // Unique pointers, to guarantee there is only one block of a particular
3189  // structure.
3190  llvm::FoldingSetNodeID ID;
3192 
3193  void *InsertPos = nullptr;
3194  if (BlockPointerType *PT =
3195  BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3196  return QualType(PT, 0);
3197 
3198  // If the block pointee type isn't canonical, this won't be a canonical
3199  // type either so fill in the canonical type field.
3200  QualType Canonical;
3201  if (!T.isCanonical()) {
3202  Canonical = getBlockPointerType(getCanonicalType(T));
3203 
3204  // Get the new insert position for the node we care about.
3205  BlockPointerType *NewIP =
3206  BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3207  assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3208  }
3209  auto *New = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
3210  Types.push_back(New);
3211  BlockPointerTypes.InsertNode(New, InsertPos);
3212  return QualType(New, 0);
3213 }
3214 
3215 /// getLValueReferenceType - Return the uniqued reference to the type for an
3216 /// lvalue reference to the specified type.
3217 QualType
3218 ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
3219  assert(getCanonicalType(T) != OverloadTy &&
3220  "Unresolved overloaded function type");
3221 
3222  // Unique pointers, to guarantee there is only one pointer of a particular
3223  // structure.
3224  llvm::FoldingSetNodeID ID;
3225  ReferenceType::Profile(ID, T, SpelledAsLValue);
3226 
3227  void *InsertPos = nullptr;
3228  if (LValueReferenceType *RT =
3229  LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
3230  return QualType(RT, 0);
3231 
3232  const auto *InnerRef = T->getAs<ReferenceType>();
3233 
3234  // If the referencee type isn't canonical, this won't be a canonical type
3235  // either, so fill in the canonical type field.
3236  QualType Canonical;
3237  if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
3238  QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
3239  Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
3240 
3241  // Get the new insert position for the node we care about.
3242  LValueReferenceType *NewIP =
3243  LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
3244  assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3245  }
3246 
3247  auto *New = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
3248  SpelledAsLValue);
3249  Types.push_back(New);
3250  LValueReferenceTypes.InsertNode(New, InsertPos);
3251 
3252  return QualType(New, 0);
3253 }
3254 
3255 /// getRValueReferenceType - Return the uniqued reference to the type for an
3256 /// rvalue reference to the specified type.
3258  // Unique pointers, to guarantee there is only one pointer of a particular
3259  // structure.
3260  llvm::FoldingSetNodeID ID;
3261  ReferenceType::Profile(ID, T, false);
3262 
3263  void *InsertPos = nullptr;
3264  if (RValueReferenceType *RT =
3265  RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
3266  return QualType(RT, 0);
3267 
3268  const auto *InnerRef = T->getAs<ReferenceType>();
3269 
3270  // If the referencee type isn't canonical, this won't be a canonical type
3271  // either, so fill in the canonical type field.
3272  QualType Canonical;
3273  if (InnerRef || !T.isCanonical()) {
3274  QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
3275  Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
3276 
3277  // Get the new insert position for the node we care about.
3278  RValueReferenceType *NewIP =
3279  RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
3280  assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3281  }
3282 
3283  auto *New = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
3284  Types.push_back(New);
3285  RValueReferenceTypes.InsertNode(New, InsertPos);
3286  return QualType(New, 0);
3287 }
3288 
3289 /// getMemberPointerType - Return the uniqued reference to the type for a
3290 /// member pointer to the specified type, in the specified class.
3292  // Unique pointers, to guarantee there is only one pointer of a particular
3293  // structure.
3294  llvm::FoldingSetNodeID ID;
3295  MemberPointerType::Profile(ID, T, Cls);
3296 
3297  void *InsertPos = nullptr;
3298  if (MemberPointerType *PT =
3299  MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3300  return QualType(PT, 0);
3301 
3302  // If the pointee or class type isn't canonical, this won't be a canonical
3303  // type either, so fill in the canonical type field.
3304  QualType Canonical;
3305  if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
3307 
3308  // Get the new insert position for the node we care about.
3309  MemberPointerType *NewIP =
3310  MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3311  assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3312  }
3313  auto *New = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
3314  Types.push_back(New);
3315  MemberPointerTypes.InsertNode(New, InsertPos);
3316  return QualType(New, 0);
3317 }
3318 
3319 /// getConstantArrayType - Return the unique reference to the type for an
3320 /// array of the specified element type.
3322  const llvm::APInt &ArySizeIn,
3323  const Expr *SizeExpr,
3325  unsigned IndexTypeQuals) const {
3326  assert((EltTy->isDependentType() ||
3327  EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
3328  "Constant array of VLAs is illegal!");
3329 
3330  // We only need the size as part of the type if it's instantiation-dependent.
3331  if (SizeExpr && !SizeExpr->isInstantiationDependent())
3332  SizeExpr = nullptr;
3333 
3334  // Convert the array size into a canonical width matching the pointer size for
3335  // the target.
3336  llvm::APInt ArySize(ArySizeIn);
3337  ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth());
3338 
3339  llvm::FoldingSetNodeID ID;
3340  ConstantArrayType::Profile(ID, *this, EltTy, ArySize, SizeExpr, ASM,
3341  IndexTypeQuals);
3342 
3343  void *InsertPos = nullptr;
3344  if (ConstantArrayType *ATP =
3345  ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
3346  return QualType(ATP, 0);
3347 
3348  // If the element type isn't canonical or has qualifiers, or the array bound
3349  // is instantiation-dependent, this won't be a canonical type either, so fill
3350  // in the canonical type field.
3351  QualType Canon;
3352  if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers() || SizeExpr) {
3353  SplitQualType canonSplit = getCanonicalType(EltTy).split();
3354  Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize, nullptr,
3355  ASM, IndexTypeQuals);
3356  Canon = getQualifiedType(Canon, canonSplit.Quals);
3357 
3358  // Get the new insert position for the node we care about.
3359  ConstantArrayType *NewIP =
3360  ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
3361  assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3362  }
3363 
3364  void *Mem = Allocate(
3365  ConstantArrayType::totalSizeToAlloc<const Expr *>(SizeExpr ? 1 : 0),
3366  TypeAlignment);
3367  auto *New = new (Mem)
3368  ConstantArrayType(EltTy, Canon, ArySize, SizeExpr, ASM, IndexTypeQuals);
3369  ConstantArrayTypes.InsertNode(New, InsertPos);
3370  Types.push_back(New);
3371  return QualType(New, 0);
3372 }
3373 
3374 /// getVariableArrayDecayedType - Turns the given type, which may be
3375 /// variably-modified, into the corresponding type with all the known
3376 /// sizes replaced with [*].
3378  // Vastly most common case.
3379  if (!type->isVariablyModifiedType()) return type;
3380 
3381  QualType result;
3382 
3383  SplitQualType split = type.getSplitDesugaredType();
3384  const Type *ty = split.Ty;
3385  switch (ty->getTypeClass()) {
3386 #define TYPE(Class, Base)
3387 #define ABSTRACT_TYPE(Class, Base)
3388 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3389 #include "clang/AST/TypeNodes.inc"
3390  llvm_unreachable("didn't desugar past all non-canonical types?");
3391 
3392  // These types should never be variably-modified.
3393  case Type::Builtin:
3394  case Type::Complex:
3395  case Type::Vector:
3396  case Type::DependentVector:
3397  case Type::ExtVector:
3398  case Type::DependentSizedExtVector:
3399  case Type::DependentAddressSpace:
3400  case Type::ObjCObject:
3401  case Type::ObjCInterface:
3402  case Type::ObjCObjectPointer:
3403  case Type::Record:
3404  case Type::Enum:
3405  case Type::UnresolvedUsing:
3406  case Type::TypeOfExpr:
3407  case Type::TypeOf:
3408  case Type::Decltype:
3409  case Type::UnaryTransform:
3410  case Type::DependentName:
3411  case Type::InjectedClassName:
3412  case Type::TemplateSpecialization:
3413  case Type::DependentTemplateSpecialization:
3414  case Type::TemplateTypeParm:
3415  case Type::SubstTemplateTypeParmPack:
3416  case Type::Auto:
3417  case Type::DeducedTemplateSpecialization:
3418  case Type::PackExpansion:
3419  llvm_unreachable("type should never be variably-modified");
3420 
3421  // These types can be variably-modified but should never need to
3422  // further decay.
3423  case Type::FunctionNoProto:
3424  case Type::FunctionProto:
3425  case Type::BlockPointer:
3426  case Type::MemberPointer:
3427  case Type::Pipe:
3428  return type;
3429 
3430  // These types can be variably-modified. All these modifications
3431  // preserve structure except as noted by comments.
3432  // TODO: if we ever care about optimizing VLAs, there are no-op
3433  // optimizations available here.
3434  case Type::Pointer:
3436  cast<PointerType>(ty)->getPointeeType()));
3437  break;
3438 
3439  case Type::LValueReference: {
3440  const auto *lv = cast<LValueReferenceType>(ty);
3441  result = getLValueReferenceType(
3442  getVariableArrayDecayedType(lv->getPointeeType()),
3443  lv->isSpelledAsLValue());
3444  break;
3445  }
3446 
3447  case Type::RValueReference: {
3448  const auto *lv = cast<RValueReferenceType>(ty);
3449  result = getRValueReferenceType(
3450  getVariableArrayDecayedType(lv->getPointeeType()));
3451  break;
3452  }
3453 
3454  case Type::Atomic: {
3455  const auto *at = cast<AtomicType>(ty);
3456  result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
3457  break;
3458  }
3459 
3460  case Type::ConstantArray: {
3461  const auto *cat = cast<ConstantArrayType>(ty);
3462  result = getConstantArrayType(
3463  getVariableArrayDecayedType(cat->getElementType()),
3464  cat->getSize(),
3465  cat->getSizeExpr(),
3466  cat->getSizeModifier(),
3467  cat->getIndexTypeCVRQualifiers());
3468  break;
3469  }
3470 
3471  case Type::DependentSizedArray: {
3472  const auto *dat = cast<DependentSizedArrayType>(ty);
3473  result = getDependentSizedArrayType(
3474  getVariableArrayDecayedType(dat->getElementType()),
3475  dat->getSizeExpr(),
3476  dat->getSizeModifier(),
3477  dat->getIndexTypeCVRQualifiers(),
3478  dat->getBracketsRange());
3479  break;
3480  }
3481 
3482  // Turn incomplete types into [*] types.
3483  case Type::IncompleteArray: {
3484  const auto *iat = cast<IncompleteArrayType>(ty);
3485  result = getVariableArrayType(
3486  getVariableArrayDecayedType(iat->getElementType()),
3487  /*size*/ nullptr,
3489  iat->getIndexTypeCVRQualifiers(),
3490  SourceRange());
3491  break;
3492  }
3493 
3494  // Turn VLA types into [*] types.
3495  case Type::VariableArray: {
3496  const auto *vat = cast<VariableArrayType>(ty);
3497  result = getVariableArrayType(
3498  getVariableArrayDecayedType(vat->getElementType()),
3499  /*size*/ nullptr,
3501  vat->getIndexTypeCVRQualifiers(),
3502  vat->getBracketsRange());
3503  break;
3504  }
3505  }
3506 
3507  // Apply the top-level qualifiers from the original.
3508  return getQualifiedType(result, split.Quals);
3509 }
3510 
3511 /// getVariableArrayType - Returns a non-unique reference to the type for a
3512 /// variable array of the specified element type.
3514  Expr *NumElts,
3516  unsigned IndexTypeQuals,
3517  SourceRange Brackets) const {
3518  // Since we don't unique expressions, it isn't possible to unique VLA's
3519  // that have an expression provided for their size.
3520  QualType Canon;
3521 
3522  // Be sure to pull qualifiers off the element type.
3523  if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
3524  SplitQualType canonSplit = getCanonicalType(EltTy).split();
3525  Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
3526  IndexTypeQuals, Brackets);
3527  Canon = getQualifiedType(Canon, canonSplit.Quals);
3528  }
3529 
3530  auto *New = new (*this, TypeAlignment)
3531  VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
3532 
3533  VariableArrayTypes.push_back(New);
3534  Types.push_back(New);
3535  return QualType(New, 0);
3536 }
3537 
3538 /// getDependentSizedArrayType - Returns a non-unique reference to
3539 /// the type for a dependently-sized array of the specified element
3540 /// type.
3542  Expr *numElements,
3544  unsigned elementTypeQuals,
3545  SourceRange brackets) const {
3546  assert((!numElements || numElements->isTypeDependent() ||
3547  numElements->isValueDependent()) &&
3548  "Size must be type- or value-dependent!");
3549 
3550  // Dependently-sized array types that do not have a specified number
3551  // of elements will have their sizes deduced from a dependent
3552  // initializer. We do no canonicalization here at all, which is okay
3553  // because they can't be used in most locations.
3554  if (!numElements) {
3555  auto *newType
3556  = new (*this, TypeAlignment)
3557  DependentSizedArrayType(*this, elementType, QualType(),
3558  numElements, ASM, elementTypeQuals,
3559  brackets);
3560  Types.push_back(newType);
3561  return QualType(newType, 0);
3562  }
3563 
3564  // Otherwise, we actually build a new type every time, but we
3565  // also build a canonical type.
3566 
3567  SplitQualType canonElementType = getCanonicalType(elementType).split();
3568 
3569  void *insertPos = nullptr;
3570  llvm::FoldingSetNodeID ID;
3572  QualType(canonElementType.Ty, 0),
3573  ASM, elementTypeQuals, numElements);
3574 
3575  // Look for an existing type with these properties.
3576  DependentSizedArrayType *canonTy =
3577  DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
3578 
3579  // If we don't have one, build one.
3580  if (!canonTy) {
3581  canonTy = new (*this, TypeAlignment)
3582  DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
3583  QualType(), numElements, ASM, elementTypeQuals,
3584  brackets);
3585  DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
3586  Types.push_back(canonTy);
3587  }
3588 
3589  // Apply qualifiers from the element type to the array.
3590  QualType canon = getQualifiedType(QualType(canonTy,0),
3591  canonElementType.Quals);
3592 
3593  // If we didn't need extra canonicalization for the element type or the size
3594  // expression, then just use that as our result.
3595  if (QualType(canonElementType.Ty, 0) == elementType &&
3596  canonTy->getSizeExpr() == numElements)
3597  return canon;
3598 
3599  // Otherwise, we need to build a type which follows the spelling
3600  // of the element type.
3601  auto *sugaredType
3602  = new (*this, TypeAlignment)
3603  DependentSizedArrayType(*this, elementType, canon, numElements,
3604  ASM, elementTypeQuals, brackets);
3605  Types.push_back(sugaredType);
3606  return QualType(sugaredType, 0);
3607 }
3608 
3611  unsigned elementTypeQuals) const {
3612  llvm::FoldingSetNodeID ID;
3613  IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
3614 
3615  void *insertPos = nullptr;
3616  if (IncompleteArrayType *iat =
3617  IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
3618  return QualType(iat, 0);
3619 
3620  // If the element type isn't canonical, this won't be a canonical type
3621  // either, so fill in the canonical type field. We also have to pull
3622  // qualifiers off the element type.
3623  QualType canon;
3624 
3625  if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
3626  SplitQualType canonSplit = getCanonicalType(elementType).split();
3627  canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
3628  ASM, elementTypeQuals);
3629  canon = getQualifiedType(canon, canonSplit.Quals);
3630 
3631  // Get the new insert position for the node we care about.
3632  IncompleteArrayType *existing =
3633  IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
3634  assert(!existing && "Shouldn't be in the map!"); (void) existing;
3635  }
3636 
3637  auto *newType = new (*this, TypeAlignment)
3638  IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
3639 
3640  IncompleteArrayTypes.InsertNode(newType, insertPos);
3641  Types.push_back(newType);
3642  return QualType(newType, 0);
3643 }
3644 
3645 /// getVectorType - Return the unique reference to a vector type of
3646 /// the specified element type and size. VectorType must be a built-in type.
3647 QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
3648  VectorType::VectorKind VecKind) const {
3649  assert(vecType->isBuiltinType());
3650 
3651  // Check if we've already instantiated a vector of this type.
3652  llvm::FoldingSetNodeID ID;
3653  VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
3654 
3655  void *InsertPos = nullptr;
3656  if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3657  return QualType(VTP, 0);
3658 
3659  // If the element type isn't canonical, this won't be a canonical type either,
3660  // so fill in the canonical type field.
3661  QualType Canonical;
3662  if (!vecType.isCanonical()) {
3663  Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
3664 
3665  // Get the new insert position for the node we care about.
3666  VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3667  assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3668  }
3669  auto *New = new (*this, TypeAlignment)
3670  VectorType(vecType, NumElts, Canonical, VecKind);
3671  VectorTypes.InsertNode(New, InsertPos);
3672  Types.push_back(New);
3673  return QualType(New, 0);
3674 }
3675 
3676 QualType
3678  SourceLocation AttrLoc,
3679  VectorType::VectorKind VecKind) const {
3680  llvm::FoldingSetNodeID ID;
3681  DependentVectorType::Profile(ID, *this, getCanonicalType(VecType), SizeExpr,
3682  VecKind);
3683  void *InsertPos = nullptr;
3684  DependentVectorType *Canon =
3685  DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3686  DependentVectorType *New;
3687 
3688  if (Canon) {
3689  New = new (*this, TypeAlignment) DependentVectorType(
3690  *this, VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind);
3691  } else {
3692  QualType CanonVecTy = getCanonicalType(VecType);
3693  if (CanonVecTy == VecType) {
3694  New = new (*this, TypeAlignment) DependentVectorType(
3695  *this, VecType, QualType(), SizeExpr, AttrLoc, VecKind);
3696 
3697  DependentVectorType *CanonCheck =
3698  DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3699  assert(!CanonCheck &&
3700  "Dependent-sized vector_size canonical type broken");
3701  (void)CanonCheck;
3702  DependentVectorTypes.InsertNode(New, InsertPos);
3703  } else {
3704  QualType CanonExtTy = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
3705  SourceLocation());
3706  New = new (*this, TypeAlignment) DependentVectorType(
3707  *this, VecType, CanonExtTy, SizeExpr, AttrLoc, VecKind);
3708  }
3709  }
3710 
3711  Types.push_back(New);
3712  return QualType(New, 0);
3713 }
3714 
3715 /// getExtVectorType - Return the unique reference to an extended vector type of
3716 /// the specified element type and size. VectorType must be a built-in type.
3717 QualType
3718 ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
3719  assert(vecType->isBuiltinType() || vecType->isDependentType());
3720 
3721  // Check if we've already instantiated a vector of this type.
3722  llvm::FoldingSetNodeID ID;
3723  VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
3725  void *InsertPos = nullptr;
3726  if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3727  return QualType(VTP, 0);
3728 
3729  // If the element type isn't canonical, this won't be a canonical type either,
3730  // so fill in the canonical type field.
3731  QualType Canonical;
3732  if (!vecType.isCanonical()) {
3733  Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
3734 
3735  // Get the new insert position for the node we care about.
3736  VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3737  assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3738  }
3739  auto *New = new (*this, TypeAlignment)
3740  ExtVectorType(vecType, NumElts, Canonical);
3741  VectorTypes.InsertNode(New, InsertPos);
3742  Types.push_back(New);
3743  return QualType(New, 0);
3744 }
3745 
3746 QualType
3748  Expr *SizeExpr,
3749  SourceLocation AttrLoc) const {
3750  llvm::FoldingSetNodeID ID;
3752  SizeExpr);
3753 
3754  void *InsertPos = nullptr;
3756  = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3758  if (Canon) {
3759  // We already have a canonical version of this array type; use it as
3760  // the canonical type for a newly-built type.
3761  New = new (*this, TypeAlignment)
3762  DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
3763  SizeExpr, AttrLoc);
3764  } else {
3765  QualType CanonVecTy = getCanonicalType(vecType);
3766  if (CanonVecTy == vecType) {
3767  New = new (*this, TypeAlignment)
3768  DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
3769  AttrLoc);
3770 
3771  DependentSizedExtVectorType *CanonCheck
3772  = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3773  assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
3774  (void)CanonCheck;
3775  DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
3776  } else {
3777  QualType CanonExtTy = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
3778  SourceLocation());
3779  New = new (*this, TypeAlignment) DependentSizedExtVectorType(
3780  *this, vecType, CanonExtTy, SizeExpr, AttrLoc);
3781  }
3782  }
3783 
3784  Types.push_back(New);
3785  return QualType(New, 0);
3786 }
3787 
3789  Expr *AddrSpaceExpr,
3790  SourceLocation AttrLoc) const {
3791  assert(AddrSpaceExpr->isInstantiationDependent());
3792 
3793  QualType canonPointeeType = getCanonicalType(PointeeType);
3794 
3795  void *insertPos = nullptr;
3796  llvm::FoldingSetNodeID ID;
3797  DependentAddressSpaceType::Profile(ID, *this, canonPointeeType,
3798  AddrSpaceExpr);
3799 
3800  DependentAddressSpaceType *canonTy =
3801  DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos);
3802 
3803  if (!canonTy) {
3804  canonTy = new (*this, TypeAlignment)
3805  DependentAddressSpaceType(*this, canonPointeeType,
3806  QualType(), AddrSpaceExpr, AttrLoc);
3807  DependentAddressSpaceTypes.InsertNode(canonTy, insertPos);
3808  Types.push_back(canonTy);
3809  }
3810 
3811  if (canonPointeeType == PointeeType &&
3812  canonTy->getAddrSpaceExpr() == AddrSpaceExpr)
3813  return QualType(canonTy, 0);
3814 
3815  auto *sugaredType
3816  = new (*this, TypeAlignment)
3817  DependentAddressSpaceType(*this, PointeeType, QualType(canonTy, 0),
3818  AddrSpaceExpr, AttrLoc);
3819  Types.push_back(sugaredType);
3820  return QualType(sugaredType, 0);
3821 }
3822 
3823 /// Determine whether \p T is canonical as the result type of a function.
3825  return T.isCanonical() &&
3828 }
3829 
3830 /// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
3831 QualType
3833  const FunctionType::ExtInfo &Info) const {
3834  // Unique functions, to guarantee there is only one function of a particular
3835  // structure.
3836  llvm::FoldingSetNodeID ID;
3837  FunctionNoProtoType::Profile(ID, ResultTy, Info);
3838 
3839  void *InsertPos = nullptr;
3840  if (FunctionNoProtoType *FT =
3841  FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
3842  return QualType(FT, 0);
3843 
3844  QualType Canonical;
3845  if (!isCanonicalResultType(ResultTy)) {
3846  Canonical =
3848 
3849  // Get the new insert position for the node we care about.
3850  FunctionNoProtoType *NewIP =
3851  FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
3852  assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3853  }
3854 
3855  auto *New = new (*this, TypeAlignment)
3856  FunctionNoProtoType(ResultTy, Canonical, Info);
3857  Types.push_back(New);
3858  FunctionNoProtoTypes.InsertNode(New, InsertPos);
3859  return QualType(New, 0);
3860 }
3861 
3864  CanQualType CanResultType = getCanonicalType(ResultType);
3865 
3866  // Canonical result types do not have ARC lifetime qualifiers.
3867  if (CanResultType.getQualifiers().hasObjCLifetime()) {
3868  Qualifiers Qs = CanResultType.getQualifiers();
3869  Qs.removeObjCLifetime();
3871  getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
3872  }
3873 
3874  return CanResultType;
3875 }
3876 
3878  const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
3879  if (ESI.Type == EST_None)
3880  return true;
3881  if (!NoexceptInType)
3882  return false;
3883 
3884  // C++17 onwards: exception specification is part of the type, as a simple
3885  // boolean "can this function type throw".
3886  if (ESI.Type == EST_BasicNoexcept)
3887  return true;
3888 
3889  // A noexcept(expr) specification is (possibly) canonical if expr is
3890  // value-dependent.
3891  if (ESI.Type == EST_DependentNoexcept)
3892  return true;
3893 
3894  // A dynamic exception specification is canonical if it only contains pack
3895  // expansions (so we can't tell whether it's non-throwing) and all its
3896  // contained types are canonical.
3897  if (ESI.Type == EST_Dynamic) {
3898  bool AnyPackExpansions = false;
3899  for (QualType ET : ESI.Exceptions) {
3900  if (!ET.isCanonical())
3901  return false;
3902  if (ET->getAs<PackExpansionType>())
3903  AnyPackExpansions = true;
3904  }
3905  return AnyPackExpansions;
3906  }
3907 
3908  return false;
3909 }
3910 
3911 QualType ASTContext::getFunctionTypeInternal(
3912  QualType ResultTy, ArrayRef<QualType> ArgArray,
3913  const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
3914  size_t NumArgs = ArgArray.size();
3915 
3916  // Unique functions, to guarantee there is only one function of a particular
3917  // structure.
3918  llvm::FoldingSetNodeID ID;
3919  FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
3920  *this, true);
3921 
3922  QualType Canonical;
3923  bool Unique = false;
3924 
3925  void *InsertPos = nullptr;
3926  if (FunctionProtoType *FPT =
3927  FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
3928  QualType Existing = QualType(FPT, 0);
3929 
3930  // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
3931  // it so long as our exception specification doesn't contain a dependent
3932  // noexcept expression, or we're just looking for a canonical type.
3933  // Otherwise, we're going to need to create a type
3934  // sugar node to hold the concrete expression.
3935  if (OnlyWantCanonical || !isComputedNoexcept(EPI.ExceptionSpec.Type) ||
3936  EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
3937  return Existing;
3938 
3939  // We need a new type sugar node for this one, to hold the new noexcept
3940  // expression. We do no canonicalization here, but that's OK since we don't
3941  // expect to see the same noexcept expression much more than once.
3942  Canonical = getCanonicalType(Existing);
3943  Unique = true;
3944  }
3945 
3946  bool NoexceptInType = getLangOpts().CPlusPlus17;
3947  bool IsCanonicalExceptionSpec =
3948  isCanonicalExceptionSpecification(EPI.ExceptionSpec, NoexceptInType);
3949 
3950  // Determine whether the type being created is already canonical or not.
3951  bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
3952  isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
3953  for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
3954  if (!ArgArray[i].isCanonicalAsParam())
3955  isCanonical = false;
3956 
3957  if (OnlyWantCanonical)
3958  assert(isCanonical &&
3959  "given non-canonical parameters constructing canonical type");
3960 
3961  // If this type isn't canonical, get the canonical version of it if we don't
3962  // already have it. The exception spec is only partially part of the
3963  // canonical type, and only in C++17 onwards.
3964  if (!isCanonical && Canonical.isNull()) {
3965  SmallVector<QualType, 16> CanonicalArgs;
3966  CanonicalArgs.reserve(NumArgs);
3967  for (unsigned i = 0; i != NumArgs; ++i)
3968  CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
3969 
3970  llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
3971  FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
3972  CanonicalEPI.HasTrailingReturn = false;
3973 
3974  if (IsCanonicalExceptionSpec) {
3975  // Exception spec is already OK.
3976  } else if (NoexceptInType) {
3977  switch (EPI.ExceptionSpec.Type) {
3979  // We don't know yet. It shouldn't matter what we pick here; no-one
3980  // should ever look at this.
3981  LLVM_FALLTHROUGH;
3982  case EST_None: case EST_MSAny: case EST_NoexceptFalse:
3983  CanonicalEPI.ExceptionSpec.Type = EST_None;
3984  break;
3985 
3986  // A dynamic exception specification is almost always "not noexcept",
3987  // with the exception that a pack expansion might expand to no types.
3988  case EST_Dynamic: {
3989  bool AnyPacks = false;
3990  for (QualType ET : EPI.ExceptionSpec.Exceptions) {
3991  if (ET->getAs<PackExpansionType>())
3992  AnyPacks = true;
3993  ExceptionTypeStorage.push_back(getCanonicalType(ET));
3994  }
3995  if (!AnyPacks)
3996  CanonicalEPI.ExceptionSpec.Type = EST_None;
3997  else {
3998  CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
3999  CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
4000  }
4001  break;
4002  }
4003 
4004  case EST_DynamicNone:
4005  case EST_BasicNoexcept:
4006  case EST_NoexceptTrue:
4007  case EST_NoThrow:
4008  CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
4009  break;
4010 
4011  case EST_DependentNoexcept:
4012  llvm_unreachable("dependent noexcept is already canonical");
4013  }
4014  } else {
4016  }
4017 
4018  // Adjust the canonical function result type.
4019  CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
4020  Canonical =
4021  getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
4022 
4023  // Get the new insert position for the node we care about.
4024  FunctionProtoType *NewIP =
4025  FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
4026  assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4027  }
4028 
4029  // Compute the needed size to hold this FunctionProtoType and the
4030  // various trailing objects.
4031  auto ESH = FunctionProtoType::getExceptionSpecSize(
4032  EPI.ExceptionSpec.Type, EPI.ExceptionSpec.Exceptions.size());
4033  size_t Size = FunctionProtoType::totalSizeToAlloc<
4036  FunctionProtoType::ExtParameterInfo, Qualifiers>(
4037  NumArgs, EPI.Variadic,
4038  FunctionProtoType::hasExtraBitfields(EPI.ExceptionSpec.Type),
4039  ESH.NumExceptionType, ESH.NumExprPtr, ESH.NumFunctionDeclPtr,
4040  EPI.ExtParameterInfos ? NumArgs : 0,
4041  EPI.TypeQuals.hasNonFastQualifiers() ? 1 : 0);
4042 
4043  auto *FTP = (FunctionProtoType *)Allocate(Size, TypeAlignment);
4044  FunctionProtoType::ExtProtoInfo newEPI = EPI;
4045  new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
4046  Types.push_back(FTP);
4047  if (!Unique)
4048  FunctionProtoTypes.InsertNode(FTP, InsertPos);
4049  return QualType(FTP, 0);
4050 }
4051 
4052 QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
4053  llvm::FoldingSetNodeID ID;
4054  PipeType::Profile(ID, T, ReadOnly);
4055 
4056  void *InsertPos = nullptr;
4057  if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
4058  return QualType(PT, 0);
4059 
4060  // If the pipe element type isn't canonical, this won't be a canonical type
4061  // either, so fill in the canonical type field.
4062  QualType Canonical;
4063  if (!T.isCanonical()) {
4064  Canonical = getPipeType(getCanonicalType(T), ReadOnly);
4065 
4066  // Get the new insert position for the node we care about.
4067  PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
4068  assert(!NewIP && "Shouldn't be in the map!");
4069  (void)NewIP;
4070  }
4071  auto *New = new (*this, TypeAlignment) PipeType(T, Canonical, ReadOnly);
4072  Types.push_back(New);
4073  PipeTypes.InsertNode(New, InsertPos);
4074  return QualType(New, 0);
4075 }
4076 
4078  // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
4079  return LangOpts.OpenCL ? getAddrSpaceQualType(Ty, LangAS::opencl_constant)
4080  : Ty;
4081 }
4082 
4084  return getPipeType(T, true);
4085 }
4086 
4088  return getPipeType(T, false);
4089 }
4090 
4091 #ifndef NDEBUG
4093  if (!isa<CXXRecordDecl>(D)) return false;
4094  const auto *RD = cast<CXXRecordDecl>(D);
4095  if (isa<ClassTemplatePartialSpecializationDecl>(RD))
4096  return true;
4097  if (RD->getDescribedClassTemplate() &&
4098  !isa<ClassTemplateSpecializationDecl>(RD))
4099  return true;
4100  return false;
4101 }
4102 #endif
4103 
4104 /// getInjectedClassNameType - Return the unique reference to the
4105 /// injected class name type for the specified templated declaration.
4107  QualType TST) const {
4108  assert(NeedsInjectedClassNameType(Decl));
4109  if (Decl->TypeForDecl) {
4110  assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
4111  } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
4112  assert(PrevDecl->TypeForDecl && "previous declaration has no type");
4113  Decl->TypeForDecl = PrevDecl->TypeForDecl;
4114  assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
4115  } else {
4116  Type *newType =
4117  new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
4118  Decl->TypeForDecl = newType;
4119  Types.push_back(newType);
4120  }
4121  return QualType(Decl->TypeForDecl, 0);
4122 }
4123 
4124 /// getTypeDeclType - Return the unique reference to the type for the
4125 /// specified type declaration.
4126 QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
4127  assert(Decl && "Passed null for Decl param");
4128  assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
4129 
4130  if (const auto *Typedef = dyn_cast<TypedefNameDecl>(Decl))
4131  return getTypedefType(Typedef);
4132 
4133  assert(!isa<TemplateTypeParmDecl>(Decl) &&
4134  "Template type parameter types are always available.");
4135 
4136  if (const auto *Record = dyn_cast<RecordDecl>(Decl)) {
4137  assert(Record->isFirstDecl() && "struct/union has previous declaration");
4138  assert(!NeedsInjectedClassNameType(Record));
4139  return getRecordType(Record);
4140  } else if (const auto *Enum = dyn_cast<EnumDecl>(Decl)) {
4141  assert(Enum->isFirstDecl() && "enum has previous declaration");
4142  return getEnumType(Enum);
4143  } else if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
4144  Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
4145  Decl->TypeForDecl = newType;
4146  Types.push_back(newType);
4147  } else
4148  llvm_unreachable("TypeDecl without a type?");
4149 
4150  return QualType(Decl->TypeForDecl, 0);
4151 }
4152 
4153 /// getTypedefType - Return the unique reference to the type for the
4154 /// specified typedef name decl.
4155 QualType
4157  QualType Canonical) const {
4158  if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
4159 
4160  if (Canonical.isNull())
4161  Canonical = getCanonicalType(Decl->getUnderlyingType());
4162  auto *newType = new (*this, TypeAlignment)
4163  TypedefType(Type::Typedef, Decl, Canonical);
4164  Decl->TypeForDecl = newType;
4165  Types.push_back(newType);
4166  return QualType(newType, 0);
4167 }
4168 
4170  if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
4171 
4172  if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
4173  if (PrevDecl->TypeForDecl)
4174  return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
4175 
4176  auto *newType = new (*this, TypeAlignment) RecordType(Decl);
4177  Decl->TypeForDecl = newType;
4178  Types.push_back(newType);
4179  return QualType(newType, 0);
4180 }
4181 
4183  if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
4184 
4185  if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
4186  if (PrevDecl->TypeForDecl)
4187  return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
4188 
4189  auto *newType = new (*this, TypeAlignment) EnumType(Decl);
4190  Decl->TypeForDecl = newType;
4191  Types.push_back(newType);
4192  return QualType(newType, 0);
4193 }
4194 
4196  QualType modifiedType,
4197  QualType equivalentType) {
4198  llvm::FoldingSetNodeID id;
4199  AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
4200 
4201  void *insertPos = nullptr;
4202  AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
4203  if (type) return QualType(type, 0);
4204 
4205  QualType canon = getCanonicalType(equivalentType);
4206  type = new (*this, TypeAlignment)
4207  AttributedType(canon, attrKind, modifiedType, equivalentType);
4208 
4209  Types.push_back(type);
4210  AttributedTypes.InsertNode(type, insertPos);
4211 
4212  return QualType(type, 0);
4213 }
4214 
4215 /// Retrieve a substitution-result type.
4216 QualType
4218  QualType Replacement) const {
4219  assert(Replacement.isCanonical()
4220  && "replacement types must always be canonical");
4221 
4222  llvm::FoldingSetNodeID ID;
4223  SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
4224  void *InsertPos = nullptr;
4225  SubstTemplateTypeParmType *SubstParm
4226  = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4227 
4228  if (!SubstParm) {
4229  SubstParm = new (*this, TypeAlignment)
4230  SubstTemplateTypeParmType(Parm, Replacement);
4231  Types.push_back(SubstParm);
4232  SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
4233  }
4234 
4235  return QualType(SubstParm, 0);
4236 }
4237 
4238 /// Retrieve a
4240  const TemplateTypeParmType *Parm,
4241  const TemplateArgument &ArgPack) {
4242 #ifndef NDEBUG
4243  for (const auto &P : ArgPack.pack_elements()) {
4244  assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
4245  assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
4246  }
4247 #endif
4248 
4249  llvm::FoldingSetNodeID ID;
4250  SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
4251  void *InsertPos = nullptr;
4252  if (SubstTemplateTypeParmPackType *SubstParm
4253  = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
4254  return QualType(SubstParm, 0);
4255 
4256  QualType Canon;
4257  if (!Parm->isCanonicalUnqualified()) {
4258  Canon = getCanonicalType(QualType(Parm, 0));
4259  Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
4260  ArgPack);
4261  SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
4262  }
4263 
4264  auto *SubstParm
4265  = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
4266  ArgPack);
4267  Types.push_back(SubstParm);
4268  SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos);
4269  return QualType(SubstParm, 0);
4270 }
4271 
4272 /// Retrieve the template type parameter type for a template
4273 /// parameter or parameter pack with the given depth, index, and (optionally)
4274 /// name.
4276  bool ParameterPack,
4277  TemplateTypeParmDecl *TTPDecl) const {
4278  llvm::FoldingSetNodeID ID;
4279  TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
4280  void *InsertPos = nullptr;
4281  TemplateTypeParmType *TypeParm
4282  = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4283 
4284  if (TypeParm)
4285  return QualType(TypeParm, 0);
4286 
4287  if (TTPDecl) {
4288  QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
4289  TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
4290 
4291  TemplateTypeParmType *TypeCheck
4292  = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4293  assert(!TypeCheck && "Template type parameter canonical type broken");
4294  (void)TypeCheck;
4295  } else
4296  TypeParm = new (*this, TypeAlignment)
4297  TemplateTypeParmType(Depth, Index, ParameterPack);
4298 
4299  Types.push_back(TypeParm);
4300  TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
4301 
4302  return QualType(TypeParm, 0);
4303 }
4304 
4307  SourceLocation NameLoc,
4308  const TemplateArgumentListInfo &Args,
4309  QualType Underlying) const {
4310  assert(!Name.getAsDependentTemplateName() &&
4311  "No dependent template names here!");
4312  QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
4313 
4318  TL.setTemplateNameLoc(NameLoc);
4319  TL.setLAngleLoc(Args.getLAngleLoc());
4320  TL.setRAngleLoc(Args.getRAngleLoc());
4321  for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
4322  TL.setArgLocInfo(i, Args[i].getLocInfo());
4323  return DI;
4324 }
4325 
4326 QualType
4328  const TemplateArgumentListInfo &Args,
4329  QualType Underlying) const {
4330  assert(!Template.getAsDependentTemplateName() &&
4331  "No dependent template names here!");
4332 
4334  ArgVec.reserve(Args.size());
4335  for (const TemplateArgumentLoc &Arg : Args.arguments())
4336  ArgVec.push_back(Arg.getArgument());
4337 
4338  return getTemplateSpecializationType(Template, ArgVec, Underlying);
4339 }
4340 
4341 #ifndef NDEBUG
4343  for (const TemplateArgument &Arg : Args)
4344  if (Arg.isPackExpansion())
4345  return true;
4346 
4347  return true;
4348 }
4349 #endif
4350 
4351 QualType
4354  QualType Underlying) const {
4355  assert(!Template.getAsDependentTemplateName() &&
4356  "No dependent template names here!");
4357  // Look through qualified template names.
4358  if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
4359  Template = TemplateName(QTN->getTemplateDecl());
4360 
4361  bool IsTypeAlias =
4362  Template.getAsTemplateDecl() &&
4363  isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
4364  QualType CanonType;
4365  if (!Underlying.isNull())
4366  CanonType = getCanonicalType(Underlying);
4367  else {
4368  // We can get here with an alias template when the specialization contains
4369  // a pack expansion that does not match up with a parameter pack.
4370  assert((!IsTypeAlias || hasAnyPackExpansions(Args)) &&
4371  "Caller must compute aliased type");
4372  IsTypeAlias = false;
4373  CanonType = getCanonicalTemplateSpecializationType(Template, Args);
4374  }
4375 
4376  // Allocate the (non-canonical) template specialization type, but don't
4377  // try to unique it: these types typically have location information that
4378  // we don't unique and don't want to lose.
4379  void *Mem = Allocate(sizeof(TemplateSpecializationType) +
4380  sizeof(TemplateArgument) * Args.size() +
4381  (IsTypeAlias? sizeof(QualType) : 0),
4382  TypeAlignment);
4383  auto *Spec
4384  = new (Mem) TemplateSpecializationType(Template, Args, CanonType,
4385  IsTypeAlias ? Underlying : QualType());
4386 
4387  Types.push_back(Spec);
4388  return QualType(Spec, 0);
4389 }
4390 
4392  TemplateName Template, ArrayRef<TemplateArgument> Args) const {
4393  assert(!Template.getAsDependentTemplateName() &&
4394  "No dependent template names here!");
4395 
4396  // Look through qualified template names.
4397  if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
4398  Template = TemplateName(QTN->getTemplateDecl());
4399 
4400  // Build the canonical template specialization type.
4401  TemplateName CanonTemplate = getCanonicalTemplateName(Template);
4403  unsigned NumArgs = Args.size();
4404  CanonArgs.reserve(NumArgs);
4405  for (const TemplateArgument &Arg : Args)
4406  CanonArgs.push_back(getCanonicalTemplateArgument(Arg));
4407 
4408  // Determine whether this canonical template specialization type already
4409  // exists.
4410  llvm::FoldingSetNodeID ID;
4411  TemplateSpecializationType::Profile(ID, CanonTemplate,
4412  CanonArgs, *this);
4413 
4414  void *InsertPos = nullptr;
4416  = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
4417 
4418  if (!Spec) {
4419  // Allocate a new canonical template specialization type.
4420  void *Mem = Allocate((sizeof(TemplateSpecializationType) +
4421  sizeof(TemplateArgument) * NumArgs),
4422  TypeAlignment);
4423  Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
4424  CanonArgs,
4425  QualType(), QualType());
4426  Types.push_back(Spec);
4427  TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
4428  }
4429 
4430  assert(Spec->isDependentType() &&
4431  "Non-dependent template-id type must have a canonical type");
4432  return QualType(Spec, 0);
4433 }
4434 
4436  NestedNameSpecifier *NNS,
4437  QualType NamedType,
4438  TagDecl *OwnedTagDecl) const {
4439  llvm::FoldingSetNodeID ID;
4440  ElaboratedType::Profile(ID, Keyword, NNS, NamedType, OwnedTagDecl);
4441 
4442  void *InsertPos = nullptr;
4443  ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
4444  if (T)
4445  return QualType(T, 0);
4446 
4447  QualType Canon = NamedType;
4448  if (!Canon.isCanonical()) {
4449  Canon = getCanonicalType(NamedType);
4450  ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
4451  assert(!CheckT && "Elaborated canonical type broken");
4452  (void)CheckT;
4453  }
4454 
4455  void *Mem = Allocate(ElaboratedType::totalSizeToAlloc<TagDecl *>(!!OwnedTagDecl),
4456  TypeAlignment);
4457  T = new (Mem) ElaboratedType(Keyword, NNS, NamedType, Canon, OwnedTagDecl);
4458 
4459  Types.push_back(T);
4460  ElaboratedTypes.InsertNode(T, InsertPos);
4461  return QualType(T, 0);
4462 }
4463 
4464 QualType
4466  llvm::FoldingSetNodeID ID;
4467  ParenType::Profile(ID, InnerType);
4468 
4469  void *InsertPos = nullptr;
4470  ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
4471  if (T)
4472  return QualType(T, 0);
4473 
4474  QualType Canon = InnerType;
4475  if (!Canon.isCanonical()) {
4476  Canon = getCanonicalType(InnerType);
4477  ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
4478  assert(!CheckT && "Paren canonical type broken");
4479  (void)CheckT;
4480  }
4481 
4482  T = new (*this, TypeAlignment) ParenType(InnerType, Canon);
4483  Types.push_back(T);
4484  ParenTypes.InsertNode(T, InsertPos);
4485  return QualType(T, 0);
4486 }
4487 
4488 QualType
4490  const IdentifierInfo *MacroII) const {
4491  QualType Canon = UnderlyingTy;
4492  if (!Canon.isCanonical())
4493  Canon = getCanonicalType(UnderlyingTy);
4494 
4495  auto *newType = new (*this, TypeAlignment)
4496  MacroQualifiedType(UnderlyingTy, Canon, MacroII);
4497  Types.push_back(newType);
4498  return QualType(newType, 0);
4499 }
4500 
4502  NestedNameSpecifier *NNS,
4503  const IdentifierInfo *Name,
4504  QualType Canon) const {
4505  if (Canon.isNull()) {
4507  if (CanonNNS != NNS)
4508  Canon = getDependentNameType(Keyword, CanonNNS, Name);
4509  }
4510 
4511  llvm::FoldingSetNodeID ID;
4512  DependentNameType::Profile(ID, Keyword, NNS, Name);
4513 
4514  void *InsertPos = nullptr;
4516  = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
4517  if (T)
4518  return QualType(T, 0);
4519 
4520  T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon);
4521  Types.push_back(T);
4522  DependentNameTypes.InsertNode(T, InsertPos);
4523  return QualType(T, 0);
4524 }
4525 
4526 QualType
4528  ElaboratedTypeKeyword Keyword,
4529  NestedNameSpecifier *NNS,
4530  const IdentifierInfo *Name,
4531  const TemplateArgumentListInfo &Args) const {
4532  // TODO: avoid this copy
4534  for (unsigned I = 0, E = Args.size(); I != E; ++I)
4535  ArgCopy.push_back(Args[I].getArgument());
4536  return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy);
4537 }
4538 
4539 QualType
4541  ElaboratedTypeKeyword Keyword,
4542  NestedNameSpecifier *NNS,
4543  const IdentifierInfo *Name,
4544  ArrayRef<TemplateArgument> Args) const {
4545  assert((!NNS || NNS->isDependent()) &&
4546  "nested-name-specifier must be dependent");
4547 
4548  llvm::FoldingSetNodeID ID;
4549  DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
4550  Name, Args);
4551 
4552  void *InsertPos = nullptr;
4554  = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
4555  if (T)
4556  return QualType(T, 0);
4557 
4559 
4560  ElaboratedTypeKeyword CanonKeyword = Keyword;
4561  if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
4562 
4563  bool AnyNonCanonArgs = false;
4564  unsigned NumArgs = Args.size();
4565  SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
4566  for (unsigned I = 0; I != NumArgs; ++I) {
4567  CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
4568  if (!CanonArgs[I].structurallyEquals(Args[I]))
4569  AnyNonCanonArgs = true;
4570  }
4571 
4572  QualType Canon;
4573  if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
4574  Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
4575  Name,
4576  CanonArgs);
4577 
4578  // Find the insert position again.
4579  DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
4580  }
4581 
4582  void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
4583  sizeof(TemplateArgument) * NumArgs),
4584  TypeAlignment);
4585  T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
4586  Name, Args, Canon);
4587  Types.push_back(T);
4588  DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
4589  return QualType(T, 0);
4590 }
4591 
4593  TemplateArgument Arg;
4594  if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
4595  QualType ArgType = getTypeDeclType(TTP);
4596  if (TTP->isParameterPack())
4597  ArgType = getPackExpansionType(ArgType, None);
4598 
4599  Arg = TemplateArgument(ArgType);
4600  } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4601  Expr *E = new (*this) DeclRefExpr(
4602  *this, NTTP, /*enclosing*/ false,
4603  NTTP->getType().getNonLValueExprType(*this),
4604  Expr::getValueKindForType(NTTP->getType()), NTTP->getLocation());
4605 
4606  if (NTTP->isParameterPack())
4607  E = new (*this) PackExpansionExpr(DependentTy, E, NTTP->getLocation(),
4608  None);
4609  Arg = TemplateArgument(E);
4610  } else {
4611  auto *TTP = cast<TemplateTemplateParmDecl>(Param);
4612  if (TTP->isParameterPack())
4614  else
4615  Arg = TemplateArgument(TemplateName(TTP));
4616  }
4617 
4618  if (Param->isTemplateParameterPack())
4619  Arg = TemplateArgument::CreatePackCopy(*this, Arg);
4620 
4621  return Arg;
4622 }
4623 
4624 void
4627  Args.reserve(Args.size() + Params->size());
4628 
4629  for (NamedDecl *Param : *Params)
4630  Args.push_back(getInjectedTemplateArg(Param));
4631 }
4632 
4634  Optional<unsigned> NumExpansions) {
4635  llvm::FoldingSetNodeID ID;
4636  PackExpansionType::Profile(ID, Pattern, NumExpansions);
4637 
4638  // A deduced type can deduce to a pack, eg
4639  // auto ...x = some_pack;
4640  // That declaration isn't (yet) valid, but is created as part of building an
4641  // init-capture pack:
4642  // [...x = some_pack] {}
4643  assert((Pattern->containsUnexpandedParameterPack() ||
4644  Pattern->getContainedDeducedType()) &&
4645  "Pack expansions must expand one or more parameter packs");
4646  void *InsertPos = nullptr;
4648  = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
4649  if (T)
4650  return QualType(T, 0);
4651 
4652  QualType Canon;
4653  if (!Pattern.isCanonical()) {
4654  Canon = getCanonicalType(Pattern);
4655  // The canonical type might not contain an unexpanded parameter pack, if it
4656  // contains an alias template specialization which ignores one of its
4657  // parameters.
4658  if (Canon->containsUnexpandedParameterPack()) {
4659  Canon = getPackExpansionType(Canon, NumExpansions);
4660 
4661  // Find the insert position again, in case we inserted an element into
4662  // PackExpansionTypes and invalidated our insert position.
4663  PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
4664  }
4665  }
4666 
4667  T = new (*this, TypeAlignment)
4668  PackExpansionType(Pattern, Canon, NumExpansions);
4669  Types.push_back(T);
4670  PackExpansionTypes.InsertNode(T, InsertPos);
4671  return QualType(T, 0);
4672 }
4673 
4674 /// CmpProtocolNames - Comparison predicate for sorting protocols
4675 /// alphabetically.
4676 static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
4677  ObjCProtocolDecl *const *RHS) {
4678  return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
4679 }
4680 
4682  if (Protocols.empty()) return true;
4683 
4684  if (Protocols[0]->getCanonicalDecl() != Protocols[0])
4685  return false;
4686 
4687  for (unsigned i = 1; i != Protocols.size(); ++i)
4688  if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
4689  Protocols[i]->getCanonicalDecl() != Protocols[i])
4690  return false;
4691  return true;
4692 }
4693 
4694 static void
4696  // Sort protocols, keyed by name.
4697  llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
4698 
4699  // Canonicalize.
4700  for (ObjCProtocolDecl *&P : Protocols)
4701  P = P->getCanonicalDecl();
4702 
4703  // Remove duplicates.
4704  auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end());
4705  Protocols.erase(ProtocolsEnd, Protocols.end());
4706 }
4707 
4709  ObjCProtocolDecl * const *Protocols,
4710  unsigned NumProtocols) const {
4711  return getObjCObjectType(BaseType, {},
4712  llvm::makeArrayRef(Protocols, NumProtocols),
4713  /*isKindOf=*/false);
4714 }
4715 
4717  QualType baseType,
4718  ArrayRef<QualType> typeArgs,
4719  ArrayRef<ObjCProtocolDecl *> protocols,
4720  bool isKindOf) const {
4721  // If the base type is an interface and there aren't any protocols or
4722  // type arguments to add, then the interface type will do just fine.
4723  if (typeArgs.empty() && protocols.empty() && !isKindOf &&
4724  isa<ObjCInterfaceType>(baseType))
4725  return baseType;
4726 
4727  // Look in the folding set for an existing type.
4728  llvm::FoldingSetNodeID ID;
4729  ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
4730  void *InsertPos = nullptr;
4731  if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
4732  return QualType(QT, 0);
4733 
4734  // Determine the type arguments to be used for canonicalization,
4735  // which may be explicitly specified here or written on the base
4736  // type.
4737  ArrayRef<QualType> effectiveTypeArgs = typeArgs;
4738  if (effectiveTypeArgs.empty()) {
4739  if (const auto *baseObject = baseType->getAs<ObjCObjectType>())
4740  effectiveTypeArgs = baseObject->getTypeArgs();
4741  }
4742 
4743  // Build the canonical type, which has the canonical base type and a
4744  // sorted-and-uniqued list of protocols and the type arguments
4745  // canonicalized.
4746  QualType canonical;
4747  bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(),
4748  effectiveTypeArgs.end(),
4749  [&](QualType type) {
4750  return type.isCanonical();
4751  });
4752  bool protocolsSorted = areSortedAndUniqued(protocols);
4753  if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
4754  // Determine the canonical type arguments.
4755  ArrayRef<QualType> canonTypeArgs;
4756  SmallVector<QualType, 4> canonTypeArgsVec;
4757  if (!typeArgsAreCanonical) {
4758  canonTypeArgsVec.reserve(effectiveTypeArgs.size());
4759  for (auto typeArg : effectiveTypeArgs)
4760  canonTypeArgsVec.push_back(getCanonicalType(typeArg));
4761  canonTypeArgs = canonTypeArgsVec;
4762  } else {
4763  canonTypeArgs = effectiveTypeArgs;
4764  }
4765 
4766  ArrayRef<ObjCProtocolDecl *> canonProtocols;
4767  SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
4768  if (!protocolsSorted) {
4769  canonProtocolsVec.append(protocols.begin(), protocols.end());
4770  SortAndUniqueProtocols(canonProtocolsVec);
4771  canonProtocols = canonProtocolsVec;
4772  } else {
4773  canonProtocols = protocols;
4774  }
4775 
4776  canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
4777  canonProtocols, isKindOf);
4778 
4779  // Regenerate InsertPos.
4780  ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
4781  }
4782 
4783  unsigned size = sizeof(ObjCObjectTypeImpl);
4784  size += typeArgs.size() * sizeof(QualType);
4785  size += protocols.size() * sizeof(ObjCProtocolDecl *);
4786  void *mem = Allocate(size, TypeAlignment);
4787  auto *T =
4788  new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
4789  isKindOf);
4790 
4791  Types.push_back(T);
4792  ObjCObjectTypes.InsertNode(T, InsertPos);
4793  return QualType(T, 0);
4794 }
4795 
4796 /// Apply Objective-C protocol qualifiers to the given type.
4797 /// If this is for the canonical type of a type parameter, we can apply
4798 /// protocol qualifiers on the ObjCObjectPointerType.
4799 QualType
4801  ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
4802  bool allowOnPointerType) const {
4803  hasError = false;
4804 
4805  if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
4806  return getObjCTypeParamType(objT->getDecl(), protocols);
4807  }
4808 
4809  // Apply protocol qualifiers to ObjCObjectPointerType.
4810  if (allowOnPointerType) {
4811  if (const auto *objPtr =
4812  dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
4813  const ObjCObjectType *objT = objPtr->getObjectType();
4814  // Merge protocol lists and construct ObjCObjectType.
4815  SmallVector<ObjCProtocolDecl*, 8> protocolsVec;
4816  protocolsVec.append(objT->qual_begin(),
4817  objT->qual_end());
4818  protocolsVec.append(protocols.begin(), protocols.end());
4819  ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
4820  type = getObjCObjectType(
4821  objT->getBaseType(),
4822  objT->getTypeArgsAsWritten(),
4823  protocols,
4824  objT->isKindOfTypeAsWritten());
4825  return getObjCObjectPointerType(type);
4826  }
4827  }
4828 
4829  // Apply protocol qualifiers to ObjCObjectType.
4830  if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
4831  // FIXME: Check for protocols to which the class type is already
4832  // known to conform.
4833 
4834  return getObjCObjectType(objT->getBaseType(),
4835  objT->getTypeArgsAsWritten(),
4836  protocols,
4837  objT->isKindOfTypeAsWritten());
4838  }
4839 
4840  // If the canonical type is ObjCObjectType, ...
4841  if (type->isObjCObjectType()) {
4842  // Silently overwrite any existing protocol qualifiers.
4843  // TODO: determine whether that's the right thing to do.
4844 
4845  // FIXME: Check for protocols to which the class type is already
4846  // known to conform.
4847  return getObjCObjectType(type, {}, protocols, false);
4848  }
4849 
4850  // id<protocol-list>
4851  if (type->isObjCIdType()) {
4852  const auto *objPtr = type->castAs<ObjCObjectPointerType>();
4853  type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols,
4854  objPtr->isKindOfType());
4855  return getObjCObjectPointerType(type);
4856  }
4857 
4858  // Class<protocol-list>
4859  if (type->isObjCClassType()) {
4860  const auto *objPtr = type->castAs<ObjCObjectPointerType>();
4861  type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols,
4862  objPtr->isKindOfType());
4863  return getObjCObjectPointerType(type);
4864  }
4865 
4866  hasError = true;
4867  return type;
4868 }
4869 
4870 QualType
4872  ArrayRef<ObjCProtocolDecl *> protocols) const {
4873  // Look in the folding set for an existing type.
4874  llvm::FoldingSetNodeID ID;
4875  ObjCTypeParamType::Profile(ID, Decl, protocols);
4876  void *InsertPos = nullptr;
4877  if (ObjCTypeParamType *TypeParam =
4878  ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
4879  return QualType(TypeParam, 0);
4880 
4881  // We canonicalize to the underlying type.
4882  QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
4883  if (!protocols.empty()) {
4884  // Apply the protocol qualifers.
4885  bool hasError;
4887  Canonical, protocols, hasError, true /*allowOnPointerType*/));
4888  assert(!hasError && "Error when apply protocol qualifier to bound type");
4889  }
4890 
4891  unsigned size = sizeof(ObjCTypeParamType);
4892  size += protocols.size() * sizeof(ObjCProtocolDecl *);
4893  void *mem = Allocate(size, TypeAlignment);
4894  auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols);
4895 
4896  Types.push_back(newType);
4897  ObjCTypeParamTypes.InsertNode(newType, InsertPos);
4898  return QualType(newType, 0);
4899 }
4900 
4901 /// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
4902 /// protocol list adopt all protocols in QT's qualified-id protocol
4903 /// list.
4905  ObjCInterfaceDecl *IC) {
4906  if (!QT->isObjCQualifiedIdType())
4907  return false;
4908 
4909  if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) {
4910  // If both the right and left sides have qualifiers.
4911  for (auto *Proto : OPT->quals()) {
4912  if (!IC->ClassImplementsProtocol(Proto, false))
4913  return false;
4914  }
4915  return true;
4916  }
4917  return false;
4918 }
4919 
4920 /// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
4921 /// QT's qualified-id protocol list adopt all protocols in IDecl's list
4922 /// of protocols.
4924  ObjCInterfaceDecl *IDecl) {
4925  if (!QT->isObjCQualifiedIdType())
4926  return false;
4927  const auto *OPT = QT->getAs<ObjCObjectPointerType>();
4928  if (!OPT)
4929  return false;
4930  if (!IDecl->hasDefinition())
4931  return false;
4932  llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
4933  CollectInheritedProtocols(IDecl, InheritedProtocols);
4934  if (InheritedProtocols.empty())
4935  return false;
4936  // Check that if every protocol in list of id<plist> conforms to a protocol
4937  // of IDecl's, then bridge casting is ok.
4938  bool Conforms = false;
4939  for (auto *Proto : OPT->quals()) {
4940  Conforms = false;
4941  for (auto *PI : InheritedProtocols) {
4942  if (ProtocolCompatibleWithProtocol(Proto, PI)) {
4943  Conforms = true;
4944  break;
4945  }
4946  }
4947  if (!Conforms)
4948  break;
4949  }
4950  if (Conforms)
4951  return true;
4952 
4953  for (auto *PI : InheritedProtocols) {
4954  // If both the right and left sides have qualifiers.
4955  bool Adopts = false;
4956  for (auto *Proto : OPT->quals()) {
4957  // return 'true' if 'PI' is in the inheritance hierarchy of Proto
4958  if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
4959  break;
4960  }
4961  if (!Adopts)
4962  return false;
4963  }
4964  return true;
4965 }
4966 
4967 /// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
4968 /// the given object type.
4970  llvm::FoldingSetNodeID ID;
4971  ObjCObjectPointerType::Profile(ID, ObjectT);
4972 
4973  void *InsertPos = nullptr;
4974  if (ObjCObjectPointerType *QT =
4975  ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
4976  return QualType(QT, 0);
4977 
4978  // Find the canonical object type.
4979  QualType Canonical;
4980  if (!ObjectT.isCanonical()) {
4981  Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
4982 
4983  // Regenerate InsertPos.
4984  ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
4985  }
4986 
4987  // No match.
4988  void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
4989  auto *QType =
4990  new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
4991 
4992  Types.push_back(QType);
4993  ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
4994  return QualType(QType, 0);
4995 }
4996 
4997 /// getObjCInterfaceType - Return the unique reference to the type for the
4998 /// specified ObjC interface decl. The list of protocols is optional.
5000  ObjCInterfaceDecl *PrevDecl) const {
5001  if (Decl->TypeForDecl)
5002  return QualType(Decl->TypeForDecl, 0);
5003 
5004  if (PrevDecl) {
5005  assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
5006  Decl->TypeForDecl = PrevDecl->TypeForDecl;
5007  return QualType(PrevDecl->TypeForDecl, 0);
5008  }
5009 
5010  // Prefer the definition, if there is one.
5011  if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
5012  Decl = Def;
5013 
5014  void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
5015  auto *T = new (Mem) ObjCInterfaceType(Decl);
5016  Decl->TypeForDecl = T;
5017  Types.push_back(T);
5018  return QualType(T, 0);
5019 }
5020 
5021 /// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
5022 /// TypeOfExprType AST's (since expression's are never shared). For example,
5023 /// multiple declarations that refer to "typeof(x)" all contain different
5024 /// DeclRefExpr's. This doesn't effect the type checker, since it operates
5025 /// on canonical type's (which are always unique).
5027  TypeOfExprType *toe;
5028  if (tofExpr->isTypeDependent()) {
5029  llvm::FoldingSetNodeID ID;
5030  DependentTypeOfExprType::Profile(ID, *this, tofExpr);
5031 
5032  void *InsertPos = nullptr;
5034  = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
5035  if (Canon) {
5036  // We already have a "canonical" version of an identical, dependent
5037  // typeof(expr) type. Use that as our canonical type.
5038  toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
5039  QualType((TypeOfExprType*)Canon, 0));
5040  } else {
5041  // Build a new, canonical typeof(expr) type.
5042  Canon
5043  = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
5044  DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
5045  toe = Canon;
5046  }
5047  } else {
5048  QualType Canonical = getCanonicalType(tofExpr->getType());
5049  toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
5050  }
5051  Types.push_back(toe);
5052  return QualType(toe, 0);
5053 }
5054 
5055 /// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
5056 /// TypeOfType nodes. The only motivation to unique these nodes would be
5057 /// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
5058 /// an issue. This doesn't affect the type checker, since it operates
5059 /// on canonical types (which are always unique).
5061  QualType Canonical = getCanonicalType(tofType);
5062  auto *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
5063  Types.push_back(tot);
5064  return QualType(tot, 0);
5065 }
5066 
5067 /// Unlike many "get<Type>" functions, we don't unique DecltypeType
5068 /// nodes. This would never be helpful, since each such type has its own
5069 /// expression, and would not give a significant memory saving, since there
5070 /// is an Expr tree under each such type.
5072  DecltypeType *dt;
5073 
5074  // C++11 [temp.type]p2:
5075  // If an expression e involves a template parameter, decltype(e) denotes a
5076  // unique dependent type. Two such decltype-specifiers refer to the same
5077  // type only if their expressions are equivalent (14.5.6.1).
5078  if (e->isInstantiationDependent()) {
5079  llvm::FoldingSetNodeID ID;
5080  DependentDecltypeType::Profile(ID, *this, e);
5081 
5082  void *InsertPos = nullptr;
5083  DependentDecltypeType *Canon
5084  = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
5085  if (!Canon) {
5086  // Build a new, canonical decltype(expr) type.
5087  Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
5088  DependentDecltypeTypes.InsertNode(Canon, InsertPos);
5089  }
5090  dt = new (*this, TypeAlignment)
5091  DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
5092  } else {
5093  dt = new (*this, TypeAlignment)
5094  DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
5095  }
5096  Types.push_back(dt);
5097  return QualType(dt, 0);
5098 }
5099 
5100 /// getUnaryTransformationType - We don't unique these, since the memory
5101 /// savings are minimal and these are rare.
5103  QualType UnderlyingType,
5105  const {
5106  UnaryTransformType *ut = nullptr;
5107 
5108  if (BaseType->isDependentType()) {
5109  // Look in the folding set for an existing type.
5110  llvm::FoldingSetNodeID ID;
5112 
5113  void *InsertPos = nullptr;
5115  = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
5116 
5117  if (!Canon) {
5118  // Build a new, canonical __underlying_type(type) type.
5119  Canon = new (*this, TypeAlignment)
5121  Kind);
5122  DependentUnaryTransformTypes.InsertNode(Canon, InsertPos);
5123  }
5124  ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
5125  QualType(), Kind,
5126  QualType(Canon, 0));
5127  } else {
5128  QualType CanonType = getCanonicalType(UnderlyingType);
5129  ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
5130  UnderlyingType, Kind,
5131  CanonType);
5132  }
5133  Types.push_back(ut);
5134  return QualType(ut, 0);
5135 }
5136 
5137 /// getAutoType - Return the uniqued reference to the 'auto' type which has been
5138 /// deduced to the given type, or to the canonical undeduced 'auto' type, or the
5139 /// canonical deduced-but-dependent 'auto' type.
5140 QualType
5142  bool IsDependent, bool IsPack,
5143  ConceptDecl *TypeConstraintConcept,
5144  ArrayRef<TemplateArgument> TypeConstraintArgs) const {
5145  assert((!IsPack || IsDependent) && "only use IsPack for a dependent pack");
5146  if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto &&
5147  !TypeConstraintConcept && !IsDependent)
5148  return getAutoDeductType();
5149 
5150  // Look in the folding set for an existing type.
5151  void *InsertPos = nullptr;
5152  llvm::FoldingSetNodeID ID;
5153  AutoType::Profile(ID, *this, DeducedType, Keyword, IsDependent,
5154  TypeConstraintConcept, TypeConstraintArgs);
5155  if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
5156  return QualType(AT, 0);
5157 
5158  void *Mem = Allocate(sizeof(AutoType) +
5159  sizeof(TemplateArgument) * TypeConstraintArgs.size(),
5160  TypeAlignment);
5161  auto *AT = new (Mem) AutoType(DeducedType, Keyword, IsDependent, IsPack,
5162  TypeConstraintConcept, TypeConstraintArgs);
5163  Types.push_back(AT);
5164  if (InsertPos)
5165  AutoTypes.InsertNode(AT, InsertPos);
5166  return QualType(AT, 0);
5167 }
5168 
5169 /// Return the uniqued reference to the deduced template specialization type
5170 /// which has been deduced to the given type, or to the canonical undeduced
5171 /// such type, or the canonical deduced-but-dependent such type.
5173  TemplateName Template, QualType DeducedType, bool IsDependent) const {
5174  // Look in the folding set for an existing type.
5175  void *InsertPos = nullptr;
5176  llvm::FoldingSetNodeID ID;
5177  DeducedTemplateSpecializationType::Profile(ID, Template, DeducedType,
5178  IsDependent);
5180  DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
5181  return QualType(DTST, 0);
5182 
5183  auto *DTST = new (*this, TypeAlignment)
5184  DeducedTemplateSpecializationType(Template, DeducedType, IsDependent);
5185  Types.push_back(DTST);
5186  if (InsertPos)
5187  DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos);
5188  return QualType(DTST, 0);
5189 }
5190 
5191 /// getAtomicType - Return the uniqued reference to the atomic type for
5192 /// the given value type.
5194  // Unique pointers, to guarantee there is only one pointer of a particular
5195  // structure.
5196  llvm::FoldingSetNodeID ID;
5197  AtomicType::Profile(ID, T);
5198 
5199  void *InsertPos = nullptr;
5200  if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
5201  return QualType(AT, 0);
5202 
5203  // If the atomic value type isn't canonical, this won't be a canonical type
5204  // either, so fill in the canonical type field.
5205  QualType Canonical;
5206  if (!T.isCanonical()) {
5207  Canonical = getAtomicType(getCanonicalType(T));
5208 
5209  // Get the new insert position for the node we care about.
5210  AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
5211  assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
5212  }
5213  auto *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
5214  Types.push_back(New);
5215  AtomicTypes.InsertNode(New, InsertPos);
5216  return QualType(New, 0);
5217 }
5218 
5219 /// getAutoDeductType - Get type pattern for deducing against 'auto'.
5221  if (AutoDeductTy.isNull())
5224  /*dependent*/false, /*pack*/false,
5225  /*concept*/nullptr, /*args*/{}),
5226  0);
5227  return AutoDeductTy;
5228 }
5229 
5230 /// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
5232  if (AutoRRefDeductTy.isNull())
5234  assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
5235  return AutoRRefDeductTy;
5236 }
5237 
5238 /// getTagDeclType - Return the unique reference to the type for the
5239 /// specified TagDecl (struct/union/class/enum) decl.
5241  assert(Decl);
5242  // FIXME: What is the design on getTagDeclType when it requires casting
5243  // away const? mutable?
5244  return getTypeDeclType(const_cast<TagDecl*>(Decl));
5245 }
5246 
5247 /// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
5248 /// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
5249 /// needs to agree with the definition in <stddef.h>.
5251  return getFromTargetType(Target->getSizeType());
5252 }
5253 
5254 /// Return the unique signed counterpart of the integer type
5255 /// corresponding to size_t.
5257  return getFromTargetType(Target->getSignedSizeType());
5258 }
5259 
5260 /// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
5262  return getFromTargetType(Target->getIntMaxType());
5263 }
5264 
5265 /// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
5267  return getFromTargetType(Target->getUIntMaxType());
5268 }
5269 
5270 /// getSignedWCharType - Return the type of "signed wchar_t".
5271 /// Used when in C++, as a GCC extension.
5273  // FIXME: derive from "Target" ?
5274  return WCharTy;
5275 }
5276 
5277 /// getUnsignedWCharType - Return the type of "unsigned wchar_t".
5278 /// Used when in C++, as a GCC extension.
5280  // FIXME: derive from "Target" ?
5281  return UnsignedIntTy;
5282 }
5283 
5285  return getFromTargetType(Target->getIntPtrType());
5286 }
5287 
5290 }
5291 
5292 /// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
5293 /// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
5295  return getFromTargetType(Target->getPtrDiffType(0));
5296 }
5297 
5298 /// Return the unique unsigned counterpart of "ptrdiff_t"
5299 /// integer type. The standard (C11 7.21.6.1p7) refers to this type
5300 /// in the definition of %tu format specifier.
5302  return getFromTargetType(Target->getUnsignedPtrDiffType(0));
5303 }
5304 
5305 /// Return the unique type for "pid_t" defined in
5306 /// <sys/types.h>. We need this to compute the correct type for vfork().
5308  return getFromTargetType(Target->getProcessIDType());
5309 }
5310 
5311 //===----------------------------------------------------------------------===//
5312 // Type Operators
5313 //===----------------------------------------------------------------------===//
5314 
5316  // Push qualifiers into arrays, and then discard any remaining
5317  // qualifiers.
5318  T = getCanonicalType(T);
5320  const Type *Ty = T.getTypePtr();
5321  QualType Result;
5322  if (isa<ArrayType>(Ty)) {
5323  Result = getArrayDecayedType(QualType(Ty,0));
5324  } else if (isa<FunctionType>(Ty)) {
5325  Result = getPointerType(QualType(Ty, 0));
5326  } else {
5327  Result = QualType(Ty, 0);
5328  }
5329 
5330  return CanQualType::CreateUnsafe(Result);
5331 }
5332 
5334  Qualifiers &quals) {
5335  SplitQualType splitType = type.getSplitUnqualifiedType();
5336 
5337  // FIXME: getSplitUnqualifiedType() actually walks all the way to
5338  // the unqualified desugared type and then drops it on the floor.
5339  // We then have to strip that sugar back off with
5340  // getUnqualifiedDesugaredType(), which is silly.
5341  const auto *AT =
5342  dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
5343 
5344  // If we don't have an array, just use the results in splitType.
5345  if (!AT) {
5346  quals = splitType.Quals;
5347  return QualType(splitType.Ty, 0);
5348  }
5349 
5350  // Otherwise, recurse on the array's element type.
5351  QualType elementType = AT->getElementType();
5352  QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
5353 
5354  // If that didn't change the element type, AT has no qualifiers, so we
5355  // can just use the results in splitType.
5356  if (elementType == unqualElementType) {
5357  assert(quals.empty()); // from the recursive call
5358  quals = splitType.Quals;
5359  return QualType(splitType.Ty, 0);
5360  }
5361 
5362  // Otherwise, add in the qualifiers from the outermost type, then
5363  // build the type back up.
5364  quals.addConsistentQualifiers(splitType.Quals);
5365 
5366  if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
5367  return getConstantArrayType(unqualElementType, CAT->getSize(),
5368  CAT->getSizeExpr(), CAT->getSizeModifier(), 0);
5369  }
5370 
5371  if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) {
5372  return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
5373  }
5374 
5375  if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) {
5376  return getVariableArrayType(unqualElementType,
5377  VAT->getSizeExpr(),
5378  VAT->getSizeModifier(),
5379  VAT->getIndexTypeCVRQualifiers(),
5380  VAT->getBracketsRange());
5381  }
5382 
5383  const auto *DSAT = cast<DependentSizedArrayType>(AT);
5384  return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
5385  DSAT->getSizeModifier(), 0,
5386  SourceRange());
5387 }
5388 
5389 /// Attempt to unwrap two types that may both be array types with the same bound
5390 /// (or both be array types of unknown bound) for the purpose of comparing the
5391 /// cv-decomposition of two types per C++ [conv.qual].
5393  bool UnwrappedAny = false;
5394  while (true) {
5395  auto *AT1 = getAsArrayType(T1);
5396  if (!AT1) return UnwrappedAny;
5397 
5398  auto *AT2 = getAsArrayType(T2);
5399  if (!AT2) return UnwrappedAny;
5400 
5401  // If we don't have two array types with the same constant bound nor two
5402  // incomplete array types, we've unwrapped everything we can.
5403  if (auto *CAT1 = dyn_cast<ConstantArrayType>(AT1)) {
5404  auto *CAT2 = dyn_cast<ConstantArrayType>(AT2);
5405  if (!CAT2 || CAT1->getSize() != CAT2->getSize())
5406  return UnwrappedAny;
5407  } else if (!isa<IncompleteArrayType>(AT1) ||
5408  !isa<IncompleteArrayType>(AT2)) {
5409  return UnwrappedAny;
5410  }
5411 
5412  T1 = AT1->getElementType();
5413  T2 = AT2->getElementType();
5414  UnwrappedAny = true;
5415  }
5416 }
5417 
5418 /// Attempt to unwrap two types that may be similar (C++ [conv.qual]).
5419 ///
5420 /// If T1 and T2 are both pointer types of the same kind, or both array types
5421 /// with the same bound, unwraps layers from T1 and T2 until a pointer type is
5422 /// unwrapped. Top-level qualifiers on T1 and T2 are ignored.
5423 ///
5424 /// This function will typically be called in a loop that successively
5425 /// "unwraps" pointer and pointer-to-member types to compare them at each
5426 /// level.
5427 ///
5428 /// \return \c true if a pointer type was unwrapped, \c false if we reached a
5429 /// pair of types that can't be unwrapped further.
5431  UnwrapSimilarArrayTypes(T1, T2);
5432 
5433  const auto *T1PtrType = T1->getAs<PointerType>();
5434  const auto *T2PtrType = T2->getAs<PointerType>();
5435  if (T1PtrType && T2PtrType) {
5436  T1 = T1PtrType->getPointeeType();
5437  T2 = T2PtrType->getPointeeType();
5438  return true;
5439  }
5440 
5441  const auto *T1MPType = T1->getAs<MemberPointerType>();
5442  const auto *T2MPType = T2->getAs<MemberPointerType>();
5443  if (T1MPType && T2MPType &&
5444  hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
5445  QualType(T2MPType->getClass(), 0))) {
5446  T1 = T1MPType->getPointeeType();
5447  T2 = T2MPType->getPointeeType();
5448  return true;
5449  }
5450 
5451  if (getLangOpts().ObjC) {
5452  const auto *T1OPType = T1->getAs<ObjCObjectPointerType>();
5453  const auto *T2OPType = T2->getAs<ObjCObjectPointerType>();
5454  if (T1OPType && T2OPType) {
5455  T1 = T1OPType->getPointeeType();
5456  T2 = T2OPType->getPointeeType();
5457  return true;
5458  }
5459  }
5460 
5461  // FIXME: Block pointers, too?
5462 
5463  return false;
5464 }
5465 
5467  while (true) {
5468  Qualifiers Quals;
5469  T1 = getUnqualifiedArrayType(T1, Quals);
5470  T2 = getUnqualifiedArrayType(T2, Quals);
5471  if (hasSameType(T1, T2))
5472  return true;
5473  if (!UnwrapSimilarTypes(T1, T2))
5474  return false;
5475  }
5476 }
5477 
5479  while (true) {
5480  Qualifiers Quals1, Quals2;
5481  T1 = getUnqualifiedArrayType(T1, Quals1);
5482  T2 = getUnqualifiedArrayType(T2, Quals2);
5483 
5484  Quals1.removeCVRQualifiers();
5485  Quals2.removeCVRQualifiers();
5486  if (Quals1 != Quals2)
5487  return false;
5488 
5489  if (hasSameType(T1, T2))
5490  return true;
5491 
5492  if (!UnwrapSimilarTypes(T1, T2))
5493  return false;
5494  }
5495 }
5496 
5499  SourceLocation NameLoc) const {
5500  switch (Name.getKind()) {
5503  // DNInfo work in progress: CHECKME: what about DNLoc?
5505  NameLoc);
5506 
5509  // DNInfo work in progress: CHECKME: what about DNLoc?
5510  return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
5511  }
5512 
5515  return DeclarationNameInfo(Storage->getDeclName(), NameLoc);
5516  }
5517 
5520  DeclarationName DName;
5521  if (DTN->isIdentifier()) {
5523  return DeclarationNameInfo(DName, NameLoc);
5524  } else {
5526  // DNInfo work in progress: FIXME: source locations?
5527  DeclarationNameLoc DNLoc;
5530  return DeclarationNameInfo(DName, NameLoc, DNLoc);
5531  }
5532  }
5533 
5537  return DeclarationNameInfo(subst->getParameter()->getDeclName(),
5538  NameLoc);
5539  }
5540 
5545  NameLoc);
5546  }
5547  }
5548 
5549  llvm_unreachable("bad template name kind!");
5550 }
5551 
5553  switch (Name.getKind()) {
5555  case TemplateName::Template: {
5556  TemplateDecl *Template = Name.getAsTemplateDecl();
5557  if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Template))
5558  Template = getCanonicalTemplateTemplateParmDecl(TTP);
5559 
5560  // The canonical template name is the canonical template declaration.
5561  return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
5562  }
5563 
5566  llvm_unreachable("cannot canonicalize unresolved template");
5567 
5570  assert(DTN && "Non-dependent template names must refer to template decls.");
5571  return DTN->CanonicalTemplateName;
5572  }
5573 
5577  return getCanonicalTemplateName(subst->getReplacement());
5578  }
5579 
5583  TemplateTemplateParmDecl *canonParameter
5584  = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
5585  TemplateArgument canonArgPack
5587  return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
5588  }
5589  }
5590 
5591  llvm_unreachable("bad template name!");
5592 }
5593 
5595  X = getCanonicalTemplateName(X);
5596  Y = getCanonicalTemplateName(Y);
5597  return X.getAsVoidPointer() == Y.getAsVoidPointer();
5598 }
5599 
5602  switch (Arg.getKind()) {
5604  return Arg;
5605 
5607  return Arg;
5608 
5610  auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
5611  return TemplateArgument(D, Arg.getParamTypeForDecl());
5612  }
5613 
5616  /*isNullPtr*/true);
5617 
5620 
5624  Arg.getNumTemplateExpansions());
5625 
5628 
5631 
5632  case TemplateArgument::Pack: {
5633  if (Arg.pack_size() == 0)
5634  return Arg;
5635 
5636  auto *CanonArgs = new (*this) TemplateArgument[Arg.pack_size()];
5637  unsigned Idx = 0;
5639  AEnd = Arg.pack_end();
5640  A != AEnd; (void)++A, ++Idx)
5641  CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
5642 
5643  return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size()));
5644  }
5645  }
5646 
5647  // Silence GCC warning
5648  llvm_unreachable("Unhandled template argument kind");
5649 }
5650 
5653  if (!NNS)
5654  return nullptr;
5655 
5656  switch (NNS->getKind()) {
5658  // Canonicalize the prefix but keep the identifier the same.
5659  return NestedNameSpecifier::Create(*this,
5661  NNS->getAsIdentifier());
5662 
5664  // A namespace is canonical; build a nested-name-specifier with
5665  // this namespace and no prefix.
5666  return NestedNameSpecifier::Create(*this, nullptr,
5668 
5670  // A namespace is canonical; build a nested-name-specifier with
5671  // this namespace and no prefix.
5672  return NestedNameSpecifier::Create(*this, nullptr,
5674  ->getOriginalNamespace());
5675 
5678  QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
5679 
5680  // If we have some kind of dependent-named type (e.g., "typename T::type"),
5681  // break it apart into its prefix and identifier, then reconsititute those
5682  // as the canonical nested-name-specifier. This is required to canonicalize
5683  // a dependent nested-name-specifier involving typedefs of dependent-name
5684  // types, e.g.,
5685  // typedef typename T::type T1;
5686  // typedef typename T1::type T2;
5687  if (const auto *DNT = T->getAs<DependentNameType>())
5688  return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
5689  const_cast<IdentifierInfo *>(DNT->getIdentifier()));
5690 
5691  // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
5692  // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
5693  // first place?
5694  return NestedNameSpecifier::Create(*this, nullptr, false,
5695  const_cast<Type *>(T.getTypePtr()));
5696  }
5697 
5700  // The global specifier and __super specifer are canonical and unique.
5701  return NNS;
5702  }
5703 
5704  llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
5705 }
5706 
5708  // Handle the non-qualified case efficiently.
5709  if (!T.hasLocalQualifiers()) {
5710  // Handle the common positive case fast.
5711  if (const auto *AT = dyn_cast<ArrayType>(T))
5712  return AT;
5713  }
5714 
5715  // Handle the common negative case fast.
5716  if (!isa<ArrayType>(T.getCanonicalType()))
5717  return nullptr;
5718 
5719  // Apply any qualifiers from the array type to the element type. This
5720  // implements C99 6.7.3p8: "If the specification of an array type includes
5721  // any type qualifiers, the element type is so qualified, not the array type."
5722 
5723  // If we get here, we either have type qualifiers on the type, or we have
5724  // sugar such as a typedef in the way. If we have type qualifiers on the type
5725  // we must propagate them down into the element type.
5726 
5728  Qualifiers qs = split.Quals;
5729 
5730  // If we have a simple case, just return now.
5731  const auto *ATy = dyn_cast<ArrayType>(split.Ty);
5732  if (!ATy || qs.empty())
5733  return ATy;
5734 
5735  // Otherwise, we have an array and we have qualifiers on it. Push the
5736  // qualifiers into the array element type and return a new array type.
5737  QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
5738 
5739  if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy))
5740  return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
5741  CAT->getSizeExpr(),
5742  CAT->getSizeModifier(),
5743  CAT->getIndexTypeCVRQualifiers()));
5744  if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy))
5745  return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
5746  IAT->getSizeModifier(),
5747  IAT->getIndexTypeCVRQualifiers()));
5748 
5749  if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy))
5750  return cast<ArrayType>(
5751  getDependentSizedArrayType(NewEltTy,
5752  DSAT->getSizeExpr(),
5753  DSAT->getSizeModifier(),
5754  DSAT->getIndexTypeCVRQualifiers(),
5755  DSAT->getBracketsRange()));
5756 
5757  const auto *VAT = cast<VariableArrayType>(ATy);
5758  return cast<ArrayType>(getVariableArrayType(NewEltTy,
5759  VAT->getSizeExpr(),
5760  VAT->getSizeModifier(),
5761  VAT->getIndexTypeCVRQualifiers(),
5762  VAT->getBracketsRange()));
5763 }
5764 
5766  if (T->isArrayType() || T->isFunctionType())
5767  return getDecayedType(T);
5768  return T;
5769 }
5770 
5773  T = getAdjustedParameterType(T);
5774  return T.getUnqualifiedType();
5775 }
5776 
5778  // C++ [except.throw]p3:
5779  // A throw-expression initializes a temporary object, called the exception
5780  // object, the type of which is determined by removing any top-level
5781  // cv-qualifiers from the static type of the operand of throw and adjusting
5782  // the type from "array of T" or "function returning T" to "pointer to T"
5783  // or "pointer to function returning T", [...]
5785  if (T->isArrayType() || T->isFunctionType())
5786  T = getDecayedType(T);
5787  return T.getUnqualifiedType();
5788 }
5789 
5790 /// getArrayDecayedType - Return the properly qualified result of decaying the
5791 /// specified array type to a pointer. This operation is non-trivial when
5792 /// handling typedefs etc. The canonical type of "T" must be an array type,
5793 /// this returns a pointer to a properly qualified element of the array.
5794 ///
5795 /// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
5797  // Get the element type with 'getAsArrayType' so that we don't lose any
5798  // typedefs in the element type of the array. This also handles propagation
5799  // of type qualifiers from the array type into the element type if present
5800  // (C99 6.7.3p8).
5801  const ArrayType *PrettyArrayType = getAsArrayType(Ty);
5802  assert(PrettyArrayType && "Not an array type!");
5803 
5804  QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
5805 
5806  // int x[restrict 4] -> int *restrict
5808  PrettyArrayType->getIndexTypeQualifiers());
5809 
5810  // int x[_Nullable] -> int * _Nullable
5811  if (auto Nullability = Ty->getNullability(*this)) {
5812  Result = const_cast<ASTContext *>(this)->getAttributedType(
5814  }
5815  return Result;
5816 }
5817 
5819  return getBaseElementType(array->getElementType());
5820 }
5821 
5823  Qualifiers qs;
5824  while (true) {
5825  SplitQualType split = type.getSplitDesugaredType();
5826  const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
5827  if (!array) break;
5828 
5829  type = array->getElementType();
5830  qs.addConsistentQualifiers(split.Quals);
5831  }
5832 
5833  return getQualifiedType(type, qs);
5834 }
5835 
5836 /// getConstantArrayElementCount - Returns number of constant array elements.
5837 uint64_t
5839  uint64_t ElementCount = 1;
5840  do {
5841  ElementCount *= CA->getSize().getZExtValue();
5842  CA = dyn_cast_or_null<ConstantArrayType>(
5844  } while (CA);
5845  return ElementCount;
5846 }
5847 
5848 /// getFloatingRank - Return a relative rank for floating point types.
5849 /// This routine will assert if passed a built-in type that isn't a float.
5851  if (const auto *CT = T->getAs<ComplexType>())
5852  return getFloatingRank(CT->getElementType());
5853 
5854  switch (T->castAs<BuiltinType>()->getKind()) {
5855  default: llvm_unreachable("getFloatingRank(): not a floating type");
5856  case BuiltinType::Float16: return Float16Rank;
5857  case BuiltinType::Half: return HalfRank;
5858  case BuiltinType::Float: return FloatRank;
5859  case BuiltinType::Double: return DoubleRank;
5860  case BuiltinType::LongDouble: return LongDoubleRank;
5861  case BuiltinType::Float128: return Float128Rank;
5862  }
5863 }
5864 
5865 /// getFloatingTypeOfSizeWithinDomain - Returns a real floating
5866 /// point or a complex type (based on typeDomain/typeSize).
5867 /// 'typeDomain' is a real floating point or complex type.
5868 /// 'typeSize' is a real floating point or complex type.
5870  QualType Domain) const {
5871  FloatingRank EltRank = getFloatingRank(Size);
5872  if (Domain->isComplexType()) {
5873  switch (EltRank) {
5874  case Float16Rank:
5875  case HalfRank: llvm_unreachable("Complex half is not supported");
5876  case FloatRank: return FloatComplexTy;
5877  case DoubleRank: return DoubleComplexTy;
5878  case LongDoubleRank: return LongDoubleComplexTy;
5879  case Float128Rank: return Float128ComplexTy;
5880  }
5881  }
5882 
5883  assert(Domain->isRealFloatingType() && "Unknown domain!");
5884  switch (EltRank) {
5885  case Float16Rank: return HalfTy;
5886  case HalfRank: return HalfTy;
5887  case FloatRank: return FloatTy;
5888  case DoubleRank: return DoubleTy;
5889  case LongDoubleRank: return LongDoubleTy;
5890  case Float128Rank: return Float128Ty;
5891  }
5892  llvm_unreachable("getFloatingRank(): illegal value for rank");
5893 }
5894 
5895 /// getFloatingTypeOrder - Compare the rank of the two specified floating
5896 /// point types, ignoring the domain of the type (i.e. 'double' ==
5897 /// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
5898 /// LHS < RHS, return -1.
5900  FloatingRank LHSR = getFloatingRank(LHS);
5901  FloatingRank RHSR = getFloatingRank(RHS);
5902 
5903  if (LHSR == RHSR)
5904  return 0;
5905  if (LHSR > RHSR)
5906  return 1;
5907  return -1;
5908 }
5909 
5911  if (&getFloatTypeSemantics(LHS) == &getFloatTypeSemantics(RHS))
5912  return 0;
5913  return getFloatingTypeOrder(LHS, RHS);
5914 }
5915 
5916 /// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
5917 /// routine will assert if passed a built-in type that isn't an integer or enum,
5918 /// or if it is not canonicalized.
5919 unsigned ASTContext::getIntegerRank(const Type *T) const {
5920  assert(T->isCanonicalUnqualified() && "T should be canonicalized");
5921 
5922  switch (cast<BuiltinType>(T)->getKind()) {
5923  default: llvm_unreachable("getIntegerRank(): not a built-in integer");
5924  case BuiltinType::Bool:
5925  return 1 + (getIntWidth(BoolTy) << 3);
5926  case BuiltinType::Char_S:
5927  case BuiltinType::Char_U:
5928  case BuiltinType::SChar:
5929  case BuiltinType::UChar:
5930  return 2 + (getIntWidth(CharTy) << 3);
5931  case BuiltinType::Short:
5932  case BuiltinType::UShort:
5933  return 3 + (getIntWidth(ShortTy) << 3);
5934  case BuiltinType::Int:
5935  case BuiltinType::UInt:
5936  return 4 + (getIntWidth(IntTy) << 3);
5937  case BuiltinType::Long:
5938  case BuiltinType::ULong:
5939  return 5 + (getIntWidth(LongTy) << 3);
5940  case BuiltinType::LongLong:
5941  case BuiltinType::ULongLong:
5942  return 6 + (getIntWidth(LongLongTy) << 3);
5943  case BuiltinType::Int128:
5944  case BuiltinType::UInt128:
5945  return 7 + (getIntWidth(Int128Ty) << 3);
5946  }
5947 }
5948 
5949 /// Whether this is a promotable bitfield reference according
5950 /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
5951 ///
5952 /// \returns the type this bit-field will promote to, or NULL if no
5953 /// promotion occurs.
5955  if (E->isTypeDependent() || E->isValueDependent())
5956  return {};
5957 
5958  // C++ [conv.prom]p5:
5959  // If the bit-field has an enumerated type, it is treated as any other
5960  // value of that type for promotion purposes.
5961  if (getLangOpts().CPlusPlus && E->getType()->isEnumeralType())
5962  return {};
5963 
5964  // FIXME: We should not do this unless E->refersToBitField() is true. This
5965  // matters in C where getSourceBitField() will find bit-fields for various
5966  // cases where the source expression is not a bit-field designator.
5967 
5968  FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
5969  if (!Field)
5970  return {};
5971 
5972  QualType FT = Field->getType();
5973 
5974  uint64_t BitWidth = Field->getBitWidthValue(*this);
5975  uint64_t IntSize = getTypeSize(IntTy);
5976  // C++ [conv.prom]p5:
5977  // A prvalue for an integral bit-field can be converted to a prvalue of type
5978  // int if int can represent all the values of the bit-field; otherwise, it
5979  // can be converted to unsigned int if unsigned int can represent all the
5980  // values of the bit-field. If the bit-field is larger yet, no integral
5981  // promotion applies to it.
5982  // C11 6.3.1.1/2:
5983  // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
5984  // If an int can represent all values of the original type (as restricted by
5985  // the width, for a bit-field), the value is converted to an int; otherwise,
5986  // it is converted to an unsigned int.
5987  //
5988  // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
5989  // We perform that promotion here to match GCC and C++.
5990  // FIXME: C does not permit promotion of an enum bit-field whose rank is
5991  // greater than that of 'int'. We perform that promotion to match GCC.
5992  if (BitWidth < IntSize)
5993  return IntTy;
5994 
5995  if (BitWidth == IntSize)
5996  return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
5997 
5998  // Bit-fields wider than int are not subject to promotions, and therefore act
5999  // like the base type. GCC has some weird bugs in this area that we
6000  // deliberately do not follow (GCC follows a pre-standard resolution to
6001  // C's DR315 which treats bit-width as being part of the type, and this leaks
6002  // into their semantics in some cases).
6003  return {};
6004 }
6005 
6006 /// getPromotedIntegerType - Returns the type that Promotable will
6007 /// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
6008 /// integer type.
6010  assert(!Promotable.isNull());
6011  assert(Promotable->isPromotableIntegerType());
6012  if (const auto *ET = Promotable->getAs<EnumType>())
6013  return ET->getDecl()->getPromotionType();
6014 
6015  if (const auto *BT = Promotable->getAs<BuiltinType>()) {
6016  // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
6017  // (3.9.1) can be converted to a prvalue of the first of the following
6018  // types that can represent all the values of its underlying type:
6019  // int, unsigned int, long int, unsigned long int, long long int, or
6020  // unsigned long long int [...]
6021  // FIXME: Is there some better way to compute this?
6022  if (BT->getKind() == BuiltinType::WChar_S ||
6023  BT->getKind() == BuiltinType::WChar_U ||
6024  BT->getKind() == BuiltinType::Char8 ||
6025  BT->getKind() == BuiltinType::Char16 ||
6026  BT->getKind() == BuiltinType::Char32) {
6027  bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
6028  uint64_t FromSize = getTypeSize(BT);
6029  QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
6031  for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
6032  uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
6033  if (FromSize < ToSize ||
6034  (FromSize == ToSize &&
6035  FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
6036  return PromoteTypes[Idx];
6037  }
6038  llvm_unreachable("char type should fit into long long");
6039  }
6040  }
6041 
6042  // At this point, we should have a signed or unsigned integer type.
6043  if (Promotable->isSignedIntegerType())
6044  return IntTy;
6045  uint64_t PromotableSize = getIntWidth(Promotable);
6046  uint64_t IntSize = getIntWidth(IntTy);
6047  assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
6048  return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
6049 }
6050 
6051 /// Recurses in pointer/array types until it finds an objc retainable
6052 /// type and returns its ownership.
6054  while (!T.isNull()) {
6056  return T.getObjCLifetime();
6057  if (T->isArrayType())
6058  T = getBaseElementType(T);
6059  else if (const auto *PT = T->getAs<PointerType>())
6060  T = PT->getPointeeType();
6061  else if (const auto *RT = T->getAs<ReferenceType>())
6062  T = RT->getPointeeType();
6063  else
6064  break;
6065  }
6066 
6067  return Qualifiers::OCL_None;
6068 }
6069 
6070 static const Type *getIntegerTypeForEnum(const EnumType *ET) {
6071  // Incomplete enum types are not treated as integer types.
6072  // FIXME: In C++, enum types are never integer types.
6073  if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
6074  return ET->getDecl()->getIntegerType().getTypePtr();
6075  return nullptr;
6076 }
6077 
6078 /// getIntegerTypeOrder - Returns the highest ranked integer type:
6079 /// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
6080 /// LHS < RHS, return -1.
6082  const Type *LHSC = getCanonicalType(LHS).getTypePtr();
6083  const Type *RHSC = getCanonicalType(RHS).getTypePtr();
6084 
6085  // Unwrap enums to their underlying type.
6086  if (const auto *ET = dyn_cast<EnumType>(LHSC))
6087  LHSC = getIntegerTypeForEnum(ET);
6088  if (const auto *ET = dyn_cast<EnumType>(RHSC))
6089  RHSC = getIntegerTypeForEnum(ET);
6090 
6091  if (LHSC == RHSC) return 0;
6092 
6093  bool LHSUnsigned = LHSC->isUnsignedIntegerType();
6094  bool RHSUnsigned = RHSC->isUnsignedIntegerType();
6095 
6096  unsigned LHSRank = getIntegerRank(LHSC);
6097  unsigned RHSRank = getIntegerRank(RHSC);
6098 
6099  if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
6100  if (LHSRank == RHSRank) return 0;
6101  return LHSRank > RHSRank ? 1 : -1;
6102  }
6103 
6104  // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
6105  if (LHSUnsigned) {
6106  // If the unsigned [LHS] type is larger, return it.
6107  if (LHSRank >= RHSRank)
6108  return 1;
6109 
6110  // If the signed type can represent all values of the unsigned type, it
6111  // wins. Because we are dealing with 2's complement and types that are
6112  // powers of two larger than each other, this is always safe.
6113  return -1;
6114  }
6115 
6116  // If the unsigned [RHS] type is larger, return it.
6117  if (RHSRank >= LHSRank)
6118  return -1;
6119 
6120  // If the signed type can represent all values of the unsigned type, it
6121  // wins. Because we are dealing with 2's complement and types that are
6122  // powers of two larger than each other, this is always safe.
6123  return 1;
6124 }
6125 
6127  if (CFConstantStringTypeDecl)
6128  return CFConstantStringTypeDecl;
6129 
6130  assert(!CFConstantStringTagDecl &&
6131  "tag and typedef should be initialized together");
6132  CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
6133  CFConstantStringTagDecl->startDefinition();
6134 
6135  struct {
6136  QualType Type;
6137  const char *Name;
6138  } Fields[5];
6139  unsigned Count = 0;
6140 
6141  /// Objective-C ABI
6142  ///
6143  /// typedef struct __NSConstantString_tag {
6144  /// const int *isa;
6145  /// int flags;
6146  /// const char *str;
6147  /// long length;
6148  /// } __NSConstantString;
6149  ///
6150  /// Swift ABI (4.1, 4.2)
6151  ///
6152  /// typedef struct __NSConstantString_tag {
6153  /// uintptr_t _cfisa;
6154  /// uintptr_t _swift_rc;
6155  /// _Atomic(uint64_t) _cfinfoa;
6156  /// const char *_ptr;
6157  /// uint32_t _length;
6158  /// } __NSConstantString;
6159  ///
6160  /// Swift ABI (5.0)
6161  ///
6162  /// typedef struct __NSConstantString_tag {
6163  /// uintptr_t _cfisa;
6164  /// uintptr_t _swift_rc;
6165  /// _Atomic(uint64_t) _cfinfoa;
6166  /// const char *_ptr;
6167  /// uintptr_t _length;
6168  /// } __NSConstantString;
6169 
6170  const auto CFRuntime = getLangOpts().CFRuntime;
6171  if (static_cast<unsigned>(CFRuntime) <
6172  static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) {
6173  Fields[Count++] = { getPointerType(IntTy.withConst()), "isa" };
6174  Fields[Count++] = { IntTy, "flags" };
6175  Fields[Count++] = { getPointerType(CharTy.withConst()), "str" };
6176  Fields[Count++] = { LongTy, "length" };
6177  } else {
6178  Fields[Count++] = { getUIntPtrType(), "_cfisa" };
6179  Fields[Count++] = { getUIntPtrType(), "_swift_rc" };
6180  Fields[Count++] = { getFromTargetType(Target->getUInt64Type()), "_swift_rc" };
6181  Fields[Count++] = { getPointerType(CharTy.withConst()), "_ptr" };
6182  if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 ||
6184  Fields[Count++] = { IntTy, "_ptr" };
6185  else
6186  Fields[Count++] = { getUIntPtrType(), "_ptr" };
6187  }
6188 
6189  // Create fields
6190  for (unsigned i = 0; i < Count; ++i) {
6191  FieldDecl *Field =
6192  FieldDecl::Create(*this, CFConstantStringTagDecl, SourceLocation(),
6193  SourceLocation(), &Idents.get(Fields[i].Name),
6194  Fields[i].Type, /*TInfo=*/nullptr,
6195  /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
6196  Field->setAccess(AS_public);
6197  CFConstantStringTagDecl->addDecl(Field);
6198  }
6199 
6200  CFConstantStringTagDecl->completeDefinition();
6201  // This type is designed to be compatible with NSConstantString, but cannot
6202  // use the same name, since NSConstantString is an interface.
6203  auto tagType = getTagDeclType(CFConstantStringTagDecl);
6204  CFConstantStringTypeDecl =
6205  buildImplicitTypedef(tagType, "__NSConstantString");
6206 
6207  return CFConstantStringTypeDecl;
6208 }
6209 
6211  if (!CFConstantStringTagDecl)
6212  getCFConstantStringDecl(); // Build the tag and the typedef.
6213  return CFConstantStringTagDecl;
6214 }
6215 
6216 // getCFConstantStringType - Return the type used for constant CFStrings.
6219 }
6220 
6222  if (ObjCSuperType.isNull()) {
6223  RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
6224  TUDecl->addDecl(ObjCSuperTypeDecl);
6225  ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
6226  }
6227  return ObjCSuperType;
6228 }
6229 
6231  const auto *TD = T->castAs<TypedefType>();
6232  CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl());
6233  const auto *TagType =
6234  CFConstantStringTypeDecl->getUnderlyingType()->castAs<RecordType>();
6235  CFConstantStringTagDecl = TagType->getDecl();
6236 }
6237 
6239  if (BlockDescriptorType)
6240  return getTagDeclType(BlockDescriptorType);
6241 
6242  RecordDecl *RD;
6243  // FIXME: Needs the FlagAppleBlock bit.
6244  RD = buildImplicitRecord("__block_descriptor");
6245  RD->startDefinition();
6246 
6247  QualType FieldTypes[] = {
6250  };
6251 
6252  static const char *const FieldNames[] = {
6253  "reserved",
6254  "Size"
6255  };
6256 
6257  for (size_t i = 0; i < 2; ++i) {
6258  FieldDecl *Field = FieldDecl::Create(
6259  *this, RD, SourceLocation(), SourceLocation(),
6260  &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
6261  /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
6262  Field->setAccess(AS_public);
6263  RD->addDecl(Field);
6264  }
6265 
6266  RD->completeDefinition();
6267 
6268  BlockDescriptorType = RD;
6269 
6270  return getTagDeclType(BlockDescriptorType);
6271 }
6272 
6274  if (BlockDescriptorExtendedType)
6275  return getTagDeclType(BlockDescriptorExtendedType);
6276 
6277  RecordDecl *RD;
6278  // FIXME: Needs the FlagAppleBlock bit.
6279  RD = buildImplicitRecord("__block_descriptor_withcopydispose");
6280  RD->startDefinition();
6281 
6282  QualType FieldTypes[] = {
6287  };
6288 
6289  static const char *const FieldNames[] = {
6290  "reserved",
6291  "Size",
6292  "CopyFuncPtr",
6293  "DestroyFuncPtr"
6294  };
6295 
6296  for (size_t i = 0; i < 4; ++i) {
6297  FieldDecl *Field = FieldDecl::Create(
6298  *this, RD, SourceLocation(), SourceLocation(),
6299  &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
6300  /*BitWidth=*/nullptr,
6301  /*Mutable=*/false, ICIS_NoInit);
6302  Field->setAccess(AS_public);
6303  RD->addDecl(Field);
6304  }
6305 
6306  RD->completeDefinition();
6307 
6308  BlockDescriptorExtendedType = RD;
6309  return getTagDeclType(BlockDescriptorExtendedType);
6310 }
6311 
6313  const auto *BT = dyn_cast<BuiltinType>(T);
6314 
6315  if (!BT) {
6316  if (isa<PipeType>(T))
6317  return TargetInfo::OCLTK_Pipe;
6318 
6320  }
6321 
6322  switch (BT->getKind()) {
6323 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6324  case BuiltinType::Id: \
6325  return TargetInfo::OCLTK_Image;
6326 #include "clang/Basic/OpenCLImageTypes.def"
6327 
6328  case BuiltinType::OCLClkEvent:
6330 
6331  case BuiltinType::OCLEvent:
6332  return TargetInfo::OCLTK_Event;
6333 
6334  case BuiltinType::OCLQueue:
6335  return TargetInfo::OCLTK_Queue;
6336 
6337  case BuiltinType::OCLReserveID:
6339 
6340  case BuiltinType::OCLSampler:
6342 
6343  default:
6345  }
6346 }
6347 
6349  return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
6350 }
6351 
6352 /// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
6353 /// requires copy/dispose. Note that this must match the logic
6354 /// in buildByrefHelpers.
6356  const VarDecl *D) {
6357  if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
6358  const Expr *copyExpr = getBlockVarCopyInit(D).getCopyExpr();
6359  if (!copyExpr && record->hasTrivialDestructor()) return false;
6360 
6361  return true;
6362  }
6363 
6364  // The block needs copy/destroy helpers if Ty is non-trivial to destructively
6365  // move or destroy.
6367  return true;
6368 
6369  if (!Ty->isObjCRetainableType()) return false;
6370 
6371  Qualifiers qs = Ty.getQualifiers();
6372 
6373  // If we have lifetime, that dominates.
6374  if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
6375  switch (lifetime) {
6376  case Qualifiers::OCL_None: llvm_unreachable("impossible");
6377 
6378  // These are just bits as far as the runtime is concerned.
6381  return false;
6382 
6383  // These cases should have been taken care of when checking the type's
6384  // non-triviality.
6385  case Qualifiers::OCL_Weak:
6387  llvm_unreachable("impossible");
6388  }
6389  llvm_unreachable("fell out of lifetime switch!");
6390  }
6391  return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
6392  Ty->isObjCObjectPointerType());
6393 }
6394 
6396  Qualifiers::ObjCLifetime &LifeTime,
6397  bool &HasByrefExtendedLayout) const {
6398  if (!getLangOpts().ObjC ||
6399  getLangOpts().getGC() != LangOptions::NonGC)
6400  return false;
6401 
6402  HasByrefExtendedLayout = false;
6403  if (Ty->isRecordType()) {
6404  HasByrefExtendedLayout = true;
6405  LifeTime = Qualifiers::OCL_None;
6406  } else if ((LifeTime = Ty.getObjCLifetime())) {
6407  // Honor the ARC qualifiers.
6408  } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
6409  // The MRR rule.
6410  LifeTime = Qualifiers::OCL_ExplicitNone;
6411  } else {
6412  LifeTime = Qualifiers::OCL_None;
6413  }
6414  return true;
6415 }
6416 
6418  if (!ObjCInstanceTypeDecl)
6419  ObjCInstanceTypeDecl =
6420  buildImplicitTypedef(getObjCIdType(), "instancetype");
6421  return ObjCInstanceTypeDecl;
6422 }
6423 
6424 // This returns true if a type has been typedefed to BOOL:
6425 // typedef <type> BOOL;
6427  if (const auto *TT = dyn_cast<TypedefType>(T))
6428  if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
6429  return II->isStr("BOOL");
6430 
6431  return false;
6432 }
6433 
6434 /// getObjCEncodingTypeSize returns size of type for objective-c encoding
6435 /// purpose.
6437  if (!type->isIncompleteArrayType() && type->isIncompleteType())
6438  return CharUnits::Zero();
6439 
6440  CharUnits sz = getTypeSizeInChars(type);
6441 
6442  // Make all integer and enum types at least as large as an int
6443  if (sz.isPositive() && type->isIntegralOrEnumerationType())
6444  sz = std::max(sz, getTypeSizeInChars(IntTy));
6445  // Treat arrays as pointers, since that's how they're passed in.
6446  else if (type->isArrayType())
6448  return sz;
6449 }
6450 
6452  return getTargetInfo().getCXXABI().isMicrosoft() &&
6453  VD->isStaticDataMember() &&
6455  !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
6456 }
6457 
6460  if (!VD->isInline())
6462 
6463  // In almost all cases, it's a weak definition.
6464  auto *First = VD->getFirstDecl();
6465  if (First->isInlineSpecified() || !First->isStaticDataMember())
6467 
6468  // If there's a file-context declaration in this translation unit, it's a
6469  // non-discardable definition.
6470  for (auto *D : VD->redecls())
6471  if (D->getLexicalDeclContext()->isFileContext() &&
6472  !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr()))
6474 
6475  // If we've not seen one yet, we don't know.
6477 }
6478 
6479 static std::string charUnitsToString(const CharUnits &CU) {
6480  return llvm::itostr(CU.getQuantity());
6481 }
6482 
6483 /// getObjCEncodingForBlock - Return the encoded type for this block
6484 /// declaration.
6486  std::string S;
6487 
6488  const BlockDecl *Decl = Expr->getBlockDecl();
6489  QualType BlockTy =
6490  Expr->getType()->castAs<BlockPointerType>()->getPointeeType();
6491  QualType BlockReturnTy = BlockTy->castAs<FunctionType>()->getReturnType();
6492  // Encode result type.
6493  if (getLangOpts().EncodeExtendedBlockSig)
6495  true /*Extended*/);
6496  else
6497  getObjCEncodingForType(BlockReturnTy, S);
6498  // Compute size of all parameters.
6499  // Start with computing size of a pointer in number of bytes.
6500  // FIXME: There might(should) be a better way of doing this computation!
6502  CharUnits ParmOffset = PtrSize;
6503  for (auto PI : Decl->parameters()) {
6504  QualType PType = PI->getType();
6505  CharUnits sz = getObjCEncodingTypeSize(PType);
6506  if (sz.isZero())
6507  continue;
6508  assert(sz.isPositive() && "BlockExpr - Incomplete param type");
6509  ParmOffset += sz;
6510  }
6511  // Size of the argument frame
6512  S += charUnitsToString(ParmOffset);
6513  // Block pointer and offset.
6514  S += "@?0";
6515 
6516  // Argument types.
6517  ParmOffset = PtrSize;
6518  for (auto PVDecl : Decl->parameters()) {
6519  QualType PType = PVDecl->getOriginalType();
6520  if (const auto *AT =
6521  dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
6522  // Use array's original type only if it has known number of
6523  // elements.
6524  if (!isa<ConstantArrayType>(AT))
6525  PType = PVDecl->getType();
6526  } else if (PType->isFunctionType())
6527  PType = PVDecl->getType();
6528  if (getLangOpts().EncodeExtendedBlockSig)
6530  S, true /*Extended*/);
6531  else
6532  getObjCEncodingForType(PType, S);
6533  S += charUnitsToString(ParmOffset);
6534  ParmOffset += getObjCEncodingTypeSize(PType);
6535  }
6536 
6537  return S;
6538 }
6539 
6540 std::string
6542  std::string S;
6543  // Encode result type.
6545  CharUnits ParmOffset;
6546  // Compute size of all parameters.
6547  for (auto PI : Decl->parameters()) {
6548  QualType PType = PI->getType();
6549  CharUnits sz = getObjCEncodingTypeSize(PType);
6550  if (sz.isZero())
6551  continue;
6552 
6553  assert(sz.isPositive() &&
6554  "getObjCEncodingForFunctionDecl - Incomplete param type");
6555  ParmOffset += sz;
6556  }
6557  S += charUnitsToString(ParmOffset);
6558  ParmOffset = CharUnits::Zero();
6559 
6560  // Argument types.
6561  for (auto PVDecl : Decl->parameters()) {
6562  QualType PType = PVDecl->getOriginalType();
6563  if (const auto *AT =
6564  dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
6565  // Use array's original type only if it has known number of
6566  // elements.
6567  if (!isa<ConstantArrayType>(AT))
6568  PType = PVDecl->getType();
6569  } else if (PType->isFunctionType())
6570  PType = PVDecl->getType();
6571  getObjCEncodingForType(PType, S);
6572  S += charUnitsToString(ParmOffset);
6573  ParmOffset += getObjCEncodingTypeSize(PType);
6574  }
6575 
6576  return S;
6577 }
6578 
6579 /// getObjCEncodingForMethodParameter - Return the encoded type for a single
6580 /// method parameter or return type. If Extended, include class names and
6581 /// block object types.
6583  QualType T, std::string& S,
6584  bool Extended) const {
6585  // Encode type qualifer, 'in', 'inout', etc. for the parameter.
6587  // Encode parameter type.
6588  ObjCEncOptions Options = ObjCEncOptions()
6589  .setExpandPointedToStructures()
6590  .setExpandStructures()
6591  .setIsOutermostType();
6592  if (Extended)
6593  Options.setEncodeBlockParameters().setEncodeClassNames();
6594  getObjCEncodingForTypeImpl(T, S, Options, /*Field=*/nullptr);
6595 }
6596 
6597 /// getObjCEncodingForMethodDecl - Return the encoded type for this method
6598 /// declaration.
6600  bool Extended) const {
6601  // FIXME: This is not very efficient.
6602  // Encode return type.
6603  std::string S;
6605  Decl->getReturnType(), S, Extended);
6606  // Compute size of all parameters.
6607  // Start with computing size of a pointer in number of bytes.
6608  // FIXME: There might(should) be a better way of doing this computation!
6610  // The first two arguments (self and _cmd) are pointers; account for
6611  // their size.
6612  CharUnits ParmOffset = 2 * PtrSize;
6614  E = Decl->sel_param_end(); PI != E; ++PI) {
6615  QualType PType = (*PI)->getType();
6616  CharUnits sz = getObjCEncodingTypeSize(PType);
6617  if (sz.isZero())
6618  continue;
6619 
6620  assert(sz.isPositive() &&
6621  "getObjCEncodingForMethodDecl - Incomplete param type");
6622  ParmOffset += sz;
6623  }
6624  S += charUnitsToString(ParmOffset);
6625  S += "@0:";
6626  S += charUnitsToString(PtrSize);
6627 
6628  // Argument types.
6629  ParmOffset = 2 * PtrSize;
6631  E = Decl->sel_param_end(); PI != E; ++PI) {
6632  const ParmVarDecl *PVDecl = *PI;
6633  QualType PType = PVDecl->getOriginalType();
6634  if (const auto *AT =
6635  dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
6636  // Use array's original type only if it has known number of
6637  // elements.
6638  if (!isa<ConstantArrayType>(AT))
6639  PType = PVDecl->getType();
6640  } else if (PType->isFunctionType())
6641  PType = PVDecl->getType();
6643  PType, S, Extended);
6644  S += charUnitsToString(ParmOffset);
6645  ParmOffset += getObjCEncodingTypeSize(PType);
6646  }
6647 
6648  return S;
6649 }
6650 
6653  const ObjCPropertyDecl *PD,
6654  const Decl *Container) const {
6655  if (!Container)
6656  return nullptr;
6657  if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) {
6658  for (auto *PID : CID->property_impls())
6659  if (PID->getPropertyDecl() == PD)
6660  return PID;
6661  } else {
6662  const auto *OID = cast<ObjCImplementationDecl>(Container);
6663  for (auto *PID : OID->property_impls())
6664  if (PID->getPropertyDecl() == PD)
6665  return PID;
6666  }
6667  return nullptr;
6668 }
6669 
6670 /// getObjCEncodingForPropertyDecl - Return the encoded type for this
6671 /// property declaration. If non-NULL, Container must be either an
6672 /// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
6673 /// NULL when getting encodings for protocol properties.
6674 /// Property attributes are stored as a comma-delimited C string. The simple
6675 /// attributes readonly and bycopy are encoded as single characters. The
6676 /// parametrized attributes, getter=name, setter=name, and ivar=name, are
6677 /// encoded as single characters, followed by an identifier. Property types
6678 /// are also encoded as a parametrized attribute. The characters used to encode
6679 /// these attributes are defined by the following enumeration:
6680 /// @code
6681 /// enum PropertyAttributes {
6682 /// kPropertyReadOnly = 'R', // property is read-only.
6683 /// kPropertyBycopy = 'C', // property is a copy of the value last assigned
6684 /// kPropertyByref = '&', // property is a reference to the value last assigned
6685 /// kPropertyDynamic = 'D', // property is dynamic
6686 /// kPropertyGetter = 'G', // followed by getter selector name
6687 /// kPropertySetter = 'S', // followed by setter selector name
6688 /// kPropertyInstanceVariable = 'V' // followed by instance variable name
6689 /// kPropertyType = 'T' // followed by old-style type encoding.
6690 /// kPropertyWeak = 'W' // 'weak' property
6691 /// kPropertyStrong = 'P' // property GC'able
6692 /// kPropertyNonAtomic = 'N' // property non-atomic
6693 /// };
6694 /// @endcode
6695 std::string
6697  const Decl *Container) const {
6698  // Collect information from the property implementation decl(s).
6699  bool Dynamic = false;
6700  ObjCPropertyImplDecl *SynthesizePID = nullptr;
6701 
6702  if (ObjCPropertyImplDecl *PropertyImpDecl =
6703  getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
6704  if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
6705  Dynamic = true;
6706  else
6707  SynthesizePID = PropertyImpDecl;
6708  }
6709 
6710  // FIXME: This is not very efficient.
6711  std::string S = "T";
6712 
6713  // Encode result type.
6714  // GCC has some special rules regarding encoding of properties which
6715  // closely resembles encoding of ivars.
6717 
6718  if (PD->isReadOnly()) {
6719  S += ",R";
6721  S += ",C";
6723  S += ",&";
6725  S += ",W";
6726  } else {
6727  switch (PD->getSetterKind()) {
6728  case ObjCPropertyDecl::Assign: break;
6729  case ObjCPropertyDecl::Copy: S += ",C"; break;
6730  case ObjCPropertyDecl::Retain: S += ",&"; break;
6731  case ObjCPropertyDecl::Weak: S += ",W"; break;
6732  }
6733  }
6734 
6735  // It really isn't clear at all what this means, since properties
6736  // are "dynamic by default".
6737  if (Dynamic)
6738  S += ",D";
6739 
6741  S += ",N";
6742 
6744  S += ",G";
6745  S += PD->getGetterName().getAsString();
6746  }
6747 
6749  S += ",S";
6750  S += PD->getSetterName().getAsString();
6751  }
6752 
6753  if (SynthesizePID) {
6754  const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
6755  S += ",V";
6756  S += OID->getNameAsString();
6757  }
6758 
6759  // FIXME: OBJCGC: weak & strong
6760  return S;
6761 }
6762 
6763 /// getLegacyIntegralTypeEncoding -
6764 /// Another legacy compatibility encoding: 32-bit longs are encoded as
6765 /// 'l' or 'L' , but not always. For typedefs, we need to use
6766 /// 'i' or 'I' instead if encoding a struct field, or a pointer!
6768  if (isa<TypedefType>(PointeeTy.getTypePtr())) {
6769  if (const auto *BT = PointeeTy->getAs<BuiltinType>()) {
6770  if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
6771  PointeeTy = UnsignedIntTy;
6772  else
6773  if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
6774  PointeeTy = IntTy;
6775  }
6776  }
6777 }
6778 
6780  const FieldDecl *Field,
6781  QualType *NotEncodedT) const {
6782  // We follow the behavior of gcc, expanding structures which are
6783  // directly pointed to, and expanding embedded structures. Note that
6784  // these rules are sufficient to prevent recursive encoding of the
6785  // same type.
6786  getObjCEncodingForTypeImpl(T, S,
6787  ObjCEncOptions()
6788  .setExpandPointedToStructures()
6789  .setExpandStructures()
6790  .setIsOutermostType(),
6791  Field, NotEncodedT);
6792 }
6793 
6795  std::string& S) const {
6796  // Encode result type.
6797  // GCC has some special rules regarding encoding of properties which
6798  // closely resembles encoding of ivars.
6799  getObjCEncodingForTypeImpl(T, S,
6800  ObjCEncOptions()
6801  .setExpandPointedToStructures()
6802  .setExpandStructures()
6803  .setIsOutermostType()
6804  .setEncodingProperty(),
6805  /*Field=*/nullptr);
6806 }
6807 
6809  const BuiltinType *BT) {
6810  BuiltinType::Kind kind = BT->getKind();
6811  switch (kind) {
6812  case BuiltinType::Void: return 'v';
6813  case BuiltinType::Bool: return 'B';
6814  case BuiltinType::Char8:
6815  case BuiltinType::Char_U:
6816  case BuiltinType::UChar: return 'C';
6817  case BuiltinType::Char16:
6818  case BuiltinType::UShort: return 'S';
6819  case BuiltinType::Char32:
6820  case BuiltinType::UInt: return 'I';
6821  case BuiltinType::ULong:
6822  return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
6823  case BuiltinType::UInt128: return 'T';
6824  case BuiltinType::ULongLong: return 'Q';
6825  case BuiltinType::Char_S:
6826  case BuiltinType::SChar: return 'c';
6827  case BuiltinType::Short: return 's';
6828  case BuiltinType::WChar_S:
6829  case BuiltinType::WChar_U:
6830  case BuiltinType::Int: return 'i';
6831  case BuiltinType::Long:
6832  return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
6833  case BuiltinType::LongLong: return 'q';
6834  case BuiltinType::Int128: return 't';
6835  case BuiltinType::Float: return 'f';
6836  case BuiltinType::Double: return 'd';
6837  case BuiltinType::LongDouble: return 'D';
6838  case BuiltinType::NullPtr: return '*'; // like char*
6839 
6840  case BuiltinType::Float16:
6841  case BuiltinType::Float128:
6842  case BuiltinType::Half:
6843  case BuiltinType::ShortAccum:
6844  case BuiltinType::Accum:
6845  case BuiltinType::LongAccum:
6846  case BuiltinType::UShortAccum:
6847  case BuiltinType::UAccum:
6848  case BuiltinType::ULongAccum:
6849  case BuiltinType::ShortFract:
6850  case BuiltinType::Fract:
6851  case BuiltinType::LongFract:
6852  case BuiltinType::UShortFract:
6853  case BuiltinType::UFract:
6854  case BuiltinType::ULongFract:
6855  case BuiltinType::SatShortAccum:
6856  case BuiltinType::SatAccum:
6857  case BuiltinType::SatLongAccum:
6858  case BuiltinType::SatUShortAccum:
6859  case BuiltinType::SatUAccum:
6860  case BuiltinType::SatULongAccum:
6861  case BuiltinType::SatShortFract:
6862  case BuiltinType::SatFract:
6863  case BuiltinType::SatLongFract:
6864  case BuiltinType::SatUShortFract:
6865  case BuiltinType::SatUFract:
6866  case BuiltinType::SatULongFract:
6867  // FIXME: potentially need @encodes for these!
6868  return ' ';
6869 
6870 #define SVE_TYPE(Name, Id, SingletonId) \
6871  case BuiltinType::Id:
6872 #include "clang/Basic/AArch64SVEACLETypes.def"
6873  {
6874  DiagnosticsEngine &Diags = C->getDiagnostics();
6875  unsigned DiagID = Diags.getCustomDiagID(
6876  DiagnosticsEngine::Error, "cannot yet @encode type %0");
6877  Diags.Report(DiagID) << BT->getName(C->getPrintingPolicy());
6878  return ' ';
6879  }
6880 
6881  case BuiltinType::ObjCId:
6882  case BuiltinType::ObjCClass:
6883  case BuiltinType::ObjCSel:
6884  llvm_unreachable("@encoding ObjC primitive type");
6885 
6886  // OpenCL and placeholder types don't need @encodings.
6887 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6888  case BuiltinType::Id:
6889 #include "clang/Basic/OpenCLImageTypes.def"
6890 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6891  case BuiltinType::Id:
6892 #include "clang/Basic/OpenCLExtensionTypes.def"
6893  case BuiltinType::OCLEvent:
6894  case BuiltinType::OCLClkEvent:
6895  case BuiltinType::OCLQueue:
6896  case BuiltinType::OCLReserveID:
6897  case BuiltinType::OCLSampler:
6898  case BuiltinType::Dependent:
6899 #define BUILTIN_TYPE(KIND, ID)
6900 #define PLACEHOLDER_TYPE(KIND, ID) \
6901  case BuiltinType::KIND:
6902 #include "clang/AST/BuiltinTypes.def"
6903  llvm_unreachable("invalid builtin type for @encode");
6904  }
6905  llvm_unreachable("invalid BuiltinType::Kind value");
6906 }
6907 
6908 static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
6909  EnumDecl *Enum = ET->getDecl();
6910 
6911  // The encoding of an non-fixed enum type is always 'i', regardless of size.
6912  if (!Enum->isFixed())
6913  return 'i';
6914 
6915  // The encoding of a fixed enum type matches its fixed underlying type.
6916  const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>();
6917  return getObjCEncodingForPrimitiveType(C, BT);
6918 }
6919 
6920 static void EncodeBitField(const ASTContext *Ctx, std::string& S,
6921  QualType T, const FieldDecl *FD) {
6922  assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
6923  S += 'b';
6924  // The NeXT runtime encodes bit fields as b followed by the number of bits.
6925  // The GNU runtime requires more information; bitfields are encoded as b,
6926  // then the offset (in bits) of the first element, then the type of the
6927  // bitfield, then the size in bits. For example, in this structure:
6928  //
6929  // struct
6930  // {
6931  // int integer;
6932  // int flags:2;
6933  // };
6934  // On a 32-bit system, the encoding for flags would be b2 for the NeXT
6935  // runtime, but b32i2 for the GNU runtime. The reason for this extra
6936  // information is not especially sensible, but we're stuck with it for
6937  // compatibility with GCC, although providing it breaks anything that
6938  // actually uses runtime introspection and wants to work on both runtimes...
6939  if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
6940  uint64_t Offset;
6941 
6942  if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) {
6943  Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), nullptr,
6944  IVD);
6945  } else {
6946  const RecordDecl *RD = FD->getParent();
6947  const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
6948  Offset = RL.getFieldOffset(FD->getFieldIndex());
6949  }
6950 
6951  S += llvm::utostr(Offset);
6952 
6953  if (const auto *ET = T->getAs<EnumType>())
6954  S += ObjCEncodingForEnumType(Ctx, ET);
6955  else {
6956  const auto *BT = T->castAs<BuiltinType>();
6957  S += getObjCEncodingForPrimitiveType(Ctx, BT);
6958  }
6959  }
6960  S += llvm::utostr(FD->getBitWidthValue(*Ctx));
6961 }
6962 
6963 // FIXME: Use SmallString for accumulating string.
6964 void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S,
6965  const ObjCEncOptions Options,
6966  const FieldDecl *FD,
6967  QualType *NotEncodedT) const {
6968  CanQualType CT = getCanonicalType(T);
6969  switch (CT->getTypeClass()) {
6970  case Type::Builtin:
6971  case Type::Enum:
6972  if (FD && FD->isBitField())
6973  return EncodeBitField(this, S, T, FD);
6974  if (const auto *BT = dyn_cast<BuiltinType>(CT))
6975  S += getObjCEncodingForPrimitiveType(this, BT);
6976  else
6977  S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
6978  return;
6979 
6980  case Type::Complex:
6981  S += 'j';
6982  getObjCEncodingForTypeImpl(T->castAs<ComplexType>()->getElementType(), S,
6983  ObjCEncOptions(),
6984  /*Field=*/nullptr);
6985  return;
6986 
6987  case Type::Atomic:
6988  S += 'A';
6989  getObjCEncodingForTypeImpl(T->castAs<AtomicType>()->getValueType(), S,
6990  ObjCEncOptions(),
6991  /*Field=*/nullptr);
6992  return;
6993 
6994  // encoding for pointer or reference types.
6995  case Type::Pointer:
6996  case Type::LValueReference:
6997  case Type::RValueReference: {
6998  QualType PointeeTy;
6999  if (isa<PointerType>(CT)) {
7000  const auto *PT = T->castAs<PointerType>();
7001  if (PT->isObjCSelType()) {
7002  S += ':';
7003  return;
7004  }
7005  PointeeTy = PT->getPointeeType();
7006  } else {
7007  PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
7008  }
7009 
7010  bool isReadOnly = false;
7011  // For historical/compatibility reasons, the read-only qualifier of the
7012  // pointee gets emitted _before_ the '^'. The read-only qualifier of
7013  // the pointer itself gets ignored, _unless_ we are looking at a typedef!
7014  // Also, do not emit the 'r' for anything but the outermost type!
7015  if (isa<TypedefType>(T.getTypePtr())) {
7016  if (Options.IsOutermostType() && T.isConstQualified()) {
7017  isReadOnly = true;
7018  S += 'r';
7019  }
7020  } else if (Options.IsOutermostType()) {
7021  QualType P = PointeeTy;
7022  while (auto PT = P->getAs<PointerType>())
7023  P = PT->getPointeeType();
7024  if (P.isConstQualified()) {
7025  isReadOnly = true;
7026  S += 'r';
7027  }
7028  }
7029  if (isReadOnly) {
7030  // Another legacy compatibility encoding. Some ObjC qualifier and type
7031  // combinations need to be rearranged.
7032  // Rewrite "in const" from "nr" to "rn"
7033  if (StringRef(S).endswith("nr"))
7034  S.replace(S.end()-2, S.end(), "rn");
7035  }
7036 
7037  if (PointeeTy->isCharType()) {
7038  // char pointer types should be encoded as '*' unless it is a
7039  // type that has been typedef'd to 'BOOL'.
7040  if (!isTypeTypedefedAsBOOL(PointeeTy)) {
7041  S += '*';
7042  return;
7043  }
7044  } else if (const auto *RTy = PointeeTy->getAs<RecordType>()) {
7045  // GCC binary compat: Need to convert "struct objc_class *" to "#".
7046  if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
7047  S += '#';
7048  return;
7049  }
7050  // GCC binary compat: Need to convert "struct objc_object *" to "@".
7051  if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
7052  S += '@';
7053  return;
7054  }
7055  // fall through...
7056  }
7057  S += '^';
7058  getLegacyIntegralTypeEncoding(PointeeTy);
7059 
7060  ObjCEncOptions NewOptions;
7061  if (Options.ExpandPointedToStructures())
7062  NewOptions.setExpandStructures();
7063  getObjCEncodingForTypeImpl(PointeeTy, S, NewOptions,
7064  /*Field=*/nullptr, NotEncodedT);
7065  return;
7066  }
7067 
7068  case Type::ConstantArray:
7069  case Type::IncompleteArray:
7070  case Type::VariableArray: {
7071  const auto *AT = cast<ArrayType>(CT);
7072 
7073  if (isa<IncompleteArrayType>(AT) && !Options.IsStructField()) {
7074  // Incomplete arrays are encoded as a pointer to the array element.
7075  S += '^';
7076 
7077  getObjCEncodingForTypeImpl(
7078  AT->getElementType(), S,
7079  Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD);
7080  } else {
7081  S += '[';
7082 
7083  if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
7084  S += llvm::utostr(CAT->getSize().getZExtValue());
7085  else {
7086  //Variable length arrays are encoded as a regular array with 0 elements.
7087  assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
7088  "Unknown array type!");
7089  S += '0';
7090  }
7091 
7092  getObjCEncodingForTypeImpl(
7093  AT->getElementType(), S,
7094  Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD,
7095  NotEncodedT);
7096  S += ']';
7097  }
7098  return;
7099  }
7100 
7101  case Type::FunctionNoProto:
7102  case Type::FunctionProto:
7103  S += '?';
7104  return;
7105 
7106  case Type::Record: {
7107  RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
7108  S += RDecl->isUnion() ? '(' : '{';
7109  // Anonymous structures print as '?'
7110  if (const IdentifierInfo *II = RDecl->getIdentifier()) {
7111  S += II->getName();
7112  if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
7113  const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
7114  llvm::raw_string_ostream OS(S);
7115  printTemplateArgumentList(OS, TemplateArgs.asArray(),
7116  getPrintingPolicy());
7117  }
7118  } else {
7119  S += '?';
7120  }
7121  if (Options.ExpandStructures()) {
7122  S += '=';
7123  if (!RDecl->isUnion()) {
7124  getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
7125  } else {
7126  for (const auto *Field : RDecl->fields()) {
7127  if (FD) {
7128  S += '"';
7129  S += Field->getNameAsString();
7130  S += '"';
7131  }
7132 
7133  // Special case bit-fields.
7134  if (Field->isBitField()) {
7135  getObjCEncodingForTypeImpl(Field->getType(), S,
7136  ObjCEncOptions().setExpandStructures(),
7137  Field);
7138  } else {
7139  QualType qt = Field->getType();
7141  getObjCEncodingForTypeImpl(
7142  qt, S,
7143  ObjCEncOptions().setExpandStructures().setIsStructField(), FD,
7144  NotEncodedT);
7145  }
7146  }
7147  }
7148  }
7149  S += RDecl->isUnion() ? ')' : '}';
7150  return;
7151  }
7152 
7153  case Type::BlockPointer: {
7154  const auto *BT = T->castAs<BlockPointerType>();
7155  S += "@?"; // Unlike a pointer-to-function, which is "^?".
7156  if (Options.EncodeBlockParameters()) {
7157  const auto *FT = BT->getPointeeType()->castAs<FunctionType>();
7158 
7159  S += '<';
7160  // Block return type
7161  getObjCEncodingForTypeImpl(FT->getReturnType(), S,
7162  Options.forComponentType(), FD, NotEncodedT);
7163  // Block self
7164  S += "@?";
7165  // Block parameters
7166  if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) {
7167  for (const auto &I : FPT->param_types())
7168  getObjCEncodingForTypeImpl(I, S, Options.forComponentType(), FD,
7169  NotEncodedT);
7170  }
7171  S += '>';
7172  }
7173  return;
7174  }
7175 
7176  case Type::ObjCObject: {
7177  // hack to match legacy encoding of *id and *Class
7179  if (Ty->isObjCIdType()) {
7180  S += "{objc_object=}";
7181  return;
7182  }
7183  else if (Ty->isObjCClassType()) {
7184  S += "{objc_class=}";
7185  return;
7186  }
7187  // TODO: Double check to make sure this intentionally falls through.
7188  LLVM_FALLTHROUGH;
7189  }
7190 
7191  case Type::ObjCInterface: {
7192  // Ignore protocol qualifiers when mangling at this level.
7193  // @encode(class_name)
7194  ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
7195  S += '{';
7196  S += OI->getObjCRuntimeNameAsString();
7197  if (Options.ExpandStructures()) {
7198  S += '=';
7200  DeepCollectObjCIvars(OI, true, Ivars);
7201  for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
7202  const FieldDecl *Field = Ivars[i];
7203  if (Field->isBitField())
7204  getObjCEncodingForTypeImpl(Field->getType(), S,
7205  ObjCEncOptions().setExpandStructures(),
7206  Field);
7207  else
7208  getObjCEncodingForTypeImpl(Field->getType(), S,
7209  ObjCEncOptions().setExpandStructures(), FD,
7210  NotEncodedT);
7211  }
7212  }
7213  S += '}';
7214  return;
7215  }
7216 
7217  case Type::ObjCObjectPointer: {
7218  const auto *OPT = T->castAs<ObjCObjectPointerType>();
7219  if (OPT->isObjCIdType()) {
7220  S += '@';
7221  return;
7222  }
7223 
7224  if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
7225  // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
7226  // Since this is a binary compatibility issue, need to consult with
7227  // runtime folks. Fortunately, this is a *very* obscure construct.
7228  S += '#';
7229  return;
7230  }
7231 
7232  if (OPT->isObjCQualifiedIdType()) {
7233  getObjCEncodingForTypeImpl(
7234  getObjCIdType(), S,
7235  Options.keepingOnly(ObjCEncOptions()
7236  .setExpandPointedToStructures()
7237  .setExpandStructures()),
7238  FD);
7239  if (FD || Options.EncodingProperty() || Options.EncodeClassNames()) {
7240  // Note that we do extended encoding of protocol qualifer list
7241  // Only when doing ivar or property encoding.
7242  S += '"';
7243  for (const auto *I : OPT->quals()) {
7244  S += '<';
7245  S += I->getObjCRuntimeNameAsString();
7246  S += '>';
7247  }
7248  S += '"';
7249  }
7250  return;
7251  }
7252 
7253  S += '@';
7254  if (OPT->getInterfaceDecl() &&
7255  (FD || Options.EncodingProperty() || Options.EncodeClassNames())) {
7256  S += '"';
7258  for (const auto *I : OPT->quals()) {
7259  S += '<';
7260  S += I->getObjCRuntimeNameAsString();
7261  S += '>';
7262  }
7263  S += '"';
7264  }
7265  return;
7266  }
7267 
7268  // gcc just blithely ignores member pointers.
7269  // FIXME: we should do better than that. 'M' is available.
7270  case Type::MemberPointer:
7271  // This matches gcc's encoding, even though technically it is insufficient.
7272  //FIXME. We should do a better job than gcc.
7273  case Type::Vector:
7274  case Type::ExtVector:
7275  // Until we have a coherent encoding of these three types, issue warning.
7276  if (NotEncodedT)
7277  *NotEncodedT = T;
7278  return;
7279 
7280  // We could see an undeduced auto type here during error recovery.
7281  // Just ignore it.
7282  case Type::Auto:
7283  case Type::DeducedTemplateSpecialization:
7284  return;
7285 
7286  case Type::Pipe:
7287 #define ABSTRACT_TYPE(KIND, BASE)
7288 #define TYPE(KIND, BASE)
7289 #define DEPENDENT_TYPE(KIND, BASE) \
7290  case Type::KIND:
7291 #define NON_CANONICAL_TYPE(KIND, BASE) \
7292  case Type::KIND:
7293 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
7294  case Type::KIND:
7295 #include "clang/AST/TypeNodes.inc"
7296  llvm_unreachable("@encode for dependent type!");
7297  }
7298  llvm_unreachable("bad type kind!");
7299 }
7300 
7301 void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
7302  std::string &S,
7303  const FieldDecl *FD,
7304  bool includeVBases,
7305  QualType *NotEncodedT) const {
7306  assert(RDecl && "Expected non-null RecordDecl");
7307  assert(!RDecl->isUnion() && "Should not be called for unions");
7308  if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
7309  return;
7310 
7311  const auto *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
7312  std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
7313  const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
7314 
7315  if (CXXRec) {
7316  for (const auto &BI : CXXRec->bases()) {
7317  if (!BI.isVirtual()) {
7318  CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
7319  if (base->isEmpty())
7320  continue;
7321  uint64_t offs = toBits(layout.getBaseClassOffset(base));
7322  FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
7323  std::make_pair(offs, base));
7324  }
7325  }
7326  }
7327 
7328  unsigned i = 0;
7329  for (auto *Field : RDecl->fields()) {
7330  uint64_t offs = layout.getFieldOffset(i);
7331  FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
7332  std::make_pair(offs, Field));
7333  ++i;
7334  }
7335 
7336  if (CXXRec && includeVBases) {
7337  for (const auto &BI : CXXRec->vbases()) {
7338  CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
7339  if (base->isEmpty())
7340  continue;
7341  uint64_t offs = toBits(layout.getVBaseClassOffset(base));
7342  if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
7343  FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
7344  FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
7345  std::make_pair(offs, base));
7346  }
7347  }
7348 
7349  CharUnits size;
7350  if (CXXRec) {
7351  size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
7352  } else {
7353  size = layout.getSize();
7354  }
7355 
7356 #ifndef NDEBUG
7357  uint64_t CurOffs = 0;
7358 #endif
7359  std::multimap<uint64_t, NamedDecl *>::iterator
7360  CurLayObj = FieldOrBaseOffsets.begin();
7361 
7362  if (CXXRec && CXXRec->isDynamicClass() &&
7363  (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
7364  if (FD) {
7365  S += "\"_vptr$";
7366  std::string recname = CXXRec->getNameAsString();
7367  if (recname.empty()) recname = "?";
7368  S += recname;
7369  S += '"';
7370  }
7371  S += "^^?";
7372 #ifndef NDEBUG
7373  CurOffs += getTypeSize(VoidPtrTy);
7374 #endif
7375  }
7376 
7377  if (!RDecl->hasFlexibleArrayMember()) {
7378  // Mark the end of the structure.
7379  uint64_t offs = toBits(size);
7380  FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
7381  std::make_pair(offs, nullptr));
7382  }
7383 
7384  for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
7385 #ifndef NDEBUG
7386  assert(CurOffs <= CurLayObj->first);
7387  if (CurOffs < CurLayObj->first) {
7388  uint64_t padding = CurLayObj->first - CurOffs;
7389  // FIXME: There doesn't seem to be a way to indicate in the encoding that
7390  // packing/alignment of members is different that normal, in which case
7391  // the encoding will be out-of-sync with the real layout.
7392  // If the runtime switches to just consider the size of types without
7393  // taking into account alignment, we could make padding explicit in the
7394  // encoding (e.g. using arrays of chars). The encoding strings would be
7395  // longer then though.
7396  CurOffs += padding;
7397  }
7398 #endif
7399 
7400  NamedDecl *dcl = CurLayObj->second;
7401  if (!dcl)
7402  break; // reached end of structure.
7403 
7404  if (auto *base = dyn_cast<CXXRecordDecl>(dcl)) {
7405  // We expand the bases without their virtual bases since those are going
7406  // in the initial structure. Note that this differs from gcc which
7407  // expands virtual bases each time one is encountered in the hierarchy,
7408  // making the encoding type bigger than it really is.
7409  getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
7410  NotEncodedT);
7411  assert(!base->isEmpty());
7412 #ifndef NDEBUG
7413  CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
7414 #endif
7415  } else {
7416  const auto *field = cast<FieldDecl>(dcl);
7417  if (FD) {
7418  S += '"';
7419  S += field->getNameAsString();
7420  S += '"';
7421  }
7422 
7423  if (field->isBitField()) {
7424  EncodeBitField(this, S, field->getType(), field);
7425 #ifndef NDEBUG
7426  CurOffs += field->getBitWidthValue(*this);
7427 #endif
7428  } else {
7429  QualType qt = field->getType();
7431  getObjCEncodingForTypeImpl(
7432  qt, S, ObjCEncOptions().setExpandStructures().setIsStructField(),
7433  FD, NotEncodedT);
7434 #ifndef NDEBUG
7435  CurOffs += getTypeSize(field->getType());
7436 #endif
7437  }
7438  }
7439  }
7440 }
7441 
7443  std::string& S) const {
7444  if (QT & Decl::OBJC_TQ_In)
7445  S += 'n';
7446  if (QT & Decl::OBJC_TQ_Inout)
7447  S += 'N';
7448  if (QT & Decl::OBJC_TQ_Out)
7449  S += 'o';
7450  if (QT & Decl::OBJC_TQ_Bycopy)
7451  S += 'O';
7452  if (QT & Decl::OBJC_TQ_Byref)
7453  S += 'R';
7454  if (QT & Decl::OBJC_TQ_Oneway)
7455  S += 'V';
7456 }
7457 
7459  if (!ObjCIdDecl) {
7461  T = getObjCObjectPointerType(T);
7462  ObjCIdDecl = buildImplicitTypedef(T, "id");
7463  }
7464  return ObjCIdDecl;
7465 }
7466 
7468  if (!ObjCSelDecl) {
7470  ObjCSelDecl = buildImplicitTypedef(T, "SEL");
7471  }
7472  return ObjCSelDecl;
7473 }
7474 
7476  if (!ObjCClassDecl) {
7478  T = getObjCObjectPointerType(T);
7479  ObjCClassDecl = buildImplicitTypedef(T, "Class");
7480  }
7481  return ObjCClassDecl;
7482 }
7483 
7485  if (!ObjCProtocolClassDecl) {
7486  ObjCProtocolClassDecl
7488  SourceLocation(),
7489  &Idents.get("Protocol"),
7490  /*typeParamList=*/nullptr,
7491  /*PrevDecl=*/nullptr,
7492  SourceLocation(), true);
7493  }
7494 
7495  return ObjCProtocolClassDecl;
7496 }
7497 
7498 //===----------------------------------------------------------------------===//
7499 // __builtin_va_list Construction Functions
7500 //===----------------------------------------------------------------------===//
7501 
7503  StringRef Name) {
7504  // typedef char* __builtin[_ms]_va_list;
7505  QualType T = Context->getPointerType(Context->CharTy);
7506  return Context->buildImplicitTypedef(T, Name);
7507 }
7508 
7509 static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
7510  return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
7511 }
7512 
7514  return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
7515 }
7516 
7518  // typedef void* __builtin_va_list;
7519  QualType T = Context->getPointerType(Context->VoidTy);
7520  return Context->buildImplicitTypedef(T, "__builtin_va_list");
7521 }
7522 
7523 static TypedefDecl *
7525  // struct __va_list
7526  RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
7527  if (Context->getLangOpts().CPlusPlus) {
7528  // namespace std { struct __va_list {
7529  NamespaceDecl *NS;
7530  NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
7531  Context->getTranslationUnitDecl(),
7532  /*Inline*/ false, SourceLocation(),
7533  SourceLocation(), &Context->Idents.get("std"),
7534  /*PrevDecl*/ nullptr);
7535  NS->setImplicit();
7536  VaListTagDecl->setDeclContext(NS);
7537  }
7538 
7539  VaListTagDecl->startDefinition();
7540 
7541  const size_t NumFields = 5;
7542  QualType FieldTypes[NumFields];
7543  const char *FieldNames[NumFields];
7544 
7545  // void *__stack;
7546  FieldTypes[0] = Context->getPointerType(Context->VoidTy);
7547  FieldNames[0] = "__stack";
7548 
7549  // void *__gr_top;
7550  FieldTypes[1] = Context->getPointerType(Context->VoidTy);
7551  FieldNames[1] = "__gr_top";
7552 
7553  // void *__vr_top;
7554  FieldTypes[2] = Context->getPointerType(Context->VoidTy);
7555  FieldNames[2] = "__vr_top";
7556 
7557  // int __gr_offs;
7558  FieldTypes[3] = Context->IntTy;
7559  FieldNames[3] = "__gr_offs";
7560 
7561  // int __vr_offs;
7562  FieldTypes[4] = Context->IntTy;
7563  FieldNames[4] = "__vr_offs";
7564 
7565  // Create fields
7566  for (unsigned i = 0; i < NumFields; ++i) {
7567  FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7568  VaListTagDecl,
7569  SourceLocation(),
7570  SourceLocation(),
7571  &Context->Idents.get(FieldNames[i]),
7572  FieldTypes[i], /*TInfo=*/nullptr,
7573  /*BitWidth=*/nullptr,
7574  /*Mutable=*/false,
7575  ICIS_NoInit);
7576  Field->setAccess(AS_public);
7577  VaListTagDecl->addDecl(Field);
7578  }
7579  VaListTagDecl->completeDefinition();
7580  Context->VaListTagDecl = VaListTagDecl;
7581  QualType VaListTagType = Context->getRecordType(VaListTagDecl);
7582 
7583  // } __builtin_va_list;
7584  return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
7585 }
7586 
7588  // typedef struct __va_list_tag {
7590 
7591  VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
7592  VaListTagDecl->startDefinition();
7593 
7594  const size_t NumFields = 5;
7595  QualType FieldTypes[NumFields];
7596  const char *FieldNames[NumFields];
7597 
7598  // unsigned char gpr;
7599  FieldTypes[0] = Context->UnsignedCharTy;
7600  FieldNames[0] = "gpr";
7601 
7602  // unsigned char fpr;
7603  FieldTypes[1] = Context->UnsignedCharTy;
7604  FieldNames[1] = "fpr";
7605 
7606  // unsigned short reserved;
7607  FieldTypes[2] = Context->UnsignedShortTy;
7608  FieldNames[2] = "reserved";
7609 
7610  // void* overflow_arg_area;
7611  FieldTypes[3] = Context->getPointerType(Context->VoidTy);
7612  FieldNames[3] = "overflow_arg_area";
7613 
7614  // void* reg_save_area;
7615  FieldTypes[4] = Context->getPointerType(Context->VoidTy);
7616  FieldNames[4] = "reg_save_area";
7617 
7618  // Create fields
7619  for (unsigned i = 0; i < NumFields; ++i) {
7620  FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
7621  SourceLocation(),
7622  SourceLocation(),
7623  &Context->Idents.get(FieldNames[i]),
7624  FieldTypes[i], /*TInfo=*/nullptr,
7625  /*BitWidth=*/nullptr,
7626  /*Mutable=*/false,
7627  ICIS_NoInit);
7628  Field->setAccess(AS_public);
7629  VaListTagDecl->addDecl(Field);
7630  }
7631  VaListTagDecl->completeDefinition();
7632  Context->VaListTagDecl = VaListTagDecl;
7633  QualType VaListTagType = Context->getRecordType(VaListTagDecl);
7634 
7635  // } __va_list_tag;
7636  TypedefDecl *VaListTagTypedefDecl =
7637  Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
7638 
7639  QualType VaListTagTypedefType =
7640  Context->getTypedefType(VaListTagTypedefDecl);
7641 
7642  // typedef __va_list_tag __builtin_va_list[1];
7643  llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
7644  QualType VaListTagArrayType
7645  = Context->getConstantArrayType(VaListTagTypedefType,
7646  Size, nullptr, ArrayType::Normal, 0);
7647  return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
7648 }
7649 
7650 static TypedefDecl *
7652  // struct __va_list_tag {
7654  VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
7655  VaListTagDecl->startDefinition();
7656 
7657  const size_t NumFields = 4;
7658  QualType FieldTypes[NumFields];
7659  const char *FieldNames[NumFields];
7660 
7661  // unsigned gp_offset;
7662  FieldTypes[0] = Context->UnsignedIntTy;
7663  FieldNames[0] = "gp_offset";
7664 
7665  // unsigned fp_offset;
7666  FieldTypes[1] = Context->UnsignedIntTy;
7667  FieldNames[1] = "fp_offset";
7668 
7669  // void* overflow_arg_area;
7670  FieldTypes[2] = Context->getPointerType(Context->VoidTy);
7671  FieldNames[2] = "overflow_arg_area";
7672 
7673  // void* reg_save_area;
7674  FieldTypes[3] = Context->getPointerType(Context->VoidTy);
7675  FieldNames[3] = "reg_save_area";
7676 
7677  // Create fields
7678  for (unsigned i = 0; i < NumFields; ++i) {
7679  FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7680  VaListTagDecl,
7681  SourceLocation(),
7682  SourceLocation(),
7683  &Context->Idents.get(FieldNames[i]),
7684  FieldTypes[i], /*TInfo=*/nullptr,
7685  /*BitWidth=*/nullptr,
7686  /*Mutable=*/false,
7687  ICIS_NoInit);
7688  Field->setAccess(AS_public);
7689  VaListTagDecl->addDecl(Field);
7690  }
7691  VaListTagDecl->completeDefinition();
7692  Context->VaListTagDecl = VaListTagDecl;
7693  QualType VaListTagType = Context->getRecordType(VaListTagDecl);
7694 
7695  // };
7696 
7697  // typedef struct __va_list_tag __builtin_va_list[1];
7698  llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
7699  QualType VaListTagArrayType = Context->getConstantArrayType(
7700  VaListTagType, Size, nullptr, ArrayType::Normal, 0);
7701  return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
7702 }
7703 
7705  // typedef int __builtin_va_list[4];
7706  llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
7707  QualType IntArrayType = Context->getConstantArrayType(
7708  Context->IntTy, Size, nullptr, ArrayType::Normal, 0);
7709  return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
7710 }
7711 
7712 static TypedefDecl *
7714  // struct __va_list
7715  RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
7716  if (Context->getLangOpts().CPlusPlus) {
7717  // namespace std { struct __va_list {
7718  NamespaceDecl *NS;
7719  NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
7720  Context->getTranslationUnitDecl(),
7721  /*Inline*/false, SourceLocation(),
7722  SourceLocation(), &Context->Idents.get("std"),
7723  /*PrevDecl*/ nullptr);
7724  NS->setImplicit();
7725  VaListDecl->setDeclContext(NS);
7726  }
7727 
7728  VaListDecl->startDefinition();
7729 
7730  // void * __ap;
7731  FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7732  VaListDecl,
7733  SourceLocation(),
7734  SourceLocation(),
7735  &Context->Idents.get("__ap"),
7736  Context->getPointerType(Context->VoidTy),
7737  /*TInfo=*/nullptr,
7738  /*BitWidth=*/nullptr,
7739  /*Mutable=*/false,
7740  ICIS_NoInit);
7741  Field->setAccess(AS_public);
7742  VaListDecl->addDecl(Field);
7743 
7744  // };
7745  VaListDecl->completeDefinition();
7746  Context->VaListTagDecl = VaListDecl;
7747 
7748  // typedef struct __va_list __builtin_va_list;
7749  QualType T = Context->getRecordType(VaListDecl);
7750  return Context->buildImplicitTypedef(T, "__builtin_va_list");
7751 }
7752 
7753 static TypedefDecl *
7755  // struct __va_list_tag {
7757  VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
7758  VaListTagDecl->startDefinition();
7759 
7760  const size_t NumFields = 4;
7761  QualType FieldTypes[NumFields];
7762  const char *FieldNames[NumFields];
7763 
7764  // long __gpr;
7765  FieldTypes[0] = Context->LongTy;
7766  FieldNames[0] = "__gpr";
7767 
7768  // long __fpr;
7769  FieldTypes[1] = Context->LongTy;
7770  FieldNames[1] = "__fpr";
7771 
7772  // void *__overflow_arg_area;
7773  FieldTypes[2] = Context->getPointerType(Context->VoidTy);
7774  FieldNames[2] = "__overflow_arg_area";
7775 
7776  // void *__reg_save_area;
7777  FieldTypes[3] = Context->getPointerType(Context->VoidTy);
7778  FieldNames[3] = "__reg_save_area";
7779 
7780  // Create fields
7781  for (unsigned i = 0; i < NumFields; ++i) {
7782  FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7783  VaListTagDecl,
7784  SourceLocation(),
7785  SourceLocation(),
7786  &Context->Idents.get(FieldNames[i]),
7787  FieldTypes[i], /*TInfo=*/nullptr,
7788  /*BitWidth=*/nullptr,
7789  /*Mutable=*/false,
7790  ICIS_NoInit);
7791  Field->setAccess(AS_public);
7792  VaListTagDecl->addDecl(Field);
7793  }
7794  VaListTagDecl->completeDefinition();
7795  Context->VaListTagDecl = VaListTagDecl;
7796  QualType VaListTagType = Context->getRecordType(VaListTagDecl);
7797 
7798  // };
7799 
7800  // typedef __va_list_tag __builtin_va_list[1];
7801  llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
7802  QualType VaListTagArrayType = Context->getConstantArrayType(
7803  VaListTagType, Size, nullptr, ArrayType::Normal, 0);
7804 
7805  return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
7806 }
7807 
7808 static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
7810  switch (Kind) {
7812  return CreateCharPtrBuiltinVaListDecl(Context);
7814  return CreateVoidPtrBuiltinVaListDecl(Context);
7816  return CreateAArch64ABIBuiltinVaListDecl(Context);
7818  return CreatePowerABIBuiltinVaListDecl(Context);
7820  return CreateX86_64ABIBuiltinVaListDecl(Context);
7822  return CreatePNaClABIBuiltinVaListDecl(Context);
7824  return CreateAAPCSABIBuiltinVaListDecl(Context);
7826  return CreateSystemZBuiltinVaListDecl(Context);
7827  }
7828 
7829  llvm_unreachable("Unhandled __builtin_va_list type kind");
7830 }
7831 
7833  if (!BuiltinVaListDecl) {
7834  BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
7835  assert(BuiltinVaListDecl->isImplicit());
7836  }
7837 
7838  return BuiltinVaListDecl;
7839 }
7840 
7842  // Force the creation of VaListTagDecl by building the __builtin_va_list
7843  // declaration.
7844  if (!VaListTagDecl)
7845  (void)getBuiltinVaListDecl();
7846 
7847  return VaListTagDecl;
7848 }
7849 
7851  if (!BuiltinMSVaListDecl)
7852  BuiltinMSVaListDecl = CreateMSVaListDecl(this);
7853 
7854  return BuiltinMSVaListDecl;
7855 }
7856 
7859 }
7860 
7862  assert(ObjCConstantStringType.isNull() &&
7863  "'NSConstantString' type already set!");
7864 
7865  ObjCConstantStringType = getObjCInterfaceType(Decl);
7866 }
7867 
7868 /// Retrieve the template name that corresponds to a non-empty
7869 /// lookup.
7872  UnresolvedSetIterator End) const {
7873  unsigned size = End - Begin;
7874  assert(size > 1 && "set is not overloaded!");
7875 
7876  void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
7877  size * sizeof(FunctionTemplateDecl*));
7878  auto *OT = new (memory) OverloadedTemplateStorage(size);
7879 
7880  NamedDecl **Storage = OT->getStorage();
7881  for (UnresolvedSetIterator I = Begin; I != End; ++I) {
7882  NamedDecl *D = *I;
7883  assert(isa<FunctionTemplateDecl>(D) ||
7884  isa<UnresolvedUsingValueDecl>(D) ||
7885  (isa<UsingShadowDecl>(D) &&
7886  isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
7887  *Storage++ = D;
7888  }
7889 
7890  return TemplateName(OT);
7891 }
7892 
7893 /// Retrieve a template name representing an unqualified-id that has been
7894 /// assumed to name a template for ADL purposes.
7896  auto *OT = new (*this) AssumedTemplateStorage(Name);
7897  return TemplateName(OT);
7898 }
7899 
7900 /// Retrieve the template name that represents a qualified
7901 /// template name such as \c std::vector.
7904  bool TemplateKeyword,
7905  TemplateDecl *Template) const {
7906  assert(NNS && "Missing nested-name-specifier in qualified template name");
7907 
7908  // FIXME: Canonicalization?
7909  llvm::FoldingSetNodeID ID;
7910  QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
7911 
7912  void *InsertPos = nullptr;
7913  QualifiedTemplateName *QTN =
7914  QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7915  if (!QTN) {
7916  QTN = new (*this, alignof(QualifiedTemplateName))
7917  QualifiedTemplateName(NNS, TemplateKeyword, Template);
7918  QualifiedTemplateNames.InsertNode(QTN, InsertPos);
7919  }
7920 
7921  return TemplateName(QTN);
7922 }
7923 
7924 /// Retrieve the template name that represents a dependent
7925 /// template name such as \c MetaFun::template apply.
7928  const IdentifierInfo *Name) const {
7929  assert((!NNS || NNS->isDependent()) &&
7930  "Nested name specifier must be dependent");
7931 
7932  llvm::FoldingSetNodeID ID;
7933  DependentTemplateName::Profile(ID, NNS, Name);
7934 
7935  void *InsertPos = nullptr;
7936  DependentTemplateName *QTN =
7937  DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7938 
7939  if (QTN)
7940  return TemplateName(QTN);
7941 
7943  if (CanonNNS == NNS) {
7944  QTN = new (*this, alignof(DependentTemplateName))
7945  DependentTemplateName(NNS, Name);
7946  } else {
7947  TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
7948  QTN = new (*this, alignof(DependentTemplateName))
7949  DependentTemplateName(NNS, Name, Canon);
7950  DependentTemplateName *CheckQTN =
7951  DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7952  assert(!CheckQTN && "Dependent type name canonicalization broken");
7953  (void)CheckQTN;
7954  }
7955 
7956  DependentTemplateNames.InsertNode(QTN, InsertPos);
7957  return TemplateName(QTN);
7958 }
7959 
7960 /// Retrieve the template name that represents a dependent
7961 /// template name such as \c MetaFun::template operator+.
7964  OverloadedOperatorKind Operator) const {
7965  assert((!NNS || NNS->isDependent()) &&
7966  "Nested name specifier must be dependent");
7967 
7968  llvm::FoldingSetNodeID ID;
7969  DependentTemplateName::Profile(ID, NNS, Operator);
7970 
7971  void *InsertPos = nullptr;
7973  = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7974 
7975  if (QTN)
7976  return TemplateName(QTN);
7977 
7979  if (CanonNNS == NNS) {
7980  QTN = new (*this, alignof(DependentTemplateName))
7981  DependentTemplateName(NNS, Operator);
7982  } else {
7983  TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
7984  QTN = new (*this, alignof(DependentTemplateName))
7985  DependentTemplateName(NNS, Operator, Canon);
7986 
7987  DependentTemplateName *CheckQTN
7988  = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7989  assert(!CheckQTN && "Dependent template name canonicalization broken");
7990  (void)CheckQTN;
7991  }
7992 
7993  DependentTemplateNames.InsertNode(QTN, InsertPos);
7994  return TemplateName(QTN);
7995 }
7996 
7999  TemplateName replacement) const {
8000  llvm::FoldingSetNodeID ID;
8001  SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
8002 
8003  void *insertPos = nullptr;
8005  = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
8006 
8007  if (!subst) {
8008  subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
8009  SubstTemplateTemplateParms.InsertNode(subst, insertPos);
8010  }
8011 
8012  return TemplateName(subst);
8013 }
8014 
8017  const TemplateArgument &ArgPack) const {
8018  auto &Self = const_cast<ASTContext &>(*this);
8019  llvm::FoldingSetNodeID ID;
8020  SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
8021 
8022  void *InsertPos = nullptr;
8024  = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
8025 
8026  if (!Subst) {
8027  Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
8028  ArgPack.pack_size(),
8029  ArgPack.pack_begin());
8030  SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
8031  }
8032 
8033  return TemplateName(Subst);
8034 }
8035 
8036 /// getFromTargetType - Given one of the integer types provided by
8037 /// TargetInfo, produce the corresponding type. The unsigned @p Type
8038 /// is actually a value of type @c TargetInfo::IntType.
8039 CanQualType ASTContext::getFromTargetType(unsigned Type) const {
8040  switch (Type) {
8041  case TargetInfo::NoInt: return {};
8042  case TargetInfo::SignedChar: return SignedCharTy;
8044  case TargetInfo::SignedShort: return ShortTy;
8046  case TargetInfo::SignedInt: return IntTy;
8048  case TargetInfo::SignedLong: return LongTy;
8052  }
8053 
8054  llvm_unreachable("Unhandled TargetInfo::IntType value");
8055 }
8056 
8057 //===----------------------------------------------------------------------===//
8058 // Type Predicates.
8059 //===----------------------------------------------------------------------===//
8060 
8061 /// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
8062 /// garbage collection attribute.
8063 ///
8065  if (getLangOpts().getGC() == LangOptions::NonGC)
8066  return Qualifiers::GCNone;
8067 
8068  assert(getLangOpts().ObjC);
8069  Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
8070 
8071  // Default behaviour under objective-C's gc is for ObjC pointers
8072  // (or pointers to them) be treated as though they were declared
8073  // as __strong.
8074  if (GCAttrs == Qualifiers::GCNone) {
8075  if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
8076  return Qualifiers::Strong;
8077  else if (Ty->isPointerType())
8079  } else {
8080  // It's not valid to set GC attributes on anything that isn't a
8081  // pointer.
8082 #ifndef NDEBUG
8084  while (const auto *AT = dyn_cast<ArrayType>(CT))
8085  CT = AT->getElementType();
8086  assert(CT->isAnyPointerType() || CT->isBlockPointerType());
8087 #endif
8088  }
8089  return GCAttrs;
8090 }
8091 
8092 //===----------------------------------------------------------------------===//
8093 // Type Compatibility Testing
8094 //===----------------------------------------------------------------------===//
8095 
8096 /// areCompatVectorTypes - Return true if the two specified vector types are
8097 /// compatible.
8098 static bool areCompatVectorTypes(const VectorType *LHS,
8099  const VectorType *RHS) {
8100  assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
8101  return LHS->getElementType() == RHS->getElementType() &&
8102  LHS->getNumElements() == RHS->getNumElements();
8103 }
8104 
8106  QualType SecondVec) {
8107  assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
8108  assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
8109 
8110  if (hasSameUnqualifiedType(FirstVec, SecondVec))
8111  return true;
8112 
8113  // Treat Neon vector types and most AltiVec vector types as if they are the
8114  // equivalent GCC vector types.
8115  const auto *First = FirstVec->castAs<VectorType>();
8116  const auto *Second = SecondVec->castAs<VectorType>();
8117  if (First->getNumElements() == Second->getNumElements() &&
8118  hasSameType(First->getElementType(), Second->getElementType()) &&
8119  First->getVectorKind() != VectorType::AltiVecPixel &&
8120  First->getVectorKind() != VectorType::AltiVecBool &&
8121  Second->getVectorKind() != VectorType::AltiVecPixel &&
8123  return true;
8124 
8125  return false;
8126 }
8127 
8129  while (true) {
8130  // __strong id
8131  if (const AttributedType *Attr = dyn_cast<AttributedType>(Ty)) {
8132  if (Attr->getAttrKind() == attr::ObjCOwnership)
8133  return true;
8134 
8135  Ty = Attr->getModifiedType();
8136 
8137  // X *__strong (...)
8138  } else if (const ParenType *Paren = dyn_cast<ParenType>(Ty)) {
8139  Ty = Paren->getInnerType();
8140 
8141  // We do not want to look through typedefs, typeof(expr),
8142  // typeof(type), or any other way that the type is somehow
8143  // abstracted.
8144  } else {
8145  return false;
8146  }
8147  }
8148 }
8149 
8150 //===----------------------------------------------------------------------===//
8151 // ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
8152 //===----------------------------------------------------------------------===//
8153 
8154 /// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
8155 /// inheritance hierarchy of 'rProto'.
8156 bool
8158  ObjCProtocolDecl *rProto) const {
8159  if (declaresSameEntity(lProto, rProto))
8160  return true;
8161  for (auto *PI : rProto->protocols())
8162  if (ProtocolCompatibleWithProtocol(lProto, PI))
8163  return true;
8164  return false;
8165 }
8166 
8167 /// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
8168 /// Class<pr1, ...>.
8170  const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs) {
8171  for (auto *lhsProto : lhs->quals()) {
8172  bool match = false;
8173  for (auto *rhsProto : rhs->quals()) {
8174  if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
8175  match = true;
8176  break;
8177  }
8178  }
8179  if (!match)
8180  return false;
8181  }
8182  return true;
8183 }
8184 
8185 /// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
8186 /// ObjCQualifiedIDType.
8188  const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs,
8189  bool compare) {
8190  // Allow id<P..> and an 'id' in all cases.
8191  if (lhs->isObjCIdType() || rhs->isObjCIdType())
8192  return true;
8193 
8194  // Don't allow id<P..> to convert to Class or Class<P..> in either direction.
8195  if (lhs->isObjCClassType() || lhs->isObjCQualifiedClassType() ||
8196  rhs->isObjCClassType() || rhs->isObjCQualifiedClassType())
8197  return false;
8198 
8199  if (lhs->isObjCQualifiedIdType()) {
8200  if (rhs->qual_empty()) {
8201  // If the RHS is a unqualified interface pointer "NSString*",
8202  // make sure we check the class hierarchy.
8203  if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
8204  for (auto *I : lhs->quals()) {
8205  // when comparing an id<P> on lhs with a static type on rhs,
8206  // see if static class implements all of id's protocols, directly or
8207  // through its super class and categories.
8208  if (!rhsID->ClassImplementsProtocol(I, true))
8209  return false;
8210  }
8211  }
8212  // If there are no qualifiers and no interface, we have an 'id'.
8213  return true;
8214  }
8215  // Both the right and left sides have qualifiers.
8216  for (auto *lhsProto : lhs->quals()) {
8217  bool match = false;
8218 
8219  // when comparing an id<P> on lhs with a static type on rhs,
8220  // see if static class implements all of id's protocols, directly or
8221  // through its super class and categories.
8222  for (auto *rhsProto : rhs->quals()) {
8223  if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
8224  (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
8225  match = true;
8226  break;
8227  }
8228  }
8229  // If the RHS is a qualified interface pointer "NSString<P>*",
8230  // make sure we check the class hierarchy.
8231  if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
8232  for (auto *I : lhs->quals()) {
8233  // when comparing an id<P> on lhs with a static type on rhs,
8234  // see if static class implements all of id's protocols, directly or
8235  // through its super class and categories.
8236  if (rhsID->ClassImplementsProtocol(I, true)) {
8237  match = true;
8238  break;
8239  }
8240  }
8241  }
8242  if (!match)
8243  return false;
8244  }
8245 
8246  return true;
8247  }
8248 
8249  assert(rhs->isObjCQualifiedIdType() && "One of the LHS/RHS should be id<x>");
8250 
8251  if (lhs->getInterfaceType()) {
8252  // If both the right and left sides have qualifiers.
8253  for (auto *lhsProto : lhs->quals()) {
8254  bool match = false;
8255 
8256  // when comparing an id<P> on rhs with a static type on lhs,
8257  // see if static class implements all of id's protocols, directly or
8258  // through its super class and categories.
8259  // First, lhs protocols in the qualifier list must be found, direct
8260  // or indirect in rhs's qualifier list or it is a mismatch.
8261  for (auto *rhsProto : rhs->quals()) {
8262  if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
8263  (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
8264  match = true;
8265  break;
8266  }
8267  }
8268  if (!match)
8269  return false;
8270  }
8271 
8272  // Static class's protocols, or its super class or category protocols
8273  // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
8274  if (ObjCInterfaceDecl *lhsID = lhs->getInterfaceDecl()) {
8275  llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
8276  CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
8277  // This is rather dubious but matches gcc's behavior. If lhs has
8278  // no type qualifier and its class has no static protocol(s)
8279  // assume that it is mismatch.
8280  if (LHSInheritedProtocols.empty() && lhs->qual_empty())
8281  return false;
8282  for (auto *lhsProto : LHSInheritedProtocols) {
8283  bool match = false;
8284  for (auto *rhsProto : rhs->quals()) {
8285  if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
8286  (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
8287  match = true;
8288  break;
8289  }
8290  }
8291  if (!match)
8292  return false;
8293  }
8294  }
8295  return true;
8296  }
8297  return false;
8298 }
8299 
8300 /// canAssignObjCInterfaces - Return true if the two interface types are
8301 /// compatible for assignment from RHS to LHS. This handles validation of any
8302 /// protocol qualifiers on the LHS or RHS.
8304  const ObjCObjectPointerType *RHSOPT) {
8305  const ObjCObjectType* LHS = LHSOPT->getObjectType();
8306  const ObjCObjectType* RHS = RHSOPT->getObjectType();
8307 
8308  // If either type represents the built-in 'id' type, return true.
8309  if (LHS->isObjCUnqualifiedId() || RHS->isObjCUnqualifiedId())
8310  return true;
8311 
8312  // Function object that propagates a successful result or handles
8313  // __kindof types.
8314  auto finish = [&](bool succeeded) -> bool {
8315  if (succeeded)
8316  return true;
8317 
8318  if (!RHS->isKindOfType())
8319  return false;
8320 
8321  // Strip off __kindof and protocol qualifiers, then check whether
8322  // we can assign the other way.
8324  LHSOPT->stripObjCKindOfTypeAndQuals(*this));
8325  };
8326 
8327  // Casts from or to id<P> are allowed when the other side has compatible
8328  // protocols.
8329  if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
8330  return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false));
8331  }
8332 
8333  // Verify protocol compatibility for casts from Class<P1> to Class<P2>.
8334  if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
8335  return finish(ObjCQualifiedClassTypesAreCompatible(LHSOPT, RHSOPT));
8336  }
8337 
8338  // Casts from Class to Class<Foo>, or vice-versa, are allowed.
8339  if (LHS->isObjCClass() && RHS->isObjCClass()) {
8340  return true;
8341  }
8342 
8343  // If we have 2 user-defined types, fall into that path.
8344  if (LHS->getInterface() && RHS->getInterface()) {
8345  return finish(canAssignObjCInterfaces(LHS, RHS));
8346  }
8347 
8348  return false;
8349 }
8350 
8351 /// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
8352 /// for providing type-safety for objective-c pointers used to pass/return
8353 /// arguments in block literals. When passed as arguments, passing 'A*' where
8354 /// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
8355 /// not OK. For the return type, the opposite is not OK.
8357  const ObjCObjectPointerType *LHSOPT,
8358  const ObjCObjectPointerType *RHSOPT,
8359  bool BlockReturnType) {
8360 
8361  // Function object that propagates a successful result or handles
8362  // __kindof types.
8363  auto finish = [&](bool succeeded) -> bool {
8364  if (succeeded)
8365  return true;
8366 
8367  const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
8368  if (!Expected->isKindOfType())
8369  return false;
8370 
8371  // Strip off __kindof and protocol qualifiers, then check whether
8372  // we can assign the other way.
8374  RHSOPT->stripObjCKindOfTypeAndQuals(*this),
8375  LHSOPT->stripObjCKindOfTypeAndQuals(*this),
8376  BlockReturnType);
8377  };
8378 
8379  if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
8380  return true;
8381 
8382  if (LHSOPT->isObjCBuiltinType()) {
8383  return finish(RHSOPT->isObjCBuiltinType() ||
8384  RHSOPT->isObjCQualifiedIdType());
8385  }
8386 
8387  if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
8388  return finish(ObjCQualifiedIdTypesAreCompatible(
8389  (BlockReturnType ? LHSOPT : RHSOPT),
8390  (BlockReturnType ? RHSOPT : LHSOPT), false));
8391 
8392  const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
8393  const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
8394  if (LHS && RHS) { // We have 2 user-defined types.
8395  if (LHS != RHS) {
8396  if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
8397  return finish(BlockReturnType);
8398  if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
8399  return finish(!BlockReturnType);
8400  }
8401  else
8402  return true;
8403  }
8404  return false;
8405 }
8406 
8407 /// Comparison routine for Objective-C protocols to be used with
8408 /// llvm::array_pod_sort.
8410  ObjCProtocolDecl * const *rhs) {
8411  return (*lhs)->getName().compare((*rhs)->getName());
8412 }
8413 
8414 /// getIntersectionOfProtocols - This routine finds the intersection of set
8415 /// of protocols inherited from two distinct objective-c pointer objects with
8416 /// the given common base.
8417 /// It is used to build composite qualifier list of the composite type of
8418 /// the conditional expression involving two objective-c pointer objects.
8419 static
8422  const ObjCObjectPointerType *LHSOPT,
8423  const ObjCObjectPointerType *RHSOPT,
8424  SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
8425 
8426  const ObjCObjectType* LHS = LHSOPT->getObjectType();
8427  const ObjCObjectType* RHS = RHSOPT->getObjectType();
8428  assert(LHS->getInterface() && "LHS must have an interface base");
8429  assert(RHS->getInterface() && "RHS must have an interface base");
8430 
8431  // Add all of the protocols for the LHS.
8432  llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
8433 
8434  // Start with the protocol qualifiers.
8435  for (auto proto : LHS->quals()) {
8436  Context.CollectInheritedProtocols(proto, LHSProtocolSet);
8437  }
8438 
8439  // Also add the protocols associated with the LHS interface.
8440  Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
8441 
8442  // Add all of the protocols for the RHS.
8443  llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
8444 
8445  // Start with the protocol qualifiers.
8446  for (auto proto : RHS->quals()) {
8447  Context.CollectInheritedProtocols(proto, RHSProtocolSet);
8448  }
8449 
8450  // Also add the protocols associated with the RHS interface.
8451  Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
8452 
8453  // Compute the intersection of the collected protocol sets.
8454  for (auto proto : LHSProtocolSet) {
8455  if (RHSProtocolSet.count(proto))
8456  IntersectionSet.push_back(proto);
8457  }
8458 
8459  // Compute the set of protocols that is implied by either the common type or
8460  // the protocols within the intersection.
8461  llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
8462  Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
8463 
8464  // Remove any implied protocols from the list of inherited protocols.
8465  if (!ImpliedProtocols.empty()) {
8466  IntersectionSet.erase(
8467  std::remove_if(IntersectionSet.begin(),
8468  IntersectionSet.end(),
8469  [&](ObjCProtocolDecl *proto) -> bool {
8470  return ImpliedProtocols.count(proto) > 0;
8471  }),
8472  IntersectionSet.end());
8473  }
8474 
8475  // Sort the remaining protocols by name.
8476  llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
8478 }
8479 
8480 /// Determine whether the first type is a subtype of the second.
8482  QualType rhs) {
8483  // Common case: two object pointers.
8484  const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
8485  const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
8486  if (lhsOPT && rhsOPT)
8487  return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
8488 
8489  // Two block pointers.
8490  const auto *lhsBlock = lhs->getAs<BlockPointerType>();
8491  const auto *rhsBlock = rhs->getAs<BlockPointerType>();
8492  if (lhsBlock && rhsBlock)
8493  return ctx.typesAreBlockPointerCompatible(lhs, rhs);
8494 
8495  // If either is an unqualified 'id' and the other is a block, it's
8496  // acceptable.
8497  if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
8498  (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
8499  return true;
8500 
8501  return false;
8502 }
8503 
8504 // Check that the given Objective-C type argument lists are equivalent.
8505 static bool sameObjCTypeArgs(ASTContext &ctx,
8506  const ObjCInterfaceDecl *iface,
8507  ArrayRef<QualType> lhsArgs,
8508  ArrayRef<QualType> rhsArgs,
8509  bool stripKindOf) {
8510  if (lhsArgs.size() != rhsArgs.size())
8511  return false;
8512 
8513  ObjCTypeParamList *typeParams = iface->getTypeParamList();
8514  for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
8515  if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
8516  continue;
8517 
8518  switch (typeParams->begin()[i]->getVariance()) {
8520  if (!stripKindOf ||
8521  !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
8522  rhsArgs[i].stripObjCKindOfType(ctx))) {
8523  return false;
8524  }
8525  break;
8526 
8528  if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
8529  return false;
8530  break;
8531 
8533  if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
8534  return false;
8535  break;
8536  }
8537  }
8538 
8539  return true;
8540 }
8541 
8543  const ObjCObjectPointerType *Lptr,
8544  const ObjCObjectPointerType *Rptr) {
8545  const ObjCObjectType *LHS = Lptr->getObjectType();
8546  const ObjCObjectType *RHS = Rptr->getObjectType();
8547  const ObjCInterfaceDecl* LDecl = LHS->getInterface();
8548  const ObjCInterfaceDecl* RDecl = RHS->getInterface();
8549 
8550  if (!LDecl || !RDecl)
8551  return {};
8552 
8553  // When either LHS or RHS is a kindof type, we should return a kindof type.
8554  // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
8555  // kindof(A).
8556  bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
8557 
8558  // Follow the left-hand side up the class hierarchy until we either hit a
8559  // root or find the RHS. Record the ancestors in case we don't find it.
8560  llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
8561  LHSAncestors;
8562  while (true) {
8563  // Record this ancestor. We'll need this if the common type isn't in the
8564  // path from the LHS to the root.
8565  LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
8566 
8567  if (declaresSameEntity(LHS->getInterface(), RDecl)) {
8568  // Get the type arguments.
8569  ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
8570  bool anyChanges = false;
8571  if (LHS->isSpecialized() && RHS->isSpecialized()) {
8572  // Both have type arguments, compare them.
8573  if (!sameObjCTypeArgs(*this, LHS->getInterface(),
8574  LHS->getTypeArgs(), RHS->getTypeArgs(),
8575  /*stripKindOf=*/true))
8576  return {};
8577  } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
8578  // If only one has type arguments, the result will not have type
8579  // arguments.
8580  LHSTypeArgs = {};
8581  anyChanges = true;
8582  }
8583 
8584  // Compute the intersection of protocols.
8586  getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
8587  Protocols);
8588  if (!Protocols.empty())
8589  anyChanges = true;
8590 
8591  // If anything in the LHS will have changed, build a new result type.
8592  // If we need to return a kindof type but LHS is not a kindof type, we
8593  // build a new result type.
8594  if (anyChanges || LHS->isKindOfType() != anyKindOf) {
8596  Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
8597  anyKindOf || LHS->isKindOfType());
8598  return getObjCObjectPointerType(Result);
8599  }
8600 
8601  return getObjCObjectPointerType(QualType(LHS, 0));
8602  }
8603 
8604  // Find the superclass.
8605  QualType LHSSuperType = LHS->getSuperClassType();
8606  if (LHSSuperType.isNull())
8607  break;
8608 
8609  LHS = LHSSuperType->castAs<ObjCObjectType>();
8610  }
8611 
8612  // We didn't find anything by following the LHS to its root; now check
8613  // the RHS against the cached set of ancestors.
8614  while (true) {
8615  auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
8616  if (KnownLHS != LHSAncestors.end()) {
8617  LHS = KnownLHS->second;
8618 
8619  // Get the type arguments.
8620  ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
8621  bool anyChanges = false;
8622  if (LHS->isSpecialized() && RHS->isSpecialized()) {
8623  // Both have type arguments, compare them.
8624  if (!sameObjCTypeArgs(*this, LHS->getInterface(),
8625  LHS->getTypeArgs(), RHS->getTypeArgs(),
8626  /*stripKindOf=*/true))
8627  return {};
8628  } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
8629  // If only one has type arguments, the result will not have type
8630  // arguments.
8631  RHSTypeArgs = {};
8632  anyChanges = true;
8633  }
8634 
8635  // Compute the intersection of protocols.
8637  getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
8638  Protocols);
8639  if (!Protocols.empty())
8640  anyChanges = true;
8641 
8642  // If we need to return a kindof type but RHS is not a kindof type, we
8643  // build a new result type.
8644  if (anyChanges || RHS->isKindOfType() != anyKindOf) {
8646  Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
8647  anyKindOf || RHS->isKindOfType());
8648  return getObjCObjectPointerType(Result);
8649  }
8650 
8651  return getObjCObjectPointerType(QualType(RHS, 0));
8652  }
8653 
8654  // Find the superclass of the RHS.
8655  QualType RHSSuperType = RHS->getSuperClassType();
8656  if (RHSSuperType.isNull())
8657  break;
8658 
8659  RHS = RHSSuperType->castAs<ObjCObjectType>();
8660  }
8661 
8662  return {};
8663 }
8664 
8666  const ObjCObjectType *RHS) {
8667  assert(LHS->getInterface() && "LHS is not an interface type");
8668  assert(RHS->getInterface() && "RHS is not an interface type");
8669 
8670  // Verify that the base decls are compatible: the RHS must be a subclass of
8671  // the LHS.
8672  ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
8673  bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
8674  if (!IsSuperClass)
8675  return false;
8676 
8677  // If the LHS has protocol qualifiers, determine whether all of them are
8678  // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
8679  // LHS).
8680  if (LHS->getNumProtocols() > 0) {
8681  // OK if conversion of LHS to SuperClass results in narrowing of types
8682  // ; i.e., SuperClass may implement at least one of the protocols
8683  // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
8684  // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
8685  llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
8686  CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
8687  // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
8688  // qualifiers.
8689  for (auto *RHSPI : RHS->quals())
8690  CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
8691  // If there is no protocols associated with RHS, it is not a match.
8692  if (SuperClassInheritedProtocols.empty())
8693  return false;
8694 
8695  for (const auto *LHSProto : LHS->quals()) {
8696  bool SuperImplementsProtocol = false;
8697  for (auto *SuperClassProto : SuperClassInheritedProtocols)
8698  if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
8699  SuperImplementsProtocol = true;
8700  break;
8701  }
8702  if (!SuperImplementsProtocol)
8703  return false;
8704  }
8705  }
8706 
8707  // If the LHS is specialized, we may need to check type arguments.
8708  if (LHS->isSpecialized()) {
8709  // Follow the superclass chain until we've matched the LHS class in the
8710  // hierarchy. This substitutes type arguments through.
8711  const ObjCObjectType *RHSSuper = RHS;
8712  while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
8713  RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
8714 
8715  // If the RHS is specializd, compare type arguments.
8716  if (RHSSuper->isSpecialized() &&
8717  !sameObjCTypeArgs(*this, LHS->getInterface(),
8718  LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
8719  /*stripKindOf=*/true)) {
8720  return false;
8721  }
8722  }
8723 
8724  return true;
8725 }
8726 
8728  // get the "pointed to" types
8729  const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
8730  const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
8731 
8732  if (!LHSOPT || !RHSOPT)
8733  return false;
8734 
8735  return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
8736  canAssignObjCInterfaces(RHSOPT, LHSOPT);
8737 }
8738 
8740  return canAssignObjCInterfaces(
8741  getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
8742  getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
8743 }
8744 
8745 /// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
8746 /// both shall have the identically qualified version of a compatible type.
8747 /// C99 6.2.7p1: Two types have compatible types if their types are the
8748 /// same. See 6.7.[2,3,5] for additional rules.
8750  bool CompareUnqualified) {
8751  if (getLangOpts().CPlusPlus)
8752  return hasSameType(LHS, RHS);
8753 
8754  return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
8755 }
8756 
8758  return typesAreCompatible(LHS, RHS);
8759 }
8760 
8762  return !mergeTypes(LHS, RHS, true).isNull();
8763 }
8764 
8765 /// mergeTransparentUnionType - if T is a transparent union type and a member
8766 /// of T is compatible with SubType, return the merged type, else return
8767 /// QualType()
8769  bool OfBlockPointer,
8770  bool Unqualified) {
8771  if (const RecordType *UT = T->getAsUnionType()) {
8772  RecordDecl *UD = UT->getDecl();
8773  if (UD->hasAttr<TransparentUnionAttr>()) {
8774  for (const auto *I : UD->fields()) {
8775  QualType ET = I->getType().getUnqualifiedType();
8776  QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
8777  if (!MT.isNull())
8778  return MT;
8779  }
8780  }
8781  }
8782 
8783  return {};
8784 }
8785 
8786 /// mergeFunctionParameterTypes - merge two types which appear as function
8787 /// parameter types
8789  bool OfBlockPointer,
8790  bool Unqualified) {
8791  // GNU extension: two types are compatible if they appear as a function
8792  // argument, one of the types is a transparent union type and the other
8793  // type is compatible with a union member
8794  QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
8795  Unqualified);
8796  if (!lmerge.isNull())
8797  return lmerge;
8798 
8799  QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
8800  Unqualified);
8801  if (!rmerge.isNull())
8802  return rmerge;
8803 
8804  return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
8805 }
8806 
8808  bool OfBlockPointer,
8809  bool Unqualified) {
8810  const auto *lbase = lhs->castAs<FunctionType>();
8811  const auto *rbase = rhs->castAs<FunctionType>();
8812  const auto *lproto = dyn_cast<FunctionProtoType>(lbase);
8813  const auto *rproto = dyn_cast<FunctionProtoType>(rbase);
8814  bool allLTypes = true;
8815  bool allRTypes = true;
8816 
8817  // Check return type
8818  QualType retType;
8819  if (OfBlockPointer) {
8820  QualType RHS = rbase->getReturnType();
8821  QualType LHS = lbase->getReturnType();
8822  bool UnqualifiedResult = Unqualified;
8823  if (!UnqualifiedResult)
8824  UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
8825  retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
8826  }
8827  else
8828  retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
8829  Unqualified);
8830  if (retType.isNull())
8831  return {};
8832 
8833  if (Unqualified)
8834  retType = retType.getUnqualifiedType();
8835 
8836  CanQualType LRetType = getCanonicalType(lbase->getReturnType());
8837  CanQualType RRetType = getCanonicalType(rbase->getReturnType());
8838  if (Unqualified) {
8839  LRetType = LRetType.getUnqualifiedType();
8840  RRetType = RRetType.getUnqualifiedType();
8841  }
8842 
8843  if (getCanonicalType(retType) != LRetType)
8844  allLTypes = false;
8845  if (getCanonicalType(retType) != RRetType)
8846  allRTypes = false;
8847 
8848  // FIXME: double check this
8849  // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
8850  // rbase->getRegParmAttr() != 0 &&
8851  // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
8852  FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
8853  FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
8854 
8855  // Compatible functions must have compatible calling conventions
8856  if (lbaseInfo.getCC() != rbaseInfo.getCC())
8857  return {};
8858 
8859  // Regparm is part of the calling convention.
8860  if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
8861  return {};
8862  if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
8863  return {};
8864 
8865  if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
8866  return {};
8867  if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs())
8868  return {};
8869  if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck())
8870  return {};
8871 
8872  // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
8873  bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
8874 
8875  if (lbaseInfo.getNoReturn() != NoReturn)
8876  allLTypes = false;
8877  if (rbaseInfo.getNoReturn() != NoReturn)
8878  allRTypes = false;
8879 
8880  FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
8881 
8882  if (lproto && rproto) { // two C99 style function prototypes
8883  assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
8884  "C++ shouldn't be here");
8885  // Compatible functions must have the same number of parameters
8886  if (lproto->getNumParams() != rproto->getNumParams())
8887  return {};
8888 
8889  // Variadic and non-variadic functions aren't compatible
8890  if (lproto->isVariadic() != rproto->isVariadic())
8891  return {};
8892 
8893  if (lproto->getMethodQuals() != rproto->getMethodQuals())
8894  return {};
8895 
8897  bool canUseLeft, canUseRight;
8898  if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight,
8899  newParamInfos))
8900  return {};
8901 
8902  if (!canUseLeft)
8903  allLTypes = false;
8904  if (!canUseRight)
8905  allRTypes = false;
8906 
8907  // Check parameter type compatibility
8909  for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
8910  QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
8911  QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
8913  lParamType, rParamType, OfBlockPointer, Unqualified);
8914  if (paramType.isNull())
8915  return {};
8916 
8917  if (Unqualified)
8918  paramType = paramType.getUnqualifiedType();
8919 
8920  types.push_back(paramType);
8921  if (Unqualified) {
8922  lParamType = lParamType.getUnqualifiedType();
8923  rParamType = rParamType.getUnqualifiedType();
8924  }
8925 
8926  if (getCanonicalType(paramType) != getCanonicalType(lParamType))
8927  allLTypes = false;
8928  if (getCanonicalType(paramType) != getCanonicalType(rParamType))
8929  allRTypes = false;
8930  }
8931 
8932  if (allLTypes) return lhs;
8933  if (allRTypes) return rhs;
8934 
8935  FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
8936  EPI.ExtInfo = einfo;
8937  EPI.ExtParameterInfos =
8938  newParamInfos.empty() ? nullptr : newParamInfos.data();
8939  return getFunctionType(retType, types, EPI);
8940  }
8941 
8942  if (lproto) allRTypes = false;
8943  if (rproto) allLTypes = false;
8944 
8945  const FunctionProtoType *proto = lproto ? lproto : rproto;
8946  if (proto) {
8947  assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
8948  if (proto->isVariadic())
8949  return {};
8950  // Check that the types are compatible with the types that
8951  // would result from default argument promotions (C99 6.7.5.3p15).
8952  // The only types actually affected are promotable integer
8953  // types and floats, which would be passed as a different
8954  // type depending on whether the prototype is visible.
8955  for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
8956  QualType paramTy = proto->getParamType(i);
8957 
8958  // Look at the converted type of enum types, since that is the type used
8959  // to pass enum values.
8960  if (const auto *Enum = paramTy->getAs<EnumType>()) {
8961  paramTy = Enum->getDecl()->getIntegerType();
8962  if (paramTy.isNull())
8963  return {};
8964  }
8965 
8966  if (paramTy->isPromotableIntegerType() ||
8968  return {};
8969  }
8970 
8971  if (allLTypes) return lhs;
8972  if (allRTypes) return rhs;
8973 
8975  EPI.ExtInfo = einfo;
8976  return getFunctionType(retType, proto->getParamTypes(), EPI);
8977  }
8978 
8979  if (allLTypes) return lhs;
8980  if (allRTypes) return rhs;
8981  return getFunctionNoProtoType(retType, einfo);
8982 }
8983 
8984 /// Given that we have an enum type and a non-enum type, try to merge them.
8986  QualType other, bool isBlockReturnType) {
8987  // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
8988  // a signed integer type, or an unsigned integer type.
8989  // Compatibility is based on the underlying type, not the promotion
8990  // type.
8991  QualType underlyingType = ET->getDecl()->getIntegerType();
8992  if (underlyingType.isNull())
8993  return {};
8994  if (Context.hasSameType(underlyingType, other))
8995  return other;
8996 
8997  // In block return types, we're more permissive and accept any
8998  // integral type of the same size.
8999  if (isBlockReturnType && other->isIntegerType() &&
9000  Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
9001  return other;
9002 
9003  return {};
9004 }
9005 
9007  bool OfBlockPointer,
9008  bool Unqualified, bool BlockReturnType) {
9009  // C++ [expr]: If an expression initially has the type "reference to T", the
9010  // type is adjusted to "T" prior to any further analysis, the expression
9011  // designates the object or function denoted by the reference, and the
9012  // expression is an lvalue unless the reference is an rvalue reference and
9013  // the expression is a function call (possibly inside parentheses).
9014  assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
9015  assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
9016 
9017  if (Unqualified) {
9018  LHS = LHS.getUnqualifiedType();
9019  RHS = RHS.getUnqualifiedType();
9020  }
9021 
9022  QualType LHSCan = getCanonicalType(LHS),
9023  RHSCan = getCanonicalType(RHS);
9024 
9025  // If two types are identical, they are compatible.
9026  if (LHSCan == RHSCan)
9027  return LHS;
9028 
9029  // If the qualifiers are different, the types aren't compatible... mostly.
9030  Qualifiers LQuals = LHSCan.getLocalQualifiers();
9031  Qualifiers RQuals = RHSCan.getLocalQualifiers();
9032  if (LQuals != RQuals) {
9033  // If any of these qualifiers are different, we have a type
9034  // mismatch.
9035  if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
9036  LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
9037  LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
9038  LQuals.hasUnaligned() != RQuals.hasUnaligned())
9039  return {};
9040 
9041  // Exactly one GC qualifier difference is allowed: __strong is
9042  // okay if the other type has no GC qualifier but is an Objective
9043  // C object pointer (i.e. implicitly strong by default). We fix
9044  // this by pretending that the unqualified type was actually
9045  // qualified __strong.
9046  Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
9047  Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
9048  assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
9049 
9050  if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
9051  return {};
9052 
9053  if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
9054  return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
9055  }
9056  if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
9057  return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
9058  }
9059  return {};
9060  }
9061 
9062  // Okay, qualifiers are equal.
9063 
9064  Type::TypeClass LHSClass = LHSCan->getTypeClass();
9065  Type::TypeClass RHSClass = RHSCan->getTypeClass();
9066 
9067  // We want to consider the two function types to be the same for these
9068  // comparisons, just force one to the other.
9069  if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
9070  if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
9071 
9072  // Same as above for arrays
9073  if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
9074  LHSClass = Type::ConstantArray;
9075  if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
9076  RHSClass = Type::ConstantArray;
9077 
9078  // ObjCInterfaces are just specialized ObjCObjects.
9079  if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
9080  if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
9081 
9082  // Canonicalize ExtVector -> Vector.
9083  if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
9084  if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
9085 
9086  // If the canonical type classes don't match.
9087  if (LHSClass != RHSClass) {
9088  // Note that we only have special rules for turning block enum
9089  // returns into block int returns, not vice-versa.
9090  if (const auto *ETy = LHS->getAs<EnumType>()) {
9091  return mergeEnumWithInteger(*this, ETy, RHS, false);
9092  }
9093  if (const EnumType* ETy = RHS->getAs<EnumType>()) {
9094  return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
9095  }
9096  // allow block pointer type to match an 'id' type.
9097  if (OfBlockPointer && !BlockReturnType) {
9098  if (LHS->isObjCIdType() && RHS->isBlockPointerType())
9099  return LHS;
9100  if (RHS->isObjCIdType() && LHS->isBlockPointerType())
9101  return RHS;
9102  }
9103 
9104  return {};
9105  }
9106 
9107  // The canonical type classes match.
9108  switch (LHSClass) {
9109 #define TYPE(Class, Base)
9110 #define ABSTRACT_TYPE(Class, Base)
9111 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
9112 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
9113 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
9114 #include "clang/AST/TypeNodes.inc"
9115  llvm_unreachable("Non-canonical and dependent types shouldn't get here");
9116 
9117  case Type::Auto:
9118  case Type::DeducedTemplateSpecialization:
9119  case Type::LValueReference:
9120  case Type::RValueReference:
9121  case Type::MemberPointer:
9122  llvm_unreachable("C++ should never be in mergeTypes");
9123 
9124  case Type::ObjCInterface:
9125  case Type::IncompleteArray:
9126  case Type::VariableArray:
9127  case Type::FunctionProto:
9128  case Type::ExtVector:
9129  llvm_unreachable("Types are eliminated above");
9130 
9131  case Type::Pointer:
9132  {
9133  // Merge two pointer types, while trying to preserve typedef info
9134  QualType LHSPointee = LHS->castAs<PointerType>()->getPointeeType();
9135  QualType RHSPointee = RHS->castAs<PointerType>()->getPointeeType();
9136  if (Unqualified) {
9137  LHSPointee = LHSPointee.getUnqualifiedType();
9138  RHSPointee = RHSPointee.getUnqualifiedType();
9139  }
9140  QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
9141  Unqualified);
9142  if (ResultType.isNull())
9143  return {};
9144  if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
9145  return LHS;
9146  if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
9147  return RHS;
9148  return getPointerType(ResultType);
9149  }
9150  case Type::BlockPointer:
9151  {
9152  // Merge two block pointer types, while trying to preserve typedef info
9153  QualType LHSPointee = LHS->castAs<BlockPointerType>()->getPointeeType();
9154  QualType RHSPointee = RHS->castAs<BlockPointerType>()->getPointeeType();
9155  if (Unqualified) {
9156  LHSPointee = LHSPointee.getUnqualifiedType();
9157  RHSPointee = RHSPointee.getUnqualifiedType();
9158  }
9159  if (getLangOpts().OpenCL) {
9160  Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
9161  Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
9162  // Blocks can't be an expression in a ternary operator (OpenCL v2.0
9163  // 6.12.5) thus the following check is asymmetric.
9164  if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual))
9165  return {};
9166  LHSPteeQual.removeAddressSpace();
9167  RHSPteeQual.removeAddressSpace();
9168  LHSPointee =
9169  QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
9170  RHSPointee =
9171  QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
9172  }
9173  QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
9174  Unqualified);
9175  if (ResultType.isNull())
9176  return {};
9177  if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
9178  return LHS;
9179  if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
9180  return RHS;
9181  return getBlockPointerType(ResultType);
9182  }
9183  case Type::Atomic:
9184  {
9185  // Merge two pointer types, while trying to preserve typedef info
9186  QualType LHSValue = LHS->castAs<AtomicType>()->getValueType();
9187  QualType RHSValue = RHS->castAs<AtomicType>()->getValueType();
9188  if (Unqualified) {
9189  LHSValue = LHSValue.getUnqualifiedType();
9190  RHSValue = RHSValue.getUnqualifiedType();
9191  }
9192  QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
9193  Unqualified);
9194  if (ResultType.isNull())
9195  return {};
9196  if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
9197  return LHS;
9198  if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
9199  return RHS;
9200  return getAtomicType(ResultType);
9201  }
9202  case Type::ConstantArray:
9203  {
9204  const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
9205  const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
9206  if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
9207  return {};
9208 
9209  QualType LHSElem = getAsArrayType(LHS)->getElementType();
9210  QualType RHSElem = getAsArrayType(RHS)->getElementType();
9211  if (Unqualified) {
9212  LHSElem = LHSElem.getUnqualifiedType();
9213  RHSElem = RHSElem.getUnqualifiedType();
9214  }
9215 
9216  QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
9217  if (ResultType.isNull())
9218  return {};
9219 
9220  const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
9221  const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
9222 
9223  // If either side is a variable array, and both are complete, check whether
9224  // the current dimension is definite.
9225  if (LVAT || RVAT) {
9226  auto SizeFetch = [this](const VariableArrayType* VAT,
9227  const ConstantArrayType* CAT)
9228  -> std::pair<bool,llvm::APInt> {
9229  if (VAT) {
9230  llvm::APSInt TheInt;
9231  Expr *E = VAT->getSizeExpr();
9232  if (E && E->isIntegerConstantExpr(TheInt, *this))
9233  return std::make_pair(true, TheInt);
9234  else
9235  return std::make_pair(false, TheInt);
9236  } else if (CAT) {
9237  return std::make_pair(true, CAT->getSize());
9238  } else {
9239  return std::make_pair(false, llvm::APInt());
9240  }
9241  };
9242 
9243  bool HaveLSize, HaveRSize;
9244  llvm::APInt LSize, RSize;
9245  std::tie(HaveLSize, LSize) = SizeFetch(LVAT, LCAT);
9246  std::tie(HaveRSize, RSize) = SizeFetch(RVAT, RCAT);
9247  if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(LSize, RSize))
9248  return {}; // Definite, but unequal, array dimension
9249  }
9250 
9251  if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
9252  return LHS;
9253  if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
9254  return RHS;
9255  if (LCAT)
9256  return getConstantArrayType(ResultType, LCAT->getSize(),
9257  LCAT->getSizeExpr(),
9259  if (RCAT)
9260  return getConstantArrayType(ResultType, RCAT->getSize(),
9261  RCAT->getSizeExpr(),
9263  if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
9264  return LHS;
9265  if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
9266  return RHS;
9267  if (LVAT) {
9268  // FIXME: This isn't correct! But tricky to implement because
9269  // the array's size has to be the size of LHS, but the type
9270  // has to be different.
9271  return LHS;
9272  }
9273  if (RVAT) {
9274  // FIXME: This isn't correct! But tricky to implement because
9275  // the array's size has to be the size of RHS, but the type
9276  // has to be different.
9277  return RHS;
9278  }
9279  if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
9280  if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
9281  return getIncompleteArrayType(ResultType,
9283  }
9284  case Type::FunctionNoProto:
9285  return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
9286  case Type::Record:
9287  case Type::Enum:
9288  return {};
9289  case Type::Builtin:
9290  // Only exactly equal builtin types are compatible, which is tested above.
9291  return {};
9292  case Type::Complex:
9293  // Distinct complex types are incompatible.
9294  return {};
9295  case Type::Vector:
9296  // FIXME: The merged type should be an ExtVector!
9297  if (areCompatVectorTypes(LHSCan->castAs<VectorType>(),
9298  RHSCan->castAs<VectorType>()))
9299  return LHS;
9300  return {};
9301  case Type::ObjCObject: {
9302  // Check if the types are assignment compatible.
9303  // FIXME: This should be type compatibility, e.g. whether
9304  // "LHS x; RHS x;" at global scope is legal.
9306  RHS->castAs<ObjCObjectType>()))
9307  return LHS;
9308  return {};
9309  }
9310  case Type::ObjCObjectPointer:
9311  if (OfBlockPointer) {
9313  LHS->castAs<ObjCObjectPointerType>(),
9314  RHS->castAs<ObjCObjectPointerType>(), BlockReturnType))
9315  return LHS;
9316  return {};
9317  }
9319  RHS->castAs<ObjCObjectPointerType>()))
9320  return LHS;
9321  return {};
9322  case Type::Pipe:
9323  assert(LHS != RHS &&
9324  "Equivalent pipe types should have already been handled!");
9325  return {};
9326  }
9327 
9328  llvm_unreachable("Invalid Type::Class!");
9329 }
9330 
9332  const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType,
9333  bool &CanUseFirst, bool &CanUseSecond,
9335  assert(NewParamInfos.empty() && "param info list not empty");
9336  CanUseFirst = CanUseSecond = true;
9337  bool FirstHasInfo = FirstFnType->hasExtParameterInfos();
9338  bool SecondHasInfo = SecondFnType->hasExtParameterInfos();
9339 
9340  // Fast path: if the first type doesn't have ext parameter infos,
9341  // we match if and only if the second type also doesn't have them.
9342  if (!FirstHasInfo && !SecondHasInfo)
9343  return true;
9344 
9345  bool NeedParamInfo = false;
9346  size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size()
9347  : SecondFnType->getExtParameterInfos().size();
9348 
9349  for (size_t I = 0; I < E; ++I) {
9350  FunctionProtoType::ExtParameterInfo FirstParam, SecondParam;
9351  if (FirstHasInfo)
9352  FirstParam = FirstFnType->getExtParameterInfo(I);
9353  if (SecondHasInfo)
9354  SecondParam = SecondFnType->getExtParameterInfo(I);
9355 
9356  // Cannot merge unless everything except the noescape flag matches.
9357  if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false))
9358  return false;
9359 
9360  bool FirstNoEscape = FirstParam.isNoEscape();
9361  bool SecondNoEscape = SecondParam.isNoEscape();
9362  bool IsNoEscape = FirstNoEscape && SecondNoEscape;
9363  NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape));
9364  if (NewParamInfos.back().getOpaqueValue())
9365  NeedParamInfo = true;
9366  if (FirstNoEscape != IsNoEscape)
9367  CanUseFirst = false;
9368  if (SecondNoEscape != IsNoEscape)
9369  CanUseSecond = false;
9370  }
9371 
9372  if (!NeedParamInfo)
9373  NewParamInfos.clear();
9374 
9375  return true;
9376 }
9377 
9379  ObjCLayouts[CD] = nullptr;
9380 }
9381 
9382 /// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
9383 /// 'RHS' attributes and returns the merged version; including for function
9384 /// return types.
9386  QualType LHSCan = getCanonicalType(LHS),
9387  RHSCan = getCanonicalType(RHS);
9388  // If two types are identical, they are compatible.
9389  if (LHSCan == RHSCan)
9390  return LHS;
9391  if (RHSCan->isFunctionType()) {
9392  if (!LHSCan->isFunctionType())
9393  return {};
9394  QualType OldReturnType =
9395  cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
9396  QualType NewReturnType =
9397  cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
9398  QualType ResReturnType =
9399  mergeObjCGCQualifiers(NewReturnType, OldReturnType);
9400  if (ResReturnType.isNull())
9401  return {};
9402  if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
9403  // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
9404  // In either case, use OldReturnType to build the new function type.
9405  const auto *F = LHS->castAs<FunctionType>();
9406  if (const auto *FPT = cast<FunctionProtoType>(F)) {
9407  FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9408  EPI.ExtInfo = getFunctionExtInfo(LHS);
9409  QualType ResultType =
9410  getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
9411  return ResultType;
9412  }
9413  }
9414  return {};
9415  }
9416 
9417  // If the qualifiers are different, the types can still be merged.
9418  Qualifiers LQuals = LHSCan.getLocalQualifiers();
9419  Qualifiers RQuals = RHSCan.getLocalQualifiers();
9420  if (LQuals != RQuals) {
9421  // If any of these qualifiers are different, we have a type mismatch.
9422  if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
9423  LQuals.getAddressSpace() != RQuals.getAddressSpace())
9424  return {};
9425 
9426  // Exactly one GC qualifier difference is allowed: __strong is
9427  // okay if the other type has no GC qualifier but is an Objective
9428  // C object pointer (i.e. implicitly strong by default). We fix
9429  // this by pretending that the unqualified type was actually
9430  // qualified __strong.
9431  Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
9432  Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
9433  assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
9434 
9435  if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
9436  return {};
9437 
9438  if (GC_L == Qualifiers::Strong)
9439  return LHS;
9440  if (GC_R == Qualifiers::Strong)
9441  return RHS;
9442  return {};
9443  }
9444 
9445  if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
9446  QualType LHSBaseQT = LHS->castAs<ObjCObjectPointerType>()->getPointeeType();
9447  QualType RHSBaseQT = RHS->castAs<ObjCObjectPointerType>()->getPointeeType();
9448  QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
9449  if (ResQT == LHSBaseQT)
9450  return LHS;
9451  if (ResQT == RHSBaseQT)
9452  return RHS;
9453  }
9454  return {};
9455 }
9456 
9457 //===----------------------------------------------------------------------===//
9458 // Integer Predicates
9459 //===----------------------------------------------------------------------===//
9460 
9462  if (const auto *ET = T->getAs<EnumType>())
9463  T = ET->getDecl()->getIntegerType();
9464  if (T->isBooleanType())
9465  return 1;
9466  // For builtin types, just use the standard type sizing method
9467  return (unsigned)getTypeSize(T);
9468 }
9469 
9472  "Unexpected type");
9473 
9474  // Turn <4 x signed int> -> <4 x unsigned int>
9475  if (const auto *VTy = T->getAs<VectorType>())
9476  return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
9477  VTy->getNumElements(), VTy->getVectorKind());
9478 
9479  // For enums, we return the unsigned version of the base type.
9480  if (const auto *ETy = T->getAs<EnumType>())
9481  T = ETy->getDecl()->getIntegerType();
9482 
9483  switch (T->castAs<BuiltinType>()->getKind()) {
9484  case BuiltinType::Char_S:
9485  case BuiltinType::SChar:
9486  return UnsignedCharTy;
9487  case BuiltinType::Short:
9488  return UnsignedShortTy;
9489  case BuiltinType::Int:
9490  return UnsignedIntTy;
9491  case BuiltinType::Long:
9492  return UnsignedLongTy;
9493  case BuiltinType::LongLong:
9494  return UnsignedLongLongTy;
9495  case BuiltinType::Int128:
9496  return UnsignedInt128Ty;
9497 
9498  case BuiltinType::ShortAccum:
9499  return UnsignedShortAccumTy;
9500  case BuiltinType::Accum:
9501  return UnsignedAccumTy;
9502  case BuiltinType::LongAccum:
9503  return UnsignedLongAccumTy;
9504  case BuiltinType::SatShortAccum:
9505  return SatUnsignedShortAccumTy;
9506  case BuiltinType::SatAccum:
9507  return SatUnsignedAccumTy;
9508  case BuiltinType::SatLongAccum:
9509  return SatUnsignedLongAccumTy;
9510  case BuiltinType::ShortFract:
9511  return UnsignedShortFractTy;
9512  case BuiltinType::Fract:
9513  return UnsignedFractTy;
9514  case BuiltinType::LongFract:
9515  return UnsignedLongFractTy;
9516  case BuiltinType::SatShortFract:
9517  return SatUnsignedShortFractTy;
9518  case BuiltinType::SatFract:
9519  return SatUnsignedFractTy;
9520  case BuiltinType::SatLongFract:
9521  return SatUnsignedLongFractTy;
9522  default:
9523  llvm_unreachable("Unexpected signed integer or fixed point type");
9524  }
9525 }
9526 
9528 
9530  QualType ReturnType) {}
9531 
9532 //===----------------------------------------------------------------------===//
9533 // Builtin Type Computation
9534 //===----------------------------------------------------------------------===//
9535 
9536 /// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
9537 /// pointer over the consumed characters. This returns the resultant type. If
9538 /// AllowTypeModifiers is false then modifier like * are not parsed, just basic
9539 /// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
9540 /// a vector of "i*".
9541 ///
9542 /// RequiresICE is filled in on return to indicate whether the value is required
9543 /// to be an Integer Constant Expression.
9544 static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
9546  bool &RequiresICE,
9547  bool AllowTypeModifiers) {
9548  // Modifiers.
9549  int HowLong = 0;
9550  bool Signed = false, Unsigned = false;
9551  RequiresICE = false;
9552 
9553  // Read the prefixed modifiers first.
9554  bool Done = false;
9555  #ifndef NDEBUG
9556  bool IsSpecial = false;
9557  #endif
9558  while (!Done) {
9559  switch (*Str++) {
9560  default: Done = true; --Str; break;
9561  case 'I':
9562  RequiresICE = true;
9563  break;
9564  case 'S':
9565  assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
9566  assert(!Signed && "Can't use 'S' modifier multiple times!");
9567  Signed = true;
9568  break;
9569  case 'U':
9570  assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
9571  assert(!Unsigned && "Can't use 'U' modifier multiple times!");
9572  Unsigned = true;
9573  break;
9574  case 'L':
9575  assert(!IsSpecial && "Can't use 'L' with 'W', 'N', 'Z' or 'O' modifiers");
9576  assert(HowLong <= 2 && "Can't have LLLL modifier");
9577  ++HowLong;
9578  break;
9579  case 'N':
9580  // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
9581  assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
9582  assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
9583  #ifndef NDEBUG
9584  IsSpecial = true;
9585  #endif
9586  if (Context.getTargetInfo().getLongWidth() == 32)
9587  ++HowLong;
9588  break;
9589  case 'W':
9590  // This modifier represents int64 type.
9591  assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
9592  assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
9593  #ifndef NDEBUG
9594  IsSpecial = true;
9595  #endif
9596  switch (Context.getTargetInfo().getInt64Type()) {
9597  default:
9598  llvm_unreachable("Unexpected integer type");
9600  HowLong = 1;
9601  break;
9603  HowLong = 2;
9604  break;
9605  }
9606  break;
9607  case 'Z':
9608  // This modifier represents int32 type.
9609  assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
9610  assert(HowLong == 0 && "Can't use both 'L' and 'Z' modifiers!");
9611  #ifndef NDEBUG
9612  IsSpecial = true;
9613  #endif
9614  switch (Context.getTargetInfo().getIntTypeByWidth(32, true)) {
9615  default:
9616  llvm_unreachable("Unexpected integer type");
9617  case TargetInfo::SignedInt:
9618  HowLong = 0;
9619  break;
9621  HowLong = 1;
9622  break;
9624  HowLong = 2;
9625  break;
9626  }
9627  break;
9628  case 'O':
9629  assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
9630  assert(HowLong == 0 && "Can't use both 'L' and 'O' modifiers!");
9631  #ifndef NDEBUG
9632  IsSpecial = true;
9633  #endif
9634  if (Context.getLangOpts().OpenCL)
9635  HowLong = 1;
9636  else
9637  HowLong = 2;
9638  break;
9639  }
9640  }
9641 
9642  QualType Type;
9643 
9644  // Read the base type.
9645  switch (*Str++) {
9646  default: llvm_unreachable("Unknown builtin type letter!");
9647  case 'v':
9648  assert(HowLong == 0 && !Signed && !Unsigned &&
9649  "Bad modifiers used with 'v'!");
9650  Type = Context.VoidTy;
9651  break;
9652  case 'h':
9653  assert(HowLong == 0 && !Signed && !Unsigned &&
9654  "Bad modifiers used with 'h'!");
9655  Type = Context.HalfTy;
9656  break;
9657  case 'f':
9658  assert(HowLong == 0 && !Signed && !Unsigned &&
9659  "Bad modifiers used with 'f'!");
9660  Type = Context.FloatTy;
9661  break;
9662  case 'd':
9663  assert(HowLong < 3 && !Signed && !Unsigned &&
9664  "Bad modifiers used with 'd'!");
9665  if (HowLong == 1)
9666  Type = Context.LongDoubleTy;
9667  else if (HowLong == 2)
9668  Type = Context.Float128Ty;
9669  else
9670  Type = Context.DoubleTy;
9671  break;
9672  case 's':
9673  assert(HowLong == 0 && "Bad modifiers used with 's'!");
9674  if (Unsigned)
9675  Type = Context.UnsignedShortTy;
9676  else
9677  Type = Context.ShortTy;
9678  break;
9679  case 'i':
9680  if (HowLong == 3)
9681  Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
9682  else if (HowLong == 2)
9683  Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
9684  else if (HowLong == 1)
9685  Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
9686  else
9687  Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
9688  break;
9689  case 'c':
9690  assert(HowLong == 0 && "Bad modifiers used with 'c'!");
9691  if (Signed)
9692  Type = Context.SignedCharTy;
9693  else if (Unsigned)
9694  Type = Context.UnsignedCharTy;
9695  else
9696  Type = Context.CharTy;
9697  break;
9698  case 'b': // boolean
9699  assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
9700  Type = Context.BoolTy;
9701  break;
9702  case 'z': // size_t.
9703  assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
9704  Type = Context.getSizeType();
9705  break;
9706  case 'w': // wchar_t.
9707  assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
9708  Type = Context.getWideCharType();
9709  break;
9710  case 'F':
9711  Type = Context.getCFConstantStringType();
9712  break;
9713  case 'G':
9714  Type = Context.getObjCIdType();
9715  break;
9716  case 'H':
9717  Type = Context.getObjCSelType();
9718  break;
9719  case 'M':
9720  Type = Context.getObjCSuperType();
9721  break;
9722  case 'a':
9723  Type = Context.getBuiltinVaListType();
9724  assert(!Type.isNull() && "builtin va list type not initialized!");
9725  break;
9726  case 'A':
9727  // This is a "reference" to a va_list; however, what exactly
9728  // this means depends on how va_list is defined. There are two
9729  // different kinds of va_list: ones passed by value, and ones
9730  // passed by reference. An example of a by-value va_list is
9731  // x86, where va_list is a char*. An example of by-ref va_list
9732  // is x86-64, where va_list is a __va_list_tag[1]. For x86,
9733  // we want this argument to be a char*&; for x86-64, we want
9734  // it to be a __va_list_tag*.
9735  Type = Context.getBuiltinVaListType();
9736  assert(!Type.isNull() && "builtin va list type not initialized!");
9737  if (Type->isArrayType())
9738  Type = Context.getArrayDecayedType(Type);
9739  else
9740  Type = Context.getLValueReferenceType(Type);
9741  break;
9742  case 'V': {
9743  char *End;
9744  unsigned NumElements = strtoul(Str, &End, 10);
9745  assert(End != Str && "Missing vector size");
9746  Str = End;
9747 
9748  QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
9749  RequiresICE, false);
9750  assert(!RequiresICE && "Can't require vector ICE");
9751 
9752  // TODO: No way to make AltiVec vectors in builtins yet.
9753  Type = Context.getVectorType(ElementType, NumElements,
9755  break;
9756  }
9757  case 'E': {
9758  char *End;
9759 
9760  unsigned NumElements = strtoul(Str, &End, 10);
9761  assert(End != Str && "Missing vector size");
9762 
9763  Str = End;
9764 
9765  QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
9766  false);
9767  Type = Context.getExtVectorType(ElementType, NumElements);
9768  break;
9769  }
9770  case 'X': {
9771  QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
9772  false);
9773  assert(!RequiresICE && "Can't require complex ICE");
9774  Type = Context.getComplexType(ElementType);
9775  break;
9776  }
9777  case 'Y':
9778  Type = Context.getPointerDiffType();
9779  break;
9780  case 'P':
9781  Type = Context.getFILEType();
9782  if (Type.isNull()) {
9784  return {};
9785  }
9786  break;
9787  case 'J':
9788  if (Signed)
9789  Type = Context.getsigjmp_bufType();
9790  else
9791  Type = Context.getjmp_bufType();
9792 
9793  if (Type.isNull()) {
9795  return {};
9796  }
9797  break;
9798  case 'K':
9799  assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
9800  Type = Context.getucontext_tType();
9801 
9802  if (Type.isNull()) {
9804  return {};
9805  }
9806  break;
9807  case 'p':
9808  Type = Context.getProcessIDType();
9809  break;
9810  }
9811 
9812  // If there are modifiers and if we're allowed to parse them, go for it.
9813  Done = !AllowTypeModifiers;
9814  while (!Done) {
9815  switch (char c = *Str++) {
9816  default: Done = true; --Str; break;
9817  case '*':
9818  case '&': {
9819  // Both pointers and references can have their pointee types
9820  // qualified with an address space.
9821  char *End;
9822  unsigned AddrSpace = strtoul(Str, &End, 10);
9823  if (End != Str) {
9824  // Note AddrSpace == 0 is not the same as an unspecified address space.
9825  Type = Context.getAddrSpaceQualType(
9826  Type,
9827  Context.getLangASForBuiltinAddressSpace(AddrSpace));
9828  Str = End;
9829  }
9830  if (c == '*')
9831  Type = Context.getPointerType(Type);
9832  else
9833  Type = Context.getLValueReferenceType(Type);
9834  break;
9835  }
9836  // FIXME: There's no way to have a built-in with an rvalue ref arg.
9837  case 'C':
9838  Type = Type.withConst();
9839  break;
9840  case 'D':
9841  Type = Context.getVolatileType(Type);
9842  break;
9843  case 'R':
9844  Type = Type.withRestrict();
9845  break;
9846  }
9847  }
9848 
9849  assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
9850  "Integer constant 'I' type must be an integer");
9851 
9852  return Type;
9853 }
9854 
9855 /// GetBuiltinType - Return the type for the specified builtin.
9858  unsigned *IntegerConstantArgs) const {
9859  const char *TypeStr = BuiltinInfo.getTypeString(Id);
9860  if (TypeStr[0] == '\0') {
9861  Error = GE_Missing_type;
9862  return {};
9863  }
9864 
9865  SmallVector<QualType, 8> ArgTypes;
9866 
9867  bool RequiresICE = false;
9868  Error = GE_None;
9869  QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
9870  RequiresICE, true);
9871  if (Error != GE_None)
9872  return {};
9873 
9874  assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
9875 
9876  while (TypeStr[0] && TypeStr[0] != '.') {
9877  QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
9878  if (Error != GE_None)
9879  return {};
9880 
9881  // If this argument is required to be an IntegerConstantExpression and the
9882  // caller cares, fill in the bitmask we return.
9883  if (RequiresICE && IntegerConstantArgs)
9884  *IntegerConstantArgs |= 1 << ArgTypes.size();
9885 
9886  // Do array -> pointer decay. The builtin should use the decayed type.
9887  if (Ty->isArrayType())
9888  Ty = getArrayDecayedType(Ty);
9889 
9890  ArgTypes.push_back(Ty);
9891  }
9892 
9893  if (Id == Builtin::BI__GetExceptionInfo)
9894  return {};
9895 
9896  assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
9897  "'.' should only occur at end of builtin type list!");
9898 
9899  bool Variadic = (TypeStr[0] == '.');
9900 
9902  Variadic, /*IsCXXMethod=*/false, /*IsBuiltin=*/true));
9903  if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
9904 
9905 
9906  // We really shouldn't be making a no-proto type here.
9907  if (ArgTypes.empty() && Variadic && !getLangOpts().CPlusPlus)
9908  return getFunctionNoProtoType(ResType, EI);
9909 
9911  EPI.ExtInfo = EI;
9912  EPI.Variadic = Variadic;
9913  if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id))
9914  EPI.ExceptionSpec.Type =
9915  getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
9916 
9917  return getFunctionType(ResType, ArgTypes, EPI);
9918 }
9919 
9921  const FunctionDecl *FD) {
9922  if (!FD->isExternallyVisible())
9923  return GVA_Internal;
9924 
9925  // Non-user-provided functions get emitted as weak definitions with every
9926  // use, no matter whether they've been explicitly instantiated etc.
9927  if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
9928  if (!MD->isUserProvided())
9929  return GVA_DiscardableODR;
9930 
9931  GVALinkage External;
9932  switch (FD->getTemplateSpecializationKind()) {
9933  case TSK_Undeclared:
9935  External = GVA_StrongExternal;
9936  break;
9937 
9939  return GVA_StrongODR;
9940 
9941  // C++11 [temp.explicit]p10:
9942  // [ Note: The intent is that an inline function that is the subject of
9943  // an explicit instantiation declaration will still be implicitly
9944  // instantiated when used so that the body can be considered for
9945  // inlining, but that no out-of-line copy of the inline function would be
9946  // generated in the translation unit. -- end note ]
9948  return GVA_AvailableExternally;
9949 
9951  External = GVA_DiscardableODR;
9952  break;
9953  }
9954 
9955  if (!FD->isInlined())
9956  return External;
9957 
9958  if ((!Context.getLangOpts().CPlusPlus &&
9959  !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
9960  !FD->hasAttr<DLLExportAttr>()) ||
9961  FD->hasAttr<GNUInlineAttr>()) {
9962  // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
9963 
9964  // GNU or C99 inline semantics. Determine whether this symbol should be
9965  // externally visible.
9967  return External;
9968 
9969  // C99 inline semantics, where the symbol is not externally visible.
9970  return GVA_AvailableExternally;
9971  }
9972 
9973  // Functions specified with extern and inline in -fms-compatibility mode
9974  // forcibly get emitted. While the body of the function cannot be later
9975  // replaced, the function definition cannot be discarded.
9976  if (FD->isMSExternInline())
9977  return GVA_StrongODR;
9978 
9979  return GVA_DiscardableODR;
9980 }
9981 
9983  const Decl *D, GVALinkage L) {
9984  // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
9985  // dllexport/dllimport on inline functions.
9986  if (D->hasAttr<DLLImportAttr>()) {
9987  if (L == GVA_DiscardableODR || L == GVA_StrongODR)
9988  return GVA_AvailableExternally;
9989  } else if (D->hasAttr<DLLExportAttr>()) {
9990  if (L == GVA_DiscardableODR)
9991  return GVA_StrongODR;
9992  } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice &&
9993  D->hasAttr<CUDAGlobalAttr>()) {
9994  // Device-side functions with __global__ attribute must always be
9995  // visible externally so they can be launched from host.
9996  if (L == GVA_DiscardableODR || L == GVA_Internal)
9997  return GVA_StrongODR;
9998  }
9999  return L;
10000 }
10001 
10002 /// Adjust the GVALinkage for a declaration based on what an external AST source
10003 /// knows about whether there can be other definitions of this declaration.
10004 static GVALinkage
10006  GVALinkage L) {
10007  ExternalASTSource *Source = Ctx.getExternalSource();
10008  if (!Source)
10009  return L;
10010 
10011  switch (Source->hasExternalDefinitions(D)) {
10013  // Other translation units rely on us to provide the definition.
10014  if (L == GVA_DiscardableODR)
10015  return GVA_StrongODR;
10016  break;
10017 
10019  return GVA_AvailableExternally;
10020 
10022  break;
10023  }
10024  return L;
10025 }
10026 
10030  basicGVALinkageForFunction(*this, FD)));
10031 }
10032 
10034  const VarDecl *VD) {
10035  if (!VD->isExternallyVisible())
10036  return GVA_Internal;
10037 
10038  if (VD->isStaticLocal()) {
10039  const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
10040  while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
10041  LexicalContext = LexicalContext->getLexicalParent();
10042 
10043  // ObjC Blocks can create local variables that don't have a FunctionDecl
10044  // LexicalContext.
10045  if (!LexicalContext)
10046  return GVA_DiscardableODR;
10047 
10048  // Otherwise, let the static local variable inherit its linkage from the
10049  // nearest enclosing function.
10050  auto StaticLocalLinkage =
10051  Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
10052 
10053  // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
10054  // be emitted in any object with references to the symbol for the object it
10055  // contains, whether inline or out-of-line."
10056  // Similar behavior is observed with MSVC. An alternative ABI could use
10057  // StrongODR/AvailableExternally to match the function, but none are
10058  // known/supported currently.
10059  if (StaticLocalLinkage == GVA_StrongODR ||
10060  StaticLocalLinkage == GVA_AvailableExternally)
10061  return GVA_DiscardableODR;
10062  return StaticLocalLinkage;
10063  }
10064 
10065  // MSVC treats in-class initialized static data members as definitions.
10066  // By giving them non-strong linkage, out-of-line definitions won't
10067  // cause link errors.
10068  if (Context.isMSStaticDataMemberInlineDefinition(VD))
10069  return GVA_DiscardableODR;
10070 
10071  // Most non-template variables have strong linkage; inline variables are
10072  // linkonce_odr or (occasionally, for compatibility) weak_odr.
10073  GVALinkage StrongLinkage;
10074  switch (Context.getInlineVariableDefinitionKind(VD)) {
10076  StrongLinkage = GVA_StrongExternal;
10077  break;
10080  StrongLinkage = GVA_DiscardableODR;
10081  break;
10083  StrongLinkage = GVA_StrongODR;
10084  break;
10085  }
10086 
10087  switch (VD->getTemplateSpecializationKind()) {
10088  case TSK_Undeclared:
10089  return StrongLinkage;
10090 
10092  return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
10093  VD->isStaticDataMember()
10094  ? GVA_StrongODR
10095  : StrongLinkage;
10096 
10098  return GVA_StrongODR;
10099 
10101  return GVA_AvailableExternally;
10102 
10104  return GVA_DiscardableODR;
10105  }
10106 
10107  llvm_unreachable("Invalid Linkage!");
10108 }
10109 
10113  basicGVALinkageForVariable(*this, VD)));
10114 }
10115 
10116 bool ASTContext::DeclMustBeEmitted(const Decl *D) {
10117  if (const auto *VD = dyn_cast<VarDecl>(D)) {
10118  if (!VD->isFileVarDecl())
10119  return false;
10120  // Global named register variables (GNU extension) are never emitted.
10121  if (VD->getStorageClass() == SC_Register)
10122  return false;
10123  if (VD->getDescribedVarTemplate() ||
10124  isa<VarTemplatePartialSpecializationDecl>(VD))
10125  return false;
10126  } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
10127  // We never need to emit an uninstantiated function template.
10128  if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
10129  return false;
10130  } else if (isa<PragmaCommentDecl>(D))
10131  return true;
10132  else if (isa<PragmaDetectMismatchDecl>(D))
10133  return true;
10134  else if (isa<OMPThreadPrivateDecl>(D))
10135  return !D->getDeclContext()->isDependentContext();
10136  else if (isa<OMPAllocateDecl>(D))
10137  return !D->getDeclContext()->isDependentContext();
10138  else if (isa<OMPDeclareReductionDecl>(D) || isa<OMPDeclareMapperDecl>(D))
10139  return !D->getDeclContext()->isDependentContext();
10140  else if (isa<ImportDecl>(D))
10141  return true;
10142  else
10143  return false;
10144 
10145  if (D->isFromASTFile() && !LangOpts.BuildingPCHWithObjectFile) {
10146  assert(getExternalSource() && "It's from an AST file; must have a source.");
10147  // On Windows, PCH files are built together with an object file. If this
10148  // declaration comes from such a PCH and DeclMustBeEmitted would return
10149  // true, it would have returned true and the decl would have been emitted
10150  // into that object file, so it doesn't need to be emitted here.
10151  // Note that decls are still emitted if they're referenced, as usual;
10152  // DeclMustBeEmitted is used to decide whether a decl must be emitted even
10153  // if it's not referenced.
10154  //
10155  // Explicit template instantiation definitions are tricky. If there was an
10156  // explicit template instantiation decl in the PCH before, it will look like
10157  // the definition comes from there, even if that was just the declaration.
10158  // (Explicit instantiation defs of variable templates always get emitted.)
10159  bool IsExpInstDef =
10160  isa<FunctionDecl>(D) &&
10161  cast<FunctionDecl>(D)->getTemplateSpecializationKind() ==
10163 
10164  // Implicit member function definitions, such as operator= might not be
10165  // marked as template specializations, since they're not coming from a
10166  // template but synthesized directly on the class.
10167  IsExpInstDef |=
10168  isa<CXXMethodDecl>(D) &&
10169  cast<CXXMethodDecl>(D)->getParent()->getTemplateSpecializationKind() ==
10171 
10172  if (getExternalSource()->DeclIsFromPCHWithObjectFile(D) && !IsExpInstDef)
10173  return false;
10174  }
10175 
10176  // If this is a member of a class template, we do not need to emit it.
10177  if (D->getDeclContext()->isDependentContext())
10178  return false;
10179 
10180  // Weak references don't produce any output by themselves.
10181  if (D->hasAttr<WeakRefAttr>())
10182  return false;
10183 
10184  // Aliases and used decls are required.
10185  if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
10186  return true;
10187 
10188  if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
10189  // Forward declarations aren't required.
10190  if (!FD->doesThisDeclarationHaveABody())
10191  return FD->doesDeclarationForceExternallyVisibleDefinition();
10192 
10193  // Constructors and destructors are required.
10194  if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
10195  return true;
10196 
10197  // The key function for a class is required. This rule only comes
10198  // into play when inline functions can be key functions, though.
10199  if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
10200  if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
10201  const CXXRecordDecl *RD = MD->getParent();
10202  if (MD->isOutOfLine() && RD->isDynamicClass()) {
10203  const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
10204  if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
10205  return true;
10206  }
10207  }
10208  }
10209 
10211 
10212  // static, static inline, always_inline, and extern inline functions can
10213  // always be deferred. Normal inline functions can be deferred in C99/C++.
10214  // Implicit template instantiations can also be deferred in C++.
10215  return !isDiscardableGVALinkage(Linkage);
10216  }
10217 
10218  const auto *VD = cast<VarDecl>(D);
10219  assert(VD->isFileVarDecl() && "Expected file scoped var");
10220 
10221  // If the decl is marked as `declare target to`, it should be emitted for the
10222  // host and for the device.
10223  if (LangOpts.OpenMP &&
10224  OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
10225  return true;
10226 
10227  if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
10229  return false;
10230 
10231  // Variables that can be needed in other TUs are required.
10232  auto Linkage = GetGVALinkageForVariable(VD);
10234  return true;
10235 
10236  // We never need to emit a variable that is available in another TU.
10238  return false;
10239 
10240  // Variables that have destruction with side-effects are required.
10241  if (VD->needsDestruction(*this))
10242  return true;
10243 
10244  // Variables that have initialization with side-effects are required.
10245  if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
10246  // We can get a value-dependent initializer during error recovery.
10247  (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
10248  return true;
10249 
10250  // Likewise, variables with tuple-like bindings are required if their
10251  // bindings have side-effects.
10252  if (const auto *DD = dyn_cast<DecompositionDecl>(VD))
10253  for (const auto *BD : DD->bindings())
10254  if (const auto *BindingVD = BD->getHoldingVar())
10255  if (DeclMustBeEmitted(BindingVD))
10256  return true;
10257 
10258  return false;
10259 }
10260 
10262  const FunctionDecl *FD,
10263  llvm::function_ref<void(FunctionDecl *)> Pred) const {
10264  assert(FD->isMultiVersion() && "Only valid for multiversioned functions");
10265  llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls;
10266  FD = FD->getMostRecentDecl();
10267  for (auto *CurDecl :
10269  FunctionDecl *CurFD = CurDecl->getAsFunction()->getMostRecentDecl();
10270  if (CurFD && hasSameType(CurFD->getType(), FD->getType()) &&
10271  std::end(SeenDecls) == llvm::find(SeenDecls, CurFD)) {
10272  SeenDecls.insert(CurFD);
10273  Pred(CurFD);
10274  }
10275  }
10276 }
10277 
10279  bool IsCXXMethod,
10280  bool IsBuiltin) const {
10281  // Pass through to the C++ ABI object
10282  if (IsCXXMethod)
10283  return ABI->getDefaultMethodCallConv(IsVariadic);
10284 
10285  // Builtins ignore user-specified default calling convention and remain the
10286  // Target's default calling convention.
10287  if (!IsBuiltin) {
10288  switch (LangOpts.getDefaultCallingConv()) {
10289  case LangOptions::DCC_None:
10290  break;
10292  return CC_C;
10294  if (getTargetInfo().hasFeature("sse2") && !IsVariadic)
10295  return CC_X86FastCall;
10296  break;
10298  if (!IsVariadic)
10299  return CC_X86StdCall;
10300  break;
10302  // __vectorcall cannot be applied to variadic functions.
10303  if (!IsVariadic)
10304  return CC_X86VectorCall;
10305  break;
10307  // __regcall cannot be applied to variadic functions.
10308  if (!IsVariadic)
10309  return CC_X86RegCall;
10310  break;
10311  }
10312  }
10313  return Target->getDefaultCallingConv();
10314 }
10315 
10317  // Pass through to the C++ ABI object
10318  return ABI->isNearlyEmpty(RD);
10319 }
10320 
10322  if (!VTContext.get()) {
10323  if (Target->getCXXABI().isMicrosoft())
10324  VTContext.reset(new MicrosoftVTableContext(*this));
10325  else
10326  VTContext.reset(new ItaniumVTableContext(*this));
10327  }
10328  return VTContext.get();
10329 }
10330 
10332  if (!T)
10333  T = Target;
10334  switch (T->getCXXABI().getKind()) {
10335  case TargetCXXABI::Fuchsia:
10340  case TargetCXXABI::iOS:
10341  case TargetCXXABI::iOS64:
10343  case TargetCXXABI::WatchOS:
10347  }
10348  llvm_unreachable("Unsupported ABI");
10349 }
10350 
10351 CXXABI::~CXXABI() = default;
10352 
10354  return ASTRecordLayouts.getMemorySize() +
10355  llvm::capacity_in_bytes(ObjCLayouts) +
10356  llvm::capacity_in_bytes(KeyFunctions) +
10357  llvm::capacity_in_bytes(ObjCImpls) +
10358  llvm::capacity_in_bytes(BlockVarCopyInits) +
10359  llvm::capacity_in_bytes(DeclAttrs) +
10360  llvm::capacity_in_bytes(TemplateOrInstantiation) +
10361  llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
10362  llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
10363  llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
10364  llvm::capacity_in_bytes(OverriddenMethods) +
10365  llvm::capacity_in_bytes(Types) +
10366  llvm::capacity_in_bytes(VariableArrayTypes);
10367 }
10368 
10369 /// getIntTypeForBitwidth -
10370 /// sets integer QualTy according to specified details:
10371 /// bitwidth, signed/unsigned.
10372 /// Returns empty type if there is no appropriate target types.
10374  unsigned Signed) const {
10375  TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
10376  CanQualType QualTy = getFromTargetType(Ty);
10377  if (!QualTy && DestWidth == 128)
10378  return Signed ? Int128Ty : UnsignedInt128Ty;
10379  return QualTy;
10380 }
10381 
10382 /// getRealTypeForBitwidth -
10383 /// sets floating point QualTy according to specified bitwidth.
10384 /// Returns empty type if there is no appropriate target types.
10387  switch (Ty) {
10388  case TargetInfo::Float:
10389  return FloatTy;
10390  case TargetInfo::Double:
10391  return DoubleTy;
10393  return LongDoubleTy;
10394  case TargetInfo::Float128:
10395  return Float128Ty;
10396  case TargetInfo::NoFloat:
10397  return {};
10398  }
10399 
10400  llvm_unreachable("Unhandled TargetInfo::RealType value");
10401 }
10402 
10403 void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
10404  if (Number > 1)
10405  MangleNumbers[ND] = Number;
10406 }
10407 
10408 unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
10409  auto I = MangleNumbers.find(ND);
10410  return I != MangleNumbers.end() ? I->second : 1;
10411 }
10412 
10413 void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
10414  if (Number > 1)
10415  StaticLocalNumbers[VD] = Number;
10416 }
10417 
10418 unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
10419  auto I = StaticLocalNumbers.find(VD);
10420  return I != StaticLocalNumbers.end() ? I->second : 1;
10421 }
10422 
10425  assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
10426  std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
10427  if (!MCtx)
10429  return *MCtx;
10430 }
10431 
10434  assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
10435  std::unique_ptr<MangleNumberingContext> &MCtx =
10436  ExtraMangleNumberingContexts[D];
10437  if (!MCtx)
10439  return *MCtx;
10440 }
10441 
10442 std::unique_ptr<MangleNumberingContext>
10444  return ABI->createMangleNumberingContext();
10445 }
10446 
10447 const CXXConstructorDecl *
10449  return ABI->getCopyConstructorForExceptionObject(
10450  cast<CXXRecordDecl>(RD->getFirstDecl()));
10451 }
10452 
10454  CXXConstructorDecl *CD) {
10455  return ABI->addCopyConstructorForExceptionObject(
10456  cast<CXXRecordDecl>(RD->getFirstDecl()),
10457  cast<CXXConstructorDecl>(CD->getFirstDecl()));
10458 }
10459 
10461  TypedefNameDecl *DD) {
10462  return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
10463 }
10464 
10467  return ABI->getTypedefNameForUnnamedTagDecl(TD);
10468 }
10469 
10471  DeclaratorDecl *DD) {
10472  return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
10473 }
10474 
10476  return ABI->getDeclaratorForUnnamedTagDecl(TD);
10477 }
10478 
10479 void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
10480  ParamIndices[D] = index;
10481 }
10482 
10483 unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
10484  ParameterIndexTable::const_iterator I = ParamIndices.find(D);
10485  assert(I != ParamIndices.end() &&
10486  "ParmIndices lacks entry set by ParmVarDecl");
10487  return I->second;
10488 }
10489 
10491  unsigned Length) const {
10492  // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
10493  if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
10494  EltTy = EltTy.withConst();
10495 
10496  EltTy = adjustStringLiteralBaseType(EltTy);
10497 
10498  // Get an array type for the string, according to C99 6.4.5. This includes
10499  // the null terminator character.
10500  return getConstantArrayType(EltTy, llvm::APInt(32, Length + 1), nullptr,
10501  ArrayType::Normal, /*IndexTypeQuals*/ 0);
10502 }
10503 
10504 StringLiteral *
10506  StringLiteral *&Result = StringLiteralCache[Key];
10507  if (!Result)
10508  Result = StringLiteral::Create(
10509  *this, Key, StringLiteral::Ascii,
10510  /*Pascal*/ false, getStringLiteralArrayType(CharTy, Key.size()),
10511  SourceLocation());
10512  return Result;
10513 }
10514 
10516  const llvm::Triple &T = getTargetInfo().getTriple();
10517  if (!T.isOSDarwin())
10518  return false;
10519 
10520  if (!(T.isiOS() && T.isOSVersionLT(7)) &&
10521  !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
10522  return false;
10523 
10524  QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
10525  CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
10526  uint64_t Size = sizeChars.getQuantity();
10527  CharUnits alignChars = getTypeAlignInChars(AtomicTy);
10528  unsigned Align = alignChars.getQuantity();
10529  unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
10530  return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
10531 }
10532 
10533 /// Template specializations to abstract away from pointers and TypeLocs.
10534 /// @{
10535 template <typename T>
10538 }
10539 template <>
10542 }
10543 template <>
10547 }
10548 /// @}
10549 
10550 /// A \c RecursiveASTVisitor that builds a map from nodes to their
10551 /// parents as defined by the \c RecursiveASTVisitor.
10552 ///
10553 /// Note that the relationship described here is purely in terms of AST
10554 /// traversal - there are other relationships (for example declaration context)
10555 /// in the AST that are better modeled by special matchers.
10556 ///
10557 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
10559  : public RecursiveASTVisitor<ASTVisitor> {
10560 public:
10562  : Map(Map), Context(Context) {}
10563 
10564 private:
10566 
10568 
10569  bool shouldVisitTemplateInstantiations() const { return true; }
10570 
10571  bool shouldVisitImplicitCode() const { return true; }
10572 
10573  template <typename T, typename MapNodeTy, typename BaseTraverseFn,
10574  typename MapTy>
10575  bool TraverseNode(T Node, MapNodeTy MapNode, BaseTraverseFn BaseTraverse,
10576  MapTy *Parents) {
10577  if (!Node)
10578  return true;
10579  if (ParentStack.size() > 0) {
10580  // FIXME: Currently we add the same parent multiple times, but only
10581  // when no memoization data is available for the type.
10582  // For example when we visit all subexpressions of template
10583  // instantiations; this is suboptimal, but benign: the only way to
10584  // visit those is with hasAncestor / hasParent, and those do not create
10585  // new matches.
10586  // The plan is to enable DynTypedNode to be storable in a map or hash
10587  // map. The main problem there is to implement hash functions /
10588  // comparison operators for all types that DynTypedNode supports that
10589  // do not have pointer identity.
10590  auto &NodeOrVector = (*Parents)[MapNode];
10591  if (NodeOrVector.isNull()) {
10592  if (const auto *D = ParentStack.back().get<Decl>())
10593  NodeOrVector = D;
10594  else if (const auto *S = ParentStack.back().get<Stmt>())
10595  NodeOrVector = S;
10596  else
10597  NodeOrVector = new ast_type_traits::DynTypedNode(ParentStack.back());
10598  } else {
10599  if (!NodeOrVector.template is<ParentVector *>()) {
10600  auto *Vector = new ParentVector(
10601  1, getSingleDynTypedNodeFromParentMap(NodeOrVector));
10602  delete NodeOrVector
10603  .template dyn_cast<ast_type_traits::DynTypedNode *>();
10604  NodeOrVector = Vector;
10605  }
10606 
10607  auto *Vector = NodeOrVector.template get<ParentVector *>();
10608  // Skip duplicates for types that have memoization data.
10609  // We must check that the type has memoization data before calling
10610  // std::find() because DynTypedNode::operator== can't compare all
10611  // types.
10612  bool Found = ParentStack.back().getMemoizationData() &&
10613  std::find(Vector->begin(), Vector->end(),
10614  ParentStack.back()) != Vector->end();
10615  if (!Found)
10616  Vector->push_back(ParentStack.back());
10617  }
10618  }
10619  ParentStack.push_back(createDynTypedNode(Node));
10620  bool Result = BaseTraverse();
10621  ParentStack.pop_back();
10622  return Result;
10623  }
10624 
10625  bool TraverseDecl(Decl *DeclNode) {
10626  return TraverseNode(
10627  DeclNode, DeclNode, [&] { return VisitorBase::TraverseDecl(DeclNode); },
10628  &Map.PointerParents);
10629  }
10630 
10631  bool TraverseStmt(Stmt *StmtNode) {
10632  Stmt *FilteredNode = StmtNode;
10633  if (auto *ExprNode = dyn_cast_or_null<Expr>(FilteredNode))
10634  FilteredNode = Context.traverseIgnored(ExprNode);
10635  return TraverseNode(FilteredNode, FilteredNode,
10636  [&] { return VisitorBase::TraverseStmt(FilteredNode); },
10637  &Map.PointerParents);
10638  }
10639 
10640  bool TraverseTypeLoc(TypeLoc TypeLocNode) {
10641  return TraverseNode(
10642  TypeLocNode, ast_type_traits::DynTypedNode::create(TypeLocNode),
10643  [&] { return VisitorBase::TraverseTypeLoc(TypeLocNode); },
10644  &Map.OtherParents);
10645  }
10646 
10647  bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNSLocNode) {
10648  return TraverseNode(
10649  NNSLocNode, ast_type_traits::DynTypedNode::create(NNSLocNode),
10650  [&] { return VisitorBase::TraverseNestedNameSpecifierLoc(NNSLocNode); },
10651  &Map.OtherParents);
10652  }
10653 
10654  ParentMap &Map;
10655  ASTContext &Context;
10657 };
10658 
10660  ASTVisitor(*this, Ctx).TraverseAST(Ctx);
10661 }
10662 
10665  std::unique_ptr<ParentMap> &P = Parents[Traversal];
10666  if (!P)
10667  // We build the parent map for the traversal scope (usually whole TU), as
10668  // hasAncestor can escape any subtree.
10669  P = std::make_unique<ParentMap>(*this);
10670  return P->getParents(Node);
10671 }
10672 
10673 bool
10675  const ObjCMethodDecl *MethodImpl) {
10676  // No point trying to match an unavailable/deprecated mothod.
10677  if (MethodDecl->hasAttr<UnavailableAttr>()
10678  || MethodDecl->hasAttr<DeprecatedAttr>())
10679  return false;
10680  if (MethodDecl->getObjCDeclQualifier() !=
10681  MethodImpl->getObjCDeclQualifier())
10682  return false;
10683  if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
10684  return false;
10685 
10686  if (MethodDecl->param_size() != MethodImpl->param_size())
10687  return false;
10688 
10689  for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
10690  IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
10691  EF = MethodDecl->param_end();
10692  IM != EM && IF != EF; ++IM, ++IF) {
10693  const ParmVarDecl *DeclVar = (*IF);
10694  const ParmVarDecl *ImplVar = (*IM);
10695  if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
10696  return false;
10697  if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
10698  return false;
10699  }
10700 
10701  return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
10702 }
10703 
10705  LangAS AS;
10707  AS = LangAS::Default;
10708  else
10709  AS = QT->getPointeeType().getAddressSpace();
10710 
10711  return getTargetInfo().getNullPointerValue(AS);
10712 }
10713 
10715  if (isTargetAddressSpace(AS))
10716  return toTargetAddressSpace(AS);
10717  else
10718  return (*AddrSpaceMap)[(unsigned)AS];
10719 }
10720 
10722  assert(Ty->isFixedPointType());
10723 
10724  if (Ty->isSaturatedFixedPointType()) return Ty;
10725 
10726  switch (Ty->castAs<BuiltinType>()->getKind()) {
10727  default:
10728  llvm_unreachable("Not a fixed point type!");
10729  case BuiltinType::ShortAccum:
10730  return SatShortAccumTy;
10731  case BuiltinType::Accum:
10732  return SatAccumTy;
10733  case BuiltinType::LongAccum:
10734  return SatLongAccumTy;
10735  case BuiltinType::UShortAccum:
10736  return SatUnsignedShortAccumTy;
10737  case BuiltinType::UAccum:
10738  return SatUnsignedAccumTy;
10739  case BuiltinType::ULongAccum:
10740  return SatUnsignedLongAccumTy;
10741  case BuiltinType::ShortFract:
10742  return SatShortFractTy;
10743  case BuiltinType::Fract:
10744  return SatFractTy;
10745  case BuiltinType::LongFract:
10746  return SatLongFractTy;
10747  case BuiltinType::UShortFract:
10748  return SatUnsignedShortFractTy;
10749  case BuiltinType::UFract:
10750  return SatUnsignedFractTy;
10751  case BuiltinType::ULongFract:
10752  return SatUnsignedLongFractTy;
10753  }
10754 }
10755 
10757  if (LangOpts.OpenCL)
10759 
10760  if (LangOpts.CUDA)
10762 
10763  return getLangASFromTargetAS(AS);
10764 }
10765 
10766 // Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
10767 // doesn't include ASTContext.h
10768 template
10770  const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
10772  const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
10773  const clang::ASTContext &Ctx, Decl *Value);
10774 
10775 unsigned char ASTContext::getFixedPointScale(QualType Ty) const {
10776  assert(Ty->isFixedPointType());
10777 
10778  const TargetInfo &Target = getTargetInfo();
10779  switch (Ty->castAs<BuiltinType>()->getKind()) {
10780  default:
10781  llvm_unreachable("Not a fixed point type!");
10782  case BuiltinType::ShortAccum:
10783  case BuiltinType::SatShortAccum:
10784  return Target.getShortAccumScale();
10785  case BuiltinType::Accum:
10786  case BuiltinType::SatAccum:
10787  return Target.getAccumScale();
10788  case BuiltinType::LongAccum:
10789  case BuiltinType::SatLongAccum:
10790  return Target.getLongAccumScale();
10791  case BuiltinType::UShortAccum:
10792  case BuiltinType::SatUShortAccum:
10793  return Target.getUnsignedShortAccumScale();
10794  case BuiltinType::UAccum:
10795  case BuiltinType::SatUAccum:
10796  return Target.getUnsignedAccumScale();
10797  case BuiltinType::ULongAccum:
10798  case BuiltinType::SatULongAccum:
10799  return Target.getUnsignedLongAccumScale();
10800  case BuiltinType::ShortFract:
10801  case BuiltinType::SatShortFract:
10802  return Target.getShortFractScale();
10803  case BuiltinType::Fract:
10804  case BuiltinType::SatFract:
10805  return Target.getFractScale();
10806  case BuiltinType::LongFract:
10807  case BuiltinType::SatLongFract:
10808  return Target.getLongFractScale();
10809  case BuiltinType::UShortFract:
10810  case BuiltinType::SatUShortFract:
10811  return Target.getUnsignedShortFractScale();
10812  case BuiltinType::UFract:
10813  case BuiltinType::SatUFract:
10814  return Target.getUnsignedFractScale();
10815  case BuiltinType::ULongFract:
10816  case BuiltinType::SatULongFract:
10817  return Target.getUnsignedLongFractScale();
10818  }
10819 }
10820 
10821 unsigned char ASTContext::getFixedPointIBits(QualType Ty) const {
10822  assert(Ty->isFixedPointType());
10823 
10824  const TargetInfo &Target = getTargetInfo();
10825  switch (Ty->castAs<BuiltinType>()->getKind()) {
10826  default:
10827  llvm_unreachable("Not a fixed point type!");
10828  case BuiltinType::ShortAccum:
10829  case BuiltinType::SatShortAccum:
10830  return Target.getShortAccumIBits();
10831  case BuiltinType::Accum:
10832  case BuiltinType::SatAccum:
10833  return Target.getAccumIBits();
10834  case BuiltinType::LongAccum:
10835  case BuiltinType::SatLongAccum:
10836  return Target.getLongAccumIBits();
10837  case BuiltinType::UShortAccum:
10838  case BuiltinType::SatUShortAccum:
10839  return Target.getUnsignedShortAccumIBits();
10840  case BuiltinType::UAccum:
10841  case BuiltinType::SatUAccum:
10842  return Target.getUnsignedAccumIBits();
10843  case BuiltinType::ULongAccum:
10844  case BuiltinType::SatULongAccum:
10845  return Target.getUnsignedLongAccumIBits();
10846  case BuiltinType::ShortFract:
10847  case BuiltinType::SatShortFract:
10848  case BuiltinType::Fract:
10849  case BuiltinType::SatFract:
10850  case BuiltinType::LongFract:
10851  case BuiltinType::SatLongFract:
10852  case BuiltinType::UShortFract:
10853  case BuiltinType::SatUShortFract:
10854  case BuiltinType::UFract:
10855  case BuiltinType::SatUFract:
10856  case BuiltinType::ULongFract:
10857  case BuiltinType::SatULongFract:
10858  return 0;
10859  }
10860 }
10861 
10863  assert((Ty->isFixedPointType() || Ty->isIntegerType()) &&
10864  "Can only get the fixed point semantics for a "
10865  "fixed point or integer type.");
10866  if (Ty->isIntegerType())
10868  Ty->isSignedIntegerType());
10869 
10870  bool isSigned = Ty->isSignedFixedPointType();
10871  return FixedPointSemantics(
10872  static_cast<unsigned>(getTypeSize(Ty)), getFixedPointScale(Ty), isSigned,
10875 }
10876 
10878  assert(Ty->isFixedPointType());
10880 }
10881 
10883  assert(Ty->isFixedPointType());
10885 }
10886 
10888  assert(Ty->isUnsignedFixedPointType() &&
10889  "Expected unsigned fixed point type");
10890 
10891  switch (Ty->castAs<BuiltinType>()->getKind()) {
10892  case BuiltinType::UShortAccum:
10893  return ShortAccumTy;
10894  case BuiltinType::UAccum:
10895  return AccumTy;
10896  case BuiltinType::ULongAccum:
10897  return LongAccumTy;
10898  case BuiltinType::SatUShortAccum:
10899  return SatShortAccumTy;
10900  case BuiltinType::SatUAccum:
10901  return SatAccumTy;
10902  case BuiltinType::SatULongAccum:
10903  return SatLongAccumTy;
10904  case BuiltinType::UShortFract:
10905  return ShortFractTy;
10906  case BuiltinType::UFract:
10907  return FractTy;
10908  case BuiltinType::ULongFract:
10909  return LongFractTy;
10910  case BuiltinType::SatUShortFract:
10911  return SatShortFractTy;
10912  case BuiltinType::SatUFract:
10913  return SatFractTy;
10914  case BuiltinType::SatULongFract:
10915  return SatLongFractTy;
10916  default:
10917  llvm_unreachable("Unexpected unsigned fixed point type");
10918  }
10919 }
10920 
10922 ASTContext::filterFunctionTargetAttrs(const TargetAttr *TD) const {
10923  assert(TD != nullptr);
10924  ParsedTargetAttr ParsedAttr = TD->parse();
10925 
10926  ParsedAttr.Features.erase(
10927  llvm::remove_if(ParsedAttr.Features,
10928  [&](const std::string &Feat) {
10929  return !Target->isValidFeatureName(
10930  StringRef{Feat}.substr(1));
10931  }),
10932  ParsedAttr.Features.end());
10933  return ParsedAttr;
10934 }
10935 
10936 void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
10937  const FunctionDecl *FD) const {
10938  if (FD)
10939  getFunctionFeatureMap(FeatureMap, GlobalDecl().getWithDecl(FD));
10940  else
10941  Target->initFeatureMap(FeatureMap, getDiagnostics(),
10942  Target->getTargetOpts().CPU,
10943  Target->getTargetOpts().Features);
10944 }
10945 
10946 // Fills in the supplied string map with the set of target features for the
10947 // passed in function.
10948 void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
10949  GlobalDecl GD) const {
10950  StringRef TargetCPU = Target->getTargetOpts().CPU;
10951  const FunctionDecl *FD = GD.getDecl()->getAsFunction();
10952  if (const auto *TD = FD->getAttr<TargetAttr>()) {
10954 
10955  // Make a copy of the features as passed on the command line into the
10956  // beginning of the additional features from the function to override.
10957  ParsedAttr.Features.insert(
10958  ParsedAttr.Features.begin(),
10959  Target->getTargetOpts().FeaturesAsWritten.begin(),
10960  Target->getTargetOpts().FeaturesAsWritten.end());
10961 
10962  if (ParsedAttr.Architecture != "" &&
10963  Target->isValidCPUName(ParsedAttr.Architecture))
10964  TargetCPU = ParsedAttr.Architecture;
10965 
10966  // Now populate the feature map, first with the TargetCPU which is either
10967  // the default or a new one from the target attribute string. Then we'll use
10968  // the passed in features (FeaturesAsWritten) along with the new ones from
10969  // the attribute.
10970  Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU,
10971  ParsedAttr.Features);
10972  } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) {
10974  Target->getCPUSpecificCPUDispatchFeatures(
10975  SD->getCPUName(GD.getMultiVersionIndex())->getName(), FeaturesTmp);
10976  std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end());
10977  Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
10978  } else {
10979  Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU,
10980  Target->getTargetOpts().Features);
10981  }
10982 }
RecordDecl * buildImplicitRecord(StringRef Name, RecordDecl::TagKind TK=TTK_Struct) const
Create a new implicit TU-level CXXRecordDecl or RecordDecl declaration.
static CanQual< Type > CreateUnsafe(QualType Other)
Builds a canonical type from a QualType.
static TypedefDecl * CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context)
Internal representation of canonical, dependent typeof(expr) types.
Definition: Type.h:4326
QualType getDecltypeType(Expr *e, QualType UnderlyingType) const
C++11 decltype.
MemberSpecializationInfo * getInstantiatedFromStaticDataMember(const VarDecl *Var)
If this variable is an instantiated static data member of a class template specialization, returns the templated static data member from which it was instantiated.
void setExternalSource(IntrusiveRefCntPtr< ExternalASTSource > Source)
Attach an external AST source to the AST context.
static NamespaceDecl * Create(ASTContext &C, DeclContext *DC, bool Inline, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, NamespaceDecl *PrevDecl)
Definition: DeclCXX.cpp:2771
std::vector< std::string > Features
Definition: Attr.h:334
static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs, QualType rhs)
Determine whether the first type is a subtype of the second.
TypedefDecl * getObjCInstanceTypeDecl()
Retrieve the typedef declaration corresponding to the Objective-C "instancetype" type.
CanQualType SatShortAccumTy
Definition: ASTContext.h:1034
Expr * getImmediatelyDeclaredConstraint() const
Get the immediately-declared constraint expression introduced by this type-constraint, that is - the constraint expression that is added to the associated constraints of the enclosing declaration in practice.
Definition: ASTConcept.h:187
TemplateTemplateParmDecl * getParameterPack() const
Retrieve the template template parameter pack being substituted.
Definition: TemplateName.h:148
const ObjCInterfaceType * getInterfaceType() const
If this pointer points to an Objective C @interface type, gets the type for that interface.
Definition: Type.cpp:1607
static void EncodeBitField(const ASTContext *Ctx, std::string &S, QualType T, const FieldDecl *FD)
CanQualType SatUnsignedLongFractTy
Definition: ASTContext.h:1038
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
Defines the clang::ASTContext interface.
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
void setTemplateOrSpecializationInfo(VarDecl *Inst, TemplateOrSpecializationInfo TSI)
const BlockDecl * getBlockDecl() const
Definition: Expr.h:5593
bool hasDefinition() const
Determine whether this class has been defined.
Definition: DeclObjC.h:1549
The generic AArch64 ABI is also a modified version of the Itanium ABI, but it has fewer divergences t...
Definition: TargetCXXABI.h:83
Represents a type that was referred to using an elaborated type keyword, e.g., struct S...
Definition: Type.h:5285
ASTMutationListener * Listener
Definition: ASTContext.h:585
IntType getInt64Type() const
Definition: TargetInfo.h:304
QualType withConst() const
Retrieves a version of this type with const applied.
const Type * Ty
The locally-unqualified type.
Definition: Type.h:595
static bool isTypeTypedefedAsBOOL(QualType T)
static unsigned getFullDataSizeForType(QualType Ty)
Returns the size of type source info data block for the given type.
Definition: TypeLoc.cpp:93
static APFixedPoint getMax(const FixedPointSemantics &Sema)
Definition: FixedPoint.cpp:114
QualType getObjCObjectType(QualType Base, ObjCProtocolDecl *const *Protocols, unsigned NumProtocols) const
Legacy interface: cannot provide type arguments or __kindof.
QualType getVariableArrayDecayedType(QualType Ty) const
Returns a vla type where known sizes are replaced with [*].
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx)
Definition: Type.h:5087
CanQualType LongLongTy
Definition: ASTContext.h:1025
static const Decl * getCanonicalDecl(const Decl *D)
void setImplicit(bool I=true)
Definition: DeclBase.h:559
Represents a function declaration or definition.
Definition: Decl.h:1783
void setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl, TemplateSpecializationKind TSK, SourceLocation PointOfInstantiation=SourceLocation())
Note that the static data member Inst is an instantiation of the static data member template Tmpl of ...
llvm::DenseMap< const Decl *, const Decl * > RedeclChainComments
Mapping from canonical declaration to the first redeclaration in chain that has a comment attached...
Definition: ASTContext.h:757
AttrVec & getDeclAttrs(const Decl *D)
Retrieve the attributes for the given declaration.
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:6824
CanQualType WIntTy
Definition: ASTContext.h:1021
bool isKindOfTypeAsWritten() const
Whether this is a "__kindof" type as written.
Definition: Type.h:5811
CXXABI * CreateMicrosoftCXXABI(ASTContext &Ctx)
const Decl * CommentDecl
Declaration the comment is actually attached to (in the source).
Definition: Comment.h:985
bool isObjCQualifiedIdType() const
True if this is equivalent to &#39;id.
Definition: Type.h:6030
SplitQualType split() const
CanQualType AccumTy
Definition: ASTContext.h:1029
no exception specification
unsigned char getFixedPointIBits(QualType Ty) const
CanQualType OCLQueueTy
Definition: ASTContext.h:1054
QualType getObjCIdType() const
Represents the Objective-CC id type.
Definition: ASTContext.h:1874
QualType getAdjustedParameterType(QualType T) const
Perform adjustment on the parameter type of a function.
Holds information about both target-independent and target-specific builtins, allowing easy queries b...
Definition: Builtins.h:65
StringRef getName(const PrintingPolicy &Policy) const
Definition: Type.cpp:2761
TypedefDecl * getCFConstantStringDecl() const
if(T->getSizeExpr()) TRY_TO(TraverseStmt(T -> getSizeExpr()))
unsigned getRawEncoding() const
When a SourceLocation itself cannot be used, this returns an (opaque) 32-bit integer encoding for it...
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:2614
ArrayRef< QualType > getTypeArgsAsWritten() const
Retrieve the type arguments of this object type as they were written.
Definition: Type.h:5805
CanQualType LongDoubleComplexTy
Definition: ASTContext.h:1042
void * getAsVoidPointer() const
Retrieve the template name as a void pointer.
Definition: TemplateName.h:332
QualType mergeFunctionTypes(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false)
QualType getPointeeType() const
Definition: Type.h:2627
CanQualType VoidPtrTy
Definition: ASTContext.h:1044
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx)
Definition: Type.h:2977
Represents the dependent type named by a dependently-scoped typename using declaration, e.g.
Definition: Type.h:4210
A (possibly-)qualified type.
Definition: Type.h:654
The iOS 64-bit ABI is follows ARM&#39;s published 64-bit ABI more closely, but we don&#39;t guarantee to foll...
Definition: TargetCXXABI.h:70
int getIntegerTypeOrder(QualType LHS, QualType RHS) const
Return the highest ranked integer type, see C99 6.3.1.8p1.
bool isBlockPointerType() const
Definition: Type.h:6512
QualType areCommonBaseCompatible(const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT)
OverloadedOperatorKind getOperator() const
Return the overloaded operator to which this template name refers.
Definition: TemplateName.h:518
bool isArrayType() const
Definition: Type.h:6570
bool getNoCfCheck() const
Definition: Type.h:3582
bool isNull() const
Definition: CanonicalType.h:97
bool isMemberPointerType() const
Definition: Type.h:6552
bool canBuiltinBeRedeclared(const FunctionDecl *) const
Return whether a declaration to a builtin is allowed to be overloaded/redeclared. ...
unsigned param_size() const
Definition: DeclObjC.h:342
unsigned char getFixedPointScale(QualType Ty) const
MangleContext * createMangleContext(const TargetInfo *T=nullptr)
If T is null pointer, assume the target in ASTContext.
ASTContext(LangOptions &LOpts, SourceManager &SM, IdentifierTable &idents, SelectorTable &sels, Builtin::Context &builtins)
Definition: ASTContext.cpp:954
CanQualType UnsignedLongFractTy
Definition: ASTContext.h:1033
QualType getBuiltinVaListType() const
Retrieve the type of the __builtin_va_list type.
Definition: ASTContext.h:1929
unsigned getLongWidth() const
getLongWidth/Align - Return the size of &#39;signed long&#39; and &#39;unsigned long&#39; for this target...
Definition: TargetInfo.h:401
ObjCIvarDecl * getPropertyIvarDecl() const
Definition: DeclObjC.h:2846
CanQualType FractTy
Definition: ASTContext.h:1032
static MicrosoftMangleContext * create(ASTContext &Context, DiagnosticsEngine &Diags)
void Profile(llvm::FoldingSetNodeID &ID) const
Definition: Type.h:1385
CanQualType Char32Ty
Definition: ASTContext.h:1024
QualType getPointerDiffType() const
Return the unique type for "ptrdiff_t" (C99 7.17) defined in <stddef.h>.
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D...
AutoTypeKeyword
Which keyword(s) were used to create an AutoType.
Definition: Type.h:1413
Stmt - This represents one statement.
Definition: Stmt.h:66
void setLAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:1592
virtual void DeducedReturnType(const FunctionDecl *FD, QualType ReturnType)
A function&#39;s return type has been deduced.
std::string getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const
Emit the encoded type for the function Decl into S.
Kind getKind() const
Definition: Type.h:2495
Internal representation of canonical, dependent __underlying_type(type) types.
Definition: Type.h:4454
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:3422
bool CommentsLoaded
True if comments are already loaded from ExternalASTSource.
Definition: ASTContext.h:744
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee...
Definition: Type.cpp:557
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:5545
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:994
bool hasExtParameterInfos() const
Is there any interesting extra information for any of the parameters of this function type...
Definition: Type.h:4148
__builtin_va_list as defined by the PNaCl ABI: http://www.chromium.org/nativeclient/pnacl/bitcode-abi...
Definition: TargetInfo.h:239
CharUnits getBaseClassOffset(const CXXRecordDecl *Base) const
getBaseClassOffset - Get the offset, in chars, for the given base class.
Definition: RecordLayout.h:232
bool isRealFloatingType() const
Floating point categories.
Definition: Type.cpp:2021
unsigned overridden_methods_size(const CXXMethodDecl *Method) const
The fixed point semantics work similarly to llvm::fltSemantics.
Definition: FixedPoint.h:33
Represents the declaration of a typedef-name via the &#39;typedef&#39; type specifier.
Definition: Decl.h:3173
C Language Family Type Representation.
Defines the SourceManager interface.
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3284
CharUnits getAlignOfGlobalVarInChars(QualType T) const
Return the alignment in characters that should be given to a global variable with type T...
Expr * IgnoreUnlessSpelledInSource()
Skip past any invisble AST nodes which might surround this statement, such as ExprWithCleanups or Imp...
Definition: Expr.cpp:3028
Microsoft&#39;s &#39;__super&#39; specifier, stored as a CXXRecordDecl* of the class it appeared in...
const AstTypeMatcher< TagType > tagType
Matches tag types (record and enum types).
Represents a qualified type name for which the type name is dependent.
Definition: Type.h:5368
static TypedefDecl * CreateSystemZBuiltinVaListDecl(const ASTContext *Context)
The template argument is an expression, and we&#39;ve not resolved it to one of the other forms yet...
Definition: TemplateBase.h:86
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.cpp:3407
bool isRecordType() const
Definition: Type.h:6594
unsigned getTypeAlignIfKnown(QualType T) const
Return the ABI-specified alignment of a type, in bits, or 0 if the type is incomplete and we cannot d...
CanQualType FloatComplexTy
Definition: ASTContext.h:1042
static TemplateTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation L, unsigned D, unsigned P, bool ParameterPack, IdentifierInfo *Id, TemplateParameterList *Params)
const ASTRecordLayout & getASTObjCImplementationLayout(const ObjCImplementationDecl *D) const
Get or compute information about the layout of the specified Objective-C implementation.
RawCommentList Comments
All comments in this translation unit.
Definition: ASTContext.h:741
const T * get() const
Retrieve the stored node as type T.
static int CmpProtocolNames(ObjCProtocolDecl *const *LHS, ObjCProtocolDecl *const *RHS)
CmpProtocolNames - Comparison predicate for sorting protocols alphabetically.
static TemplateTypeParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation KeyLoc, SourceLocation NameLoc, unsigned D, unsigned P, IdentifierInfo *Id, bool Typename, bool ParameterPack, bool HasTypeConstraint=false, Optional< unsigned > NumExpanded=None)
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:1958
QualType getEnumType(const EnumDecl *Decl) const
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type...
const Type * getTypeForDecl() const
Definition: Decl.h:3053
CoreFoundationABI CFRuntime
Definition: LangOptions.h:259
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:88
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:4086
EnumDecl * getPreviousDecl()
Definition: Decl.h:3567
CanQualType ObjCBuiltinSelTy
Definition: ASTContext.h:1048
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclBase.h:421
bool isDiscardableGVALinkage(GVALinkage L)
Definition: Linkage.h:81
NestedNameSpecifier * getPrefix() const
Return the prefix of this nested name specifier.
QualType getDeducedTemplateSpecializationType(TemplateName Template, QualType DeducedType, bool IsDependent) const
C++17 deduced class template specialization type.
CanQualType getCanonicalFunctionResultType(QualType ResultType) const
Adjust the given function result type.
Defines the C++ template declaration subclasses.
StringRef P
ivar_range ivars() const
Definition: DeclObjC.h:1472
Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained by a type-constraint.
Definition: Type.h:4874
Kind getKind() const
Definition: TargetCXXABI.h:137
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition: Decl.cpp:4074
A class providing a concrete implementation of ObjCObjectType, so as to not increase the footprint of...
Definition: Type.h:5847
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx)
Definition: Type.cpp:3191
unsigned getDefaultAlignForAttributeAligned() const
Return the default alignment for attribute((aligned)) on this target, to be used if no alignment valu...
Definition: TargetInfo.h:542
ObjCTypeParamList * getTypeParamList() const
Retrieve the type parameters of this class.
Definition: DeclObjC.cpp:307
Defines types useful for describing an Objective-C runtime.
QualType getDependentVectorType(QualType VectorType, Expr *SizeExpr, SourceLocation AttrLoc, VectorType::VectorKind VecKind) const
Return the unique reference to the type for a dependently sized vector of the specified element type...
CanQualType ARCUnbridgedCastTy
Definition: ASTContext.h:1047
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined...
Definition: Decl.h:2918
QualType getBlockPointerType(QualType T) const
Return the uniqued reference to the type for a block of the specified type.
bool isExpandedParameterPack() const
Whether this parameter is a template template parameter pack that has a known list of different templ...
The base class of the type hierarchy.
Definition: Type.h:1450
void setParameterIndex(const ParmVarDecl *D, unsigned index)
Used by ParmVarDecl to store on the side the index of the parameter when it exceeds the size of the n...
CanQualType SatUnsignedAccumTy
Definition: ASTContext.h:1035
Expr * getCopyExpr() const
Definition: Expr.h:5634
The parameter is covariant, e.g., X<T> is a subtype of X<U> when the type parameter is covariant and ...
QualType getsigjmp_bufType() const
Retrieve the C sigjmp_buf type.
Definition: ASTContext.h:1791
static bool areSortedAndUniqued(ArrayRef< ObjCProtocolDecl *> Protocols)
CanQual< T > getUnqualifiedType() const
Retrieve the unqualified form of this type.
CanQualType LongTy
Definition: ASTContext.h:1025
DiagnosticsEngine & getDiagnostics() const
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:4924
QualType getCorrespondingSignedFixedPointType(QualType Ty) const
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Definition: Diagnostic.h:1300
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:2889
QualType getCorrespondingUnsignedType(QualType T) const
The template argument is a declaration that was provided for a pointer, reference, or pointer to member non-type template parameter.
Definition: TemplateBase.h:63
CharUnits getObjCEncodingTypeSize(QualType T) const
Return the size of type T for Objective-C encoding purpose, in characters.
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:2572
Represent a C++ namespace.
Definition: Decl.h:497
unsigned NumImplicitCopyConstructors
The number of implicitly-declared copy constructors.
Definition: ASTContext.h:2872
DeclarationName getDeclName() const
Get the name of the template.
static ExprValueKind getValueKindForType(QualType T)
getValueKindForType - Given a formal return or parameter type, give its value kind.
Definition: Expr.h:404
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:2736
virtual void completeDefinition()
Note that the definition of this type is now complete.
Definition: Decl.cpp:4434
bool isZero() const
isZero - Test whether the quantity equals zero.
Definition: CharUnits.h:116
QualType withConst() const
Definition: Type.h:826
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:707
QualType adjustStringLiteralBaseType(QualType StrLTy) const
A container of type source information.
Definition: Type.h:6227
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition: Type.h:6140
llvm::DenseMap< Stmt *, Stmt * > MapTy
Definition: ParentMap.cpp:22
CharUnits getAlignment() const
getAlignment - Get the record alignment in characters.
Definition: RecordLayout.h:176
static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod, SmallVectorImpl< const NamedDecl *> &Redeclared)
Definition: ASTContext.cpp:474
Interoperability with the latest known version of the Swift runtime.
FieldDecl * getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field)
unsigned NumImplicitDestructorsDeclared
The number of implicitly-declared destructors for which declarations were built.
Definition: ASTContext.h:2904
__builtin_va_list as defined by the x86-64 ABI: http://refspecs.linuxbase.org/elf/x86_64-abi-0.21.pdf
Definition: TargetInfo.h:248
QualType getAtomicType(QualType T) const
Return the uniqued reference to the atomic type for the specified type.
param_const_iterator param_end() const
Definition: DeclObjC.h:353
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2383
CanQualType WideCharTy
Definition: ASTContext.h:1020
unsigned NumImplicitCopyAssignmentOperatorsDeclared
The number of implicitly-declared copy assignment operators for which declarations were built...
Definition: ASTContext.h:2890
const DeclContext * getParentFunctionOrMethod() const
If this decl is defined inside a function/method/block it returns the corresponding DeclContext...
Definition: DeclBase.cpp:254
A template template parameter that has been substituted for some other template name.
Definition: TemplateName.h:223
CanQualType HalfTy
Definition: ASTContext.h:1040
QualType getElementType() const
Definition: Type.h:2910
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition: Type.cpp:592
void AddDeallocation(void(*Callback)(void *), void *Data) const
Add a deallocation callback that will be invoked when the ASTContext is destroyed.
StringRef getBufferData(FileID FID, bool *Invalid=nullptr) const
Return a StringRef to the source buffer data for the specified FileID.
unsigned getTypeAlign(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in bits.
Definition: ASTContext.h:2135
const IdentifierInfo * getIdentifier() const
Returns the identifier to which this template name refers.
Definition: TemplateName.h:508
interp::Context & getInterpContext()
Returns the clang bytecode interpreter context.
Definition: ASTContext.cpp:909
void Profile(llvm::FoldingSetNodeID &ID, ASTContext &Context)
An identifier, stored as an IdentifierInfo*.
bool isUnsignedIntegerType() const
Return true if this is an integer type that is unsigned, according to C99 6.2.5p6 [which returns true...
Definition: Type.cpp:1968
ASTVisitor(ParentMap &Map, ASTContext &Context)
unsigned getDepth() const
Get the nesting depth of the template parameter.
static const Type * getIntegerTypeForEnum(const EnumType *ET)
CanQualType getCanonicalParamType(QualType T) const
Return the canonical parameter type corresponding to the specific potentially non-canonical one...
Represents a variable declaration or definition.
Definition: Decl.h:820
QualType getCFConstantStringType() const
Return the C structure type used to represent constant CFStrings.
static NestedNameSpecifier * Create(const ASTContext &Context, NestedNameSpecifier *Prefix, IdentifierInfo *II)
Builds a specifier combining a prefix and an identifier.
void removeObjCLifetime()
Definition: Type.h:339
QualType getReturnType() const
Definition: Decl.h:2445
LangAS getLangASFromTargetAS(unsigned TargetAS)
Definition: AddressSpaces.h:71
void initialize(ASTContext &Context, SourceLocation Loc) const
Initializes this to state that every location in this type is the given location. ...
Definition: TypeLoc.h:196
RecordDecl * getPreviousDecl()
Definition: Decl.h:3787
unsigned getNumParams() const
Definition: Type.h:3964
bool isEnumeralType() const
Definition: Type.h:6598
APFixedPoint getFixedPointMax(QualType Ty) const
bool isFixed() const
Returns true if this is an Objective-C, C++11, or Microsoft-style enumeration with a fixed underlying...
Definition: Decl.h:3684
NamedDecl *const * const_iterator
Iterates through the template parameters in this list.
Definition: DeclTemplate.h:122
const T * getAs() const
Member-template getAs<specific type>&#39;.
Definition: Type.h:7002
CanQualType Float128Ty
Definition: ASTContext.h:1028
virtual void CompleteRedeclChain(const Decl *D)
Gives the external AST source an opportunity to complete the redeclaration chain for a declaration...
Represents an empty template argument, e.g., one that has not been deduced.
Definition: TemplateBase.h:56
Extra information about a function prototype.
Definition: Type.h:3837
CanQualType ShortAccumTy
Definition: ASTContext.h:1029
Declaration context for names declared as extern "C" in C++.
Definition: Decl.h:196
LangAS
Defines the address space values used by the address space qualifier of QualType. ...
Definition: AddressSpaces.h:25
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, bool Canonical) const
Produce a unique representation of the given statement.
Represents a C++17 deduced template specialization type.
Definition: Type.h:4940
__builtin_va_list as defined by the AArch64 ABI http://infocenter.arm.com/help/topic/com.arm.doc.ihi0055a/IHI0055A_aapcs64.pdf
Definition: TargetInfo.h:235
QualifiedTemplateName * getAsQualifiedTemplateName() const
Retrieve the underlying qualified template name structure, if any.
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:138
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition: Decl.h:414
ObjCImplementationDecl * getObjCImplementation(ObjCInterfaceDecl *D)
Get the implementation of the ObjCInterfaceDecl D, or nullptr if none exists.
bool field_empty() const
Definition: Decl.h:3971
A namespace, stored as a NamespaceDecl*.
QualType getMemberPointerType(QualType T, const Type *Cls) const
Return the uniqued reference to the type for a member pointer to the specified type in the specified ...
bool ClassImplementsProtocol(ObjCProtocolDecl *lProto, bool lookupCategory, bool RHSIsQualifiedID=false)
ClassImplementsProtocol - Checks that &#39;lProto&#39; protocol has been implemented in IDecl class...
Definition: DeclObjC.cpp:1728
bool isInvalidDecl() const
Definition: DeclBase.h:553
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:69
static ObjCPropertyDecl * findPropertyDecl(const DeclContext *DC, const IdentifierInfo *propertyID, ObjCPropertyQueryKind queryKind)
Lookup a property by name in the specified DeclContext.
Definition: DeclObjC.cpp:176
TemplateName getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param, TemplateName replacement) const
Describes how types, statements, expressions, and declarations should be printed. ...
Definition: PrettyPrinter.h:47
CanQualType ShortFractTy
Definition: ASTContext.h:1032
SpecifierKind getKind() const
Determine what kind of nested name specifier is stored.
protocol_range protocols() const
Definition: DeclObjC.h:2143
Decl * getVaListTagDecl() const
Retrieve the C type declaration corresponding to the predefined __va_list_tag type used to help defin...
Holds all information required to evaluate constexpr code in a module.
Definition: Context.h:38
Represents a parameter to a function.
Definition: Decl.h:1595
Represents the result of substituting a type for a template type parameter.
Definition: Type.h:4728
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:2648
Linkage
Describes the different kinds of linkage (C++ [basic.link], C99 6.2.2) that an entity may have...
Definition: Linkage.h:23
Defines the clang::Expr interface and subclasses for C++ expressions.
QualType getIntegralType() const
Retrieve the type of the integral value.
Definition: TemplateBase.h:314
noexcept(expression), value-dependent
static TypedefDecl * CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context)
Represents the builtin template declaration which is used to implement __make_integer_seq and other b...
The collection of all-type qualifiers we support.
Definition: Type.h:143
FieldDecl * getSourceBitField()
If this expression refers to a bit-field, retrieve the declaration of that bit-field.
Definition: Expr.cpp:3900
PipeType - OpenCL20.
Definition: Type.h:6159
bool UnwrapSimilarTypes(QualType &T1, QualType &T2)
Attempt to unwrap two types that may be similar (C++ [conv.qual]).
static void getIntersectionOfProtocols(ASTContext &Context, const ObjCInterfaceDecl *CommonBase, const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT, SmallVectorImpl< ObjCProtocolDecl *> &IntersectionSet)
getIntersectionOfProtocols - This routine finds the intersection of set of protocols inherited from t...
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3132
Qualifiers getQualifiers() const
Retrieve all qualifiers.
SubstTemplateTemplateParmStorage * getAsSubstTemplateTemplateParm() const
Retrieve the substituted template template parameter, if known.
CanQualType OCLSamplerTy
Definition: ASTContext.h:1053
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:244
Base wrapper for a particular "section" of type source info.
Definition: TypeLoc.h:58
Represents a struct/union/class.
Definition: Decl.h:3748
TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg) const
Retrieve the "canonical" template argument.
bool isEmpty() const
Determine whether this is an empty class in the sense of (C++11 [meta.unary.prop]).
Definition: DeclCXX.h:1099
uint64_t getPointerWidth(unsigned AddrSpace) const
Return the width of pointers on this target, for the specified address space.
Definition: TargetInfo.h:361
RecordDecl * getCFConstantStringTagDecl() const
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:272
QualType getSubstTemplateTypeParmType(const TemplateTypeParmType *Replaced, QualType Replacement) const
Retrieve a substitution-result type.
TypedefDecl * getObjCIdDecl() const
Retrieve the typedef corresponding to the predefined id type in Objective-C.
FunctionType::ExtInfo ExtInfo
Definition: Type.h:3838
bool isComplete() const
Returns true if this can be considered a complete type.
Definition: Decl.h:3689
One of these records is kept for each identifier that is lexed.
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1063
bool isObjCQualifiedClass() const
Definition: Type.h:5777
This table allows us to fully hide how we implement multi-keyword caching.
unsigned getRegParm() const
Definition: Type.h:3585
Represents a class type in Objective C.
Definition: Type.h:5694
static RecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, RecordDecl *PrevDecl=nullptr)
Definition: Decl.cpp:4387
QualType getPointeeType() const
Definition: Type.h:2731
void setManglingNumber(const NamedDecl *ND, unsigned Number)
CXXRecordDecl * getPreviousDecl()
Definition: DeclCXX.h:500
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:168
A C++ nested-name-specifier augmented with source location information.
Represents a dependent template name that cannot be resolved prior to template instantiation.
Definition: TemplateName.h:446
QualType getObjCSuperType() const
Returns the C struct type for objc_super.
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:3971
ArrayRef< ExtParameterInfo > getExtParameterInfos() const
Definition: Type.h:4152
const ParmVarDecl *const * param_const_iterator
Definition: DeclObjC.h:344
NamespaceDecl * getNamespace()
Retrieve the namespace declaration aliased by this directive.
Definition: DeclCXX.h:3040
Will traverse all child nodes.
Definition: ASTTypeTraits.h:42
The template argument is an integral value stored in an llvm::APSInt that was provided for an integra...
Definition: TemplateBase.h:71
void setObjCConstantStringInterface(ObjCInterfaceDecl *Decl)
void setArgLocInfo(unsigned i, TemplateArgumentLocInfo AI)
Definition: TypeLoc.h:1608
void setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, FieldDecl *Tmpl)
Missing a type from <ucontext.h>
Definition: ASTContext.h:2042
static bool isCanonicalExceptionSpecification(const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType)
TemplateDecl * getAsTemplateDecl() const
Retrieve the underlying template declaration that this template name refers to, if known...
CanQualType UnsignedFractTy
Definition: ASTContext.h:1033
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition: Decl.h:3953
The parameter is contravariant, e.g., X<T> is a subtype of X<U> when the type parameter is covariant ...
bool isCharType() const
Definition: Type.cpp:1871
field_range fields() const
Definition: Decl.h:3963
static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context, const Decl *D, GVALinkage L)
QualType getDependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, const IdentifierInfo *Name, QualType Canon=QualType()) const
std::unique_ptr< MangleNumberingContext > createMangleNumberingContext() const
SetterKind getSetterKind() const
getSetterKind - Return the method used for doing assignment in the property setter.
Definition: DeclObjC.h:908
bool isObjCIdType() const
Definition: Type.h:6651
The generic Mips ABI is a modified version of the Itanium ABI.
Definition: TargetCXXABI.h:89
Represents a member of a struct/union/class.
Definition: Decl.h:2729
const Type * getAsType() const
Retrieve the type stored in this nested name specifier.
static CGCXXABI * createCXXABI(CodeGenModule &CGM)
unsigned NumImplicitDefaultConstructors
The number of implicitly-declared default constructors.
Definition: ASTContext.h:2865
bool isCanonicalUnqualified() const
Determines if this type would be canonical if it had no further qualification.
Definition: Type.h:1902
DynTypedNodeList getParents(const NodeT &Node)
Returns the parents of the given node (within the traversal scope).
Definition: ASTContext.h:665
SubstTemplateTemplateParmPackStorage * getAsSubstTemplateTemplateParmPack() const
Retrieve the substituted template template parameter pack, if known.
Defines the ExceptionSpecificationType enumeration and various utility functions. ...
unsigned getStaticLocalNumber(const VarDecl *VD) const
const char * getTypeString(unsigned ID) const
Get the type descriptor string for the specified builtin.
Definition: Builtins.h:88
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:2873
unsigned getCommentEndOffset(RawComment *C) const
RawComment * getRawCommentForDeclNoCacheImpl(const Decl *D, const SourceLocation RepresentativeLocForDecl, const std::map< unsigned, RawComment *> &CommentsInFile) const
Definition: ASTContext.cpp:222
void addLazyModuleInitializers(Module *M, ArrayRef< uint32_t > IDs)
void setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern)
Remember that the using decl Inst is an instantiation of the using decl Pattern of a class template...
void startDefinition()
Starts the definition of this tag declaration.
Definition: Decl.cpp:4154
CanQualType LongAccumTy
Definition: ASTContext.h:1029
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:2017
CanQualType OCLEventTy
Definition: ASTContext.h:1053
Optional< unsigned > getNumTemplateExpansions() const
Retrieve the number of expansions that a template template argument expansion will produce...
CharUnits getTypeUnadjustedAlignInChars(QualType T) const
getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a type, in characters, before alignment adjustments.
The iterator over UnresolvedSets.
Definition: UnresolvedSet.h:32
Interoperability with the Swift 4.1 runtime.
Represents the result of substituting a set of types for a template type parameter pack...
Definition: Type.h:4784
Container for either a single DynTypedNode or for an ArrayRef to DynTypedNode.
Definition: ASTContext.h:592
void setStaticLocalNumber(const VarDecl *VD, unsigned Number)
bool ObjCQualifiedIdTypesAreCompatible(const ObjCObjectPointerType *LHS, const ObjCObjectPointerType *RHS, bool ForCompare)
ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an ObjCQualifiedIDType.
unsigned getPosition() const
Get the position of the template parameter within its parameter list.
TemplateName getOverloadedTemplateName(UnresolvedSetIterator Begin, UnresolvedSetIterator End) const
Retrieve the template name that corresponds to a non-empty lookup.
std::string getObjCEncodingForBlock(const BlockExpr *blockExpr) const
Return the encoded type for this block declaration.
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition: Type.h:6744
static CharUnits Zero()
Zero - Construct a CharUnits quantity of zero.
Definition: CharUnits.h:53
qual_iterator qual_begin() const
Definition: Type.h:5595
RawComment * getRawCommentForDeclNoCache(const Decl *D) const
Return the documentation comment attached to a given declaration, without looking into cache...
Definition: ASTContext.cpp:300
CharUnits getVBaseClassOffset(const CXXRecordDecl *VBase) const
getVBaseClassOffset - Get the offset, in chars, for the given base class.
Definition: RecordLayout.h:240
__DEVICE__ int max(int __a, int __b)
uint64_t lookupFieldBitOffset(const ObjCInterfaceDecl *OID, const ObjCImplementationDecl *ID, const ObjCIvarDecl *Ivar) const
Get the offset of an ObjCIvarDecl in bits.
static ast_type_traits::DynTypedNode createDynTypedNode(const T &Node)
Template specializations to abstract away from pointers and TypeLocs.
static TypedefDecl * CreatePowerABIBuiltinVaListDecl(const ASTContext *Context)
CanQualType OCLReserveIDTy
Definition: ASTContext.h:1054
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:53
QualType getUnsignedPointerDiffType() const
Return the unique unsigned counterpart of "ptrdiff_t" integer type.
const ASTRecordLayout & getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const
Get or compute information about the layout of the specified Objective-C interface.
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:6179
static TypedefDecl * CreateCharPtrNamedVaListDecl(const ASTContext *Context, StringRef Name)
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:6881
QualType getParamTypeForDecl() const
Definition: TemplateBase.h:268
Describes a module or submodule.
Definition: Module.h:64
IdentifierTable & Idents
Definition: ASTContext.h:580
bool ObjCObjectAdoptsQTypeProtocols(QualType QT, ObjCInterfaceDecl *Decl)
ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC&#39;s protocol list adopt all protocols in Q...
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition: Type.h:6275
static bool hasAnyPackExpansions(ArrayRef< TemplateArgument > Args)
const ObjCObjectPointerType * stripObjCKindOfTypeAndQuals(const ASTContext &ctx) const
Strip off the Objective-C "kindof" type and (with it) any protocol qualifiers.
Definition: Type.cpp:769
bool ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto, ObjCProtocolDecl *rProto) const
ProtocolCompatibleWithProtocol - return &#39;true&#39; if &#39;lProto&#39; is in the inheritance hierarchy of &#39;rProto...
TypeSourceInfo * getTemplateSpecializationTypeInfo(TemplateName T, SourceLocation TLoc, const TemplateArgumentListInfo &Args, QualType Canon=QualType()) const
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2399
CanQualType LongFractTy
Definition: ASTContext.h:1032
bool getProducesResult() const
Definition: Type.h:3580
QualType mergeObjCGCQualifiers(QualType, QualType)
mergeObjCGCQualifiers - This routine merges ObjC&#39;s GC attribute of &#39;LHS&#39; and &#39;RHS&#39; attributes and ret...
static bool isTypeSigned(IntType T)
Returns true if the type is signed; false otherwise.
Definition: TargetInfo.cpp:308
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3177
uint64_t getConstantArrayElementCount(const ConstantArrayType *CA) const
Return number of constant array elements.
An rvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:2815
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:2807
static APFixedPoint getMin(const FixedPointSemantics &Sema)
Definition: FixedPoint.cpp:122
IdentifierInfo * getAsIdentifier() const
Retrieve the identifier stored in this nested name specifier.
qual_iterator qual_end() const
Definition: Type.h:5596
A qualified template name, where the qualification is kept to describe the source code as written...
Definition: TemplateName.h:215
unsigned getAlignOfGlobalVar(QualType T) const
Return the alignment in bits that should be given to a global variable with type T.
static bool unionHasUniqueObjectRepresentations(const ASTContext &Context, const RecordDecl *RD)
static ObjCInterfaceDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation atLoc, IdentifierInfo *Id, ObjCTypeParamList *typeParamList, ObjCInterfaceDecl *PrevDecl, SourceLocation ClassLoc=SourceLocation(), bool isInternal=false)
Definition: DeclObjC.cpp:1481
const LangASMap & getAddressSpaceMap() const
Definition: TargetInfo.h:1241
static int compareObjCProtocolsByName(ObjCProtocolDecl *const *lhs, ObjCProtocolDecl *const *rhs)
Comparison routine for Objective-C protocols to be used with llvm::array_pod_sort.
static llvm::Optional< int64_t > structHasUniqueObjectRepresentations(const ASTContext &Context, const RecordDecl *RD)
ObjCContainerDecl - Represents a container for method declarations.
Definition: DeclObjC.h:983
static ItaniumMangleContext * create(ASTContext &Context, DiagnosticsEngine &Diags)
QualType getOriginalType() const
Definition: Decl.cpp:2681
void addObjCGCAttr(GC type)
Definition: Type.h:312
static ExternCContextDecl * Create(const ASTContext &C, TranslationUnitDecl *TU)
Definition: Decl.cpp:4642
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:38
Microsoft throw(...) extension.
A convenient class for passing around template argument information.
Definition: TemplateBase.h:554
CanQualType SatShortFractTy
Definition: ASTContext.h:1037
ArrayRef< QualType > getTypeArgs() const
Retrieve the type arguments of this object type (semantically).
Definition: Type.cpp:716
QualType getVolatileType(QualType T) const
Return the uniqued reference to the type for a volatile qualified type.
Definition: ASTContext.h:1184
Qualifiers::GC getObjCGCAttrKind(QualType Ty) const
Return one of the GCNone, Weak or Strong Objective-C garbage collection attributes.
Expr * getPtr() const
Definition: Expr.h:5881
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition: Type.cpp:2289
The Microsoft ABI is the ABI used by Microsoft Visual Studio (and compatible compilers).
Definition: TargetCXXABI.h:118
TypedefDecl * getObjCSelDecl() const
Retrieve the typedef corresponding to the predefined &#39;SEL&#39; type in Objective-C.
bool hasAddressSpace() const
Definition: Type.h:358
CanQualType SatUnsignedShortAccumTy
Definition: ASTContext.h:1035
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified...
An unqualified-id that has been assumed to name a function template that will be found by ADL...
Definition: TemplateName.h:211
Keeps track of the mangled names of lambda expressions and block literals within a particular context...
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type...
Definition: Type.h:7053
QualType getNullPtrType() const
Retrieve the type for null non-type template argument.
Definition: TemplateBase.h:274
SourceLocation getExpansionLoc(SourceLocation Loc) const
Given a SourceLocation object Loc, return the expansion location referenced by the ID...
PropertyAttributeKind getPropertyAttributes() const
Definition: DeclObjC.h:853
unsigned toTargetAddressSpace(LangAS AS)
Definition: AddressSpaces.h:66
NamespaceAliasDecl * getAsNamespaceAlias() const
Retrieve the namespace alias stored in this nested name specifier.
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:149
Sugar type that represents a type that was qualified by a qualifier written as a macro invocation...
Definition: Type.h:4266
Represents a typeof (or typeof) expression (a GCC extension).
Definition: Type.h:4300
const clang::PrintingPolicy & getPrintingPolicy() const
Definition: ASTContext.h:671
static char getObjCEncodingForPrimitiveType(const ASTContext *C, const BuiltinType *BT)
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition: Type.h:1896
TemplateSpecializationKind getTemplateSpecializationKind() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
Definition: Decl.cpp:2549
Represents a declaration of a type.
Definition: Decl.h:3029
CanQualType PseudoObjectTy
Definition: ASTContext.h:1047
LangAS getAddressSpace() const
Definition: Type.h:359
QualType getExceptionObjectType(QualType T) const
GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const
const Type * getClass() const
Definition: Type.h:2867
CXXMethodVector::const_iterator overridden_cxx_method_iterator
Definition: ASTContext.h:927
bool isReadOnly() const
isReadOnly - Return true iff the property has a setter.
Definition: DeclObjC.h:876
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:5340
llvm::Error Error
void getObjCEncodingForPropertyType(QualType T, std::string &S) const
Emit the Objective-C property type encoding for the given type T into S.
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
void attachCommentsToJustParsedDecls(ArrayRef< Decl *> Decls, const Preprocessor *PP)
Searches existing comments for doc comments that should be attached to Decls.
Definition: ASTContext.cpp:491
CanQualType LongDoubleTy
Definition: ASTContext.h:1028
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition: Expr.cpp:3000
static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI, const LangOptions &LangOpts)
Definition: ASTContext.cpp:941
Expr * getSizeExpr() const
Definition: Type.h:3058
static TemplateArgument CreatePackCopy(ASTContext &Context, ArrayRef< TemplateArgument > Args)
Create a new template argument pack by copying the given set of template arguments.
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:6256
unsigned Align
Definition: ASTContext.h:158
unsigned getBitWidthValue(const ASTContext &Ctx) const
Definition: Decl.cpp:4031
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition: DeclBase.h:1166
bool AlignIsRequired
Definition: ASTContext.h:159
overridden_cxx_method_iterator overridden_methods_end(const CXXMethodDecl *Method) const
unsigned getIndex() const
Get the index of the template parameter within its parameter list.
void eraseDeclAttrs(const Decl *D)
Erase the attributes corresponding to the given declaration.
bool isInlineDefinitionExternallyVisible() const
For an inline function definition in C, or for a gnu_inline function in C++, determine whether the de...
Definition: Decl.cpp:3449
Defines the Linkage enumeration and various utility functions.
Represents an Objective-C protocol declaration.
Definition: DeclObjC.h:2078
TemplateTemplateParmDecl * getParameter() const
Definition: TemplateName.h:362
QualType mergeTransparentUnionType(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false)
mergeTransparentUnionType - if T is a transparent union type and a member of T is compatible with Sub...
bool isTypeDependent() const
isTypeDependent - Determines whether this expression is type-dependent (C++ [temp.dep.expr]), which means that its type could change from one template instantiation to the next.
Definition: Expr.h:176
bool isAlignmentRequired(const Type *T) const
Determine if the alignment the type has was required using an alignment attribute.
CXXABI * CreateItaniumCXXABI(ASTContext &Ctx)
Creates an instance of a C++ ABI class.
void * getAsOpaquePtr() const
Definition: Type.h:699
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization, retrieves the function from which it was instantiated.
Definition: Decl.cpp:3533
SmallVector< BoundNodes, 1 > match(MatcherT Matcher, const NodeT &Node, ASTContext &Context)
Returns the results of matching Matcher on Node.
A class that does preorder or postorder depth-first traversal on the entire Clang AST and visits each...
unsigned getTypeUnadjustedAlign(QualType T) const
Return the ABI-specified natural alignment of a (complete) type T, before alignment adjustments...
Definition: ASTContext.h:2143
Represents an ObjC class declaration.
Definition: DeclObjC.h:1186
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs, typeofs, etc., as well as any qualifiers.
Definition: Type.cpp:471
QualType getReturnType() const
Definition: DeclObjC.h:324
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition: Decl.cpp:3173
ObjCInterfaceDecl * getInterface() const
Gets the interface declaration for this object type, if the base type really is an interface...
Definition: Type.h:5930
bool getNoReturn() const
Definition: Type.h:3579
bool isKindOfType() const
Whether this is a "__kindof" type.
Definition: Type.h:6041
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
Definition: CanonicalType.h:83
bool isParameterPack() const
Whether this template template parameter is a template parameter pack.
SplitQualType getSplitDesugaredType() const
Definition: Type.h:958
The iOS ABI is a partial implementation of the ARM ABI.
Definition: TargetCXXABI.h:62
IntrusiveRefCntPtr< ExternalASTSource > ExternalSource
Definition: ASTContext.h:584
CanQualType UnsignedCharTy
Definition: ASTContext.h:1026
Expr * getSizeExpr() const
Definition: Type.h:3115
QualType removePtrSizeAddrSpace(QualType T) const
Remove the existing address space on the type if it is a pointer size address space and return the ty...
bool getNoCallerSavedRegs() const
Definition: Type.h:3581
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:877
unsigned getNumProtocols() const
Return the number of qualifying protocols in this type, or 0 if there are none.
Definition: Type.h:5602
bool isUnsignedFixedPointType() const
Return true if this is a fixed point type that is unsigned according to ISO/IEC JTC1 SC22 WG14 N1169...
Definition: Type.h:6862
CallingConv getDefaultCallingConvention(bool IsVariadic, bool IsCXXMethod, bool IsBuiltin=false) const
Retrieves the default calling convention for the current target.
llvm::iterator_range< overridden_cxx_method_iterator > overridden_method_range
Definition: ASTContext.h:937
std::string getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, bool Extended=false) const
Emit the encoded type for the method declaration Decl into S.
Represents an extended vector type where either the type or size is dependent.
Definition: Type.h:3195
This object can be modified without requiring retains or releases.
Definition: Type.h:164
QualType getObjCTypeParamType(const ObjCTypeParamDecl *Decl, ArrayRef< ObjCProtocolDecl *> protocols) const
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1612
The APFixedPoint class works similarly to APInt/APSInt in that it is a functional replacement for a s...
Definition: FixedPoint.h:95
void Profile(llvm::FoldingSetNodeID &ID)
Definition: TemplateName.h:524
static bool isCanonicalResultType(QualType T)
Determine whether T is canonical as the result type of a function.
Represents a K&R-style &#39;int foo()&#39; function, which has no information available about its arguments...
Definition: Type.h:3717
CanQualType Float128ComplexTy
Definition: ASTContext.h:1043
ObjCPropertyImplDecl - Represents implementation declaration of a property in a class or category imp...
Definition: DeclObjC.h:2773
Expr * getAddrSpaceExpr() const
Definition: Type.h:3166
NodeId Parent
Definition: ASTDiff.cpp:191
Provides definitions for the various language-specific address spaces.
void adjustDeducedFunctionResultType(FunctionDecl *FD, QualType ResultType)
Change the result type of a function type once it is deduced.
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:5401
QualType getBlockDescriptorExtendedType() const
Gets the struct used to keep track of the extended descriptor for pointer to blocks.
ast_type_traits::TraversalKind Traversal
bool hasAttr() const
Definition: DeclBase.h:542
QualType getBaseType() const
Gets the base type of this object type.
Definition: Type.h:5757
unsigned getTargetDefaultAlignForAttributeAligned() const
Return the default alignment for attribute((aligned)) on this target, to be used if no alignment valu...
QualType getUnaryTransformType(QualType BaseType, QualType UnderlyingType, UnaryTransformType::UTTKind UKind) const
Unary type transforms.
QualType getCorrespondingSaturatedType(QualType Ty) const
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:2602
bool isPromotableIntegerType() const
More type predicates useful for type checking/promotion.
Definition: Type.cpp:2560
Contains information gathered from parsing the contents of TargetAttr.
Definition: Attr.h:333
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1690
Represents a prototype with parameter type info, e.g.
Definition: Type.h:3754
The generic ARM ABI is a modified version of the Itanium ABI proposed by ARM for use on ARM-based pla...
Definition: TargetCXXABI.h:51
bool isDynamicClass() const
Definition: DeclCXX.h:553
QualType getDependentAddressSpaceType(QualType PointeeType, Expr *AddrSpaceExpr, SourceLocation AttrLoc) const
QualType applyObjCProtocolQualifiers(QualType type, ArrayRef< ObjCProtocolDecl *> protocols, bool &hasError, bool allowOnPointerType=false) const
Apply Objective-C protocol qualifiers to the given type.
bool isComplexType() const
isComplexType() does not include complex integers (a GCC extension).
Definition: Type.cpp:533
Represents a ValueDecl that came out of a declarator.
Definition: Decl.h:671
unsigned NumImplicitMoveAssignmentOperators
The number of implicitly-declared move assignment operators.
Definition: ASTContext.h:2893
qual_range quals() const
Definition: Type.h:5594
A dependent template name that has not been resolved to a template (or set of templates).
Definition: TemplateName.h:219
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:583
comments::FullComment * cloneFullComment(comments::FullComment *FC, const Decl *D) const
Definition: ASTContext.cpp:537
TypedefDecl * getBuiltinMSVaListDecl() const
Retrieve the C type declaration corresponding to the predefined __builtin_ms_va_list type...
bool UnwrapSimilarArrayTypes(QualType &T1, QualType &T2)
Attempt to unwrap two types that may both be array types with the same bound (or both be array types ...
ArraySizeModifier
Capture whether this is a normal array (e.g.
Definition: Type.h:2895
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition: Type.h:6331
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:179
QualType getAutoRRefDeductType() const
C++11 deduction pattern for &#39;auto &&&#39; type.
void setCFConstantStringType(QualType T)
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location, which defaults to the empty location.
ValueDecl * getAsDecl() const
Retrieve the declaration for a declaration non-type template argument.
Definition: TemplateBase.h:263
bool isSaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169...
Definition: Type.h:6836
CanQualType UnsignedAccumTy
Definition: ASTContext.h:1031
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3732
void DeepCollectObjCIvars(const ObjCInterfaceDecl *OI, bool leafClass, SmallVectorImpl< const ObjCIvarDecl *> &Ivars) const
DeepCollectObjCIvars - This routine first collects all declared, but not synthesized, ivars in super class and then collects all ivars, including those synthesized for current class.
bool ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl, const ObjCMethodDecl *MethodImp)
QualType getPromotedIntegerType(QualType PromotableType) const
Return the type that PromotableType will promote to: C99 6.3.1.1p2, assuming that PromotableType is a...
unsigned Offset
Definition: Format.cpp:1827
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
Definition: RecordLayout.h:38
typedef void* __builtin_va_list;
Definition: TargetInfo.h:231
bool hasPointerIdentity() const
Check if the given ASTNodeKind identifies a type that offers pointer identity.
CanQualType UnsignedShortFractTy
Definition: ASTContext.h:1033
Exposes information about the current target.
Definition: TargetInfo.h:164
Represents an array type in C++ whose size is a value-dependent expression.
Definition: Type.h:3093
unsigned NumImplicitCopyConstructorsDeclared
The number of implicitly-declared copy constructors for which declarations were built.
Definition: ASTContext.h:2876
Defines the TargetCXXABI class, which abstracts details of the C++ ABI that we&#39;re targeting...
CommentOptions CommentOpts
Options for parsing comments.
Definition: LangOptions.h:286
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:421
static StringLiteral * Create(const ASTContext &Ctx, StringRef Str, StringKind Kind, bool Pascal, QualType Ty, const SourceLocation *Loc, unsigned NumConcatenated)
This is the "fully general" constructor that allows representation of strings formed from multiple co...
Definition: Expr.cpp:1084
PrimitiveCopyKind isNonTrivialToPrimitiveDestructiveMove() const
Check if this is a non-trivial type that would cause a C struct transitively containing this type to ...
Definition: Type.cpp:2379
bool isNoReturn(unsigned ID) const
Return true if we know this builtin never returns.
Definition: Builtins.h:114
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition: DeclBase.h:1800
bool isCanonicalDecl() const
Whether this particular Decl is a canonical one.
Definition: DeclBase.h:883
QualType getElementType() const
Definition: Type.h:2567
bool isGNUFamily() const
Is this runtime basically of the GNU family of runtimes?
Definition: ObjCRuntime.h:118
ExtParameterInfo withIsNoEscape(bool NoEscape) const
Definition: Type.h:3488
QualType getVectorType(QualType VectorType, unsigned NumElts, VectorType::VectorKind VecKind) const
Return the unique reference to a vector type of the specified element type and size.
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition: Decl.h:4037
NamespaceDecl * getAsNamespace() const
Retrieve the namespace stored in this nested name specifier.
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition: Decl.h:2351
This represents one expression.
Definition: Expr.h:108
Defines the clang::LangOptions interface.
SourceLocation End
void setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst, UsingShadowDecl *Pattern)
known_extensions_range known_extensions() const
Definition: DeclObjC.h:1775
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
Definition: Type.h:5224
bool isPositive() const
isPositive - Test whether the quantity is greater than zero.
Definition: CharUnits.h:122
Selector getSetterName() const
Definition: DeclObjC.h:928
QualType getucontext_tType() const
Retrieve the C ucontext_t type.
Definition: ASTContext.h:1803
void addTypedefNameForUnnamedTagDecl(TagDecl *TD, TypedefNameDecl *TND)
static const LangASMap * getAddressSpaceMap(const TargetInfo &T, const LangOptions &LOpts)
Definition: ASTContext.cpp:916
static bool compare(const PathDiagnostic &X, const PathDiagnostic &Y)
unsigned getAsOpaqueValue() const
Definition: Type.h:256
void ResetObjCLayout(const ObjCContainerDecl *CD)
int Id
Definition: ASTDiff.cpp:190
static Kind getNullabilityAttrKind(NullabilityKind kind)
Retrieve the attribute kind corresponding to the given nullability kind.
Definition: Type.h:4606
static std::pair< CharUnits, CharUnits > getConstantArrayInfoInChars(const ASTContext &Context, const ConstantArrayType *CAT)
getConstantArrayInfoInChars - Performing the computation in CharUnits instead of in bits prevents ove...
QualType getCanonicalTemplateSpecializationType(TemplateName T, ArrayRef< TemplateArgument > Args) const
Declaration of a template type parameter.
Will not traverse implicit casts and parentheses.
Definition: ASTTypeTraits.h:46
static Expr * canonicalizeImmediatelyDeclaredConstraint(const ASTContext &C, Expr *IDC, QualType ConstrainedType)
Definition: ASTContext.cpp:720
llvm::DenseMap< const Decl *, const RawComment * > DeclRawComments
Mapping from declaration to directly attached comment.
Definition: ASTContext.h:750
Internal representation of canonical, dependent decltype(expr) types.
Definition: Type.h:4398
TypedefDecl * buildImplicitTypedef(QualType T, StringRef Name) const
Create a new implicit TU-level typedef declaration.
Defines the clang::CommentOptions interface.
Implements an efficient mapping from strings to IdentifierInfo nodes.
bool getHasRegParm() const
Definition: Type.h:3583
bool isObjCBuiltinType() const
Definition: Type.h:6669
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:7067
std::string getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD, const Decl *Container) const
getObjCEncodingForPropertyDecl - Return the encoded type for this method declaration.
void setObjCMethodRedeclaration(const ObjCMethodDecl *MD, const ObjCMethodDecl *Redecl)
ElaboratedTypeKeyword
The elaboration keyword that precedes a qualified type name or introduces an elaborated-type-specifie...
Definition: Type.h:5206
The template argument is a null pointer or null pointer to member that was provided for a non-type te...
Definition: TemplateBase.h:67
bool isNearlyEmpty(const CXXRecordDecl *RD) const
bool isObjCRetainableType() const
Definition: Type.cpp:4060
Inits[]
Definition: OpenMPClause.h:150
QualType getTypeOfExprType(Expr *e) const
GCC extension.
#define V(N, I)
Definition: ASTContext.h:2941
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:4631
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition: Expr.h:5579
Qualifiers::GC getObjCGCAttr() const
Returns gc attribute of this type.
Definition: Type.h:6382
QualType getParenType(QualType NamedType) const
CanQualType OMPArraySectionTy
Definition: ASTContext.h:1055
static TypedefDecl * CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context)
const Decl * getDecl() const LLVM_READONLY
Definition: Comment.h:1121
static TypedefDecl * CreateMSVaListDecl(const ASTContext *Context)
bool hasUniqueObjectRepresentations(QualType Ty) const
Return true if the specified type has unique object representations according to (C++17 [meta...
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:558
QualType getTagDeclType(const TagDecl *Decl) const
Return the unique reference to the type for the specified TagDecl (struct/union/class/enum) decl...
static std::string charUnitsToString(const CharUnits &CU)
void Profile(llvm::FoldingSetNodeID &ID)
bool isNullPtrType() const
Definition: Type.h:6802
unsigned getFastQualifiers() const
Definition: Type.h:393
Ignore AST nodes not written in the source.
Definition: ASTTypeTraits.h:49
bool canBeRedeclared(unsigned ID) const
Returns true if this is a builtin that can be redeclared.
Definition: Builtins.cpp:188
ObjCLifetime getObjCLifetime() const
Definition: Type.h:333
void removeFastQualifiers(unsigned mask)
Definition: Type.h:398
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
void setBlockVarCopyInit(const VarDecl *VD, Expr *CopyExpr, bool CanThrow)
Set the copy initialization expression of a block var decl.
bool isObjCClassType() const
Definition: Type.h:6657
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:2684
DeclContext * getDeclContext()
Definition: DeclBase.h:438
A structure for storing the information associated with a substituted template template parameter...
Definition: TemplateName.h:349
bool isObjCIdType() const
True if this is equivalent to the &#39;id&#39; type, i.e.
Definition: Type.h:6013
ObjCInterfaceDecl * getSuperClass() const
Definition: DeclObjC.cpp:337
SourceLocation Begin
UsingShadowDecl * getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst)
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:4404
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition: CharUnits.h:63
CanQualType ShortTy
Definition: ASTContext.h:1025
An abstract interface that should be implemented by listeners that want to be notified when an AST en...
ArrayRef< TemplateArgument > asArray() const
Produce this as an array ref.
Definition: DeclTemplate.h:293
TypedefDecl * getInt128Decl() const
Retrieve the declaration for the 128-bit signed integer type.
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
bool isTemplateParameterPack() const
isTemplateParameter - Determines whether this declaration is a template parameter pack...
Definition: DeclBase.cpp:201
Represents a C++ template name within the type system.
Definition: TemplateName.h:191
Represents the type decltype(expr) (C++11).
Definition: Type.h:4370
static TypedefDecl * CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context)
LangAS getLangASForBuiltinAddressSpace(unsigned AS) const
QualType getFILEType() const
Retrieve the C FILE type.
Definition: ASTContext.h:1767
llvm::PointerUnion< ClassTemplateDecl *, ClassTemplatePartialSpecializationDecl * > getSpecializedTemplateOrPartial() const
Retrieve the class template or class template partial specialization which was specialized by this...
void printTemplateArgumentList(raw_ostream &OS, ArrayRef< TemplateArgument > Args, const PrintingPolicy &Policy)
Print a template argument list, including the &#39;<&#39; and &#39;>&#39; enclosing the template arguments.
Defines the clang::TypeLoc interface and its subclasses.
A namespace alias, stored as a NamespaceAliasDecl*.
bool isIdentifier() const
Determine whether this template name refers to an identifier.
Definition: TemplateName.h:505
int Depth
Definition: ASTDiff.cpp:190
TemplateOrSpecializationInfo getTemplateOrSpecializationInfo(const VarDecl *Var)
const AstTypeMatcher< ArrayType > arrayType
Matches all kinds of arrays.
void setObjCImplementation(ObjCInterfaceDecl *IFaceD, ObjCImplementationDecl *ImplD)
Set the implementation of ObjCInterfaceDecl.
virtual void RedefinedHiddenDefinition(const NamedDecl *D, Module *M)
A definition has been made visible by being redefined locally.
const TemplateParameterList * TemplateParameters
Template parameters that can be referenced by \tparam if CommentDecl is a template (IsTemplateDecl or...
Definition: Comment.h:1008
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type...
Definition: Type.h:2251
bool TraverseAST(ASTContext &AST)
Recursively visits an entire AST, starting from the top-level Decls in the AST traversal scope (by de...
CanQualType UnsignedInt128Ty
Definition: ASTContext.h:1027
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition: Expr.h:739
A std::pair-like structure for storing a qualified type split into its local qualifiers and its local...
Definition: Type.h:593
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char, signed char, short, int, long..], or an enum decl which has a signed representation.
Definition: Type.cpp:1928
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3339
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
QualType getType() const
Definition: Expr.h:137
static SourceLocation getDeclLocForCommentSearch(const Decl *D, SourceManager &SourceMgr)
Definition: ASTContext.cpp:131
A unary type transform, which is a type constructed from another.
Definition: Type.h:4413
const ObjCMethodDecl * getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const
Get the duplicate declaration of a ObjCMethod in the same interface, or null if none exists...
overridden_method_range overridden_methods(const CXXMethodDecl *Method) const
clang::ObjCRuntime ObjCRuntime
Definition: LangOptions.h:257
DeclarationName getCXXOperatorName(OverloadedOperatorKind Op)
Get the name of the overloadable C++ operator corresponding to Op.
Qualifiers Quals
The local qualifiers.
Definition: Type.h:598
ASTEdit remove(RangeSelector S)
Removes the source selected by S.
Definition: RewriteRule.cpp:82
unsigned getMaxAlignment() const
getMaxAlignment - return the maximum alignment specified by attributes on this decl, 0 if there are none.
Definition: DeclBase.cpp:385
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:1784
void setAddressSpace(LangAS space)
Definition: Type.h:379
Represents a folding of a pack over an operator.
Definition: ExprCXX.h:4529
bool isObjCUnqualifiedId() const
Definition: Type.h:5767
void setTypeConstraint(NestedNameSpecifierLoc NNS, DeclarationNameInfo NameInfo, NamedDecl *FoundDecl, ConceptDecl *CD, const ASTTemplateArgumentListInfo *ArgsAsWritten, Expr *ImmediatelyDeclaredConstraint)
QualType getRecordType(const RecordDecl *Decl) const
QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl, ObjCInterfaceDecl *PrevDecl=nullptr) const
getObjCInterfaceType - Return the unique reference to the type for the specified ObjC interface decl...
QualType getFunctionTypeWithExceptionSpec(QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI)
Get a function type and produce the equivalent function type with the specified exception specificati...
bool isInstanceMethod() const
Definition: DeclObjC.h:423
unsigned NumImplicitMoveConstructors
The number of implicitly-declared move constructors.
Definition: ASTContext.h:2879
QualType getBlockDescriptorType() const
Gets the struct used to keep track of the descriptor for pointer to blocks.
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
Definition: ASTContext.h:1401
Represents a GCC generic vector type.
Definition: Type.h:3235
struct CXXOpName CXXOperatorName
static bool CanThrow(Expr *E, ASTContext &Ctx)
Definition: CFG.cpp:2580
An lvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:2797
TypedefDecl * getBuiltinVaListDecl() const
Retrieve the C type declaration corresponding to the predefined __builtin_va_list type...
TemplateTemplateParmDecl - Declares a template template parameter, e.g., "T" in.
void addDeclaratorForUnnamedTagDecl(TagDecl *TD, DeclaratorDecl *DD)
QualType getSubstTemplateTypeParmPackType(const TemplateTypeParmType *Replaced, const TemplateArgument &ArgPack)
Retrieve a.
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1091
CanQualType SatLongAccumTy
Definition: ASTContext.h:1034
Common base class for placeholders for types that get replaced by placeholder type deduction: C++11 a...
Definition: Type.h:4833
Implements C++ ABI-specific semantic analysis functions.
Definition: CXXABI.h:29
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition: Type.h:6925
unsigned getParameterIndex(const ParmVarDecl *D) const
Used by ParmVarDecl to retrieve on the side the index of the parameter when it exceeds the size of th...
NamedDecl * getInstantiatedFromUsingDecl(NamedDecl *Inst)
If the given using decl Inst is an instantiation of a (possibly unresolved) using decl from a templat...
void deduplicateMergedDefinitonsFor(NamedDecl *ND)
Clean up the merged definition list.
void CollectInheritedProtocols(const Decl *CDecl, llvm::SmallPtrSet< ObjCProtocolDecl *, 8 > &Protocols)
CollectInheritedProtocols - Collect all protocols in current class and those inherited by it...
Selector getSelector() const
Definition: DeclObjC.h:322
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1417
The result type of a method or function.
This template specialization was implicitly instantiated from a template.
Definition: Specifiers.h:181
bool isObjCClass() const
Definition: Type.h:5763
bool isNull() const
Return true if this QualType doesn&#39;t point to a type yet.
Definition: Type.h:719
QualType getDependentSizedExtVectorType(QualType VectorType, Expr *SizeExpr, SourceLocation AttrLoc) const
void removeCVRQualifiers(unsigned mask)
Definition: Type.h:283
bool useAddressSpaceMapMangling() const
Specify if mangling based on address space map should be used or not for language specific address sp...
Definition: TargetInfo.h:760
QualType getType() const
Definition: DeclObjC.h:842
const SourceManager & SM
Definition: Format.cpp:1685
comments::FullComment * parse(const ASTContext &Context, const Preprocessor *PP, const Decl *D) const
Parse the comment, assuming it is attached to decl D.
void setDeclContext(DeclContext *DC)
setDeclContext - Set both the semantic and lexical DeclContext to DC.
Definition: DeclBase.cpp:295
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:265
GlobalDecl - represents a global declaration.
Definition: GlobalDecl.h:40
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:4460
CanQualType SignedCharTy
Definition: ASTContext.h:1025
LangAS getOpenCLTypeAddrSpace(const Type *T) const
Get address space for OpenCL type.
static TemplateParameterList * Create(const ASTContext &C, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef< NamedDecl *> Params, SourceLocation RAngleLoc, Expr *RequiresClause)
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
Definition: Redeclarable.h:215
static CXXRecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, CXXRecordDecl *PrevDecl=nullptr, bool DelayTypeCreation=false)
Definition: DeclCXX.cpp:126
bool isSignedFixedPointType() const
Return true if this is a fixed point type that is signed according to ISO/IEC JTC1 SC22 WG14 N1169...
Definition: Type.h:6848
QualType getObjCGCQualType(QualType T, Qualifiers::GC gcAttr) const
Return the uniqued reference to the type for an Objective-C gc-qualified type.
QualType getAttributedType(attr::Kind attrKind, QualType modifiedType, QualType equivalentType)
ExtInfo withNoReturn(bool noReturn) const
Definition: Type.h:3604
std::pair< CharUnits, CharUnits > getTypeInfoDataSizeInChars(QualType T) const
WatchOS is a modernisation of the iOS ABI, which roughly means it&#39;s the iOS64 ABI ported to 32-bits...
Definition: TargetCXXABI.h:75
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:6315
EnumDecl * getInstantiatedFromMemberEnum() const
Returns the enumeration (declared within the template) from which this enumeration type was instantia...
Definition: Decl.cpp:4338
SplitQualType split() const
Divides a QualType into its unqualified type and a set of local qualifiers.
Definition: Type.h:6264
RecordDecl * getDecl() const
Definition: Type.h:4505
noexcept(expression), evals to &#39;false&#39;
QualType getPackExpansionType(QualType Pattern, Optional< unsigned > NumExpansions)
CanQualType getUIntMaxType() const
Return the unique type for "uintmax_t" (C99 7.18.1.5), defined in <stdint.h>.
Abstract interface for external sources of AST nodes.
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
Definition: RecordLayout.h:190
unsigned getCommentBeginLine(RawComment *C, FileID File, unsigned Offset) const
QualType getWideCharType() const
Return the type of wide characters.
Definition: ASTContext.h:1590
Copy initialization expr of a __block variable and a boolean flag that indicates whether the expressi...
Definition: Expr.h:5627
A template template parameter pack that has been substituted for a template template argument pack...
Definition: TemplateName.h:228
bool isComputedNoexcept(ExceptionSpecificationType ESpecType)
CanQualType OverloadTy
Definition: ASTContext.h:1045
There is no lifetime qualification on this type.
Definition: Type.h:160
OverloadedTemplateStorage * getAsOverloadedTemplate() const
Retrieve the underlying, overloaded function template declarations that this template name refers to...
void PrintStats() const
std::string getAsString() const
Derive the full selector name (e.g.
is AltiVec &#39;vector Pixel&#39;
Definition: Type.h:3245
CanQualType BuiltinFnTy
Definition: ASTContext.h:1046
TemplateName getDependentTemplateName(NestedNameSpecifier *NNS, const IdentifierInfo *Name) const
Retrieve the template name that represents a dependent template name such as MetaFun::template apply...
SelectorTable & Selectors
Definition: ASTContext.h:581
Assigning into this object requires the old value to be released and the new value to be retained...
Definition: Type.h:171
Kind
bool QIdProtocolsAdoptObjCObjectProtocols(QualType QT, ObjCInterfaceDecl *IDecl)
QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in QT&#39;s qualified-id protocol list adopt...
QualType getCanonicalType() const
Definition: Type.h:6295
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition: Type.h:6590
not a target-specific vector type
Definition: Type.h:3239
llvm::PointerUnion< VarTemplateDecl *, MemberSpecializationInfo * > TemplateOrSpecializationInfo
A type synonym for the TemplateOrInstantiation mapping.
Definition: ASTContext.h:422
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition: Type.h:3813
QualType getElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, QualType NamedType, TagDecl *OwnedTagDecl=nullptr) const
bool isInstantiationDependent() const
Whether this expression is instantiation-dependent, meaning that it depends in some way on a template...
Definition: Expr.h:200
decl_type * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
Definition: Redeclarable.h:203
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition: Type.h:4167
bool isSpecialized() const
Determine whether this object type is "specialized", meaning that it has type arguments.
Definition: Type.cpp:698
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:3975
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition: DeclBase.cpp:218
static GVALinkage basicGVALinkageForFunction(const ASTContext &Context, const FunctionDecl *FD)
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition: Redeclarable.h:294
QualType getSignatureParameterType(QualType T) const
Retrieve the parameter type as adjusted for use in the signature of a function, decaying array and fu...
const ExtParameterInfo * ExtParameterInfos
Definition: Type.h:3844
unsigned getMaxAtomicInlineWidth() const
Return the maximum width lock-free atomic operation which can be inlined given the supported features...
Definition: TargetInfo.h:624
NullPointerConstantKind isNullPointerConstant(ASTContext &Ctx, NullPointerConstantValueDependence NPC) const
isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to a Null pointer constant...
Definition: Expr.cpp:3743
Encodes a location in the source.
ObjCInterfaceDecl * getDecl() const
Get the declaration of this interface.
Definition: Type.h:5908
TypedefDecl * getUInt128Decl() const
Retrieve the declaration for the 128-bit unsigned integer type.
Sugar for parentheses used when specifying types.
Definition: Type.h:2584
StringLiteral * getPredefinedStringLiteralFromCache(StringRef Key) const
Return a string representing the human readable name for the specified function declaration or file n...
QualType getReturnType() const
Definition: Type.h:3680
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums...
Definition: Type.h:4521
bool hasSameTemplateName(TemplateName X, TemplateName Y)
Determine whether the given template names refer to the same template.
bool qual_empty() const
Definition: Type.h:6084
llvm::APSInt APSInt
ParsedTargetAttr filterFunctionTargetAttrs(const TargetAttr *TD) const
Parses the target attributes passed in, and returns only the ones that are valid feature names...
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:6377
QualType getUIntPtrType() const
Return a type compatible with "uintptr_t" (C99 7.18.1.4), as defined by the target.
CanQualType UnsignedLongAccumTy
Definition: ASTContext.h:1031
unsigned getOpenMPDefaultSimdAlign(QualType T) const
Get default simd alignment of the specified complete type in bits.
CanQualType Int128Ty
Definition: ASTContext.h:1025
Represents typeof(type), a GCC extension.
Definition: Type.h:4343
Interfaces are the core concept in Objective-C for object oriented design.
Definition: Type.h:5894
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:2166
bool isObjCQualifiedClassType() const
True if this is equivalent to &#39;Class.
Definition: Type.h:6036
This names the __make_integer_seq BuiltinTemplateDecl.
Definition: Builtins.h:248
unsigned getManglingNumber(const NamedDecl *ND) const
A structure for storing an already-substituted template template parameter pack.
Definition: TemplateName.h:134
A simple holder for various uncommon bits which do not fit in FunctionTypeBitfields.
Definition: Type.h:3656
const std::map< unsigned, RawComment * > * getCommentsInFile(FileID File) const
std::string getNameAsString() const
Get a human-readable name for the declaration, even if it is one of the special kinds of names (C++ c...
Definition: Decl.h:266
CanQualType SatFractTy
Definition: ASTContext.h:1037
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3219
TypeSourceInfo * CreateTypeSourceInfo(QualType T, unsigned Size=0) const
Allocate an uninitialized TypeSourceInfo.
size_t getSideTableAllocatedMemory() const
Return the total memory used for various side tables.
virtual LangAS getOpenCLBuiltinAddressSpace(unsigned AS) const
Map from the address space field in builtin description strings to the language address space...
Definition: TargetInfo.h:1245
CallingConv getCC() const
Definition: Type.h:3592
QualType getElementType() const
Definition: Type.h:3270
const Decl * getDecl() const
Definition: GlobalDecl.h:77
static QualType getUnderlyingType(const SubRegion *R)
QualType getObjCSelType() const
Retrieve the type that corresponds to the predefined Objective-C &#39;SEL&#39; type.
Definition: ASTContext.h:1884
ParsedAttr - Represents a syntactic attribute.
Definition: ParsedAttr.h:117
Represents a vector type where either the type or size is dependent.
Definition: Type.h:3312
ObjCInterfaceDecl * getObjCProtocolDecl() const
Retrieve the Objective-C class declaration corresponding to the predefined Protocol class...
QualType getWritePipeType(QualType T) const
Return a write_only pipe type for the specified type.
void Profile(llvm::FoldingSetNodeID &ID)
Definition: TemplateName.h:426
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
MangleContext - Context for tracking state which persists across multiple calls to the C++ name mangl...
Definition: Mangle.h:43
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:1931
TypedefNameDecl * getTypedefNameForUnnamedTagDecl(const TagDecl *TD)
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2466
bool hasExceptionSpec() const
Return whether this function has any kind of exception spec.
Definition: Type.h:3995
QualType getExtVectorType(QualType VectorType, unsigned NumElts) const
Return the unique reference to an extended vector type of the specified element type and size...
DeclarationNameInfo getNameForTemplate(TemplateName Name, SourceLocation NameLoc) const
Expr * getRequiresClause()
The constraint-expression of the associated requires-clause.
Definition: DeclTemplate.h:176
Weak for now, might become strong later in this TU.
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:4756
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
CanQualType FloatTy
Definition: ASTContext.h:1028
unsigned getLineNumber(FileID FID, unsigned FilePos, bool *Invalid=nullptr) const
Given a SourceLocation, return the spelling line number for the position indicated.
This file defines OpenMP nodes for declarative directives.
overridden_cxx_method_iterator overridden_methods_begin(const CXXMethodDecl *Method) const
CanQualType SatUnsignedLongAccumTy
Definition: ASTContext.h:1035
DeclarationName getIdentifier(const IdentifierInfo *ID)
Create a declaration name that is a simple identifier.
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
ObjCCategoryDecl - Represents a category declaration.
Definition: DeclObjC.h:2294
unsigned pack_size() const
The number of template arguments in the given template argument pack.
Definition: TemplateBase.h:359
BuiltinTemplateKind
Kinds of BuiltinTemplateDecl.
Definition: Builtins.h:246
AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*, __atomic_load, __atomic_store, and __atomic_compare_exchange_*, for the similarly-named C++11 instructions, and __c11 variants for <stdatomic.h>, and corresponding __opencl_atomic_* for OpenCL 2.0.
Definition: Expr.h:5849
CanQualType VoidTy
Definition: ASTContext.h:1016
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition: Decl.h:3675
bool isValueDependent() const
isValueDependent - Determines whether this expression is value-dependent (C++ [temp.dep.constexpr]).
Definition: Expr.h:158
CanQualType Float16Ty
Definition: ASTContext.h:1041
CanQualType getSignedSizeType() const
Return the unique signed counterpart of the integer type corresponding to size_t. ...
bool isObjCObjectPointerType() const
Definition: Type.h:6618
bool isAnyPointerType() const
Definition: Type.h:6508
CanQualType SatLongFractTy
Definition: ASTContext.h:1037
This declaration is only a declaration.
Definition: Decl.h:1156
is AltiVec &#39;vector bool ...&#39;
Definition: Type.h:3248
SplitQualType getSplitUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:6343
llvm::APInt APInt
Definition: Integral.h:27
Represents one property declaration in an Objective-C interface.
Definition: DeclObjC.h:741
bool isFromASTFile() const
Determine whether this declaration came from an AST file (such as a precompiled header or module) rat...
Definition: DeclBase.h:702
__builtin_va_list as defined by the Power ABI: https://www.power.org /resources/downloads/Power-Arch-...
Definition: TargetInfo.h:244
bool canBindObjCObjectType(QualType To, QualType From)
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after...
Definition: Type.h:1174
The generic Itanium ABI is the standard ABI of most open-source and Unix-like platforms.
Definition: TargetCXXABI.h:33
void getOverriddenMethods(const NamedDecl *Method, SmallVectorImpl< const NamedDecl *> &Overridden) const
Return C++ or ObjC overridden methods for the given Method.
void InitBuiltinTypes(const TargetInfo &Target, const TargetInfo *AuxTarget=nullptr)
Initialize built-in types.
unsigned getCustomDiagID(Level L, const char(&FormatString)[N])
Return an ID for a diagnostic with the specified format string and level.
Definition: Diagnostic.h:782
bool isSuperClassOf(const ObjCInterfaceDecl *I) const
isSuperClassOf - Return true if this class is the specified class or is a super class of the specifie...
Definition: DeclObjC.h:1824
Qualifiers getIndexTypeQualifiers() const
Definition: Type.h:2916
TypeClass getTypeClass() const
Definition: Type.h:1876
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition: Specifiers.h:193
This template specialization was formed from a template-id but has not yet been declared, defined, or instantiated.
Definition: Specifiers.h:178
bool typesAreBlockPointerCompatible(QualType, QualType)
CharUnits getDataSize() const
getDataSize() - Get the record data size, which is the record size without tail padding, in characters.
Definition: RecordLayout.h:196
QualType getSuperClassType() const
Retrieve the type of the superclass of this object type.
Definition: Type.h:5822
ObjCDeclQualifier getObjCDeclQualifier() const
Definition: DeclObjC.h:248
bool isTargetAddressSpace(LangAS AS)
Definition: AddressSpaces.h:62
EnumDecl * getDecl() const
Definition: Type.h:4528
bool isVectorType() const
Definition: Type.h:6606
ObjCPropertyImplDecl * getObjCPropertyImplDeclForPropertyDecl(const ObjCPropertyDecl *PD, const Decl *Container) const
Assigning into this object requires a lifetime extension.
Definition: Type.h:177
static ConceptSpecializationExpr * Create(const ASTContext &C, NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc, DeclarationNameInfo ConceptNameInfo, NamedDecl *FoundDecl, ConceptDecl *NamedConcept, const ASTTemplateArgumentListInfo *ArgsAsWritten, ArrayRef< TemplateArgument > ConvertedArgs, const ConstraintSatisfaction *Satisfaction)
QualType AutoDeductTy
Definition: ASTContext.h:1064
CanQualType SatUnsignedFractTy
Definition: ASTContext.h:1038
unsigned getPreferredTypeAlign(const Type *T) const
Return the "preferred" alignment of the specified type T for the current target, in bits...
FixedPointSemantics getFixedPointSemantics(QualType Ty) const
ObjCImplementationDecl * getImplementation() const
Definition: DeclObjC.cpp:1574
static DynTypedNode create(const T &Node)
Creates a DynTypedNode from Node.
comments::FullComment * getCommentForDecl(const Decl *D, const Preprocessor *PP) const
Return parsed documentation comment attached to a given declaration.
Definition: ASTContext.cpp:557
bool isCanonical() const
Definition: Type.h:6300
CanQualType SatUnsignedShortFractTy
Definition: ASTContext.h:1038
bool hasFlexibleArrayMember() const
Definition: Decl.h:3802
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2345
DependentTemplateName * getAsDependentTemplateName() const
Retrieve the underlying dependent template name structure, if any.
void addArgument(const TemplateArgumentLoc &Loc)
Definition: TemplateBase.h:594
bool isPtrSizeAddressSpace(LangAS AS)
Definition: AddressSpaces.h:76
__builtin_va_list as defined by ARM AAPCS ABI http://infocenter.arm.com
Definition: TargetInfo.h:253
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:6112
Defines the fixed point number interface.
CharUnits getUnadjustedAlignment() const
getUnadjustedAlignment - Get the record alignment in characters, before alignment adjustement...
Definition: RecordLayout.h:180
Describes a module import declaration, which makes the contents of the named module visible in the cu...
Definition: Decl.h:4331
Represents a pointer type decayed from an array or function type.
Definition: Type.h:2699
void setTraversalScope(const std::vector< Decl *> &)
QualType getArrayDecayedType(QualType T) const
Return the properly qualified result of decaying the specified array type to a pointer.
The WebAssembly ABI is a modified version of the Itanium ABI.
Definition: TargetCXXABI.h:104
CanQualType SatAccumTy
Definition: ASTContext.h:1034
The injected class name of a C++ class template or class template partial specialization.
Definition: Type.h:5133
const llvm::fltSemantics & getFloatTypeSemantics(QualType T) const
Return the APFloat &#39;semantics&#39; for the specified scalar floating point type.
Represents a pack expansion of types.
Definition: Type.h:5511
std::pair< CharUnits, CharUnits > getTypeInfoInChars(const Type *T) const
static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET, QualType other, bool isBlockReturnType)
Given that we have an enum type and a non-enum type, try to merge them.
ArrayRef< TemplateArgument > pack_elements() const
Iterator range referencing all of the elements of a template argument pack.
Definition: TemplateBase.h:353
ast_type_traits::DynTypedNode DynTypedNode
IntType
===-— Target Data Type Query Methods ----------------------------—===//
Definition: TargetInfo.h:107
Defines various enumerations that describe declaration and type specifiers.
DeclarationNameLoc - Additional source/type location info for a declaration name. ...
void setTemplateKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:1584
void * Allocate(size_t Size, unsigned Align=8) const
Definition: ASTContext.h:686
ObjCDeclQualifier getObjCDeclQualifier() const
Definition: Decl.h:1656
ArrayRef< Decl * > getModuleInitializers(Module *M)
Get the initializations to perform when importing a module, if any.
Stencil cat(Ts &&... Parts)
Concatenates 0+ stencil pieces into a single stencil.
Definition: Stencil.h:64
CanQualType UnsignedShortTy
Definition: ASTContext.h:1026
ObjCIvarDecl * getNextIvar()
Definition: DeclObjC.h:1992
QualType getTypedefType(const TypedefNameDecl *Decl, QualType Canon=QualType()) const
Return the unique reference to the type for the specified typedef-name decl.
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:3071
ast_type_traits::DynTypedNode Node
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
CanQualType CharTy
Definition: ASTContext.h:1018
bool propertyTypesAreCompatible(QualType, QualType)
Represents a template argument.
Definition: TemplateBase.h:50
static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context, ASTContext::GetBuiltinTypeError &Error, bool &RequiresICE, bool AllowTypeModifiers)
DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the pointer over the consume...
QualType getTemplateSpecializationType(TemplateName T, ArrayRef< TemplateArgument > Args, QualType Canon=QualType()) const
Represents a type which was implicitly adjusted by the semantic engine for arbitrary reasons...
Definition: Type.h:2662
QualType withRestrict() const
Definition: Type.h:842
Represents a template name that was expressed as a qualified name.
Definition: TemplateName.h:390
TagTypeKind
The kind of a tag type.
Definition: Type.h:5187
bool hasSameFunctionTypeIgnoringPtrSizes(QualType T, QualType U)
Determine whether two function types are the same, ignoring pointer sizes in the return type and para...
RealType getRealTypeByWidth(unsigned BitWidth) const
Return floating point type with specified width.
Definition: TargetInfo.cpp:265
QualType getDecayedType(QualType T) const
Return the uniqued reference to the decayed version of the given type.
QualType getTypeOfType(QualType t) const
getTypeOfType - Unlike many "get<Type>" functions, we don&#39;t unique TypeOfType nodes.
const ObjCInterfaceDecl * getClassInterface() const
Definition: DeclObjC.h:2454
void setPlaceholderTypeConstraint(Expr *E)
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition: DeclBase.h:948
CanQualType ObjCBuiltinIdTy
Definition: ASTContext.h:1048
void getLegacyIntegralTypeEncoding(QualType &t) const
getLegacyIntegralTypeEncoding - Another legacy compatibility encoding: 32-bit longs are encoded as &#39;l...
GC getObjCGCAttr() const
Definition: Type.h:307
Dataflow Directional Tag Classes.
int getFloatingTypeOrder(QualType LHS, QualType RHS) const
Compare the rank of the two specified floating point types, ignoring the domain of the type (i...
void getInjectedTemplateArgs(const TemplateParameterList *Params, SmallVectorImpl< TemplateArgument > &Args)
Get a template argument list with one argument per template parameter in a template parameter list...
TemplateName getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param, const TemplateArgument &ArgPack) const
CharUnits getSize() const
getSize - Get the record size in characters.
Definition: RecordLayout.h:183
bool isTrailingComment() const LLVM_READONLY
Returns true if it is a comment that should be put after a member:
DeducedType * getContainedDeducedType() const
Get the DeducedType whose type will be deduced for a variable with an initializer of this type...
Definition: Type.cpp:1808
A RecursiveASTVisitor that builds a map from nodes to their parents as defined by the RecursiveASTVis...
ExtInfo getExtInfo() const
Definition: Type.h:3691
TargetInfo::OpenCLTypeKind getOpenCLTypeKind(const Type *T) const
Map an AST Type to an OpenCLTypeKind enum value.
not evaluated yet, for special member function
static NonTypeTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, unsigned D, unsigned P, IdentifierInfo *Id, QualType T, bool ParameterPack, TypeSourceInfo *TInfo)
A qualifier set is used to build a set of qualifiers.
Definition: Type.h:6196
QualType mergeTypes(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false, bool BlockReturnType=false)
bool hasDirectOwnershipQualifier(QualType Ty) const
Return true if the type has been explicitly qualified with ObjC ownership.
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1271
CanQualType NullPtrTy
Definition: ASTContext.h:1044
void forEachMultiversionedFunctionVersion(const FunctionDecl *FD, llvm::function_ref< void(FunctionDecl *)> Pred) const
Visits all versions of a multiversioned function with the passed predicate.
bool isSentinelNullExpr(const Expr *E)
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:402
CanQualType DoubleComplexTy
Definition: ASTContext.h:1042
static GVALinkage adjustGVALinkageForExternalDefinitionKind(const ASTContext &Ctx, const Decl *D, GVALinkage L)
Adjust the GVALinkage for a declaration based on what an external AST source knows about whether ther...
static std::string getName(const CallEvent &Call)
const Expr * traverseIgnored(const Expr *E) const
Definition: ASTContext.cpp:102
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
Definition: OperatorKinds.h:21
void addCopyConstructorForExceptionObject(CXXRecordDecl *RD, CXXConstructorDecl *CD)
typedef char* __builtin_va_list;
Definition: TargetInfo.h:228
static FloatingRank getFloatingRank(QualType T)
getFloatingRank - Return a relative rank for floating point types.
APFixedPoint getFixedPointMin(QualType Ty) const
CanQualType UnsignedShortAccumTy
Definition: ASTContext.h:1031
static BuiltinTemplateDecl * Create(const ASTContext &C, DeclContext *DC, DeclarationName Name, BuiltinTemplateKind BTK)
The template argument is a pack expansion of a template name that was provided for a template templat...
Definition: TemplateBase.h:79
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition: Decl.cpp:3756
bool isObjCClassType() const
True if this is equivalent to the &#39;Class&#39; type, i.e.
Definition: Type.h:6019
unsigned[(unsigned) LangAS::FirstTargetAddressSpace] LangASMap
The type of a lookup table which maps from language-specific address spaces to target-specific ones...
Definition: AddressSpaces.h:58
static bool areCompatVectorTypes(const VectorType *LHS, const VectorType *RHS)
areCompatVectorTypes - Return true if the two specified vector types are compatible.
QualType getUnderlyingType() const
Definition: Decl.h:3126
Interesting information about a specific parameter that can&#39;t simply be reflected in parameter&#39;s type...
Definition: Type.h:3448
CanQualType UnsignedLongLongTy
Definition: ASTContext.h:1027
bool isDependent() const
Whether this nested name specifier refers to a dependent type or not.
unsigned NumImplicitMoveAssignmentOperatorsDeclared
The number of implicitly-declared move assignment operators for which declarations were built...
Definition: ASTContext.h:2897
unsigned NumImplicitDefaultConstructorsDeclared
The number of implicitly-declared default constructors for which declarations were built...
Definition: ASTContext.h:2869
ObjCInterfaceDecl * getDefinition()
Retrieve the definition of this class, or NULL if this class has been forward-declared (with @class) ...
Definition: DeclObjC.h:1563
bool hasCvrSimilarType(QualType T1, QualType T2)
Determine if two types are similar, ignoring only CVR qualifiers.
NamespaceDecl * getOriginalNamespace()
Get the original (first) namespace declaration.
Definition: DeclCXX.cpp:2784
bool hasLocalQualifiers() const
Determine whether this particular QualType instance has any qualifiers, without looking through any t...
Definition: Type.h:756
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition: Specifiers.h:189
QualType getProcessIDType() const
Return the unique type for "pid_t" defined in <sys/types.h>.
bool isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const
Returns true if this is an inline-initialized static data member which is treated as a definition for...
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.cpp:3530
The name of a declaration.
VectorKind getVectorKind() const
Definition: Type.h:3280
Represents the declaration of an Objective-C type parameter.
Definition: DeclObjC.h:571
void cacheRawCommentForDecl(const Decl &OriginalD, const RawComment &Comment) const
Attaches Comment to OriginalD and to its redeclaration chain and removes the redeclaration chain from...
Definition: ASTContext.cpp:465
bool isBooleanType() const
Definition: Type.h:6894
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition: Type.h:6203
const CXXRecordDecl * getBaseSharingVBPtr() const
Definition: RecordLayout.h:310
Represents a C++11 pack expansion that produces a sequence of expressions.
Definition: ExprCXX.h:4015
QualType getFunctionNoProtoType(QualType ResultTy, const FunctionType::ExtInfo &Info) const
Return a K&R style C function type like &#39;int()&#39;.
The Fuchsia ABI is a modified version of the Itanium ABI.
Definition: TargetCXXABI.h:110
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3221
MangleNumberingContext & getManglingNumberContext(const DeclContext *DC)
Retrieve the context for computing mangling numbers in the given DeclContext.
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.cpp:3545
static FixedPointSemantics GetIntegerSemantics(unsigned Width, bool IsSigned)
Return the FixedPointSemantics for an integer type.
Definition: FixedPoint.h:70
const ObjCObjectType * getObjectType() const
Gets the type pointed to by this ObjC pointer.
Definition: Type.h:5992
bool isKindOfType() const
Whether this ia a "__kindof" type (semantically).
Definition: Type.cpp:734
Represents an enum.
Definition: Decl.h:3481
FunctionType::ExtInfo getFunctionExtInfo(const Type &t)
Definition: Type.h:6404
Information about the declaration, useful to clients of FullComment.
Definition: Comment.h:982
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:2779
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:2833
bool isIntegerConstantExpr(llvm::APSInt &Result, const ASTContext &Ctx, SourceLocation *Loc=nullptr, bool isEvaluated=true) const
isIntegerConstantExpr - Return true if this expression is a valid integer constant expression...
const FunctionType * adjustFunctionType(const FunctionType *Fn, FunctionType::ExtInfo EInfo)
Change the ExtInfo on a function type.
This names the __type_pack_element BuiltinTemplateDecl.
Definition: Builtins.h:251
bool canAssignObjCInterfacesInBlockPointer(const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT, bool BlockReturnType)
canAssignObjCInterfacesInBlockPointer - This routine is specifically written for providing type-safet...
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition: Specifiers.h:175
bool hasObjCLifetime() const
Definition: Type.h:332
QualType AutoRRefDeductTy
Definition: ASTContext.h:1065
BlockVarCopyInit getBlockVarCopyInit(const VarDecl *VD) const
Get the copy initialization expression of the VarDecl VD, or nullptr if none exists.
virtual ~CXXABI()
llvm::ArrayRef< TemplateArgumentLoc > arguments() const
Definition: TemplateBase.h:582
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspnd...
A type that was preceded by the &#39;template&#39; keyword, stored as a Type*.
ExternalASTSource * getExternalSource() const
Retrieve a pointer to the external AST source associated with this AST context, if any...
Definition: ASTContext.h:1086
pack_iterator pack_begin() const
Iterator referencing the first argument of a template argument pack.
Definition: TemplateBase.h:339
virtual bool hasFeature(StringRef Feature) const
Determine whether the given target has the given feature.
Definition: TargetInfo.h:1143
bool areComparableObjCPointerTypes(QualType LHS, QualType RHS)
QualType getUnsignedWCharType() const
Return the type of "unsigned wchar_t".
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:4703
void addConsistentQualifiers(Qualifiers qs)
Add the qualifiers from the given set to this set, given that they don&#39;t conflict.
Definition: Type.h:459
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition: Expr.cpp:2995
bool isMacroID() const
bool ObjCQualifiedClassTypesAreCompatible(const ObjCObjectPointerType *LHS, const ObjCObjectPointerType *RHS)
ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and Class<pr1, ...>. ...
GVALinkage GetGVALinkageForVariable(const VarDecl *VD)
A dynamically typed AST node container.
virtual IntType getIntTypeByWidth(unsigned BitWidth, bool IsSigned) const
Return integer type with specified width.
Definition: TargetInfo.cpp:235
Represents a pointer to an Objective C object.
Definition: Type.h:5951
unsigned getMultiVersionIndex() const
Definition: GlobalDecl.h:96
Pointer to a block type.
Definition: Type.h:2716
CanQualType ObjCBuiltinBoolTy
Definition: ASTContext.h:1049
unsigned getIntWidth(QualType T) const
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
Definition: DeclObjC.h:2566
QualType getDependentSizedArrayType(QualType EltTy, Expr *NumElts, ArrayType::ArraySizeModifier ASM, unsigned IndexTypeQuals, SourceRange Brackets) const
Return a non-unique reference to the type for a dependently-sized array of the specified element type...
CharUnits getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const
Loading virtual member pointers using the virtual inheritance model always results in an adjustment u...
virtual ExtKind hasExternalDefinitions(const Decl *D)
bool isIncompleteArrayType() const
Definition: Type.h:6578
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:4495
StringRef getObjCRuntimeNameAsString() const
Produce a name to be used for class&#39;s metadata.
Definition: DeclObjC.cpp:1558
Complex values, per C99 6.2.5p11.
Definition: Type.h:2554
Location wrapper for a TemplateArgument.
Definition: TemplateBase.h:449
BuiltinTemplateDecl * getTypePackElementDecl() const
bool isMacroArgExpansion(SourceLocation Loc, SourceLocation *StartLoc=nullptr) const
Tests whether the given source location represents a macro argument&#39;s expansion into the function-lik...
QualType getStringLiteralArrayType(QualType EltTy, unsigned Length) const
Return a type for a constant array for a string literal of the specified element type and length...
bool isObjCQualifiedId() const
Definition: Type.h:5776
CanQualType UnknownAnyTy
Definition: ASTContext.h:1045
bool empty() const
Definition: Type.h:421
bool isConstantSizeType() const
Return true if this is not a variable sized type, according to the rules of C99 6.7.5p3.
Definition: Type.cpp:2105
bool doUnsignedFixedPointTypesHavePadding() const
In the event this target uses the same number of fractional bits for its unsigned types as it does wi...
Definition: TargetInfo.h:332
ObjCInterfaceDecl * getInterfaceDecl() const
If this pointer points to an Objective @interface type, gets the declaration for that interface...
Definition: Type.h:6007
TemplateName getAssumedTemplateName(DeclarationName Name) const
Retrieve a template name representing an unqualified-id that has been assumed to name a template for ...
comments::FullComment * getLocalCommentForDeclUncached(const Decl *D) const
Return parsed documentation comment attached to a given declaration.
Definition: ASTContext.cpp:552
QualType getCanonicalTypeInternal() const
Definition: Type.h:2429
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:6811
This template specialization was declared or defined by an explicit specialization (C++ [temp...
Definition: Specifiers.h:185
CanQualType UnsignedLongTy
Definition: ASTContext.h:1026
bool areCompatibleVectorTypes(QualType FirstVec, QualType SecondVec)
Return true if the given vector types are of the same unqualified type or if they are equivalent to t...
T * getAttr() const
Definition: DeclBase.h:538
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3012
const llvm::APInt & getSize() const
Definition: Type.h:2958
uint64_t getCharWidth() const
Return the size of the character type, in bits.
Definition: ASTContext.h:2108
CanQualType DependentTy
Definition: ASTContext.h:1045
QualType getFloatingTypeOfSizeWithinDomain(QualType typeSize, QualType typeDomain) const
Return a real floating point or a complex type (based on typeDomain/typeSize).
void getObjCEncodingForType(QualType T, std::string &S, const FieldDecl *Field=nullptr, QualType *NotEncodedT=nullptr) const
Emit the Objective-CC type encoding for the given type T into S.
CanQualType WCharTy
Definition: ASTContext.h:1019
bool isFunctionType() const
Definition: Type.h:6500
bool hasNonFastQualifiers() const
Return true if the set contains any qualifiers which require an ExtQuals node to be allocated...
Definition: Type.h:412
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition: Decl.h:1069
bool isObjCQualifiedIdType() const
Definition: Type.h:6639
static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET)
static GVALinkage basicGVALinkageForVariable(const ASTContext &Context, const VarDecl *VD)
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:700
bool isMSExternInline() const
The combination of the extern and inline keywords under MSVC forces the function to be required...
Definition: Decl.cpp:3279
ExtVectorType - Extended vector type.
Definition: Type.h:3354
CanQualType ObjCBuiltinClassTy
Definition: ASTContext.h:1048
DeclaratorDecl * getDeclaratorForUnnamedTagDecl(const TagDecl *TD)
param_const_iterator param_begin() const
Definition: DeclObjC.h:349
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:2750
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:1747
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2321
CanQualType BoundMemberTy
Definition: ASTContext.h:1045
const Expr * getSizeExpr() const
Definition: Type.h:2959
static TypedefDecl * CreateCharPtrBuiltinVaListDecl(const ASTContext *Context)
QualType getAutoDeductType() const
C++11 deduction pattern for &#39;auto&#39; type.
int getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const
Compare the rank of two floating point types as above, but compare equal if both types have the same ...
ObjCInterfaceDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this Objective-C class.
Definition: DeclObjC.h:1929
llvm::DenseMap< const Decl *, comments::FullComment * > ParsedComments
Mapping from declarations to parsed comments attached to any redeclaration.
Definition: ASTContext.h:770
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, const Expr *SizeExpr, ArrayType::ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type...
The template argument is a type.
Definition: TemplateBase.h:59
qual_range quals() const
Definition: Type.h:6074
Holds information about the various types of exception specification.
Definition: Type.h:3811
AssumedTemplateStorage * getAsAssumedTemplateName() const
Retrieve information on a name that has been assumed to be a template-name in order to permit a call ...
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1524
bool canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT)
canAssignObjCInterfaces - Return true if the two interface types are compatible for assignment from R...
TemplateArgument getInjectedTemplateArg(NamedDecl *ParamDecl)
Optional< NullabilityKind > getNullability(const ASTContext &context) const
Determine the nullability of the given type.
Definition: Type.cpp:3828
The template argument is actually a parameter pack.
Definition: TemplateBase.h:90
void getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT, std::string &S) const
Put the string version of the type qualifiers QT into S.
BuiltinVaListKind
The different kinds of __builtin_va_list types defined by the target implementation.
Definition: TargetInfo.h:226
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat]...
Definition: APValue.h:115
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2104
ArrayRef< QualType > Exceptions
Explicitly-specified list of exception types.
Definition: Type.h:3816
bool isObjCObjectType() const
Definition: Type.h:6622
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types...
Definition: Type.cpp:2115
bool hasObjCGCAttr() const
Definition: Type.h:306
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition: Decl.h:2513
CanQualType Char8Ty
Definition: ASTContext.h:1022
DynTypedNodeList getParents(const ast_type_traits::DynTypedNode &Node)
ASTMutationListener * getASTMutationListener() const
Retrieve a pointer to the AST mutation listener associated with this AST context, if any...
Definition: ASTContext.h:1101
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2305
A template argument list.
Definition: DeclTemplate.h:239
uint64_t getFieldOffset(const ValueDecl *FD) const
Get the offset of a FieldDecl or IndirectFieldDecl, in bits.
BuiltinTemplateDecl * buildBuiltinTemplateDecl(BuiltinTemplateKind BTK, const IdentifierInfo *II) const
static TypedefDecl * CreateVaListDecl(const ASTContext *Context, TargetInfo::BuiltinVaListKind Kind)
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:244
void mergeDefinitionIntoModule(NamedDecl *ND, Module *M, bool NotifyListeners=true)
Note that the definition ND has been merged into module M, and should be visible whenever M is visibl...
bool isNoThrow(unsigned ID) const
Return true if we know this builtin never throws an exception.
Definition: Builtins.h:109
X
Add a minimal nested name specifier fixit hint to allow lookup of a tag name from an outer enclosing ...
Definition: SemaDecl.cpp:14781
pack_iterator pack_end() const
Iterator referencing one past the last argument of a template argument pack.
Definition: TemplateBase.h:346
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
Reading or writing from this object requires a barrier call.
Definition: Type.h:174
ExternCContextDecl * getExternCContextDecl() const
bool hasSimilarType(QualType T1, QualType T2)
Determine if two types are similar, according to the C++ rules.
ArgKind getKind() const
Return the kind of stored template argument.
Definition: TemplateBase.h:234
An attributed type is a type to which a type attribute has been applied.
Definition: Type.h:4550
StringRef Architecture
Definition: Attr.h:335
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate.h) and friends (in DeclFriend.h).
QualType getParamType(unsigned i) const
Definition: Type.h:3966
QualType getTemplateTypeParmType(unsigned Depth, unsigned Index, bool ParameterPack, TemplateTypeParmDecl *ParmDecl=nullptr) const
Retrieve the template type parameter type for a template parameter or parameter pack with the given d...
Represents a type parameter type in Objective C.
Definition: Type.h:5620
bool typesAreCompatible(QualType T1, QualType T2, bool CompareUnqualified=false)
Compatibility predicates used to check assignment expressions.
int64_t toBits(CharUnits CharSize) const
Convert a size in characters to a size in bits.
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1009
Defines the clang::SourceLocation class and associated facilities.
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:4960
Interoperability with the Swift 4.2 runtime.
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:6336
bool hasUnaligned() const
Definition: Type.h:299
bool mergeExtParameterInfo(const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType, bool &CanUseFirst, bool &CanUseSecond, SmallVectorImpl< FunctionProtoType::ExtParameterInfo > &NewParamInfos)
This function merges the ExtParameterInfo lists of two functions.
void addModuleInitializer(Module *M, Decl *Init)
Add a declaration to the list of declarations that are initialized for a module.
const CXXMethodDecl * getCurrentKeyFunction(const CXXRecordDecl *RD)
Get our current best idea for the key function of the given record decl, or nullptr if there isn&#39;t on...
bool hasSignedIntegerRepresentation() const
Determine whether this type has an signed integer representation of some sort, e.g., it is an signed integer type or a vector.
Definition: Type.cpp:1958
Represents a C++ struct/union/class.
Definition: DeclCXX.h:253
VarDecl * getInstantiatedFromStaticDataMember() const
If this variable is an instantiated static data member of a class template specialization, returns the templated static data member from which it was instantiated.
Definition: Decl.cpp:2542
IdentifierInfo * getTypePackElementName() const
Definition: ASTContext.h:1747
Represents a template specialization type whose template cannot be resolved, e.g. ...
Definition: Type.h:5420
QualType getRValueReferenceType(QualType T) const
Return the uniqued reference to the type for an rvalue reference to the specified type...
TypeInfo getTypeInfo(const Type *T) const
Get the size and alignment of the specified complete type in bits.
The template argument is a template name that was provided for a template template parameter...
Definition: TemplateBase.h:75
ObjCDeclQualifier
ObjCDeclQualifier - &#39;Qualifiers&#39; written next to the return and parameter types in method declaration...
Definition: DeclBase.h:200
unsigned NumImplicitDestructors
The number of implicitly-declared destructors.
Definition: ASTContext.h:2900
Represents a C array with an unspecified size.
Definition: Type.h:2995
VTableContextBase * getVTableContext()
TemplateName getCanonicalTemplateName(TemplateName Name) const
Retrieves the "canonical" template name that refers to a given template.
Missing a type from <stdio.h>
Definition: ASTContext.h:2036
bool isOutOfLine() const override
Determine whether this is or was instantiated from an out-of-line definition of a static data member...
Definition: Decl.cpp:2267
static TranslationUnitDecl * Create(ASTContext &C)
Definition: Decl.cpp:4589
static void SortAndUniqueProtocols(SmallVectorImpl< ObjCProtocolDecl *> &Protocols)
IdentifierInfo * getMakeIntegerSeqName() const
Definition: ASTContext.h:1741
const ObjCInterfaceDecl * getObjContainingInterface(const NamedDecl *ND) const
Returns the Objective-C interface that ND belongs to if it is an Objective-C method/property/ivar etc...
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:6283
ObjCIvarDecl - Represents an ObjC instance variable.
Definition: DeclObjC.h:1959
static int compare(DeclarationName LHS, DeclarationName RHS)
static TypedefDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition: Decl.cpp:4803
Provides information a specialization of a member of a class template, which may be a member function...
Definition: DeclTemplate.h:622
CanQualType Char16Ty
Definition: ASTContext.h:1023
QualType removeAddrSpaceQualType(QualType T) const
Remove any existing address space on the type and returns the type with qualifiers intact (or that&#39;s ...
A structure for storing the information associated with an overloaded template name.
Definition: TemplateName.h:104
QualType getMacroQualifiedType(QualType UnderlyingTy, const IdentifierInfo *MacroII) const
Represents the specialization of a concept - evaluates to a prvalue of type bool. ...
Definition: ExprConcepts.h:40
A structure for storing the information associated with a name that has been assumed to be a template...
void getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT, QualType T, std::string &S, bool Extended) const
getObjCEncodingForMethodParameter - Return the encoded type for a single method parameter or return t...
Builtin::Context & BuiltinInfo
Definition: ASTContext.h:582
Location information for a TemplateArgument.
Definition: TemplateBase.h:392
Weak definition of inline variable.
CharUnits getNonVirtualSize() const
getNonVirtualSize - Get the non-virtual size (in chars) of an object, which is the size of the object...
Definition: RecordLayout.h:202
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:4334
Declaration of a class template.
static bool isAddressSpaceSupersetOf(LangAS A, LangAS B)
Returns true if address space A is equal to or a superset of B.
Definition: Type.h:476
Stores a list of Objective-C type parameters for a parameterized class or a category/extension thereo...
Definition: DeclObjC.h:649
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
unsigned kind
All of the diagnostics that can be emitted by the frontend.
Definition: DiagnosticIDs.h:60
This class is used for builtin types like &#39;int&#39;.
Definition: Type.h:2465
bool isVariadic() const
Definition: DeclObjC.h:428
void getFunctionFeatureMap(llvm::StringMap< bool > &FeatureMap, const FunctionDecl *) const
virtual LangAS getCUDABuiltinAddressSpace(unsigned AS) const
Map from the address space field in builtin description strings to the language address space...
Definition: TargetInfo.h:1251
TypedefDecl * getObjCClassDecl() const
Retrieve the typedef declaration corresponding to the predefined Objective-C &#39;Class&#39; type...
QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error, unsigned *IntegerConstantArgs=nullptr) const
Return the type for the specified builtin.
param_const_iterator sel_param_end() const
Definition: DeclObjC.h:362
__DEVICE__ int min(int __a, int __b)
QualType getInjectedClassNameType(CXXRecordDecl *Decl, QualType TST) const
getInjectedClassNameType - Return the unique reference to the injected class name type for the specif...
static TypedefDecl * CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context)
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1711
Defines the clang::TargetInfo interface.
bool hasSameFunctionTypeIgnoringExceptionSpec(QualType T, QualType U)
Determine whether two function types are the same, ignoring exception specifications in cases where t...
unsigned getSimdDefaultAlign() const
Return default simd alignment for the given target.
Definition: TargetInfo.h:643
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:160
static const Decl & adjustDeclToTemplate(const Decl &D)
If we have a &#39;templated&#39; declaration for a template, adjust &#39;D&#39; to refer to the actual template...
Definition: ASTContext.cpp:327
unsigned CountNonClassIvars(const ObjCInterfaceDecl *OI) const
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition: Decl.h:3635
void setRAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:1600
unsigned getCVRQualifiers() const
Definition: Type.h:276
Qualifiers::ObjCLifetime getInnerObjCOwnership(QualType T) const
Recurses in pointer/array types until it finds an Objective-C retainable type and returns its ownersh...
SourceLocation getLAngleLoc() const
Definition: TemplateBase.h:570
void adjustExceptionSpec(FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI, bool AsWritten=false)
Change the exception specification on a function once it is delay-parsed, instantiated, or computed.
bool isDocumentation() const LLVM_READONLY
Returns true if this comment any kind of a documentation comment.
const VariableArrayType * getAsVariableArrayType(QualType T) const
Definition: ASTContext.h:2469
uint64_t Width
Definition: ASTContext.h:157
static bool sameObjCTypeArgs(ASTContext &ctx, const ObjCInterfaceDecl *iface, ArrayRef< QualType > lhsArgs, ArrayRef< QualType > rhsArgs, bool stripKindOf)
QualType getjmp_bufType() const
Retrieve the C jmp_buf type.
Definition: ASTContext.h:1779
NameKind getKind() const
static Decl::Kind getKind(const Decl *D)
Definition: DeclBase.cpp:947
CanQualType IntTy
Definition: ASTContext.h:1025
QualType getSignedWCharType() const
Return the type of "signed wchar_t".
unsigned getNumElements() const
Definition: Type.h:3271
decl_type * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
Definition: Redeclarable.h:225
static bool NeedsInjectedClassNameType(const RecordDecl *D)
uint64_t getTargetNullPointerValue(QualType QT) const
Get target-dependent integer value for null pointer which is used for constant folding.
QualType getRealTypeForBitwidth(unsigned DestWidth) const
getRealTypeForBitwidth - sets floating point QualTy according to specified bitwidth.
Microsoft __declspec(nothrow) extension.
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2150
QualType getAsType() const
Retrieve the type for a type template argument.
Definition: TemplateBase.h:256
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1171
QualType getIntPtrType() const
Return a type compatible with "intptr_t" (C99 7.18.1.4), as defined by the target.
Represents an extended address space qualifier where the input address space value is dependent...
Definition: Type.h:3153
bool isUnion() const
Definition: Decl.h:3407
Represents a type template specialization; the template must be a class template, a type alias templa...
Definition: Type.h:4996
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:4123
ObjCTypeParamVariance getVariance() const
Determine the variance of this type parameter.
Definition: DeclObjC.h:614
GVALinkage
A more specific kind of linkage than enum Linkage.
Definition: Linkage.h:73
A lazy value (of type T) that is within an AST node of type Owner, where the value might change in la...
bool isPointerType() const
Definition: Type.h:6504
QualType mergeFunctionParameterTypes(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false)
mergeFunctionParameterTypes - merge two types which appear as function parameter types ...
const DeclInfo * getDeclInfo() const LLVM_READONLY
Definition: Comment.h:1125
void addAddressSpace(LangAS space)
Definition: Type.h:385
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
StringRef Text
Definition: Format.cpp:1826
llvm::DenseMap< const Decl *, const Decl * > CommentlessRedeclChains
Keeps track of redeclaration chains that don&#39;t have any comment attached.
Definition: ASTContext.h:766
QualType getDependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, const IdentifierInfo *Name, const TemplateArgumentListInfo &Args) const
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition: Decl.h:1144
We can encode up to four bits in the low bits of a type pointer, but there are many more type qualifi...
Definition: Type.h:1338
QualType getType() const
Definition: Decl.h:630
TemplateArgument getArgumentPack() const
Retrieve the template template argument pack with which this parameter was substituted.
A set of overloaded template declarations.
Definition: TemplateName.h:207
A trivial tuple used to represent a source range.
This represents a decl that may have a name.
Definition: Decl.h:223
ArrayRef< BlockContentComment * > getBlocks() const
Definition: Comment.h:1131
QualType getObjCObjectPointerType(QualType OIT) const
Return a ObjCObjectPointerType type for the given ObjCObjectType.
A simple holder for a QualType representing a type in an exception specification. ...
Definition: Type.h:3650
T castAs() const
Convert to the specified TypeLoc type, asserting that this TypeLoc is of the desired type...
Definition: TypeLoc.h:77
void setAccess(AccessSpecifier AS)
Definition: DeclBase.h:468
unsigned NumImplicitMoveConstructorsDeclared
The number of implicitly-declared move constructors for which declarations were built.
Definition: ASTContext.h:2883
Represents a C array with a specified size that is not an integer-constant-expression.
Definition: Type.h:3039
CanQualType BoolTy
Definition: ASTContext.h:1017
void setTemplateNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:1624
void addOverriddenMethod(const CXXMethodDecl *Method, const CXXMethodDecl *Overridden)
Note that the given C++ Method overrides the given Overridden method.
bool DeclMustBeEmitted(const Decl *D)
Determines if the decl can be CodeGen&#39;ed or deserialized from PCH lazily, only when used; this is onl...
const CXXConstructorDecl * getCopyConstructorForExceptionObject(CXXRecordDecl *RD)
No keyword precedes the qualified type name.
Definition: Type.h:5227
QualType getVariableArrayType(QualType EltTy, Expr *NumElts, ArrayType::ArraySizeModifier ASM, unsigned IndexTypeQuals, SourceRange Brackets) const
Return a non-unique reference to the type for a variable array of the specified element type...
FloatingRank
Definition: ASTContext.cpp:99
bool isInline() const
Whether this variable is (C++1z) inline.
Definition: Decl.h:1394
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:6145
CanQualType getIntMaxType() const
Return the unique type for "intmax_t" (C99 7.18.1.5), defined in <stdint.h>.
TemplateName getAsTemplate() const
Retrieve the template name for a template name argument.
Definition: TemplateBase.h:280
unsigned NumImplicitCopyAssignmentOperators
The number of implicitly-declared copy assignment operators.
Definition: ASTContext.h:2886
unsigned getTargetAddressSpace(QualType T) const
Definition: ASTContext.h:2557
CanQualType DoubleTy
Definition: ASTContext.h:1028
Selector getGetterName() const
Definition: DeclObjC.h:920
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:5473
static bool isObjCNSObjectType(QualType Ty)
Return true if this is an NSObject object with its NSObject attribute set.
Definition: ASTContext.h:2084
SourceLocation getRAngleLoc() const
Definition: TemplateBase.h:571
static FieldDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable, InClassInitStyle InitStyle)
Definition: Decl.cpp:4006
void addedLocalImportDecl(ImportDecl *Import)
Notify the AST context that a new import declaration has been parsed or implicitly created within thi...
QualType getFunctionTypeWithoutPtrSizes(QualType T)
Get a function type and produce the equivalent function type where pointer size address spaces in the...
virtual uint64_t getNullPointerValue(LangAS AddrSpace) const
Get integer value for null pointer.
Definition: TargetInfo.h:375
The global specifier &#39;::&#39;. There is no stored value.
static bool isStructEmpty(QualType Ty)
NestedNameSpecifier * getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const
Retrieves the "canonical" nested name specifier for a given nested name specifier.
TemplateName getAsTemplateOrTemplatePattern() const
Retrieve the template argument as a template name; if the argument is a pack expansion, return the pattern as a template name.
Definition: TemplateBase.h:287
Missing a type from <setjmp.h>
Definition: ASTContext.h:2039
void setType(QualType newType)
Definition: Decl.h:631
void removeAddressSpace()
Definition: Type.h:384
This file provides AST data structures related to concepts.
bool hasInit() const
Definition: Decl.cpp:2226
QualType getReadPipeType(QualType T) const
Return a read_only pipe type for the specified type.
const LangOptions & getLangOpts() const
Definition: ASTContext.h:724
ObjCCategoryImplDecl - An object of this class encapsulates a category @implementation declaration...
Definition: DeclObjC.h:2513
No in-class initializer.
Definition: Specifiers.h:259
QualType getAutoType(QualType DeducedType, AutoTypeKeyword Keyword, bool IsDependent, bool IsPack=false, ConceptDecl *TypeConstraintConcept=nullptr, ArrayRef< TemplateArgument > TypeConstraintArgs={}) const
C++11 deduced auto type.
bool AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:2935
This class handles loading and caching of source files into memory.
The parameter is invariant: must match exactly.
ExceptionSpecInfo ExceptionSpec
Definition: Type.h:3843
QualType isPromotableBitField(Expr *E) const
Whether this is a promotable bitfield reference according to C99 6.3.1.1p2, bullet 2 (and GCC extensi...
Defines enum values for all the target-independent builtin functions.
QualType getAdjustedType(QualType Orig, QualType New) const
Return the uniqued reference to a type adjusted from the original type to a new type.
Declaration of a template function.
Definition: DeclTemplate.h:977
const void * getMemoizationData() const
Returns a pointer that identifies the stored AST node.
A class which abstracts out some details necessary for making a call.
Definition: Type.h:3533
QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals)
Return this type as a completely-unqualified array type, capturing the qualifiers in Quals...
TemplateName getQualifiedTemplateName(NestedNameSpecifier *NNS, bool TemplateKeyword, TemplateDecl *Template) const
Retrieve the template name that represents a qualified template name such as std::vector.
bool BlockRequiresCopying(QualType Ty, const VarDecl *D)
Returns true iff we need copy/dispose helpers for the given type.
Attr - This represents one attribute.
Definition: Attr.h:45
InlineVariableDefinitionKind getInlineVariableDefinitionKind(const VarDecl *VD) const
Determine whether a definition of this inline variable should be treated as a weak or strong definiti...
SourceLocation getLocation() const
Definition: DeclBase.h:429
QualType getPointeeType() const
Definition: Type.h:2853
const RawComment * getRawCommentForAnyRedecl(const Decl *D, const Decl **OriginalDecl=nullptr) const
Return the documentation comment attached to a given declaration.
Definition: ASTContext.cpp:394
Represents a shadow declaration introduced into a scope by a (resolved) using declaration.
Definition: DeclCXX.h:3162
bool isExternallyVisible() const
Definition: Decl.h:362
A full comment attached to a declaration, contains block content.
Definition: Comment.h:1093
A single template declaration.
Definition: TemplateName.h:204
CanQualType OCLClkEventTy
Definition: ASTContext.h:1053
bool getByrefLifetime(QualType Ty, Qualifiers::ObjCLifetime &Lifetime, bool &HasByrefExtendedLayout) const
Returns true, if given type has a known lifetime.
std::pair< FileID, unsigned > getDecomposedLoc(SourceLocation Loc) const
Decompose the specified location into a raw FileID + Offset pair.
noexcept(expression), evals to &#39;true&#39;
QualType getComplexType(QualType T) const
Return the uniqued reference to the type for a complex number with the specified element type...
QualType getIntTypeForBitwidth(unsigned DestWidth, unsigned Signed) const
getIntTypeForBitwidth - sets integer QualTy according to specified details: bitwidth, signed/unsigned.
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Definition: Preprocessor.h:128
CanQualType UnsignedIntTy
Definition: ASTContext.h:1026
QualType getIncompleteArrayType(QualType EltTy, ArrayType::ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return a unique reference to the type for an incomplete array of the specified element type...
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
bool ParseAllComments
Treat ordinary comments as documentation comments.
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1080
BuiltinTemplateDecl * getMakeIntegerSeqDecl() const
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition: Type.h:5967
ComparisonCategories CompCategories
Types and expressions required to build C++2a three-way comparisons using operator<=>, including the values return by builtin <=> operators.
Definition: ASTContext.h:2055