clang  7.0.0
ASTContext.cpp
Go to the documentation of this file.
1 //===- ASTContext.cpp - Context to hold long-lived AST nodes --------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the ASTContext interface.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/AST/ASTContext.h"
15 #include "CXXABI.h"
16 #include "clang/AST/APValue.h"
19 #include "clang/AST/Attr.h"
20 #include "clang/AST/AttrIterator.h"
21 #include "clang/AST/CharUnits.h"
22 #include "clang/AST/Comment.h"
23 #include "clang/AST/Decl.h"
24 #include "clang/AST/DeclBase.h"
25 #include "clang/AST/DeclCXX.h"
27 #include "clang/AST/DeclObjC.h"
28 #include "clang/AST/DeclOpenMP.h"
29 #include "clang/AST/DeclTemplate.h"
31 #include "clang/AST/Expr.h"
32 #include "clang/AST/ExprCXX.h"
34 #include "clang/AST/Mangle.h"
38 #include "clang/AST/RecordLayout.h"
40 #include "clang/AST/Stmt.h"
41 #include "clang/AST/TemplateBase.h"
42 #include "clang/AST/TemplateName.h"
43 #include "clang/AST/Type.h"
44 #include "clang/AST/TypeLoc.h"
48 #include "clang/Basic/Builtins.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 
109 
112 };
113 
115  if (!CommentsLoaded && ExternalSource) {
116  ExternalSource->ReadComments();
117 
118 #ifndef NDEBUG
120  assert(std::is_sorted(RawComments.begin(), RawComments.end(),
121  BeforeThanCompare<RawComment>(SourceMgr)));
122 #endif
123 
124  CommentsLoaded = true;
125  }
126 
127  assert(D);
128 
129  // User can not attach documentation to implicit declarations.
130  if (D->isImplicit())
131  return nullptr;
132 
133  // User can not attach documentation to implicit instantiations.
134  if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
135  if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
136  return nullptr;
137  }
138 
139  if (const auto *VD = dyn_cast<VarDecl>(D)) {
140  if (VD->isStaticDataMember() &&
141  VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
142  return nullptr;
143  }
144 
145  if (const auto *CRD = dyn_cast<CXXRecordDecl>(D)) {
146  if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
147  return nullptr;
148  }
149 
150  if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
151  TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
152  if (TSK == TSK_ImplicitInstantiation ||
153  TSK == TSK_Undeclared)
154  return nullptr;
155  }
156 
157  if (const auto *ED = dyn_cast<EnumDecl>(D)) {
158  if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
159  return nullptr;
160  }
161  if (const auto *TD = dyn_cast<TagDecl>(D)) {
162  // When tag declaration (but not definition!) is part of the
163  // decl-specifier-seq of some other declaration, it doesn't get comment
164  if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
165  return nullptr;
166  }
167  // TODO: handle comments for function parameters properly.
168  if (isa<ParmVarDecl>(D))
169  return nullptr;
170 
171  // TODO: we could look up template parameter documentation in the template
172  // documentation.
173  if (isa<TemplateTypeParmDecl>(D) ||
174  isa<NonTypeTemplateParmDecl>(D) ||
175  isa<TemplateTemplateParmDecl>(D))
176  return nullptr;
177 
179 
180  // If there are no comments anywhere, we won't find anything.
181  if (RawComments.empty())
182  return nullptr;
183 
184  // Find declaration location.
185  // For Objective-C declarations we generally don't expect to have multiple
186  // declarators, thus use declaration starting location as the "declaration
187  // location".
188  // For all other declarations multiple declarators are used quite frequently,
189  // so we use the location of the identifier as the "declaration location".
190  SourceLocation DeclLoc;
191  if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
192  isa<ObjCPropertyDecl>(D) ||
193  isa<RedeclarableTemplateDecl>(D) ||
194  isa<ClassTemplateSpecializationDecl>(D))
195  DeclLoc = D->getLocStart();
196  else {
197  DeclLoc = D->getLocation();
198  if (DeclLoc.isMacroID()) {
199  if (isa<TypedefDecl>(D)) {
200  // If location of the typedef name is in a macro, it is because being
201  // declared via a macro. Try using declaration's starting location as
202  // the "declaration location".
203  DeclLoc = D->getLocStart();
204  } else if (const auto *TD = dyn_cast<TagDecl>(D)) {
205  // If location of the tag decl is inside a macro, but the spelling of
206  // the tag name comes from a macro argument, it looks like a special
207  // macro like NS_ENUM is being used to define the tag decl. In that
208  // case, adjust the source location to the expansion loc so that we can
209  // attach the comment to the tag decl.
210  if (SourceMgr.isMacroArgExpansion(DeclLoc) &&
211  TD->isCompleteDefinition())
212  DeclLoc = SourceMgr.getExpansionLoc(DeclLoc);
213  }
214  }
215  }
216 
217  // If the declaration doesn't map directly to a location in a file, we
218  // can't find the comment.
219  if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
220  return nullptr;
221 
222  // Find the comment that occurs just after this declaration.
224  {
225  // When searching for comments during parsing, the comment we are looking
226  // for is usually among the last two comments we parsed -- check them
227  // first.
228  RawComment CommentAtDeclLoc(
229  SourceMgr, SourceRange(DeclLoc), LangOpts.CommentOpts, false);
230  BeforeThanCompare<RawComment> Compare(SourceMgr);
231  ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1;
232  bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
233  if (!Found && RawComments.size() >= 2) {
234  MaybeBeforeDecl--;
235  Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
236  }
237 
238  if (Found) {
239  Comment = MaybeBeforeDecl + 1;
240  assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(),
241  &CommentAtDeclLoc, Compare));
242  } else {
243  // Slow path.
244  Comment = std::lower_bound(RawComments.begin(), RawComments.end(),
245  &CommentAtDeclLoc, Compare);
246  }
247  }
248 
249  // Decompose the location for the declaration and find the beginning of the
250  // file buffer.
251  std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
252 
253  // First check whether we have a trailing comment.
254  if (Comment != RawComments.end() &&
255  ((*Comment)->isDocumentation() || LangOpts.CommentOpts.ParseAllComments)
256  && (*Comment)->isTrailingComment() &&
257  (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
258  isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
259  std::pair<FileID, unsigned> CommentBeginDecomp
260  = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
261  // Check that Doxygen trailing comment comes after the declaration, starts
262  // on the same line and in the same file as the declaration.
263  if (DeclLocDecomp.first == CommentBeginDecomp.first &&
264  SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
265  == SourceMgr.getLineNumber(CommentBeginDecomp.first,
266  CommentBeginDecomp.second)) {
267  return *Comment;
268  }
269  }
270 
271  // The comment just after the declaration was not a trailing comment.
272  // Let's look at the previous comment.
273  if (Comment == RawComments.begin())
274  return nullptr;
275  --Comment;
276 
277  // Check that we actually have a non-member Doxygen comment.
278  if (!((*Comment)->isDocumentation() ||
279  LangOpts.CommentOpts.ParseAllComments) ||
280  (*Comment)->isTrailingComment())
281  return nullptr;
282 
283  // Decompose the end of the comment.
284  std::pair<FileID, unsigned> CommentEndDecomp
285  = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
286 
287  // If the comment and the declaration aren't in the same file, then they
288  // aren't related.
289  if (DeclLocDecomp.first != CommentEndDecomp.first)
290  return nullptr;
291 
292  // Get the corresponding buffer.
293  bool Invalid = false;
294  const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
295  &Invalid).data();
296  if (Invalid)
297  return nullptr;
298 
299  // Extract text between the comment and declaration.
300  StringRef Text(Buffer + CommentEndDecomp.second,
301  DeclLocDecomp.second - CommentEndDecomp.second);
302 
303  // There should be no other declarations or preprocessor directives between
304  // comment and declaration.
305  if (Text.find_first_of(";{}#@") != StringRef::npos)
306  return nullptr;
307 
308  return *Comment;
309 }
310 
311 /// If we have a 'templated' declaration for a template, adjust 'D' to
312 /// refer to the actual template.
313 /// If we have an implicit instantiation, adjust 'D' to refer to template.
314 static const Decl *adjustDeclToTemplate(const Decl *D) {
315  if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
316  // Is this function declaration part of a function template?
317  if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
318  return FTD;
319 
320  // Nothing to do if function is not an implicit instantiation.
321  if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
322  return D;
323 
324  // Function is an implicit instantiation of a function template?
325  if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
326  return FTD;
327 
328  // Function is instantiated from a member definition of a class template?
329  if (const FunctionDecl *MemberDecl =
331  return MemberDecl;
332 
333  return D;
334  }
335  if (const auto *VD = dyn_cast<VarDecl>(D)) {
336  // Static data member is instantiated from a member definition of a class
337  // template?
338  if (VD->isStaticDataMember())
339  if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
340  return MemberDecl;
341 
342  return D;
343  }
344  if (const auto *CRD = dyn_cast<CXXRecordDecl>(D)) {
345  // Is this class declaration part of a class template?
346  if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
347  return CTD;
348 
349  // Class is an implicit instantiation of a class template or partial
350  // specialization?
351  if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
352  if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
353  return D;
354  llvm::PointerUnion<ClassTemplateDecl *,
356  PU = CTSD->getSpecializedTemplateOrPartial();
357  return PU.is<ClassTemplateDecl*>() ?
358  static_cast<const Decl*>(PU.get<ClassTemplateDecl *>()) :
359  static_cast<const Decl*>(
361  }
362 
363  // Class is instantiated from a member definition of a class template?
364  if (const MemberSpecializationInfo *Info =
365  CRD->getMemberSpecializationInfo())
366  return Info->getInstantiatedFrom();
367 
368  return D;
369  }
370  if (const auto *ED = dyn_cast<EnumDecl>(D)) {
371  // Enum is instantiated from a member definition of a class template?
372  if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
373  return MemberDecl;
374 
375  return D;
376  }
377  // FIXME: Adjust alias templates?
378  return D;
379 }
380 
382  const Decl *D,
383  const Decl **OriginalDecl) const {
384  D = adjustDeclToTemplate(D);
385 
386  // Check whether we have cached a comment for this declaration already.
387  {
388  llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
389  RedeclComments.find(D);
390  if (Pos != RedeclComments.end()) {
391  const RawCommentAndCacheFlags &Raw = Pos->second;
393  if (OriginalDecl)
394  *OriginalDecl = Raw.getOriginalDecl();
395  return Raw.getRaw();
396  }
397  }
398  }
399 
400  // Search for comments attached to declarations in the redeclaration chain.
401  const RawComment *RC = nullptr;
402  const Decl *OriginalDeclForRC = nullptr;
403  for (auto I : D->redecls()) {
404  llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
405  RedeclComments.find(I);
406  if (Pos != RedeclComments.end()) {
407  const RawCommentAndCacheFlags &Raw = Pos->second;
409  RC = Raw.getRaw();
410  OriginalDeclForRC = Raw.getOriginalDecl();
411  break;
412  }
413  } else {
415  OriginalDeclForRC = I;
417  if (RC) {
418  // Call order swapped to work around ICE in VS2015 RTM (Release Win32)
419  // https://connect.microsoft.com/VisualStudio/feedback/details/1741530
421  Raw.setRaw(RC);
422  } else
424  Raw.setOriginalDecl(I);
425  RedeclComments[I] = Raw;
426  if (RC)
427  break;
428  }
429  }
430 
431  // If we found a comment, it should be a documentation comment.
432  assert(!RC || RC->isDocumentation() || LangOpts.CommentOpts.ParseAllComments);
433 
434  if (OriginalDecl)
435  *OriginalDecl = OriginalDeclForRC;
436 
437  // Update cache for every declaration in the redeclaration chain.
439  Raw.setRaw(RC);
441  Raw.setOriginalDecl(OriginalDeclForRC);
442 
443  for (auto I : D->redecls()) {
446  R = Raw;
447  }
448 
449  return RC;
450 }
451 
452 static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
454  const DeclContext *DC = ObjCMethod->getDeclContext();
455  if (const auto *IMD = dyn_cast<ObjCImplDecl>(DC)) {
456  const ObjCInterfaceDecl *ID = IMD->getClassInterface();
457  if (!ID)
458  return;
459  // Add redeclared method here.
460  for (const auto *Ext : ID->known_extensions()) {
461  if (ObjCMethodDecl *RedeclaredMethod =
462  Ext->getMethod(ObjCMethod->getSelector(),
463  ObjCMethod->isInstanceMethod()))
464  Redeclared.push_back(RedeclaredMethod);
465  }
466  }
467 }
468 
470  const Decl *D) const {
471  auto *ThisDeclInfo = new (*this) comments::DeclInfo;
472  ThisDeclInfo->CommentDecl = D;
473  ThisDeclInfo->IsFilled = false;
474  ThisDeclInfo->fill();
475  ThisDeclInfo->CommentDecl = FC->getDecl();
476  if (!ThisDeclInfo->TemplateParameters)
477  ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
478  comments::FullComment *CFC =
479  new (*this) comments::FullComment(FC->getBlocks(),
480  ThisDeclInfo);
481  return CFC;
482 }
483 
486  return RC ? RC->parse(*this, nullptr, D) : nullptr;
487 }
488 
490  const Decl *D,
491  const Preprocessor *PP) const {
492  if (D->isInvalidDecl())
493  return nullptr;
494  D = adjustDeclToTemplate(D);
495 
496  const Decl *Canonical = D->getCanonicalDecl();
497  llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
498  ParsedComments.find(Canonical);
499 
500  if (Pos != ParsedComments.end()) {
501  if (Canonical != D) {
502  comments::FullComment *FC = Pos->second;
504  return CFC;
505  }
506  return Pos->second;
507  }
508 
509  const Decl *OriginalDecl;
510 
511  const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
512  if (!RC) {
513  if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
515  const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
516  if (OMD && OMD->isPropertyAccessor())
517  if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
518  if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
519  return cloneFullComment(FC, D);
520  if (OMD)
521  addRedeclaredMethods(OMD, Overridden);
522  getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
523  for (unsigned i = 0, e = Overridden.size(); i < e; i++)
524  if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
525  return cloneFullComment(FC, D);
526  }
527  else if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
528  // Attach any tag type's documentation to its typedef if latter
529  // does not have one of its own.
530  QualType QT = TD->getUnderlyingType();
531  if (const auto *TT = QT->getAs<TagType>())
532  if (const Decl *TD = TT->getDecl())
533  if (comments::FullComment *FC = getCommentForDecl(TD, PP))
534  return cloneFullComment(FC, D);
535  }
536  else if (const auto *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
537  while (IC->getSuperClass()) {
538  IC = IC->getSuperClass();
539  if (comments::FullComment *FC = getCommentForDecl(IC, PP))
540  return cloneFullComment(FC, D);
541  }
542  }
543  else if (const auto *CD = dyn_cast<ObjCCategoryDecl>(D)) {
544  if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
545  if (comments::FullComment *FC = getCommentForDecl(IC, PP))
546  return cloneFullComment(FC, D);
547  }
548  else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
549  if (!(RD = RD->getDefinition()))
550  return nullptr;
551  // Check non-virtual bases.
552  for (const auto &I : RD->bases()) {
553  if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
554  continue;
555  QualType Ty = I.getType();
556  if (Ty.isNull())
557  continue;
558  if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
559  if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
560  continue;
561 
562  if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
563  return cloneFullComment(FC, D);
564  }
565  }
566  // Check virtual bases.
567  for (const auto &I : RD->vbases()) {
568  if (I.getAccessSpecifier() != AS_public)
569  continue;
570  QualType Ty = I.getType();
571  if (Ty.isNull())
572  continue;
573  if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
574  if (!(VirtualBase= VirtualBase->getDefinition()))
575  continue;
576  if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
577  return cloneFullComment(FC, D);
578  }
579  }
580  }
581  return nullptr;
582  }
583 
584  // If the RawComment was attached to other redeclaration of this Decl, we
585  // should parse the comment in context of that other Decl. This is important
586  // because comments can contain references to parameter names which can be
587  // different across redeclarations.
588  if (D != OriginalDecl)
589  return getCommentForDecl(OriginalDecl, PP);
590 
591  comments::FullComment *FC = RC->parse(*this, PP, D);
592  ParsedComments[Canonical] = FC;
593  return FC;
594 }
595 
596 void
597 ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
598  TemplateTemplateParmDecl *Parm) {
599  ID.AddInteger(Parm->getDepth());
600  ID.AddInteger(Parm->getPosition());
601  ID.AddBoolean(Parm->isParameterPack());
602 
604  ID.AddInteger(Params->size());
606  PEnd = Params->end();
607  P != PEnd; ++P) {
608  if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
609  ID.AddInteger(0);
610  ID.AddBoolean(TTP->isParameterPack());
611  continue;
612  }
613 
614  if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
615  ID.AddInteger(1);
616  ID.AddBoolean(NTTP->isParameterPack());
617  ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
618  if (NTTP->isExpandedParameterPack()) {
619  ID.AddBoolean(true);
620  ID.AddInteger(NTTP->getNumExpansionTypes());
621  for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
622  QualType T = NTTP->getExpansionType(I);
623  ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
624  }
625  } else
626  ID.AddBoolean(false);
627  continue;
628  }
629 
630  auto *TTP = cast<TemplateTemplateParmDecl>(*P);
631  ID.AddInteger(2);
632  Profile(ID, TTP);
633  }
634 }
635 
637 ASTContext::getCanonicalTemplateTemplateParmDecl(
638  TemplateTemplateParmDecl *TTP) const {
639  // Check if we already have a canonical template template parameter.
640  llvm::FoldingSetNodeID ID;
641  CanonicalTemplateTemplateParm::Profile(ID, TTP);
642  void *InsertPos = nullptr;
643  CanonicalTemplateTemplateParm *Canonical
644  = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
645  if (Canonical)
646  return Canonical->getParam();
647 
648  // Build a canonical template parameter list.
650  SmallVector<NamedDecl *, 4> CanonParams;
651  CanonParams.reserve(Params->size());
653  PEnd = Params->end();
654  P != PEnd; ++P) {
655  if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
656  CanonParams.push_back(
658  SourceLocation(),
659  SourceLocation(),
660  TTP->getDepth(),
661  TTP->getIndex(), nullptr, false,
662  TTP->isParameterPack()));
663  else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
664  QualType T = getCanonicalType(NTTP->getType());
667  if (NTTP->isExpandedParameterPack()) {
668  SmallVector<QualType, 2> ExpandedTypes;
669  SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
670  for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
671  ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
672  ExpandedTInfos.push_back(
673  getTrivialTypeSourceInfo(ExpandedTypes.back()));
674  }
675 
677  SourceLocation(),
678  SourceLocation(),
679  NTTP->getDepth(),
680  NTTP->getPosition(), nullptr,
681  T,
682  TInfo,
683  ExpandedTypes,
684  ExpandedTInfos);
685  } else {
687  SourceLocation(),
688  SourceLocation(),
689  NTTP->getDepth(),
690  NTTP->getPosition(), nullptr,
691  T,
692  NTTP->isParameterPack(),
693  TInfo);
694  }
695  CanonParams.push_back(Param);
696 
697  } else
698  CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
699  cast<TemplateTemplateParmDecl>(*P)));
700  }
701 
702  assert(!TTP->getRequiresClause() &&
703  "Unexpected requires-clause on template template-parameter");
704  Expr *const CanonRequiresClause = nullptr;
705 
706  TemplateTemplateParmDecl *CanonTTP
708  SourceLocation(), TTP->getDepth(),
709  TTP->getPosition(),
710  TTP->isParameterPack(),
711  nullptr,
713  SourceLocation(),
714  CanonParams,
715  SourceLocation(),
716  CanonRequiresClause));
717 
718  // Get the new insert position for the node we care about.
719  Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
720  assert(!Canonical && "Shouldn't be in the map!");
721  (void)Canonical;
722 
723  // Create the canonical template template parameter entry.
724  Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
725  CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
726  return CanonTTP;
727 }
728 
729 CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
730  if (!LangOpts.CPlusPlus) return nullptr;
731 
732  switch (T.getCXXABI().getKind()) {
733  case TargetCXXABI::GenericARM: // Same as Itanium at this level
734  case TargetCXXABI::iOS:
735  case TargetCXXABI::iOS64:
741  return CreateItaniumCXXABI(*this);
743  return CreateMicrosoftCXXABI(*this);
744  }
745  llvm_unreachable("Invalid CXXABI type!");
746 }
747 
748 static const LangASMap *getAddressSpaceMap(const TargetInfo &T,
749  const LangOptions &LOpts) {
750  if (LOpts.FakeAddressSpaceMap) {
751  // The fake address space map must have a distinct entry for each
752  // language-specific address space.
753  static const unsigned FakeAddrSpaceMap[] = {
754  0, // Default
755  1, // opencl_global
756  3, // opencl_local
757  2, // opencl_constant
758  0, // opencl_private
759  4, // opencl_generic
760  5, // cuda_device
761  6, // cuda_constant
762  7 // cuda_shared
763  };
764  return &FakeAddrSpaceMap;
765  } else {
766  return &T.getAddressSpaceMap();
767  }
768 }
769 
771  const LangOptions &LangOpts) {
772  switch (LangOpts.getAddressSpaceMapMangling()) {
774  return TI.useAddressSpaceMapMangling();
776  return true;
778  return false;
779  }
780  llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
781 }
782 
784  IdentifierTable &idents, SelectorTable &sels,
785  Builtin::Context &builtins)
786  : FunctionProtoTypes(this_()), TemplateSpecializationTypes(this_()),
787  DependentTemplateSpecializationTypes(this_()),
788  SubstTemplateTemplateParmPacks(this_()), SourceMgr(SM), LangOpts(LOpts),
789  SanitizerBL(new SanitizerBlacklist(LangOpts.SanitizerBlacklistFiles, SM)),
790  XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles,
791  LangOpts.XRayNeverInstrumentFiles,
792  LangOpts.XRayAttrListFiles, SM)),
793  PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
794  BuiltinInfo(builtins), DeclarationNames(*this), Comments(SM),
795  CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
796  CompCategories(this_()), LastSDM(nullptr, 0) {
797  TUDecl = TranslationUnitDecl::Create(*this);
798 }
799 
801  ReleaseParentMapEntries();
802 
803  // Release the DenseMaps associated with DeclContext objects.
804  // FIXME: Is this the ideal solution?
805  ReleaseDeclContextMaps();
806 
807  // Call all of the deallocation functions on all of their targets.
808  for (auto &Pair : Deallocations)
809  (Pair.first)(Pair.second);
810 
811  // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
812  // because they can contain DenseMaps.
813  for (llvm::DenseMap<const ObjCContainerDecl*,
814  const ASTRecordLayout*>::iterator
815  I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
816  // Increment in loop to prevent using deallocated memory.
817  if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
818  R->Destroy(*this);
819 
820  for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
821  I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
822  // Increment in loop to prevent using deallocated memory.
823  if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
824  R->Destroy(*this);
825  }
826 
827  for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
828  AEnd = DeclAttrs.end();
829  A != AEnd; ++A)
830  A->second->~AttrVec();
831 
832  for (std::pair<const MaterializeTemporaryExpr *, APValue *> &MTVPair :
833  MaterializedTemporaryValues)
834  MTVPair.second->~APValue();
835 
836  for (const auto &Value : ModuleInitializers)
837  Value.second->~PerModuleInitializers();
838 }
839 
840 void ASTContext::ReleaseParentMapEntries() {
841  if (!PointerParents) return;
842  for (const auto &Entry : *PointerParents) {
843  if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
844  delete Entry.second.get<ast_type_traits::DynTypedNode *>();
845  } else if (Entry.second.is<ParentVector *>()) {
846  delete Entry.second.get<ParentVector *>();
847  }
848  }
849  for (const auto &Entry : *OtherParents) {
850  if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
851  delete Entry.second.get<ast_type_traits::DynTypedNode *>();
852  } else if (Entry.second.is<ParentVector *>()) {
853  delete Entry.second.get<ParentVector *>();
854  }
855  }
856 }
857 
858 void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
859  Deallocations.push_back({Callback, Data});
860 }
861 
862 void
864  ExternalSource = std::move(Source);
865 }
866 
868  llvm::errs() << "\n*** AST Context Stats:\n";
869  llvm::errs() << " " << Types.size() << " types total.\n";
870 
871  unsigned counts[] = {
872 #define TYPE(Name, Parent) 0,
873 #define ABSTRACT_TYPE(Name, Parent)
874 #include "clang/AST/TypeNodes.def"
875  0 // Extra
876  };
877 
878  for (unsigned i = 0, e = Types.size(); i != e; ++i) {
879  Type *T = Types[i];
880  counts[(unsigned)T->getTypeClass()]++;
881  }
882 
883  unsigned Idx = 0;
884  unsigned TotalBytes = 0;
885 #define TYPE(Name, Parent) \
886  if (counts[Idx]) \
887  llvm::errs() << " " << counts[Idx] << " " << #Name \
888  << " types\n"; \
889  TotalBytes += counts[Idx] * sizeof(Name##Type); \
890  ++Idx;
891 #define ABSTRACT_TYPE(Name, Parent)
892 #include "clang/AST/TypeNodes.def"
893 
894  llvm::errs() << "Total bytes = " << TotalBytes << "\n";
895 
896  // Implicit special member functions.
897  llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
899  << " implicit default constructors created\n";
900  llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
902  << " implicit copy constructors created\n";
903  if (getLangOpts().CPlusPlus)
904  llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
906  << " implicit move constructors created\n";
907  llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
909  << " implicit copy assignment operators created\n";
910  if (getLangOpts().CPlusPlus)
911  llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
913  << " implicit move assignment operators created\n";
914  llvm::errs() << NumImplicitDestructorsDeclared << "/"
916  << " implicit destructors created\n";
917 
918  if (ExternalSource) {
919  llvm::errs() << "\n";
920  ExternalSource->PrintStats();
921  }
922 
923  BumpAlloc.PrintStats();
924 }
925 
927  bool NotifyListeners) {
928  if (NotifyListeners)
929  if (auto *Listener = getASTMutationListener())
931 
932  if (getLangOpts().ModulesLocalVisibility)
933  MergedDefModules[ND].push_back(M);
934  else
936 }
937 
939  auto It = MergedDefModules.find(ND);
940  if (It == MergedDefModules.end())
941  return;
942 
943  auto &Merged = It->second;
945  for (Module *&M : Merged)
946  if (!Found.insert(M).second)
947  M = nullptr;
948  Merged.erase(std::remove(Merged.begin(), Merged.end(), nullptr), Merged.end());
949 }
950 
951 void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
952  if (LazyInitializers.empty())
953  return;
954 
955  auto *Source = Ctx.getExternalSource();
956  assert(Source && "lazy initializers but no external source");
957 
958  auto LazyInits = std::move(LazyInitializers);
959  LazyInitializers.clear();
960 
961  for (auto ID : LazyInits)
962  Initializers.push_back(Source->GetExternalDecl(ID));
963 
964  assert(LazyInitializers.empty() &&
965  "GetExternalDecl for lazy module initializer added more inits");
966 }
967 
969  // One special case: if we add a module initializer that imports another
970  // module, and that module's only initializer is an ImportDecl, simplify.
971  if (const auto *ID = dyn_cast<ImportDecl>(D)) {
972  auto It = ModuleInitializers.find(ID->getImportedModule());
973 
974  // Maybe the ImportDecl does nothing at all. (Common case.)
975  if (It == ModuleInitializers.end())
976  return;
977 
978  // Maybe the ImportDecl only imports another ImportDecl.
979  auto &Imported = *It->second;
980  if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
981  Imported.resolve(*this);
982  auto *OnlyDecl = Imported.Initializers.front();
983  if (isa<ImportDecl>(OnlyDecl))
984  D = OnlyDecl;
985  }
986  }
987 
988  auto *&Inits = ModuleInitializers[M];
989  if (!Inits)
990  Inits = new (*this) PerModuleInitializers;
991  Inits->Initializers.push_back(D);
992 }
993 
995  auto *&Inits = ModuleInitializers[M];
996  if (!Inits)
997  Inits = new (*this) PerModuleInitializers;
998  Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
999  IDs.begin(), IDs.end());
1000 }
1001 
1003  auto It = ModuleInitializers.find(M);
1004  if (It == ModuleInitializers.end())
1005  return None;
1006 
1007  auto *Inits = It->second;
1008  Inits->resolve(*this);
1009  return Inits->Initializers;
1010 }
1011 
1013  if (!ExternCContext)
1014  ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
1015 
1016  return ExternCContext;
1017 }
1018 
1021  const IdentifierInfo *II) const {
1022  auto *BuiltinTemplate = BuiltinTemplateDecl::Create(*this, TUDecl, II, BTK);
1023  BuiltinTemplate->setImplicit();
1024  TUDecl->addDecl(BuiltinTemplate);
1025 
1026  return BuiltinTemplate;
1027 }
1028 
1031  if (!MakeIntegerSeqDecl)
1032  MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq,
1034  return MakeIntegerSeqDecl;
1035 }
1036 
1039  if (!TypePackElementDecl)
1040  TypePackElementDecl = buildBuiltinTemplateDecl(BTK__type_pack_element,
1042  return TypePackElementDecl;
1043 }
1044 
1046  RecordDecl::TagKind TK) const {
1047  SourceLocation Loc;
1048  RecordDecl *NewDecl;
1049  if (getLangOpts().CPlusPlus)
1050  NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
1051  Loc, &Idents.get(Name));
1052  else
1053  NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
1054  &Idents.get(Name));
1055  NewDecl->setImplicit();
1056  NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
1057  const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
1058  return NewDecl;
1059 }
1060 
1062  StringRef Name) const {
1064  TypedefDecl *NewDecl = TypedefDecl::Create(
1065  const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
1066  SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
1067  NewDecl->setImplicit();
1068  return NewDecl;
1069 }
1070 
1072  if (!Int128Decl)
1073  Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
1074  return Int128Decl;
1075 }
1076 
1078  if (!UInt128Decl)
1079  UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
1080  return UInt128Decl;
1081 }
1082 
1083 void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
1084  auto *Ty = new (*this, TypeAlignment) BuiltinType(K);
1085  R = CanQualType::CreateUnsafe(QualType(Ty, 0));
1086  Types.push_back(Ty);
1087 }
1088 
1090  const TargetInfo *AuxTarget) {
1091  assert((!this->Target || this->Target == &Target) &&
1092  "Incorrect target reinitialization");
1093  assert(VoidTy.isNull() && "Context reinitialized?");
1094 
1095  this->Target = &Target;
1096  this->AuxTarget = AuxTarget;
1097 
1098  ABI.reset(createCXXABI(Target));
1099  AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
1100  AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
1101 
1102  // C99 6.2.5p19.
1103  InitBuiltinType(VoidTy, BuiltinType::Void);
1104 
1105  // C99 6.2.5p2.
1106  InitBuiltinType(BoolTy, BuiltinType::Bool);
1107  // C99 6.2.5p3.
1108  if (LangOpts.CharIsSigned)
1109  InitBuiltinType(CharTy, BuiltinType::Char_S);
1110  else
1111  InitBuiltinType(CharTy, BuiltinType::Char_U);
1112  // C99 6.2.5p4.
1113  InitBuiltinType(SignedCharTy, BuiltinType::SChar);
1114  InitBuiltinType(ShortTy, BuiltinType::Short);
1115  InitBuiltinType(IntTy, BuiltinType::Int);
1116  InitBuiltinType(LongTy, BuiltinType::Long);
1117  InitBuiltinType(LongLongTy, BuiltinType::LongLong);
1118 
1119  // C99 6.2.5p6.
1120  InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
1121  InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
1122  InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
1123  InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
1124  InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
1125 
1126  // C99 6.2.5p10.
1127  InitBuiltinType(FloatTy, BuiltinType::Float);
1128  InitBuiltinType(DoubleTy, BuiltinType::Double);
1129  InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
1130 
1131  // GNU extension, __float128 for IEEE quadruple precision
1132  InitBuiltinType(Float128Ty, BuiltinType::Float128);
1133 
1134  // C11 extension ISO/IEC TS 18661-3
1135  InitBuiltinType(Float16Ty, BuiltinType::Float16);
1136 
1137  // ISO/IEC JTC1 SC22 WG14 N1169 Extension
1138  InitBuiltinType(ShortAccumTy, BuiltinType::ShortAccum);
1139  InitBuiltinType(AccumTy, BuiltinType::Accum);
1140  InitBuiltinType(LongAccumTy, BuiltinType::LongAccum);
1141  InitBuiltinType(UnsignedShortAccumTy, BuiltinType::UShortAccum);
1142  InitBuiltinType(UnsignedAccumTy, BuiltinType::UAccum);
1143  InitBuiltinType(UnsignedLongAccumTy, BuiltinType::ULongAccum);
1144  InitBuiltinType(ShortFractTy, BuiltinType::ShortFract);
1145  InitBuiltinType(FractTy, BuiltinType::Fract);
1146  InitBuiltinType(LongFractTy, BuiltinType::LongFract);
1147  InitBuiltinType(UnsignedShortFractTy, BuiltinType::UShortFract);
1148  InitBuiltinType(UnsignedFractTy, BuiltinType::UFract);
1149  InitBuiltinType(UnsignedLongFractTy, BuiltinType::ULongFract);
1150  InitBuiltinType(SatShortAccumTy, BuiltinType::SatShortAccum);
1151  InitBuiltinType(SatAccumTy, BuiltinType::SatAccum);
1152  InitBuiltinType(SatLongAccumTy, BuiltinType::SatLongAccum);
1153  InitBuiltinType(SatUnsignedShortAccumTy, BuiltinType::SatUShortAccum);
1154  InitBuiltinType(SatUnsignedAccumTy, BuiltinType::SatUAccum);
1155  InitBuiltinType(SatUnsignedLongAccumTy, BuiltinType::SatULongAccum);
1156  InitBuiltinType(SatShortFractTy, BuiltinType::SatShortFract);
1157  InitBuiltinType(SatFractTy, BuiltinType::SatFract);
1158  InitBuiltinType(SatLongFractTy, BuiltinType::SatLongFract);
1159  InitBuiltinType(SatUnsignedShortFractTy, BuiltinType::SatUShortFract);
1160  InitBuiltinType(SatUnsignedFractTy, BuiltinType::SatUFract);
1161  InitBuiltinType(SatUnsignedLongFractTy, BuiltinType::SatULongFract);
1162 
1163  // GNU extension, 128-bit integers.
1164  InitBuiltinType(Int128Ty, BuiltinType::Int128);
1165  InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
1166 
1167  // C++ 3.9.1p5
1168  if (TargetInfo::isTypeSigned(Target.getWCharType()))
1169  InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1170  else // -fshort-wchar makes wchar_t be unsigned.
1171  InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1172  if (LangOpts.CPlusPlus && LangOpts.WChar)
1173  WideCharTy = WCharTy;
1174  else {
1175  // C99 (or C++ using -fno-wchar).
1176  WideCharTy = getFromTargetType(Target.getWCharType());
1177  }
1178 
1179  WIntTy = getFromTargetType(Target.getWIntType());
1180 
1181  // C++20 (proposed)
1182  InitBuiltinType(Char8Ty, BuiltinType::Char8);
1183 
1184  if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1185  InitBuiltinType(Char16Ty, BuiltinType::Char16);
1186  else // C99
1187  Char16Ty = getFromTargetType(Target.getChar16Type());
1188 
1189  if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1190  InitBuiltinType(Char32Ty, BuiltinType::Char32);
1191  else // C99
1192  Char32Ty = getFromTargetType(Target.getChar32Type());
1193 
1194  // Placeholder type for type-dependent expressions whose type is
1195  // completely unknown. No code should ever check a type against
1196  // DependentTy and users should never see it; however, it is here to
1197  // help diagnose failures to properly check for type-dependent
1198  // expressions.
1199  InitBuiltinType(DependentTy, BuiltinType::Dependent);
1200 
1201  // Placeholder type for functions.
1202  InitBuiltinType(OverloadTy, BuiltinType::Overload);
1203 
1204  // Placeholder type for bound members.
1205  InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1206 
1207  // Placeholder type for pseudo-objects.
1208  InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1209 
1210  // "any" type; useful for debugger-like clients.
1211  InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1212 
1213  // Placeholder type for unbridged ARC casts.
1214  InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1215 
1216  // Placeholder type for builtin functions.
1217  InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1218 
1219  // Placeholder type for OMP array sections.
1220  if (LangOpts.OpenMP)
1221  InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection);
1222 
1223  // C99 6.2.5p11.
1228 
1229  // Builtin types for 'id', 'Class', and 'SEL'.
1230  InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1231  InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
1232  InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
1233 
1234  if (LangOpts.OpenCL) {
1235 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1236  InitBuiltinType(SingletonId, BuiltinType::Id);
1237 #include "clang/Basic/OpenCLImageTypes.def"
1238 
1239  InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
1240  InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
1241  InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1242  InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
1243  InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
1244  }
1245 
1246  // Builtin type for __objc_yes and __objc_no
1247  ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1248  SignedCharTy : BoolTy);
1249 
1250  ObjCConstantStringType = QualType();
1251 
1252  ObjCSuperType = QualType();
1253 
1254  // void * type
1255  if (LangOpts.OpenCLVersion >= 200) {
1256  auto Q = VoidTy.getQualifiers();
1260  } else {
1262  }
1263 
1264  // nullptr type (C++0x 2.14.7)
1265  InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
1266 
1267  // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1268  InitBuiltinType(HalfTy, BuiltinType::Half);
1269 
1270  // Builtin type used to help define __builtin_va_list.
1271  VaListTagDecl = nullptr;
1272 }
1273 
1275  return SourceMgr.getDiagnostics();
1276 }
1277 
1279  AttrVec *&Result = DeclAttrs[D];
1280  if (!Result) {
1281  void *Mem = Allocate(sizeof(AttrVec));
1282  Result = new (Mem) AttrVec;
1283  }
1284 
1285  return *Result;
1286 }
1287 
1288 /// Erase the attributes corresponding to the given declaration.
1290  llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1291  if (Pos != DeclAttrs.end()) {
1292  Pos->second->~AttrVec();
1293  DeclAttrs.erase(Pos);
1294  }
1295 }
1296 
1297 // FIXME: Remove ?
1300  assert(Var->isStaticDataMember() && "Not a static data member");
1302  .dyn_cast<MemberSpecializationInfo *>();
1303 }
1304 
1307  llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1308  TemplateOrInstantiation.find(Var);
1309  if (Pos == TemplateOrInstantiation.end())
1310  return {};
1311 
1312  return Pos->second;
1313 }
1314 
1315 void
1318  SourceLocation PointOfInstantiation) {
1319  assert(Inst->isStaticDataMember() && "Not a static data member");
1320  assert(Tmpl->isStaticDataMember() && "Not a static data member");
1322  Tmpl, TSK, PointOfInstantiation));
1323 }
1324 
1325 void
1328  assert(!TemplateOrInstantiation[Inst] &&
1329  "Already noted what the variable was instantiated from");
1330  TemplateOrInstantiation[Inst] = TSI;
1331 }
1332 
1334  const FunctionDecl *FD){
1335  assert(FD && "Specialization is 0");
1336  llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
1337  = ClassScopeSpecializationPattern.find(FD);
1338  if (Pos == ClassScopeSpecializationPattern.end())
1339  return nullptr;
1340 
1341  return Pos->second;
1342 }
1343 
1345  FunctionDecl *Pattern) {
1346  assert(FD && "Specialization is 0");
1347  assert(Pattern && "Class scope specialization pattern is 0");
1348  ClassScopeSpecializationPattern[FD] = Pattern;
1349 }
1350 
1351 NamedDecl *
1353  auto Pos = InstantiatedFromUsingDecl.find(UUD);
1354  if (Pos == InstantiatedFromUsingDecl.end())
1355  return nullptr;
1356 
1357  return Pos->second;
1358 }
1359 
1360 void
1362  assert((isa<UsingDecl>(Pattern) ||
1363  isa<UnresolvedUsingValueDecl>(Pattern) ||
1364  isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1365  "pattern decl is not a using decl");
1366  assert((isa<UsingDecl>(Inst) ||
1367  isa<UnresolvedUsingValueDecl>(Inst) ||
1368  isa<UnresolvedUsingTypenameDecl>(Inst)) &&
1369  "instantiation did not produce a using decl");
1370  assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1371  InstantiatedFromUsingDecl[Inst] = Pattern;
1372 }
1373 
1376  llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1377  = InstantiatedFromUsingShadowDecl.find(Inst);
1378  if (Pos == InstantiatedFromUsingShadowDecl.end())
1379  return nullptr;
1380 
1381  return Pos->second;
1382 }
1383 
1384 void
1386  UsingShadowDecl *Pattern) {
1387  assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1388  InstantiatedFromUsingShadowDecl[Inst] = Pattern;
1389 }
1390 
1392  llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1393  = InstantiatedFromUnnamedFieldDecl.find(Field);
1394  if (Pos == InstantiatedFromUnnamedFieldDecl.end())
1395  return nullptr;
1396 
1397  return Pos->second;
1398 }
1399 
1401  FieldDecl *Tmpl) {
1402  assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1403  assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1404  assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1405  "Already noted what unnamed field was instantiated from");
1406 
1407  InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1408 }
1409 
1412  return overridden_methods(Method).begin();
1413 }
1414 
1417  return overridden_methods(Method).end();
1418 }
1419 
1420 unsigned
1422  auto Range = overridden_methods(Method);
1423  return Range.end() - Range.begin();
1424 }
1425 
1428  llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1429  OverriddenMethods.find(Method->getCanonicalDecl());
1430  if (Pos == OverriddenMethods.end())
1431  return overridden_method_range(nullptr, nullptr);
1432  return overridden_method_range(Pos->second.begin(), Pos->second.end());
1433 }
1434 
1436  const CXXMethodDecl *Overridden) {
1437  assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
1438  OverriddenMethods[Method].push_back(Overridden);
1439 }
1440 
1442  const NamedDecl *D,
1443  SmallVectorImpl<const NamedDecl *> &Overridden) const {
1444  assert(D);
1445 
1446  if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
1447  Overridden.append(overridden_methods_begin(CXXMethod),
1448  overridden_methods_end(CXXMethod));
1449  return;
1450  }
1451 
1452  const auto *Method = dyn_cast<ObjCMethodDecl>(D);
1453  if (!Method)
1454  return;
1455 
1457  Method->getOverriddenMethods(OverDecls);
1458  Overridden.append(OverDecls.begin(), OverDecls.end());
1459 }
1460 
1462  assert(!Import->NextLocalImport && "Import declaration already in the chain");
1463  assert(!Import->isFromASTFile() && "Non-local import declaration");
1464  if (!FirstLocalImport) {
1465  FirstLocalImport = Import;
1466  LastLocalImport = Import;
1467  return;
1468  }
1469 
1470  LastLocalImport->NextLocalImport = Import;
1471  LastLocalImport = Import;
1472 }
1473 
1474 //===----------------------------------------------------------------------===//
1475 // Type Sizing and Analysis
1476 //===----------------------------------------------------------------------===//
1477 
1478 /// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1479 /// scalar floating point type.
1480 const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
1481  const auto *BT = T->getAs<BuiltinType>();
1482  assert(BT && "Not a floating point type!");
1483  switch (BT->getKind()) {
1484  default: llvm_unreachable("Not a floating point type!");
1485  case BuiltinType::Float16:
1486  case BuiltinType::Half:
1487  return Target->getHalfFormat();
1488  case BuiltinType::Float: return Target->getFloatFormat();
1489  case BuiltinType::Double: return Target->getDoubleFormat();
1490  case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
1491  case BuiltinType::Float128: return Target->getFloat128Format();
1492  }
1493 }
1494 
1495 CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
1496  unsigned Align = Target->getCharWidth();
1497 
1498  bool UseAlignAttrOnly = false;
1499  if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1500  Align = AlignFromAttr;
1501 
1502  // __attribute__((aligned)) can increase or decrease alignment
1503  // *except* on a struct or struct member, where it only increases
1504  // alignment unless 'packed' is also specified.
1505  //
1506  // It is an error for alignas to decrease alignment, so we can
1507  // ignore that possibility; Sema should diagnose it.
1508  if (isa<FieldDecl>(D)) {
1509  UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1510  cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1511  } else {
1512  UseAlignAttrOnly = true;
1513  }
1514  }
1515  else if (isa<FieldDecl>(D))
1516  UseAlignAttrOnly =
1517  D->hasAttr<PackedAttr>() ||
1518  cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1519 
1520  // If we're using the align attribute only, just ignore everything
1521  // else about the declaration and its type.
1522  if (UseAlignAttrOnly) {
1523  // do nothing
1524  } else if (const auto *VD = dyn_cast<ValueDecl>(D)) {
1525  QualType T = VD->getType();
1526  if (const auto *RT = T->getAs<ReferenceType>()) {
1527  if (ForAlignof)
1528  T = RT->getPointeeType();
1529  else
1530  T = getPointerType(RT->getPointeeType());
1531  }
1532  QualType BaseT = getBaseElementType(T);
1533  if (T->isFunctionType())
1534  Align = getTypeInfoImpl(T.getTypePtr()).Align;
1535  else if (!BaseT->isIncompleteType()) {
1536  // Adjust alignments of declarations with array type by the
1537  // large-array alignment on the target.
1538  if (const ArrayType *arrayType = getAsArrayType(T)) {
1539  unsigned MinWidth = Target->getLargeArrayMinWidth();
1540  if (!ForAlignof && MinWidth) {
1541  if (isa<VariableArrayType>(arrayType))
1542  Align = std::max(Align, Target->getLargeArrayAlign());
1543  else if (isa<ConstantArrayType>(arrayType) &&
1544  MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1545  Align = std::max(Align, Target->getLargeArrayAlign());
1546  }
1547  }
1548  Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
1549  if (BaseT.getQualifiers().hasUnaligned())
1550  Align = Target->getCharWidth();
1551  if (const auto *VD = dyn_cast<VarDecl>(D)) {
1552  if (VD->hasGlobalStorage() && !ForAlignof)
1553  Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1554  }
1555  }
1556 
1557  // Fields can be subject to extra alignment constraints, like if
1558  // the field is packed, the struct is packed, or the struct has a
1559  // a max-field-alignment constraint (#pragma pack). So calculate
1560  // the actual alignment of the field within the struct, and then
1561  // (as we're expected to) constrain that by the alignment of the type.
1562  if (const auto *Field = dyn_cast<FieldDecl>(VD)) {
1563  const RecordDecl *Parent = Field->getParent();
1564  // We can only produce a sensible answer if the record is valid.
1565  if (!Parent->isInvalidDecl()) {
1566  const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
1567 
1568  // Start with the record's overall alignment.
1569  unsigned FieldAlign = toBits(Layout.getAlignment());
1570 
1571  // Use the GCD of that and the offset within the record.
1572  uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1573  if (Offset > 0) {
1574  // Alignment is always a power of 2, so the GCD will be a power of 2,
1575  // which means we get to do this crazy thing instead of Euclid's.
1576  uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1577  if (LowBitOfOffset < FieldAlign)
1578  FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1579  }
1580 
1581  Align = std::min(Align, FieldAlign);
1582  }
1583  }
1584  }
1585 
1586  return toCharUnitsFromBits(Align);
1587 }
1588 
1589 // getTypeInfoDataSizeInChars - Return the size of a type, in
1590 // chars. If the type is a record, its data size is returned. This is
1591 // the size of the memcpy that's performed when assigning this type
1592 // using a trivial copy/move assignment operator.
1593 std::pair<CharUnits, CharUnits>
1595  std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1596 
1597  // In C++, objects can sometimes be allocated into the tail padding
1598  // of a base-class subobject. We decide whether that's possible
1599  // during class layout, so here we can just trust the layout results.
1600  if (getLangOpts().CPlusPlus) {
1601  if (const auto *RT = T->getAs<RecordType>()) {
1602  const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1603  sizeAndAlign.first = layout.getDataSize();
1604  }
1605  }
1606 
1607  return sizeAndAlign;
1608 }
1609 
1610 /// getConstantArrayInfoInChars - Performing the computation in CharUnits
1611 /// instead of in bits prevents overflowing the uint64_t for some large arrays.
1612 std::pair<CharUnits, CharUnits>
1614  const ConstantArrayType *CAT) {
1615  std::pair<CharUnits, CharUnits> EltInfo =
1616  Context.getTypeInfoInChars(CAT->getElementType());
1617  uint64_t Size = CAT->getSize().getZExtValue();
1618  assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1619  (uint64_t)(-1)/Size) &&
1620  "Overflow in array type char size evaluation");
1621  uint64_t Width = EltInfo.first.getQuantity() * Size;
1622  unsigned Align = EltInfo.second.getQuantity();
1623  if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1624  Context.getTargetInfo().getPointerWidth(0) == 64)
1625  Width = llvm::alignTo(Width, Align);
1626  return std::make_pair(CharUnits::fromQuantity(Width),
1627  CharUnits::fromQuantity(Align));
1628 }
1629 
1630 std::pair<CharUnits, CharUnits>
1632  if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
1633  return getConstantArrayInfoInChars(*this, CAT);
1634  TypeInfo Info = getTypeInfo(T);
1635  return std::make_pair(toCharUnitsFromBits(Info.Width),
1636  toCharUnitsFromBits(Info.Align));
1637 }
1638 
1639 std::pair<CharUnits, CharUnits>
1641  return getTypeInfoInChars(T.getTypePtr());
1642 }
1643 
1645  return getTypeInfo(T).AlignIsRequired;
1646 }
1647 
1649  return isAlignmentRequired(T.getTypePtr());
1650 }
1651 
1653  // An alignment on a typedef overrides anything else.
1654  if (const auto *TT = T->getAs<TypedefType>())
1655  if (unsigned Align = TT->getDecl()->getMaxAlignment())
1656  return Align;
1657 
1658  // If we have an (array of) complete type, we're done.
1659  T = getBaseElementType(T);
1660  if (!T->isIncompleteType())
1661  return getTypeAlign(T);
1662 
1663  // If we had an array type, its element type might be a typedef
1664  // type with an alignment attribute.
1665  if (const auto *TT = T->getAs<TypedefType>())
1666  if (unsigned Align = TT->getDecl()->getMaxAlignment())
1667  return Align;
1668 
1669  // Otherwise, see if the declaration of the type had an attribute.
1670  if (const auto *TT = T->getAs<TagType>())
1671  return TT->getDecl()->getMaxAlignment();
1672 
1673  return 0;
1674 }
1675 
1677  TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1678  if (I != MemoizedTypeInfo.end())
1679  return I->second;
1680 
1681  // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1682  TypeInfo TI = getTypeInfoImpl(T);
1683  MemoizedTypeInfo[T] = TI;
1684  return TI;
1685 }
1686 
1687 /// getTypeInfoImpl - Return the size of the specified type, in bits. This
1688 /// method does not work on incomplete types.
1689 ///
1690 /// FIXME: Pointers into different addr spaces could have different sizes and
1691 /// alignment requirements: getPointerInfo should take an AddrSpace, this
1692 /// should take a QualType, &c.
1693 TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1694  uint64_t Width = 0;
1695  unsigned Align = 8;
1696  bool AlignIsRequired = false;
1697  unsigned AS = 0;
1698  switch (T->getTypeClass()) {
1699 #define TYPE(Class, Base)
1700 #define ABSTRACT_TYPE(Class, Base)
1701 #define NON_CANONICAL_TYPE(Class, Base)
1702 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
1703 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1704  case Type::Class: \
1705  assert(!T->isDependentType() && "should not see dependent types here"); \
1706  return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
1707 #include "clang/AST/TypeNodes.def"
1708  llvm_unreachable("Should not see dependent types");
1709 
1710  case Type::FunctionNoProto:
1711  case Type::FunctionProto:
1712  // GCC extension: alignof(function) = 32 bits
1713  Width = 0;
1714  Align = 32;
1715  break;
1716 
1717  case Type::IncompleteArray:
1718  case Type::VariableArray:
1719  Width = 0;
1720  Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1721  break;
1722 
1723  case Type::ConstantArray: {
1724  const auto *CAT = cast<ConstantArrayType>(T);
1725 
1726  TypeInfo EltInfo = getTypeInfo(CAT->getElementType());
1727  uint64_t Size = CAT->getSize().getZExtValue();
1728  assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
1729  "Overflow in array type bit size evaluation");
1730  Width = EltInfo.Width * Size;
1731  Align = EltInfo.Align;
1732  if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1733  getTargetInfo().getPointerWidth(0) == 64)
1734  Width = llvm::alignTo(Width, Align);
1735  break;
1736  }
1737  case Type::ExtVector:
1738  case Type::Vector: {
1739  const auto *VT = cast<VectorType>(T);
1740  TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1741  Width = EltInfo.Width * VT->getNumElements();
1742  Align = Width;
1743  // If the alignment is not a power of 2, round up to the next power of 2.
1744  // This happens for non-power-of-2 length vectors.
1745  if (Align & (Align-1)) {
1746  Align = llvm::NextPowerOf2(Align);
1747  Width = llvm::alignTo(Width, Align);
1748  }
1749  // Adjust the alignment based on the target max.
1750  uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1751  if (TargetVectorAlign && TargetVectorAlign < Align)
1752  Align = TargetVectorAlign;
1753  break;
1754  }
1755 
1756  case Type::Builtin:
1757  switch (cast<BuiltinType>(T)->getKind()) {
1758  default: llvm_unreachable("Unknown builtin type!");
1759  case BuiltinType::Void:
1760  // GCC extension: alignof(void) = 8 bits.
1761  Width = 0;
1762  Align = 8;
1763  break;
1764  case BuiltinType::Bool:
1765  Width = Target->getBoolWidth();
1766  Align = Target->getBoolAlign();
1767  break;
1768  case BuiltinType::Char_S:
1769  case BuiltinType::Char_U:
1770  case BuiltinType::UChar:
1771  case BuiltinType::SChar:
1772  case BuiltinType::Char8:
1773  Width = Target->getCharWidth();
1774  Align = Target->getCharAlign();
1775  break;
1776  case BuiltinType::WChar_S:
1777  case BuiltinType::WChar_U:
1778  Width = Target->getWCharWidth();
1779  Align = Target->getWCharAlign();
1780  break;
1781  case BuiltinType::Char16:
1782  Width = Target->getChar16Width();
1783  Align = Target->getChar16Align();
1784  break;
1785  case BuiltinType::Char32:
1786  Width = Target->getChar32Width();
1787  Align = Target->getChar32Align();
1788  break;
1789  case BuiltinType::UShort:
1790  case BuiltinType::Short:
1791  Width = Target->getShortWidth();
1792  Align = Target->getShortAlign();
1793  break;
1794  case BuiltinType::UInt:
1795  case BuiltinType::Int:
1796  Width = Target->getIntWidth();
1797  Align = Target->getIntAlign();
1798  break;
1799  case BuiltinType::ULong:
1800  case BuiltinType::Long:
1801  Width = Target->getLongWidth();
1802  Align = Target->getLongAlign();
1803  break;
1804  case BuiltinType::ULongLong:
1805  case BuiltinType::LongLong:
1806  Width = Target->getLongLongWidth();
1807  Align = Target->getLongLongAlign();
1808  break;
1809  case BuiltinType::Int128:
1810  case BuiltinType::UInt128:
1811  Width = 128;
1812  Align = 128; // int128_t is 128-bit aligned on all targets.
1813  break;
1814  case BuiltinType::ShortAccum:
1815  case BuiltinType::UShortAccum:
1816  case BuiltinType::SatShortAccum:
1817  case BuiltinType::SatUShortAccum:
1818  Width = Target->getShortAccumWidth();
1819  Align = Target->getShortAccumAlign();
1820  break;
1821  case BuiltinType::Accum:
1822  case BuiltinType::UAccum:
1823  case BuiltinType::SatAccum:
1824  case BuiltinType::SatUAccum:
1825  Width = Target->getAccumWidth();
1826  Align = Target->getAccumAlign();
1827  break;
1828  case BuiltinType::LongAccum:
1829  case BuiltinType::ULongAccum:
1830  case BuiltinType::SatLongAccum:
1831  case BuiltinType::SatULongAccum:
1832  Width = Target->getLongAccumWidth();
1833  Align = Target->getLongAccumAlign();
1834  break;
1835  case BuiltinType::ShortFract:
1836  case BuiltinType::UShortFract:
1837  case BuiltinType::SatShortFract:
1838  case BuiltinType::SatUShortFract:
1839  Width = Target->getShortFractWidth();
1840  Align = Target->getShortFractAlign();
1841  break;
1842  case BuiltinType::Fract:
1843  case BuiltinType::UFract:
1844  case BuiltinType::SatFract:
1845  case BuiltinType::SatUFract:
1846  Width = Target->getFractWidth();
1847  Align = Target->getFractAlign();
1848  break;
1849  case BuiltinType::LongFract:
1850  case BuiltinType::ULongFract:
1851  case BuiltinType::SatLongFract:
1852  case BuiltinType::SatULongFract:
1853  Width = Target->getLongFractWidth();
1854  Align = Target->getLongFractAlign();
1855  break;
1856  case BuiltinType::Float16:
1857  case BuiltinType::Half:
1858  Width = Target->getHalfWidth();
1859  Align = Target->getHalfAlign();
1860  break;
1861  case BuiltinType::Float:
1862  Width = Target->getFloatWidth();
1863  Align = Target->getFloatAlign();
1864  break;
1865  case BuiltinType::Double:
1866  Width = Target->getDoubleWidth();
1867  Align = Target->getDoubleAlign();
1868  break;
1869  case BuiltinType::LongDouble:
1870  Width = Target->getLongDoubleWidth();
1871  Align = Target->getLongDoubleAlign();
1872  break;
1873  case BuiltinType::Float128:
1874  Width = Target->getFloat128Width();
1875  Align = Target->getFloat128Align();
1876  break;
1877  case BuiltinType::NullPtr:
1878  Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1879  Align = Target->getPointerAlign(0); // == sizeof(void*)
1880  break;
1881  case BuiltinType::ObjCId:
1882  case BuiltinType::ObjCClass:
1883  case BuiltinType::ObjCSel:
1884  Width = Target->getPointerWidth(0);
1885  Align = Target->getPointerAlign(0);
1886  break;
1887  case BuiltinType::OCLSampler:
1888  case BuiltinType::OCLEvent:
1889  case BuiltinType::OCLClkEvent:
1890  case BuiltinType::OCLQueue:
1891  case BuiltinType::OCLReserveID:
1892 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1893  case BuiltinType::Id:
1894 #include "clang/Basic/OpenCLImageTypes.def"
1895  AS = getTargetAddressSpace(
1897  Width = Target->getPointerWidth(AS);
1898  Align = Target->getPointerAlign(AS);
1899  break;
1900  }
1901  break;
1902  case Type::ObjCObjectPointer:
1903  Width = Target->getPointerWidth(0);
1904  Align = Target->getPointerAlign(0);
1905  break;
1906  case Type::BlockPointer:
1907  AS = getTargetAddressSpace(cast<BlockPointerType>(T)->getPointeeType());
1908  Width = Target->getPointerWidth(AS);
1909  Align = Target->getPointerAlign(AS);
1910  break;
1911  case Type::LValueReference:
1912  case Type::RValueReference:
1913  // alignof and sizeof should never enter this code path here, so we go
1914  // the pointer route.
1915  AS = getTargetAddressSpace(cast<ReferenceType>(T)->getPointeeType());
1916  Width = Target->getPointerWidth(AS);
1917  Align = Target->getPointerAlign(AS);
1918  break;
1919  case Type::Pointer:
1920  AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
1921  Width = Target->getPointerWidth(AS);
1922  Align = Target->getPointerAlign(AS);
1923  break;
1924  case Type::MemberPointer: {
1925  const auto *MPT = cast<MemberPointerType>(T);
1926  CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT);
1927  Width = MPI.Width;
1928  Align = MPI.Align;
1929  break;
1930  }
1931  case Type::Complex: {
1932  // Complex types have the same alignment as their elements, but twice the
1933  // size.
1934  TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
1935  Width = EltInfo.Width * 2;
1936  Align = EltInfo.Align;
1937  break;
1938  }
1939  case Type::ObjCObject:
1940  return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
1941  case Type::Adjusted:
1942  case Type::Decayed:
1943  return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
1944  case Type::ObjCInterface: {
1945  const auto *ObjCI = cast<ObjCInterfaceType>(T);
1946  const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
1947  Width = toBits(Layout.getSize());
1948  Align = toBits(Layout.getAlignment());
1949  break;
1950  }
1951  case Type::Record:
1952  case Type::Enum: {
1953  const auto *TT = cast<TagType>(T);
1954 
1955  if (TT->getDecl()->isInvalidDecl()) {
1956  Width = 8;
1957  Align = 8;
1958  break;
1959  }
1960 
1961  if (const auto *ET = dyn_cast<EnumType>(TT)) {
1962  const EnumDecl *ED = ET->getDecl();
1963  TypeInfo Info =
1965  if (unsigned AttrAlign = ED->getMaxAlignment()) {
1966  Info.Align = AttrAlign;
1967  Info.AlignIsRequired = true;
1968  }
1969  return Info;
1970  }
1971 
1972  const auto *RT = cast<RecordType>(TT);
1973  const RecordDecl *RD = RT->getDecl();
1974  const ASTRecordLayout &Layout = getASTRecordLayout(RD);
1975  Width = toBits(Layout.getSize());
1976  Align = toBits(Layout.getAlignment());
1977  AlignIsRequired = RD->hasAttr<AlignedAttr>();
1978  break;
1979  }
1980 
1981  case Type::SubstTemplateTypeParm:
1982  return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1983  getReplacementType().getTypePtr());
1984 
1985  case Type::Auto:
1986  case Type::DeducedTemplateSpecialization: {
1987  const auto *A = cast<DeducedType>(T);
1988  assert(!A->getDeducedType().isNull() &&
1989  "cannot request the size of an undeduced or dependent auto type");
1990  return getTypeInfo(A->getDeducedType().getTypePtr());
1991  }
1992 
1993  case Type::Paren:
1994  return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1995 
1996  case Type::ObjCTypeParam:
1997  return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr());
1998 
1999  case Type::Typedef: {
2000  const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
2001  TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
2002  // If the typedef has an aligned attribute on it, it overrides any computed
2003  // alignment we have. This violates the GCC documentation (which says that
2004  // attribute(aligned) can only round up) but matches its implementation.
2005  if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
2006  Align = AttrAlign;
2007  AlignIsRequired = true;
2008  } else {
2009  Align = Info.Align;
2010  AlignIsRequired = Info.AlignIsRequired;
2011  }
2012  Width = Info.Width;
2013  break;
2014  }
2015 
2016  case Type::Elaborated:
2017  return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
2018 
2019  case Type::Attributed:
2020  return getTypeInfo(
2021  cast<AttributedType>(T)->getEquivalentType().getTypePtr());
2022 
2023  case Type::Atomic: {
2024  // Start with the base type information.
2025  TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
2026  Width = Info.Width;
2027  Align = Info.Align;
2028 
2029  if (!Width) {
2030  // An otherwise zero-sized type should still generate an
2031  // atomic operation.
2032  Width = Target->getCharWidth();
2033  assert(Align);
2034  } else if (Width <= Target->getMaxAtomicPromoteWidth()) {
2035  // If the size of the type doesn't exceed the platform's max
2036  // atomic promotion width, make the size and alignment more
2037  // favorable to atomic operations:
2038 
2039  // Round the size up to a power of 2.
2040  if (!llvm::isPowerOf2_64(Width))
2041  Width = llvm::NextPowerOf2(Width);
2042 
2043  // Set the alignment equal to the size.
2044  Align = static_cast<unsigned>(Width);
2045  }
2046  }
2047  break;
2048 
2049  case Type::Pipe:
2052  break;
2053  }
2054 
2055  assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
2056  return TypeInfo(Width, Align, AlignIsRequired);
2057 }
2058 
2059 unsigned ASTContext::getTypeUnadjustedAlign(const Type *T) const {
2060  UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(T);
2061  if (I != MemoizedUnadjustedAlign.end())
2062  return I->second;
2063 
2064  unsigned UnadjustedAlign;
2065  if (const auto *RT = T->getAs<RecordType>()) {
2066  const RecordDecl *RD = RT->getDecl();
2067  const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2068  UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2069  } else if (const auto *ObjCI = T->getAs<ObjCInterfaceType>()) {
2070  const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2071  UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2072  } else {
2073  UnadjustedAlign = getTypeAlign(T);
2074  }
2075 
2076  MemoizedUnadjustedAlign[T] = UnadjustedAlign;
2077  return UnadjustedAlign;
2078 }
2079 
2081  unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign();
2082  // Target ppc64 with QPX: simd default alignment for pointer to double is 32.
2083  if ((getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64 ||
2084  getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64le) &&
2085  getTargetInfo().getABI() == "elfv1-qpx" &&
2086  T->isSpecificBuiltinType(BuiltinType::Double))
2087  SimdAlign = 256;
2088  return SimdAlign;
2089 }
2090 
2091 /// toCharUnitsFromBits - Convert a size in bits to a size in characters.
2093  return CharUnits::fromQuantity(BitSize / getCharWidth());
2094 }
2095 
2096 /// toBits - Convert a size in characters to a size in characters.
2097 int64_t ASTContext::toBits(CharUnits CharSize) const {
2098  return CharSize.getQuantity() * getCharWidth();
2099 }
2100 
2101 /// getTypeSizeInChars - Return the size of the specified type, in characters.
2102 /// This method does not work on incomplete types.
2104  return getTypeInfoInChars(T).first;
2105 }
2107  return getTypeInfoInChars(T).first;
2108 }
2109 
2110 /// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
2111 /// characters. This method does not work on incomplete types.
2113  return toCharUnitsFromBits(getTypeAlign(T));
2114 }
2116  return toCharUnitsFromBits(getTypeAlign(T));
2117 }
2118 
2119 /// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a
2120 /// type, in characters, before alignment adustments. This method does
2121 /// not work on incomplete types.
2124 }
2127 }
2128 
2129 /// getPreferredTypeAlign - Return the "preferred" alignment of the specified
2130 /// type for the current target in bits. This can be different than the ABI
2131 /// alignment in cases where it is beneficial for performance to overalign
2132 /// a data type.
2133 unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
2134  TypeInfo TI = getTypeInfo(T);
2135  unsigned ABIAlign = TI.Align;
2136 
2137  T = T->getBaseElementTypeUnsafe();
2138 
2139  // The preferred alignment of member pointers is that of a pointer.
2140  if (T->isMemberPointerType())
2142 
2143  if (!Target->allowsLargerPreferedTypeAlignment())
2144  return ABIAlign;
2145 
2146  // Double and long long should be naturally aligned if possible.
2147  if (const auto *CT = T->getAs<ComplexType>())
2148  T = CT->getElementType().getTypePtr();
2149  if (const auto *ET = T->getAs<EnumType>())
2150  T = ET->getDecl()->getIntegerType().getTypePtr();
2151  if (T->isSpecificBuiltinType(BuiltinType::Double) ||
2152  T->isSpecificBuiltinType(BuiltinType::LongLong) ||
2153  T->isSpecificBuiltinType(BuiltinType::ULongLong))
2154  // Don't increase the alignment if an alignment attribute was specified on a
2155  // typedef declaration.
2156  if (!TI.AlignIsRequired)
2157  return std::max(ABIAlign, (unsigned)getTypeSize(T));
2158 
2159  return ABIAlign;
2160 }
2161 
2162 /// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2163 /// for __attribute__((aligned)) on this target, to be used if no alignment
2164 /// value is specified.
2167 }
2168 
2169 /// getAlignOfGlobalVar - Return the alignment in bits that should be given
2170 /// to a global variable of the specified type.
2172  return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
2173 }
2174 
2175 /// getAlignOfGlobalVarInChars - Return the alignment in characters that
2176 /// should be given to a global variable of the specified type.
2179 }
2180 
2183  const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
2184  while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2185  Offset += Layout->getBaseClassOffset(Base);
2186  Layout = &getASTRecordLayout(Base);
2187  }
2188  return Offset;
2189 }
2190 
2191 /// DeepCollectObjCIvars -
2192 /// This routine first collects all declared, but not synthesized, ivars in
2193 /// super class and then collects all ivars, including those synthesized for
2194 /// current class. This routine is used for implementation of current class
2195 /// when all ivars, declared and synthesized are known.
2197  bool leafClass,
2198  SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
2199  if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2200  DeepCollectObjCIvars(SuperClass, false, Ivars);
2201  if (!leafClass) {
2202  for (const auto *I : OI->ivars())
2203  Ivars.push_back(I);
2204  } else {
2205  auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
2206  for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
2207  Iv= Iv->getNextIvar())
2208  Ivars.push_back(Iv);
2209  }
2210 }
2211 
2212 /// CollectInheritedProtocols - Collect all protocols in current class and
2213 /// those inherited by it.
2215  llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
2216  if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
2217  // We can use protocol_iterator here instead of
2218  // all_referenced_protocol_iterator since we are walking all categories.
2219  for (auto *Proto : OI->all_referenced_protocols()) {
2220  CollectInheritedProtocols(Proto, Protocols);
2221  }
2222 
2223  // Categories of this Interface.
2224  for (const auto *Cat : OI->visible_categories())
2225  CollectInheritedProtocols(Cat, Protocols);
2226 
2227  if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2228  while (SD) {
2229  CollectInheritedProtocols(SD, Protocols);
2230  SD = SD->getSuperClass();
2231  }
2232  } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
2233  for (auto *Proto : OC->protocols()) {
2234  CollectInheritedProtocols(Proto, Protocols);
2235  }
2236  } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
2237  // Insert the protocol.
2238  if (!Protocols.insert(
2239  const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2240  return;
2241 
2242  for (auto *Proto : OP->protocols())
2243  CollectInheritedProtocols(Proto, Protocols);
2244  }
2245 }
2246 
2248  const RecordDecl *RD) {
2249  assert(RD->isUnion() && "Must be union type");
2250  CharUnits UnionSize = Context.getTypeSizeInChars(RD->getTypeForDecl());
2251 
2252  for (const auto *Field : RD->fields()) {
2253  if (!Context.hasUniqueObjectRepresentations(Field->getType()))
2254  return false;
2255  CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType());
2256  if (FieldSize != UnionSize)
2257  return false;
2258  }
2259  return !RD->field_empty();
2260 }
2261 
2262 static bool isStructEmpty(QualType Ty) {
2263  const RecordDecl *RD = Ty->castAs<RecordType>()->getDecl();
2264 
2265  if (!RD->field_empty())
2266  return false;
2267 
2268  if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD))
2269  return ClassDecl->isEmpty();
2270 
2271  return true;
2272 }
2273 
2276  const RecordDecl *RD) {
2277  assert(!RD->isUnion() && "Must be struct/class type");
2278  const auto &Layout = Context.getASTRecordLayout(RD);
2279 
2280  int64_t CurOffsetInBits = 0;
2281  if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) {
2282  if (ClassDecl->isDynamicClass())
2283  return llvm::None;
2284 
2286  for (const auto Base : ClassDecl->bases()) {
2287  // Empty types can be inherited from, and non-empty types can potentially
2288  // have tail padding, so just make sure there isn't an error.
2289  if (!isStructEmpty(Base.getType())) {
2291  Context, Base.getType()->getAs<RecordType>()->getDecl());
2292  if (!Size)
2293  return llvm::None;
2294  Bases.emplace_back(Base.getType(), Size.getValue());
2295  }
2296  }
2297 
2298  llvm::sort(
2299  Bases.begin(), Bases.end(), [&](const std::pair<QualType, int64_t> &L,
2300  const std::pair<QualType, int64_t> &R) {
2301  return Layout.getBaseClassOffset(L.first->getAsCXXRecordDecl()) <
2302  Layout.getBaseClassOffset(R.first->getAsCXXRecordDecl());
2303  });
2304 
2305  for (const auto Base : Bases) {
2306  int64_t BaseOffset = Context.toBits(
2307  Layout.getBaseClassOffset(Base.first->getAsCXXRecordDecl()));
2308  int64_t BaseSize = Base.second;
2309  if (BaseOffset != CurOffsetInBits)
2310  return llvm::None;
2311  CurOffsetInBits = BaseOffset + BaseSize;
2312  }
2313  }
2314 
2315  for (const auto *Field : RD->fields()) {
2316  if (!Field->getType()->isReferenceType() &&
2317  !Context.hasUniqueObjectRepresentations(Field->getType()))
2318  return llvm::None;
2319 
2320  int64_t FieldSizeInBits =
2321  Context.toBits(Context.getTypeSizeInChars(Field->getType()));
2322  if (Field->isBitField()) {
2323  int64_t BitfieldSize = Field->getBitWidthValue(Context);
2324 
2325  if (BitfieldSize > FieldSizeInBits)
2326  return llvm::None;
2327  FieldSizeInBits = BitfieldSize;
2328  }
2329 
2330  int64_t FieldOffsetInBits = Context.getFieldOffset(Field);
2331 
2332  if (FieldOffsetInBits != CurOffsetInBits)
2333  return llvm::None;
2334 
2335  CurOffsetInBits = FieldSizeInBits + FieldOffsetInBits;
2336  }
2337 
2338  return CurOffsetInBits;
2339 }
2340 
2342  // C++17 [meta.unary.prop]:
2343  // The predicate condition for a template specialization
2344  // has_unique_object_representations<T> shall be
2345  // satisfied if and only if:
2346  // (9.1) - T is trivially copyable, and
2347  // (9.2) - any two objects of type T with the same value have the same
2348  // object representation, where two objects
2349  // of array or non-union class type are considered to have the same value
2350  // if their respective sequences of
2351  // direct subobjects have the same values, and two objects of union type
2352  // are considered to have the same
2353  // value if they have the same active member and the corresponding members
2354  // have the same value.
2355  // The set of scalar types for which this condition holds is
2356  // implementation-defined. [ Note: If a type has padding
2357  // bits, the condition does not hold; otherwise, the condition holds true
2358  // for unsigned integral types. -- end note ]
2359  assert(!Ty.isNull() && "Null QualType sent to unique object rep check");
2360 
2361  // Arrays are unique only if their element type is unique.
2362  if (Ty->isArrayType())
2364 
2365  // (9.1) - T is trivially copyable...
2366  if (!Ty.isTriviallyCopyableType(*this))
2367  return false;
2368 
2369  // All integrals and enums are unique.
2370  if (Ty->isIntegralOrEnumerationType())
2371  return true;
2372 
2373  // All other pointers are unique.
2374  if (Ty->isPointerType())
2375  return true;
2376 
2377  if (Ty->isMemberPointerType()) {
2378  const auto *MPT = Ty->getAs<MemberPointerType>();
2379  return !ABI->getMemberPointerInfo(MPT).HasPadding;
2380  }
2381 
2382  if (Ty->isRecordType()) {
2383  const RecordDecl *Record = Ty->getAs<RecordType>()->getDecl();
2384 
2385  if (Record->isInvalidDecl())
2386  return false;
2387 
2388  if (Record->isUnion())
2389  return unionHasUniqueObjectRepresentations(*this, Record);
2390 
2391  Optional<int64_t> StructSize =
2392  structHasUniqueObjectRepresentations(*this, Record);
2393 
2394  return StructSize &&
2395  StructSize.getValue() == static_cast<int64_t>(getTypeSize(Ty));
2396  }
2397 
2398  // FIXME: More cases to handle here (list by rsmith):
2399  // vectors (careful about, eg, vector of 3 foo)
2400  // _Complex int and friends
2401  // _Atomic T
2402  // Obj-C block pointers
2403  // Obj-C object pointers
2404  // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t,
2405  // clk_event_t, queue_t, reserve_id_t)
2406  // There're also Obj-C class types and the Obj-C selector type, but I think it
2407  // makes sense for those to return false here.
2408 
2409  return false;
2410 }
2411 
2413  unsigned count = 0;
2414  // Count ivars declared in class extension.
2415  for (const auto *Ext : OI->known_extensions())
2416  count += Ext->ivar_size();
2417 
2418  // Count ivar defined in this class's implementation. This
2419  // includes synthesized ivars.
2420  if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
2421  count += ImplDecl->ivar_size();
2422 
2423  return count;
2424 }
2425 
2427  if (!E)
2428  return false;
2429 
2430  // nullptr_t is always treated as null.
2431  if (E->getType()->isNullPtrType()) return true;
2432 
2433  if (E->getType()->isAnyPointerType() &&
2436  return true;
2437 
2438  // Unfortunately, __null has type 'int'.
2439  if (isa<GNUNullExpr>(E)) return true;
2440 
2441  return false;
2442 }
2443 
2444 /// Get the implementation of ObjCInterfaceDecl, or nullptr if none
2445 /// exists.
2447  llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2448  I = ObjCImpls.find(D);
2449  if (I != ObjCImpls.end())
2450  return cast<ObjCImplementationDecl>(I->second);
2451  return nullptr;
2452 }
2453 
2454 /// Get the implementation of ObjCCategoryDecl, or nullptr if none
2455 /// exists.
2457  llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2458  I = ObjCImpls.find(D);
2459  if (I != ObjCImpls.end())
2460  return cast<ObjCCategoryImplDecl>(I->second);
2461  return nullptr;
2462 }
2463 
2464 /// Set the implementation of ObjCInterfaceDecl.
2466  ObjCImplementationDecl *ImplD) {
2467  assert(IFaceD && ImplD && "Passed null params");
2468  ObjCImpls[IFaceD] = ImplD;
2469 }
2470 
2471 /// Set the implementation of ObjCCategoryDecl.
2473  ObjCCategoryImplDecl *ImplD) {
2474  assert(CatD && ImplD && "Passed null params");
2475  ObjCImpls[CatD] = ImplD;
2476 }
2477 
2478 const ObjCMethodDecl *
2480  return ObjCMethodRedecls.lookup(MD);
2481 }
2482 
2484  const ObjCMethodDecl *Redecl) {
2485  assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
2486  ObjCMethodRedecls[MD] = Redecl;
2487 }
2488 
2490  const NamedDecl *ND) const {
2491  if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
2492  return ID;
2493  if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
2494  return CD->getClassInterface();
2495  if (const auto *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
2496  return IMD->getClassInterface();
2497 
2498  return nullptr;
2499 }
2500 
2501 /// Get the copy initialization expression of VarDecl, or nullptr if
2502 /// none exists.
2504  assert(VD && "Passed null params");
2505  assert(VD->hasAttr<BlocksAttr>() &&
2506  "getBlockVarCopyInits - not __block var");
2507  llvm::DenseMap<const VarDecl*, Expr*>::iterator
2508  I = BlockVarCopyInits.find(VD);
2509  return (I != BlockVarCopyInits.end()) ? I->second : nullptr;
2510 }
2511 
2512 /// Set the copy inialization expression of a block var decl.
2514  assert(VD && Init && "Passed null params");
2515  assert(VD->hasAttr<BlocksAttr>() &&
2516  "setBlockVarCopyInits - not __block var");
2517  BlockVarCopyInits[VD] = Init;
2518 }
2519 
2521  unsigned DataSize) const {
2522  if (!DataSize)
2523  DataSize = TypeLoc::getFullDataSizeForType(T);
2524  else
2525  assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
2526  "incorrect data size provided to CreateTypeSourceInfo!");
2527 
2528  auto *TInfo =
2529  (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
2530  new (TInfo) TypeSourceInfo(T);
2531  return TInfo;
2532 }
2533 
2535  SourceLocation L) const {
2537  DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
2538  return DI;
2539 }
2540 
2541 const ASTRecordLayout &
2543  return getObjCLayout(D, nullptr);
2544 }
2545 
2546 const ASTRecordLayout &
2548  const ObjCImplementationDecl *D) const {
2549  return getObjCLayout(D->getClassInterface(), D);
2550 }
2551 
2552 //===----------------------------------------------------------------------===//
2553 // Type creation/memoization methods
2554 //===----------------------------------------------------------------------===//
2555 
2556 QualType
2557 ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2558  unsigned fastQuals = quals.getFastQualifiers();
2559  quals.removeFastQualifiers();
2560 
2561  // Check if we've already instantiated this type.
2562  llvm::FoldingSetNodeID ID;
2563  ExtQuals::Profile(ID, baseType, quals);
2564  void *insertPos = nullptr;
2565  if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2566  assert(eq->getQualifiers() == quals);
2567  return QualType(eq, fastQuals);
2568  }
2569 
2570  // If the base type is not canonical, make the appropriate canonical type.
2571  QualType canon;
2572  if (!baseType->isCanonicalUnqualified()) {
2573  SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
2574  canonSplit.Quals.addConsistentQualifiers(quals);
2575  canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
2576 
2577  // Re-find the insert position.
2578  (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2579  }
2580 
2581  auto *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2582  ExtQualNodes.InsertNode(eq, insertPos);
2583  return QualType(eq, fastQuals);
2584 }
2585 
2587  LangAS AddressSpace) const {
2588  QualType CanT = getCanonicalType(T);
2589  if (CanT.getAddressSpace() == AddressSpace)
2590  return T;
2591 
2592  // If we are composing extended qualifiers together, merge together
2593  // into one ExtQuals node.
2594  QualifierCollector Quals;
2595  const Type *TypeNode = Quals.strip(T);
2596 
2597  // If this type already has an address space specified, it cannot get
2598  // another one.
2599  assert(!Quals.hasAddressSpace() &&
2600  "Type cannot be in multiple addr spaces!");
2601  Quals.addAddressSpace(AddressSpace);
2602 
2603  return getExtQualType(TypeNode, Quals);
2604 }
2605 
2607  // If we are composing extended qualifiers together, merge together
2608  // into one ExtQuals node.
2609  QualifierCollector Quals;
2610  const Type *TypeNode = Quals.strip(T);
2611 
2612  // If the qualifier doesn't have an address space just return it.
2613  if (!Quals.hasAddressSpace())
2614  return T;
2615 
2616  Quals.removeAddressSpace();
2617 
2618  // Removal of the address space can mean there are no longer any
2619  // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts)
2620  // or required.
2621  if (Quals.hasNonFastQualifiers())
2622  return getExtQualType(TypeNode, Quals);
2623  else
2624  return QualType(TypeNode, Quals.getFastQualifiers());
2625 }
2626 
2628  Qualifiers::GC GCAttr) const {
2629  QualType CanT = getCanonicalType(T);
2630  if (CanT.getObjCGCAttr() == GCAttr)
2631  return T;
2632 
2633  if (const auto *ptr = T->getAs<PointerType>()) {
2634  QualType Pointee = ptr->getPointeeType();
2635  if (Pointee->isAnyPointerType()) {
2636  QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2637  return getPointerType(ResultType);
2638  }
2639  }
2640 
2641  // If we are composing extended qualifiers together, merge together
2642  // into one ExtQuals node.
2643  QualifierCollector Quals;
2644  const Type *TypeNode = Quals.strip(T);
2645 
2646  // If this type already has an ObjCGC specified, it cannot get
2647  // another one.
2648  assert(!Quals.hasObjCGCAttr() &&
2649  "Type cannot have multiple ObjCGCs!");
2650  Quals.addObjCGCAttr(GCAttr);
2651 
2652  return getExtQualType(TypeNode, Quals);
2653 }
2654 
2656  FunctionType::ExtInfo Info) {
2657  if (T->getExtInfo() == Info)
2658  return T;
2659 
2660  QualType Result;
2661  if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
2662  Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
2663  } else {
2664  const auto *FPT = cast<FunctionProtoType>(T);
2665  FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2666  EPI.ExtInfo = Info;
2667  Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
2668  }
2669 
2670  return cast<FunctionType>(Result.getTypePtr());
2671 }
2672 
2674  QualType ResultType) {
2675  FD = FD->getMostRecentDecl();
2676  while (true) {
2677  const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
2678  FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2679  FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
2680  if (FunctionDecl *Next = FD->getPreviousDecl())
2681  FD = Next;
2682  else
2683  break;
2684  }
2686  L->DeducedReturnType(FD, ResultType);
2687 }
2688 
2689 /// Get a function type and produce the equivalent function type with the
2690 /// specified exception specification. Type sugar that can be present on a
2691 /// declaration of a function with an exception specification is permitted
2692 /// and preserved. Other type sugar (for instance, typedefs) is not.
2695  // Might have some parens.
2696  if (const auto *PT = dyn_cast<ParenType>(Orig))
2697  return getParenType(
2698  getFunctionTypeWithExceptionSpec(PT->getInnerType(), ESI));
2699 
2700  // Might have a calling-convention attribute.
2701  if (const auto *AT = dyn_cast<AttributedType>(Orig))
2702  return getAttributedType(
2703  AT->getAttrKind(),
2704  getFunctionTypeWithExceptionSpec(AT->getModifiedType(), ESI),
2705  getFunctionTypeWithExceptionSpec(AT->getEquivalentType(), ESI));
2706 
2707  // Anything else must be a function type. Rebuild it with the new exception
2708  // specification.
2709  const auto *Proto = cast<FunctionProtoType>(Orig);
2710  return getFunctionType(
2711  Proto->getReturnType(), Proto->getParamTypes(),
2712  Proto->getExtProtoInfo().withExceptionSpec(ESI));
2713 }
2714 
2716  QualType U) {
2717  return hasSameType(T, U) ||
2718  (getLangOpts().CPlusPlus17 &&
2721 }
2722 
2725  bool AsWritten) {
2726  // Update the type.
2727  QualType Updated =
2729  FD->setType(Updated);
2730 
2731  if (!AsWritten)
2732  return;
2733 
2734  // Update the type in the type source information too.
2735  if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
2736  // If the type and the type-as-written differ, we may need to update
2737  // the type-as-written too.
2738  if (TSInfo->getType() != FD->getType())
2739  Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI);
2740 
2741  // FIXME: When we get proper type location information for exceptions,
2742  // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
2743  // up the TypeSourceInfo;
2744  assert(TypeLoc::getFullDataSizeForType(Updated) ==
2745  TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
2746  "TypeLoc size mismatch from updating exception specification");
2747  TSInfo->overrideType(Updated);
2748  }
2749 }
2750 
2751 /// getComplexType - Return the uniqued reference to the type for a complex
2752 /// number with the specified element type.
2754  // Unique pointers, to guarantee there is only one pointer of a particular
2755  // structure.
2756  llvm::FoldingSetNodeID ID;
2757  ComplexType::Profile(ID, T);
2758 
2759  void *InsertPos = nullptr;
2760  if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2761  return QualType(CT, 0);
2762 
2763  // If the pointee type isn't canonical, this won't be a canonical type either,
2764  // so fill in the canonical type field.
2765  QualType Canonical;
2766  if (!T.isCanonical()) {
2767  Canonical = getComplexType(getCanonicalType(T));
2768 
2769  // Get the new insert position for the node we care about.
2770  ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
2771  assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2772  }
2773  auto *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
2774  Types.push_back(New);
2775  ComplexTypes.InsertNode(New, InsertPos);
2776  return QualType(New, 0);
2777 }
2778 
2779 /// getPointerType - Return the uniqued reference to the type for a pointer to
2780 /// the specified type.
2782  // Unique pointers, to guarantee there is only one pointer of a particular
2783  // structure.
2784  llvm::FoldingSetNodeID ID;
2785  PointerType::Profile(ID, T);
2786 
2787  void *InsertPos = nullptr;
2788  if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2789  return QualType(PT, 0);
2790 
2791  // If the pointee type isn't canonical, this won't be a canonical type either,
2792  // so fill in the canonical type field.
2793  QualType Canonical;
2794  if (!T.isCanonical()) {
2795  Canonical = getPointerType(getCanonicalType(T));
2796 
2797  // Get the new insert position for the node we care about.
2798  PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2799  assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2800  }
2801  auto *New = new (*this, TypeAlignment) PointerType(T, Canonical);
2802  Types.push_back(New);
2803  PointerTypes.InsertNode(New, InsertPos);
2804  return QualType(New, 0);
2805 }
2806 
2808  llvm::FoldingSetNodeID ID;
2809  AdjustedType::Profile(ID, Orig, New);
2810  void *InsertPos = nullptr;
2811  AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2812  if (AT)
2813  return QualType(AT, 0);
2814 
2815  QualType Canonical = getCanonicalType(New);
2816 
2817  // Get the new insert position for the node we care about.
2818  AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2819  assert(!AT && "Shouldn't be in the map!");
2820 
2821  AT = new (*this, TypeAlignment)
2822  AdjustedType(Type::Adjusted, Orig, New, Canonical);
2823  Types.push_back(AT);
2824  AdjustedTypes.InsertNode(AT, InsertPos);
2825  return QualType(AT, 0);
2826 }
2827 
2829  assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2830 
2831  QualType Decayed;
2832 
2833  // C99 6.7.5.3p7:
2834  // A declaration of a parameter as "array of type" shall be
2835  // adjusted to "qualified pointer to type", where the type
2836  // qualifiers (if any) are those specified within the [ and ] of
2837  // the array type derivation.
2838  if (T->isArrayType())
2839  Decayed = getArrayDecayedType(T);
2840 
2841  // C99 6.7.5.3p8:
2842  // A declaration of a parameter as "function returning type"
2843  // shall be adjusted to "pointer to function returning type", as
2844  // in 6.3.2.1.
2845  if (T->isFunctionType())
2846  Decayed = getPointerType(T);
2847 
2848  llvm::FoldingSetNodeID ID;
2849  AdjustedType::Profile(ID, T, Decayed);
2850  void *InsertPos = nullptr;
2851  AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2852  if (AT)
2853  return QualType(AT, 0);
2854 
2855  QualType Canonical = getCanonicalType(Decayed);
2856 
2857  // Get the new insert position for the node we care about.
2858  AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2859  assert(!AT && "Shouldn't be in the map!");
2860 
2861  AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2862  Types.push_back(AT);
2863  AdjustedTypes.InsertNode(AT, InsertPos);
2864  return QualType(AT, 0);
2865 }
2866 
2867 /// getBlockPointerType - Return the uniqued reference to the type for
2868 /// a pointer to the specified block.
2870  assert(T->isFunctionType() && "block of function types only");
2871  // Unique pointers, to guarantee there is only one block of a particular
2872  // structure.
2873  llvm::FoldingSetNodeID ID;
2875 
2876  void *InsertPos = nullptr;
2877  if (BlockPointerType *PT =
2878  BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2879  return QualType(PT, 0);
2880 
2881  // If the block pointee type isn't canonical, this won't be a canonical
2882  // type either so fill in the canonical type field.
2883  QualType Canonical;
2884  if (!T.isCanonical()) {
2885  Canonical = getBlockPointerType(getCanonicalType(T));
2886 
2887  // Get the new insert position for the node we care about.
2888  BlockPointerType *NewIP =
2889  BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2890  assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2891  }
2892  auto *New = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
2893  Types.push_back(New);
2894  BlockPointerTypes.InsertNode(New, InsertPos);
2895  return QualType(New, 0);
2896 }
2897 
2898 /// getLValueReferenceType - Return the uniqued reference to the type for an
2899 /// lvalue reference to the specified type.
2900 QualType
2901 ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
2902  assert(getCanonicalType(T) != OverloadTy &&
2903  "Unresolved overloaded function type");
2904 
2905  // Unique pointers, to guarantee there is only one pointer of a particular
2906  // structure.
2907  llvm::FoldingSetNodeID ID;
2908  ReferenceType::Profile(ID, T, SpelledAsLValue);
2909 
2910  void *InsertPos = nullptr;
2911  if (LValueReferenceType *RT =
2912  LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2913  return QualType(RT, 0);
2914 
2915  const auto *InnerRef = T->getAs<ReferenceType>();
2916 
2917  // If the referencee type isn't canonical, this won't be a canonical type
2918  // either, so fill in the canonical type field.
2919  QualType Canonical;
2920  if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2921  QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2922  Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
2923 
2924  // Get the new insert position for the node we care about.
2925  LValueReferenceType *NewIP =
2926  LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
2927  assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2928  }
2929 
2930  auto *New = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2931  SpelledAsLValue);
2932  Types.push_back(New);
2933  LValueReferenceTypes.InsertNode(New, InsertPos);
2934 
2935  return QualType(New, 0);
2936 }
2937 
2938 /// getRValueReferenceType - Return the uniqued reference to the type for an
2939 /// rvalue reference to the specified type.
2941  // Unique pointers, to guarantee there is only one pointer of a particular
2942  // structure.
2943  llvm::FoldingSetNodeID ID;
2944  ReferenceType::Profile(ID, T, false);
2945 
2946  void *InsertPos = nullptr;
2947  if (RValueReferenceType *RT =
2948  RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2949  return QualType(RT, 0);
2950 
2951  const auto *InnerRef = T->getAs<ReferenceType>();
2952 
2953  // If the referencee type isn't canonical, this won't be a canonical type
2954  // either, so fill in the canonical type field.
2955  QualType Canonical;
2956  if (InnerRef || !T.isCanonical()) {
2957  QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2958  Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
2959 
2960  // Get the new insert position for the node we care about.
2961  RValueReferenceType *NewIP =
2962  RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
2963  assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2964  }
2965 
2966  auto *New = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
2967  Types.push_back(New);
2968  RValueReferenceTypes.InsertNode(New, InsertPos);
2969  return QualType(New, 0);
2970 }
2971 
2972 /// getMemberPointerType - Return the uniqued reference to the type for a
2973 /// member pointer to the specified type, in the specified class.
2975  // Unique pointers, to guarantee there is only one pointer of a particular
2976  // structure.
2977  llvm::FoldingSetNodeID ID;
2978  MemberPointerType::Profile(ID, T, Cls);
2979 
2980  void *InsertPos = nullptr;
2981  if (MemberPointerType *PT =
2982  MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2983  return QualType(PT, 0);
2984 
2985  // If the pointee or class type isn't canonical, this won't be a canonical
2986  // type either, so fill in the canonical type field.
2987  QualType Canonical;
2988  if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
2990 
2991  // Get the new insert position for the node we care about.
2992  MemberPointerType *NewIP =
2993  MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2994  assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2995  }
2996  auto *New = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
2997  Types.push_back(New);
2998  MemberPointerTypes.InsertNode(New, InsertPos);
2999  return QualType(New, 0);
3000 }
3001 
3002 /// getConstantArrayType - Return the unique reference to the type for an
3003 /// array of the specified element type.
3005  const llvm::APInt &ArySizeIn,
3007  unsigned IndexTypeQuals) const {
3008  assert((EltTy->isDependentType() ||
3009  EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
3010  "Constant array of VLAs is illegal!");
3011 
3012  // Convert the array size into a canonical width matching the pointer size for
3013  // the target.
3014  llvm::APInt ArySize(ArySizeIn);
3015  ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth());
3016 
3017  llvm::FoldingSetNodeID ID;
3018  ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
3019 
3020  void *InsertPos = nullptr;
3021  if (ConstantArrayType *ATP =
3022  ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
3023  return QualType(ATP, 0);
3024 
3025  // If the element type isn't canonical or has qualifiers, this won't
3026  // be a canonical type either, so fill in the canonical type field.
3027  QualType Canon;
3028  if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
3029  SplitQualType canonSplit = getCanonicalType(EltTy).split();
3030  Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
3031  ASM, IndexTypeQuals);
3032  Canon = getQualifiedType(Canon, canonSplit.Quals);
3033 
3034  // Get the new insert position for the node we care about.
3035  ConstantArrayType *NewIP =
3036  ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
3037  assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3038  }
3039 
3040  auto *New = new (*this,TypeAlignment)
3041  ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
3042  ConstantArrayTypes.InsertNode(New, InsertPos);
3043  Types.push_back(New);
3044  return QualType(New, 0);
3045 }
3046 
3047 /// getVariableArrayDecayedType - Turns the given type, which may be
3048 /// variably-modified, into the corresponding type with all the known
3049 /// sizes replaced with [*].
3051  // Vastly most common case.
3052  if (!type->isVariablyModifiedType()) return type;
3053 
3054  QualType result;
3055 
3056  SplitQualType split = type.getSplitDesugaredType();
3057  const Type *ty = split.Ty;
3058  switch (ty->getTypeClass()) {
3059 #define TYPE(Class, Base)
3060 #define ABSTRACT_TYPE(Class, Base)
3061 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3062 #include "clang/AST/TypeNodes.def"
3063  llvm_unreachable("didn't desugar past all non-canonical types?");
3064 
3065  // These types should never be variably-modified.
3066  case Type::Builtin:
3067  case Type::Complex:
3068  case Type::Vector:
3069  case Type::DependentVector:
3070  case Type::ExtVector:
3071  case Type::DependentSizedExtVector:
3072  case Type::DependentAddressSpace:
3073  case Type::ObjCObject:
3074  case Type::ObjCInterface:
3075  case Type::ObjCObjectPointer:
3076  case Type::Record:
3077  case Type::Enum:
3078  case Type::UnresolvedUsing:
3079  case Type::TypeOfExpr:
3080  case Type::TypeOf:
3081  case Type::Decltype:
3082  case Type::UnaryTransform:
3083  case Type::DependentName:
3084  case Type::InjectedClassName:
3085  case Type::TemplateSpecialization:
3086  case Type::DependentTemplateSpecialization:
3087  case Type::TemplateTypeParm:
3088  case Type::SubstTemplateTypeParmPack:
3089  case Type::Auto:
3090  case Type::DeducedTemplateSpecialization:
3091  case Type::PackExpansion:
3092  llvm_unreachable("type should never be variably-modified");
3093 
3094  // These types can be variably-modified but should never need to
3095  // further decay.
3096  case Type::FunctionNoProto:
3097  case Type::FunctionProto:
3098  case Type::BlockPointer:
3099  case Type::MemberPointer:
3100  case Type::Pipe:
3101  return type;
3102 
3103  // These types can be variably-modified. All these modifications
3104  // preserve structure except as noted by comments.
3105  // TODO: if we ever care about optimizing VLAs, there are no-op
3106  // optimizations available here.
3107  case Type::Pointer:
3109  cast<PointerType>(ty)->getPointeeType()));
3110  break;
3111 
3112  case Type::LValueReference: {
3113  const auto *lv = cast<LValueReferenceType>(ty);
3114  result = getLValueReferenceType(
3115  getVariableArrayDecayedType(lv->getPointeeType()),
3116  lv->isSpelledAsLValue());
3117  break;
3118  }
3119 
3120  case Type::RValueReference: {
3121  const auto *lv = cast<RValueReferenceType>(ty);
3122  result = getRValueReferenceType(
3123  getVariableArrayDecayedType(lv->getPointeeType()));
3124  break;
3125  }
3126 
3127  case Type::Atomic: {
3128  const auto *at = cast<AtomicType>(ty);
3129  result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
3130  break;
3131  }
3132 
3133  case Type::ConstantArray: {
3134  const auto *cat = cast<ConstantArrayType>(ty);
3135  result = getConstantArrayType(
3136  getVariableArrayDecayedType(cat->getElementType()),
3137  cat->getSize(),
3138  cat->getSizeModifier(),
3139  cat->getIndexTypeCVRQualifiers());
3140  break;
3141  }
3142 
3143  case Type::DependentSizedArray: {
3144  const auto *dat = cast<DependentSizedArrayType>(ty);
3145  result = getDependentSizedArrayType(
3146  getVariableArrayDecayedType(dat->getElementType()),
3147  dat->getSizeExpr(),
3148  dat->getSizeModifier(),
3149  dat->getIndexTypeCVRQualifiers(),
3150  dat->getBracketsRange());
3151  break;
3152  }
3153 
3154  // Turn incomplete types into [*] types.
3155  case Type::IncompleteArray: {
3156  const auto *iat = cast<IncompleteArrayType>(ty);
3157  result = getVariableArrayType(
3158  getVariableArrayDecayedType(iat->getElementType()),
3159  /*size*/ nullptr,
3161  iat->getIndexTypeCVRQualifiers(),
3162  SourceRange());
3163  break;
3164  }
3165 
3166  // Turn VLA types into [*] types.
3167  case Type::VariableArray: {
3168  const auto *vat = cast<VariableArrayType>(ty);
3169  result = getVariableArrayType(
3170  getVariableArrayDecayedType(vat->getElementType()),
3171  /*size*/ nullptr,
3173  vat->getIndexTypeCVRQualifiers(),
3174  vat->getBracketsRange());
3175  break;
3176  }
3177  }
3178 
3179  // Apply the top-level qualifiers from the original.
3180  return getQualifiedType(result, split.Quals);
3181 }
3182 
3183 /// getVariableArrayType - Returns a non-unique reference to the type for a
3184 /// variable array of the specified element type.
3186  Expr *NumElts,
3188  unsigned IndexTypeQuals,
3189  SourceRange Brackets) const {
3190  // Since we don't unique expressions, it isn't possible to unique VLA's
3191  // that have an expression provided for their size.
3192  QualType Canon;
3193 
3194  // Be sure to pull qualifiers off the element type.
3195  if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
3196  SplitQualType canonSplit = getCanonicalType(EltTy).split();
3197  Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
3198  IndexTypeQuals, Brackets);
3199  Canon = getQualifiedType(Canon, canonSplit.Quals);
3200  }
3201 
3202  auto *New = new (*this, TypeAlignment)
3203  VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
3204 
3205  VariableArrayTypes.push_back(New);
3206  Types.push_back(New);
3207  return QualType(New, 0);
3208 }
3209 
3210 /// getDependentSizedArrayType - Returns a non-unique reference to
3211 /// the type for a dependently-sized array of the specified element
3212 /// type.
3214  Expr *numElements,
3216  unsigned elementTypeQuals,
3217  SourceRange brackets) const {
3218  assert((!numElements || numElements->isTypeDependent() ||
3219  numElements->isValueDependent()) &&
3220  "Size must be type- or value-dependent!");
3221 
3222  // Dependently-sized array types that do not have a specified number
3223  // of elements will have their sizes deduced from a dependent
3224  // initializer. We do no canonicalization here at all, which is okay
3225  // because they can't be used in most locations.
3226  if (!numElements) {
3227  auto *newType
3228  = new (*this, TypeAlignment)
3229  DependentSizedArrayType(*this, elementType, QualType(),
3230  numElements, ASM, elementTypeQuals,
3231  brackets);
3232  Types.push_back(newType);
3233  return QualType(newType, 0);
3234  }
3235 
3236  // Otherwise, we actually build a new type every time, but we
3237  // also build a canonical type.
3238 
3239  SplitQualType canonElementType = getCanonicalType(elementType).split();
3240 
3241  void *insertPos = nullptr;
3242  llvm::FoldingSetNodeID ID;
3244  QualType(canonElementType.Ty, 0),
3245  ASM, elementTypeQuals, numElements);
3246 
3247  // Look for an existing type with these properties.
3248  DependentSizedArrayType *canonTy =
3249  DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
3250 
3251  // If we don't have one, build one.
3252  if (!canonTy) {
3253  canonTy = new (*this, TypeAlignment)
3254  DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
3255  QualType(), numElements, ASM, elementTypeQuals,
3256  brackets);
3257  DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
3258  Types.push_back(canonTy);
3259  }
3260 
3261  // Apply qualifiers from the element type to the array.
3262  QualType canon = getQualifiedType(QualType(canonTy,0),
3263  canonElementType.Quals);
3264 
3265  // If we didn't need extra canonicalization for the element type or the size
3266  // expression, then just use that as our result.
3267  if (QualType(canonElementType.Ty, 0) == elementType &&
3268  canonTy->getSizeExpr() == numElements)
3269  return canon;
3270 
3271  // Otherwise, we need to build a type which follows the spelling
3272  // of the element type.
3273  auto *sugaredType
3274  = new (*this, TypeAlignment)
3275  DependentSizedArrayType(*this, elementType, canon, numElements,
3276  ASM, elementTypeQuals, brackets);
3277  Types.push_back(sugaredType);
3278  return QualType(sugaredType, 0);
3279 }
3280 
3283  unsigned elementTypeQuals) const {
3284  llvm::FoldingSetNodeID ID;
3285  IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
3286 
3287  void *insertPos = nullptr;
3288  if (IncompleteArrayType *iat =
3289  IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
3290  return QualType(iat, 0);
3291 
3292  // If the element type isn't canonical, this won't be a canonical type
3293  // either, so fill in the canonical type field. We also have to pull
3294  // qualifiers off the element type.
3295  QualType canon;
3296 
3297  if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
3298  SplitQualType canonSplit = getCanonicalType(elementType).split();
3299  canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
3300  ASM, elementTypeQuals);
3301  canon = getQualifiedType(canon, canonSplit.Quals);
3302 
3303  // Get the new insert position for the node we care about.
3304  IncompleteArrayType *existing =
3305  IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
3306  assert(!existing && "Shouldn't be in the map!"); (void) existing;
3307  }
3308 
3309  auto *newType = new (*this, TypeAlignment)
3310  IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
3311 
3312  IncompleteArrayTypes.InsertNode(newType, insertPos);
3313  Types.push_back(newType);
3314  return QualType(newType, 0);
3315 }
3316 
3317 /// getVectorType - Return the unique reference to a vector type of
3318 /// the specified element type and size. VectorType must be a built-in type.
3319 QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
3320  VectorType::VectorKind VecKind) const {
3321  assert(vecType->isBuiltinType());
3322 
3323  // Check if we've already instantiated a vector of this type.
3324  llvm::FoldingSetNodeID ID;
3325  VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
3326 
3327  void *InsertPos = nullptr;
3328  if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3329  return QualType(VTP, 0);
3330 
3331  // If the element type isn't canonical, this won't be a canonical type either,
3332  // so fill in the canonical type field.
3333  QualType Canonical;
3334  if (!vecType.isCanonical()) {
3335  Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
3336 
3337  // Get the new insert position for the node we care about.
3338  VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3339  assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3340  }
3341  auto *New = new (*this, TypeAlignment)
3342  VectorType(vecType, NumElts, Canonical, VecKind);
3343  VectorTypes.InsertNode(New, InsertPos);
3344  Types.push_back(New);
3345  return QualType(New, 0);
3346 }
3347 
3348 QualType
3350  SourceLocation AttrLoc,
3351  VectorType::VectorKind VecKind) const {
3352  llvm::FoldingSetNodeID ID;
3353  DependentVectorType::Profile(ID, *this, getCanonicalType(VecType), SizeExpr,
3354  VecKind);
3355  void *InsertPos = nullptr;
3356  DependentVectorType *Canon =
3357  DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3358  DependentVectorType *New;
3359 
3360  if (Canon) {
3361  New = new (*this, TypeAlignment) DependentVectorType(
3362  *this, VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind);
3363  } else {
3364  QualType CanonVecTy = getCanonicalType(VecType);
3365  if (CanonVecTy == VecType) {
3366  New = new (*this, TypeAlignment) DependentVectorType(
3367  *this, VecType, QualType(), SizeExpr, AttrLoc, VecKind);
3368 
3369  DependentVectorType *CanonCheck =
3370  DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3371  assert(!CanonCheck &&
3372  "Dependent-sized vector_size canonical type broken");
3373  (void)CanonCheck;
3374  DependentVectorTypes.InsertNode(New, InsertPos);
3375  } else {
3376  QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
3377  SourceLocation());
3378  New = new (*this, TypeAlignment) DependentVectorType(
3379  *this, VecType, Canon, SizeExpr, AttrLoc, VecKind);
3380  }
3381  }
3382 
3383  Types.push_back(New);
3384  return QualType(New, 0);
3385 }
3386 
3387 /// getExtVectorType - Return the unique reference to an extended vector type of
3388 /// the specified element type and size. VectorType must be a built-in type.
3389 QualType
3390 ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
3391  assert(vecType->isBuiltinType() || vecType->isDependentType());
3392 
3393  // Check if we've already instantiated a vector of this type.
3394  llvm::FoldingSetNodeID ID;
3395  VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
3397  void *InsertPos = nullptr;
3398  if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3399  return QualType(VTP, 0);
3400 
3401  // If the element type isn't canonical, this won't be a canonical type either,
3402  // so fill in the canonical type field.
3403  QualType Canonical;
3404  if (!vecType.isCanonical()) {
3405  Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
3406 
3407  // Get the new insert position for the node we care about.
3408  VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3409  assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3410  }
3411  auto *New = new (*this, TypeAlignment)
3412  ExtVectorType(vecType, NumElts, Canonical);
3413  VectorTypes.InsertNode(New, InsertPos);
3414  Types.push_back(New);
3415  return QualType(New, 0);
3416 }
3417 
3418 QualType
3420  Expr *SizeExpr,
3421  SourceLocation AttrLoc) const {
3422  llvm::FoldingSetNodeID ID;
3424  SizeExpr);
3425 
3426  void *InsertPos = nullptr;
3428  = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3430  if (Canon) {
3431  // We already have a canonical version of this array type; use it as
3432  // the canonical type for a newly-built type.
3433  New = new (*this, TypeAlignment)
3434  DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
3435  SizeExpr, AttrLoc);
3436  } else {
3437  QualType CanonVecTy = getCanonicalType(vecType);
3438  if (CanonVecTy == vecType) {
3439  New = new (*this, TypeAlignment)
3440  DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
3441  AttrLoc);
3442 
3443  DependentSizedExtVectorType *CanonCheck
3444  = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3445  assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
3446  (void)CanonCheck;
3447  DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
3448  } else {
3449  QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
3450  SourceLocation());
3451  New = new (*this, TypeAlignment)
3452  DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
3453  }
3454  }
3455 
3456  Types.push_back(New);
3457  return QualType(New, 0);
3458 }
3459 
3461  Expr *AddrSpaceExpr,
3462  SourceLocation AttrLoc) const {
3463  assert(AddrSpaceExpr->isInstantiationDependent());
3464 
3465  QualType canonPointeeType = getCanonicalType(PointeeType);
3466 
3467  void *insertPos = nullptr;
3468  llvm::FoldingSetNodeID ID;
3469  DependentAddressSpaceType::Profile(ID, *this, canonPointeeType,
3470  AddrSpaceExpr);
3471 
3472  DependentAddressSpaceType *canonTy =
3473  DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos);
3474 
3475  if (!canonTy) {
3476  canonTy = new (*this, TypeAlignment)
3477  DependentAddressSpaceType(*this, canonPointeeType,
3478  QualType(), AddrSpaceExpr, AttrLoc);
3479  DependentAddressSpaceTypes.InsertNode(canonTy, insertPos);
3480  Types.push_back(canonTy);
3481  }
3482 
3483  if (canonPointeeType == PointeeType &&
3484  canonTy->getAddrSpaceExpr() == AddrSpaceExpr)
3485  return QualType(canonTy, 0);
3486 
3487  auto *sugaredType
3488  = new (*this, TypeAlignment)
3489  DependentAddressSpaceType(*this, PointeeType, QualType(canonTy, 0),
3490  AddrSpaceExpr, AttrLoc);
3491  Types.push_back(sugaredType);
3492  return QualType(sugaredType, 0);
3493 }
3494 
3495 /// Determine whether \p T is canonical as the result type of a function.
3497  return T.isCanonical() &&
3500 }
3501 
3502 /// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
3503 QualType
3505  const FunctionType::ExtInfo &Info) const {
3506  // Unique functions, to guarantee there is only one function of a particular
3507  // structure.
3508  llvm::FoldingSetNodeID ID;
3509  FunctionNoProtoType::Profile(ID, ResultTy, Info);
3510 
3511  void *InsertPos = nullptr;
3512  if (FunctionNoProtoType *FT =
3513  FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
3514  return QualType(FT, 0);
3515 
3516  QualType Canonical;
3517  if (!isCanonicalResultType(ResultTy)) {
3518  Canonical =
3520 
3521  // Get the new insert position for the node we care about.
3522  FunctionNoProtoType *NewIP =
3523  FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
3524  assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3525  }
3526 
3527  auto *New = new (*this, TypeAlignment)
3528  FunctionNoProtoType(ResultTy, Canonical, Info);
3529  Types.push_back(New);
3530  FunctionNoProtoTypes.InsertNode(New, InsertPos);
3531  return QualType(New, 0);
3532 }
3533 
3536  CanQualType CanResultType = getCanonicalType(ResultType);
3537 
3538  // Canonical result types do not have ARC lifetime qualifiers.
3539  if (CanResultType.getQualifiers().hasObjCLifetime()) {
3540  Qualifiers Qs = CanResultType.getQualifiers();
3541  Qs.removeObjCLifetime();
3543  getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
3544  }
3545 
3546  return CanResultType;
3547 }
3548 
3550  const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
3551  if (ESI.Type == EST_None)
3552  return true;
3553  if (!NoexceptInType)
3554  return false;
3555 
3556  // C++17 onwards: exception specification is part of the type, as a simple
3557  // boolean "can this function type throw".
3558  if (ESI.Type == EST_BasicNoexcept)
3559  return true;
3560 
3561  // A noexcept(expr) specification is (possibly) canonical if expr is
3562  // value-dependent.
3563  if (ESI.Type == EST_DependentNoexcept)
3564  return true;
3565 
3566  // A dynamic exception specification is canonical if it only contains pack
3567  // expansions (so we can't tell whether it's non-throwing) and all its
3568  // contained types are canonical.
3569  if (ESI.Type == EST_Dynamic) {
3570  bool AnyPackExpansions = false;
3571  for (QualType ET : ESI.Exceptions) {
3572  if (!ET.isCanonical())
3573  return false;
3574  if (ET->getAs<PackExpansionType>())
3575  AnyPackExpansions = true;
3576  }
3577  return AnyPackExpansions;
3578  }
3579 
3580  return false;
3581 }
3582 
3583 QualType ASTContext::getFunctionTypeInternal(
3584  QualType ResultTy, ArrayRef<QualType> ArgArray,
3585  const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
3586  size_t NumArgs = ArgArray.size();
3587 
3588  // Unique functions, to guarantee there is only one function of a particular
3589  // structure.
3590  llvm::FoldingSetNodeID ID;
3591  FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
3592  *this, true);
3593 
3594  QualType Canonical;
3595  bool Unique = false;
3596 
3597  void *InsertPos = nullptr;
3598  if (FunctionProtoType *FPT =
3599  FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
3600  QualType Existing = QualType(FPT, 0);
3601 
3602  // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
3603  // it so long as our exception specification doesn't contain a dependent
3604  // noexcept expression, or we're just looking for a canonical type.
3605  // Otherwise, we're going to need to create a type
3606  // sugar node to hold the concrete expression.
3607  if (OnlyWantCanonical || !isComputedNoexcept(EPI.ExceptionSpec.Type) ||
3608  EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
3609  return Existing;
3610 
3611  // We need a new type sugar node for this one, to hold the new noexcept
3612  // expression. We do no canonicalization here, but that's OK since we don't
3613  // expect to see the same noexcept expression much more than once.
3614  Canonical = getCanonicalType(Existing);
3615  Unique = true;
3616  }
3617 
3618  bool NoexceptInType = getLangOpts().CPlusPlus17;
3619  bool IsCanonicalExceptionSpec =
3620  isCanonicalExceptionSpecification(EPI.ExceptionSpec, NoexceptInType);
3621 
3622  // Determine whether the type being created is already canonical or not.
3623  bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
3624  isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
3625  for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
3626  if (!ArgArray[i].isCanonicalAsParam())
3627  isCanonical = false;
3628 
3629  if (OnlyWantCanonical)
3630  assert(isCanonical &&
3631  "given non-canonical parameters constructing canonical type");
3632 
3633  // If this type isn't canonical, get the canonical version of it if we don't
3634  // already have it. The exception spec is only partially part of the
3635  // canonical type, and only in C++17 onwards.
3636  if (!isCanonical && Canonical.isNull()) {
3637  SmallVector<QualType, 16> CanonicalArgs;
3638  CanonicalArgs.reserve(NumArgs);
3639  for (unsigned i = 0; i != NumArgs; ++i)
3640  CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
3641 
3642  llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
3643  FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
3644  CanonicalEPI.HasTrailingReturn = false;
3645 
3646  if (IsCanonicalExceptionSpec) {
3647  // Exception spec is already OK.
3648  } else if (NoexceptInType) {
3649  switch (EPI.ExceptionSpec.Type) {
3651  // We don't know yet. It shouldn't matter what we pick here; no-one
3652  // should ever look at this.
3653  LLVM_FALLTHROUGH;
3654  case EST_None: case EST_MSAny: case EST_NoexceptFalse:
3655  CanonicalEPI.ExceptionSpec.Type = EST_None;
3656  break;
3657 
3658  // A dynamic exception specification is almost always "not noexcept",
3659  // with the exception that a pack expansion might expand to no types.
3660  case EST_Dynamic: {
3661  bool AnyPacks = false;
3662  for (QualType ET : EPI.ExceptionSpec.Exceptions) {
3663  if (ET->getAs<PackExpansionType>())
3664  AnyPacks = true;
3665  ExceptionTypeStorage.push_back(getCanonicalType(ET));
3666  }
3667  if (!AnyPacks)
3668  CanonicalEPI.ExceptionSpec.Type = EST_None;
3669  else {
3670  CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
3671  CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
3672  }
3673  break;
3674  }
3675 
3677  CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
3678  break;
3679 
3680  case EST_DependentNoexcept:
3681  llvm_unreachable("dependent noexcept is already canonical");
3682  }
3683  } else {
3685  }
3686 
3687  // Adjust the canonical function result type.
3688  CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
3689  Canonical =
3690  getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
3691 
3692  // Get the new insert position for the node we care about.
3693  FunctionProtoType *NewIP =
3694  FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
3695  assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3696  }
3697 
3698  // FunctionProtoType objects are allocated with extra bytes after
3699  // them for three variable size arrays at the end:
3700  // - parameter types
3701  // - exception types
3702  // - extended parameter information
3703  // Instead of the exception types, there could be a noexcept
3704  // expression, or information used to resolve the exception
3705  // specification.
3706  size_t Size =
3707  sizeof(FunctionProtoType) + NumArgs * sizeof(QualType) +
3708  FunctionProtoType::getExceptionSpecSize(
3709  EPI.ExceptionSpec.Type, EPI.ExceptionSpec.Exceptions.size());
3710 
3711  // Put the ExtParameterInfos last. If all were equal, it would make
3712  // more sense to put these before the exception specification, because
3713  // it's much easier to skip past them compared to the elaborate switch
3714  // required to skip the exception specification. However, all is not
3715  // equal; ExtParameterInfos are used to model very uncommon features,
3716  // and it's better not to burden the more common paths.
3717  if (EPI.ExtParameterInfos) {
3718  Size += NumArgs * sizeof(FunctionProtoType::ExtParameterInfo);
3719  }
3720 
3721  auto *FTP = (FunctionProtoType *) Allocate(Size, TypeAlignment);
3722  FunctionProtoType::ExtProtoInfo newEPI = EPI;
3723  new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
3724  Types.push_back(FTP);
3725  if (!Unique)
3726  FunctionProtoTypes.InsertNode(FTP, InsertPos);
3727  return QualType(FTP, 0);
3728 }
3729 
3730 QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
3731  llvm::FoldingSetNodeID ID;
3732  PipeType::Profile(ID, T, ReadOnly);
3733 
3734  void *InsertPos = nullptr;
3735  if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
3736  return QualType(PT, 0);
3737 
3738  // If the pipe element type isn't canonical, this won't be a canonical type
3739  // either, so fill in the canonical type field.
3740  QualType Canonical;
3741  if (!T.isCanonical()) {
3742  Canonical = getPipeType(getCanonicalType(T), ReadOnly);
3743 
3744  // Get the new insert position for the node we care about.
3745  PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
3746  assert(!NewIP && "Shouldn't be in the map!");
3747  (void)NewIP;
3748  }
3749  auto *New = new (*this, TypeAlignment) PipeType(T, Canonical, ReadOnly);
3750  Types.push_back(New);
3751  PipeTypes.InsertNode(New, InsertPos);
3752  return QualType(New, 0);
3753 }
3754 
3756  // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
3757  return LangOpts.OpenCL ? getAddrSpaceQualType(Ty, LangAS::opencl_constant)
3758  : Ty;
3759 }
3760 
3762  return getPipeType(T, true);
3763 }
3764 
3766  return getPipeType(T, false);
3767 }
3768 
3769 #ifndef NDEBUG
3771  if (!isa<CXXRecordDecl>(D)) return false;
3772  const auto *RD = cast<CXXRecordDecl>(D);
3773  if (isa<ClassTemplatePartialSpecializationDecl>(RD))
3774  return true;
3775  if (RD->getDescribedClassTemplate() &&
3776  !isa<ClassTemplateSpecializationDecl>(RD))
3777  return true;
3778  return false;
3779 }
3780 #endif
3781 
3782 /// getInjectedClassNameType - Return the unique reference to the
3783 /// injected class name type for the specified templated declaration.
3785  QualType TST) const {
3786  assert(NeedsInjectedClassNameType(Decl));
3787  if (Decl->TypeForDecl) {
3788  assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
3789  } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
3790  assert(PrevDecl->TypeForDecl && "previous declaration has no type");
3791  Decl->TypeForDecl = PrevDecl->TypeForDecl;
3792  assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
3793  } else {
3794  Type *newType =
3795  new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
3796  Decl->TypeForDecl = newType;
3797  Types.push_back(newType);
3798  }
3799  return QualType(Decl->TypeForDecl, 0);
3800 }
3801 
3802 /// getTypeDeclType - Return the unique reference to the type for the
3803 /// specified type declaration.
3804 QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
3805  assert(Decl && "Passed null for Decl param");
3806  assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
3807 
3808  if (const auto *Typedef = dyn_cast<TypedefNameDecl>(Decl))
3809  return getTypedefType(Typedef);
3810 
3811  assert(!isa<TemplateTypeParmDecl>(Decl) &&
3812  "Template type parameter types are always available.");
3813 
3814  if (const auto *Record = dyn_cast<RecordDecl>(Decl)) {
3815  assert(Record->isFirstDecl() && "struct/union has previous declaration");
3816  assert(!NeedsInjectedClassNameType(Record));
3817  return getRecordType(Record);
3818  } else if (const auto *Enum = dyn_cast<EnumDecl>(Decl)) {
3819  assert(Enum->isFirstDecl() && "enum has previous declaration");
3820  return getEnumType(Enum);
3821  } else if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
3822  Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
3823  Decl->TypeForDecl = newType;
3824  Types.push_back(newType);
3825  } else
3826  llvm_unreachable("TypeDecl without a type?");
3827 
3828  return QualType(Decl->TypeForDecl, 0);
3829 }
3830 
3831 /// getTypedefType - Return the unique reference to the type for the
3832 /// specified typedef name decl.
3833 QualType
3835  QualType Canonical) const {
3836  if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3837 
3838  if (Canonical.isNull())
3839  Canonical = getCanonicalType(Decl->getUnderlyingType());
3840  auto *newType = new (*this, TypeAlignment)
3841  TypedefType(Type::Typedef, Decl, Canonical);
3842  Decl->TypeForDecl = newType;
3843  Types.push_back(newType);
3844  return QualType(newType, 0);
3845 }
3846 
3848  if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3849 
3850  if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
3851  if (PrevDecl->TypeForDecl)
3852  return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3853 
3854  auto *newType = new (*this, TypeAlignment) RecordType(Decl);
3855  Decl->TypeForDecl = newType;
3856  Types.push_back(newType);
3857  return QualType(newType, 0);
3858 }
3859 
3861  if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3862 
3863  if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
3864  if (PrevDecl->TypeForDecl)
3865  return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3866 
3867  auto *newType = new (*this, TypeAlignment) EnumType(Decl);
3868  Decl->TypeForDecl = newType;
3869  Types.push_back(newType);
3870  return QualType(newType, 0);
3871 }
3872 
3874  QualType modifiedType,
3875  QualType equivalentType) {
3876  llvm::FoldingSetNodeID id;
3877  AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
3878 
3879  void *insertPos = nullptr;
3880  AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3881  if (type) return QualType(type, 0);
3882 
3883  QualType canon = getCanonicalType(equivalentType);
3884  type = new (*this, TypeAlignment)
3885  AttributedType(canon, attrKind, modifiedType, equivalentType);
3886 
3887  Types.push_back(type);
3888  AttributedTypes.InsertNode(type, insertPos);
3889 
3890  return QualType(type, 0);
3891 }
3892 
3893 /// Retrieve a substitution-result type.
3894 QualType
3896  QualType Replacement) const {
3897  assert(Replacement.isCanonical()
3898  && "replacement types must always be canonical");
3899 
3900  llvm::FoldingSetNodeID ID;
3901  SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
3902  void *InsertPos = nullptr;
3903  SubstTemplateTypeParmType *SubstParm
3904  = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3905 
3906  if (!SubstParm) {
3907  SubstParm = new (*this, TypeAlignment)
3908  SubstTemplateTypeParmType(Parm, Replacement);
3909  Types.push_back(SubstParm);
3910  SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3911  }
3912 
3913  return QualType(SubstParm, 0);
3914 }
3915 
3916 /// Retrieve a
3918  const TemplateTypeParmType *Parm,
3919  const TemplateArgument &ArgPack) {
3920 #ifndef NDEBUG
3921  for (const auto &P : ArgPack.pack_elements()) {
3922  assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3923  assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
3924  }
3925 #endif
3926 
3927  llvm::FoldingSetNodeID ID;
3928  SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
3929  void *InsertPos = nullptr;
3930  if (SubstTemplateTypeParmPackType *SubstParm
3931  = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3932  return QualType(SubstParm, 0);
3933 
3934  QualType Canon;
3935  if (!Parm->isCanonicalUnqualified()) {
3936  Canon = getCanonicalType(QualType(Parm, 0));
3937  Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3938  ArgPack);
3939  SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3940  }
3941 
3942  auto *SubstParm
3943  = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3944  ArgPack);
3945  Types.push_back(SubstParm);
3946  SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos);
3947  return QualType(SubstParm, 0);
3948 }
3949 
3950 /// Retrieve the template type parameter type for a template
3951 /// parameter or parameter pack with the given depth, index, and (optionally)
3952 /// name.
3954  bool ParameterPack,
3955  TemplateTypeParmDecl *TTPDecl) const {
3956  llvm::FoldingSetNodeID ID;
3957  TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
3958  void *InsertPos = nullptr;
3959  TemplateTypeParmType *TypeParm
3960  = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3961 
3962  if (TypeParm)
3963  return QualType(TypeParm, 0);
3964 
3965  if (TTPDecl) {
3966  QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
3967  TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
3968 
3969  TemplateTypeParmType *TypeCheck
3970  = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3971  assert(!TypeCheck && "Template type parameter canonical type broken");
3972  (void)TypeCheck;
3973  } else
3974  TypeParm = new (*this, TypeAlignment)
3975  TemplateTypeParmType(Depth, Index, ParameterPack);
3976 
3977  Types.push_back(TypeParm);
3978  TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3979 
3980  return QualType(TypeParm, 0);
3981 }
3982 
3985  SourceLocation NameLoc,
3986  const TemplateArgumentListInfo &Args,
3987  QualType Underlying) const {
3988  assert(!Name.getAsDependentTemplateName() &&
3989  "No dependent template names here!");
3990  QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
3991 
3996  TL.setTemplateNameLoc(NameLoc);
3997  TL.setLAngleLoc(Args.getLAngleLoc());
3998  TL.setRAngleLoc(Args.getRAngleLoc());
3999  for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
4000  TL.setArgLocInfo(i, Args[i].getLocInfo());
4001  return DI;
4002 }
4003 
4004 QualType
4006  const TemplateArgumentListInfo &Args,
4007  QualType Underlying) const {
4008  assert(!Template.getAsDependentTemplateName() &&
4009  "No dependent template names here!");
4010 
4012  ArgVec.reserve(Args.size());
4013  for (const TemplateArgumentLoc &Arg : Args.arguments())
4014  ArgVec.push_back(Arg.getArgument());
4015 
4016  return getTemplateSpecializationType(Template, ArgVec, Underlying);
4017 }
4018 
4019 #ifndef NDEBUG
4021  for (const TemplateArgument &Arg : Args)
4022  if (Arg.isPackExpansion())
4023  return true;
4024 
4025  return true;
4026 }
4027 #endif
4028 
4029 QualType
4032  QualType Underlying) const {
4033  assert(!Template.getAsDependentTemplateName() &&
4034  "No dependent template names here!");
4035  // Look through qualified template names.
4036  if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
4037  Template = TemplateName(QTN->getTemplateDecl());
4038 
4039  bool IsTypeAlias =
4040  Template.getAsTemplateDecl() &&
4041  isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
4042  QualType CanonType;
4043  if (!Underlying.isNull())
4044  CanonType = getCanonicalType(Underlying);
4045  else {
4046  // We can get here with an alias template when the specialization contains
4047  // a pack expansion that does not match up with a parameter pack.
4048  assert((!IsTypeAlias || hasAnyPackExpansions(Args)) &&
4049  "Caller must compute aliased type");
4050  IsTypeAlias = false;
4051  CanonType = getCanonicalTemplateSpecializationType(Template, Args);
4052  }
4053 
4054  // Allocate the (non-canonical) template specialization type, but don't
4055  // try to unique it: these types typically have location information that
4056  // we don't unique and don't want to lose.
4057  void *Mem = Allocate(sizeof(TemplateSpecializationType) +
4058  sizeof(TemplateArgument) * Args.size() +
4059  (IsTypeAlias? sizeof(QualType) : 0),
4060  TypeAlignment);
4061  auto *Spec
4062  = new (Mem) TemplateSpecializationType(Template, Args, CanonType,
4063  IsTypeAlias ? Underlying : QualType());
4064 
4065  Types.push_back(Spec);
4066  return QualType(Spec, 0);
4067 }
4068 
4070  TemplateName Template, ArrayRef<TemplateArgument> Args) const {
4071  assert(!Template.getAsDependentTemplateName() &&
4072  "No dependent template names here!");
4073 
4074  // Look through qualified template names.
4075  if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
4076  Template = TemplateName(QTN->getTemplateDecl());
4077 
4078  // Build the canonical template specialization type.
4079  TemplateName CanonTemplate = getCanonicalTemplateName(Template);
4081  unsigned NumArgs = Args.size();
4082  CanonArgs.reserve(NumArgs);
4083  for (const TemplateArgument &Arg : Args)
4084  CanonArgs.push_back(getCanonicalTemplateArgument(Arg));
4085 
4086  // Determine whether this canonical template specialization type already
4087  // exists.
4088  llvm::FoldingSetNodeID ID;
4089  TemplateSpecializationType::Profile(ID, CanonTemplate,
4090  CanonArgs, *this);
4091 
4092  void *InsertPos = nullptr;
4094  = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
4095 
4096  if (!Spec) {
4097  // Allocate a new canonical template specialization type.
4098  void *Mem = Allocate((sizeof(TemplateSpecializationType) +
4099  sizeof(TemplateArgument) * NumArgs),
4100  TypeAlignment);
4101  Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
4102  CanonArgs,
4103  QualType(), QualType());
4104  Types.push_back(Spec);
4105  TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
4106  }
4107 
4108  assert(Spec->isDependentType() &&
4109  "Non-dependent template-id type must have a canonical type");
4110  return QualType(Spec, 0);
4111 }
4112 
4114  NestedNameSpecifier *NNS,
4115  QualType NamedType,
4116  TagDecl *OwnedTagDecl) const {
4117  llvm::FoldingSetNodeID ID;
4118  ElaboratedType::Profile(ID, Keyword, NNS, NamedType, OwnedTagDecl);
4119 
4120  void *InsertPos = nullptr;
4121  ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
4122  if (T)
4123  return QualType(T, 0);
4124 
4125  QualType Canon = NamedType;
4126  if (!Canon.isCanonical()) {
4127  Canon = getCanonicalType(NamedType);
4128  ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
4129  assert(!CheckT && "Elaborated canonical type broken");
4130  (void)CheckT;
4131  }
4132 
4133  T = new (*this, TypeAlignment)
4134  ElaboratedType(Keyword, NNS, NamedType, Canon, OwnedTagDecl);
4135  Types.push_back(T);
4136  ElaboratedTypes.InsertNode(T, InsertPos);
4137  return QualType(T, 0);
4138 }
4139 
4140 QualType
4142  llvm::FoldingSetNodeID ID;
4143  ParenType::Profile(ID, InnerType);
4144 
4145  void *InsertPos = nullptr;
4146  ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
4147  if (T)
4148  return QualType(T, 0);
4149 
4150  QualType Canon = InnerType;
4151  if (!Canon.isCanonical()) {
4152  Canon = getCanonicalType(InnerType);
4153  ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
4154  assert(!CheckT && "Paren canonical type broken");
4155  (void)CheckT;
4156  }
4157 
4158  T = new (*this, TypeAlignment) ParenType(InnerType, Canon);
4159  Types.push_back(T);
4160  ParenTypes.InsertNode(T, InsertPos);
4161  return QualType(T, 0);
4162 }
4163 
4165  NestedNameSpecifier *NNS,
4166  const IdentifierInfo *Name,
4167  QualType Canon) const {
4168  if (Canon.isNull()) {
4170  if (CanonNNS != NNS)
4171  Canon = getDependentNameType(Keyword, CanonNNS, Name);
4172  }
4173 
4174  llvm::FoldingSetNodeID ID;
4175  DependentNameType::Profile(ID, Keyword, NNS, Name);
4176 
4177  void *InsertPos = nullptr;
4179  = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
4180  if (T)
4181  return QualType(T, 0);
4182 
4183  T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon);
4184  Types.push_back(T);
4185  DependentNameTypes.InsertNode(T, InsertPos);
4186  return QualType(T, 0);
4187 }
4188 
4189 QualType
4191  ElaboratedTypeKeyword Keyword,
4192  NestedNameSpecifier *NNS,
4193  const IdentifierInfo *Name,
4194  const TemplateArgumentListInfo &Args) const {
4195  // TODO: avoid this copy
4197  for (unsigned I = 0, E = Args.size(); I != E; ++I)
4198  ArgCopy.push_back(Args[I].getArgument());
4199  return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy);
4200 }
4201 
4202 QualType
4204  ElaboratedTypeKeyword Keyword,
4205  NestedNameSpecifier *NNS,
4206  const IdentifierInfo *Name,
4207  ArrayRef<TemplateArgument> Args) const {
4208  assert((!NNS || NNS->isDependent()) &&
4209  "nested-name-specifier must be dependent");
4210 
4211  llvm::FoldingSetNodeID ID;
4212  DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
4213  Name, Args);
4214 
4215  void *InsertPos = nullptr;
4217  = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
4218  if (T)
4219  return QualType(T, 0);
4220 
4222 
4223  ElaboratedTypeKeyword CanonKeyword = Keyword;
4224  if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
4225 
4226  bool AnyNonCanonArgs = false;
4227  unsigned NumArgs = Args.size();
4228  SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
4229  for (unsigned I = 0; I != NumArgs; ++I) {
4230  CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
4231  if (!CanonArgs[I].structurallyEquals(Args[I]))
4232  AnyNonCanonArgs = true;
4233  }
4234 
4235  QualType Canon;
4236  if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
4237  Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
4238  Name,
4239  CanonArgs);
4240 
4241  // Find the insert position again.
4242  DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
4243  }
4244 
4245  void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
4246  sizeof(TemplateArgument) * NumArgs),
4247  TypeAlignment);
4248  T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
4249  Name, Args, Canon);
4250  Types.push_back(T);
4251  DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
4252  return QualType(T, 0);
4253 }
4254 
4256  TemplateArgument Arg;
4257  if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
4258  QualType ArgType = getTypeDeclType(TTP);
4259  if (TTP->isParameterPack())
4260  ArgType = getPackExpansionType(ArgType, None);
4261 
4262  Arg = TemplateArgument(ArgType);
4263  } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4264  Expr *E = new (*this) DeclRefExpr(
4265  NTTP, /*enclosing*/false,
4266  NTTP->getType().getNonLValueExprType(*this),
4267  Expr::getValueKindForType(NTTP->getType()), NTTP->getLocation());
4268 
4269  if (NTTP->isParameterPack())
4270  E = new (*this) PackExpansionExpr(DependentTy, E, NTTP->getLocation(),
4271  None);
4272  Arg = TemplateArgument(E);
4273  } else {
4274  auto *TTP = cast<TemplateTemplateParmDecl>(Param);
4275  if (TTP->isParameterPack())
4277  else
4278  Arg = TemplateArgument(TemplateName(TTP));
4279  }
4280 
4281  if (Param->isTemplateParameterPack())
4282  Arg = TemplateArgument::CreatePackCopy(*this, Arg);
4283 
4284  return Arg;
4285 }
4286 
4287 void
4290  Args.reserve(Args.size() + Params->size());
4291 
4292  for (NamedDecl *Param : *Params)
4293  Args.push_back(getInjectedTemplateArg(Param));
4294 }
4295 
4297  Optional<unsigned> NumExpansions) {
4298  llvm::FoldingSetNodeID ID;
4299  PackExpansionType::Profile(ID, Pattern, NumExpansions);
4300 
4301  assert(Pattern->containsUnexpandedParameterPack() &&
4302  "Pack expansions must expand one or more parameter packs");
4303  void *InsertPos = nullptr;
4305  = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
4306  if (T)
4307  return QualType(T, 0);
4308 
4309  QualType Canon;
4310  if (!Pattern.isCanonical()) {
4311  Canon = getCanonicalType(Pattern);
4312  // The canonical type might not contain an unexpanded parameter pack, if it
4313  // contains an alias template specialization which ignores one of its
4314  // parameters.
4315  if (Canon->containsUnexpandedParameterPack()) {
4316  Canon = getPackExpansionType(Canon, NumExpansions);
4317 
4318  // Find the insert position again, in case we inserted an element into
4319  // PackExpansionTypes and invalidated our insert position.
4320  PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
4321  }
4322  }
4323 
4324  T = new (*this, TypeAlignment)
4325  PackExpansionType(Pattern, Canon, NumExpansions);
4326  Types.push_back(T);
4327  PackExpansionTypes.InsertNode(T, InsertPos);
4328  return QualType(T, 0);
4329 }
4330 
4331 /// CmpProtocolNames - Comparison predicate for sorting protocols
4332 /// alphabetically.
4333 static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
4334  ObjCProtocolDecl *const *RHS) {
4335  return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
4336 }
4337 
4339  if (Protocols.empty()) return true;
4340 
4341  if (Protocols[0]->getCanonicalDecl() != Protocols[0])
4342  return false;
4343 
4344  for (unsigned i = 1; i != Protocols.size(); ++i)
4345  if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
4346  Protocols[i]->getCanonicalDecl() != Protocols[i])
4347  return false;
4348  return true;
4349 }
4350 
4351 static void
4353  // Sort protocols, keyed by name.
4354  llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
4355 
4356  // Canonicalize.
4357  for (ObjCProtocolDecl *&P : Protocols)
4358  P = P->getCanonicalDecl();
4359 
4360  // Remove duplicates.
4361  auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end());
4362  Protocols.erase(ProtocolsEnd, Protocols.end());
4363 }
4364 
4366  ObjCProtocolDecl * const *Protocols,
4367  unsigned NumProtocols) const {
4368  return getObjCObjectType(BaseType, {},
4369  llvm::makeArrayRef(Protocols, NumProtocols),
4370  /*isKindOf=*/false);
4371 }
4372 
4374  QualType baseType,
4375  ArrayRef<QualType> typeArgs,
4376  ArrayRef<ObjCProtocolDecl *> protocols,
4377  bool isKindOf) const {
4378  // If the base type is an interface and there aren't any protocols or
4379  // type arguments to add, then the interface type will do just fine.
4380  if (typeArgs.empty() && protocols.empty() && !isKindOf &&
4381  isa<ObjCInterfaceType>(baseType))
4382  return baseType;
4383 
4384  // Look in the folding set for an existing type.
4385  llvm::FoldingSetNodeID ID;
4386  ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
4387  void *InsertPos = nullptr;
4388  if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
4389  return QualType(QT, 0);
4390 
4391  // Determine the type arguments to be used for canonicalization,
4392  // which may be explicitly specified here or written on the base
4393  // type.
4394  ArrayRef<QualType> effectiveTypeArgs = typeArgs;
4395  if (effectiveTypeArgs.empty()) {
4396  if (const auto *baseObject = baseType->getAs<ObjCObjectType>())
4397  effectiveTypeArgs = baseObject->getTypeArgs();
4398  }
4399 
4400  // Build the canonical type, which has the canonical base type and a
4401  // sorted-and-uniqued list of protocols and the type arguments
4402  // canonicalized.
4403  QualType canonical;
4404  bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(),
4405  effectiveTypeArgs.end(),
4406  [&](QualType type) {
4407  return type.isCanonical();
4408  });
4409  bool protocolsSorted = areSortedAndUniqued(protocols);
4410  if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
4411  // Determine the canonical type arguments.
4412  ArrayRef<QualType> canonTypeArgs;
4413  SmallVector<QualType, 4> canonTypeArgsVec;
4414  if (!typeArgsAreCanonical) {
4415  canonTypeArgsVec.reserve(effectiveTypeArgs.size());
4416  for (auto typeArg : effectiveTypeArgs)
4417  canonTypeArgsVec.push_back(getCanonicalType(typeArg));
4418  canonTypeArgs = canonTypeArgsVec;
4419  } else {
4420  canonTypeArgs = effectiveTypeArgs;
4421  }
4422 
4423  ArrayRef<ObjCProtocolDecl *> canonProtocols;
4424  SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
4425  if (!protocolsSorted) {
4426  canonProtocolsVec.append(protocols.begin(), protocols.end());
4427  SortAndUniqueProtocols(canonProtocolsVec);
4428  canonProtocols = canonProtocolsVec;
4429  } else {
4430  canonProtocols = protocols;
4431  }
4432 
4433  canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
4434  canonProtocols, isKindOf);
4435 
4436  // Regenerate InsertPos.
4437  ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
4438  }
4439 
4440  unsigned size = sizeof(ObjCObjectTypeImpl);
4441  size += typeArgs.size() * sizeof(QualType);
4442  size += protocols.size() * sizeof(ObjCProtocolDecl *);
4443  void *mem = Allocate(size, TypeAlignment);
4444  auto *T =
4445  new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
4446  isKindOf);
4447 
4448  Types.push_back(T);
4449  ObjCObjectTypes.InsertNode(T, InsertPos);
4450  return QualType(T, 0);
4451 }
4452 
4453 /// Apply Objective-C protocol qualifiers to the given type.
4454 /// If this is for the canonical type of a type parameter, we can apply
4455 /// protocol qualifiers on the ObjCObjectPointerType.
4456 QualType
4458  ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
4459  bool allowOnPointerType) const {
4460  hasError = false;
4461 
4462  if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
4463  return getObjCTypeParamType(objT->getDecl(), protocols);
4464  }
4465 
4466  // Apply protocol qualifiers to ObjCObjectPointerType.
4467  if (allowOnPointerType) {
4468  if (const auto *objPtr =
4469  dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
4470  const ObjCObjectType *objT = objPtr->getObjectType();
4471  // Merge protocol lists and construct ObjCObjectType.
4472  SmallVector<ObjCProtocolDecl*, 8> protocolsVec;
4473  protocolsVec.append(objT->qual_begin(),
4474  objT->qual_end());
4475  protocolsVec.append(protocols.begin(), protocols.end());
4476  ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
4477  type = getObjCObjectType(
4478  objT->getBaseType(),
4479  objT->getTypeArgsAsWritten(),
4480  protocols,
4481  objT->isKindOfTypeAsWritten());
4482  return getObjCObjectPointerType(type);
4483  }
4484  }
4485 
4486  // Apply protocol qualifiers to ObjCObjectType.
4487  if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
4488  // FIXME: Check for protocols to which the class type is already
4489  // known to conform.
4490 
4491  return getObjCObjectType(objT->getBaseType(),
4492  objT->getTypeArgsAsWritten(),
4493  protocols,
4494  objT->isKindOfTypeAsWritten());
4495  }
4496 
4497  // If the canonical type is ObjCObjectType, ...
4498  if (type->isObjCObjectType()) {
4499  // Silently overwrite any existing protocol qualifiers.
4500  // TODO: determine whether that's the right thing to do.
4501 
4502  // FIXME: Check for protocols to which the class type is already
4503  // known to conform.
4504  return getObjCObjectType(type, {}, protocols, false);
4505  }
4506 
4507  // id<protocol-list>
4508  if (type->isObjCIdType()) {
4509  const auto *objPtr = type->castAs<ObjCObjectPointerType>();
4510  type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols,
4511  objPtr->isKindOfType());
4512  return getObjCObjectPointerType(type);
4513  }
4514 
4515  // Class<protocol-list>
4516  if (type->isObjCClassType()) {
4517  const auto *objPtr = type->castAs<ObjCObjectPointerType>();
4518  type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols,
4519  objPtr->isKindOfType());
4520  return getObjCObjectPointerType(type);
4521  }
4522 
4523  hasError = true;
4524  return type;
4525 }
4526 
4527 QualType
4529  ArrayRef<ObjCProtocolDecl *> protocols,
4530  QualType Canonical) const {
4531  // Look in the folding set for an existing type.
4532  llvm::FoldingSetNodeID ID;
4533  ObjCTypeParamType::Profile(ID, Decl, protocols);
4534  void *InsertPos = nullptr;
4535  if (ObjCTypeParamType *TypeParam =
4536  ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
4537  return QualType(TypeParam, 0);
4538 
4539  if (Canonical.isNull()) {
4540  // We canonicalize to the underlying type.
4541  Canonical = getCanonicalType(Decl->getUnderlyingType());
4542  if (!protocols.empty()) {
4543  // Apply the protocol qualifers.
4544  bool hasError;
4545  Canonical = applyObjCProtocolQualifiers(Canonical, protocols, hasError,
4546  true/*allowOnPointerType*/);
4547  assert(!hasError && "Error when apply protocol qualifier to bound type");
4548  }
4549  }
4550 
4551  unsigned size = sizeof(ObjCTypeParamType);
4552  size += protocols.size() * sizeof(ObjCProtocolDecl *);
4553  void *mem = Allocate(size, TypeAlignment);
4554  auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols);
4555 
4556  Types.push_back(newType);
4557  ObjCTypeParamTypes.InsertNode(newType, InsertPos);
4558  return QualType(newType, 0);
4559 }
4560 
4561 /// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
4562 /// protocol list adopt all protocols in QT's qualified-id protocol
4563 /// list.
4565  ObjCInterfaceDecl *IC) {
4566  if (!QT->isObjCQualifiedIdType())
4567  return false;
4568 
4569  if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) {
4570  // If both the right and left sides have qualifiers.
4571  for (auto *Proto : OPT->quals()) {
4572  if (!IC->ClassImplementsProtocol(Proto, false))
4573  return false;
4574  }
4575  return true;
4576  }
4577  return false;
4578 }
4579 
4580 /// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
4581 /// QT's qualified-id protocol list adopt all protocols in IDecl's list
4582 /// of protocols.
4584  ObjCInterfaceDecl *IDecl) {
4585  if (!QT->isObjCQualifiedIdType())
4586  return false;
4587  const auto *OPT = QT->getAs<ObjCObjectPointerType>();
4588  if (!OPT)
4589  return false;
4590  if (!IDecl->hasDefinition())
4591  return false;
4592  llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
4593  CollectInheritedProtocols(IDecl, InheritedProtocols);
4594  if (InheritedProtocols.empty())
4595  return false;
4596  // Check that if every protocol in list of id<plist> conforms to a protocol
4597  // of IDecl's, then bridge casting is ok.
4598  bool Conforms = false;
4599  for (auto *Proto : OPT->quals()) {
4600  Conforms = false;
4601  for (auto *PI : InheritedProtocols) {
4602  if (ProtocolCompatibleWithProtocol(Proto, PI)) {
4603  Conforms = true;
4604  break;
4605  }
4606  }
4607  if (!Conforms)
4608  break;
4609  }
4610  if (Conforms)
4611  return true;
4612 
4613  for (auto *PI : InheritedProtocols) {
4614  // If both the right and left sides have qualifiers.
4615  bool Adopts = false;
4616  for (auto *Proto : OPT->quals()) {
4617  // return 'true' if 'PI' is in the inheritance hierarchy of Proto
4618  if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
4619  break;
4620  }
4621  if (!Adopts)
4622  return false;
4623  }
4624  return true;
4625 }
4626 
4627 /// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
4628 /// the given object type.
4630  llvm::FoldingSetNodeID ID;
4631  ObjCObjectPointerType::Profile(ID, ObjectT);
4632 
4633  void *InsertPos = nullptr;
4634  if (ObjCObjectPointerType *QT =
4635  ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
4636  return QualType(QT, 0);
4637 
4638  // Find the canonical object type.
4639  QualType Canonical;
4640  if (!ObjectT.isCanonical()) {
4641  Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
4642 
4643  // Regenerate InsertPos.
4644  ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
4645  }
4646 
4647  // No match.
4648  void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
4649  auto *QType =
4650  new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
4651 
4652  Types.push_back(QType);
4653  ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
4654  return QualType(QType, 0);
4655 }
4656 
4657 /// getObjCInterfaceType - Return the unique reference to the type for the
4658 /// specified ObjC interface decl. The list of protocols is optional.
4660  ObjCInterfaceDecl *PrevDecl) const {
4661  if (Decl->TypeForDecl)
4662  return QualType(Decl->TypeForDecl, 0);
4663 
4664  if (PrevDecl) {
4665  assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
4666  Decl->TypeForDecl = PrevDecl->TypeForDecl;
4667  return QualType(PrevDecl->TypeForDecl, 0);
4668  }
4669 
4670  // Prefer the definition, if there is one.
4671  if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
4672  Decl = Def;
4673 
4674  void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
4675  auto *T = new (Mem) ObjCInterfaceType(Decl);
4676  Decl->TypeForDecl = T;
4677  Types.push_back(T);
4678  return QualType(T, 0);
4679 }
4680 
4681 /// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
4682 /// TypeOfExprType AST's (since expression's are never shared). For example,
4683 /// multiple declarations that refer to "typeof(x)" all contain different
4684 /// DeclRefExpr's. This doesn't effect the type checker, since it operates
4685 /// on canonical type's (which are always unique).
4687  TypeOfExprType *toe;
4688  if (tofExpr->isTypeDependent()) {
4689  llvm::FoldingSetNodeID ID;
4690  DependentTypeOfExprType::Profile(ID, *this, tofExpr);
4691 
4692  void *InsertPos = nullptr;
4694  = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
4695  if (Canon) {
4696  // We already have a "canonical" version of an identical, dependent
4697  // typeof(expr) type. Use that as our canonical type.
4698  toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
4699  QualType((TypeOfExprType*)Canon, 0));
4700  } else {
4701  // Build a new, canonical typeof(expr) type.
4702  Canon
4703  = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
4704  DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
4705  toe = Canon;
4706  }
4707  } else {
4708  QualType Canonical = getCanonicalType(tofExpr->getType());
4709  toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
4710  }
4711  Types.push_back(toe);
4712  return QualType(toe, 0);
4713 }
4714 
4715 /// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
4716 /// TypeOfType nodes. The only motivation to unique these nodes would be
4717 /// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
4718 /// an issue. This doesn't affect the type checker, since it operates
4719 /// on canonical types (which are always unique).
4721  QualType Canonical = getCanonicalType(tofType);
4722  auto *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
4723  Types.push_back(tot);
4724  return QualType(tot, 0);
4725 }
4726 
4727 /// Unlike many "get<Type>" functions, we don't unique DecltypeType
4728 /// nodes. This would never be helpful, since each such type has its own
4729 /// expression, and would not give a significant memory saving, since there
4730 /// is an Expr tree under each such type.
4732  DecltypeType *dt;
4733 
4734  // C++11 [temp.type]p2:
4735  // If an expression e involves a template parameter, decltype(e) denotes a
4736  // unique dependent type. Two such decltype-specifiers refer to the same
4737  // type only if their expressions are equivalent (14.5.6.1).
4738  if (e->isInstantiationDependent()) {
4739  llvm::FoldingSetNodeID ID;
4740  DependentDecltypeType::Profile(ID, *this, e);
4741 
4742  void *InsertPos = nullptr;
4743  DependentDecltypeType *Canon
4744  = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
4745  if (!Canon) {
4746  // Build a new, canonical decltype(expr) type.
4747  Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
4748  DependentDecltypeTypes.InsertNode(Canon, InsertPos);
4749  }
4750  dt = new (*this, TypeAlignment)
4751  DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
4752  } else {
4753  dt = new (*this, TypeAlignment)
4754  DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
4755  }
4756  Types.push_back(dt);
4757  return QualType(dt, 0);
4758 }
4759 
4760 /// getUnaryTransformationType - We don't unique these, since the memory
4761 /// savings are minimal and these are rare.
4763  QualType UnderlyingType,
4765  const {
4766  UnaryTransformType *ut = nullptr;
4767 
4768  if (BaseType->isDependentType()) {
4769  // Look in the folding set for an existing type.
4770  llvm::FoldingSetNodeID ID;
4772 
4773  void *InsertPos = nullptr;
4775  = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
4776 
4777  if (!Canon) {
4778  // Build a new, canonical __underlying_type(type) type.
4779  Canon = new (*this, TypeAlignment)
4781  Kind);
4782  DependentUnaryTransformTypes.InsertNode(Canon, InsertPos);
4783  }
4784  ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4785  QualType(), Kind,
4786  QualType(Canon, 0));
4787  } else {
4788  QualType CanonType = getCanonicalType(UnderlyingType);
4789  ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4790  UnderlyingType, Kind,
4791  CanonType);
4792  }
4793  Types.push_back(ut);
4794  return QualType(ut, 0);
4795 }
4796 
4797 /// getAutoType - Return the uniqued reference to the 'auto' type which has been
4798 /// deduced to the given type, or to the canonical undeduced 'auto' type, or the
4799 /// canonical deduced-but-dependent 'auto' type.
4801  bool IsDependent) const {
4802  if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto && !IsDependent)
4803  return getAutoDeductType();
4804 
4805  // Look in the folding set for an existing type.
4806  void *InsertPos = nullptr;
4807  llvm::FoldingSetNodeID ID;
4808  AutoType::Profile(ID, DeducedType, Keyword, IsDependent);
4809  if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
4810  return QualType(AT, 0);
4811 
4812  auto *AT = new (*this, TypeAlignment)
4813  AutoType(DeducedType, Keyword, IsDependent);
4814  Types.push_back(AT);
4815  if (InsertPos)
4816  AutoTypes.InsertNode(AT, InsertPos);
4817  return QualType(AT, 0);
4818 }
4819 
4820 /// Return the uniqued reference to the deduced template specialization type
4821 /// which has been deduced to the given type, or to the canonical undeduced
4822 /// such type, or the canonical deduced-but-dependent such type.
4824  TemplateName Template, QualType DeducedType, bool IsDependent) const {
4825  // Look in the folding set for an existing type.
4826  void *InsertPos = nullptr;
4827  llvm::FoldingSetNodeID ID;
4828  DeducedTemplateSpecializationType::Profile(ID, Template, DeducedType,
4829  IsDependent);
4831  DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
4832  return QualType(DTST, 0);
4833 
4834  auto *DTST = new (*this, TypeAlignment)
4835  DeducedTemplateSpecializationType(Template, DeducedType, IsDependent);
4836  Types.push_back(DTST);
4837  if (InsertPos)
4838  DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos);
4839  return QualType(DTST, 0);
4840 }
4841 
4842 /// getAtomicType - Return the uniqued reference to the atomic type for
4843 /// the given value type.
4845  // Unique pointers, to guarantee there is only one pointer of a particular
4846  // structure.
4847  llvm::FoldingSetNodeID ID;
4848  AtomicType::Profile(ID, T);
4849 
4850  void *InsertPos = nullptr;
4851  if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
4852  return QualType(AT, 0);
4853 
4854  // If the atomic value type isn't canonical, this won't be a canonical type
4855  // either, so fill in the canonical type field.
4856  QualType Canonical;
4857  if (!T.isCanonical()) {
4858  Canonical = getAtomicType(getCanonicalType(T));
4859 
4860  // Get the new insert position for the node we care about.
4861  AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
4862  assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4863  }
4864  auto *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
4865  Types.push_back(New);
4866  AtomicTypes.InsertNode(New, InsertPos);
4867  return QualType(New, 0);
4868 }
4869 
4870 /// getAutoDeductType - Get type pattern for deducing against 'auto'.
4872  if (AutoDeductTy.isNull())
4875  /*dependent*/false),
4876  0);
4877  return AutoDeductTy;
4878 }
4879 
4880 /// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
4882  if (AutoRRefDeductTy.isNull())
4884  assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
4885  return AutoRRefDeductTy;
4886 }
4887 
4888 /// getTagDeclType - Return the unique reference to the type for the
4889 /// specified TagDecl (struct/union/class/enum) decl.
4891  assert(Decl);
4892  // FIXME: What is the design on getTagDeclType when it requires casting
4893  // away const? mutable?
4894  return getTypeDeclType(const_cast<TagDecl*>(Decl));
4895 }
4896 
4897 /// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
4898 /// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
4899 /// needs to agree with the definition in <stddef.h>.
4901  return getFromTargetType(Target->getSizeType());
4902 }
4903 
4904 /// Return the unique signed counterpart of the integer type
4905 /// corresponding to size_t.
4907  return getFromTargetType(Target->getSignedSizeType());
4908 }
4909 
4910 /// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
4912  return getFromTargetType(Target->getIntMaxType());
4913 }
4914 
4915 /// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
4917  return getFromTargetType(Target->getUIntMaxType());
4918 }
4919 
4920 /// getSignedWCharType - Return the type of "signed wchar_t".
4921 /// Used when in C++, as a GCC extension.
4923  // FIXME: derive from "Target" ?
4924  return WCharTy;
4925 }
4926 
4927 /// getUnsignedWCharType - Return the type of "unsigned wchar_t".
4928 /// Used when in C++, as a GCC extension.
4930  // FIXME: derive from "Target" ?
4931  return UnsignedIntTy;
4932 }
4933 
4935  return getFromTargetType(Target->getIntPtrType());
4936 }
4937 
4940 }
4941 
4942 /// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
4943 /// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
4945  return getFromTargetType(Target->getPtrDiffType(0));
4946 }
4947 
4948 /// Return the unique unsigned counterpart of "ptrdiff_t"
4949 /// integer type. The standard (C11 7.21.6.1p7) refers to this type
4950 /// in the definition of %tu format specifier.
4952  return getFromTargetType(Target->getUnsignedPtrDiffType(0));
4953 }
4954 
4955 /// Return the unique type for "pid_t" defined in
4956 /// <sys/types.h>. We need this to compute the correct type for vfork().
4958  return getFromTargetType(Target->getProcessIDType());
4959 }
4960 
4961 //===----------------------------------------------------------------------===//
4962 // Type Operators
4963 //===----------------------------------------------------------------------===//
4964 
4966  // Push qualifiers into arrays, and then discard any remaining
4967  // qualifiers.
4968  T = getCanonicalType(T);
4970  const Type *Ty = T.getTypePtr();
4971  QualType Result;
4972  if (isa<ArrayType>(Ty)) {
4973  Result = getArrayDecayedType(QualType(Ty,0));
4974  } else if (isa<FunctionType>(Ty)) {
4975  Result = getPointerType(QualType(Ty, 0));
4976  } else {
4977  Result = QualType(Ty, 0);
4978  }
4979 
4980  return CanQualType::CreateUnsafe(Result);
4981 }
4982 
4984  Qualifiers &quals) {
4985  SplitQualType splitType = type.getSplitUnqualifiedType();
4986 
4987  // FIXME: getSplitUnqualifiedType() actually walks all the way to
4988  // the unqualified desugared type and then drops it on the floor.
4989  // We then have to strip that sugar back off with
4990  // getUnqualifiedDesugaredType(), which is silly.
4991  const auto *AT =
4992  dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
4993 
4994  // If we don't have an array, just use the results in splitType.
4995  if (!AT) {
4996  quals = splitType.Quals;
4997  return QualType(splitType.Ty, 0);
4998  }
4999 
5000  // Otherwise, recurse on the array's element type.
5001  QualType elementType = AT->getElementType();
5002  QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
5003 
5004  // If that didn't change the element type, AT has no qualifiers, so we
5005  // can just use the results in splitType.
5006  if (elementType == unqualElementType) {
5007  assert(quals.empty()); // from the recursive call
5008  quals = splitType.Quals;
5009  return QualType(splitType.Ty, 0);
5010  }
5011 
5012  // Otherwise, add in the qualifiers from the outermost type, then
5013  // build the type back up.
5014  quals.addConsistentQualifiers(splitType.Quals);
5015 
5016  if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
5017  return getConstantArrayType(unqualElementType, CAT->getSize(),
5018  CAT->getSizeModifier(), 0);
5019  }
5020 
5021  if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) {
5022  return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
5023  }
5024 
5025  if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) {
5026  return getVariableArrayType(unqualElementType,
5027  VAT->getSizeExpr(),
5028  VAT->getSizeModifier(),
5029  VAT->getIndexTypeCVRQualifiers(),
5030  VAT->getBracketsRange());
5031  }
5032 
5033  const auto *DSAT = cast<DependentSizedArrayType>(AT);
5034  return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
5035  DSAT->getSizeModifier(), 0,
5036  SourceRange());
5037 }
5038 
5039 /// Attempt to unwrap two types that may both be array types with the same bound
5040 /// (or both be array types of unknown bound) for the purpose of comparing the
5041 /// cv-decomposition of two types per C++ [conv.qual].
5043  bool UnwrappedAny = false;
5044  while (true) {
5045  auto *AT1 = getAsArrayType(T1);
5046  if (!AT1) return UnwrappedAny;
5047 
5048  auto *AT2 = getAsArrayType(T2);
5049  if (!AT2) return UnwrappedAny;
5050 
5051  // If we don't have two array types with the same constant bound nor two
5052  // incomplete array types, we've unwrapped everything we can.
5053  if (auto *CAT1 = dyn_cast<ConstantArrayType>(AT1)) {
5054  auto *CAT2 = dyn_cast<ConstantArrayType>(AT2);
5055  if (!CAT2 || CAT1->getSize() != CAT2->getSize())
5056  return UnwrappedAny;
5057  } else if (!isa<IncompleteArrayType>(AT1) ||
5058  !isa<IncompleteArrayType>(AT2)) {
5059  return UnwrappedAny;
5060  }
5061 
5062  T1 = AT1->getElementType();
5063  T2 = AT2->getElementType();
5064  UnwrappedAny = true;
5065  }
5066 }
5067 
5068 /// Attempt to unwrap two types that may be similar (C++ [conv.qual]).
5069 ///
5070 /// If T1 and T2 are both pointer types of the same kind, or both array types
5071 /// with the same bound, unwraps layers from T1 and T2 until a pointer type is
5072 /// unwrapped. Top-level qualifiers on T1 and T2 are ignored.
5073 ///
5074 /// This function will typically be called in a loop that successively
5075 /// "unwraps" pointer and pointer-to-member types to compare them at each
5076 /// level.
5077 ///
5078 /// \return \c true if a pointer type was unwrapped, \c false if we reached a
5079 /// pair of types that can't be unwrapped further.
5081  UnwrapSimilarArrayTypes(T1, T2);
5082 
5083  const auto *T1PtrType = T1->getAs<PointerType>();
5084  const auto *T2PtrType = T2->getAs<PointerType>();
5085  if (T1PtrType && T2PtrType) {
5086  T1 = T1PtrType->getPointeeType();
5087  T2 = T2PtrType->getPointeeType();
5088  return true;
5089  }
5090 
5091  const auto *T1MPType = T1->getAs<MemberPointerType>();
5092  const auto *T2MPType = T2->getAs<MemberPointerType>();
5093  if (T1MPType && T2MPType &&
5094  hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
5095  QualType(T2MPType->getClass(), 0))) {
5096  T1 = T1MPType->getPointeeType();
5097  T2 = T2MPType->getPointeeType();
5098  return true;
5099  }
5100 
5101  if (getLangOpts().ObjC1) {
5102  const auto *T1OPType = T1->getAs<ObjCObjectPointerType>();
5103  const auto *T2OPType = T2->getAs<ObjCObjectPointerType>();
5104  if (T1OPType && T2OPType) {
5105  T1 = T1OPType->getPointeeType();
5106  T2 = T2OPType->getPointeeType();
5107  return true;
5108  }
5109  }
5110 
5111  // FIXME: Block pointers, too?
5112 
5113  return false;
5114 }
5115 
5117  while (true) {
5118  Qualifiers Quals;
5119  T1 = getUnqualifiedArrayType(T1, Quals);
5120  T2 = getUnqualifiedArrayType(T2, Quals);
5121  if (hasSameType(T1, T2))
5122  return true;
5123  if (!UnwrapSimilarTypes(T1, T2))
5124  return false;
5125  }
5126 }
5127 
5129  while (true) {
5130  Qualifiers Quals1, Quals2;
5131  T1 = getUnqualifiedArrayType(T1, Quals1);
5132  T2 = getUnqualifiedArrayType(T2, Quals2);
5133 
5134  Quals1.removeCVRQualifiers();
5135  Quals2.removeCVRQualifiers();
5136  if (Quals1 != Quals2)
5137  return false;
5138 
5139  if (hasSameType(T1, T2))
5140  return true;
5141 
5142  if (!UnwrapSimilarTypes(T1, T2))
5143  return false;
5144  }
5145 }
5146 
5149  SourceLocation NameLoc) const {
5150  switch (Name.getKind()) {
5153  // DNInfo work in progress: CHECKME: what about DNLoc?
5155  NameLoc);
5156 
5159  // DNInfo work in progress: CHECKME: what about DNLoc?
5160  return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
5161  }
5162 
5165  DeclarationName DName;
5166  if (DTN->isIdentifier()) {
5168  return DeclarationNameInfo(DName, NameLoc);
5169  } else {
5171  // DNInfo work in progress: FIXME: source locations?
5172  DeclarationNameLoc DNLoc;
5175  return DeclarationNameInfo(DName, NameLoc, DNLoc);
5176  }
5177  }
5178 
5182  return DeclarationNameInfo(subst->getParameter()->getDeclName(),
5183  NameLoc);
5184  }
5185 
5190  NameLoc);
5191  }
5192  }
5193 
5194  llvm_unreachable("bad template name kind!");
5195 }
5196 
5198  switch (Name.getKind()) {
5200  case TemplateName::Template: {
5201  TemplateDecl *Template = Name.getAsTemplateDecl();
5202  if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Template))
5203  Template = getCanonicalTemplateTemplateParmDecl(TTP);
5204 
5205  // The canonical template name is the canonical template declaration.
5206  return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
5207  }
5208 
5210  llvm_unreachable("cannot canonicalize overloaded template");
5211 
5214  assert(DTN && "Non-dependent template names must refer to template decls.");
5215  return DTN->CanonicalTemplateName;
5216  }
5217 
5221  return getCanonicalTemplateName(subst->getReplacement());
5222  }
5223 
5227  TemplateTemplateParmDecl *canonParameter
5228  = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
5229  TemplateArgument canonArgPack
5231  return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
5232  }
5233  }
5234 
5235  llvm_unreachable("bad template name!");
5236 }
5237 
5239  X = getCanonicalTemplateName(X);
5240  Y = getCanonicalTemplateName(Y);
5241  return X.getAsVoidPointer() == Y.getAsVoidPointer();
5242 }
5243 
5246  switch (Arg.getKind()) {
5248  return Arg;
5249 
5251  return Arg;
5252 
5254  auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
5255  return TemplateArgument(D, Arg.getParamTypeForDecl());
5256  }
5257 
5260  /*isNullPtr*/true);
5261 
5264 
5268  Arg.getNumTemplateExpansions());
5269 
5272 
5275 
5276  case TemplateArgument::Pack: {
5277  if (Arg.pack_size() == 0)
5278  return Arg;
5279 
5280  auto *CanonArgs = new (*this) TemplateArgument[Arg.pack_size()];
5281  unsigned Idx = 0;
5283  AEnd = Arg.pack_end();
5284  A != AEnd; (void)++A, ++Idx)
5285  CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
5286 
5287  return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size()));
5288  }
5289  }
5290 
5291  // Silence GCC warning
5292  llvm_unreachable("Unhandled template argument kind");
5293 }
5294 
5297  if (!NNS)
5298  return nullptr;
5299 
5300  switch (NNS->getKind()) {
5302  // Canonicalize the prefix but keep the identifier the same.
5303  return NestedNameSpecifier::Create(*this,
5305  NNS->getAsIdentifier());
5306 
5308  // A namespace is canonical; build a nested-name-specifier with
5309  // this namespace and no prefix.
5310  return NestedNameSpecifier::Create(*this, nullptr,
5312 
5314  // A namespace is canonical; build a nested-name-specifier with
5315  // this namespace and no prefix.
5316  return NestedNameSpecifier::Create(*this, nullptr,
5318  ->getOriginalNamespace());
5319 
5322  QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
5323 
5324  // If we have some kind of dependent-named type (e.g., "typename T::type"),
5325  // break it apart into its prefix and identifier, then reconsititute those
5326  // as the canonical nested-name-specifier. This is required to canonicalize
5327  // a dependent nested-name-specifier involving typedefs of dependent-name
5328  // types, e.g.,
5329  // typedef typename T::type T1;
5330  // typedef typename T1::type T2;
5331  if (const auto *DNT = T->getAs<DependentNameType>())
5332  return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
5333  const_cast<IdentifierInfo *>(DNT->getIdentifier()));
5334 
5335  // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
5336  // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
5337  // first place?
5338  return NestedNameSpecifier::Create(*this, nullptr, false,
5339  const_cast<Type *>(T.getTypePtr()));
5340  }
5341 
5344  // The global specifier and __super specifer are canonical and unique.
5345  return NNS;
5346  }
5347 
5348  llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
5349 }
5350 
5352  // Handle the non-qualified case efficiently.
5353  if (!T.hasLocalQualifiers()) {
5354  // Handle the common positive case fast.
5355  if (const auto *AT = dyn_cast<ArrayType>(T))
5356  return AT;
5357  }
5358 
5359  // Handle the common negative case fast.
5360  if (!isa<ArrayType>(T.getCanonicalType()))
5361  return nullptr;
5362 
5363  // Apply any qualifiers from the array type to the element type. This
5364  // implements C99 6.7.3p8: "If the specification of an array type includes
5365  // any type qualifiers, the element type is so qualified, not the array type."
5366 
5367  // If we get here, we either have type qualifiers on the type, or we have
5368  // sugar such as a typedef in the way. If we have type qualifiers on the type
5369  // we must propagate them down into the element type.
5370 
5372  Qualifiers qs = split.Quals;
5373 
5374  // If we have a simple case, just return now.
5375  const auto *ATy = dyn_cast<ArrayType>(split.Ty);
5376  if (!ATy || qs.empty())
5377  return ATy;
5378 
5379  // Otherwise, we have an array and we have qualifiers on it. Push the
5380  // qualifiers into the array element type and return a new array type.
5381  QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
5382 
5383  if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy))
5384  return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
5385  CAT->getSizeModifier(),
5386  CAT->getIndexTypeCVRQualifiers()));
5387  if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy))
5388  return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
5389  IAT->getSizeModifier(),
5390  IAT->getIndexTypeCVRQualifiers()));
5391 
5392  if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy))
5393  return cast<ArrayType>(
5394  getDependentSizedArrayType(NewEltTy,
5395  DSAT->getSizeExpr(),
5396  DSAT->getSizeModifier(),
5397  DSAT->getIndexTypeCVRQualifiers(),
5398  DSAT->getBracketsRange()));
5399 
5400  const auto *VAT = cast<VariableArrayType>(ATy);
5401  return cast<ArrayType>(getVariableArrayType(NewEltTy,
5402  VAT->getSizeExpr(),
5403  VAT->getSizeModifier(),
5404  VAT->getIndexTypeCVRQualifiers(),
5405  VAT->getBracketsRange()));
5406 }
5407 
5409  if (T->isArrayType() || T->isFunctionType())
5410  return getDecayedType(T);
5411  return T;
5412 }
5413 
5416  T = getAdjustedParameterType(T);
5417  return T.getUnqualifiedType();
5418 }
5419 
5421  // C++ [except.throw]p3:
5422  // A throw-expression initializes a temporary object, called the exception
5423  // object, the type of which is determined by removing any top-level
5424  // cv-qualifiers from the static type of the operand of throw and adjusting
5425  // the type from "array of T" or "function returning T" to "pointer to T"
5426  // or "pointer to function returning T", [...]
5428  if (T->isArrayType() || T->isFunctionType())
5429  T = getDecayedType(T);
5430  return T.getUnqualifiedType();
5431 }
5432 
5433 /// getArrayDecayedType - Return the properly qualified result of decaying the
5434 /// specified array type to a pointer. This operation is non-trivial when
5435 /// handling typedefs etc. The canonical type of "T" must be an array type,
5436 /// this returns a pointer to a properly qualified element of the array.
5437 ///
5438 /// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
5440  // Get the element type with 'getAsArrayType' so that we don't lose any
5441  // typedefs in the element type of the array. This also handles propagation
5442  // of type qualifiers from the array type into the element type if present
5443  // (C99 6.7.3p8).
5444  const ArrayType *PrettyArrayType = getAsArrayType(Ty);
5445  assert(PrettyArrayType && "Not an array type!");
5446 
5447  QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
5448 
5449  // int x[restrict 4] -> int *restrict
5451  PrettyArrayType->getIndexTypeQualifiers());
5452 
5453  // int x[_Nullable] -> int * _Nullable
5454  if (auto Nullability = Ty->getNullability(*this)) {
5455  Result = const_cast<ASTContext *>(this)->getAttributedType(
5457  }
5458  return Result;
5459 }
5460 
5462  return getBaseElementType(array->getElementType());
5463 }
5464 
5466  Qualifiers qs;
5467  while (true) {
5468  SplitQualType split = type.getSplitDesugaredType();
5469  const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
5470  if (!array) break;
5471 
5472  type = array->getElementType();
5473  qs.addConsistentQualifiers(split.Quals);
5474  }
5475 
5476  return getQualifiedType(type, qs);
5477 }
5478 
5479 /// getConstantArrayElementCount - Returns number of constant array elements.
5480 uint64_t
5482  uint64_t ElementCount = 1;
5483  do {
5484  ElementCount *= CA->getSize().getZExtValue();
5485  CA = dyn_cast_or_null<ConstantArrayType>(
5487  } while (CA);
5488  return ElementCount;
5489 }
5490 
5491 /// getFloatingRank - Return a relative rank for floating point types.
5492 /// This routine will assert if passed a built-in type that isn't a float.
5494  if (const auto *CT = T->getAs<ComplexType>())
5495  return getFloatingRank(CT->getElementType());
5496 
5497  assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
5498  switch (T->getAs<BuiltinType>()->getKind()) {
5499  default: llvm_unreachable("getFloatingRank(): not a floating type");
5500  case BuiltinType::Float16: return Float16Rank;
5501  case BuiltinType::Half: return HalfRank;
5502  case BuiltinType::Float: return FloatRank;
5503  case BuiltinType::Double: return DoubleRank;
5504  case BuiltinType::LongDouble: return LongDoubleRank;
5505  case BuiltinType::Float128: return Float128Rank;
5506  }
5507 }
5508 
5509 /// getFloatingTypeOfSizeWithinDomain - Returns a real floating
5510 /// point or a complex type (based on typeDomain/typeSize).
5511 /// 'typeDomain' is a real floating point or complex type.
5512 /// 'typeSize' is a real floating point or complex type.
5514  QualType Domain) const {
5515  FloatingRank EltRank = getFloatingRank(Size);
5516  if (Domain->isComplexType()) {
5517  switch (EltRank) {
5518  case Float16Rank:
5519  case HalfRank: llvm_unreachable("Complex half is not supported");
5520  case FloatRank: return FloatComplexTy;
5521  case DoubleRank: return DoubleComplexTy;
5522  case LongDoubleRank: return LongDoubleComplexTy;
5523  case Float128Rank: return Float128ComplexTy;
5524  }
5525  }
5526 
5527  assert(Domain->isRealFloatingType() && "Unknown domain!");
5528  switch (EltRank) {
5529  case Float16Rank: return HalfTy;
5530  case HalfRank: return HalfTy;
5531  case FloatRank: return FloatTy;
5532  case DoubleRank: return DoubleTy;
5533  case LongDoubleRank: return LongDoubleTy;
5534  case Float128Rank: return Float128Ty;
5535  }
5536  llvm_unreachable("getFloatingRank(): illegal value for rank");
5537 }
5538 
5539 /// getFloatingTypeOrder - Compare the rank of the two specified floating
5540 /// point types, ignoring the domain of the type (i.e. 'double' ==
5541 /// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
5542 /// LHS < RHS, return -1.
5544  FloatingRank LHSR = getFloatingRank(LHS);
5545  FloatingRank RHSR = getFloatingRank(RHS);
5546 
5547  if (LHSR == RHSR)
5548  return 0;
5549  if (LHSR > RHSR)
5550  return 1;
5551  return -1;
5552 }
5553 
5554 /// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
5555 /// routine will assert if passed a built-in type that isn't an integer or enum,
5556 /// or if it is not canonicalized.
5557 unsigned ASTContext::getIntegerRank(const Type *T) const {
5558  assert(T->isCanonicalUnqualified() && "T should be canonicalized");
5559 
5560  switch (cast<BuiltinType>(T)->getKind()) {
5561  default: llvm_unreachable("getIntegerRank(): not a built-in integer");
5562  case BuiltinType::Bool:
5563  return 1 + (getIntWidth(BoolTy) << 3);
5564  case BuiltinType::Char_S:
5565  case BuiltinType::Char_U:
5566  case BuiltinType::SChar:
5567  case BuiltinType::UChar:
5568  return 2 + (getIntWidth(CharTy) << 3);
5569  case BuiltinType::Short:
5570  case BuiltinType::UShort:
5571  return 3 + (getIntWidth(ShortTy) << 3);
5572  case BuiltinType::Int:
5573  case BuiltinType::UInt:
5574  return 4 + (getIntWidth(IntTy) << 3);
5575  case BuiltinType::Long:
5576  case BuiltinType::ULong:
5577  return 5 + (getIntWidth(LongTy) << 3);
5578  case BuiltinType::LongLong:
5579  case BuiltinType::ULongLong:
5580  return 6 + (getIntWidth(LongLongTy) << 3);
5581  case BuiltinType::Int128:
5582  case BuiltinType::UInt128:
5583  return 7 + (getIntWidth(Int128Ty) << 3);
5584  }
5585 }
5586 
5587 /// Whether this is a promotable bitfield reference according
5588 /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
5589 ///
5590 /// \returns the type this bit-field will promote to, or NULL if no
5591 /// promotion occurs.
5593  if (E->isTypeDependent() || E->isValueDependent())
5594  return {};
5595 
5596  // C++ [conv.prom]p5:
5597  // If the bit-field has an enumerated type, it is treated as any other
5598  // value of that type for promotion purposes.
5599  if (getLangOpts().CPlusPlus && E->getType()->isEnumeralType())
5600  return {};
5601 
5602  // FIXME: We should not do this unless E->refersToBitField() is true. This
5603  // matters in C where getSourceBitField() will find bit-fields for various
5604  // cases where the source expression is not a bit-field designator.
5605 
5606  FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
5607  if (!Field)
5608  return {};
5609 
5610  QualType FT = Field->getType();
5611 
5612  uint64_t BitWidth = Field->getBitWidthValue(*this);
5613  uint64_t IntSize = getTypeSize(IntTy);
5614  // C++ [conv.prom]p5:
5615  // A prvalue for an integral bit-field can be converted to a prvalue of type
5616  // int if int can represent all the values of the bit-field; otherwise, it
5617  // can be converted to unsigned int if unsigned int can represent all the
5618  // values of the bit-field. If the bit-field is larger yet, no integral
5619  // promotion applies to it.
5620  // C11 6.3.1.1/2:
5621  // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
5622  // If an int can represent all values of the original type (as restricted by
5623  // the width, for a bit-field), the value is converted to an int; otherwise,
5624  // it is converted to an unsigned int.
5625  //
5626  // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
5627  // We perform that promotion here to match GCC and C++.
5628  // FIXME: C does not permit promotion of an enum bit-field whose rank is
5629  // greater than that of 'int'. We perform that promotion to match GCC.
5630  if (BitWidth < IntSize)
5631  return IntTy;
5632 
5633  if (BitWidth == IntSize)
5634  return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
5635 
5636  // Bit-fields wider than int are not subject to promotions, and therefore act
5637  // like the base type. GCC has some weird bugs in this area that we
5638  // deliberately do not follow (GCC follows a pre-standard resolution to
5639  // C's DR315 which treats bit-width as being part of the type, and this leaks
5640  // into their semantics in some cases).
5641  return {};
5642 }
5643 
5644 /// getPromotedIntegerType - Returns the type that Promotable will
5645 /// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
5646 /// integer type.
5648  assert(!Promotable.isNull());
5649  assert(Promotable->isPromotableIntegerType());
5650  if (const auto *ET = Promotable->getAs<EnumType>())
5651  return ET->getDecl()->getPromotionType();
5652 
5653  if (const auto *BT = Promotable->getAs<BuiltinType>()) {
5654  // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
5655  // (3.9.1) can be converted to a prvalue of the first of the following
5656  // types that can represent all the values of its underlying type:
5657  // int, unsigned int, long int, unsigned long int, long long int, or
5658  // unsigned long long int [...]
5659  // FIXME: Is there some better way to compute this?
5660  if (BT->getKind() == BuiltinType::WChar_S ||
5661  BT->getKind() == BuiltinType::WChar_U ||
5662  BT->getKind() == BuiltinType::Char8 ||
5663  BT->getKind() == BuiltinType::Char16 ||
5664  BT->getKind() == BuiltinType::Char32) {
5665  bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
5666  uint64_t FromSize = getTypeSize(BT);
5667  QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
5669  for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
5670  uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
5671  if (FromSize < ToSize ||
5672  (FromSize == ToSize &&
5673  FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
5674  return PromoteTypes[Idx];
5675  }
5676  llvm_unreachable("char type should fit into long long");
5677  }
5678  }
5679 
5680  // At this point, we should have a signed or unsigned integer type.
5681  if (Promotable->isSignedIntegerType())
5682  return IntTy;
5683  uint64_t PromotableSize = getIntWidth(Promotable);
5684  uint64_t IntSize = getIntWidth(IntTy);
5685  assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
5686  return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
5687 }
5688 
5689 /// Recurses in pointer/array types until it finds an objc retainable
5690 /// type and returns its ownership.
5692  while (!T.isNull()) {
5694  return T.getObjCLifetime();
5695  if (T->isArrayType())
5696  T = getBaseElementType(T);
5697  else if (const auto *PT = T->getAs<PointerType>())
5698  T = PT->getPointeeType();
5699  else if (const auto *RT = T->getAs<ReferenceType>())
5700  T = RT->getPointeeType();
5701  else
5702  break;
5703  }
5704 
5705  return Qualifiers::OCL_None;
5706 }
5707 
5708 static const Type *getIntegerTypeForEnum(const EnumType *ET) {
5709  // Incomplete enum types are not treated as integer types.
5710  // FIXME: In C++, enum types are never integer types.
5711  if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
5712  return ET->getDecl()->getIntegerType().getTypePtr();
5713  return nullptr;
5714 }
5715 
5716 /// getIntegerTypeOrder - Returns the highest ranked integer type:
5717 /// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
5718 /// LHS < RHS, return -1.
5720  const Type *LHSC = getCanonicalType(LHS).getTypePtr();
5721  const Type *RHSC = getCanonicalType(RHS).getTypePtr();
5722 
5723  // Unwrap enums to their underlying type.
5724  if (const auto *ET = dyn_cast<EnumType>(LHSC))
5725  LHSC = getIntegerTypeForEnum(ET);
5726  if (const auto *ET = dyn_cast<EnumType>(RHSC))
5727  RHSC = getIntegerTypeForEnum(ET);
5728 
5729  if (LHSC == RHSC) return 0;
5730 
5731  bool LHSUnsigned = LHSC->isUnsignedIntegerType();
5732  bool RHSUnsigned = RHSC->isUnsignedIntegerType();
5733 
5734  unsigned LHSRank = getIntegerRank(LHSC);
5735  unsigned RHSRank = getIntegerRank(RHSC);
5736 
5737  if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
5738  if (LHSRank == RHSRank) return 0;
5739  return LHSRank > RHSRank ? 1 : -1;
5740  }
5741 
5742  // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
5743  if (LHSUnsigned) {
5744  // If the unsigned [LHS] type is larger, return it.
5745  if (LHSRank >= RHSRank)
5746  return 1;
5747 
5748  // If the signed type can represent all values of the unsigned type, it
5749  // wins. Because we are dealing with 2's complement and types that are
5750  // powers of two larger than each other, this is always safe.
5751  return -1;
5752  }
5753 
5754  // If the unsigned [RHS] type is larger, return it.
5755  if (RHSRank >= LHSRank)
5756  return -1;
5757 
5758  // If the signed type can represent all values of the unsigned type, it
5759  // wins. Because we are dealing with 2's complement and types that are
5760  // powers of two larger than each other, this is always safe.
5761  return 1;
5762 }
5763 
5765  if (!CFConstantStringTypeDecl) {
5766  assert(!CFConstantStringTagDecl &&
5767  "tag and typedef should be initialized together");
5768  CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
5769  CFConstantStringTagDecl->startDefinition();
5770 
5771  QualType FieldTypes[4];
5772  const char *FieldNames[4];
5773 
5774  // const int *isa;
5775  FieldTypes[0] = getPointerType(IntTy.withConst());
5776  FieldNames[0] = "isa";
5777  // int flags;
5778  FieldTypes[1] = IntTy;
5779  FieldNames[1] = "flags";
5780  // const char *str;
5781  FieldTypes[2] = getPointerType(CharTy.withConst());
5782  FieldNames[2] = "str";
5783  // long length;
5784  FieldTypes[3] = LongTy;
5785  FieldNames[3] = "length";
5786 
5787  // Create fields
5788  for (unsigned i = 0; i < 4; ++i) {
5789  FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTagDecl,
5790  SourceLocation(),
5791  SourceLocation(),
5792  &Idents.get(FieldNames[i]),
5793  FieldTypes[i], /*TInfo=*/nullptr,
5794  /*BitWidth=*/nullptr,
5795  /*Mutable=*/false,
5796  ICIS_NoInit);
5797  Field->setAccess(AS_public);
5798  CFConstantStringTagDecl->addDecl(Field);
5799  }
5800 
5801  CFConstantStringTagDecl->completeDefinition();
5802  // This type is designed to be compatible with NSConstantString, but cannot
5803  // use the same name, since NSConstantString is an interface.
5804  auto tagType = getTagDeclType(CFConstantStringTagDecl);
5805  CFConstantStringTypeDecl =
5806  buildImplicitTypedef(tagType, "__NSConstantString");
5807  }
5808 
5809  return CFConstantStringTypeDecl;
5810 }
5811 
5813  if (!CFConstantStringTagDecl)
5814  getCFConstantStringDecl(); // Build the tag and the typedef.
5815  return CFConstantStringTagDecl;
5816 }
5817 
5818 // getCFConstantStringType - Return the type used for constant CFStrings.
5821 }
5822 
5824  if (ObjCSuperType.isNull()) {
5825  RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
5826  TUDecl->addDecl(ObjCSuperTypeDecl);
5827  ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
5828  }
5829  return ObjCSuperType;
5830 }
5831 
5833  const auto *TD = T->getAs<TypedefType>();
5834  assert(TD && "Invalid CFConstantStringType");
5835  CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl());
5836  const auto *TagType =
5837  CFConstantStringTypeDecl->getUnderlyingType()->getAs<RecordType>();
5838  assert(TagType && "Invalid CFConstantStringType");
5839  CFConstantStringTagDecl = TagType->getDecl();
5840 }
5841 
5843  if (BlockDescriptorType)
5844  return getTagDeclType(BlockDescriptorType);
5845 
5846  RecordDecl *RD;
5847  // FIXME: Needs the FlagAppleBlock bit.
5848  RD = buildImplicitRecord("__block_descriptor");
5849  RD->startDefinition();
5850 
5851  QualType FieldTypes[] = {
5854  };
5855 
5856  static const char *const FieldNames[] = {
5857  "reserved",
5858  "Size"
5859  };
5860 
5861  for (size_t i = 0; i < 2; ++i) {
5862  FieldDecl *Field = FieldDecl::Create(
5863  *this, RD, SourceLocation(), SourceLocation(),
5864  &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
5865  /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
5866  Field->setAccess(AS_public);
5867  RD->addDecl(Field);
5868  }
5869 
5870  RD->completeDefinition();
5871 
5872  BlockDescriptorType = RD;
5873 
5874  return getTagDeclType(BlockDescriptorType);
5875 }
5876 
5878  if (BlockDescriptorExtendedType)
5879  return getTagDeclType(BlockDescriptorExtendedType);
5880 
5881  RecordDecl *RD;
5882  // FIXME: Needs the FlagAppleBlock bit.
5883  RD = buildImplicitRecord("__block_descriptor_withcopydispose");
5884  RD->startDefinition();
5885 
5886  QualType FieldTypes[] = {
5891  };
5892 
5893  static const char *const FieldNames[] = {
5894  "reserved",
5895  "Size",
5896  "CopyFuncPtr",
5897  "DestroyFuncPtr"
5898  };
5899 
5900  for (size_t i = 0; i < 4; ++i) {
5901  FieldDecl *Field = FieldDecl::Create(
5902  *this, RD, SourceLocation(), SourceLocation(),
5903  &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
5904  /*BitWidth=*/nullptr,
5905  /*Mutable=*/false, ICIS_NoInit);
5906  Field->setAccess(AS_public);
5907  RD->addDecl(Field);
5908  }
5909 
5910  RD->completeDefinition();
5911 
5912  BlockDescriptorExtendedType = RD;
5913  return getTagDeclType(BlockDescriptorExtendedType);
5914 }
5915 
5917  const auto *BT = dyn_cast<BuiltinType>(T);
5918 
5919  if (!BT) {
5920  if (isa<PipeType>(T))
5921  return TargetInfo::OCLTK_Pipe;
5922 
5924  }
5925 
5926  switch (BT->getKind()) {
5927 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5928  case BuiltinType::Id: \
5929  return TargetInfo::OCLTK_Image;
5930 #include "clang/Basic/OpenCLImageTypes.def"
5931 
5932  case BuiltinType::OCLClkEvent:
5934 
5935  case BuiltinType::OCLEvent:
5936  return TargetInfo::OCLTK_Event;
5937 
5938  case BuiltinType::OCLQueue:
5939  return TargetInfo::OCLTK_Queue;
5940 
5941  case BuiltinType::OCLReserveID:
5943 
5944  case BuiltinType::OCLSampler:
5946 
5947  default:
5949  }
5950 }
5951 
5953  return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
5954 }
5955 
5956 /// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
5957 /// requires copy/dispose. Note that this must match the logic
5958 /// in buildByrefHelpers.
5960  const VarDecl *D) {
5961  if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
5962  const Expr *copyExpr = getBlockVarCopyInits(D);
5963  if (!copyExpr && record->hasTrivialDestructor()) return false;
5964 
5965  return true;
5966  }
5967 
5968  // The block needs copy/destroy helpers if Ty is non-trivial to destructively
5969  // move or destroy.
5971  return true;
5972 
5973  if (!Ty->isObjCRetainableType()) return false;
5974 
5975  Qualifiers qs = Ty.getQualifiers();
5976 
5977  // If we have lifetime, that dominates.
5978  if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
5979  switch (lifetime) {
5980  case Qualifiers::OCL_None: llvm_unreachable("impossible");
5981 
5982  // These are just bits as far as the runtime is concerned.
5985  return false;
5986 
5987  // These cases should have been taken care of when checking the type's
5988  // non-triviality.
5989  case Qualifiers::OCL_Weak:
5991  llvm_unreachable("impossible");
5992  }
5993  llvm_unreachable("fell out of lifetime switch!");
5994  }
5995  return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
5996  Ty->isObjCObjectPointerType());
5997 }
5998 
6000  Qualifiers::ObjCLifetime &LifeTime,
6001  bool &HasByrefExtendedLayout) const {
6002  if (!getLangOpts().ObjC1 ||
6003  getLangOpts().getGC() != LangOptions::NonGC)
6004  return false;
6005 
6006  HasByrefExtendedLayout = false;
6007  if (Ty->isRecordType()) {
6008  HasByrefExtendedLayout = true;
6009  LifeTime = Qualifiers::OCL_None;
6010  } else if ((LifeTime = Ty.getObjCLifetime())) {
6011  // Honor the ARC qualifiers.
6012  } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
6013  // The MRR rule.
6014  LifeTime = Qualifiers::OCL_ExplicitNone;
6015  } else {
6016  LifeTime = Qualifiers::OCL_None;
6017  }
6018  return true;
6019 }
6020 
6022  if (!ObjCInstanceTypeDecl)
6023  ObjCInstanceTypeDecl =
6024  buildImplicitTypedef(getObjCIdType(), "instancetype");
6025  return ObjCInstanceTypeDecl;
6026 }
6027 
6028 // This returns true if a type has been typedefed to BOOL:
6029 // typedef <type> BOOL;
6031  if (const auto *TT = dyn_cast<TypedefType>(T))
6032  if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
6033  return II->isStr("BOOL");
6034 
6035  return false;
6036 }
6037 
6038 /// getObjCEncodingTypeSize returns size of type for objective-c encoding
6039 /// purpose.
6041  if (!type->isIncompleteArrayType() && type->isIncompleteType())
6042  return CharUnits::Zero();
6043 
6044  CharUnits sz = getTypeSizeInChars(type);
6045 
6046  // Make all integer and enum types at least as large as an int
6047  if (sz.isPositive() && type->isIntegralOrEnumerationType())
6048  sz = std::max(sz, getTypeSizeInChars(IntTy));
6049  // Treat arrays as pointers, since that's how they're passed in.
6050  else if (type->isArrayType())
6052  return sz;
6053 }
6054 
6056  return getTargetInfo().getCXXABI().isMicrosoft() &&
6057  VD->isStaticDataMember() &&
6059  !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
6060 }
6061 
6064  if (!VD->isInline())
6066 
6067  // In almost all cases, it's a weak definition.
6068  auto *First = VD->getFirstDecl();
6069  if (First->isInlineSpecified() || !First->isStaticDataMember())
6071 
6072  // If there's a file-context declaration in this translation unit, it's a
6073  // non-discardable definition.
6074  for (auto *D : VD->redecls())
6075  if (D->getLexicalDeclContext()->isFileContext() &&
6076  !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr()))
6078 
6079  // If we've not seen one yet, we don't know.
6081 }
6082 
6083 static std::string charUnitsToString(const CharUnits &CU) {
6084  return llvm::itostr(CU.getQuantity());
6085 }
6086 
6087 /// getObjCEncodingForBlock - Return the encoded type for this block
6088 /// declaration.
6090  std::string S;
6091 
6092  const BlockDecl *Decl = Expr->getBlockDecl();
6093  QualType BlockTy =
6094  Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
6095  // Encode result type.
6096  if (getLangOpts().EncodeExtendedBlockSig)
6099  true /*Extended*/);
6100  else
6102  // Compute size of all parameters.
6103  // Start with computing size of a pointer in number of bytes.
6104  // FIXME: There might(should) be a better way of doing this computation!
6106  CharUnits ParmOffset = PtrSize;
6107  for (auto PI : Decl->parameters()) {
6108  QualType PType = PI->getType();
6109  CharUnits sz = getObjCEncodingTypeSize(PType);
6110  if (sz.isZero())
6111  continue;
6112  assert(sz.isPositive() && "BlockExpr - Incomplete param type");
6113  ParmOffset += sz;
6114  }
6115  // Size of the argument frame
6116  S += charUnitsToString(ParmOffset);
6117  // Block pointer and offset.
6118  S += "@?0";
6119 
6120  // Argument types.
6121  ParmOffset = PtrSize;
6122  for (auto PVDecl : Decl->parameters()) {
6123  QualType PType = PVDecl->getOriginalType();
6124  if (const auto *AT =
6125  dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
6126  // Use array's original type only if it has known number of
6127  // elements.
6128  if (!isa<ConstantArrayType>(AT))
6129  PType = PVDecl->getType();
6130  } else if (PType->isFunctionType())
6131  PType = PVDecl->getType();
6132  if (getLangOpts().EncodeExtendedBlockSig)
6134  S, true /*Extended*/);
6135  else
6136  getObjCEncodingForType(PType, S);
6137  S += charUnitsToString(ParmOffset);
6138  ParmOffset += getObjCEncodingTypeSize(PType);
6139  }
6140 
6141  return S;
6142 }
6143 
6144 std::string
6146  std::string S;
6147  // Encode result type.
6149  CharUnits ParmOffset;
6150  // Compute size of all parameters.
6151  for (auto PI : Decl->parameters()) {
6152  QualType PType = PI->getType();
6153  CharUnits sz = getObjCEncodingTypeSize(PType);
6154  if (sz.isZero())
6155  continue;
6156 
6157  assert(sz.isPositive() &&
6158  "getObjCEncodingForFunctionDecl - Incomplete param type");
6159  ParmOffset += sz;
6160  }
6161  S += charUnitsToString(ParmOffset);
6162  ParmOffset = CharUnits::Zero();
6163 
6164  // Argument types.
6165  for (auto PVDecl : Decl->parameters()) {
6166  QualType PType = PVDecl->getOriginalType();
6167  if (const auto *AT =
6168  dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
6169  // Use array's original type only if it has known number of
6170  // elements.
6171  if (!isa<ConstantArrayType>(AT))
6172  PType = PVDecl->getType();
6173  } else if (PType->isFunctionType())
6174  PType = PVDecl->getType();
6175  getObjCEncodingForType(PType, S);
6176  S += charUnitsToString(ParmOffset);
6177  ParmOffset += getObjCEncodingTypeSize(PType);
6178  }
6179 
6180  return S;
6181 }
6182 
6183 /// getObjCEncodingForMethodParameter - Return the encoded type for a single
6184 /// method parameter or return type. If Extended, include class names and
6185 /// block object types.
6187  QualType T, std::string& S,
6188  bool Extended) const {
6189  // Encode type qualifer, 'in', 'inout', etc. for the parameter.
6191  // Encode parameter type.
6192  getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
6193  true /*OutermostType*/,
6194  false /*EncodingProperty*/,
6195  false /*StructField*/,
6196  Extended /*EncodeBlockParameters*/,
6197  Extended /*EncodeClassNames*/);
6198 }
6199 
6200 /// getObjCEncodingForMethodDecl - Return the encoded type for this method
6201 /// declaration.
6203  bool Extended) const {
6204  // FIXME: This is not very efficient.
6205  // Encode return type.
6206  std::string S;
6208  Decl->getReturnType(), S, Extended);
6209  // Compute size of all parameters.
6210  // Start with computing size of a pointer in number of bytes.
6211  // FIXME: There might(should) be a better way of doing this computation!
6213  // The first two arguments (self and _cmd) are pointers; account for
6214  // their size.
6215  CharUnits ParmOffset = 2 * PtrSize;
6217  E = Decl->sel_param_end(); PI != E; ++PI) {
6218  QualType PType = (*PI)->getType();
6219  CharUnits sz = getObjCEncodingTypeSize(PType);
6220  if (sz.isZero())
6221  continue;
6222 
6223  assert(sz.isPositive() &&
6224  "getObjCEncodingForMethodDecl - Incomplete param type");
6225  ParmOffset += sz;
6226  }
6227  S += charUnitsToString(ParmOffset);
6228  S += "@0:";
6229  S += charUnitsToString(PtrSize);
6230 
6231  // Argument types.
6232  ParmOffset = 2 * PtrSize;
6234  E = Decl->sel_param_end(); PI != E; ++PI) {
6235  const ParmVarDecl *PVDecl = *PI;
6236  QualType PType = PVDecl->getOriginalType();
6237  if (const auto *AT =
6238  dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
6239  // Use array's original type only if it has known number of
6240  // elements.
6241  if (!isa<ConstantArrayType>(AT))
6242  PType = PVDecl->getType();
6243  } else if (PType->isFunctionType())
6244  PType = PVDecl->getType();
6246  PType, S, Extended);
6247  S += charUnitsToString(ParmOffset);
6248  ParmOffset += getObjCEncodingTypeSize(PType);
6249  }
6250 
6251  return S;
6252 }
6253 
6256  const ObjCPropertyDecl *PD,
6257  const Decl *Container) const {
6258  if (!Container)
6259  return nullptr;
6260  if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) {
6261  for (auto *PID : CID->property_impls())
6262  if (PID->getPropertyDecl() == PD)
6263  return PID;
6264  } else {
6265  const auto *OID = cast<ObjCImplementationDecl>(Container);
6266  for (auto *PID : OID->property_impls())
6267  if (PID->getPropertyDecl() == PD)
6268  return PID;
6269  }
6270  return nullptr;
6271 }
6272 
6273 /// getObjCEncodingForPropertyDecl - Return the encoded type for this
6274 /// property declaration. If non-NULL, Container must be either an
6275 /// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
6276 /// NULL when getting encodings for protocol properties.
6277 /// Property attributes are stored as a comma-delimited C string. The simple
6278 /// attributes readonly and bycopy are encoded as single characters. The
6279 /// parametrized attributes, getter=name, setter=name, and ivar=name, are
6280 /// encoded as single characters, followed by an identifier. Property types
6281 /// are also encoded as a parametrized attribute. The characters used to encode
6282 /// these attributes are defined by the following enumeration:
6283 /// @code
6284 /// enum PropertyAttributes {
6285 /// kPropertyReadOnly = 'R', // property is read-only.
6286 /// kPropertyBycopy = 'C', // property is a copy of the value last assigned
6287 /// kPropertyByref = '&', // property is a reference to the value last assigned
6288 /// kPropertyDynamic = 'D', // property is dynamic
6289 /// kPropertyGetter = 'G', // followed by getter selector name
6290 /// kPropertySetter = 'S', // followed by setter selector name
6291 /// kPropertyInstanceVariable = 'V' // followed by instance variable name
6292 /// kPropertyType = 'T' // followed by old-style type encoding.
6293 /// kPropertyWeak = 'W' // 'weak' property
6294 /// kPropertyStrong = 'P' // property GC'able
6295 /// kPropertyNonAtomic = 'N' // property non-atomic
6296 /// };
6297 /// @endcode
6298 std::string
6300  const Decl *Container) const {
6301  // Collect information from the property implementation decl(s).
6302  bool Dynamic = false;
6303  ObjCPropertyImplDecl *SynthesizePID = nullptr;
6304 
6305  if (ObjCPropertyImplDecl *PropertyImpDecl =
6306  getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
6307  if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
6308  Dynamic = true;
6309  else
6310  SynthesizePID = PropertyImpDecl;
6311  }
6312 
6313  // FIXME: This is not very efficient.
6314  std::string S = "T";
6315 
6316  // Encode result type.
6317  // GCC has some special rules regarding encoding of properties which
6318  // closely resembles encoding of ivars.
6320 
6321  if (PD->isReadOnly()) {
6322  S += ",R";
6324  S += ",C";
6326  S += ",&";
6328  S += ",W";
6329  } else {
6330  switch (PD->getSetterKind()) {
6331  case ObjCPropertyDecl::Assign: break;
6332  case ObjCPropertyDecl::Copy: S += ",C"; break;
6333  case ObjCPropertyDecl::Retain: S += ",&"; break;
6334  case ObjCPropertyDecl::Weak: S += ",W"; break;
6335  }
6336  }
6337 
6338  // It really isn't clear at all what this means, since properties
6339  // are "dynamic by default".
6340  if (Dynamic)
6341  S += ",D";
6342 
6344  S += ",N";
6345 
6347  S += ",G";
6348  S += PD->getGetterName().getAsString();
6349  }
6350 
6352  S += ",S";
6353  S += PD->getSetterName().getAsString();
6354  }
6355 
6356  if (SynthesizePID) {
6357  const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
6358  S += ",V";
6359  S += OID->getNameAsString();
6360  }
6361 
6362  // FIXME: OBJCGC: weak & strong
6363  return S;
6364 }
6365 
6366 /// getLegacyIntegralTypeEncoding -
6367 /// Another legacy compatibility encoding: 32-bit longs are encoded as
6368 /// 'l' or 'L' , but not always. For typedefs, we need to use
6369 /// 'i' or 'I' instead if encoding a struct field, or a pointer!
6371  if (isa<TypedefType>(PointeeTy.getTypePtr())) {
6372  if (const auto *BT = PointeeTy->getAs<BuiltinType>()) {
6373  if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
6374  PointeeTy = UnsignedIntTy;
6375  else
6376  if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
6377  PointeeTy = IntTy;
6378  }
6379  }
6380 }
6381 
6383  const FieldDecl *Field,
6384  QualType *NotEncodedT) const {
6385  // We follow the behavior of gcc, expanding structures which are
6386  // directly pointed to, and expanding embedded structures. Note that
6387  // these rules are sufficient to prevent recursive encoding of the
6388  // same type.
6389  getObjCEncodingForTypeImpl(T, S, true, true, Field,
6390  true /* outermost type */, false, false,
6391  false, false, false, NotEncodedT);
6392 }
6393 
6395  std::string& S) const {
6396  // Encode result type.
6397  // GCC has some special rules regarding encoding of properties which
6398  // closely resembles encoding of ivars.
6399  getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
6400  true /* outermost type */,
6401  true /* encoding property */);
6402 }
6403 
6406  switch (kind) {
6407  case BuiltinType::Void: return 'v';
6408  case BuiltinType::Bool: return 'B';
6409  case BuiltinType::Char8:
6410  case BuiltinType::Char_U:
6411  case BuiltinType::UChar: return 'C';
6412  case BuiltinType::Char16:
6413  case BuiltinType::UShort: return 'S';
6414  case BuiltinType::Char32:
6415  case BuiltinType::UInt: return 'I';
6416  case BuiltinType::ULong:
6417  return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
6418  case BuiltinType::UInt128: return 'T';
6419  case BuiltinType::ULongLong: return 'Q';
6420  case BuiltinType::Char_S:
6421  case BuiltinType::SChar: return 'c';
6422  case BuiltinType::Short: return 's';
6423  case BuiltinType::WChar_S:
6424  case BuiltinType::WChar_U:
6425  case BuiltinType::Int: return 'i';
6426  case BuiltinType::Long:
6427  return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
6428  case BuiltinType::LongLong: return 'q';
6429  case BuiltinType::Int128: return 't';
6430  case BuiltinType::Float: return 'f';
6431  case BuiltinType::Double: return 'd';
6432  case BuiltinType::LongDouble: return 'D';
6433  case BuiltinType::NullPtr: return '*'; // like char*
6434 
6435  case BuiltinType::Float16:
6436  case BuiltinType::Float128:
6437  case BuiltinType::Half:
6438  case BuiltinType::ShortAccum:
6439  case BuiltinType::Accum:
6440  case BuiltinType::LongAccum:
6441  case BuiltinType::UShortAccum:
6442  case BuiltinType::UAccum:
6443  case BuiltinType::ULongAccum:
6444  case BuiltinType::ShortFract:
6445  case BuiltinType::Fract:
6446  case BuiltinType::LongFract:
6447  case BuiltinType::UShortFract:
6448  case BuiltinType::UFract:
6449  case BuiltinType::ULongFract:
6450  case BuiltinType::SatShortAccum:
6451  case BuiltinType::SatAccum:
6452  case BuiltinType::SatLongAccum:
6453  case BuiltinType::SatUShortAccum:
6454  case BuiltinType::SatUAccum:
6455  case BuiltinType::SatULongAccum:
6456  case BuiltinType::SatShortFract:
6457  case BuiltinType::SatFract:
6458  case BuiltinType::SatLongFract:
6459  case BuiltinType::SatUShortFract:
6460  case BuiltinType::SatUFract:
6461  case BuiltinType::SatULongFract:
6462  // FIXME: potentially need @encodes for these!
6463  return ' ';
6464 
6465  case BuiltinType::ObjCId:
6466  case BuiltinType::ObjCClass:
6467  case BuiltinType::ObjCSel:
6468  llvm_unreachable("@encoding ObjC primitive type");
6469 
6470  // OpenCL and placeholder types don't need @encodings.
6471 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6472  case BuiltinType::Id:
6473 #include "clang/Basic/OpenCLImageTypes.def"
6474  case BuiltinType::OCLEvent:
6475  case BuiltinType::OCLClkEvent:
6476  case BuiltinType::OCLQueue:
6477  case BuiltinType::OCLReserveID:
6478  case BuiltinType::OCLSampler:
6479  case BuiltinType::Dependent:
6480 #define BUILTIN_TYPE(KIND, ID)
6481 #define PLACEHOLDER_TYPE(KIND, ID) \
6482  case BuiltinType::KIND:
6483 #include "clang/AST/BuiltinTypes.def"
6484  llvm_unreachable("invalid builtin type for @encode");
6485  }
6486  llvm_unreachable("invalid BuiltinType::Kind value");
6487 }
6488 
6489 static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
6490  EnumDecl *Enum = ET->getDecl();
6491 
6492  // The encoding of an non-fixed enum type is always 'i', regardless of size.
6493  if (!Enum->isFixed())
6494  return 'i';
6495 
6496  // The encoding of a fixed enum type matches its fixed underlying type.
6497  const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>();
6498  return getObjCEncodingForPrimitiveKind(C, BT->getKind());
6499 }
6500 
6501 static void EncodeBitField(const ASTContext *Ctx, std::string& S,
6502  QualType T, const FieldDecl *FD) {
6503  assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
6504  S += 'b';
6505  // The NeXT runtime encodes bit fields as b followed by the number of bits.
6506  // The GNU runtime requires more information; bitfields are encoded as b,
6507  // then the offset (in bits) of the first element, then the type of the
6508  // bitfield, then the size in bits. For example, in this structure:
6509  //
6510  // struct
6511  // {
6512  // int integer;
6513  // int flags:2;
6514  // };
6515  // On a 32-bit system, the encoding for flags would be b2 for the NeXT
6516  // runtime, but b32i2 for the GNU runtime. The reason for this extra
6517  // information is not especially sensible, but we're stuck with it for
6518  // compatibility with GCC, although providing it breaks anything that
6519  // actually uses runtime introspection and wants to work on both runtimes...
6520  if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
6521  uint64_t Offset;
6522 
6523  if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) {
6524  Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), nullptr,
6525  IVD);
6526  } else {
6527  const RecordDecl *RD = FD->getParent();
6528  const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
6529  Offset = RL.getFieldOffset(FD->getFieldIndex());
6530  }
6531 
6532  S += llvm::utostr(Offset);
6533 
6534  if (const auto *ET = T->getAs<EnumType>())
6535  S += ObjCEncodingForEnumType(Ctx, ET);
6536  else {
6537  const auto *BT = T->castAs<BuiltinType>();
6538  S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
6539  }
6540  }
6541  S += llvm::utostr(FD->getBitWidthValue(*Ctx));
6542 }
6543 
6544 // FIXME: Use SmallString for accumulating string.
6545 void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
6546  bool ExpandPointedToStructures,
6547  bool ExpandStructures,
6548  const FieldDecl *FD,
6549  bool OutermostType,
6550  bool EncodingProperty,
6551  bool StructField,
6552  bool EncodeBlockParameters,
6553  bool EncodeClassNames,
6554  bool EncodePointerToObjCTypedef,
6555  QualType *NotEncodedT) const {
6556  CanQualType CT = getCanonicalType(T);
6557  switch (CT->getTypeClass()) {
6558  case Type::Builtin:
6559  case Type::Enum:
6560  if (FD && FD->isBitField())
6561  return EncodeBitField(this, S, T, FD);
6562  if (const auto *BT = dyn_cast<BuiltinType>(CT))
6563  S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
6564  else
6565  S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
6566  return;
6567 
6568  case Type::Complex: {
6569  const auto *CT = T->castAs<ComplexType>();
6570  S += 'j';
6571  getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, nullptr);
6572  return;
6573  }
6574 
6575  case Type::Atomic: {
6576  const auto *AT = T->castAs<AtomicType>();
6577  S += 'A';
6578  getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, nullptr);
6579  return;
6580  }
6581 
6582  // encoding for pointer or reference types.
6583  case Type::Pointer:
6584  case Type::LValueReference:
6585  case Type::RValueReference: {
6586  QualType PointeeTy;
6587  if (isa<PointerType>(CT)) {
6588  const auto *PT = T->castAs<PointerType>();
6589  if (PT->isObjCSelType()) {
6590  S += ':';
6591  return;
6592  }
6593  PointeeTy = PT->getPointeeType();
6594  } else {
6595  PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
6596  }
6597 
6598  bool isReadOnly = false;
6599  // For historical/compatibility reasons, the read-only qualifier of the
6600  // pointee gets emitted _before_ the '^'. The read-only qualifier of
6601  // the pointer itself gets ignored, _unless_ we are looking at a typedef!
6602  // Also, do not emit the 'r' for anything but the outermost type!
6603  if (isa<TypedefType>(T.getTypePtr())) {
6604  if (OutermostType && T.isConstQualified()) {
6605  isReadOnly = true;
6606  S += 'r';
6607  }
6608  } else if (OutermostType) {
6609  QualType P = PointeeTy;
6610  while (P->getAs<PointerType>())
6611  P = P->getAs<PointerType>()->getPointeeType();
6612  if (P.isConstQualified()) {
6613  isReadOnly = true;
6614  S += 'r';
6615  }
6616  }
6617  if (isReadOnly) {
6618  // Another legacy compatibility encoding. Some ObjC qualifier and type
6619  // combinations need to be rearranged.
6620  // Rewrite "in const" from "nr" to "rn"
6621  if (StringRef(S).endswith("nr"))
6622  S.replace(S.end()-2, S.end(), "rn");
6623  }
6624 
6625  if (PointeeTy->isCharType()) {
6626  // char pointer types should be encoded as '*' unless it is a
6627  // type that has been typedef'd to 'BOOL'.
6628  if (!isTypeTypedefedAsBOOL(PointeeTy)) {
6629  S += '*';
6630  return;
6631  }
6632  } else if (const auto *RTy = PointeeTy->getAs<RecordType>()) {
6633  // GCC binary compat: Need to convert "struct objc_class *" to "#".
6634  if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
6635  S += '#';
6636  return;
6637  }
6638  // GCC binary compat: Need to convert "struct objc_object *" to "@".
6639  if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
6640  S += '@';
6641  return;
6642  }
6643  // fall through...
6644  }
6645  S += '^';
6646  getLegacyIntegralTypeEncoding(PointeeTy);
6647 
6648  getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
6649  nullptr, false, false, false, false, false, false,
6650  NotEncodedT);
6651  return;
6652  }
6653 
6654  case Type::ConstantArray:
6655  case Type::IncompleteArray:
6656  case Type::VariableArray: {
6657  const auto *AT = cast<ArrayType>(CT);
6658 
6659  if (isa<IncompleteArrayType>(AT) && !StructField) {
6660  // Incomplete arrays are encoded as a pointer to the array element.
6661  S += '^';
6662 
6663  getObjCEncodingForTypeImpl(AT->getElementType(), S,
6664  false, ExpandStructures, FD);
6665  } else {
6666  S += '[';
6667 
6668  if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
6669  S += llvm::utostr(CAT->getSize().getZExtValue());
6670  else {
6671  //Variable length arrays are encoded as a regular array with 0 elements.
6672  assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
6673  "Unknown array type!");
6674  S += '0';
6675  }
6676 
6677  getObjCEncodingForTypeImpl(AT->getElementType(), S,
6678  false, ExpandStructures, FD,
6679  false, false, false, false, false, false,
6680  NotEncodedT);
6681  S += ']';
6682  }
6683  return;
6684  }
6685 
6686  case Type::FunctionNoProto:
6687  case Type::FunctionProto:
6688  S += '?';
6689  return;
6690 
6691  case Type::Record: {
6692  RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
6693  S += RDecl->isUnion() ? '(' : '{';
6694  // Anonymous structures print as '?'
6695  if (const IdentifierInfo *II = RDecl->getIdentifier()) {
6696  S += II->getName();
6697  if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
6698  const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
6699  llvm::raw_string_ostream OS(S);
6700  printTemplateArgumentList(OS, TemplateArgs.asArray(),
6701  getPrintingPolicy());
6702  }
6703  } else {
6704  S += '?';
6705  }
6706  if (ExpandStructures) {
6707  S += '=';
6708  if (!RDecl->isUnion()) {
6709  getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
6710  } else {
6711  for (const auto *Field : RDecl->fields()) {
6712  if (FD) {
6713  S += '"';
6714  S += Field->getNameAsString();
6715  S += '"';
6716  }
6717 
6718  // Special case bit-fields.
6719  if (Field->isBitField()) {
6720  getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
6721  Field);
6722  } else {
6723  QualType qt = Field->getType();
6725  getObjCEncodingForTypeImpl(qt, S, false, true,
6726  FD, /*OutermostType*/false,
6727  /*EncodingProperty*/false,
6728  /*StructField*/true,
6729  false, false, false, NotEncodedT);
6730  }
6731  }
6732  }
6733  }
6734  S += RDecl->isUnion() ? ')' : '}';
6735  return;
6736  }
6737 
6738  case Type::BlockPointer: {
6739  const auto *BT = T->castAs<BlockPointerType>();
6740  S += "@?"; // Unlike a pointer-to-function, which is "^?".
6741  if (EncodeBlockParameters) {
6742  const auto *FT = BT->getPointeeType()->castAs<FunctionType>();
6743 
6744  S += '<';
6745  // Block return type
6746  getObjCEncodingForTypeImpl(
6747  FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures,
6748  FD, false /* OutermostType */, EncodingProperty,
6749  false /* StructField */, EncodeBlockParameters, EncodeClassNames, false,
6750  NotEncodedT);
6751  // Block self
6752  S += "@?";
6753  // Block parameters
6754  if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) {
6755  for (const auto &I : FPT->param_types())
6756  getObjCEncodingForTypeImpl(
6757  I, S, ExpandPointedToStructures, ExpandStructures, FD,
6758  false /* OutermostType */, EncodingProperty,
6759  false /* StructField */, EncodeBlockParameters, EncodeClassNames,
6760  false, NotEncodedT);
6761  }
6762  S += '>';
6763  }
6764  return;
6765  }
6766 
6767  case Type::ObjCObject: {
6768  // hack to match legacy encoding of *id and *Class
6770  if (Ty->isObjCIdType()) {
6771  S += "{objc_object=}";
6772  return;
6773  }
6774  else if (Ty->isObjCClassType()) {
6775  S += "{objc_class=}";
6776  return;
6777  }
6778  // TODO: Double check to make sure this intentionally falls through.
6779  LLVM_FALLTHROUGH;
6780  }
6781 
6782  case Type::ObjCInterface: {
6783  // Ignore protocol qualifiers when mangling at this level.
6784  // @encode(class_name)
6785  ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
6786  S += '{';
6787  S += OI->getObjCRuntimeNameAsString();
6788  if (ExpandStructures) {
6789  S += '=';
6791  DeepCollectObjCIvars(OI, true, Ivars);
6792  for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
6793  const FieldDecl *Field = Ivars[i];
6794  if (Field->isBitField())
6795  getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
6796  else
6797  getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
6798  false, false, false, false, false,
6799  EncodePointerToObjCTypedef,
6800  NotEncodedT);
6801  }
6802  }
6803  S += '}';
6804  return;
6805  }
6806 
6807  case Type::ObjCObjectPointer: {
6808  const auto *OPT = T->castAs<ObjCObjectPointerType>();
6809  if (OPT->isObjCIdType()) {
6810  S += '@';
6811  return;
6812  }
6813 
6814  if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
6815  // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
6816  // Since this is a binary compatibility issue, need to consult with runtime
6817  // folks. Fortunately, this is a *very* obscure construct.
6818  S += '#';
6819  return;
6820  }
6821 
6822  if (OPT->isObjCQualifiedIdType()) {
6823  getObjCEncodingForTypeImpl(getObjCIdType(), S,
6824  ExpandPointedToStructures,
6825  ExpandStructures, FD);
6826  if (FD || EncodingProperty || EncodeClassNames) {
6827  // Note that we do extended encoding of protocol qualifer list
6828  // Only when doing ivar or property encoding.
6829  S += '"';
6830  for (const auto *I : OPT->quals()) {
6831  S += '<';
6832  S += I->getObjCRuntimeNameAsString();
6833  S += '>';
6834  }
6835  S += '"';
6836  }
6837  return;
6838  }
6839 
6840  QualType PointeeTy = OPT->getPointeeType();
6841  if (!EncodingProperty &&
6842  isa<TypedefType>(PointeeTy.getTypePtr()) &&
6843  !EncodePointerToObjCTypedef) {
6844  // Another historical/compatibility reason.
6845  // We encode the underlying type which comes out as
6846  // {...};
6847  S += '^';
6848  if (FD && OPT->getInterfaceDecl()) {
6849  // Prevent recursive encoding of fields in some rare cases.
6850  ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
6852  DeepCollectObjCIvars(OI, true, Ivars);
6853  for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
6854  if (Ivars[i] == FD) {
6855  S += '{';
6856  S += OI->getObjCRuntimeNameAsString();
6857  S += '}';
6858  return;
6859  }
6860  }
6861  }
6862  getObjCEncodingForTypeImpl(PointeeTy, S,
6863  false, ExpandPointedToStructures,
6864  nullptr,
6865  false, false, false, false, false,
6866  /*EncodePointerToObjCTypedef*/true);
6867  return;
6868  }
6869 
6870  S += '@';
6871  if (OPT->getInterfaceDecl() &&
6872  (FD || EncodingProperty || EncodeClassNames)) {
6873  S += '"';
6874  S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
6875  for (const auto *I : OPT->quals()) {
6876  S += '<';
6877  S += I->getObjCRuntimeNameAsString();
6878  S += '>';
6879  }
6880  S += '"';
6881  }
6882  return;
6883  }
6884 
6885  // gcc just blithely ignores member pointers.
6886  // FIXME: we shoul do better than that. 'M' is available.
6887  case Type::MemberPointer:
6888  // This matches gcc's encoding, even though technically it is insufficient.
6889  //FIXME. We should do a better job than gcc.
6890  case Type::Vector:
6891  case Type::ExtVector:
6892  // Until we have a coherent encoding of these three types, issue warning.
6893  if (NotEncodedT)
6894  *NotEncodedT = T;
6895  return;
6896 
6897  // We could see an undeduced auto type here during error recovery.
6898  // Just ignore it.
6899  case Type::Auto:
6900  case Type::DeducedTemplateSpecialization:
6901  return;
6902 
6903  case Type::Pipe:
6904 #define ABSTRACT_TYPE(KIND, BASE)
6905 #define TYPE(KIND, BASE)
6906 #define DEPENDENT_TYPE(KIND, BASE) \
6907  case Type::KIND:
6908 #define NON_CANONICAL_TYPE(KIND, BASE) \
6909  case Type::KIND:
6910 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
6911  case Type::KIND:
6912 #include "clang/AST/TypeNodes.def"
6913  llvm_unreachable("@encode for dependent type!");
6914  }
6915  llvm_unreachable("bad type kind!");
6916 }
6917 
6918 void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
6919  std::string &S,
6920  const FieldDecl *FD,
6921  bool includeVBases,
6922  QualType *NotEncodedT) const {
6923  assert(RDecl && "Expected non-null RecordDecl");
6924  assert(!RDecl->isUnion() && "Should not be called for unions");
6925  if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
6926  return;
6927 
6928  const auto *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
6929  std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
6930  const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
6931 
6932  if (CXXRec) {
6933  for (const auto &BI : CXXRec->bases()) {
6934  if (!BI.isVirtual()) {
6935  CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
6936  if (base->isEmpty())
6937  continue;
6938  uint64_t offs = toBits(layout.getBaseClassOffset(base));
6939  FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
6940  std::make_pair(offs, base));
6941  }
6942  }
6943  }
6944 
6945  unsigned i = 0;
6946  for (auto *Field : RDecl->fields()) {
6947  uint64_t offs = layout.getFieldOffset(i);
6948  FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
6949  std::make_pair(offs, Field));
6950  ++i;
6951  }
6952 
6953  if (CXXRec && includeVBases) {
6954  for (const auto &BI : CXXRec->vbases()) {
6955  CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
6956  if (base->isEmpty())
6957  continue;
6958  uint64_t offs = toBits(layout.getVBaseClassOffset(base));
6959  if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
6960  FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
6961  FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
6962  std::make_pair(offs, base));
6963  }
6964  }
6965 
6966  CharUnits size;
6967  if (CXXRec) {
6968  size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
6969  } else {
6970  size = layout.getSize();
6971  }
6972 
6973 #ifndef NDEBUG
6974  uint64_t CurOffs = 0;
6975 #endif
6976  std::multimap<uint64_t, NamedDecl *>::iterator
6977  CurLayObj = FieldOrBaseOffsets.begin();
6978 
6979  if (CXXRec && CXXRec->isDynamicClass() &&
6980  (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
6981  if (FD) {
6982  S += "\"_vptr$";
6983  std::string recname = CXXRec->getNameAsString();
6984  if (recname.empty()) recname = "?";
6985  S += recname;
6986  S += '"';
6987  }
6988  S += "^^?";
6989 #ifndef NDEBUG
6990  CurOffs += getTypeSize(VoidPtrTy);
6991 #endif
6992  }
6993 
6994  if (!RDecl->hasFlexibleArrayMember()) {
6995  // Mark the end of the structure.
6996  uint64_t offs = toBits(size);
6997  FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
6998  std::make_pair(offs, nullptr));
6999  }
7000 
7001  for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
7002 #ifndef NDEBUG
7003  assert(CurOffs <= CurLayObj->first);
7004  if (CurOffs < CurLayObj->first) {
7005  uint64_t padding = CurLayObj->first - CurOffs;
7006  // FIXME: There doesn't seem to be a way to indicate in the encoding that
7007  // packing/alignment of members is different that normal, in which case
7008  // the encoding will be out-of-sync with the real layout.
7009  // If the runtime switches to just consider the size of types without
7010  // taking into account alignment, we could make padding explicit in the
7011  // encoding (e.g. using arrays of chars). The encoding strings would be
7012  // longer then though.
7013  CurOffs += padding;
7014  }
7015 #endif
7016 
7017  NamedDecl *dcl = CurLayObj->second;
7018  if (!dcl)
7019  break; // reached end of structure.
7020 
7021  if (auto *base = dyn_cast<CXXRecordDecl>(dcl)) {
7022  // We expand the bases without their virtual bases since those are going
7023  // in the initial structure. Note that this differs from gcc which
7024  // expands virtual bases each time one is encountered in the hierarchy,
7025  // making the encoding type bigger than it really is.
7026  getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
7027  NotEncodedT);
7028  assert(!base->isEmpty());
7029 #ifndef NDEBUG
7030  CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
7031 #endif
7032  } else {
7033  const auto *field = cast<FieldDecl>(dcl);
7034  if (FD) {
7035  S += '"';
7036  S += field->getNameAsString();
7037  S += '"';
7038  }
7039 
7040  if (field->isBitField()) {
7041  EncodeBitField(this, S, field->getType(), field);
7042 #ifndef NDEBUG
7043  CurOffs += field->getBitWidthValue(*this);
7044 #endif
7045  } else {
7046  QualType qt = field->getType();
7048  getObjCEncodingForTypeImpl(qt, S, false, true, FD,
7049  /*OutermostType*/false,
7050  /*EncodingProperty*/false,
7051  /*StructField*/true,
7052  false, false, false, NotEncodedT);
7053 #ifndef NDEBUG
7054  CurOffs += getTypeSize(field->getType());
7055 #endif
7056  }
7057  }
7058  }
7059 }
7060 
7062  std::string& S) const {
7063  if (QT & Decl::OBJC_TQ_In)
7064  S += 'n';
7065  if (QT & Decl::OBJC_TQ_Inout)
7066  S += 'N';
7067  if (QT & Decl::OBJC_TQ_Out)
7068  S += 'o';
7069  if (QT & Decl::OBJC_TQ_Bycopy)
7070  S += 'O';
7071  if (QT & Decl::OBJC_TQ_Byref)
7072  S += 'R';
7073  if (QT & Decl::OBJC_TQ_Oneway)
7074  S += 'V';
7075 }
7076 
7078  if (!ObjCIdDecl) {
7080  T = getObjCObjectPointerType(T);
7081  ObjCIdDecl = buildImplicitTypedef(T, "id");
7082  }
7083  return ObjCIdDecl;
7084 }
7085 
7087  if (!ObjCSelDecl) {
7089  ObjCSelDecl = buildImplicitTypedef(T, "SEL");
7090  }
7091  return ObjCSelDecl;
7092 }
7093 
7095  if (!ObjCClassDecl) {
7097  T = getObjCObjectPointerType(T);
7098  ObjCClassDecl = buildImplicitTypedef(T, "Class");
7099  }
7100  return ObjCClassDecl;
7101 }
7102 
7104  if (!ObjCProtocolClassDecl) {
7105  ObjCProtocolClassDecl
7107  SourceLocation(),
7108  &Idents.get("Protocol"),
7109  /*typeParamList=*/nullptr,
7110  /*PrevDecl=*/nullptr,
7111  SourceLocation(), true);
7112  }
7113 
7114  return ObjCProtocolClassDecl;
7115 }
7116 
7117 //===----------------------------------------------------------------------===//
7118 // __builtin_va_list Construction Functions
7119 //===----------------------------------------------------------------------===//
7120 
7122  StringRef Name) {
7123  // typedef char* __builtin[_ms]_va_list;
7124  QualType T = Context->getPointerType(Context->CharTy);
7125  return Context->buildImplicitTypedef(T, Name);
7126 }
7127 
7128 static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
7129  return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
7130 }
7131 
7133  return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
7134 }
7135 
7137  // typedef void* __builtin_va_list;
7138  QualType T = Context->getPointerType(Context->VoidTy);
7139  return Context->buildImplicitTypedef(T, "__builtin_va_list");
7140 }
7141 
7142 static TypedefDecl *
7144  // struct __va_list
7145  RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
7146  if (Context->getLangOpts().CPlusPlus) {
7147  // namespace std { struct __va_list {
7148  NamespaceDecl *NS;
7149  NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
7150  Context->getTranslationUnitDecl(),
7151  /*Inline*/ false, SourceLocation(),
7152  SourceLocation(), &Context->Idents.get("std"),
7153  /*PrevDecl*/ nullptr);
7154  NS->setImplicit();
7155  VaListTagDecl->setDeclContext(NS);
7156  }
7157 
7158  VaListTagDecl->startDefinition();
7159 
7160  const size_t NumFields = 5;
7161  QualType FieldTypes[NumFields];
7162  const char *FieldNames[NumFields];
7163 
7164  // void *__stack;
7165  FieldTypes[0] = Context->getPointerType(Context->VoidTy);
7166  FieldNames[0] = "__stack";
7167 
7168  // void *__gr_top;
7169  FieldTypes[1] = Context->getPointerType(Context->VoidTy);
7170  FieldNames[1] = "__gr_top";
7171 
7172  // void *__vr_top;
7173  FieldTypes[2] = Context->getPointerType(Context->VoidTy);
7174  FieldNames[2] = "__vr_top";
7175 
7176  // int __gr_offs;
7177  FieldTypes[3] = Context->IntTy;
7178  FieldNames[3] = "__gr_offs";
7179 
7180  // int __vr_offs;
7181  FieldTypes[4] = Context->IntTy;
7182  FieldNames[4] = "__vr_offs";
7183 
7184  // Create fields
7185  for (unsigned i = 0; i < NumFields; ++i) {
7186  FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7187  VaListTagDecl,
7188  SourceLocation(),
7189  SourceLocation(),
7190  &Context->Idents.get(FieldNames[i]),
7191  FieldTypes[i], /*TInfo=*/nullptr,
7192  /*BitWidth=*/nullptr,
7193  /*Mutable=*/false,
7194  ICIS_NoInit);
7195  Field->setAccess(AS_public);
7196  VaListTagDecl->addDecl(Field);
7197  }
7198  VaListTagDecl->completeDefinition();
7199  Context->VaListTagDecl = VaListTagDecl;
7200  QualType VaListTagType = Context->getRecordType(VaListTagDecl);
7201 
7202  // } __builtin_va_list;
7203  return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
7204 }
7205 
7207  // typedef struct __va_list_tag {
7209 
7210  VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
7211  VaListTagDecl->startDefinition();
7212 
7213  const size_t NumFields = 5;
7214  QualType FieldTypes[NumFields];
7215  const char *FieldNames[NumFields];
7216 
7217  // unsigned char gpr;
7218  FieldTypes[0] = Context->UnsignedCharTy;
7219  FieldNames[0] = "gpr";
7220 
7221  // unsigned char fpr;
7222  FieldTypes[1] = Context->UnsignedCharTy;
7223  FieldNames[1] = "fpr";
7224 
7225  // unsigned short reserved;
7226  FieldTypes[2] = Context->UnsignedShortTy;
7227  FieldNames[2] = "reserved";
7228 
7229  // void* overflow_arg_area;
7230  FieldTypes[3] = Context->getPointerType(Context->VoidTy);
7231  FieldNames[3] = "overflow_arg_area";
7232 
7233  // void* reg_save_area;
7234  FieldTypes[4] = Context->getPointerType(Context->VoidTy);
7235  FieldNames[4] = "reg_save_area";
7236 
7237  // Create fields
7238  for (unsigned i = 0; i < NumFields; ++i) {
7239  FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
7240  SourceLocation(),
7241  SourceLocation(),
7242  &Context->Idents.get(FieldNames[i]),
7243  FieldTypes[i], /*TInfo=*/nullptr,
7244  /*BitWidth=*/nullptr,
7245  /*Mutable=*/false,
7246  ICIS_NoInit);
7247  Field->setAccess(AS_public);
7248  VaListTagDecl->addDecl(Field);
7249  }
7250  VaListTagDecl->completeDefinition();
7251  Context->VaListTagDecl = VaListTagDecl;
7252  QualType VaListTagType = Context->getRecordType(VaListTagDecl);
7253 
7254  // } __va_list_tag;
7255  TypedefDecl *VaListTagTypedefDecl =
7256  Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
7257 
7258  QualType VaListTagTypedefType =
7259  Context->getTypedefType(VaListTagTypedefDecl);
7260 
7261  // typedef __va_list_tag __builtin_va_list[1];
7262  llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
7263  QualType VaListTagArrayType
7264  = Context->getConstantArrayType(VaListTagTypedefType,
7265  Size, ArrayType::Normal, 0);
7266  return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
7267 }
7268 
7269 static TypedefDecl *
7271  // struct __va_list_tag {
7273  VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
7274  VaListTagDecl->startDefinition();
7275 
7276  const size_t NumFields = 4;
7277  QualType FieldTypes[NumFields];
7278  const char *FieldNames[NumFields];
7279 
7280  // unsigned gp_offset;
7281  FieldTypes[0] = Context->UnsignedIntTy;
7282  FieldNames[0] = "gp_offset";
7283 
7284  // unsigned fp_offset;
7285  FieldTypes[1] = Context->UnsignedIntTy;
7286  FieldNames[1] = "fp_offset";
7287 
7288  // void* overflow_arg_area;
7289  FieldTypes[2] = Context->getPointerType(Context->VoidTy);
7290  FieldNames[2] = "overflow_arg_area";
7291 
7292  // void* reg_save_area;
7293  FieldTypes[3] = Context->getPointerType(Context->VoidTy);
7294  FieldNames[3] = "reg_save_area";
7295 
7296  // Create fields
7297  for (unsigned i = 0; i < NumFields; ++i) {
7298  FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7299  VaListTagDecl,
7300  SourceLocation(),
7301  SourceLocation(),
7302  &Context->Idents.get(FieldNames[i]),
7303  FieldTypes[i], /*TInfo=*/nullptr,
7304  /*BitWidth=*/nullptr,
7305  /*Mutable=*/false,
7306  ICIS_NoInit);
7307  Field->setAccess(AS_public);
7308  VaListTagDecl->addDecl(Field);
7309  }
7310  VaListTagDecl->completeDefinition();
7311  Context->VaListTagDecl = VaListTagDecl;
7312  QualType VaListTagType = Context->getRecordType(VaListTagDecl);
7313 
7314  // };
7315 
7316  // typedef struct __va_list_tag __builtin_va_list[1];
7317  llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
7318  QualType VaListTagArrayType =
7319  Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
7320  return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
7321 }
7322 
7324  // typedef int __builtin_va_list[4];
7325  llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
7326  QualType IntArrayType =
7327  Context->getConstantArrayType(Context->IntTy, Size, ArrayType::Normal, 0);
7328  return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
7329 }
7330 
7331 static TypedefDecl *
7333  // struct __va_list
7334  RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
7335  if (Context->getLangOpts().CPlusPlus) {
7336  // namespace std { struct __va_list {
7337  NamespaceDecl *NS;
7338  NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
7339  Context->getTranslationUnitDecl(),
7340  /*Inline*/false, SourceLocation(),
7341  SourceLocation(), &Context->Idents.get("std"),
7342  /*PrevDecl*/ nullptr);
7343  NS->setImplicit();
7344  VaListDecl->setDeclContext(NS);
7345  }
7346 
7347  VaListDecl->startDefinition();
7348 
7349  // void * __ap;
7350  FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7351  VaListDecl,
7352  SourceLocation(),
7353  SourceLocation(),
7354  &Context->Idents.get("__ap"),
7355  Context->getPointerType(Context->VoidTy),
7356  /*TInfo=*/nullptr,
7357  /*BitWidth=*/nullptr,
7358  /*Mutable=*/false,
7359  ICIS_NoInit);
7360  Field->setAccess(AS_public);
7361  VaListDecl->addDecl(Field);
7362 
7363  // };
7364  VaListDecl->completeDefinition();
7365  Context->VaListTagDecl = VaListDecl;
7366 
7367  // typedef struct __va_list __builtin_va_list;
7368  QualType T = Context->getRecordType(VaListDecl);
7369  return Context->buildImplicitTypedef(T, "__builtin_va_list");
7370 }
7371 
7372 static TypedefDecl *
7374  // struct __va_list_tag {
7376  VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
7377  VaListTagDecl->startDefinition();
7378 
7379  const size_t NumFields = 4;
7380  QualType FieldTypes[NumFields];
7381  const char *FieldNames[NumFields];
7382 
7383  // long __gpr;
7384  FieldTypes[0] = Context->LongTy;
7385  FieldNames[0] = "__gpr";
7386 
7387  // long __fpr;
7388  FieldTypes[1] = Context->LongTy;
7389  FieldNames[1] = "__fpr";
7390 
7391  // void *__overflow_arg_area;
7392  FieldTypes[2] = Context->getPointerType(Context->VoidTy);
7393  FieldNames[2] = "__overflow_arg_area";
7394 
7395  // void *__reg_save_area;
7396  FieldTypes[3] = Context->getPointerType(Context->VoidTy);
7397  FieldNames[3] = "__reg_save_area";
7398 
7399  // Create fields
7400  for (unsigned i = 0; i < NumFields; ++i) {
7401  FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7402  VaListTagDecl,
7403  SourceLocation(),
7404  SourceLocation(),
7405  &Context->Idents.get(FieldNames[i]),
7406  FieldTypes[i], /*TInfo=*/nullptr,
7407  /*BitWidth=*/nullptr,
7408  /*Mutable=*/false,
7409  ICIS_NoInit);
7410  Field->setAccess(AS_public);
7411  VaListTagDecl->addDecl(Field);
7412  }
7413  VaListTagDecl->completeDefinition();
7414  Context->VaListTagDecl = VaListTagDecl;
7415  QualType VaListTagType = Context->getRecordType(VaListTagDecl);
7416 
7417  // };
7418 
7419  // typedef __va_list_tag __builtin_va_list[1];
7420  llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
7421  QualType VaListTagArrayType =
7422  Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
7423 
7424  return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
7425 }
7426 
7427 static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
7429  switch (Kind) {
7431  return CreateCharPtrBuiltinVaListDecl(Context);
7433  return CreateVoidPtrBuiltinVaListDecl(Context);
7435  return CreateAArch64ABIBuiltinVaListDecl(Context);
7437  return CreatePowerABIBuiltinVaListDecl(Context);
7439  return CreateX86_64ABIBuiltinVaListDecl(Context);
7441  return CreatePNaClABIBuiltinVaListDecl(Context);
7443  return CreateAAPCSABIBuiltinVaListDecl(Context);
7445  return CreateSystemZBuiltinVaListDecl(Context);
7446  }
7447 
7448  llvm_unreachable("Unhandled __builtin_va_list type kind");
7449 }
7450 
7452  if (!BuiltinVaListDecl) {
7453  BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
7454  assert(BuiltinVaListDecl->isImplicit());
7455  }
7456 
7457  return BuiltinVaListDecl;
7458 }
7459 
7461  // Force the creation of VaListTagDecl by building the __builtin_va_list
7462  // declaration.
7463  if (!VaListTagDecl)
7464  (void)getBuiltinVaListDecl();
7465 
7466  return VaListTagDecl;
7467 }
7468 
7470  if (!BuiltinMSVaListDecl)
7471  BuiltinMSVaListDecl = CreateMSVaListDecl(this);
7472 
7473  return BuiltinMSVaListDecl;
7474 }
7475 
7478 }
7479 
7481  assert(ObjCConstantStringType.isNull() &&
7482  "'NSConstantString' type already set!");
7483 
7484  ObjCConstantStringType = getObjCInterfaceType(Decl);
7485 }
7486 
7487 /// Retrieve the template name that corresponds to a non-empty
7488 /// lookup.
7491  UnresolvedSetIterator End) const {
7492  unsigned size = End - Begin;
7493  assert(size > 1 && "set is not overloaded!");
7494 
7495  void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
7496  size * sizeof(FunctionTemplateDecl*));
7497  auto *OT = new (memory) OverloadedTemplateStorage(size);
7498 
7499  NamedDecl **Storage = OT->getStorage();
7500  for (UnresolvedSetIterator I = Begin; I != End; ++I) {
7501  NamedDecl *D = *I;
7502  assert(isa<FunctionTemplateDecl>(D) ||
7503  isa<UnresolvedUsingValueDecl>(D) ||
7504  (isa<UsingShadowDecl>(D) &&
7505  isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
7506  *Storage++ = D;
7507  }
7508 
7509  return TemplateName(OT);
7510 }
7511 
7512 /// Retrieve the template name that represents a qualified
7513 /// template name such as \c std::vector.
7516  bool TemplateKeyword,
7517  TemplateDecl *Template) const {
7518  assert(NNS && "Missing nested-name-specifier in qualified template name");
7519 
7520  // FIXME: Canonicalization?
7521  llvm::FoldingSetNodeID ID;
7522  QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
7523 
7524  void *InsertPos = nullptr;
7525  QualifiedTemplateName *QTN =
7526  QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7527  if (!QTN) {
7528  QTN = new (*this, alignof(QualifiedTemplateName))
7529  QualifiedTemplateName(NNS, TemplateKeyword, Template);
7530  QualifiedTemplateNames.InsertNode(QTN, InsertPos);
7531  }
7532 
7533  return TemplateName(QTN);
7534 }
7535 
7536 /// Retrieve the template name that represents a dependent
7537 /// template name such as \c MetaFun::template apply.
7540  const IdentifierInfo *Name) const {
7541  assert((!NNS || NNS->isDependent()) &&
7542  "Nested name specifier must be dependent");
7543 
7544  llvm::FoldingSetNodeID ID;
7545  DependentTemplateName::Profile(ID, NNS, Name);
7546 
7547  void *InsertPos = nullptr;
7548  DependentTemplateName *QTN =
7549  DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7550 
7551  if (QTN)
7552  return TemplateName(QTN);
7553 
7555  if (CanonNNS == NNS) {
7556  QTN = new (*this, alignof(DependentTemplateName))
7557  DependentTemplateName(NNS, Name);
7558  } else {
7559  TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
7560  QTN = new (*this, alignof(DependentTemplateName))
7561  DependentTemplateName(NNS, Name, Canon);
7562  DependentTemplateName *CheckQTN =
7563  DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7564  assert(!CheckQTN && "Dependent type name canonicalization broken");
7565  (void)CheckQTN;
7566  }
7567 
7568  DependentTemplateNames.InsertNode(QTN, InsertPos);
7569  return TemplateName(QTN);
7570 }
7571 
7572 /// Retrieve the template name that represents a dependent
7573 /// template name such as \c MetaFun::template operator+.
7576  OverloadedOperatorKind Operator) const {
7577  assert((!NNS || NNS->isDependent()) &&
7578  "Nested name specifier must be dependent");
7579 
7580  llvm::FoldingSetNodeID ID;
7581  DependentTemplateName::Profile(ID, NNS, Operator);
7582 
7583  void *InsertPos = nullptr;
7585  = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7586 
7587  if (QTN)
7588  return TemplateName(QTN);
7589 
7591  if (CanonNNS == NNS) {
7592  QTN = new (*this, alignof(DependentTemplateName))
7593  DependentTemplateName(NNS, Operator);
7594  } else {
7595  TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
7596  QTN = new (*this, alignof(DependentTemplateName))
7597  DependentTemplateName(NNS, Operator, Canon);
7598 
7599  DependentTemplateName *CheckQTN
7600  = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7601  assert(!CheckQTN && "Dependent template name canonicalization broken");
7602  (void)CheckQTN;
7603  }
7604 
7605  DependentTemplateNames.InsertNode(QTN, InsertPos);
7606  return TemplateName(QTN);
7607 }
7608 
7611  TemplateName replacement) const {
7612  llvm::FoldingSetNodeID ID;
7613  SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
7614 
7615  void *insertPos = nullptr;
7617  = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
7618 
7619  if (!subst) {
7620  subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
7621  SubstTemplateTemplateParms.InsertNode(subst, insertPos);
7622  }
7623 
7624  return TemplateName(subst);
7625 }
7626 
7629  const TemplateArgument &ArgPack) const {
7630  auto &Self = const_cast<ASTContext &>(*this);
7631  llvm::FoldingSetNodeID ID;
7632  SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
7633 
7634  void *InsertPos = nullptr;
7636  = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
7637 
7638  if (!Subst) {
7639  Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
7640  ArgPack.pack_size(),
7641  ArgPack.pack_begin());
7642  SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
7643  }
7644 
7645  return TemplateName(Subst);
7646 }
7647 
7648 /// getFromTargetType - Given one of the integer types provided by
7649 /// TargetInfo, produce the corresponding type. The unsigned @p Type
7650 /// is actually a value of type @c TargetInfo::IntType.
7651 CanQualType ASTContext::getFromTargetType(unsigned Type) const {
7652  switch (Type) {
7653  case TargetInfo::NoInt: return {};
7654  case TargetInfo::SignedChar: return SignedCharTy;
7656  case TargetInfo::SignedShort: return ShortTy;
7658  case TargetInfo::SignedInt: return IntTy;
7660  case TargetInfo::SignedLong: return LongTy;
7664  }
7665 
7666  llvm_unreachable("Unhandled TargetInfo::IntType value");
7667 }
7668 
7669 //===----------------------------------------------------------------------===//
7670 // Type Predicates.
7671 //===----------------------------------------------------------------------===//
7672 
7673 /// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
7674 /// garbage collection attribute.
7675 ///
7677  if (getLangOpts().getGC() == LangOptions::NonGC)
7678  return Qualifiers::GCNone;
7679 
7680  assert(getLangOpts().ObjC1);
7681  Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
7682 
7683  // Default behaviour under objective-C's gc is for ObjC pointers
7684  // (or pointers to them) be treated as though they were declared
7685  // as __strong.
7686  if (GCAttrs == Qualifiers::GCNone) {
7687  if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
7688  return Qualifiers::Strong;
7689  else if (Ty->isPointerType())
7691  } else {
7692  // It's not valid to set GC attributes on anything that isn't a
7693  // pointer.
7694 #ifndef NDEBUG
7696  while (const auto *AT = dyn_cast<ArrayType>(CT))
7697  CT = AT->getElementType();
7698  assert(CT->isAnyPointerType() || CT->isBlockPointerType());
7699 #endif
7700  }
7701  return GCAttrs;
7702 }
7703 
7704 //===----------------------------------------------------------------------===//
7705 // Type Compatibility Testing
7706 //===----------------------------------------------------------------------===//
7707 
7708 /// areCompatVectorTypes - Return true if the two specified vector types are
7709 /// compatible.
7710 static bool areCompatVectorTypes(const VectorType *LHS,
7711  const VectorType *RHS) {
7712  assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
7713  return LHS->getElementType() == RHS->getElementType() &&
7714  LHS->getNumElements() == RHS->getNumElements();
7715 }
7716 
7718  QualType SecondVec) {
7719  assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
7720  assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
7721 
7722  if (hasSameUnqualifiedType(FirstVec, SecondVec))
7723  return true;
7724 
7725  // Treat Neon vector types and most AltiVec vector types as if they are the
7726  // equivalent GCC vector types.
7727  const auto *First = FirstVec->getAs<VectorType>();
7728  const auto *Second = SecondVec->getAs<VectorType>();
7729  if (First->getNumElements() == Second->getNumElements() &&
7730  hasSameType(First->getElementType(), Second->getElementType()) &&
7731  First->getVectorKind() != VectorType::AltiVecPixel &&
7732  First->getVectorKind() != VectorType::AltiVecBool &&
7733  Second->getVectorKind() != VectorType::AltiVecPixel &&
7735  return true;
7736 
7737  return false;
7738 }
7739 
7740 //===----------------------------------------------------------------------===//
7741 // ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
7742 //===----------------------------------------------------------------------===//
7743 
7744 /// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
7745 /// inheritance hierarchy of 'rProto'.
7746 bool
7748  ObjCProtocolDecl *rProto) const {
7749  if (declaresSameEntity(lProto, rProto))
7750  return true;
7751  for (auto *PI : rProto->protocols())
7752  if (ProtocolCompatibleWithProtocol(lProto, PI))
7753  return true;
7754  return false;
7755 }
7756 
7757 /// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
7758 /// Class<pr1, ...>.
7760  QualType rhs) {
7761  const auto *lhsQID = lhs->getAs<ObjCObjectPointerType>();
7762  const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
7763  assert((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
7764 
7765  for (auto *lhsProto : lhsQID->quals()) {
7766  bool match = false;
7767  for (auto *rhsProto : rhsOPT->quals()) {
7768  if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
7769  match = true;
7770  break;
7771  }
7772  }
7773  if (!match)
7774  return false;
7775  }
7776  return true;
7777 }
7778 
7779 /// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
7780 /// ObjCQualifiedIDType.
7782  bool compare) {
7783  // Allow id<P..> and an 'id' or void* type in all cases.
7784  if (lhs->isVoidPointerType() ||
7785  lhs->isObjCIdType() || lhs->isObjCClassType())
7786  return true;
7787  else if (rhs->isVoidPointerType() ||
7788  rhs->isObjCIdType() || rhs->isObjCClassType())
7789  return true;
7790 
7791  if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
7792  const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
7793 
7794  if (!rhsOPT) return false;
7795 
7796  if (rhsOPT->qual_empty()) {
7797  // If the RHS is a unqualified interface pointer "NSString*",
7798  // make sure we check the class hierarchy.
7799  if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
7800  for (auto *I : lhsQID->quals()) {
7801  // when comparing an id<P> on lhs with a static type on rhs,
7802  // see if static class implements all of id's protocols, directly or
7803  // through its super class and categories.
7804  if (!rhsID->ClassImplementsProtocol(I, true))
7805  return false;
7806  }
7807  }
7808  // If there are no qualifiers and no interface, we have an 'id'.
7809  return true;
7810  }
7811  // Both the right and left sides have qualifiers.
7812  for (auto *lhsProto : lhsQID->quals()) {
7813  bool match = false;
7814 
7815  // when comparing an id<P> on lhs with a static type on rhs,
7816  // see if static class implements all of id's protocols, directly or
7817  // through its super class and categories.
7818  for (auto *rhsProto : rhsOPT->quals()) {
7819  if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7820  (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7821  match = true;
7822  break;
7823  }
7824  }
7825  // If the RHS is a qualified interface pointer "NSString<P>*",
7826  // make sure we check the class hierarchy.
7827  if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
7828  for (auto *I : lhsQID->quals()) {
7829  // when comparing an id<P> on lhs with a static type on rhs,
7830  // see if static class implements all of id's protocols, directly or
7831  // through its super class and categories.
7832  if (rhsID->ClassImplementsProtocol(I, true)) {
7833  match = true;
7834  break;
7835  }
7836  }
7837  }
7838  if (!match)
7839  return false;
7840  }
7841 
7842  return true;
7843  }
7844 
7845  const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
7846  assert(rhsQID && "One of the LHS/RHS should be id<x>");
7847 
7848  if (const ObjCObjectPointerType *lhsOPT =
7850  // If both the right and left sides have qualifiers.
7851  for (auto *lhsProto : lhsOPT->quals()) {
7852  bool match = false;
7853 
7854  // when comparing an id<P> on rhs with a static type on lhs,
7855  // see if static class implements all of id's protocols, directly or
7856  // through its super class and categories.
7857  // First, lhs protocols in the qualifier list must be found, direct
7858  // or indirect in rhs's qualifier list or it is a mismatch.
7859  for (auto *rhsProto : rhsQID->quals()) {
7860  if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7861  (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7862  match = true;
7863  break;
7864  }
7865  }
7866  if (!match)
7867  return false;
7868  }
7869 
7870  // Static class's protocols, or its super class or category protocols
7871  // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
7872  if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
7873  llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
7874  CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
7875  // This is rather dubious but matches gcc's behavior. If lhs has
7876  // no type qualifier and its class has no static protocol(s)
7877  // assume that it is mismatch.
7878  if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
7879  return false;
7880  for (auto *lhsProto : LHSInheritedProtocols) {
7881  bool match = false;
7882  for (auto *rhsProto : rhsQID->quals()) {
7883  if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7884  (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7885  match = true;
7886  break;
7887  }
7888  }
7889  if (!match)
7890  return false;
7891  }
7892  }
7893  return true;
7894  }
7895  return false;
7896 }
7897 
7898 /// canAssignObjCInterfaces - Return true if the two interface types are
7899 /// compatible for assignment from RHS to LHS. This handles validation of any
7900 /// protocol qualifiers on the LHS or RHS.
7902  const ObjCObjectPointerType *RHSOPT) {
7903  const ObjCObjectType* LHS = LHSOPT->getObjectType();
7904  const ObjCObjectType* RHS = RHSOPT->getObjectType();
7905 
7906  // If either type represents the built-in 'id' or 'Class' types, return true.
7907  if (LHS->isObjCUnqualifiedIdOrClass() ||
7909  return true;
7910 
7911  // Function object that propagates a successful result or handles
7912  // __kindof types.
7913  auto finish = [&](bool succeeded) -> bool {
7914  if (succeeded)
7915  return true;
7916 
7917  if (!RHS->isKindOfType())
7918  return false;
7919 
7920  // Strip off __kindof and protocol qualifiers, then check whether
7921  // we can assign the other way.
7923  LHSOPT->stripObjCKindOfTypeAndQuals(*this));
7924  };
7925 
7926  if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
7927  return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
7928  QualType(RHSOPT,0),
7929  false));
7930  }
7931 
7932  if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
7933  return finish(ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
7934  QualType(RHSOPT,0)));
7935  }
7936 
7937  // If we have 2 user-defined types, fall into that path.
7938  if (LHS->getInterface() && RHS->getInterface()) {
7939  return finish(canAssignObjCInterfaces(LHS, RHS));
7940  }
7941 
7942  return false;
7943 }
7944 
7945 /// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
7946 /// for providing type-safety for objective-c pointers used to pass/return
7947 /// arguments in block literals. When passed as arguments, passing 'A*' where
7948 /// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
7949 /// not OK. For the return type, the opposite is not OK.
7951  const ObjCObjectPointerType *LHSOPT,
7952  const ObjCObjectPointerType *RHSOPT,
7953  bool BlockReturnType) {
7954 
7955  // Function object that propagates a successful result or handles
7956  // __kindof types.
7957  auto finish = [&](bool succeeded) -> bool {
7958  if (succeeded)
7959  return true;
7960 
7961  const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
7962  if (!Expected->isKindOfType())
7963  return false;
7964 
7965  // Strip off __kindof and protocol qualifiers, then check whether
7966  // we can assign the other way.
7968  RHSOPT->stripObjCKindOfTypeAndQuals(*this),
7969  LHSOPT->stripObjCKindOfTypeAndQuals(*this),
7970  BlockReturnType);
7971  };
7972 
7973  if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
7974  return true;
7975 
7976  if (LHSOPT->isObjCBuiltinType()) {
7977  return finish(RHSOPT->isObjCBuiltinType() ||
7978  RHSOPT->isObjCQualifiedIdType());
7979  }
7980 
7981  if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
7982  return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
7983  QualType(RHSOPT,0),
7984  false));
7985 
7986  const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
7987  const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
7988  if (LHS && RHS) { // We have 2 user-defined types.
7989  if (LHS != RHS) {
7990  if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
7991  return finish(BlockReturnType);
7992  if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
7993  return finish(!BlockReturnType);
7994  }
7995  else
7996  return true;
7997  }
7998  return false;
7999 }
8000 
8001 /// Comparison routine for Objective-C protocols to be used with
8002 /// llvm::array_pod_sort.
8004  ObjCProtocolDecl * const *rhs) {
8005  return (*lhs)->getName().compare((*rhs)->getName());
8006 }
8007 
8008 /// getIntersectionOfProtocols - This routine finds the intersection of set
8009 /// of protocols inherited from two distinct objective-c pointer objects with
8010 /// the given common base.
8011 /// It is used to build composite qualifier list of the composite type of
8012 /// the conditional expression involving two objective-c pointer objects.
8013 static
8016  const ObjCObjectPointerType *LHSOPT,
8017  const ObjCObjectPointerType *RHSOPT,
8018  SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
8019 
8020  const ObjCObjectType* LHS = LHSOPT->getObjectType();
8021  const ObjCObjectType* RHS = RHSOPT->getObjectType();
8022  assert(LHS->getInterface() && "LHS must have an interface base");
8023  assert(RHS->getInterface() && "RHS must have an interface base");
8024 
8025  // Add all of the protocols for the LHS.
8026  llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
8027 
8028  // Start with the protocol qualifiers.
8029  for (auto proto : LHS->quals()) {
8030  Context.CollectInheritedProtocols(proto, LHSProtocolSet);
8031  }
8032 
8033  // Also add the protocols associated with the LHS interface.
8034  Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
8035 
8036  // Add all of the protocls for the RHS.
8037  llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
8038 
8039  // Start with the protocol qualifiers.
8040  for (auto proto : RHS->quals()) {
8041  Context.CollectInheritedProtocols(proto, RHSProtocolSet);
8042  }
8043 
8044  // Also add the protocols associated with the RHS interface.
8045  Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
8046 
8047  // Compute the intersection of the collected protocol sets.
8048  for (auto proto : LHSProtocolSet) {
8049  if (RHSProtocolSet.count(proto))
8050  IntersectionSet.push_back(proto);
8051  }
8052 
8053  // Compute the set of protocols that is implied by either the common type or
8054  // the protocols within the intersection.
8055  llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
8056  Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
8057 
8058  // Remove any implied protocols from the list of inherited protocols.
8059  if (!ImpliedProtocols.empty()) {
8060  IntersectionSet.erase(
8061  std::remove_if(IntersectionSet.begin(),
8062  IntersectionSet.end(),
8063  [&](ObjCProtocolDecl *proto) -> bool {
8064  return ImpliedProtocols.count(proto) > 0;
8065  }),
8066  IntersectionSet.end());
8067  }
8068 
8069  // Sort the remaining protocols by name.
8070  llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
8072 }
8073 
8074 /// Determine whether the first type is a subtype of the second.
8076  QualType rhs) {
8077  // Common case: two object pointers.
8078  const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
8079  const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
8080  if (lhsOPT && rhsOPT)
8081  return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
8082 
8083  // Two block pointers.
8084  const auto *lhsBlock = lhs->getAs<BlockPointerType>();
8085  const auto *rhsBlock = rhs->getAs<BlockPointerType>();
8086  if (lhsBlock && rhsBlock)
8087  return ctx.typesAreBlockPointerCompatible(lhs, rhs);
8088 
8089  // If either is an unqualified 'id' and the other is a block, it's
8090  // acceptable.
8091  if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
8092  (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
8093  return true;
8094 
8095  return false;
8096 }
8097 
8098 // Check that the given Objective-C type argument lists are equivalent.
8099 static bool sameObjCTypeArgs(ASTContext &ctx,
8100  const ObjCInterfaceDecl *iface,
8101  ArrayRef<QualType> lhsArgs,
8102  ArrayRef<QualType> rhsArgs,
8103  bool stripKindOf) {
8104  if (lhsArgs.size() != rhsArgs.size())
8105  return false;
8106 
8107  ObjCTypeParamList *typeParams = iface->getTypeParamList();
8108  for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
8109  if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
8110  continue;
8111 
8112  switch (typeParams->begin()[i]->getVariance()) {
8114  if (!stripKindOf ||
8115  !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
8116  rhsArgs[i].stripObjCKindOfType(ctx))) {
8117  return false;
8118  }
8119  break;
8120 
8122  if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
8123  return false;
8124  break;
8125 
8127  if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
8128  return false;
8129  break;
8130  }
8131  }
8132 
8133  return true;
8134 }
8135 
8137  const ObjCObjectPointerType *Lptr,
8138  const ObjCObjectPointerType *Rptr) {
8139  const ObjCObjectType *LHS = Lptr->getObjectType();
8140  const ObjCObjectType *RHS = Rptr->getObjectType();
8141  const ObjCInterfaceDecl* LDecl = LHS->getInterface();
8142  const ObjCInterfaceDecl* RDecl = RHS->getInterface();
8143 
8144  if (!LDecl || !RDecl)
8145  return {};
8146 
8147  // When either LHS or RHS is a kindof type, we should return a kindof type.
8148  // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
8149  // kindof(A).
8150  bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
8151 
8152  // Follow the left-hand side up the class hierarchy until we either hit a
8153  // root or find the RHS. Record the ancestors in case we don't find it.
8154  llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
8155  LHSAncestors;
8156  while (true) {
8157  // Record this ancestor. We'll need this if the common type isn't in the
8158  // path from the LHS to the root.
8159  LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
8160 
8161  if (declaresSameEntity(LHS->getInterface(), RDecl)) {
8162  // Get the type arguments.
8163  ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
8164  bool anyChanges = false;
8165  if (LHS->isSpecialized() && RHS->isSpecialized()) {
8166  // Both have type arguments, compare them.
8167  if (!sameObjCTypeArgs(*this, LHS->getInterface(),
8168  LHS->getTypeArgs(), RHS->getTypeArgs(),
8169  /*stripKindOf=*/true))
8170  return {};
8171  } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
8172  // If only one has type arguments, the result will not have type
8173  // arguments.
8174  LHSTypeArgs = {};
8175  anyChanges = true;
8176  }
8177 
8178  // Compute the intersection of protocols.
8180  getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
8181  Protocols);
8182  if (!Protocols.empty())
8183  anyChanges = true;
8184 
8185  // If anything in the LHS will have changed, build a new result type.
8186  // If we need to return a kindof type but LHS is not a kindof type, we
8187  // build a new result type.
8188  if (anyChanges || LHS->isKindOfType() != anyKindOf) {
8190  Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
8191  anyKindOf || LHS->isKindOfType());
8192  return getObjCObjectPointerType(Result);
8193  }
8194 
8195  return getObjCObjectPointerType(QualType(LHS, 0));
8196  }
8197 
8198  // Find the superclass.
8199  QualType LHSSuperType = LHS->getSuperClassType();
8200  if (LHSSuperType.isNull())
8201  break;
8202 
8203  LHS = LHSSuperType->castAs<ObjCObjectType>();
8204  }
8205 
8206  // We didn't find anything by following the LHS to its root; now check
8207  // the RHS against the cached set of ancestors.
8208  while (true) {
8209  auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
8210  if (KnownLHS != LHSAncestors.end()) {
8211  LHS = KnownLHS->second;
8212 
8213  // Get the type arguments.
8214  ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
8215  bool anyChanges = false;
8216  if (LHS->isSpecialized() && RHS->isSpecialized()) {
8217  // Both have type arguments, compare them.
8218  if (!sameObjCTypeArgs(*this, LHS->getInterface(),
8219  LHS->getTypeArgs(), RHS->getTypeArgs(),
8220  /*stripKindOf=*/true))
8221  return {};
8222  } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
8223  // If only one has type arguments, the result will not have type
8224  // arguments.
8225  RHSTypeArgs = {};
8226  anyChanges = true;
8227  }
8228 
8229  // Compute the intersection of protocols.
8231  getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
8232  Protocols);
8233  if (!Protocols.empty())
8234  anyChanges = true;
8235 
8236  // If we need to return a kindof type but RHS is not a kindof type, we
8237  // build a new result type.
8238  if (anyChanges || RHS->isKindOfType() != anyKindOf) {
8240  Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
8241  anyKindOf || RHS->isKindOfType());
8242  return getObjCObjectPointerType(Result);
8243  }
8244 
8245  return getObjCObjectPointerType(QualType(RHS, 0));
8246  }
8247 
8248  // Find the superclass of the RHS.
8249  QualType RHSSuperType = RHS->getSuperClassType();
8250  if (RHSSuperType.isNull())
8251  break;
8252 
8253  RHS = RHSSuperType->castAs<ObjCObjectType>();
8254  }
8255 
8256  return {};
8257 }
8258 
8260  const ObjCObjectType *RHS) {
8261  assert(LHS->getInterface() && "LHS is not an interface type");
8262  assert(RHS->getInterface() && "RHS is not an interface type");
8263 
8264  // Verify that the base decls are compatible: the RHS must be a subclass of
8265  // the LHS.
8266  ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
8267  bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
8268  if (!IsSuperClass)
8269  return false;
8270 
8271  // If the LHS has protocol qualifiers, determine whether all of them are
8272  // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
8273  // LHS).
8274  if (LHS->getNumProtocols() > 0) {
8275  // OK if conversion of LHS to SuperClass results in narrowing of types
8276  // ; i.e., SuperClass may implement at least one of the protocols
8277  // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
8278  // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
8279  llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
8280  CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
8281  // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
8282  // qualifiers.
8283  for (auto *RHSPI : RHS->quals())
8284  CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
8285  // If there is no protocols associated with RHS, it is not a match.
8286  if (SuperClassInheritedProtocols.empty())
8287  return false;
8288 
8289  for (const auto *LHSProto : LHS->quals()) {
8290  bool SuperImplementsProtocol = false;
8291  for (auto *SuperClassProto : SuperClassInheritedProtocols)
8292  if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
8293  SuperImplementsProtocol = true;
8294  break;
8295  }
8296  if (!SuperImplementsProtocol)
8297  return false;
8298  }
8299  }
8300 
8301  // If the LHS is specialized, we may need to check type arguments.
8302  if (LHS->isSpecialized()) {
8303  // Follow the superclass chain until we've matched the LHS class in the
8304  // hierarchy. This substitutes type arguments through.
8305  const ObjCObjectType *RHSSuper = RHS;
8306  while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
8307  RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
8308 
8309  // If the RHS is specializd, compare type arguments.
8310  if (RHSSuper->isSpecialized() &&
8311  !sameObjCTypeArgs(*this, LHS->getInterface(),
8312  LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
8313  /*stripKindOf=*/true)) {
8314  return false;
8315  }
8316  }
8317 
8318  return true;
8319 }
8320 
8322  // get the "pointed to" types
8323  const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
8324  const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
8325 
8326  if (!LHSOPT || !RHSOPT)
8327  return false;
8328 
8329  return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
8330  canAssignObjCInterfaces(RHSOPT, LHSOPT);
8331 }
8332 
8334  return canAssignObjCInterfaces(
8335  getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
8336  getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
8337 }
8338 
8339 /// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
8340 /// both shall have the identically qualified version of a compatible type.
8341 /// C99 6.2.7p1: Two types have compatible types if their types are the
8342 /// same. See 6.7.[2,3,5] for additional rules.
8344  bool CompareUnqualified) {
8345  if (getLangOpts().CPlusPlus)
8346  return hasSameType(LHS, RHS);
8347 
8348  return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
8349 }
8350 
8352  return typesAreCompatible(LHS, RHS);
8353 }
8354 
8356  return !mergeTypes(LHS, RHS, true).isNull();
8357 }
8358 
8359 /// mergeTransparentUnionType - if T is a transparent union type and a member
8360 /// of T is compatible with SubType, return the merged type, else return
8361 /// QualType()
8363  bool OfBlockPointer,
8364  bool Unqualified) {
8365  if (const RecordType *UT = T->getAsUnionType()) {
8366  RecordDecl *UD = UT->getDecl();
8367  if (UD->hasAttr<TransparentUnionAttr>()) {
8368  for (const auto *I : UD->fields()) {
8369  QualType ET = I->getType().getUnqualifiedType();
8370  QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
8371  if (!MT.isNull())
8372  return MT;
8373  }
8374  }
8375  }
8376 
8377  return {};
8378 }
8379 
8380 /// mergeFunctionParameterTypes - merge two types which appear as function
8381 /// parameter types
8383  bool OfBlockPointer,
8384  bool Unqualified) {
8385  // GNU extension: two types are compatible if they appear as a function
8386  // argument, one of the types is a transparent union type and the other
8387  // type is compatible with a union member
8388  QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
8389  Unqualified);
8390  if (!lmerge.isNull())
8391  return lmerge;
8392 
8393  QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
8394  Unqualified);
8395  if (!rmerge.isNull())
8396  return rmerge;
8397 
8398  return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
8399 }
8400 
8402  bool OfBlockPointer,
8403  bool Unqualified) {
8404  const auto *lbase = lhs->getAs<FunctionType>();
8405  const auto *rbase = rhs->getAs<FunctionType>();
8406  const auto *lproto = dyn_cast<FunctionProtoType>(lbase);
8407  const auto *rproto = dyn_cast<FunctionProtoType>(rbase);
8408  bool allLTypes = true;
8409  bool allRTypes = true;
8410 
8411  // Check return type
8412  QualType retType;
8413  if (OfBlockPointer) {
8414  QualType RHS = rbase->getReturnType();
8415  QualType LHS = lbase->getReturnType();
8416  bool UnqualifiedResult = Unqualified;
8417  if (!UnqualifiedResult)
8418  UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
8419  retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
8420  }
8421  else
8422  retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
8423  Unqualified);
8424  if (retType.isNull())
8425  return {};
8426 
8427  if (Unqualified)
8428  retType = retType.getUnqualifiedType();
8429 
8430  CanQualType LRetType = getCanonicalType(lbase->getReturnType());
8431  CanQualType RRetType = getCanonicalType(rbase->getReturnType());
8432  if (Unqualified) {
8433  LRetType = LRetType.getUnqualifiedType();
8434  RRetType = RRetType.getUnqualifiedType();
8435  }
8436 
8437  if (getCanonicalType(retType) != LRetType)
8438  allLTypes = false;
8439  if (getCanonicalType(retType) != RRetType)
8440  allRTypes = false;
8441 
8442  // FIXME: double check this
8443  // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
8444  // rbase->getRegParmAttr() != 0 &&
8445  // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
8446  FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
8447  FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
8448 
8449  // Compatible functions must have compatible calling conventions
8450  if (lbaseInfo.getCC() != rbaseInfo.getCC())
8451  return {};
8452 
8453  // Regparm is part of the calling convention.
8454  if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
8455  return {};
8456  if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
8457  return {};
8458 
8459  if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
8460  return {};
8461  if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs())
8462  return {};
8463  if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck())
8464  return {};
8465 
8466  // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
8467  bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
8468 
8469  if (lbaseInfo.getNoReturn() != NoReturn)
8470  allLTypes = false;
8471  if (rbaseInfo.getNoReturn() != NoReturn)
8472  allRTypes = false;
8473 
8474  FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
8475 
8476  if (lproto && rproto) { // two C99 style function prototypes
8477  assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
8478  "C++ shouldn't be here");
8479  // Compatible functions must have the same number of parameters
8480  if (lproto->getNumParams() != rproto->getNumParams())
8481  return {};
8482 
8483  // Variadic and non-variadic functions aren't compatible
8484  if (lproto->isVariadic() != rproto->isVariadic())
8485  return {};
8486 
8487  if (lproto->getTypeQuals() != rproto->getTypeQuals())
8488  return {};
8489 
8491  bool canUseLeft, canUseRight;
8492  if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight,
8493  newParamInfos))
8494  return {};
8495 
8496  if (!canUseLeft)
8497  allLTypes = false;
8498  if (!canUseRight)
8499  allRTypes = false;
8500 
8501  // Check parameter type compatibility
8503  for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
8504  QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
8505  QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
8507  lParamType, rParamType, OfBlockPointer, Unqualified);
8508  if (paramType.isNull())
8509  return {};
8510 
8511  if (Unqualified)
8512  paramType = paramType.getUnqualifiedType();
8513 
8514  types.push_back(paramType);
8515  if (Unqualified) {
8516  lParamType = lParamType.getUnqualifiedType();
8517  rParamType = rParamType.getUnqualifiedType();
8518  }
8519 
8520  if (getCanonicalType(paramType) != getCanonicalType(lParamType))
8521  allLTypes = false;
8522  if (getCanonicalType(paramType) != getCanonicalType(rParamType))
8523  allRTypes = false;
8524  }
8525 
8526  if (allLTypes) return lhs;
8527  if (allRTypes) return rhs;
8528 
8529  FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
8530  EPI.ExtInfo = einfo;
8531  EPI.ExtParameterInfos =
8532  newParamInfos.empty() ? nullptr : newParamInfos.data();
8533  return getFunctionType(retType, types, EPI);
8534  }
8535 
8536  if (lproto) allRTypes = false;
8537  if (rproto) allLTypes = false;
8538 
8539  const FunctionProtoType *proto = lproto ? lproto : rproto;
8540  if (proto) {
8541  assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
8542  if (proto->isVariadic())
8543  return {};
8544  // Check that the types are compatible with the types that
8545  // would result from default argument promotions (C99 6.7.5.3p15).
8546  // The only types actually affected are promotable integer
8547  // types and floats, which would be passed as a different
8548  // type depending on whether the prototype is visible.
8549  for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
8550  QualType paramTy = proto->getParamType(i);
8551 
8552  // Look at the converted type of enum types, since that is the type used
8553  // to pass enum values.
8554  if (const auto *Enum = paramTy->getAs<EnumType>()) {
8555  paramTy = Enum->getDecl()->getIntegerType();
8556  if (paramTy.isNull())
8557  return {};
8558  }
8559 
8560  if (paramTy->isPromotableIntegerType() ||
8562  return {};
8563  }
8564 
8565  if (allLTypes) return lhs;
8566  if (allRTypes) return rhs;
8567 
8569  EPI.ExtInfo = einfo;
8570  return getFunctionType(retType, proto->getParamTypes(), EPI);
8571  }
8572 
8573  if (allLTypes) return lhs;
8574  if (allRTypes) return rhs;
8575  return getFunctionNoProtoType(retType, einfo);
8576 }
8577 
8578 /// Given that we have an enum type and a non-enum type, try to merge them.
8580  QualType other, bool isBlockReturnType) {
8581  // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
8582  // a signed integer type, or an unsigned integer type.
8583  // Compatibility is based on the underlying type, not the promotion
8584  // type.
8585  QualType underlyingType = ET->getDecl()->getIntegerType();
8586  if (underlyingType.isNull())
8587  return {};
8588  if (Context.hasSameType(underlyingType, other))
8589  return other;
8590 
8591  // In block return types, we're more permissive and accept any
8592  // integral type of the same size.
8593  if (isBlockReturnType && other->isIntegerType() &&
8594  Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
8595  return other;
8596 
8597  return {};
8598 }
8599 
8601  bool OfBlockPointer,
8602  bool Unqualified, bool BlockReturnType) {
8603  // C++ [expr]: If an expression initially has the type "reference to T", the
8604  // type is adjusted to "T" prior to any further analysis, the expression
8605  // designates the object or function denoted by the reference, and the
8606  // expression is an lvalue unless the reference is an rvalue reference and
8607  // the expression is a function call (possibly inside parentheses).
8608  assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
8609  assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
8610 
8611  if (Unqualified) {
8612  LHS = LHS.getUnqualifiedType();
8613  RHS = RHS.getUnqualifiedType();
8614  }
8615 
8616  QualType LHSCan = getCanonicalType(LHS),
8617  RHSCan = getCanonicalType(RHS);
8618 
8619  // If two types are identical, they are compatible.
8620  if (LHSCan == RHSCan)
8621  return LHS;
8622 
8623  // If the qualifiers are different, the types aren't compatible... mostly.
8624  Qualifiers LQuals = LHSCan.getLocalQualifiers();
8625  Qualifiers RQuals = RHSCan.getLocalQualifiers();
8626  if (LQuals != RQuals) {
8627  // If any of these qualifiers are different, we have a type
8628  // mismatch.
8629  if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
8630  LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
8631  LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
8632  LQuals.hasUnaligned() != RQuals.hasUnaligned())
8633  return {};
8634 
8635  // Exactly one GC qualifier difference is allowed: __strong is
8636  // okay if the other type has no GC qualifier but is an Objective
8637  // C object pointer (i.e. implicitly strong by default). We fix
8638  // this by pretending that the unqualified type was actually
8639  // qualified __strong.
8640  Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
8641  Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
8642  assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
8643 
8644  if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
8645  return {};
8646 
8647  if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
8648  return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
8649  }
8650  if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
8651  return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
8652  }
8653  return {};
8654  }
8655 
8656  // Okay, qualifiers are equal.
8657 
8658  Type::TypeClass LHSClass = LHSCan->getTypeClass();
8659  Type::TypeClass RHSClass = RHSCan->getTypeClass();
8660 
8661  // We want to consider the two function types to be the same for these
8662  // comparisons, just force one to the other.
8663  if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
8664  if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
8665 
8666  // Same as above for arrays
8667  if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
8668  LHSClass = Type::ConstantArray;
8669  if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
8670  RHSClass = Type::ConstantArray;
8671 
8672  // ObjCInterfaces are just specialized ObjCObjects.
8673  if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
8674  if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
8675 
8676  // Canonicalize ExtVector -> Vector.
8677  if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
8678  if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
8679 
8680  // If the canonical type classes don't match.
8681  if (LHSClass != RHSClass) {
8682  // Note that we only have special rules for turning block enum
8683  // returns into block int returns, not vice-versa.
8684  if (const auto *ETy = LHS->getAs<EnumType>()) {
8685  return mergeEnumWithInteger(*this, ETy, RHS, false);
8686  }
8687  if (const EnumType* ETy = RHS->getAs<EnumType>()) {
8688  return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
8689  }
8690  // allow block pointer type to match an 'id' type.
8691  if (OfBlockPointer && !BlockReturnType) {
8692  if (LHS->isObjCIdType() && RHS->isBlockPointerType())
8693  return LHS;
8694  if (RHS->isObjCIdType() && LHS->isBlockPointerType())
8695  return RHS;
8696  }
8697 
8698  return {};
8699  }
8700 
8701  // The canonical type classes match.
8702  switch (LHSClass) {
8703 #define TYPE(Class, Base)
8704 #define ABSTRACT_TYPE(Class, Base)
8705 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
8706 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
8707 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
8708 #include "clang/AST/TypeNodes.def"
8709  llvm_unreachable("Non-canonical and dependent types shouldn't get here");
8710 
8711  case Type::Auto:
8712  case Type::DeducedTemplateSpecialization:
8713  case Type::LValueReference:
8714  case Type::RValueReference:
8715  case Type::MemberPointer:
8716  llvm_unreachable("C++ should never be in mergeTypes");
8717 
8718  case Type::ObjCInterface:
8719  case Type::IncompleteArray:
8720  case Type::VariableArray:
8721  case Type::FunctionProto:
8722  case Type::ExtVector:
8723  llvm_unreachable("Types are eliminated above");
8724 
8725  case Type::Pointer:
8726  {
8727  // Merge two pointer types, while trying to preserve typedef info
8728  QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
8729  QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
8730  if (Unqualified) {
8731  LHSPointee = LHSPointee.getUnqualifiedType();
8732  RHSPointee = RHSPointee.getUnqualifiedType();
8733  }
8734  QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
8735  Unqualified);
8736  if (ResultType.isNull())
8737  return {};
8738  if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
8739  return LHS;
8740  if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
8741  return RHS;
8742  return getPointerType(ResultType);
8743  }
8744  case Type::BlockPointer:
8745  {
8746  // Merge two block pointer types, while trying to preserve typedef info
8747  QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
8748  QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
8749  if (Unqualified) {
8750  LHSPointee = LHSPointee.getUnqualifiedType();
8751  RHSPointee = RHSPointee.getUnqualifiedType();
8752  }
8753  if (getLangOpts().OpenCL) {
8754  Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
8755  Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
8756  // Blocks can't be an expression in a ternary operator (OpenCL v2.0
8757  // 6.12.5) thus the following check is asymmetric.
8758  if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual))
8759  return {};
8760  LHSPteeQual.removeAddressSpace();
8761  RHSPteeQual.removeAddressSpace();
8762  LHSPointee =
8763  QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
8764  RHSPointee =
8765  QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
8766  }
8767  QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
8768  Unqualified);
8769  if (ResultType.isNull())
8770  return {};
8771  if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
8772  return LHS;
8773  if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
8774  return RHS;
8775  return getBlockPointerType(ResultType);
8776  }
8777  case Type::Atomic:
8778  {
8779  // Merge two pointer types, while trying to preserve typedef info
8780  QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
8781  QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
8782  if (Unqualified) {
8783  LHSValue = LHSValue.getUnqualifiedType();
8784  RHSValue = RHSValue.getUnqualifiedType();
8785  }
8786  QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
8787  Unqualified);
8788  if (ResultType.isNull())
8789  return {};
8790  if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
8791  return LHS;
8792  if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
8793  return RHS;
8794  return getAtomicType(ResultType);
8795  }
8796  case Type::ConstantArray:
8797  {
8798  const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
8799  const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
8800  if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
8801  return {};
8802 
8803  QualType LHSElem = getAsArrayType(LHS)->getElementType();
8804  QualType RHSElem = getAsArrayType(RHS)->getElementType();
8805  if (Unqualified) {
8806  LHSElem = LHSElem.getUnqualifiedType();
8807  RHSElem = RHSElem.getUnqualifiedType();
8808  }
8809 
8810  QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
8811  if (ResultType.isNull())
8812  return {};
8813 
8814  const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
8815  const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
8816 
8817  // If either side is a variable array, and both are complete, check whether
8818  // the current dimension is definite.
8819  if (LVAT || RVAT) {
8820  auto SizeFetch = [this](const VariableArrayType* VAT,
8821  const ConstantArrayType* CAT)
8822  -> std::pair<bool,llvm::APInt> {
8823  if (VAT) {
8824  llvm::APSInt TheInt;
8825  Expr *E = VAT->getSizeExpr();
8826  if (E && E->isIntegerConstantExpr(TheInt, *this))
8827  return std::make_pair(true, TheInt);
8828  else
8829  return std::make_pair(false, TheInt);
8830  } else if (CAT) {
8831  return std::make_pair(true, CAT->getSize());
8832  } else {
8833  return std::make_pair(false, llvm::APInt());
8834  }
8835  };
8836 
8837  bool HaveLSize, HaveRSize;
8838  llvm::APInt LSize, RSize;
8839  std::tie(HaveLSize, LSize) = SizeFetch(LVAT, LCAT);
8840  std::tie(HaveRSize, RSize) = SizeFetch(RVAT, RCAT);
8841  if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(LSize, RSize))
8842  return {}; // Definite, but unequal, array dimension
8843  }
8844 
8845  if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
8846  return LHS;
8847  if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
8848  return RHS;
8849  if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
8851  if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
8853  if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
8854  return LHS;
8855  if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
8856  return RHS;
8857  if (LVAT) {
8858  // FIXME: This isn't correct! But tricky to implement because
8859  // the array's size has to be the size of LHS, but the type
8860  // has to be different.
8861  return LHS;
8862  }
8863  if (RVAT) {
8864  // FIXME: This isn't correct! But tricky to implement because
8865  // the array's size has to be the size of RHS, but the type
8866  // has to be different.
8867  return RHS;
8868  }
8869  if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
8870  if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
8871  return getIncompleteArrayType(ResultType,
8873  }
8874  case Type::FunctionNoProto:
8875  return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
8876  case Type::Record:
8877  case Type::Enum:
8878  return {};
8879  case Type::Builtin:
8880  // Only exactly equal builtin types are compatible, which is tested above.
8881  return {};
8882  case Type::Complex:
8883  // Distinct complex types are incompatible.
8884  return {};
8885  case Type::Vector:
8886  // FIXME: The merged type should be an ExtVector!
8887  if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
8888  RHSCan->getAs<VectorType>()))
8889  return LHS;
8890  return {};
8891  case Type::ObjCObject: {
8892  // Check if the types are assignment compatible.
8893  // FIXME: This should be type compatibility, e.g. whether
8894  // "LHS x; RHS x;" at global scope is legal.
8895  const auto *LHSIface = LHS->getAs<ObjCObjectType>();
8896  const auto *RHSIface = RHS->getAs<ObjCObjectType>();
8897  if (canAssignObjCInterfaces(LHSIface, RHSIface))
8898  return LHS;
8899 
8900  return {};
8901  }
8902  case Type::ObjCObjectPointer:
8903  if (OfBlockPointer) {
8905  LHS->getAs<ObjCObjectPointerType>(),
8906  RHS->getAs<ObjCObjectPointerType>(),
8907  BlockReturnType))
8908  return LHS;
8909  return {};
8910  }
8912  RHS->getAs<ObjCObjectPointerType>()))
8913  return LHS;
8914 
8915  return {};
8916  case Type::Pipe:
8917  assert(LHS != RHS &&
8918  "Equivalent pipe types should have already been handled!");
8919  return {};
8920  }
8921 
8922  llvm_unreachable("Invalid Type::Class!");
8923 }
8924 
8926  const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType,
8927  bool &CanUseFirst, bool &CanUseSecond,
8929  assert(NewParamInfos.empty() && "param info list not empty");
8930  CanUseFirst = CanUseSecond = true;
8931  bool FirstHasInfo = FirstFnType->hasExtParameterInfos();
8932  bool SecondHasInfo = SecondFnType->hasExtParameterInfos();
8933 
8934  // Fast path: if the first type doesn't have ext parameter infos,
8935  // we match if and only if the second type also doesn't have them.
8936  if (!FirstHasInfo && !SecondHasInfo)
8937  return true;
8938 
8939  bool NeedParamInfo = false;
8940  size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size()
8941  : SecondFnType->getExtParameterInfos().size();
8942 
8943  for (size_t I = 0; I < E; ++I) {
8944  FunctionProtoType::ExtParameterInfo FirstParam, SecondParam;
8945  if (FirstHasInfo)
8946  FirstParam = FirstFnType->getExtParameterInfo(I);
8947  if (SecondHasInfo)
8948  SecondParam = SecondFnType->getExtParameterInfo(I);
8949 
8950  // Cannot merge unless everything except the noescape flag matches.
8951  if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false))
8952  return false;
8953 
8954  bool FirstNoEscape = FirstParam.isNoEscape();
8955  bool SecondNoEscape = SecondParam.isNoEscape();
8956  bool IsNoEscape = FirstNoEscape && SecondNoEscape;
8957  NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape));
8958  if (NewParamInfos.back().getOpaqueValue())
8959  NeedParamInfo = true;
8960  if (FirstNoEscape != IsNoEscape)
8961  CanUseFirst = false;
8962  if (SecondNoEscape != IsNoEscape)
8963  CanUseSecond = false;
8964  }
8965 
8966  if (!NeedParamInfo)
8967  NewParamInfos.clear();
8968 
8969  return true;
8970 }
8971 
8973  ObjCLayouts[CD] = nullptr;
8974 }
8975 
8976 /// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
8977 /// 'RHS' attributes and returns the merged version; including for function
8978 /// return types.
8980  QualType LHSCan = getCanonicalType(LHS),
8981  RHSCan = getCanonicalType(RHS);
8982  // If two types are identical, they are compatible.
8983  if (LHSCan == RHSCan)
8984  return LHS;
8985  if (RHSCan->isFunctionType()) {
8986  if (!LHSCan->isFunctionType())
8987  return {};
8988  QualType OldReturnType =
8989  cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
8990  QualType NewReturnType =
8991  cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
8992  QualType ResReturnType =
8993  mergeObjCGCQualifiers(NewReturnType, OldReturnType);
8994  if (ResReturnType.isNull())
8995  return {};
8996  if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
8997  // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
8998  // In either case, use OldReturnType to build the new function type.
8999  const auto *F = LHS->getAs<FunctionType>();
9000  if (const auto *FPT = cast<FunctionProtoType>(F)) {
9001  FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9002  EPI.ExtInfo = getFunctionExtInfo(LHS);
9003  QualType ResultType =
9004  getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
9005  return ResultType;
9006  }
9007  }
9008  return {};
9009  }
9010 
9011  // If the qualifiers are different, the types can still be merged.
9012  Qualifiers LQuals = LHSCan.getLocalQualifiers();
9013  Qualifiers RQuals = RHSCan.getLocalQualifiers();
9014  if (LQuals != RQuals) {
9015  // If any of these qualifiers are different, we have a type mismatch.
9016  if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
9017  LQuals.getAddressSpace() != RQuals.getAddressSpace())
9018  return {};
9019 
9020  // Exactly one GC qualifier difference is allowed: __strong is
9021  // okay if the other type has no GC qualifier but is an Objective
9022  // C object pointer (i.e. implicitly strong by default). We fix
9023  // this by pretending that the unqualified type was actually
9024  // qualified __strong.
9025  Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
9026  Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
9027  assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
9028 
9029  if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
9030  return {};
9031 
9032  if (GC_L == Qualifiers::Strong)
9033  return LHS;
9034  if (GC_R == Qualifiers::Strong)
9035  return RHS;
9036  return {};
9037  }
9038 
9039  if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
9040  QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
9041  QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
9042  QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
9043  if (ResQT == LHSBaseQT)
9044  return LHS;
9045  if (ResQT == RHSBaseQT)
9046  return RHS;
9047  }
9048  return {};
9049 }
9050 
9051 //===----------------------------------------------------------------------===//
9052 // Integer Predicates
9053 //===----------------------------------------------------------------------===//
9054 
9056  if (const auto *ET = T->getAs<EnumType>())
9057  T = ET->getDecl()->getIntegerType();
9058  if (T->isBooleanType())
9059  return 1;
9060  // For builtin types, just use the standard type sizing method
9061  return (unsigned)getTypeSize(T);
9062 }
9063 
9066  "Unexpected type");
9067 
9068  // Turn <4 x signed int> -> <4 x unsigned int>
9069  if (const auto *VTy = T->getAs<VectorType>())
9070  return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
9071  VTy->getNumElements(), VTy->getVectorKind());
9072 
9073  // For enums, we return the unsigned version of the base type.
9074  if (const auto *ETy = T->getAs<EnumType>())
9075  T = ETy->getDecl()->getIntegerType();
9076 
9077  const auto *BTy = T->getAs<BuiltinType>();
9078  assert(BTy && "Unexpected signed integer or fixed point type");
9079  switch (BTy->getKind()) {
9080  case BuiltinType::Char_S:
9081  case BuiltinType::SChar:
9082  return UnsignedCharTy;
9083  case BuiltinType::Short:
9084  return UnsignedShortTy;
9085  case BuiltinType::Int:
9086  return UnsignedIntTy;
9087  case BuiltinType::Long:
9088  return UnsignedLongTy;
9089  case BuiltinType::LongLong:
9090  return UnsignedLongLongTy;
9091  case BuiltinType::Int128:
9092  return UnsignedInt128Ty;
9093 
9094  case BuiltinType::ShortAccum:
9095  return UnsignedShortAccumTy;
9096  case BuiltinType::Accum:
9097  return UnsignedAccumTy;
9098  case BuiltinType::LongAccum:
9099  return UnsignedLongAccumTy;
9100  case BuiltinType::SatShortAccum:
9101  return SatUnsignedShortAccumTy;
9102  case BuiltinType::SatAccum:
9103  return SatUnsignedAccumTy;
9104  case BuiltinType::SatLongAccum:
9105  return SatUnsignedLongAccumTy;
9106  case BuiltinType::ShortFract:
9107  return UnsignedShortFractTy;
9108  case BuiltinType::Fract:
9109  return UnsignedFractTy;
9110  case BuiltinType::LongFract:
9111  return UnsignedLongFractTy;
9112  case BuiltinType::SatShortFract:
9113  return SatUnsignedShortFractTy;
9114  case BuiltinType::SatFract:
9115  return SatUnsignedFractTy;
9116  case BuiltinType::SatLongFract:
9117  return SatUnsignedLongFractTy;
9118  default:
9119  llvm_unreachable("Unexpected signed integer or fixed point type");
9120  }
9121 }
9122 
9124 
9126  QualType ReturnType) {}
9127 
9128 //===----------------------------------------------------------------------===//
9129 // Builtin Type Computation
9130 //===----------------------------------------------------------------------===//
9131 
9132 /// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
9133 /// pointer over the consumed characters. This returns the resultant type. If
9134 /// AllowTypeModifiers is false then modifier like * are not parsed, just basic
9135 /// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
9136 /// a vector of "i*".
9137 ///
9138 /// RequiresICE is filled in on return to indicate whether the value is required
9139 /// to be an Integer Constant Expression.
9140 static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
9142  bool &RequiresICE,
9143  bool AllowTypeModifiers) {
9144  // Modifiers.
9145  int HowLong = 0;
9146  bool Signed = false, Unsigned = false;
9147  RequiresICE = false;
9148 
9149  // Read the prefixed modifiers first.
9150  bool Done = false;
9151  #ifndef NDEBUG
9152  bool IsSpecialLong = false;
9153  #endif
9154  while (!Done) {
9155  switch (*Str++) {
9156  default: Done = true; --Str; break;
9157  case 'I':
9158  RequiresICE = true;
9159  break;
9160  case 'S':
9161  assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
9162  assert(!Signed && "Can't use 'S' modifier multiple times!");
9163  Signed = true;
9164  break;
9165  case 'U':
9166  assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
9167  assert(!Unsigned && "Can't use 'U' modifier multiple times!");
9168  Unsigned = true;
9169  break;
9170  case 'L':
9171  assert(!IsSpecialLong && "Can't use 'L' with 'W' or 'N' modifiers");
9172  assert(HowLong <= 2 && "Can't have LLLL modifier");
9173  ++HowLong;
9174  break;
9175  case 'N':
9176  // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
9177  assert(!IsSpecialLong && "Can't use two 'N' or 'W' modifiers!");
9178  assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
9179  #ifndef NDEBUG
9180  IsSpecialLong = true;
9181  #endif
9182  if (Context.getTargetInfo().getLongWidth() == 32)
9183  ++HowLong;
9184  break;
9185  case 'W':
9186  // This modifier represents int64 type.
9187  assert(!IsSpecialLong && "Can't use two 'N' or 'W' modifiers!");
9188  assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
9189  #ifndef NDEBUG
9190  IsSpecialLong = true;
9191  #endif
9192  switch (Context.getTargetInfo().getInt64Type()) {
9193  default:
9194  llvm_unreachable("Unexpected integer type");
9196  HowLong = 1;
9197  break;
9199  HowLong = 2;
9200  break;
9201  }
9202  break;
9203  }
9204  }
9205 
9206  QualType Type;
9207 
9208  // Read the base type.
9209  switch (*Str++) {
9210  default: llvm_unreachable("Unknown builtin type letter!");
9211  case 'v':
9212  assert(HowLong == 0 && !Signed && !Unsigned &&
9213  "Bad modifiers used with 'v'!");
9214  Type = Context.VoidTy;
9215  break;
9216  case 'h':
9217  assert(HowLong == 0 && !Signed && !Unsigned &&
9218  "Bad modifiers used with 'h'!");
9219  Type = Context.HalfTy;
9220  break;
9221  case 'f':
9222  assert(HowLong == 0 && !Signed && !Unsigned &&
9223  "Bad modifiers used with 'f'!");
9224  Type = Context.FloatTy;
9225  break;
9226  case 'd':
9227  assert(HowLong < 3 && !Signed && !Unsigned &&
9228  "Bad modifiers used with 'd'!");
9229  if (HowLong == 1)
9230  Type = Context.LongDoubleTy;
9231  else if (HowLong == 2)
9232  Type = Context.Float128Ty;
9233  else
9234  Type = Context.DoubleTy;
9235  break;
9236  case 's':
9237  assert(HowLong == 0 && "Bad modifiers used with 's'!");
9238  if (Unsigned)
9239  Type = Context.UnsignedShortTy;
9240  else
9241  Type = Context.ShortTy;
9242  break;
9243  case 'i':
9244  if (HowLong == 3)
9245  Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
9246  else if (HowLong == 2)
9247  Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
9248  else if (HowLong == 1)
9249  Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
9250  else
9251  Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
9252  break;
9253  case 'c':
9254  assert(HowLong == 0 && "Bad modifiers used with 'c'!");
9255  if (Signed)
9256  Type = Context.SignedCharTy;
9257  else if (Unsigned)
9258  Type = Context.UnsignedCharTy;
9259  else
9260  Type = Context.CharTy;
9261  break;
9262  case 'b': // boolean
9263  assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
9264  Type = Context.BoolTy;
9265  break;
9266  case 'z': // size_t.
9267  assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
9268  Type = Context.getSizeType();
9269  break;
9270  case 'w': // wchar_t.
9271  assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
9272  Type = Context.getWideCharType();
9273  break;
9274  case 'F':
9275  Type = Context.getCFConstantStringType();
9276  break;
9277  case 'G':
9278  Type = Context.getObjCIdType();
9279  break;
9280  case 'H':
9281  Type = Context.getObjCSelType();
9282  break;
9283  case 'M':
9284  Type = Context.getObjCSuperType();
9285  break;
9286  case 'a':
9287  Type = Context.getBuiltinVaListType();
9288  assert(!Type.isNull() && "builtin va list type not initialized!");
9289  break;
9290  case 'A':
9291  // This is a "reference" to a va_list; however, what exactly
9292  // this means depends on how va_list is defined. There are two
9293  // different kinds of va_list: ones passed by value, and ones
9294  // passed by reference. An example of a by-value va_list is
9295  // x86, where va_list is a char*. An example of by-ref va_list
9296  // is x86-64, where va_list is a __va_list_tag[1]. For x86,
9297  // we want this argument to be a char*&; for x86-64, we want
9298  // it to be a __va_list_tag*.
9299  Type = Context.getBuiltinVaListType();
9300  assert(!Type.isNull() && "builtin va list type not initialized!");
9301  if (Type->isArrayType())
9302  Type = Context.getArrayDecayedType(Type);
9303  else
9304  Type = Context.getLValueReferenceType(Type);
9305  break;
9306  case 'V': {
9307  char *End;
9308  unsigned NumElements = strtoul(Str, &End, 10);
9309  assert(End != Str && "Missing vector size");
9310  Str = End;
9311 
9312  QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
9313  RequiresICE, false);
9314  assert(!RequiresICE && "Can't require vector ICE");
9315 
9316  // TODO: No way to make AltiVec vectors in builtins yet.
9317  Type = Context.getVectorType(ElementType, NumElements,
9319  break;
9320  }
9321  case 'E': {
9322  char *End;
9323 
9324  unsigned NumElements = strtoul(Str, &End, 10);
9325  assert(End != Str && "Missing vector size");
9326 
9327  Str = End;
9328 
9329  QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
9330  false);
9331  Type = Context.getExtVectorType(ElementType, NumElements);
9332  break;
9333  }
9334  case 'X': {
9335  QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
9336  false);
9337  assert(!RequiresICE && "Can't require complex ICE");
9338  Type = Context.getComplexType(ElementType);
9339  break;
9340  }
9341  case 'Y':
9342  Type = Context.getPointerDiffType();
9343  break;
9344  case 'P':
9345  Type = Context.getFILEType();
9346  if (Type.isNull()) {
9348  return {};
9349  }
9350  break;
9351  case 'J':
9352  if (Signed)
9353  Type = Context.getsigjmp_bufType();
9354  else
9355  Type = Context.getjmp_bufType();
9356 
9357  if (Type.isNull()) {
9359  return {};
9360  }
9361  break;
9362  case 'K':
9363  assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
9364  Type = Context.getucontext_tType();
9365 
9366  if (Type.isNull()) {
9368  return {};
9369  }
9370  break;
9371  case 'p':
9372  Type = Context.getProcessIDType();
9373  break;
9374  }
9375 
9376  // If there are modifiers and if we're allowed to parse them, go for it.
9377  Done = !AllowTypeModifiers;
9378  while (!Done) {
9379  switch (char c = *Str++) {
9380  default: Done = true; --Str; break;
9381  case '*':
9382  case '&': {
9383  // Both pointers and references can have their pointee types
9384  // qualified with an address space.
9385  char *End;
9386  unsigned AddrSpace = strtoul(Str, &End, 10);
9387  if (End != Str && AddrSpace != 0) {
9388  Type = Context.getAddrSpaceQualType(Type,
9389  getLangASFromTargetAS(AddrSpace));
9390  Str = End;
9391  }
9392  if (c == '*')
9393  Type = Context.getPointerType(Type);
9394  else
9395  Type = Context.getLValueReferenceType(Type);
9396  break;
9397  }
9398  // FIXME: There's no way to have a built-in with an rvalue ref arg.
9399  case 'C':
9400  Type = Type.withConst();
9401  break;
9402  case 'D':
9403  Type = Context.getVolatileType(Type);
9404  break;
9405  case 'R':
9406  Type = Type.withRestrict();
9407  break;
9408  }
9409  }
9410 
9411  assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
9412  "Integer constant 'I' type must be an integer");
9413 
9414  return Type;
9415 }
9416 
9417 /// GetBuiltinType - Return the type for the specified builtin.
9420  unsigned *IntegerConstantArgs) const {
9421  const char *TypeStr = BuiltinInfo.getTypeString(Id);
9422 
9423  SmallVector<QualType, 8> ArgTypes;
9424 
9425  bool RequiresICE = false;
9426  Error = GE_None;
9427  QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
9428  RequiresICE, true);
9429  if (Error != GE_None)
9430  return {};
9431 
9432  assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
9433 
9434  while (TypeStr[0] && TypeStr[0] != '.') {
9435  QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
9436  if (Error != GE_None)
9437  return {};
9438 
9439  // If this argument is required to be an IntegerConstantExpression and the
9440  // caller cares, fill in the bitmask we return.
9441  if (RequiresICE && IntegerConstantArgs)
9442  *IntegerConstantArgs |= 1 << ArgTypes.size();
9443 
9444  // Do array -> pointer decay. The builtin should use the decayed type.
9445  if (Ty->isArrayType())
9446  Ty = getArrayDecayedType(Ty);
9447 
9448  ArgTypes.push_back(Ty);
9449  }
9450 
9451  if (Id == Builtin::BI__GetExceptionInfo)
9452  return {};
9453 
9454  assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
9455  "'.' should only occur at end of builtin type list!");
9456 
9458  if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
9459 
9460  bool Variadic = (TypeStr[0] == '.');
9461 
9462  // We really shouldn't be making a no-proto type here.
9463  if (ArgTypes.empty() && Variadic && !getLangOpts().CPlusPlus)
9464  return getFunctionNoProtoType(ResType, EI);
9465 
9467  EPI.ExtInfo = EI;
9468  EPI.Variadic = Variadic;
9469  if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id))
9470  EPI.ExceptionSpec.Type =
9471  getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
9472 
9473  return getFunctionType(ResType, ArgTypes, EPI);
9474 }
9475 
9477  const FunctionDecl *FD) {
9478  if (!FD->isExternallyVisible())
9479  return GVA_Internal;
9480 
9481  // Non-user-provided functions get emitted as weak definitions with every
9482  // use, no matter whether they've been explicitly instantiated etc.
9483  if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
9484  if (!MD->isUserProvided())
9485  return GVA_DiscardableODR;
9486 
9487  GVALinkage External;
9488  switch (FD->getTemplateSpecializationKind()) {
9489  case TSK_Undeclared:
9491  External = GVA_StrongExternal;
9492  break;
9493 
9495  return GVA_StrongODR;
9496 
9497  // C++11 [temp.explicit]p10:
9498  // [ Note: The intent is that an inline function that is the subject of
9499  // an explicit instantiation declaration will still be implicitly
9500  // instantiated when used so that the body can be considered for
9501  // inlining, but that no out-of-line copy of the inline function would be
9502  // generated in the translation unit. -- end note ]
9504  return GVA_AvailableExternally;
9505 
9507  External = GVA_DiscardableODR;
9508  break;
9509  }
9510 
9511  if (!FD->isInlined())
9512  return External;
9513 
9514  if ((!Context.getLangOpts().CPlusPlus &&
9515  !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
9516  !FD->hasAttr<DLLExportAttr>()) ||
9517  FD->hasAttr<GNUInlineAttr>()) {
9518  // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
9519 
9520  // GNU or C99 inline semantics. Determine whether this symbol should be
9521  // externally visible.
9523  return External;
9524 
9525  // C99 inline semantics, where the symbol is not externally visible.
9526  return GVA_AvailableExternally;
9527  }
9528 
9529  // Functions specified with extern and inline in -fms-compatibility mode
9530  // forcibly get emitted. While the body of the function cannot be later
9531  // replaced, the function definition cannot be discarded.
9532  if (FD->isMSExternInline())
9533  return GVA_StrongODR;
9534 
9535  return GVA_DiscardableODR;
9536 }
9537 
9539  const Decl *D, GVALinkage L) {
9540  // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
9541  // dllexport/dllimport on inline functions.
9542  if (D->hasAttr<DLLImportAttr>()) {
9543  if (L == GVA_DiscardableODR || L == GVA_StrongODR)
9544  return GVA_AvailableExternally;
9545  } else if (D->hasAttr<DLLExportAttr>()) {
9546  if (L == GVA_DiscardableODR)
9547  return GVA_StrongODR;
9548  } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice &&
9549  D->hasAttr<CUDAGlobalAttr>()) {
9550  // Device-side functions with __global__ attribute must always be
9551  // visible externally so they can be launched from host.
9552  if (L == GVA_DiscardableODR || L == GVA_Internal)
9553  return GVA_StrongODR;
9554  }
9555  return L;
9556 }
9557 
9558 /// Adjust the GVALinkage for a declaration based on what an external AST source
9559 /// knows about whether there can be other definitions of this declaration.
9560 static GVALinkage
9562  GVALinkage L) {
9563  ExternalASTSource *Source = Ctx.getExternalSource();
9564  if (!Source)
9565  return L;
9566 
9567  switch (Source->hasExternalDefinitions(D)) {
9569  // Other translation units rely on us to provide the definition.
9570  if (L == GVA_DiscardableODR)
9571  return GVA_StrongODR;
9572  break;
9573 
9575  return GVA_AvailableExternally;
9576 
9578  break;
9579  }
9580  return L;
9581 }
9582 
9586  basicGVALinkageForFunction(*this, FD)));
9587 }
9588 
9590  const VarDecl *VD) {
9591  if (!VD->isExternallyVisible())
9592  return GVA_Internal;
9593 
9594  if (VD->isStaticLocal()) {
9595  const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
9596  while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
9597  LexicalContext = LexicalContext->getLexicalParent();
9598 
9599  // ObjC Blocks can create local variables that don't have a FunctionDecl
9600  // LexicalContext.
9601  if (!LexicalContext)
9602  return GVA_DiscardableODR;
9603 
9604  // Otherwise, let the static local variable inherit its linkage from the
9605  // nearest enclosing function.
9606  auto StaticLocalLinkage =
9607  Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
9608 
9609  // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
9610  // be emitted in any object with references to the symbol for the object it
9611  // contains, whether inline or out-of-line."
9612  // Similar behavior is observed with MSVC. An alternative ABI could use
9613  // StrongODR/AvailableExternally to match the function, but none are
9614  // known/supported currently.
9615  if (StaticLocalLinkage == GVA_StrongODR ||
9616  StaticLocalLinkage == GVA_AvailableExternally)
9617  return GVA_DiscardableODR;
9618  return StaticLocalLinkage;
9619  }
9620 
9621  // MSVC treats in-class initialized static data members as definitions.
9622  // By giving them non-strong linkage, out-of-line definitions won't
9623  // cause link errors.
9624  if (Context.isMSStaticDataMemberInlineDefinition(VD))
9625  return GVA_DiscardableODR;
9626 
9627  // Most non-template variables have strong linkage; inline variables are
9628  // linkonce_odr or (occasionally, for compatibility) weak_odr.
9629  GVALinkage StrongLinkage;
9630  switch (Context.getInlineVariableDefinitionKind(VD)) {
9632  StrongLinkage = GVA_StrongExternal;
9633  break;
9636  StrongLinkage = GVA_DiscardableODR;
9637  break;
9639  StrongLinkage = GVA_StrongODR;
9640  break;
9641  }
9642 
9643  switch (VD->getTemplateSpecializationKind()) {
9644  case TSK_Undeclared:
9645  return StrongLinkage;
9646 
9648  return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
9649  VD->isStaticDataMember()
9650  ? GVA_StrongODR
9651  : StrongLinkage;
9652 
9654  return GVA_StrongODR;
9655 
9657  return GVA_AvailableExternally;
9658 
9660  return GVA_DiscardableODR;
9661  }
9662 
9663  llvm_unreachable("Invalid Linkage!");
9664 }
9665 
9669  basicGVALinkageForVariable(*this, VD)));
9670 }
9671 
9672 bool ASTContext::DeclMustBeEmitted(const Decl *D) {
9673  if (const auto *VD = dyn_cast<VarDecl>(D)) {
9674  if (!VD->isFileVarDecl())
9675  return false;
9676  // Global named register variables (GNU extension) are never emitted.
9677  if (VD->getStorageClass() == SC_Register)
9678  return false;
9679  if (VD->getDescribedVarTemplate() ||
9680  isa<VarTemplatePartialSpecializationDecl>(VD))
9681  return false;
9682  } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
9683  // We never need to emit an uninstantiated function template.
9684  if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
9685  return false;
9686  } else if (isa<PragmaCommentDecl>(D))
9687  return true;
9688  else if (isa<OMPThreadPrivateDecl>(D))
9689  return true;
9690  else if (isa<PragmaDetectMismatchDecl>(D))
9691  return true;
9692  else if (isa<OMPThreadPrivateDecl>(D))
9693  return !D->getDeclContext()->isDependentContext();
9694  else if (isa<OMPDeclareReductionDecl>(D))
9695  return !D->getDeclContext()->isDependentContext();
9696  else if (isa<ImportDecl>(D))
9697  return true;
9698  else
9699  return false;
9700 
9701  if (D->isFromASTFile() && !LangOpts.BuildingPCHWithObjectFile) {
9702  assert(getExternalSource() && "It's from an AST file; must have a source.");
9703  // On Windows, PCH files are built together with an object file. If this
9704  // declaration comes from such a PCH and DeclMustBeEmitted would return
9705  // true, it would have returned true and the decl would have been emitted
9706  // into that object file, so it doesn't need to be emitted here.
9707  // Note that decls are still emitted if they're referenced, as usual;
9708  // DeclMustBeEmitted is used to decide whether a decl must be emitted even
9709  // if it's not referenced.
9710  //
9711  // Explicit template instantiation definitions are tricky. If there was an
9712  // explicit template instantiation decl in the PCH before, it will look like
9713  // the definition comes from there, even if that was just the declaration.
9714  // (Explicit instantiation defs of variable templates always get emitted.)
9715  bool IsExpInstDef =
9716  isa<FunctionDecl>(D) &&
9717  cast<FunctionDecl>(D)->getTemplateSpecializationKind() ==
9719 
9720  if (getExternalSource()->DeclIsFromPCHWithObjectFile(D) && !IsExpInstDef)
9721  return false;
9722  }
9723 
9724  // If this is a member of a class template, we do not need to emit it.
9725  if (D->getDeclContext()->isDependentContext())
9726  return false;
9727 
9728  // Weak references don't produce any output by themselves.
9729  if (D->hasAttr<WeakRefAttr>())
9730  return false;
9731 
9732  // Aliases and used decls are required.
9733  if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
9734  return true;
9735 
9736  if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
9737  // Forward declarations aren't required.
9738  if (!FD->doesThisDeclarationHaveABody())
9739  return FD->doesDeclarationForceExternallyVisibleDefinition();
9740 
9741  // Constructors and destructors are required.
9742  if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
9743  return true;
9744 
9745  // The key function for a class is required. This rule only comes
9746  // into play when inline functions can be key functions, though.
9747  if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
9748  if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
9749  const CXXRecordDecl *RD = MD->getParent();
9750  if (MD->isOutOfLine() && RD->isDynamicClass()) {
9751  const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
9752  if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
9753  return true;
9754  }
9755  }
9756  }
9757 
9759 
9760  // static, static inline, always_inline, and extern inline functions can
9761  // always be deferred. Normal inline functions can be deferred in C99/C++.
9762  // Implicit template instantiations can also be deferred in C++.
9763  return !isDiscardableGVALinkage(Linkage);
9764  }
9765 
9766  const auto *VD = cast<VarDecl>(D);
9767  assert(VD->isFileVarDecl() && "Expected file scoped var");
9768 
9769  if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
9771  return false;
9772 
9773  // Variables that can be needed in other TUs are required.
9774  auto Linkage = GetGVALinkageForVariable(VD);
9776  return true;
9777 
9778  // We never need to emit a variable that is available in another TU.
9780  return false;
9781 
9782  // Variables that have destruction with side-effects are required.
9783  if (VD->getType().isDestructedType())
9784  return true;
9785 
9786  // Variables that have initialization with side-effects are required.
9787  if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
9788  // We can get a value-dependent initializer during error recovery.
9789  (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
9790  return true;
9791 
9792  // Likewise, variables with tuple-like bindings are required if their
9793  // bindings have side-effects.
9794  if (const auto *DD = dyn_cast<DecompositionDecl>(VD))
9795  for (const auto *BD : DD->bindings())
9796  if (const auto *BindingVD = BD->getHoldingVar())
9797  if (DeclMustBeEmitted(BindingVD))
9798  return true;
9799 
9800  // If the decl is marked as `declare target`, it should be emitted.
9802  OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
9803  return *Res != OMPDeclareTargetDeclAttr::MT_Link;
9804 
9805  return false;
9806 }
9807 
9809  const FunctionDecl *FD,
9810  llvm::function_ref<void(FunctionDecl *)> Pred) const {
9811  assert(FD->isMultiVersion() && "Only valid for multiversioned functions");
9812  llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls;
9813  FD = FD->getCanonicalDecl();
9814  for (auto *CurDecl :
9816  FunctionDecl *CurFD = CurDecl->getAsFunction()->getCanonicalDecl();
9817  if (CurFD && hasSameType(CurFD->getType(), FD->getType()) &&
9818  std::end(SeenDecls) == llvm::find(SeenDecls, CurFD)) {
9819  SeenDecls.insert(CurFD);
9820  Pred(CurFD);
9821  }
9822  }
9823 }
9824 
9826  bool IsCXXMethod) const {
9827  // Pass through to the C++ ABI object
9828  if (IsCXXMethod)
9829  return ABI->getDefaultMethodCallConv(IsVariadic);
9830 
9831  switch (LangOpts.getDefaultCallingConv()) {
9832  case LangOptions::DCC_None:
9833  break;
9835  return CC_C;
9837  if (getTargetInfo().hasFeature("sse2") && !IsVariadic)
9838  return CC_X86FastCall;
9839  break;
9841  if (!IsVariadic)
9842  return CC_X86StdCall;
9843  break;
9845  // __vectorcall cannot be applied to variadic functions.
9846  if (!IsVariadic)
9847  return CC_X86VectorCall;
9848  break;
9850  // __regcall cannot be applied to variadic functions.
9851  if (!IsVariadic)
9852  return CC_X86RegCall;
9853  break;
9854  }
9856 }
9857 
9859  // Pass through to the C++ ABI object
9860  return ABI->isNearlyEmpty(RD);
9861 }
9862 
9864  if (!VTContext.get()) {
9865  if (Target->getCXXABI().isMicrosoft())
9866  VTContext.reset(new MicrosoftVTableContext(*this));
9867  else
9868  VTContext.reset(new ItaniumVTableContext(*this));
9869  }
9870  return VTContext.get();
9871 }
9872 
9874  switch (Target->getCXXABI().getKind()) {
9879  case TargetCXXABI::iOS:
9880  case TargetCXXABI::iOS64:
9882  case TargetCXXABI::WatchOS:
9886  }
9887  llvm_unreachable("Unsupported ABI");
9888 }
9889 
9890 CXXABI::~CXXABI() = default;
9891 
9893  return ASTRecordLayouts.getMemorySize() +
9894  llvm::capacity_in_bytes(ObjCLayouts) +
9895  llvm::capacity_in_bytes(KeyFunctions) +
9896  llvm::capacity_in_bytes(ObjCImpls) +
9897  llvm::capacity_in_bytes(BlockVarCopyInits) +
9898  llvm::capacity_in_bytes(DeclAttrs) +
9899  llvm::capacity_in_bytes(TemplateOrInstantiation) +
9900  llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
9901  llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
9902  llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
9903  llvm::capacity_in_bytes(OverriddenMethods) +
9904  llvm::capacity_in_bytes(Types) +
9905  llvm::capacity_in_bytes(VariableArrayTypes) +
9906  llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
9907 }
9908 
9909 /// getIntTypeForBitwidth -
9910 /// sets integer QualTy according to specified details:
9911 /// bitwidth, signed/unsigned.
9912 /// Returns empty type if there is no appropriate target types.
9914  unsigned Signed) const {
9915  TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
9916  CanQualType QualTy = getFromTargetType(Ty);
9917  if (!QualTy && DestWidth == 128)
9918  return Signed ? Int128Ty : UnsignedInt128Ty;
9919  return QualTy;
9920 }
9921 
9922 /// getRealTypeForBitwidth -
9923 /// sets floating point QualTy according to specified bitwidth.
9924 /// Returns empty type if there is no appropriate target types.
9927  switch (Ty) {
9928  case TargetInfo::Float:
9929  return FloatTy;
9930  case TargetInfo::Double:
9931  return DoubleTy;
9933  return LongDoubleTy;
9934  case TargetInfo::Float128:
9935  return Float128Ty;
9936  case TargetInfo::NoFloat:
9937  return {};
9938  }
9939 
9940  llvm_unreachable("Unhandled TargetInfo::RealType value");
9941 }
9942 
9943 void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
9944  if (Number > 1)
9945  MangleNumbers[ND] = Number;
9946 }
9947 
9948 unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
9949  auto I = MangleNumbers.find(ND);
9950  return I != MangleNumbers.end() ? I->second : 1;
9951 }
9952 
9953 void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
9954  if (Number > 1)
9955  StaticLocalNumbers[VD] = Number;
9956 }
9957 
9958 unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
9959  auto I = StaticLocalNumbers.find(VD);
9960  return I != StaticLocalNumbers.end() ? I->second : 1;
9961 }
9962 
9965  assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
9966  std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
9967  if (!MCtx)
9969  return *MCtx;
9970 }
9971 
9972 std::unique_ptr<MangleNumberingContext>
9974  return ABI->createMangleNumberingContext();
9975 }
9976 
9977 const CXXConstructorDecl *
9979  return ABI->getCopyConstructorForExceptionObject(
9980  cast<CXXRecordDecl>(RD->getFirstDecl()));
9981 }
9982 
9984  CXXConstructorDecl *CD) {
9985  return ABI->addCopyConstructorForExceptionObject(
9986  cast<CXXRecordDecl>(RD->getFirstDecl()),
9987  cast<CXXConstructorDecl>(CD->getFirstDecl()));
9988 }
9989 
9991  TypedefNameDecl *DD) {
9992  return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
9993 }
9994 
9997  return ABI->getTypedefNameForUnnamedTagDecl(TD);
9998 }
9999 
10001  DeclaratorDecl *DD) {
10002  return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
10003 }
10004 
10006  return ABI->getDeclaratorForUnnamedTagDecl(TD);
10007 }
10008 
10009 void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
10010  ParamIndices[D] = index;
10011 }
10012 
10013 unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
10014  ParameterIndexTable::const_iterator I = ParamIndices.find(D);
10015  assert(I != ParamIndices.end() &&
10016  "ParmIndices lacks entry set by ParmVarDecl");
10017  return I->second;
10018 }
10019 
10020 APValue *
10022  bool MayCreate) {
10023  assert(E && E->getStorageDuration() == SD_Static &&
10024  "don't need to cache the computed value for this temporary");
10025  if (MayCreate) {
10026  APValue *&MTVI = MaterializedTemporaryValues[E];
10027  if (!MTVI)
10028  MTVI = new (*this) APValue;
10029  return MTVI;
10030  }
10031 
10032  return MaterializedTemporaryValues.lookup(E);
10033 }
10034 
10036  const llvm::Triple &T = getTargetInfo().getTriple();
10037  if (!T.isOSDarwin())
10038  return false;
10039 
10040  if (!(T.isiOS() && T.isOSVersionLT(7)) &&
10041  !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
10042  return false;
10043 
10044  QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
10045  CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
10046  uint64_t Size = sizeChars.getQuantity();
10047  CharUnits alignChars = getTypeAlignInChars(AtomicTy);
10048  unsigned Align = alignChars.getQuantity();
10049  unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
10050  return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
10051 }
10052 
10054  ASTContext::ParentMapPointers::mapped_type U) {
10055  if (const auto *D = U.dyn_cast<const Decl *>())
10057  if (const auto *S = U.dyn_cast<const Stmt *>())
10059  return *U.get<ast_type_traits::DynTypedNode *>();
10060 }
10061 
10062 namespace {
10063 
10064 /// Template specializations to abstract away from pointers and TypeLocs.
10065 /// @{
10066 template <typename T>
10067 ast_type_traits::DynTypedNode createDynTypedNode(const T &Node) {
10069 }
10070 template <>
10071 ast_type_traits::DynTypedNode createDynTypedNode(const TypeLoc &Node) {
10073 }
10074 template <>
10076 createDynTypedNode(const NestedNameSpecifierLoc &Node) {
10078 }
10079 /// @}
10080 
10081  /// A \c RecursiveASTVisitor that builds a map from nodes to their
10082  /// parents as defined by the \c RecursiveASTVisitor.
10083  ///
10084  /// Note that the relationship described here is purely in terms of AST
10085  /// traversal - there are other relationships (for example declaration context)
10086  /// in the AST that are better modeled by special matchers.
10087  ///
10088  /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
10089  class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
10090  public:
10091  /// Builds and returns the translation unit's parent map.
10092  ///
10093  /// The caller takes ownership of the returned \c ParentMap.
10094  static std::pair<ASTContext::ParentMapPointers *,
10096  buildMap(TranslationUnitDecl &TU) {
10097  ParentMapASTVisitor Visitor(new ASTContext::ParentMapPointers,
10099  Visitor.TraverseDecl(&TU);
10100  return std::make_pair(Visitor.Parents, Visitor.OtherParents);
10101  }
10102 
10103  private:
10104  friend class RecursiveASTVisitor<ParentMapASTVisitor>;
10105 
10106  using VisitorBase = RecursiveASTVisitor<ParentMapASTVisitor>;
10107 
10108  ParentMapASTVisitor(ASTContext::ParentMapPointers *Parents,
10109  ASTContext::ParentMapOtherNodes *OtherParents)
10110  : Parents(Parents), OtherParents(OtherParents) {}
10111 
10112  bool shouldVisitTemplateInstantiations() const {
10113  return true;
10114  }
10115 
10116  bool shouldVisitImplicitCode() const {
10117  return true;
10118  }
10119 
10120  template <typename T, typename MapNodeTy, typename BaseTraverseFn,
10121  typename MapTy>
10122  bool TraverseNode(T Node, MapNodeTy MapNode,
10123  BaseTraverseFn BaseTraverse, MapTy *Parents) {
10124  if (!Node)
10125  return true;
10126  if (ParentStack.size() > 0) {
10127  // FIXME: Currently we add the same parent multiple times, but only
10128  // when no memoization data is available for the type.
10129  // For example when we visit all subexpressions of template
10130  // instantiations; this is suboptimal, but benign: the only way to
10131  // visit those is with hasAncestor / hasParent, and those do not create
10132  // new matches.
10133  // The plan is to enable DynTypedNode to be storable in a map or hash
10134  // map. The main problem there is to implement hash functions /
10135  // comparison operators for all types that DynTypedNode supports that
10136  // do not have pointer identity.
10137  auto &NodeOrVector = (*Parents)[MapNode];
10138  if (NodeOrVector.isNull()) {
10139  if (const auto *D = ParentStack.back().get<Decl>())
10140  NodeOrVector = D;
10141  else if (const auto *S = ParentStack.back().get<Stmt>())
10142  NodeOrVector = S;
10143  else
10144  NodeOrVector =
10145  new ast_type_traits::DynTypedNode(ParentStack.back());
10146  } else {
10147  if (!NodeOrVector.template is<ASTContext::ParentVector *>()) {
10148  auto *Vector = new ASTContext::ParentVector(
10149  1, getSingleDynTypedNodeFromParentMap(NodeOrVector));
10150  delete NodeOrVector
10151  .template dyn_cast<ast_type_traits::DynTypedNode *>();
10152  NodeOrVector = Vector;
10153  }
10154 
10155  auto *Vector =
10156  NodeOrVector.template get<ASTContext::ParentVector *>();
10157  // Skip duplicates for types that have memoization data.
10158  // We must check that the type has memoization data before calling
10159  // std::find() because DynTypedNode::operator== can't compare all
10160  // types.
10161  bool Found = ParentStack.back().getMemoizationData() &&
10162  std::find(Vector->begin(), Vector->end(),
10163  ParentStack.back()) != Vector->end();
10164  if (!Found)
10165  Vector->push_back(ParentStack.back());
10166  }
10167  }
10168  ParentStack.push_back(createDynTypedNode(Node));
10169  bool Result = BaseTraverse();
10170  ParentStack.pop_back();
10171  return Result;
10172  }
10173 
10174  bool TraverseDecl(Decl *DeclNode) {
10175  return TraverseNode(DeclNode, DeclNode,
10176  [&] { return VisitorBase::TraverseDecl(DeclNode); },
10177  Parents);
10178  }
10179 
10180  bool TraverseStmt(Stmt *StmtNode) {
10181  return TraverseNode(StmtNode, StmtNode,
10182  [&] { return VisitorBase::TraverseStmt(StmtNode); },
10183  Parents);
10184  }
10185 
10186  bool TraverseTypeLoc(TypeLoc TypeLocNode) {
10187  return TraverseNode(
10188  TypeLocNode, ast_type_traits::DynTypedNode::create(TypeLocNode),
10189  [&] { return VisitorBase::TraverseTypeLoc(TypeLocNode); },
10190  OtherParents);
10191  }
10192 
10193  bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNSLocNode) {
10194  return TraverseNode(
10195  NNSLocNode, ast_type_traits::DynTypedNode::create(NNSLocNode),
10196  [&] {
10197  return VisitorBase::TraverseNestedNameSpecifierLoc(NNSLocNode);
10198  },
10199  OtherParents);
10200  }
10201 
10202  ASTContext::ParentMapPointers *Parents;
10203  ASTContext::ParentMapOtherNodes *OtherParents;
10205  };
10206 
10207 } // namespace
10208 
10209 template <typename NodeTy, typename MapTy>
10211  const MapTy &Map) {
10212  auto I = Map.find(Node);
10213  if (I == Map.end()) {
10215  }
10216  if (const auto *V =
10217  I->second.template dyn_cast<ASTContext::ParentVector *>()) {
10218  return llvm::makeArrayRef(*V);
10219  }
10220  return getSingleDynTypedNodeFromParentMap(I->second);
10221 }
10222 
10225  if (!PointerParents) {
10226  // We always need to run over the whole translation unit, as
10227  // hasAncestor can escape any subtree.
10228  auto Maps = ParentMapASTVisitor::buildMap(*getTranslationUnitDecl());
10229  PointerParents.reset(Maps.first);
10230  OtherParents.reset(Maps.second);
10231  }
10232  if (Node.getNodeKind().hasPointerIdentity())
10233  return getDynNodeFromMap(Node.getMemoizationData(), *PointerParents);
10234  return getDynNodeFromMap(Node, *OtherParents);
10235 }
10236 
10237 bool
10239  const ObjCMethodDecl *MethodImpl) {
10240  // No point trying to match an unavailable/deprecated mothod.
10241  if (MethodDecl->hasAttr<UnavailableAttr>()
10242  || MethodDecl->hasAttr<DeprecatedAttr>())
10243  return false;
10244  if (MethodDecl->getObjCDeclQualifier() !=
10245  MethodImpl->getObjCDeclQualifier())
10246  return false;
10247  if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
10248  return false;
10249 
10250  if (MethodDecl->param_size() != MethodImpl->param_size())
10251  return false;
10252 
10253  for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
10254  IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
10255  EF = MethodDecl->param_end();
10256  IM != EM && IF != EF; ++IM, ++IF) {
10257  const ParmVarDecl *DeclVar = (*IF);
10258  const ParmVarDecl *ImplVar = (*IM);
10259  if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
10260  return false;
10261  if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
10262  return false;
10263  }
10264 
10265  return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
10266 }
10267 
10269  LangAS AS;
10271  AS = LangAS::Default;
10272  else
10273  AS = QT->getPointeeType().getAddressSpace();
10274 
10275  return getTargetInfo().getNullPointerValue(AS);
10276 }
10277 
10279  if (isTargetAddressSpace(AS))
10280  return toTargetAddressSpace(AS);
10281  else
10282  return (*AddrSpaceMap)[(unsigned)AS];
10283 }
10284 
10286  assert(Ty->isFixedPointType());
10287 
10288  if (Ty->isSaturatedFixedPointType()) return Ty;
10289 
10290  const auto &BT = Ty->getAs<BuiltinType>();
10291  switch (BT->getKind()) {
10292  default:
10293  llvm_unreachable("Not a fixed point type!");
10294  case BuiltinType::ShortAccum:
10295  return SatShortAccumTy;
10296  case BuiltinType::Accum:
10297  return SatAccumTy;
10298  case BuiltinType::LongAccum:
10299  return SatLongAccumTy;
10300  case BuiltinType::UShortAccum:
10301  return SatUnsignedShortAccumTy;
10302  case BuiltinType::UAccum:
10303  return SatUnsignedAccumTy;
10304  case BuiltinType::ULongAccum:
10305  return SatUnsignedLongAccumTy;
10306  case BuiltinType::ShortFract:
10307  return SatShortFractTy;
10308  case BuiltinType::Fract:
10309  return SatFractTy;
10310  case BuiltinType::LongFract:
10311  return SatLongFractTy;
10312  case BuiltinType::UShortFract:
10313  return SatUnsignedShortFractTy;
10314  case BuiltinType::UFract:
10315  return SatUnsignedFractTy;
10316  case BuiltinType::ULongFract:
10317  return SatUnsignedLongFractTy;
10318  }
10319 }
10320 
10321 // Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
10322 // doesn't include ASTContext.h
10323 template
10325  const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
10327  const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
10328  const clang::ASTContext &Ctx, Decl *Value);
10329 
10330 unsigned char ASTContext::getFixedPointScale(QualType Ty) const {
10331  assert(Ty->isFixedPointType());
10332 
10333  const auto *BT = Ty->getAs<BuiltinType>();
10334  const TargetInfo &Target = getTargetInfo();
10335  switch (BT->getKind()) {
10336  default:
10337  llvm_unreachable("Not a fixed point type!");
10338  case BuiltinType::ShortAccum:
10339  case BuiltinType::SatShortAccum:
10340  return Target.getShortAccumScale();
10341  case BuiltinType::Accum:
10342  case BuiltinType::SatAccum:
10343  return Target.getAccumScale();
10344  case BuiltinType::LongAccum:
10345  case BuiltinType::SatLongAccum:
10346  return Target.getLongAccumScale();
10347  case BuiltinType::UShortAccum:
10348  case BuiltinType::SatUShortAccum:
10349  return Target.getUnsignedShortAccumScale();
10350  case BuiltinType::UAccum:
10351  case BuiltinType::SatUAccum:
10352  return Target.getUnsignedAccumScale();
10353  case BuiltinType::ULongAccum:
10354  case BuiltinType::SatULongAccum:
10355  return Target.getUnsignedLongAccumScale();
10356  case BuiltinType::ShortFract:
10357  case BuiltinType::SatShortFract:
10358  return Target.getShortFractScale();
10359  case BuiltinType::Fract:
10360  case BuiltinType::SatFract:
10361  return Target.getFractScale();
10362  case BuiltinType::LongFract:
10363  case BuiltinType::SatLongFract:
10364  return Target.getLongFractScale();
10365  case BuiltinType::UShortFract:
10366  case BuiltinType::SatUShortFract:
10367  return Target.getUnsignedShortFractScale();
10368  case BuiltinType::UFract:
10369  case BuiltinType::SatUFract:
10370  return Target.getUnsignedFractScale();
10371  case BuiltinType::ULongFract:
10372  case BuiltinType::SatULongFract:
10373  return Target.getUnsignedLongFractScale();
10374  }
10375 }
10376 
10377 unsigned char ASTContext::getFixedPointIBits(QualType Ty) const {
10378  assert(Ty->isFixedPointType());
10379 
10380  const auto *BT = Ty->getAs<BuiltinType>();
10381  const TargetInfo &Target = getTargetInfo();
10382  switch (BT->getKind()) {
10383  default:
10384  llvm_unreachable("Not a fixed point type!");
10385  case BuiltinType::ShortAccum:
10386  case BuiltinType::SatShortAccum:
10387  return Target.getShortAccumIBits();
10388  case BuiltinType::Accum:
10389  case BuiltinType::SatAccum:
10390  return Target.getAccumIBits();
10391  case BuiltinType::LongAccum:
10392  case BuiltinType::SatLongAccum:
10393  return Target.getLongAccumIBits();
10394  case BuiltinType::UShortAccum:
10395  case BuiltinType::SatUShortAccum:
10396  return Target.getUnsignedShortAccumIBits();
10397  case BuiltinType::UAccum:
10398  case BuiltinType::SatUAccum:
10399  return Target.getUnsignedAccumIBits();
10400  case BuiltinType::ULongAccum:
10401  case BuiltinType::SatULongAccum:
10402  return Target.getUnsignedLongAccumIBits();
10403  case BuiltinType::ShortFract:
10404  case BuiltinType::SatShortFract:
10405  case BuiltinType::Fract:
10406  case BuiltinType::SatFract:
10407  case BuiltinType::LongFract:
10408  case BuiltinType::SatLongFract:
10409  case BuiltinType::UShortFract:
10410  case BuiltinType::SatUShortFract:
10411  case BuiltinType::UFract:
10412  case BuiltinType::SatUFract:
10413  case BuiltinType::ULongFract:
10414  case BuiltinType::SatULongFract:
10415  return 0;
10416  }
10417 }
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:3967
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:863
static NamespaceDecl * Create(ASTContext &C, DeclContext *DC, bool Inline, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, NamespaceDecl *PrevDecl)
Definition: DeclCXX.cpp:2512
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:1022
TemplateTemplateParmDecl * getParameterPack() const
Retrieve the template template parameter pack being substituted.
Definition: TemplateName.h:135
const ObjCInterfaceType * getInterfaceType() const
If this pointer points to an Objective C @interface type, gets the type for that interface.
Definition: Type.cpp:1544
static void EncodeBitField(const ASTContext *Ctx, std::string &S, QualType T, const FieldDecl *FD)
CanQualType SatUnsignedLongFractTy
Definition: ASTContext.h:1026
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:5065
bool hasDefinition() const
Determine whether this class has been defined.
Definition: DeclObjC.h:1556
The generic AArch64 ABI is also a modified version of the Itanium ABI, but it has fewer divergences t...
Definition: TargetCXXABI.h:84
static ast_type_traits::DynTypedNode getSingleDynTypedNodeFromParentMap(ASTContext::ParentMapPointers::mapped_type U)
Represents a type that was referred to using an elaborated type keyword, e.g., struct S...
Definition: Type.h:4945
ASTMutationListener * Listener
Definition: ASTContext.h:550
IntType getInt64Type() const
Definition: TargetInfo.h:291
unsigned getHalfWidth() const
getHalfWidth/Align/Format - Return the size/align/format of &#39;half&#39;.
Definition: TargetInfo.h:549
QualType withConst() const
Retrieves a version of this type with const applied.
const Type * Ty
The locally-unqualified type.
Definition: Type.h:596
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:92
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:4748
CanQualType LongLongTy
Definition: ASTContext.h:1013
static const Decl * getCanonicalDecl(const Decl *D)
void setImplicit(bool I=true)
Definition: DeclBase.h:555
Represents a function declaration or definition.
Definition: Decl.h:1716
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.
unsigned getFloatWidth() const
getFloatWidth/Align/Format - Return the size/align/format of &#39;float&#39;.
Definition: TargetInfo.h:554
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:6387
CanQualType WIntTy
Definition: ASTContext.h:1009
bool isKindOfTypeAsWritten() const
Whether this is a "__kindof" type as written.
Definition: Type.h:5472
unsigned getLongFractAlign() const
Definition: TargetInfo.h:416
CXXABI * CreateMicrosoftCXXABI(ASTContext &Ctx)
const Decl * CommentDecl
Declaration the comment is actually attached to (in the source).
Definition: Comment.h:987
bool isObjCQualifiedIdType() const
True if this is equivalent to &#39;id.
Definition: Type.h:5690
SplitQualType split() const
CanQualType AccumTy
Definition: ASTContext.h:1017
no exception specification
unsigned char getFixedPointIBits(QualType Ty) const
CanQualType OCLQueueTy
Definition: ASTContext.h:1042
QualType getObjCIdType() const
Represents the Objective-CC id type.
Definition: ASTContext.h:1834
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:68
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:2393
ArrayRef< QualType > getTypeArgsAsWritten() const
Retrieve the type arguments of this object type as they were written.
Definition: Type.h:5466
CanQualType LongDoubleComplexTy
Definition: ASTContext.h:1030
void * getAsVoidPointer() const
Retrieve the template name as a void pointer.
Definition: TemplateName.h:310
QualType mergeFunctionTypes(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false)
QualType getPointeeType() const
Definition: Type.h:2406
CanQualType VoidPtrTy
Definition: ASTContext.h:1032
Represents the dependent type named by a dependently-scoped typename using declaration, e.g.
Definition: Type.h:3886
A (possibly-)qualified type.
Definition: Type.h:655
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:71
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:6121
Static storage duration.
Definition: Specifiers.h:280
QualType areCommonBaseCompatible(const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT)
OverloadedOperatorKind getOperator() const
Return the overloaded operator to which this template name refers.
Definition: TemplateName.h:494
bool isArrayType() const
Definition: Type.h:6162
bool getNoCfCheck() const
Definition: Type.h:3285
bool isNull() const
Definition: CanonicalType.h:98
bool isMemberPointerType() const
Definition: Type.h:6144
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:381
unsigned char getFixedPointScale(QualType Ty) const
ASTContext(LangOptions &LOpts, SourceManager &SM, IdentifierTable &idents, SelectorTable &sels, Builtin::Context &builtins)
Definition: ASTContext.cpp:783
CanQualType UnsignedLongFractTy
Definition: ASTContext.h:1021
QualType getBuiltinVaListType() const
Retrieve the type of the __builtin_va_list type.
Definition: ASTContext.h:1889
unsigned getBoolWidth() const
Return the size of &#39;_Bool&#39; and C++ &#39;bool&#39; for this target, in bits.
Definition: TargetInfo.h:357
unsigned getLongWidth() const
getLongWidth/Align - Return the size of &#39;signed long&#39; and &#39;unsigned long&#39; for this target...
Definition: TargetInfo.h:380
static unsigned NumImplicitMoveAssignmentOperatorsDeclared
The number of implicitly-declared move assignment operators for which declarations were built...
Definition: ASTContext.h:2799
ObjCIvarDecl * getPropertyIvarDecl() const
Definition: DeclObjC.h:2849
CanQualType FractTy
Definition: ASTContext.h:1020
static MicrosoftMangleContext * create(ASTContext &Context, DiagnosticsEngine &Diags)
void Profile(llvm::FoldingSetNodeID &ID) const
Definition: Type.h:1363
CanQualType Char32Ty
Definition: ASTContext.h:1012
QualType getPointerDiffType() const
Return the unique type for "ptrdiff_t" (C99 7.17) defined in <stddef.h>.
static unsigned NumImplicitDefaultConstructors
The number of implicitly-declared default constructors.
Definition: ASTContext.h:2767
unsigned getMaxVectorAlign() const
Return the maximum vector alignment supported for the given target.
Definition: TargetInfo.h:611
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:1391
Stmt - This represents one statement.
Definition: Stmt.h:66
void setLAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:1637
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:2274
Internal representation of canonical, dependent __underlying_type(type) types.
Definition: Type.h:4095
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:3211
unsigned getLargeArrayAlign() const
Definition: TargetInfo.h:589
bool CommentsLoaded
True if comments are already loaded from ExternalASTSource.
Definition: ASTContext.h:716
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee...
Definition: Type.cpp:497
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:5206
unsigned getFloat128Align() const
Definition: TargetInfo.h:574
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:941
bool hasExtParameterInfos() const
Is there any interesting extra information for any of the parameters of this function type...
Definition: Type.h:3827
__builtin_va_list as defined by the PNaCl ABI: http://www.chromium.org/nativeclient/pnacl/bitcode-abi...
Definition: TargetInfo.h:194
CharUnits getBaseClassOffset(const CXXRecordDecl *Base) const
getBaseClassOffset - Get the offset, in chars, for the given base class.
Definition: RecordLayout.h:233
bool isRealFloatingType() const
Floating point categories.
Definition: Type.cpp:1941
unsigned overridden_methods_size(const CXXMethodDecl *Method) const
Represents the declaration of a typedef-name via the &#39;typedef&#39; type specifier.
Definition: Decl.h:2974
C Language Family Type Representation.
unsigned getLongAlign() const
Definition: TargetInfo.h:381
Defines the SourceManager interface.
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3073
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...
static unsigned NumImplicitMoveAssignmentOperators
The number of implicitly-declared move assignment operators.
Definition: ASTContext.h:2795
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:5020
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:87
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.cpp:3294
bool isRecordType() const
Definition: Type.h:6186
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:1030
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:713
const T * get() const
Retrieve the stored node as type T.
static int CmpProtocolNames(ObjCProtocolDecl *const *LHS, ObjCProtocolDecl *const *RHS)
CmpProtocolNames - Comparison predicate for sorting protocols alphabetically.
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:1918
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:2853
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
bool isVariadic() const
Definition: Type.h:3774
EnumDecl * getPreviousDecl()
Definition: Decl.h:3374
CanQualType ObjCBuiltinSelTy
Definition: ASTContext.h:1036
bool isDiscardableGVALinkage(GVALinkage L)
Definition: Linkage.h:82
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:1479
Represents a C++11 auto or C++14 decltype(auto) type.
Definition: Type.h:4562
Kind getKind() const
Definition: TargetCXXABI.h:132
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition: Decl.cpp:3727
A class providing a concrete implementation of ObjCObjectType, so as to not increase the footprint of...
Definition: Type.h:5508
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx)
Definition: Type.cpp:3057
unsigned getDefaultAlignForAttributeAligned() const
Return the default alignment for attribute((aligned)) on this target, to be used if no alignment valu...
Definition: TargetInfo.h:518
ObjCTypeParamList * getTypeParamList() const
Retrieve the type parameters of this class.
Definition: DeclObjC.cpp:301
Defines types useful for describing an Objective-C runtime.
unsigned getFractWidth() const
getFractWidth/Align - Return the size of &#39;signed _Fract&#39; and &#39;unsigned _Fract&#39; for this target...
Definition: TargetInfo.h:410
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:1035
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined...
Definition: Decl.h:2718
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:1428
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:1023
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:1751
static bool areSortedAndUniqued(ArrayRef< ObjCProtocolDecl *> Protocols)
CanQual< T > getUnqualifiedType() const
Retrieve the unqualified form of this type.
CanQualType LongTy
Definition: ASTContext.h:1013
DiagnosticsEngine & getDiagnostics() const
virtual LangAS getOpenCLTypeAddrSpace(OpenCLTypeKind TK) const
Get address space for OpenCL type.
Definition: TargetInfo.cpp:404
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:2668
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:64
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:2351
Represent a C++ namespace.
Definition: Decl.h:514
const ObjCObjectPointerType * getAsObjCInterfacePointerType() const
Definition: Type.cpp:1604
static ExprValueKind getValueKindForType(QualType T)
getValueKindForType - Given a formal return or parameter type, give its value kind.
Definition: Expr.h:395
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:2515
virtual void completeDefinition()
Note that the definition of this type is now complete.
Definition: Decl.cpp:4049
bool isZero() const
isZero - Test whether the quantity equals zero.
Definition: CharUnits.h:116
QualType withConst() const
Definition: Type.h:827
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:679
QualType adjustStringLiteralBaseType(QualType StrLTy) const
A container of type source information.
Definition: Decl.h:86
llvm::DenseMap< Stmt *, Stmt * > MapTy
Definition: ParentMap.cpp:23
CharUnits getAlignment() const
getAlignment - Get the record alignment in characters.
Definition: RecordLayout.h:177
static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod, SmallVectorImpl< const NamedDecl *> &Redeclared)
Definition: ASTContext.cpp:452
FieldDecl * getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field)
__builtin_va_list as defined by the x86-64 ABI: http://refspecs.linuxbase.org/elf/x86_64-abi-0.21.pdf
Definition: TargetInfo.h:203
const Expr * getRequiresClause() const
Get the constraint-expression from the associated requires-clause (if any)
Definition: DeclTemplate.h:440
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:392
unsigned getCharWidth() const
Definition: TargetInfo.h:362
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2477
Represents a prvalue temporary that is written into memory so that a reference can bind to it...
Definition: ExprCXX.h:4150
CanQualType WideCharTy
Definition: ASTContext.h:1008
const DeclContext * getParentFunctionOrMethod() const
If this decl is defined inside a function/method/block it returns the corresponding DeclContext...
Definition: DeclBase.cpp:254
A template template parameter that has been substituted for some other template name.
Definition: TemplateName.h:206
CanQualType HalfTy
Definition: ASTContext.h:1028
ExtParameterInfo withIsNoEscape(bool NoEscape) const
Definition: Type.h:3503
QualType getElementType() const
Definition: Type.h:2703
unsigned getLargeArrayMinWidth() const
Definition: TargetInfo.h:588
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition: Type.cpp:532
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:2073
const IdentifierInfo * getIdentifier() const
Returns the identifier to which this template name refers.
Definition: TemplateName.h:484
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:1888
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:751
Represents a variable declaration or definition.
Definition: Decl.h:814
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:349
QualType getReturnType() const
Definition: Decl.h:2271
LangAS getLangASFromTargetAS(unsigned TargetAS)
Definition: AddressSpaces.h:67
void initialize(ASTContext &Context, SourceLocation Loc) const
Initializes this to state that every location in this type is the given location. ...
Definition: TypeLoc.h:191
RecordDecl * getPreviousDecl()
Definition: Decl.h:3646
llvm::SmallVector< ast_type_traits::DynTypedNode, 2 > ParentVector
Contains parents of a node.
Definition: ASTContext.h:553
unsigned getNumParams() const
Definition: Type.h:3668
bool isEnumeralType() const
Definition: Type.h:6190
bool isFixed() const
Returns true if this is an Objective-C, C++11, or Microsoft-style enumeration with a fixed underlying...
Definition: Decl.h:3504
NamedDecl *const * const_iterator
Iterates through the template parameters in this list.
Definition: DeclTemplate.h:117
const T * getAs() const
Member-template getAs<specific type>&#39;.
Definition: Type.h:6526
void setClassScopeSpecializationPattern(FunctionDecl *FD, FunctionDecl *Pattern)
CanQualType Float128Ty
Definition: ASTContext.h:1016
virtual void CompleteRedeclChain(const Decl *D)
Gives the external AST source an opportunity to complete the redeclaration chain for a declaration...
MangleContext * createMangleContext()
unsigned getCharAlign() const
Definition: TargetInfo.h:363
Represents an empty template argument, e.g., one that has not been deduced.
Definition: TemplateBase.h:57
Extra information about a function prototype.
Definition: Type.h:3551
CanQualType ShortAccumTy
Definition: ASTContext.h:1017
unsigned getWCharAlign() const
Definition: TargetInfo.h:536
Declaration context for names declared as extern "C" in C++.
Definition: Decl.h:221
const llvm::fltSemantics & getHalfFormat() const
Definition: TargetInfo.h:551
LangAS
Defines the address space values used by the address space qualifier of QualType. ...
Definition: AddressSpaces.h:26
Represents a C++17 deduced template specialization type.
Definition: Type.h:4598
__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:190
QualifiedTemplateName * getAsQualifiedTemplateName() const
Retrieve the underlying qualified template name structure, if any.
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:139
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:3794
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:1657
void setRaw(const RawComment *RC)
Definition: ASTContext.h:755
bool isInvalidDecl() const
Definition: DeclBase.h:549
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:68
static ObjCPropertyDecl * findPropertyDecl(const DeclContext *DC, const IdentifierInfo *propertyID, ObjCPropertyQueryKind queryKind)
Lookup a property by name in the specified DeclContext.
Definition: DeclObjC.cpp:170
TemplateName getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param, TemplateName replacement) const
Describes how types, statements, expressions, and declarations should be printed. ...
Definition: PrettyPrinter.h:38
CanQualType ShortFractTy
Definition: ASTContext.h:1020
SpecifierKind getKind() const
Determine what kind of nested name specifier is stored.
protocol_range protocols() const
Definition: DeclObjC.h:2150
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:1535
Represents the result of substituting a type for a template type parameter.
Definition: Type.h:4417
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:2427
Linkage
Describes the different kinds of linkage (C++ [basic.link], C99 6.2.2) that an entity may have...
Definition: Linkage.h:24
Defines the clang::Expr interface and subclasses for C++ expressions.
unsigned getAccumAlign() const
Definition: TargetInfo.h:396
QualType getIntegralType() const
Retrieve the type of the integral value.
Definition: TemplateBase.h:315
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:154
FieldDecl * getSourceBitField()
If this expression refers to a bit-field, retrieve the declaration of that bit-field.
Definition: Expr.cpp:3525
PipeType - OpenCL20.
Definition: Type.h:5819
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:2921
Qualifiers getQualifiers() const
Retrieve all qualifiers.
SubstTemplateTemplateParmStorage * getAsSubstTemplateTemplateParm() const
Retrieve the substituted template template parameter, if known.
CanQualType OCLSamplerTy
Definition: ASTContext.h:1041
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:3570
unsigned getLongDoubleAlign() const
Definition: TargetInfo.h:566
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:1331
uint64_t getPointerWidth(unsigned AddrSpace) const
Return the width of pointers on this target, for the specified address space.
Definition: TargetInfo.h:340
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:3552
bool isComplete() const
Returns true if this can be considered a complete type.
Definition: Decl.h:3511
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:1010
bool isObjCQualifiedClass() const
Definition: Type.h:5438
This table allows us to fully hide how we implement multi-keyword caching.
unsigned getIntAlign() const
Definition: TargetInfo.h:376
unsigned getRegParm() const
Definition: Type.h:3288
IntType getUnsignedPtrDiffType(unsigned AddrSpace) const
Definition: TargetInfo.h:280
Represents a class type in Objective C.
Definition: Type.h:5355
static RecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, RecordDecl *PrevDecl=nullptr)
Definition: Decl.cpp:4002
QualType getPointeeType() const
Definition: Type.h:2510
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:150
static unsigned NumImplicitMoveConstructorsDeclared
The number of implicitly-declared move constructors for which declarations were built.
Definition: ASTContext.h:2785
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:422
QualType getObjCSuperType() const
Returns the C struct type for objc_super.
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:3675
ArrayRef< ExtParameterInfo > getExtParameterInfos() const
Definition: Type.h:3828
const ParmVarDecl *const * param_const_iterator
Definition: DeclObjC.h:383
NamespaceDecl * getNamespace()
Retrieve the namespace declaration aliased by this directive.
Definition: DeclCXX.h:3101
The template argument is an integral value stored in an llvm::APSInt that was provided for an integra...
Definition: TemplateBase.h:72
void setObjCConstantStringInterface(ObjCInterfaceDecl *Decl)
void setArgLocInfo(unsigned i, TemplateArgumentLocInfo AI)
Definition: TypeLoc.h:1653
void setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, FieldDecl *Tmpl)
Missing a type from <ucontext.h>
Definition: ASTContext.h:1995
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:1021
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition: Decl.h:3776
unsigned getChar32Width() const
getChar32Width/Align - Return the size of &#39;char32_t&#39; for this target, in bits.
Definition: TargetInfo.h:545
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:1791
field_range fields() const
Definition: Decl.h:3786
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:913
bool isObjCIdType() const
Definition: Type.h:6239
The generic Mips ABI is a modified version of the Itanium ABI.
Definition: TargetCXXABI.h:90
Represents a member of a struct/union/class.
Definition: Decl.h:2534
const Type * getAsType() const
Retrieve the type stored in this nested name specifier.
bool isCanonicalUnqualified() const
Determines if this type would be canonical if it had no further qualification.
Definition: Type.h:1717
DynTypedNodeList getParents(const NodeT &Node)
Returns the parents of the given node.
Definition: ASTContext.h:637
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:91
void setVisibleDespiteOwningModule()
Set that this declaration is globally visible, even if it came from a module that is not visible...
Definition: DeclBase.h:780
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:2652
const ObjCObjectPointerType * getAsObjCQualifiedIdType() const
Definition: Type.cpp:1576
void addLazyModuleInitializers(Module *M, ArrayRef< uint32_t > IDs)
Definition: ASTContext.cpp:994
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:3791
CanQualType LongAccumTy
Definition: ASTContext.h:1017
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:2126
CanQualType OCLEventTy
Definition: ASTContext.h:1041
Optional< unsigned > getNumTemplateExpansions() const
Retrieve the number of expansions that a template template argument expansion will produce...
Interesting information about a specific parameter that can&#39;t simply be reflected in parameter&#39;s type...
Definition: Type.h:3453
CharUnits getTypeUnadjustedAlignInChars(QualType T) const
getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a type, in characters, before alignment adjustments.
The iterator over UnresolvedSets.
Definition: UnresolvedSet.h:32
Represents the result of substituting a set of types for a template type parameter pack...
Definition: Type.h:4473
IntType getSizeType() const
Definition: TargetInfo.h:258
Container for either a single DynTypedNode or for an ArrayRef to DynTypedNode.
Definition: ASTContext.h:574
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:6307
static CharUnits Zero()
Zero - Construct a CharUnits quantity of zero.
Definition: CharUnits.h:53
qual_iterator qual_begin() const
Definition: Type.h:5256
RawComment * getRawCommentForDeclNoCache(const Decl *D) const
Return the documentation comment attached to a given declaration, without looking into cache...
Definition: ASTContext.cpp:114
CharUnits getVBaseClassOffset(const CXXRecordDecl *VBase) const
getVBaseClassOffset - Get the offset, in chars, for the given base class.
Definition: RecordLayout.h:241
uint64_t lookupFieldBitOffset(const ObjCInterfaceDecl *OID, const ObjCImplementationDecl *ID, const ObjCIvarDecl *Ivar) const
Get the offset of an ObjCIvarDecl in bits.
static TypedefDecl * CreatePowerABIBuiltinVaListDecl(const ASTContext *Context)
CanQualType OCLReserveIDTy
Definition: ASTContext.h:1042
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:50
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:5839
static TypedefDecl * CreateCharPtrNamedVaListDecl(const ASTContext *Context, StringRef Name)
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:6440
QualType getParamTypeForDecl() const
Definition: TemplateBase.h:269
Describes a module or submodule.
Definition: Module.h:65
IdentifierTable & Idents
Definition: ASTContext.h:545
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:5908
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:731
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:2231
CanQualType LongFractTy
Definition: ASTContext.h:1020
bool getProducesResult() const
Definition: Type.h:3283
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:301
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:2966
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:2594
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:2612
IdentifierInfo * getAsIdentifier() const
Retrieve the identifier stored in this nested name specifier.
qual_iterator qual_end() const
Definition: Type.h:5257
A qualified template name, where the qualification is kept to describe the source code as written...
Definition: TemplateName.h:198
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:1410
const LangASMap & getAddressSpaceMap() const
Definition: TargetInfo.h:1169
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:988
static ItaniumMangleContext * create(ASTContext &Context, DiagnosticsEngine &Diags)
QualType getOriginalType() const
Definition: Decl.cpp:2510
void addObjCGCAttr(GC type)
Definition: Type.h:327
static ExternCContextDecl * Create(const ASTContext &C, TranslationUnitDecl *TU)
Definition: Decl.cpp:4247
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:38
Microsoft throw(...) extension.
A convenient class for passing around template argument information.
Definition: TemplateBase.h:552
uint32_t Offset
Definition: CacheTokens.cpp:43
CanQualType SatShortFractTy
Definition: ASTContext.h:1025
ArrayRef< QualType > getTypeArgs() const
Retrieve the type arguments of this object type (semantically).
Definition: Type.cpp:678
QualType getVolatileType(QualType T) const
Return the uniqued reference to the type for a volatile qualified type.
Definition: ASTContext.h:1162
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:5345
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition: Type.cpp:2208
The Microsoft ABI is the ABI used by Microsoft Visual Studio (and compatible compilers).
Definition: TargetCXXABI.h:113
TypedefDecl * getObjCSelDecl() const
Retrieve the typedef corresponding to the predefined &#39;SEL&#39; type in Objective-C.
bool hasAddressSpace() const
Definition: Type.h:368
CanQualType SatUnsignedShortAccumTy
Definition: ASTContext.h:1023
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified...
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:6575
QualType getNullPtrType() const
Retrieve the type for null non-type template argument.
Definition: TemplateBase.h:275
SourceLocation getExpansionLoc(SourceLocation Loc) const
Given a SourceLocation object Loc, return the expansion location referenced by the ID...
PropertyAttributeKind getPropertyAttributes() const
Definition: DeclObjC.h:859
unsigned toTargetAddressSpace(LangAS AS)
Definition: AddressSpaces.h:62
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
Represents a typeof (or typeof) expression (a GCC extension).
Definition: Type.h:3941
const clang::PrintingPolicy & getPrintingPolicy() const
Definition: ASTContext.h:643
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:314
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition: Type.h:1711
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:2406
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:2829
CanQualType PseudoObjectTy
Definition: ASTContext.h:1035
LangAS getAddressSpace() const
Definition: Type.h:369
QualType getExceptionObjectType(QualType T) const
GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const
const Type * getClass() const
Definition: Type.h:2646
CXXMethodVector::const_iterator overridden_cxx_method_iterator
Definition: ASTContext.h:916
bool isReadOnly() const
isReadOnly - Return true iff the property has a setter.
Definition: DeclObjC.h:882
unsigned getShortWidth() const
Return the size of &#39;signed short&#39; and &#39;unsigned short&#39; for this target, in bits.
Definition: TargetInfo.h:367
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:4990
void getObjCEncodingForPropertyType(QualType T, std::string &S) const
Emit the Objective-C property type encoding for the given type T into S.
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
CanQualType LongDoubleTy
Definition: ASTContext.h:1016
Expr * IgnoreParenCasts() LLVM_READONLY
IgnoreParenCasts - Ignore parentheses and casts.
Definition: Expr.cpp:2544
static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI, const LangOptions &LangOpts)
Definition: ASTContext.cpp:770
Expr * getSizeExpr() const
Definition: Type.h:2847
static TemplateArgument CreatePackCopy(ASTContext &Context, ArrayRef< TemplateArgument > Args)
Create a new template argument pack by copying the given set of template arguments.
unsigned getChar16Align() const
Definition: TargetInfo.h:541
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:5889
unsigned Align
Definition: ASTContext.h:140
unsigned getBitWidthValue(const ASTContext &Ctx) const
Definition: Decl.cpp:3717
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition: DeclBase.h:1161
bool AlignIsRequired
Definition: ASTContext.h:141
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:3181
unsigned getFractAlign() const
Definition: TargetInfo.h:411
Defines the Linkage enumeration and various utility functions.
DiagnosticsEngine & getDiagnostics() const
Represents an Objective-C protocol declaration.
Definition: DeclObjC.h:2085
static unsigned NumImplicitDefaultConstructorsDeclared
The number of implicitly-declared default constructors for which declarations were built...
Definition: ASTContext.h:2771
TemplateTemplateParmDecl * getParameter() const
Definition: TemplateName.h:338
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:167
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:700
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:3262
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:2081
Represents an ObjC class declaration.
Definition: DeclObjC.h:1193
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:411
QualType getReturnType() const
Definition: DeclObjC.h:363
unsigned getLongLongAlign() const
Definition: TargetInfo.h:386
ObjCInterfaceDecl * getInterface() const
Gets the interface declaration for this object type, if the base type really is an interface...
Definition: Type.h:5590
bool getNoReturn() const
Definition: Type.h:3282
bool isKindOfType() const
Whether this is a "__kindof" type.
Definition: Type.h:5701
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
Definition: CanonicalType.h:84
bool isParameterPack() const
Whether this template template parameter is a template parameter pack.
SplitQualType getSplitDesugaredType() const
Definition: Type.h:959
The iOS ABI is a partial implementation of the ARM ABI.
Definition: TargetCXXABI.h:63
IntrusiveRefCntPtr< ExternalASTSource > ExternalSource
Definition: ASTContext.h:549
CanQualType UnsignedCharTy
Definition: ASTContext.h:1014
Expr * getSizeExpr() const
Definition: Type.h:2904
bool getNoCallerSavedRegs() const
Definition: Type.h:3284
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:5263
llvm::iterator_range< overridden_cxx_method_iterator > overridden_method_range
Definition: ASTContext.h:926
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:2984
This object can be modified without requiring retains or releases.
Definition: Type.h:175
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1545
void Profile(llvm::FoldingSetNodeID &ID)
Definition: TemplateName.h:500
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:3397
CanQualType Float128ComplexTy
Definition: ASTContext.h:1031
unsigned getTypeQuals() const
Definition: Type.h:3362
ObjCPropertyImplDecl - Represents implementation declaration of a property in a class or category imp...
Definition: DeclObjC.h:2780
Expr * getAddrSpaceExpr() const
Definition: Type.h:2955
NodeId Parent
Definition: ASTDiff.cpp:192
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:5053
QualType getBlockDescriptorExtendedType() const
Gets the struct used to keep track of the extended descriptor for pointer to blocks.
bool hasAttr() const
Definition: DeclBase.h:538
QualType getBaseType() const
Gets the base type of this object type.
Definition: Type.h:5418
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
unsigned getMinGlobalAlign() const
getMinGlobalAlign - Return the minimum alignment of a global variable, unless its alignment is explic...
Definition: TargetInfo.h:524
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:2381
bool isPromotableIntegerType() const
More type predicates useful for type checking/promotion.
Definition: Type.cpp:2458
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1627
Represents a prototype with parameter type info, e.g.
Definition: Type.h:3432
The generic ARM ABI is a modified version of the Itanium ABI proposed by ARM for use on ARM-based pla...
Definition: TargetCXXABI.h:52
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.
const llvm::fltSemantics & getDoubleFormat() const
Definition: TargetInfo.h:561
bool isComplexType() const
isComplexType() does not include complex integers (a GCC extension).
Definition: Type.cpp:473
static unsigned NumImplicitCopyConstructors
The number of implicitly-declared copy constructors.
Definition: ASTContext.h:2774
Represents a ValueDecl that came out of a declarator.
Definition: Decl.h:689
qual_range quals() const
Definition: Type.h:5255
A dependent template name that has not been resolved to a template (or set of templates).
Definition: TemplateName.h:202
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:548
comments::FullComment * cloneFullComment(comments::FullComment *FC, const Decl *D) const
Definition: ASTContext.cpp:469
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:2674
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition: Type.h:5964
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:179
QualType getAutoRRefDeductType() const
C++11 deduction pattern for &#39;auto &&&#39; type.
void setCFConstantStringType(QualType T)
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location, which defaults to the empty location.
ValueDecl * getAsDecl() const
Retrieve the declaration for a declaration non-type template argument.
Definition: TemplateBase.h:264
bool isSaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169...
Definition: Type.h:6395
CanQualType UnsignedAccumTy
Definition: ASTContext.h:1019
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3412
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...
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
Definition: RecordLayout.h:39
const llvm::fltSemantics & getLongDoubleFormat() const
Definition: TargetInfo.h:567
typedef void* __builtin_va_list;
Definition: TargetInfo.h:186
bool hasPointerIdentity() const
Check if the given ASTNodeKind identifies a type that offers pointer identity.
CanQualType UnsignedShortFractTy
Definition: ASTContext.h:1021
Exposes information about the current target.
Definition: TargetInfo.h:54
Represents an array type in C++ whose size is a value-dependent expression.
Definition: Type.h:2882
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:192
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:432
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:2286
bool isNoReturn(unsigned ID) const
Return true if we know this builtin never returns.
Definition: Builtins.h:117
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition: DeclBase.h:1359
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:119
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.
Pepresents a block literal declaration, which is like an unnamed FunctionDecl.
Definition: Decl.h:3860
unsigned getShortFractAlign() const
Definition: TargetInfo.h:406
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:2206
Expr - This represents one expression.
Definition: Expr.h:106
Defines the clang::LangOptions interface.
SourceLocation End
IntType getSignedSizeType() const
Definition: TargetInfo.h:259
void setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst, UsingShadowDecl *Pattern)
known_extensions_range known_extensions() const
Definition: DeclObjC.h:1782
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
Definition: Type.h:4884
bool isPositive() const
isPositive - Test whether the quantity is greater than zero.
Definition: CharUnits.h:122
Selector getSetterName() const
Definition: DeclObjC.h:933
QualType getucontext_tType() const
Retrieve the C ucontext_t type.
Definition: ASTContext.h:1763
void addTypedefNameForUnnamedTagDecl(TagDecl *TD, TypedefNameDecl *TND)
static const LangASMap * getAddressSpaceMap(const TargetInfo &T, const LangOptions &LOpts)
Definition: ASTContext.cpp:748
static bool compare(const PathDiagnostic &X, const PathDiagnostic &Y)
unsigned getAsOpaqueValue() const
Definition: Type.h:267
void ResetObjCLayout(const ObjCContainerDecl *CD)
int Id
Definition: ASTDiff.cpp:191
static Kind getNullabilityAttrKind(NullabilityKind kind)
Retrieve the attribute kind corresponding to the given nullability kind.
Definition: Type.h:4295
static std::pair< CharUnits, CharUnits > getConstantArrayInfoInChars(const ASTContext &Context, const ConstantArrayType *CAT)
getConstantArrayInfoInChars - Performing the computation in CharUnits instead of in bits prevents ove...
unsigned getIntWidth() const
getIntWidth/Align - Return the size of &#39;signed int&#39; and &#39;unsigned int&#39; for this target, in bits.
Definition: TargetInfo.h:375
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:4039
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:3286
bool isObjCBuiltinType() const
Definition: Type.h:6257
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:6589
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:4866
The template argument is a null pointer or null pointer to member that was provided for a non-type te...
Definition: TemplateBase.h:68
bool isNearlyEmpty(const CXXRecordDecl *RD) const
bool isObjCRetainableType() const
Definition: Type.cpp:3938
Inits[]
Definition: OpenMPClause.h:145
QualType getTypeOfExprType(Expr *e) const
GCC extension.
unsigned getShortAccumWidth() const
getShortAccumWidth/Align - Return the size of &#39;signed short _Accum&#39; and &#39;unsigned short _Accum&#39; for t...
Definition: TargetInfo.h:390
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:4320
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition: Expr.h:5051
Qualifiers::GC getObjCGCAttr() const
Returns gc attribute of this type.
Definition: Type.h:6010
QualType getParenType(QualType NamedType) const
CanQualType OMPArraySectionTy
Definition: ASTContext.h:1043
static TypedefDecl * CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context)
const Decl * getDecl() const LLVM_READONLY
Definition: Comment.h:1123
static unsigned NumImplicitMoveConstructors
The number of implicitly-declared move constructors.
Definition: ASTContext.h:2781
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:554
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:6365
unsigned getFastQualifiers() const
Definition: Type.h:403
bool canBeRedeclared(unsigned ID) const
Returns true if this is a builtin that can be redeclared.
Definition: Builtins.cpp:159
unsigned getAccumWidth() const
getAccumWidth/Align - Return the size of &#39;signed _Accum&#39; and &#39;unsigned _Accum&#39; for this target...
Definition: TargetInfo.h:395
ObjCLifetime getObjCLifetime() const
Definition: Type.h:343
void removeFastQualifiers(unsigned mask)
Definition: Type.h:408
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
bool isObjCClassType() const
Definition: Type.h:6245
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:2463
DeclContext * getDeclContext()
Definition: DeclBase.h:428
A structure for storing the information associated with a substituted template template parameter...
Definition: TemplateName.h:325
bool isObjCIdType() const
True if this is equivalent to the &#39;id&#39; type, i.e.
Definition: Type.h:5673
ObjCInterfaceDecl * getSuperClass() const
Definition: DeclObjC.cpp:331
SourceLocation Begin
UsingShadowDecl * getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst)
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:4045
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition: CharUnits.h:63
CanQualType ShortTy
Definition: ASTContext.h:1013
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:137
ArrayRef< TemplateArgument > asArray() const
Produce this as an array ref.
Definition: DeclTemplate.h:264
TypedefDecl * getInt128Decl() const
Retrieve the declaration for the 128-bit signed integer type.
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
bool isTemplateParameterPack() const
isTemplateParameter - Determines whether this declaration is a template parameter pack...
Definition: DeclBase.cpp:201
Represents a C++ template name within the type system.
Definition: TemplateName.h:178
Represents the type decltype(expr) (C++11).
Definition: Type.h:4011
static TypedefDecl * CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context)
unsigned getLongAccumWidth() const
getLongAccumWidth/Align - Return the size of &#39;signed long _Accum&#39; and &#39;unsigned long _Accum&#39; for this...
Definition: TargetInfo.h:400
QualType getFILEType() const
Retrieve the C FILE type.
Definition: ASTContext.h:1727
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:481
int Depth
Definition: ASTDiff.cpp:191
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:1010
CanQualType UnsignedInt128Ty
Definition: ASTContext.h:1015
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition: Expr.h:709
A std::pair-like structure for storing a qualified type split into its local qualifiers and its local...
Definition: Type.h:594
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:1848
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3128
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
QualType getType() const
Definition: Expr.h:128
A unary type transform, which is a type constructed from another.
Definition: Type.h:4054
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:165
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...
Qualifiers Quals
The local qualifiers.
Definition: Type.h:599
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:1343
StorageDuration getStorageDuration() const
Retrieve the storage duration for the materialized temporary.
Definition: ExprCXX.h:4194
void setAddressSpace(LangAS space)
Definition: Type.h:389
unsigned getShortAlign() const
Return the alignment of &#39;signed short&#39; and &#39;unsigned short&#39; for this target.
Definition: TargetInfo.h:371
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:454
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:1365
Represents a GCC generic vector type.
Definition: Type.h:3024
struct CXXOpName CXXOperatorName
An lvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:2576
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:1040
CanQualType SatLongAccumTy
Definition: ASTContext.h:1022
Common base class for placeholders for types that get replaced by placeholder type deduction: C++11 a...
Definition: Type.h:4522
Implements C++ ABI-specific semantic analysis functions.
Definition: CXXABI.h:30
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition: Type.h:6484
unsigned getParameterIndex(const ParmVarDecl *D) const
Used by ParmVarDecl to retrieve on the side the index of the parameter when it exceeds the size of th...
NamedDecl * getInstantiatedFromUsingDecl(NamedDecl *Inst)
If the given using decl Inst is an instantiation of a (possibly unresolved) using decl from a templat...
void deduplicateMergedDefinitonsFor(NamedDecl *ND)
Clean up the merged definition list.
Definition: ASTContext.cpp:938
void CollectInheritedProtocols(const Decl *CDecl, llvm::SmallPtrSet< ObjCProtocolDecl *, 8 > &Protocols)
CollectInheritedProtocols - Collect all protocols in current class and those inherited by it...
unsigned getDoubleAlign() const
Definition: TargetInfo.h:560
Selector getSelector() const
Definition: DeclObjC.h:361
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:1381
The result type of a method or function.
This template specialization was implicitly instantiated from a template.
Definition: Specifiers.h:152
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:720
QualType getDependentSizedExtVectorType(QualType VectorType, Expr *SizeExpr, SourceLocation AttrLoc) const
void removeCVRQualifiers(unsigned mask)
Definition: Type.h:298
bool useAddressSpaceMapMangling() const
Specify if mangling based on address space map should be used or not for language specific address sp...
Definition: TargetInfo.h:717
QualType getType() const
Definition: DeclObjC.h:848
IntType getUIntMaxType() const
Definition: TargetInfo.h:274
const SourceManager & SM
Definition: Format.cpp:1475
void setOriginalDecl(const Decl *Orig)
Definition: ASTContext.h:763
unsigned getDoubleWidth() const
getDoubleWidth/Align/Format - Return the size/align/format of &#39;double&#39;.
Definition: TargetInfo.h:559
comments::FullComment * parse(const ASTContext &Context, const Preprocessor *PP, const Decl *D) const
Parse the comment, assuming it is attached to decl D.
void setDeclContext(DeclContext *DC)
setDeclContext - Set both the semantic and lexical DeclContext to DC.
Definition: DeclBase.cpp:295
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:236
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:4101
CanQualType SignedCharTy
Definition: ASTContext.h:1013
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:216
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:124
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:6407
QualType getObjCGCQualType(QualType T, Qualifiers::GC gcAttr) const
Return the uniqued reference to the type for an Objective-C gc-qualified type.
virtual bool allowsLargerPreferedTypeAlignment() const
Whether target allows to overalign ABI-specified preferred alignment.
Definition: TargetInfo.h:1247
ExtInfo withNoReturn(bool noReturn) const
Definition: Type.h:3307
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:76
bool isVoidPointerType() const
Definition: Type.cpp:461
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:5948
EnumDecl * getInstantiatedFromMemberEnum() const
Returns the enumeration (declared within the template) from which this enumeration type was instantia...
Definition: Decl.cpp:3960
QualType getAutoType(QualType DeducedType, AutoTypeKeyword Keyword, bool IsDependent) const
C++11 deduced auto type.
SplitQualType split() const
Divides a QualType into its unqualified type and a set of local qualifiers.
Definition: Type.h:5897
unsigned getWCharWidth() const
getWCharWidth/Align - Return the size of &#39;wchar_t&#39; for this target, in bits.
Definition: TargetInfo.h:535
noexcept(expression), evals to &#39;false&#39;
unsigned getLongAccumAlign() const
Definition: TargetInfo.h:401
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:191
SourceLocation getLocStart() const LLVM_READONLY
Definition: DeclBase.h:409
QualType getWideCharType() const
Return the type of wide characters.
Definition: ASTContext.h:1550
IntType getPtrDiffType(unsigned AddrSpace) const
Definition: TargetInfo.h:277
A template template parameter pack that has been substituted for a template template argument pack...
Definition: TemplateName.h:211
bool isComputedNoexcept(ExceptionSpecificationType ESpecType)
CanQualType OverloadTy
Definition: ASTContext.h:1033
There is no lifetime qualification on this type.
Definition: Type.h:171
Compare comments&#39; source locations.
static unsigned NumImplicitDestructorsDeclared
The number of implicitly-declared destructors for which declarations were built.
Definition: ASTContext.h:2806
OverloadedTemplateStorage * getAsOverloadedTemplate() const
Retrieve the underlying, overloaded function template.
void PrintStats() const
Definition: ASTContext.cpp:867
std::string getAsString() const
Derive the full selector name (e.g.
is AltiVec &#39;vector Pixel&#39;
Definition: Type.h:3034
CanQualType BuiltinFnTy
Definition: ASTContext.h:1034
This declaration does not have an attached comment, and we have searched the redeclaration chain...
Definition: ASTContext.h:740
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:546
Assigning into this object requires the old value to be released and the new value to be retained...
Definition: Type.h:182
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:5928
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition: Type.h:6182
not a target-specific vector type
Definition: Type.h:3028
llvm::PointerUnion< VarTemplateDecl *, MemberSpecializationInfo * > TemplateOrSpecializationInfo
A type synonym for the TemplateOrInstantiation mapping.
Definition: ASTContext.h:401
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition: Type.h:3529
QualType getElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, QualType NamedType, TagDecl *OwnedTagDecl=nullptr) const
Expr * getBlockVarCopyInits(const VarDecl *VD)
Get the copy initialization expression of the VarDecl VD, or nullptr if none exists.
bool isInstantiationDependent() const
Whether this expression is instantiation-dependent, meaning that it depends in some way on a template...
Definition: Expr.h:191
decl_type * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
Definition: Redeclarable.h:204
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition: Type.h:3843
bool isSpecialized() const
Determine whether this object type is "specialized", meaning that it has type arguments.
Definition: Type.cpp:660
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:3679
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition: DeclBase.cpp:218
static GVALinkage basicGVALinkageForFunction(const ASTContext &Context, const FunctionDecl *FD)
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition: Redeclarable.h:295
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:3558
unsigned getMaxAtomicInlineWidth() const
Return the maximum width lock-free atomic operation which can be inlined given the supported features...
Definition: TargetInfo.h:596
void AddDeallocation(void(*Callback)(void *), void *Data)
Add a deallocation callback that will be invoked when the ASTContext is destroyed.
Definition: ASTContext.cpp:858
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:3368
Encodes a location in the source.
ObjCInterfaceDecl * getDecl() const
Get the declaration of this interface.
Definition: Type.h:5568
TypedefDecl * getUInt128Decl() const
Retrieve the declaration for the 128-bit unsigned integer type.
Sugar for parentheses used when specifying types.
Definition: Type.h:2363
QualType getReturnType() const
Definition: Type.h:3365
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:4161
bool hasSameTemplateName(TemplateName X, TemplateName Y)
Determine whether the given template names refer to the same template.
unsigned getShortAccumAlign() const
Definition: TargetInfo.h:391
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:6005
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:1019
unsigned getOpenMPDefaultSimdAlign(QualType T) const
Get default simd alignment of the specified complete type in bits.
CanQualType Int128Ty
Definition: ASTContext.h:1013
Represents typeof(type), a GCC extension.
Definition: Type.h:3984
Interfaces are the core concept in Objective-C for object oriented design.
Definition: Type.h:5555
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:1958
This names the __make_integer_seq BuiltinTemplateDecl.
Definition: Builtins.h:245
unsigned getManglingNumber(const NamedDecl *ND) const
A structure for storing an already-substituted template template parameter pack.
Definition: TemplateName.h:121
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
static unsigned NumImplicitCopyAssignmentOperatorsDeclared
The number of implicitly-declared copy assignment operators for which declarations were built...
Definition: ASTContext.h:2792
Kind getKind() const LLVM_READONLY
Definition: ASTContext.h:743
CanQualType SatFractTy
Definition: ASTContext.h:1025
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3020
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.
unsigned getChar16Width() const
getChar16Width/Align - Return the size of &#39;char16_t&#39; for this target, in bits.
Definition: TargetInfo.h:540
unsigned getLongLongWidth() const
getLongLongWidth/Align - Return the size of &#39;signed long long&#39; and &#39;unsigned long long&#39; for this targ...
Definition: TargetInfo.h:385
CallingConv getCC() const
Definition: Type.h:3295
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:2760
QualType getElementType() const
Definition: Type.h:3059
QualType getObjCSelType() const
Retrieve the type that corresponds to the predefined Objective-C &#39;SEL&#39; type.
Definition: ASTContext.h:1844
Represents a vector type where either the type or size is dependent.
Definition: Type.h:3101
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:402
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:2045
TypedefNameDecl * getTypedefNameForUnnamedTagDecl(const TagDecl *TD)
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2395
IntType getIntMaxType() const
Definition: TargetInfo.h:273
bool hasExceptionSpec() const
Return whether this function has any kind of exception spec.
Definition: Type.h:3708
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:4445
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
CanQualType FloatTy
Definition: ASTContext.h:1016
unsigned getLineNumber(FileID FID, unsigned FilePos, bool *Invalid=nullptr) const
Given a SourceLocation, return the spelling line number for the position indicated.
unsigned getFloat128Width() const
getFloat128Width/Align/Format - Return the size/align/format of &#39;__float128&#39;.
Definition: TargetInfo.h:573
This file defines OpenMP nodes for declarative directives.
overridden_cxx_method_iterator overridden_methods_begin(const CXXMethodDecl *Method) const
CanQualType SatUnsignedLongAccumTy
Definition: ASTContext.h:1023
DeclarationName getIdentifier(const IdentifierInfo *ID)
getIdentifier - 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:2301
unsigned pack_size() const
The number of template arguments in the given template argument pack.
Definition: TemplateBase.h:360
BuiltinTemplateKind
Kinds of BuiltinTemplateDecl.
Definition: Builtins.h:243
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:5313
unsigned getHalfAlign() const
Definition: TargetInfo.h:550
CanQualType VoidTy
Definition: ASTContext.h:1004
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition: Decl.h:3493
bool isValueDependent() const
isValueDependent - Determines whether this expression is value-dependent (C++ [temp.dep.constexpr]).
Definition: Expr.h:149
CanQualType Float16Ty
Definition: ASTContext.h:1029
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:6210
bool isAnyPointerType() const
Definition: Type.h:6117
CanQualType SatLongFractTy
Definition: ASTContext.h:1025
This declaration is only a declaration.
Definition: Decl.h:1146
is AltiVec &#39;vector bool ...&#39;
Definition: Type.h:3037
virtual BuiltinVaListKind getBuiltinVaListKind() const =0
Returns the kind of __builtin_va_list type that should be used with this target.
SplitQualType getSplitUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:5976
Represents one property declaration in an Objective-C interface.
Definition: DeclObjC.h:748
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:199
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:1173
We have found a comment attached to this particular declaration.
Definition: ASTContext.h:730
The generic Itanium ABI is the standard ABI of most open-source and Unix-like platforms.
Definition: TargetCXXABI.h:34
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:1831
Qualifiers getIndexTypeQualifiers() const
Definition: Type.h:2709
TypeClass getTypeClass() const
Definition: Type.h:1691
QualType getAttributedType(AttributedType::Kind attrKind, QualType modifiedType, QualType equivalentType)
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition: Specifiers.h:164
This template specialization was formed from a template-id but has not yet been declared, defined, or instantiated.
Definition: Specifiers.h:149
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:197
QualType getSuperClassType() const
Retrieve the type of the superclass of this object type.
Definition: Type.h:5483
ObjCDeclQualifier getObjCDeclQualifier() const
Definition: DeclObjC.h:299
bool isTargetAddressSpace(LangAS AS)
Definition: AddressSpaces.h:58
EnumDecl * getDecl() const
Definition: Type.h:4168
bool isVectorType() const
Definition: Type.h:6198
ObjCPropertyImplDecl * getObjCPropertyImplDeclForPropertyDecl(const ObjCPropertyDecl *PD, const Decl *Container) const
FunctionDecl * getClassScopeSpecializationPattern(const FunctionDecl *FD)
Assigning into this object requires a lifetime extension.
Definition: Type.h:188
QualType AutoDeductTy
Definition: ASTContext.h:1046
CanQualType SatUnsignedFractTy
Definition: ASTContext.h:1026
unsigned getPreferredTypeAlign(const Type *T) const
Return the "preferred" alignment of the specified type T for the current target, in bits...
ObjCImplementationDecl * getImplementation() const
Definition: DeclObjC.cpp:1503
llvm::DenseMap< const Decl *, RawCommentAndCacheFlags > RedeclComments
Mapping from declarations to comments attached to any redeclaration.
Definition: ASTContext.h:777
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:489
bool isCanonical() const
Definition: Type.h:5933
CanQualType SatUnsignedShortFractTy
Definition: ASTContext.h:1026
bool hasFlexibleArrayMember() const
Definition: Decl.h:3661
unsigned getLongDoubleWidth() const
getLongDoubleWidth/Align/Format - Return the size/align/format of &#39;long double&#39;.
Definition: TargetInfo.h:565
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2275
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:208
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:5772
CharUnits getUnadjustedAlignment() const
getUnadjustedAlignment - Get the record alignment in characters, before alignment adjustement...
Definition: RecordLayout.h:181
Describes a module import declaration, which makes the contents of the named module visible in the cu...
Definition: Decl.h:4142
Represents a pointer type decayed from an array or function type.
Definition: Type.h:2478
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:105
CanQualType SatAccumTy
Definition: ASTContext.h:1022
The injected class name of a C++ class template or class template partial specialization.
Definition: Type.h:4794
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:5165
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:354
ast_type_traits::DynTypedNode DynTypedNode
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:1629
void * Allocate(size_t Size, unsigned Align=8) const
Definition: ASTContext.h:658
ObjCDeclQualifier getObjCDeclQualifier() const
Definition: Decl.h:1592
ArrayRef< Decl * > getModuleInitializers(Module *M)
Get the initializations to perform when importing a module, if any.
const llvm::fltSemantics & getFloat128Format() const
Definition: TargetInfo.h:575
CanQualType UnsignedShortTy
Definition: ASTContext.h:1014
ObjCIvarDecl * getNextIvar()
Definition: DeclObjC.h:1999
CallingConv getDefaultCallingConvention(bool IsVariadic, bool IsCXXMethod) const
Retrieves the default calling convention for the current target.
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:2872
ast_type_traits::DynTypedNode Node
CanQualType CharTy
Definition: ASTContext.h:1006
bool propertyTypesAreCompatible(QualType, QualType)
Represents a template argument.
Definition: TemplateBase.h:51
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:2441
IntType
===-— Target Data Type Query Methods ----------------------------—===//
Definition: TargetInfo.h:157
QualType withRestrict() const
Definition: Type.h:843
Represents a template name that was expressed as a qualified name.
Definition: TemplateName.h:366
TagTypeKind
The kind of a tag type.
Definition: Type.h:4847
RealType getRealTypeByWidth(unsigned BitWidth) const
Return floating point type with specified width.
Definition: TargetInfo.cpp:258
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:2461
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:1036
void getLegacyIntegralTypeEncoding(QualType &t) const
getLegacyIntegralTypeEncoding - Another legacy compatibility encoding: 32-bit longs are encoded as &#39;l...
GC getObjCGCAttr() const
Definition: Type.h:322
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:184
ExtInfo getExtInfo() const
Definition: Type.h:3376
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:5856
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:1264
CanQualType NullPtrTy
Definition: ASTContext.h:1032
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:399
CanQualType DoubleComplexTy
Definition: ASTContext.h:1030
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:22
void addCopyConstructorForExceptionObject(CXXRecordDecl *RD, CXXConstructorDecl *CD)
typedef char* __builtin_va_list;
Definition: TargetInfo.h:183
static FloatingRank getFloatingRank(QualType T)
getFloatingRank - Return a relative rank for floating point types.
CanQualType UnsignedShortAccumTy
Definition: ASTContext.h:1019
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:80
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition: Decl.cpp:3488
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:54
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:2927
CanQualType UnsignedLongLongTy
Definition: ASTContext.h:1015
bool isDependent() const
Whether this nested name specifier refers to a dependent type or not.
ObjCInterfaceDecl * getDefinition()
Retrieve the definition of this class, or NULL if this class has been forward-declared (with @class) ...
Definition: DeclObjC.h:1570
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:2525
bool hasLocalQualifiers() const
Determine whether this particular QualType instance has any qualifiers, without looking through any t...
Definition: Type.h:757
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition: Specifiers.h:160
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:3415
DeclarationName - The name of a declaration.
VectorKind getVectorKind() const
Definition: Type.h:3069
Represents the declaration of an Objective-C type parameter.
Definition: DeclObjC.h:578
bool isBooleanType() const
Definition: Type.h:6453
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition: Type.h:5863
const CXXRecordDecl * getBaseSharingVBPtr() const
Definition: RecordLayout.h:311
Represents a C++11 pack expansion that produces a sequence of expressions.
Definition: ExprCXX.h:3756
QualType getFunctionNoProtoType(QualType ResultTy, const FunctionType::ExtInfo &Info) const
Return a K&R style C function type like &#39;int()&#39;.
static ASTContext::DynTypedNodeList getDynNodeFromMap(const NodeTy &Node, const MapTy &Map)
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3010
MangleNumberingContext & getManglingNumberContext(const DeclContext *DC)
Retrieve the context for computing mangling numbers in the given DeclContext.
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.cpp:3430
const ObjCObjectType * getObjectType() const
Gets the type pointed to by this ObjC pointer.
Definition: Type.h:5652
bool isKindOfType() const
Whether this ia a "__kindof" type (semantically).
Definition: Type.cpp:696
Represents an enum.
Definition: Decl.h:3313
FunctionType::ExtInfo getFunctionExtInfo(const Type &t)
Definition: Type.h:6014
Information about the declaration, useful to clients of FullComment.
Definition: Comment.h:984
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:2558
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:2612
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:248
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:146
bool hasObjCLifetime() const
Definition: Type.h:342
QualType AutoRRefDeductTy
Definition: ASTContext.h:1047
virtual ~CXXABI()
llvm::ArrayRef< TemplateArgumentLoc > arguments() const
Definition: TemplateBase.h:580
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:1068
pack_iterator pack_begin() const
Iterator referencing the first argument of a template argument pack.
Definition: TemplateBase.h:340
unsigned getShortFractWidth() const
getShortFractWidth/Align - Return the size of &#39;signed short _Fract&#39; and &#39;unsigned short _Fract&#39; for t...
Definition: TargetInfo.h:405
virtual bool hasFeature(StringRef Feature) const
Determine whether the given target has the given feature.
Definition: TargetInfo.h:1073
bool areComparableObjCPointerTypes(QualType LHS, QualType RHS)
QualType getUnsignedWCharType() const
Return the type of "unsigned wchar_t".
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:4392
const Expr * Replacement
Definition: ParsedAttr.h:67
static unsigned NumImplicitCopyAssignmentOperators
The number of implicitly-declared copy assignment operators.
Definition: ASTContext.h:2788
void addConsistentQualifiers(Qualifiers qs)
Add the qualifiers from the given set to this set, given that they don&#39;t conflict.
Definition: Type.h:469
bool isObjCUnqualifiedIdOrClass() const
Definition: Type.h:5430
GVALinkage GetGVALinkageForVariable(const VarDecl *VD)
A dynamically typed AST node container.
const Decl * getOriginalDecl() const LLVM_READONLY
Definition: ASTContext.h:759
virtual IntType getIntTypeByWidth(unsigned BitWidth, bool IsSigned) const
Return integer type with specified width.
Definition: TargetInfo.cpp:228
Represents a pointer to an Objective C object.
Definition: Type.h:5611
Pointer to a block type.
Definition: Type.h:2495
CanQualType ObjCBuiltinBoolTy
Definition: ASTContext.h:1037
unsigned getLongFractWidth() const
getLongFractWidth/Align - Return the size of &#39;signed long _Fract&#39; and &#39;unsigned long _Fract&#39; for this...
Definition: TargetInfo.h:415
unsigned getIntWidth(QualType T) const
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
Definition: DeclObjC.h:2573
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:6170
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:4135
StringRef getObjCRuntimeNameAsString() const
Produce a name to be used for class&#39;s metadata.
Definition: DeclObjC.cpp:1487
Complex values, per C99 6.2.5p11.
Definition: Type.h:2333
Location wrapper for a TemplateArgument.
Definition: TemplateBase.h:450
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...
bool isObjCQualifiedId() const
Definition: Type.h:5437
CanQualType UnknownAnyTy
Definition: ASTContext.h:1033
bool empty() const
Definition: Type.h:431
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:2024
comments::FullComment * getLocalCommentForDeclUncached(const Decl *D) const
Return parsed documentation comment attached to a given declaration.
Definition: ASTContext.cpp:484
QualType getCanonicalTypeInternal() const
Definition: Type.h:2214
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:6374
This template specialization was declared or defined by an explicit specialization (C++ [temp...
Definition: Specifiers.h:156
CanQualType UnsignedLongTy
Definition: ASTContext.h:1014
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:2800
const llvm::APInt & getSize() const
Definition: Type.h:2746
uint64_t getCharWidth() const
Return the size of the character type, in bits.
Definition: ASTContext.h:2056
CanQualType DependentTy
Definition: ASTContext.h:1033
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:1007
bool isFunctionType() const
Definition: Type.h:6109
bool hasNonFastQualifiers() const
Return true if the set contains any qualifiers which require an ExtQuals node to be allocated...
Definition: Type.h:422
bool isAddressSpaceSupersetOf(Qualifiers other) const
Returns true if this address space is a superset of the other one.
Definition: Type.h:486
unsigned getBoolAlign() const
Return the alignment of &#39;_Bool&#39; and C++ &#39;bool&#39; for this target.
Definition: TargetInfo.h:360
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:6227
static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET)
static GVALinkage basicGVALinkageForVariable(const ASTContext &Context, const VarDecl *VD)
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:716
bool isMSExternInline() const
The combination of the extern and inline keywords under MSVC forces the function to be required...
Definition: Decl.cpp:3008
ExtVectorType - Extended vector type.
Definition: Type.h:3143
CanQualType ObjCBuiltinClassTy
Definition: ASTContext.h:1036
DeclaratorDecl * getDeclaratorForUnnamedTagDecl(const TagDecl *TD)
param_const_iterator param_begin() const
Definition: DeclObjC.h:388
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:2529
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:1675
virtual uint64_t getMaxPointerWidth() const
Return the maximum width of pointers on this target.
Definition: TargetInfo.h:348
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2251
CanQualType BoundMemberTy
Definition: ASTContext.h:1033
static TypedefDecl * CreateCharPtrBuiltinVaListDecl(const ASTContext *Context)
QualType getAutoDeductType() const
C++11 deduction pattern for &#39;auto&#39; type.
ObjCInterfaceDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this Objective-C class.
Definition: DeclObjC.h:1936
llvm::DenseMap< const Decl *, comments::FullComment * > ParsedComments
Mapping from declarations to parsed comments attached to any redeclaration.
Definition: ASTContext.h:781
The template argument is a type.
Definition: TemplateBase.h:60
qual_range quals() const
Definition: Type.h:5734
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1460
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)
void setBlockVarCopyInits(VarDecl *VD, Expr *Init)
Set the copy inialization expression of a block var decl.
Optional< NullabilityKind > getNullability(const ASTContext &context) const
Determine the nullability of the given type.
Definition: Type.cpp:3711
The template argument is actually a parameter pack.
Definition: TemplateBase.h:91
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:181
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat]...
Definition: APValue.h:38
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2052
ArrayRef< QualType > Exceptions
Explicitly-specified list of exception types.
Definition: Type.h:3532
virtual CallingConv getDefaultCallingConv(CallingConvMethodType MT) const
Gets the default calling convention for the given target and declaration context. ...
Definition: TargetInfo.h:1198
bool isObjCObjectType() const
Definition: Type.h:6214
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types...
Definition: Type.cpp:2034
bool hasObjCGCAttr() const
Definition: Type.h:321
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition: Decl.h:2321
CanQualType Char8Ty
Definition: ASTContext.h:1010
ASTMutationListener * getASTMutationListener() const
Retrieve a pointer to the AST mutation listener associated with this AST context, if any...
Definition: ASTContext.h:1083
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2235
A template argument list.
Definition: DeclTemplate.h:210
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:239
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:926
bool isNoThrow(unsigned ID) const
Return true if we know this builtin never throws an exception.
Definition: Builtins.h:112
X
Add a minimal nested name specifier fixit hint to allow lookup of a tag name from an outer enclosing ...
Definition: SemaDecl.cpp:13820
pack_iterator pack_end() const
Iterator referencing one past the last argument of a template argument pack.
Definition: TemplateBase.h:347
unsigned getFloatAlign() const
Definition: TargetInfo.h:555
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:185
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:235
An attributed type is a type to which a type attribute has been applied.
Definition: Type.h:4190
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:3670
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:5281
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:997
Defines the clang::SourceLocation class and associated facilities.
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:4618
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:5969
bool hasUnaligned() const
Definition: Type.h:314
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.
llvm::DenseMap< const void *, llvm::PointerUnion4< const Decl *, const Stmt *, ast_type_traits::DynTypedNode *, ParentVector * > > ParentMapPointers
Maps from a node to its parents.
Definition: ASTContext.h:562
void addModuleInitializer(Module *M, Decl *Init)
Add a declaration to the list of declarations that are initialized for a module.
Definition: ASTContext.cpp:968
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:1878
Represents a C++ struct/union/class.
Definition: DeclCXX.h:302
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:2399
IdentifierInfo * getTypePackElementName() const
Definition: ASTContext.h:1707
Represents a template specialization type whose template cannot be resolved, e.g. ...
Definition: Type.h:5072
const llvm::fltSemantics & getFloatFormat() const
Definition: TargetInfo.h:556
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:76
unsigned getBuiltinID() const
Returns a value indicating whether this function corresponds to a builtin function.
Definition: Decl.cpp:2910
ObjCDeclQualifier
ObjCDeclQualifier - &#39;Qualifiers&#39; written next to the return and parameter types in method declaration...
Definition: DeclBase.h:195
Represents a C array with an unspecified size.
Definition: Type.h:2782
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:1989
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:2169
static TranslationUnitDecl * Create(ASTContext &C)
Definition: Decl.cpp:4194
static void SortAndUniqueProtocols(SmallVectorImpl< ObjCProtocolDecl *> &Protocols)
IdentifierInfo * getMakeIntegerSeqName() const
Definition: ASTContext.h:1701
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:5916
ObjCIvarDecl - Represents an ObjC instance variable.
Definition: DeclObjC.h:1966
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:4407
Provides information a specialization of a member of a class template, which may be a member function...
Definition: DeclTemplate.h:608
CanQualType Char16Ty
Definition: ASTContext.h:1011
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:95
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:725
static unsigned NumImplicitCopyConstructorsDeclared
The number of implicitly-declared copy constructors for which declarations were built.
Definition: ASTContext.h:2778
Builtin::Context & BuiltinInfo
Definition: ASTContext.h:547
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:203
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3975
Declaration of a class template.
Stores a list of Objective-C type parameters for a parameterized class or a category/extension thereo...
Definition: DeclObjC.h:656
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:61
This class is used for builtin types like &#39;int&#39;.
Definition: Type.h:2250
bool isVariadic() const
Definition: DeclObjC.h:456
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:401
QualType getInjectedClassNameType(CXXRecordDecl *Decl, QualType TST) const
getInjectedClassNameType - Return the unique reference to the injected class name type for the specif...
uint64_t getPointerAlign(unsigned AddrSpace) const
Definition: TargetInfo.h:343
static TypedefDecl * CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context)
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:615
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:154
unsigned CountNonClassIvars(const ObjCInterfaceDecl *OI) const
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition: Decl.h:3442
void setRAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:1645
unsigned getCVRQualifiers() const
Definition: Type.h:293
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:568
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:2398
uint64_t Width
Definition: ASTContext.h:139
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:1739
__DEVICE__ int max(int __a, int __b)
NameKind getKind() const
static Decl::Kind getKind(const Decl *D)
Definition: DeclBase.cpp:930
CanQualType IntTy
Definition: ASTContext.h:1013
QualType getSignedWCharType() const
Return the type of "signed wchar_t".
unsigned getNumElements() const
Definition: Type.h:3060
IntType getIntPtrType() const
Definition: TargetInfo.h:283
decl_type * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
Definition: Redeclarable.h:226
static bool NeedsInjectedClassNameType(const RecordDecl *D)
The top declaration context.
Definition: Decl.h:107
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.
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:1942
QualType getAsType() const
Retrieve the type for a type template argument.
Definition: TemplateBase.h:257
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:974
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:2942
bool isUnion() const
Definition: Decl.h:3239
Represents a type template specialization; the template must be a class template, a type alias templa...
Definition: Type.h:4654
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:3949
ObjCTypeParamVariance getVariance() const
Determine the variance of this type parameter.
Definition: DeclObjC.h:621
GVALinkage
A more specific kind of linkage than enum Linkage.
Definition: Linkage.h:74
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:6113
llvm::DenseMap< ast_type_traits::DynTypedNode, llvm::PointerUnion4< const Decl *, const Stmt *, ast_type_traits::DynTypedNode *, ParentVector * > > ParentMapOtherNodes
Parent map for nodes without pointer identity.
Definition: ASTContext.h:570
QualType mergeFunctionParameterTypes(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false)
mergeFunctionParameterTypes - merge two types which appear as function parameter types ...
__DEVICE__ int min(int __a, int __b)
const DeclInfo * getDeclInfo() const LLVM_READONLY
Definition: Comment.h:1127
void addAddressSpace(LangAS space)
Definition: Type.h:395
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
StringRef Text
Definition: Format.cpp:1606
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:1316
QualType getType() const
Definition: Decl.h:648
TemplateArgument getArgumentPack() const
Retrieve the template template argument pack with which this parameter was substituted.
A set of overloaded template declarations.
Definition: TemplateName.h:194
unsigned getChar32Align() const
Definition: TargetInfo.h:546
A trivial tuple used to represent a source range.
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:2899
This represents a decl that may have a name.
Definition: Decl.h:248
ArrayRef< BlockContentComment * > getBlocks() const
Definition: Comment.h:1133
QualType getObjCObjectPointerType(QualType OIT) const
Return a ObjCObjectPointerType type for the given ObjCObjectType.
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:458
Represents a C array with a specified size that is not an integer-constant-expression.
Definition: Type.h:2827
CanQualType BoolTy
Definition: ASTContext.h:1005
void setTemplateNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:1669
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:4887
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:110
bool isInline() const
Whether this variable is (C++1z) inline.
Definition: Decl.h:1365
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:5805
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:281
unsigned getTargetAddressSpace(QualType T) const
Definition: ASTContext.h:2481
CanQualType DoubleTy
Definition: ASTContext.h:1016
Selector getGetterName() const
Definition: DeclObjC.h:925
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:5127
static bool isObjCNSObjectType(QualType Ty)
Return true if this is an NSObject object with its NSObject attribute set.
Definition: ASTContext.h:2032
SourceLocation getRAngleLoc() const
Definition: TemplateBase.h:569
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:3692
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:354
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:288
Missing a type from <setjmp.h>
Definition: ASTContext.h:1992
void setType(QualType newType)
Definition: Decl.h:649
void removeAddressSpace()
Definition: Type.h:394
IntType getProcessIDType() const
Definition: TargetInfo.h:296
bool hasInit() const
Definition: Decl.cpp:2144
QualType getReadPipeType(QualType T) const
Return a read_only pipe type for the specified type.
const LangOptions & getLangOpts() const
Definition: ASTContext.h:696
ObjCCategoryImplDecl - An object of this class encapsulates a category @implementation declaration...
Definition: DeclObjC.h:2520
No in-class initializer.
Definition: Specifiers.h:230
bool AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:2728
This class handles loading and caching of source files into memory.
The parameter is invariant: must match exactly.
ExceptionSpecInfo ExceptionSpec
Definition: Type.h:3557
QualType isPromotableBitField(Expr *E) const
Whether this is a promotable bitfield reference according to C99 6.3.1.1p2, bullet 2 (and GCC extensi...
Defines enum values for all the target-independent builtin functions.
QualType getAdjustedType(QualType Orig, QualType New) const
Return the uniqued reference to a type adjusted from the original type to a new type.
Declaration of a template function.
Definition: DeclTemplate.h:968
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:3236
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:419
QualType getPointeeType() const
Definition: Type.h:2632
const RawComment * getRawCommentForAnyRedecl(const Decl *D, const Decl **OriginalDecl=nullptr) const
Return the documentation comment attached to a given declaration.
Definition: ASTContext.cpp:381
Represents a shadow declaration introduced into a scope by a (resolved) using declaration.
Definition: DeclCXX.h:3147
bool isExternallyVisible() const
Definition: Decl.h:379
A full comment attached to a declaration, contains block content.
Definition: Comment.h:1095
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:191
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:4581
CanQualType OCLClkEventTy
Definition: ASTContext.h:1041
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:127
CanQualType UnsignedIntTy
Definition: ASTContext.h:1014
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:1079
static unsigned NumImplicitDestructors
The number of implicitly-declared destructors.
Definition: ASTContext.h:2802
DeclarationName getCXXOperatorName(OverloadedOperatorKind Op)
getCXXOperatorName - Get the name of the overloadable C++ operator corresponding to Op...
BuiltinTemplateDecl * getMakeIntegerSeqDecl() const
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition: Type.h:5627
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:2008