clang  9.0.0
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 "clang/AST/APValue.h"
18 #include "clang/AST/Attr.h"
19 #include "clang/AST/AttrIterator.h"
20 #include "clang/AST/CharUnits.h"
21 #include "clang/AST/Comment.h"
22 #include "clang/AST/Decl.h"
23 #include "clang/AST/DeclBase.h"
24 #include "clang/AST/DeclCXX.h"
26 #include "clang/AST/DeclObjC.h"
27 #include "clang/AST/DeclOpenMP.h"
28 #include "clang/AST/DeclTemplate.h"
30 #include "clang/AST/Expr.h"
31 #include "clang/AST/ExprCXX.h"
33 #include "clang/AST/Mangle.h"
37 #include "clang/AST/RecordLayout.h"
39 #include "clang/AST/Stmt.h"
40 #include "clang/AST/TemplateBase.h"
41 #include "clang/AST/TemplateName.h"
42 #include "clang/AST/Type.h"
43 #include "clang/AST/TypeLoc.h"
47 #include "clang/Basic/Builtins.h"
50 #include "clang/Basic/FixedPoint.h"
52 #include "clang/Basic/LLVM.h"
54 #include "clang/Basic/Linkage.h"
59 #include "clang/Basic/Specifiers.h"
61 #include "clang/Basic/TargetInfo.h"
62 #include "clang/Basic/XRayLists.h"
63 #include "llvm/ADT/APInt.h"
64 #include "llvm/ADT/APSInt.h"
65 #include "llvm/ADT/ArrayRef.h"
66 #include "llvm/ADT/DenseMap.h"
67 #include "llvm/ADT/DenseSet.h"
68 #include "llvm/ADT/FoldingSet.h"
69 #include "llvm/ADT/None.h"
70 #include "llvm/ADT/Optional.h"
71 #include "llvm/ADT/PointerUnion.h"
72 #include "llvm/ADT/STLExtras.h"
73 #include "llvm/ADT/SmallPtrSet.h"
74 #include "llvm/ADT/SmallVector.h"
75 #include "llvm/ADT/StringExtras.h"
76 #include "llvm/ADT/StringRef.h"
77 #include "llvm/ADT/Triple.h"
78 #include "llvm/Support/Capacity.h"
79 #include "llvm/Support/Casting.h"
80 #include "llvm/Support/Compiler.h"
81 #include "llvm/Support/ErrorHandling.h"
82 #include "llvm/Support/MathExtras.h"
83 #include "llvm/Support/raw_ostream.h"
84 #include <algorithm>
85 #include <cassert>
86 #include <cstddef>
87 #include <cstdint>
88 #include <cstdlib>
89 #include <map>
90 #include <memory>
91 #include <string>
92 #include <tuple>
93 #include <utility>
94 
95 using namespace clang;
96 
99 };
100 
102  assert(D);
103 
104  // If we already tried to load comments but there are none,
105  // we won't find anything.
106  if (CommentsLoaded && Comments.getComments().empty())
107  return nullptr;
108 
109  // User can not attach documentation to implicit declarations.
110  if (D->isImplicit())
111  return nullptr;
112 
113  // User can not attach documentation to implicit instantiations.
114  if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
115  if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
116  return nullptr;
117  }
118 
119  if (const auto *VD = dyn_cast<VarDecl>(D)) {
120  if (VD->isStaticDataMember() &&
121  VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
122  return nullptr;
123  }
124 
125  if (const auto *CRD = dyn_cast<CXXRecordDecl>(D)) {
126  if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
127  return nullptr;
128  }
129 
130  if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
131  TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
132  if (TSK == TSK_ImplicitInstantiation ||
133  TSK == TSK_Undeclared)
134  return nullptr;
135  }
136 
137  if (const auto *ED = dyn_cast<EnumDecl>(D)) {
138  if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
139  return nullptr;
140  }
141  if (const auto *TD = dyn_cast<TagDecl>(D)) {
142  // When tag declaration (but not definition!) is part of the
143  // decl-specifier-seq of some other declaration, it doesn't get comment
144  if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
145  return nullptr;
146  }
147  // TODO: handle comments for function parameters properly.
148  if (isa<ParmVarDecl>(D))
149  return nullptr;
150 
151  // TODO: we could look up template parameter documentation in the template
152  // documentation.
153  if (isa<TemplateTypeParmDecl>(D) ||
154  isa<NonTypeTemplateParmDecl>(D) ||
155  isa<TemplateTemplateParmDecl>(D))
156  return nullptr;
157 
158  // Find declaration location.
159  // For Objective-C declarations we generally don't expect to have multiple
160  // declarators, thus use declaration starting location as the "declaration
161  // location".
162  // For all other declarations multiple declarators are used quite frequently,
163  // so we use the location of the identifier as the "declaration location".
164  SourceLocation DeclLoc;
165  if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
166  isa<ObjCPropertyDecl>(D) ||
167  isa<RedeclarableTemplateDecl>(D) ||
168  isa<ClassTemplateSpecializationDecl>(D))
169  DeclLoc = D->getBeginLoc();
170  else {
171  DeclLoc = D->getLocation();
172  if (DeclLoc.isMacroID()) {
173  if (isa<TypedefDecl>(D)) {
174  // If location of the typedef name is in a macro, it is because being
175  // declared via a macro. Try using declaration's starting location as
176  // the "declaration location".
177  DeclLoc = D->getBeginLoc();
178  } else if (const auto *TD = dyn_cast<TagDecl>(D)) {
179  // If location of the tag decl is inside a macro, but the spelling of
180  // the tag name comes from a macro argument, it looks like a special
181  // macro like NS_ENUM is being used to define the tag decl. In that
182  // case, adjust the source location to the expansion loc so that we can
183  // attach the comment to the tag decl.
184  if (SourceMgr.isMacroArgExpansion(DeclLoc) &&
185  TD->isCompleteDefinition())
186  DeclLoc = SourceMgr.getExpansionLoc(DeclLoc);
187  }
188  }
189  }
190 
191  // If the declaration doesn't map directly to a location in a file, we
192  // can't find the comment.
193  if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
194  return nullptr;
195 
196  if (!CommentsLoaded && ExternalSource) {
197  ExternalSource->ReadComments();
198 
199 #ifndef NDEBUG
201  assert(std::is_sorted(RawComments.begin(), RawComments.end(),
202  BeforeThanCompare<RawComment>(SourceMgr)));
203 #endif
204 
205  CommentsLoaded = true;
206  }
207 
209  // If there are no comments anywhere, we won't find anything.
210  if (RawComments.empty())
211  return nullptr;
212 
213  // Find the comment that occurs just after this declaration.
215  {
216  // When searching for comments during parsing, the comment we are looking
217  // for is usually among the last two comments we parsed -- check them
218  // first.
219  RawComment CommentAtDeclLoc(
220  SourceMgr, SourceRange(DeclLoc), LangOpts.CommentOpts, false);
221  BeforeThanCompare<RawComment> Compare(SourceMgr);
222  ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1;
223  bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
224  if (!Found && RawComments.size() >= 2) {
225  MaybeBeforeDecl--;
226  Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
227  }
228 
229  if (Found) {
230  Comment = MaybeBeforeDecl + 1;
231  assert(Comment ==
232  llvm::lower_bound(RawComments, &CommentAtDeclLoc, Compare));
233  } else {
234  // Slow path.
235  Comment = llvm::lower_bound(RawComments, &CommentAtDeclLoc, Compare);
236  }
237  }
238 
239  // Decompose the location for the declaration and find the beginning of the
240  // file buffer.
241  std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
242 
243  // First check whether we have a trailing comment.
244  if (Comment != RawComments.end() &&
245  ((*Comment)->isDocumentation() || LangOpts.CommentOpts.ParseAllComments)
246  && (*Comment)->isTrailingComment() &&
247  (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
248  isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
249  std::pair<FileID, unsigned> CommentBeginDecomp
250  = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
251  // Check that Doxygen trailing comment comes after the declaration, starts
252  // on the same line and in the same file as the declaration.
253  if (DeclLocDecomp.first == CommentBeginDecomp.first &&
254  SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
255  == SourceMgr.getLineNumber(CommentBeginDecomp.first,
256  CommentBeginDecomp.second)) {
257  (**Comment).setAttached();
258  return *Comment;
259  }
260  }
261 
262  // The comment just after the declaration was not a trailing comment.
263  // Let's look at the previous comment.
264  if (Comment == RawComments.begin())
265  return nullptr;
266  --Comment;
267 
268  // Check that we actually have a non-member Doxygen comment.
269  if (!((*Comment)->isDocumentation() ||
270  LangOpts.CommentOpts.ParseAllComments) ||
271  (*Comment)->isTrailingComment())
272  return nullptr;
273 
274  // Decompose the end of the comment.
275  std::pair<FileID, unsigned> CommentEndDecomp
276  = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
277 
278  // If the comment and the declaration aren't in the same file, then they
279  // aren't related.
280  if (DeclLocDecomp.first != CommentEndDecomp.first)
281  return nullptr;
282 
283  // Get the corresponding buffer.
284  bool Invalid = false;
285  const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
286  &Invalid).data();
287  if (Invalid)
288  return nullptr;
289 
290  // Extract text between the comment and declaration.
291  StringRef Text(Buffer + CommentEndDecomp.second,
292  DeclLocDecomp.second - CommentEndDecomp.second);
293 
294  // There should be no other declarations or preprocessor directives between
295  // comment and declaration.
296  if (Text.find_first_of(";{}#@") != StringRef::npos)
297  return nullptr;
298 
299  (**Comment).setAttached();
300  return *Comment;
301 }
302 
303 /// If we have a 'templated' declaration for a template, adjust 'D' to
304 /// refer to the actual template.
305 /// If we have an implicit instantiation, adjust 'D' to refer to template.
306 static const Decl *adjustDeclToTemplate(const Decl *D) {
307  if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
308  // Is this function declaration part of a function template?
309  if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
310  return FTD;
311 
312  // Nothing to do if function is not an implicit instantiation.
313  if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
314  return D;
315 
316  // Function is an implicit instantiation of a function template?
317  if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
318  return FTD;
319 
320  // Function is instantiated from a member definition of a class template?
321  if (const FunctionDecl *MemberDecl =
323  return MemberDecl;
324 
325  return D;
326  }
327  if (const auto *VD = dyn_cast<VarDecl>(D)) {
328  // Static data member is instantiated from a member definition of a class
329  // template?
330  if (VD->isStaticDataMember())
331  if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
332  return MemberDecl;
333 
334  return D;
335  }
336  if (const auto *CRD = dyn_cast<CXXRecordDecl>(D)) {
337  // Is this class declaration part of a class template?
338  if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
339  return CTD;
340 
341  // Class is an implicit instantiation of a class template or partial
342  // specialization?
343  if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
344  if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
345  return D;
346  llvm::PointerUnion<ClassTemplateDecl *,
348  PU = CTSD->getSpecializedTemplateOrPartial();
349  return PU.is<ClassTemplateDecl*>() ?
350  static_cast<const Decl*>(PU.get<ClassTemplateDecl *>()) :
351  static_cast<const Decl*>(
353  }
354 
355  // Class is instantiated from a member definition of a class template?
356  if (const MemberSpecializationInfo *Info =
357  CRD->getMemberSpecializationInfo())
358  return Info->getInstantiatedFrom();
359 
360  return D;
361  }
362  if (const auto *ED = dyn_cast<EnumDecl>(D)) {
363  // Enum is instantiated from a member definition of a class template?
364  if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
365  return MemberDecl;
366 
367  return D;
368  }
369  // FIXME: Adjust alias templates?
370  return D;
371 }
372 
374  const Decl *D,
375  const Decl **OriginalDecl) const {
376  D = adjustDeclToTemplate(D);
377 
378  // Check whether we have cached a comment for this declaration already.
379  {
380  llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
381  RedeclComments.find(D);
382  if (Pos != RedeclComments.end()) {
383  const RawCommentAndCacheFlags &Raw = Pos->second;
385  if (OriginalDecl)
386  *OriginalDecl = Raw.getOriginalDecl();
387  return Raw.getRaw();
388  }
389  }
390  }
391 
392  // Search for comments attached to declarations in the redeclaration chain.
393  const RawComment *RC = nullptr;
394  const Decl *OriginalDeclForRC = nullptr;
395  for (auto I : D->redecls()) {
396  llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
397  RedeclComments.find(I);
398  if (Pos != RedeclComments.end()) {
399  const RawCommentAndCacheFlags &Raw = Pos->second;
401  RC = Raw.getRaw();
402  OriginalDeclForRC = Raw.getOriginalDecl();
403  break;
404  }
405  } else {
407  OriginalDeclForRC = I;
409  if (RC) {
410  // Call order swapped to work around ICE in VS2015 RTM (Release Win32)
411  // https://connect.microsoft.com/VisualStudio/feedback/details/1741530
413  Raw.setRaw(RC);
414  } else
416  Raw.setOriginalDecl(I);
417  RedeclComments[I] = Raw;
418  if (RC)
419  break;
420  }
421  }
422 
423  // If we found a comment, it should be a documentation comment.
424  assert(!RC || RC->isDocumentation() || LangOpts.CommentOpts.ParseAllComments);
425 
426  if (OriginalDecl)
427  *OriginalDecl = OriginalDeclForRC;
428 
429  // Update cache for every declaration in the redeclaration chain.
431  Raw.setRaw(RC);
433  Raw.setOriginalDecl(OriginalDeclForRC);
434 
435  for (auto I : D->redecls()) {
438  R = Raw;
439  }
440 
441  return RC;
442 }
443 
444 static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
446  const DeclContext *DC = ObjCMethod->getDeclContext();
447  if (const auto *IMD = dyn_cast<ObjCImplDecl>(DC)) {
448  const ObjCInterfaceDecl *ID = IMD->getClassInterface();
449  if (!ID)
450  return;
451  // Add redeclared method here.
452  for (const auto *Ext : ID->known_extensions()) {
453  if (ObjCMethodDecl *RedeclaredMethod =
454  Ext->getMethod(ObjCMethod->getSelector(),
455  ObjCMethod->isInstanceMethod()))
456  Redeclared.push_back(RedeclaredMethod);
457  }
458  }
459 }
460 
462  const Decl *D) const {
463  auto *ThisDeclInfo = new (*this) comments::DeclInfo;
464  ThisDeclInfo->CommentDecl = D;
465  ThisDeclInfo->IsFilled = false;
466  ThisDeclInfo->fill();
467  ThisDeclInfo->CommentDecl = FC->getDecl();
468  if (!ThisDeclInfo->TemplateParameters)
469  ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
470  comments::FullComment *CFC =
471  new (*this) comments::FullComment(FC->getBlocks(),
472  ThisDeclInfo);
473  return CFC;
474 }
475 
478  return RC ? RC->parse(*this, nullptr, D) : nullptr;
479 }
480 
482  const Decl *D,
483  const Preprocessor *PP) const {
484  if (D->isInvalidDecl())
485  return nullptr;
486  D = adjustDeclToTemplate(D);
487 
488  const Decl *Canonical = D->getCanonicalDecl();
489  llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
490  ParsedComments.find(Canonical);
491 
492  if (Pos != ParsedComments.end()) {
493  if (Canonical != D) {
494  comments::FullComment *FC = Pos->second;
496  return CFC;
497  }
498  return Pos->second;
499  }
500 
501  const Decl *OriginalDecl;
502 
503  const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
504  if (!RC) {
505  if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
507  const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
508  if (OMD && OMD->isPropertyAccessor())
509  if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
510  if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
511  return cloneFullComment(FC, D);
512  if (OMD)
513  addRedeclaredMethods(OMD, Overridden);
514  getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
515  for (unsigned i = 0, e = Overridden.size(); i < e; i++)
516  if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
517  return cloneFullComment(FC, D);
518  }
519  else if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
520  // Attach any tag type's documentation to its typedef if latter
521  // does not have one of its own.
522  QualType QT = TD->getUnderlyingType();
523  if (const auto *TT = QT->getAs<TagType>())
524  if (const Decl *TD = TT->getDecl())
525  if (comments::FullComment *FC = getCommentForDecl(TD, PP))
526  return cloneFullComment(FC, D);
527  }
528  else if (const auto *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
529  while (IC->getSuperClass()) {
530  IC = IC->getSuperClass();
531  if (comments::FullComment *FC = getCommentForDecl(IC, PP))
532  return cloneFullComment(FC, D);
533  }
534  }
535  else if (const auto *CD = dyn_cast<ObjCCategoryDecl>(D)) {
536  if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
537  if (comments::FullComment *FC = getCommentForDecl(IC, PP))
538  return cloneFullComment(FC, D);
539  }
540  else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
541  if (!(RD = RD->getDefinition()))
542  return nullptr;
543  // Check non-virtual bases.
544  for (const auto &I : RD->bases()) {
545  if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
546  continue;
547  QualType Ty = I.getType();
548  if (Ty.isNull())
549  continue;
550  if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
551  if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
552  continue;
553 
554  if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
555  return cloneFullComment(FC, D);
556  }
557  }
558  // Check virtual bases.
559  for (const auto &I : RD->vbases()) {
560  if (I.getAccessSpecifier() != AS_public)
561  continue;
562  QualType Ty = I.getType();
563  if (Ty.isNull())
564  continue;
565  if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
566  if (!(VirtualBase= VirtualBase->getDefinition()))
567  continue;
568  if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
569  return cloneFullComment(FC, D);
570  }
571  }
572  }
573  return nullptr;
574  }
575 
576  // If the RawComment was attached to other redeclaration of this Decl, we
577  // should parse the comment in context of that other Decl. This is important
578  // because comments can contain references to parameter names which can be
579  // different across redeclarations.
580  if (D != OriginalDecl)
581  return getCommentForDecl(OriginalDecl, PP);
582 
583  comments::FullComment *FC = RC->parse(*this, PP, D);
584  ParsedComments[Canonical] = FC;
585  return FC;
586 }
587 
588 void
589 ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
590  TemplateTemplateParmDecl *Parm) {
591  ID.AddInteger(Parm->getDepth());
592  ID.AddInteger(Parm->getPosition());
593  ID.AddBoolean(Parm->isParameterPack());
594 
596  ID.AddInteger(Params->size());
598  PEnd = Params->end();
599  P != PEnd; ++P) {
600  if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
601  ID.AddInteger(0);
602  ID.AddBoolean(TTP->isParameterPack());
603  continue;
604  }
605 
606  if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
607  ID.AddInteger(1);
608  ID.AddBoolean(NTTP->isParameterPack());
609  ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
610  if (NTTP->isExpandedParameterPack()) {
611  ID.AddBoolean(true);
612  ID.AddInteger(NTTP->getNumExpansionTypes());
613  for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
614  QualType T = NTTP->getExpansionType(I);
615  ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
616  }
617  } else
618  ID.AddBoolean(false);
619  continue;
620  }
621 
622  auto *TTP = cast<TemplateTemplateParmDecl>(*P);
623  ID.AddInteger(2);
624  Profile(ID, TTP);
625  }
626 }
627 
629 ASTContext::getCanonicalTemplateTemplateParmDecl(
630  TemplateTemplateParmDecl *TTP) const {
631  // Check if we already have a canonical template template parameter.
632  llvm::FoldingSetNodeID ID;
633  CanonicalTemplateTemplateParm::Profile(ID, TTP);
634  void *InsertPos = nullptr;
635  CanonicalTemplateTemplateParm *Canonical
636  = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
637  if (Canonical)
638  return Canonical->getParam();
639 
640  // Build a canonical template parameter list.
642  SmallVector<NamedDecl *, 4> CanonParams;
643  CanonParams.reserve(Params->size());
645  PEnd = Params->end();
646  P != PEnd; ++P) {
647  if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
648  CanonParams.push_back(
650  SourceLocation(),
651  SourceLocation(),
652  TTP->getDepth(),
653  TTP->getIndex(), nullptr, false,
654  TTP->isParameterPack()));
655  else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
656  QualType T = getCanonicalType(NTTP->getType());
659  if (NTTP->isExpandedParameterPack()) {
660  SmallVector<QualType, 2> ExpandedTypes;
661  SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
662  for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
663  ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
664  ExpandedTInfos.push_back(
665  getTrivialTypeSourceInfo(ExpandedTypes.back()));
666  }
667 
669  SourceLocation(),
670  SourceLocation(),
671  NTTP->getDepth(),
672  NTTP->getPosition(), nullptr,
673  T,
674  TInfo,
675  ExpandedTypes,
676  ExpandedTInfos);
677  } else {
679  SourceLocation(),
680  SourceLocation(),
681  NTTP->getDepth(),
682  NTTP->getPosition(), nullptr,
683  T,
684  NTTP->isParameterPack(),
685  TInfo);
686  }
687  CanonParams.push_back(Param);
688 
689  } else
690  CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
691  cast<TemplateTemplateParmDecl>(*P)));
692  }
693 
694  assert(!TTP->getRequiresClause() &&
695  "Unexpected requires-clause on template template-parameter");
696  Expr *const CanonRequiresClause = nullptr;
697 
698  TemplateTemplateParmDecl *CanonTTP
700  SourceLocation(), TTP->getDepth(),
701  TTP->getPosition(),
702  TTP->isParameterPack(),
703  nullptr,
705  SourceLocation(),
706  CanonParams,
707  SourceLocation(),
708  CanonRequiresClause));
709 
710  // Get the new insert position for the node we care about.
711  Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
712  assert(!Canonical && "Shouldn't be in the map!");
713  (void)Canonical;
714 
715  // Create the canonical template template parameter entry.
716  Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
717  CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
718  return CanonTTP;
719 }
720 
721 CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
722  if (!LangOpts.CPlusPlus) return nullptr;
723 
724  switch (T.getCXXABI().getKind()) {
725  case TargetCXXABI::GenericARM: // Same as Itanium at this level
726  case TargetCXXABI::iOS:
727  case TargetCXXABI::iOS64:
733  return CreateItaniumCXXABI(*this);
735  return CreateMicrosoftCXXABI(*this);
736  }
737  llvm_unreachable("Invalid CXXABI type!");
738 }
739 
740 static const LangASMap *getAddressSpaceMap(const TargetInfo &T,
741  const LangOptions &LOpts) {
742  if (LOpts.FakeAddressSpaceMap) {
743  // The fake address space map must have a distinct entry for each
744  // language-specific address space.
745  static const unsigned FakeAddrSpaceMap[] = {
746  0, // Default
747  1, // opencl_global
748  3, // opencl_local
749  2, // opencl_constant
750  0, // opencl_private
751  4, // opencl_generic
752  5, // cuda_device
753  6, // cuda_constant
754  7 // cuda_shared
755  };
756  return &FakeAddrSpaceMap;
757  } else {
758  return &T.getAddressSpaceMap();
759  }
760 }
761 
763  const LangOptions &LangOpts) {
764  switch (LangOpts.getAddressSpaceMapMangling()) {
766  return TI.useAddressSpaceMapMangling();
768  return true;
770  return false;
771  }
772  llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
773 }
774 
776  IdentifierTable &idents, SelectorTable &sels,
777  Builtin::Context &builtins)
778  : FunctionProtoTypes(this_()), TemplateSpecializationTypes(this_()),
779  DependentTemplateSpecializationTypes(this_()),
780  SubstTemplateTemplateParmPacks(this_()), SourceMgr(SM), LangOpts(LOpts),
781  SanitizerBL(new SanitizerBlacklist(LangOpts.SanitizerBlacklistFiles, SM)),
782  XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles,
783  LangOpts.XRayNeverInstrumentFiles,
784  LangOpts.XRayAttrListFiles, SM)),
785  PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
786  BuiltinInfo(builtins), DeclarationNames(*this), Comments(SM),
787  CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
788  CompCategories(this_()), LastSDM(nullptr, 0) {
789  TUDecl = TranslationUnitDecl::Create(*this);
790  TraversalScope = {TUDecl};
791 }
792 
794  // Release the DenseMaps associated with DeclContext objects.
795  // FIXME: Is this the ideal solution?
796  ReleaseDeclContextMaps();
797 
798  // Call all of the deallocation functions on all of their targets.
799  for (auto &Pair : Deallocations)
800  (Pair.first)(Pair.second);
801 
802  // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
803  // because they can contain DenseMaps.
804  for (llvm::DenseMap<const ObjCContainerDecl*,
805  const ASTRecordLayout*>::iterator
806  I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
807  // Increment in loop to prevent using deallocated memory.
808  if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
809  R->Destroy(*this);
810 
811  for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
812  I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
813  // Increment in loop to prevent using deallocated memory.
814  if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
815  R->Destroy(*this);
816  }
817 
818  for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
819  AEnd = DeclAttrs.end();
820  A != AEnd; ++A)
821  A->second->~AttrVec();
822 
823  for (std::pair<const MaterializeTemporaryExpr *, APValue *> &MTVPair :
824  MaterializedTemporaryValues)
825  MTVPair.second->~APValue();
826 
827  for (const auto &Value : ModuleInitializers)
828  Value.second->~PerModuleInitializers();
829 
830  for (APValue *Value : APValueCleanups)
831  Value->~APValue();
832 }
833 
835  /// Contains parents of a node.
837 
838  /// Maps from a node to its parents. This is used for nodes that have
839  /// pointer identity only, which are more common and we can save space by
840  /// only storing a unique pointer to them.
841  using ParentMapPointers = llvm::DenseMap<
842  const void *,
843  llvm::PointerUnion4<const Decl *, const Stmt *,
845 
846  /// Parent map for nodes without pointer identity. We store a full
847  /// DynTypedNode for all keys.
848  using ParentMapOtherNodes = llvm::DenseMap<
850  llvm::PointerUnion4<const Decl *, const Stmt *,
851  ast_type_traits::DynTypedNode *, ParentVector *>>;
852 
853  ParentMapPointers PointerParents;
854  ParentMapOtherNodes OtherParents;
855  class ASTVisitor;
856 
857  static ast_type_traits::DynTypedNode
858  getSingleDynTypedNodeFromParentMap(ParentMapPointers::mapped_type U) {
859  if (const auto *D = U.dyn_cast<const Decl *>())
861  if (const auto *S = U.dyn_cast<const Stmt *>())
863  return *U.get<ast_type_traits::DynTypedNode *>();
864  }
865 
866  template <typename NodeTy, typename MapTy>
867  static ASTContext::DynTypedNodeList getDynNodeFromMap(const NodeTy &Node,
868  const MapTy &Map) {
869  auto I = Map.find(Node);
870  if (I == Map.end()) {
872  }
873  if (const auto *V = I->second.template dyn_cast<ParentVector *>()) {
874  return llvm::makeArrayRef(*V);
875  }
876  return getSingleDynTypedNodeFromParentMap(I->second);
877  }
878 
879 public:
880  ParentMap(ASTContext &Ctx);
882  for (const auto &Entry : PointerParents) {
883  if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
884  delete Entry.second.get<ast_type_traits::DynTypedNode *>();
885  } else if (Entry.second.is<ParentVector *>()) {
886  delete Entry.second.get<ParentVector *>();
887  }
888  }
889  for (const auto &Entry : OtherParents) {
890  if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
891  delete Entry.second.get<ast_type_traits::DynTypedNode *>();
892  } else if (Entry.second.is<ParentVector *>()) {
893  delete Entry.second.get<ParentVector *>();
894  }
895  }
896  }
897 
898  DynTypedNodeList getParents(const ast_type_traits::DynTypedNode &Node) {
899  if (Node.getNodeKind().hasPointerIdentity())
900  return getDynNodeFromMap(Node.getMemoizationData(), PointerParents);
901  return getDynNodeFromMap(Node, OtherParents);
902  }
903 };
904 
905 void ASTContext::setTraversalScope(const std::vector<Decl *> &TopLevelDecls) {
906  TraversalScope = TopLevelDecls;
907  Parents.reset();
908 }
909 
910 void ASTContext::AddDeallocation(void (*Callback)(void *), void *Data) const {
911  Deallocations.push_back({Callback, Data});
912 }
913 
914 void
916  ExternalSource = std::move(Source);
917 }
918 
920  llvm::errs() << "\n*** AST Context Stats:\n";
921  llvm::errs() << " " << Types.size() << " types total.\n";
922 
923  unsigned counts[] = {
924 #define TYPE(Name, Parent) 0,
925 #define ABSTRACT_TYPE(Name, Parent)
926 #include "clang/AST/TypeNodes.def"
927  0 // Extra
928  };
929 
930  for (unsigned i = 0, e = Types.size(); i != e; ++i) {
931  Type *T = Types[i];
932  counts[(unsigned)T->getTypeClass()]++;
933  }
934 
935  unsigned Idx = 0;
936  unsigned TotalBytes = 0;
937 #define TYPE(Name, Parent) \
938  if (counts[Idx]) \
939  llvm::errs() << " " << counts[Idx] << " " << #Name \
940  << " types, " << sizeof(Name##Type) << " each " \
941  << "(" << counts[Idx] * sizeof(Name##Type) \
942  << " bytes)\n"; \
943  TotalBytes += counts[Idx] * sizeof(Name##Type); \
944  ++Idx;
945 #define ABSTRACT_TYPE(Name, Parent)
946 #include "clang/AST/TypeNodes.def"
947 
948  llvm::errs() << "Total bytes = " << TotalBytes << "\n";
949 
950  // Implicit special member functions.
951  llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
953  << " implicit default constructors created\n";
954  llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
956  << " implicit copy constructors created\n";
957  if (getLangOpts().CPlusPlus)
958  llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
960  << " implicit move constructors created\n";
961  llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
963  << " implicit copy assignment operators created\n";
964  if (getLangOpts().CPlusPlus)
965  llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
967  << " implicit move assignment operators created\n";
968  llvm::errs() << NumImplicitDestructorsDeclared << "/"
970  << " implicit destructors created\n";
971 
972  if (ExternalSource) {
973  llvm::errs() << "\n";
974  ExternalSource->PrintStats();
975  }
976 
977  BumpAlloc.PrintStats();
978 }
979 
981  bool NotifyListeners) {
982  if (NotifyListeners)
983  if (auto *Listener = getASTMutationListener())
985 
986  MergedDefModules[cast<NamedDecl>(ND->getCanonicalDecl())].push_back(M);
987 }
988 
990  auto It = MergedDefModules.find(cast<NamedDecl>(ND->getCanonicalDecl()));
991  if (It == MergedDefModules.end())
992  return;
993 
994  auto &Merged = It->second;
996  for (Module *&M : Merged)
997  if (!Found.insert(M).second)
998  M = nullptr;
999  Merged.erase(std::remove(Merged.begin(), Merged.end(), nullptr), Merged.end());
1000 }
1001 
1002 void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
1003  if (LazyInitializers.empty())
1004  return;
1005 
1006  auto *Source = Ctx.getExternalSource();
1007  assert(Source && "lazy initializers but no external source");
1008 
1009  auto LazyInits = std::move(LazyInitializers);
1010  LazyInitializers.clear();
1011 
1012  for (auto ID : LazyInits)
1013  Initializers.push_back(Source->GetExternalDecl(ID));
1014 
1015  assert(LazyInitializers.empty() &&
1016  "GetExternalDecl for lazy module initializer added more inits");
1017 }
1018 
1020  // One special case: if we add a module initializer that imports another
1021  // module, and that module's only initializer is an ImportDecl, simplify.
1022  if (const auto *ID = dyn_cast<ImportDecl>(D)) {
1023  auto It = ModuleInitializers.find(ID->getImportedModule());
1024 
1025  // Maybe the ImportDecl does nothing at all. (Common case.)
1026  if (It == ModuleInitializers.end())
1027  return;
1028 
1029  // Maybe the ImportDecl only imports another ImportDecl.
1030  auto &Imported = *It->second;
1031  if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
1032  Imported.resolve(*this);
1033  auto *OnlyDecl = Imported.Initializers.front();
1034  if (isa<ImportDecl>(OnlyDecl))
1035  D = OnlyDecl;
1036  }
1037  }
1038 
1039  auto *&Inits = ModuleInitializers[M];
1040  if (!Inits)
1041  Inits = new (*this) PerModuleInitializers;
1042  Inits->Initializers.push_back(D);
1043 }
1044 
1046  auto *&Inits = ModuleInitializers[M];
1047  if (!Inits)
1048  Inits = new (*this) PerModuleInitializers;
1049  Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
1050  IDs.begin(), IDs.end());
1051 }
1052 
1054  auto It = ModuleInitializers.find(M);
1055  if (It == ModuleInitializers.end())
1056  return None;
1057 
1058  auto *Inits = It->second;
1059  Inits->resolve(*this);
1060  return Inits->Initializers;
1061 }
1062 
1064  if (!ExternCContext)
1065  ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
1066 
1067  return ExternCContext;
1068 }
1069 
1072  const IdentifierInfo *II) const {
1073  auto *BuiltinTemplate = BuiltinTemplateDecl::Create(*this, TUDecl, II, BTK);
1074  BuiltinTemplate->setImplicit();
1075  TUDecl->addDecl(BuiltinTemplate);
1076 
1077  return BuiltinTemplate;
1078 }
1079 
1082  if (!MakeIntegerSeqDecl)
1083  MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq,
1085  return MakeIntegerSeqDecl;
1086 }
1087 
1090  if (!TypePackElementDecl)
1091  TypePackElementDecl = buildBuiltinTemplateDecl(BTK__type_pack_element,
1093  return TypePackElementDecl;
1094 }
1095 
1097  RecordDecl::TagKind TK) const {
1098  SourceLocation Loc;
1099  RecordDecl *NewDecl;
1100  if (getLangOpts().CPlusPlus)
1101  NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
1102  Loc, &Idents.get(Name));
1103  else
1104  NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
1105  &Idents.get(Name));
1106  NewDecl->setImplicit();
1107  NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
1108  const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
1109  return NewDecl;
1110 }
1111 
1113  StringRef Name) const {
1115  TypedefDecl *NewDecl = TypedefDecl::Create(
1116  const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
1117  SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
1118  NewDecl->setImplicit();
1119  return NewDecl;
1120 }
1121 
1123  if (!Int128Decl)
1124  Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
1125  return Int128Decl;
1126 }
1127 
1129  if (!UInt128Decl)
1130  UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
1131  return UInt128Decl;
1132 }
1133 
1134 void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
1135  auto *Ty = new (*this, TypeAlignment) BuiltinType(K);
1136  R = CanQualType::CreateUnsafe(QualType(Ty, 0));
1137  Types.push_back(Ty);
1138 }
1139 
1141  const TargetInfo *AuxTarget) {
1142  assert((!this->Target || this->Target == &Target) &&
1143  "Incorrect target reinitialization");
1144  assert(VoidTy.isNull() && "Context reinitialized?");
1145 
1146  this->Target = &Target;
1147  this->AuxTarget = AuxTarget;
1148 
1149  ABI.reset(createCXXABI(Target));
1150  AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
1151  AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
1152 
1153  // C99 6.2.5p19.
1154  InitBuiltinType(VoidTy, BuiltinType::Void);
1155 
1156  // C99 6.2.5p2.
1157  InitBuiltinType(BoolTy, BuiltinType::Bool);
1158  // C99 6.2.5p3.
1159  if (LangOpts.CharIsSigned)
1160  InitBuiltinType(CharTy, BuiltinType::Char_S);
1161  else
1162  InitBuiltinType(CharTy, BuiltinType::Char_U);
1163  // C99 6.2.5p4.
1164  InitBuiltinType(SignedCharTy, BuiltinType::SChar);
1165  InitBuiltinType(ShortTy, BuiltinType::Short);
1166  InitBuiltinType(IntTy, BuiltinType::Int);
1167  InitBuiltinType(LongTy, BuiltinType::Long);
1168  InitBuiltinType(LongLongTy, BuiltinType::LongLong);
1169 
1170  // C99 6.2.5p6.
1171  InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
1172  InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
1173  InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
1174  InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
1175  InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
1176 
1177  // C99 6.2.5p10.
1178  InitBuiltinType(FloatTy, BuiltinType::Float);
1179  InitBuiltinType(DoubleTy, BuiltinType::Double);
1180  InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
1181 
1182  // GNU extension, __float128 for IEEE quadruple precision
1183  InitBuiltinType(Float128Ty, BuiltinType::Float128);
1184 
1185  // C11 extension ISO/IEC TS 18661-3
1186  InitBuiltinType(Float16Ty, BuiltinType::Float16);
1187 
1188  // ISO/IEC JTC1 SC22 WG14 N1169 Extension
1189  InitBuiltinType(ShortAccumTy, BuiltinType::ShortAccum);
1190  InitBuiltinType(AccumTy, BuiltinType::Accum);
1191  InitBuiltinType(LongAccumTy, BuiltinType::LongAccum);
1192  InitBuiltinType(UnsignedShortAccumTy, BuiltinType::UShortAccum);
1193  InitBuiltinType(UnsignedAccumTy, BuiltinType::UAccum);
1194  InitBuiltinType(UnsignedLongAccumTy, BuiltinType::ULongAccum);
1195  InitBuiltinType(ShortFractTy, BuiltinType::ShortFract);
1196  InitBuiltinType(FractTy, BuiltinType::Fract);
1197  InitBuiltinType(LongFractTy, BuiltinType::LongFract);
1198  InitBuiltinType(UnsignedShortFractTy, BuiltinType::UShortFract);
1199  InitBuiltinType(UnsignedFractTy, BuiltinType::UFract);
1200  InitBuiltinType(UnsignedLongFractTy, BuiltinType::ULongFract);
1201  InitBuiltinType(SatShortAccumTy, BuiltinType::SatShortAccum);
1202  InitBuiltinType(SatAccumTy, BuiltinType::SatAccum);
1203  InitBuiltinType(SatLongAccumTy, BuiltinType::SatLongAccum);
1204  InitBuiltinType(SatUnsignedShortAccumTy, BuiltinType::SatUShortAccum);
1205  InitBuiltinType(SatUnsignedAccumTy, BuiltinType::SatUAccum);
1206  InitBuiltinType(SatUnsignedLongAccumTy, BuiltinType::SatULongAccum);
1207  InitBuiltinType(SatShortFractTy, BuiltinType::SatShortFract);
1208  InitBuiltinType(SatFractTy, BuiltinType::SatFract);
1209  InitBuiltinType(SatLongFractTy, BuiltinType::SatLongFract);
1210  InitBuiltinType(SatUnsignedShortFractTy, BuiltinType::SatUShortFract);
1211  InitBuiltinType(SatUnsignedFractTy, BuiltinType::SatUFract);
1212  InitBuiltinType(SatUnsignedLongFractTy, BuiltinType::SatULongFract);
1213 
1214  // GNU extension, 128-bit integers.
1215  InitBuiltinType(Int128Ty, BuiltinType::Int128);
1216  InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
1217 
1218  // C++ 3.9.1p5
1219  if (TargetInfo::isTypeSigned(Target.getWCharType()))
1220  InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1221  else // -fshort-wchar makes wchar_t be unsigned.
1222  InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1223  if (LangOpts.CPlusPlus && LangOpts.WChar)
1224  WideCharTy = WCharTy;
1225  else {
1226  // C99 (or C++ using -fno-wchar).
1227  WideCharTy = getFromTargetType(Target.getWCharType());
1228  }
1229 
1230  WIntTy = getFromTargetType(Target.getWIntType());
1231 
1232  // C++20 (proposed)
1233  InitBuiltinType(Char8Ty, BuiltinType::Char8);
1234 
1235  if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1236  InitBuiltinType(Char16Ty, BuiltinType::Char16);
1237  else // C99
1238  Char16Ty = getFromTargetType(Target.getChar16Type());
1239 
1240  if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1241  InitBuiltinType(Char32Ty, BuiltinType::Char32);
1242  else // C99
1243  Char32Ty = getFromTargetType(Target.getChar32Type());
1244 
1245  // Placeholder type for type-dependent expressions whose type is
1246  // completely unknown. No code should ever check a type against
1247  // DependentTy and users should never see it; however, it is here to
1248  // help diagnose failures to properly check for type-dependent
1249  // expressions.
1250  InitBuiltinType(DependentTy, BuiltinType::Dependent);
1251 
1252  // Placeholder type for functions.
1253  InitBuiltinType(OverloadTy, BuiltinType::Overload);
1254 
1255  // Placeholder type for bound members.
1256  InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1257 
1258  // Placeholder type for pseudo-objects.
1259  InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1260 
1261  // "any" type; useful for debugger-like clients.
1262  InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1263 
1264  // Placeholder type for unbridged ARC casts.
1265  InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1266 
1267  // Placeholder type for builtin functions.
1268  InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1269 
1270  // Placeholder type for OMP array sections.
1271  if (LangOpts.OpenMP)
1272  InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection);
1273 
1274  // C99 6.2.5p11.
1279 
1280  // Builtin types for 'id', 'Class', and 'SEL'.
1281  InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1282  InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
1283  InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
1284 
1285  if (LangOpts.OpenCL) {
1286 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1287  InitBuiltinType(SingletonId, BuiltinType::Id);
1288 #include "clang/Basic/OpenCLImageTypes.def"
1289 
1290  InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
1291  InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
1292  InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1293  InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
1294  InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
1295 
1296 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1297  InitBuiltinType(Id##Ty, BuiltinType::Id);
1298 #include "clang/Basic/OpenCLExtensionTypes.def"
1299  }
1300 
1301  // Builtin type for __objc_yes and __objc_no
1302  ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1303  SignedCharTy : BoolTy);
1304 
1305  ObjCConstantStringType = QualType();
1306 
1307  ObjCSuperType = QualType();
1308 
1309  // void * type
1310  if (LangOpts.OpenCLVersion >= 200) {
1311  auto Q = VoidTy.getQualifiers();
1315  } else {
1317  }
1318 
1319  // nullptr type (C++0x 2.14.7)
1320  InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
1321 
1322  // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1323  InitBuiltinType(HalfTy, BuiltinType::Half);
1324 
1325  // Builtin type used to help define __builtin_va_list.
1326  VaListTagDecl = nullptr;
1327 }
1328 
1330  return SourceMgr.getDiagnostics();
1331 }
1332 
1334  AttrVec *&Result = DeclAttrs[D];
1335  if (!Result) {
1336  void *Mem = Allocate(sizeof(AttrVec));
1337  Result = new (Mem) AttrVec;
1338  }
1339 
1340  return *Result;
1341 }
1342 
1343 /// Erase the attributes corresponding to the given declaration.
1345  llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1346  if (Pos != DeclAttrs.end()) {
1347  Pos->second->~AttrVec();
1348  DeclAttrs.erase(Pos);
1349  }
1350 }
1351 
1352 // FIXME: Remove ?
1355  assert(Var->isStaticDataMember() && "Not a static data member");
1357  .dyn_cast<MemberSpecializationInfo *>();
1358 }
1359 
1362  llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1363  TemplateOrInstantiation.find(Var);
1364  if (Pos == TemplateOrInstantiation.end())
1365  return {};
1366 
1367  return Pos->second;
1368 }
1369 
1370 void
1373  SourceLocation PointOfInstantiation) {
1374  assert(Inst->isStaticDataMember() && "Not a static data member");
1375  assert(Tmpl->isStaticDataMember() && "Not a static data member");
1377  Tmpl, TSK, PointOfInstantiation));
1378 }
1379 
1380 void
1383  assert(!TemplateOrInstantiation[Inst] &&
1384  "Already noted what the variable was instantiated from");
1385  TemplateOrInstantiation[Inst] = TSI;
1386 }
1387 
1388 NamedDecl *
1390  auto Pos = InstantiatedFromUsingDecl.find(UUD);
1391  if (Pos == InstantiatedFromUsingDecl.end())
1392  return nullptr;
1393 
1394  return Pos->second;
1395 }
1396 
1397 void
1399  assert((isa<UsingDecl>(Pattern) ||
1400  isa<UnresolvedUsingValueDecl>(Pattern) ||
1401  isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1402  "pattern decl is not a using decl");
1403  assert((isa<UsingDecl>(Inst) ||
1404  isa<UnresolvedUsingValueDecl>(Inst) ||
1405  isa<UnresolvedUsingTypenameDecl>(Inst)) &&
1406  "instantiation did not produce a using decl");
1407  assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1408  InstantiatedFromUsingDecl[Inst] = Pattern;
1409 }
1410 
1413  llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1414  = InstantiatedFromUsingShadowDecl.find(Inst);
1415  if (Pos == InstantiatedFromUsingShadowDecl.end())
1416  return nullptr;
1417 
1418  return Pos->second;
1419 }
1420 
1421 void
1423  UsingShadowDecl *Pattern) {
1424  assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1425  InstantiatedFromUsingShadowDecl[Inst] = Pattern;
1426 }
1427 
1429  llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1430  = InstantiatedFromUnnamedFieldDecl.find(Field);
1431  if (Pos == InstantiatedFromUnnamedFieldDecl.end())
1432  return nullptr;
1433 
1434  return Pos->second;
1435 }
1436 
1438  FieldDecl *Tmpl) {
1439  assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1440  assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1441  assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1442  "Already noted what unnamed field was instantiated from");
1443 
1444  InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1445 }
1446 
1449  return overridden_methods(Method).begin();
1450 }
1451 
1454  return overridden_methods(Method).end();
1455 }
1456 
1457 unsigned
1459  auto Range = overridden_methods(Method);
1460  return Range.end() - Range.begin();
1461 }
1462 
1465  llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1466  OverriddenMethods.find(Method->getCanonicalDecl());
1467  if (Pos == OverriddenMethods.end())
1468  return overridden_method_range(nullptr, nullptr);
1469  return overridden_method_range(Pos->second.begin(), Pos->second.end());
1470 }
1471 
1473  const CXXMethodDecl *Overridden) {
1474  assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
1475  OverriddenMethods[Method].push_back(Overridden);
1476 }
1477 
1479  const NamedDecl *D,
1480  SmallVectorImpl<const NamedDecl *> &Overridden) const {
1481  assert(D);
1482 
1483  if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
1484  Overridden.append(overridden_methods_begin(CXXMethod),
1485  overridden_methods_end(CXXMethod));
1486  return;
1487  }
1488 
1489  const auto *Method = dyn_cast<ObjCMethodDecl>(D);
1490  if (!Method)
1491  return;
1492 
1494  Method->getOverriddenMethods(OverDecls);
1495  Overridden.append(OverDecls.begin(), OverDecls.end());
1496 }
1497 
1499  assert(!Import->NextLocalImport && "Import declaration already in the chain");
1500  assert(!Import->isFromASTFile() && "Non-local import declaration");
1501  if (!FirstLocalImport) {
1502  FirstLocalImport = Import;
1503  LastLocalImport = Import;
1504  return;
1505  }
1506 
1507  LastLocalImport->NextLocalImport = Import;
1508  LastLocalImport = Import;
1509 }
1510 
1511 //===----------------------------------------------------------------------===//
1512 // Type Sizing and Analysis
1513 //===----------------------------------------------------------------------===//
1514 
1515 /// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1516 /// scalar floating point type.
1517 const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
1518  const auto *BT = T->getAs<BuiltinType>();
1519  assert(BT && "Not a floating point type!");
1520  switch (BT->getKind()) {
1521  default: llvm_unreachable("Not a floating point type!");
1522  case BuiltinType::Float16:
1523  case BuiltinType::Half:
1524  return Target->getHalfFormat();
1525  case BuiltinType::Float: return Target->getFloatFormat();
1526  case BuiltinType::Double: return Target->getDoubleFormat();
1527  case BuiltinType::LongDouble:
1528  if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice)
1529  return AuxTarget->getLongDoubleFormat();
1530  return Target->getLongDoubleFormat();
1531  case BuiltinType::Float128:
1532  if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice)
1533  return AuxTarget->getFloat128Format();
1534  return Target->getFloat128Format();
1535  }
1536 }
1537 
1538 CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
1539  unsigned Align = Target->getCharWidth();
1540 
1541  bool UseAlignAttrOnly = false;
1542  if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1543  Align = AlignFromAttr;
1544 
1545  // __attribute__((aligned)) can increase or decrease alignment
1546  // *except* on a struct or struct member, where it only increases
1547  // alignment unless 'packed' is also specified.
1548  //
1549  // It is an error for alignas to decrease alignment, so we can
1550  // ignore that possibility; Sema should diagnose it.
1551  if (isa<FieldDecl>(D)) {
1552  UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1553  cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1554  } else {
1555  UseAlignAttrOnly = true;
1556  }
1557  }
1558  else if (isa<FieldDecl>(D))
1559  UseAlignAttrOnly =
1560  D->hasAttr<PackedAttr>() ||
1561  cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1562 
1563  // If we're using the align attribute only, just ignore everything
1564  // else about the declaration and its type.
1565  if (UseAlignAttrOnly) {
1566  // do nothing
1567  } else if (const auto *VD = dyn_cast<ValueDecl>(D)) {
1568  QualType T = VD->getType();
1569  if (const auto *RT = T->getAs<ReferenceType>()) {
1570  if (ForAlignof)
1571  T = RT->getPointeeType();
1572  else
1573  T = getPointerType(RT->getPointeeType());
1574  }
1575  QualType BaseT = getBaseElementType(T);
1576  if (T->isFunctionType())
1577  Align = getTypeInfoImpl(T.getTypePtr()).Align;
1578  else if (!BaseT->isIncompleteType()) {
1579  // Adjust alignments of declarations with array type by the
1580  // large-array alignment on the target.
1581  if (const ArrayType *arrayType = getAsArrayType(T)) {
1582  unsigned MinWidth = Target->getLargeArrayMinWidth();
1583  if (!ForAlignof && MinWidth) {
1584  if (isa<VariableArrayType>(arrayType))
1585  Align = std::max(Align, Target->getLargeArrayAlign());
1586  else if (isa<ConstantArrayType>(arrayType) &&
1587  MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1588  Align = std::max(Align, Target->getLargeArrayAlign());
1589  }
1590  }
1591  Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
1592  if (BaseT.getQualifiers().hasUnaligned())
1593  Align = Target->getCharWidth();
1594  if (const auto *VD = dyn_cast<VarDecl>(D)) {
1595  if (VD->hasGlobalStorage() && !ForAlignof) {
1596  uint64_t TypeSize = getTypeSize(T.getTypePtr());
1597  Align = std::max(Align, getTargetInfo().getMinGlobalAlign(TypeSize));
1598  }
1599  }
1600  }
1601 
1602  // Fields can be subject to extra alignment constraints, like if
1603  // the field is packed, the struct is packed, or the struct has a
1604  // a max-field-alignment constraint (#pragma pack). So calculate
1605  // the actual alignment of the field within the struct, and then
1606  // (as we're expected to) constrain that by the alignment of the type.
1607  if (const auto *Field = dyn_cast<FieldDecl>(VD)) {
1608  const RecordDecl *Parent = Field->getParent();
1609  // We can only produce a sensible answer if the record is valid.
1610  if (!Parent->isInvalidDecl()) {
1611  const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
1612 
1613  // Start with the record's overall alignment.
1614  unsigned FieldAlign = toBits(Layout.getAlignment());
1615 
1616  // Use the GCD of that and the offset within the record.
1617  uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1618  if (Offset > 0) {
1619  // Alignment is always a power of 2, so the GCD will be a power of 2,
1620  // which means we get to do this crazy thing instead of Euclid's.
1621  uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1622  if (LowBitOfOffset < FieldAlign)
1623  FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1624  }
1625 
1626  Align = std::min(Align, FieldAlign);
1627  }
1628  }
1629  }
1630 
1631  return toCharUnitsFromBits(Align);
1632 }
1633 
1634 // getTypeInfoDataSizeInChars - Return the size of a type, in
1635 // chars. If the type is a record, its data size is returned. This is
1636 // the size of the memcpy that's performed when assigning this type
1637 // using a trivial copy/move assignment operator.
1638 std::pair<CharUnits, CharUnits>
1640  std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1641 
1642  // In C++, objects can sometimes be allocated into the tail padding
1643  // of a base-class subobject. We decide whether that's possible
1644  // during class layout, so here we can just trust the layout results.
1645  if (getLangOpts().CPlusPlus) {
1646  if (const auto *RT = T->getAs<RecordType>()) {
1647  const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1648  sizeAndAlign.first = layout.getDataSize();
1649  }
1650  }
1651 
1652  return sizeAndAlign;
1653 }
1654 
1655 /// getConstantArrayInfoInChars - Performing the computation in CharUnits
1656 /// instead of in bits prevents overflowing the uint64_t for some large arrays.
1657 std::pair<CharUnits, CharUnits>
1659  const ConstantArrayType *CAT) {
1660  std::pair<CharUnits, CharUnits> EltInfo =
1661  Context.getTypeInfoInChars(CAT->getElementType());
1662  uint64_t Size = CAT->getSize().getZExtValue();
1663  assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1664  (uint64_t)(-1)/Size) &&
1665  "Overflow in array type char size evaluation");
1666  uint64_t Width = EltInfo.first.getQuantity() * Size;
1667  unsigned Align = EltInfo.second.getQuantity();
1668  if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1669  Context.getTargetInfo().getPointerWidth(0) == 64)
1670  Width = llvm::alignTo(Width, Align);
1671  return std::make_pair(CharUnits::fromQuantity(Width),
1672  CharUnits::fromQuantity(Align));
1673 }
1674 
1675 std::pair<CharUnits, CharUnits>
1677  if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
1678  return getConstantArrayInfoInChars(*this, CAT);
1679  TypeInfo Info = getTypeInfo(T);
1680  return std::make_pair(toCharUnitsFromBits(Info.Width),
1681  toCharUnitsFromBits(Info.Align));
1682 }
1683 
1684 std::pair<CharUnits, CharUnits>
1686  return getTypeInfoInChars(T.getTypePtr());
1687 }
1688 
1690  return getTypeInfo(T).AlignIsRequired;
1691 }
1692 
1694  return isAlignmentRequired(T.getTypePtr());
1695 }
1696 
1698  // An alignment on a typedef overrides anything else.
1699  if (const auto *TT = T->getAs<TypedefType>())
1700  if (unsigned Align = TT->getDecl()->getMaxAlignment())
1701  return Align;
1702 
1703  // If we have an (array of) complete type, we're done.
1704  T = getBaseElementType(T);
1705  if (!T->isIncompleteType())
1706  return getTypeAlign(T);
1707 
1708  // If we had an array type, its element type might be a typedef
1709  // type with an alignment attribute.
1710  if (const auto *TT = T->getAs<TypedefType>())
1711  if (unsigned Align = TT->getDecl()->getMaxAlignment())
1712  return Align;
1713 
1714  // Otherwise, see if the declaration of the type had an attribute.
1715  if (const auto *TT = T->getAs<TagType>())
1716  return TT->getDecl()->getMaxAlignment();
1717 
1718  return 0;
1719 }
1720 
1722  TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1723  if (I != MemoizedTypeInfo.end())
1724  return I->second;
1725 
1726  // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1727  TypeInfo TI = getTypeInfoImpl(T);
1728  MemoizedTypeInfo[T] = TI;
1729  return TI;
1730 }
1731 
1732 /// getTypeInfoImpl - Return the size of the specified type, in bits. This
1733 /// method does not work on incomplete types.
1734 ///
1735 /// FIXME: Pointers into different addr spaces could have different sizes and
1736 /// alignment requirements: getPointerInfo should take an AddrSpace, this
1737 /// should take a QualType, &c.
1738 TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1739  uint64_t Width = 0;
1740  unsigned Align = 8;
1741  bool AlignIsRequired = false;
1742  unsigned AS = 0;
1743  switch (T->getTypeClass()) {
1744 #define TYPE(Class, Base)
1745 #define ABSTRACT_TYPE(Class, Base)
1746 #define NON_CANONICAL_TYPE(Class, Base)
1747 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
1748 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1749  case Type::Class: \
1750  assert(!T->isDependentType() && "should not see dependent types here"); \
1751  return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
1752 #include "clang/AST/TypeNodes.def"
1753  llvm_unreachable("Should not see dependent types");
1754 
1755  case Type::FunctionNoProto:
1756  case Type::FunctionProto:
1757  // GCC extension: alignof(function) = 32 bits
1758  Width = 0;
1759  Align = 32;
1760  break;
1761 
1762  case Type::IncompleteArray:
1763  case Type::VariableArray:
1764  Width = 0;
1765  Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1766  break;
1767 
1768  case Type::ConstantArray: {
1769  const auto *CAT = cast<ConstantArrayType>(T);
1770 
1771  TypeInfo EltInfo = getTypeInfo(CAT->getElementType());
1772  uint64_t Size = CAT->getSize().getZExtValue();
1773  assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
1774  "Overflow in array type bit size evaluation");
1775  Width = EltInfo.Width * Size;
1776  Align = EltInfo.Align;
1777  if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1778  getTargetInfo().getPointerWidth(0) == 64)
1779  Width = llvm::alignTo(Width, Align);
1780  break;
1781  }
1782  case Type::ExtVector:
1783  case Type::Vector: {
1784  const auto *VT = cast<VectorType>(T);
1785  TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1786  Width = EltInfo.Width * VT->getNumElements();
1787  Align = Width;
1788  // If the alignment is not a power of 2, round up to the next power of 2.
1789  // This happens for non-power-of-2 length vectors.
1790  if (Align & (Align-1)) {
1791  Align = llvm::NextPowerOf2(Align);
1792  Width = llvm::alignTo(Width, Align);
1793  }
1794  // Adjust the alignment based on the target max.
1795  uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1796  if (TargetVectorAlign && TargetVectorAlign < Align)
1797  Align = TargetVectorAlign;
1798  break;
1799  }
1800 
1801  case Type::Builtin:
1802  switch (cast<BuiltinType>(T)->getKind()) {
1803  default: llvm_unreachable("Unknown builtin type!");
1804  case BuiltinType::Void:
1805  // GCC extension: alignof(void) = 8 bits.
1806  Width = 0;
1807  Align = 8;
1808  break;
1809  case BuiltinType::Bool:
1810  Width = Target->getBoolWidth();
1811  Align = Target->getBoolAlign();
1812  break;
1813  case BuiltinType::Char_S:
1814  case BuiltinType::Char_U:
1815  case BuiltinType::UChar:
1816  case BuiltinType::SChar:
1817  case BuiltinType::Char8:
1818  Width = Target->getCharWidth();
1819  Align = Target->getCharAlign();
1820  break;
1821  case BuiltinType::WChar_S:
1822  case BuiltinType::WChar_U:
1823  Width = Target->getWCharWidth();
1824  Align = Target->getWCharAlign();
1825  break;
1826  case BuiltinType::Char16:
1827  Width = Target->getChar16Width();
1828  Align = Target->getChar16Align();
1829  break;
1830  case BuiltinType::Char32:
1831  Width = Target->getChar32Width();
1832  Align = Target->getChar32Align();
1833  break;
1834  case BuiltinType::UShort:
1835  case BuiltinType::Short:
1836  Width = Target->getShortWidth();
1837  Align = Target->getShortAlign();
1838  break;
1839  case BuiltinType::UInt:
1840  case BuiltinType::Int:
1841  Width = Target->getIntWidth();
1842  Align = Target->getIntAlign();
1843  break;
1844  case BuiltinType::ULong:
1845  case BuiltinType::Long:
1846  Width = Target->getLongWidth();
1847  Align = Target->getLongAlign();
1848  break;
1849  case BuiltinType::ULongLong:
1850  case BuiltinType::LongLong:
1851  Width = Target->getLongLongWidth();
1852  Align = Target->getLongLongAlign();
1853  break;
1854  case BuiltinType::Int128:
1855  case BuiltinType::UInt128:
1856  Width = 128;
1857  Align = 128; // int128_t is 128-bit aligned on all targets.
1858  break;
1859  case BuiltinType::ShortAccum:
1860  case BuiltinType::UShortAccum:
1861  case BuiltinType::SatShortAccum:
1862  case BuiltinType::SatUShortAccum:
1863  Width = Target->getShortAccumWidth();
1864  Align = Target->getShortAccumAlign();
1865  break;
1866  case BuiltinType::Accum:
1867  case BuiltinType::UAccum:
1868  case BuiltinType::SatAccum:
1869  case BuiltinType::SatUAccum:
1870  Width = Target->getAccumWidth();
1871  Align = Target->getAccumAlign();
1872  break;
1873  case BuiltinType::LongAccum:
1874  case BuiltinType::ULongAccum:
1875  case BuiltinType::SatLongAccum:
1876  case BuiltinType::SatULongAccum:
1877  Width = Target->getLongAccumWidth();
1878  Align = Target->getLongAccumAlign();
1879  break;
1880  case BuiltinType::ShortFract:
1881  case BuiltinType::UShortFract:
1882  case BuiltinType::SatShortFract:
1883  case BuiltinType::SatUShortFract:
1884  Width = Target->getShortFractWidth();
1885  Align = Target->getShortFractAlign();
1886  break;
1887  case BuiltinType::Fract:
1888  case BuiltinType::UFract:
1889  case BuiltinType::SatFract:
1890  case BuiltinType::SatUFract:
1891  Width = Target->getFractWidth();
1892  Align = Target->getFractAlign();
1893  break;
1894  case BuiltinType::LongFract:
1895  case BuiltinType::ULongFract:
1896  case BuiltinType::SatLongFract:
1897  case BuiltinType::SatULongFract:
1898  Width = Target->getLongFractWidth();
1899  Align = Target->getLongFractAlign();
1900  break;
1901  case BuiltinType::Float16:
1902  case BuiltinType::Half:
1903  if (Target->hasFloat16Type() || !getLangOpts().OpenMP ||
1904  !getLangOpts().OpenMPIsDevice) {
1905  Width = Target->getHalfWidth();
1906  Align = Target->getHalfAlign();
1907  } else {
1908  assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
1909  "Expected OpenMP device compilation.");
1910  Width = AuxTarget->getHalfWidth();
1911  Align = AuxTarget->getHalfAlign();
1912  }
1913  break;
1914  case BuiltinType::Float:
1915  Width = Target->getFloatWidth();
1916  Align = Target->getFloatAlign();
1917  break;
1918  case BuiltinType::Double:
1919  Width = Target->getDoubleWidth();
1920  Align = Target->getDoubleAlign();
1921  break;
1922  case BuiltinType::LongDouble:
1923  if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
1924  (Target->getLongDoubleWidth() != AuxTarget->getLongDoubleWidth() ||
1925  Target->getLongDoubleAlign() != AuxTarget->getLongDoubleAlign())) {
1926  Width = AuxTarget->getLongDoubleWidth();
1927  Align = AuxTarget->getLongDoubleAlign();
1928  } else {
1929  Width = Target->getLongDoubleWidth();
1930  Align = Target->getLongDoubleAlign();
1931  }
1932  break;
1933  case BuiltinType::Float128:
1934  if (Target->hasFloat128Type() || !getLangOpts().OpenMP ||
1935  !getLangOpts().OpenMPIsDevice) {
1936  Width = Target->getFloat128Width();
1937  Align = Target->getFloat128Align();
1938  } else {
1939  assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
1940  "Expected OpenMP device compilation.");
1941  Width = AuxTarget->getFloat128Width();
1942  Align = AuxTarget->getFloat128Align();
1943  }
1944  break;
1945  case BuiltinType::NullPtr:
1946  Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1947  Align = Target->getPointerAlign(0); // == sizeof(void*)
1948  break;
1949  case BuiltinType::ObjCId:
1950  case BuiltinType::ObjCClass:
1951  case BuiltinType::ObjCSel:
1952  Width = Target->getPointerWidth(0);
1953  Align = Target->getPointerAlign(0);
1954  break;
1955  case BuiltinType::OCLSampler:
1956  case BuiltinType::OCLEvent:
1957  case BuiltinType::OCLClkEvent:
1958  case BuiltinType::OCLQueue:
1959  case BuiltinType::OCLReserveID:
1960 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1961  case BuiltinType::Id:
1962 #include "clang/Basic/OpenCLImageTypes.def"
1963 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1964  case BuiltinType::Id:
1965 #include "clang/Basic/OpenCLExtensionTypes.def"
1966  AS = getTargetAddressSpace(
1967  Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T)));
1968  Width = Target->getPointerWidth(AS);
1969  Align = Target->getPointerAlign(AS);
1970  break;
1971  }
1972  break;
1973  case Type::ObjCObjectPointer:
1974  Width = Target->getPointerWidth(0);
1975  Align = Target->getPointerAlign(0);
1976  break;
1977  case Type::BlockPointer:
1978  AS = getTargetAddressSpace(cast<BlockPointerType>(T)->getPointeeType());
1979  Width = Target->getPointerWidth(AS);
1980  Align = Target->getPointerAlign(AS);
1981  break;
1982  case Type::LValueReference:
1983  case Type::RValueReference:
1984  // alignof and sizeof should never enter this code path here, so we go
1985  // the pointer route.
1986  AS = getTargetAddressSpace(cast<ReferenceType>(T)->getPointeeType());
1987  Width = Target->getPointerWidth(AS);
1988  Align = Target->getPointerAlign(AS);
1989  break;
1990  case Type::Pointer:
1991  AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
1992  Width = Target->getPointerWidth(AS);
1993  Align = Target->getPointerAlign(AS);
1994  break;
1995  case Type::MemberPointer: {
1996  const auto *MPT = cast<MemberPointerType>(T);
1997  CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT);
1998  Width = MPI.Width;
1999  Align = MPI.Align;
2000  break;
2001  }
2002  case Type::Complex: {
2003  // Complex types have the same alignment as their elements, but twice the
2004  // size.
2005  TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
2006  Width = EltInfo.Width * 2;
2007  Align = EltInfo.Align;
2008  break;
2009  }
2010  case Type::ObjCObject:
2011  return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
2012  case Type::Adjusted:
2013  case Type::Decayed:
2014  return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
2015  case Type::ObjCInterface: {
2016  const auto *ObjCI = cast<ObjCInterfaceType>(T);
2017  const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2018  Width = toBits(Layout.getSize());
2019  Align = toBits(Layout.getAlignment());
2020  break;
2021  }
2022  case Type::Record:
2023  case Type::Enum: {
2024  const auto *TT = cast<TagType>(T);
2025 
2026  if (TT->getDecl()->isInvalidDecl()) {
2027  Width = 8;
2028  Align = 8;
2029  break;
2030  }
2031 
2032  if (const auto *ET = dyn_cast<EnumType>(TT)) {
2033  const EnumDecl *ED = ET->getDecl();
2034  TypeInfo Info =
2036  if (unsigned AttrAlign = ED->getMaxAlignment()) {
2037  Info.Align = AttrAlign;
2038  Info.AlignIsRequired = true;
2039  }
2040  return Info;
2041  }
2042 
2043  const auto *RT = cast<RecordType>(TT);
2044  const RecordDecl *RD = RT->getDecl();
2045  const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2046  Width = toBits(Layout.getSize());
2047  Align = toBits(Layout.getAlignment());
2048  AlignIsRequired = RD->hasAttr<AlignedAttr>();
2049  break;
2050  }
2051 
2052  case Type::SubstTemplateTypeParm:
2053  return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
2054  getReplacementType().getTypePtr());
2055 
2056  case Type::Auto:
2057  case Type::DeducedTemplateSpecialization: {
2058  const auto *A = cast<DeducedType>(T);
2059  assert(!A->getDeducedType().isNull() &&
2060  "cannot request the size of an undeduced or dependent auto type");
2061  return getTypeInfo(A->getDeducedType().getTypePtr());
2062  }
2063 
2064  case Type::Paren:
2065  return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
2066 
2067  case Type::MacroQualified:
2068  return getTypeInfo(
2069  cast<MacroQualifiedType>(T)->getUnderlyingType().getTypePtr());
2070 
2071  case Type::ObjCTypeParam:
2072  return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr());
2073 
2074  case Type::Typedef: {
2075  const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
2076  TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
2077  // If the typedef has an aligned attribute on it, it overrides any computed
2078  // alignment we have. This violates the GCC documentation (which says that
2079  // attribute(aligned) can only round up) but matches its implementation.
2080  if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
2081  Align = AttrAlign;
2082  AlignIsRequired = true;
2083  } else {
2084  Align = Info.Align;
2085  AlignIsRequired = Info.AlignIsRequired;
2086  }
2087  Width = Info.Width;
2088  break;
2089  }
2090 
2091  case Type::Elaborated:
2092  return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
2093 
2094  case Type::Attributed:
2095  return getTypeInfo(
2096  cast<AttributedType>(T)->getEquivalentType().getTypePtr());
2097 
2098  case Type::Atomic: {
2099  // Start with the base type information.
2100  TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
2101  Width = Info.Width;
2102  Align = Info.Align;
2103 
2104  if (!Width) {
2105  // An otherwise zero-sized type should still generate an
2106  // atomic operation.
2107  Width = Target->getCharWidth();
2108  assert(Align);
2109  } else if (Width <= Target->getMaxAtomicPromoteWidth()) {
2110  // If the size of the type doesn't exceed the platform's max
2111  // atomic promotion width, make the size and alignment more
2112  // favorable to atomic operations:
2113 
2114  // Round the size up to a power of 2.
2115  if (!llvm::isPowerOf2_64(Width))
2116  Width = llvm::NextPowerOf2(Width);
2117 
2118  // Set the alignment equal to the size.
2119  Align = static_cast<unsigned>(Width);
2120  }
2121  }
2122  break;
2123 
2124  case Type::Pipe:
2125  Width = Target->getPointerWidth(getTargetAddressSpace(LangAS::opencl_global));
2126  Align = Target->getPointerAlign(getTargetAddressSpace(LangAS::opencl_global));
2127  break;
2128  }
2129 
2130  assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
2131  return TypeInfo(Width, Align, AlignIsRequired);
2132 }
2133 
2134 unsigned ASTContext::getTypeUnadjustedAlign(const Type *T) const {
2135  UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(T);
2136  if (I != MemoizedUnadjustedAlign.end())
2137  return I->second;
2138 
2139  unsigned UnadjustedAlign;
2140  if (const auto *RT = T->getAs<RecordType>()) {
2141  const RecordDecl *RD = RT->getDecl();
2142  const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2143  UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2144  } else if (const auto *ObjCI = T->getAs<ObjCInterfaceType>()) {
2145  const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2146  UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2147  } else {
2148  UnadjustedAlign = getTypeAlign(T->getUnqualifiedDesugaredType());
2149  }
2150 
2151  MemoizedUnadjustedAlign[T] = UnadjustedAlign;
2152  return UnadjustedAlign;
2153 }
2154 
2156  unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign();
2157  // Target ppc64 with QPX: simd default alignment for pointer to double is 32.
2158  if ((getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64 ||
2159  getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64le) &&
2160  getTargetInfo().getABI() == "elfv1-qpx" &&
2161  T->isSpecificBuiltinType(BuiltinType::Double))
2162  SimdAlign = 256;
2163  return SimdAlign;
2164 }
2165 
2166 /// toCharUnitsFromBits - Convert a size in bits to a size in characters.
2168  return CharUnits::fromQuantity(BitSize / getCharWidth());
2169 }
2170 
2171 /// toBits - Convert a size in characters to a size in characters.
2172 int64_t ASTContext::toBits(CharUnits CharSize) const {
2173  return CharSize.getQuantity() * getCharWidth();
2174 }
2175 
2176 /// getTypeSizeInChars - Return the size of the specified type, in characters.
2177 /// This method does not work on incomplete types.
2179  return getTypeInfoInChars(T).first;
2180 }
2182  return getTypeInfoInChars(T).first;
2183 }
2184 
2185 /// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
2186 /// characters. This method does not work on incomplete types.
2188  return toCharUnitsFromBits(getTypeAlign(T));
2189 }
2191  return toCharUnitsFromBits(getTypeAlign(T));
2192 }
2193 
2194 /// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a
2195 /// type, in characters, before alignment adustments. This method does
2196 /// not work on incomplete types.
2199 }
2202 }
2203 
2204 /// getPreferredTypeAlign - Return the "preferred" alignment of the specified
2205 /// type for the current target in bits. This can be different than the ABI
2206 /// alignment in cases where it is beneficial for performance to overalign
2207 /// a data type.
2208 unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
2209  TypeInfo TI = getTypeInfo(T);
2210  unsigned ABIAlign = TI.Align;
2211 
2212  T = T->getBaseElementTypeUnsafe();
2213 
2214  // The preferred alignment of member pointers is that of a pointer.
2215  if (T->isMemberPointerType())
2217 
2218  if (!Target->allowsLargerPreferedTypeAlignment())
2219  return ABIAlign;
2220 
2221  // Double and long long should be naturally aligned if possible.
2222  if (const auto *CT = T->getAs<ComplexType>())
2223  T = CT->getElementType().getTypePtr();
2224  if (const auto *ET = T->getAs<EnumType>())
2225  T = ET->getDecl()->getIntegerType().getTypePtr();
2226  if (T->isSpecificBuiltinType(BuiltinType::Double) ||
2227  T->isSpecificBuiltinType(BuiltinType::LongLong) ||
2228  T->isSpecificBuiltinType(BuiltinType::ULongLong))
2229  // Don't increase the alignment if an alignment attribute was specified on a
2230  // typedef declaration.
2231  if (!TI.AlignIsRequired)
2232  return std::max(ABIAlign, (unsigned)getTypeSize(T));
2233 
2234  return ABIAlign;
2235 }
2236 
2237 /// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2238 /// for __attribute__((aligned)) on this target, to be used if no alignment
2239 /// value is specified.
2242 }
2243 
2244 /// getAlignOfGlobalVar - Return the alignment in bits that should be given
2245 /// to a global variable of the specified type.
2247  uint64_t TypeSize = getTypeSize(T.getTypePtr());
2248  return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign(TypeSize));
2249 }
2250 
2251 /// getAlignOfGlobalVarInChars - Return the alignment in characters that
2252 /// should be given to a global variable of the specified type.
2255 }
2256 
2259  const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
2260  while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2261  Offset += Layout->getBaseClassOffset(Base);
2262  Layout = &getASTRecordLayout(Base);
2263  }
2264  return Offset;
2265 }
2266 
2267 /// DeepCollectObjCIvars -
2268 /// This routine first collects all declared, but not synthesized, ivars in
2269 /// super class and then collects all ivars, including those synthesized for
2270 /// current class. This routine is used for implementation of current class
2271 /// when all ivars, declared and synthesized are known.
2273  bool leafClass,
2274  SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
2275  if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2276  DeepCollectObjCIvars(SuperClass, false, Ivars);
2277  if (!leafClass) {
2278  for (const auto *I : OI->ivars())
2279  Ivars.push_back(I);
2280  } else {
2281  auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
2282  for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
2283  Iv= Iv->getNextIvar())
2284  Ivars.push_back(Iv);
2285  }
2286 }
2287 
2288 /// CollectInheritedProtocols - Collect all protocols in current class and
2289 /// those inherited by it.
2291  llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
2292  if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
2293  // We can use protocol_iterator here instead of
2294  // all_referenced_protocol_iterator since we are walking all categories.
2295  for (auto *Proto : OI->all_referenced_protocols()) {
2296  CollectInheritedProtocols(Proto, Protocols);
2297  }
2298 
2299  // Categories of this Interface.
2300  for (const auto *Cat : OI->visible_categories())
2301  CollectInheritedProtocols(Cat, Protocols);
2302 
2303  if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2304  while (SD) {
2305  CollectInheritedProtocols(SD, Protocols);
2306  SD = SD->getSuperClass();
2307  }
2308  } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
2309  for (auto *Proto : OC->protocols()) {
2310  CollectInheritedProtocols(Proto, Protocols);
2311  }
2312  } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
2313  // Insert the protocol.
2314  if (!Protocols.insert(
2315  const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2316  return;
2317 
2318  for (auto *Proto : OP->protocols())
2319  CollectInheritedProtocols(Proto, Protocols);
2320  }
2321 }
2322 
2324  const RecordDecl *RD) {
2325  assert(RD->isUnion() && "Must be union type");
2326  CharUnits UnionSize = Context.getTypeSizeInChars(RD->getTypeForDecl());
2327 
2328  for (const auto *Field : RD->fields()) {
2329  if (!Context.hasUniqueObjectRepresentations(Field->getType()))
2330  return false;
2331  CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType());
2332  if (FieldSize != UnionSize)
2333  return false;
2334  }
2335  return !RD->field_empty();
2336 }
2337 
2338 static bool isStructEmpty(QualType Ty) {
2339  const RecordDecl *RD = Ty->castAs<RecordType>()->getDecl();
2340 
2341  if (!RD->field_empty())
2342  return false;
2343 
2344  if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD))
2345  return ClassDecl->isEmpty();
2346 
2347  return true;
2348 }
2349 
2352  const RecordDecl *RD) {
2353  assert(!RD->isUnion() && "Must be struct/class type");
2354  const auto &Layout = Context.getASTRecordLayout(RD);
2355 
2356  int64_t CurOffsetInBits = 0;
2357  if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) {
2358  if (ClassDecl->isDynamicClass())
2359  return llvm::None;
2360 
2362  for (const auto Base : ClassDecl->bases()) {
2363  // Empty types can be inherited from, and non-empty types can potentially
2364  // have tail padding, so just make sure there isn't an error.
2365  if (!isStructEmpty(Base.getType())) {
2367  Context, Base.getType()->getAs<RecordType>()->getDecl());
2368  if (!Size)
2369  return llvm::None;
2370  Bases.emplace_back(Base.getType(), Size.getValue());
2371  }
2372  }
2373 
2374  llvm::sort(Bases, [&](const std::pair<QualType, int64_t> &L,
2375  const std::pair<QualType, int64_t> &R) {
2376  return Layout.getBaseClassOffset(L.first->getAsCXXRecordDecl()) <
2377  Layout.getBaseClassOffset(R.first->getAsCXXRecordDecl());
2378  });
2379 
2380  for (const auto Base : Bases) {
2381  int64_t BaseOffset = Context.toBits(
2382  Layout.getBaseClassOffset(Base.first->getAsCXXRecordDecl()));
2383  int64_t BaseSize = Base.second;
2384  if (BaseOffset != CurOffsetInBits)
2385  return llvm::None;
2386  CurOffsetInBits = BaseOffset + BaseSize;
2387  }
2388  }
2389 
2390  for (const auto *Field : RD->fields()) {
2391  if (!Field->getType()->isReferenceType() &&
2392  !Context.hasUniqueObjectRepresentations(Field->getType()))
2393  return llvm::None;
2394 
2395  int64_t FieldSizeInBits =
2396  Context.toBits(Context.getTypeSizeInChars(Field->getType()));
2397  if (Field->isBitField()) {
2398  int64_t BitfieldSize = Field->getBitWidthValue(Context);
2399 
2400  if (BitfieldSize > FieldSizeInBits)
2401  return llvm::None;
2402  FieldSizeInBits = BitfieldSize;
2403  }
2404 
2405  int64_t FieldOffsetInBits = Context.getFieldOffset(Field);
2406 
2407  if (FieldOffsetInBits != CurOffsetInBits)
2408  return llvm::None;
2409 
2410  CurOffsetInBits = FieldSizeInBits + FieldOffsetInBits;
2411  }
2412 
2413  return CurOffsetInBits;
2414 }
2415 
2417  // C++17 [meta.unary.prop]:
2418  // The predicate condition for a template specialization
2419  // has_unique_object_representations<T> shall be
2420  // satisfied if and only if:
2421  // (9.1) - T is trivially copyable, and
2422  // (9.2) - any two objects of type T with the same value have the same
2423  // object representation, where two objects
2424  // of array or non-union class type are considered to have the same value
2425  // if their respective sequences of
2426  // direct subobjects have the same values, and two objects of union type
2427  // are considered to have the same
2428  // value if they have the same active member and the corresponding members
2429  // have the same value.
2430  // The set of scalar types for which this condition holds is
2431  // implementation-defined. [ Note: If a type has padding
2432  // bits, the condition does not hold; otherwise, the condition holds true
2433  // for unsigned integral types. -- end note ]
2434  assert(!Ty.isNull() && "Null QualType sent to unique object rep check");
2435 
2436  // Arrays are unique only if their element type is unique.
2437  if (Ty->isArrayType())
2439 
2440  // (9.1) - T is trivially copyable...
2441  if (!Ty.isTriviallyCopyableType(*this))
2442  return false;
2443 
2444  // All integrals and enums are unique.
2445  if (Ty->isIntegralOrEnumerationType())
2446  return true;
2447 
2448  // All other pointers are unique.
2449  if (Ty->isPointerType())
2450  return true;
2451 
2452  if (Ty->isMemberPointerType()) {
2453  const auto *MPT = Ty->getAs<MemberPointerType>();
2454  return !ABI->getMemberPointerInfo(MPT).HasPadding;
2455  }
2456 
2457  if (Ty->isRecordType()) {
2458  const RecordDecl *Record = Ty->getAs<RecordType>()->getDecl();
2459 
2460  if (Record->isInvalidDecl())
2461  return false;
2462 
2463  if (Record->isUnion())
2464  return unionHasUniqueObjectRepresentations(*this, Record);
2465 
2466  Optional<int64_t> StructSize =
2467  structHasUniqueObjectRepresentations(*this, Record);
2468 
2469  return StructSize &&
2470  StructSize.getValue() == static_cast<int64_t>(getTypeSize(Ty));
2471  }
2472 
2473  // FIXME: More cases to handle here (list by rsmith):
2474  // vectors (careful about, eg, vector of 3 foo)
2475  // _Complex int and friends
2476  // _Atomic T
2477  // Obj-C block pointers
2478  // Obj-C object pointers
2479  // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t,
2480  // clk_event_t, queue_t, reserve_id_t)
2481  // There're also Obj-C class types and the Obj-C selector type, but I think it
2482  // makes sense for those to return false here.
2483 
2484  return false;
2485 }
2486 
2488  unsigned count = 0;
2489  // Count ivars declared in class extension.
2490  for (const auto *Ext : OI->known_extensions())
2491  count += Ext->ivar_size();
2492 
2493  // Count ivar defined in this class's implementation. This
2494  // includes synthesized ivars.
2495  if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
2496  count += ImplDecl->ivar_size();
2497 
2498  return count;
2499 }
2500 
2502  if (!E)
2503  return false;
2504 
2505  // nullptr_t is always treated as null.
2506  if (E->getType()->isNullPtrType()) return true;
2507 
2508  if (E->getType()->isAnyPointerType() &&
2511  return true;
2512 
2513  // Unfortunately, __null has type 'int'.
2514  if (isa<GNUNullExpr>(E)) return true;
2515 
2516  return false;
2517 }
2518 
2519 /// Get the implementation of ObjCInterfaceDecl, or nullptr if none
2520 /// exists.
2522  llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2523  I = ObjCImpls.find(D);
2524  if (I != ObjCImpls.end())
2525  return cast<ObjCImplementationDecl>(I->second);
2526  return nullptr;
2527 }
2528 
2529 /// Get the implementation of ObjCCategoryDecl, or nullptr if none
2530 /// exists.
2532  llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2533  I = ObjCImpls.find(D);
2534  if (I != ObjCImpls.end())
2535  return cast<ObjCCategoryImplDecl>(I->second);
2536  return nullptr;
2537 }
2538 
2539 /// Set the implementation of ObjCInterfaceDecl.
2541  ObjCImplementationDecl *ImplD) {
2542  assert(IFaceD && ImplD && "Passed null params");
2543  ObjCImpls[IFaceD] = ImplD;
2544 }
2545 
2546 /// Set the implementation of ObjCCategoryDecl.
2548  ObjCCategoryImplDecl *ImplD) {
2549  assert(CatD && ImplD && "Passed null params");
2550  ObjCImpls[CatD] = ImplD;
2551 }
2552 
2553 const ObjCMethodDecl *
2555  return ObjCMethodRedecls.lookup(MD);
2556 }
2557 
2559  const ObjCMethodDecl *Redecl) {
2560  assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
2561  ObjCMethodRedecls[MD] = Redecl;
2562 }
2563 
2565  const NamedDecl *ND) const {
2566  if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
2567  return ID;
2568  if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
2569  return CD->getClassInterface();
2570  if (const auto *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
2571  return IMD->getClassInterface();
2572 
2573  return nullptr;
2574 }
2575 
2576 /// Get the copy initialization expression of VarDecl, or nullptr if
2577 /// none exists.
2580  assert(VD && "Passed null params");
2581  assert(VD->hasAttr<BlocksAttr>() &&
2582  "getBlockVarCopyInits - not __block var");
2583  auto I = BlockVarCopyInits.find(VD);
2584  if (I != BlockVarCopyInits.end())
2585  return I->second;
2586  return {nullptr, false};
2587 }
2588 
2589 /// Set the copy initialization expression of a block var decl.
2591  bool CanThrow) {
2592  assert(VD && CopyExpr && "Passed null params");
2593  assert(VD->hasAttr<BlocksAttr>() &&
2594  "setBlockVarCopyInits - not __block var");
2595  BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow);
2596 }
2597 
2599  unsigned DataSize) const {
2600  if (!DataSize)
2601  DataSize = TypeLoc::getFullDataSizeForType(T);
2602  else
2603  assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
2604  "incorrect data size provided to CreateTypeSourceInfo!");
2605 
2606  auto *TInfo =
2607  (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
2608  new (TInfo) TypeSourceInfo(T);
2609  return TInfo;
2610 }
2611 
2613  SourceLocation L) const {
2615  DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
2616  return DI;
2617 }
2618 
2619 const ASTRecordLayout &
2621  return getObjCLayout(D, nullptr);
2622 }
2623 
2624 const ASTRecordLayout &
2626  const ObjCImplementationDecl *D) const {
2627  return getObjCLayout(D->getClassInterface(), D);
2628 }
2629 
2630 //===----------------------------------------------------------------------===//
2631 // Type creation/memoization methods
2632 //===----------------------------------------------------------------------===//
2633 
2634 QualType
2635 ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2636  unsigned fastQuals = quals.getFastQualifiers();
2637  quals.removeFastQualifiers();
2638 
2639  // Check if we've already instantiated this type.
2640  llvm::FoldingSetNodeID ID;
2641  ExtQuals::Profile(ID, baseType, quals);
2642  void *insertPos = nullptr;
2643  if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2644  assert(eq->getQualifiers() == quals);
2645  return QualType(eq, fastQuals);
2646  }
2647 
2648  // If the base type is not canonical, make the appropriate canonical type.
2649  QualType canon;
2650  if (!baseType->isCanonicalUnqualified()) {
2651  SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
2652  canonSplit.Quals.addConsistentQualifiers(quals);
2653  canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
2654 
2655  // Re-find the insert position.
2656  (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2657  }
2658 
2659  auto *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2660  ExtQualNodes.InsertNode(eq, insertPos);
2661  return QualType(eq, fastQuals);
2662 }
2663 
2665  LangAS AddressSpace) const {
2666  QualType CanT = getCanonicalType(T);
2667  if (CanT.getAddressSpace() == AddressSpace)
2668  return T;
2669 
2670  // If we are composing extended qualifiers together, merge together
2671  // into one ExtQuals node.
2672  QualifierCollector Quals;
2673  const Type *TypeNode = Quals.strip(T);
2674 
2675  // If this type already has an address space specified, it cannot get
2676  // another one.
2677  assert(!Quals.hasAddressSpace() &&
2678  "Type cannot be in multiple addr spaces!");
2679  Quals.addAddressSpace(AddressSpace);
2680 
2681  return getExtQualType(TypeNode, Quals);
2682 }
2683 
2685  // If we are composing extended qualifiers together, merge together
2686  // into one ExtQuals node.
2687  QualifierCollector Quals;
2688  const Type *TypeNode = Quals.strip(T);
2689 
2690  // If the qualifier doesn't have an address space just return it.
2691  if (!Quals.hasAddressSpace())
2692  return T;
2693 
2694  Quals.removeAddressSpace();
2695 
2696  // Removal of the address space can mean there are no longer any
2697  // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts)
2698  // or required.
2699  if (Quals.hasNonFastQualifiers())
2700  return getExtQualType(TypeNode, Quals);
2701  else
2702  return QualType(TypeNode, Quals.getFastQualifiers());
2703 }
2704 
2706  Qualifiers::GC GCAttr) const {
2707  QualType CanT = getCanonicalType(T);
2708  if (CanT.getObjCGCAttr() == GCAttr)
2709  return T;
2710 
2711  if (const auto *ptr = T->getAs<PointerType>()) {
2712  QualType Pointee = ptr->getPointeeType();
2713  if (Pointee->isAnyPointerType()) {
2714  QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2715  return getPointerType(ResultType);
2716  }
2717  }
2718 
2719  // If we are composing extended qualifiers together, merge together
2720  // into one ExtQuals node.
2721  QualifierCollector Quals;
2722  const Type *TypeNode = Quals.strip(T);
2723 
2724  // If this type already has an ObjCGC specified, it cannot get
2725  // another one.
2726  assert(!Quals.hasObjCGCAttr() &&
2727  "Type cannot have multiple ObjCGCs!");
2728  Quals.addObjCGCAttr(GCAttr);
2729 
2730  return getExtQualType(TypeNode, Quals);
2731 }
2732 
2734  FunctionType::ExtInfo Info) {
2735  if (T->getExtInfo() == Info)
2736  return T;
2737 
2738  QualType Result;
2739  if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
2740  Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
2741  } else {
2742  const auto *FPT = cast<FunctionProtoType>(T);
2743  FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2744  EPI.ExtInfo = Info;
2745  Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
2746  }
2747 
2748  return cast<FunctionType>(Result.getTypePtr());
2749 }
2750 
2752  QualType ResultType) {
2753  FD = FD->getMostRecentDecl();
2754  while (true) {
2755  const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
2756  FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2757  FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
2758  if (FunctionDecl *Next = FD->getPreviousDecl())
2759  FD = Next;
2760  else
2761  break;
2762  }
2764  L->DeducedReturnType(FD, ResultType);
2765 }
2766 
2767 /// Get a function type and produce the equivalent function type with the
2768 /// specified exception specification. Type sugar that can be present on a
2769 /// declaration of a function with an exception specification is permitted
2770 /// and preserved. Other type sugar (for instance, typedefs) is not.
2773  // Might have some parens.
2774  if (const auto *PT = dyn_cast<ParenType>(Orig))
2775  return getParenType(
2776  getFunctionTypeWithExceptionSpec(PT->getInnerType(), ESI));
2777 
2778  // Might be wrapped in a macro qualified type.
2779  if (const auto *MQT = dyn_cast<MacroQualifiedType>(Orig))
2780  return getMacroQualifiedType(
2781  getFunctionTypeWithExceptionSpec(MQT->getUnderlyingType(), ESI),
2782  MQT->getMacroIdentifier());
2783 
2784  // Might have a calling-convention attribute.
2785  if (const auto *AT = dyn_cast<AttributedType>(Orig))
2786  return getAttributedType(
2787  AT->getAttrKind(),
2788  getFunctionTypeWithExceptionSpec(AT->getModifiedType(), ESI),
2789  getFunctionTypeWithExceptionSpec(AT->getEquivalentType(), ESI));
2790 
2791  // Anything else must be a function type. Rebuild it with the new exception
2792  // specification.
2793  const auto *Proto = Orig->getAs<FunctionProtoType>();
2794  return getFunctionType(
2795  Proto->getReturnType(), Proto->getParamTypes(),
2796  Proto->getExtProtoInfo().withExceptionSpec(ESI));
2797 }
2798 
2800  QualType U) {
2801  return hasSameType(T, U) ||
2802  (getLangOpts().CPlusPlus17 &&
2805 }
2806 
2809  bool AsWritten) {
2810  // Update the type.
2811  QualType Updated =
2813  FD->setType(Updated);
2814 
2815  if (!AsWritten)
2816  return;
2817 
2818  // Update the type in the type source information too.
2819  if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
2820  // If the type and the type-as-written differ, we may need to update
2821  // the type-as-written too.
2822  if (TSInfo->getType() != FD->getType())
2823  Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI);
2824 
2825  // FIXME: When we get proper type location information for exceptions,
2826  // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
2827  // up the TypeSourceInfo;
2828  assert(TypeLoc::getFullDataSizeForType(Updated) ==
2829  TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
2830  "TypeLoc size mismatch from updating exception specification");
2831  TSInfo->overrideType(Updated);
2832  }
2833 }
2834 
2835 /// getComplexType - Return the uniqued reference to the type for a complex
2836 /// number with the specified element type.
2838  // Unique pointers, to guarantee there is only one pointer of a particular
2839  // structure.
2840  llvm::FoldingSetNodeID ID;
2841  ComplexType::Profile(ID, T);
2842 
2843  void *InsertPos = nullptr;
2844  if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2845  return QualType(CT, 0);
2846 
2847  // If the pointee type isn't canonical, this won't be a canonical type either,
2848  // so fill in the canonical type field.
2849  QualType Canonical;
2850  if (!T.isCanonical()) {
2851  Canonical = getComplexType(getCanonicalType(T));
2852 
2853  // Get the new insert position for the node we care about.
2854  ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
2855  assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2856  }
2857  auto *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
2858  Types.push_back(New);
2859  ComplexTypes.InsertNode(New, InsertPos);
2860  return QualType(New, 0);
2861 }
2862 
2863 /// getPointerType - Return the uniqued reference to the type for a pointer to
2864 /// the specified type.
2866  // Unique pointers, to guarantee there is only one pointer of a particular
2867  // structure.
2868  llvm::FoldingSetNodeID ID;
2869  PointerType::Profile(ID, T);
2870 
2871  void *InsertPos = nullptr;
2872  if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2873  return QualType(PT, 0);
2874 
2875  // If the pointee type isn't canonical, this won't be a canonical type either,
2876  // so fill in the canonical type field.
2877  QualType Canonical;
2878  if (!T.isCanonical()) {
2879  Canonical = getPointerType(getCanonicalType(T));
2880 
2881  // Get the new insert position for the node we care about.
2882  PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2883  assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2884  }
2885  auto *New = new (*this, TypeAlignment) PointerType(T, Canonical);
2886  Types.push_back(New);
2887  PointerTypes.InsertNode(New, InsertPos);
2888  return QualType(New, 0);
2889 }
2890 
2892  llvm::FoldingSetNodeID ID;
2893  AdjustedType::Profile(ID, Orig, New);
2894  void *InsertPos = nullptr;
2895  AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2896  if (AT)
2897  return QualType(AT, 0);
2898 
2899  QualType Canonical = getCanonicalType(New);
2900 
2901  // Get the new insert position for the node we care about.
2902  AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2903  assert(!AT && "Shouldn't be in the map!");
2904 
2905  AT = new (*this, TypeAlignment)
2906  AdjustedType(Type::Adjusted, Orig, New, Canonical);
2907  Types.push_back(AT);
2908  AdjustedTypes.InsertNode(AT, InsertPos);
2909  return QualType(AT, 0);
2910 }
2911 
2913  assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2914 
2915  QualType Decayed;
2916 
2917  // C99 6.7.5.3p7:
2918  // A declaration of a parameter as "array of type" shall be
2919  // adjusted to "qualified pointer to type", where the type
2920  // qualifiers (if any) are those specified within the [ and ] of
2921  // the array type derivation.
2922  if (T->isArrayType())
2923  Decayed = getArrayDecayedType(T);
2924 
2925  // C99 6.7.5.3p8:
2926  // A declaration of a parameter as "function returning type"
2927  // shall be adjusted to "pointer to function returning type", as
2928  // in 6.3.2.1.
2929  if (T->isFunctionType())
2930  Decayed = getPointerType(T);
2931 
2932  llvm::FoldingSetNodeID ID;
2933  AdjustedType::Profile(ID, T, Decayed);
2934  void *InsertPos = nullptr;
2935  AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2936  if (AT)
2937  return QualType(AT, 0);
2938 
2939  QualType Canonical = getCanonicalType(Decayed);
2940 
2941  // Get the new insert position for the node we care about.
2942  AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2943  assert(!AT && "Shouldn't be in the map!");
2944 
2945  AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2946  Types.push_back(AT);
2947  AdjustedTypes.InsertNode(AT, InsertPos);
2948  return QualType(AT, 0);
2949 }
2950 
2951 /// getBlockPointerType - Return the uniqued reference to the type for
2952 /// a pointer to the specified block.
2954  assert(T->isFunctionType() && "block of function types only");
2955  // Unique pointers, to guarantee there is only one block of a particular
2956  // structure.
2957  llvm::FoldingSetNodeID ID;
2959 
2960  void *InsertPos = nullptr;
2961  if (BlockPointerType *PT =
2962  BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2963  return QualType(PT, 0);
2964 
2965  // If the block pointee type isn't canonical, this won't be a canonical
2966  // type either so fill in the canonical type field.
2967  QualType Canonical;
2968  if (!T.isCanonical()) {
2969  Canonical = getBlockPointerType(getCanonicalType(T));
2970 
2971  // Get the new insert position for the node we care about.
2972  BlockPointerType *NewIP =
2973  BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2974  assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2975  }
2976  auto *New = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
2977  Types.push_back(New);
2978  BlockPointerTypes.InsertNode(New, InsertPos);
2979  return QualType(New, 0);
2980 }
2981 
2982 /// getLValueReferenceType - Return the uniqued reference to the type for an
2983 /// lvalue reference to the specified type.
2984 QualType
2985 ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
2986  assert(getCanonicalType(T) != OverloadTy &&
2987  "Unresolved overloaded function type");
2988 
2989  // Unique pointers, to guarantee there is only one pointer of a particular
2990  // structure.
2991  llvm::FoldingSetNodeID ID;
2992  ReferenceType::Profile(ID, T, SpelledAsLValue);
2993 
2994  void *InsertPos = nullptr;
2995  if (LValueReferenceType *RT =
2996  LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2997  return QualType(RT, 0);
2998 
2999  const auto *InnerRef = T->getAs<ReferenceType>();
3000 
3001  // If the referencee type isn't canonical, this won't be a canonical type
3002  // either, so fill in the canonical type field.
3003  QualType Canonical;
3004  if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
3005  QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
3006  Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
3007 
3008  // Get the new insert position for the node we care about.
3009  LValueReferenceType *NewIP =
3010  LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
3011  assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3012  }
3013 
3014  auto *New = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
3015  SpelledAsLValue);
3016  Types.push_back(New);
3017  LValueReferenceTypes.InsertNode(New, InsertPos);
3018 
3019  return QualType(New, 0);
3020 }
3021 
3022 /// getRValueReferenceType - Return the uniqued reference to the type for an
3023 /// rvalue reference to the specified type.
3025  // Unique pointers, to guarantee there is only one pointer of a particular
3026  // structure.
3027  llvm::FoldingSetNodeID ID;
3028  ReferenceType::Profile(ID, T, false);
3029 
3030  void *InsertPos = nullptr;
3031  if (RValueReferenceType *RT =
3032  RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
3033  return QualType(RT, 0);
3034 
3035  const auto *InnerRef = T->getAs<ReferenceType>();
3036 
3037  // If the referencee type isn't canonical, this won't be a canonical type
3038  // either, so fill in the canonical type field.
3039  QualType Canonical;
3040  if (InnerRef || !T.isCanonical()) {
3041  QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
3042  Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
3043 
3044  // Get the new insert position for the node we care about.
3045  RValueReferenceType *NewIP =
3046  RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
3047  assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3048  }
3049 
3050  auto *New = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
3051  Types.push_back(New);
3052  RValueReferenceTypes.InsertNode(New, InsertPos);
3053  return QualType(New, 0);
3054 }
3055 
3056 /// getMemberPointerType - Return the uniqued reference to the type for a
3057 /// member pointer to the specified type, in the specified class.
3059  // Unique pointers, to guarantee there is only one pointer of a particular
3060  // structure.
3061  llvm::FoldingSetNodeID ID;
3062  MemberPointerType::Profile(ID, T, Cls);
3063 
3064  void *InsertPos = nullptr;
3065  if (MemberPointerType *PT =
3066  MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3067  return QualType(PT, 0);
3068 
3069  // If the pointee or class type isn't canonical, this won't be a canonical
3070  // type either, so fill in the canonical type field.
3071  QualType Canonical;
3072  if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
3074 
3075  // Get the new insert position for the node we care about.
3076  MemberPointerType *NewIP =
3077  MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3078  assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3079  }
3080  auto *New = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
3081  Types.push_back(New);
3082  MemberPointerTypes.InsertNode(New, InsertPos);
3083  return QualType(New, 0);
3084 }
3085 
3086 /// getConstantArrayType - Return the unique reference to the type for an
3087 /// array of the specified element type.
3089  const llvm::APInt &ArySizeIn,
3091  unsigned IndexTypeQuals) const {
3092  assert((EltTy->isDependentType() ||
3093  EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
3094  "Constant array of VLAs is illegal!");
3095 
3096  // Convert the array size into a canonical width matching the pointer size for
3097  // the target.
3098  llvm::APInt ArySize(ArySizeIn);
3099  ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth());
3100 
3101  llvm::FoldingSetNodeID ID;
3102  ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
3103 
3104  void *InsertPos = nullptr;
3105  if (ConstantArrayType *ATP =
3106  ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
3107  return QualType(ATP, 0);
3108 
3109  // If the element type isn't canonical or has qualifiers, this won't
3110  // be a canonical type either, so fill in the canonical type field.
3111  QualType Canon;
3112  if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
3113  SplitQualType canonSplit = getCanonicalType(EltTy).split();
3114  Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
3115  ASM, IndexTypeQuals);
3116  Canon = getQualifiedType(Canon, canonSplit.Quals);
3117 
3118  // Get the new insert position for the node we care about.
3119  ConstantArrayType *NewIP =
3120  ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
3121  assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3122  }
3123 
3124  auto *New = new (*this,TypeAlignment)
3125  ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
3126  ConstantArrayTypes.InsertNode(New, InsertPos);
3127  Types.push_back(New);
3128  return QualType(New, 0);
3129 }
3130 
3131 /// getVariableArrayDecayedType - Turns the given type, which may be
3132 /// variably-modified, into the corresponding type with all the known
3133 /// sizes replaced with [*].
3135  // Vastly most common case.
3136  if (!type->isVariablyModifiedType()) return type;
3137 
3138  QualType result;
3139 
3140  SplitQualType split = type.getSplitDesugaredType();
3141  const Type *ty = split.Ty;
3142  switch (ty->getTypeClass()) {
3143 #define TYPE(Class, Base)
3144 #define ABSTRACT_TYPE(Class, Base)
3145 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3146 #include "clang/AST/TypeNodes.def"
3147  llvm_unreachable("didn't desugar past all non-canonical types?");
3148 
3149  // These types should never be variably-modified.
3150  case Type::Builtin:
3151  case Type::Complex:
3152  case Type::Vector:
3153  case Type::DependentVector:
3154  case Type::ExtVector:
3155  case Type::DependentSizedExtVector:
3156  case Type::DependentAddressSpace:
3157  case Type::ObjCObject:
3158  case Type::ObjCInterface:
3159  case Type::ObjCObjectPointer:
3160  case Type::Record:
3161  case Type::Enum:
3162  case Type::UnresolvedUsing:
3163  case Type::TypeOfExpr:
3164  case Type::TypeOf:
3165  case Type::Decltype:
3166  case Type::UnaryTransform:
3167  case Type::DependentName:
3168  case Type::InjectedClassName:
3169  case Type::TemplateSpecialization:
3170  case Type::DependentTemplateSpecialization:
3171  case Type::TemplateTypeParm:
3172  case Type::SubstTemplateTypeParmPack:
3173  case Type::Auto:
3174  case Type::DeducedTemplateSpecialization:
3175  case Type::PackExpansion:
3176  llvm_unreachable("type should never be variably-modified");
3177 
3178  // These types can be variably-modified but should never need to
3179  // further decay.
3180  case Type::FunctionNoProto:
3181  case Type::FunctionProto:
3182  case Type::BlockPointer:
3183  case Type::MemberPointer:
3184  case Type::Pipe:
3185  return type;
3186 
3187  // These types can be variably-modified. All these modifications
3188  // preserve structure except as noted by comments.
3189  // TODO: if we ever care about optimizing VLAs, there are no-op
3190  // optimizations available here.
3191  case Type::Pointer:
3193  cast<PointerType>(ty)->getPointeeType()));
3194  break;
3195 
3196  case Type::LValueReference: {
3197  const auto *lv = cast<LValueReferenceType>(ty);
3198  result = getLValueReferenceType(
3199  getVariableArrayDecayedType(lv->getPointeeType()),
3200  lv->isSpelledAsLValue());
3201  break;
3202  }
3203 
3204  case Type::RValueReference: {
3205  const auto *lv = cast<RValueReferenceType>(ty);
3206  result = getRValueReferenceType(
3207  getVariableArrayDecayedType(lv->getPointeeType()));
3208  break;
3209  }
3210 
3211  case Type::Atomic: {
3212  const auto *at = cast<AtomicType>(ty);
3213  result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
3214  break;
3215  }
3216 
3217  case Type::ConstantArray: {
3218  const auto *cat = cast<ConstantArrayType>(ty);
3219  result = getConstantArrayType(
3220  getVariableArrayDecayedType(cat->getElementType()),
3221  cat->getSize(),
3222  cat->getSizeModifier(),
3223  cat->getIndexTypeCVRQualifiers());
3224  break;
3225  }
3226 
3227  case Type::DependentSizedArray: {
3228  const auto *dat = cast<DependentSizedArrayType>(ty);
3229  result = getDependentSizedArrayType(
3230  getVariableArrayDecayedType(dat->getElementType()),
3231  dat->getSizeExpr(),
3232  dat->getSizeModifier(),
3233  dat->getIndexTypeCVRQualifiers(),
3234  dat->getBracketsRange());
3235  break;
3236  }
3237 
3238  // Turn incomplete types into [*] types.
3239  case Type::IncompleteArray: {
3240  const auto *iat = cast<IncompleteArrayType>(ty);
3241  result = getVariableArrayType(
3242  getVariableArrayDecayedType(iat->getElementType()),
3243  /*size*/ nullptr,
3245  iat->getIndexTypeCVRQualifiers(),
3246  SourceRange());
3247  break;
3248  }
3249 
3250  // Turn VLA types into [*] types.
3251  case Type::VariableArray: {
3252  const auto *vat = cast<VariableArrayType>(ty);
3253  result = getVariableArrayType(
3254  getVariableArrayDecayedType(vat->getElementType()),
3255  /*size*/ nullptr,
3257  vat->getIndexTypeCVRQualifiers(),
3258  vat->getBracketsRange());
3259  break;
3260  }
3261  }
3262 
3263  // Apply the top-level qualifiers from the original.
3264  return getQualifiedType(result, split.Quals);
3265 }
3266 
3267 /// getVariableArrayType - Returns a non-unique reference to the type for a
3268 /// variable array of the specified element type.
3270  Expr *NumElts,
3272  unsigned IndexTypeQuals,
3273  SourceRange Brackets) const {
3274  // Since we don't unique expressions, it isn't possible to unique VLA's
3275  // that have an expression provided for their size.
3276  QualType Canon;
3277 
3278  // Be sure to pull qualifiers off the element type.
3279  if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
3280  SplitQualType canonSplit = getCanonicalType(EltTy).split();
3281  Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
3282  IndexTypeQuals, Brackets);
3283  Canon = getQualifiedType(Canon, canonSplit.Quals);
3284  }
3285 
3286  auto *New = new (*this, TypeAlignment)
3287  VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
3288 
3289  VariableArrayTypes.push_back(New);
3290  Types.push_back(New);
3291  return QualType(New, 0);
3292 }
3293 
3294 /// getDependentSizedArrayType - Returns a non-unique reference to
3295 /// the type for a dependently-sized array of the specified element
3296 /// type.
3298  Expr *numElements,
3300  unsigned elementTypeQuals,
3301  SourceRange brackets) const {
3302  assert((!numElements || numElements->isTypeDependent() ||
3303  numElements->isValueDependent()) &&
3304  "Size must be type- or value-dependent!");
3305 
3306  // Dependently-sized array types that do not have a specified number
3307  // of elements will have their sizes deduced from a dependent
3308  // initializer. We do no canonicalization here at all, which is okay
3309  // because they can't be used in most locations.
3310  if (!numElements) {
3311  auto *newType
3312  = new (*this, TypeAlignment)
3313  DependentSizedArrayType(*this, elementType, QualType(),
3314  numElements, ASM, elementTypeQuals,
3315  brackets);
3316  Types.push_back(newType);
3317  return QualType(newType, 0);
3318  }
3319 
3320  // Otherwise, we actually build a new type every time, but we
3321  // also build a canonical type.
3322 
3323  SplitQualType canonElementType = getCanonicalType(elementType).split();
3324 
3325  void *insertPos = nullptr;
3326  llvm::FoldingSetNodeID ID;
3328  QualType(canonElementType.Ty, 0),
3329  ASM, elementTypeQuals, numElements);
3330 
3331  // Look for an existing type with these properties.
3332  DependentSizedArrayType *canonTy =
3333  DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
3334 
3335  // If we don't have one, build one.
3336  if (!canonTy) {
3337  canonTy = new (*this, TypeAlignment)
3338  DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
3339  QualType(), numElements, ASM, elementTypeQuals,
3340  brackets);
3341  DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
3342  Types.push_back(canonTy);
3343  }
3344 
3345  // Apply qualifiers from the element type to the array.
3346  QualType canon = getQualifiedType(QualType(canonTy,0),
3347  canonElementType.Quals);
3348 
3349  // If we didn't need extra canonicalization for the element type or the size
3350  // expression, then just use that as our result.
3351  if (QualType(canonElementType.Ty, 0) == elementType &&
3352  canonTy->getSizeExpr() == numElements)
3353  return canon;
3354 
3355  // Otherwise, we need to build a type which follows the spelling
3356  // of the element type.
3357  auto *sugaredType
3358  = new (*this, TypeAlignment)
3359  DependentSizedArrayType(*this, elementType, canon, numElements,
3360  ASM, elementTypeQuals, brackets);
3361  Types.push_back(sugaredType);
3362  return QualType(sugaredType, 0);
3363 }
3364 
3367  unsigned elementTypeQuals) const {
3368  llvm::FoldingSetNodeID ID;
3369  IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
3370 
3371  void *insertPos = nullptr;
3372  if (IncompleteArrayType *iat =
3373  IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
3374  return QualType(iat, 0);
3375 
3376  // If the element type isn't canonical, this won't be a canonical type
3377  // either, so fill in the canonical type field. We also have to pull
3378  // qualifiers off the element type.
3379  QualType canon;
3380 
3381  if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
3382  SplitQualType canonSplit = getCanonicalType(elementType).split();
3383  canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
3384  ASM, elementTypeQuals);
3385  canon = getQualifiedType(canon, canonSplit.Quals);
3386 
3387  // Get the new insert position for the node we care about.
3388  IncompleteArrayType *existing =
3389  IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
3390  assert(!existing && "Shouldn't be in the map!"); (void) existing;
3391  }
3392 
3393  auto *newType = new (*this, TypeAlignment)
3394  IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
3395 
3396  IncompleteArrayTypes.InsertNode(newType, insertPos);
3397  Types.push_back(newType);
3398  return QualType(newType, 0);
3399 }
3400 
3401 /// getVectorType - Return the unique reference to a vector type of
3402 /// the specified element type and size. VectorType must be a built-in type.
3403 QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
3404  VectorType::VectorKind VecKind) const {
3405  assert(vecType->isBuiltinType());
3406 
3407  // Check if we've already instantiated a vector of this type.
3408  llvm::FoldingSetNodeID ID;
3409  VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
3410 
3411  void *InsertPos = nullptr;
3412  if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3413  return QualType(VTP, 0);
3414 
3415  // If the element type isn't canonical, this won't be a canonical type either,
3416  // so fill in the canonical type field.
3417  QualType Canonical;
3418  if (!vecType.isCanonical()) {
3419  Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
3420 
3421  // Get the new insert position for the node we care about.
3422  VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3423  assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3424  }
3425  auto *New = new (*this, TypeAlignment)
3426  VectorType(vecType, NumElts, Canonical, VecKind);
3427  VectorTypes.InsertNode(New, InsertPos);
3428  Types.push_back(New);
3429  return QualType(New, 0);
3430 }
3431 
3432 QualType
3434  SourceLocation AttrLoc,
3435  VectorType::VectorKind VecKind) const {
3436  llvm::FoldingSetNodeID ID;
3437  DependentVectorType::Profile(ID, *this, getCanonicalType(VecType), SizeExpr,
3438  VecKind);
3439  void *InsertPos = nullptr;
3440  DependentVectorType *Canon =
3441  DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3442  DependentVectorType *New;
3443 
3444  if (Canon) {
3445  New = new (*this, TypeAlignment) DependentVectorType(
3446  *this, VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind);
3447  } else {
3448  QualType CanonVecTy = getCanonicalType(VecType);
3449  if (CanonVecTy == VecType) {
3450  New = new (*this, TypeAlignment) DependentVectorType(
3451  *this, VecType, QualType(), SizeExpr, AttrLoc, VecKind);
3452 
3453  DependentVectorType *CanonCheck =
3454  DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3455  assert(!CanonCheck &&
3456  "Dependent-sized vector_size canonical type broken");
3457  (void)CanonCheck;
3458  DependentVectorTypes.InsertNode(New, InsertPos);
3459  } else {
3460  QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
3461  SourceLocation());
3462  New = new (*this, TypeAlignment) DependentVectorType(
3463  *this, VecType, Canon, SizeExpr, AttrLoc, VecKind);
3464  }
3465  }
3466 
3467  Types.push_back(New);
3468  return QualType(New, 0);
3469 }
3470 
3471 /// getExtVectorType - Return the unique reference to an extended vector type of
3472 /// the specified element type and size. VectorType must be a built-in type.
3473 QualType
3474 ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
3475  assert(vecType->isBuiltinType() || vecType->isDependentType());
3476 
3477  // Check if we've already instantiated a vector of this type.
3478  llvm::FoldingSetNodeID ID;
3479  VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
3481  void *InsertPos = nullptr;
3482  if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3483  return QualType(VTP, 0);
3484 
3485  // If the element type isn't canonical, this won't be a canonical type either,
3486  // so fill in the canonical type field.
3487  QualType Canonical;
3488  if (!vecType.isCanonical()) {
3489  Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
3490 
3491  // Get the new insert position for the node we care about.
3492  VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3493  assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3494  }
3495  auto *New = new (*this, TypeAlignment)
3496  ExtVectorType(vecType, NumElts, Canonical);
3497  VectorTypes.InsertNode(New, InsertPos);
3498  Types.push_back(New);
3499  return QualType(New, 0);
3500 }
3501 
3502 QualType
3504  Expr *SizeExpr,
3505  SourceLocation AttrLoc) const {
3506  llvm::FoldingSetNodeID ID;
3508  SizeExpr);
3509 
3510  void *InsertPos = nullptr;
3512  = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3514  if (Canon) {
3515  // We already have a canonical version of this array type; use it as
3516  // the canonical type for a newly-built type.
3517  New = new (*this, TypeAlignment)
3518  DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
3519  SizeExpr, AttrLoc);
3520  } else {
3521  QualType CanonVecTy = getCanonicalType(vecType);
3522  if (CanonVecTy == vecType) {
3523  New = new (*this, TypeAlignment)
3524  DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
3525  AttrLoc);
3526 
3527  DependentSizedExtVectorType *CanonCheck
3528  = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3529  assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
3530  (void)CanonCheck;
3531  DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
3532  } else {
3533  QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
3534  SourceLocation());
3535  New = new (*this, TypeAlignment)
3536  DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
3537  }
3538  }
3539 
3540  Types.push_back(New);
3541  return QualType(New, 0);
3542 }
3543 
3545  Expr *AddrSpaceExpr,
3546  SourceLocation AttrLoc) const {
3547  assert(AddrSpaceExpr->isInstantiationDependent());
3548 
3549  QualType canonPointeeType = getCanonicalType(PointeeType);
3550 
3551  void *insertPos = nullptr;
3552  llvm::FoldingSetNodeID ID;
3553  DependentAddressSpaceType::Profile(ID, *this, canonPointeeType,
3554  AddrSpaceExpr);
3555 
3556  DependentAddressSpaceType *canonTy =
3557  DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos);
3558 
3559  if (!canonTy) {
3560  canonTy = new (*this, TypeAlignment)
3561  DependentAddressSpaceType(*this, canonPointeeType,
3562  QualType(), AddrSpaceExpr, AttrLoc);
3563  DependentAddressSpaceTypes.InsertNode(canonTy, insertPos);
3564  Types.push_back(canonTy);
3565  }
3566 
3567  if (canonPointeeType == PointeeType &&
3568  canonTy->getAddrSpaceExpr() == AddrSpaceExpr)
3569  return QualType(canonTy, 0);
3570 
3571  auto *sugaredType
3572  = new (*this, TypeAlignment)
3573  DependentAddressSpaceType(*this, PointeeType, QualType(canonTy, 0),
3574  AddrSpaceExpr, AttrLoc);
3575  Types.push_back(sugaredType);
3576  return QualType(sugaredType, 0);
3577 }
3578 
3579 /// Determine whether \p T is canonical as the result type of a function.
3581  return T.isCanonical() &&
3584 }
3585 
3586 /// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
3587 QualType
3589  const FunctionType::ExtInfo &Info) const {
3590  // Unique functions, to guarantee there is only one function of a particular
3591  // structure.
3592  llvm::FoldingSetNodeID ID;
3593  FunctionNoProtoType::Profile(ID, ResultTy, Info);
3594 
3595  void *InsertPos = nullptr;
3596  if (FunctionNoProtoType *FT =
3597  FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
3598  return QualType(FT, 0);
3599 
3600  QualType Canonical;
3601  if (!isCanonicalResultType(ResultTy)) {
3602  Canonical =
3604 
3605  // Get the new insert position for the node we care about.
3606  FunctionNoProtoType *NewIP =
3607  FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
3608  assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3609  }
3610 
3611  auto *New = new (*this, TypeAlignment)
3612  FunctionNoProtoType(ResultTy, Canonical, Info);
3613  Types.push_back(New);
3614  FunctionNoProtoTypes.InsertNode(New, InsertPos);
3615  return QualType(New, 0);
3616 }
3617 
3620  CanQualType CanResultType = getCanonicalType(ResultType);
3621 
3622  // Canonical result types do not have ARC lifetime qualifiers.
3623  if (CanResultType.getQualifiers().hasObjCLifetime()) {
3624  Qualifiers Qs = CanResultType.getQualifiers();
3625  Qs.removeObjCLifetime();
3627  getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
3628  }
3629 
3630  return CanResultType;
3631 }
3632 
3634  const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
3635  if (ESI.Type == EST_None)
3636  return true;
3637  if (!NoexceptInType)
3638  return false;
3639 
3640  // C++17 onwards: exception specification is part of the type, as a simple
3641  // boolean "can this function type throw".
3642  if (ESI.Type == EST_BasicNoexcept)
3643  return true;
3644 
3645  // A noexcept(expr) specification is (possibly) canonical if expr is
3646  // value-dependent.
3647  if (ESI.Type == EST_DependentNoexcept)
3648  return true;
3649 
3650  // A dynamic exception specification is canonical if it only contains pack
3651  // expansions (so we can't tell whether it's non-throwing) and all its
3652  // contained types are canonical.
3653  if (ESI.Type == EST_Dynamic) {
3654  bool AnyPackExpansions = false;
3655  for (QualType ET : ESI.Exceptions) {
3656  if (!ET.isCanonical())
3657  return false;
3658  if (ET->getAs<PackExpansionType>())
3659  AnyPackExpansions = true;
3660  }
3661  return AnyPackExpansions;
3662  }
3663 
3664  return false;
3665 }
3666 
3667 QualType ASTContext::getFunctionTypeInternal(
3668  QualType ResultTy, ArrayRef<QualType> ArgArray,
3669  const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
3670  size_t NumArgs = ArgArray.size();
3671 
3672  // Unique functions, to guarantee there is only one function of a particular
3673  // structure.
3674  llvm::FoldingSetNodeID ID;
3675  FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
3676  *this, true);
3677 
3678  QualType Canonical;
3679  bool Unique = false;
3680 
3681  void *InsertPos = nullptr;
3682  if (FunctionProtoType *FPT =
3683  FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
3684  QualType Existing = QualType(FPT, 0);
3685 
3686  // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
3687  // it so long as our exception specification doesn't contain a dependent
3688  // noexcept expression, or we're just looking for a canonical type.
3689  // Otherwise, we're going to need to create a type
3690  // sugar node to hold the concrete expression.
3691  if (OnlyWantCanonical || !isComputedNoexcept(EPI.ExceptionSpec.Type) ||
3692  EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
3693  return Existing;
3694 
3695  // We need a new type sugar node for this one, to hold the new noexcept
3696  // expression. We do no canonicalization here, but that's OK since we don't
3697  // expect to see the same noexcept expression much more than once.
3698  Canonical = getCanonicalType(Existing);
3699  Unique = true;
3700  }
3701 
3702  bool NoexceptInType = getLangOpts().CPlusPlus17;
3703  bool IsCanonicalExceptionSpec =
3704  isCanonicalExceptionSpecification(EPI.ExceptionSpec, NoexceptInType);
3705 
3706  // Determine whether the type being created is already canonical or not.
3707  bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
3708  isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
3709  for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
3710  if (!ArgArray[i].isCanonicalAsParam())
3711  isCanonical = false;
3712 
3713  if (OnlyWantCanonical)
3714  assert(isCanonical &&
3715  "given non-canonical parameters constructing canonical type");
3716 
3717  // If this type isn't canonical, get the canonical version of it if we don't
3718  // already have it. The exception spec is only partially part of the
3719  // canonical type, and only in C++17 onwards.
3720  if (!isCanonical && Canonical.isNull()) {
3721  SmallVector<QualType, 16> CanonicalArgs;
3722  CanonicalArgs.reserve(NumArgs);
3723  for (unsigned i = 0; i != NumArgs; ++i)
3724  CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
3725 
3726  llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
3727  FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
3728  CanonicalEPI.HasTrailingReturn = false;
3729 
3730  if (IsCanonicalExceptionSpec) {
3731  // Exception spec is already OK.
3732  } else if (NoexceptInType) {
3733  switch (EPI.ExceptionSpec.Type) {
3735  // We don't know yet. It shouldn't matter what we pick here; no-one
3736  // should ever look at this.
3737  LLVM_FALLTHROUGH;
3738  case EST_None: case EST_MSAny: case EST_NoexceptFalse:
3739  CanonicalEPI.ExceptionSpec.Type = EST_None;
3740  break;
3741 
3742  // A dynamic exception specification is almost always "not noexcept",
3743  // with the exception that a pack expansion might expand to no types.
3744  case EST_Dynamic: {
3745  bool AnyPacks = false;
3746  for (QualType ET : EPI.ExceptionSpec.Exceptions) {
3747  if (ET->getAs<PackExpansionType>())
3748  AnyPacks = true;
3749  ExceptionTypeStorage.push_back(getCanonicalType(ET));
3750  }
3751  if (!AnyPacks)
3752  CanonicalEPI.ExceptionSpec.Type = EST_None;
3753  else {
3754  CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
3755  CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
3756  }
3757  break;
3758  }
3759 
3760  case EST_DynamicNone:
3761  case EST_BasicNoexcept:
3762  case EST_NoexceptTrue:
3763  case EST_NoThrow:
3764  CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
3765  break;
3766 
3767  case EST_DependentNoexcept:
3768  llvm_unreachable("dependent noexcept is already canonical");
3769  }
3770  } else {
3772  }
3773 
3774  // Adjust the canonical function result type.
3775  CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
3776  Canonical =
3777  getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
3778 
3779  // Get the new insert position for the node we care about.
3780  FunctionProtoType *NewIP =
3781  FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
3782  assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3783  }
3784 
3785  // Compute the needed size to hold this FunctionProtoType and the
3786  // various trailing objects.
3787  auto ESH = FunctionProtoType::getExceptionSpecSize(
3788  EPI.ExceptionSpec.Type, EPI.ExceptionSpec.Exceptions.size());
3789  size_t Size = FunctionProtoType::totalSizeToAlloc<
3792  FunctionProtoType::ExtParameterInfo, Qualifiers>(
3793  NumArgs, FunctionProtoType::hasExtraBitfields(EPI.ExceptionSpec.Type),
3794  ESH.NumExceptionType, ESH.NumExprPtr, ESH.NumFunctionDeclPtr,
3795  EPI.ExtParameterInfos ? NumArgs : 0,
3796  EPI.TypeQuals.hasNonFastQualifiers() ? 1 : 0);
3797 
3798  auto *FTP = (FunctionProtoType *)Allocate(Size, TypeAlignment);
3799  FunctionProtoType::ExtProtoInfo newEPI = EPI;
3800  new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
3801  Types.push_back(FTP);
3802  if (!Unique)
3803  FunctionProtoTypes.InsertNode(FTP, InsertPos);
3804  return QualType(FTP, 0);
3805 }
3806 
3807 QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
3808  llvm::FoldingSetNodeID ID;
3809  PipeType::Profile(ID, T, ReadOnly);
3810 
3811  void *InsertPos = nullptr;
3812  if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
3813  return QualType(PT, 0);
3814 
3815  // If the pipe element type isn't canonical, this won't be a canonical type
3816  // either, so fill in the canonical type field.
3817  QualType Canonical;
3818  if (!T.isCanonical()) {
3819  Canonical = getPipeType(getCanonicalType(T), ReadOnly);
3820 
3821  // Get the new insert position for the node we care about.
3822  PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
3823  assert(!NewIP && "Shouldn't be in the map!");
3824  (void)NewIP;
3825  }
3826  auto *New = new (*this, TypeAlignment) PipeType(T, Canonical, ReadOnly);
3827  Types.push_back(New);
3828  PipeTypes.InsertNode(New, InsertPos);
3829  return QualType(New, 0);
3830 }
3831 
3833  // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
3834  return LangOpts.OpenCL ? getAddrSpaceQualType(Ty, LangAS::opencl_constant)
3835  : Ty;
3836 }
3837 
3839  return getPipeType(T, true);
3840 }
3841 
3843  return getPipeType(T, false);
3844 }
3845 
3846 #ifndef NDEBUG
3848  if (!isa<CXXRecordDecl>(D)) return false;
3849  const auto *RD = cast<CXXRecordDecl>(D);
3850  if (isa<ClassTemplatePartialSpecializationDecl>(RD))
3851  return true;
3852  if (RD->getDescribedClassTemplate() &&
3853  !isa<ClassTemplateSpecializationDecl>(RD))
3854  return true;
3855  return false;
3856 }
3857 #endif
3858 
3859 /// getInjectedClassNameType - Return the unique reference to the
3860 /// injected class name type for the specified templated declaration.
3862  QualType TST) const {
3863  assert(NeedsInjectedClassNameType(Decl));
3864  if (Decl->TypeForDecl) {
3865  assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
3866  } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
3867  assert(PrevDecl->TypeForDecl && "previous declaration has no type");
3868  Decl->TypeForDecl = PrevDecl->TypeForDecl;
3869  assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
3870  } else {
3871  Type *newType =
3872  new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
3873  Decl->TypeForDecl = newType;
3874  Types.push_back(newType);
3875  }
3876  return QualType(Decl->TypeForDecl, 0);
3877 }
3878 
3879 /// getTypeDeclType - Return the unique reference to the type for the
3880 /// specified type declaration.
3881 QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
3882  assert(Decl && "Passed null for Decl param");
3883  assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
3884 
3885  if (const auto *Typedef = dyn_cast<TypedefNameDecl>(Decl))
3886  return getTypedefType(Typedef);
3887 
3888  assert(!isa<TemplateTypeParmDecl>(Decl) &&
3889  "Template type parameter types are always available.");
3890 
3891  if (const auto *Record = dyn_cast<RecordDecl>(Decl)) {
3892  assert(Record->isFirstDecl() && "struct/union has previous declaration");
3893  assert(!NeedsInjectedClassNameType(Record));
3894  return getRecordType(Record);
3895  } else if (const auto *Enum = dyn_cast<EnumDecl>(Decl)) {
3896  assert(Enum->isFirstDecl() && "enum has previous declaration");
3897  return getEnumType(Enum);
3898  } else if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
3899  Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
3900  Decl->TypeForDecl = newType;
3901  Types.push_back(newType);
3902  } else
3903  llvm_unreachable("TypeDecl without a type?");
3904 
3905  return QualType(Decl->TypeForDecl, 0);
3906 }
3907 
3908 /// getTypedefType - Return the unique reference to the type for the
3909 /// specified typedef name decl.
3910 QualType
3912  QualType Canonical) const {
3913  if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3914 
3915  if (Canonical.isNull())
3916  Canonical = getCanonicalType(Decl->getUnderlyingType());
3917  auto *newType = new (*this, TypeAlignment)
3918  TypedefType(Type::Typedef, Decl, Canonical);
3919  Decl->TypeForDecl = newType;
3920  Types.push_back(newType);
3921  return QualType(newType, 0);
3922 }
3923 
3925  if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3926 
3927  if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
3928  if (PrevDecl->TypeForDecl)
3929  return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3930 
3931  auto *newType = new (*this, TypeAlignment) RecordType(Decl);
3932  Decl->TypeForDecl = newType;
3933  Types.push_back(newType);
3934  return QualType(newType, 0);
3935 }
3936 
3938  if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3939 
3940  if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
3941  if (PrevDecl->TypeForDecl)
3942  return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3943 
3944  auto *newType = new (*this, TypeAlignment) EnumType(Decl);
3945  Decl->TypeForDecl = newType;
3946  Types.push_back(newType);
3947  return QualType(newType, 0);
3948 }
3949 
3951  QualType modifiedType,
3952  QualType equivalentType) {
3953  llvm::FoldingSetNodeID id;
3954  AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
3955 
3956  void *insertPos = nullptr;
3957  AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3958  if (type) return QualType(type, 0);
3959 
3960  QualType canon = getCanonicalType(equivalentType);
3961  type = new (*this, TypeAlignment)
3962  AttributedType(canon, attrKind, modifiedType, equivalentType);
3963 
3964  Types.push_back(type);
3965  AttributedTypes.InsertNode(type, insertPos);
3966 
3967  return QualType(type, 0);
3968 }
3969 
3970 /// Retrieve a substitution-result type.
3971 QualType
3973  QualType Replacement) const {
3974  assert(Replacement.isCanonical()
3975  && "replacement types must always be canonical");
3976 
3977  llvm::FoldingSetNodeID ID;
3978  SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
3979  void *InsertPos = nullptr;
3980  SubstTemplateTypeParmType *SubstParm
3981  = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3982 
3983  if (!SubstParm) {
3984  SubstParm = new (*this, TypeAlignment)
3985  SubstTemplateTypeParmType(Parm, Replacement);
3986  Types.push_back(SubstParm);
3987  SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3988  }
3989 
3990  return QualType(SubstParm, 0);
3991 }
3992 
3993 /// Retrieve a
3995  const TemplateTypeParmType *Parm,
3996  const TemplateArgument &ArgPack) {
3997 #ifndef NDEBUG
3998  for (const auto &P : ArgPack.pack_elements()) {
3999  assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
4000  assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
4001  }
4002 #endif
4003 
4004  llvm::FoldingSetNodeID ID;
4005  SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
4006  void *InsertPos = nullptr;
4007  if (SubstTemplateTypeParmPackType *SubstParm
4008  = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
4009  return QualType(SubstParm, 0);
4010 
4011  QualType Canon;
4012  if (!Parm->isCanonicalUnqualified()) {
4013  Canon = getCanonicalType(QualType(Parm, 0));
4014  Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
4015  ArgPack);
4016  SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
4017  }
4018 
4019  auto *SubstParm
4020  = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
4021  ArgPack);
4022  Types.push_back(SubstParm);
4023  SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos);
4024  return QualType(SubstParm, 0);
4025 }
4026 
4027 /// Retrieve the template type parameter type for a template
4028 /// parameter or parameter pack with the given depth, index, and (optionally)
4029 /// name.
4031  bool ParameterPack,
4032  TemplateTypeParmDecl *TTPDecl) const {
4033  llvm::FoldingSetNodeID ID;
4034  TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
4035  void *InsertPos = nullptr;
4036  TemplateTypeParmType *TypeParm
4037  = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4038 
4039  if (TypeParm)
4040  return QualType(TypeParm, 0);
4041 
4042  if (TTPDecl) {
4043  QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
4044  TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
4045 
4046  TemplateTypeParmType *TypeCheck
4047  = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4048  assert(!TypeCheck && "Template type parameter canonical type broken");
4049  (void)TypeCheck;
4050  } else
4051  TypeParm = new (*this, TypeAlignment)
4052  TemplateTypeParmType(Depth, Index, ParameterPack);
4053 
4054  Types.push_back(TypeParm);
4055  TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
4056 
4057  return QualType(TypeParm, 0);
4058 }
4059 
4062  SourceLocation NameLoc,
4063  const TemplateArgumentListInfo &Args,
4064  QualType Underlying) const {
4065  assert(!Name.getAsDependentTemplateName() &&
4066  "No dependent template names here!");
4067  QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
4068 
4073  TL.setTemplateNameLoc(NameLoc);
4074  TL.setLAngleLoc(Args.getLAngleLoc());
4075  TL.setRAngleLoc(Args.getRAngleLoc());
4076  for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
4077  TL.setArgLocInfo(i, Args[i].getLocInfo());
4078  return DI;
4079 }
4080 
4081 QualType
4083  const TemplateArgumentListInfo &Args,
4084  QualType Underlying) const {
4085  assert(!Template.getAsDependentTemplateName() &&
4086  "No dependent template names here!");
4087 
4089  ArgVec.reserve(Args.size());
4090  for (const TemplateArgumentLoc &Arg : Args.arguments())
4091  ArgVec.push_back(Arg.getArgument());
4092 
4093  return getTemplateSpecializationType(Template, ArgVec, Underlying);
4094 }
4095 
4096 #ifndef NDEBUG
4098  for (const TemplateArgument &Arg : Args)
4099  if (Arg.isPackExpansion())
4100  return true;
4101 
4102  return true;
4103 }
4104 #endif
4105 
4106 QualType
4109  QualType Underlying) const {
4110  assert(!Template.getAsDependentTemplateName() &&
4111  "No dependent template names here!");
4112  // Look through qualified template names.
4113  if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
4114  Template = TemplateName(QTN->getTemplateDecl());
4115 
4116  bool IsTypeAlias =
4117  Template.getAsTemplateDecl() &&
4118  isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
4119  QualType CanonType;
4120  if (!Underlying.isNull())
4121  CanonType = getCanonicalType(Underlying);
4122  else {
4123  // We can get here with an alias template when the specialization contains
4124  // a pack expansion that does not match up with a parameter pack.
4125  assert((!IsTypeAlias || hasAnyPackExpansions(Args)) &&
4126  "Caller must compute aliased type");
4127  IsTypeAlias = false;
4128  CanonType = getCanonicalTemplateSpecializationType(Template, Args);
4129  }
4130 
4131  // Allocate the (non-canonical) template specialization type, but don't
4132  // try to unique it: these types typically have location information that
4133  // we don't unique and don't want to lose.
4134  void *Mem = Allocate(sizeof(TemplateSpecializationType) +
4135  sizeof(TemplateArgument) * Args.size() +
4136  (IsTypeAlias? sizeof(QualType) : 0),
4137  TypeAlignment);
4138  auto *Spec
4139  = new (Mem) TemplateSpecializationType(Template, Args, CanonType,
4140  IsTypeAlias ? Underlying : QualType());
4141 
4142  Types.push_back(Spec);
4143  return QualType(Spec, 0);
4144 }
4145 
4147  TemplateName Template, ArrayRef<TemplateArgument> Args) const {
4148  assert(!Template.getAsDependentTemplateName() &&
4149  "No dependent template names here!");
4150 
4151  // Look through qualified template names.
4152  if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
4153  Template = TemplateName(QTN->getTemplateDecl());
4154 
4155  // Build the canonical template specialization type.
4156  TemplateName CanonTemplate = getCanonicalTemplateName(Template);
4158  unsigned NumArgs = Args.size();
4159  CanonArgs.reserve(NumArgs);
4160  for (const TemplateArgument &Arg : Args)
4161  CanonArgs.push_back(getCanonicalTemplateArgument(Arg));
4162 
4163  // Determine whether this canonical template specialization type already
4164  // exists.
4165  llvm::FoldingSetNodeID ID;
4166  TemplateSpecializationType::Profile(ID, CanonTemplate,
4167  CanonArgs, *this);
4168 
4169  void *InsertPos = nullptr;
4171  = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
4172 
4173  if (!Spec) {
4174  // Allocate a new canonical template specialization type.
4175  void *Mem = Allocate((sizeof(TemplateSpecializationType) +
4176  sizeof(TemplateArgument) * NumArgs),
4177  TypeAlignment);
4178  Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
4179  CanonArgs,
4180  QualType(), QualType());
4181  Types.push_back(Spec);
4182  TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
4183  }
4184 
4185  assert(Spec->isDependentType() &&
4186  "Non-dependent template-id type must have a canonical type");
4187  return QualType(Spec, 0);
4188 }
4189 
4191  NestedNameSpecifier *NNS,
4192  QualType NamedType,
4193  TagDecl *OwnedTagDecl) const {
4194  llvm::FoldingSetNodeID ID;
4195  ElaboratedType::Profile(ID, Keyword, NNS, NamedType, OwnedTagDecl);
4196 
4197  void *InsertPos = nullptr;
4198  ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
4199  if (T)
4200  return QualType(T, 0);
4201 
4202  QualType Canon = NamedType;
4203  if (!Canon.isCanonical()) {
4204  Canon = getCanonicalType(NamedType);
4205  ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
4206  assert(!CheckT && "Elaborated canonical type broken");
4207  (void)CheckT;
4208  }
4209 
4210  void *Mem = Allocate(ElaboratedType::totalSizeToAlloc<TagDecl *>(!!OwnedTagDecl),
4211  TypeAlignment);
4212  T = new (Mem) ElaboratedType(Keyword, NNS, NamedType, Canon, OwnedTagDecl);
4213 
4214  Types.push_back(T);
4215  ElaboratedTypes.InsertNode(T, InsertPos);
4216  return QualType(T, 0);
4217 }
4218 
4219 QualType
4221  llvm::FoldingSetNodeID ID;
4222  ParenType::Profile(ID, InnerType);
4223 
4224  void *InsertPos = nullptr;
4225  ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
4226  if (T)
4227  return QualType(T, 0);
4228 
4229  QualType Canon = InnerType;
4230  if (!Canon.isCanonical()) {
4231  Canon = getCanonicalType(InnerType);
4232  ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
4233  assert(!CheckT && "Paren canonical type broken");
4234  (void)CheckT;
4235  }
4236 
4237  T = new (*this, TypeAlignment) ParenType(InnerType, Canon);
4238  Types.push_back(T);
4239  ParenTypes.InsertNode(T, InsertPos);
4240  return QualType(T, 0);
4241 }
4242 
4243 QualType
4245  const IdentifierInfo *MacroII) const {
4246  QualType Canon = UnderlyingTy;
4247  if (!Canon.isCanonical())
4248  Canon = getCanonicalType(UnderlyingTy);
4249 
4250  auto *newType = new (*this, TypeAlignment)
4251  MacroQualifiedType(UnderlyingTy, Canon, MacroII);
4252  Types.push_back(newType);
4253  return QualType(newType, 0);
4254 }
4255 
4257  NestedNameSpecifier *NNS,
4258  const IdentifierInfo *Name,
4259  QualType Canon) const {
4260  if (Canon.isNull()) {
4262  if (CanonNNS != NNS)
4263  Canon = getDependentNameType(Keyword, CanonNNS, Name);
4264  }
4265 
4266  llvm::FoldingSetNodeID ID;
4267  DependentNameType::Profile(ID, Keyword, NNS, Name);
4268 
4269  void *InsertPos = nullptr;
4271  = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
4272  if (T)
4273  return QualType(T, 0);
4274 
4275  T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon);
4276  Types.push_back(T);
4277  DependentNameTypes.InsertNode(T, InsertPos);
4278  return QualType(T, 0);
4279 }
4280 
4281 QualType
4283  ElaboratedTypeKeyword Keyword,
4284  NestedNameSpecifier *NNS,
4285  const IdentifierInfo *Name,
4286  const TemplateArgumentListInfo &Args) const {
4287  // TODO: avoid this copy
4289  for (unsigned I = 0, E = Args.size(); I != E; ++I)
4290  ArgCopy.push_back(Args[I].getArgument());
4291  return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy);
4292 }
4293 
4294 QualType
4296  ElaboratedTypeKeyword Keyword,
4297  NestedNameSpecifier *NNS,
4298  const IdentifierInfo *Name,
4299  ArrayRef<TemplateArgument> Args) const {
4300  assert((!NNS || NNS->isDependent()) &&
4301  "nested-name-specifier must be dependent");
4302 
4303  llvm::FoldingSetNodeID ID;
4304  DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
4305  Name, Args);
4306 
4307  void *InsertPos = nullptr;
4309  = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
4310  if (T)
4311  return QualType(T, 0);
4312 
4314 
4315  ElaboratedTypeKeyword CanonKeyword = Keyword;
4316  if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
4317 
4318  bool AnyNonCanonArgs = false;
4319  unsigned NumArgs = Args.size();
4320  SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
4321  for (unsigned I = 0; I != NumArgs; ++I) {
4322  CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
4323  if (!CanonArgs[I].structurallyEquals(Args[I]))
4324  AnyNonCanonArgs = true;
4325  }
4326 
4327  QualType Canon;
4328  if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
4329  Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
4330  Name,
4331  CanonArgs);
4332 
4333  // Find the insert position again.
4334  DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
4335  }
4336 
4337  void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
4338  sizeof(TemplateArgument) * NumArgs),
4339  TypeAlignment);
4340  T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
4341  Name, Args, Canon);
4342  Types.push_back(T);
4343  DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
4344  return QualType(T, 0);
4345 }
4346 
4348  TemplateArgument Arg;
4349  if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
4350  QualType ArgType = getTypeDeclType(TTP);
4351  if (TTP->isParameterPack())
4352  ArgType = getPackExpansionType(ArgType, None);
4353 
4354  Arg = TemplateArgument(ArgType);
4355  } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4356  Expr *E = new (*this) DeclRefExpr(
4357  *this, NTTP, /*enclosing*/ false,
4358  NTTP->getType().getNonLValueExprType(*this),
4359  Expr::getValueKindForType(NTTP->getType()), NTTP->getLocation());
4360 
4361  if (NTTP->isParameterPack())
4362  E = new (*this) PackExpansionExpr(DependentTy, E, NTTP->getLocation(),
4363  None);
4364  Arg = TemplateArgument(E);
4365  } else {
4366  auto *TTP = cast<TemplateTemplateParmDecl>(Param);
4367  if (TTP->isParameterPack())
4369  else
4370  Arg = TemplateArgument(TemplateName(TTP));
4371  }
4372 
4373  if (Param->isTemplateParameterPack())
4374  Arg = TemplateArgument::CreatePackCopy(*this, Arg);
4375 
4376  return Arg;
4377 }
4378 
4379 void
4382  Args.reserve(Args.size() + Params->size());
4383 
4384  for (NamedDecl *Param : *Params)
4385  Args.push_back(getInjectedTemplateArg(Param));
4386 }
4387 
4389  Optional<unsigned> NumExpansions) {
4390  llvm::FoldingSetNodeID ID;
4391  PackExpansionType::Profile(ID, Pattern, NumExpansions);
4392 
4393  // A deduced type can deduce to a pack, eg
4394  // auto ...x = some_pack;
4395  // That declaration isn't (yet) valid, but is created as part of building an
4396  // init-capture pack:
4397  // [...x = some_pack] {}
4398  assert((Pattern->containsUnexpandedParameterPack() ||
4399  Pattern->getContainedDeducedType()) &&
4400  "Pack expansions must expand one or more parameter packs");
4401  void *InsertPos = nullptr;
4403  = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
4404  if (T)
4405  return QualType(T, 0);
4406 
4407  QualType Canon;
4408  if (!Pattern.isCanonical()) {
4409  Canon = getCanonicalType(Pattern);
4410  // The canonical type might not contain an unexpanded parameter pack, if it
4411  // contains an alias template specialization which ignores one of its
4412  // parameters.
4413  if (Canon->containsUnexpandedParameterPack()) {
4414  Canon = getPackExpansionType(Canon, NumExpansions);
4415 
4416  // Find the insert position again, in case we inserted an element into
4417  // PackExpansionTypes and invalidated our insert position.
4418  PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
4419  }
4420  }
4421 
4422  T = new (*this, TypeAlignment)
4423  PackExpansionType(Pattern, Canon, NumExpansions);
4424  Types.push_back(T);
4425  PackExpansionTypes.InsertNode(T, InsertPos);
4426  return QualType(T, 0);
4427 }
4428 
4429 /// CmpProtocolNames - Comparison predicate for sorting protocols
4430 /// alphabetically.
4431 static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
4432  ObjCProtocolDecl *const *RHS) {
4433  return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
4434 }
4435 
4437  if (Protocols.empty()) return true;
4438 
4439  if (Protocols[0]->getCanonicalDecl() != Protocols[0])
4440  return false;
4441 
4442  for (unsigned i = 1; i != Protocols.size(); ++i)
4443  if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
4444  Protocols[i]->getCanonicalDecl() != Protocols[i])
4445  return false;
4446  return true;
4447 }
4448 
4449 static void
4451  // Sort protocols, keyed by name.
4452  llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
4453 
4454  // Canonicalize.
4455  for (ObjCProtocolDecl *&P : Protocols)
4456  P = P->getCanonicalDecl();
4457 
4458  // Remove duplicates.
4459  auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end());
4460  Protocols.erase(ProtocolsEnd, Protocols.end());
4461 }
4462 
4464  ObjCProtocolDecl * const *Protocols,
4465  unsigned NumProtocols) const {
4466  return getObjCObjectType(BaseType, {},
4467  llvm::makeArrayRef(Protocols, NumProtocols),
4468  /*isKindOf=*/false);
4469 }
4470 
4472  QualType baseType,
4473  ArrayRef<QualType> typeArgs,
4474  ArrayRef<ObjCProtocolDecl *> protocols,
4475  bool isKindOf) const {
4476  // If the base type is an interface and there aren't any protocols or
4477  // type arguments to add, then the interface type will do just fine.
4478  if (typeArgs.empty() && protocols.empty() && !isKindOf &&
4479  isa<ObjCInterfaceType>(baseType))
4480  return baseType;
4481 
4482  // Look in the folding set for an existing type.
4483  llvm::FoldingSetNodeID ID;
4484  ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
4485  void *InsertPos = nullptr;
4486  if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
4487  return QualType(QT, 0);
4488 
4489  // Determine the type arguments to be used for canonicalization,
4490  // which may be explicitly specified here or written on the base
4491  // type.
4492  ArrayRef<QualType> effectiveTypeArgs = typeArgs;
4493  if (effectiveTypeArgs.empty()) {
4494  if (const auto *baseObject = baseType->getAs<ObjCObjectType>())
4495  effectiveTypeArgs = baseObject->getTypeArgs();
4496  }
4497 
4498  // Build the canonical type, which has the canonical base type and a
4499  // sorted-and-uniqued list of protocols and the type arguments
4500  // canonicalized.
4501  QualType canonical;
4502  bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(),
4503  effectiveTypeArgs.end(),
4504  [&](QualType type) {
4505  return type.isCanonical();
4506  });
4507  bool protocolsSorted = areSortedAndUniqued(protocols);
4508  if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
4509  // Determine the canonical type arguments.
4510  ArrayRef<QualType> canonTypeArgs;
4511  SmallVector<QualType, 4> canonTypeArgsVec;
4512  if (!typeArgsAreCanonical) {
4513  canonTypeArgsVec.reserve(effectiveTypeArgs.size());
4514  for (auto typeArg : effectiveTypeArgs)
4515  canonTypeArgsVec.push_back(getCanonicalType(typeArg));
4516  canonTypeArgs = canonTypeArgsVec;
4517  } else {
4518  canonTypeArgs = effectiveTypeArgs;
4519  }
4520 
4521  ArrayRef<ObjCProtocolDecl *> canonProtocols;
4522  SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
4523  if (!protocolsSorted) {
4524  canonProtocolsVec.append(protocols.begin(), protocols.end());
4525  SortAndUniqueProtocols(canonProtocolsVec);
4526  canonProtocols = canonProtocolsVec;
4527  } else {
4528  canonProtocols = protocols;
4529  }
4530 
4531  canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
4532  canonProtocols, isKindOf);
4533 
4534  // Regenerate InsertPos.
4535  ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
4536  }
4537 
4538  unsigned size = sizeof(ObjCObjectTypeImpl);
4539  size += typeArgs.size() * sizeof(QualType);
4540  size += protocols.size() * sizeof(ObjCProtocolDecl *);
4541  void *mem = Allocate(size, TypeAlignment);
4542  auto *T =
4543  new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
4544  isKindOf);
4545 
4546  Types.push_back(T);
4547  ObjCObjectTypes.InsertNode(T, InsertPos);
4548  return QualType(T, 0);
4549 }
4550 
4551 /// Apply Objective-C protocol qualifiers to the given type.
4552 /// If this is for the canonical type of a type parameter, we can apply
4553 /// protocol qualifiers on the ObjCObjectPointerType.
4554 QualType
4556  ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
4557  bool allowOnPointerType) const {
4558  hasError = false;
4559 
4560  if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
4561  return getObjCTypeParamType(objT->getDecl(), protocols);
4562  }
4563 
4564  // Apply protocol qualifiers to ObjCObjectPointerType.
4565  if (allowOnPointerType) {
4566  if (const auto *objPtr =
4567  dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
4568  const ObjCObjectType *objT = objPtr->getObjectType();
4569  // Merge protocol lists and construct ObjCObjectType.
4570  SmallVector<ObjCProtocolDecl*, 8> protocolsVec;
4571  protocolsVec.append(objT->qual_begin(),
4572  objT->qual_end());
4573  protocolsVec.append(protocols.begin(), protocols.end());
4574  ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
4575  type = getObjCObjectType(
4576  objT->getBaseType(),
4577  objT->getTypeArgsAsWritten(),
4578  protocols,
4579  objT->isKindOfTypeAsWritten());
4580  return getObjCObjectPointerType(type);
4581  }
4582  }
4583 
4584  // Apply protocol qualifiers to ObjCObjectType.
4585  if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
4586  // FIXME: Check for protocols to which the class type is already
4587  // known to conform.
4588 
4589  return getObjCObjectType(objT->getBaseType(),
4590  objT->getTypeArgsAsWritten(),
4591  protocols,
4592  objT->isKindOfTypeAsWritten());
4593  }
4594 
4595  // If the canonical type is ObjCObjectType, ...
4596  if (type->isObjCObjectType()) {
4597  // Silently overwrite any existing protocol qualifiers.
4598  // TODO: determine whether that's the right thing to do.
4599 
4600  // FIXME: Check for protocols to which the class type is already
4601  // known to conform.
4602  return getObjCObjectType(type, {}, protocols, false);
4603  }
4604 
4605  // id<protocol-list>
4606  if (type->isObjCIdType()) {
4607  const auto *objPtr = type->castAs<ObjCObjectPointerType>();
4608  type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols,
4609  objPtr->isKindOfType());
4610  return getObjCObjectPointerType(type);
4611  }
4612 
4613  // Class<protocol-list>
4614  if (type->isObjCClassType()) {
4615  const auto *objPtr = type->castAs<ObjCObjectPointerType>();
4616  type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols,
4617  objPtr->isKindOfType());
4618  return getObjCObjectPointerType(type);
4619  }
4620 
4621  hasError = true;
4622  return type;
4623 }
4624 
4625 QualType
4627  ArrayRef<ObjCProtocolDecl *> protocols,
4628  QualType Canonical) const {
4629  // Look in the folding set for an existing type.
4630  llvm::FoldingSetNodeID ID;
4631  ObjCTypeParamType::Profile(ID, Decl, protocols);
4632  void *InsertPos = nullptr;
4633  if (ObjCTypeParamType *TypeParam =
4634  ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
4635  return QualType(TypeParam, 0);
4636 
4637  if (Canonical.isNull()) {
4638  // We canonicalize to the underlying type.
4639  Canonical = getCanonicalType(Decl->getUnderlyingType());
4640  if (!protocols.empty()) {
4641  // Apply the protocol qualifers.
4642  bool hasError;
4644  Canonical, protocols, hasError, true /*allowOnPointerType*/));
4645  assert(!hasError && "Error when apply protocol qualifier to bound type");
4646  }
4647  }
4648 
4649  unsigned size = sizeof(ObjCTypeParamType);
4650  size += protocols.size() * sizeof(ObjCProtocolDecl *);
4651  void *mem = Allocate(size, TypeAlignment);
4652  auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols);
4653 
4654  Types.push_back(newType);
4655  ObjCTypeParamTypes.InsertNode(newType, InsertPos);
4656  return QualType(newType, 0);
4657 }
4658 
4659 /// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
4660 /// protocol list adopt all protocols in QT's qualified-id protocol
4661 /// list.
4663  ObjCInterfaceDecl *IC) {
4664  if (!QT->isObjCQualifiedIdType())
4665  return false;
4666 
4667  if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) {
4668  // If both the right and left sides have qualifiers.
4669  for (auto *Proto : OPT->quals()) {
4670  if (!IC->ClassImplementsProtocol(Proto, false))
4671  return false;
4672  }
4673  return true;
4674  }
4675  return false;
4676 }
4677 
4678 /// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
4679 /// QT's qualified-id protocol list adopt all protocols in IDecl's list
4680 /// of protocols.
4682  ObjCInterfaceDecl *IDecl) {
4683  if (!QT->isObjCQualifiedIdType())
4684  return false;
4685  const auto *OPT = QT->getAs<ObjCObjectPointerType>();
4686  if (!OPT)
4687  return false;
4688  if (!IDecl->hasDefinition())
4689  return false;
4690  llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
4691  CollectInheritedProtocols(IDecl, InheritedProtocols);
4692  if (InheritedProtocols.empty())
4693  return false;
4694  // Check that if every protocol in list of id<plist> conforms to a protocol
4695  // of IDecl's, then bridge casting is ok.
4696  bool Conforms = false;
4697  for (auto *Proto : OPT->quals()) {
4698  Conforms = false;
4699  for (auto *PI : InheritedProtocols) {
4700  if (ProtocolCompatibleWithProtocol(Proto, PI)) {
4701  Conforms = true;
4702  break;
4703  }
4704  }
4705  if (!Conforms)
4706  break;
4707  }
4708  if (Conforms)
4709  return true;
4710 
4711  for (auto *PI : InheritedProtocols) {
4712  // If both the right and left sides have qualifiers.
4713  bool Adopts = false;
4714  for (auto *Proto : OPT->quals()) {
4715  // return 'true' if 'PI' is in the inheritance hierarchy of Proto
4716  if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
4717  break;
4718  }
4719  if (!Adopts)
4720  return false;
4721  }
4722  return true;
4723 }
4724 
4725 /// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
4726 /// the given object type.
4728  llvm::FoldingSetNodeID ID;
4729  ObjCObjectPointerType::Profile(ID, ObjectT);
4730 
4731  void *InsertPos = nullptr;
4732  if (ObjCObjectPointerType *QT =
4733  ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
4734  return QualType(QT, 0);
4735 
4736  // Find the canonical object type.
4737  QualType Canonical;
4738  if (!ObjectT.isCanonical()) {
4739  Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
4740 
4741  // Regenerate InsertPos.
4742  ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
4743  }
4744 
4745  // No match.
4746  void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
4747  auto *QType =
4748  new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
4749 
4750  Types.push_back(QType);
4751  ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
4752  return QualType(QType, 0);
4753 }
4754 
4755 /// getObjCInterfaceType - Return the unique reference to the type for the
4756 /// specified ObjC interface decl. The list of protocols is optional.
4758  ObjCInterfaceDecl *PrevDecl) const {
4759  if (Decl->TypeForDecl)
4760  return QualType(Decl->TypeForDecl, 0);
4761 
4762  if (PrevDecl) {
4763  assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
4764  Decl->TypeForDecl = PrevDecl->TypeForDecl;
4765  return QualType(PrevDecl->TypeForDecl, 0);
4766  }
4767 
4768  // Prefer the definition, if there is one.
4769  if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
4770  Decl = Def;
4771 
4772  void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
4773  auto *T = new (Mem) ObjCInterfaceType(Decl);
4774  Decl->TypeForDecl = T;
4775  Types.push_back(T);
4776  return QualType(T, 0);
4777 }
4778 
4779 /// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
4780 /// TypeOfExprType AST's (since expression's are never shared). For example,
4781 /// multiple declarations that refer to "typeof(x)" all contain different
4782 /// DeclRefExpr's. This doesn't effect the type checker, since it operates
4783 /// on canonical type's (which are always unique).
4785  TypeOfExprType *toe;
4786  if (tofExpr->isTypeDependent()) {
4787  llvm::FoldingSetNodeID ID;
4788  DependentTypeOfExprType::Profile(ID, *this, tofExpr);
4789 
4790  void *InsertPos = nullptr;
4792  = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
4793  if (Canon) {
4794  // We already have a "canonical" version of an identical, dependent
4795  // typeof(expr) type. Use that as our canonical type.
4796  toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
4797  QualType((TypeOfExprType*)Canon, 0));
4798  } else {
4799  // Build a new, canonical typeof(expr) type.
4800  Canon
4801  = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
4802  DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
4803  toe = Canon;
4804  }
4805  } else {
4806  QualType Canonical = getCanonicalType(tofExpr->getType());
4807  toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
4808  }
4809  Types.push_back(toe);
4810  return QualType(toe, 0);
4811 }
4812 
4813 /// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
4814 /// TypeOfType nodes. The only motivation to unique these nodes would be
4815 /// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
4816 /// an issue. This doesn't affect the type checker, since it operates
4817 /// on canonical types (which are always unique).
4819  QualType Canonical = getCanonicalType(tofType);
4820  auto *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
4821  Types.push_back(tot);
4822  return QualType(tot, 0);
4823 }
4824 
4825 /// Unlike many "get<Type>" functions, we don't unique DecltypeType
4826 /// nodes. This would never be helpful, since each such type has its own
4827 /// expression, and would not give a significant memory saving, since there
4828 /// is an Expr tree under each such type.
4830  DecltypeType *dt;
4831 
4832  // C++11 [temp.type]p2:
4833  // If an expression e involves a template parameter, decltype(e) denotes a
4834  // unique dependent type. Two such decltype-specifiers refer to the same
4835  // type only if their expressions are equivalent (14.5.6.1).
4836  if (e->isInstantiationDependent()) {
4837  llvm::FoldingSetNodeID ID;
4838  DependentDecltypeType::Profile(ID, *this, e);
4839 
4840  void *InsertPos = nullptr;
4841  DependentDecltypeType *Canon
4842  = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
4843  if (!Canon) {
4844  // Build a new, canonical decltype(expr) type.
4845  Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
4846  DependentDecltypeTypes.InsertNode(Canon, InsertPos);
4847  }
4848  dt = new (*this, TypeAlignment)
4849  DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
4850  } else {
4851  dt = new (*this, TypeAlignment)
4852  DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
4853  }
4854  Types.push_back(dt);
4855  return QualType(dt, 0);
4856 }
4857 
4858 /// getUnaryTransformationType - We don't unique these, since the memory
4859 /// savings are minimal and these are rare.
4861  QualType UnderlyingType,
4863  const {
4864  UnaryTransformType *ut = nullptr;
4865 
4866  if (BaseType->isDependentType()) {
4867  // Look in the folding set for an existing type.
4868  llvm::FoldingSetNodeID ID;
4870 
4871  void *InsertPos = nullptr;
4873  = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
4874 
4875  if (!Canon) {
4876  // Build a new, canonical __underlying_type(type) type.
4877  Canon = new (*this, TypeAlignment)
4879  Kind);
4880  DependentUnaryTransformTypes.InsertNode(Canon, InsertPos);
4881  }
4882  ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4883  QualType(), Kind,
4884  QualType(Canon, 0));
4885  } else {
4886  QualType CanonType = getCanonicalType(UnderlyingType);
4887  ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4888  UnderlyingType, Kind,
4889  CanonType);
4890  }
4891  Types.push_back(ut);
4892  return QualType(ut, 0);
4893 }
4894 
4895 /// getAutoType - Return the uniqued reference to the 'auto' type which has been
4896 /// deduced to the given type, or to the canonical undeduced 'auto' type, or the
4897 /// canonical deduced-but-dependent 'auto' type.
4899  bool IsDependent, bool IsPack) const {
4900  assert((!IsPack || IsDependent) && "only use IsPack for a dependent pack");
4901  if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto && !IsDependent)
4902  return getAutoDeductType();
4903 
4904  // Look in the folding set for an existing type.
4905  void *InsertPos = nullptr;
4906  llvm::FoldingSetNodeID ID;
4907  AutoType::Profile(ID, DeducedType, Keyword, IsDependent, IsPack);
4908  if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
4909  return QualType(AT, 0);
4910 
4911  auto *AT = new (*this, TypeAlignment)
4912  AutoType(DeducedType, Keyword, IsDependent, IsPack);
4913  Types.push_back(AT);
4914  if (InsertPos)
4915  AutoTypes.InsertNode(AT, InsertPos);
4916  return QualType(AT, 0);
4917 }
4918 
4919 /// Return the uniqued reference to the deduced template specialization type
4920 /// which has been deduced to the given type, or to the canonical undeduced
4921 /// such type, or the canonical deduced-but-dependent such type.
4923  TemplateName Template, QualType DeducedType, bool IsDependent) const {
4924  // Look in the folding set for an existing type.
4925  void *InsertPos = nullptr;
4926  llvm::FoldingSetNodeID ID;
4927  DeducedTemplateSpecializationType::Profile(ID, Template, DeducedType,
4928  IsDependent);
4930  DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
4931  return QualType(DTST, 0);
4932 
4933  auto *DTST = new (*this, TypeAlignment)
4934  DeducedTemplateSpecializationType(Template, DeducedType, IsDependent);
4935  Types.push_back(DTST);
4936  if (InsertPos)
4937  DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos);
4938  return QualType(DTST, 0);
4939 }
4940 
4941 /// getAtomicType - Return the uniqued reference to the atomic type for
4942 /// the given value type.
4944  // Unique pointers, to guarantee there is only one pointer of a particular
4945  // structure.
4946  llvm::FoldingSetNodeID ID;
4947  AtomicType::Profile(ID, T);
4948 
4949  void *InsertPos = nullptr;
4950  if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
4951  return QualType(AT, 0);
4952 
4953  // If the atomic value type isn't canonical, this won't be a canonical type
4954  // either, so fill in the canonical type field.
4955  QualType Canonical;
4956  if (!T.isCanonical()) {
4957  Canonical = getAtomicType(getCanonicalType(T));
4958 
4959  // Get the new insert position for the node we care about.
4960  AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
4961  assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4962  }
4963  auto *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
4964  Types.push_back(New);
4965  AtomicTypes.InsertNode(New, InsertPos);
4966  return QualType(New, 0);
4967 }
4968 
4969 /// getAutoDeductType - Get type pattern for deducing against 'auto'.
4971  if (AutoDeductTy.isNull())
4974  /*dependent*/false, /*pack*/false),
4975  0);
4976  return AutoDeductTy;
4977 }
4978 
4979 /// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
4981  if (AutoRRefDeductTy.isNull())
4983  assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
4984  return AutoRRefDeductTy;
4985 }
4986 
4987 /// getTagDeclType - Return the unique reference to the type for the
4988 /// specified TagDecl (struct/union/class/enum) decl.
4990  assert(Decl);
4991  // FIXME: What is the design on getTagDeclType when it requires casting
4992  // away const? mutable?
4993  return getTypeDeclType(const_cast<TagDecl*>(Decl));
4994 }
4995 
4996 /// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
4997 /// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
4998 /// needs to agree with the definition in <stddef.h>.
5000  return getFromTargetType(Target->getSizeType());
5001 }
5002 
5003 /// Return the unique signed counterpart of the integer type
5004 /// corresponding to size_t.
5006  return getFromTargetType(Target->getSignedSizeType());
5007 }
5008 
5009 /// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
5011  return getFromTargetType(Target->getIntMaxType());
5012 }
5013 
5014 /// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
5016  return getFromTargetType(Target->getUIntMaxType());
5017 }
5018 
5019 /// getSignedWCharType - Return the type of "signed wchar_t".
5020 /// Used when in C++, as a GCC extension.
5022  // FIXME: derive from "Target" ?
5023  return WCharTy;
5024 }
5025 
5026 /// getUnsignedWCharType - Return the type of "unsigned wchar_t".
5027 /// Used when in C++, as a GCC extension.
5029  // FIXME: derive from "Target" ?
5030  return UnsignedIntTy;
5031 }
5032 
5034  return getFromTargetType(Target->getIntPtrType());
5035 }
5036 
5039 }
5040 
5041 /// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
5042 /// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
5044  return getFromTargetType(Target->getPtrDiffType(0));
5045 }
5046 
5047 /// Return the unique unsigned counterpart of "ptrdiff_t"
5048 /// integer type. The standard (C11 7.21.6.1p7) refers to this type
5049 /// in the definition of %tu format specifier.
5051  return getFromTargetType(Target->getUnsignedPtrDiffType(0));
5052 }
5053 
5054 /// Return the unique type for "pid_t" defined in
5055 /// <sys/types.h>. We need this to compute the correct type for vfork().
5057  return getFromTargetType(Target->getProcessIDType());
5058 }
5059 
5060 //===----------------------------------------------------------------------===//
5061 // Type Operators
5062 //===----------------------------------------------------------------------===//
5063 
5065  // Push qualifiers into arrays, and then discard any remaining
5066  // qualifiers.
5067  T = getCanonicalType(T);
5069  const Type *Ty = T.getTypePtr();
5070  QualType Result;
5071  if (isa<ArrayType>(Ty)) {
5072  Result = getArrayDecayedType(QualType(Ty,0));
5073  } else if (isa<FunctionType>(Ty)) {
5074  Result = getPointerType(QualType(Ty, 0));
5075  } else {
5076  Result = QualType(Ty, 0);
5077  }
5078 
5079  return CanQualType::CreateUnsafe(Result);
5080 }
5081 
5083  Qualifiers &quals) {
5084  SplitQualType splitType = type.getSplitUnqualifiedType();
5085 
5086  // FIXME: getSplitUnqualifiedType() actually walks all the way to
5087  // the unqualified desugared type and then drops it on the floor.
5088  // We then have to strip that sugar back off with
5089  // getUnqualifiedDesugaredType(), which is silly.
5090  const auto *AT =
5091  dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
5092 
5093  // If we don't have an array, just use the results in splitType.
5094  if (!AT) {
5095  quals = splitType.Quals;
5096  return QualType(splitType.Ty, 0);
5097  }
5098 
5099  // Otherwise, recurse on the array's element type.
5100  QualType elementType = AT->getElementType();
5101  QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
5102 
5103  // If that didn't change the element type, AT has no qualifiers, so we
5104  // can just use the results in splitType.
5105  if (elementType == unqualElementType) {
5106  assert(quals.empty()); // from the recursive call
5107  quals = splitType.Quals;
5108  return QualType(splitType.Ty, 0);
5109  }
5110 
5111  // Otherwise, add in the qualifiers from the outermost type, then
5112  // build the type back up.
5113  quals.addConsistentQualifiers(splitType.Quals);
5114 
5115  if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
5116  return getConstantArrayType(unqualElementType, CAT->getSize(),
5117  CAT->getSizeModifier(), 0);
5118  }
5119 
5120  if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) {
5121  return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
5122  }
5123 
5124  if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) {
5125  return getVariableArrayType(unqualElementType,
5126  VAT->getSizeExpr(),
5127  VAT->getSizeModifier(),
5128  VAT->getIndexTypeCVRQualifiers(),
5129  VAT->getBracketsRange());
5130  }
5131 
5132  const auto *DSAT = cast<DependentSizedArrayType>(AT);
5133  return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
5134  DSAT->getSizeModifier(), 0,
5135  SourceRange());
5136 }
5137 
5138 /// Attempt to unwrap two types that may both be array types with the same bound
5139 /// (or both be array types of unknown bound) for the purpose of comparing the
5140 /// cv-decomposition of two types per C++ [conv.qual].
5142  bool UnwrappedAny = false;
5143  while (true) {
5144  auto *AT1 = getAsArrayType(T1);
5145  if (!AT1) return UnwrappedAny;
5146 
5147  auto *AT2 = getAsArrayType(T2);
5148  if (!AT2) return UnwrappedAny;
5149 
5150  // If we don't have two array types with the same constant bound nor two
5151  // incomplete array types, we've unwrapped everything we can.
5152  if (auto *CAT1 = dyn_cast<ConstantArrayType>(AT1)) {
5153  auto *CAT2 = dyn_cast<ConstantArrayType>(AT2);
5154  if (!CAT2 || CAT1->getSize() != CAT2->getSize())
5155  return UnwrappedAny;
5156  } else if (!isa<IncompleteArrayType>(AT1) ||
5157  !isa<IncompleteArrayType>(AT2)) {
5158  return UnwrappedAny;
5159  }
5160 
5161  T1 = AT1->getElementType();
5162  T2 = AT2->getElementType();
5163  UnwrappedAny = true;
5164  }
5165 }
5166 
5167 /// Attempt to unwrap two types that may be similar (C++ [conv.qual]).
5168 ///
5169 /// If T1 and T2 are both pointer types of the same kind, or both array types
5170 /// with the same bound, unwraps layers from T1 and T2 until a pointer type is
5171 /// unwrapped. Top-level qualifiers on T1 and T2 are ignored.
5172 ///
5173 /// This function will typically be called in a loop that successively
5174 /// "unwraps" pointer and pointer-to-member types to compare them at each
5175 /// level.
5176 ///
5177 /// \return \c true if a pointer type was unwrapped, \c false if we reached a
5178 /// pair of types that can't be unwrapped further.
5180  UnwrapSimilarArrayTypes(T1, T2);
5181 
5182  const auto *T1PtrType = T1->getAs<PointerType>();
5183  const auto *T2PtrType = T2->getAs<PointerType>();
5184  if (T1PtrType && T2PtrType) {
5185  T1 = T1PtrType->getPointeeType();
5186  T2 = T2PtrType->getPointeeType();
5187  return true;
5188  }
5189 
5190  const auto *T1MPType = T1->getAs<MemberPointerType>();
5191  const auto *T2MPType = T2->getAs<MemberPointerType>();
5192  if (T1MPType && T2MPType &&
5193  hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
5194  QualType(T2MPType->getClass(), 0))) {
5195  T1 = T1MPType->getPointeeType();
5196  T2 = T2MPType->getPointeeType();
5197  return true;
5198  }
5199 
5200  if (getLangOpts().ObjC) {
5201  const auto *T1OPType = T1->getAs<ObjCObjectPointerType>();
5202  const auto *T2OPType = T2->getAs<ObjCObjectPointerType>();
5203  if (T1OPType && T2OPType) {
5204  T1 = T1OPType->getPointeeType();
5205  T2 = T2OPType->getPointeeType();
5206  return true;
5207  }
5208  }
5209 
5210  // FIXME: Block pointers, too?
5211 
5212  return false;
5213 }
5214 
5216  while (true) {
5217  Qualifiers Quals;
5218  T1 = getUnqualifiedArrayType(T1, Quals);
5219  T2 = getUnqualifiedArrayType(T2, Quals);
5220  if (hasSameType(T1, T2))
5221  return true;
5222  if (!UnwrapSimilarTypes(T1, T2))
5223  return false;
5224  }
5225 }
5226 
5228  while (true) {
5229  Qualifiers Quals1, Quals2;
5230  T1 = getUnqualifiedArrayType(T1, Quals1);
5231  T2 = getUnqualifiedArrayType(T2, Quals2);
5232 
5233  Quals1.removeCVRQualifiers();
5234  Quals2.removeCVRQualifiers();
5235  if (Quals1 != Quals2)
5236  return false;
5237 
5238  if (hasSameType(T1, T2))
5239  return true;
5240 
5241  if (!UnwrapSimilarTypes(T1, T2))
5242  return false;
5243  }
5244 }
5245 
5248  SourceLocation NameLoc) const {
5249  switch (Name.getKind()) {
5252  // DNInfo work in progress: CHECKME: what about DNLoc?
5254  NameLoc);
5255 
5258  // DNInfo work in progress: CHECKME: what about DNLoc?
5259  return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
5260  }
5261 
5264  return DeclarationNameInfo(Storage->getDeclName(), NameLoc);
5265  }
5266 
5269  DeclarationName DName;
5270  if (DTN->isIdentifier()) {
5272  return DeclarationNameInfo(DName, NameLoc);
5273  } else {
5275  // DNInfo work in progress: FIXME: source locations?
5276  DeclarationNameLoc DNLoc;
5279  return DeclarationNameInfo(DName, NameLoc, DNLoc);
5280  }
5281  }
5282 
5286  return DeclarationNameInfo(subst->getParameter()->getDeclName(),
5287  NameLoc);
5288  }
5289 
5294  NameLoc);
5295  }
5296  }
5297 
5298  llvm_unreachable("bad template name kind!");
5299 }
5300 
5302  switch (Name.getKind()) {
5304  case TemplateName::Template: {
5305  TemplateDecl *Template = Name.getAsTemplateDecl();
5306  if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Template))
5307  Template = getCanonicalTemplateTemplateParmDecl(TTP);
5308 
5309  // The canonical template name is the canonical template declaration.
5310  return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
5311  }
5312 
5315  llvm_unreachable("cannot canonicalize unresolved template");
5316 
5319  assert(DTN && "Non-dependent template names must refer to template decls.");
5320  return DTN->CanonicalTemplateName;
5321  }
5322 
5326  return getCanonicalTemplateName(subst->getReplacement());
5327  }
5328 
5332  TemplateTemplateParmDecl *canonParameter
5333  = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
5334  TemplateArgument canonArgPack
5336  return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
5337  }
5338  }
5339 
5340  llvm_unreachable("bad template name!");
5341 }
5342 
5344  X = getCanonicalTemplateName(X);
5345  Y = getCanonicalTemplateName(Y);
5346  return X.getAsVoidPointer() == Y.getAsVoidPointer();
5347 }
5348 
5351  switch (Arg.getKind()) {
5353  return Arg;
5354 
5356  return Arg;
5357 
5359  auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
5360  return TemplateArgument(D, Arg.getParamTypeForDecl());
5361  }
5362 
5365  /*isNullPtr*/true);
5366 
5369 
5373  Arg.getNumTemplateExpansions());
5374 
5377 
5380 
5381  case TemplateArgument::Pack: {
5382  if (Arg.pack_size() == 0)
5383  return Arg;
5384 
5385  auto *CanonArgs = new (*this) TemplateArgument[Arg.pack_size()];
5386  unsigned Idx = 0;
5388  AEnd = Arg.pack_end();
5389  A != AEnd; (void)++A, ++Idx)
5390  CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
5391 
5392  return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size()));
5393  }
5394  }
5395 
5396  // Silence GCC warning
5397  llvm_unreachable("Unhandled template argument kind");
5398 }
5399 
5402  if (!NNS)
5403  return nullptr;
5404 
5405  switch (NNS->getKind()) {
5407  // Canonicalize the prefix but keep the identifier the same.
5408  return NestedNameSpecifier::Create(*this,
5410  NNS->getAsIdentifier());
5411 
5413  // A namespace is canonical; build a nested-name-specifier with
5414  // this namespace and no prefix.
5415  return NestedNameSpecifier::Create(*this, nullptr,
5417 
5419  // A namespace is canonical; build a nested-name-specifier with
5420  // this namespace and no prefix.
5421  return NestedNameSpecifier::Create(*this, nullptr,
5423  ->getOriginalNamespace());
5424 
5427  QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
5428 
5429  // If we have some kind of dependent-named type (e.g., "typename T::type"),
5430  // break it apart into its prefix and identifier, then reconsititute those
5431  // as the canonical nested-name-specifier. This is required to canonicalize
5432  // a dependent nested-name-specifier involving typedefs of dependent-name
5433  // types, e.g.,
5434  // typedef typename T::type T1;
5435  // typedef typename T1::type T2;
5436  if (const auto *DNT = T->getAs<DependentNameType>())
5437  return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
5438  const_cast<IdentifierInfo *>(DNT->getIdentifier()));
5439 
5440  // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
5441  // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
5442  // first place?
5443  return NestedNameSpecifier::Create(*this, nullptr, false,
5444  const_cast<Type *>(T.getTypePtr()));
5445  }
5446 
5449  // The global specifier and __super specifer are canonical and unique.
5450  return NNS;
5451  }
5452 
5453  llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
5454 }
5455 
5457  // Handle the non-qualified case efficiently.
5458  if (!T.hasLocalQualifiers()) {
5459  // Handle the common positive case fast.
5460  if (const auto *AT = dyn_cast<ArrayType>(T))
5461  return AT;
5462  }
5463 
5464  // Handle the common negative case fast.
5465  if (!isa<ArrayType>(T.getCanonicalType()))
5466  return nullptr;
5467 
5468  // Apply any qualifiers from the array type to the element type. This
5469  // implements C99 6.7.3p8: "If the specification of an array type includes
5470  // any type qualifiers, the element type is so qualified, not the array type."
5471 
5472  // If we get here, we either have type qualifiers on the type, or we have
5473  // sugar such as a typedef in the way. If we have type qualifiers on the type
5474  // we must propagate them down into the element type.
5475 
5477  Qualifiers qs = split.Quals;
5478 
5479  // If we have a simple case, just return now.
5480  const auto *ATy = dyn_cast<ArrayType>(split.Ty);
5481  if (!ATy || qs.empty())
5482  return ATy;
5483 
5484  // Otherwise, we have an array and we have qualifiers on it. Push the
5485  // qualifiers into the array element type and return a new array type.
5486  QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
5487 
5488  if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy))
5489  return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
5490  CAT->getSizeModifier(),
5491  CAT->getIndexTypeCVRQualifiers()));
5492  if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy))
5493  return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
5494  IAT->getSizeModifier(),
5495  IAT->getIndexTypeCVRQualifiers()));
5496 
5497  if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy))
5498  return cast<ArrayType>(
5499  getDependentSizedArrayType(NewEltTy,
5500  DSAT->getSizeExpr(),
5501  DSAT->getSizeModifier(),
5502  DSAT->getIndexTypeCVRQualifiers(),
5503  DSAT->getBracketsRange()));
5504 
5505  const auto *VAT = cast<VariableArrayType>(ATy);
5506  return cast<ArrayType>(getVariableArrayType(NewEltTy,
5507  VAT->getSizeExpr(),
5508  VAT->getSizeModifier(),
5509  VAT->getIndexTypeCVRQualifiers(),
5510  VAT->getBracketsRange()));
5511 }
5512 
5514  if (T->isArrayType() || T->isFunctionType())
5515  return getDecayedType(T);
5516  return T;
5517 }
5518 
5521  T = getAdjustedParameterType(T);
5522  return T.getUnqualifiedType();
5523 }
5524 
5526  // C++ [except.throw]p3:
5527  // A throw-expression initializes a temporary object, called the exception
5528  // object, the type of which is determined by removing any top-level
5529  // cv-qualifiers from the static type of the operand of throw and adjusting
5530  // the type from "array of T" or "function returning T" to "pointer to T"
5531  // or "pointer to function returning T", [...]
5533  if (T->isArrayType() || T->isFunctionType())
5534  T = getDecayedType(T);
5535  return T.getUnqualifiedType();
5536 }
5537 
5538 /// getArrayDecayedType - Return the properly qualified result of decaying the
5539 /// specified array type to a pointer. This operation is non-trivial when
5540 /// handling typedefs etc. The canonical type of "T" must be an array type,
5541 /// this returns a pointer to a properly qualified element of the array.
5542 ///
5543 /// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
5545  // Get the element type with 'getAsArrayType' so that we don't lose any
5546  // typedefs in the element type of the array. This also handles propagation
5547  // of type qualifiers from the array type into the element type if present
5548  // (C99 6.7.3p8).
5549  const ArrayType *PrettyArrayType = getAsArrayType(Ty);
5550  assert(PrettyArrayType && "Not an array type!");
5551 
5552  QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
5553 
5554  // int x[restrict 4] -> int *restrict
5556  PrettyArrayType->getIndexTypeQualifiers());
5557 
5558  // int x[_Nullable] -> int * _Nullable
5559  if (auto Nullability = Ty->getNullability(*this)) {
5560  Result = const_cast<ASTContext *>(this)->getAttributedType(
5562  }
5563  return Result;
5564 }
5565 
5567  return getBaseElementType(array->getElementType());
5568 }
5569 
5571  Qualifiers qs;
5572  while (true) {
5573  SplitQualType split = type.getSplitDesugaredType();
5574  const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
5575  if (!array) break;
5576 
5577  type = array->getElementType();
5578  qs.addConsistentQualifiers(split.Quals);
5579  }
5580 
5581  return getQualifiedType(type, qs);
5582 }
5583 
5584 /// getConstantArrayElementCount - Returns number of constant array elements.
5585 uint64_t
5587  uint64_t ElementCount = 1;
5588  do {
5589  ElementCount *= CA->getSize().getZExtValue();
5590  CA = dyn_cast_or_null<ConstantArrayType>(
5592  } while (CA);
5593  return ElementCount;
5594 }
5595 
5596 /// getFloatingRank - Return a relative rank for floating point types.
5597 /// This routine will assert if passed a built-in type that isn't a float.
5599  if (const auto *CT = T->getAs<ComplexType>())
5600  return getFloatingRank(CT->getElementType());
5601 
5602  assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
5603  switch (T->getAs<BuiltinType>()->getKind()) {
5604  default: llvm_unreachable("getFloatingRank(): not a floating type");
5605  case BuiltinType::Float16: return Float16Rank;
5606  case BuiltinType::Half: return HalfRank;
5607  case BuiltinType::Float: return FloatRank;
5608  case BuiltinType::Double: return DoubleRank;
5609  case BuiltinType::LongDouble: return LongDoubleRank;
5610  case BuiltinType::Float128: return Float128Rank;
5611  }
5612 }
5613 
5614 /// getFloatingTypeOfSizeWithinDomain - Returns a real floating
5615 /// point or a complex type (based on typeDomain/typeSize).
5616 /// 'typeDomain' is a real floating point or complex type.
5617 /// 'typeSize' is a real floating point or complex type.
5619  QualType Domain) const {
5620  FloatingRank EltRank = getFloatingRank(Size);
5621  if (Domain->isComplexType()) {
5622  switch (EltRank) {
5623  case Float16Rank:
5624  case HalfRank: llvm_unreachable("Complex half is not supported");
5625  case FloatRank: return FloatComplexTy;
5626  case DoubleRank: return DoubleComplexTy;
5627  case LongDoubleRank: return LongDoubleComplexTy;
5628  case Float128Rank: return Float128ComplexTy;
5629  }
5630  }
5631 
5632  assert(Domain->isRealFloatingType() && "Unknown domain!");
5633  switch (EltRank) {
5634  case Float16Rank: return HalfTy;
5635  case HalfRank: return HalfTy;
5636  case FloatRank: return FloatTy;
5637  case DoubleRank: return DoubleTy;
5638  case LongDoubleRank: return LongDoubleTy;
5639  case Float128Rank: return Float128Ty;
5640  }
5641  llvm_unreachable("getFloatingRank(): illegal value for rank");
5642 }
5643 
5644 /// getFloatingTypeOrder - Compare the rank of the two specified floating
5645 /// point types, ignoring the domain of the type (i.e. 'double' ==
5646 /// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
5647 /// LHS < RHS, return -1.
5649  FloatingRank LHSR = getFloatingRank(LHS);
5650  FloatingRank RHSR = getFloatingRank(RHS);
5651 
5652  if (LHSR == RHSR)
5653  return 0;
5654  if (LHSR > RHSR)
5655  return 1;
5656  return -1;
5657 }
5658 
5660  if (&getFloatTypeSemantics(LHS) == &getFloatTypeSemantics(RHS))
5661  return 0;
5662  return getFloatingTypeOrder(LHS, RHS);
5663 }
5664 
5665 /// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
5666 /// routine will assert if passed a built-in type that isn't an integer or enum,
5667 /// or if it is not canonicalized.
5668 unsigned ASTContext::getIntegerRank(const Type *T) const {
5669  assert(T->isCanonicalUnqualified() && "T should be canonicalized");
5670 
5671  switch (cast<BuiltinType>(T)->getKind()) {
5672  default: llvm_unreachable("getIntegerRank(): not a built-in integer");
5673  case BuiltinType::Bool:
5674  return 1 + (getIntWidth(BoolTy) << 3);
5675  case BuiltinType::Char_S:
5676  case BuiltinType::Char_U:
5677  case BuiltinType::SChar:
5678  case BuiltinType::UChar:
5679  return 2 + (getIntWidth(CharTy) << 3);
5680  case BuiltinType::Short:
5681  case BuiltinType::UShort:
5682  return 3 + (getIntWidth(ShortTy) << 3);
5683  case BuiltinType::Int:
5684  case BuiltinType::UInt:
5685  return 4 + (getIntWidth(IntTy) << 3);
5686  case BuiltinType::Long:
5687  case BuiltinType::ULong:
5688  return 5 + (getIntWidth(LongTy) << 3);
5689  case BuiltinType::LongLong:
5690  case BuiltinType::ULongLong:
5691  return 6 + (getIntWidth(LongLongTy) << 3);
5692  case BuiltinType::Int128:
5693  case BuiltinType::UInt128:
5694  return 7 + (getIntWidth(Int128Ty) << 3);
5695  }
5696 }
5697 
5698 /// Whether this is a promotable bitfield reference according
5699 /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
5700 ///
5701 /// \returns the type this bit-field will promote to, or NULL if no
5702 /// promotion occurs.
5704  if (E->isTypeDependent() || E->isValueDependent())
5705  return {};
5706 
5707  // C++ [conv.prom]p5:
5708  // If the bit-field has an enumerated type, it is treated as any other
5709  // value of that type for promotion purposes.
5710  if (getLangOpts().CPlusPlus && E->getType()->isEnumeralType())
5711  return {};
5712 
5713  // FIXME: We should not do this unless E->refersToBitField() is true. This
5714  // matters in C where getSourceBitField() will find bit-fields for various
5715  // cases where the source expression is not a bit-field designator.
5716 
5717  FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
5718  if (!Field)
5719  return {};
5720 
5721  QualType FT = Field->getType();
5722 
5723  uint64_t BitWidth = Field->getBitWidthValue(*this);
5724  uint64_t IntSize = getTypeSize(IntTy);
5725  // C++ [conv.prom]p5:
5726  // A prvalue for an integral bit-field can be converted to a prvalue of type
5727  // int if int can represent all the values of the bit-field; otherwise, it
5728  // can be converted to unsigned int if unsigned int can represent all the
5729  // values of the bit-field. If the bit-field is larger yet, no integral
5730  // promotion applies to it.
5731  // C11 6.3.1.1/2:
5732  // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
5733  // If an int can represent all values of the original type (as restricted by
5734  // the width, for a bit-field), the value is converted to an int; otherwise,
5735  // it is converted to an unsigned int.
5736  //
5737  // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
5738  // We perform that promotion here to match GCC and C++.
5739  // FIXME: C does not permit promotion of an enum bit-field whose rank is
5740  // greater than that of 'int'. We perform that promotion to match GCC.
5741  if (BitWidth < IntSize)
5742  return IntTy;
5743 
5744  if (BitWidth == IntSize)
5745  return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
5746 
5747  // Bit-fields wider than int are not subject to promotions, and therefore act
5748  // like the base type. GCC has some weird bugs in this area that we
5749  // deliberately do not follow (GCC follows a pre-standard resolution to
5750  // C's DR315 which treats bit-width as being part of the type, and this leaks
5751  // into their semantics in some cases).
5752  return {};
5753 }
5754 
5755 /// getPromotedIntegerType - Returns the type that Promotable will
5756 /// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
5757 /// integer type.
5759  assert(!Promotable.isNull());
5760  assert(Promotable->isPromotableIntegerType());
5761  if (const auto *ET = Promotable->getAs<EnumType>())
5762  return ET->getDecl()->getPromotionType();
5763 
5764  if (const auto *BT = Promotable->getAs<BuiltinType>()) {
5765  // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
5766  // (3.9.1) can be converted to a prvalue of the first of the following
5767  // types that can represent all the values of its underlying type:
5768  // int, unsigned int, long int, unsigned long int, long long int, or
5769  // unsigned long long int [...]
5770  // FIXME: Is there some better way to compute this?
5771  if (BT->getKind() == BuiltinType::WChar_S ||
5772  BT->getKind() == BuiltinType::WChar_U ||
5773  BT->getKind() == BuiltinType::Char8 ||
5774  BT->getKind() == BuiltinType::Char16 ||
5775  BT->getKind() == BuiltinType::Char32) {
5776  bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
5777  uint64_t FromSize = getTypeSize(BT);
5778  QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
5780  for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
5781  uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
5782  if (FromSize < ToSize ||
5783  (FromSize == ToSize &&
5784  FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
5785  return PromoteTypes[Idx];
5786  }
5787  llvm_unreachable("char type should fit into long long");
5788  }
5789  }
5790 
5791  // At this point, we should have a signed or unsigned integer type.
5792  if (Promotable->isSignedIntegerType())
5793  return IntTy;
5794  uint64_t PromotableSize = getIntWidth(Promotable);
5795  uint64_t IntSize = getIntWidth(IntTy);
5796  assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
5797  return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
5798 }
5799 
5800 /// Recurses in pointer/array types until it finds an objc retainable
5801 /// type and returns its ownership.
5803  while (!T.isNull()) {
5805  return T.getObjCLifetime();
5806  if (T->isArrayType())
5807  T = getBaseElementType(T);
5808  else if (const auto *PT = T->getAs<PointerType>())
5809  T = PT->getPointeeType();
5810  else if (const auto *RT = T->getAs<ReferenceType>())
5811  T = RT->getPointeeType();
5812  else
5813  break;
5814  }
5815 
5816  return Qualifiers::OCL_None;
5817 }
5818 
5819 static const Type *getIntegerTypeForEnum(const EnumType *ET) {
5820  // Incomplete enum types are not treated as integer types.
5821  // FIXME: In C++, enum types are never integer types.
5822  if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
5823  return ET->getDecl()->getIntegerType().getTypePtr();
5824  return nullptr;
5825 }
5826 
5827 /// getIntegerTypeOrder - Returns the highest ranked integer type:
5828 /// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
5829 /// LHS < RHS, return -1.
5831  const Type *LHSC = getCanonicalType(LHS).getTypePtr();
5832  const Type *RHSC = getCanonicalType(RHS).getTypePtr();
5833 
5834  // Unwrap enums to their underlying type.
5835  if (const auto *ET = dyn_cast<EnumType>(LHSC))
5836  LHSC = getIntegerTypeForEnum(ET);
5837  if (const auto *ET = dyn_cast<EnumType>(RHSC))
5838  RHSC = getIntegerTypeForEnum(ET);
5839 
5840  if (LHSC == RHSC) return 0;
5841 
5842  bool LHSUnsigned = LHSC->isUnsignedIntegerType();
5843  bool RHSUnsigned = RHSC->isUnsignedIntegerType();
5844 
5845  unsigned LHSRank = getIntegerRank(LHSC);
5846  unsigned RHSRank = getIntegerRank(RHSC);
5847 
5848  if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
5849  if (LHSRank == RHSRank) return 0;
5850  return LHSRank > RHSRank ? 1 : -1;
5851  }
5852 
5853  // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
5854  if (LHSUnsigned) {
5855  // If the unsigned [LHS] type is larger, return it.
5856  if (LHSRank >= RHSRank)
5857  return 1;
5858 
5859  // If the signed type can represent all values of the unsigned type, it
5860  // wins. Because we are dealing with 2's complement and types that are
5861  // powers of two larger than each other, this is always safe.
5862  return -1;
5863  }
5864 
5865  // If the unsigned [RHS] type is larger, return it.
5866  if (RHSRank >= LHSRank)
5867  return -1;
5868 
5869  // If the signed type can represent all values of the unsigned type, it
5870  // wins. Because we are dealing with 2's complement and types that are
5871  // powers of two larger than each other, this is always safe.
5872  return 1;
5873 }
5874 
5876  if (CFConstantStringTypeDecl)
5877  return CFConstantStringTypeDecl;
5878 
5879  assert(!CFConstantStringTagDecl &&
5880  "tag and typedef should be initialized together");
5881  CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
5882  CFConstantStringTagDecl->startDefinition();
5883 
5884  struct {
5885  QualType Type;
5886  const char *Name;
5887  } Fields[5];
5888  unsigned Count = 0;
5889 
5890  /// Objective-C ABI
5891  ///
5892  /// typedef struct __NSConstantString_tag {
5893  /// const int *isa;
5894  /// int flags;
5895  /// const char *str;
5896  /// long length;
5897  /// } __NSConstantString;
5898  ///
5899  /// Swift ABI (4.1, 4.2)
5900  ///
5901  /// typedef struct __NSConstantString_tag {
5902  /// uintptr_t _cfisa;
5903  /// uintptr_t _swift_rc;
5904  /// _Atomic(uint64_t) _cfinfoa;
5905  /// const char *_ptr;
5906  /// uint32_t _length;
5907  /// } __NSConstantString;
5908  ///
5909  /// Swift ABI (5.0)
5910  ///
5911  /// typedef struct __NSConstantString_tag {
5912  /// uintptr_t _cfisa;
5913  /// uintptr_t _swift_rc;
5914  /// _Atomic(uint64_t) _cfinfoa;
5915  /// const char *_ptr;
5916  /// uintptr_t _length;
5917  /// } __NSConstantString;
5918 
5919  const auto CFRuntime = getLangOpts().CFRuntime;
5920  if (static_cast<unsigned>(CFRuntime) <
5921  static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) {
5922  Fields[Count++] = { getPointerType(IntTy.withConst()), "isa" };
5923  Fields[Count++] = { IntTy, "flags" };
5924  Fields[Count++] = { getPointerType(CharTy.withConst()), "str" };
5925  Fields[Count++] = { LongTy, "length" };
5926  } else {
5927  Fields[Count++] = { getUIntPtrType(), "_cfisa" };
5928  Fields[Count++] = { getUIntPtrType(), "_swift_rc" };
5929  Fields[Count++] = { getFromTargetType(Target->getUInt64Type()), "_swift_rc" };
5930  Fields[Count++] = { getPointerType(CharTy.withConst()), "_ptr" };
5931  if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 ||
5933  Fields[Count++] = { IntTy, "_ptr" };
5934  else
5935  Fields[Count++] = { getUIntPtrType(), "_ptr" };
5936  }
5937 
5938  // Create fields
5939  for (unsigned i = 0; i < Count; ++i) {
5940  FieldDecl *Field =
5941  FieldDecl::Create(*this, CFConstantStringTagDecl, SourceLocation(),
5942  SourceLocation(), &Idents.get(Fields[i].Name),
5943  Fields[i].Type, /*TInfo=*/nullptr,
5944  /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
5945  Field->setAccess(AS_public);
5946  CFConstantStringTagDecl->addDecl(Field);
5947  }
5948 
5949  CFConstantStringTagDecl->completeDefinition();
5950  // This type is designed to be compatible with NSConstantString, but cannot
5951  // use the same name, since NSConstantString is an interface.
5952  auto tagType = getTagDeclType(CFConstantStringTagDecl);
5953  CFConstantStringTypeDecl =
5954  buildImplicitTypedef(tagType, "__NSConstantString");
5955 
5956  return CFConstantStringTypeDecl;
5957 }
5958 
5960  if (!CFConstantStringTagDecl)
5961  getCFConstantStringDecl(); // Build the tag and the typedef.
5962  return CFConstantStringTagDecl;
5963 }
5964 
5965 // getCFConstantStringType - Return the type used for constant CFStrings.
5968 }
5969 
5971  if (ObjCSuperType.isNull()) {
5972  RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
5973  TUDecl->addDecl(ObjCSuperTypeDecl);
5974  ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
5975  }
5976  return ObjCSuperType;
5977 }
5978 
5980  const auto *TD = T->getAs<TypedefType>();
5981  assert(TD && "Invalid CFConstantStringType");
5982  CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl());
5983  const auto *TagType =
5984  CFConstantStringTypeDecl->getUnderlyingType()->getAs<RecordType>();
5985  assert(TagType && "Invalid CFConstantStringType");
5986  CFConstantStringTagDecl = TagType->getDecl();
5987 }
5988 
5990  if (BlockDescriptorType)
5991  return getTagDeclType(BlockDescriptorType);
5992 
5993  RecordDecl *RD;
5994  // FIXME: Needs the FlagAppleBlock bit.
5995  RD = buildImplicitRecord("__block_descriptor");
5996  RD->startDefinition();
5997 
5998  QualType FieldTypes[] = {
6001  };
6002 
6003  static const char *const FieldNames[] = {
6004  "reserved",
6005  "Size"
6006  };
6007 
6008  for (size_t i = 0; i < 2; ++i) {
6009  FieldDecl *Field = FieldDecl::Create(
6010  *this, RD, SourceLocation(), SourceLocation(),
6011  &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
6012  /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
6013  Field->setAccess(AS_public);
6014  RD->addDecl(Field);
6015  }
6016 
6017  RD->completeDefinition();
6018 
6019  BlockDescriptorType = RD;
6020 
6021  return getTagDeclType(BlockDescriptorType);
6022 }
6023 
6025  if (BlockDescriptorExtendedType)
6026  return getTagDeclType(BlockDescriptorExtendedType);
6027 
6028  RecordDecl *RD;
6029  // FIXME: Needs the FlagAppleBlock bit.
6030  RD = buildImplicitRecord("__block_descriptor_withcopydispose");
6031  RD->startDefinition();
6032 
6033  QualType FieldTypes[] = {
6038  };
6039 
6040  static const char *const FieldNames[] = {
6041  "reserved",
6042  "Size",
6043  "CopyFuncPtr",
6044  "DestroyFuncPtr"
6045  };
6046 
6047  for (size_t i = 0; i < 4; ++i) {
6048  FieldDecl *Field = FieldDecl::Create(
6049  *this, RD, SourceLocation(), SourceLocation(),
6050  &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
6051  /*BitWidth=*/nullptr,
6052  /*Mutable=*/false, ICIS_NoInit);
6053  Field->setAccess(AS_public);
6054  RD->addDecl(Field);
6055  }
6056 
6057  RD->completeDefinition();
6058 
6059  BlockDescriptorExtendedType = RD;
6060  return getTagDeclType(BlockDescriptorExtendedType);
6061 }
6062 
6064  const auto *BT = dyn_cast<BuiltinType>(T);
6065 
6066  if (!BT) {
6067  if (isa<PipeType>(T))
6068  return TargetInfo::OCLTK_Pipe;
6069 
6071  }
6072 
6073  switch (BT->getKind()) {
6074 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6075  case BuiltinType::Id: \
6076  return TargetInfo::OCLTK_Image;
6077 #include "clang/Basic/OpenCLImageTypes.def"
6078 
6079  case BuiltinType::OCLClkEvent:
6081 
6082  case BuiltinType::OCLEvent:
6083  return TargetInfo::OCLTK_Event;
6084 
6085  case BuiltinType::OCLQueue:
6086  return TargetInfo::OCLTK_Queue;
6087 
6088  case BuiltinType::OCLReserveID:
6090 
6091  case BuiltinType::OCLSampler:
6093 
6094  default:
6096  }
6097 }
6098 
6100  return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
6101 }
6102 
6103 /// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
6104 /// requires copy/dispose. Note that this must match the logic
6105 /// in buildByrefHelpers.
6107  const VarDecl *D) {
6108  if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
6109  const Expr *copyExpr = getBlockVarCopyInit(D).getCopyExpr();
6110  if (!copyExpr && record->hasTrivialDestructor()) return false;
6111 
6112  return true;
6113  }
6114 
6115  // The block needs copy/destroy helpers if Ty is non-trivial to destructively
6116  // move or destroy.
6118  return true;
6119 
6120  if (!Ty->isObjCRetainableType()) return false;
6121 
6122  Qualifiers qs = Ty.getQualifiers();
6123 
6124  // If we have lifetime, that dominates.
6125  if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
6126  switch (lifetime) {
6127  case Qualifiers::OCL_None: llvm_unreachable("impossible");
6128 
6129  // These are just bits as far as the runtime is concerned.
6132  return false;
6133 
6134  // These cases should have been taken care of when checking the type's
6135  // non-triviality.
6136  case Qualifiers::OCL_Weak:
6138  llvm_unreachable("impossible");
6139  }
6140  llvm_unreachable("fell out of lifetime switch!");
6141  }
6142  return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
6143  Ty->isObjCObjectPointerType());
6144 }
6145 
6147  Qualifiers::ObjCLifetime &LifeTime,
6148  bool &HasByrefExtendedLayout) const {
6149  if (!getLangOpts().ObjC ||
6150  getLangOpts().getGC() != LangOptions::NonGC)
6151  return false;
6152 
6153  HasByrefExtendedLayout = false;
6154  if (Ty->isRecordType()) {
6155  HasByrefExtendedLayout = true;
6156  LifeTime = Qualifiers::OCL_None;
6157  } else if ((LifeTime = Ty.getObjCLifetime())) {
6158  // Honor the ARC qualifiers.
6159  } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
6160  // The MRR rule.
6161  LifeTime = Qualifiers::OCL_ExplicitNone;
6162  } else {
6163  LifeTime = Qualifiers::OCL_None;
6164  }
6165  return true;
6166 }
6167 
6169  if (!ObjCInstanceTypeDecl)
6170  ObjCInstanceTypeDecl =
6171  buildImplicitTypedef(getObjCIdType(), "instancetype");
6172  return ObjCInstanceTypeDecl;
6173 }
6174 
6175 // This returns true if a type has been typedefed to BOOL:
6176 // typedef <type> BOOL;
6178  if (const auto *TT = dyn_cast<TypedefType>(T))
6179  if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
6180  return II->isStr("BOOL");
6181 
6182  return false;
6183 }
6184 
6185 /// getObjCEncodingTypeSize returns size of type for objective-c encoding
6186 /// purpose.
6188  if (!type->isIncompleteArrayType() && type->isIncompleteType())
6189  return CharUnits::Zero();
6190 
6191  CharUnits sz = getTypeSizeInChars(type);
6192 
6193  // Make all integer and enum types at least as large as an int
6194  if (sz.isPositive() && type->isIntegralOrEnumerationType())
6195  sz = std::max(sz, getTypeSizeInChars(IntTy));
6196  // Treat arrays as pointers, since that's how they're passed in.
6197  else if (type->isArrayType())
6199  return sz;
6200 }
6201 
6203  return getTargetInfo().getCXXABI().isMicrosoft() &&
6204  VD->isStaticDataMember() &&
6206  !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
6207 }
6208 
6211  if (!VD->isInline())
6213 
6214  // In almost all cases, it's a weak definition.
6215  auto *First = VD->getFirstDecl();
6216  if (First->isInlineSpecified() || !First->isStaticDataMember())
6218 
6219  // If there's a file-context declaration in this translation unit, it's a
6220  // non-discardable definition.
6221  for (auto *D : VD->redecls())
6222  if (D->getLexicalDeclContext()->isFileContext() &&
6223  !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr()))
6225 
6226  // If we've not seen one yet, we don't know.
6228 }
6229 
6230 static std::string charUnitsToString(const CharUnits &CU) {
6231  return llvm::itostr(CU.getQuantity());
6232 }
6233 
6234 /// getObjCEncodingForBlock - Return the encoded type for this block
6235 /// declaration.
6237  std::string S;
6238 
6239  const BlockDecl *Decl = Expr->getBlockDecl();
6240  QualType BlockTy =
6241  Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
6242  // Encode result type.
6243  if (getLangOpts().EncodeExtendedBlockSig)
6246  true /*Extended*/);
6247  else
6249  // Compute size of all parameters.
6250  // Start with computing size of a pointer in number of bytes.
6251  // FIXME: There might(should) be a better way of doing this computation!
6253  CharUnits ParmOffset = PtrSize;
6254  for (auto PI : Decl->parameters()) {
6255  QualType PType = PI->getType();
6256  CharUnits sz = getObjCEncodingTypeSize(PType);
6257  if (sz.isZero())
6258  continue;
6259  assert(sz.isPositive() && "BlockExpr - Incomplete param type");
6260  ParmOffset += sz;
6261  }
6262  // Size of the argument frame
6263  S += charUnitsToString(ParmOffset);
6264  // Block pointer and offset.
6265  S += "@?0";
6266 
6267  // Argument types.
6268  ParmOffset = PtrSize;
6269  for (auto PVDecl : Decl->parameters()) {
6270  QualType PType = PVDecl->getOriginalType();
6271  if (const auto *AT =
6272  dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
6273  // Use array's original type only if it has known number of
6274  // elements.
6275  if (!isa<ConstantArrayType>(AT))
6276  PType = PVDecl->getType();
6277  } else if (PType->isFunctionType())
6278  PType = PVDecl->getType();
6279  if (getLangOpts().EncodeExtendedBlockSig)
6281  S, true /*Extended*/);
6282  else
6283  getObjCEncodingForType(PType, S);
6284  S += charUnitsToString(ParmOffset);
6285  ParmOffset += getObjCEncodingTypeSize(PType);
6286  }
6287 
6288  return S;
6289 }
6290 
6291 std::string
6293  std::string S;
6294  // Encode result type.
6296  CharUnits ParmOffset;
6297  // Compute size of all parameters.
6298  for (auto PI : Decl->parameters()) {
6299  QualType PType = PI->getType();
6300  CharUnits sz = getObjCEncodingTypeSize(PType);
6301  if (sz.isZero())
6302  continue;
6303 
6304  assert(sz.isPositive() &&
6305  "getObjCEncodingForFunctionDecl - Incomplete param type");
6306  ParmOffset += sz;
6307  }
6308  S += charUnitsToString(ParmOffset);
6309  ParmOffset = CharUnits::Zero();
6310 
6311  // Argument types.
6312  for (auto PVDecl : Decl->parameters()) {
6313  QualType PType = PVDecl->getOriginalType();
6314  if (const auto *AT =
6315  dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
6316  // Use array's original type only if it has known number of
6317  // elements.
6318  if (!isa<ConstantArrayType>(AT))
6319  PType = PVDecl->getType();
6320  } else if (PType->isFunctionType())
6321  PType = PVDecl->getType();
6322  getObjCEncodingForType(PType, S);
6323  S += charUnitsToString(ParmOffset);
6324  ParmOffset += getObjCEncodingTypeSize(PType);
6325  }
6326 
6327  return S;
6328 }
6329 
6330 /// getObjCEncodingForMethodParameter - Return the encoded type for a single
6331 /// method parameter or return type. If Extended, include class names and
6332 /// block object types.
6334  QualType T, std::string& S,
6335  bool Extended) const {
6336  // Encode type qualifer, 'in', 'inout', etc. for the parameter.
6338  // Encode parameter type.
6339  ObjCEncOptions Options = ObjCEncOptions()
6340  .setExpandPointedToStructures()
6341  .setExpandStructures()
6342  .setIsOutermostType();
6343  if (Extended)
6344  Options.setEncodeBlockParameters().setEncodeClassNames();
6345  getObjCEncodingForTypeImpl(T, S, Options, /*Field=*/nullptr);
6346 }
6347 
6348 /// getObjCEncodingForMethodDecl - Return the encoded type for this method
6349 /// declaration.
6351  bool Extended) const {
6352  // FIXME: This is not very efficient.
6353  // Encode return type.
6354  std::string S;
6356  Decl->getReturnType(), S, Extended);
6357  // Compute size of all parameters.
6358  // Start with computing size of a pointer in number of bytes.
6359  // FIXME: There might(should) be a better way of doing this computation!
6361  // The first two arguments (self and _cmd) are pointers; account for
6362  // their size.
6363  CharUnits ParmOffset = 2 * PtrSize;
6365  E = Decl->sel_param_end(); PI != E; ++PI) {
6366  QualType PType = (*PI)->getType();
6367  CharUnits sz = getObjCEncodingTypeSize(PType);
6368  if (sz.isZero())
6369  continue;
6370 
6371  assert(sz.isPositive() &&
6372  "getObjCEncodingForMethodDecl - Incomplete param type");
6373  ParmOffset += sz;
6374  }
6375  S += charUnitsToString(ParmOffset);
6376  S += "@0:";
6377  S += charUnitsToString(PtrSize);
6378 
6379  // Argument types.
6380  ParmOffset = 2 * PtrSize;
6382  E = Decl->sel_param_end(); PI != E; ++PI) {
6383  const ParmVarDecl *PVDecl = *PI;
6384  QualType PType = PVDecl->getOriginalType();
6385  if (const auto *AT =
6386  dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
6387  // Use array's original type only if it has known number of
6388  // elements.
6389  if (!isa<ConstantArrayType>(AT))
6390  PType = PVDecl->getType();
6391  } else if (PType->isFunctionType())
6392  PType = PVDecl->getType();
6394  PType, S, Extended);
6395  S += charUnitsToString(ParmOffset);
6396  ParmOffset += getObjCEncodingTypeSize(PType);
6397  }
6398 
6399  return S;
6400 }
6401 
6404  const ObjCPropertyDecl *PD,
6405  const Decl *Container) const {
6406  if (!Container)
6407  return nullptr;
6408  if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) {
6409  for (auto *PID : CID->property_impls())
6410  if (PID->getPropertyDecl() == PD)
6411  return PID;
6412  } else {
6413  const auto *OID = cast<ObjCImplementationDecl>(Container);
6414  for (auto *PID : OID->property_impls())
6415  if (PID->getPropertyDecl() == PD)
6416  return PID;
6417  }
6418  return nullptr;
6419 }
6420 
6421 /// getObjCEncodingForPropertyDecl - Return the encoded type for this
6422 /// property declaration. If non-NULL, Container must be either an
6423 /// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
6424 /// NULL when getting encodings for protocol properties.
6425 /// Property attributes are stored as a comma-delimited C string. The simple
6426 /// attributes readonly and bycopy are encoded as single characters. The
6427 /// parametrized attributes, getter=name, setter=name, and ivar=name, are
6428 /// encoded as single characters, followed by an identifier. Property types
6429 /// are also encoded as a parametrized attribute. The characters used to encode
6430 /// these attributes are defined by the following enumeration:
6431 /// @code
6432 /// enum PropertyAttributes {
6433 /// kPropertyReadOnly = 'R', // property is read-only.
6434 /// kPropertyBycopy = 'C', // property is a copy of the value last assigned
6435 /// kPropertyByref = '&', // property is a reference to the value last assigned
6436 /// kPropertyDynamic = 'D', // property is dynamic
6437 /// kPropertyGetter = 'G', // followed by getter selector name
6438 /// kPropertySetter = 'S', // followed by setter selector name
6439 /// kPropertyInstanceVariable = 'V' // followed by instance variable name
6440 /// kPropertyType = 'T' // followed by old-style type encoding.
6441 /// kPropertyWeak = 'W' // 'weak' property
6442 /// kPropertyStrong = 'P' // property GC'able
6443 /// kPropertyNonAtomic = 'N' // property non-atomic
6444 /// };
6445 /// @endcode
6446 std::string
6448  const Decl *Container) const {
6449  // Collect information from the property implementation decl(s).
6450  bool Dynamic = false;
6451  ObjCPropertyImplDecl *SynthesizePID = nullptr;
6452 
6453  if (ObjCPropertyImplDecl *PropertyImpDecl =
6454  getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
6455  if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
6456  Dynamic = true;
6457  else
6458  SynthesizePID = PropertyImpDecl;
6459  }
6460 
6461  // FIXME: This is not very efficient.
6462  std::string S = "T";
6463 
6464  // Encode result type.
6465  // GCC has some special rules regarding encoding of properties which
6466  // closely resembles encoding of ivars.
6468 
6469  if (PD->isReadOnly()) {
6470  S += ",R";
6472  S += ",C";
6474  S += ",&";
6476  S += ",W";
6477  } else {
6478  switch (PD->getSetterKind()) {
6479  case ObjCPropertyDecl::Assign: break;
6480  case ObjCPropertyDecl::Copy: S += ",C"; break;
6481  case ObjCPropertyDecl::Retain: S += ",&"; break;
6482  case ObjCPropertyDecl::Weak: S += ",W"; break;
6483  }
6484  }
6485 
6486  // It really isn't clear at all what this means, since properties
6487  // are "dynamic by default".
6488  if (Dynamic)
6489  S += ",D";
6490 
6492  S += ",N";
6493 
6495  S += ",G";
6496  S += PD->getGetterName().getAsString();
6497  }
6498 
6500  S += ",S";
6501  S += PD->getSetterName().getAsString();
6502  }
6503 
6504  if (SynthesizePID) {
6505  const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
6506  S += ",V";
6507  S += OID->getNameAsString();
6508  }
6509 
6510  // FIXME: OBJCGC: weak & strong
6511  return S;
6512 }
6513 
6514 /// getLegacyIntegralTypeEncoding -
6515 /// Another legacy compatibility encoding: 32-bit longs are encoded as
6516 /// 'l' or 'L' , but not always. For typedefs, we need to use
6517 /// 'i' or 'I' instead if encoding a struct field, or a pointer!
6519  if (isa<TypedefType>(PointeeTy.getTypePtr())) {
6520  if (const auto *BT = PointeeTy->getAs<BuiltinType>()) {
6521  if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
6522  PointeeTy = UnsignedIntTy;
6523  else
6524  if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
6525  PointeeTy = IntTy;
6526  }
6527  }
6528 }
6529 
6531  const FieldDecl *Field,
6532  QualType *NotEncodedT) const {
6533  // We follow the behavior of gcc, expanding structures which are
6534  // directly pointed to, and expanding embedded structures. Note that
6535  // these rules are sufficient to prevent recursive encoding of the
6536  // same type.
6537  getObjCEncodingForTypeImpl(T, S,
6538  ObjCEncOptions()
6539  .setExpandPointedToStructures()
6540  .setExpandStructures()
6541  .setIsOutermostType(),
6542  Field, NotEncodedT);
6543 }
6544 
6546  std::string& S) const {
6547  // Encode result type.
6548  // GCC has some special rules regarding encoding of properties which
6549  // closely resembles encoding of ivars.
6550  getObjCEncodingForTypeImpl(T, S,
6551  ObjCEncOptions()
6552  .setExpandPointedToStructures()
6553  .setExpandStructures()
6554  .setIsOutermostType()
6555  .setEncodingProperty(),
6556  /*Field=*/nullptr);
6557 }
6558 
6561  switch (kind) {
6562  case BuiltinType::Void: return 'v';
6563  case BuiltinType::Bool: return 'B';
6564  case BuiltinType::Char8:
6565  case BuiltinType::Char_U:
6566  case BuiltinType::UChar: return 'C';
6567  case BuiltinType::Char16:
6568  case BuiltinType::UShort: return 'S';
6569  case BuiltinType::Char32:
6570  case BuiltinType::UInt: return 'I';
6571  case BuiltinType::ULong:
6572  return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
6573  case BuiltinType::UInt128: return 'T';
6574  case BuiltinType::ULongLong: return 'Q';
6575  case BuiltinType::Char_S:
6576  case BuiltinType::SChar: return 'c';
6577  case BuiltinType::Short: return 's';
6578  case BuiltinType::WChar_S:
6579  case BuiltinType::WChar_U:
6580  case BuiltinType::Int: return 'i';
6581  case BuiltinType::Long:
6582  return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
6583  case BuiltinType::LongLong: return 'q';
6584  case BuiltinType::Int128: return 't';
6585  case BuiltinType::Float: return 'f';
6586  case BuiltinType::Double: return 'd';
6587  case BuiltinType::LongDouble: return 'D';
6588  case BuiltinType::NullPtr: return '*'; // like char*
6589 
6590  case BuiltinType::Float16:
6591  case BuiltinType::Float128:
6592  case BuiltinType::Half:
6593  case BuiltinType::ShortAccum:
6594  case BuiltinType::Accum:
6595  case BuiltinType::LongAccum:
6596  case BuiltinType::UShortAccum:
6597  case BuiltinType::UAccum:
6598  case BuiltinType::ULongAccum:
6599  case BuiltinType::ShortFract:
6600  case BuiltinType::Fract:
6601  case BuiltinType::LongFract:
6602  case BuiltinType::UShortFract:
6603  case BuiltinType::UFract:
6604  case BuiltinType::ULongFract:
6605  case BuiltinType::SatShortAccum:
6606  case BuiltinType::SatAccum:
6607  case BuiltinType::SatLongAccum:
6608  case BuiltinType::SatUShortAccum:
6609  case BuiltinType::SatUAccum:
6610  case BuiltinType::SatULongAccum:
6611  case BuiltinType::SatShortFract:
6612  case BuiltinType::SatFract:
6613  case BuiltinType::SatLongFract:
6614  case BuiltinType::SatUShortFract:
6615  case BuiltinType::SatUFract:
6616  case BuiltinType::SatULongFract:
6617  // FIXME: potentially need @encodes for these!
6618  return ' ';
6619 
6620  case BuiltinType::ObjCId:
6621  case BuiltinType::ObjCClass:
6622  case BuiltinType::ObjCSel:
6623  llvm_unreachable("@encoding ObjC primitive type");
6624 
6625  // OpenCL and placeholder types don't need @encodings.
6626 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6627  case BuiltinType::Id:
6628 #include "clang/Basic/OpenCLImageTypes.def"
6629 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6630  case BuiltinType::Id:
6631 #include "clang/Basic/OpenCLExtensionTypes.def"
6632  case BuiltinType::OCLEvent:
6633  case BuiltinType::OCLClkEvent:
6634  case BuiltinType::OCLQueue:
6635  case BuiltinType::OCLReserveID:
6636  case BuiltinType::OCLSampler:
6637  case BuiltinType::Dependent:
6638 #define BUILTIN_TYPE(KIND, ID)
6639 #define PLACEHOLDER_TYPE(KIND, ID) \
6640  case BuiltinType::KIND:
6641 #include "clang/AST/BuiltinTypes.def"
6642  llvm_unreachable("invalid builtin type for @encode");
6643  }
6644  llvm_unreachable("invalid BuiltinType::Kind value");
6645 }
6646 
6647 static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
6648  EnumDecl *Enum = ET->getDecl();
6649 
6650  // The encoding of an non-fixed enum type is always 'i', regardless of size.
6651  if (!Enum->isFixed())
6652  return 'i';
6653 
6654  // The encoding of a fixed enum type matches its fixed underlying type.
6655  const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>();
6656  return getObjCEncodingForPrimitiveKind(C, BT->getKind());
6657 }
6658 
6659 static void EncodeBitField(const ASTContext *Ctx, std::string& S,
6660  QualType T, const FieldDecl *FD) {
6661  assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
6662  S += 'b';
6663  // The NeXT runtime encodes bit fields as b followed by the number of bits.
6664  // The GNU runtime requires more information; bitfields are encoded as b,
6665  // then the offset (in bits) of the first element, then the type of the
6666  // bitfield, then the size in bits. For example, in this structure:
6667  //
6668  // struct
6669  // {
6670  // int integer;
6671  // int flags:2;
6672  // };
6673  // On a 32-bit system, the encoding for flags would be b2 for the NeXT
6674  // runtime, but b32i2 for the GNU runtime. The reason for this extra
6675  // information is not especially sensible, but we're stuck with it for
6676  // compatibility with GCC, although providing it breaks anything that
6677  // actually uses runtime introspection and wants to work on both runtimes...
6678  if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
6679  uint64_t Offset;
6680 
6681  if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) {
6682  Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), nullptr,
6683  IVD);
6684  } else {
6685  const RecordDecl *RD = FD->getParent();
6686  const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
6687  Offset = RL.getFieldOffset(FD->getFieldIndex());
6688  }
6689 
6690  S += llvm::utostr(Offset);
6691 
6692  if (const auto *ET = T->getAs<EnumType>())
6693  S += ObjCEncodingForEnumType(Ctx, ET);
6694  else {
6695  const auto *BT = T->castAs<BuiltinType>();
6696  S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
6697  }
6698  }
6699  S += llvm::utostr(FD->getBitWidthValue(*Ctx));
6700 }
6701 
6702 // FIXME: Use SmallString for accumulating string.
6703 void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S,
6704  const ObjCEncOptions Options,
6705  const FieldDecl *FD,
6706  QualType *NotEncodedT) const {
6707  CanQualType CT = getCanonicalType(T);
6708  switch (CT->getTypeClass()) {
6709  case Type::Builtin:
6710  case Type::Enum:
6711  if (FD && FD->isBitField())
6712  return EncodeBitField(this, S, T, FD);
6713  if (const auto *BT = dyn_cast<BuiltinType>(CT))
6714  S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
6715  else
6716  S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
6717  return;
6718 
6719  case Type::Complex: {
6720  const auto *CT = T->castAs<ComplexType>();
6721  S += 'j';
6722  getObjCEncodingForTypeImpl(CT->getElementType(), S, ObjCEncOptions(),
6723  /*Field=*/nullptr);
6724  return;
6725  }
6726 
6727  case Type::Atomic: {
6728  const auto *AT = T->castAs<AtomicType>();
6729  S += 'A';
6730  getObjCEncodingForTypeImpl(AT->getValueType(), S, ObjCEncOptions(),
6731  /*Field=*/nullptr);
6732  return;
6733  }
6734 
6735  // encoding for pointer or reference types.
6736  case Type::Pointer:
6737  case Type::LValueReference:
6738  case Type::RValueReference: {
6739  QualType PointeeTy;
6740  if (isa<PointerType>(CT)) {
6741  const auto *PT = T->castAs<PointerType>();
6742  if (PT->isObjCSelType()) {
6743  S += ':';
6744  return;
6745  }
6746  PointeeTy = PT->getPointeeType();
6747  } else {
6748  PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
6749  }
6750 
6751  bool isReadOnly = false;
6752  // For historical/compatibility reasons, the read-only qualifier of the
6753  // pointee gets emitted _before_ the '^'. The read-only qualifier of
6754  // the pointer itself gets ignored, _unless_ we are looking at a typedef!
6755  // Also, do not emit the 'r' for anything but the outermost type!
6756  if (isa<TypedefType>(T.getTypePtr())) {
6757  if (Options.IsOutermostType() && T.isConstQualified()) {
6758  isReadOnly = true;
6759  S += 'r';
6760  }
6761  } else if (Options.IsOutermostType()) {
6762  QualType P = PointeeTy;
6763  while (P->getAs<PointerType>())
6764  P = P->getAs<PointerType>()->getPointeeType();
6765  if (P.isConstQualified()) {
6766  isReadOnly = true;
6767  S += 'r';
6768  }
6769  }
6770  if (isReadOnly) {
6771  // Another legacy compatibility encoding. Some ObjC qualifier and type
6772  // combinations need to be rearranged.
6773  // Rewrite "in const" from "nr" to "rn"
6774  if (StringRef(S).endswith("nr"))
6775  S.replace(S.end()-2, S.end(), "rn");
6776  }
6777 
6778  if (PointeeTy->isCharType()) {
6779  // char pointer types should be encoded as '*' unless it is a
6780  // type that has been typedef'd to 'BOOL'.
6781  if (!isTypeTypedefedAsBOOL(PointeeTy)) {
6782  S += '*';
6783  return;
6784  }
6785  } else if (const auto *RTy = PointeeTy->getAs<RecordType>()) {
6786  // GCC binary compat: Need to convert "struct objc_class *" to "#".
6787  if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
6788  S += '#';
6789  return;
6790  }
6791  // GCC binary compat: Need to convert "struct objc_object *" to "@".
6792  if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
6793  S += '@';
6794  return;
6795  }
6796  // fall through...
6797  }
6798  S += '^';
6799  getLegacyIntegralTypeEncoding(PointeeTy);
6800 
6801  ObjCEncOptions NewOptions;
6802  if (Options.ExpandPointedToStructures())
6803  NewOptions.setExpandStructures();
6804  getObjCEncodingForTypeImpl(PointeeTy, S, NewOptions,
6805  /*Field=*/nullptr, NotEncodedT);
6806  return;
6807  }
6808 
6809  case Type::ConstantArray:
6810  case Type::IncompleteArray:
6811  case Type::VariableArray: {
6812  const auto *AT = cast<ArrayType>(CT);
6813 
6814  if (isa<IncompleteArrayType>(AT) && !Options.IsStructField()) {
6815  // Incomplete arrays are encoded as a pointer to the array element.
6816  S += '^';
6817 
6818  getObjCEncodingForTypeImpl(
6819  AT->getElementType(), S,
6820  Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD);
6821  } else {
6822  S += '[';
6823 
6824  if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
6825  S += llvm::utostr(CAT->getSize().getZExtValue());
6826  else {
6827  //Variable length arrays are encoded as a regular array with 0 elements.
6828  assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
6829  "Unknown array type!");
6830  S += '0';
6831  }
6832 
6833  getObjCEncodingForTypeImpl(
6834  AT->getElementType(), S,
6835  Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD,
6836  NotEncodedT);
6837  S += ']';
6838  }
6839  return;
6840  }
6841 
6842  case Type::FunctionNoProto:
6843  case Type::FunctionProto:
6844  S += '?';
6845  return;
6846 
6847  case Type::Record: {
6848  RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
6849  S += RDecl->isUnion() ? '(' : '{';
6850  // Anonymous structures print as '?'
6851  if (const IdentifierInfo *II = RDecl->getIdentifier()) {
6852  S += II->getName();
6853  if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
6854  const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
6855  llvm::raw_string_ostream OS(S);
6856  printTemplateArgumentList(OS, TemplateArgs.asArray(),
6857  getPrintingPolicy());
6858  }
6859  } else {
6860  S += '?';
6861  }
6862  if (Options.ExpandStructures()) {
6863  S += '=';
6864  if (!RDecl->isUnion()) {
6865  getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
6866  } else {
6867  for (const auto *Field : RDecl->fields()) {
6868  if (FD) {
6869  S += '"';
6870  S += Field->getNameAsString();
6871  S += '"';
6872  }
6873 
6874  // Special case bit-fields.
6875  if (Field->isBitField()) {
6876  getObjCEncodingForTypeImpl(Field->getType(), S,
6877  ObjCEncOptions().setExpandStructures(),
6878  Field);
6879  } else {
6880  QualType qt = Field->getType();
6882  getObjCEncodingForTypeImpl(
6883  qt, S,
6884  ObjCEncOptions().setExpandStructures().setIsStructField(), FD,
6885  NotEncodedT);
6886  }
6887  }
6888  }
6889  }
6890  S += RDecl->isUnion() ? ')' : '}';
6891  return;
6892  }
6893 
6894  case Type::BlockPointer: {
6895  const auto *BT = T->castAs<BlockPointerType>();
6896  S += "@?"; // Unlike a pointer-to-function, which is "^?".
6897  if (Options.EncodeBlockParameters()) {
6898  const auto *FT = BT->getPointeeType()->castAs<FunctionType>();
6899 
6900  S += '<';
6901  // Block return type
6902  getObjCEncodingForTypeImpl(FT->getReturnType(), S,
6903  Options.forComponentType(), FD, NotEncodedT);
6904  // Block self
6905  S += "@?";
6906  // Block parameters
6907  if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) {
6908  for (const auto &I : FPT->param_types())
6909  getObjCEncodingForTypeImpl(I, S, Options.forComponentType(), FD,
6910  NotEncodedT);
6911  }
6912  S += '>';
6913  }
6914  return;
6915  }
6916 
6917  case Type::ObjCObject: {
6918  // hack to match legacy encoding of *id and *Class
6920  if (Ty->isObjCIdType()) {
6921  S += "{objc_object=}";
6922  return;
6923  }
6924  else if (Ty->isObjCClassType()) {
6925  S += "{objc_class=}";
6926  return;
6927  }
6928  // TODO: Double check to make sure this intentionally falls through.
6929  LLVM_FALLTHROUGH;
6930  }
6931 
6932  case Type::ObjCInterface: {
6933  // Ignore protocol qualifiers when mangling at this level.
6934  // @encode(class_name)
6935  ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
6936  S += '{';
6937  S += OI->getObjCRuntimeNameAsString();
6938  if (Options.ExpandStructures()) {
6939  S += '=';
6941  DeepCollectObjCIvars(OI, true, Ivars);
6942  for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
6943  const FieldDecl *Field = Ivars[i];
6944  if (Field->isBitField())
6945  getObjCEncodingForTypeImpl(Field->getType(), S,
6946  ObjCEncOptions().setExpandStructures(),
6947  Field);
6948  else
6949  getObjCEncodingForTypeImpl(Field->getType(), S,
6950  ObjCEncOptions().setExpandStructures(), FD,
6951  NotEncodedT);
6952  }
6953  }
6954  S += '}';
6955  return;
6956  }
6957 
6958  case Type::ObjCObjectPointer: {
6959  const auto *OPT = T->castAs<ObjCObjectPointerType>();
6960  if (OPT->isObjCIdType()) {
6961  S += '@';
6962  return;
6963  }
6964 
6965  if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
6966  // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
6967  // Since this is a binary compatibility issue, need to consult with
6968  // runtime folks. Fortunately, this is a *very* obscure construct.
6969  S += '#';
6970  return;
6971  }
6972 
6973  if (OPT->isObjCQualifiedIdType()) {
6974  getObjCEncodingForTypeImpl(
6975  getObjCIdType(), S,
6976  Options.keepingOnly(ObjCEncOptions()
6977  .setExpandPointedToStructures()
6978  .setExpandStructures()),
6979  FD);
6980  if (FD || Options.EncodingProperty() || Options.EncodeClassNames()) {
6981  // Note that we do extended encoding of protocol qualifer list
6982  // Only when doing ivar or property encoding.
6983  S += '"';
6984  for (const auto *I : OPT->quals()) {
6985  S += '<';
6986  S += I->getObjCRuntimeNameAsString();
6987  S += '>';
6988  }
6989  S += '"';
6990  }
6991  return;
6992  }
6993 
6994  S += '@';
6995  if (OPT->getInterfaceDecl() &&
6996  (FD || Options.EncodingProperty() || Options.EncodeClassNames())) {
6997  S += '"';
6999  for (const auto *I : OPT->quals()) {
7000  S += '<';
7001  S += I->getObjCRuntimeNameAsString();
7002  S += '>';
7003  }
7004  S += '"';
7005  }
7006  return;
7007  }
7008 
7009  // gcc just blithely ignores member pointers.
7010  // FIXME: we should do better than that. 'M' is available.
7011  case Type::MemberPointer:
7012  // This matches gcc's encoding, even though technically it is insufficient.
7013  //FIXME. We should do a better job than gcc.
7014  case Type::Vector:
7015  case Type::ExtVector:
7016  // Until we have a coherent encoding of these three types, issue warning.
7017  if (NotEncodedT)
7018  *NotEncodedT = T;
7019  return;
7020 
7021  // We could see an undeduced auto type here during error recovery.
7022  // Just ignore it.
7023  case Type::Auto:
7024  case Type::DeducedTemplateSpecialization:
7025  return;
7026 
7027  case Type::Pipe:
7028 #define ABSTRACT_TYPE(KIND, BASE)
7029 #define TYPE(KIND, BASE)
7030 #define DEPENDENT_TYPE(KIND, BASE) \
7031  case Type::KIND:
7032 #define NON_CANONICAL_TYPE(KIND, BASE) \
7033  case Type::KIND:
7034 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
7035  case Type::KIND:
7036 #include "clang/AST/TypeNodes.def"
7037  llvm_unreachable("@encode for dependent type!");
7038  }
7039  llvm_unreachable("bad type kind!");
7040 }
7041 
7042 void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
7043  std::string &S,
7044  const FieldDecl *FD,
7045  bool includeVBases,
7046  QualType *NotEncodedT) const {
7047  assert(RDecl && "Expected non-null RecordDecl");
7048  assert(!RDecl->isUnion() && "Should not be called for unions");
7049  if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
7050  return;
7051 
7052  const auto *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
7053  std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
7054  const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
7055 
7056  if (CXXRec) {
7057  for (const auto &BI : CXXRec->bases()) {
7058  if (!BI.isVirtual()) {
7059  CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
7060  if (base->isEmpty())
7061  continue;
7062  uint64_t offs = toBits(layout.getBaseClassOffset(base));
7063  FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
7064  std::make_pair(offs, base));
7065  }
7066  }
7067  }
7068 
7069  unsigned i = 0;
7070  for (auto *Field : RDecl->fields()) {
7071  uint64_t offs = layout.getFieldOffset(i);
7072  FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
7073  std::make_pair(offs, Field));
7074  ++i;
7075  }
7076 
7077  if (CXXRec && includeVBases) {
7078  for (const auto &BI : CXXRec->vbases()) {
7079  CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
7080  if (base->isEmpty())
7081  continue;
7082  uint64_t offs = toBits(layout.getVBaseClassOffset(base));
7083  if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
7084  FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
7085  FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
7086  std::make_pair(offs, base));
7087  }
7088  }
7089 
7090  CharUnits size;
7091  if (CXXRec) {
7092  size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
7093  } else {
7094  size = layout.getSize();
7095  }
7096 
7097 #ifndef NDEBUG
7098  uint64_t CurOffs = 0;
7099 #endif
7100  std::multimap<uint64_t, NamedDecl *>::iterator
7101  CurLayObj = FieldOrBaseOffsets.begin();
7102 
7103  if (CXXRec && CXXRec->isDynamicClass() &&
7104  (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
7105  if (FD) {
7106  S += "\"_vptr$";
7107  std::string recname = CXXRec->getNameAsString();
7108  if (recname.empty()) recname = "?";
7109  S += recname;
7110  S += '"';
7111  }
7112  S += "^^?";
7113 #ifndef NDEBUG
7114  CurOffs += getTypeSize(VoidPtrTy);
7115 #endif
7116  }
7117 
7118  if (!RDecl->hasFlexibleArrayMember()) {
7119  // Mark the end of the structure.
7120  uint64_t offs = toBits(size);
7121  FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
7122  std::make_pair(offs, nullptr));
7123  }
7124 
7125  for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
7126 #ifndef NDEBUG
7127  assert(CurOffs <= CurLayObj->first);
7128  if (CurOffs < CurLayObj->first) {
7129  uint64_t padding = CurLayObj->first - CurOffs;
7130  // FIXME: There doesn't seem to be a way to indicate in the encoding that
7131  // packing/alignment of members is different that normal, in which case
7132  // the encoding will be out-of-sync with the real layout.
7133  // If the runtime switches to just consider the size of types without
7134  // taking into account alignment, we could make padding explicit in the
7135  // encoding (e.g. using arrays of chars). The encoding strings would be
7136  // longer then though.
7137  CurOffs += padding;
7138  }
7139 #endif
7140 
7141  NamedDecl *dcl = CurLayObj->second;
7142  if (!dcl)
7143  break; // reached end of structure.
7144 
7145  if (auto *base = dyn_cast<CXXRecordDecl>(dcl)) {
7146  // We expand the bases without their virtual bases since those are going
7147  // in the initial structure. Note that this differs from gcc which
7148  // expands virtual bases each time one is encountered in the hierarchy,
7149  // making the encoding type bigger than it really is.
7150  getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
7151  NotEncodedT);
7152  assert(!base->isEmpty());
7153 #ifndef NDEBUG
7154  CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
7155 #endif
7156  } else {
7157  const auto *field = cast<FieldDecl>(dcl);
7158  if (FD) {
7159  S += '"';
7160  S += field->getNameAsString();
7161  S += '"';
7162  }
7163 
7164  if (field->isBitField()) {
7165  EncodeBitField(this, S, field->getType(), field);
7166 #ifndef NDEBUG
7167  CurOffs += field->getBitWidthValue(*this);
7168 #endif
7169  } else {
7170  QualType qt = field->getType();
7172  getObjCEncodingForTypeImpl(
7173  qt, S, ObjCEncOptions().setExpandStructures().setIsStructField(),
7174  FD, NotEncodedT);
7175 #ifndef NDEBUG
7176  CurOffs += getTypeSize(field->getType());
7177 #endif
7178  }
7179  }
7180  }
7181 }
7182 
7184  std::string& S) const {
7185  if (QT & Decl::OBJC_TQ_In)
7186  S += 'n';
7187  if (QT & Decl::OBJC_TQ_Inout)
7188  S += 'N';
7189  if (QT & Decl::OBJC_TQ_Out)
7190  S += 'o';
7191  if (QT & Decl::OBJC_TQ_Bycopy)
7192  S += 'O';
7193  if (QT & Decl::OBJC_TQ_Byref)
7194  S += 'R';
7195  if (QT & Decl::OBJC_TQ_Oneway)
7196  S += 'V';
7197 }
7198 
7200  if (!ObjCIdDecl) {
7202  T = getObjCObjectPointerType(T);
7203  ObjCIdDecl = buildImplicitTypedef(T, "id");
7204  }
7205  return ObjCIdDecl;
7206 }
7207 
7209  if (!ObjCSelDecl) {
7211  ObjCSelDecl = buildImplicitTypedef(T, "SEL");
7212  }
7213  return ObjCSelDecl;
7214 }
7215 
7217  if (!ObjCClassDecl) {
7219  T = getObjCObjectPointerType(T);
7220  ObjCClassDecl = buildImplicitTypedef(T, "Class");
7221  }
7222  return ObjCClassDecl;
7223 }
7224 
7226  if (!ObjCProtocolClassDecl) {
7227  ObjCProtocolClassDecl
7229  SourceLocation(),
7230  &Idents.get("Protocol"),
7231  /*typeParamList=*/nullptr,
7232  /*PrevDecl=*/nullptr,
7233  SourceLocation(), true);
7234  }
7235 
7236  return ObjCProtocolClassDecl;
7237 }
7238 
7239 //===----------------------------------------------------------------------===//
7240 // __builtin_va_list Construction Functions
7241 //===----------------------------------------------------------------------===//
7242 
7244  StringRef Name) {
7245  // typedef char* __builtin[_ms]_va_list;
7246  QualType T = Context->getPointerType(Context->CharTy);
7247  return Context->buildImplicitTypedef(T, Name);
7248 }
7249 
7250 static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
7251  return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
7252 }
7253 
7255  return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
7256 }
7257 
7259  // typedef void* __builtin_va_list;
7260  QualType T = Context->getPointerType(Context->VoidTy);
7261  return Context->buildImplicitTypedef(T, "__builtin_va_list");
7262 }
7263 
7264 static TypedefDecl *
7266  // struct __va_list
7267  RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
7268  if (Context->getLangOpts().CPlusPlus) {
7269  // namespace std { struct __va_list {
7270  NamespaceDecl *NS;
7271  NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
7272  Context->getTranslationUnitDecl(),
7273  /*Inline*/ false, SourceLocation(),
7274  SourceLocation(), &Context->Idents.get("std"),
7275  /*PrevDecl*/ nullptr);
7276  NS->setImplicit();
7277  VaListTagDecl->setDeclContext(NS);
7278  }
7279 
7280  VaListTagDecl->startDefinition();
7281 
7282  const size_t NumFields = 5;
7283  QualType FieldTypes[NumFields];
7284  const char *FieldNames[NumFields];
7285 
7286  // void *__stack;
7287  FieldTypes[0] = Context->getPointerType(Context->VoidTy);
7288  FieldNames[0] = "__stack";
7289 
7290  // void *__gr_top;
7291  FieldTypes[1] = Context->getPointerType(Context->VoidTy);
7292  FieldNames[1] = "__gr_top";
7293 
7294  // void *__vr_top;
7295  FieldTypes[2] = Context->getPointerType(Context->VoidTy);
7296  FieldNames[2] = "__vr_top";
7297 
7298  // int __gr_offs;
7299  FieldTypes[3] = Context->IntTy;
7300  FieldNames[3] = "__gr_offs";
7301 
7302  // int __vr_offs;
7303  FieldTypes[4] = Context->IntTy;
7304  FieldNames[4] = "__vr_offs";
7305 
7306  // Create fields
7307  for (unsigned i = 0; i < NumFields; ++i) {
7308  FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7309  VaListTagDecl,
7310  SourceLocation(),
7311  SourceLocation(),
7312  &Context->Idents.get(FieldNames[i]),
7313  FieldTypes[i], /*TInfo=*/nullptr,
7314  /*BitWidth=*/nullptr,
7315  /*Mutable=*/false,
7316  ICIS_NoInit);
7317  Field->setAccess(AS_public);
7318  VaListTagDecl->addDecl(Field);
7319  }
7320  VaListTagDecl->completeDefinition();
7321  Context->VaListTagDecl = VaListTagDecl;
7322  QualType VaListTagType = Context->getRecordType(VaListTagDecl);
7323 
7324  // } __builtin_va_list;
7325  return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
7326 }
7327 
7329  // typedef struct __va_list_tag {
7331 
7332  VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
7333  VaListTagDecl->startDefinition();
7334 
7335  const size_t NumFields = 5;
7336  QualType FieldTypes[NumFields];
7337  const char *FieldNames[NumFields];
7338 
7339  // unsigned char gpr;
7340  FieldTypes[0] = Context->UnsignedCharTy;
7341  FieldNames[0] = "gpr";
7342 
7343  // unsigned char fpr;
7344  FieldTypes[1] = Context->UnsignedCharTy;
7345  FieldNames[1] = "fpr";
7346 
7347  // unsigned short reserved;
7348  FieldTypes[2] = Context->UnsignedShortTy;
7349  FieldNames[2] = "reserved";
7350 
7351  // void* overflow_arg_area;
7352  FieldTypes[3] = Context->getPointerType(Context->VoidTy);
7353  FieldNames[3] = "overflow_arg_area";
7354 
7355  // void* reg_save_area;
7356  FieldTypes[4] = Context->getPointerType(Context->VoidTy);
7357  FieldNames[4] = "reg_save_area";
7358 
7359  // Create fields
7360  for (unsigned i = 0; i < NumFields; ++i) {
7361  FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
7362  SourceLocation(),
7363  SourceLocation(),
7364  &Context->Idents.get(FieldNames[i]),
7365  FieldTypes[i], /*TInfo=*/nullptr,
7366  /*BitWidth=*/nullptr,
7367  /*Mutable=*/false,
7368  ICIS_NoInit);
7369  Field->setAccess(AS_public);
7370  VaListTagDecl->addDecl(Field);
7371  }
7372  VaListTagDecl->completeDefinition();
7373  Context->VaListTagDecl = VaListTagDecl;
7374  QualType VaListTagType = Context->getRecordType(VaListTagDecl);
7375 
7376  // } __va_list_tag;
7377  TypedefDecl *VaListTagTypedefDecl =
7378  Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
7379 
7380  QualType VaListTagTypedefType =
7381  Context->getTypedefType(VaListTagTypedefDecl);
7382 
7383  // typedef __va_list_tag __builtin_va_list[1];
7384  llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
7385  QualType VaListTagArrayType
7386  = Context->getConstantArrayType(VaListTagTypedefType,
7387  Size, ArrayType::Normal, 0);
7388  return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
7389 }
7390 
7391 static TypedefDecl *
7393  // struct __va_list_tag {
7395  VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
7396  VaListTagDecl->startDefinition();
7397 
7398  const size_t NumFields = 4;
7399  QualType FieldTypes[NumFields];
7400  const char *FieldNames[NumFields];
7401 
7402  // unsigned gp_offset;
7403  FieldTypes[0] = Context->UnsignedIntTy;
7404  FieldNames[0] = "gp_offset";
7405 
7406  // unsigned fp_offset;
7407  FieldTypes[1] = Context->UnsignedIntTy;
7408  FieldNames[1] = "fp_offset";
7409 
7410  // void* overflow_arg_area;
7411  FieldTypes[2] = Context->getPointerType(Context->VoidTy);
7412  FieldNames[2] = "overflow_arg_area";
7413 
7414  // void* reg_save_area;
7415  FieldTypes[3] = Context->getPointerType(Context->VoidTy);
7416  FieldNames[3] = "reg_save_area";
7417 
7418  // Create fields
7419  for (unsigned i = 0; i < NumFields; ++i) {
7420  FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7421  VaListTagDecl,
7422  SourceLocation(),
7423  SourceLocation(),
7424  &Context->Idents.get(FieldNames[i]),
7425  FieldTypes[i], /*TInfo=*/nullptr,
7426  /*BitWidth=*/nullptr,
7427  /*Mutable=*/false,
7428  ICIS_NoInit);
7429  Field->setAccess(AS_public);
7430  VaListTagDecl->addDecl(Field);
7431  }
7432  VaListTagDecl->completeDefinition();
7433  Context->VaListTagDecl = VaListTagDecl;
7434  QualType VaListTagType = Context->getRecordType(VaListTagDecl);
7435 
7436  // };
7437 
7438  // typedef struct __va_list_tag __builtin_va_list[1];
7439  llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
7440  QualType VaListTagArrayType =
7441  Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
7442  return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
7443 }
7444 
7446  // typedef int __builtin_va_list[4];
7447  llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
7448  QualType IntArrayType =
7449  Context->getConstantArrayType(Context->IntTy, Size, ArrayType::Normal, 0);
7450  return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
7451 }
7452 
7453 static TypedefDecl *
7455  // struct __va_list
7456  RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
7457  if (Context->getLangOpts().CPlusPlus) {
7458  // namespace std { struct __va_list {
7459  NamespaceDecl *NS;
7460  NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
7461  Context->getTranslationUnitDecl(),
7462  /*Inline*/false, SourceLocation(),
7463  SourceLocation(), &Context->Idents.get("std"),
7464  /*PrevDecl*/ nullptr);
7465  NS->setImplicit();
7466  VaListDecl->setDeclContext(NS);
7467  }
7468 
7469  VaListDecl->startDefinition();
7470 
7471  // void * __ap;
7472  FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7473  VaListDecl,
7474  SourceLocation(),
7475  SourceLocation(),
7476  &Context->Idents.get("__ap"),
7477  Context->getPointerType(Context->VoidTy),
7478  /*TInfo=*/nullptr,
7479  /*BitWidth=*/nullptr,
7480  /*Mutable=*/false,
7481  ICIS_NoInit);
7482  Field->setAccess(AS_public);
7483  VaListDecl->addDecl(Field);
7484 
7485  // };
7486  VaListDecl->completeDefinition();
7487  Context->VaListTagDecl = VaListDecl;
7488 
7489  // typedef struct __va_list __builtin_va_list;
7490  QualType T = Context->getRecordType(VaListDecl);
7491  return Context->buildImplicitTypedef(T, "__builtin_va_list");
7492 }
7493 
7494 static TypedefDecl *
7496  // struct __va_list_tag {
7498  VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
7499  VaListTagDecl->startDefinition();
7500 
7501  const size_t NumFields = 4;
7502  QualType FieldTypes[NumFields];
7503  const char *FieldNames[NumFields];
7504 
7505  // long __gpr;
7506  FieldTypes[0] = Context->LongTy;
7507  FieldNames[0] = "__gpr";
7508 
7509  // long __fpr;
7510  FieldTypes[1] = Context->LongTy;
7511  FieldNames[1] = "__fpr";
7512 
7513  // void *__overflow_arg_area;
7514  FieldTypes[2] = Context->getPointerType(Context->VoidTy);
7515  FieldNames[2] = "__overflow_arg_area";
7516 
7517  // void *__reg_save_area;
7518  FieldTypes[3] = Context->getPointerType(Context->VoidTy);
7519  FieldNames[3] = "__reg_save_area";
7520 
7521  // Create fields
7522  for (unsigned i = 0; i < NumFields; ++i) {
7523  FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7524  VaListTagDecl,
7525  SourceLocation(),
7526  SourceLocation(),
7527  &Context->Idents.get(FieldNames[i]),
7528  FieldTypes[i], /*TInfo=*/nullptr,
7529  /*BitWidth=*/nullptr,
7530  /*Mutable=*/false,
7531  ICIS_NoInit);
7532  Field->setAccess(AS_public);
7533  VaListTagDecl->addDecl(Field);
7534  }
7535  VaListTagDecl->completeDefinition();
7536  Context->VaListTagDecl = VaListTagDecl;
7537  QualType VaListTagType = Context->getRecordType(VaListTagDecl);
7538 
7539  // };
7540 
7541  // typedef __va_list_tag __builtin_va_list[1];
7542  llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
7543  QualType VaListTagArrayType =
7544  Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
7545 
7546  return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
7547 }
7548 
7549 static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
7551  switch (Kind) {
7553  return CreateCharPtrBuiltinVaListDecl(Context);
7555  return CreateVoidPtrBuiltinVaListDecl(Context);
7557  return CreateAArch64ABIBuiltinVaListDecl(Context);
7559  return CreatePowerABIBuiltinVaListDecl(Context);
7561  return CreateX86_64ABIBuiltinVaListDecl(Context);
7563  return CreatePNaClABIBuiltinVaListDecl(Context);
7565  return CreateAAPCSABIBuiltinVaListDecl(Context);
7567  return CreateSystemZBuiltinVaListDecl(Context);
7568  }
7569 
7570  llvm_unreachable("Unhandled __builtin_va_list type kind");
7571 }
7572 
7574  if (!BuiltinVaListDecl) {
7575  BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
7576  assert(BuiltinVaListDecl->isImplicit());
7577  }
7578 
7579  return BuiltinVaListDecl;
7580 }
7581 
7583  // Force the creation of VaListTagDecl by building the __builtin_va_list
7584  // declaration.
7585  if (!VaListTagDecl)
7586  (void)getBuiltinVaListDecl();
7587 
7588  return VaListTagDecl;
7589 }
7590 
7592  if (!BuiltinMSVaListDecl)
7593  BuiltinMSVaListDecl = CreateMSVaListDecl(this);
7594 
7595  return BuiltinMSVaListDecl;
7596 }
7597 
7600 }
7601 
7603  assert(ObjCConstantStringType.isNull() &&
7604  "'NSConstantString' type already set!");
7605 
7606  ObjCConstantStringType = getObjCInterfaceType(Decl);
7607 }
7608 
7609 /// Retrieve the template name that corresponds to a non-empty
7610 /// lookup.
7613  UnresolvedSetIterator End) const {
7614  unsigned size = End - Begin;
7615  assert(size > 1 && "set is not overloaded!");
7616 
7617  void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
7618  size * sizeof(FunctionTemplateDecl*));
7619  auto *OT = new (memory) OverloadedTemplateStorage(size);
7620 
7621  NamedDecl **Storage = OT->getStorage();
7622  for (UnresolvedSetIterator I = Begin; I != End; ++I) {
7623  NamedDecl *D = *I;
7624  assert(isa<FunctionTemplateDecl>(D) ||
7625  isa<UnresolvedUsingValueDecl>(D) ||
7626  (isa<UsingShadowDecl>(D) &&
7627  isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
7628  *Storage++ = D;
7629  }
7630 
7631  return TemplateName(OT);
7632 }
7633 
7634 /// Retrieve a template name representing an unqualified-id that has been
7635 /// assumed to name a template for ADL purposes.
7637  auto *OT = new (*this) AssumedTemplateStorage(Name);
7638  return TemplateName(OT);
7639 }
7640 
7641 /// Retrieve the template name that represents a qualified
7642 /// template name such as \c std::vector.
7645  bool TemplateKeyword,
7646  TemplateDecl *Template) const {
7647  assert(NNS && "Missing nested-name-specifier in qualified template name");
7648 
7649  // FIXME: Canonicalization?
7650  llvm::FoldingSetNodeID ID;
7651  QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
7652 
7653  void *InsertPos = nullptr;
7654  QualifiedTemplateName *QTN =
7655  QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7656  if (!QTN) {
7657  QTN = new (*this, alignof(QualifiedTemplateName))
7658  QualifiedTemplateName(NNS, TemplateKeyword, Template);
7659  QualifiedTemplateNames.InsertNode(QTN, InsertPos);
7660  }
7661 
7662  return TemplateName(QTN);
7663 }
7664 
7665 /// Retrieve the template name that represents a dependent
7666 /// template name such as \c MetaFun::template apply.
7669  const IdentifierInfo *Name) const {
7670  assert((!NNS || NNS->isDependent()) &&
7671  "Nested name specifier must be dependent");
7672 
7673  llvm::FoldingSetNodeID ID;
7674  DependentTemplateName::Profile(ID, NNS, Name);
7675 
7676  void *InsertPos = nullptr;
7677  DependentTemplateName *QTN =
7678  DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7679 
7680  if (QTN)
7681  return TemplateName(QTN);
7682 
7684  if (CanonNNS == NNS) {
7685  QTN = new (*this, alignof(DependentTemplateName))
7686  DependentTemplateName(NNS, Name);
7687  } else {
7688  TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
7689  QTN = new (*this, alignof(DependentTemplateName))
7690  DependentTemplateName(NNS, Name, Canon);
7691  DependentTemplateName *CheckQTN =
7692  DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7693  assert(!CheckQTN && "Dependent type name canonicalization broken");
7694  (void)CheckQTN;
7695  }
7696 
7697  DependentTemplateNames.InsertNode(QTN, InsertPos);
7698  return TemplateName(QTN);
7699 }
7700 
7701 /// Retrieve the template name that represents a dependent
7702 /// template name such as \c MetaFun::template operator+.
7705  OverloadedOperatorKind Operator) const {
7706  assert((!NNS || NNS->isDependent()) &&
7707  "Nested name specifier must be dependent");
7708 
7709  llvm::FoldingSetNodeID ID;
7710  DependentTemplateName::Profile(ID, NNS, Operator);
7711 
7712  void *InsertPos = nullptr;
7714  = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7715 
7716  if (QTN)
7717  return TemplateName(QTN);
7718 
7720  if (CanonNNS == NNS) {
7721  QTN = new (*this, alignof(DependentTemplateName))
7722  DependentTemplateName(NNS, Operator);
7723  } else {
7724  TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
7725  QTN = new (*this, alignof(DependentTemplateName))
7726  DependentTemplateName(NNS, Operator, Canon);
7727 
7728  DependentTemplateName *CheckQTN
7729  = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7730  assert(!CheckQTN && "Dependent template name canonicalization broken");
7731  (void)CheckQTN;
7732  }
7733 
7734  DependentTemplateNames.InsertNode(QTN, InsertPos);
7735  return TemplateName(QTN);
7736 }
7737 
7740  TemplateName replacement) const {
7741  llvm::FoldingSetNodeID ID;
7742  SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
7743 
7744  void *insertPos = nullptr;
7746  = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
7747 
7748  if (!subst) {
7749  subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
7750  SubstTemplateTemplateParms.InsertNode(subst, insertPos);
7751  }
7752 
7753  return TemplateName(subst);
7754 }
7755 
7758  const TemplateArgument &ArgPack) const {
7759  auto &Self = const_cast<ASTContext &>(*this);
7760  llvm::FoldingSetNodeID ID;
7761  SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
7762 
7763  void *InsertPos = nullptr;
7765  = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
7766 
7767  if (!Subst) {
7768  Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
7769  ArgPack.pack_size(),
7770  ArgPack.pack_begin());
7771  SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
7772  }
7773 
7774  return TemplateName(Subst);
7775 }
7776 
7777 /// getFromTargetType - Given one of the integer types provided by
7778 /// TargetInfo, produce the corresponding type. The unsigned @p Type
7779 /// is actually a value of type @c TargetInfo::IntType.
7780 CanQualType ASTContext::getFromTargetType(unsigned Type) const {
7781  switch (Type) {
7782  case TargetInfo::NoInt: return {};
7783  case TargetInfo::SignedChar: return SignedCharTy;
7785  case TargetInfo::SignedShort: return ShortTy;
7787  case TargetInfo::SignedInt: return IntTy;
7789  case TargetInfo::SignedLong: return LongTy;
7793  }
7794 
7795  llvm_unreachable("Unhandled TargetInfo::IntType value");
7796 }
7797 
7798 //===----------------------------------------------------------------------===//
7799 // Type Predicates.
7800 //===----------------------------------------------------------------------===//
7801 
7802 /// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
7803 /// garbage collection attribute.
7804 ///
7806  if (getLangOpts().getGC() == LangOptions::NonGC)
7807  return Qualifiers::GCNone;
7808 
7809  assert(getLangOpts().ObjC);
7810  Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
7811 
7812  // Default behaviour under objective-C's gc is for ObjC pointers
7813  // (or pointers to them) be treated as though they were declared
7814  // as __strong.
7815  if (GCAttrs == Qualifiers::GCNone) {
7816  if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
7817  return Qualifiers::Strong;
7818  else if (Ty->isPointerType())
7820  } else {
7821  // It's not valid to set GC attributes on anything that isn't a
7822  // pointer.
7823 #ifndef NDEBUG
7825  while (const auto *AT = dyn_cast<ArrayType>(CT))
7826  CT = AT->getElementType();
7827  assert(CT->isAnyPointerType() || CT->isBlockPointerType());
7828 #endif
7829  }
7830  return GCAttrs;
7831 }
7832 
7833 //===----------------------------------------------------------------------===//
7834 // Type Compatibility Testing
7835 //===----------------------------------------------------------------------===//
7836 
7837 /// areCompatVectorTypes - Return true if the two specified vector types are
7838 /// compatible.
7839 static bool areCompatVectorTypes(const VectorType *LHS,
7840  const VectorType *RHS) {
7841  assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
7842  return LHS->getElementType() == RHS->getElementType() &&
7843  LHS->getNumElements() == RHS->getNumElements();
7844 }
7845 
7847  QualType SecondVec) {
7848  assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
7849  assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
7850 
7851  if (hasSameUnqualifiedType(FirstVec, SecondVec))
7852  return true;
7853 
7854  // Treat Neon vector types and most AltiVec vector types as if they are the
7855  // equivalent GCC vector types.
7856  const auto *First = FirstVec->getAs<VectorType>();
7857  const auto *Second = SecondVec->getAs<VectorType>();
7858  if (First->getNumElements() == Second->getNumElements() &&
7859  hasSameType(First->getElementType(), Second->getElementType()) &&
7860  First->getVectorKind() != VectorType::AltiVecPixel &&
7861  First->getVectorKind() != VectorType::AltiVecBool &&
7862  Second->getVectorKind() != VectorType::AltiVecPixel &&
7864  return true;
7865 
7866  return false;
7867 }
7868 
7869 //===----------------------------------------------------------------------===//
7870 // ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
7871 //===----------------------------------------------------------------------===//
7872 
7873 /// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
7874 /// inheritance hierarchy of 'rProto'.
7875 bool
7877  ObjCProtocolDecl *rProto) const {
7878  if (declaresSameEntity(lProto, rProto))
7879  return true;
7880  for (auto *PI : rProto->protocols())
7881  if (ProtocolCompatibleWithProtocol(lProto, PI))
7882  return true;
7883  return false;
7884 }
7885 
7886 /// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
7887 /// Class<pr1, ...>.
7889  QualType rhs) {
7890  const auto *lhsQID = lhs->getAs<ObjCObjectPointerType>();
7891  const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
7892  assert((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
7893 
7894  for (auto *lhsProto : lhsQID->quals()) {
7895  bool match = false;
7896  for (auto *rhsProto : rhsOPT->quals()) {
7897  if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
7898  match = true;
7899  break;
7900  }
7901  }
7902  if (!match)
7903  return false;
7904  }
7905  return true;
7906 }
7907 
7908 /// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
7909 /// ObjCQualifiedIDType.
7911  bool compare) {
7912  // Allow id<P..> and an 'id' or void* type in all cases.
7913  if (lhs->isVoidPointerType() ||
7914  lhs->isObjCIdType() || lhs->isObjCClassType())
7915  return true;
7916  else if (rhs->isVoidPointerType() ||
7917  rhs->isObjCIdType() || rhs->isObjCClassType())
7918  return true;
7919 
7920  if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
7921  const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
7922 
7923  if (!rhsOPT) return false;
7924 
7925  if (rhsOPT->qual_empty()) {
7926  // If the RHS is a unqualified interface pointer "NSString*",
7927  // make sure we check the class hierarchy.
7928  if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
7929  for (auto *I : lhsQID->quals()) {
7930  // when comparing an id<P> on lhs with a static type on rhs,
7931  // see if static class implements all of id's protocols, directly or
7932  // through its super class and categories.
7933  if (!rhsID->ClassImplementsProtocol(I, true))
7934  return false;
7935  }
7936  }
7937  // If there are no qualifiers and no interface, we have an 'id'.
7938  return true;
7939  }
7940  // Both the right and left sides have qualifiers.
7941  for (auto *lhsProto : lhsQID->quals()) {
7942  bool match = false;
7943 
7944  // when comparing an id<P> on lhs with a static type on rhs,
7945  // see if static class implements all of id's protocols, directly or
7946  // through its super class and categories.
7947  for (auto *rhsProto : rhsOPT->quals()) {
7948  if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7949  (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7950  match = true;
7951  break;
7952  }
7953  }
7954  // If the RHS is a qualified interface pointer "NSString<P>*",
7955  // make sure we check the class hierarchy.
7956  if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
7957  for (auto *I : lhsQID->quals()) {
7958  // when comparing an id<P> on lhs with a static type on rhs,
7959  // see if static class implements all of id's protocols, directly or
7960  // through its super class and categories.
7961  if (rhsID->ClassImplementsProtocol(I, true)) {
7962  match = true;
7963  break;
7964  }
7965  }
7966  }
7967  if (!match)
7968  return false;
7969  }
7970 
7971  return true;
7972  }
7973 
7974  const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
7975  assert(rhsQID && "One of the LHS/RHS should be id<x>");
7976 
7977  if (const ObjCObjectPointerType *lhsOPT =
7979  // If both the right and left sides have qualifiers.
7980  for (auto *lhsProto : lhsOPT->quals()) {
7981  bool match = false;
7982 
7983  // when comparing an id<P> on rhs with a static type on lhs,
7984  // see if static class implements all of id's protocols, directly or
7985  // through its super class and categories.
7986  // First, lhs protocols in the qualifier list must be found, direct
7987  // or indirect in rhs's qualifier list or it is a mismatch.
7988  for (auto *rhsProto : rhsQID->quals()) {
7989  if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7990  (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7991  match = true;
7992  break;
7993  }
7994  }
7995  if (!match)
7996  return false;
7997  }
7998 
7999  // Static class's protocols, or its super class or category protocols
8000  // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
8001  if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
8002  llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
8003  CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
8004  // This is rather dubious but matches gcc's behavior. If lhs has
8005  // no type qualifier and its class has no static protocol(s)
8006  // assume that it is mismatch.
8007  if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
8008  return false;
8009  for (auto *lhsProto : LHSInheritedProtocols) {
8010  bool match = false;
8011  for (auto *rhsProto : rhsQID->quals()) {
8012  if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
8013  (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
8014  match = true;
8015  break;
8016  }
8017  }
8018  if (!match)
8019  return false;
8020  }
8021  }
8022  return true;
8023  }
8024  return false;
8025 }
8026 
8027 /// canAssignObjCInterfaces - Return true if the two interface types are
8028 /// compatible for assignment from RHS to LHS. This handles validation of any
8029 /// protocol qualifiers on the LHS or RHS.
8031  const ObjCObjectPointerType *RHSOPT) {
8032  const ObjCObjectType* LHS = LHSOPT->getObjectType();
8033  const ObjCObjectType* RHS = RHSOPT->getObjectType();
8034 
8035  // If either type represents the built-in 'id' or 'Class' types, return true.
8036  if (LHS->isObjCUnqualifiedIdOrClass() ||
8038  return true;
8039 
8040  // Function object that propagates a successful result or handles
8041  // __kindof types.
8042  auto finish = [&](bool succeeded) -> bool {
8043  if (succeeded)
8044  return true;
8045 
8046  if (!RHS->isKindOfType())
8047  return false;
8048 
8049  // Strip off __kindof and protocol qualifiers, then check whether
8050  // we can assign the other way.
8052  LHSOPT->stripObjCKindOfTypeAndQuals(*this));
8053  };
8054 
8055  if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
8056  return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
8057  QualType(RHSOPT,0),
8058  false));
8059  }
8060 
8061  if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
8062  return finish(ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
8063  QualType(RHSOPT,0)));
8064  }
8065 
8066  // If we have 2 user-defined types, fall into that path.
8067  if (LHS->getInterface() && RHS->getInterface()) {
8068  return finish(canAssignObjCInterfaces(LHS, RHS));
8069  }
8070 
8071  return false;
8072 }
8073 
8074 /// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
8075 /// for providing type-safety for objective-c pointers used to pass/return
8076 /// arguments in block literals. When passed as arguments, passing 'A*' where
8077 /// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
8078 /// not OK. For the return type, the opposite is not OK.
8080  const ObjCObjectPointerType *LHSOPT,
8081  const ObjCObjectPointerType *RHSOPT,
8082  bool BlockReturnType) {
8083 
8084  // Function object that propagates a successful result or handles
8085  // __kindof types.
8086  auto finish = [&](bool succeeded) -> bool {
8087  if (succeeded)
8088  return true;
8089 
8090  const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
8091  if (!Expected->isKindOfType())
8092  return false;
8093 
8094  // Strip off __kindof and protocol qualifiers, then check whether
8095  // we can assign the other way.
8097  RHSOPT->stripObjCKindOfTypeAndQuals(*this),
8098  LHSOPT->stripObjCKindOfTypeAndQuals(*this),
8099  BlockReturnType);
8100  };
8101 
8102  if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
8103  return true;
8104 
8105  if (LHSOPT->isObjCBuiltinType()) {
8106  return finish(RHSOPT->isObjCBuiltinType() ||
8107  RHSOPT->isObjCQualifiedIdType());
8108  }
8109 
8110  if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
8111  return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
8112  QualType(RHSOPT,0),
8113  false));
8114 
8115  const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
8116  const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
8117  if (LHS && RHS) { // We have 2 user-defined types.
8118  if (LHS != RHS) {
8119  if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
8120  return finish(BlockReturnType);
8121  if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
8122  return finish(!BlockReturnType);
8123  }
8124  else
8125  return true;
8126  }
8127  return false;
8128 }
8129 
8130 /// Comparison routine for Objective-C protocols to be used with
8131 /// llvm::array_pod_sort.
8133  ObjCProtocolDecl * const *rhs) {
8134  return (*lhs)->getName().compare((*rhs)->getName());
8135 }
8136 
8137 /// getIntersectionOfProtocols - This routine finds the intersection of set
8138 /// of protocols inherited from two distinct objective-c pointer objects with
8139 /// the given common base.
8140 /// It is used to build composite qualifier list of the composite type of
8141 /// the conditional expression involving two objective-c pointer objects.
8142 static
8145  const ObjCObjectPointerType *LHSOPT,
8146  const ObjCObjectPointerType *RHSOPT,
8147  SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
8148 
8149  const ObjCObjectType* LHS = LHSOPT->getObjectType();
8150  const ObjCObjectType* RHS = RHSOPT->getObjectType();
8151  assert(LHS->getInterface() && "LHS must have an interface base");
8152  assert(RHS->getInterface() && "RHS must have an interface base");
8153 
8154  // Add all of the protocols for the LHS.
8155  llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
8156 
8157  // Start with the protocol qualifiers.
8158  for (auto proto : LHS->quals()) {
8159  Context.CollectInheritedProtocols(proto, LHSProtocolSet);
8160  }
8161 
8162  // Also add the protocols associated with the LHS interface.
8163  Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
8164 
8165  // Add all of the protocols for the RHS.
8166  llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
8167 
8168  // Start with the protocol qualifiers.
8169  for (auto proto : RHS->quals()) {
8170  Context.CollectInheritedProtocols(proto, RHSProtocolSet);
8171  }
8172 
8173  // Also add the protocols associated with the RHS interface.
8174  Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
8175 
8176  // Compute the intersection of the collected protocol sets.
8177  for (auto proto : LHSProtocolSet) {
8178  if (RHSProtocolSet.count(proto))
8179  IntersectionSet.push_back(proto);
8180  }
8181 
8182  // Compute the set of protocols that is implied by either the common type or
8183  // the protocols within the intersection.
8184  llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
8185  Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
8186 
8187  // Remove any implied protocols from the list of inherited protocols.
8188  if (!ImpliedProtocols.empty()) {
8189  IntersectionSet.erase(
8190  std::remove_if(IntersectionSet.begin(),
8191  IntersectionSet.end(),
8192  [&](ObjCProtocolDecl *proto) -> bool {
8193  return ImpliedProtocols.count(proto) > 0;
8194  }),
8195  IntersectionSet.end());
8196  }
8197 
8198  // Sort the remaining protocols by name.
8199  llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
8201 }
8202 
8203 /// Determine whether the first type is a subtype of the second.
8205  QualType rhs) {
8206  // Common case: two object pointers.
8207  const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
8208  const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
8209  if (lhsOPT && rhsOPT)
8210  return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
8211 
8212  // Two block pointers.
8213  const auto *lhsBlock = lhs->getAs<BlockPointerType>();
8214  const auto *rhsBlock = rhs->getAs<BlockPointerType>();
8215  if (lhsBlock && rhsBlock)
8216  return ctx.typesAreBlockPointerCompatible(lhs, rhs);
8217 
8218  // If either is an unqualified 'id' and the other is a block, it's
8219  // acceptable.
8220  if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
8221  (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
8222  return true;
8223 
8224  return false;
8225 }
8226 
8227 // Check that the given Objective-C type argument lists are equivalent.
8228 static bool sameObjCTypeArgs(ASTContext &ctx,
8229  const ObjCInterfaceDecl *iface,
8230  ArrayRef<QualType> lhsArgs,
8231  ArrayRef<QualType> rhsArgs,
8232  bool stripKindOf) {
8233  if (lhsArgs.size() != rhsArgs.size())
8234  return false;
8235 
8236  ObjCTypeParamList *typeParams = iface->getTypeParamList();
8237  for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
8238  if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
8239  continue;
8240 
8241  switch (typeParams->begin()[i]->getVariance()) {
8243  if (!stripKindOf ||
8244  !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
8245  rhsArgs[i].stripObjCKindOfType(ctx))) {
8246  return false;
8247  }
8248  break;
8249 
8251  if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
8252  return false;
8253  break;
8254 
8256  if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
8257  return false;
8258  break;
8259  }
8260  }
8261 
8262  return true;
8263 }
8264 
8266  const ObjCObjectPointerType *Lptr,
8267  const ObjCObjectPointerType *Rptr) {
8268  const ObjCObjectType *LHS = Lptr->getObjectType();
8269  const ObjCObjectType *RHS = Rptr->getObjectType();
8270  const ObjCInterfaceDecl* LDecl = LHS->getInterface();
8271  const ObjCInterfaceDecl* RDecl = RHS->getInterface();
8272 
8273  if (!LDecl || !RDecl)
8274  return {};
8275 
8276  // When either LHS or RHS is a kindof type, we should return a kindof type.
8277  // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
8278  // kindof(A).
8279  bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
8280 
8281  // Follow the left-hand side up the class hierarchy until we either hit a
8282  // root or find the RHS. Record the ancestors in case we don't find it.
8283  llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
8284  LHSAncestors;
8285  while (true) {
8286  // Record this ancestor. We'll need this if the common type isn't in the
8287  // path from the LHS to the root.
8288  LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
8289 
8290  if (declaresSameEntity(LHS->getInterface(), RDecl)) {
8291  // Get the type arguments.
8292  ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
8293  bool anyChanges = false;
8294  if (LHS->isSpecialized() && RHS->isSpecialized()) {
8295  // Both have type arguments, compare them.
8296  if (!sameObjCTypeArgs(*this, LHS->getInterface(),
8297  LHS->getTypeArgs(), RHS->getTypeArgs(),
8298  /*stripKindOf=*/true))
8299  return {};
8300  } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
8301  // If only one has type arguments, the result will not have type
8302  // arguments.
8303  LHSTypeArgs = {};
8304  anyChanges = true;
8305  }
8306 
8307  // Compute the intersection of protocols.
8309  getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
8310  Protocols);
8311  if (!Protocols.empty())
8312  anyChanges = true;
8313 
8314  // If anything in the LHS will have changed, build a new result type.
8315  // If we need to return a kindof type but LHS is not a kindof type, we
8316  // build a new result type.
8317  if (anyChanges || LHS->isKindOfType() != anyKindOf) {
8319  Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
8320  anyKindOf || LHS->isKindOfType());
8321  return getObjCObjectPointerType(Result);
8322  }
8323 
8324  return getObjCObjectPointerType(QualType(LHS, 0));
8325  }
8326 
8327  // Find the superclass.
8328  QualType LHSSuperType = LHS->getSuperClassType();
8329  if (LHSSuperType.isNull())
8330  break;
8331 
8332  LHS = LHSSuperType->castAs<ObjCObjectType>();
8333  }
8334 
8335  // We didn't find anything by following the LHS to its root; now check
8336  // the RHS against the cached set of ancestors.
8337  while (true) {
8338  auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
8339  if (KnownLHS != LHSAncestors.end()) {
8340  LHS = KnownLHS->second;
8341 
8342  // Get the type arguments.
8343  ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
8344  bool anyChanges = false;
8345  if (LHS->isSpecialized() && RHS->isSpecialized()) {
8346  // Both have type arguments, compare them.
8347  if (!sameObjCTypeArgs(*this, LHS->getInterface(),
8348  LHS->getTypeArgs(), RHS->getTypeArgs(),
8349  /*stripKindOf=*/true))
8350  return {};
8351  } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
8352  // If only one has type arguments, the result will not have type
8353  // arguments.
8354  RHSTypeArgs = {};
8355  anyChanges = true;
8356  }
8357 
8358  // Compute the intersection of protocols.
8360  getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
8361  Protocols);
8362  if (!Protocols.empty())
8363  anyChanges = true;
8364 
8365  // If we need to return a kindof type but RHS is not a kindof type, we
8366  // build a new result type.
8367  if (anyChanges || RHS->isKindOfType() != anyKindOf) {
8369  Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
8370  anyKindOf || RHS->isKindOfType());
8371  return getObjCObjectPointerType(Result);
8372  }
8373 
8374  return getObjCObjectPointerType(QualType(RHS, 0));
8375  }
8376 
8377  // Find the superclass of the RHS.
8378  QualType RHSSuperType = RHS->getSuperClassType();
8379  if (RHSSuperType.isNull())
8380  break;
8381 
8382  RHS = RHSSuperType->castAs<ObjCObjectType>();
8383  }
8384 
8385  return {};
8386 }
8387 
8389  const ObjCObjectType *RHS) {
8390  assert(LHS->getInterface() && "LHS is not an interface type");
8391  assert(RHS->getInterface() && "RHS is not an interface type");
8392 
8393  // Verify that the base decls are compatible: the RHS must be a subclass of
8394  // the LHS.
8395  ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
8396  bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
8397  if (!IsSuperClass)
8398  return false;
8399 
8400  // If the LHS has protocol qualifiers, determine whether all of them are
8401  // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
8402  // LHS).
8403  if (LHS->getNumProtocols() > 0) {
8404  // OK if conversion of LHS to SuperClass results in narrowing of types
8405  // ; i.e., SuperClass may implement at least one of the protocols
8406  // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
8407  // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
8408  llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
8409  CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
8410  // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
8411  // qualifiers.
8412  for (auto *RHSPI : RHS->quals())
8413  CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
8414  // If there is no protocols associated with RHS, it is not a match.
8415  if (SuperClassInheritedProtocols.empty())
8416  return false;
8417 
8418  for (const auto *LHSProto : LHS->quals()) {
8419  bool SuperImplementsProtocol = false;
8420  for (auto *SuperClassProto : SuperClassInheritedProtocols)
8421  if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
8422  SuperImplementsProtocol = true;
8423  break;
8424  }
8425  if (!SuperImplementsProtocol)
8426  return false;
8427  }
8428  }
8429 
8430  // If the LHS is specialized, we may need to check type arguments.
8431  if (LHS->isSpecialized()) {
8432  // Follow the superclass chain until we've matched the LHS class in the
8433  // hierarchy. This substitutes type arguments through.
8434  const ObjCObjectType *RHSSuper = RHS;
8435  while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
8436  RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
8437 
8438  // If the RHS is specializd, compare type arguments.
8439  if (RHSSuper->isSpecialized() &&
8440  !sameObjCTypeArgs(*this, LHS->getInterface(),
8441  LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
8442  /*stripKindOf=*/true)) {
8443  return false;
8444  }
8445  }
8446 
8447  return true;
8448 }
8449 
8451  // get the "pointed to" types
8452  const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
8453  const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
8454 
8455  if (!LHSOPT || !RHSOPT)
8456  return false;
8457 
8458  return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
8459  canAssignObjCInterfaces(RHSOPT, LHSOPT);
8460 }
8461 
8463  return canAssignObjCInterfaces(
8464  getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
8465  getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
8466 }
8467 
8468 /// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
8469 /// both shall have the identically qualified version of a compatible type.
8470 /// C99 6.2.7p1: Two types have compatible types if their types are the
8471 /// same. See 6.7.[2,3,5] for additional rules.
8473  bool CompareUnqualified) {
8474  if (getLangOpts().CPlusPlus)
8475  return hasSameType(LHS, RHS);
8476 
8477  return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
8478 }
8479 
8481  return typesAreCompatible(LHS, RHS);
8482 }
8483 
8485  return !mergeTypes(LHS, RHS, true).isNull();
8486 }
8487 
8488 /// mergeTransparentUnionType - if T is a transparent union type and a member
8489 /// of T is compatible with SubType, return the merged type, else return
8490 /// QualType()
8492  bool OfBlockPointer,
8493  bool Unqualified) {
8494  if (const RecordType *UT = T->getAsUnionType()) {
8495  RecordDecl *UD = UT->getDecl();
8496  if (UD->hasAttr<TransparentUnionAttr>()) {
8497  for (const auto *I : UD->fields()) {
8498  QualType ET = I->getType().getUnqualifiedType();
8499  QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
8500  if (!MT.isNull())
8501  return MT;
8502  }
8503  }
8504  }
8505 
8506  return {};
8507 }
8508 
8509 /// mergeFunctionParameterTypes - merge two types which appear as function
8510 /// parameter types
8512  bool OfBlockPointer,
8513  bool Unqualified) {
8514  // GNU extension: two types are compatible if they appear as a function
8515  // argument, one of the types is a transparent union type and the other
8516  // type is compatible with a union member
8517  QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
8518  Unqualified);
8519  if (!lmerge.isNull())
8520  return lmerge;
8521 
8522  QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
8523  Unqualified);
8524  if (!rmerge.isNull())
8525  return rmerge;
8526 
8527  return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
8528 }
8529 
8531  bool OfBlockPointer,
8532  bool Unqualified) {
8533  const auto *lbase = lhs->getAs<FunctionType>();
8534  const auto *rbase = rhs->getAs<FunctionType>();
8535  const auto *lproto = dyn_cast<FunctionProtoType>(lbase);
8536  const auto *rproto = dyn_cast<FunctionProtoType>(rbase);
8537  bool allLTypes = true;
8538  bool allRTypes = true;
8539 
8540  // Check return type
8541  QualType retType;
8542  if (OfBlockPointer) {
8543  QualType RHS = rbase->getReturnType();
8544  QualType LHS = lbase->getReturnType();
8545  bool UnqualifiedResult = Unqualified;
8546  if (!UnqualifiedResult)
8547  UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
8548  retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
8549  }
8550  else
8551  retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
8552  Unqualified);
8553  if (retType.isNull())
8554  return {};
8555 
8556  if (Unqualified)
8557  retType = retType.getUnqualifiedType();
8558 
8559  CanQualType LRetType = getCanonicalType(lbase->getReturnType());
8560  CanQualType RRetType = getCanonicalType(rbase->getReturnType());
8561  if (Unqualified) {
8562  LRetType = LRetType.getUnqualifiedType();
8563  RRetType = RRetType.getUnqualifiedType();
8564  }
8565 
8566  if (getCanonicalType(retType) != LRetType)
8567  allLTypes = false;
8568  if (getCanonicalType(retType) != RRetType)
8569  allRTypes = false;
8570 
8571  // FIXME: double check this
8572  // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
8573  // rbase->getRegParmAttr() != 0 &&
8574  // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
8575  FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
8576  FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
8577 
8578  // Compatible functions must have compatible calling conventions
8579  if (lbaseInfo.getCC() != rbaseInfo.getCC())
8580  return {};
8581 
8582  // Regparm is part of the calling convention.
8583  if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
8584  return {};
8585  if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
8586  return {};
8587 
8588  if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
8589  return {};
8590  if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs())
8591  return {};
8592  if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck())
8593  return {};
8594 
8595  // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
8596  bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
8597 
8598  if (lbaseInfo.getNoReturn() != NoReturn)
8599  allLTypes = false;
8600  if (rbaseInfo.getNoReturn() != NoReturn)
8601  allRTypes = false;
8602 
8603  FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
8604 
8605  if (lproto && rproto) { // two C99 style function prototypes
8606  assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
8607  "C++ shouldn't be here");
8608  // Compatible functions must have the same number of parameters
8609  if (lproto->getNumParams() != rproto->getNumParams())
8610  return {};
8611 
8612  // Variadic and non-variadic functions aren't compatible
8613  if (lproto->isVariadic() != rproto->isVariadic())
8614  return {};
8615 
8616  if (lproto->getMethodQuals() != rproto->getMethodQuals())
8617  return {};
8618 
8620  bool canUseLeft, canUseRight;
8621  if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight,
8622  newParamInfos))
8623  return {};
8624 
8625  if (!canUseLeft)
8626  allLTypes = false;
8627  if (!canUseRight)
8628  allRTypes = false;
8629 
8630  // Check parameter type compatibility
8632  for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
8633  QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
8634  QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
8636  lParamType, rParamType, OfBlockPointer, Unqualified);
8637  if (paramType.isNull())
8638  return {};
8639 
8640  if (Unqualified)
8641  paramType = paramType.getUnqualifiedType();
8642 
8643  types.push_back(paramType);
8644  if (Unqualified) {
8645  lParamType = lParamType.getUnqualifiedType();
8646  rParamType = rParamType.getUnqualifiedType();
8647  }
8648 
8649  if (getCanonicalType(paramType) != getCanonicalType(lParamType))
8650  allLTypes = false;
8651  if (getCanonicalType(paramType) != getCanonicalType(rParamType))
8652  allRTypes = false;
8653  }
8654 
8655  if (allLTypes) return lhs;
8656  if (allRTypes) return rhs;
8657 
8658  FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
8659  EPI.ExtInfo = einfo;
8660  EPI.ExtParameterInfos =
8661  newParamInfos.empty() ? nullptr : newParamInfos.data();
8662  return getFunctionType(retType, types, EPI);
8663  }
8664 
8665  if (lproto) allRTypes = false;
8666  if (rproto) allLTypes = false;
8667 
8668  const FunctionProtoType *proto = lproto ? lproto : rproto;
8669  if (proto) {
8670  assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
8671  if (proto->isVariadic())
8672  return {};
8673  // Check that the types are compatible with the types that
8674  // would result from default argument promotions (C99 6.7.5.3p15).
8675  // The only types actually affected are promotable integer
8676  // types and floats, which would be passed as a different
8677  // type depending on whether the prototype is visible.
8678  for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
8679  QualType paramTy = proto->getParamType(i);
8680 
8681  // Look at the converted type of enum types, since that is the type used
8682  // to pass enum values.
8683  if (const auto *Enum = paramTy->getAs<EnumType>()) {
8684  paramTy = Enum->getDecl()->getIntegerType();
8685  if (paramTy.isNull())
8686  return {};
8687  }
8688 
8689  if (paramTy->isPromotableIntegerType() ||
8691  return {};
8692  }
8693 
8694  if (allLTypes) return lhs;
8695  if (allRTypes) return rhs;
8696 
8698  EPI.ExtInfo = einfo;
8699  return getFunctionType(retType, proto->getParamTypes(), EPI);
8700  }
8701 
8702  if (allLTypes) return lhs;
8703  if (allRTypes) return rhs;
8704  return getFunctionNoProtoType(retType, einfo);
8705 }
8706 
8707 /// Given that we have an enum type and a non-enum type, try to merge them.
8709  QualType other, bool isBlockReturnType) {
8710  // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
8711  // a signed integer type, or an unsigned integer type.
8712  // Compatibility is based on the underlying type, not the promotion
8713  // type.
8714  QualType underlyingType = ET->getDecl()->getIntegerType();
8715  if (underlyingType.isNull())
8716  return {};
8717  if (Context.hasSameType(underlyingType, other))
8718  return other;
8719 
8720  // In block return types, we're more permissive and accept any
8721  // integral type of the same size.
8722  if (isBlockReturnType && other->isIntegerType() &&
8723  Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
8724  return other;
8725 
8726  return {};
8727 }
8728 
8730  bool OfBlockPointer,
8731  bool Unqualified, bool BlockReturnType) {
8732  // C++ [expr]: If an expression initially has the type "reference to T", the
8733  // type is adjusted to "T" prior to any further analysis, the expression
8734  // designates the object or function denoted by the reference, and the
8735  // expression is an lvalue unless the reference is an rvalue reference and
8736  // the expression is a function call (possibly inside parentheses).
8737  assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
8738  assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
8739 
8740  if (Unqualified) {
8741  LHS = LHS.getUnqualifiedType();
8742  RHS = RHS.getUnqualifiedType();
8743  }
8744 
8745  QualType LHSCan = getCanonicalType(LHS),
8746  RHSCan = getCanonicalType(RHS);
8747 
8748  // If two types are identical, they are compatible.
8749  if (LHSCan == RHSCan)
8750  return LHS;
8751 
8752  // If the qualifiers are different, the types aren't compatible... mostly.
8753  Qualifiers LQuals = LHSCan.getLocalQualifiers();
8754  Qualifiers RQuals = RHSCan.getLocalQualifiers();
8755  if (LQuals != RQuals) {
8756  // If any of these qualifiers are different, we have a type
8757  // mismatch.
8758  if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
8759  LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
8760  LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
8761  LQuals.hasUnaligned() != RQuals.hasUnaligned())
8762  return {};
8763 
8764  // Exactly one GC qualifier difference is allowed: __strong is
8765  // okay if the other type has no GC qualifier but is an Objective
8766  // C object pointer (i.e. implicitly strong by default). We fix
8767  // this by pretending that the unqualified type was actually
8768  // qualified __strong.
8769  Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
8770  Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
8771  assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
8772 
8773  if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
8774  return {};
8775 
8776  if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
8777  return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
8778  }
8779  if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
8780  return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
8781  }
8782  return {};
8783  }
8784 
8785  // Okay, qualifiers are equal.
8786 
8787  Type::TypeClass LHSClass = LHSCan->getTypeClass();
8788  Type::TypeClass RHSClass = RHSCan->getTypeClass();
8789 
8790  // We want to consider the two function types to be the same for these
8791  // comparisons, just force one to the other.
8792  if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
8793  if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
8794 
8795  // Same as above for arrays
8796  if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
8797  LHSClass = Type::ConstantArray;
8798  if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
8799  RHSClass = Type::ConstantArray;
8800 
8801  // ObjCInterfaces are just specialized ObjCObjects.
8802  if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
8803  if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
8804 
8805  // Canonicalize ExtVector -> Vector.
8806  if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
8807  if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
8808 
8809  // If the canonical type classes don't match.
8810  if (LHSClass != RHSClass) {
8811  // Note that we only have special rules for turning block enum
8812  // returns into block int returns, not vice-versa.
8813  if (const auto *ETy = LHS->getAs<EnumType>()) {
8814  return mergeEnumWithInteger(*this, ETy, RHS, false);
8815  }
8816  if (const EnumType* ETy = RHS->getAs<EnumType>()) {
8817  return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
8818  }
8819  // allow block pointer type to match an 'id' type.
8820  if (OfBlockPointer && !BlockReturnType) {
8821  if (LHS->isObjCIdType() && RHS->isBlockPointerType())
8822  return LHS;
8823  if (RHS->isObjCIdType() && LHS->isBlockPointerType())
8824  return RHS;
8825  }
8826 
8827  return {};
8828  }
8829 
8830  // The canonical type classes match.
8831  switch (LHSClass) {
8832 #define TYPE(Class, Base)
8833 #define ABSTRACT_TYPE(Class, Base)
8834 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
8835 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
8836 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
8837 #include "clang/AST/TypeNodes.def"
8838  llvm_unreachable("Non-canonical and dependent types shouldn't get here");
8839 
8840  case Type::Auto:
8841  case Type::DeducedTemplateSpecialization:
8842  case Type::LValueReference:
8843  case Type::RValueReference:
8844  case Type::MemberPointer:
8845  llvm_unreachable("C++ should never be in mergeTypes");
8846 
8847  case Type::ObjCInterface:
8848  case Type::IncompleteArray:
8849  case Type::VariableArray:
8850  case Type::FunctionProto:
8851  case Type::ExtVector:
8852  llvm_unreachable("Types are eliminated above");
8853 
8854  case Type::Pointer:
8855  {
8856  // Merge two pointer types, while trying to preserve typedef info
8857  QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
8858  QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
8859  if (Unqualified) {
8860  LHSPointee = LHSPointee.getUnqualifiedType();
8861  RHSPointee = RHSPointee.getUnqualifiedType();
8862  }
8863  QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
8864  Unqualified);
8865  if (ResultType.isNull())
8866  return {};
8867  if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
8868  return LHS;
8869  if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
8870  return RHS;
8871  return getPointerType(ResultType);
8872  }
8873  case Type::BlockPointer:
8874  {
8875  // Merge two block pointer types, while trying to preserve typedef info
8876  QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
8877  QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
8878  if (Unqualified) {
8879  LHSPointee = LHSPointee.getUnqualifiedType();
8880  RHSPointee = RHSPointee.getUnqualifiedType();
8881  }
8882  if (getLangOpts().OpenCL) {
8883  Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
8884  Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
8885  // Blocks can't be an expression in a ternary operator (OpenCL v2.0
8886  // 6.12.5) thus the following check is asymmetric.
8887  if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual))
8888  return {};
8889  LHSPteeQual.removeAddressSpace();
8890  RHSPteeQual.removeAddressSpace();
8891  LHSPointee =
8892  QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
8893  RHSPointee =
8894  QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
8895  }
8896  QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
8897  Unqualified);
8898  if (ResultType.isNull())
8899  return {};
8900  if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
8901  return LHS;
8902  if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
8903  return RHS;
8904  return getBlockPointerType(ResultType);
8905  }
8906  case Type::Atomic:
8907  {
8908  // Merge two pointer types, while trying to preserve typedef info
8909  QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
8910  QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
8911  if (Unqualified) {
8912  LHSValue = LHSValue.getUnqualifiedType();
8913  RHSValue = RHSValue.getUnqualifiedType();
8914  }
8915  QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
8916  Unqualified);
8917  if (ResultType.isNull())
8918  return {};
8919  if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
8920  return LHS;
8921  if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
8922  return RHS;
8923  return getAtomicType(ResultType);
8924  }
8925  case Type::ConstantArray:
8926  {
8927  const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
8928  const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
8929  if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
8930  return {};
8931 
8932  QualType LHSElem = getAsArrayType(LHS)->getElementType();
8933  QualType RHSElem = getAsArrayType(RHS)->getElementType();
8934  if (Unqualified) {
8935  LHSElem = LHSElem.getUnqualifiedType();
8936  RHSElem = RHSElem.getUnqualifiedType();
8937  }
8938 
8939  QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
8940  if (ResultType.isNull())
8941  return {};
8942 
8943  const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
8944  const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
8945 
8946  // If either side is a variable array, and both are complete, check whether
8947  // the current dimension is definite.
8948  if (LVAT || RVAT) {
8949  auto SizeFetch = [this](const VariableArrayType* VAT,
8950  const ConstantArrayType* CAT)
8951  -> std::pair<bool,llvm::APInt> {
8952  if (VAT) {
8953  llvm::APSInt TheInt;
8954  Expr *E = VAT->getSizeExpr();
8955  if (E && E->isIntegerConstantExpr(TheInt, *this))
8956  return std::make_pair(true, TheInt);
8957  else
8958  return std::make_pair(false, TheInt);
8959  } else if (CAT) {
8960  return std::make_pair(true, CAT->getSize());
8961  } else {
8962  return std::make_pair(false, llvm::APInt());
8963  }
8964  };
8965 
8966  bool HaveLSize, HaveRSize;
8967  llvm::APInt LSize, RSize;
8968  std::tie(HaveLSize, LSize) = SizeFetch(LVAT, LCAT);
8969  std::tie(HaveRSize, RSize) = SizeFetch(RVAT, RCAT);
8970  if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(LSize, RSize))
8971  return {}; // Definite, but unequal, array dimension
8972  }
8973 
8974  if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
8975  return LHS;
8976  if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
8977  return RHS;
8978  if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
8980  if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
8982  if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
8983  return LHS;
8984  if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
8985  return RHS;
8986  if (LVAT) {
8987  // FIXME: This isn't correct! But tricky to implement because
8988  // the array's size has to be the size of LHS, but the type
8989  // has to be different.
8990  return LHS;
8991  }
8992  if (RVAT) {
8993  // FIXME: This isn't correct! But tricky to implement because
8994  // the array's size has to be the size of RHS, but the type
8995  // has to be different.
8996  return RHS;
8997  }
8998  if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
8999  if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
9000  return getIncompleteArrayType(ResultType,
9002  }
9003  case Type::FunctionNoProto:
9004  return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
9005  case Type::Record:
9006  case Type::Enum:
9007  return {};
9008  case Type::Builtin:
9009  // Only exactly equal builtin types are compatible, which is tested above.
9010  return {};
9011  case Type::Complex:
9012  // Distinct complex types are incompatible.
9013  return {};
9014  case Type::Vector:
9015  // FIXME: The merged type should be an ExtVector!
9016  if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
9017  RHSCan->getAs<VectorType>()))
9018  return LHS;
9019  return {};
9020  case Type::ObjCObject: {
9021  // Check if the types are assignment compatible.
9022  // FIXME: This should be type compatibility, e.g. whether
9023  // "LHS x; RHS x;" at global scope is legal.
9024  const auto *LHSIface = LHS->getAs<ObjCObjectType>();
9025  const auto *RHSIface = RHS->getAs<ObjCObjectType>();
9026  if (canAssignObjCInterfaces(LHSIface, RHSIface))
9027  return LHS;
9028 
9029  return {};
9030  }
9031  case Type::ObjCObjectPointer:
9032  if (OfBlockPointer) {
9034  LHS->getAs<ObjCObjectPointerType>(),
9035  RHS->getAs<ObjCObjectPointerType>(),
9036  BlockReturnType))
9037  return LHS;
9038  return {};
9039  }
9041  RHS->getAs<ObjCObjectPointerType>()))
9042  return LHS;
9043 
9044  return {};
9045  case Type::Pipe:
9046  assert(LHS != RHS &&
9047  "Equivalent pipe types should have already been handled!");
9048  return {};
9049  }
9050 
9051  llvm_unreachable("Invalid Type::Class!");
9052 }
9053 
9055  const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType,
9056  bool &CanUseFirst, bool &CanUseSecond,
9058  assert(NewParamInfos.empty() && "param info list not empty");
9059  CanUseFirst = CanUseSecond = true;
9060  bool FirstHasInfo = FirstFnType->hasExtParameterInfos();
9061  bool SecondHasInfo = SecondFnType->hasExtParameterInfos();
9062 
9063  // Fast path: if the first type doesn't have ext parameter infos,
9064  // we match if and only if the second type also doesn't have them.
9065  if (!FirstHasInfo && !SecondHasInfo)
9066  return true;
9067 
9068  bool NeedParamInfo = false;
9069  size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size()
9070  : SecondFnType->getExtParameterInfos().size();
9071 
9072  for (size_t I = 0; I < E; ++I) {
9073  FunctionProtoType::ExtParameterInfo FirstParam, SecondParam;
9074  if (FirstHasInfo)
9075  FirstParam = FirstFnType->getExtParameterInfo(I);
9076  if (SecondHasInfo)
9077  SecondParam = SecondFnType->getExtParameterInfo(I);
9078 
9079  // Cannot merge unless everything except the noescape flag matches.
9080  if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false))
9081  return false;
9082 
9083  bool FirstNoEscape = FirstParam.isNoEscape();
9084  bool SecondNoEscape = SecondParam.isNoEscape();
9085  bool IsNoEscape = FirstNoEscape && SecondNoEscape;
9086  NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape));
9087  if (NewParamInfos.back().getOpaqueValue())
9088  NeedParamInfo = true;
9089  if (FirstNoEscape != IsNoEscape)
9090  CanUseFirst = false;
9091  if (SecondNoEscape != IsNoEscape)
9092  CanUseSecond = false;
9093  }
9094 
9095  if (!NeedParamInfo)
9096  NewParamInfos.clear();
9097 
9098  return true;
9099 }
9100 
9102  ObjCLayouts[CD] = nullptr;
9103 }
9104 
9105 /// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
9106 /// 'RHS' attributes and returns the merged version; including for function
9107 /// return types.
9109  QualType LHSCan = getCanonicalType(LHS),
9110  RHSCan = getCanonicalType(RHS);
9111  // If two types are identical, they are compatible.
9112  if (LHSCan == RHSCan)
9113  return LHS;
9114  if (RHSCan->isFunctionType()) {
9115  if (!LHSCan->isFunctionType())
9116  return {};
9117  QualType OldReturnType =
9118  cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
9119  QualType NewReturnType =
9120  cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
9121  QualType ResReturnType =
9122  mergeObjCGCQualifiers(NewReturnType, OldReturnType);
9123  if (ResReturnType.isNull())
9124  return {};
9125  if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
9126  // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
9127  // In either case, use OldReturnType to build the new function type.
9128  const auto *F = LHS->getAs<FunctionType>();
9129  if (const auto *FPT = cast<FunctionProtoType>(F)) {
9130  FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9131  EPI.ExtInfo = getFunctionExtInfo(LHS);
9132  QualType ResultType =
9133  getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
9134  return ResultType;
9135  }
9136  }
9137  return {};
9138  }
9139 
9140  // If the qualifiers are different, the types can still be merged.
9141  Qualifiers LQuals = LHSCan.getLocalQualifiers();
9142  Qualifiers RQuals = RHSCan.getLocalQualifiers();
9143  if (LQuals != RQuals) {
9144  // If any of these qualifiers are different, we have a type mismatch.
9145  if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
9146  LQuals.getAddressSpace() != RQuals.getAddressSpace())
9147  return {};
9148 
9149  // Exactly one GC qualifier difference is allowed: __strong is
9150  // okay if the other type has no GC qualifier but is an Objective
9151  // C object pointer (i.e. implicitly strong by default). We fix
9152  // this by pretending that the unqualified type was actually
9153  // qualified __strong.
9154  Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
9155  Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
9156  assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
9157 
9158  if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
9159  return {};
9160 
9161  if (GC_L == Qualifiers::Strong)
9162  return LHS;
9163  if (GC_R == Qualifiers::Strong)
9164  return RHS;
9165  return {};
9166  }
9167 
9168  if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
9169  QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
9170  QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
9171  QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
9172  if (ResQT == LHSBaseQT)
9173  return LHS;
9174  if (ResQT == RHSBaseQT)
9175  return RHS;
9176  }
9177  return {};
9178 }
9179 
9180 //===----------------------------------------------------------------------===//
9181 // Integer Predicates
9182 //===----------------------------------------------------------------------===//
9183 
9185  if (const auto *ET = T->getAs<EnumType>())
9186  T = ET->getDecl()->getIntegerType();
9187  if (T->isBooleanType())
9188  return 1;
9189  // For builtin types, just use the standard type sizing method
9190  return (unsigned)getTypeSize(T);
9191 }
9192 
9195  "Unexpected type");
9196 
9197  // Turn <4 x signed int> -> <4 x unsigned int>
9198  if (const auto *VTy = T->getAs<VectorType>())
9199  return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
9200  VTy->getNumElements(), VTy->getVectorKind());
9201 
9202  // For enums, we return the unsigned version of the base type.
9203  if (const auto *ETy = T->getAs<EnumType>())
9204  T = ETy->getDecl()->getIntegerType();
9205 
9206  const auto *BTy = T->getAs<BuiltinType>();
9207  assert(BTy && "Unexpected signed integer or fixed point type");
9208  switch (BTy->getKind()) {
9209  case BuiltinType::Char_S:
9210  case BuiltinType::SChar:
9211  return UnsignedCharTy;
9212  case BuiltinType::Short:
9213  return UnsignedShortTy;
9214  case BuiltinType::Int:
9215  return UnsignedIntTy;
9216  case BuiltinType::Long:
9217  return UnsignedLongTy;
9218  case BuiltinType::LongLong:
9219  return UnsignedLongLongTy;
9220  case BuiltinType::Int128:
9221  return UnsignedInt128Ty;
9222 
9223  case BuiltinType::ShortAccum:
9224  return UnsignedShortAccumTy;
9225  case BuiltinType::Accum:
9226  return UnsignedAccumTy;
9227  case BuiltinType::LongAccum:
9228  return UnsignedLongAccumTy;
9229  case BuiltinType::SatShortAccum:
9230  return SatUnsignedShortAccumTy;
9231  case BuiltinType::SatAccum:
9232  return SatUnsignedAccumTy;
9233  case BuiltinType::SatLongAccum:
9234  return SatUnsignedLongAccumTy;
9235  case BuiltinType::ShortFract:
9236  return UnsignedShortFractTy;
9237  case BuiltinType::Fract:
9238  return UnsignedFractTy;
9239  case BuiltinType::LongFract:
9240  return UnsignedLongFractTy;
9241  case BuiltinType::SatShortFract:
9242  return SatUnsignedShortFractTy;
9243  case BuiltinType::SatFract:
9244  return SatUnsignedFractTy;
9245  case BuiltinType::SatLongFract:
9246  return SatUnsignedLongFractTy;
9247  default:
9248  llvm_unreachable("Unexpected signed integer or fixed point type");
9249  }
9250 }
9251 
9253 
9255  QualType ReturnType) {}
9256 
9257 //===----------------------------------------------------------------------===//
9258 // Builtin Type Computation
9259 //===----------------------------------------------------------------------===//
9260 
9261 /// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
9262 /// pointer over the consumed characters. This returns the resultant type. If
9263 /// AllowTypeModifiers is false then modifier like * are not parsed, just basic
9264 /// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
9265 /// a vector of "i*".
9266 ///
9267 /// RequiresICE is filled in on return to indicate whether the value is required
9268 /// to be an Integer Constant Expression.
9269 static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
9271  bool &RequiresICE,
9272  bool AllowTypeModifiers) {
9273  // Modifiers.
9274  int HowLong = 0;
9275  bool Signed = false, Unsigned = false;
9276  RequiresICE = false;
9277 
9278  // Read the prefixed modifiers first.
9279  bool Done = false;
9280  #ifndef NDEBUG
9281  bool IsSpecial = false;
9282  #endif
9283  while (!Done) {
9284  switch (*Str++) {
9285  default: Done = true; --Str; break;
9286  case 'I':
9287  RequiresICE = true;
9288  break;
9289  case 'S':
9290  assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
9291  assert(!Signed && "Can't use 'S' modifier multiple times!");
9292  Signed = true;
9293  break;
9294  case 'U':
9295  assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
9296  assert(!Unsigned && "Can't use 'U' modifier multiple times!");
9297  Unsigned = true;
9298  break;
9299  case 'L':
9300  assert(!IsSpecial && "Can't use 'L' with 'W', 'N', 'Z' or 'O' modifiers");
9301  assert(HowLong <= 2 && "Can't have LLLL modifier");
9302  ++HowLong;
9303  break;
9304  case 'N':
9305  // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
9306  assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
9307  assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
9308  #ifndef NDEBUG
9309  IsSpecial = true;
9310  #endif
9311  if (Context.getTargetInfo().getLongWidth() == 32)
9312  ++HowLong;
9313  break;
9314  case 'W':
9315  // This modifier represents int64 type.
9316  assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
9317  assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
9318  #ifndef NDEBUG
9319  IsSpecial = true;
9320  #endif
9321  switch (Context.getTargetInfo().getInt64Type()) {
9322  default:
9323  llvm_unreachable("Unexpected integer type");
9325  HowLong = 1;
9326  break;
9328  HowLong = 2;
9329  break;
9330  }
9331  break;
9332  case 'Z':
9333  // This modifier represents int32 type.
9334  assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
9335  assert(HowLong == 0 && "Can't use both 'L' and 'Z' modifiers!");
9336  #ifndef NDEBUG
9337  IsSpecial = true;
9338  #endif
9339  switch (Context.getTargetInfo().getIntTypeByWidth(32, true)) {
9340  default:
9341  llvm_unreachable("Unexpected integer type");
9342  case TargetInfo::SignedInt:
9343  HowLong = 0;
9344  break;
9346  HowLong = 1;
9347  break;
9349  HowLong = 2;
9350  break;
9351  }
9352  break;
9353  case 'O':
9354  assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
9355  assert(HowLong == 0 && "Can't use both 'L' and 'O' modifiers!");
9356  #ifndef NDEBUG
9357  IsSpecial = true;
9358  #endif
9359  if (Context.getLangOpts().OpenCL)
9360  HowLong = 1;
9361  else
9362  HowLong = 2;
9363  break;
9364  }
9365  }
9366 
9367  QualType Type;
9368 
9369  // Read the base type.
9370  switch (*Str++) {
9371  default: llvm_unreachable("Unknown builtin type letter!");
9372  case 'v':
9373  assert(HowLong == 0 && !Signed && !Unsigned &&
9374  "Bad modifiers used with 'v'!");
9375  Type = Context.VoidTy;
9376  break;
9377  case 'h':
9378  assert(HowLong == 0 && !Signed && !Unsigned &&
9379  "Bad modifiers used with 'h'!");
9380  Type = Context.HalfTy;
9381  break;
9382  case 'f':
9383  assert(HowLong == 0 && !Signed && !Unsigned &&
9384  "Bad modifiers used with 'f'!");
9385  Type = Context.FloatTy;
9386  break;
9387  case 'd':
9388  assert(HowLong < 3 && !Signed && !Unsigned &&
9389  "Bad modifiers used with 'd'!");
9390  if (HowLong == 1)
9391  Type = Context.LongDoubleTy;
9392  else if (HowLong == 2)
9393  Type = Context.Float128Ty;
9394  else
9395  Type = Context.DoubleTy;
9396  break;
9397  case 's':
9398  assert(HowLong == 0 && "Bad modifiers used with 's'!");
9399  if (Unsigned)
9400  Type = Context.UnsignedShortTy;
9401  else
9402  Type = Context.ShortTy;
9403  break;
9404  case 'i':
9405  if (HowLong == 3)
9406  Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
9407  else if (HowLong == 2)
9408  Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
9409  else if (HowLong == 1)
9410  Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
9411  else
9412  Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
9413  break;
9414  case 'c':
9415  assert(HowLong == 0 && "Bad modifiers used with 'c'!");
9416  if (Signed)
9417  Type = Context.SignedCharTy;
9418  else if (Unsigned)
9419  Type = Context.UnsignedCharTy;
9420  else
9421  Type = Context.CharTy;
9422  break;
9423  case 'b': // boolean
9424  assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
9425  Type = Context.BoolTy;
9426  break;
9427  case 'z': // size_t.
9428  assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
9429  Type = Context.getSizeType();
9430  break;
9431  case 'w': // wchar_t.
9432  assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
9433  Type = Context.getWideCharType();
9434  break;
9435  case 'F':
9436  Type = Context.getCFConstantStringType();
9437  break;
9438  case 'G':
9439  Type = Context.getObjCIdType();
9440  break;
9441  case 'H':
9442  Type = Context.getObjCSelType();
9443  break;
9444  case 'M':
9445  Type = Context.getObjCSuperType();
9446  break;
9447  case 'a':
9448  Type = Context.getBuiltinVaListType();
9449  assert(!Type.isNull() && "builtin va list type not initialized!");
9450  break;
9451  case 'A':
9452  // This is a "reference" to a va_list; however, what exactly
9453  // this means depends on how va_list is defined. There are two
9454  // different kinds of va_list: ones passed by value, and ones
9455  // passed by reference. An example of a by-value va_list is
9456  // x86, where va_list is a char*. An example of by-ref va_list
9457  // is x86-64, where va_list is a __va_list_tag[1]. For x86,
9458  // we want this argument to be a char*&; for x86-64, we want
9459  // it to be a __va_list_tag*.
9460  Type = Context.getBuiltinVaListType();
9461  assert(!Type.isNull() && "builtin va list type not initialized!");
9462  if (Type->isArrayType())
9463  Type = Context.getArrayDecayedType(Type);
9464  else
9465  Type = Context.getLValueReferenceType(Type);
9466  break;
9467  case 'V': {
9468  char *End;
9469  unsigned NumElements = strtoul(Str, &End, 10);
9470  assert(End != Str && "Missing vector size");
9471  Str = End;
9472 
9473  QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
9474  RequiresICE, false);
9475  assert(!RequiresICE && "Can't require vector ICE");
9476 
9477  // TODO: No way to make AltiVec vectors in builtins yet.
9478  Type = Context.getVectorType(ElementType, NumElements,
9480  break;
9481  }
9482  case 'E': {
9483  char *End;
9484 
9485  unsigned NumElements = strtoul(Str, &End, 10);
9486  assert(End != Str && "Missing vector size");
9487 
9488  Str = End;
9489 
9490  QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
9491  false);
9492  Type = Context.getExtVectorType(ElementType, NumElements);
9493  break;
9494  }
9495  case 'X': {
9496  QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
9497  false);
9498  assert(!RequiresICE && "Can't require complex ICE");
9499  Type = Context.getComplexType(ElementType);
9500  break;
9501  }
9502  case 'Y':
9503  Type = Context.getPointerDiffType();
9504  break;
9505  case 'P':
9506  Type = Context.getFILEType();
9507  if (Type.isNull()) {
9509  return {};
9510  }
9511  break;
9512  case 'J':
9513  if (Signed)
9514  Type = Context.getsigjmp_bufType();
9515  else
9516  Type = Context.getjmp_bufType();
9517 
9518  if (Type.isNull()) {
9520  return {};
9521  }
9522  break;
9523  case 'K':
9524  assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
9525  Type = Context.getucontext_tType();
9526 
9527  if (Type.isNull()) {
9529  return {};
9530  }
9531  break;
9532  case 'p':
9533  Type = Context.getProcessIDType();
9534  break;
9535  }
9536 
9537  // If there are modifiers and if we're allowed to parse them, go for it.
9538  Done = !AllowTypeModifiers;
9539  while (!Done) {
9540  switch (char c = *Str++) {
9541  default: Done = true; --Str; break;
9542  case '*':
9543  case '&': {
9544  // Both pointers and references can have their pointee types
9545  // qualified with an address space.
9546  char *End;
9547  unsigned AddrSpace = strtoul(Str, &End, 10);
9548  if (End != Str) {
9549  // Note AddrSpace == 0 is not the same as an unspecified address space.
9550  Type = Context.getAddrSpaceQualType(
9551  Type,
9552  Context.getLangASForBuiltinAddressSpace(AddrSpace));
9553  Str = End;
9554  }
9555  if (c == '*')
9556  Type = Context.getPointerType(Type);
9557  else
9558  Type = Context.getLValueReferenceType(Type);
9559  break;
9560  }
9561  // FIXME: There's no way to have a built-in with an rvalue ref arg.
9562  case 'C':
9563  Type = Type.withConst();
9564  break;
9565  case 'D':
9566  Type = Context.getVolatileType(Type);
9567  break;
9568  case 'R':
9569  Type = Type.withRestrict();
9570  break;
9571  }
9572  }
9573 
9574  assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
9575  "Integer constant 'I' type must be an integer");
9576 
9577  return Type;
9578 }
9579 
9580 /// GetBuiltinType - Return the type for the specified builtin.
9583  unsigned *IntegerConstantArgs) const {
9584  const char *TypeStr = BuiltinInfo.getTypeString(Id);
9585  if (TypeStr[0] == '\0') {
9586  Error = GE_Missing_type;
9587  return {};
9588  }
9589 
9590  SmallVector<QualType, 8> ArgTypes;
9591 
9592  bool RequiresICE = false;
9593  Error = GE_None;
9594  QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
9595  RequiresICE, true);
9596  if (Error != GE_None)
9597  return {};
9598 
9599  assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
9600 
9601  while (TypeStr[0] && TypeStr[0] != '.') {
9602  QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
9603  if (Error != GE_None)
9604  return {};
9605 
9606  // If this argument is required to be an IntegerConstantExpression and the
9607  // caller cares, fill in the bitmask we return.
9608  if (RequiresICE && IntegerConstantArgs)
9609  *IntegerConstantArgs |= 1 << ArgTypes.size();
9610 
9611  // Do array -> pointer decay. The builtin should use the decayed type.
9612  if (Ty->isArrayType())
9613  Ty = getArrayDecayedType(Ty);
9614 
9615  ArgTypes.push_back(Ty);
9616  }
9617 
9618  if (Id == Builtin::BI__GetExceptionInfo)
9619  return {};
9620 
9621  assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
9622  "'.' should only occur at end of builtin type list!");
9623 
9624  bool Variadic = (TypeStr[0] == '.');
9625 
9627  Variadic, /*IsCXXMethod=*/false, /*IsBuiltin=*/true));
9628  if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
9629 
9630 
9631  // We really shouldn't be making a no-proto type here.
9632  if (ArgTypes.empty() && Variadic && !getLangOpts().CPlusPlus)
9633  return getFunctionNoProtoType(ResType, EI);
9634 
9636  EPI.ExtInfo = EI;
9637  EPI.Variadic = Variadic;
9638  if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id))
9639  EPI.ExceptionSpec.Type =
9640  getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
9641 
9642  return getFunctionType(ResType, ArgTypes, EPI);
9643 }
9644 
9646  const FunctionDecl *FD) {
9647  if (!FD->isExternallyVisible())
9648  return GVA_Internal;
9649 
9650  // Non-user-provided functions get emitted as weak definitions with every
9651  // use, no matter whether they've been explicitly instantiated etc.
9652  if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
9653  if (!MD->isUserProvided())
9654  return GVA_DiscardableODR;
9655 
9656  GVALinkage External;
9657  switch (FD->getTemplateSpecializationKind()) {
9658  case TSK_Undeclared:
9660  External = GVA_StrongExternal;
9661  break;
9662 
9664  return GVA_StrongODR;
9665 
9666  // C++11 [temp.explicit]p10:
9667  // [ Note: The intent is that an inline function that is the subject of
9668  // an explicit instantiation declaration will still be implicitly
9669  // instantiated when used so that the body can be considered for
9670  // inlining, but that no out-of-line copy of the inline function would be
9671  // generated in the translation unit. -- end note ]
9673  return GVA_AvailableExternally;
9674 
9676  External = GVA_DiscardableODR;
9677  break;
9678  }
9679 
9680  if (!FD->isInlined())
9681  return External;
9682 
9683  if ((!Context.getLangOpts().CPlusPlus &&
9684  !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
9685  !FD->hasAttr<DLLExportAttr>()) ||
9686  FD->hasAttr<GNUInlineAttr>()) {
9687  // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
9688 
9689  // GNU or C99 inline semantics. Determine whether this symbol should be
9690  // externally visible.
9692  return External;
9693 
9694  // C99 inline semantics, where the symbol is not externally visible.
9695  return GVA_AvailableExternally;
9696  }
9697 
9698  // Functions specified with extern and inline in -fms-compatibility mode
9699  // forcibly get emitted. While the body of the function cannot be later
9700  // replaced, the function definition cannot be discarded.
9701  if (FD->isMSExternInline())
9702  return GVA_StrongODR;
9703 
9704  return GVA_DiscardableODR;
9705 }
9706 
9708  const Decl *D, GVALinkage L) {
9709  // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
9710  // dllexport/dllimport on inline functions.
9711  if (D->hasAttr<DLLImportAttr>()) {
9712  if (L == GVA_DiscardableODR || L == GVA_StrongODR)
9713  return GVA_AvailableExternally;
9714  } else if (D->hasAttr<DLLExportAttr>()) {
9715  if (L == GVA_DiscardableODR)
9716  return GVA_StrongODR;
9717  } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice &&
9718  D->hasAttr<CUDAGlobalAttr>()) {
9719  // Device-side functions with __global__ attribute must always be
9720  // visible externally so they can be launched from host.
9721  if (L == GVA_DiscardableODR || L == GVA_Internal)
9722  return GVA_StrongODR;
9723  }
9724  return L;
9725 }
9726 
9727 /// Adjust the GVALinkage for a declaration based on what an external AST source
9728 /// knows about whether there can be other definitions of this declaration.
9729 static GVALinkage
9731  GVALinkage L) {
9732  ExternalASTSource *Source = Ctx.getExternalSource();
9733  if (!Source)
9734  return L;
9735 
9736  switch (Source->hasExternalDefinitions(D)) {
9738  // Other translation units rely on us to provide the definition.
9739  if (L == GVA_DiscardableODR)
9740  return GVA_StrongODR;
9741  break;
9742 
9744  return GVA_AvailableExternally;
9745 
9747  break;
9748  }
9749  return L;
9750 }
9751 
9755  basicGVALinkageForFunction(*this, FD)));
9756 }
9757 
9759  const VarDecl *VD) {
9760  if (!VD->isExternallyVisible())
9761  return GVA_Internal;
9762 
9763  if (VD->isStaticLocal()) {
9764  const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
9765  while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
9766  LexicalContext = LexicalContext->getLexicalParent();
9767 
9768  // ObjC Blocks can create local variables that don't have a FunctionDecl
9769  // LexicalContext.
9770  if (!LexicalContext)
9771  return GVA_DiscardableODR;
9772 
9773  // Otherwise, let the static local variable inherit its linkage from the
9774  // nearest enclosing function.
9775  auto StaticLocalLinkage =
9776  Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
9777 
9778  // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
9779  // be emitted in any object with references to the symbol for the object it
9780  // contains, whether inline or out-of-line."
9781  // Similar behavior is observed with MSVC. An alternative ABI could use
9782  // StrongODR/AvailableExternally to match the function, but none are
9783  // known/supported currently.
9784  if (StaticLocalLinkage == GVA_StrongODR ||
9785  StaticLocalLinkage == GVA_AvailableExternally)
9786  return GVA_DiscardableODR;
9787  return StaticLocalLinkage;
9788  }
9789 
9790  // MSVC treats in-class initialized static data members as definitions.
9791  // By giving them non-strong linkage, out-of-line definitions won't
9792  // cause link errors.
9793  if (Context.isMSStaticDataMemberInlineDefinition(VD))
9794  return GVA_DiscardableODR;
9795 
9796  // Most non-template variables have strong linkage; inline variables are
9797  // linkonce_odr or (occasionally, for compatibility) weak_odr.
9798  GVALinkage StrongLinkage;
9799  switch (Context.getInlineVariableDefinitionKind(VD)) {
9801  StrongLinkage = GVA_StrongExternal;
9802  break;
9805  StrongLinkage = GVA_DiscardableODR;
9806  break;
9808  StrongLinkage = GVA_StrongODR;
9809  break;
9810  }
9811 
9812  switch (VD->getTemplateSpecializationKind()) {
9813  case TSK_Undeclared:
9814  return StrongLinkage;
9815 
9817  if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
9818  // If this is a fully specialized constexpr variable template, pretend it
9819  // was marked inline. MSVC 14.21.27702 headers define _Is_integral in a
9820  // header this way, and we don't want to emit non-discardable definitions
9821  // of these variables in every TU that includes <type_traits>. This
9822  // behavior is non-conforming, since another TU could use an extern
9823  // template declaration for this variable, but for constexpr variables,
9824  // it's unlikely for a user to want to do that. This behavior can be
9825  // removed if the headers change to explicitly mark such variable template
9826  // specializations inline.
9827  if (isa<VarTemplateSpecializationDecl>(VD) && VD->isConstexpr())
9828  return GVA_DiscardableODR;
9829 
9830  // Use ODR linkage for static data members of fully specialized templates
9831  // to prevent duplicate definition errors with MSVC.
9832  if (VD->isStaticDataMember())
9833  return GVA_StrongODR;
9834  }
9835  return StrongLinkage;
9836 
9838  return GVA_StrongODR;
9839 
9841  return GVA_AvailableExternally;
9842 
9844  return GVA_DiscardableODR;
9845  }
9846 
9847  llvm_unreachable("Invalid Linkage!");
9848 }
9849 
9853  basicGVALinkageForVariable(*this, VD)));
9854 }
9855 
9856 bool ASTContext::DeclMustBeEmitted(const Decl *D) {
9857  if (const auto *VD = dyn_cast<VarDecl>(D)) {
9858  if (!VD->isFileVarDecl())
9859  return false;
9860  // Global named register variables (GNU extension) are never emitted.
9861  if (VD->getStorageClass() == SC_Register)
9862  return false;
9863  if (VD->getDescribedVarTemplate() ||
9864  isa<VarTemplatePartialSpecializationDecl>(VD))
9865  return false;
9866  } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
9867  // We never need to emit an uninstantiated function template.
9868  if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
9869  return false;
9870  } else if (isa<PragmaCommentDecl>(D))
9871  return true;
9872  else if (isa<PragmaDetectMismatchDecl>(D))
9873  return true;
9874  else if (isa<OMPThreadPrivateDecl>(D))
9875  return !D->getDeclContext()->isDependentContext();
9876  else if (isa<OMPAllocateDecl>(D))
9877  return !D->getDeclContext()->isDependentContext();
9878  else if (isa<OMPDeclareReductionDecl>(D))
9879  return !D->getDeclContext()->isDependentContext();
9880  else if (isa<ImportDecl>(D))
9881  return true;
9882  else
9883  return false;
9884 
9885  if (D->isFromASTFile() && !LangOpts.BuildingPCHWithObjectFile) {
9886  assert(getExternalSource() && "It's from an AST file; must have a source.");
9887  // On Windows, PCH files are built together with an object file. If this
9888  // declaration comes from such a PCH and DeclMustBeEmitted would return
9889  // true, it would have returned true and the decl would have been emitted
9890  // into that object file, so it doesn't need to be emitted here.
9891  // Note that decls are still emitted if they're referenced, as usual;
9892  // DeclMustBeEmitted is used to decide whether a decl must be emitted even
9893  // if it's not referenced.
9894  //
9895  // Explicit template instantiation definitions are tricky. If there was an
9896  // explicit template instantiation decl in the PCH before, it will look like
9897  // the definition comes from there, even if that was just the declaration.
9898  // (Explicit instantiation defs of variable templates always get emitted.)
9899  bool IsExpInstDef =
9900  isa<FunctionDecl>(D) &&
9901  cast<FunctionDecl>(D)->getTemplateSpecializationKind() ==
9903 
9904  // Implicit member function definitions, such as operator= might not be
9905  // marked as template specializations, since they're not coming from a
9906  // template but synthesized directly on the class.
9907  IsExpInstDef |=
9908  isa<CXXMethodDecl>(D) &&
9909  cast<CXXMethodDecl>(D)->getParent()->getTemplateSpecializationKind() ==
9911 
9912  if (getExternalSource()->DeclIsFromPCHWithObjectFile(D) && !IsExpInstDef)
9913  return false;
9914  }
9915 
9916  // If this is a member of a class template, we do not need to emit it.
9917  if (D->getDeclContext()->isDependentContext())
9918  return false;
9919 
9920  // Weak references don't produce any output by themselves.
9921  if (D->hasAttr<WeakRefAttr>())
9922  return false;
9923 
9924  // Aliases and used decls are required.
9925  if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
9926  return true;
9927 
9928  if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
9929  // Forward declarations aren't required.
9930  if (!FD->doesThisDeclarationHaveABody())
9931  return FD->doesDeclarationForceExternallyVisibleDefinition();
9932 
9933  // Constructors and destructors are required.
9934  if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
9935  return true;
9936 
9937  // The key function for a class is required. This rule only comes
9938  // into play when inline functions can be key functions, though.
9939  if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
9940  if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
9941  const CXXRecordDecl *RD = MD->getParent();
9942  if (MD->isOutOfLine() && RD->isDynamicClass()) {
9943  const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
9944  if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
9945  return true;
9946  }
9947  }
9948  }
9949 
9951 
9952  // static, static inline, always_inline, and extern inline functions can
9953  // always be deferred. Normal inline functions can be deferred in C99/C++.
9954  // Implicit template instantiations can also be deferred in C++.
9955  return !isDiscardableGVALinkage(Linkage);
9956  }
9957 
9958  const auto *VD = cast<VarDecl>(D);
9959  assert(VD->isFileVarDecl() && "Expected file scoped var");
9960 
9961  // If the decl is marked as `declare target to`, it should be emitted for the
9962  // host and for the device.
9963  if (LangOpts.OpenMP &&
9964  OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
9965  return true;
9966 
9967  if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
9969  return false;
9970 
9971  // Variables that can be needed in other TUs are required.
9972  auto Linkage = GetGVALinkageForVariable(VD);
9974  return true;
9975 
9976  // We never need to emit a variable that is available in another TU.
9978  return false;
9979 
9980  // Variables that have destruction with side-effects are required.
9981  if (VD->getType().isDestructedType())
9982  return true;
9983 
9984  // Variables that have initialization with side-effects are required.
9985  if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
9986  // We can get a value-dependent initializer during error recovery.
9987  (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
9988  return true;
9989 
9990  // Likewise, variables with tuple-like bindings are required if their
9991  // bindings have side-effects.
9992  if (const auto *DD = dyn_cast<DecompositionDecl>(VD))
9993  for (const auto *BD : DD->bindings())
9994  if (const auto *BindingVD = BD->getHoldingVar())
9995  if (DeclMustBeEmitted(BindingVD))
9996  return true;
9997 
9998  return false;
9999 }
10000 
10002  const FunctionDecl *FD,
10003  llvm::function_ref<void(FunctionDecl *)> Pred) const {
10004  assert(FD->isMultiVersion() && "Only valid for multiversioned functions");
10005  llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls;
10006  FD = FD->getMostRecentDecl();
10007  for (auto *CurDecl :
10009  FunctionDecl *CurFD = CurDecl->getAsFunction()->getMostRecentDecl();
10010  if (CurFD && hasSameType(CurFD->getType(), FD->getType()) &&
10011  std::end(SeenDecls) == llvm::find(SeenDecls, CurFD)) {
10012  SeenDecls.insert(CurFD);
10013  Pred(CurFD);
10014  }
10015  }
10016 }
10017 
10019  bool IsCXXMethod,
10020  bool IsBuiltin) const {
10021  // Pass through to the C++ ABI object
10022  if (IsCXXMethod)
10023  return ABI->getDefaultMethodCallConv(IsVariadic);
10024 
10025  // Builtins ignore user-specified default calling convention and remain the
10026  // Target's default calling convention.
10027  if (!IsBuiltin) {
10028  switch (LangOpts.getDefaultCallingConv()) {
10029  case LangOptions::DCC_None:
10030  break;
10032  return CC_C;
10034  if (getTargetInfo().hasFeature("sse2") && !IsVariadic)
10035  return CC_X86FastCall;
10036  break;
10038  if (!IsVariadic)
10039  return CC_X86StdCall;
10040  break;
10042  // __vectorcall cannot be applied to variadic functions.
10043  if (!IsVariadic)
10044  return CC_X86VectorCall;
10045  break;
10047  // __regcall cannot be applied to variadic functions.
10048  if (!IsVariadic)
10049  return CC_X86RegCall;
10050  break;
10051  }
10052  }
10053  return Target->getDefaultCallingConv();
10054 }
10055 
10057  // Pass through to the C++ ABI object
10058  return ABI->isNearlyEmpty(RD);
10059 }
10060 
10062  if (!VTContext.get()) {
10063  if (Target->getCXXABI().isMicrosoft())
10064  VTContext.reset(new MicrosoftVTableContext(*this));
10065  else
10066  VTContext.reset(new ItaniumVTableContext(*this));
10067  }
10068  return VTContext.get();
10069 }
10070 
10072  if (!T)
10073  T = Target;
10074  switch (T->getCXXABI().getKind()) {
10079  case TargetCXXABI::iOS:
10080  case TargetCXXABI::iOS64:
10082  case TargetCXXABI::WatchOS:
10086  }
10087  llvm_unreachable("Unsupported ABI");
10088 }
10089 
10090 CXXABI::~CXXABI() = default;
10091 
10093  return ASTRecordLayouts.getMemorySize() +
10094  llvm::capacity_in_bytes(ObjCLayouts) +
10095  llvm::capacity_in_bytes(KeyFunctions) +
10096  llvm::capacity_in_bytes(ObjCImpls) +
10097  llvm::capacity_in_bytes(BlockVarCopyInits) +
10098  llvm::capacity_in_bytes(DeclAttrs) +
10099  llvm::capacity_in_bytes(TemplateOrInstantiation) +
10100  llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
10101  llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
10102  llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
10103  llvm::capacity_in_bytes(OverriddenMethods) +
10104  llvm::capacity_in_bytes(Types) +
10105  llvm::capacity_in_bytes(VariableArrayTypes);
10106 }
10107 
10108 /// getIntTypeForBitwidth -
10109 /// sets integer QualTy according to specified details:
10110 /// bitwidth, signed/unsigned.
10111 /// Returns empty type if there is no appropriate target types.
10113  unsigned Signed) const {
10114  TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
10115  CanQualType QualTy = getFromTargetType(Ty);
10116  if (!QualTy && DestWidth == 128)
10117  return Signed ? Int128Ty : UnsignedInt128Ty;
10118  return QualTy;
10119 }
10120 
10121 /// getRealTypeForBitwidth -
10122 /// sets floating point QualTy according to specified bitwidth.
10123 /// Returns empty type if there is no appropriate target types.
10126  switch (Ty) {
10127  case TargetInfo::Float:
10128  return FloatTy;
10129  case TargetInfo::Double:
10130  return DoubleTy;
10132  return LongDoubleTy;
10133  case TargetInfo::Float128:
10134  return Float128Ty;
10135  case TargetInfo::NoFloat:
10136  return {};
10137  }
10138 
10139  llvm_unreachable("Unhandled TargetInfo::RealType value");
10140 }
10141 
10142 void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
10143  if (Number > 1)
10144  MangleNumbers[ND] = Number;
10145 }
10146 
10147 unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
10148  auto I = MangleNumbers.find(ND);
10149  return I != MangleNumbers.end() ? I->second : 1;
10150 }
10151 
10152 void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
10153  if (Number > 1)
10154  StaticLocalNumbers[VD] = Number;
10155 }
10156 
10157 unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
10158  auto I = StaticLocalNumbers.find(VD);
10159  return I != StaticLocalNumbers.end() ? I->second : 1;
10160 }
10161 
10164  assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
10165  std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
10166  if (!MCtx)
10168  return *MCtx;
10169 }
10170 
10171 std::unique_ptr<MangleNumberingContext>
10173  return ABI->createMangleNumberingContext();
10174 }
10175 
10176 const CXXConstructorDecl *
10178  return ABI->getCopyConstructorForExceptionObject(
10179  cast<CXXRecordDecl>(RD->getFirstDecl()));
10180 }
10181 
10183  CXXConstructorDecl *CD) {
10184  return ABI->addCopyConstructorForExceptionObject(
10185  cast<CXXRecordDecl>(RD->getFirstDecl()),
10186  cast<CXXConstructorDecl>(CD->getFirstDecl()));
10187 }
10188 
10190  TypedefNameDecl *DD) {
10191  return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
10192 }
10193 
10196  return ABI->getTypedefNameForUnnamedTagDecl(TD);
10197 }
10198 
10200  DeclaratorDecl *DD) {
10201  return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
10202 }
10203 
10205  return ABI->getDeclaratorForUnnamedTagDecl(TD);
10206 }
10207 
10208 void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
10209  ParamIndices[D] = index;
10210 }
10211 
10212 unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
10213  ParameterIndexTable::const_iterator I = ParamIndices.find(D);
10214  assert(I != ParamIndices.end() &&
10215  "ParmIndices lacks entry set by ParmVarDecl");
10216  return I->second;
10217 }
10218 
10219 APValue *
10221  bool MayCreate) {
10222  assert(E && E->getStorageDuration() == SD_Static &&
10223  "don't need to cache the computed value for this temporary");
10224  if (MayCreate) {
10225  APValue *&MTVI = MaterializedTemporaryValues[E];
10226  if (!MTVI)
10227  MTVI = new (*this) APValue;
10228  return MTVI;
10229  }
10230 
10231  return MaterializedTemporaryValues.lookup(E);
10232 }
10233 
10235  unsigned Length) const {
10236  // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
10237  if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
10238  EltTy = EltTy.withConst();
10239 
10240  EltTy = adjustStringLiteralBaseType(EltTy);
10241 
10242  // Get an array type for the string, according to C99 6.4.5. This includes
10243  // the null terminator character.
10244  return getConstantArrayType(EltTy, llvm::APInt(32, Length + 1),
10245  ArrayType::Normal, /*IndexTypeQuals*/ 0);
10246 }
10247 
10248 StringLiteral *
10250  StringLiteral *&Result = StringLiteralCache[Key];
10251  if (!Result)
10252  Result = StringLiteral::Create(
10253  *this, Key, StringLiteral::Ascii,
10254  /*Pascal*/ false, getStringLiteralArrayType(CharTy, Key.size()),
10255  SourceLocation());
10256  return Result;
10257 }
10258 
10260  const llvm::Triple &T = getTargetInfo().getTriple();
10261  if (!T.isOSDarwin())
10262  return false;
10263 
10264  if (!(T.isiOS() && T.isOSVersionLT(7)) &&
10265  !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
10266  return false;
10267 
10268  QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
10269  CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
10270  uint64_t Size = sizeChars.getQuantity();
10271  CharUnits alignChars = getTypeAlignInChars(AtomicTy);
10272  unsigned Align = alignChars.getQuantity();
10273  unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
10274  return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
10275 }
10276 
10277 /// Template specializations to abstract away from pointers and TypeLocs.
10278 /// @{
10279 template <typename T>
10282 }
10283 template <>
10286 }
10287 template <>
10291 }
10292 /// @}
10293 
10294 /// A \c RecursiveASTVisitor that builds a map from nodes to their
10295 /// parents as defined by the \c RecursiveASTVisitor.
10296 ///
10297 /// Note that the relationship described here is purely in terms of AST
10298 /// traversal - there are other relationships (for example declaration context)
10299 /// in the AST that are better modeled by special matchers.
10300 ///
10301 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
10303  : public RecursiveASTVisitor<ASTVisitor> {
10304 public:
10305  ASTVisitor(ParentMap &Map) : Map(Map) {}
10306 
10307 private:
10309 
10311 
10312  bool shouldVisitTemplateInstantiations() const { return true; }
10313 
10314  bool shouldVisitImplicitCode() const { return true; }
10315 
10316  template <typename T, typename MapNodeTy, typename BaseTraverseFn,
10317  typename MapTy>
10318  bool TraverseNode(T Node, MapNodeTy MapNode, BaseTraverseFn BaseTraverse,
10319  MapTy *Parents) {
10320  if (!Node)
10321  return true;
10322  if (ParentStack.size() > 0) {
10323  // FIXME: Currently we add the same parent multiple times, but only
10324  // when no memoization data is available for the type.
10325  // For example when we visit all subexpressions of template
10326  // instantiations; this is suboptimal, but benign: the only way to
10327  // visit those is with hasAncestor / hasParent, and those do not create
10328  // new matches.
10329  // The plan is to enable DynTypedNode to be storable in a map or hash
10330  // map. The main problem there is to implement hash functions /
10331  // comparison operators for all types that DynTypedNode supports that
10332  // do not have pointer identity.
10333  auto &NodeOrVector = (*Parents)[MapNode];
10334  if (NodeOrVector.isNull()) {
10335  if (const auto *D = ParentStack.back().get<Decl>())
10336  NodeOrVector = D;
10337  else if (const auto *S = ParentStack.back().get<Stmt>())
10338  NodeOrVector = S;
10339  else
10340  NodeOrVector = new ast_type_traits::DynTypedNode(ParentStack.back());
10341  } else {
10342  if (!NodeOrVector.template is<ParentVector *>()) {
10343  auto *Vector = new ParentVector(
10344  1, getSingleDynTypedNodeFromParentMap(NodeOrVector));
10345  delete NodeOrVector
10346  .template dyn_cast<ast_type_traits::DynTypedNode *>();
10347  NodeOrVector = Vector;
10348  }
10349 
10350  auto *Vector = NodeOrVector.template get<ParentVector *>();
10351  // Skip duplicates for types that have memoization data.
10352  // We must check that the type has memoization data before calling
10353  // std::find() because DynTypedNode::operator== can't compare all
10354  // types.
10355  bool Found = ParentStack.back().getMemoizationData() &&
10356  std::find(Vector->begin(), Vector->end(),
10357  ParentStack.back()) != Vector->end();
10358  if (!Found)
10359  Vector->push_back(ParentStack.back());
10360  }
10361  }
10362  ParentStack.push_back(createDynTypedNode(Node));
10363  bool Result = BaseTraverse();
10364  ParentStack.pop_back();
10365  return Result;
10366  }
10367 
10368  bool TraverseDecl(Decl *DeclNode) {
10369  return TraverseNode(
10370  DeclNode, DeclNode, [&] { return VisitorBase::TraverseDecl(DeclNode); },
10371  &Map.PointerParents);
10372  }
10373 
10374  bool TraverseStmt(Stmt *StmtNode) {
10375  return TraverseNode(
10376  StmtNode, StmtNode, [&] { return VisitorBase::TraverseStmt(StmtNode); },
10377  &Map.PointerParents);
10378  }
10379 
10380  bool TraverseTypeLoc(TypeLoc TypeLocNode) {
10381  return TraverseNode(
10382  TypeLocNode, ast_type_traits::DynTypedNode::create(TypeLocNode),
10383  [&] { return VisitorBase::TraverseTypeLoc(TypeLocNode); },
10384  &Map.OtherParents);
10385  }
10386 
10387  bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNSLocNode) {
10388  return TraverseNode(
10389  NNSLocNode, ast_type_traits::DynTypedNode::create(NNSLocNode),
10390  [&] { return VisitorBase::TraverseNestedNameSpecifierLoc(NNSLocNode); },
10391  &Map.OtherParents);
10392  }
10393 
10394  ParentMap &Map;
10396 };
10397 
10399  ASTVisitor(*this).TraverseAST(Ctx);
10400 }
10401 
10404  if (!Parents)
10405  // We build the parent map for the traversal scope (usually whole TU), as
10406  // hasAncestor can escape any subtree.
10407  Parents = llvm::make_unique<ParentMap>(*this);
10408  return Parents->getParents(Node);
10409 }
10410 
10411 bool
10413  const ObjCMethodDecl *MethodImpl) {
10414  // No point trying to match an unavailable/deprecated mothod.
10415  if (MethodDecl->hasAttr<UnavailableAttr>()
10416  || MethodDecl->hasAttr<DeprecatedAttr>())
10417  return false;
10418  if (MethodDecl->getObjCDeclQualifier() !=
10419  MethodImpl->getObjCDeclQualifier())
10420  return false;
10421  if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
10422  return false;
10423 
10424  if (MethodDecl->param_size() != MethodImpl->param_size())
10425  return false;
10426 
10427  for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
10428  IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
10429  EF = MethodDecl->param_end();
10430  IM != EM && IF != EF; ++IM, ++IF) {
10431  const ParmVarDecl *DeclVar = (*IF);
10432  const ParmVarDecl *ImplVar = (*IM);
10433  if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
10434  return false;
10435  if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
10436  return false;
10437  }
10438 
10439  return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
10440 }
10441 
10443  LangAS AS;
10445  AS = LangAS::Default;
10446  else
10447  AS = QT->getPointeeType().getAddressSpace();
10448 
10449  return getTargetInfo().getNullPointerValue(AS);
10450 }
10451 
10453  if (isTargetAddressSpace(AS))
10454  return toTargetAddressSpace(AS);
10455  else
10456  return (*AddrSpaceMap)[(unsigned)AS];
10457 }
10458 
10460  assert(Ty->isFixedPointType());
10461 
10462  if (Ty->isSaturatedFixedPointType()) return Ty;
10463 
10464  const auto &BT = Ty->getAs<BuiltinType>();
10465  switch (BT->getKind()) {
10466  default:
10467  llvm_unreachable("Not a fixed point type!");
10468  case BuiltinType::ShortAccum:
10469  return SatShortAccumTy;
10470  case BuiltinType::Accum:
10471  return SatAccumTy;
10472  case BuiltinType::LongAccum:
10473  return SatLongAccumTy;
10474  case BuiltinType::UShortAccum:
10475  return SatUnsignedShortAccumTy;
10476  case BuiltinType::UAccum:
10477  return SatUnsignedAccumTy;
10478  case BuiltinType::ULongAccum:
10479  return SatUnsignedLongAccumTy;
10480  case BuiltinType::ShortFract:
10481  return SatShortFractTy;
10482  case BuiltinType::Fract:
10483  return SatFractTy;
10484  case BuiltinType::LongFract:
10485  return SatLongFractTy;
10486  case BuiltinType::UShortFract:
10487  return SatUnsignedShortFractTy;
10488  case BuiltinType::UFract:
10489  return SatUnsignedFractTy;
10490  case BuiltinType::ULongFract:
10491  return SatUnsignedLongFractTy;
10492  }
10493 }
10494 
10496  if (LangOpts.OpenCL)
10498 
10499  if (LangOpts.CUDA)
10501 
10502  return getLangASFromTargetAS(AS);
10503 }
10504 
10505 // Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
10506 // doesn't include ASTContext.h
10507 template
10509  const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
10511  const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
10512  const clang::ASTContext &Ctx, Decl *Value);
10513 
10514 unsigned char ASTContext::getFixedPointScale(QualType Ty) const {
10515  assert(Ty->isFixedPointType());
10516 
10517  const auto *BT = Ty->getAs<BuiltinType>();
10518  const TargetInfo &Target = getTargetInfo();
10519  switch (BT->getKind()) {
10520  default:
10521  llvm_unreachable("Not a fixed point type!");
10522  case BuiltinType::ShortAccum:
10523  case BuiltinType::SatShortAccum:
10524  return Target.getShortAccumScale();
10525  case BuiltinType::Accum:
10526  case BuiltinType::SatAccum:
10527  return Target.getAccumScale();
10528  case BuiltinType::LongAccum:
10529  case BuiltinType::SatLongAccum:
10530  return Target.getLongAccumScale();
10531  case BuiltinType::UShortAccum:
10532  case BuiltinType::SatUShortAccum:
10533  return Target.getUnsignedShortAccumScale();
10534  case BuiltinType::UAccum:
10535  case BuiltinType::SatUAccum:
10536  return Target.getUnsignedAccumScale();
10537  case BuiltinType::ULongAccum:
10538  case BuiltinType::SatULongAccum:
10539  return Target.getUnsignedLongAccumScale();
10540  case BuiltinType::ShortFract:
10541  case BuiltinType::SatShortFract:
10542  return Target.getShortFractScale();
10543  case BuiltinType::Fract:
10544  case BuiltinType::SatFract:
10545  return Target.getFractScale();
10546  case BuiltinType::LongFract:
10547  case BuiltinType::SatLongFract:
10548  return Target.getLongFractScale();
10549  case BuiltinType::UShortFract:
10550  case BuiltinType::SatUShortFract:
10551  return Target.getUnsignedShortFractScale();
10552  case BuiltinType::UFract:
10553  case BuiltinType::SatUFract:
10554  return Target.getUnsignedFractScale();
10555  case BuiltinType::ULongFract:
10556  case BuiltinType::SatULongFract:
10557  return Target.getUnsignedLongFractScale();
10558  }
10559 }
10560 
10561 unsigned char ASTContext::getFixedPointIBits(QualType Ty) const {
10562  assert(Ty->isFixedPointType());
10563 
10564  const auto *BT = Ty->getAs<BuiltinType>();
10565  const TargetInfo &Target = getTargetInfo();
10566  switch (BT->getKind()) {
10567  default:
10568  llvm_unreachable("Not a fixed point type!");
10569  case BuiltinType::ShortAccum:
10570  case BuiltinType::SatShortAccum:
10571  return Target.getShortAccumIBits();
10572  case BuiltinType::Accum:
10573  case BuiltinType::SatAccum:
10574  return Target.getAccumIBits();
10575  case BuiltinType::LongAccum:
10576  case BuiltinType::SatLongAccum:
10577  return Target.getLongAccumIBits();
10578  case BuiltinType::UShortAccum:
10579  case BuiltinType::SatUShortAccum:
10580  return Target.getUnsignedShortAccumIBits();
10581  case BuiltinType::UAccum:
10582  case BuiltinType::SatUAccum:
10583  return Target.getUnsignedAccumIBits();
10584  case BuiltinType::ULongAccum:
10585  case BuiltinType::SatULongAccum:
10586  return Target.getUnsignedLongAccumIBits();
10587  case BuiltinType::ShortFract:
10588  case BuiltinType::SatShortFract:
10589  case BuiltinType::Fract:
10590  case BuiltinType::SatFract:
10591  case BuiltinType::LongFract:
10592  case BuiltinType::SatLongFract:
10593  case BuiltinType::UShortFract:
10594  case BuiltinType::SatUShortFract:
10595  case BuiltinType::UFract:
10596  case BuiltinType::SatUFract:
10597  case BuiltinType::ULongFract:
10598  case BuiltinType::SatULongFract:
10599  return 0;
10600  }
10601 }
10602 
10604  assert((Ty->isFixedPointType() || Ty->isIntegerType()) &&
10605  "Can only get the fixed point semantics for a "
10606  "fixed point or integer type.");
10607  if (Ty->isIntegerType())
10609  Ty->isSignedIntegerType());
10610 
10611  bool isSigned = Ty->isSignedFixedPointType();
10612  return FixedPointSemantics(
10613  static_cast<unsigned>(getTypeSize(Ty)), getFixedPointScale(Ty), isSigned,
10616 }
10617 
10619  assert(Ty->isFixedPointType());
10621 }
10622 
10624  assert(Ty->isFixedPointType());
10626 }
10627 
10629  assert(Ty->isUnsignedFixedPointType() &&
10630  "Expected unsigned fixed point type");
10631  const auto *BTy = Ty->getAs<BuiltinType>();
10632 
10633  switch (BTy->getKind()) {
10634  case BuiltinType::UShortAccum:
10635  return ShortAccumTy;
10636  case BuiltinType::UAccum:
10637  return AccumTy;
10638  case BuiltinType::ULongAccum:
10639  return LongAccumTy;
10640  case BuiltinType::SatUShortAccum:
10641  return SatShortAccumTy;
10642  case BuiltinType::SatUAccum:
10643  return SatAccumTy;
10644  case BuiltinType::SatULongAccum:
10645  return SatLongAccumTy;
10646  case BuiltinType::UShortFract:
10647  return ShortFractTy;
10648  case BuiltinType::UFract:
10649  return FractTy;
10650  case BuiltinType::ULongFract:
10651  return LongFractTy;
10652  case BuiltinType::SatUShortFract:
10653  return SatShortFractTy;
10654  case BuiltinType::SatUFract:
10655  return SatFractTy;
10656  case BuiltinType::SatULongFract:
10657  return SatLongFractTy;
10658  default:
10659  llvm_unreachable("Unexpected unsigned fixed point type");
10660  }
10661 }
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:4270
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.
Definition: ASTContext.cpp:915
static NamespaceDecl * Create(ASTContext &C, DeclContext *DC, bool Inline, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, NamespaceDecl *PrevDecl)
Definition: DeclCXX.cpp:2688
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:1032
TemplateTemplateParmDecl * getParameterPack() const
Retrieve the template template parameter pack being substituted.
Definition: TemplateName.h:144
const ObjCInterfaceType * getInterfaceType() const
If this pointer points to an Objective C @interface type, gets the type for that interface.
Definition: Type.cpp:1553
static void EncodeBitField(const ASTContext *Ctx, std::string &S, QualType T, const FieldDecl *FD)
CanQualType SatUnsignedLongFractTy
Definition: ASTContext.h:1036
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:5555
bool hasDefinition() const
Determine whether this class has been defined.
Definition: DeclObjC.h:1534
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:5199
ASTMutationListener * Listener
Definition: ASTContext.h:574
IntType getInt64Type() const
Definition: TargetInfo.h:301
QualType withConst() const
Retrieves a version of this type with const applied.
const Type * Ty
The locally-unqualified type.
Definition: Type.h:584
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:91
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:5002
CanQualType LongLongTy
Definition: ASTContext.h:1023
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:1748
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 ...
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:6690
CanQualType WIntTy
Definition: ASTContext.h:1019
bool isKindOfTypeAsWritten() const
Whether this is a "__kindof" type as written.
Definition: Type.h:5725
CXXABI * CreateMicrosoftCXXABI(ASTContext &Ctx)
const Decl * CommentDecl
Declaration the comment is actually attached to (in the source).
Definition: Comment.h:983
bool isObjCQualifiedIdType() const
True if this is equivalent to &#39;id.
Definition: Type.h:5943
SplitQualType split() const
CanQualType AccumTy
Definition: ASTContext.h:1027
no exception specification
unsigned char getFixedPointIBits(QualType Ty) const
CanQualType OCLQueueTy
Definition: ASTContext.h:1052
QualType getObjCIdType() const
Represents the Objective-CC id type.
Definition: ASTContext.h:1854
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:67
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:2569
ArrayRef< QualType > getTypeArgsAsWritten() const
Retrieve the type arguments of this object type as they were written.
Definition: Type.h:5719
CanQualType LongDoubleComplexTy
Definition: ASTContext.h:1040
void * getAsVoidPointer() const
Retrieve the template name as a void pointer.
Definition: TemplateName.h:328
QualType mergeFunctionTypes(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false)
QualType getPointeeType() const
Definition: Type.h:2582
CanQualType VoidPtrTy
Definition: ASTContext.h:1042
Represents the dependent type named by a dependently-scoped typename using declaration, e.g.
Definition: Type.h:4154
A (possibly-)qualified type.
Definition: Type.h:643
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:6392
Static storage duration.
Definition: Specifiers.h:309
QualType areCommonBaseCompatible(const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT)
OverloadedOperatorKind getOperator() const
Return the overloaded operator to which this template name refers.
Definition: TemplateName.h:514
bool isArrayType() const
Definition: Type.h:6440
bool getNoCfCheck() const
Definition: Type.h:3547
bool isNull() const
Definition: CanonicalType.h:97
bool isMemberPointerType() const
Definition: Type.h:6422
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:340
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:775
CanQualType UnsignedLongFractTy
Definition: ASTContext.h:1031
QualType getBuiltinVaListType() const
Retrieve the type of the __builtin_va_list type.
Definition: ASTContext.h:1909
unsigned getLongWidth() const
getLongWidth/Align - Return the size of &#39;signed long&#39; and &#39;unsigned long&#39; for this target...
Definition: TargetInfo.h:398
ObjCIvarDecl * getPropertyIvarDecl() const
Definition: DeclObjC.h:2826
CanQualType FractTy
Definition: ASTContext.h:1030
static MicrosoftMangleContext * create(ASTContext &Context, DiagnosticsEngine &Diags)
void Profile(llvm::FoldingSetNodeID &ID) const
Definition: Type.h:1368
CanQualType Char32Ty
Definition: ASTContext.h:1022
QualType getPointerDiffType() const
Return the unique type for "ptrdiff_t" (C99 7.17) defined in <stddef.h>.
BlockVarCopyInit getBlockVarCopyInit(const VarDecl *VD) const
Get the copy initialization expression of the VarDecl VD, or nullptr if none exists.
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:1396
Stmt - This represents one statement.
Definition: Stmt.h:66
void setLAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:1603
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:2450
Internal representation of canonical, dependent __underlying_type(type) types.
Definition: Type.h:4398
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:3387
bool CommentsLoaded
True if comments are already loaded from ExternalASTSource.
Definition: ASTContext.h:730
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee...
Definition: Type.cpp:505
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:5459
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:985
bool hasExtParameterInfos() const
Is there any interesting extra information for any of the parameters of this function type...
Definition: Type.h:4092
__builtin_va_list as defined by the PNaCl ABI: http://www.chromium.org/nativeclient/pnacl/bitcode-abi...
Definition: TargetInfo.h:236
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:1968
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:3051
C Language Family Type Representation.
Defines the SourceManager interface.
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3249
CharUnits getAlignOfGlobalVarInChars(QualType T) const
Return the alignment in characters that should be given to a global variable with type T...
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:5282
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:3335
bool isRecordType() const
Definition: Type.h:6464
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:1040
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:727
static int CmpProtocolNames(ObjCProtocolDecl *const *LHS, ObjCProtocolDecl *const *RHS)
CmpProtocolNames - Comparison predicate for sorting protocols alphabetically.
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:1938
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:2931
CoreFoundationABI CFRuntime
Definition: LangOptions.h:209
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:4035
EnumDecl * getPreviousDecl()
Definition: Decl.h:3445
CanQualType ObjCBuiltinSelTy
Definition: ASTContext.h:1046
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:1457
Represents a C++11 auto or C++14 decltype(auto) type.
Definition: Type.h:4817
Kind getKind() const
Definition: TargetCXXABI.h:131
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition: Decl.cpp:3950
A class providing a concrete implementation of ObjCObjectType, so as to not increase the footprint of...
Definition: Type.h:5761
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx)
Definition: Type.cpp:3119
unsigned getDefaultAlignForAttributeAligned() const
Return the default alignment for attribute((aligned)) on this target, to be used if no alignment valu...
Definition: TargetInfo.h:539
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:1045
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined...
Definition: Decl.h:2796
QualType getBlockPointerType(QualType T) const
Return the uniqued reference to the type for a block of the specified type.
The base class of the type hierarchy.
Definition: Type.h:1433
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:1033
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:1771
static bool areSortedAndUniqued(ArrayRef< ObjCProtocolDecl *> Protocols)
CanQual< T > getUnqualifiedType() const
Retrieve the unqualified form of this type.
CanQualType LongTy
Definition: ASTContext.h:1023
DiagnosticsEngine & getDiagnostics() const
QualType getCorrespondingSignedFixedPointType(QualType Ty) const
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:2844
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:2527
Represent a C++ namespace.
Definition: Decl.h:514
unsigned NumImplicitCopyConstructors
The number of implicitly-declared copy constructors.
Definition: ASTContext.h:2838
const ObjCObjectPointerType * getAsObjCInterfacePointerType() const
Definition: Type.cpp:1613
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:2691
virtual void completeDefinition()
Note that the definition of this type is now complete.
Definition: Decl.cpp:4310
bool isZero() const
isZero - Test whether the quantity equals zero.
Definition: CharUnits.h:115
QualType withConst() const
Definition: Type.h:815
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:693
QualType adjustStringLiteralBaseType(QualType StrLTy) const
A container of type source information.
Definition: Decl.h:86
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:444
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:2870
__builtin_va_list as defined by the x86-64 ABI: http://refspecs.linuxbase.org/elf/x86_64-abi-0.21.pdf
Definition: TargetInfo.h:245
const Expr * getRequiresClause() const
Get the constraint-expression from the associated requires-clause (if any)
Definition: DeclTemplate.h:444
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:351
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2574
Represents a prvalue temporary that is written into memory so that a reference can bind to it...
Definition: ExprCXX.h:4325
CanQualType WideCharTy
Definition: ASTContext.h:1018
unsigned NumImplicitCopyAssignmentOperatorsDeclared
The number of implicitly-declared copy assignment operators for which declarations were built...
Definition: ASTContext.h:2856
const DeclContext * getParentFunctionOrMethod() const
If this decl is defined inside a function/method/block it returns the corresponding DeclContext...
Definition: DeclBase.cpp:253
A template template parameter that has been substituted for some other template name.
Definition: TemplateName.h:219
CanQualType HalfTy
Definition: ASTContext.h:1038
QualType getElementType() const
Definition: Type.h:2879
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition: Type.cpp:540
void AddDeallocation(void(*Callback)(void *), void *Data) const
Add a deallocation callback that will be invoked when the ASTContext is destroyed.
Definition: ASTContext.cpp:910
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:2110
const IdentifierInfo * getIdentifier() const
Returns the identifier to which this template name refers.
Definition: TemplateName.h:504
void Profile(llvm::FoldingSetNodeID &ID, ASTContext &Context)
ArrayRef< RawComment * > getComments() const
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:1915
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...
const RawComment * getRaw() const LLVM_READONLY
Definition: ASTContext.h:765
Represents a variable declaration or definition.
Definition: Decl.h:812
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:333
QualType getReturnType() const
Definition: Decl.h:2329
LangAS getLangASFromTargetAS(unsigned TargetAS)
Definition: AddressSpaces.h:66
void initialize(ASTContext &Context, SourceLocation Loc) const
Initializes this to state that every location in this type is the given location. ...
Definition: TypeLoc.h:192
RecordDecl * getPreviousDecl()
Definition: Decl.h:3665
unsigned getNumParams() const
Definition: Type.h:3921
bool isEnumeralType() const
Definition: Type.h:6468
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:3562
NamedDecl *const * const_iterator
Iterates through the template parameters in this list.
Definition: DeclTemplate.h:116
const T * getAs() const
Member-template getAs<specific type>&#39;.
Definition: Type.h:6851
CanQualType Float128Ty
Definition: ASTContext.h:1026
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:3799
CanQualType ShortAccumTy
Definition: ASTContext.h:1027
Declaration context for names declared as extern "C" in C++.
Definition: Decl.h:221
LangAS
Defines the address space values used by the address space qualifier of QualType. ...
Definition: AddressSpaces.h:25
Represents a C++17 deduced template specialization type.
Definition: Type.h:4855
__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:232
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:431
ObjCImplementationDecl * getObjCImplementation(ObjCInterfaceDecl *D)
Get the implementation of the ObjCInterfaceDecl D, or nullptr if none exists.
bool field_empty() const
Definition: Decl.h:3849
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:1702
void setRaw(const RawComment *RC)
Definition: ASTContext.h:769
bool isInvalidDecl() const
Definition: DeclBase.h:553
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:67
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:37
CanQualType ShortFractTy
Definition: ASTContext.h:1030
SpecifierKind getKind() const
Determine what kind of nested name specifier is stored.
protocol_range protocols() const
Definition: DeclObjC.h:2128
Decl * getVaListTagDecl() const
Retrieve the C type declaration corresponding to the predefined __va_list_tag type used to help defin...
Represents a parameter to a function.
Definition: Decl.h:1564
Represents the result of substituting a type for a template type parameter.
Definition: Type.h:4671
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:2603
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
long i
Definition: xmmintrin.h:1456
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:137
FieldDecl * getSourceBitField()
If this expression refers to a bit-field, retrieve the declaration of that bit-field.
Definition: Expr.cpp:3815
PipeType - OpenCL20.
Definition: Type.h:6072
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:3097
Qualifiers getQualifiers() const
Retrieve all qualifiers.
SubstTemplateTemplateParmStorage * getAsSubstTemplateTemplateParm() const
Retrieve the substituted template template parameter, if known.
CanQualType OCLSamplerTy
Definition: ASTContext.h:1051
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:269
Base wrapper for a particular "section" of type source info.
Definition: TypeLoc.h:56
Represents a struct/union/class.
Definition: Decl.h:3626
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:1332
uint64_t getPointerWidth(unsigned AddrSpace) const
Return the width of pointers on this target, for the specified address space.
Definition: TargetInfo.h:358
RecordDecl * getCFConstantStringTagDecl() const
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:297
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:3800
bool isComplete() const
Returns true if this can be considered a complete type.
Definition: Decl.h:3567
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:1054
bool isObjCQualifiedClass() const
Definition: Type.h:5691
This table allows us to fully hide how we implement multi-keyword caching.
unsigned getRegParm() const
Definition: Type.h:3550
Represents a class type in Objective C.
Definition: Type.h:5608
static RecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, RecordDecl *PrevDecl=nullptr)
Definition: Decl.cpp:4263
QualType getPointeeType() const
Definition: Type.h:2686
void setManglingNumber(const NamedDecl *ND, unsigned Number)
CXXRecordDecl * getPreviousDecl()
Definition: DeclCXX.h:738
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:154
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:442
QualType getObjCSuperType() const
Returns the C struct type for objc_super.
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:3928
ArrayRef< ExtParameterInfo > getExtParameterInfos() const
Definition: Type.h:4096
const ParmVarDecl *const * param_const_iterator
Definition: DeclObjC.h:342
NamespaceDecl * getNamespace()
Retrieve the namespace declaration aliased by this directive.
Definition: DeclCXX.h:3229
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:1619
void setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, FieldDecl *Tmpl)
Missing a type from <ucontext.h>
Definition: ASTContext.h:2022
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:1031
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition: Decl.h:3831
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:1818
field_range fields() const
Definition: Decl.h:3841
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:893
bool isObjCIdType() const
Definition: Type.h:6517
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:2607
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:2831
bool isCanonicalUnqualified() const
Determines if this type would be canonical if it had no further qualification.
Definition: Type.h:1865
DynTypedNodeList getParents(const NodeT &Node)
Returns the parents of the given node (within the traversal scope).
Definition: ASTContext.h:651
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:90
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:2828
const ObjCObjectPointerType * getAsObjCQualifiedIdType() const
Definition: Type.cpp:1585
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:4030
CanQualType LongAccumTy
Definition: ASTContext.h:1027
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:2198
CanQualType OCLEventTy
Definition: ASTContext.h:1051
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:31
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:4727
Container for either a single DynTypedNode or for an ArrayRef to DynTypedNode.
Definition: ASTContext.h:578
void setStaticLocalNumber(const VarDecl *VD, unsigned Number)
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:6610
static CharUnits Zero()
Zero - Construct a CharUnits quantity of zero.
Definition: CharUnits.h:52
qual_iterator qual_begin() const
Definition: Type.h:5509
RawComment * getRawCommentForDeclNoCache(const Decl *D) const
Return the documentation comment attached to a given declaration, without looking into cache...
Definition: ASTContext.cpp:101
CharUnits getVBaseClassOffset(const CXXRecordDecl *VBase) const
getVBaseClassOffset - Get the offset, in chars, for the given base class.
Definition: RecordLayout.h:240
c
Definition: emmintrin.h:306
__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:1052
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:49
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:6092
static TypedefDecl * CreateCharPtrNamedVaListDecl(const ASTContext *Context, StringRef Name)
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:6747
QualType getParamTypeForDecl() const
Definition: TemplateBase.h:268
Describes a module or submodule.
Definition: Module.h:64
IdentifierTable & Idents
Definition: ASTContext.h:569
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:6161
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:717
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:2289
CanQualType LongFractTy
Definition: ASTContext.h:1030
bool getProducesResult() const
Definition: Type.h:3545
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:302
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3142
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:2770
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:2685
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:5510
A qualified template name, where the qualification is kept to describe the source code as written...
Definition: TemplateName.h:211
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:1455
const LangASMap & getAddressSpaceMap() const
Definition: TargetInfo.h:1219
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:968
static ItaniumMangleContext * create(ASTContext &Context, DiagnosticsEngine &Diags)
QualType getOriginalType() const
Definition: Decl.cpp:2625
void addObjCGCAttr(GC type)
Definition: Type.h:306
static ExternCContextDecl * Create(const ASTContext &C, TranslationUnitDecl *TU)
Definition: Decl.cpp:4518
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:37
Microsoft throw(...) extension.
A convenient class for passing around template argument information.
Definition: TemplateBase.h:554
CanQualType SatShortFractTy
Definition: ASTContext.h:1035
ArrayRef< QualType > getTypeArgs() const
Retrieve the type arguments of this object type (semantically).
Definition: Type.cpp:664
QualType getVolatileType(QualType T) const
Return the uniqued reference to the type for a volatile qualified type.
Definition: ASTContext.h:1175
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:5829
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition: Type.cpp:2236
The Microsoft ABI is the ABI used by Microsoft Visual Studio (and compatible compilers).
Definition: TargetCXXABI.h:112
TypedefDecl * getObjCSelDecl() const
Retrieve the typedef corresponding to the predefined &#39;SEL&#39; type in Objective-C.
bool hasAddressSpace() const
Definition: Type.h:352
CanQualType SatUnsignedShortAccumTy
Definition: ASTContext.h:1033
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:207
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:6902
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:839
unsigned toTargetAddressSpace(LangAS AS)
Definition: AddressSpaces.h:61
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:4210
Represents a typeof (or typeof) expression (a GCC extension).
Definition: Type.h:4244
const clang::PrintingPolicy & getPrintingPolicy() const
Definition: ASTContext.h:657
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:306
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition: Type.h:1859
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:2505
static TemplateTypeParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation KeyLoc, SourceLocation NameLoc, unsigned D, unsigned P, IdentifierInfo *Id, bool Typename, bool ParameterPack)
Represents a declaration of a type.
Definition: Decl.h:2907
CanQualType PseudoObjectTy
Definition: ASTContext.h:1045
LangAS getAddressSpace() const
Definition: Type.h:353
QualType getExceptionObjectType(QualType T) const
GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const
const Type * getClass() const
Definition: Type.h:2822
CXXMethodVector::const_iterator overridden_cxx_method_iterator
Definition: ASTContext.h:925
bool isReadOnly() const
isReadOnly - Return true iff the property has a setter.
Definition: DeclObjC.h:862
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:5254
void getObjCEncodingForPropertyType(QualType T, std::string &S) const
Emit the Objective-C property type encoding for the given type T into S.
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition: Decl.h:1386
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
CanQualType LongDoubleTy
Definition: ASTContext.h:1026
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition: Expr.cpp:2947
static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI, const LangOptions &LangOpts)
Definition: ASTContext.cpp:762
Expr * getSizeExpr() const
Definition: Type.h:3023
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:6142
unsigned Align
Definition: ASTContext.h:144
unsigned getBitWidthValue(const ASTContext &Ctx) const
Definition: Decl.cpp:3907
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:145
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:3334
Defines the Linkage enumeration and various utility functions.
Represents an Objective-C protocol declaration.
Definition: DeclObjC.h:2063
TemplateTemplateParmDecl * getParameter() const
Definition: TemplateName.h:358
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:688
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:3416
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:2118
Represents an ObjC class declaration.
Definition: DeclObjC.h:1171
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:419
QualType getReturnType() const
Definition: DeclObjC.h:322
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition: Decl.cpp:3077
ObjCInterfaceDecl * getInterface() const
Gets the interface declaration for this object type, if the base type really is an interface...
Definition: Type.h:5843
bool getNoReturn() const
Definition: Type.h:3544
bool isKindOfType() const
Whether this is a "__kindof" type.
Definition: Type.h:5954
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:947
The iOS ABI is a partial implementation of the ARM ABI.
Definition: TargetCXXABI.h:62
IntrusiveRefCntPtr< ExternalASTSource > ExternalSource
Definition: ASTContext.h:573
CanQualType UnsignedCharTy
Definition: ASTContext.h:1024
Expr * getSizeExpr() const
Definition: Type.h:3080
bool getNoCallerSavedRegs() const
Definition: Type.h:3546
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:5516
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:6728
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:935
static char getObjCEncodingForPrimitiveKind(const ASTContext *C, BuiltinType::Kind kind)
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:3160
This object can be modified without requiring retains or releases.
Definition: Type.h:158
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1602
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:520
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:3682
CanQualType Float128ComplexTy
Definition: ASTContext.h:1041
ObjCPropertyImplDecl - Represents implementation declaration of a property in a class or category imp...
Definition: DeclObjC.h:2758
Expr * getAddrSpaceExpr() const
Definition: Type.h:3131
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:5315
QualType getBlockDescriptorExtendedType() const
Gets the struct used to keep track of the extended descriptor for pointer to blocks.
bool hasAttr() const
Definition: DeclBase.h:542
QualType getBaseType() const
Gets the base type of this object type.
Definition: Type.h:5671
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:2557
bool isPromotableIntegerType() const
More type predicates useful for type checking/promotion.
Definition: Type.cpp:2498
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1636
Represents a prototype with parameter type info, e.g.
Definition: Type.h:3719
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:791
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:481
Represents a ValueDecl that came out of a declarator.
Definition: Decl.h:688
unsigned NumImplicitMoveAssignmentOperators
The number of implicitly-declared move assignment operators.
Definition: ASTContext.h:2859
qual_range quals() const
Definition: Type.h:5508
A dependent template name that has not been resolved to a template (or set of templates).
Definition: TemplateName.h:215
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:572
comments::FullComment * cloneFullComment(comments::FullComment *FC, const Decl *D) const
Definition: ASTContext.cpp:461
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:2850
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition: Type.h:6217
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:178
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:6702
CanQualType UnsignedAccumTy
Definition: ASTContext.h:1029
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3697
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:1713
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:228
bool hasPointerIdentity() const
Check if the given ASTNodeKind identifies a type that offers pointer identity.
CanQualType UnsignedShortFractTy
Definition: ASTContext.h:1031
Exposes information about the current target.
Definition: TargetInfo.h:161
Represents an array type in C++ whose size is a value-dependent expression.
Definition: Type.h:3058
unsigned NumImplicitCopyConstructorsDeclared
The number of implicitly-declared copy constructors for which declarations were built.
Definition: ASTContext.h:2842
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:236
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:436
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:1075
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:2326
bool isNoReturn(unsigned ID) const
Return true if we know this builtin never returns.
Definition: Builtins.h:116
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition: DeclBase.h:1795
bool isCanonicalDecl() const
Whether this particular Decl is a canonical one.
Definition: DeclBase.h:883
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:3453
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:3915
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:2252
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:1760
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
Definition: Type.h:5138
bool isPositive() const
isPositive - Test whether the quantity is greater than zero.
Definition: CharUnits.h:121
Selector getSetterName() const
Definition: DeclObjC.h:913
QualType getucontext_tType() const
Retrieve the C ucontext_t type.
Definition: ASTContext.h:1783
void addTypedefNameForUnnamedTagDecl(TagDecl *TD, TypedefNameDecl *TND)
static const LangASMap * getAddressSpaceMap(const TargetInfo &T, const LangOptions &LOpts)
Definition: ASTContext.cpp:740
static bool compare(const PathDiagnostic &X, const PathDiagnostic &Y)
unsigned getAsOpaqueValue() const
Definition: Type.h:250
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:4549
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.
Internal representation of canonical, dependent decltype(expr) types.
Definition: Type.h:4342
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:3548
bool isObjCBuiltinType() const
Definition: Type.h:6535
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:6916
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:5120
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:3984
Inits[]
Definition: OpenMPClause.h:150
QualType getTypeOfExprType(Expr *e) const
GCC extension.
#define V(N, I)
Definition: ASTContext.h:2907
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:4574
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition: Expr.h:5541
Qualifiers::GC getObjCGCAttr() const
Returns gc attribute of this type.
Definition: Type.h:6263
QualType getParenType(QualType NamedType) const
CanQualType OMPArraySectionTy
Definition: ASTContext.h:1053
static TypedefDecl * CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context)
const Decl * getDecl() const LLVM_READONLY
Definition: Comment.h:1119
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:6668
unsigned getFastQualifiers() const
Definition: Type.h:387
bool canBeRedeclared(unsigned ID) const
Returns true if this is a builtin that can be redeclared.
Definition: Builtins.cpp:189
ObjCLifetime getObjCLifetime() const
Definition: Type.h:327
void removeFastQualifiers(unsigned mask)
Definition: Type.h:392
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:6523
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:2639
DeclContext * getDeclContext()
Definition: DeclBase.h:438
A structure for storing the information associated with a substituted template template parameter...
Definition: TemplateName.h:345
bool isObjCIdType() const
True if this is equivalent to the &#39;id&#39; type, i.e.
Definition: Type.h:5926
ObjCInterfaceDecl * getSuperClass() const
Definition: DeclObjC.cpp:337
SourceLocation Begin
UsingShadowDecl * getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst)
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:4348
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition: CharUnits.h:62
CanQualType ShortTy
Definition: ASTContext.h:1023
An abstract interface that should be implemented by listeners that want to be notified when an AST en...
internal::Matcher< T > id(StringRef ID, const internal::BindableMatcher< T > &InnerMatcher)
If the provided matcher matches a node, binds the node to ID.
Definition: ASTMatchers.h:138
ASTEdit remove(RangeSelector S)
Removes the source selected by S.
Definition: Transformer.h:232
ArrayRef< TemplateArgument > asArray() const
Produce this as an array ref.
Definition: DeclTemplate.h:268
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:200
Represents a C++ template name within the type system.
Definition: TemplateName.h:187
Represents the type decltype(expr) (C++11).
Definition: Type.h:4314
static TypedefDecl * CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context)
LangAS getLangASForBuiltinAddressSpace(unsigned AS) const
QualType getFILEType() const
Retrieve the C FILE type.
Definition: ASTContext.h:1747
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:501
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:1006
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:1025
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition: Expr.h:733
A std::pair-like structure for storing a qualified type split into its local qualifiers and its local...
Definition: Type.h:582
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:1875
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3304
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
QualType getType() const
Definition: Expr.h:137
A unary type transform, which is a type constructed from another.
Definition: Type.h:4357
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:207
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, ArrayType::ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type...
DeclarationName getCXXOperatorName(OverloadedOperatorKind Op)
Get the name of the overloadable C++ operator corresponding to Op.
Qualifiers Quals
The local qualifiers.
Definition: Type.h:587
unsigned getMaxAlignment() const
getMaxAlignment - return the maximum alignment specified by attributes on this decl, 0 if there are none.
Definition: DeclBase.cpp:384
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:1779
StorageDuration getStorageDuration() const
Retrieve the storage duration for the materialized temporary.
Definition: ExprCXX.h:4369
void setAddressSpace(LangAS space)
Definition: Type.h:373
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:421
unsigned NumImplicitMoveConstructors
The number of implicitly-declared move constructors.
Definition: ASTContext.h:2845
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:1382
Represents a GCC generic vector type.
Definition: Type.h:3200
struct CXXOpName CXXOperatorName
static bool CanThrow(Expr *E, ASTContext &Ctx)
Definition: CFG.cpp:2475
An lvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:2752
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:1082
CanQualType SatLongAccumTy
Definition: ASTContext.h:1032
Common base class for placeholders for types that get replaced by placeholder type deduction: C++11 a...
Definition: Type.h:4777
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:6791
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...
Stencil cat(Ts &&... Parts)
Convenience wrapper for Stencil::cat that can be imported with a using decl.
Definition: Stencil.h:140
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.
Definition: ASTContext.cpp:989
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:320
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:1398
The result type of a method or function.
This template specialization was implicitly instantiated from a template.
Definition: Specifiers.h:180
bool ObjCQualifiedClassTypesAreCompatible(QualType LHS, QualType RHS)
ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and Class<pr1, ...>. ...
bool isNull() const
Return true if this QualType doesn&#39;t point to a type yet.
Definition: Type.h:708
QualType getDependentSizedExtVectorType(QualType VectorType, Expr *SizeExpr, SourceLocation AttrLoc) const
void removeCVRQualifiers(unsigned mask)
Definition: Type.h:277
bool useAddressSpaceMapMangling() const
Specify if mangling based on address space map should be used or not for language specific address sp...
Definition: TargetInfo.h:757
QualType getType() const
Definition: DeclObjC.h:828
const SourceManager & SM
Definition: Format.cpp:1572
void setOriginalDecl(const Decl *Orig)
Definition: ASTContext.h:777
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:294
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:264
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:4404
CanQualType SignedCharTy
Definition: ASTContext.h:1023
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:123
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:6714
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:3569
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 isVoidPointerType() const
Definition: Type.cpp:469
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:6201
EnumDecl * getInstantiatedFromMemberEnum() const
Returns the enumeration (declared within the template) from which this enumeration type was instantia...
Definition: Decl.cpp:4214
SplitQualType split() const
Divides a QualType into its unqualified type and a set of local qualifiers.
Definition: Type.h:6150
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
QualType getWideCharType() const
Return the type of wide characters.
Definition: ASTContext.h:1570
A template template parameter pack that has been substituted for a template template argument pack...
Definition: TemplateName.h:224
bool isComputedNoexcept(ExceptionSpecificationType ESpecType)
CanQualType OverloadTy
Definition: ASTContext.h:1043
There is no lifetime qualification on this type.
Definition: Type.h:154
Compare comments&#39; source locations.
OverloadedTemplateStorage * getAsOverloadedTemplate() const
Retrieve the underlying, overloaded function template declarations that this template name refers to...
void PrintStats() const
Definition: ASTContext.cpp:919
std::string getAsString() const
Derive the full selector name (e.g.
is AltiVec &#39;vector Pixel&#39;
Definition: Type.h:3210
CanQualType BuiltinFnTy
Definition: ASTContext.h:1044
This declaration does not have an attached comment, and we have searched the redeclaration chain...
Definition: ASTContext.h:754
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:570
Assigning into this object requires the old value to be released and the new value to be retained...
Definition: Type.h:165
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:6181
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition: Type.h:6460
not a target-specific vector type
Definition: Type.h:3204
llvm::PointerUnion< VarTemplateDecl *, MemberSpecializationInfo * > TemplateOrSpecializationInfo
A type synonym for the TemplateOrInstantiation mapping.
Definition: ASTContext.h:425
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition: Type.h:3775
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:4111
bool isSpecialized() const
Determine whether this object type is "specialized", meaning that it has type arguments.
Definition: Type.cpp:646
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:3932
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition: DeclBase.cpp:217
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:3806
unsigned getMaxAtomicInlineWidth() const
Return the maximum width lock-free atomic operation which can be inlined given the supported features...
Definition: TargetInfo.h:621
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:3658
Encodes a location in the source.
ObjCInterfaceDecl * getDecl() const
Get the declaration of this interface.
Definition: Type.h:5821
TypedefDecl * getUInt128Decl() const
Retrieve the declaration for the 128-bit unsigned integer type.
Sugar for parentheses used when specifying types.
Definition: Type.h:2539
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:3645
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:4464
bool hasSameTemplateName(TemplateName X, TemplateName Y)
Determine whether the given template names refer to the same template.
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:6258
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:1029
unsigned getOpenMPDefaultSimdAlign(QualType T) const
Get default simd alignment of the specified complete type in bits.
CanQualType Int128Ty
Definition: ASTContext.h:1023
Represents typeof(type), a GCC extension.
Definition: Type.h:4287
Interfaces are the core concept in Objective-C for object oriented design.
Definition: Type.h:5808
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:2124
This names the __make_integer_seq BuiltinTemplateDecl.
Definition: Builtins.h:250
unsigned getManglingNumber(const NamedDecl *ND) const
A structure for storing an already-substituted template template parameter pack.
Definition: TemplateName.h:130
A simple holder for various uncommon bits which do not fit in FunctionTypeBitfields.
Definition: Type.h:3621
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:291
Kind getKind() const LLVM_READONLY
Definition: ASTContext.h:757
CanQualType SatFractTy
Definition: ASTContext.h:1035
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3097
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:1223
CallingConv getCC() const
Definition: Type.h:3557
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:2936
QualType getElementType() const
Definition: Type.h:3235
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:1864
Represents a vector type where either the type or size is dependent.
Definition: Type.h:3277
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:422
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:2114
TypedefNameDecl * getTypedefNameForUnnamedTagDecl(const TagDecl *TD)
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2441
bool hasExceptionSpec() const
Return whether this function has any kind of exception spec.
Definition: Type.h:3961
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
Weak for now, might become strong later in this TU.
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:4699
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
CanQualType FloatTy
Definition: ASTContext.h:1026
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:1033
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:2279
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:248
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:5797
CanQualType VoidTy
Definition: ASTContext.h:1014
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition: Decl.h:3553
bool isValueDependent() const
isValueDependent - Determines whether this expression is value-dependent (C++ [temp.dep.constexpr]).
Definition: Expr.h:158
CanQualType Float16Ty
Definition: ASTContext.h:1039
CanQualType getSignedSizeType() const
Return the unique signed counterpart of the integer type corresponding to size_t. ...
QualType getObjCTypeParamType(const ObjCTypeParamDecl *Decl, ArrayRef< ObjCProtocolDecl *> protocols, QualType Canonical=QualType()) const
bool isObjCObjectPointerType() const
Definition: Type.h:6488
bool isAnyPointerType() const
Definition: Type.h:6388
CanQualType SatLongFractTy
Definition: ASTContext.h:1035
This declaration is only a declaration.
Definition: Decl.h:1146
is AltiVec &#39;vector bool ...&#39;
Definition: Type.h:3213
SplitQualType getSplitUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:6229
Represents one property declaration in an Objective-C interface.
Definition: DeclObjC.h:728
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:241
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:1157
We have found a comment attached to this particular declaration.
Definition: ASTContext.h:744
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.
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:1809
Qualifiers getIndexTypeQualifiers() const
Definition: Type.h:2885
TypeClass getTypeClass() const
Definition: Type.h:1839
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition: Specifiers.h:192
This template specialization was formed from a template-id but has not yet been declared, defined, or instantiated.
Definition: Specifiers.h:177
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:5736
ObjCDeclQualifier getObjCDeclQualifier() const
Definition: DeclObjC.h:246
bool isTargetAddressSpace(LangAS AS)
Definition: AddressSpaces.h:57
EnumDecl * getDecl() const
Definition: Type.h:4471
bool isVectorType() const
Definition: Type.h:6476
ObjCPropertyImplDecl * getObjCPropertyImplDeclForPropertyDecl(const ObjCPropertyDecl *PD, const Decl *Container) const
Assigning into this object requires a lifetime extension.
Definition: Type.h:171
QualType AutoDeductTy
Definition: ASTContext.h:1059
CanQualType SatUnsignedFractTy
Definition: ASTContext.h:1036
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:1548
llvm::DenseMap< const Decl *, RawCommentAndCacheFlags > RedeclComments
Mapping from declarations to comments attached to any redeclaration.
Definition: ASTContext.h:791
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:481
bool isCanonical() const
Definition: Type.h:6186
CanQualType SatUnsignedShortFractTy
Definition: ASTContext.h:1036
bool hasFlexibleArrayMember() const
Definition: Decl.h:3680
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2320
DependentTemplateName * getAsDependentTemplateName() const
Retrieve the underlying dependent template name structure, if any.
__builtin_va_list as defined by ARM AAPCS ABI http://infocenter.arm.com
Definition: TargetInfo.h:250
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:6025
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:4213
Represents a pointer type decayed from an array or function type.
Definition: Type.h:2654
void setTraversalScope(const std::vector< Decl *> &)
Definition: ASTContext.cpp:905
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:1032
The injected class name of a C++ class template or class template partial specialization.
Definition: Type.h:5048
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:5425
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:104
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:1595
void * Allocate(size_t Size, unsigned Align=8) const
Definition: ASTContext.h:672
ObjCDeclQualifier getObjCDeclQualifier() const
Definition: Decl.h:1621
ArrayRef< Decl * > getModuleInitializers(Module *M)
Get the initializations to perform when importing a module, if any.
CanQualType UnsignedShortTy
Definition: ASTContext.h:1024
ObjCIvarDecl * getNextIvar()
Definition: DeclObjC.h:1977
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:2949
ast_type_traits::DynTypedNode Node
CanQualType CharTy
Definition: ASTContext.h:1016
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:2617
QualType withRestrict() const
Definition: Type.h:831
Represents a template name that was expressed as a qualified name.
Definition: TemplateName.h:386
TagTypeKind
The kind of a tag type.
Definition: Type.h:5101
RealType getRealTypeByWidth(unsigned BitWidth) const
Return floating point type with specified width.
Definition: TargetInfo.cpp:259
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:2439
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:1046
void getLegacyIntegralTypeEncoding(QualType &t) const
getLegacyIntegralTypeEncoding - Another legacy compatibility encoding: 32-bit longs are encoded as &#39;l...
GC getObjCGCAttr() const
Definition: Type.h:301
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
DeducedType * getContainedDeducedType() const
Get the DeducedType whose type will be deduced for a variable with an initializer of this type...
Definition: Type.cpp:1754
A RecursiveASTVisitor that builds a map from nodes to their parents as defined by the RecursiveASTVis...
ExtInfo getExtInfo() const
Definition: Type.h:3656
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:6109
QualType mergeTypes(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false, bool BlockReturnType=false)
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:1042
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:403
CanQualType DoubleComplexTy
Definition: ASTContext.h:1040
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...
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:225
static FloatingRank getFloatingRank(QualType T)
getFloatingRank - Return a relative rank for floating point types.
APFixedPoint getFixedPointMin(QualType Ty) const
CanQualType UnsignedShortAccumTy
Definition: ASTContext.h:1029
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:3639
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:53
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:3004
Interesting information about a specific parameter that can&#39;t simply be reflected in parameter&#39;s type...
Definition: Type.h:3413
CanQualType UnsignedLongLongTy
Definition: ASTContext.h:1025
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:2863
unsigned NumImplicitDefaultConstructorsDeclared
The number of implicitly-declared default constructors for which declarations were built...
Definition: ASTContext.h:2835
ObjCInterfaceDecl * getDefinition()
Retrieve the definition of this class, or NULL if this class has been forward-declared (with @class) ...
Definition: DeclObjC.h:1548
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:2701
bool hasLocalQualifiers() const
Determine whether this particular QualType instance has any qualifiers, without looking through any t...
Definition: Type.h:745
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition: Specifiers.h:188
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:3458
The name of a declaration.
VectorKind getVectorKind() const
Definition: Type.h:3245
Represents the declaration of an Objective-C type parameter.
Definition: DeclObjC.h:558
bool isBooleanType() const
Definition: Type.h:6760
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition: Type.h:6116
const CXXRecordDecl * getBaseSharingVBPtr() const
Definition: RecordLayout.h:310
Represents a C++11 pack expansion that produces a sequence of expressions.
Definition: ExprCXX.h:3921
QualType getFunctionNoProtoType(QualType ResultTy, const FunctionType::ExtInfo &Info) const
Return a K&R style C function type like &#39;int()&#39;.
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3186
MangleNumberingContext & getManglingNumberContext(const DeclContext *DC)
Retrieve the context for computing mangling numbers in the given DeclContext.
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.cpp:3473
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:5905
bool isKindOfType() const
Whether this ia a "__kindof" type (semantically).
Definition: Type.cpp:682
Represents an enum.
Definition: Decl.h:3359
FunctionType::ExtInfo getFunctionExtInfo(const Type &t)
Definition: Type.h:6285
Information about the declaration, useful to clients of FullComment.
Definition: Comment.h:980
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:2734
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:2788
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:253
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:174
bool hasObjCLifetime() const
Definition: Type.h:326
QualType AutoRRefDeductTy
Definition: ASTContext.h:1060
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:1081
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:1117
bool areComparableObjCPointerTypes(QualType LHS, QualType RHS)
QualType getUnsignedWCharType() const
Return the type of "unsigned wchar_t".
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:4646
void addConsistentQualifiers(Qualifiers qs)
Add the qualifiers from the given set to this set, given that they don&#39;t conflict.
Definition: Type.h:453
bool isObjCUnqualifiedIdOrClass() const
Definition: Type.h:5683
bool isMacroID() const
GVALinkage GetGVALinkageForVariable(const VarDecl *VD)
A dynamically typed AST node container.
const Decl * getOriginalDecl() const LLVM_READONLY
Definition: ASTContext.h:773
virtual IntType getIntTypeByWidth(unsigned BitWidth, bool IsSigned) const
Return integer type with specified width.
Definition: TargetInfo.cpp:229
Represents a pointer to an Objective C object.
Definition: Type.h:5864
Copy initialization expr of a __block variable and a boolean flag that indicates whether the expressi...
Definition: ASTContext.h:158
Pointer to a block type.
Definition: Type.h:2671
CanQualType ObjCBuiltinBoolTy
Definition: ASTContext.h:1047
unsigned getIntWidth(QualType T) const
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
Definition: DeclObjC.h:2551
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:6448
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:4438
StringRef getObjCRuntimeNameAsString() const
Produce a name to be used for class&#39;s metadata.
Definition: DeclObjC.cpp:1532
Complex values, per C99 6.2.5p11.
Definition: Type.h:2509
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:5690
CanQualType UnknownAnyTy
Definition: ASTContext.h:1043
bool empty() const
Definition: Type.h:415
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:2052
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:329
ObjCInterfaceDecl * getInterfaceDecl() const
If this pointer points to an Objective @interface type, gets the declaration for that interface...
Definition: Type.h:5920
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:476
QualType getCanonicalTypeInternal() const
Definition: Type.h:2387
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:6677
This template specialization was declared or defined by an explicit specialization (C++ [temp...
Definition: Specifiers.h:184
CanQualType UnsignedLongTy
Definition: ASTContext.h:1024
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...
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:2976
const llvm::APInt & getSize() const
Definition: Type.h:2922
uint64_t getCharWidth() const
Return the size of the character type, in bits.
Definition: ASTContext.h:2083
CanQualType DependentTy
Definition: ASTContext.h:1043
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:1017
bool isFunctionType() const
Definition: Type.h:6380
bool hasNonFastQualifiers() const
Return true if the set contains any qualifiers which require an ExtQuals node to be allocated...
Definition: Type.h:406
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition: Decl.h:1059
bool isObjCQualifiedIdType() const
Definition: Type.h:6505
static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET)
static GVALinkage basicGVALinkageForVariable(const ASTContext &Context, const VarDecl *VD)
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:715
bool isMSExternInline() const
The combination of the extern and inline keywords under MSVC forces the function to be required...
Definition: Decl.cpp:3175
ExtVectorType - Extended vector type.
Definition: Type.h:3319
CanQualType ObjCBuiltinClassTy
Definition: ASTContext.h:1046
DeclaratorDecl * getDeclaratorForUnnamedTagDecl(const TagDecl *TD)
param_const_iterator param_begin() const
Definition: DeclObjC.h:347
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:2705
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:1737
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2296
CanQualType BoundMemberTy
Definition: ASTContext.h:1043
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:1914
llvm::DenseMap< const Decl *, comments::FullComment * > ParsedComments
Mapping from declarations to parsed comments attached to any redeclaration.
Definition: ASTContext.h:795
The template argument is a type.
Definition: TemplateBase.h:59
qual_range quals() const
Definition: Type.h:5987
Holds information about the various types of exception specification.
Definition: Type.h:3773
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:1514
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:3755
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:223
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat]...
Definition: APValue.h:76
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2079
ArrayRef< QualType > Exceptions
Explicitly-specified list of exception types.
Definition: Type.h:3778
bool isObjCObjectType() const
Definition: Type.h:6492
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types...
Definition: Type.cpp:2062
bool hasObjCGCAttr() const
Definition: Type.h:300
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition: Decl.h:2391
CanQualType Char8Ty
Definition: ASTContext.h:1020
DynTypedNodeList getParents(const ast_type_traits::DynTypedNode &Node)
Definition: ASTContext.cpp:898
ASTMutationListener * getASTMutationListener() const
Retrieve a pointer to the AST mutation listener associated with this AST context, if any...
Definition: ASTContext.h:1096
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2280
A template argument list.
Definition: DeclTemplate.h:214
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:240
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...
Definition: ASTContext.cpp:980
bool isNoThrow(unsigned ID) const
Return true if we know this builtin never throws an exception.
Definition: Builtins.h:111
X
Add a minimal nested name specifier fixit hint to allow lookup of a tag name from an outer enclosing ...
Definition: SemaDecl.cpp:14445
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:168
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:4493
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:3923
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:5534
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:1007
Defines the clang::SourceLocation class and associated facilities.
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:4875
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:6222
bool hasUnaligned() const
Definition: Type.h:293
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:1905
Represents a C++ struct/union/class.
Definition: DeclCXX.h:300
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:2498
IdentifierInfo * getTypePackElementName() const
Definition: ASTContext.h:1727
Represents a template specialization type whose template cannot be resolved, e.g. ...
Definition: Type.h:5334
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:2866
Represents a C array with an unspecified size.
Definition: Type.h:2958
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:2016
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:2223
static TranslationUnitDecl * Create(ASTContext &C)
Definition: Decl.cpp:4465
static void SortAndUniqueProtocols(SmallVectorImpl< ObjCProtocolDecl *> &Protocols)
IdentifierInfo * getMakeIntegerSeqName() const
Definition: ASTContext.h:1721
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:6169
ObjCIvarDecl - Represents an ObjC instance variable.
Definition: DeclObjC.h:1944
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:4677
Provides information a specialization of a member of a class template, which may be a member function...
Definition: DeclTemplate.h:664
CanQualType Char16Ty
Definition: ASTContext.h:1021
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
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...
We searched for a comment attached to the particular declaration, but didn&#39;t find any...
Definition: ASTContext.h:739
Builtin::Context & BuiltinInfo
Definition: ASTContext.h:571
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:4278
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:470
Stores a list of Objective-C type parameters for a parameterized class or a category/extension thereo...
Definition: DeclObjC.h:636
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:2423
bool isVariadic() const
Definition: DeclObjC.h:426
virtual LangAS getCUDABuiltinAddressSpace(unsigned AS) const
Map from the address space field in builtin description strings to the language address space...
Definition: TargetInfo.h:1229
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:360
__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:1681
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:640
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:153
unsigned CountNonClassIvars(const ObjCInterfaceDecl *OI) const
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition: Decl.h:3513
void setRAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:1611
unsigned getCVRQualifiers() const
Definition: Type.h:270
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:2444
uint64_t Width
Definition: ASTContext.h:143
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:1759
NameKind getKind() const
static Decl::Kind getKind(const Decl *D)
Definition: DeclBase.cpp:944
CanQualType IntTy
Definition: ASTContext.h:1023
QualType getSignedWCharType() const
Return the type of "signed wchar_t".
unsigned getNumElements() const
Definition: Type.h:3236
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:2108
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:1141
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:3118
result[0]
Definition: emmintrin.h:120
bool isUnion() const
Definition: Decl.h:3285
Represents a type template specialization; the template must be a class template, a type alias templa...
Definition: Type.h:4911
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:4001
ObjCTypeParamVariance getVariance() const
Determine the variance of this type parameter.
Definition: DeclObjC.h:601
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:6384
QualType mergeFunctionParameterTypes(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false)
mergeFunctionParameterTypes - merge two types which appear as function parameter types ...
QualType getAutoType(QualType DeducedType, AutoTypeKeyword Keyword, bool IsDependent, bool IsPack=false) const
C++11 deduced auto type.
const DeclInfo * getDeclInfo() const LLVM_READONLY
Definition: Comment.h:1123
void addAddressSpace(LangAS space)
Definition: Type.h:379
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
StringRef Text
Definition: Format.cpp:1712
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:1134
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:1321
QualType getType() const
Definition: Decl.h:647
TemplateArgument getArgumentPack() const
Retrieve the template template argument pack with which this parameter was substituted.
A set of overloaded template declarations.
Definition: TemplateName.h:203
A trivial tuple used to represent a source range.
This represents a decl that may have a name.
Definition: Decl.h:248
ArrayRef< BlockContentComment * > getBlocks() const
Definition: Comment.h:1129
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:3615
T castAs() const
Convert to the specified TypeLoc type, asserting that this TypeLoc is of the desired type...
Definition: TypeLoc.h:75
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:2849
Represents a C array with a specified size that is not an integer-constant-expression.
Definition: Type.h:3003
CanQualType BoolTy
Definition: ASTContext.h:1015
void setTemplateNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:1635
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:5141
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...
bool ObjCQualifiedIdTypesAreCompatible(QualType LHS, QualType RHS, bool ForCompare)
ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an ObjCQualifiedIDType.
FloatingRank
Definition: ASTContext.cpp:97
bool isInline() const
Whether this variable is (C++1z) inline.
Definition: Decl.h:1368
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:6058
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:2852
unsigned getTargetAddressSpace(QualType T) const
Definition: ASTContext.h:2532
CanQualType DoubleTy
Definition: ASTContext.h:1026
Selector getGetterName() const
Definition: DeclObjC.h:905
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:5387
static bool isObjCNSObjectType(QualType Ty)
Return true if this is an NSObject object with its NSObject attribute set.
Definition: ASTContext.h:2059
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:3882
void addedLocalImportDecl(ImportDecl *Import)
Notify the AST context that a new import declaration has been parsed or implicitly created within thi...
virtual uint64_t getNullPointerValue(LangAS AddrSpace) const
Get integer value for null pointer.
Definition: TargetInfo.h:372
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:2019
void setType(QualType newType)
Definition: Decl.h:648
void removeAddressSpace()
Definition: Type.h:378
bool hasInit() const
Definition: Decl.cpp:2198
QualType getReadPipeType(QualType T) const
Return a read_only pipe type for the specified type.
const LangOptions & getLangOpts() const
Definition: ASTContext.h:710
ObjCCategoryImplDecl - An object of this class encapsulates a category @implementation declaration...
Definition: DeclObjC.h:2498
No in-class initializer.
Definition: Specifiers.h:258
bool AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:2904
This class handles loading and caching of source files into memory.
The parameter is invariant: must match exactly.
ExceptionSpecInfo ExceptionSpec
Definition: Type.h:3805
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.
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:3498
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.
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:2808
const RawComment * getRawCommentForAnyRedecl(const Decl *D, const Decl **OriginalDecl=nullptr) const
Return the documentation comment attached to a given declaration.
Definition: ASTContext.cpp:373
Represents a shadow declaration introduced into a scope by a (resolved) using declaration.
Definition: DeclCXX.h:3275
bool isExternallyVisible() const
Definition: Decl.h:379
A full comment attached to a declaration, contains block content.
Definition: Comment.h:1091
APValue * getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E, bool MayCreate)
Get the storage for the constant value of a materialized temporary of static storage duration...
A single template declaration.
Definition: TemplateName.h:200
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:4836
CanQualType OCLClkEventTy
Definition: ASTContext.h:1051
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:124
CanQualType UnsignedIntTy
Definition: ASTContext.h:1024
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:1063
BuiltinTemplateDecl * getMakeIntegerSeqDecl() const
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition: Type.h:5880
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:2035