Coverage Report

Created: 2024-01-17 10:31

/src/llvm-project/clang/lib/AST/ASTContext.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- ASTContext.cpp - Context to hold long-lived AST nodes --------------===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
//  This file implements the ASTContext interface.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "clang/AST/ASTContext.h"
14
#include "CXXABI.h"
15
#include "Interp/Context.h"
16
#include "clang/AST/APValue.h"
17
#include "clang/AST/ASTConcept.h"
18
#include "clang/AST/ASTMutationListener.h"
19
#include "clang/AST/ASTTypeTraits.h"
20
#include "clang/AST/Attr.h"
21
#include "clang/AST/AttrIterator.h"
22
#include "clang/AST/CharUnits.h"
23
#include "clang/AST/Comment.h"
24
#include "clang/AST/Decl.h"
25
#include "clang/AST/DeclBase.h"
26
#include "clang/AST/DeclCXX.h"
27
#include "clang/AST/DeclContextInternals.h"
28
#include "clang/AST/DeclObjC.h"
29
#include "clang/AST/DeclOpenMP.h"
30
#include "clang/AST/DeclTemplate.h"
31
#include "clang/AST/DeclarationName.h"
32
#include "clang/AST/DependenceFlags.h"
33
#include "clang/AST/Expr.h"
34
#include "clang/AST/ExprCXX.h"
35
#include "clang/AST/ExprConcepts.h"
36
#include "clang/AST/ExternalASTSource.h"
37
#include "clang/AST/Mangle.h"
38
#include "clang/AST/MangleNumberingContext.h"
39
#include "clang/AST/NestedNameSpecifier.h"
40
#include "clang/AST/ParentMapContext.h"
41
#include "clang/AST/RawCommentList.h"
42
#include "clang/AST/RecordLayout.h"
43
#include "clang/AST/Stmt.h"
44
#include "clang/AST/TemplateBase.h"
45
#include "clang/AST/TemplateName.h"
46
#include "clang/AST/Type.h"
47
#include "clang/AST/TypeLoc.h"
48
#include "clang/AST/UnresolvedSet.h"
49
#include "clang/AST/VTableBuilder.h"
50
#include "clang/Basic/AddressSpaces.h"
51
#include "clang/Basic/Builtins.h"
52
#include "clang/Basic/CommentOptions.h"
53
#include "clang/Basic/ExceptionSpecificationType.h"
54
#include "clang/Basic/IdentifierTable.h"
55
#include "clang/Basic/LLVM.h"
56
#include "clang/Basic/LangOptions.h"
57
#include "clang/Basic/Linkage.h"
58
#include "clang/Basic/Module.h"
59
#include "clang/Basic/NoSanitizeList.h"
60
#include "clang/Basic/ObjCRuntime.h"
61
#include "clang/Basic/ProfileList.h"
62
#include "clang/Basic/SourceLocation.h"
63
#include "clang/Basic/SourceManager.h"
64
#include "clang/Basic/Specifiers.h"
65
#include "clang/Basic/TargetCXXABI.h"
66
#include "clang/Basic/TargetInfo.h"
67
#include "clang/Basic/XRayLists.h"
68
#include "llvm/ADT/APFixedPoint.h"
69
#include "llvm/ADT/APInt.h"
70
#include "llvm/ADT/APSInt.h"
71
#include "llvm/ADT/ArrayRef.h"
72
#include "llvm/ADT/DenseMap.h"
73
#include "llvm/ADT/DenseSet.h"
74
#include "llvm/ADT/FoldingSet.h"
75
#include "llvm/ADT/PointerUnion.h"
76
#include "llvm/ADT/STLExtras.h"
77
#include "llvm/ADT/SmallPtrSet.h"
78
#include "llvm/ADT/SmallVector.h"
79
#include "llvm/ADT/StringExtras.h"
80
#include "llvm/ADT/StringRef.h"
81
#include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
82
#include "llvm/Support/Capacity.h"
83
#include "llvm/Support/Casting.h"
84
#include "llvm/Support/Compiler.h"
85
#include "llvm/Support/ErrorHandling.h"
86
#include "llvm/Support/MD5.h"
87
#include "llvm/Support/MathExtras.h"
88
#include "llvm/Support/raw_ostream.h"
89
#include "llvm/TargetParser/Triple.h"
90
#include <algorithm>
91
#include <cassert>
92
#include <cstddef>
93
#include <cstdint>
94
#include <cstdlib>
95
#include <map>
96
#include <memory>
97
#include <optional>
98
#include <string>
99
#include <tuple>
100
#include <utility>
101
102
using namespace clang;
103
104
enum FloatingRank {
105
  BFloat16Rank,
106
  Float16Rank,
107
  HalfRank,
108
  FloatRank,
109
  DoubleRank,
110
  LongDoubleRank,
111
  Float128Rank,
112
  Ibm128Rank
113
};
114
115
/// \returns The locations that are relevant when searching for Doc comments
116
/// related to \p D.
117
static SmallVector<SourceLocation, 2>
118
0
getDeclLocsForCommentSearch(const Decl *D, SourceManager &SourceMgr) {
119
0
  assert(D);
120
121
  // User can not attach documentation to implicit declarations.
122
0
  if (D->isImplicit())
123
0
    return {};
124
125
  // User can not attach documentation to implicit instantiations.
126
0
  if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
127
0
    if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
128
0
      return {};
129
0
  }
130
131
0
  if (const auto *VD = dyn_cast<VarDecl>(D)) {
132
0
    if (VD->isStaticDataMember() &&
133
0
        VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
134
0
      return {};
135
0
  }
136
137
0
  if (const auto *CRD = dyn_cast<CXXRecordDecl>(D)) {
138
0
    if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
139
0
      return {};
140
0
  }
141
142
0
  if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
143
0
    TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
144
0
    if (TSK == TSK_ImplicitInstantiation ||
145
0
        TSK == TSK_Undeclared)
146
0
      return {};
147
0
  }
148
149
0
  if (const auto *ED = dyn_cast<EnumDecl>(D)) {
150
0
    if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
151
0
      return {};
152
0
  }
153
0
  if (const auto *TD = dyn_cast<TagDecl>(D)) {
154
    // When tag declaration (but not definition!) is part of the
155
    // decl-specifier-seq of some other declaration, it doesn't get comment
156
0
    if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
157
0
      return {};
158
0
  }
159
  // TODO: handle comments for function parameters properly.
160
0
  if (isa<ParmVarDecl>(D))
161
0
    return {};
162
163
  // TODO: we could look up template parameter documentation in the template
164
  // documentation.
165
0
  if (isa<TemplateTypeParmDecl>(D) ||
166
0
      isa<NonTypeTemplateParmDecl>(D) ||
167
0
      isa<TemplateTemplateParmDecl>(D))
168
0
    return {};
169
170
0
  SmallVector<SourceLocation, 2> Locations;
171
  // Find declaration location.
172
  // For Objective-C declarations we generally don't expect to have multiple
173
  // declarators, thus use declaration starting location as the "declaration
174
  // location".
175
  // For all other declarations multiple declarators are used quite frequently,
176
  // so we use the location of the identifier as the "declaration location".
177
0
  SourceLocation BaseLocation;
178
0
  if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
179
0
      isa<ObjCPropertyDecl>(D) || isa<RedeclarableTemplateDecl>(D) ||
180
0
      isa<ClassTemplateSpecializationDecl>(D) ||
181
      // Allow association with Y across {} in `typedef struct X {} Y`.
182
0
      isa<TypedefDecl>(D))
183
0
    BaseLocation = D->getBeginLoc();
184
0
  else
185
0
    BaseLocation = D->getLocation();
186
187
0
  if (!D->getLocation().isMacroID()) {
188
0
    Locations.emplace_back(BaseLocation);
189
0
  } else {
190
0
    const auto *DeclCtx = D->getDeclContext();
191
192
    // When encountering definitions generated from a macro (that are not
193
    // contained by another declaration in the macro) we need to try and find
194
    // the comment at the location of the expansion but if there is no comment
195
    // there we should retry to see if there is a comment inside the macro as
196
    // well. To this end we return first BaseLocation to first look at the
197
    // expansion site, the second value is the spelling location of the
198
    // beginning of the declaration defined inside the macro.
199
0
    if (!(DeclCtx &&
200
0
          Decl::castFromDeclContext(DeclCtx)->getLocation().isMacroID())) {
201
0
      Locations.emplace_back(SourceMgr.getExpansionLoc(BaseLocation));
202
0
    }
203
204
    // We use Decl::getBeginLoc() and not just BaseLocation here to ensure that
205
    // we don't refer to the macro argument location at the expansion site (this
206
    // can happen if the name's spelling is provided via macro argument), and
207
    // always to the declaration itself.
208
0
    Locations.emplace_back(SourceMgr.getSpellingLoc(D->getBeginLoc()));
209
0
  }
210
211
0
  return Locations;
212
0
}
213
214
RawComment *ASTContext::getRawCommentForDeclNoCacheImpl(
215
    const Decl *D, const SourceLocation RepresentativeLocForDecl,
216
0
    const std::map<unsigned, RawComment *> &CommentsInTheFile) const {
217
  // If the declaration doesn't map directly to a location in a file, we
218
  // can't find the comment.
219
0
  if (RepresentativeLocForDecl.isInvalid() ||
220
0
      !RepresentativeLocForDecl.isFileID())
221
0
    return nullptr;
222
223
  // If there are no comments anywhere, we won't find anything.
224
0
  if (CommentsInTheFile.empty())
225
0
    return nullptr;
226
227
  // Decompose the location for the declaration and find the beginning of the
228
  // file buffer.
229
0
  const std::pair<FileID, unsigned> DeclLocDecomp =
230
0
      SourceMgr.getDecomposedLoc(RepresentativeLocForDecl);
231
232
  // Slow path.
233
0
  auto OffsetCommentBehindDecl =
234
0
      CommentsInTheFile.lower_bound(DeclLocDecomp.second);
235
236
  // First check whether we have a trailing comment.
237
0
  if (OffsetCommentBehindDecl != CommentsInTheFile.end()) {
238
0
    RawComment *CommentBehindDecl = OffsetCommentBehindDecl->second;
239
0
    if ((CommentBehindDecl->isDocumentation() ||
240
0
         LangOpts.CommentOpts.ParseAllComments) &&
241
0
        CommentBehindDecl->isTrailingComment() &&
242
0
        (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
243
0
         isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
244
245
      // Check that Doxygen trailing comment comes after the declaration, starts
246
      // on the same line and in the same file as the declaration.
247
0
      if (SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second) ==
248
0
          Comments.getCommentBeginLine(CommentBehindDecl, DeclLocDecomp.first,
249
0
                                       OffsetCommentBehindDecl->first)) {
250
0
        return CommentBehindDecl;
251
0
      }
252
0
    }
253
0
  }
254
255
  // The comment just after the declaration was not a trailing comment.
256
  // Let's look at the previous comment.
257
0
  if (OffsetCommentBehindDecl == CommentsInTheFile.begin())
258
0
    return nullptr;
259
260
0
  auto OffsetCommentBeforeDecl = --OffsetCommentBehindDecl;
261
0
  RawComment *CommentBeforeDecl = OffsetCommentBeforeDecl->second;
262
263
  // Check that we actually have a non-member Doxygen comment.
264
0
  if (!(CommentBeforeDecl->isDocumentation() ||
265
0
        LangOpts.CommentOpts.ParseAllComments) ||
266
0
      CommentBeforeDecl->isTrailingComment())
267
0
    return nullptr;
268
269
  // Decompose the end of the comment.
270
0
  const unsigned CommentEndOffset =
271
0
      Comments.getCommentEndOffset(CommentBeforeDecl);
272
273
  // Get the corresponding buffer.
274
0
  bool Invalid = false;
275
0
  const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
276
0
                                               &Invalid).data();
277
0
  if (Invalid)
278
0
    return nullptr;
279
280
  // Extract text between the comment and declaration.
281
0
  StringRef Text(Buffer + CommentEndOffset,
282
0
                 DeclLocDecomp.second - CommentEndOffset);
283
284
  // There should be no other declarations or preprocessor directives between
285
  // comment and declaration.
286
0
  if (Text.find_last_of(";{}#@") != StringRef::npos)
287
0
    return nullptr;
288
289
0
  return CommentBeforeDecl;
290
0
}
291
292
0
RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
293
0
  const auto DeclLocs = getDeclLocsForCommentSearch(D, SourceMgr);
294
295
0
  for (const auto DeclLoc : DeclLocs) {
296
    // If the declaration doesn't map directly to a location in a file, we
297
    // can't find the comment.
298
0
    if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
299
0
      continue;
300
301
0
    if (ExternalSource && !CommentsLoaded) {
302
0
      ExternalSource->ReadComments();
303
0
      CommentsLoaded = true;
304
0
    }
305
306
0
    if (Comments.empty())
307
0
      continue;
308
309
0
    const FileID File = SourceMgr.getDecomposedLoc(DeclLoc).first;
310
0
    if (!File.isValid())
311
0
      continue;
312
313
0
    const auto CommentsInThisFile = Comments.getCommentsInFile(File);
314
0
    if (!CommentsInThisFile || CommentsInThisFile->empty())
315
0
      continue;
316
317
0
    if (RawComment *Comment =
318
0
            getRawCommentForDeclNoCacheImpl(D, DeclLoc, *CommentsInThisFile))
319
0
      return Comment;
320
0
  }
321
322
0
  return nullptr;
323
0
}
324
325
943
void ASTContext::addComment(const RawComment &RC) {
326
943
  assert(LangOpts.RetainCommentsFromSystemHeaders ||
327
943
         !SourceMgr.isInSystemHeader(RC.getSourceRange().getBegin()));
328
0
  Comments.addComment(RC, LangOpts.CommentOpts, BumpAlloc);
329
943
}
330
331
/// If we have a 'templated' declaration for a template, adjust 'D' to
332
/// refer to the actual template.
333
/// If we have an implicit instantiation, adjust 'D' to refer to template.
334
0
static const Decl &adjustDeclToTemplate(const Decl &D) {
335
0
  if (const auto *FD = dyn_cast<FunctionDecl>(&D)) {
336
    // Is this function declaration part of a function template?
337
0
    if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
338
0
      return *FTD;
339
340
    // Nothing to do if function is not an implicit instantiation.
341
0
    if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
342
0
      return D;
343
344
    // Function is an implicit instantiation of a function template?
345
0
    if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
346
0
      return *FTD;
347
348
    // Function is instantiated from a member definition of a class template?
349
0
    if (const FunctionDecl *MemberDecl =
350
0
            FD->getInstantiatedFromMemberFunction())
351
0
      return *MemberDecl;
352
353
0
    return D;
354
0
  }
355
0
  if (const auto *VD = dyn_cast<VarDecl>(&D)) {
356
    // Static data member is instantiated from a member definition of a class
357
    // template?
358
0
    if (VD->isStaticDataMember())
359
0
      if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
360
0
        return *MemberDecl;
361
362
0
    return D;
363
0
  }
364
0
  if (const auto *CRD = dyn_cast<CXXRecordDecl>(&D)) {
365
    // Is this class declaration part of a class template?
366
0
    if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
367
0
      return *CTD;
368
369
    // Class is an implicit instantiation of a class template or partial
370
    // specialization?
371
0
    if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
372
0
      if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
373
0
        return D;
374
0
      llvm::PointerUnion<ClassTemplateDecl *,
375
0
                         ClassTemplatePartialSpecializationDecl *>
376
0
          PU = CTSD->getSpecializedTemplateOrPartial();
377
0
      return PU.is<ClassTemplateDecl *>()
378
0
                 ? *static_cast<const Decl *>(PU.get<ClassTemplateDecl *>())
379
0
                 : *static_cast<const Decl *>(
380
0
                       PU.get<ClassTemplatePartialSpecializationDecl *>());
381
0
    }
382
383
    // Class is instantiated from a member definition of a class template?
384
0
    if (const MemberSpecializationInfo *Info =
385
0
            CRD->getMemberSpecializationInfo())
386
0
      return *Info->getInstantiatedFrom();
387
388
0
    return D;
389
0
  }
390
0
  if (const auto *ED = dyn_cast<EnumDecl>(&D)) {
391
    // Enum is instantiated from a member definition of a class template?
392
0
    if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
393
0
      return *MemberDecl;
394
395
0
    return D;
396
0
  }
397
  // FIXME: Adjust alias templates?
398
0
  return D;
399
0
}
400
401
const RawComment *ASTContext::getRawCommentForAnyRedecl(
402
                                                const Decl *D,
403
0
                                                const Decl **OriginalDecl) const {
404
0
  if (!D) {
405
0
    if (OriginalDecl)
406
0
      OriginalDecl = nullptr;
407
0
    return nullptr;
408
0
  }
409
410
0
  D = &adjustDeclToTemplate(*D);
411
412
  // Any comment directly attached to D?
413
0
  {
414
0
    auto DeclComment = DeclRawComments.find(D);
415
0
    if (DeclComment != DeclRawComments.end()) {
416
0
      if (OriginalDecl)
417
0
        *OriginalDecl = D;
418
0
      return DeclComment->second;
419
0
    }
420
0
  }
421
422
  // Any comment attached to any redeclaration of D?
423
0
  const Decl *CanonicalD = D->getCanonicalDecl();
424
0
  if (!CanonicalD)
425
0
    return nullptr;
426
427
0
  {
428
0
    auto RedeclComment = RedeclChainComments.find(CanonicalD);
429
0
    if (RedeclComment != RedeclChainComments.end()) {
430
0
      if (OriginalDecl)
431
0
        *OriginalDecl = RedeclComment->second;
432
0
      auto CommentAtRedecl = DeclRawComments.find(RedeclComment->second);
433
0
      assert(CommentAtRedecl != DeclRawComments.end() &&
434
0
             "This decl is supposed to have comment attached.");
435
0
      return CommentAtRedecl->second;
436
0
    }
437
0
  }
438
439
  // Any redeclarations of D that we haven't checked for comments yet?
440
  // We can't use DenseMap::iterator directly since it'd get invalid.
441
0
  auto LastCheckedRedecl = [this, CanonicalD]() -> const Decl * {
442
0
    return CommentlessRedeclChains.lookup(CanonicalD);
443
0
  }();
444
445
0
  for (const auto Redecl : D->redecls()) {
446
0
    assert(Redecl);
447
    // Skip all redeclarations that have been checked previously.
448
0
    if (LastCheckedRedecl) {
449
0
      if (LastCheckedRedecl == Redecl) {
450
0
        LastCheckedRedecl = nullptr;
451
0
      }
452
0
      continue;
453
0
    }
454
0
    const RawComment *RedeclComment = getRawCommentForDeclNoCache(Redecl);
455
0
    if (RedeclComment) {
456
0
      cacheRawCommentForDecl(*Redecl, *RedeclComment);
457
0
      if (OriginalDecl)
458
0
        *OriginalDecl = Redecl;
459
0
      return RedeclComment;
460
0
    }
461
0
    CommentlessRedeclChains[CanonicalD] = Redecl;
462
0
  }
463
464
0
  if (OriginalDecl)
465
0
    *OriginalDecl = nullptr;
466
0
  return nullptr;
467
0
}
468
469
void ASTContext::cacheRawCommentForDecl(const Decl &OriginalD,
470
0
                                        const RawComment &Comment) const {
471
0
  assert(Comment.isDocumentation() || LangOpts.CommentOpts.ParseAllComments);
472
0
  DeclRawComments.try_emplace(&OriginalD, &Comment);
473
0
  const Decl *const CanonicalDecl = OriginalD.getCanonicalDecl();
474
0
  RedeclChainComments.try_emplace(CanonicalDecl, &OriginalD);
475
0
  CommentlessRedeclChains.erase(CanonicalDecl);
476
0
}
477
478
static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
479
0
                   SmallVectorImpl<const NamedDecl *> &Redeclared) {
480
0
  const DeclContext *DC = ObjCMethod->getDeclContext();
481
0
  if (const auto *IMD = dyn_cast<ObjCImplDecl>(DC)) {
482
0
    const ObjCInterfaceDecl *ID = IMD->getClassInterface();
483
0
    if (!ID)
484
0
      return;
485
    // Add redeclared method here.
486
0
    for (const auto *Ext : ID->known_extensions()) {
487
0
      if (ObjCMethodDecl *RedeclaredMethod =
488
0
            Ext->getMethod(ObjCMethod->getSelector(),
489
0
                                  ObjCMethod->isInstanceMethod()))
490
0
        Redeclared.push_back(RedeclaredMethod);
491
0
    }
492
0
  }
493
0
}
494
495
void ASTContext::attachCommentsToJustParsedDecls(ArrayRef<Decl *> Decls,
496
0
                                                 const Preprocessor *PP) {
497
0
  if (Comments.empty() || Decls.empty())
498
0
    return;
499
500
0
  FileID File;
501
0
  for (Decl *D : Decls) {
502
0
    SourceLocation Loc = D->getLocation();
503
0
    if (Loc.isValid()) {
504
      // See if there are any new comments that are not attached to a decl.
505
      // The location doesn't have to be precise - we care only about the file.
506
0
      File = SourceMgr.getDecomposedLoc(Loc).first;
507
0
      break;
508
0
    }
509
0
  }
510
511
0
  if (File.isInvalid())
512
0
    return;
513
514
0
  auto CommentsInThisFile = Comments.getCommentsInFile(File);
515
0
  if (!CommentsInThisFile || CommentsInThisFile->empty() ||
516
0
      CommentsInThisFile->rbegin()->second->isAttached())
517
0
    return;
518
519
  // There is at least one comment not attached to a decl.
520
  // Maybe it should be attached to one of Decls?
521
  //
522
  // Note that this way we pick up not only comments that precede the
523
  // declaration, but also comments that *follow* the declaration -- thanks to
524
  // the lookahead in the lexer: we've consumed the semicolon and looked
525
  // ahead through comments.
526
0
  for (const Decl *D : Decls) {
527
0
    assert(D);
528
0
    if (D->isInvalidDecl())
529
0
      continue;
530
531
0
    D = &adjustDeclToTemplate(*D);
532
533
0
    if (DeclRawComments.count(D) > 0)
534
0
      continue;
535
536
0
    const auto DeclLocs = getDeclLocsForCommentSearch(D, SourceMgr);
537
538
0
    for (const auto DeclLoc : DeclLocs) {
539
0
      if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
540
0
        continue;
541
542
0
      if (RawComment *const DocComment = getRawCommentForDeclNoCacheImpl(
543
0
              D, DeclLoc, *CommentsInThisFile)) {
544
0
        cacheRawCommentForDecl(*D, *DocComment);
545
0
        comments::FullComment *FC = DocComment->parse(*this, PP, D);
546
0
        ParsedComments[D->getCanonicalDecl()] = FC;
547
0
        break;
548
0
      }
549
0
    }
550
0
  }
551
0
}
552
553
comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
554
0
                                                    const Decl *D) const {
555
0
  auto *ThisDeclInfo = new (*this) comments::DeclInfo;
556
0
  ThisDeclInfo->CommentDecl = D;
557
0
  ThisDeclInfo->IsFilled = false;
558
0
  ThisDeclInfo->fill();
559
0
  ThisDeclInfo->CommentDecl = FC->getDecl();
560
0
  if (!ThisDeclInfo->TemplateParameters)
561
0
    ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
562
0
  comments::FullComment *CFC =
563
0
    new (*this) comments::FullComment(FC->getBlocks(),
564
0
                                      ThisDeclInfo);
565
0
  return CFC;
566
0
}
567
568
0
comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
569
0
  const RawComment *RC = getRawCommentForDeclNoCache(D);
570
0
  return RC ? RC->parse(*this, nullptr, D) : nullptr;
571
0
}
572
573
comments::FullComment *ASTContext::getCommentForDecl(
574
                                              const Decl *D,
575
0
                                              const Preprocessor *PP) const {
576
0
  if (!D || D->isInvalidDecl())
577
0
    return nullptr;
578
0
  D = &adjustDeclToTemplate(*D);
579
580
0
  const Decl *Canonical = D->getCanonicalDecl();
581
0
  llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
582
0
      ParsedComments.find(Canonical);
583
584
0
  if (Pos != ParsedComments.end()) {
585
0
    if (Canonical != D) {
586
0
      comments::FullComment *FC = Pos->second;
587
0
      comments::FullComment *CFC = cloneFullComment(FC, D);
588
0
      return CFC;
589
0
    }
590
0
    return Pos->second;
591
0
  }
592
593
0
  const Decl *OriginalDecl = nullptr;
594
595
0
  const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
596
0
  if (!RC) {
597
0
    if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
598
0
      SmallVector<const NamedDecl*, 8> Overridden;
599
0
      const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
600
0
      if (OMD && OMD->isPropertyAccessor())
601
0
        if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
602
0
          if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
603
0
            return cloneFullComment(FC, D);
604
0
      if (OMD)
605
0
        addRedeclaredMethods(OMD, Overridden);
606
0
      getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
607
0
      for (unsigned i = 0, e = Overridden.size(); i < e; i++)
608
0
        if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
609
0
          return cloneFullComment(FC, D);
610
0
    }
611
0
    else if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
612
      // Attach any tag type's documentation to its typedef if latter
613
      // does not have one of its own.
614
0
      QualType QT = TD->getUnderlyingType();
615
0
      if (const auto *TT = QT->getAs<TagType>())
616
0
        if (const Decl *TD = TT->getDecl())
617
0
          if (comments::FullComment *FC = getCommentForDecl(TD, PP))
618
0
            return cloneFullComment(FC, D);
619
0
    }
620
0
    else if (const auto *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
621
0
      while (IC->getSuperClass()) {
622
0
        IC = IC->getSuperClass();
623
0
        if (comments::FullComment *FC = getCommentForDecl(IC, PP))
624
0
          return cloneFullComment(FC, D);
625
0
      }
626
0
    }
627
0
    else if (const auto *CD = dyn_cast<ObjCCategoryDecl>(D)) {
628
0
      if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
629
0
        if (comments::FullComment *FC = getCommentForDecl(IC, PP))
630
0
          return cloneFullComment(FC, D);
631
0
    }
632
0
    else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
633
0
      if (!(RD = RD->getDefinition()))
634
0
        return nullptr;
635
      // Check non-virtual bases.
636
0
      for (const auto &I : RD->bases()) {
637
0
        if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
638
0
          continue;
639
0
        QualType Ty = I.getType();
640
0
        if (Ty.isNull())
641
0
          continue;
642
0
        if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
643
0
          if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
644
0
            continue;
645
646
0
          if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
647
0
            return cloneFullComment(FC, D);
648
0
        }
649
0
      }
650
      // Check virtual bases.
651
0
      for (const auto &I : RD->vbases()) {
652
0
        if (I.getAccessSpecifier() != AS_public)
653
0
          continue;
654
0
        QualType Ty = I.getType();
655
0
        if (Ty.isNull())
656
0
          continue;
657
0
        if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
658
0
          if (!(VirtualBase= VirtualBase->getDefinition()))
659
0
            continue;
660
0
          if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
661
0
            return cloneFullComment(FC, D);
662
0
        }
663
0
      }
664
0
    }
665
0
    return nullptr;
666
0
  }
667
668
  // If the RawComment was attached to other redeclaration of this Decl, we
669
  // should parse the comment in context of that other Decl.  This is important
670
  // because comments can contain references to parameter names which can be
671
  // different across redeclarations.
672
0
  if (D != OriginalDecl && OriginalDecl)
673
0
    return getCommentForDecl(OriginalDecl, PP);
674
675
0
  comments::FullComment *FC = RC->parse(*this, PP, D);
676
0
  ParsedComments[Canonical] = FC;
677
0
  return FC;
678
0
}
679
680
void
681
ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
682
                                                   const ASTContext &C,
683
0
                                               TemplateTemplateParmDecl *Parm) {
684
0
  ID.AddInteger(Parm->getDepth());
685
0
  ID.AddInteger(Parm->getPosition());
686
0
  ID.AddBoolean(Parm->isParameterPack());
687
688
0
  TemplateParameterList *Params = Parm->getTemplateParameters();
689
0
  ID.AddInteger(Params->size());
690
0
  for (TemplateParameterList::const_iterator P = Params->begin(),
691
0
                                          PEnd = Params->end();
692
0
       P != PEnd; ++P) {
693
0
    if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
694
0
      ID.AddInteger(0);
695
0
      ID.AddBoolean(TTP->isParameterPack());
696
0
      if (TTP->isExpandedParameterPack()) {
697
0
        ID.AddBoolean(true);
698
0
        ID.AddInteger(TTP->getNumExpansionParameters());
699
0
      } else
700
0
        ID.AddBoolean(false);
701
0
      continue;
702
0
    }
703
704
0
    if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
705
0
      ID.AddInteger(1);
706
0
      ID.AddBoolean(NTTP->isParameterPack());
707
0
      ID.AddPointer(C.getUnconstrainedType(C.getCanonicalType(NTTP->getType()))
708
0
                        .getAsOpaquePtr());
709
0
      if (NTTP->isExpandedParameterPack()) {
710
0
        ID.AddBoolean(true);
711
0
        ID.AddInteger(NTTP->getNumExpansionTypes());
712
0
        for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
713
0
          QualType T = NTTP->getExpansionType(I);
714
0
          ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
715
0
        }
716
0
      } else
717
0
        ID.AddBoolean(false);
718
0
      continue;
719
0
    }
720
721
0
    auto *TTP = cast<TemplateTemplateParmDecl>(*P);
722
0
    ID.AddInteger(2);
723
0
    Profile(ID, C, TTP);
724
0
  }
725
0
}
726
727
TemplateTemplateParmDecl *
728
ASTContext::getCanonicalTemplateTemplateParmDecl(
729
0
                                          TemplateTemplateParmDecl *TTP) const {
730
  // Check if we already have a canonical template template parameter.
731
0
  llvm::FoldingSetNodeID ID;
732
0
  CanonicalTemplateTemplateParm::Profile(ID, *this, TTP);
733
0
  void *InsertPos = nullptr;
734
0
  CanonicalTemplateTemplateParm *Canonical
735
0
    = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
736
0
  if (Canonical)
737
0
    return Canonical->getParam();
738
739
  // Build a canonical template parameter list.
740
0
  TemplateParameterList *Params = TTP->getTemplateParameters();
741
0
  SmallVector<NamedDecl *, 4> CanonParams;
742
0
  CanonParams.reserve(Params->size());
743
0
  for (TemplateParameterList::const_iterator P = Params->begin(),
744
0
                                          PEnd = Params->end();
745
0
       P != PEnd; ++P) {
746
    // Note that, per C++20 [temp.over.link]/6, when determining whether
747
    // template-parameters are equivalent, constraints are ignored.
748
0
    if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
749
0
      TemplateTypeParmDecl *NewTTP = TemplateTypeParmDecl::Create(
750
0
          *this, getTranslationUnitDecl(), SourceLocation(), SourceLocation(),
751
0
          TTP->getDepth(), TTP->getIndex(), nullptr, false,
752
0
          TTP->isParameterPack(), /*HasTypeConstraint=*/false,
753
0
          TTP->isExpandedParameterPack()
754
0
              ? std::optional<unsigned>(TTP->getNumExpansionParameters())
755
0
              : std::nullopt);
756
0
      CanonParams.push_back(NewTTP);
757
0
    } else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
758
0
      QualType T = getUnconstrainedType(getCanonicalType(NTTP->getType()));
759
0
      TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
760
0
      NonTypeTemplateParmDecl *Param;
761
0
      if (NTTP->isExpandedParameterPack()) {
762
0
        SmallVector<QualType, 2> ExpandedTypes;
763
0
        SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
764
0
        for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
765
0
          ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
766
0
          ExpandedTInfos.push_back(
767
0
                                getTrivialTypeSourceInfo(ExpandedTypes.back()));
768
0
        }
769
770
0
        Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
771
0
                                                SourceLocation(),
772
0
                                                SourceLocation(),
773
0
                                                NTTP->getDepth(),
774
0
                                                NTTP->getPosition(), nullptr,
775
0
                                                T,
776
0
                                                TInfo,
777
0
                                                ExpandedTypes,
778
0
                                                ExpandedTInfos);
779
0
      } else {
780
0
        Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
781
0
                                                SourceLocation(),
782
0
                                                SourceLocation(),
783
0
                                                NTTP->getDepth(),
784
0
                                                NTTP->getPosition(), nullptr,
785
0
                                                T,
786
0
                                                NTTP->isParameterPack(),
787
0
                                                TInfo);
788
0
      }
789
0
      CanonParams.push_back(Param);
790
0
    } else
791
0
      CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
792
0
                                           cast<TemplateTemplateParmDecl>(*P)));
793
0
  }
794
795
0
  TemplateTemplateParmDecl *CanonTTP = TemplateTemplateParmDecl::Create(
796
0
      *this, getTranslationUnitDecl(), SourceLocation(), TTP->getDepth(),
797
0
      TTP->getPosition(), TTP->isParameterPack(), nullptr,
798
0
      TemplateParameterList::Create(*this, SourceLocation(), SourceLocation(),
799
0
                                    CanonParams, SourceLocation(),
800
0
                                    /*RequiresClause=*/nullptr));
801
802
  // Get the new insert position for the node we care about.
803
0
  Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
804
0
  assert(!Canonical && "Shouldn't be in the map!");
805
0
  (void)Canonical;
806
807
  // Create the canonical template template parameter entry.
808
0
  Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
809
0
  CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
810
0
  return CanonTTP;
811
0
}
812
813
115
TargetCXXABI::Kind ASTContext::getCXXABIKind() const {
814
115
  auto Kind = getTargetInfo().getCXXABI().getKind();
815
115
  return getLangOpts().CXXABI.value_or(Kind);
816
115
}
817
818
46
CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
819
46
  if (!LangOpts.CPlusPlus) return nullptr;
820
821
23
  switch (getCXXABIKind()) {
822
0
  case TargetCXXABI::AppleARM64:
823
0
  case TargetCXXABI::Fuchsia:
824
0
  case TargetCXXABI::GenericARM: // Same as Itanium at this level
825
0
  case TargetCXXABI::iOS:
826
0
  case TargetCXXABI::WatchOS:
827
0
  case TargetCXXABI::GenericAArch64:
828
0
  case TargetCXXABI::GenericMIPS:
829
23
  case TargetCXXABI::GenericItanium:
830
23
  case TargetCXXABI::WebAssembly:
831
23
  case TargetCXXABI::XL:
832
23
    return CreateItaniumCXXABI(*this);
833
0
  case TargetCXXABI::Microsoft:
834
0
    return CreateMicrosoftCXXABI(*this);
835
23
  }
836
0
  llvm_unreachable("Invalid CXXABI type!");
837
0
}
838
839
0
interp::Context &ASTContext::getInterpContext() {
840
0
  if (!InterpContext) {
841
0
    InterpContext.reset(new interp::Context(*this));
842
0
  }
843
0
  return *InterpContext.get();
844
0
}
845
846
0
ParentMapContext &ASTContext::getParentMapContext() {
847
0
  if (!ParentMapCtx)
848
0
    ParentMapCtx.reset(new ParentMapContext(*this));
849
0
  return *ParentMapCtx.get();
850
0
}
851
852
static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
853
46
                                          const LangOptions &LangOpts) {
854
46
  switch (LangOpts.getAddressSpaceMapMangling()) {
855
46
  case LangOptions::ASMM_Target:
856
46
    return TI.useAddressSpaceMapMangling();
857
0
  case LangOptions::ASMM_On:
858
0
    return true;
859
0
  case LangOptions::ASMM_Off:
860
0
    return false;
861
46
  }
862
0
  llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
863
0
}
864
865
ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
866
                       IdentifierTable &idents, SelectorTable &sels,
867
                       Builtin::Context &builtins, TranslationUnitKind TUKind)
868
    : ConstantArrayTypes(this_(), ConstantArrayTypesLog2InitSize),
869
      DependentSizedArrayTypes(this_()), DependentSizedExtVectorTypes(this_()),
870
      DependentAddressSpaceTypes(this_()), DependentVectorTypes(this_()),
871
      DependentSizedMatrixTypes(this_()),
872
      FunctionProtoTypes(this_(), FunctionProtoTypesLog2InitSize),
873
      DependentTypeOfExprTypes(this_()), DependentDecltypeTypes(this_()),
874
      TemplateSpecializationTypes(this_()),
875
      DependentTemplateSpecializationTypes(this_()), AutoTypes(this_()),
876
      DependentBitIntTypes(this_()), SubstTemplateTemplateParmPacks(this_()),
877
      CanonTemplateTemplateParms(this_()), SourceMgr(SM), LangOpts(LOpts),
878
      NoSanitizeL(new NoSanitizeList(LangOpts.NoSanitizeFiles, SM)),
879
      XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles,
880
                                        LangOpts.XRayNeverInstrumentFiles,
881
                                        LangOpts.XRayAttrListFiles, SM)),
882
      ProfList(new ProfileList(LangOpts.ProfileListFiles, SM)),
883
      PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
884
      BuiltinInfo(builtins), TUKind(TUKind), DeclarationNames(*this),
885
      Comments(SM), CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
886
46
      CompCategories(this_()), LastSDM(nullptr, 0) {
887
46
  addTranslationUnitDecl();
888
46
}
889
890
46
void ASTContext::cleanup() {
891
  // Release the DenseMaps associated with DeclContext objects.
892
  // FIXME: Is this the ideal solution?
893
46
  ReleaseDeclContextMaps();
894
895
  // Call all of the deallocation functions on all of their targets.
896
46
  for (auto &Pair : Deallocations)
897
0
    (Pair.first)(Pair.second);
898
46
  Deallocations.clear();
899
900
  // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
901
  // because they can contain DenseMaps.
902
46
  for (llvm::DenseMap<const ObjCContainerDecl*,
903
46
       const ASTRecordLayout*>::iterator
904
46
       I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
905
    // Increment in loop to prevent using deallocated memory.
906
0
    if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
907
0
      R->Destroy(*this);
908
46
  ObjCLayouts.clear();
909
910
46
  for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
911
92
       I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
912
    // Increment in loop to prevent using deallocated memory.
913
46
    if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
914
46
      R->Destroy(*this);
915
46
  }
916
46
  ASTRecordLayouts.clear();
917
918
46
  for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
919
46
                                                    AEnd = DeclAttrs.end();
920
138
       A != AEnd; ++A)
921
92
    A->second->~AttrVec();
922
46
  DeclAttrs.clear();
923
924
46
  for (const auto &Value : ModuleInitializers)
925
0
    Value.second->~PerModuleInitializers();
926
46
  ModuleInitializers.clear();
927
46
}
928
929
46
ASTContext::~ASTContext() { cleanup(); }
930
931
0
void ASTContext::setTraversalScope(const std::vector<Decl *> &TopLevelDecls) {
932
0
  TraversalScope = TopLevelDecls;
933
0
  getParentMapContext().clear();
934
0
}
935
936
0
void ASTContext::AddDeallocation(void (*Callback)(void *), void *Data) const {
937
0
  Deallocations.push_back({Callback, Data});
938
0
}
939
940
void
941
0
ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
942
0
  ExternalSource = std::move(Source);
943
0
}
944
945
0
void ASTContext::PrintStats() const {
946
0
  llvm::errs() << "\n*** AST Context Stats:\n";
947
0
  llvm::errs() << "  " << Types.size() << " types total.\n";
948
949
0
  unsigned counts[] = {
950
0
#define TYPE(Name, Parent) 0,
951
0
#define ABSTRACT_TYPE(Name, Parent)
952
0
#include "clang/AST/TypeNodes.inc"
953
0
    0 // Extra
954
0
  };
955
956
0
  for (unsigned i = 0, e = Types.size(); i != e; ++i) {
957
0
    Type *T = Types[i];
958
0
    counts[(unsigned)T->getTypeClass()]++;
959
0
  }
960
961
0
  unsigned Idx = 0;
962
0
  unsigned TotalBytes = 0;
963
0
#define TYPE(Name, Parent)                                              \
964
0
  if (counts[Idx])                                                      \
965
0
    llvm::errs() << "    " << counts[Idx] << " " << #Name               \
966
0
                 << " types, " << sizeof(Name##Type) << " each "        \
967
0
                 << "(" << counts[Idx] * sizeof(Name##Type)             \
968
0
                 << " bytes)\n";                                        \
969
0
  TotalBytes += counts[Idx] * sizeof(Name##Type);                       \
970
0
  ++Idx;
971
0
#define ABSTRACT_TYPE(Name, Parent)
972
0
#include "clang/AST/TypeNodes.inc"
973
974
0
  llvm::errs() << "Total bytes = " << TotalBytes << "\n";
975
976
  // Implicit special member functions.
977
0
  llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
978
0
               << NumImplicitDefaultConstructors
979
0
               << " implicit default constructors created\n";
980
0
  llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
981
0
               << NumImplicitCopyConstructors
982
0
               << " implicit copy constructors created\n";
983
0
  if (getLangOpts().CPlusPlus)
984
0
    llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
985
0
                 << NumImplicitMoveConstructors
986
0
                 << " implicit move constructors created\n";
987
0
  llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
988
0
               << NumImplicitCopyAssignmentOperators
989
0
               << " implicit copy assignment operators created\n";
990
0
  if (getLangOpts().CPlusPlus)
991
0
    llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
992
0
                 << NumImplicitMoveAssignmentOperators
993
0
                 << " implicit move assignment operators created\n";
994
0
  llvm::errs() << NumImplicitDestructorsDeclared << "/"
995
0
               << NumImplicitDestructors
996
0
               << " implicit destructors created\n";
997
998
0
  if (ExternalSource) {
999
0
    llvm::errs() << "\n";
1000
0
    ExternalSource->PrintStats();
1001
0
  }
1002
1003
0
  BumpAlloc.PrintStats();
1004
0
}
1005
1006
void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
1007
0
                                           bool NotifyListeners) {
1008
0
  if (NotifyListeners)
1009
0
    if (auto *Listener = getASTMutationListener())
1010
0
      Listener->RedefinedHiddenDefinition(ND, M);
1011
1012
0
  MergedDefModules[cast<NamedDecl>(ND->getCanonicalDecl())].push_back(M);
1013
0
}
1014
1015
0
void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) {
1016
0
  auto It = MergedDefModules.find(cast<NamedDecl>(ND->getCanonicalDecl()));
1017
0
  if (It == MergedDefModules.end())
1018
0
    return;
1019
1020
0
  auto &Merged = It->second;
1021
0
  llvm::DenseSet<Module*> Found;
1022
0
  for (Module *&M : Merged)
1023
0
    if (!Found.insert(M).second)
1024
0
      M = nullptr;
1025
0
  llvm::erase(Merged, nullptr);
1026
0
}
1027
1028
ArrayRef<Module *>
1029
0
ASTContext::getModulesWithMergedDefinition(const NamedDecl *Def) {
1030
0
  auto MergedIt =
1031
0
      MergedDefModules.find(cast<NamedDecl>(Def->getCanonicalDecl()));
1032
0
  if (MergedIt == MergedDefModules.end())
1033
0
    return std::nullopt;
1034
0
  return MergedIt->second;
1035
0
}
1036
1037
0
void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
1038
0
  if (LazyInitializers.empty())
1039
0
    return;
1040
1041
0
  auto *Source = Ctx.getExternalSource();
1042
0
  assert(Source && "lazy initializers but no external source");
1043
1044
0
  auto LazyInits = std::move(LazyInitializers);
1045
0
  LazyInitializers.clear();
1046
1047
0
  for (auto ID : LazyInits)
1048
0
    Initializers.push_back(Source->GetExternalDecl(ID));
1049
1050
0
  assert(LazyInitializers.empty() &&
1051
0
         "GetExternalDecl for lazy module initializer added more inits");
1052
0
}
1053
1054
0
void ASTContext::addModuleInitializer(Module *M, Decl *D) {
1055
  // One special case: if we add a module initializer that imports another
1056
  // module, and that module's only initializer is an ImportDecl, simplify.
1057
0
  if (const auto *ID = dyn_cast<ImportDecl>(D)) {
1058
0
    auto It = ModuleInitializers.find(ID->getImportedModule());
1059
1060
    // Maybe the ImportDecl does nothing at all. (Common case.)
1061
0
    if (It == ModuleInitializers.end())
1062
0
      return;
1063
1064
    // Maybe the ImportDecl only imports another ImportDecl.
1065
0
    auto &Imported = *It->second;
1066
0
    if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
1067
0
      Imported.resolve(*this);
1068
0
      auto *OnlyDecl = Imported.Initializers.front();
1069
0
      if (isa<ImportDecl>(OnlyDecl))
1070
0
        D = OnlyDecl;
1071
0
    }
1072
0
  }
1073
1074
0
  auto *&Inits = ModuleInitializers[M];
1075
0
  if (!Inits)
1076
0
    Inits = new (*this) PerModuleInitializers;
1077
0
  Inits->Initializers.push_back(D);
1078
0
}
1079
1080
0
void ASTContext::addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs) {
1081
0
  auto *&Inits = ModuleInitializers[M];
1082
0
  if (!Inits)
1083
0
    Inits = new (*this) PerModuleInitializers;
1084
0
  Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
1085
0
                                 IDs.begin(), IDs.end());
1086
0
}
1087
1088
0
ArrayRef<Decl *> ASTContext::getModuleInitializers(Module *M) {
1089
0
  auto It = ModuleInitializers.find(M);
1090
0
  if (It == ModuleInitializers.end())
1091
0
    return std::nullopt;
1092
1093
0
  auto *Inits = It->second;
1094
0
  Inits->resolve(*this);
1095
0
  return Inits->Initializers;
1096
0
}
1097
1098
0
void ASTContext::setCurrentNamedModule(Module *M) {
1099
0
  assert(M->isNamedModule());
1100
0
  assert(!CurrentCXXNamedModule &&
1101
0
         "We should set named module for ASTContext for only once");
1102
0
  CurrentCXXNamedModule = M;
1103
0
}
1104
1105
291
ExternCContextDecl *ASTContext::getExternCContextDecl() const {
1106
291
  if (!ExternCContext)
1107
18
    ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
1108
1109
291
  return ExternCContext;
1110
291
}
1111
1112
BuiltinTemplateDecl *
1113
ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
1114
0
                                     const IdentifierInfo *II) const {
1115
0
  auto *BuiltinTemplate =
1116
0
      BuiltinTemplateDecl::Create(*this, getTranslationUnitDecl(), II, BTK);
1117
0
  BuiltinTemplate->setImplicit();
1118
0
  getTranslationUnitDecl()->addDecl(BuiltinTemplate);
1119
1120
0
  return BuiltinTemplate;
1121
0
}
1122
1123
BuiltinTemplateDecl *
1124
0
ASTContext::getMakeIntegerSeqDecl() const {
1125
0
  if (!MakeIntegerSeqDecl)
1126
0
    MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq,
1127
0
                                                  getMakeIntegerSeqName());
1128
0
  return MakeIntegerSeqDecl;
1129
0
}
1130
1131
BuiltinTemplateDecl *
1132
0
ASTContext::getTypePackElementDecl() const {
1133
0
  if (!TypePackElementDecl)
1134
0
    TypePackElementDecl = buildBuiltinTemplateDecl(BTK__type_pack_element,
1135
0
                                                   getTypePackElementName());
1136
0
  return TypePackElementDecl;
1137
0
}
1138
1139
RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
1140
92
                                            RecordDecl::TagKind TK) const {
1141
92
  SourceLocation Loc;
1142
92
  RecordDecl *NewDecl;
1143
92
  if (getLangOpts().CPlusPlus)
1144
46
    NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
1145
46
                                    Loc, &Idents.get(Name));
1146
46
  else
1147
46
    NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
1148
46
                                 &Idents.get(Name));
1149
92
  NewDecl->setImplicit();
1150
92
  NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
1151
92
      const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
1152
92
  return NewDecl;
1153
92
}
1154
1155
TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
1156
299
                                              StringRef Name) const {
1157
299
  TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
1158
299
  TypedefDecl *NewDecl = TypedefDecl::Create(
1159
299
      const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
1160
299
      SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
1161
299
  NewDecl->setImplicit();
1162
299
  return NewDecl;
1163
299
}
1164
1165
46
TypedefDecl *ASTContext::getInt128Decl() const {
1166
46
  if (!Int128Decl)
1167
46
    Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
1168
46
  return Int128Decl;
1169
46
}
1170
1171
46
TypedefDecl *ASTContext::getUInt128Decl() const {
1172
46
  if (!UInt128Decl)
1173
46
    UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
1174
46
  return UInt128Decl;
1175
46
}
1176
1177
2.80k
void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
1178
2.80k
  auto *Ty = new (*this, alignof(BuiltinType)) BuiltinType(K);
1179
2.80k
  R = CanQualType::CreateUnsafe(QualType(Ty, 0));
1180
2.80k
  Types.push_back(Ty);
1181
2.80k
}
1182
1183
void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
1184
46
                                  const TargetInfo *AuxTarget) {
1185
46
  assert((!this->Target || this->Target == &Target) &&
1186
46
         "Incorrect target reinitialization");
1187
0
  assert(VoidTy.isNull() && "Context reinitialized?");
1188
1189
0
  this->Target = &Target;
1190
46
  this->AuxTarget = AuxTarget;
1191
1192
46
  ABI.reset(createCXXABI(Target));
1193
46
  AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
1194
1195
  // C99 6.2.5p19.
1196
46
  InitBuiltinType(VoidTy,              BuiltinType::Void);
1197
1198
  // C99 6.2.5p2.
1199
46
  InitBuiltinType(BoolTy,              BuiltinType::Bool);
1200
  // C99 6.2.5p3.
1201
46
  if (LangOpts.CharIsSigned)
1202
46
    InitBuiltinType(CharTy,            BuiltinType::Char_S);
1203
0
  else
1204
0
    InitBuiltinType(CharTy,            BuiltinType::Char_U);
1205
  // C99 6.2.5p4.
1206
46
  InitBuiltinType(SignedCharTy,        BuiltinType::SChar);
1207
46
  InitBuiltinType(ShortTy,             BuiltinType::Short);
1208
46
  InitBuiltinType(IntTy,               BuiltinType::Int);
1209
46
  InitBuiltinType(LongTy,              BuiltinType::Long);
1210
46
  InitBuiltinType(LongLongTy,          BuiltinType::LongLong);
1211
1212
  // C99 6.2.5p6.
1213
46
  InitBuiltinType(UnsignedCharTy,      BuiltinType::UChar);
1214
46
  InitBuiltinType(UnsignedShortTy,     BuiltinType::UShort);
1215
46
  InitBuiltinType(UnsignedIntTy,       BuiltinType::UInt);
1216
46
  InitBuiltinType(UnsignedLongTy,      BuiltinType::ULong);
1217
46
  InitBuiltinType(UnsignedLongLongTy,  BuiltinType::ULongLong);
1218
1219
  // C99 6.2.5p10.
1220
46
  InitBuiltinType(FloatTy,             BuiltinType::Float);
1221
46
  InitBuiltinType(DoubleTy,            BuiltinType::Double);
1222
46
  InitBuiltinType(LongDoubleTy,        BuiltinType::LongDouble);
1223
1224
  // GNU extension, __float128 for IEEE quadruple precision
1225
46
  InitBuiltinType(Float128Ty,          BuiltinType::Float128);
1226
1227
  // __ibm128 for IBM extended precision
1228
46
  InitBuiltinType(Ibm128Ty, BuiltinType::Ibm128);
1229
1230
  // C11 extension ISO/IEC TS 18661-3
1231
46
  InitBuiltinType(Float16Ty,           BuiltinType::Float16);
1232
1233
  // ISO/IEC JTC1 SC22 WG14 N1169 Extension
1234
46
  InitBuiltinType(ShortAccumTy,            BuiltinType::ShortAccum);
1235
46
  InitBuiltinType(AccumTy,                 BuiltinType::Accum);
1236
46
  InitBuiltinType(LongAccumTy,             BuiltinType::LongAccum);
1237
46
  InitBuiltinType(UnsignedShortAccumTy,    BuiltinType::UShortAccum);
1238
46
  InitBuiltinType(UnsignedAccumTy,         BuiltinType::UAccum);
1239
46
  InitBuiltinType(UnsignedLongAccumTy,     BuiltinType::ULongAccum);
1240
46
  InitBuiltinType(ShortFractTy,            BuiltinType::ShortFract);
1241
46
  InitBuiltinType(FractTy,                 BuiltinType::Fract);
1242
46
  InitBuiltinType(LongFractTy,             BuiltinType::LongFract);
1243
46
  InitBuiltinType(UnsignedShortFractTy,    BuiltinType::UShortFract);
1244
46
  InitBuiltinType(UnsignedFractTy,         BuiltinType::UFract);
1245
46
  InitBuiltinType(UnsignedLongFractTy,     BuiltinType::ULongFract);
1246
46
  InitBuiltinType(SatShortAccumTy,         BuiltinType::SatShortAccum);
1247
46
  InitBuiltinType(SatAccumTy,              BuiltinType::SatAccum);
1248
46
  InitBuiltinType(SatLongAccumTy,          BuiltinType::SatLongAccum);
1249
46
  InitBuiltinType(SatUnsignedShortAccumTy, BuiltinType::SatUShortAccum);
1250
46
  InitBuiltinType(SatUnsignedAccumTy,      BuiltinType::SatUAccum);
1251
46
  InitBuiltinType(SatUnsignedLongAccumTy,  BuiltinType::SatULongAccum);
1252
46
  InitBuiltinType(SatShortFractTy,         BuiltinType::SatShortFract);
1253
46
  InitBuiltinType(SatFractTy,              BuiltinType::SatFract);
1254
46
  InitBuiltinType(SatLongFractTy,          BuiltinType::SatLongFract);
1255
46
  InitBuiltinType(SatUnsignedShortFractTy, BuiltinType::SatUShortFract);
1256
46
  InitBuiltinType(SatUnsignedFractTy,      BuiltinType::SatUFract);
1257
46
  InitBuiltinType(SatUnsignedLongFractTy,  BuiltinType::SatULongFract);
1258
1259
  // GNU extension, 128-bit integers.
1260
46
  InitBuiltinType(Int128Ty,            BuiltinType::Int128);
1261
46
  InitBuiltinType(UnsignedInt128Ty,    BuiltinType::UInt128);
1262
1263
  // C++ 3.9.1p5
1264
46
  if (TargetInfo::isTypeSigned(Target.getWCharType()))
1265
46
    InitBuiltinType(WCharTy,           BuiltinType::WChar_S);
1266
0
  else  // -fshort-wchar makes wchar_t be unsigned.
1267
0
    InitBuiltinType(WCharTy,           BuiltinType::WChar_U);
1268
46
  if (LangOpts.CPlusPlus && LangOpts.WChar)
1269
23
    WideCharTy = WCharTy;
1270
23
  else {
1271
    // C99 (or C++ using -fno-wchar).
1272
23
    WideCharTy = getFromTargetType(Target.getWCharType());
1273
23
  }
1274
1275
46
  WIntTy = getFromTargetType(Target.getWIntType());
1276
1277
  // C++20 (proposed)
1278
46
  InitBuiltinType(Char8Ty,              BuiltinType::Char8);
1279
1280
46
  if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1281
23
    InitBuiltinType(Char16Ty,           BuiltinType::Char16);
1282
23
  else // C99
1283
23
    Char16Ty = getFromTargetType(Target.getChar16Type());
1284
1285
46
  if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1286
23
    InitBuiltinType(Char32Ty,           BuiltinType::Char32);
1287
23
  else // C99
1288
23
    Char32Ty = getFromTargetType(Target.getChar32Type());
1289
1290
  // Placeholder type for type-dependent expressions whose type is
1291
  // completely unknown. No code should ever check a type against
1292
  // DependentTy and users should never see it; however, it is here to
1293
  // help diagnose failures to properly check for type-dependent
1294
  // expressions.
1295
46
  InitBuiltinType(DependentTy,         BuiltinType::Dependent);
1296
1297
  // Placeholder type for functions.
1298
46
  InitBuiltinType(OverloadTy,          BuiltinType::Overload);
1299
1300
  // Placeholder type for bound members.
1301
46
  InitBuiltinType(BoundMemberTy,       BuiltinType::BoundMember);
1302
1303
  // Placeholder type for pseudo-objects.
1304
46
  InitBuiltinType(PseudoObjectTy,      BuiltinType::PseudoObject);
1305
1306
  // "any" type; useful for debugger-like clients.
1307
46
  InitBuiltinType(UnknownAnyTy,        BuiltinType::UnknownAny);
1308
1309
  // Placeholder type for unbridged ARC casts.
1310
46
  InitBuiltinType(ARCUnbridgedCastTy,  BuiltinType::ARCUnbridgedCast);
1311
1312
  // Placeholder type for builtin functions.
1313
46
  InitBuiltinType(BuiltinFnTy,  BuiltinType::BuiltinFn);
1314
1315
  // Placeholder type for OMP array sections.
1316
46
  if (LangOpts.OpenMP) {
1317
0
    InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection);
1318
0
    InitBuiltinType(OMPArrayShapingTy, BuiltinType::OMPArrayShaping);
1319
0
    InitBuiltinType(OMPIteratorTy, BuiltinType::OMPIterator);
1320
0
  }
1321
  // Placeholder type for OpenACC array sections.
1322
46
  if (LangOpts.OpenACC) {
1323
    // FIXME: Once we implement OpenACC array sections in Sema, this will either
1324
    // be combined with the OpenMP type, or given its own type. In the meantime,
1325
    // just use the OpenMP type so that parsing can work.
1326
0
    InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection);
1327
0
  }
1328
46
  if (LangOpts.MatrixTypes)
1329
0
    InitBuiltinType(IncompleteMatrixIdxTy, BuiltinType::IncompleteMatrixIdx);
1330
1331
  // Builtin types for 'id', 'Class', and 'SEL'.
1332
46
  InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1333
46
  InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
1334
46
  InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
1335
1336
46
  if (LangOpts.OpenCL) {
1337
0
#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1338
0
    InitBuiltinType(SingletonId, BuiltinType::Id);
1339
0
#include "clang/Basic/OpenCLImageTypes.def"
1340
1341
0
    InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
1342
0
    InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
1343
0
    InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1344
0
    InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
1345
0
    InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
1346
1347
0
#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1348
0
    InitBuiltinType(Id##Ty, BuiltinType::Id);
1349
0
#include "clang/Basic/OpenCLExtensionTypes.def"
1350
0
  }
1351
1352
46
  if (Target.hasAArch64SVETypes()) {
1353
0
#define SVE_TYPE(Name, Id, SingletonId) \
1354
0
    InitBuiltinType(SingletonId, BuiltinType::Id);
1355
0
#include "clang/Basic/AArch64SVEACLETypes.def"
1356
0
  }
1357
1358
46
  if (Target.getTriple().isPPC64()) {
1359
0
#define PPC_VECTOR_MMA_TYPE(Name, Id, Size) \
1360
0
      InitBuiltinType(Id##Ty, BuiltinType::Id);
1361
0
#include "clang/Basic/PPCTypes.def"
1362
0
#define PPC_VECTOR_VSX_TYPE(Name, Id, Size) \
1363
0
    InitBuiltinType(Id##Ty, BuiltinType::Id);
1364
0
#include "clang/Basic/PPCTypes.def"
1365
0
  }
1366
1367
46
  if (Target.hasRISCVVTypes()) {
1368
0
#define RVV_TYPE(Name, Id, SingletonId)                                        \
1369
0
  InitBuiltinType(SingletonId, BuiltinType::Id);
1370
0
#include "clang/Basic/RISCVVTypes.def"
1371
0
  }
1372
1373
46
  if (Target.getTriple().isWasm() && Target.hasFeature("reference-types")) {
1374
0
#define WASM_TYPE(Name, Id, SingletonId)                                       \
1375
0
  InitBuiltinType(SingletonId, BuiltinType::Id);
1376
0
#include "clang/Basic/WebAssemblyReferenceTypes.def"
1377
0
  }
1378
1379
  // Builtin type for __objc_yes and __objc_no
1380
46
  ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1381
46
                       SignedCharTy : BoolTy);
1382
1383
46
  ObjCConstantStringType = QualType();
1384
1385
46
  ObjCSuperType = QualType();
1386
1387
  // void * type
1388
46
  if (LangOpts.OpenCLGenericAddressSpace) {
1389
0
    auto Q = VoidTy.getQualifiers();
1390
0
    Q.setAddressSpace(LangAS::opencl_generic);
1391
0
    VoidPtrTy = getPointerType(getCanonicalType(
1392
0
        getQualifiedType(VoidTy.getUnqualifiedType(), Q)));
1393
46
  } else {
1394
46
    VoidPtrTy = getPointerType(VoidTy);
1395
46
  }
1396
1397
  // nullptr type (C++0x 2.14.7)
1398
46
  InitBuiltinType(NullPtrTy,           BuiltinType::NullPtr);
1399
1400
  // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1401
46
  InitBuiltinType(HalfTy, BuiltinType::Half);
1402
1403
46
  InitBuiltinType(BFloat16Ty, BuiltinType::BFloat16);
1404
1405
  // Builtin type used to help define __builtin_va_list.
1406
46
  VaListTagDecl = nullptr;
1407
1408
  // MSVC predeclares struct _GUID, and we need it to create MSGuidDecls.
1409
46
  if (LangOpts.MicrosoftExt || LangOpts.Borland) {
1410
0
    MSGuidTagDecl = buildImplicitRecord("_GUID");
1411
0
    getTranslationUnitDecl()->addDecl(MSGuidTagDecl);
1412
0
  }
1413
46
}
1414
1415
71
DiagnosticsEngine &ASTContext::getDiagnostics() const {
1416
71
  return SourceMgr.getDiagnostics();
1417
71
}
1418
1419
92
AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1420
92
  AttrVec *&Result = DeclAttrs[D];
1421
92
  if (!Result) {
1422
92
    void *Mem = Allocate(sizeof(AttrVec));
1423
92
    Result = new (Mem) AttrVec;
1424
92
  }
1425
1426
92
  return *Result;
1427
92
}
1428
1429
/// Erase the attributes corresponding to the given declaration.
1430
0
void ASTContext::eraseDeclAttrs(const Decl *D) {
1431
0
  llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1432
0
  if (Pos != DeclAttrs.end()) {
1433
0
    Pos->second->~AttrVec();
1434
0
    DeclAttrs.erase(Pos);
1435
0
  }
1436
0
}
1437
1438
// FIXME: Remove ?
1439
MemberSpecializationInfo *
1440
0
ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
1441
0
  assert(Var->isStaticDataMember() && "Not a static data member");
1442
0
  return getTemplateOrSpecializationInfo(Var)
1443
0
      .dyn_cast<MemberSpecializationInfo *>();
1444
0
}
1445
1446
ASTContext::TemplateOrSpecializationInfo
1447
1.47k
ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1448
1.47k
  llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1449
1.47k
      TemplateOrInstantiation.find(Var);
1450
1.47k
  if (Pos == TemplateOrInstantiation.end())
1451
1.47k
    return {};
1452
1453
0
  return Pos->second;
1454
1.47k
}
1455
1456
void
1457
ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
1458
                                                TemplateSpecializationKind TSK,
1459
0
                                          SourceLocation PointOfInstantiation) {
1460
0
  assert(Inst->isStaticDataMember() && "Not a static data member");
1461
0
  assert(Tmpl->isStaticDataMember() && "Not a static data member");
1462
0
  setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1463
0
                                            Tmpl, TSK, PointOfInstantiation));
1464
0
}
1465
1466
void
1467
ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1468
0
                                            TemplateOrSpecializationInfo TSI) {
1469
0
  assert(!TemplateOrInstantiation[Inst] &&
1470
0
         "Already noted what the variable was instantiated from");
1471
0
  TemplateOrInstantiation[Inst] = TSI;
1472
0
}
1473
1474
NamedDecl *
1475
0
ASTContext::getInstantiatedFromUsingDecl(NamedDecl *UUD) {
1476
0
  return InstantiatedFromUsingDecl.lookup(UUD);
1477
0
}
1478
1479
void
1480
0
ASTContext::setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern) {
1481
0
  assert((isa<UsingDecl>(Pattern) ||
1482
0
          isa<UnresolvedUsingValueDecl>(Pattern) ||
1483
0
          isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1484
0
         "pattern decl is not a using decl");
1485
0
  assert((isa<UsingDecl>(Inst) ||
1486
0
          isa<UnresolvedUsingValueDecl>(Inst) ||
1487
0
          isa<UnresolvedUsingTypenameDecl>(Inst)) &&
1488
0
         "instantiation did not produce a using decl");
1489
0
  assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1490
0
  InstantiatedFromUsingDecl[Inst] = Pattern;
1491
0
}
1492
1493
UsingEnumDecl *
1494
0
ASTContext::getInstantiatedFromUsingEnumDecl(UsingEnumDecl *UUD) {
1495
0
  return InstantiatedFromUsingEnumDecl.lookup(UUD);
1496
0
}
1497
1498
void ASTContext::setInstantiatedFromUsingEnumDecl(UsingEnumDecl *Inst,
1499
0
                                                  UsingEnumDecl *Pattern) {
1500
0
  assert(!InstantiatedFromUsingEnumDecl[Inst] && "pattern already exists");
1501
0
  InstantiatedFromUsingEnumDecl[Inst] = Pattern;
1502
0
}
1503
1504
UsingShadowDecl *
1505
0
ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1506
0
  return InstantiatedFromUsingShadowDecl.lookup(Inst);
1507
0
}
1508
1509
void
1510
ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1511
0
                                               UsingShadowDecl *Pattern) {
1512
0
  assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1513
0
  InstantiatedFromUsingShadowDecl[Inst] = Pattern;
1514
0
}
1515
1516
0
FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1517
0
  return InstantiatedFromUnnamedFieldDecl.lookup(Field);
1518
0
}
1519
1520
void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1521
0
                                                     FieldDecl *Tmpl) {
1522
0
  assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1523
0
  assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1524
0
  assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1525
0
         "Already noted what unnamed field was instantiated from");
1526
1527
0
  InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1528
0
}
1529
1530
ASTContext::overridden_cxx_method_iterator
1531
0
ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1532
0
  return overridden_methods(Method).begin();
1533
0
}
1534
1535
ASTContext::overridden_cxx_method_iterator
1536
0
ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1537
0
  return overridden_methods(Method).end();
1538
0
}
1539
1540
unsigned
1541
0
ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1542
0
  auto Range = overridden_methods(Method);
1543
0
  return Range.end() - Range.begin();
1544
0
}
1545
1546
ASTContext::overridden_method_range
1547
0
ASTContext::overridden_methods(const CXXMethodDecl *Method) const {
1548
0
  llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1549
0
      OverriddenMethods.find(Method->getCanonicalDecl());
1550
0
  if (Pos == OverriddenMethods.end())
1551
0
    return overridden_method_range(nullptr, nullptr);
1552
0
  return overridden_method_range(Pos->second.begin(), Pos->second.end());
1553
0
}
1554
1555
void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1556
0
                                     const CXXMethodDecl *Overridden) {
1557
0
  assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
1558
0
  OverriddenMethods[Method].push_back(Overridden);
1559
0
}
1560
1561
void ASTContext::getOverriddenMethods(
1562
                      const NamedDecl *D,
1563
0
                      SmallVectorImpl<const NamedDecl *> &Overridden) const {
1564
0
  assert(D);
1565
1566
0
  if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
1567
0
    Overridden.append(overridden_methods_begin(CXXMethod),
1568
0
                      overridden_methods_end(CXXMethod));
1569
0
    return;
1570
0
  }
1571
1572
0
  const auto *Method = dyn_cast<ObjCMethodDecl>(D);
1573
0
  if (!Method)
1574
0
    return;
1575
1576
0
  SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1577
0
  Method->getOverriddenMethods(OverDecls);
1578
0
  Overridden.append(OverDecls.begin(), OverDecls.end());
1579
0
}
1580
1581
0
void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1582
0
  assert(!Import->getNextLocalImport() &&
1583
0
         "Import declaration already in the chain");
1584
0
  assert(!Import->isFromASTFile() && "Non-local import declaration");
1585
0
  if (!FirstLocalImport) {
1586
0
    FirstLocalImport = Import;
1587
0
    LastLocalImport = Import;
1588
0
    return;
1589
0
  }
1590
1591
0
  LastLocalImport->setNextLocalImport(Import);
1592
0
  LastLocalImport = Import;
1593
0
}
1594
1595
//===----------------------------------------------------------------------===//
1596
//                         Type Sizing and Analysis
1597
//===----------------------------------------------------------------------===//
1598
1599
/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1600
/// scalar floating point type.
1601
1
const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
1602
1
  switch (T->castAs<BuiltinType>()->getKind()) {
1603
0
  default:
1604
0
    llvm_unreachable("Not a floating point type!");
1605
0
  case BuiltinType::BFloat16:
1606
0
    return Target->getBFloat16Format();
1607
0
  case BuiltinType::Float16:
1608
0
    return Target->getHalfFormat();
1609
0
  case BuiltinType::Half:
1610
    // For HLSL, when the native half type is disabled, half will be treat as
1611
    // float.
1612
0
    if (getLangOpts().HLSL)
1613
0
      if (getLangOpts().NativeHalfType)
1614
0
        return Target->getHalfFormat();
1615
0
      else
1616
0
        return Target->getFloatFormat();
1617
0
    else
1618
0
      return Target->getHalfFormat();
1619
0
  case BuiltinType::Float:      return Target->getFloatFormat();
1620
1
  case BuiltinType::Double:     return Target->getDoubleFormat();
1621
0
  case BuiltinType::Ibm128:
1622
0
    return Target->getIbm128Format();
1623
0
  case BuiltinType::LongDouble:
1624
0
    if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice)
1625
0
      return AuxTarget->getLongDoubleFormat();
1626
0
    return Target->getLongDoubleFormat();
1627
0
  case BuiltinType::Float128:
1628
0
    if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice)
1629
0
      return AuxTarget->getFloat128Format();
1630
0
    return Target->getFloat128Format();
1631
1
  }
1632
1
}
1633
1634
0
CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
1635
0
  unsigned Align = Target->getCharWidth();
1636
1637
0
  const unsigned AlignFromAttr = D->getMaxAlignment();
1638
0
  if (AlignFromAttr)
1639
0
    Align = AlignFromAttr;
1640
1641
  // __attribute__((aligned)) can increase or decrease alignment
1642
  // *except* on a struct or struct member, where it only increases
1643
  // alignment unless 'packed' is also specified.
1644
  //
1645
  // It is an error for alignas to decrease alignment, so we can
1646
  // ignore that possibility;  Sema should diagnose it.
1647
0
  bool UseAlignAttrOnly;
1648
0
  if (const FieldDecl *FD = dyn_cast<FieldDecl>(D))
1649
0
    UseAlignAttrOnly =
1650
0
        FD->hasAttr<PackedAttr>() || FD->getParent()->hasAttr<PackedAttr>();
1651
0
  else
1652
0
    UseAlignAttrOnly = AlignFromAttr != 0;
1653
  // If we're using the align attribute only, just ignore everything
1654
  // else about the declaration and its type.
1655
0
  if (UseAlignAttrOnly) {
1656
    // do nothing
1657
0
  } else if (const auto *VD = dyn_cast<ValueDecl>(D)) {
1658
0
    QualType T = VD->getType();
1659
0
    if (const auto *RT = T->getAs<ReferenceType>()) {
1660
0
      if (ForAlignof)
1661
0
        T = RT->getPointeeType();
1662
0
      else
1663
0
        T = getPointerType(RT->getPointeeType());
1664
0
    }
1665
0
    QualType BaseT = getBaseElementType(T);
1666
0
    if (T->isFunctionType())
1667
0
      Align = getTypeInfoImpl(T.getTypePtr()).Align;
1668
0
    else if (!BaseT->isIncompleteType()) {
1669
      // Adjust alignments of declarations with array type by the
1670
      // large-array alignment on the target.
1671
0
      if (const ArrayType *arrayType = getAsArrayType(T)) {
1672
0
        unsigned MinWidth = Target->getLargeArrayMinWidth();
1673
0
        if (!ForAlignof && MinWidth) {
1674
0
          if (isa<VariableArrayType>(arrayType))
1675
0
            Align = std::max(Align, Target->getLargeArrayAlign());
1676
0
          else if (isa<ConstantArrayType>(arrayType) &&
1677
0
                   MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1678
0
            Align = std::max(Align, Target->getLargeArrayAlign());
1679
0
        }
1680
0
      }
1681
0
      Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
1682
0
      if (BaseT.getQualifiers().hasUnaligned())
1683
0
        Align = Target->getCharWidth();
1684
0
    }
1685
1686
    // Ensure miminum alignment for global variables.
1687
0
    if (const auto *VD = dyn_cast<VarDecl>(D))
1688
0
      if (VD->hasGlobalStorage() && !ForAlignof) {
1689
0
        uint64_t TypeSize =
1690
0
            !BaseT->isIncompleteType() ? getTypeSize(T.getTypePtr()) : 0;
1691
0
        Align = std::max(Align, getTargetInfo().getMinGlobalAlign(TypeSize));
1692
0
      }
1693
1694
    // Fields can be subject to extra alignment constraints, like if
1695
    // the field is packed, the struct is packed, or the struct has a
1696
    // a max-field-alignment constraint (#pragma pack).  So calculate
1697
    // the actual alignment of the field within the struct, and then
1698
    // (as we're expected to) constrain that by the alignment of the type.
1699
0
    if (const auto *Field = dyn_cast<FieldDecl>(VD)) {
1700
0
      const RecordDecl *Parent = Field->getParent();
1701
      // We can only produce a sensible answer if the record is valid.
1702
0
      if (!Parent->isInvalidDecl()) {
1703
0
        const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
1704
1705
        // Start with the record's overall alignment.
1706
0
        unsigned FieldAlign = toBits(Layout.getAlignment());
1707
1708
        // Use the GCD of that and the offset within the record.
1709
0
        uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1710
0
        if (Offset > 0) {
1711
          // Alignment is always a power of 2, so the GCD will be a power of 2,
1712
          // which means we get to do this crazy thing instead of Euclid's.
1713
0
          uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1714
0
          if (LowBitOfOffset < FieldAlign)
1715
0
            FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1716
0
        }
1717
1718
0
        Align = std::min(Align, FieldAlign);
1719
0
      }
1720
0
    }
1721
0
  }
1722
1723
  // Some targets have hard limitation on the maximum requestable alignment in
1724
  // aligned attribute for static variables.
1725
0
  const unsigned MaxAlignedAttr = getTargetInfo().getMaxAlignedAttribute();
1726
0
  const auto *VD = dyn_cast<VarDecl>(D);
1727
0
  if (MaxAlignedAttr && VD && VD->getStorageClass() == SC_Static)
1728
0
    Align = std::min(Align, MaxAlignedAttr);
1729
1730
0
  return toCharUnitsFromBits(Align);
1731
0
}
1732
1733
0
CharUnits ASTContext::getExnObjectAlignment() const {
1734
0
  return toCharUnitsFromBits(Target->getExnObjectAlignment());
1735
0
}
1736
1737
// getTypeInfoDataSizeInChars - Return the size of a type, in
1738
// chars. If the type is a record, its data size is returned.  This is
1739
// the size of the memcpy that's performed when assigning this type
1740
// using a trivial copy/move assignment operator.
1741
0
TypeInfoChars ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1742
0
  TypeInfoChars Info = getTypeInfoInChars(T);
1743
1744
  // In C++, objects can sometimes be allocated into the tail padding
1745
  // of a base-class subobject.  We decide whether that's possible
1746
  // during class layout, so here we can just trust the layout results.
1747
0
  if (getLangOpts().CPlusPlus) {
1748
0
    if (const auto *RT = T->getAs<RecordType>()) {
1749
0
      const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1750
0
      Info.Width = layout.getDataSize();
1751
0
    }
1752
0
  }
1753
1754
0
  return Info;
1755
0
}
1756
1757
/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1758
/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1759
TypeInfoChars
1760
static getConstantArrayInfoInChars(const ASTContext &Context,
1761
0
                                   const ConstantArrayType *CAT) {
1762
0
  TypeInfoChars EltInfo = Context.getTypeInfoInChars(CAT->getElementType());
1763
0
  uint64_t Size = CAT->getSize().getZExtValue();
1764
0
  assert((Size == 0 || static_cast<uint64_t>(EltInfo.Width.getQuantity()) <=
1765
0
              (uint64_t)(-1)/Size) &&
1766
0
         "Overflow in array type char size evaluation");
1767
0
  uint64_t Width = EltInfo.Width.getQuantity() * Size;
1768
0
  unsigned Align = EltInfo.Align.getQuantity();
1769
0
  if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1770
0
      Context.getTargetInfo().getPointerWidth(LangAS::Default) == 64)
1771
0
    Width = llvm::alignTo(Width, Align);
1772
0
  return TypeInfoChars(CharUnits::fromQuantity(Width),
1773
0
                       CharUnits::fromQuantity(Align),
1774
0
                       EltInfo.AlignRequirement);
1775
0
}
1776
1777
144
TypeInfoChars ASTContext::getTypeInfoInChars(const Type *T) const {
1778
144
  if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
1779
0
    return getConstantArrayInfoInChars(*this, CAT);
1780
144
  TypeInfo Info = getTypeInfo(T);
1781
144
  return TypeInfoChars(toCharUnitsFromBits(Info.Width),
1782
144
                       toCharUnitsFromBits(Info.Align), Info.AlignRequirement);
1783
144
}
1784
1785
144
TypeInfoChars ASTContext::getTypeInfoInChars(QualType T) const {
1786
144
  return getTypeInfoInChars(T.getTypePtr());
1787
144
}
1788
1789
5
bool ASTContext::isPromotableIntegerType(QualType T) const {
1790
  // HLSL doesn't promote all small integer types to int, it
1791
  // just uses the rank-based promotion rules for all types.
1792
5
  if (getLangOpts().HLSL)
1793
0
    return false;
1794
1795
5
  if (const auto *BT = T->getAs<BuiltinType>())
1796
4
    switch (BT->getKind()) {
1797
0
    case BuiltinType::Bool:
1798
0
    case BuiltinType::Char_S:
1799
0
    case BuiltinType::Char_U:
1800
0
    case BuiltinType::SChar:
1801
0
    case BuiltinType::UChar:
1802
0
    case BuiltinType::Short:
1803
0
    case BuiltinType::UShort:
1804
0
    case BuiltinType::WChar_S:
1805
0
    case BuiltinType::WChar_U:
1806
0
    case BuiltinType::Char8:
1807
0
    case BuiltinType::Char16:
1808
0
    case BuiltinType::Char32:
1809
0
      return true;
1810
4
    default:
1811
4
      return false;
1812
4
    }
1813
1814
  // Enumerated types are promotable to their compatible integer types
1815
  // (C99 6.3.1.1) a.k.a. its underlying type (C++ [conv.prom]p2).
1816
1
  if (const auto *ET = T->getAs<EnumType>()) {
1817
0
    if (T->isDependentType() || ET->getDecl()->getPromotionType().isNull() ||
1818
0
        ET->getDecl()->isScoped())
1819
0
      return false;
1820
1821
0
    return true;
1822
0
  }
1823
1824
1
  return false;
1825
1
}
1826
1827
0
bool ASTContext::isAlignmentRequired(const Type *T) const {
1828
0
  return getTypeInfo(T).AlignRequirement != AlignRequirementKind::None;
1829
0
}
1830
1831
0
bool ASTContext::isAlignmentRequired(QualType T) const {
1832
0
  return isAlignmentRequired(T.getTypePtr());
1833
0
}
1834
1835
unsigned ASTContext::getTypeAlignIfKnown(QualType T,
1836
0
                                         bool NeedsPreferredAlignment) const {
1837
  // An alignment on a typedef overrides anything else.
1838
0
  if (const auto *TT = T->getAs<TypedefType>())
1839
0
    if (unsigned Align = TT->getDecl()->getMaxAlignment())
1840
0
      return Align;
1841
1842
  // If we have an (array of) complete type, we're done.
1843
0
  T = getBaseElementType(T);
1844
0
  if (!T->isIncompleteType())
1845
0
    return NeedsPreferredAlignment ? getPreferredTypeAlign(T) : getTypeAlign(T);
1846
1847
  // If we had an array type, its element type might be a typedef
1848
  // type with an alignment attribute.
1849
0
  if (const auto *TT = T->getAs<TypedefType>())
1850
0
    if (unsigned Align = TT->getDecl()->getMaxAlignment())
1851
0
      return Align;
1852
1853
  // Otherwise, see if the declaration of the type had an attribute.
1854
0
  if (const auto *TT = T->getAs<TagType>())
1855
0
    return TT->getDecl()->getMaxAlignment();
1856
1857
0
  return 0;
1858
0
}
1859
1860
2.35k
TypeInfo ASTContext::getTypeInfo(const Type *T) const {
1861
2.35k
  TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1862
2.35k
  if (I != MemoizedTypeInfo.end())
1863
2.02k
    return I->second;
1864
1865
  // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1866
326
  TypeInfo TI = getTypeInfoImpl(T);
1867
326
  MemoizedTypeInfo[T] = TI;
1868
326
  return TI;
1869
2.35k
}
1870
1871
/// getTypeInfoImpl - Return the size of the specified type, in bits.  This
1872
/// method does not work on incomplete types.
1873
///
1874
/// FIXME: Pointers into different addr spaces could have different sizes and
1875
/// alignment requirements: getPointerInfo should take an AddrSpace, this
1876
/// should take a QualType, &c.
1877
326
TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1878
326
  uint64_t Width = 0;
1879
326
  unsigned Align = 8;
1880
326
  AlignRequirementKind AlignRequirement = AlignRequirementKind::None;
1881
326
  LangAS AS = LangAS::Default;
1882
326
  switch (T->getTypeClass()) {
1883
0
#define TYPE(Class, Base)
1884
0
#define ABSTRACT_TYPE(Class, Base)
1885
0
#define NON_CANONICAL_TYPE(Class, Base)
1886
0
#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1887
0
#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)                       \
1888
0
  case Type::Class:                                                            \
1889
0
  assert(!T->isDependentType() && "should not see dependent types here");      \
1890
0
  return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
1891
0
#include "clang/AST/TypeNodes.inc"
1892
0
    llvm_unreachable("Should not see dependent types");
1893
1894
0
  case Type::FunctionNoProto:
1895
0
  case Type::FunctionProto:
1896
    // GCC extension: alignof(function) = 32 bits
1897
0
    Width = 0;
1898
0
    Align = 32;
1899
0
    break;
1900
1901
0
  case Type::IncompleteArray:
1902
0
  case Type::VariableArray:
1903
0
  case Type::ConstantArray: {
1904
    // Model non-constant sized arrays as size zero, but track the alignment.
1905
0
    uint64_t Size = 0;
1906
0
    if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
1907
0
      Size = CAT->getSize().getZExtValue();
1908
1909
0
    TypeInfo EltInfo = getTypeInfo(cast<ArrayType>(T)->getElementType());
1910
0
    assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
1911
0
           "Overflow in array type bit size evaluation");
1912
0
    Width = EltInfo.Width * Size;
1913
0
    Align = EltInfo.Align;
1914
0
    AlignRequirement = EltInfo.AlignRequirement;
1915
0
    if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1916
0
        getTargetInfo().getPointerWidth(LangAS::Default) == 64)
1917
0
      Width = llvm::alignTo(Width, Align);
1918
0
    break;
1919
0
  }
1920
1921
0
  case Type::ExtVector:
1922
0
  case Type::Vector: {
1923
0
    const auto *VT = cast<VectorType>(T);
1924
0
    TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1925
0
    Width = VT->isExtVectorBoolType() ? VT->getNumElements()
1926
0
                                      : EltInfo.Width * VT->getNumElements();
1927
    // Enforce at least byte size and alignment.
1928
0
    Width = std::max<unsigned>(8, Width);
1929
0
    Align = std::max<unsigned>(8, Width);
1930
1931
    // If the alignment is not a power of 2, round up to the next power of 2.
1932
    // This happens for non-power-of-2 length vectors.
1933
0
    if (Align & (Align-1)) {
1934
0
      Align = llvm::bit_ceil(Align);
1935
0
      Width = llvm::alignTo(Width, Align);
1936
0
    }
1937
    // Adjust the alignment based on the target max.
1938
0
    uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1939
0
    if (TargetVectorAlign && TargetVectorAlign < Align)
1940
0
      Align = TargetVectorAlign;
1941
0
    if (VT->getVectorKind() == VectorKind::SveFixedLengthData)
1942
      // Adjust the alignment for fixed-length SVE vectors. This is important
1943
      // for non-power-of-2 vector lengths.
1944
0
      Align = 128;
1945
0
    else if (VT->getVectorKind() == VectorKind::SveFixedLengthPredicate)
1946
      // Adjust the alignment for fixed-length SVE predicates.
1947
0
      Align = 16;
1948
0
    else if (VT->getVectorKind() == VectorKind::RVVFixedLengthData)
1949
      // Adjust the alignment for fixed-length RVV vectors.
1950
0
      Align = std::min<unsigned>(64, Width);
1951
0
    break;
1952
0
  }
1953
1954
0
  case Type::ConstantMatrix: {
1955
0
    const auto *MT = cast<ConstantMatrixType>(T);
1956
0
    TypeInfo ElementInfo = getTypeInfo(MT->getElementType());
1957
    // The internal layout of a matrix value is implementation defined.
1958
    // Initially be ABI compatible with arrays with respect to alignment and
1959
    // size.
1960
0
    Width = ElementInfo.Width * MT->getNumRows() * MT->getNumColumns();
1961
0
    Align = ElementInfo.Align;
1962
0
    break;
1963
0
  }
1964
1965
165
  case Type::Builtin:
1966
165
    switch (cast<BuiltinType>(T)->getKind()) {
1967
0
    default: llvm_unreachable("Unknown builtin type!");
1968
0
    case BuiltinType::Void:
1969
      // GCC extension: alignof(void) = 8 bits.
1970
0
      Width = 0;
1971
0
      Align = 8;
1972
0
      break;
1973
0
    case BuiltinType::Bool:
1974
0
      Width = Target->getBoolWidth();
1975
0
      Align = Target->getBoolAlign();
1976
0
      break;
1977
46
    case BuiltinType::Char_S:
1978
46
    case BuiltinType::Char_U:
1979
46
    case BuiltinType::UChar:
1980
46
    case BuiltinType::SChar:
1981
46
    case BuiltinType::Char8:
1982
46
      Width = Target->getCharWidth();
1983
46
      Align = Target->getCharAlign();
1984
46
      break;
1985
0
    case BuiltinType::WChar_S:
1986
0
    case BuiltinType::WChar_U:
1987
0
      Width = Target->getWCharWidth();
1988
0
      Align = Target->getWCharAlign();
1989
0
      break;
1990
0
    case BuiltinType::Char16:
1991
0
      Width = Target->getChar16Width();
1992
0
      Align = Target->getChar16Align();
1993
0
      break;
1994
0
    case BuiltinType::Char32:
1995
0
      Width = Target->getChar32Width();
1996
0
      Align = Target->getChar32Align();
1997
0
      break;
1998
0
    case BuiltinType::UShort:
1999
23
    case BuiltinType::Short:
2000
23
      Width = Target->getShortWidth();
2001
23
      Align = Target->getShortAlign();
2002
23
      break;
2003
0
    case BuiltinType::UInt:
2004
25
    case BuiltinType::Int:
2005
25
      Width = Target->getIntWidth();
2006
25
      Align = Target->getIntAlign();
2007
25
      break;
2008
46
    case BuiltinType::ULong:
2009
71
    case BuiltinType::Long:
2010
71
      Width = Target->getLongWidth();
2011
71
      Align = Target->getLongAlign();
2012
71
      break;
2013
0
    case BuiltinType::ULongLong:
2014
0
    case BuiltinType::LongLong:
2015
0
      Width = Target->getLongLongWidth();
2016
0
      Align = Target->getLongLongAlign();
2017
0
      break;
2018
0
    case BuiltinType::Int128:
2019
0
    case BuiltinType::UInt128:
2020
0
      Width = 128;
2021
0
      Align = Target->getInt128Align();
2022
0
      break;
2023
0
    case BuiltinType::ShortAccum:
2024
0
    case BuiltinType::UShortAccum:
2025
0
    case BuiltinType::SatShortAccum:
2026
0
    case BuiltinType::SatUShortAccum:
2027
0
      Width = Target->getShortAccumWidth();
2028
0
      Align = Target->getShortAccumAlign();
2029
0
      break;
2030
0
    case BuiltinType::Accum:
2031
0
    case BuiltinType::UAccum:
2032
0
    case BuiltinType::SatAccum:
2033
0
    case BuiltinType::SatUAccum:
2034
0
      Width = Target->getAccumWidth();
2035
0
      Align = Target->getAccumAlign();
2036
0
      break;
2037
0
    case BuiltinType::LongAccum:
2038
0
    case BuiltinType::ULongAccum:
2039
0
    case BuiltinType::SatLongAccum:
2040
0
    case BuiltinType::SatULongAccum:
2041
0
      Width = Target->getLongAccumWidth();
2042
0
      Align = Target->getLongAccumAlign();
2043
0
      break;
2044
0
    case BuiltinType::ShortFract:
2045
0
    case BuiltinType::UShortFract:
2046
0
    case BuiltinType::SatShortFract:
2047
0
    case BuiltinType::SatUShortFract:
2048
0
      Width = Target->getShortFractWidth();
2049
0
      Align = Target->getShortFractAlign();
2050
0
      break;
2051
0
    case BuiltinType::Fract:
2052
0
    case BuiltinType::UFract:
2053
0
    case BuiltinType::SatFract:
2054
0
    case BuiltinType::SatUFract:
2055
0
      Width = Target->getFractWidth();
2056
0
      Align = Target->getFractAlign();
2057
0
      break;
2058
0
    case BuiltinType::LongFract:
2059
0
    case BuiltinType::ULongFract:
2060
0
    case BuiltinType::SatLongFract:
2061
0
    case BuiltinType::SatULongFract:
2062
0
      Width = Target->getLongFractWidth();
2063
0
      Align = Target->getLongFractAlign();
2064
0
      break;
2065
0
    case BuiltinType::BFloat16:
2066
0
      if (Target->hasBFloat16Type()) {
2067
0
        Width = Target->getBFloat16Width();
2068
0
        Align = Target->getBFloat16Align();
2069
0
      } else if ((getLangOpts().SYCLIsDevice ||
2070
0
                  (getLangOpts().OpenMP &&
2071
0
                   getLangOpts().OpenMPIsTargetDevice)) &&
2072
0
                 AuxTarget->hasBFloat16Type()) {
2073
0
        Width = AuxTarget->getBFloat16Width();
2074
0
        Align = AuxTarget->getBFloat16Align();
2075
0
      }
2076
0
      break;
2077
0
    case BuiltinType::Float16:
2078
0
    case BuiltinType::Half:
2079
0
      if (Target->hasFloat16Type() || !getLangOpts().OpenMP ||
2080
0
          !getLangOpts().OpenMPIsTargetDevice) {
2081
0
        Width = Target->getHalfWidth();
2082
0
        Align = Target->getHalfAlign();
2083
0
      } else {
2084
0
        assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2085
0
               "Expected OpenMP device compilation.");
2086
0
        Width = AuxTarget->getHalfWidth();
2087
0
        Align = AuxTarget->getHalfAlign();
2088
0
      }
2089
0
      break;
2090
0
    case BuiltinType::Float:
2091
0
      Width = Target->getFloatWidth();
2092
0
      Align = Target->getFloatAlign();
2093
0
      break;
2094
0
    case BuiltinType::Double:
2095
0
      Width = Target->getDoubleWidth();
2096
0
      Align = Target->getDoubleAlign();
2097
0
      break;
2098
0
    case BuiltinType::Ibm128:
2099
0
      Width = Target->getIbm128Width();
2100
0
      Align = Target->getIbm128Align();
2101
0
      break;
2102
0
    case BuiltinType::LongDouble:
2103
0
      if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2104
0
          (Target->getLongDoubleWidth() != AuxTarget->getLongDoubleWidth() ||
2105
0
           Target->getLongDoubleAlign() != AuxTarget->getLongDoubleAlign())) {
2106
0
        Width = AuxTarget->getLongDoubleWidth();
2107
0
        Align = AuxTarget->getLongDoubleAlign();
2108
0
      } else {
2109
0
        Width = Target->getLongDoubleWidth();
2110
0
        Align = Target->getLongDoubleAlign();
2111
0
      }
2112
0
      break;
2113
0
    case BuiltinType::Float128:
2114
0
      if (Target->hasFloat128Type() || !getLangOpts().OpenMP ||
2115
0
          !getLangOpts().OpenMPIsTargetDevice) {
2116
0
        Width = Target->getFloat128Width();
2117
0
        Align = Target->getFloat128Align();
2118
0
      } else {
2119
0
        assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2120
0
               "Expected OpenMP device compilation.");
2121
0
        Width = AuxTarget->getFloat128Width();
2122
0
        Align = AuxTarget->getFloat128Align();
2123
0
      }
2124
0
      break;
2125
0
    case BuiltinType::NullPtr:
2126
      // C++ 3.9.1p11: sizeof(nullptr_t) == sizeof(void*)
2127
0
      Width = Target->getPointerWidth(LangAS::Default);
2128
0
      Align = Target->getPointerAlign(LangAS::Default);
2129
0
      break;
2130
0
    case BuiltinType::ObjCId:
2131
0
    case BuiltinType::ObjCClass:
2132
0
    case BuiltinType::ObjCSel:
2133
0
      Width = Target->getPointerWidth(LangAS::Default);
2134
0
      Align = Target->getPointerAlign(LangAS::Default);
2135
0
      break;
2136
0
    case BuiltinType::OCLSampler:
2137
0
    case BuiltinType::OCLEvent:
2138
0
    case BuiltinType::OCLClkEvent:
2139
0
    case BuiltinType::OCLQueue:
2140
0
    case BuiltinType::OCLReserveID:
2141
0
#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2142
0
    case BuiltinType::Id:
2143
0
#include "clang/Basic/OpenCLImageTypes.def"
2144
0
#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2145
0
  case BuiltinType::Id:
2146
0
#include "clang/Basic/OpenCLExtensionTypes.def"
2147
0
      AS = Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
2148
0
      Width = Target->getPointerWidth(AS);
2149
0
      Align = Target->getPointerAlign(AS);
2150
0
      break;
2151
    // The SVE types are effectively target-specific.  The length of an
2152
    // SVE_VECTOR_TYPE is only known at runtime, but it is always a multiple
2153
    // of 128 bits.  There is one predicate bit for each vector byte, so the
2154
    // length of an SVE_PREDICATE_TYPE is always a multiple of 16 bits.
2155
    //
2156
    // Because the length is only known at runtime, we use a dummy value
2157
    // of 0 for the static length.  The alignment values are those defined
2158
    // by the Procedure Call Standard for the Arm Architecture.
2159
0
#define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId, NumEls, ElBits,    \
2160
0
                        IsSigned, IsFP, IsBF)                                  \
2161
0
  case BuiltinType::Id:                                                        \
2162
0
    Width = 0;                                                                 \
2163
0
    Align = 128;                                                               \
2164
0
    break;
2165
0
#define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId, NumEls)         \
2166
0
  case BuiltinType::Id:                                                        \
2167
0
    Width = 0;                                                                 \
2168
0
    Align = 16;                                                                \
2169
0
    break;
2170
0
#define SVE_OPAQUE_TYPE(Name, MangledName, Id, SingletonId)                    \
2171
0
  case BuiltinType::Id:                                                        \
2172
0
    Width = 0;                                                                 \
2173
0
    Align = 16;                                                                \
2174
0
    break;
2175
0
#include "clang/Basic/AArch64SVEACLETypes.def"
2176
0
#define PPC_VECTOR_TYPE(Name, Id, Size)                                        \
2177
0
  case BuiltinType::Id:                                                        \
2178
0
    Width = Size;                                                              \
2179
0
    Align = Size;                                                              \
2180
0
    break;
2181
0
#include "clang/Basic/PPCTypes.def"
2182
0
#define RVV_VECTOR_TYPE(Name, Id, SingletonId, ElKind, ElBits, NF, IsSigned,   \
2183
0
                        IsFP, IsBF)                                            \
2184
0
  case BuiltinType::Id:                                                        \
2185
0
    Width = 0;                                                                 \
2186
0
    Align = ElBits;                                                            \
2187
0
    break;
2188
0
#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, ElKind)                      \
2189
0
  case BuiltinType::Id:                                                        \
2190
0
    Width = 0;                                                                 \
2191
0
    Align = 8;                                                                 \
2192
0
    break;
2193
0
#include "clang/Basic/RISCVVTypes.def"
2194
0
#define WASM_TYPE(Name, Id, SingletonId)                                       \
2195
0
  case BuiltinType::Id:                                                        \
2196
0
    Width = 0;                                                                 \
2197
0
    Align = 8;                                                                 \
2198
0
    break;
2199
165
#include "clang/Basic/WebAssemblyReferenceTypes.def"
2200
165
    }
2201
165
    break;
2202
165
  case Type::ObjCObjectPointer:
2203
46
    Width = Target->getPointerWidth(LangAS::Default);
2204
46
    Align = Target->getPointerAlign(LangAS::Default);
2205
46
    break;
2206
0
  case Type::BlockPointer:
2207
0
    AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
2208
0
    Width = Target->getPointerWidth(AS);
2209
0
    Align = Target->getPointerAlign(AS);
2210
0
    break;
2211
0
  case Type::LValueReference:
2212
0
  case Type::RValueReference:
2213
    // alignof and sizeof should never enter this code path here, so we go
2214
    // the pointer route.
2215
0
    AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
2216
0
    Width = Target->getPointerWidth(AS);
2217
0
    Align = Target->getPointerAlign(AS);
2218
0
    break;
2219
46
  case Type::Pointer:
2220
46
    AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
2221
46
    Width = Target->getPointerWidth(AS);
2222
46
    Align = Target->getPointerAlign(AS);
2223
46
    break;
2224
0
  case Type::MemberPointer: {
2225
0
    const auto *MPT = cast<MemberPointerType>(T);
2226
0
    CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT);
2227
0
    Width = MPI.Width;
2228
0
    Align = MPI.Align;
2229
0
    break;
2230
0
  }
2231
0
  case Type::Complex: {
2232
    // Complex types have the same alignment as their elements, but twice the
2233
    // size.
2234
0
    TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
2235
0
    Width = EltInfo.Width * 2;
2236
0
    Align = EltInfo.Align;
2237
0
    break;
2238
0
  }
2239
0
  case Type::ObjCObject:
2240
0
    return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
2241
0
  case Type::Adjusted:
2242
0
  case Type::Decayed:
2243
0
    return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
2244
0
  case Type::ObjCInterface: {
2245
0
    const auto *ObjCI = cast<ObjCInterfaceType>(T);
2246
0
    if (ObjCI->getDecl()->isInvalidDecl()) {
2247
0
      Width = 8;
2248
0
      Align = 8;
2249
0
      break;
2250
0
    }
2251
0
    const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2252
0
    Width = toBits(Layout.getSize());
2253
0
    Align = toBits(Layout.getAlignment());
2254
0
    break;
2255
0
  }
2256
0
  case Type::BitInt: {
2257
0
    const auto *EIT = cast<BitIntType>(T);
2258
0
    Align = std::clamp<unsigned>(llvm::PowerOf2Ceil(EIT->getNumBits()),
2259
0
                                 getCharWidth(), Target->getLongLongAlign());
2260
0
    Width = llvm::alignTo(EIT->getNumBits(), Align);
2261
0
    break;
2262
0
  }
2263
0
  case Type::Record:
2264
0
  case Type::Enum: {
2265
0
    const auto *TT = cast<TagType>(T);
2266
2267
0
    if (TT->getDecl()->isInvalidDecl()) {
2268
0
      Width = 8;
2269
0
      Align = 8;
2270
0
      break;
2271
0
    }
2272
2273
0
    if (const auto *ET = dyn_cast<EnumType>(TT)) {
2274
0
      const EnumDecl *ED = ET->getDecl();
2275
0
      TypeInfo Info =
2276
0
          getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType());
2277
0
      if (unsigned AttrAlign = ED->getMaxAlignment()) {
2278
0
        Info.Align = AttrAlign;
2279
0
        Info.AlignRequirement = AlignRequirementKind::RequiredByEnum;
2280
0
      }
2281
0
      return Info;
2282
0
    }
2283
2284
0
    const auto *RT = cast<RecordType>(TT);
2285
0
    const RecordDecl *RD = RT->getDecl();
2286
0
    const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2287
0
    Width = toBits(Layout.getSize());
2288
0
    Align = toBits(Layout.getAlignment());
2289
0
    AlignRequirement = RD->hasAttr<AlignedAttr>()
2290
0
                           ? AlignRequirementKind::RequiredByRecord
2291
0
                           : AlignRequirementKind::None;
2292
0
    break;
2293
0
  }
2294
2295
0
  case Type::SubstTemplateTypeParm:
2296
0
    return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
2297
0
                       getReplacementType().getTypePtr());
2298
2299
0
  case Type::Auto:
2300
0
  case Type::DeducedTemplateSpecialization: {
2301
0
    const auto *A = cast<DeducedType>(T);
2302
0
    assert(!A->getDeducedType().isNull() &&
2303
0
           "cannot request the size of an undeduced or dependent auto type");
2304
0
    return getTypeInfo(A->getDeducedType().getTypePtr());
2305
0
  }
2306
2307
0
  case Type::Paren:
2308
0
    return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
2309
2310
0
  case Type::MacroQualified:
2311
0
    return getTypeInfo(
2312
0
        cast<MacroQualifiedType>(T)->getUnderlyingType().getTypePtr());
2313
2314
0
  case Type::ObjCTypeParam:
2315
0
    return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr());
2316
2317
0
  case Type::Using:
2318
0
    return getTypeInfo(cast<UsingType>(T)->desugar().getTypePtr());
2319
2320
69
  case Type::Typedef: {
2321
69
    const auto *TT = cast<TypedefType>(T);
2322
69
    TypeInfo Info = getTypeInfo(TT->desugar().getTypePtr());
2323
    // If the typedef has an aligned attribute on it, it overrides any computed
2324
    // alignment we have.  This violates the GCC documentation (which says that
2325
    // attribute(aligned) can only round up) but matches its implementation.
2326
69
    if (unsigned AttrAlign = TT->getDecl()->getMaxAlignment()) {
2327
0
      Align = AttrAlign;
2328
0
      AlignRequirement = AlignRequirementKind::RequiredByTypedef;
2329
69
    } else {
2330
69
      Align = Info.Align;
2331
69
      AlignRequirement = Info.AlignRequirement;
2332
69
    }
2333
69
    Width = Info.Width;
2334
69
    break;
2335
0
  }
2336
2337
0
  case Type::Elaborated:
2338
0
    return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
2339
2340
0
  case Type::Attributed:
2341
0
    return getTypeInfo(
2342
0
                  cast<AttributedType>(T)->getEquivalentType().getTypePtr());
2343
2344
0
  case Type::BTFTagAttributed:
2345
0
    return getTypeInfo(
2346
0
        cast<BTFTagAttributedType>(T)->getWrappedType().getTypePtr());
2347
2348
0
  case Type::Atomic: {
2349
    // Start with the base type information.
2350
0
    TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
2351
0
    Width = Info.Width;
2352
0
    Align = Info.Align;
2353
2354
0
    if (!Width) {
2355
      // An otherwise zero-sized type should still generate an
2356
      // atomic operation.
2357
0
      Width = Target->getCharWidth();
2358
0
      assert(Align);
2359
0
    } else if (Width <= Target->getMaxAtomicPromoteWidth()) {
2360
      // If the size of the type doesn't exceed the platform's max
2361
      // atomic promotion width, make the size and alignment more
2362
      // favorable to atomic operations:
2363
2364
      // Round the size up to a power of 2.
2365
0
      Width = llvm::bit_ceil(Width);
2366
2367
      // Set the alignment equal to the size.
2368
0
      Align = static_cast<unsigned>(Width);
2369
0
    }
2370
0
  }
2371
0
  break;
2372
2373
0
  case Type::Pipe:
2374
0
    Width = Target->getPointerWidth(LangAS::opencl_global);
2375
0
    Align = Target->getPointerAlign(LangAS::opencl_global);
2376
0
    break;
2377
326
  }
2378
2379
326
  assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
2380
0
  return TypeInfo(Width, Align, AlignRequirement);
2381
326
}
2382
2383
0
unsigned ASTContext::getTypeUnadjustedAlign(const Type *T) const {
2384
0
  UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(T);
2385
0
  if (I != MemoizedUnadjustedAlign.end())
2386
0
    return I->second;
2387
2388
0
  unsigned UnadjustedAlign;
2389
0
  if (const auto *RT = T->getAs<RecordType>()) {
2390
0
    const RecordDecl *RD = RT->getDecl();
2391
0
    const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2392
0
    UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2393
0
  } else if (const auto *ObjCI = T->getAs<ObjCInterfaceType>()) {
2394
0
    const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2395
0
    UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2396
0
  } else {
2397
0
    UnadjustedAlign = getTypeAlign(T->getUnqualifiedDesugaredType());
2398
0
  }
2399
2400
0
  MemoizedUnadjustedAlign[T] = UnadjustedAlign;
2401
0
  return UnadjustedAlign;
2402
0
}
2403
2404
0
unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
2405
0
  unsigned SimdAlign = llvm::OpenMPIRBuilder::getOpenMPDefaultSimdAlign(
2406
0
      getTargetInfo().getTriple(), Target->getTargetOpts().FeatureMap);
2407
0
  return SimdAlign;
2408
0
}
2409
2410
/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
2411
841
CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
2412
841
  return CharUnits::fromQuantity(BitSize / getCharWidth());
2413
841
}
2414
2415
/// toBits - Convert a size in characters to a size in characters.
2416
782
int64_t ASTContext::toBits(CharUnits CharSize) const {
2417
782
  return CharSize.getQuantity() * getCharWidth();
2418
782
}
2419
2420
/// getTypeSizeInChars - Return the size of the specified type, in characters.
2421
/// This method does not work on incomplete types.
2422
52
CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
2423
52
  return getTypeInfoInChars(T).Width;
2424
52
}
2425
0
CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
2426
0
  return getTypeInfoInChars(T).Width;
2427
0
}
2428
2429
/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
2430
/// characters. This method does not work on incomplete types.
2431
47
CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
2432
47
  return toCharUnitsFromBits(getTypeAlign(T));
2433
47
}
2434
0
CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
2435
0
  return toCharUnitsFromBits(getTypeAlign(T));
2436
0
}
2437
2438
/// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a
2439
/// type, in characters, before alignment adjustments. This method does
2440
/// not work on incomplete types.
2441
0
CharUnits ASTContext::getTypeUnadjustedAlignInChars(QualType T) const {
2442
0
  return toCharUnitsFromBits(getTypeUnadjustedAlign(T));
2443
0
}
2444
0
CharUnits ASTContext::getTypeUnadjustedAlignInChars(const Type *T) const {
2445
0
  return toCharUnitsFromBits(getTypeUnadjustedAlign(T));
2446
0
}
2447
2448
/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
2449
/// type for the current target in bits.  This can be different than the ABI
2450
/// alignment in cases where it is beneficial for performance or backwards
2451
/// compatibility preserving to overalign a data type. (Note: despite the name,
2452
/// the preferred alignment is ABI-impacting, and not an optimization.)
2453
0
unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
2454
0
  TypeInfo TI = getTypeInfo(T);
2455
0
  unsigned ABIAlign = TI.Align;
2456
2457
0
  T = T->getBaseElementTypeUnsafe();
2458
2459
  // The preferred alignment of member pointers is that of a pointer.
2460
0
  if (T->isMemberPointerType())
2461
0
    return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
2462
2463
0
  if (!Target->allowsLargerPreferedTypeAlignment())
2464
0
    return ABIAlign;
2465
2466
0
  if (const auto *RT = T->getAs<RecordType>()) {
2467
0
    const RecordDecl *RD = RT->getDecl();
2468
2469
    // When used as part of a typedef, or together with a 'packed' attribute,
2470
    // the 'aligned' attribute can be used to decrease alignment. Note that the
2471
    // 'packed' case is already taken into consideration when computing the
2472
    // alignment, we only need to handle the typedef case here.
2473
0
    if (TI.AlignRequirement == AlignRequirementKind::RequiredByTypedef ||
2474
0
        RD->isInvalidDecl())
2475
0
      return ABIAlign;
2476
2477
0
    unsigned PreferredAlign = static_cast<unsigned>(
2478
0
        toBits(getASTRecordLayout(RD).PreferredAlignment));
2479
0
    assert(PreferredAlign >= ABIAlign &&
2480
0
           "PreferredAlign should be at least as large as ABIAlign.");
2481
0
    return PreferredAlign;
2482
0
  }
2483
2484
  // Double (and, for targets supporting AIX `power` alignment, long double) and
2485
  // long long should be naturally aligned (despite requiring less alignment) if
2486
  // possible.
2487
0
  if (const auto *CT = T->getAs<ComplexType>())
2488
0
    T = CT->getElementType().getTypePtr();
2489
0
  if (const auto *ET = T->getAs<EnumType>())
2490
0
    T = ET->getDecl()->getIntegerType().getTypePtr();
2491
0
  if (T->isSpecificBuiltinType(BuiltinType::Double) ||
2492
0
      T->isSpecificBuiltinType(BuiltinType::LongLong) ||
2493
0
      T->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2494
0
      (T->isSpecificBuiltinType(BuiltinType::LongDouble) &&
2495
0
       Target->defaultsToAIXPowerAlignment()))
2496
    // Don't increase the alignment if an alignment attribute was specified on a
2497
    // typedef declaration.
2498
0
    if (!TI.isAlignRequired())
2499
0
      return std::max(ABIAlign, (unsigned)getTypeSize(T));
2500
2501
0
  return ABIAlign;
2502
0
}
2503
2504
/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2505
/// for __attribute__((aligned)) on this target, to be used if no alignment
2506
/// value is specified.
2507
0
unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const {
2508
0
  return getTargetInfo().getDefaultAlignForAttributeAligned();
2509
0
}
2510
2511
/// getAlignOfGlobalVar - Return the alignment in bits that should be given
2512
/// to a global variable of the specified type.
2513
0
unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
2514
0
  uint64_t TypeSize = getTypeSize(T.getTypePtr());
2515
0
  return std::max(getPreferredTypeAlign(T),
2516
0
                  getTargetInfo().getMinGlobalAlign(TypeSize));
2517
0
}
2518
2519
/// getAlignOfGlobalVarInChars - Return the alignment in characters that
2520
/// should be given to a global variable of the specified type.
2521
0
CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
2522
0
  return toCharUnitsFromBits(getAlignOfGlobalVar(T));
2523
0
}
2524
2525
0
CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
2526
0
  CharUnits Offset = CharUnits::Zero();
2527
0
  const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
2528
0
  while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2529
0
    Offset += Layout->getBaseClassOffset(Base);
2530
0
    Layout = &getASTRecordLayout(Base);
2531
0
  }
2532
0
  return Offset;
2533
0
}
2534
2535
0
CharUnits ASTContext::getMemberPointerPathAdjustment(const APValue &MP) const {
2536
0
  const ValueDecl *MPD = MP.getMemberPointerDecl();
2537
0
  CharUnits ThisAdjustment = CharUnits::Zero();
2538
0
  ArrayRef<const CXXRecordDecl*> Path = MP.getMemberPointerPath();
2539
0
  bool DerivedMember = MP.isMemberPointerToDerivedMember();
2540
0
  const CXXRecordDecl *RD = cast<CXXRecordDecl>(MPD->getDeclContext());
2541
0
  for (unsigned I = 0, N = Path.size(); I != N; ++I) {
2542
0
    const CXXRecordDecl *Base = RD;
2543
0
    const CXXRecordDecl *Derived = Path[I];
2544
0
    if (DerivedMember)
2545
0
      std::swap(Base, Derived);
2546
0
    ThisAdjustment += getASTRecordLayout(Derived).getBaseClassOffset(Base);
2547
0
    RD = Path[I];
2548
0
  }
2549
0
  if (DerivedMember)
2550
0
    ThisAdjustment = -ThisAdjustment;
2551
0
  return ThisAdjustment;
2552
0
}
2553
2554
/// DeepCollectObjCIvars -
2555
/// This routine first collects all declared, but not synthesized, ivars in
2556
/// super class and then collects all ivars, including those synthesized for
2557
/// current class. This routine is used for implementation of current class
2558
/// when all ivars, declared and synthesized are known.
2559
void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
2560
                                      bool leafClass,
2561
0
                            SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
2562
0
  if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2563
0
    DeepCollectObjCIvars(SuperClass, false, Ivars);
2564
0
  if (!leafClass) {
2565
0
    llvm::append_range(Ivars, OI->ivars());
2566
0
  } else {
2567
0
    auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
2568
0
    for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
2569
0
         Iv= Iv->getNextIvar())
2570
0
      Ivars.push_back(Iv);
2571
0
  }
2572
0
}
2573
2574
/// CollectInheritedProtocols - Collect all protocols in current class and
2575
/// those inherited by it.
2576
void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
2577
0
                          llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
2578
0
  if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
2579
    // We can use protocol_iterator here instead of
2580
    // all_referenced_protocol_iterator since we are walking all categories.
2581
0
    for (auto *Proto : OI->all_referenced_protocols()) {
2582
0
      CollectInheritedProtocols(Proto, Protocols);
2583
0
    }
2584
2585
    // Categories of this Interface.
2586
0
    for (const auto *Cat : OI->visible_categories())
2587
0
      CollectInheritedProtocols(Cat, Protocols);
2588
2589
0
    if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2590
0
      while (SD) {
2591
0
        CollectInheritedProtocols(SD, Protocols);
2592
0
        SD = SD->getSuperClass();
2593
0
      }
2594
0
  } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
2595
0
    for (auto *Proto : OC->protocols()) {
2596
0
      CollectInheritedProtocols(Proto, Protocols);
2597
0
    }
2598
0
  } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
2599
    // Insert the protocol.
2600
0
    if (!Protocols.insert(
2601
0
          const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2602
0
      return;
2603
2604
0
    for (auto *Proto : OP->protocols())
2605
0
      CollectInheritedProtocols(Proto, Protocols);
2606
0
  }
2607
0
}
2608
2609
static bool unionHasUniqueObjectRepresentations(const ASTContext &Context,
2610
                                                const RecordDecl *RD,
2611
0
                                                bool CheckIfTriviallyCopyable) {
2612
0
  assert(RD->isUnion() && "Must be union type");
2613
0
  CharUnits UnionSize = Context.getTypeSizeInChars(RD->getTypeForDecl());
2614
2615
0
  for (const auto *Field : RD->fields()) {
2616
0
    if (!Context.hasUniqueObjectRepresentations(Field->getType(),
2617
0
                                                CheckIfTriviallyCopyable))
2618
0
      return false;
2619
0
    CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType());
2620
0
    if (FieldSize != UnionSize)
2621
0
      return false;
2622
0
  }
2623
0
  return !RD->field_empty();
2624
0
}
2625
2626
static int64_t getSubobjectOffset(const FieldDecl *Field,
2627
                                  const ASTContext &Context,
2628
0
                                  const clang::ASTRecordLayout & /*Layout*/) {
2629
0
  return Context.getFieldOffset(Field);
2630
0
}
2631
2632
static int64_t getSubobjectOffset(const CXXRecordDecl *RD,
2633
                                  const ASTContext &Context,
2634
0
                                  const clang::ASTRecordLayout &Layout) {
2635
0
  return Context.toBits(Layout.getBaseClassOffset(RD));
2636
0
}
2637
2638
static std::optional<int64_t>
2639
structHasUniqueObjectRepresentations(const ASTContext &Context,
2640
                                     const RecordDecl *RD,
2641
                                     bool CheckIfTriviallyCopyable);
2642
2643
static std::optional<int64_t>
2644
getSubobjectSizeInBits(const FieldDecl *Field, const ASTContext &Context,
2645
0
                       bool CheckIfTriviallyCopyable) {
2646
0
  if (Field->getType()->isRecordType()) {
2647
0
    const RecordDecl *RD = Field->getType()->getAsRecordDecl();
2648
0
    if (!RD->isUnion())
2649
0
      return structHasUniqueObjectRepresentations(Context, RD,
2650
0
                                                  CheckIfTriviallyCopyable);
2651
0
  }
2652
2653
  // A _BitInt type may not be unique if it has padding bits
2654
  // but if it is a bitfield the padding bits are not used.
2655
0
  bool IsBitIntType = Field->getType()->isBitIntType();
2656
0
  if (!Field->getType()->isReferenceType() && !IsBitIntType &&
2657
0
      !Context.hasUniqueObjectRepresentations(Field->getType(),
2658
0
                                              CheckIfTriviallyCopyable))
2659
0
    return std::nullopt;
2660
2661
0
  int64_t FieldSizeInBits =
2662
0
      Context.toBits(Context.getTypeSizeInChars(Field->getType()));
2663
0
  if (Field->isBitField()) {
2664
    // If we have explicit padding bits, they don't contribute bits
2665
    // to the actual object representation, so return 0.
2666
0
    if (Field->isUnnamedBitfield())
2667
0
      return 0;
2668
2669
0
    int64_t BitfieldSize = Field->getBitWidthValue(Context);
2670
0
    if (IsBitIntType) {
2671
0
      if ((unsigned)BitfieldSize >
2672
0
          cast<BitIntType>(Field->getType())->getNumBits())
2673
0
        return std::nullopt;
2674
0
    } else if (BitfieldSize > FieldSizeInBits) {
2675
0
      return std::nullopt;
2676
0
    }
2677
0
    FieldSizeInBits = BitfieldSize;
2678
0
  } else if (IsBitIntType && !Context.hasUniqueObjectRepresentations(
2679
0
                                 Field->getType(), CheckIfTriviallyCopyable)) {
2680
0
    return std::nullopt;
2681
0
  }
2682
0
  return FieldSizeInBits;
2683
0
}
2684
2685
static std::optional<int64_t>
2686
getSubobjectSizeInBits(const CXXRecordDecl *RD, const ASTContext &Context,
2687
0
                       bool CheckIfTriviallyCopyable) {
2688
0
  return structHasUniqueObjectRepresentations(Context, RD,
2689
0
                                              CheckIfTriviallyCopyable);
2690
0
}
2691
2692
template <typename RangeT>
2693
static std::optional<int64_t> structSubobjectsHaveUniqueObjectRepresentations(
2694
    const RangeT &Subobjects, int64_t CurOffsetInBits,
2695
    const ASTContext &Context, const clang::ASTRecordLayout &Layout,
2696
0
    bool CheckIfTriviallyCopyable) {
2697
0
  for (const auto *Subobject : Subobjects) {
2698
0
    std::optional<int64_t> SizeInBits =
2699
0
        getSubobjectSizeInBits(Subobject, Context, CheckIfTriviallyCopyable);
2700
0
    if (!SizeInBits)
2701
0
      return std::nullopt;
2702
0
    if (*SizeInBits != 0) {
2703
0
      int64_t Offset = getSubobjectOffset(Subobject, Context, Layout);
2704
0
      if (Offset != CurOffsetInBits)
2705
0
        return std::nullopt;
2706
0
      CurOffsetInBits += *SizeInBits;
2707
0
    }
2708
0
  }
2709
0
  return CurOffsetInBits;
2710
0
}
Unexecuted instantiation: ASTContext.cpp:std::__1::optional<long> structSubobjectsHaveUniqueObjectRepresentations<llvm::SmallVector<clang::CXXRecordDecl*, 4u> >(llvm::SmallVector<clang::CXXRecordDecl*, 4u> const&, long, clang::ASTContext const&, clang::ASTRecordLayout const&, bool)
Unexecuted instantiation: ASTContext.cpp:std::__1::optional<long> structSubobjectsHaveUniqueObjectRepresentations<llvm::iterator_range<clang::DeclContext::specific_decl_iterator<clang::FieldDecl> > >(llvm::iterator_range<clang::DeclContext::specific_decl_iterator<clang::FieldDecl> > const&, long, clang::ASTContext const&, clang::ASTRecordLayout const&, bool)
2711
2712
static std::optional<int64_t>
2713
structHasUniqueObjectRepresentations(const ASTContext &Context,
2714
                                     const RecordDecl *RD,
2715
0
                                     bool CheckIfTriviallyCopyable) {
2716
0
  assert(!RD->isUnion() && "Must be struct/class type");
2717
0
  const auto &Layout = Context.getASTRecordLayout(RD);
2718
2719
0
  int64_t CurOffsetInBits = 0;
2720
0
  if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) {
2721
0
    if (ClassDecl->isDynamicClass())
2722
0
      return std::nullopt;
2723
2724
0
    SmallVector<CXXRecordDecl *, 4> Bases;
2725
0
    for (const auto &Base : ClassDecl->bases()) {
2726
      // Empty types can be inherited from, and non-empty types can potentially
2727
      // have tail padding, so just make sure there isn't an error.
2728
0
      Bases.emplace_back(Base.getType()->getAsCXXRecordDecl());
2729
0
    }
2730
2731
0
    llvm::sort(Bases, [&](const CXXRecordDecl *L, const CXXRecordDecl *R) {
2732
0
      return Layout.getBaseClassOffset(L) < Layout.getBaseClassOffset(R);
2733
0
    });
2734
2735
0
    std::optional<int64_t> OffsetAfterBases =
2736
0
        structSubobjectsHaveUniqueObjectRepresentations(
2737
0
            Bases, CurOffsetInBits, Context, Layout, CheckIfTriviallyCopyable);
2738
0
    if (!OffsetAfterBases)
2739
0
      return std::nullopt;
2740
0
    CurOffsetInBits = *OffsetAfterBases;
2741
0
  }
2742
2743
0
  std::optional<int64_t> OffsetAfterFields =
2744
0
      structSubobjectsHaveUniqueObjectRepresentations(
2745
0
          RD->fields(), CurOffsetInBits, Context, Layout,
2746
0
          CheckIfTriviallyCopyable);
2747
0
  if (!OffsetAfterFields)
2748
0
    return std::nullopt;
2749
0
  CurOffsetInBits = *OffsetAfterFields;
2750
2751
0
  return CurOffsetInBits;
2752
0
}
2753
2754
bool ASTContext::hasUniqueObjectRepresentations(
2755
0
    QualType Ty, bool CheckIfTriviallyCopyable) const {
2756
  // C++17 [meta.unary.prop]:
2757
  //   The predicate condition for a template specialization
2758
  //   has_unique_object_representations<T> shall be satisfied if and only if:
2759
  //     (9.1) - T is trivially copyable, and
2760
  //     (9.2) - any two objects of type T with the same value have the same
2761
  //     object representation, where:
2762
  //     - two objects of array or non-union class type are considered to have
2763
  //       the same value if their respective sequences of direct subobjects
2764
  //       have the same values, and
2765
  //     - two objects of union type are considered to have the same value if
2766
  //       they have the same active member and the corresponding members have
2767
  //       the same value.
2768
  //   The set of scalar types for which this condition holds is
2769
  //   implementation-defined. [ Note: If a type has padding bits, the condition
2770
  //   does not hold; otherwise, the condition holds true for unsigned integral
2771
  //   types. -- end note ]
2772
0
  assert(!Ty.isNull() && "Null QualType sent to unique object rep check");
2773
2774
  // Arrays are unique only if their element type is unique.
2775
0
  if (Ty->isArrayType())
2776
0
    return hasUniqueObjectRepresentations(getBaseElementType(Ty),
2777
0
                                          CheckIfTriviallyCopyable);
2778
2779
  // (9.1) - T is trivially copyable...
2780
0
  if (CheckIfTriviallyCopyable && !Ty.isTriviallyCopyableType(*this))
2781
0
    return false;
2782
2783
  // All integrals and enums are unique.
2784
0
  if (Ty->isIntegralOrEnumerationType()) {
2785
    // Except _BitInt types that have padding bits.
2786
0
    if (const auto *BIT = Ty->getAs<BitIntType>())
2787
0
      return getTypeSize(BIT) == BIT->getNumBits();
2788
2789
0
    return true;
2790
0
  }
2791
2792
  // All other pointers are unique.
2793
0
  if (Ty->isPointerType())
2794
0
    return true;
2795
2796
0
  if (const auto *MPT = Ty->getAs<MemberPointerType>())
2797
0
    return !ABI->getMemberPointerInfo(MPT).HasPadding;
2798
2799
0
  if (Ty->isRecordType()) {
2800
0
    const RecordDecl *Record = Ty->castAs<RecordType>()->getDecl();
2801
2802
0
    if (Record->isInvalidDecl())
2803
0
      return false;
2804
2805
0
    if (Record->isUnion())
2806
0
      return unionHasUniqueObjectRepresentations(*this, Record,
2807
0
                                                 CheckIfTriviallyCopyable);
2808
2809
0
    std::optional<int64_t> StructSize = structHasUniqueObjectRepresentations(
2810
0
        *this, Record, CheckIfTriviallyCopyable);
2811
2812
0
    return StructSize && *StructSize == static_cast<int64_t>(getTypeSize(Ty));
2813
0
  }
2814
2815
  // FIXME: More cases to handle here (list by rsmith):
2816
  // vectors (careful about, eg, vector of 3 foo)
2817
  // _Complex int and friends
2818
  // _Atomic T
2819
  // Obj-C block pointers
2820
  // Obj-C object pointers
2821
  // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t,
2822
  // clk_event_t, queue_t, reserve_id_t)
2823
  // There're also Obj-C class types and the Obj-C selector type, but I think it
2824
  // makes sense for those to return false here.
2825
2826
0
  return false;
2827
0
}
2828
2829
0
unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
2830
0
  unsigned count = 0;
2831
  // Count ivars declared in class extension.
2832
0
  for (const auto *Ext : OI->known_extensions())
2833
0
    count += Ext->ivar_size();
2834
2835
  // Count ivar defined in this class's implementation.  This
2836
  // includes synthesized ivars.
2837
0
  if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
2838
0
    count += ImplDecl->ivar_size();
2839
2840
0
  return count;
2841
0
}
2842
2843
0
bool ASTContext::isSentinelNullExpr(const Expr *E) {
2844
0
  if (!E)
2845
0
    return false;
2846
2847
  // nullptr_t is always treated as null.
2848
0
  if (E->getType()->isNullPtrType()) return true;
2849
2850
0
  if (E->getType()->isAnyPointerType() &&
2851
0
      E->IgnoreParenCasts()->isNullPointerConstant(*this,
2852
0
                                                Expr::NPC_ValueDependentIsNull))
2853
0
    return true;
2854
2855
  // Unfortunately, __null has type 'int'.
2856
0
  if (isa<GNUNullExpr>(E)) return true;
2857
2858
0
  return false;
2859
0
}
2860
2861
/// Get the implementation of ObjCInterfaceDecl, or nullptr if none
2862
/// exists.
2863
0
ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
2864
0
  llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2865
0
    I = ObjCImpls.find(D);
2866
0
  if (I != ObjCImpls.end())
2867
0
    return cast<ObjCImplementationDecl>(I->second);
2868
0
  return nullptr;
2869
0
}
2870
2871
/// Get the implementation of ObjCCategoryDecl, or nullptr if none
2872
/// exists.
2873
0
ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
2874
0
  llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2875
0
    I = ObjCImpls.find(D);
2876
0
  if (I != ObjCImpls.end())
2877
0
    return cast<ObjCCategoryImplDecl>(I->second);
2878
0
  return nullptr;
2879
0
}
2880
2881
/// Set the implementation of ObjCInterfaceDecl.
2882
void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2883
0
                           ObjCImplementationDecl *ImplD) {
2884
0
  assert(IFaceD && ImplD && "Passed null params");
2885
0
  ObjCImpls[IFaceD] = ImplD;
2886
0
}
2887
2888
/// Set the implementation of ObjCCategoryDecl.
2889
void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
2890
0
                           ObjCCategoryImplDecl *ImplD) {
2891
0
  assert(CatD && ImplD && "Passed null params");
2892
0
  ObjCImpls[CatD] = ImplD;
2893
0
}
2894
2895
const ObjCMethodDecl *
2896
0
ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const {
2897
0
  return ObjCMethodRedecls.lookup(MD);
2898
0
}
2899
2900
void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
2901
0
                                            const ObjCMethodDecl *Redecl) {
2902
0
  assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
2903
0
  ObjCMethodRedecls[MD] = Redecl;
2904
0
}
2905
2906
const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
2907
0
                                              const NamedDecl *ND) const {
2908
0
  if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
2909
0
    return ID;
2910
0
  if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
2911
0
    return CD->getClassInterface();
2912
0
  if (const auto *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
2913
0
    return IMD->getClassInterface();
2914
2915
0
  return nullptr;
2916
0
}
2917
2918
/// Get the copy initialization expression of VarDecl, or nullptr if
2919
/// none exists.
2920
0
BlockVarCopyInit ASTContext::getBlockVarCopyInit(const VarDecl *VD) const {
2921
0
  assert(VD && "Passed null params");
2922
0
  assert(VD->hasAttr<BlocksAttr>() &&
2923
0
         "getBlockVarCopyInits - not __block var");
2924
0
  auto I = BlockVarCopyInits.find(VD);
2925
0
  if (I != BlockVarCopyInits.end())
2926
0
    return I->second;
2927
0
  return {nullptr, false};
2928
0
}
2929
2930
/// Set the copy initialization expression of a block var decl.
2931
void ASTContext::setBlockVarCopyInit(const VarDecl*VD, Expr *CopyExpr,
2932
0
                                     bool CanThrow) {
2933
0
  assert(VD && CopyExpr && "Passed null params");
2934
0
  assert(VD->hasAttr<BlocksAttr>() &&
2935
0
         "setBlockVarCopyInits - not __block var");
2936
0
  BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow);
2937
0
}
2938
2939
TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
2940
5.51k
                                                 unsigned DataSize) const {
2941
5.51k
  if (!DataSize)
2942
5.51k
    DataSize = TypeLoc::getFullDataSizeForType(T);
2943
4
  else
2944
4
    assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
2945
5.51k
           "incorrect data size provided to CreateTypeSourceInfo!");
2946
2947
0
  auto *TInfo =
2948
5.51k
    (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
2949
5.51k
  new (TInfo) TypeSourceInfo(T, DataSize);
2950
5.51k
  return TInfo;
2951
5.51k
}
2952
2953
TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
2954
449
                                                     SourceLocation L) const {
2955
449
  TypeSourceInfo *DI = CreateTypeSourceInfo(T);
2956
449
  DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
2957
449
  return DI;
2958
449
}
2959
2960
const ASTRecordLayout &
2961
0
ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
2962
0
  return getObjCLayout(D, nullptr);
2963
0
}
2964
2965
const ASTRecordLayout &
2966
ASTContext::getASTObjCImplementationLayout(
2967
0
                                        const ObjCImplementationDecl *D) const {
2968
0
  return getObjCLayout(D->getClassInterface(), D);
2969
0
}
2970
2971
static auto getCanonicalTemplateArguments(const ASTContext &C,
2972
                                          ArrayRef<TemplateArgument> Args,
2973
0
                                          bool &AnyNonCanonArgs) {
2974
0
  SmallVector<TemplateArgument, 16> CanonArgs(Args);
2975
0
  for (auto &Arg : CanonArgs) {
2976
0
    TemplateArgument OrigArg = Arg;
2977
0
    Arg = C.getCanonicalTemplateArgument(Arg);
2978
0
    AnyNonCanonArgs |= !Arg.structurallyEquals(OrigArg);
2979
0
  }
2980
0
  return CanonArgs;
2981
0
}
2982
2983
//===----------------------------------------------------------------------===//
2984
//                   Type creation/memoization methods
2985
//===----------------------------------------------------------------------===//
2986
2987
QualType
2988
0
ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2989
0
  unsigned fastQuals = quals.getFastQualifiers();
2990
0
  quals.removeFastQualifiers();
2991
2992
  // Check if we've already instantiated this type.
2993
0
  llvm::FoldingSetNodeID ID;
2994
0
  ExtQuals::Profile(ID, baseType, quals);
2995
0
  void *insertPos = nullptr;
2996
0
  if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2997
0
    assert(eq->getQualifiers() == quals);
2998
0
    return QualType(eq, fastQuals);
2999
0
  }
3000
3001
  // If the base type is not canonical, make the appropriate canonical type.
3002
0
  QualType canon;
3003
0
  if (!baseType->isCanonicalUnqualified()) {
3004
0
    SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
3005
0
    canonSplit.Quals.addConsistentQualifiers(quals);
3006
0
    canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
3007
3008
    // Re-find the insert position.
3009
0
    (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
3010
0
  }
3011
3012
0
  auto *eq = new (*this, alignof(ExtQuals)) ExtQuals(baseType, canon, quals);
3013
0
  ExtQualNodes.InsertNode(eq, insertPos);
3014
0
  return QualType(eq, fastQuals);
3015
0
}
3016
3017
QualType ASTContext::getAddrSpaceQualType(QualType T,
3018
0
                                          LangAS AddressSpace) const {
3019
0
  QualType CanT = getCanonicalType(T);
3020
0
  if (CanT.getAddressSpace() == AddressSpace)
3021
0
    return T;
3022
3023
  // If we are composing extended qualifiers together, merge together
3024
  // into one ExtQuals node.
3025
0
  QualifierCollector Quals;
3026
0
  const Type *TypeNode = Quals.strip(T);
3027
3028
  // If this type already has an address space specified, it cannot get
3029
  // another one.
3030
0
  assert(!Quals.hasAddressSpace() &&
3031
0
         "Type cannot be in multiple addr spaces!");
3032
0
  Quals.addAddressSpace(AddressSpace);
3033
3034
0
  return getExtQualType(TypeNode, Quals);
3035
0
}
3036
3037
0
QualType ASTContext::removeAddrSpaceQualType(QualType T) const {
3038
  // If the type is not qualified with an address space, just return it
3039
  // immediately.
3040
0
  if (!T.hasAddressSpace())
3041
0
    return T;
3042
3043
  // If we are composing extended qualifiers together, merge together
3044
  // into one ExtQuals node.
3045
0
  QualifierCollector Quals;
3046
0
  const Type *TypeNode;
3047
3048
0
  while (T.hasAddressSpace()) {
3049
0
    TypeNode = Quals.strip(T);
3050
3051
    // If the type no longer has an address space after stripping qualifiers,
3052
    // jump out.
3053
0
    if (!QualType(TypeNode, 0).hasAddressSpace())
3054
0
      break;
3055
3056
    // There might be sugar in the way. Strip it and try again.
3057
0
    T = T.getSingleStepDesugaredType(*this);
3058
0
  }
3059
3060
0
  Quals.removeAddressSpace();
3061
3062
  // Removal of the address space can mean there are no longer any
3063
  // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts)
3064
  // or required.
3065
0
  if (Quals.hasNonFastQualifiers())
3066
0
    return getExtQualType(TypeNode, Quals);
3067
0
  else
3068
0
    return QualType(TypeNode, Quals.getFastQualifiers());
3069
0
}
3070
3071
QualType ASTContext::getObjCGCQualType(QualType T,
3072
0
                                       Qualifiers::GC GCAttr) const {
3073
0
  QualType CanT = getCanonicalType(T);
3074
0
  if (CanT.getObjCGCAttr() == GCAttr)
3075
0
    return T;
3076
3077
0
  if (const auto *ptr = T->getAs<PointerType>()) {
3078
0
    QualType Pointee = ptr->getPointeeType();
3079
0
    if (Pointee->isAnyPointerType()) {
3080
0
      QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
3081
0
      return getPointerType(ResultType);
3082
0
    }
3083
0
  }
3084
3085
  // If we are composing extended qualifiers together, merge together
3086
  // into one ExtQuals node.
3087
0
  QualifierCollector Quals;
3088
0
  const Type *TypeNode = Quals.strip(T);
3089
3090
  // If this type already has an ObjCGC specified, it cannot get
3091
  // another one.
3092
0
  assert(!Quals.hasObjCGCAttr() &&
3093
0
         "Type cannot have multiple ObjCGCs!");
3094
0
  Quals.addObjCGCAttr(GCAttr);
3095
3096
0
  return getExtQualType(TypeNode, Quals);
3097
0
}
3098
3099
0
QualType ASTContext::removePtrSizeAddrSpace(QualType T) const {
3100
0
  if (const PointerType *Ptr = T->getAs<PointerType>()) {
3101
0
    QualType Pointee = Ptr->getPointeeType();
3102
0
    if (isPtrSizeAddressSpace(Pointee.getAddressSpace())) {
3103
0
      return getPointerType(removeAddrSpaceQualType(Pointee));
3104
0
    }
3105
0
  }
3106
0
  return T;
3107
0
}
3108
3109
const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
3110
0
                                                   FunctionType::ExtInfo Info) {
3111
0
  if (T->getExtInfo() == Info)
3112
0
    return T;
3113
3114
0
  QualType Result;
3115
0
  if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
3116
0
    Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
3117
0
  } else {
3118
0
    const auto *FPT = cast<FunctionProtoType>(T);
3119
0
    FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
3120
0
    EPI.ExtInfo = Info;
3121
0
    Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
3122
0
  }
3123
3124
0
  return cast<FunctionType>(Result.getTypePtr());
3125
0
}
3126
3127
void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
3128
0
                                                 QualType ResultType) {
3129
0
  FD = FD->getMostRecentDecl();
3130
0
  while (true) {
3131
0
    const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
3132
0
    FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
3133
0
    FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
3134
0
    if (FunctionDecl *Next = FD->getPreviousDecl())
3135
0
      FD = Next;
3136
0
    else
3137
0
      break;
3138
0
  }
3139
0
  if (ASTMutationListener *L = getASTMutationListener())
3140
0
    L->DeducedReturnType(FD, ResultType);
3141
0
}
3142
3143
/// Get a function type and produce the equivalent function type with the
3144
/// specified exception specification. Type sugar that can be present on a
3145
/// declaration of a function with an exception specification is permitted
3146
/// and preserved. Other type sugar (for instance, typedefs) is not.
3147
QualType ASTContext::getFunctionTypeWithExceptionSpec(
3148
0
    QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) const {
3149
  // Might have some parens.
3150
0
  if (const auto *PT = dyn_cast<ParenType>(Orig))
3151
0
    return getParenType(
3152
0
        getFunctionTypeWithExceptionSpec(PT->getInnerType(), ESI));
3153
3154
  // Might be wrapped in a macro qualified type.
3155
0
  if (const auto *MQT = dyn_cast<MacroQualifiedType>(Orig))
3156
0
    return getMacroQualifiedType(
3157
0
        getFunctionTypeWithExceptionSpec(MQT->getUnderlyingType(), ESI),
3158
0
        MQT->getMacroIdentifier());
3159
3160
  // Might have a calling-convention attribute.
3161
0
  if (const auto *AT = dyn_cast<AttributedType>(Orig))
3162
0
    return getAttributedType(
3163
0
        AT->getAttrKind(),
3164
0
        getFunctionTypeWithExceptionSpec(AT->getModifiedType(), ESI),
3165
0
        getFunctionTypeWithExceptionSpec(AT->getEquivalentType(), ESI));
3166
3167
  // Anything else must be a function type. Rebuild it with the new exception
3168
  // specification.
3169
0
  const auto *Proto = Orig->castAs<FunctionProtoType>();
3170
0
  return getFunctionType(
3171
0
      Proto->getReturnType(), Proto->getParamTypes(),
3172
0
      Proto->getExtProtoInfo().withExceptionSpec(ESI));
3173
0
}
3174
3175
bool ASTContext::hasSameFunctionTypeIgnoringExceptionSpec(QualType T,
3176
0
                                                          QualType U) const {
3177
0
  return hasSameType(T, U) ||
3178
0
         (getLangOpts().CPlusPlus17 &&
3179
0
          hasSameType(getFunctionTypeWithExceptionSpec(T, EST_None),
3180
0
                      getFunctionTypeWithExceptionSpec(U, EST_None)));
3181
0
}
3182
3183
0
QualType ASTContext::getFunctionTypeWithoutPtrSizes(QualType T) {
3184
0
  if (const auto *Proto = T->getAs<FunctionProtoType>()) {
3185
0
    QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3186
0
    SmallVector<QualType, 16> Args(Proto->param_types().size());
3187
0
    for (unsigned i = 0, n = Args.size(); i != n; ++i)
3188
0
      Args[i] = removePtrSizeAddrSpace(Proto->param_types()[i]);
3189
0
    return getFunctionType(RetTy, Args, Proto->getExtProtoInfo());
3190
0
  }
3191
3192
0
  if (const FunctionNoProtoType *Proto = T->getAs<FunctionNoProtoType>()) {
3193
0
    QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3194
0
    return getFunctionNoProtoType(RetTy, Proto->getExtInfo());
3195
0
  }
3196
3197
0
  return T;
3198
0
}
3199
3200
0
bool ASTContext::hasSameFunctionTypeIgnoringPtrSizes(QualType T, QualType U) {
3201
0
  return hasSameType(T, U) ||
3202
0
         hasSameType(getFunctionTypeWithoutPtrSizes(T),
3203
0
                     getFunctionTypeWithoutPtrSizes(U));
3204
0
}
3205
3206
void ASTContext::adjustExceptionSpec(
3207
    FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
3208
0
    bool AsWritten) {
3209
  // Update the type.
3210
0
  QualType Updated =
3211
0
      getFunctionTypeWithExceptionSpec(FD->getType(), ESI);
3212
0
  FD->setType(Updated);
3213
3214
0
  if (!AsWritten)
3215
0
    return;
3216
3217
  // Update the type in the type source information too.
3218
0
  if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
3219
    // If the type and the type-as-written differ, we may need to update
3220
    // the type-as-written too.
3221
0
    if (TSInfo->getType() != FD->getType())
3222
0
      Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI);
3223
3224
    // FIXME: When we get proper type location information for exceptions,
3225
    // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
3226
    // up the TypeSourceInfo;
3227
0
    assert(TypeLoc::getFullDataSizeForType(Updated) ==
3228
0
               TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
3229
0
           "TypeLoc size mismatch from updating exception specification");
3230
0
    TSInfo->overrideType(Updated);
3231
0
  }
3232
0
}
3233
3234
/// getComplexType - Return the uniqued reference to the type for a complex
3235
/// number with the specified element type.
3236
0
QualType ASTContext::getComplexType(QualType T) const {
3237
  // Unique pointers, to guarantee there is only one pointer of a particular
3238
  // structure.
3239
0
  llvm::FoldingSetNodeID ID;
3240
0
  ComplexType::Profile(ID, T);
3241
3242
0
  void *InsertPos = nullptr;
3243
0
  if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
3244
0
    return QualType(CT, 0);
3245
3246
  // If the pointee type isn't canonical, this won't be a canonical type either,
3247
  // so fill in the canonical type field.
3248
0
  QualType Canonical;
3249
0
  if (!T.isCanonical()) {
3250
0
    Canonical = getComplexType(getCanonicalType(T));
3251
3252
    // Get the new insert position for the node we care about.
3253
0
    ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
3254
0
    assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3255
0
  }
3256
0
  auto *New = new (*this, alignof(ComplexType)) ComplexType(T, Canonical);
3257
0
  Types.push_back(New);
3258
0
  ComplexTypes.InsertNode(New, InsertPos);
3259
0
  return QualType(New, 0);
3260
0
}
3261
3262
/// getPointerType - Return the uniqued reference to the type for a pointer to
3263
/// the specified type.
3264
493
QualType ASTContext::getPointerType(QualType T) const {
3265
  // Unique pointers, to guarantee there is only one pointer of a particular
3266
  // structure.
3267
493
  llvm::FoldingSetNodeID ID;
3268
493
  PointerType::Profile(ID, T);
3269
3270
493
  void *InsertPos = nullptr;
3271
493
  if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3272
210
    return QualType(PT, 0);
3273
3274
  // If the pointee type isn't canonical, this won't be a canonical type either,
3275
  // so fill in the canonical type field.
3276
283
  QualType Canonical;
3277
283
  if (!T.isCanonical()) {
3278
0
    Canonical = getPointerType(getCanonicalType(T));
3279
3280
    // Get the new insert position for the node we care about.
3281
0
    PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3282
0
    assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3283
0
  }
3284
0
  auto *New = new (*this, alignof(PointerType)) PointerType(T, Canonical);
3285
283
  Types.push_back(New);
3286
283
  PointerTypes.InsertNode(New, InsertPos);
3287
283
  return QualType(New, 0);
3288
493
}
3289
3290
0
QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
3291
0
  llvm::FoldingSetNodeID ID;
3292
0
  AdjustedType::Profile(ID, Orig, New);
3293
0
  void *InsertPos = nullptr;
3294
0
  AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3295
0
  if (AT)
3296
0
    return QualType(AT, 0);
3297
3298
0
  QualType Canonical = getCanonicalType(New);
3299
3300
  // Get the new insert position for the node we care about.
3301
0
  AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3302
0
  assert(!AT && "Shouldn't be in the map!");
3303
3304
0
  AT = new (*this, alignof(AdjustedType))
3305
0
      AdjustedType(Type::Adjusted, Orig, New, Canonical);
3306
0
  Types.push_back(AT);
3307
0
  AdjustedTypes.InsertNode(AT, InsertPos);
3308
0
  return QualType(AT, 0);
3309
0
}
3310
3311
0
QualType ASTContext::getDecayedType(QualType Orig, QualType Decayed) const {
3312
0
  llvm::FoldingSetNodeID ID;
3313
0
  AdjustedType::Profile(ID, Orig, Decayed);
3314
0
  void *InsertPos = nullptr;
3315
0
  AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3316
0
  if (AT)
3317
0
    return QualType(AT, 0);
3318
3319
0
  QualType Canonical = getCanonicalType(Decayed);
3320
3321
  // Get the new insert position for the node we care about.
3322
0
  AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3323
0
  assert(!AT && "Shouldn't be in the map!");
3324
3325
0
  AT = new (*this, alignof(DecayedType)) DecayedType(Orig, Decayed, Canonical);
3326
0
  Types.push_back(AT);
3327
0
  AdjustedTypes.InsertNode(AT, InsertPos);
3328
0
  return QualType(AT, 0);
3329
0
}
3330
3331
0
QualType ASTContext::getDecayedType(QualType T) const {
3332
0
  assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
3333
3334
0
  QualType Decayed;
3335
3336
  // C99 6.7.5.3p7:
3337
  //   A declaration of a parameter as "array of type" shall be
3338
  //   adjusted to "qualified pointer to type", where the type
3339
  //   qualifiers (if any) are those specified within the [ and ] of
3340
  //   the array type derivation.
3341
0
  if (T->isArrayType())
3342
0
    Decayed = getArrayDecayedType(T);
3343
3344
  // C99 6.7.5.3p8:
3345
  //   A declaration of a parameter as "function returning type"
3346
  //   shall be adjusted to "pointer to function returning type", as
3347
  //   in 6.3.2.1.
3348
0
  if (T->isFunctionType())
3349
0
    Decayed = getPointerType(T);
3350
3351
0
  return getDecayedType(T, Decayed);
3352
0
}
3353
3354
/// getBlockPointerType - Return the uniqued reference to the type for
3355
/// a pointer to the specified block.
3356
1
QualType ASTContext::getBlockPointerType(QualType T) const {
3357
1
  assert(T->isFunctionType() && "block of function types only");
3358
  // Unique pointers, to guarantee there is only one block of a particular
3359
  // structure.
3360
0
  llvm::FoldingSetNodeID ID;
3361
1
  BlockPointerType::Profile(ID, T);
3362
3363
1
  void *InsertPos = nullptr;
3364
1
  if (BlockPointerType *PT =
3365
1
        BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3366
0
    return QualType(PT, 0);
3367
3368
  // If the block pointee type isn't canonical, this won't be a canonical
3369
  // type either so fill in the canonical type field.
3370
1
  QualType Canonical;
3371
1
  if (!T.isCanonical()) {
3372
0
    Canonical = getBlockPointerType(getCanonicalType(T));
3373
3374
    // Get the new insert position for the node we care about.
3375
0
    BlockPointerType *NewIP =
3376
0
      BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3377
0
    assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3378
0
  }
3379
0
  auto *New =
3380
1
      new (*this, alignof(BlockPointerType)) BlockPointerType(T, Canonical);
3381
1
  Types.push_back(New);
3382
1
  BlockPointerTypes.InsertNode(New, InsertPos);
3383
1
  return QualType(New, 0);
3384
1
}
3385
3386
/// getLValueReferenceType - Return the uniqued reference to the type for an
3387
/// lvalue reference to the specified type.
3388
QualType
3389
57
ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
3390
57
  assert((!T->isPlaceholderType() ||
3391
57
          T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
3392
57
         "Unresolved placeholder type");
3393
3394
  // Unique pointers, to guarantee there is only one pointer of a particular
3395
  // structure.
3396
0
  llvm::FoldingSetNodeID ID;
3397
57
  ReferenceType::Profile(ID, T, SpelledAsLValue);
3398
3399
57
  void *InsertPos = nullptr;
3400
57
  if (LValueReferenceType *RT =
3401
57
        LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
3402
46
    return QualType(RT, 0);
3403
3404
11
  const auto *InnerRef = T->getAs<ReferenceType>();
3405
3406
  // If the referencee type isn't canonical, this won't be a canonical type
3407
  // either, so fill in the canonical type field.
3408
11
  QualType Canonical;
3409
11
  if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
3410
1
    QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
3411
1
    Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
3412
3413
    // Get the new insert position for the node we care about.
3414
1
    LValueReferenceType *NewIP =
3415
1
      LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
3416
1
    assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3417
1
  }
3418
3419
0
  auto *New = new (*this, alignof(LValueReferenceType))
3420
11
      LValueReferenceType(T, Canonical, SpelledAsLValue);
3421
11
  Types.push_back(New);
3422
11
  LValueReferenceTypes.InsertNode(New, InsertPos);
3423
3424
11
  return QualType(New, 0);
3425
57
}
3426
3427
/// getRValueReferenceType - Return the uniqued reference to the type for an
3428
/// rvalue reference to the specified type.
3429
0
QualType ASTContext::getRValueReferenceType(QualType T) const {
3430
0
  assert((!T->isPlaceholderType() ||
3431
0
          T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
3432
0
         "Unresolved placeholder type");
3433
3434
  // Unique pointers, to guarantee there is only one pointer of a particular
3435
  // structure.
3436
0
  llvm::FoldingSetNodeID ID;
3437
0
  ReferenceType::Profile(ID, T, false);
3438
3439
0
  void *InsertPos = nullptr;
3440
0
  if (RValueReferenceType *RT =
3441
0
        RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
3442
0
    return QualType(RT, 0);
3443
3444
0
  const auto *InnerRef = T->getAs<ReferenceType>();
3445
3446
  // If the referencee type isn't canonical, this won't be a canonical type
3447
  // either, so fill in the canonical type field.
3448
0
  QualType Canonical;
3449
0
  if (InnerRef || !T.isCanonical()) {
3450
0
    QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
3451
0
    Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
3452
3453
    // Get the new insert position for the node we care about.
3454
0
    RValueReferenceType *NewIP =
3455
0
      RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
3456
0
    assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3457
0
  }
3458
3459
0
  auto *New = new (*this, alignof(RValueReferenceType))
3460
0
      RValueReferenceType(T, Canonical);
3461
0
  Types.push_back(New);
3462
0
  RValueReferenceTypes.InsertNode(New, InsertPos);
3463
0
  return QualType(New, 0);
3464
0
}
3465
3466
/// getMemberPointerType - Return the uniqued reference to the type for a
3467
/// member pointer to the specified type, in the specified class.
3468
0
QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
3469
  // Unique pointers, to guarantee there is only one pointer of a particular
3470
  // structure.
3471
0
  llvm::FoldingSetNodeID ID;
3472
0
  MemberPointerType::Profile(ID, T, Cls);
3473
3474
0
  void *InsertPos = nullptr;
3475
0
  if (MemberPointerType *PT =
3476
0
      MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3477
0
    return QualType(PT, 0);
3478
3479
  // If the pointee or class type isn't canonical, this won't be a canonical
3480
  // type either, so fill in the canonical type field.
3481
0
  QualType Canonical;
3482
0
  if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
3483
0
    Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
3484
3485
    // Get the new insert position for the node we care about.
3486
0
    MemberPointerType *NewIP =
3487
0
      MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3488
0
    assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3489
0
  }
3490
0
  auto *New = new (*this, alignof(MemberPointerType))
3491
0
      MemberPointerType(T, Cls, Canonical);
3492
0
  Types.push_back(New);
3493
0
  MemberPointerTypes.InsertNode(New, InsertPos);
3494
0
  return QualType(New, 0);
3495
0
}
3496
3497
/// getConstantArrayType - Return the unique reference to the type for an
3498
/// array of the specified element type.
3499
QualType ASTContext::getConstantArrayType(QualType EltTy,
3500
                                          const llvm::APInt &ArySizeIn,
3501
                                          const Expr *SizeExpr,
3502
                                          ArraySizeModifier ASM,
3503
53
                                          unsigned IndexTypeQuals) const {
3504
53
  assert((EltTy->isDependentType() ||
3505
53
          EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
3506
53
         "Constant array of VLAs is illegal!");
3507
3508
  // We only need the size as part of the type if it's instantiation-dependent.
3509
53
  if (SizeExpr && !SizeExpr->isInstantiationDependent())
3510
5
    SizeExpr = nullptr;
3511
3512
  // Convert the array size into a canonical width matching the pointer size for
3513
  // the target.
3514
53
  llvm::APInt ArySize(ArySizeIn);
3515
53
  ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth());
3516
3517
53
  llvm::FoldingSetNodeID ID;
3518
53
  ConstantArrayType::Profile(ID, *this, EltTy, ArySize, SizeExpr, ASM,
3519
53
                             IndexTypeQuals);
3520
3521
53
  void *InsertPos = nullptr;
3522
53
  if (ConstantArrayType *ATP =
3523
53
      ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
3524
0
    return QualType(ATP, 0);
3525
3526
  // If the element type isn't canonical or has qualifiers, or the array bound
3527
  // is instantiation-dependent, this won't be a canonical type either, so fill
3528
  // in the canonical type field.
3529
53
  QualType Canon;
3530
  // FIXME: Check below should look for qualifiers behind sugar.
3531
53
  if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers() || SizeExpr) {
3532
1
    SplitQualType canonSplit = getCanonicalType(EltTy).split();
3533
1
    Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize, nullptr,
3534
1
                                 ASM, IndexTypeQuals);
3535
1
    Canon = getQualifiedType(Canon, canonSplit.Quals);
3536
3537
    // Get the new insert position for the node we care about.
3538
1
    ConstantArrayType *NewIP =
3539
1
      ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
3540
1
    assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3541
1
  }
3542
3543
0
  void *Mem = Allocate(
3544
53
      ConstantArrayType::totalSizeToAlloc<const Expr *>(SizeExpr ? 1 : 0),
3545
53
      alignof(ConstantArrayType));
3546
53
  auto *New = new (Mem)
3547
53
    ConstantArrayType(EltTy, Canon, ArySize, SizeExpr, ASM, IndexTypeQuals);
3548
53
  ConstantArrayTypes.InsertNode(New, InsertPos);
3549
53
  Types.push_back(New);
3550
53
  return QualType(New, 0);
3551
53
}
3552
3553
/// getVariableArrayDecayedType - Turns the given type, which may be
3554
/// variably-modified, into the corresponding type with all the known
3555
/// sizes replaced with [*].
3556
0
QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
3557
  // Vastly most common case.
3558
0
  if (!type->isVariablyModifiedType()) return type;
3559
3560
0
  QualType result;
3561
3562
0
  SplitQualType split = type.getSplitDesugaredType();
3563
0
  const Type *ty = split.Ty;
3564
0
  switch (ty->getTypeClass()) {
3565
0
#define TYPE(Class, Base)
3566
0
#define ABSTRACT_TYPE(Class, Base)
3567
0
#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3568
0
#include "clang/AST/TypeNodes.inc"
3569
0
    llvm_unreachable("didn't desugar past all non-canonical types?");
3570
3571
  // These types should never be variably-modified.
3572
0
  case Type::Builtin:
3573
0
  case Type::Complex:
3574
0
  case Type::Vector:
3575
0
  case Type::DependentVector:
3576
0
  case Type::ExtVector:
3577
0
  case Type::DependentSizedExtVector:
3578
0
  case Type::ConstantMatrix:
3579
0
  case Type::DependentSizedMatrix:
3580
0
  case Type::DependentAddressSpace:
3581
0
  case Type::ObjCObject:
3582
0
  case Type::ObjCInterface:
3583
0
  case Type::ObjCObjectPointer:
3584
0
  case Type::Record:
3585
0
  case Type::Enum:
3586
0
  case Type::UnresolvedUsing:
3587
0
  case Type::TypeOfExpr:
3588
0
  case Type::TypeOf:
3589
0
  case Type::Decltype:
3590
0
  case Type::UnaryTransform:
3591
0
  case Type::DependentName:
3592
0
  case Type::InjectedClassName:
3593
0
  case Type::TemplateSpecialization:
3594
0
  case Type::DependentTemplateSpecialization:
3595
0
  case Type::TemplateTypeParm:
3596
0
  case Type::SubstTemplateTypeParmPack:
3597
0
  case Type::Auto:
3598
0
  case Type::DeducedTemplateSpecialization:
3599
0
  case Type::PackExpansion:
3600
0
  case Type::BitInt:
3601
0
  case Type::DependentBitInt:
3602
0
    llvm_unreachable("type should never be variably-modified");
3603
3604
  // These types can be variably-modified but should never need to
3605
  // further decay.
3606
0
  case Type::FunctionNoProto:
3607
0
  case Type::FunctionProto:
3608
0
  case Type::BlockPointer:
3609
0
  case Type::MemberPointer:
3610
0
  case Type::Pipe:
3611
0
    return type;
3612
3613
  // These types can be variably-modified.  All these modifications
3614
  // preserve structure except as noted by comments.
3615
  // TODO: if we ever care about optimizing VLAs, there are no-op
3616
  // optimizations available here.
3617
0
  case Type::Pointer:
3618
0
    result = getPointerType(getVariableArrayDecayedType(
3619
0
                              cast<PointerType>(ty)->getPointeeType()));
3620
0
    break;
3621
3622
0
  case Type::LValueReference: {
3623
0
    const auto *lv = cast<LValueReferenceType>(ty);
3624
0
    result = getLValueReferenceType(
3625
0
                 getVariableArrayDecayedType(lv->getPointeeType()),
3626
0
                                    lv->isSpelledAsLValue());
3627
0
    break;
3628
0
  }
3629
3630
0
  case Type::RValueReference: {
3631
0
    const auto *lv = cast<RValueReferenceType>(ty);
3632
0
    result = getRValueReferenceType(
3633
0
                 getVariableArrayDecayedType(lv->getPointeeType()));
3634
0
    break;
3635
0
  }
3636
3637
0
  case Type::Atomic: {
3638
0
    const auto *at = cast<AtomicType>(ty);
3639
0
    result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
3640
0
    break;
3641
0
  }
3642
3643
0
  case Type::ConstantArray: {
3644
0
    const auto *cat = cast<ConstantArrayType>(ty);
3645
0
    result = getConstantArrayType(
3646
0
                 getVariableArrayDecayedType(cat->getElementType()),
3647
0
                                  cat->getSize(),
3648
0
                                  cat->getSizeExpr(),
3649
0
                                  cat->getSizeModifier(),
3650
0
                                  cat->getIndexTypeCVRQualifiers());
3651
0
    break;
3652
0
  }
3653
3654
0
  case Type::DependentSizedArray: {
3655
0
    const auto *dat = cast<DependentSizedArrayType>(ty);
3656
0
    result = getDependentSizedArrayType(
3657
0
                 getVariableArrayDecayedType(dat->getElementType()),
3658
0
                                        dat->getSizeExpr(),
3659
0
                                        dat->getSizeModifier(),
3660
0
                                        dat->getIndexTypeCVRQualifiers(),
3661
0
                                        dat->getBracketsRange());
3662
0
    break;
3663
0
  }
3664
3665
  // Turn incomplete types into [*] types.
3666
0
  case Type::IncompleteArray: {
3667
0
    const auto *iat = cast<IncompleteArrayType>(ty);
3668
0
    result =
3669
0
        getVariableArrayType(getVariableArrayDecayedType(iat->getElementType()),
3670
0
                             /*size*/ nullptr, ArraySizeModifier::Normal,
3671
0
                             iat->getIndexTypeCVRQualifiers(), SourceRange());
3672
0
    break;
3673
0
  }
3674
3675
  // Turn VLA types into [*] types.
3676
0
  case Type::VariableArray: {
3677
0
    const auto *vat = cast<VariableArrayType>(ty);
3678
0
    result = getVariableArrayType(
3679
0
        getVariableArrayDecayedType(vat->getElementType()),
3680
0
        /*size*/ nullptr, ArraySizeModifier::Star,
3681
0
        vat->getIndexTypeCVRQualifiers(), vat->getBracketsRange());
3682
0
    break;
3683
0
  }
3684
0
  }
3685
3686
  // Apply the top-level qualifiers from the original.
3687
0
  return getQualifiedType(result, split.Quals);
3688
0
}
3689
3690
/// getVariableArrayType - Returns a non-unique reference to the type for a
3691
/// variable array of the specified element type.
3692
QualType ASTContext::getVariableArrayType(QualType EltTy, Expr *NumElts,
3693
                                          ArraySizeModifier ASM,
3694
                                          unsigned IndexTypeQuals,
3695
2
                                          SourceRange Brackets) const {
3696
  // Since we don't unique expressions, it isn't possible to unique VLA's
3697
  // that have an expression provided for their size.
3698
2
  QualType Canon;
3699
3700
  // Be sure to pull qualifiers off the element type.
3701
  // FIXME: Check below should look for qualifiers behind sugar.
3702
2
  if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
3703
0
    SplitQualType canonSplit = getCanonicalType(EltTy).split();
3704
0
    Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
3705
0
                                 IndexTypeQuals, Brackets);
3706
0
    Canon = getQualifiedType(Canon, canonSplit.Quals);
3707
0
  }
3708
3709
2
  auto *New = new (*this, alignof(VariableArrayType))
3710
2
      VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
3711
3712
2
  VariableArrayTypes.push_back(New);
3713
2
  Types.push_back(New);
3714
2
  return QualType(New, 0);
3715
2
}
3716
3717
/// getDependentSizedArrayType - Returns a non-unique reference to
3718
/// the type for a dependently-sized array of the specified element
3719
/// type.
3720
QualType ASTContext::getDependentSizedArrayType(QualType elementType,
3721
                                                Expr *numElements,
3722
                                                ArraySizeModifier ASM,
3723
                                                unsigned elementTypeQuals,
3724
36
                                                SourceRange brackets) const {
3725
36
  assert((!numElements || numElements->isTypeDependent() ||
3726
36
          numElements->isValueDependent()) &&
3727
36
         "Size must be type- or value-dependent!");
3728
3729
  // Dependently-sized array types that do not have a specified number
3730
  // of elements will have their sizes deduced from a dependent
3731
  // initializer.  We do no canonicalization here at all, which is okay
3732
  // because they can't be used in most locations.
3733
36
  if (!numElements) {
3734
0
    auto *newType = new (*this, alignof(DependentSizedArrayType))
3735
0
        DependentSizedArrayType(elementType, QualType(), numElements, ASM,
3736
0
                                elementTypeQuals, brackets);
3737
0
    Types.push_back(newType);
3738
0
    return QualType(newType, 0);
3739
0
  }
3740
3741
  // Otherwise, we actually build a new type every time, but we
3742
  // also build a canonical type.
3743
3744
36
  SplitQualType canonElementType = getCanonicalType(elementType).split();
3745
3746
36
  void *insertPos = nullptr;
3747
36
  llvm::FoldingSetNodeID ID;
3748
36
  DependentSizedArrayType::Profile(ID, *this,
3749
36
                                   QualType(canonElementType.Ty, 0),
3750
36
                                   ASM, elementTypeQuals, numElements);
3751
3752
  // Look for an existing type with these properties.
3753
36
  DependentSizedArrayType *canonTy =
3754
36
    DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
3755
3756
  // If we don't have one, build one.
3757
36
  if (!canonTy) {
3758
21
    canonTy = new (*this, alignof(DependentSizedArrayType))
3759
21
        DependentSizedArrayType(QualType(canonElementType.Ty, 0), QualType(),
3760
21
                                numElements, ASM, elementTypeQuals, brackets);
3761
21
    DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
3762
21
    Types.push_back(canonTy);
3763
21
  }
3764
3765
  // Apply qualifiers from the element type to the array.
3766
36
  QualType canon = getQualifiedType(QualType(canonTy,0),
3767
36
                                    canonElementType.Quals);
3768
3769
  // If we didn't need extra canonicalization for the element type or the size
3770
  // expression, then just use that as our result.
3771
36
  if (QualType(canonElementType.Ty, 0) == elementType &&
3772
36
      canonTy->getSizeExpr() == numElements)
3773
21
    return canon;
3774
3775
  // Otherwise, we need to build a type which follows the spelling
3776
  // of the element type.
3777
15
  auto *sugaredType = new (*this, alignof(DependentSizedArrayType))
3778
15
      DependentSizedArrayType(elementType, canon, numElements, ASM,
3779
15
                              elementTypeQuals, brackets);
3780
15
  Types.push_back(sugaredType);
3781
15
  return QualType(sugaredType, 0);
3782
36
}
3783
3784
QualType ASTContext::getIncompleteArrayType(QualType elementType,
3785
                                            ArraySizeModifier ASM,
3786
0
                                            unsigned elementTypeQuals) const {
3787
0
  llvm::FoldingSetNodeID ID;
3788
0
  IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
3789
3790
0
  void *insertPos = nullptr;
3791
0
  if (IncompleteArrayType *iat =
3792
0
       IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
3793
0
    return QualType(iat, 0);
3794
3795
  // If the element type isn't canonical, this won't be a canonical type
3796
  // either, so fill in the canonical type field.  We also have to pull
3797
  // qualifiers off the element type.
3798
0
  QualType canon;
3799
3800
  // FIXME: Check below should look for qualifiers behind sugar.
3801
0
  if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
3802
0
    SplitQualType canonSplit = getCanonicalType(elementType).split();
3803
0
    canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
3804
0
                                   ASM, elementTypeQuals);
3805
0
    canon = getQualifiedType(canon, canonSplit.Quals);
3806
3807
    // Get the new insert position for the node we care about.
3808
0
    IncompleteArrayType *existing =
3809
0
      IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
3810
0
    assert(!existing && "Shouldn't be in the map!"); (void) existing;
3811
0
  }
3812
3813
0
  auto *newType = new (*this, alignof(IncompleteArrayType))
3814
0
      IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
3815
3816
0
  IncompleteArrayTypes.InsertNode(newType, insertPos);
3817
0
  Types.push_back(newType);
3818
0
  return QualType(newType, 0);
3819
0
}
3820
3821
ASTContext::BuiltinVectorTypeInfo
3822
0
ASTContext::getBuiltinVectorTypeInfo(const BuiltinType *Ty) const {
3823
0
#define SVE_INT_ELTTY(BITS, ELTS, SIGNED, NUMVECTORS)                          \
3824
0
  {getIntTypeForBitwidth(BITS, SIGNED), llvm::ElementCount::getScalable(ELTS), \
3825
0
   NUMVECTORS};
3826
3827
0
#define SVE_ELTTY(ELTTY, ELTS, NUMVECTORS)                                     \
3828
0
  {ELTTY, llvm::ElementCount::getScalable(ELTS), NUMVECTORS};
3829
3830
0
  switch (Ty->getKind()) {
3831
0
  default:
3832
0
    llvm_unreachable("Unsupported builtin vector type");
3833
0
  case BuiltinType::SveInt8:
3834
0
    return SVE_INT_ELTTY(8, 16, true, 1);
3835
0
  case BuiltinType::SveUint8:
3836
0
    return SVE_INT_ELTTY(8, 16, false, 1);
3837
0
  case BuiltinType::SveInt8x2:
3838
0
    return SVE_INT_ELTTY(8, 16, true, 2);
3839
0
  case BuiltinType::SveUint8x2:
3840
0
    return SVE_INT_ELTTY(8, 16, false, 2);
3841
0
  case BuiltinType::SveInt8x3:
3842
0
    return SVE_INT_ELTTY(8, 16, true, 3);
3843
0
  case BuiltinType::SveUint8x3:
3844
0
    return SVE_INT_ELTTY(8, 16, false, 3);
3845
0
  case BuiltinType::SveInt8x4:
3846
0
    return SVE_INT_ELTTY(8, 16, true, 4);
3847
0
  case BuiltinType::SveUint8x4:
3848
0
    return SVE_INT_ELTTY(8, 16, false, 4);
3849
0
  case BuiltinType::SveInt16:
3850
0
    return SVE_INT_ELTTY(16, 8, true, 1);
3851
0
  case BuiltinType::SveUint16:
3852
0
    return SVE_INT_ELTTY(16, 8, false, 1);
3853
0
  case BuiltinType::SveInt16x2:
3854
0
    return SVE_INT_ELTTY(16, 8, true, 2);
3855
0
  case BuiltinType::SveUint16x2:
3856
0
    return SVE_INT_ELTTY(16, 8, false, 2);
3857
0
  case BuiltinType::SveInt16x3:
3858
0
    return SVE_INT_ELTTY(16, 8, true, 3);
3859
0
  case BuiltinType::SveUint16x3:
3860
0
    return SVE_INT_ELTTY(16, 8, false, 3);
3861
0
  case BuiltinType::SveInt16x4:
3862
0
    return SVE_INT_ELTTY(16, 8, true, 4);
3863
0
  case BuiltinType::SveUint16x4:
3864
0
    return SVE_INT_ELTTY(16, 8, false, 4);
3865
0
  case BuiltinType::SveInt32:
3866
0
    return SVE_INT_ELTTY(32, 4, true, 1);
3867
0
  case BuiltinType::SveUint32:
3868
0
    return SVE_INT_ELTTY(32, 4, false, 1);
3869
0
  case BuiltinType::SveInt32x2:
3870
0
    return SVE_INT_ELTTY(32, 4, true, 2);
3871
0
  case BuiltinType::SveUint32x2:
3872
0
    return SVE_INT_ELTTY(32, 4, false, 2);
3873
0
  case BuiltinType::SveInt32x3:
3874
0
    return SVE_INT_ELTTY(32, 4, true, 3);
3875
0
  case BuiltinType::SveUint32x3:
3876
0
    return SVE_INT_ELTTY(32, 4, false, 3);
3877
0
  case BuiltinType::SveInt32x4:
3878
0
    return SVE_INT_ELTTY(32, 4, true, 4);
3879
0
  case BuiltinType::SveUint32x4:
3880
0
    return SVE_INT_ELTTY(32, 4, false, 4);
3881
0
  case BuiltinType::SveInt64:
3882
0
    return SVE_INT_ELTTY(64, 2, true, 1);
3883
0
  case BuiltinType::SveUint64:
3884
0
    return SVE_INT_ELTTY(64, 2, false, 1);
3885
0
  case BuiltinType::SveInt64x2:
3886
0
    return SVE_INT_ELTTY(64, 2, true, 2);
3887
0
  case BuiltinType::SveUint64x2:
3888
0
    return SVE_INT_ELTTY(64, 2, false, 2);
3889
0
  case BuiltinType::SveInt64x3:
3890
0
    return SVE_INT_ELTTY(64, 2, true, 3);
3891
0
  case BuiltinType::SveUint64x3:
3892
0
    return SVE_INT_ELTTY(64, 2, false, 3);
3893
0
  case BuiltinType::SveInt64x4:
3894
0
    return SVE_INT_ELTTY(64, 2, true, 4);
3895
0
  case BuiltinType::SveUint64x4:
3896
0
    return SVE_INT_ELTTY(64, 2, false, 4);
3897
0
  case BuiltinType::SveBool:
3898
0
    return SVE_ELTTY(BoolTy, 16, 1);
3899
0
  case BuiltinType::SveBoolx2:
3900
0
    return SVE_ELTTY(BoolTy, 16, 2);
3901
0
  case BuiltinType::SveBoolx4:
3902
0
    return SVE_ELTTY(BoolTy, 16, 4);
3903
0
  case BuiltinType::SveFloat16:
3904
0
    return SVE_ELTTY(HalfTy, 8, 1);
3905
0
  case BuiltinType::SveFloat16x2:
3906
0
    return SVE_ELTTY(HalfTy, 8, 2);
3907
0
  case BuiltinType::SveFloat16x3:
3908
0
    return SVE_ELTTY(HalfTy, 8, 3);
3909
0
  case BuiltinType::SveFloat16x4:
3910
0
    return SVE_ELTTY(HalfTy, 8, 4);
3911
0
  case BuiltinType::SveFloat32:
3912
0
    return SVE_ELTTY(FloatTy, 4, 1);
3913
0
  case BuiltinType::SveFloat32x2:
3914
0
    return SVE_ELTTY(FloatTy, 4, 2);
3915
0
  case BuiltinType::SveFloat32x3:
3916
0
    return SVE_ELTTY(FloatTy, 4, 3);
3917
0
  case BuiltinType::SveFloat32x4:
3918
0
    return SVE_ELTTY(FloatTy, 4, 4);
3919
0
  case BuiltinType::SveFloat64:
3920
0
    return SVE_ELTTY(DoubleTy, 2, 1);
3921
0
  case BuiltinType::SveFloat64x2:
3922
0
    return SVE_ELTTY(DoubleTy, 2, 2);
3923
0
  case BuiltinType::SveFloat64x3:
3924
0
    return SVE_ELTTY(DoubleTy, 2, 3);
3925
0
  case BuiltinType::SveFloat64x4:
3926
0
    return SVE_ELTTY(DoubleTy, 2, 4);
3927
0
  case BuiltinType::SveBFloat16:
3928
0
    return SVE_ELTTY(BFloat16Ty, 8, 1);
3929
0
  case BuiltinType::SveBFloat16x2:
3930
0
    return SVE_ELTTY(BFloat16Ty, 8, 2);
3931
0
  case BuiltinType::SveBFloat16x3:
3932
0
    return SVE_ELTTY(BFloat16Ty, 8, 3);
3933
0
  case BuiltinType::SveBFloat16x4:
3934
0
    return SVE_ELTTY(BFloat16Ty, 8, 4);
3935
0
#define RVV_VECTOR_TYPE_INT(Name, Id, SingletonId, NumEls, ElBits, NF,         \
3936
0
                            IsSigned)                                          \
3937
0
  case BuiltinType::Id:                                                        \
3938
0
    return {getIntTypeForBitwidth(ElBits, IsSigned),                           \
3939
0
            llvm::ElementCount::getScalable(NumEls), NF};
3940
0
#define RVV_VECTOR_TYPE_FLOAT(Name, Id, SingletonId, NumEls, ElBits, NF)       \
3941
0
  case BuiltinType::Id:                                                        \
3942
0
    return {ElBits == 16 ? Float16Ty : (ElBits == 32 ? FloatTy : DoubleTy),    \
3943
0
            llvm::ElementCount::getScalable(NumEls), NF};
3944
0
#define RVV_VECTOR_TYPE_BFLOAT(Name, Id, SingletonId, NumEls, ElBits, NF)      \
3945
0
  case BuiltinType::Id:                                                        \
3946
0
    return {BFloat16Ty, llvm::ElementCount::getScalable(NumEls), NF};
3947
0
#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls)                      \
3948
0
  case BuiltinType::Id:                                                        \
3949
0
    return {BoolTy, llvm::ElementCount::getScalable(NumEls), 1};
3950
0
#include "clang/Basic/RISCVVTypes.def"
3951
0
  }
3952
0
}
3953
3954
/// getExternrefType - Return a WebAssembly externref type, which represents an
3955
/// opaque reference to a host value.
3956
0
QualType ASTContext::getWebAssemblyExternrefType() const {
3957
0
  if (Target->getTriple().isWasm() && Target->hasFeature("reference-types")) {
3958
0
#define WASM_REF_TYPE(Name, MangledName, Id, SingletonId, AS)                  \
3959
0
  if (BuiltinType::Id == BuiltinType::WasmExternRef)                           \
3960
0
    return SingletonId;
3961
0
#include "clang/Basic/WebAssemblyReferenceTypes.def"
3962
0
  }
3963
0
  llvm_unreachable(
3964
0
      "shouldn't try to generate type externref outside WebAssembly target");
3965
0
}
3966
3967
/// getScalableVectorType - Return the unique reference to a scalable vector
3968
/// type of the specified element type and size. VectorType must be a built-in
3969
/// type.
3970
QualType ASTContext::getScalableVectorType(QualType EltTy, unsigned NumElts,
3971
0
                                           unsigned NumFields) const {
3972
0
  if (Target->hasAArch64SVETypes()) {
3973
0
    uint64_t EltTySize = getTypeSize(EltTy);
3974
0
#define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId, NumEls, ElBits,    \
3975
0
                        IsSigned, IsFP, IsBF)                                  \
3976
0
  if (!EltTy->isBooleanType() &&                                               \
3977
0
      ((EltTy->hasIntegerRepresentation() &&                                   \
3978
0
        EltTy->hasSignedIntegerRepresentation() == IsSigned) ||                \
3979
0
       (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() &&      \
3980
0
        IsFP && !IsBF) ||                                                      \
3981
0
       (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() &&       \
3982
0
        IsBF && !IsFP)) &&                                                     \
3983
0
      EltTySize == ElBits && NumElts == NumEls) {                              \
3984
0
    return SingletonId;                                                        \
3985
0
  }
3986
0
#define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId, NumEls)         \
3987
0
  if (EltTy->isBooleanType() && NumElts == NumEls)                             \
3988
0
    return SingletonId;
3989
0
#define SVE_OPAQUE_TYPE(Name, MangledName, Id, SingleTonId)
3990
0
#include "clang/Basic/AArch64SVEACLETypes.def"
3991
0
  } else if (Target->hasRISCVVTypes()) {
3992
0
    uint64_t EltTySize = getTypeSize(EltTy);
3993
0
#define RVV_VECTOR_TYPE(Name, Id, SingletonId, NumEls, ElBits, NF, IsSigned,   \
3994
0
                        IsFP, IsBF)                                            \
3995
0
  if (!EltTy->isBooleanType() &&                                               \
3996
0
      ((EltTy->hasIntegerRepresentation() &&                                   \
3997
0
        EltTy->hasSignedIntegerRepresentation() == IsSigned) ||                \
3998
0
       (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() &&      \
3999
0
        IsFP && !IsBF) ||                                                      \
4000
0
       (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() &&       \
4001
0
        IsBF && !IsFP)) &&                                                     \
4002
0
      EltTySize == ElBits && NumElts == NumEls && NumFields == NF)             \
4003
0
    return SingletonId;
4004
0
#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls)                      \
4005
0
  if (EltTy->isBooleanType() && NumElts == NumEls)                             \
4006
0
    return SingletonId;
4007
0
#include "clang/Basic/RISCVVTypes.def"
4008
0
  }
4009
0
  return QualType();
4010
0
}
4011
4012
/// getVectorType - Return the unique reference to a vector type of
4013
/// the specified element type and size. VectorType must be a built-in type.
4014
QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
4015
0
                                   VectorKind VecKind) const {
4016
0
  assert(vecType->isBuiltinType() ||
4017
0
         (vecType->isBitIntType() &&
4018
          // Only support _BitInt elements with byte-sized power of 2 NumBits.
4019
0
          llvm::isPowerOf2_32(vecType->castAs<BitIntType>()->getNumBits()) &&
4020
0
          vecType->castAs<BitIntType>()->getNumBits() >= 8));
4021
4022
  // Check if we've already instantiated a vector of this type.
4023
0
  llvm::FoldingSetNodeID ID;
4024
0
  VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
4025
4026
0
  void *InsertPos = nullptr;
4027
0
  if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
4028
0
    return QualType(VTP, 0);
4029
4030
  // If the element type isn't canonical, this won't be a canonical type either,
4031
  // so fill in the canonical type field.
4032
0
  QualType Canonical;
4033
0
  if (!vecType.isCanonical()) {
4034
0
    Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
4035
4036
    // Get the new insert position for the node we care about.
4037
0
    VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4038
0
    assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4039
0
  }
4040
0
  auto *New = new (*this, alignof(VectorType))
4041
0
      VectorType(vecType, NumElts, Canonical, VecKind);
4042
0
  VectorTypes.InsertNode(New, InsertPos);
4043
0
  Types.push_back(New);
4044
0
  return QualType(New, 0);
4045
0
}
4046
4047
QualType ASTContext::getDependentVectorType(QualType VecType, Expr *SizeExpr,
4048
                                            SourceLocation AttrLoc,
4049
0
                                            VectorKind VecKind) const {
4050
0
  llvm::FoldingSetNodeID ID;
4051
0
  DependentVectorType::Profile(ID, *this, getCanonicalType(VecType), SizeExpr,
4052
0
                               VecKind);
4053
0
  void *InsertPos = nullptr;
4054
0
  DependentVectorType *Canon =
4055
0
      DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4056
0
  DependentVectorType *New;
4057
4058
0
  if (Canon) {
4059
0
    New = new (*this, alignof(DependentVectorType)) DependentVectorType(
4060
0
        VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind);
4061
0
  } else {
4062
0
    QualType CanonVecTy = getCanonicalType(VecType);
4063
0
    if (CanonVecTy == VecType) {
4064
0
      New = new (*this, alignof(DependentVectorType))
4065
0
          DependentVectorType(VecType, QualType(), SizeExpr, AttrLoc, VecKind);
4066
4067
0
      DependentVectorType *CanonCheck =
4068
0
          DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4069
0
      assert(!CanonCheck &&
4070
0
             "Dependent-sized vector_size canonical type broken");
4071
0
      (void)CanonCheck;
4072
0
      DependentVectorTypes.InsertNode(New, InsertPos);
4073
0
    } else {
4074
0
      QualType CanonTy = getDependentVectorType(CanonVecTy, SizeExpr,
4075
0
                                                SourceLocation(), VecKind);
4076
0
      New = new (*this, alignof(DependentVectorType))
4077
0
          DependentVectorType(VecType, CanonTy, SizeExpr, AttrLoc, VecKind);
4078
0
    }
4079
0
  }
4080
4081
0
  Types.push_back(New);
4082
0
  return QualType(New, 0);
4083
0
}
4084
4085
/// getExtVectorType - Return the unique reference to an extended vector type of
4086
/// the specified element type and size. VectorType must be a built-in type.
4087
QualType ASTContext::getExtVectorType(QualType vecType,
4088
0
                                      unsigned NumElts) const {
4089
0
  assert(vecType->isBuiltinType() || vecType->isDependentType() ||
4090
0
         (vecType->isBitIntType() &&
4091
          // Only support _BitInt elements with byte-sized power of 2 NumBits.
4092
0
          llvm::isPowerOf2_32(vecType->castAs<BitIntType>()->getNumBits()) &&
4093
0
          vecType->castAs<BitIntType>()->getNumBits() >= 8));
4094
4095
  // Check if we've already instantiated a vector of this type.
4096
0
  llvm::FoldingSetNodeID ID;
4097
0
  VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
4098
0
                      VectorKind::Generic);
4099
0
  void *InsertPos = nullptr;
4100
0
  if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
4101
0
    return QualType(VTP, 0);
4102
4103
  // If the element type isn't canonical, this won't be a canonical type either,
4104
  // so fill in the canonical type field.
4105
0
  QualType Canonical;
4106
0
  if (!vecType.isCanonical()) {
4107
0
    Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
4108
4109
    // Get the new insert position for the node we care about.
4110
0
    VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4111
0
    assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4112
0
  }
4113
0
  auto *New = new (*this, alignof(ExtVectorType))
4114
0
      ExtVectorType(vecType, NumElts, Canonical);
4115
0
  VectorTypes.InsertNode(New, InsertPos);
4116
0
  Types.push_back(New);
4117
0
  return QualType(New, 0);
4118
0
}
4119
4120
QualType
4121
ASTContext::getDependentSizedExtVectorType(QualType vecType,
4122
                                           Expr *SizeExpr,
4123
0
                                           SourceLocation AttrLoc) const {
4124
0
  llvm::FoldingSetNodeID ID;
4125
0
  DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
4126
0
                                       SizeExpr);
4127
4128
0
  void *InsertPos = nullptr;
4129
0
  DependentSizedExtVectorType *Canon
4130
0
    = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4131
0
  DependentSizedExtVectorType *New;
4132
0
  if (Canon) {
4133
    // We already have a canonical version of this array type; use it as
4134
    // the canonical type for a newly-built type.
4135
0
    New = new (*this, alignof(DependentSizedExtVectorType))
4136
0
        DependentSizedExtVectorType(vecType, QualType(Canon, 0), SizeExpr,
4137
0
                                    AttrLoc);
4138
0
  } else {
4139
0
    QualType CanonVecTy = getCanonicalType(vecType);
4140
0
    if (CanonVecTy == vecType) {
4141
0
      New = new (*this, alignof(DependentSizedExtVectorType))
4142
0
          DependentSizedExtVectorType(vecType, QualType(), SizeExpr, AttrLoc);
4143
4144
0
      DependentSizedExtVectorType *CanonCheck
4145
0
        = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4146
0
      assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
4147
0
      (void)CanonCheck;
4148
0
      DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
4149
0
    } else {
4150
0
      QualType CanonExtTy = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
4151
0
                                                           SourceLocation());
4152
0
      New = new (*this, alignof(DependentSizedExtVectorType))
4153
0
          DependentSizedExtVectorType(vecType, CanonExtTy, SizeExpr, AttrLoc);
4154
0
    }
4155
0
  }
4156
4157
0
  Types.push_back(New);
4158
0
  return QualType(New, 0);
4159
0
}
4160
4161
QualType ASTContext::getConstantMatrixType(QualType ElementTy, unsigned NumRows,
4162
0
                                           unsigned NumColumns) const {
4163
0
  llvm::FoldingSetNodeID ID;
4164
0
  ConstantMatrixType::Profile(ID, ElementTy, NumRows, NumColumns,
4165
0
                              Type::ConstantMatrix);
4166
4167
0
  assert(MatrixType::isValidElementType(ElementTy) &&
4168
0
         "need a valid element type");
4169
0
  assert(ConstantMatrixType::isDimensionValid(NumRows) &&
4170
0
         ConstantMatrixType::isDimensionValid(NumColumns) &&
4171
0
         "need valid matrix dimensions");
4172
0
  void *InsertPos = nullptr;
4173
0
  if (ConstantMatrixType *MTP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos))
4174
0
    return QualType(MTP, 0);
4175
4176
0
  QualType Canonical;
4177
0
  if (!ElementTy.isCanonical()) {
4178
0
    Canonical =
4179
0
        getConstantMatrixType(getCanonicalType(ElementTy), NumRows, NumColumns);
4180
4181
0
    ConstantMatrixType *NewIP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4182
0
    assert(!NewIP && "Matrix type shouldn't already exist in the map");
4183
0
    (void)NewIP;
4184
0
  }
4185
4186
0
  auto *New = new (*this, alignof(ConstantMatrixType))
4187
0
      ConstantMatrixType(ElementTy, NumRows, NumColumns, Canonical);
4188
0
  MatrixTypes.InsertNode(New, InsertPos);
4189
0
  Types.push_back(New);
4190
0
  return QualType(New, 0);
4191
0
}
4192
4193
QualType ASTContext::getDependentSizedMatrixType(QualType ElementTy,
4194
                                                 Expr *RowExpr,
4195
                                                 Expr *ColumnExpr,
4196
0
                                                 SourceLocation AttrLoc) const {
4197
0
  QualType CanonElementTy = getCanonicalType(ElementTy);
4198
0
  llvm::FoldingSetNodeID ID;
4199
0
  DependentSizedMatrixType::Profile(ID, *this, CanonElementTy, RowExpr,
4200
0
                                    ColumnExpr);
4201
4202
0
  void *InsertPos = nullptr;
4203
0
  DependentSizedMatrixType *Canon =
4204
0
      DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4205
4206
0
  if (!Canon) {
4207
0
    Canon = new (*this, alignof(DependentSizedMatrixType))
4208
0
        DependentSizedMatrixType(CanonElementTy, QualType(), RowExpr,
4209
0
                                 ColumnExpr, AttrLoc);
4210
0
#ifndef NDEBUG
4211
0
    DependentSizedMatrixType *CanonCheck =
4212
0
        DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4213
0
    assert(!CanonCheck && "Dependent-sized matrix canonical type broken");
4214
0
#endif
4215
0
    DependentSizedMatrixTypes.InsertNode(Canon, InsertPos);
4216
0
    Types.push_back(Canon);
4217
0
  }
4218
4219
  // Already have a canonical version of the matrix type
4220
  //
4221
  // If it exactly matches the requested type, use it directly.
4222
0
  if (Canon->getElementType() == ElementTy && Canon->getRowExpr() == RowExpr &&
4223
0
      Canon->getRowExpr() == ColumnExpr)
4224
0
    return QualType(Canon, 0);
4225
4226
  // Use Canon as the canonical type for newly-built type.
4227
0
  DependentSizedMatrixType *New = new (*this, alignof(DependentSizedMatrixType))
4228
0
      DependentSizedMatrixType(ElementTy, QualType(Canon, 0), RowExpr,
4229
0
                               ColumnExpr, AttrLoc);
4230
0
  Types.push_back(New);
4231
0
  return QualType(New, 0);
4232
0
}
4233
4234
QualType ASTContext::getDependentAddressSpaceType(QualType PointeeType,
4235
                                                  Expr *AddrSpaceExpr,
4236
0
                                                  SourceLocation AttrLoc) const {
4237
0
  assert(AddrSpaceExpr->isInstantiationDependent());
4238
4239
0
  QualType canonPointeeType = getCanonicalType(PointeeType);
4240
4241
0
  void *insertPos = nullptr;
4242
0
  llvm::FoldingSetNodeID ID;
4243
0
  DependentAddressSpaceType::Profile(ID, *this, canonPointeeType,
4244
0
                                     AddrSpaceExpr);
4245
4246
0
  DependentAddressSpaceType *canonTy =
4247
0
    DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos);
4248
4249
0
  if (!canonTy) {
4250
0
    canonTy = new (*this, alignof(DependentAddressSpaceType))
4251
0
        DependentAddressSpaceType(canonPointeeType, QualType(), AddrSpaceExpr,
4252
0
                                  AttrLoc);
4253
0
    DependentAddressSpaceTypes.InsertNode(canonTy, insertPos);
4254
0
    Types.push_back(canonTy);
4255
0
  }
4256
4257
0
  if (canonPointeeType == PointeeType &&
4258
0
      canonTy->getAddrSpaceExpr() == AddrSpaceExpr)
4259
0
    return QualType(canonTy, 0);
4260
4261
0
  auto *sugaredType = new (*this, alignof(DependentAddressSpaceType))
4262
0
      DependentAddressSpaceType(PointeeType, QualType(canonTy, 0),
4263
0
                                AddrSpaceExpr, AttrLoc);
4264
0
  Types.push_back(sugaredType);
4265
0
  return QualType(sugaredType, 0);
4266
0
}
4267
4268
/// Determine whether \p T is canonical as the result type of a function.
4269
20
static bool isCanonicalResultType(QualType T) {
4270
20
  return T.isCanonical() &&
4271
20
         (T.getObjCLifetime() == Qualifiers::OCL_None ||
4272
20
          T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
4273
20
}
4274
4275
/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
4276
QualType
4277
ASTContext::getFunctionNoProtoType(QualType ResultTy,
4278
11
                                   const FunctionType::ExtInfo &Info) const {
4279
  // FIXME: This assertion cannot be enabled (yet) because the ObjC rewriter
4280
  // functionality creates a function without a prototype regardless of
4281
  // language mode (so it makes them even in C++). Once the rewriter has been
4282
  // fixed, this assertion can be enabled again.
4283
  //assert(!LangOpts.requiresStrictPrototypes() &&
4284
  //       "strict prototypes are disabled");
4285
4286
  // Unique functions, to guarantee there is only one function of a particular
4287
  // structure.
4288
11
  llvm::FoldingSetNodeID ID;
4289
11
  FunctionNoProtoType::Profile(ID, ResultTy, Info);
4290
4291
11
  void *InsertPos = nullptr;
4292
11
  if (FunctionNoProtoType *FT =
4293
11
        FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
4294
3
    return QualType(FT, 0);
4295
4296
8
  QualType Canonical;
4297
8
  if (!isCanonicalResultType(ResultTy)) {
4298
0
    Canonical =
4299
0
      getFunctionNoProtoType(getCanonicalFunctionResultType(ResultTy), Info);
4300
4301
    // Get the new insert position for the node we care about.
4302
0
    FunctionNoProtoType *NewIP =
4303
0
      FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
4304
0
    assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4305
0
  }
4306
4307
0
  auto *New = new (*this, alignof(FunctionNoProtoType))
4308
8
      FunctionNoProtoType(ResultTy, Canonical, Info);
4309
8
  Types.push_back(New);
4310
8
  FunctionNoProtoTypes.InsertNode(New, InsertPos);
4311
8
  return QualType(New, 0);
4312
11
}
4313
4314
CanQualType
4315
0
ASTContext::getCanonicalFunctionResultType(QualType ResultType) const {
4316
0
  CanQualType CanResultType = getCanonicalType(ResultType);
4317
4318
  // Canonical result types do not have ARC lifetime qualifiers.
4319
0
  if (CanResultType.getQualifiers().hasObjCLifetime()) {
4320
0
    Qualifiers Qs = CanResultType.getQualifiers();
4321
0
    Qs.removeObjCLifetime();
4322
0
    return CanQualType::CreateUnsafe(
4323
0
             getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
4324
0
  }
4325
4326
0
  return CanResultType;
4327
0
}
4328
4329
static bool isCanonicalExceptionSpecification(
4330
12
    const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
4331
12
  if (ESI.Type == EST_None)
4332
12
    return true;
4333
0
  if (!NoexceptInType)
4334
0
    return false;
4335
4336
  // C++17 onwards: exception specification is part of the type, as a simple
4337
  // boolean "can this function type throw".
4338
0
  if (ESI.Type == EST_BasicNoexcept)
4339
0
    return true;
4340
4341
  // A noexcept(expr) specification is (possibly) canonical if expr is
4342
  // value-dependent.
4343
0
  if (ESI.Type == EST_DependentNoexcept)
4344
0
    return true;
4345
4346
  // A dynamic exception specification is canonical if it only contains pack
4347
  // expansions (so we can't tell whether it's non-throwing) and all its
4348
  // contained types are canonical.
4349
0
  if (ESI.Type == EST_Dynamic) {
4350
0
    bool AnyPackExpansions = false;
4351
0
    for (QualType ET : ESI.Exceptions) {
4352
0
      if (!ET.isCanonical())
4353
0
        return false;
4354
0
      if (ET->getAs<PackExpansionType>())
4355
0
        AnyPackExpansions = true;
4356
0
    }
4357
0
    return AnyPackExpansions;
4358
0
  }
4359
4360
0
  return false;
4361
0
}
4362
4363
QualType ASTContext::getFunctionTypeInternal(
4364
    QualType ResultTy, ArrayRef<QualType> ArgArray,
4365
14
    const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
4366
14
  size_t NumArgs = ArgArray.size();
4367
4368
  // Unique functions, to guarantee there is only one function of a particular
4369
  // structure.
4370
14
  llvm::FoldingSetNodeID ID;
4371
14
  FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
4372
14
                             *this, true);
4373
4374
14
  QualType Canonical;
4375
14
  bool Unique = false;
4376
4377
14
  void *InsertPos = nullptr;
4378
14
  if (FunctionProtoType *FPT =
4379
14
        FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
4380
2
    QualType Existing = QualType(FPT, 0);
4381
4382
    // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
4383
    // it so long as our exception specification doesn't contain a dependent
4384
    // noexcept expression, or we're just looking for a canonical type.
4385
    // Otherwise, we're going to need to create a type
4386
    // sugar node to hold the concrete expression.
4387
2
    if (OnlyWantCanonical || !isComputedNoexcept(EPI.ExceptionSpec.Type) ||
4388
2
        EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
4389
2
      return Existing;
4390
4391
    // We need a new type sugar node for this one, to hold the new noexcept
4392
    // expression. We do no canonicalization here, but that's OK since we don't
4393
    // expect to see the same noexcept expression much more than once.
4394
0
    Canonical = getCanonicalType(Existing);
4395
0
    Unique = true;
4396
0
  }
4397
4398
12
  bool NoexceptInType = getLangOpts().CPlusPlus17;
4399
12
  bool IsCanonicalExceptionSpec =
4400
12
      isCanonicalExceptionSpecification(EPI.ExceptionSpec, NoexceptInType);
4401
4402
  // Determine whether the type being created is already canonical or not.
4403
12
  bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
4404
12
                     isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
4405
19
  for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
4406
7
    if (!ArgArray[i].isCanonicalAsParam())
4407
0
      isCanonical = false;
4408
4409
12
  if (OnlyWantCanonical)
4410
0
    assert(isCanonical &&
4411
12
           "given non-canonical parameters constructing canonical type");
4412
4413
  // If this type isn't canonical, get the canonical version of it if we don't
4414
  // already have it. The exception spec is only partially part of the
4415
  // canonical type, and only in C++17 onwards.
4416
12
  if (!isCanonical && Canonical.isNull()) {
4417
0
    SmallVector<QualType, 16> CanonicalArgs;
4418
0
    CanonicalArgs.reserve(NumArgs);
4419
0
    for (unsigned i = 0; i != NumArgs; ++i)
4420
0
      CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
4421
4422
0
    llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
4423
0
    FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
4424
0
    CanonicalEPI.HasTrailingReturn = false;
4425
4426
0
    if (IsCanonicalExceptionSpec) {
4427
      // Exception spec is already OK.
4428
0
    } else if (NoexceptInType) {
4429
0
      switch (EPI.ExceptionSpec.Type) {
4430
0
      case EST_Unparsed: case EST_Unevaluated: case EST_Uninstantiated:
4431
        // We don't know yet. It shouldn't matter what we pick here; no-one
4432
        // should ever look at this.
4433
0
        [[fallthrough]];
4434
0
      case EST_None: case EST_MSAny: case EST_NoexceptFalse:
4435
0
        CanonicalEPI.ExceptionSpec.Type = EST_None;
4436
0
        break;
4437
4438
        // A dynamic exception specification is almost always "not noexcept",
4439
        // with the exception that a pack expansion might expand to no types.
4440
0
      case EST_Dynamic: {
4441
0
        bool AnyPacks = false;
4442
0
        for (QualType ET : EPI.ExceptionSpec.Exceptions) {
4443
0
          if (ET->getAs<PackExpansionType>())
4444
0
            AnyPacks = true;
4445
0
          ExceptionTypeStorage.push_back(getCanonicalType(ET));
4446
0
        }
4447
0
        if (!AnyPacks)
4448
0
          CanonicalEPI.ExceptionSpec.Type = EST_None;
4449
0
        else {
4450
0
          CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
4451
0
          CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
4452
0
        }
4453
0
        break;
4454
0
      }
4455
4456
0
      case EST_DynamicNone:
4457
0
      case EST_BasicNoexcept:
4458
0
      case EST_NoexceptTrue:
4459
0
      case EST_NoThrow:
4460
0
        CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
4461
0
        break;
4462
4463
0
      case EST_DependentNoexcept:
4464
0
        llvm_unreachable("dependent noexcept is already canonical");
4465
0
      }
4466
0
    } else {
4467
0
      CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
4468
0
    }
4469
4470
    // Adjust the canonical function result type.
4471
0
    CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
4472
0
    Canonical =
4473
0
        getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
4474
4475
    // Get the new insert position for the node we care about.
4476
0
    FunctionProtoType *NewIP =
4477
0
      FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
4478
0
    assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4479
0
  }
4480
4481
  // Compute the needed size to hold this FunctionProtoType and the
4482
  // various trailing objects.
4483
12
  auto ESH = FunctionProtoType::getExceptionSpecSize(
4484
12
      EPI.ExceptionSpec.Type, EPI.ExceptionSpec.Exceptions.size());
4485
12
  size_t Size = FunctionProtoType::totalSizeToAlloc<
4486
12
      QualType, SourceLocation, FunctionType::FunctionTypeExtraBitfields,
4487
12
      FunctionType::ExceptionType, Expr *, FunctionDecl *,
4488
12
      FunctionProtoType::ExtParameterInfo, Qualifiers>(
4489
12
      NumArgs, EPI.Variadic, EPI.requiresFunctionProtoTypeExtraBitfields(),
4490
12
      ESH.NumExceptionType, ESH.NumExprPtr, ESH.NumFunctionDeclPtr,
4491
12
      EPI.ExtParameterInfos ? NumArgs : 0,
4492
12
      EPI.TypeQuals.hasNonFastQualifiers() ? 1 : 0);
4493
4494
12
  auto *FTP = (FunctionProtoType *)Allocate(Size, alignof(FunctionProtoType));
4495
12
  FunctionProtoType::ExtProtoInfo newEPI = EPI;
4496
12
  new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
4497
12
  Types.push_back(FTP);
4498
12
  if (!Unique)
4499
12
    FunctionProtoTypes.InsertNode(FTP, InsertPos);
4500
12
  return QualType(FTP, 0);
4501
12
}
4502
4503
0
QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
4504
0
  llvm::FoldingSetNodeID ID;
4505
0
  PipeType::Profile(ID, T, ReadOnly);
4506
4507
0
  void *InsertPos = nullptr;
4508
0
  if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
4509
0
    return QualType(PT, 0);
4510
4511
  // If the pipe element type isn't canonical, this won't be a canonical type
4512
  // either, so fill in the canonical type field.
4513
0
  QualType Canonical;
4514
0
  if (!T.isCanonical()) {
4515
0
    Canonical = getPipeType(getCanonicalType(T), ReadOnly);
4516
4517
    // Get the new insert position for the node we care about.
4518
0
    PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
4519
0
    assert(!NewIP && "Shouldn't be in the map!");
4520
0
    (void)NewIP;
4521
0
  }
4522
0
  auto *New = new (*this, alignof(PipeType)) PipeType(T, Canonical, ReadOnly);
4523
0
  Types.push_back(New);
4524
0
  PipeTypes.InsertNode(New, InsertPos);
4525
0
  return QualType(New, 0);
4526
0
}
4527
4528
1
QualType ASTContext::adjustStringLiteralBaseType(QualType Ty) const {
4529
  // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
4530
1
  return LangOpts.OpenCL ? getAddrSpaceQualType(Ty, LangAS::opencl_constant)
4531
1
                         : Ty;
4532
1
}
4533
4534
0
QualType ASTContext::getReadPipeType(QualType T) const {
4535
0
  return getPipeType(T, true);
4536
0
}
4537
4538
0
QualType ASTContext::getWritePipeType(QualType T) const {
4539
0
  return getPipeType(T, false);
4540
0
}
4541
4542
0
QualType ASTContext::getBitIntType(bool IsUnsigned, unsigned NumBits) const {
4543
0
  llvm::FoldingSetNodeID ID;
4544
0
  BitIntType::Profile(ID, IsUnsigned, NumBits);
4545
4546
0
  void *InsertPos = nullptr;
4547
0
  if (BitIntType *EIT = BitIntTypes.FindNodeOrInsertPos(ID, InsertPos))
4548
0
    return QualType(EIT, 0);
4549
4550
0
  auto *New = new (*this, alignof(BitIntType)) BitIntType(IsUnsigned, NumBits);
4551
0
  BitIntTypes.InsertNode(New, InsertPos);
4552
0
  Types.push_back(New);
4553
0
  return QualType(New, 0);
4554
0
}
4555
4556
QualType ASTContext::getDependentBitIntType(bool IsUnsigned,
4557
0
                                            Expr *NumBitsExpr) const {
4558
0
  assert(NumBitsExpr->isInstantiationDependent() && "Only good for dependent");
4559
0
  llvm::FoldingSetNodeID ID;
4560
0
  DependentBitIntType::Profile(ID, *this, IsUnsigned, NumBitsExpr);
4561
4562
0
  void *InsertPos = nullptr;
4563
0
  if (DependentBitIntType *Existing =
4564
0
          DependentBitIntTypes.FindNodeOrInsertPos(ID, InsertPos))
4565
0
    return QualType(Existing, 0);
4566
4567
0
  auto *New = new (*this, alignof(DependentBitIntType))
4568
0
      DependentBitIntType(IsUnsigned, NumBitsExpr);
4569
0
  DependentBitIntTypes.InsertNode(New, InsertPos);
4570
4571
0
  Types.push_back(New);
4572
0
  return QualType(New, 0);
4573
0
}
4574
4575
#ifndef NDEBUG
4576
138
static bool NeedsInjectedClassNameType(const RecordDecl *D) {
4577
138
  if (!isa<CXXRecordDecl>(D)) return false;
4578
46
  const auto *RD = cast<CXXRecordDecl>(D);
4579
46
  if (isa<ClassTemplatePartialSpecializationDecl>(RD))
4580
0
    return true;
4581
46
  if (RD->getDescribedClassTemplate() &&
4582
46
      !isa<ClassTemplateSpecializationDecl>(RD))
4583
0
    return true;
4584
46
  return false;
4585
46
}
4586
#endif
4587
4588
/// getInjectedClassNameType - Return the unique reference to the
4589
/// injected class name type for the specified templated declaration.
4590
QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
4591
0
                                              QualType TST) const {
4592
0
  assert(NeedsInjectedClassNameType(Decl));
4593
0
  if (Decl->TypeForDecl) {
4594
0
    assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
4595
0
  } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
4596
0
    assert(PrevDecl->TypeForDecl && "previous declaration has no type");
4597
0
    Decl->TypeForDecl = PrevDecl->TypeForDecl;
4598
0
    assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
4599
0
  } else {
4600
0
    Type *newType = new (*this, alignof(InjectedClassNameType))
4601
0
        InjectedClassNameType(Decl, TST);
4602
0
    Decl->TypeForDecl = newType;
4603
0
    Types.push_back(newType);
4604
0
  }
4605
0
  return QualType(Decl->TypeForDecl, 0);
4606
0
}
4607
4608
/// getTypeDeclType - Return the unique reference to the type for the
4609
/// specified type declaration.
4610
207
QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
4611
207
  assert(Decl && "Passed null for Decl param");
4612
0
  assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
4613
4614
207
  if (const auto *Typedef = dyn_cast<TypedefNameDecl>(Decl))
4615
69
    return getTypedefType(Typedef);
4616
4617
138
  assert(!isa<TemplateTypeParmDecl>(Decl) &&
4618
138
         "Template type parameter types are always available.");
4619
4620
138
  if (const auto *Record = dyn_cast<RecordDecl>(Decl)) {
4621
138
    assert(Record->isFirstDecl() && "struct/union has previous declaration");
4622
0
    assert(!NeedsInjectedClassNameType(Record));
4623
0
    return getRecordType(Record);
4624
138
  } else if (const auto *Enum = dyn_cast<EnumDecl>(Decl)) {
4625
0
    assert(Enum->isFirstDecl() && "enum has previous declaration");
4626
0
    return getEnumType(Enum);
4627
0
  } else if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
4628
0
    return getUnresolvedUsingType(Using);
4629
0
  } else
4630
0
    llvm_unreachable("TypeDecl without a type?");
4631
4632
0
  return QualType(Decl->TypeForDecl, 0);
4633
138
}
4634
4635
/// getTypedefType - Return the unique reference to the type for the
4636
/// specified typedef name decl.
4637
QualType ASTContext::getTypedefType(const TypedefNameDecl *Decl,
4638
69
                                    QualType Underlying) const {
4639
69
  if (!Decl->TypeForDecl) {
4640
69
    if (Underlying.isNull())
4641
69
      Underlying = Decl->getUnderlyingType();
4642
69
    auto *NewType = new (*this, alignof(TypedefType)) TypedefType(
4643
69
        Type::Typedef, Decl, QualType(), getCanonicalType(Underlying));
4644
69
    Decl->TypeForDecl = NewType;
4645
69
    Types.push_back(NewType);
4646
69
    return QualType(NewType, 0);
4647
69
  }
4648
0
  if (Underlying.isNull() || Decl->getUnderlyingType() == Underlying)
4649
0
    return QualType(Decl->TypeForDecl, 0);
4650
0
  assert(hasSameType(Decl->getUnderlyingType(), Underlying));
4651
4652
0
  llvm::FoldingSetNodeID ID;
4653
0
  TypedefType::Profile(ID, Decl, Underlying);
4654
4655
0
  void *InsertPos = nullptr;
4656
0
  if (TypedefType *T = TypedefTypes.FindNodeOrInsertPos(ID, InsertPos)) {
4657
0
    assert(!T->typeMatchesDecl() &&
4658
0
           "non-divergent case should be handled with TypeDecl");
4659
0
    return QualType(T, 0);
4660
0
  }
4661
4662
0
  void *Mem = Allocate(TypedefType::totalSizeToAlloc<QualType>(true),
4663
0
                       alignof(TypedefType));
4664
0
  auto *NewType = new (Mem) TypedefType(Type::Typedef, Decl, Underlying,
4665
0
                                        getCanonicalType(Underlying));
4666
0
  TypedefTypes.InsertNode(NewType, InsertPos);
4667
0
  Types.push_back(NewType);
4668
0
  return QualType(NewType, 0);
4669
0
}
4670
4671
QualType ASTContext::getUsingType(const UsingShadowDecl *Found,
4672
0
                                  QualType Underlying) const {
4673
0
  llvm::FoldingSetNodeID ID;
4674
0
  UsingType::Profile(ID, Found, Underlying);
4675
4676
0
  void *InsertPos = nullptr;
4677
0
  if (UsingType *T = UsingTypes.FindNodeOrInsertPos(ID, InsertPos))
4678
0
    return QualType(T, 0);
4679
4680
0
  const Type *TypeForDecl =
4681
0
      cast<TypeDecl>(Found->getTargetDecl())->getTypeForDecl();
4682
4683
0
  assert(!Underlying.hasLocalQualifiers());
4684
0
  QualType Canon = Underlying->getCanonicalTypeInternal();
4685
0
  assert(TypeForDecl->getCanonicalTypeInternal() == Canon);
4686
4687
0
  if (Underlying.getTypePtr() == TypeForDecl)
4688
0
    Underlying = QualType();
4689
0
  void *Mem =
4690
0
      Allocate(UsingType::totalSizeToAlloc<QualType>(!Underlying.isNull()),
4691
0
               alignof(UsingType));
4692
0
  UsingType *NewType = new (Mem) UsingType(Found, Underlying, Canon);
4693
0
  Types.push_back(NewType);
4694
0
  UsingTypes.InsertNode(NewType, InsertPos);
4695
0
  return QualType(NewType, 0);
4696
0
}
4697
4698
184
QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
4699
184
  if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
4700
4701
138
  if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
4702
0
    if (PrevDecl->TypeForDecl)
4703
0
      return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
4704
4705
138
  auto *newType = new (*this, alignof(RecordType)) RecordType(Decl);
4706
138
  Decl->TypeForDecl = newType;
4707
138
  Types.push_back(newType);
4708
138
  return QualType(newType, 0);
4709
138
}
4710
4711
0
QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
4712
0
  if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
4713
4714
0
  if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
4715
0
    if (PrevDecl->TypeForDecl)
4716
0
      return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
4717
4718
0
  auto *newType = new (*this, alignof(EnumType)) EnumType(Decl);
4719
0
  Decl->TypeForDecl = newType;
4720
0
  Types.push_back(newType);
4721
0
  return QualType(newType, 0);
4722
0
}
4723
4724
QualType ASTContext::getUnresolvedUsingType(
4725
0
    const UnresolvedUsingTypenameDecl *Decl) const {
4726
0
  if (Decl->TypeForDecl)
4727
0
    return QualType(Decl->TypeForDecl, 0);
4728
4729
0
  if (const UnresolvedUsingTypenameDecl *CanonicalDecl =
4730
0
          Decl->getCanonicalDecl())
4731
0
    if (CanonicalDecl->TypeForDecl)
4732
0
      return QualType(Decl->TypeForDecl = CanonicalDecl->TypeForDecl, 0);
4733
4734
0
  Type *newType =
4735
0
      new (*this, alignof(UnresolvedUsingType)) UnresolvedUsingType(Decl);
4736
0
  Decl->TypeForDecl = newType;
4737
0
  Types.push_back(newType);
4738
0
  return QualType(newType, 0);
4739
0
}
4740
4741
QualType ASTContext::getAttributedType(attr::Kind attrKind,
4742
                                       QualType modifiedType,
4743
0
                                       QualType equivalentType) const {
4744
0
  llvm::FoldingSetNodeID id;
4745
0
  AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
4746
4747
0
  void *insertPos = nullptr;
4748
0
  AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
4749
0
  if (type) return QualType(type, 0);
4750
4751
0
  QualType canon = getCanonicalType(equivalentType);
4752
0
  type = new (*this, alignof(AttributedType))
4753
0
      AttributedType(canon, attrKind, modifiedType, equivalentType);
4754
4755
0
  Types.push_back(type);
4756
0
  AttributedTypes.InsertNode(type, insertPos);
4757
4758
0
  return QualType(type, 0);
4759
0
}
4760
4761
QualType ASTContext::getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr,
4762
0
                                             QualType Wrapped) {
4763
0
  llvm::FoldingSetNodeID ID;
4764
0
  BTFTagAttributedType::Profile(ID, Wrapped, BTFAttr);
4765
4766
0
  void *InsertPos = nullptr;
4767
0
  BTFTagAttributedType *Ty =
4768
0
      BTFTagAttributedTypes.FindNodeOrInsertPos(ID, InsertPos);
4769
0
  if (Ty)
4770
0
    return QualType(Ty, 0);
4771
4772
0
  QualType Canon = getCanonicalType(Wrapped);
4773
0
  Ty = new (*this, alignof(BTFTagAttributedType))
4774
0
      BTFTagAttributedType(Canon, Wrapped, BTFAttr);
4775
4776
0
  Types.push_back(Ty);
4777
0
  BTFTagAttributedTypes.InsertNode(Ty, InsertPos);
4778
4779
0
  return QualType(Ty, 0);
4780
0
}
4781
4782
/// Retrieve a substitution-result type.
4783
QualType ASTContext::getSubstTemplateTypeParmType(
4784
    QualType Replacement, Decl *AssociatedDecl, unsigned Index,
4785
0
    std::optional<unsigned> PackIndex) const {
4786
0
  llvm::FoldingSetNodeID ID;
4787
0
  SubstTemplateTypeParmType::Profile(ID, Replacement, AssociatedDecl, Index,
4788
0
                                     PackIndex);
4789
0
  void *InsertPos = nullptr;
4790
0
  SubstTemplateTypeParmType *SubstParm =
4791
0
      SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4792
4793
0
  if (!SubstParm) {
4794
0
    void *Mem = Allocate(SubstTemplateTypeParmType::totalSizeToAlloc<QualType>(
4795
0
                             !Replacement.isCanonical()),
4796
0
                         alignof(SubstTemplateTypeParmType));
4797
0
    SubstParm = new (Mem) SubstTemplateTypeParmType(Replacement, AssociatedDecl,
4798
0
                                                    Index, PackIndex);
4799
0
    Types.push_back(SubstParm);
4800
0
    SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
4801
0
  }
4802
4803
0
  return QualType(SubstParm, 0);
4804
0
}
4805
4806
/// Retrieve a
4807
QualType
4808
ASTContext::getSubstTemplateTypeParmPackType(Decl *AssociatedDecl,
4809
                                             unsigned Index, bool Final,
4810
0
                                             const TemplateArgument &ArgPack) {
4811
0
#ifndef NDEBUG
4812
0
  for (const auto &P : ArgPack.pack_elements())
4813
0
    assert(P.getKind() == TemplateArgument::Type && "Pack contains a non-type");
4814
0
#endif
4815
4816
0
  llvm::FoldingSetNodeID ID;
4817
0
  SubstTemplateTypeParmPackType::Profile(ID, AssociatedDecl, Index, Final,
4818
0
                                         ArgPack);
4819
0
  void *InsertPos = nullptr;
4820
0
  if (SubstTemplateTypeParmPackType *SubstParm =
4821
0
          SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
4822
0
    return QualType(SubstParm, 0);
4823
4824
0
  QualType Canon;
4825
0
  {
4826
0
    TemplateArgument CanonArgPack = getCanonicalTemplateArgument(ArgPack);
4827
0
    if (!AssociatedDecl->isCanonicalDecl() ||
4828
0
        !CanonArgPack.structurallyEquals(ArgPack)) {
4829
0
      Canon = getSubstTemplateTypeParmPackType(
4830
0
          AssociatedDecl->getCanonicalDecl(), Index, Final, CanonArgPack);
4831
0
      [[maybe_unused]] const auto *Nothing =
4832
0
          SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
4833
0
      assert(!Nothing);
4834
0
    }
4835
0
  }
4836
4837
0
  auto *SubstParm = new (*this, alignof(SubstTemplateTypeParmPackType))
4838
0
      SubstTemplateTypeParmPackType(Canon, AssociatedDecl, Index, Final,
4839
0
                                    ArgPack);
4840
0
  Types.push_back(SubstParm);
4841
0
  SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos);
4842
0
  return QualType(SubstParm, 0);
4843
0
}
4844
4845
/// Retrieve the template type parameter type for a template
4846
/// parameter or parameter pack with the given depth, index, and (optionally)
4847
/// name.
4848
QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
4849
                                             bool ParameterPack,
4850
0
                                             TemplateTypeParmDecl *TTPDecl) const {
4851
0
  llvm::FoldingSetNodeID ID;
4852
0
  TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
4853
0
  void *InsertPos = nullptr;
4854
0
  TemplateTypeParmType *TypeParm
4855
0
    = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4856
4857
0
  if (TypeParm)
4858
0
    return QualType(TypeParm, 0);
4859
4860
0
  if (TTPDecl) {
4861
0
    QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
4862
0
    TypeParm = new (*this, alignof(TemplateTypeParmType))
4863
0
        TemplateTypeParmType(TTPDecl, Canon);
4864
4865
0
    TemplateTypeParmType *TypeCheck
4866
0
      = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4867
0
    assert(!TypeCheck && "Template type parameter canonical type broken");
4868
0
    (void)TypeCheck;
4869
0
  } else
4870
0
    TypeParm = new (*this, alignof(TemplateTypeParmType))
4871
0
        TemplateTypeParmType(Depth, Index, ParameterPack);
4872
4873
0
  Types.push_back(TypeParm);
4874
0
  TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
4875
4876
0
  return QualType(TypeParm, 0);
4877
0
}
4878
4879
TypeSourceInfo *
4880
ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
4881
                                              SourceLocation NameLoc,
4882
                                        const TemplateArgumentListInfo &Args,
4883
0
                                              QualType Underlying) const {
4884
0
  assert(!Name.getAsDependentTemplateName() &&
4885
0
         "No dependent template names here!");
4886
0
  QualType TST =
4887
0
      getTemplateSpecializationType(Name, Args.arguments(), Underlying);
4888
4889
0
  TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
4890
0
  TemplateSpecializationTypeLoc TL =
4891
0
      DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
4892
0
  TL.setTemplateKeywordLoc(SourceLocation());
4893
0
  TL.setTemplateNameLoc(NameLoc);
4894
0
  TL.setLAngleLoc(Args.getLAngleLoc());
4895
0
  TL.setRAngleLoc(Args.getRAngleLoc());
4896
0
  for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
4897
0
    TL.setArgLocInfo(i, Args[i].getLocInfo());
4898
0
  return DI;
4899
0
}
4900
4901
QualType
4902
ASTContext::getTemplateSpecializationType(TemplateName Template,
4903
                                          ArrayRef<TemplateArgumentLoc> Args,
4904
0
                                          QualType Underlying) const {
4905
0
  assert(!Template.getAsDependentTemplateName() &&
4906
0
         "No dependent template names here!");
4907
4908
0
  SmallVector<TemplateArgument, 4> ArgVec;
4909
0
  ArgVec.reserve(Args.size());
4910
0
  for (const TemplateArgumentLoc &Arg : Args)
4911
0
    ArgVec.push_back(Arg.getArgument());
4912
4913
0
  return getTemplateSpecializationType(Template, ArgVec, Underlying);
4914
0
}
4915
4916
#ifndef NDEBUG
4917
0
static bool hasAnyPackExpansions(ArrayRef<TemplateArgument> Args) {
4918
0
  for (const TemplateArgument &Arg : Args)
4919
0
    if (Arg.isPackExpansion())
4920
0
      return true;
4921
4922
0
  return true;
4923
0
}
4924
#endif
4925
4926
QualType
4927
ASTContext::getTemplateSpecializationType(TemplateName Template,
4928
                                          ArrayRef<TemplateArgument> Args,
4929
0
                                          QualType Underlying) const {
4930
0
  assert(!Template.getAsDependentTemplateName() &&
4931
0
         "No dependent template names here!");
4932
  // Look through qualified template names.
4933
0
  if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
4934
0
    Template = QTN->getUnderlyingTemplate();
4935
4936
0
  const auto *TD = Template.getAsTemplateDecl();
4937
0
  bool IsTypeAlias = TD && TD->isTypeAlias();
4938
0
  QualType CanonType;
4939
0
  if (!Underlying.isNull())
4940
0
    CanonType = getCanonicalType(Underlying);
4941
0
  else {
4942
    // We can get here with an alias template when the specialization contains
4943
    // a pack expansion that does not match up with a parameter pack.
4944
0
    assert((!IsTypeAlias || hasAnyPackExpansions(Args)) &&
4945
0
           "Caller must compute aliased type");
4946
0
    IsTypeAlias = false;
4947
0
    CanonType = getCanonicalTemplateSpecializationType(Template, Args);
4948
0
  }
4949
4950
  // Allocate the (non-canonical) template specialization type, but don't
4951
  // try to unique it: these types typically have location information that
4952
  // we don't unique and don't want to lose.
4953
0
  void *Mem = Allocate(sizeof(TemplateSpecializationType) +
4954
0
                           sizeof(TemplateArgument) * Args.size() +
4955
0
                           (IsTypeAlias ? sizeof(QualType) : 0),
4956
0
                       alignof(TemplateSpecializationType));
4957
0
  auto *Spec
4958
0
    = new (Mem) TemplateSpecializationType(Template, Args, CanonType,
4959
0
                                         IsTypeAlias ? Underlying : QualType());
4960
4961
0
  Types.push_back(Spec);
4962
0
  return QualType(Spec, 0);
4963
0
}
4964
4965
QualType ASTContext::getCanonicalTemplateSpecializationType(
4966
0
    TemplateName Template, ArrayRef<TemplateArgument> Args) const {
4967
0
  assert(!Template.getAsDependentTemplateName() &&
4968
0
         "No dependent template names here!");
4969
4970
  // Look through qualified template names.
4971
0
  if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
4972
0
    Template = TemplateName(QTN->getUnderlyingTemplate());
4973
4974
  // Build the canonical template specialization type.
4975
0
  TemplateName CanonTemplate = getCanonicalTemplateName(Template);
4976
0
  bool AnyNonCanonArgs = false;
4977
0
  auto CanonArgs =
4978
0
      ::getCanonicalTemplateArguments(*this, Args, AnyNonCanonArgs);
4979
4980
  // Determine whether this canonical template specialization type already
4981
  // exists.
4982
0
  llvm::FoldingSetNodeID ID;
4983
0
  TemplateSpecializationType::Profile(ID, CanonTemplate,
4984
0
                                      CanonArgs, *this);
4985
4986
0
  void *InsertPos = nullptr;
4987
0
  TemplateSpecializationType *Spec
4988
0
    = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
4989
4990
0
  if (!Spec) {
4991
    // Allocate a new canonical template specialization type.
4992
0
    void *Mem = Allocate((sizeof(TemplateSpecializationType) +
4993
0
                          sizeof(TemplateArgument) * CanonArgs.size()),
4994
0
                         alignof(TemplateSpecializationType));
4995
0
    Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
4996
0
                                                CanonArgs,
4997
0
                                                QualType(), QualType());
4998
0
    Types.push_back(Spec);
4999
0
    TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
5000
0
  }
5001
5002
0
  assert(Spec->isDependentType() &&
5003
0
         "Non-dependent template-id type must have a canonical type");
5004
0
  return QualType(Spec, 0);
5005
0
}
5006
5007
QualType ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
5008
                                       NestedNameSpecifier *NNS,
5009
                                       QualType NamedType,
5010
0
                                       TagDecl *OwnedTagDecl) const {
5011
0
  llvm::FoldingSetNodeID ID;
5012
0
  ElaboratedType::Profile(ID, Keyword, NNS, NamedType, OwnedTagDecl);
5013
5014
0
  void *InsertPos = nullptr;
5015
0
  ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
5016
0
  if (T)
5017
0
    return QualType(T, 0);
5018
5019
0
  QualType Canon = NamedType;
5020
0
  if (!Canon.isCanonical()) {
5021
0
    Canon = getCanonicalType(NamedType);
5022
0
    ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
5023
0
    assert(!CheckT && "Elaborated canonical type broken");
5024
0
    (void)CheckT;
5025
0
  }
5026
5027
0
  void *Mem =
5028
0
      Allocate(ElaboratedType::totalSizeToAlloc<TagDecl *>(!!OwnedTagDecl),
5029
0
               alignof(ElaboratedType));
5030
0
  T = new (Mem) ElaboratedType(Keyword, NNS, NamedType, Canon, OwnedTagDecl);
5031
5032
0
  Types.push_back(T);
5033
0
  ElaboratedTypes.InsertNode(T, InsertPos);
5034
0
  return QualType(T, 0);
5035
0
}
5036
5037
QualType
5038
87
ASTContext::getParenType(QualType InnerType) const {
5039
87
  llvm::FoldingSetNodeID ID;
5040
87
  ParenType::Profile(ID, InnerType);
5041
5042
87
  void *InsertPos = nullptr;
5043
87
  ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
5044
87
  if (T)
5045
55
    return QualType(T, 0);
5046
5047
32
  QualType Canon = InnerType;
5048
32
  if (!Canon.isCanonical()) {
5049
3
    Canon = getCanonicalType(InnerType);
5050
3
    ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
5051
3
    assert(!CheckT && "Paren canonical type broken");
5052
0
    (void)CheckT;
5053
3
  }
5054
5055
0
  T = new (*this, alignof(ParenType)) ParenType(InnerType, Canon);
5056
32
  Types.push_back(T);
5057
32
  ParenTypes.InsertNode(T, InsertPos);
5058
32
  return QualType(T, 0);
5059
87
}
5060
5061
QualType
5062
ASTContext::getMacroQualifiedType(QualType UnderlyingTy,
5063
0
                                  const IdentifierInfo *MacroII) const {
5064
0
  QualType Canon = UnderlyingTy;
5065
0
  if (!Canon.isCanonical())
5066
0
    Canon = getCanonicalType(UnderlyingTy);
5067
5068
0
  auto *newType = new (*this, alignof(MacroQualifiedType))
5069
0
      MacroQualifiedType(UnderlyingTy, Canon, MacroII);
5070
0
  Types.push_back(newType);
5071
0
  return QualType(newType, 0);
5072
0
}
5073
5074
QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
5075
                                          NestedNameSpecifier *NNS,
5076
                                          const IdentifierInfo *Name,
5077
0
                                          QualType Canon) const {
5078
0
  if (Canon.isNull()) {
5079
0
    NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5080
0
    if (CanonNNS != NNS)
5081
0
      Canon = getDependentNameType(Keyword, CanonNNS, Name);
5082
0
  }
5083
5084
0
  llvm::FoldingSetNodeID ID;
5085
0
  DependentNameType::Profile(ID, Keyword, NNS, Name);
5086
5087
0
  void *InsertPos = nullptr;
5088
0
  DependentNameType *T
5089
0
    = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
5090
0
  if (T)
5091
0
    return QualType(T, 0);
5092
5093
0
  T = new (*this, alignof(DependentNameType))
5094
0
      DependentNameType(Keyword, NNS, Name, Canon);
5095
0
  Types.push_back(T);
5096
0
  DependentNameTypes.InsertNode(T, InsertPos);
5097
0
  return QualType(T, 0);
5098
0
}
5099
5100
QualType ASTContext::getDependentTemplateSpecializationType(
5101
    ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
5102
0
    const IdentifierInfo *Name, ArrayRef<TemplateArgumentLoc> Args) const {
5103
  // TODO: avoid this copy
5104
0
  SmallVector<TemplateArgument, 16> ArgCopy;
5105
0
  for (unsigned I = 0, E = Args.size(); I != E; ++I)
5106
0
    ArgCopy.push_back(Args[I].getArgument());
5107
0
  return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy);
5108
0
}
5109
5110
QualType
5111
ASTContext::getDependentTemplateSpecializationType(
5112
                                 ElaboratedTypeKeyword Keyword,
5113
                                 NestedNameSpecifier *NNS,
5114
                                 const IdentifierInfo *Name,
5115
0
                                 ArrayRef<TemplateArgument> Args) const {
5116
0
  assert((!NNS || NNS->isDependent()) &&
5117
0
         "nested-name-specifier must be dependent");
5118
5119
0
  llvm::FoldingSetNodeID ID;
5120
0
  DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
5121
0
                                               Name, Args);
5122
5123
0
  void *InsertPos = nullptr;
5124
0
  DependentTemplateSpecializationType *T
5125
0
    = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
5126
0
  if (T)
5127
0
    return QualType(T, 0);
5128
5129
0
  NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5130
5131
0
  ElaboratedTypeKeyword CanonKeyword = Keyword;
5132
0
  if (Keyword == ElaboratedTypeKeyword::None)
5133
0
    CanonKeyword = ElaboratedTypeKeyword::Typename;
5134
5135
0
  bool AnyNonCanonArgs = false;
5136
0
  auto CanonArgs =
5137
0
      ::getCanonicalTemplateArguments(*this, Args, AnyNonCanonArgs);
5138
5139
0
  QualType Canon;
5140
0
  if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
5141
0
    Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
5142
0
                                                   Name,
5143
0
                                                   CanonArgs);
5144
5145
    // Find the insert position again.
5146
0
    [[maybe_unused]] auto *Nothing =
5147
0
        DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
5148
0
    assert(!Nothing && "canonical type broken");
5149
0
  }
5150
5151
0
  void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
5152
0
                        sizeof(TemplateArgument) * Args.size()),
5153
0
                       alignof(DependentTemplateSpecializationType));
5154
0
  T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
5155
0
                                                    Name, Args, Canon);
5156
0
  Types.push_back(T);
5157
0
  DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
5158
0
  return QualType(T, 0);
5159
0
}
5160
5161
0
TemplateArgument ASTContext::getInjectedTemplateArg(NamedDecl *Param) {
5162
0
  TemplateArgument Arg;
5163
0
  if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
5164
0
    QualType ArgType = getTypeDeclType(TTP);
5165
0
    if (TTP->isParameterPack())
5166
0
      ArgType = getPackExpansionType(ArgType, std::nullopt);
5167
5168
0
    Arg = TemplateArgument(ArgType);
5169
0
  } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5170
0
    QualType T =
5171
0
        NTTP->getType().getNonPackExpansionType().getNonLValueExprType(*this);
5172
    // For class NTTPs, ensure we include the 'const' so the type matches that
5173
    // of a real template argument.
5174
    // FIXME: It would be more faithful to model this as something like an
5175
    // lvalue-to-rvalue conversion applied to a const-qualified lvalue.
5176
0
    if (T->isRecordType())
5177
0
      T.addConst();
5178
0
    Expr *E = new (*this) DeclRefExpr(
5179
0
        *this, NTTP, /*RefersToEnclosingVariableOrCapture*/ false, T,
5180
0
        Expr::getValueKindForType(NTTP->getType()), NTTP->getLocation());
5181
5182
0
    if (NTTP->isParameterPack())
5183
0
      E = new (*this)
5184
0
          PackExpansionExpr(DependentTy, E, NTTP->getLocation(), std::nullopt);
5185
0
    Arg = TemplateArgument(E);
5186
0
  } else {
5187
0
    auto *TTP = cast<TemplateTemplateParmDecl>(Param);
5188
0
    if (TTP->isParameterPack())
5189
0
      Arg = TemplateArgument(TemplateName(TTP), std::optional<unsigned>());
5190
0
    else
5191
0
      Arg = TemplateArgument(TemplateName(TTP));
5192
0
  }
5193
5194
0
  if (Param->isTemplateParameterPack())
5195
0
    Arg = TemplateArgument::CreatePackCopy(*this, Arg);
5196
5197
0
  return Arg;
5198
0
}
5199
5200
void
5201
ASTContext::getInjectedTemplateArgs(const TemplateParameterList *Params,
5202
0
                                    SmallVectorImpl<TemplateArgument> &Args) {
5203
0
  Args.reserve(Args.size() + Params->size());
5204
5205
0
  for (NamedDecl *Param : *Params)
5206
0
    Args.push_back(getInjectedTemplateArg(Param));
5207
0
}
5208
5209
QualType ASTContext::getPackExpansionType(QualType Pattern,
5210
                                          std::optional<unsigned> NumExpansions,
5211
0
                                          bool ExpectPackInType) {
5212
0
  assert((!ExpectPackInType || Pattern->containsUnexpandedParameterPack()) &&
5213
0
         "Pack expansions must expand one or more parameter packs");
5214
5215
0
  llvm::FoldingSetNodeID ID;
5216
0
  PackExpansionType::Profile(ID, Pattern, NumExpansions);
5217
5218
0
  void *InsertPos = nullptr;
5219
0
  PackExpansionType *T = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
5220
0
  if (T)
5221
0
    return QualType(T, 0);
5222
5223
0
  QualType Canon;
5224
0
  if (!Pattern.isCanonical()) {
5225
0
    Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions,
5226
0
                                 /*ExpectPackInType=*/false);
5227
5228
    // Find the insert position again, in case we inserted an element into
5229
    // PackExpansionTypes and invalidated our insert position.
5230
0
    PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
5231
0
  }
5232
5233
0
  T = new (*this, alignof(PackExpansionType))
5234
0
      PackExpansionType(Pattern, Canon, NumExpansions);
5235
0
  Types.push_back(T);
5236
0
  PackExpansionTypes.InsertNode(T, InsertPos);
5237
0
  return QualType(T, 0);
5238
0
}
5239
5240
/// CmpProtocolNames - Comparison predicate for sorting protocols
5241
/// alphabetically.
5242
static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
5243
0
                            ObjCProtocolDecl *const *RHS) {
5244
0
  return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
5245
0
}
5246
5247
46
static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) {
5248
46
  if (Protocols.empty()) return true;
5249
5250
0
  if (Protocols[0]->getCanonicalDecl() != Protocols[0])
5251
0
    return false;
5252
5253
0
  for (unsigned i = 1; i != Protocols.size(); ++i)
5254
0
    if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
5255
0
        Protocols[i]->getCanonicalDecl() != Protocols[i])
5256
0
      return false;
5257
0
  return true;
5258
0
}
5259
5260
static void
5261
0
SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) {
5262
  // Sort protocols, keyed by name.
5263
0
  llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
5264
5265
  // Canonicalize.
5266
0
  for (ObjCProtocolDecl *&P : Protocols)
5267
0
    P = P->getCanonicalDecl();
5268
5269
  // Remove duplicates.
5270
0
  auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end());
5271
0
  Protocols.erase(ProtocolsEnd, Protocols.end());
5272
0
}
5273
5274
QualType ASTContext::getObjCObjectType(QualType BaseType,
5275
                                       ObjCProtocolDecl * const *Protocols,
5276
46
                                       unsigned NumProtocols) const {
5277
46
  return getObjCObjectType(BaseType, {},
5278
46
                           llvm::ArrayRef(Protocols, NumProtocols),
5279
46
                           /*isKindOf=*/false);
5280
46
}
5281
5282
QualType ASTContext::getObjCObjectType(
5283
           QualType baseType,
5284
           ArrayRef<QualType> typeArgs,
5285
           ArrayRef<ObjCProtocolDecl *> protocols,
5286
126
           bool isKindOf) const {
5287
  // If the base type is an interface and there aren't any protocols or
5288
  // type arguments to add, then the interface type will do just fine.
5289
126
  if (typeArgs.empty() && protocols.empty() && !isKindOf &&
5290
126
      isa<ObjCInterfaceType>(baseType))
5291
0
    return baseType;
5292
5293
  // Look in the folding set for an existing type.
5294
126
  llvm::FoldingSetNodeID ID;
5295
126
  ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
5296
126
  void *InsertPos = nullptr;
5297
126
  if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
5298
80
    return QualType(QT, 0);
5299
5300
  // Determine the type arguments to be used for canonicalization,
5301
  // which may be explicitly specified here or written on the base
5302
  // type.
5303
46
  ArrayRef<QualType> effectiveTypeArgs = typeArgs;
5304
46
  if (effectiveTypeArgs.empty()) {
5305
46
    if (const auto *baseObject = baseType->getAs<ObjCObjectType>())
5306
0
      effectiveTypeArgs = baseObject->getTypeArgs();
5307
46
  }
5308
5309
  // Build the canonical type, which has the canonical base type and a
5310
  // sorted-and-uniqued list of protocols and the type arguments
5311
  // canonicalized.
5312
46
  QualType canonical;
5313
46
  bool typeArgsAreCanonical = llvm::all_of(
5314
46
      effectiveTypeArgs, [&](QualType type) { return type.isCanonical(); });
5315
46
  bool protocolsSorted = areSortedAndUniqued(protocols);
5316
46
  if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
5317
    // Determine the canonical type arguments.
5318
0
    ArrayRef<QualType> canonTypeArgs;
5319
0
    SmallVector<QualType, 4> canonTypeArgsVec;
5320
0
    if (!typeArgsAreCanonical) {
5321
0
      canonTypeArgsVec.reserve(effectiveTypeArgs.size());
5322
0
      for (auto typeArg : effectiveTypeArgs)
5323
0
        canonTypeArgsVec.push_back(getCanonicalType(typeArg));
5324
0
      canonTypeArgs = canonTypeArgsVec;
5325
0
    } else {
5326
0
      canonTypeArgs = effectiveTypeArgs;
5327
0
    }
5328
5329
0
    ArrayRef<ObjCProtocolDecl *> canonProtocols;
5330
0
    SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
5331
0
    if (!protocolsSorted) {
5332
0
      canonProtocolsVec.append(protocols.begin(), protocols.end());
5333
0
      SortAndUniqueProtocols(canonProtocolsVec);
5334
0
      canonProtocols = canonProtocolsVec;
5335
0
    } else {
5336
0
      canonProtocols = protocols;
5337
0
    }
5338
5339
0
    canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
5340
0
                                  canonProtocols, isKindOf);
5341
5342
    // Regenerate InsertPos.
5343
0
    ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
5344
0
  }
5345
5346
46
  unsigned size = sizeof(ObjCObjectTypeImpl);
5347
46
  size += typeArgs.size() * sizeof(QualType);
5348
46
  size += protocols.size() * sizeof(ObjCProtocolDecl *);
5349
46
  void *mem = Allocate(size, alignof(ObjCObjectTypeImpl));
5350
46
  auto *T =
5351
46
    new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
5352
46
                                 isKindOf);
5353
5354
46
  Types.push_back(T);
5355
46
  ObjCObjectTypes.InsertNode(T, InsertPos);
5356
46
  return QualType(T, 0);
5357
126
}
5358
5359
/// Apply Objective-C protocol qualifiers to the given type.
5360
/// If this is for the canonical type of a type parameter, we can apply
5361
/// protocol qualifiers on the ObjCObjectPointerType.
5362
QualType
5363
ASTContext::applyObjCProtocolQualifiers(QualType type,
5364
                  ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
5365
0
                  bool allowOnPointerType) const {
5366
0
  hasError = false;
5367
5368
0
  if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
5369
0
    return getObjCTypeParamType(objT->getDecl(), protocols);
5370
0
  }
5371
5372
  // Apply protocol qualifiers to ObjCObjectPointerType.
5373
0
  if (allowOnPointerType) {
5374
0
    if (const auto *objPtr =
5375
0
            dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
5376
0
      const ObjCObjectType *objT = objPtr->getObjectType();
5377
      // Merge protocol lists and construct ObjCObjectType.
5378
0
      SmallVector<ObjCProtocolDecl*, 8> protocolsVec;
5379
0
      protocolsVec.append(objT->qual_begin(),
5380
0
                          objT->qual_end());
5381
0
      protocolsVec.append(protocols.begin(), protocols.end());
5382
0
      ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
5383
0
      type = getObjCObjectType(
5384
0
             objT->getBaseType(),
5385
0
             objT->getTypeArgsAsWritten(),
5386
0
             protocols,
5387
0
             objT->isKindOfTypeAsWritten());
5388
0
      return getObjCObjectPointerType(type);
5389
0
    }
5390
0
  }
5391
5392
  // Apply protocol qualifiers to ObjCObjectType.
5393
0
  if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
5394
    // FIXME: Check for protocols to which the class type is already
5395
    // known to conform.
5396
5397
0
    return getObjCObjectType(objT->getBaseType(),
5398
0
                             objT->getTypeArgsAsWritten(),
5399
0
                             protocols,
5400
0
                             objT->isKindOfTypeAsWritten());
5401
0
  }
5402
5403
  // If the canonical type is ObjCObjectType, ...
5404
0
  if (type->isObjCObjectType()) {
5405
    // Silently overwrite any existing protocol qualifiers.
5406
    // TODO: determine whether that's the right thing to do.
5407
5408
    // FIXME: Check for protocols to which the class type is already
5409
    // known to conform.
5410
0
    return getObjCObjectType(type, {}, protocols, false);
5411
0
  }
5412
5413
  // id<protocol-list>
5414
0
  if (type->isObjCIdType()) {
5415
0
    const auto *objPtr = type->castAs<ObjCObjectPointerType>();
5416
0
    type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols,
5417
0
                                 objPtr->isKindOfType());
5418
0
    return getObjCObjectPointerType(type);
5419
0
  }
5420
5421
  // Class<protocol-list>
5422
0
  if (type->isObjCClassType()) {
5423
0
    const auto *objPtr = type->castAs<ObjCObjectPointerType>();
5424
0
    type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols,
5425
0
                                 objPtr->isKindOfType());
5426
0
    return getObjCObjectPointerType(type);
5427
0
  }
5428
5429
0
  hasError = true;
5430
0
  return type;
5431
0
}
5432
5433
QualType
5434
ASTContext::getObjCTypeParamType(const ObjCTypeParamDecl *Decl,
5435
0
                                 ArrayRef<ObjCProtocolDecl *> protocols) const {
5436
  // Look in the folding set for an existing type.
5437
0
  llvm::FoldingSetNodeID ID;
5438
0
  ObjCTypeParamType::Profile(ID, Decl, Decl->getUnderlyingType(), protocols);
5439
0
  void *InsertPos = nullptr;
5440
0
  if (ObjCTypeParamType *TypeParam =
5441
0
      ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
5442
0
    return QualType(TypeParam, 0);
5443
5444
  // We canonicalize to the underlying type.
5445
0
  QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
5446
0
  if (!protocols.empty()) {
5447
    // Apply the protocol qualifers.
5448
0
    bool hasError;
5449
0
    Canonical = getCanonicalType(applyObjCProtocolQualifiers(
5450
0
        Canonical, protocols, hasError, true /*allowOnPointerType*/));
5451
0
    assert(!hasError && "Error when apply protocol qualifier to bound type");
5452
0
  }
5453
5454
0
  unsigned size = sizeof(ObjCTypeParamType);
5455
0
  size += protocols.size() * sizeof(ObjCProtocolDecl *);
5456
0
  void *mem = Allocate(size, alignof(ObjCTypeParamType));
5457
0
  auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols);
5458
5459
0
  Types.push_back(newType);
5460
0
  ObjCTypeParamTypes.InsertNode(newType, InsertPos);
5461
0
  return QualType(newType, 0);
5462
0
}
5463
5464
void ASTContext::adjustObjCTypeParamBoundType(const ObjCTypeParamDecl *Orig,
5465
0
                                              ObjCTypeParamDecl *New) const {
5466
0
  New->setTypeSourceInfo(getTrivialTypeSourceInfo(Orig->getUnderlyingType()));
5467
  // Update TypeForDecl after updating TypeSourceInfo.
5468
0
  auto NewTypeParamTy = cast<ObjCTypeParamType>(New->getTypeForDecl());
5469
0
  SmallVector<ObjCProtocolDecl *, 8> protocols;
5470
0
  protocols.append(NewTypeParamTy->qual_begin(), NewTypeParamTy->qual_end());
5471
0
  QualType UpdatedTy = getObjCTypeParamType(New, protocols);
5472
0
  New->setTypeForDecl(UpdatedTy.getTypePtr());
5473
0
}
5474
5475
/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
5476
/// protocol list adopt all protocols in QT's qualified-id protocol
5477
/// list.
5478
bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
5479
0
                                                ObjCInterfaceDecl *IC) {
5480
0
  if (!QT->isObjCQualifiedIdType())
5481
0
    return false;
5482
5483
0
  if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) {
5484
    // If both the right and left sides have qualifiers.
5485
0
    for (auto *Proto : OPT->quals()) {
5486
0
      if (!IC->ClassImplementsProtocol(Proto, false))
5487
0
        return false;
5488
0
    }
5489
0
    return true;
5490
0
  }
5491
0
  return false;
5492
0
}
5493
5494
/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
5495
/// QT's qualified-id protocol list adopt all protocols in IDecl's list
5496
/// of protocols.
5497
bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
5498
0
                                                ObjCInterfaceDecl *IDecl) {
5499
0
  if (!QT->isObjCQualifiedIdType())
5500
0
    return false;
5501
0
  const auto *OPT = QT->getAs<ObjCObjectPointerType>();
5502
0
  if (!OPT)
5503
0
    return false;
5504
0
  if (!IDecl->hasDefinition())
5505
0
    return false;
5506
0
  llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
5507
0
  CollectInheritedProtocols(IDecl, InheritedProtocols);
5508
0
  if (InheritedProtocols.empty())
5509
0
    return false;
5510
  // Check that if every protocol in list of id<plist> conforms to a protocol
5511
  // of IDecl's, then bridge casting is ok.
5512
0
  bool Conforms = false;
5513
0
  for (auto *Proto : OPT->quals()) {
5514
0
    Conforms = false;
5515
0
    for (auto *PI : InheritedProtocols) {
5516
0
      if (ProtocolCompatibleWithProtocol(Proto, PI)) {
5517
0
        Conforms = true;
5518
0
        break;
5519
0
      }
5520
0
    }
5521
0
    if (!Conforms)
5522
0
      break;
5523
0
  }
5524
0
  if (Conforms)
5525
0
    return true;
5526
5527
0
  for (auto *PI : InheritedProtocols) {
5528
    // If both the right and left sides have qualifiers.
5529
0
    bool Adopts = false;
5530
0
    for (auto *Proto : OPT->quals()) {
5531
      // return 'true' if 'PI' is in the inheritance hierarchy of Proto
5532
0
      if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
5533
0
        break;
5534
0
    }
5535
0
    if (!Adopts)
5536
0
      return false;
5537
0
  }
5538
0
  return true;
5539
0
}
5540
5541
/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
5542
/// the given object type.
5543
126
QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
5544
126
  llvm::FoldingSetNodeID ID;
5545
126
  ObjCObjectPointerType::Profile(ID, ObjectT);
5546
5547
126
  void *InsertPos = nullptr;
5548
126
  if (ObjCObjectPointerType *QT =
5549
126
              ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
5550
80
    return QualType(QT, 0);
5551
5552
  // Find the canonical object type.
5553
46
  QualType Canonical;
5554
46
  if (!ObjectT.isCanonical()) {
5555
0
    Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
5556
5557
    // Regenerate InsertPos.
5558
0
    ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
5559
0
  }
5560
5561
  // No match.
5562
46
  void *Mem =
5563
46
      Allocate(sizeof(ObjCObjectPointerType), alignof(ObjCObjectPointerType));
5564
46
  auto *QType =
5565
46
    new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
5566
5567
46
  Types.push_back(QType);
5568
46
  ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
5569
46
  return QualType(QType, 0);
5570
126
}
5571
5572
/// getObjCInterfaceType - Return the unique reference to the type for the
5573
/// specified ObjC interface decl. The list of protocols is optional.
5574
QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
5575
23
                                          ObjCInterfaceDecl *PrevDecl) const {
5576
23
  if (Decl->TypeForDecl)
5577
0
    return QualType(Decl->TypeForDecl, 0);
5578
5579
23
  if (PrevDecl) {
5580
0
    assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
5581
0
    Decl->TypeForDecl = PrevDecl->TypeForDecl;
5582
0
    return QualType(PrevDecl->TypeForDecl, 0);
5583
0
  }
5584
5585
  // Prefer the definition, if there is one.
5586
23
  if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
5587
0
    Decl = Def;
5588
5589
23
  void *Mem = Allocate(sizeof(ObjCInterfaceType), alignof(ObjCInterfaceType));
5590
23
  auto *T = new (Mem) ObjCInterfaceType(Decl);
5591
23
  Decl->TypeForDecl = T;
5592
23
  Types.push_back(T);
5593
23
  return QualType(T, 0);
5594
23
}
5595
5596
/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
5597
/// TypeOfExprType AST's (since expression's are never shared). For example,
5598
/// multiple declarations that refer to "typeof(x)" all contain different
5599
/// DeclRefExpr's. This doesn't effect the type checker, since it operates
5600
/// on canonical type's (which are always unique).
5601
0
QualType ASTContext::getTypeOfExprType(Expr *tofExpr, TypeOfKind Kind) const {
5602
0
  TypeOfExprType *toe;
5603
0
  if (tofExpr->isTypeDependent()) {
5604
0
    llvm::FoldingSetNodeID ID;
5605
0
    DependentTypeOfExprType::Profile(ID, *this, tofExpr,
5606
0
                                     Kind == TypeOfKind::Unqualified);
5607
5608
0
    void *InsertPos = nullptr;
5609
0
    DependentTypeOfExprType *Canon =
5610
0
        DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
5611
0
    if (Canon) {
5612
      // We already have a "canonical" version of an identical, dependent
5613
      // typeof(expr) type. Use that as our canonical type.
5614
0
      toe = new (*this, alignof(TypeOfExprType))
5615
0
          TypeOfExprType(tofExpr, Kind, QualType((TypeOfExprType *)Canon, 0));
5616
0
    } else {
5617
      // Build a new, canonical typeof(expr) type.
5618
0
      Canon = new (*this, alignof(DependentTypeOfExprType))
5619
0
          DependentTypeOfExprType(tofExpr, Kind);
5620
0
      DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
5621
0
      toe = Canon;
5622
0
    }
5623
0
  } else {
5624
0
    QualType Canonical = getCanonicalType(tofExpr->getType());
5625
0
    toe = new (*this, alignof(TypeOfExprType))
5626
0
        TypeOfExprType(tofExpr, Kind, Canonical);
5627
0
  }
5628
0
  Types.push_back(toe);
5629
0
  return QualType(toe, 0);
5630
0
}
5631
5632
/// getTypeOfType -  Unlike many "get<Type>" functions, we don't unique
5633
/// TypeOfType nodes. The only motivation to unique these nodes would be
5634
/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
5635
/// an issue. This doesn't affect the type checker, since it operates
5636
/// on canonical types (which are always unique).
5637
0
QualType ASTContext::getTypeOfType(QualType tofType, TypeOfKind Kind) const {
5638
0
  QualType Canonical = getCanonicalType(tofType);
5639
0
  auto *tot =
5640
0
      new (*this, alignof(TypeOfType)) TypeOfType(tofType, Canonical, Kind);
5641
0
  Types.push_back(tot);
5642
0
  return QualType(tot, 0);
5643
0
}
5644
5645
/// getReferenceQualifiedType - Given an expr, will return the type for
5646
/// that expression, as in [dcl.type.simple]p4 but without taking id-expressions
5647
/// and class member access into account.
5648
0
QualType ASTContext::getReferenceQualifiedType(const Expr *E) const {
5649
  // C++11 [dcl.type.simple]p4:
5650
  //   [...]
5651
0
  QualType T = E->getType();
5652
0
  switch (E->getValueKind()) {
5653
  //     - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the
5654
  //       type of e;
5655
0
  case VK_XValue:
5656
0
    return getRValueReferenceType(T);
5657
  //     - otherwise, if e is an lvalue, decltype(e) is T&, where T is the
5658
  //       type of e;
5659
0
  case VK_LValue:
5660
0
    return getLValueReferenceType(T);
5661
  //  - otherwise, decltype(e) is the type of e.
5662
0
  case VK_PRValue:
5663
0
    return T;
5664
0
  }
5665
0
  llvm_unreachable("Unknown value kind");
5666
0
}
5667
5668
/// Unlike many "get<Type>" functions, we don't unique DecltypeType
5669
/// nodes. This would never be helpful, since each such type has its own
5670
/// expression, and would not give a significant memory saving, since there
5671
/// is an Expr tree under each such type.
5672
0
QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
5673
0
  DecltypeType *dt;
5674
5675
  // C++11 [temp.type]p2:
5676
  //   If an expression e involves a template parameter, decltype(e) denotes a
5677
  //   unique dependent type. Two such decltype-specifiers refer to the same
5678
  //   type only if their expressions are equivalent (14.5.6.1).
5679
0
  if (e->isInstantiationDependent()) {
5680
0
    llvm::FoldingSetNodeID ID;
5681
0
    DependentDecltypeType::Profile(ID, *this, e);
5682
5683
0
    void *InsertPos = nullptr;
5684
0
    DependentDecltypeType *Canon
5685
0
      = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
5686
0
    if (!Canon) {
5687
      // Build a new, canonical decltype(expr) type.
5688
0
      Canon = new (*this, alignof(DependentDecltypeType))
5689
0
          DependentDecltypeType(e, DependentTy);
5690
0
      DependentDecltypeTypes.InsertNode(Canon, InsertPos);
5691
0
    }
5692
0
    dt = new (*this, alignof(DecltypeType))
5693
0
        DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
5694
0
  } else {
5695
0
    dt = new (*this, alignof(DecltypeType))
5696
0
        DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
5697
0
  }
5698
0
  Types.push_back(dt);
5699
0
  return QualType(dt, 0);
5700
0
}
5701
5702
/// getUnaryTransformationType - We don't unique these, since the memory
5703
/// savings are minimal and these are rare.
5704
QualType ASTContext::getUnaryTransformType(QualType BaseType,
5705
                                           QualType UnderlyingType,
5706
                                           UnaryTransformType::UTTKind Kind)
5707
0
    const {
5708
0
  UnaryTransformType *ut = nullptr;
5709
5710
0
  if (BaseType->isDependentType()) {
5711
    // Look in the folding set for an existing type.
5712
0
    llvm::FoldingSetNodeID ID;
5713
0
    DependentUnaryTransformType::Profile(ID, getCanonicalType(BaseType), Kind);
5714
5715
0
    void *InsertPos = nullptr;
5716
0
    DependentUnaryTransformType *Canon
5717
0
      = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
5718
5719
0
    if (!Canon) {
5720
      // Build a new, canonical __underlying_type(type) type.
5721
0
      Canon = new (*this, alignof(DependentUnaryTransformType))
5722
0
          DependentUnaryTransformType(*this, getCanonicalType(BaseType), Kind);
5723
0
      DependentUnaryTransformTypes.InsertNode(Canon, InsertPos);
5724
0
    }
5725
0
    ut = new (*this, alignof(UnaryTransformType))
5726
0
        UnaryTransformType(BaseType, QualType(), Kind, QualType(Canon, 0));
5727
0
  } else {
5728
0
    QualType CanonType = getCanonicalType(UnderlyingType);
5729
0
    ut = new (*this, alignof(UnaryTransformType))
5730
0
        UnaryTransformType(BaseType, UnderlyingType, Kind, CanonType);
5731
0
  }
5732
0
  Types.push_back(ut);
5733
0
  return QualType(ut, 0);
5734
0
}
5735
5736
QualType ASTContext::getAutoTypeInternal(
5737
    QualType DeducedType, AutoTypeKeyword Keyword, bool IsDependent,
5738
    bool IsPack, ConceptDecl *TypeConstraintConcept,
5739
0
    ArrayRef<TemplateArgument> TypeConstraintArgs, bool IsCanon) const {
5740
0
  if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto &&
5741
0
      !TypeConstraintConcept && !IsDependent)
5742
0
    return getAutoDeductType();
5743
5744
  // Look in the folding set for an existing type.
5745
0
  void *InsertPos = nullptr;
5746
0
  llvm::FoldingSetNodeID ID;
5747
0
  AutoType::Profile(ID, *this, DeducedType, Keyword, IsDependent,
5748
0
                    TypeConstraintConcept, TypeConstraintArgs);
5749
0
  if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
5750
0
    return QualType(AT, 0);
5751
5752
0
  QualType Canon;
5753
0
  if (!IsCanon) {
5754
0
    if (!DeducedType.isNull()) {
5755
0
      Canon = DeducedType.getCanonicalType();
5756
0
    } else if (TypeConstraintConcept) {
5757
0
      bool AnyNonCanonArgs = false;
5758
0
      ConceptDecl *CanonicalConcept = TypeConstraintConcept->getCanonicalDecl();
5759
0
      auto CanonicalConceptArgs = ::getCanonicalTemplateArguments(
5760
0
          *this, TypeConstraintArgs, AnyNonCanonArgs);
5761
0
      if (CanonicalConcept != TypeConstraintConcept || AnyNonCanonArgs) {
5762
0
        Canon =
5763
0
            getAutoTypeInternal(QualType(), Keyword, IsDependent, IsPack,
5764
0
                                CanonicalConcept, CanonicalConceptArgs, true);
5765
        // Find the insert position again.
5766
0
        [[maybe_unused]] auto *Nothing =
5767
0
            AutoTypes.FindNodeOrInsertPos(ID, InsertPos);
5768
0
        assert(!Nothing && "canonical type broken");
5769
0
      }
5770
0
    }
5771
0
  }
5772
5773
0
  void *Mem = Allocate(sizeof(AutoType) +
5774
0
                           sizeof(TemplateArgument) * TypeConstraintArgs.size(),
5775
0
                       alignof(AutoType));
5776
0
  auto *AT = new (Mem) AutoType(
5777
0
      DeducedType, Keyword,
5778
0
      (IsDependent ? TypeDependence::DependentInstantiation
5779
0
                   : TypeDependence::None) |
5780
0
          (IsPack ? TypeDependence::UnexpandedPack : TypeDependence::None),
5781
0
      Canon, TypeConstraintConcept, TypeConstraintArgs);
5782
0
  Types.push_back(AT);
5783
0
  AutoTypes.InsertNode(AT, InsertPos);
5784
0
  return QualType(AT, 0);
5785
0
}
5786
5787
/// getAutoType - Return the uniqued reference to the 'auto' type which has been
5788
/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
5789
/// canonical deduced-but-dependent 'auto' type.
5790
QualType
5791
ASTContext::getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
5792
                        bool IsDependent, bool IsPack,
5793
                        ConceptDecl *TypeConstraintConcept,
5794
0
                        ArrayRef<TemplateArgument> TypeConstraintArgs) const {
5795
0
  assert((!IsPack || IsDependent) && "only use IsPack for a dependent pack");
5796
0
  assert((!IsDependent || DeducedType.isNull()) &&
5797
0
         "A dependent auto should be undeduced");
5798
0
  return getAutoTypeInternal(DeducedType, Keyword, IsDependent, IsPack,
5799
0
                             TypeConstraintConcept, TypeConstraintArgs);
5800
0
}
5801
5802
0
QualType ASTContext::getUnconstrainedType(QualType T) const {
5803
0
  QualType CanonT = T.getCanonicalType();
5804
5805
  // Remove a type-constraint from a top-level auto or decltype(auto).
5806
0
  if (auto *AT = CanonT->getAs<AutoType>()) {
5807
0
    if (!AT->isConstrained())
5808
0
      return T;
5809
0
    return getQualifiedType(getAutoType(QualType(), AT->getKeyword(), false,
5810
0
                                        AT->containsUnexpandedParameterPack()),
5811
0
                            T.getQualifiers());
5812
0
  }
5813
5814
  // FIXME: We only support constrained auto at the top level in the type of a
5815
  // non-type template parameter at the moment. Once we lift that restriction,
5816
  // we'll need to recursively build types containing auto here.
5817
0
  assert(!CanonT->getContainedAutoType() ||
5818
0
         !CanonT->getContainedAutoType()->isConstrained());
5819
0
  return T;
5820
0
}
5821
5822
/// Return the uniqued reference to the deduced template specialization type
5823
/// which has been deduced to the given type, or to the canonical undeduced
5824
/// such type, or the canonical deduced-but-dependent such type.
5825
QualType ASTContext::getDeducedTemplateSpecializationType(
5826
0
    TemplateName Template, QualType DeducedType, bool IsDependent) const {
5827
  // Look in the folding set for an existing type.
5828
0
  void *InsertPos = nullptr;
5829
0
  llvm::FoldingSetNodeID ID;
5830
0
  DeducedTemplateSpecializationType::Profile(ID, Template, DeducedType,
5831
0
                                             IsDependent);
5832
0
  if (DeducedTemplateSpecializationType *DTST =
5833
0
          DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
5834
0
    return QualType(DTST, 0);
5835
5836
0
  auto *DTST = new (*this, alignof(DeducedTemplateSpecializationType))
5837
0
      DeducedTemplateSpecializationType(Template, DeducedType, IsDependent);
5838
0
  llvm::FoldingSetNodeID TempID;
5839
0
  DTST->Profile(TempID);
5840
0
  assert(ID == TempID && "ID does not match");
5841
0
  Types.push_back(DTST);
5842
0
  DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos);
5843
0
  return QualType(DTST, 0);
5844
0
}
5845
5846
/// getAtomicType - Return the uniqued reference to the atomic type for
5847
/// the given value type.
5848
0
QualType ASTContext::getAtomicType(QualType T) const {
5849
  // Unique pointers, to guarantee there is only one pointer of a particular
5850
  // structure.
5851
0
  llvm::FoldingSetNodeID ID;
5852
0
  AtomicType::Profile(ID, T);
5853
5854
0
  void *InsertPos = nullptr;
5855
0
  if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
5856
0
    return QualType(AT, 0);
5857
5858
  // If the atomic value type isn't canonical, this won't be a canonical type
5859
  // either, so fill in the canonical type field.
5860
0
  QualType Canonical;
5861
0
  if (!T.isCanonical()) {
5862
0
    Canonical = getAtomicType(getCanonicalType(T));
5863
5864
    // Get the new insert position for the node we care about.
5865
0
    AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
5866
0
    assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
5867
0
  }
5868
0
  auto *New = new (*this, alignof(AtomicType)) AtomicType(T, Canonical);
5869
0
  Types.push_back(New);
5870
0
  AtomicTypes.InsertNode(New, InsertPos);
5871
0
  return QualType(New, 0);
5872
0
}
5873
5874
/// getAutoDeductType - Get type pattern for deducing against 'auto'.
5875
0
QualType ASTContext::getAutoDeductType() const {
5876
0
  if (AutoDeductTy.isNull())
5877
0
    AutoDeductTy = QualType(new (*this, alignof(AutoType))
5878
0
                                AutoType(QualType(), AutoTypeKeyword::Auto,
5879
0
                                         TypeDependence::None, QualType(),
5880
0
                                         /*concept*/ nullptr, /*args*/ {}),
5881
0
                            0);
5882
0
  return AutoDeductTy;
5883
0
}
5884
5885
/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
5886
0
QualType ASTContext::getAutoRRefDeductType() const {
5887
0
  if (AutoRRefDeductTy.isNull())
5888
0
    AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
5889
0
  assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
5890
0
  return AutoRRefDeductTy;
5891
0
}
5892
5893
/// getTagDeclType - Return the unique reference to the type for the
5894
/// specified TagDecl (struct/union/class/enum) decl.
5895
138
QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
5896
138
  assert(Decl);
5897
  // FIXME: What is the design on getTagDeclType when it requires casting
5898
  // away const?  mutable?
5899
0
  return getTypeDeclType(const_cast<TagDecl*>(Decl));
5900
138
}
5901
5902
/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
5903
/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
5904
/// needs to agree with the definition in <stddef.h>.
5905
97
CanQualType ASTContext::getSizeType() const {
5906
97
  return getFromTargetType(Target->getSizeType());
5907
97
}
5908
5909
/// Return the unique signed counterpart of the integer type
5910
/// corresponding to size_t.
5911
2
CanQualType ASTContext::getSignedSizeType() const {
5912
2
  return getFromTargetType(Target->getSignedSizeType());
5913
2
}
5914
5915
/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
5916
0
CanQualType ASTContext::getIntMaxType() const {
5917
0
  return getFromTargetType(Target->getIntMaxType());
5918
0
}
5919
5920
/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
5921
0
CanQualType ASTContext::getUIntMaxType() const {
5922
0
  return getFromTargetType(Target->getUIntMaxType());
5923
0
}
5924
5925
/// getSignedWCharType - Return the type of "signed wchar_t".
5926
/// Used when in C++, as a GCC extension.
5927
0
QualType ASTContext::getSignedWCharType() const {
5928
  // FIXME: derive from "Target" ?
5929
0
  return WCharTy;
5930
0
}
5931
5932
/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
5933
/// Used when in C++, as a GCC extension.
5934
0
QualType ASTContext::getUnsignedWCharType() const {
5935
  // FIXME: derive from "Target" ?
5936
0
  return UnsignedIntTy;
5937
0
}
5938
5939
0
QualType ASTContext::getIntPtrType() const {
5940
0
  return getFromTargetType(Target->getIntPtrType());
5941
0
}
5942
5943
0
QualType ASTContext::getUIntPtrType() const {
5944
0
  return getCorrespondingUnsignedType(getIntPtrType());
5945
0
}
5946
5947
/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
5948
/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
5949
0
QualType ASTContext::getPointerDiffType() const {
5950
0
  return getFromTargetType(Target->getPtrDiffType(LangAS::Default));
5951
0
}
5952
5953
/// Return the unique unsigned counterpart of "ptrdiff_t"
5954
/// integer type. The standard (C11 7.21.6.1p7) refers to this type
5955
/// in the definition of %tu format specifier.
5956
0
QualType ASTContext::getUnsignedPointerDiffType() const {
5957
0
  return getFromTargetType(Target->getUnsignedPtrDiffType(LangAS::Default));
5958
0
}
5959
5960
/// Return the unique type for "pid_t" defined in
5961
/// <sys/types.h>. We need this to compute the correct type for vfork().
5962
0
QualType ASTContext::getProcessIDType() const {
5963
0
  return getFromTargetType(Target->getProcessIDType());
5964
0
}
5965
5966
//===----------------------------------------------------------------------===//
5967
//                              Type Operators
5968
//===----------------------------------------------------------------------===//
5969
5970
0
CanQualType ASTContext::getCanonicalParamType(QualType T) const {
5971
  // Push qualifiers into arrays, and then discard any remaining
5972
  // qualifiers.
5973
0
  T = getCanonicalType(T);
5974
0
  T = getVariableArrayDecayedType(T);
5975
0
  const Type *Ty = T.getTypePtr();
5976
0
  QualType Result;
5977
0
  if (isa<ArrayType>(Ty)) {
5978
0
    Result = getArrayDecayedType(QualType(Ty,0));
5979
0
  } else if (isa<FunctionType>(Ty)) {
5980
0
    Result = getPointerType(QualType(Ty, 0));
5981
0
  } else {
5982
0
    Result = QualType(Ty, 0);
5983
0
  }
5984
5985
0
  return CanQualType::CreateUnsafe(Result);
5986
0
}
5987
5988
QualType ASTContext::getUnqualifiedArrayType(QualType type,
5989
0
                                             Qualifiers &quals) {
5990
0
  SplitQualType splitType = type.getSplitUnqualifiedType();
5991
5992
  // FIXME: getSplitUnqualifiedType() actually walks all the way to
5993
  // the unqualified desugared type and then drops it on the floor.
5994
  // We then have to strip that sugar back off with
5995
  // getUnqualifiedDesugaredType(), which is silly.
5996
0
  const auto *AT =
5997
0
      dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
5998
5999
  // If we don't have an array, just use the results in splitType.
6000
0
  if (!AT) {
6001
0
    quals = splitType.Quals;
6002
0
    return QualType(splitType.Ty, 0);
6003
0
  }
6004
6005
  // Otherwise, recurse on the array's element type.
6006
0
  QualType elementType = AT->getElementType();
6007
0
  QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
6008
6009
  // If that didn't change the element type, AT has no qualifiers, so we
6010
  // can just use the results in splitType.
6011
0
  if (elementType == unqualElementType) {
6012
0
    assert(quals.empty()); // from the recursive call
6013
0
    quals = splitType.Quals;
6014
0
    return QualType(splitType.Ty, 0);
6015
0
  }
6016
6017
  // Otherwise, add in the qualifiers from the outermost type, then
6018
  // build the type back up.
6019
0
  quals.addConsistentQualifiers(splitType.Quals);
6020
6021
0
  if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
6022
0
    return getConstantArrayType(unqualElementType, CAT->getSize(),
6023
0
                                CAT->getSizeExpr(), CAT->getSizeModifier(), 0);
6024
0
  }
6025
6026
0
  if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) {
6027
0
    return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
6028
0
  }
6029
6030
0
  if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) {
6031
0
    return getVariableArrayType(unqualElementType,
6032
0
                                VAT->getSizeExpr(),
6033
0
                                VAT->getSizeModifier(),
6034
0
                                VAT->getIndexTypeCVRQualifiers(),
6035
0
                                VAT->getBracketsRange());
6036
0
  }
6037
6038
0
  const auto *DSAT = cast<DependentSizedArrayType>(AT);
6039
0
  return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
6040
0
                                    DSAT->getSizeModifier(), 0,
6041
0
                                    SourceRange());
6042
0
}
6043
6044
/// Attempt to unwrap two types that may both be array types with the same bound
6045
/// (or both be array types of unknown bound) for the purpose of comparing the
6046
/// cv-decomposition of two types per C++ [conv.qual].
6047
///
6048
/// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
6049
///        C++20 [conv.qual], if permitted by the current language mode.
6050
void ASTContext::UnwrapSimilarArrayTypes(QualType &T1, QualType &T2,
6051
1
                                         bool AllowPiMismatch) {
6052
1
  while (true) {
6053
1
    auto *AT1 = getAsArrayType(T1);
6054
1
    if (!AT1)
6055
1
      return;
6056
6057
0
    auto *AT2 = getAsArrayType(T2);
6058
0
    if (!AT2)
6059
0
      return;
6060
6061
    // If we don't have two array types with the same constant bound nor two
6062
    // incomplete array types, we've unwrapped everything we can.
6063
    // C++20 also permits one type to be a constant array type and the other
6064
    // to be an incomplete array type.
6065
    // FIXME: Consider also unwrapping array of unknown bound and VLA.
6066
0
    if (auto *CAT1 = dyn_cast<ConstantArrayType>(AT1)) {
6067
0
      auto *CAT2 = dyn_cast<ConstantArrayType>(AT2);
6068
0
      if (!((CAT2 && CAT1->getSize() == CAT2->getSize()) ||
6069
0
            (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
6070
0
             isa<IncompleteArrayType>(AT2))))
6071
0
        return;
6072
0
    } else if (isa<IncompleteArrayType>(AT1)) {
6073
0
      if (!(isa<IncompleteArrayType>(AT2) ||
6074
0
            (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
6075
0
             isa<ConstantArrayType>(AT2))))
6076
0
        return;
6077
0
    } else {
6078
0
      return;
6079
0
    }
6080
6081
0
    T1 = AT1->getElementType();
6082
0
    T2 = AT2->getElementType();
6083
0
  }
6084
1
}
6085
6086
/// Attempt to unwrap two types that may be similar (C++ [conv.qual]).
6087
///
6088
/// If T1 and T2 are both pointer types of the same kind, or both array types
6089
/// with the same bound, unwraps layers from T1 and T2 until a pointer type is
6090
/// unwrapped. Top-level qualifiers on T1 and T2 are ignored.
6091
///
6092
/// This function will typically be called in a loop that successively
6093
/// "unwraps" pointer and pointer-to-member types to compare them at each
6094
/// level.
6095
///
6096
/// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
6097
///        C++20 [conv.qual], if permitted by the current language mode.
6098
///
6099
/// \return \c true if a pointer type was unwrapped, \c false if we reached a
6100
/// pair of types that can't be unwrapped further.
6101
bool ASTContext::UnwrapSimilarTypes(QualType &T1, QualType &T2,
6102
1
                                    bool AllowPiMismatch) {
6103
1
  UnwrapSimilarArrayTypes(T1, T2, AllowPiMismatch);
6104
6105
1
  const auto *T1PtrType = T1->getAs<PointerType>();
6106
1
  const auto *T2PtrType = T2->getAs<PointerType>();
6107
1
  if (T1PtrType && T2PtrType) {
6108
0
    T1 = T1PtrType->getPointeeType();
6109
0
    T2 = T2PtrType->getPointeeType();
6110
0
    return true;
6111
0
  }
6112
6113
1
  const auto *T1MPType = T1->getAs<MemberPointerType>();
6114
1
  const auto *T2MPType = T2->getAs<MemberPointerType>();
6115
1
  if (T1MPType && T2MPType &&
6116
1
      hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
6117
0
                             QualType(T2MPType->getClass(), 0))) {
6118
0
    T1 = T1MPType->getPointeeType();
6119
0
    T2 = T2MPType->getPointeeType();
6120
0
    return true;
6121
0
  }
6122
6123
1
  if (getLangOpts().ObjC) {
6124
0
    const auto *T1OPType = T1->getAs<ObjCObjectPointerType>();
6125
0
    const auto *T2OPType = T2->getAs<ObjCObjectPointerType>();
6126
0
    if (T1OPType && T2OPType) {
6127
0
      T1 = T1OPType->getPointeeType();
6128
0
      T2 = T2OPType->getPointeeType();
6129
0
      return true;
6130
0
    }
6131
0
  }
6132
6133
  // FIXME: Block pointers, too?
6134
6135
1
  return false;
6136
1
}
6137
6138
0
bool ASTContext::hasSimilarType(QualType T1, QualType T2) {
6139
0
  while (true) {
6140
0
    Qualifiers Quals;
6141
0
    T1 = getUnqualifiedArrayType(T1, Quals);
6142
0
    T2 = getUnqualifiedArrayType(T2, Quals);
6143
0
    if (hasSameType(T1, T2))
6144
0
      return true;
6145
0
    if (!UnwrapSimilarTypes(T1, T2))
6146
0
      return false;
6147
0
  }
6148
0
}
6149
6150
0
bool ASTContext::hasCvrSimilarType(QualType T1, QualType T2) {
6151
0
  while (true) {
6152
0
    Qualifiers Quals1, Quals2;
6153
0
    T1 = getUnqualifiedArrayType(T1, Quals1);
6154
0
    T2 = getUnqualifiedArrayType(T2, Quals2);
6155
6156
0
    Quals1.removeCVRQualifiers();
6157
0
    Quals2.removeCVRQualifiers();
6158
0
    if (Quals1 != Quals2)
6159
0
      return false;
6160
6161
0
    if (hasSameType(T1, T2))
6162
0
      return true;
6163
6164
0
    if (!UnwrapSimilarTypes(T1, T2, /*AllowPiMismatch*/ false))
6165
0
      return false;
6166
0
  }
6167
0
}
6168
6169
DeclarationNameInfo
6170
ASTContext::getNameForTemplate(TemplateName Name,
6171
0
                               SourceLocation NameLoc) const {
6172
0
  switch (Name.getKind()) {
6173
0
  case TemplateName::QualifiedTemplate:
6174
0
  case TemplateName::Template:
6175
    // DNInfo work in progress: CHECKME: what about DNLoc?
6176
0
    return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
6177
0
                               NameLoc);
6178
6179
0
  case TemplateName::OverloadedTemplate: {
6180
0
    OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
6181
    // DNInfo work in progress: CHECKME: what about DNLoc?
6182
0
    return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
6183
0
  }
6184
6185
0
  case TemplateName::AssumedTemplate: {
6186
0
    AssumedTemplateStorage *Storage = Name.getAsAssumedTemplateName();
6187
0
    return DeclarationNameInfo(Storage->getDeclName(), NameLoc);
6188
0
  }
6189
6190
0
  case TemplateName::DependentTemplate: {
6191
0
    DependentTemplateName *DTN = Name.getAsDependentTemplateName();
6192
0
    DeclarationName DName;
6193
0
    if (DTN->isIdentifier()) {
6194
0
      DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
6195
0
      return DeclarationNameInfo(DName, NameLoc);
6196
0
    } else {
6197
0
      DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
6198
      // DNInfo work in progress: FIXME: source locations?
6199
0
      DeclarationNameLoc DNLoc =
6200
0
          DeclarationNameLoc::makeCXXOperatorNameLoc(SourceRange());
6201
0
      return DeclarationNameInfo(DName, NameLoc, DNLoc);
6202
0
    }
6203
0
  }
6204
6205
0
  case TemplateName::SubstTemplateTemplateParm: {
6206
0
    SubstTemplateTemplateParmStorage *subst
6207
0
      = Name.getAsSubstTemplateTemplateParm();
6208
0
    return DeclarationNameInfo(subst->getParameter()->getDeclName(),
6209
0
                               NameLoc);
6210
0
  }
6211
6212
0
  case TemplateName::SubstTemplateTemplateParmPack: {
6213
0
    SubstTemplateTemplateParmPackStorage *subst
6214
0
      = Name.getAsSubstTemplateTemplateParmPack();
6215
0
    return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
6216
0
                               NameLoc);
6217
0
  }
6218
0
  case TemplateName::UsingTemplate:
6219
0
    return DeclarationNameInfo(Name.getAsUsingShadowDecl()->getDeclName(),
6220
0
                               NameLoc);
6221
0
  }
6222
6223
0
  llvm_unreachable("bad template name kind!");
6224
0
}
6225
6226
TemplateName
6227
0
ASTContext::getCanonicalTemplateName(const TemplateName &Name) const {
6228
0
  switch (Name.getKind()) {
6229
0
  case TemplateName::UsingTemplate:
6230
0
  case TemplateName::QualifiedTemplate:
6231
0
  case TemplateName::Template: {
6232
0
    TemplateDecl *Template = Name.getAsTemplateDecl();
6233
0
    if (auto *TTP  = dyn_cast<TemplateTemplateParmDecl>(Template))
6234
0
      Template = getCanonicalTemplateTemplateParmDecl(TTP);
6235
6236
    // The canonical template name is the canonical template declaration.
6237
0
    return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
6238
0
  }
6239
6240
0
  case TemplateName::OverloadedTemplate:
6241
0
  case TemplateName::AssumedTemplate:
6242
0
    llvm_unreachable("cannot canonicalize unresolved template");
6243
6244
0
  case TemplateName::DependentTemplate: {
6245
0
    DependentTemplateName *DTN = Name.getAsDependentTemplateName();
6246
0
    assert(DTN && "Non-dependent template names must refer to template decls.");
6247
0
    return DTN->CanonicalTemplateName;
6248
0
  }
6249
6250
0
  case TemplateName::SubstTemplateTemplateParm: {
6251
0
    SubstTemplateTemplateParmStorage *subst
6252
0
      = Name.getAsSubstTemplateTemplateParm();
6253
0
    return getCanonicalTemplateName(subst->getReplacement());
6254
0
  }
6255
6256
0
  case TemplateName::SubstTemplateTemplateParmPack: {
6257
0
    SubstTemplateTemplateParmPackStorage *subst =
6258
0
        Name.getAsSubstTemplateTemplateParmPack();
6259
0
    TemplateArgument canonArgPack =
6260
0
        getCanonicalTemplateArgument(subst->getArgumentPack());
6261
0
    return getSubstTemplateTemplateParmPack(
6262
0
        canonArgPack, subst->getAssociatedDecl()->getCanonicalDecl(),
6263
0
        subst->getFinal(), subst->getIndex());
6264
0
  }
6265
0
  }
6266
6267
0
  llvm_unreachable("bad template name!");
6268
0
}
6269
6270
bool ASTContext::hasSameTemplateName(const TemplateName &X,
6271
0
                                     const TemplateName &Y) const {
6272
0
  return getCanonicalTemplateName(X).getAsVoidPointer() ==
6273
0
         getCanonicalTemplateName(Y).getAsVoidPointer();
6274
0
}
6275
6276
0
bool ASTContext::isSameConstraintExpr(const Expr *XCE, const Expr *YCE) const {
6277
0
  if (!XCE != !YCE)
6278
0
    return false;
6279
6280
0
  if (!XCE)
6281
0
    return true;
6282
6283
0
  llvm::FoldingSetNodeID XCEID, YCEID;
6284
0
  XCE->Profile(XCEID, *this, /*Canonical=*/true, /*ProfileLambdaExpr=*/true);
6285
0
  YCE->Profile(YCEID, *this, /*Canonical=*/true, /*ProfileLambdaExpr=*/true);
6286
0
  return XCEID == YCEID;
6287
0
}
6288
6289
bool ASTContext::isSameTypeConstraint(const TypeConstraint *XTC,
6290
0
                                      const TypeConstraint *YTC) const {
6291
0
  if (!XTC != !YTC)
6292
0
    return false;
6293
6294
0
  if (!XTC)
6295
0
    return true;
6296
6297
0
  auto *NCX = XTC->getNamedConcept();
6298
0
  auto *NCY = YTC->getNamedConcept();
6299
0
  if (!NCX || !NCY || !isSameEntity(NCX, NCY))
6300
0
    return false;
6301
0
  if (XTC->getConceptReference()->hasExplicitTemplateArgs() !=
6302
0
      YTC->getConceptReference()->hasExplicitTemplateArgs())
6303
0
    return false;
6304
0
  if (XTC->getConceptReference()->hasExplicitTemplateArgs())
6305
0
    if (XTC->getConceptReference()
6306
0
            ->getTemplateArgsAsWritten()
6307
0
            ->NumTemplateArgs !=
6308
0
        YTC->getConceptReference()->getTemplateArgsAsWritten()->NumTemplateArgs)
6309
0
      return false;
6310
6311
  // Compare slowly by profiling.
6312
  //
6313
  // We couldn't compare the profiling result for the template
6314
  // args here. Consider the following example in different modules:
6315
  //
6316
  // template <__integer_like _Tp, C<_Tp> Sentinel>
6317
  // constexpr _Tp operator()(_Tp &&__t, Sentinel &&last) const {
6318
  //   return __t;
6319
  // }
6320
  //
6321
  // When we compare the profiling result for `C<_Tp>` in different
6322
  // modules, it will compare the type of `_Tp` in different modules.
6323
  // However, the type of `_Tp` in different modules refer to different
6324
  // types here naturally. So we couldn't compare the profiling result
6325
  // for the template args directly.
6326
0
  return isSameConstraintExpr(XTC->getImmediatelyDeclaredConstraint(),
6327
0
                              YTC->getImmediatelyDeclaredConstraint());
6328
0
}
6329
6330
bool ASTContext::isSameTemplateParameter(const NamedDecl *X,
6331
0
                                         const NamedDecl *Y) const {
6332
0
  if (X->getKind() != Y->getKind())
6333
0
    return false;
6334
6335
0
  if (auto *TX = dyn_cast<TemplateTypeParmDecl>(X)) {
6336
0
    auto *TY = cast<TemplateTypeParmDecl>(Y);
6337
0
    if (TX->isParameterPack() != TY->isParameterPack())
6338
0
      return false;
6339
0
    if (TX->hasTypeConstraint() != TY->hasTypeConstraint())
6340
0
      return false;
6341
0
    return isSameTypeConstraint(TX->getTypeConstraint(),
6342
0
                                TY->getTypeConstraint());
6343
0
  }
6344
6345
0
  if (auto *TX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
6346
0
    auto *TY = cast<NonTypeTemplateParmDecl>(Y);
6347
0
    return TX->isParameterPack() == TY->isParameterPack() &&
6348
0
           TX->getASTContext().hasSameType(TX->getType(), TY->getType()) &&
6349
0
           isSameConstraintExpr(TX->getPlaceholderTypeConstraint(),
6350
0
                                TY->getPlaceholderTypeConstraint());
6351
0
  }
6352
6353
0
  auto *TX = cast<TemplateTemplateParmDecl>(X);
6354
0
  auto *TY = cast<TemplateTemplateParmDecl>(Y);
6355
0
  return TX->isParameterPack() == TY->isParameterPack() &&
6356
0
         isSameTemplateParameterList(TX->getTemplateParameters(),
6357
0
                                     TY->getTemplateParameters());
6358
0
}
6359
6360
bool ASTContext::isSameTemplateParameterList(
6361
0
    const TemplateParameterList *X, const TemplateParameterList *Y) const {
6362
0
  if (X->size() != Y->size())
6363
0
    return false;
6364
6365
0
  for (unsigned I = 0, N = X->size(); I != N; ++I)
6366
0
    if (!isSameTemplateParameter(X->getParam(I), Y->getParam(I)))
6367
0
      return false;
6368
6369
0
  return isSameConstraintExpr(X->getRequiresClause(), Y->getRequiresClause());
6370
0
}
6371
6372
bool ASTContext::isSameDefaultTemplateArgument(const NamedDecl *X,
6373
0
                                               const NamedDecl *Y) const {
6374
  // If the type parameter isn't the same already, we don't need to check the
6375
  // default argument further.
6376
0
  if (!isSameTemplateParameter(X, Y))
6377
0
    return false;
6378
6379
0
  if (auto *TTPX = dyn_cast<TemplateTypeParmDecl>(X)) {
6380
0
    auto *TTPY = cast<TemplateTypeParmDecl>(Y);
6381
0
    if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument())
6382
0
      return false;
6383
6384
0
    return hasSameType(TTPX->getDefaultArgument(), TTPY->getDefaultArgument());
6385
0
  }
6386
6387
0
  if (auto *NTTPX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
6388
0
    auto *NTTPY = cast<NonTypeTemplateParmDecl>(Y);
6389
0
    if (!NTTPX->hasDefaultArgument() || !NTTPY->hasDefaultArgument())
6390
0
      return false;
6391
6392
0
    Expr *DefaultArgumentX = NTTPX->getDefaultArgument()->IgnoreImpCasts();
6393
0
    Expr *DefaultArgumentY = NTTPY->getDefaultArgument()->IgnoreImpCasts();
6394
0
    llvm::FoldingSetNodeID XID, YID;
6395
0
    DefaultArgumentX->Profile(XID, *this, /*Canonical=*/true);
6396
0
    DefaultArgumentY->Profile(YID, *this, /*Canonical=*/true);
6397
0
    return XID == YID;
6398
0
  }
6399
6400
0
  auto *TTPX = cast<TemplateTemplateParmDecl>(X);
6401
0
  auto *TTPY = cast<TemplateTemplateParmDecl>(Y);
6402
6403
0
  if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument())
6404
0
    return false;
6405
6406
0
  const TemplateArgument &TAX = TTPX->getDefaultArgument().getArgument();
6407
0
  const TemplateArgument &TAY = TTPY->getDefaultArgument().getArgument();
6408
0
  return hasSameTemplateName(TAX.getAsTemplate(), TAY.getAsTemplate());
6409
0
}
6410
6411
0
static NamespaceDecl *getNamespace(const NestedNameSpecifier *X) {
6412
0
  if (auto *NS = X->getAsNamespace())
6413
0
    return NS;
6414
0
  if (auto *NAS = X->getAsNamespaceAlias())
6415
0
    return NAS->getNamespace();
6416
0
  return nullptr;
6417
0
}
6418
6419
static bool isSameQualifier(const NestedNameSpecifier *X,
6420
0
                            const NestedNameSpecifier *Y) {
6421
0
  if (auto *NSX = getNamespace(X)) {
6422
0
    auto *NSY = getNamespace(Y);
6423
0
    if (!NSY || NSX->getCanonicalDecl() != NSY->getCanonicalDecl())
6424
0
      return false;
6425
0
  } else if (X->getKind() != Y->getKind())
6426
0
    return false;
6427
6428
  // FIXME: For namespaces and types, we're permitted to check that the entity
6429
  // is named via the same tokens. We should probably do so.
6430
0
  switch (X->getKind()) {
6431
0
  case NestedNameSpecifier::Identifier:
6432
0
    if (X->getAsIdentifier() != Y->getAsIdentifier())
6433
0
      return false;
6434
0
    break;
6435
0
  case NestedNameSpecifier::Namespace:
6436
0
  case NestedNameSpecifier::NamespaceAlias:
6437
    // We've already checked that we named the same namespace.
6438
0
    break;
6439
0
  case NestedNameSpecifier::TypeSpec:
6440
0
  case NestedNameSpecifier::TypeSpecWithTemplate:
6441
0
    if (X->getAsType()->getCanonicalTypeInternal() !=
6442
0
        Y->getAsType()->getCanonicalTypeInternal())
6443
0
      return false;
6444
0
    break;
6445
0
  case NestedNameSpecifier::Global:
6446
0
  case NestedNameSpecifier::Super:
6447
0
    return true;
6448
0
  }
6449
6450
  // Recurse into earlier portion of NNS, if any.
6451
0
  auto *PX = X->getPrefix();
6452
0
  auto *PY = Y->getPrefix();
6453
0
  if (PX && PY)
6454
0
    return isSameQualifier(PX, PY);
6455
0
  return !PX && !PY;
6456
0
}
6457
6458
/// Determine whether the attributes we can overload on are identical for A and
6459
/// B. Will ignore any overloadable attrs represented in the type of A and B.
6460
static bool hasSameOverloadableAttrs(const FunctionDecl *A,
6461
0
                                     const FunctionDecl *B) {
6462
  // Note that pass_object_size attributes are represented in the function's
6463
  // ExtParameterInfo, so we don't need to check them here.
6464
6465
0
  llvm::FoldingSetNodeID Cand1ID, Cand2ID;
6466
0
  auto AEnableIfAttrs = A->specific_attrs<EnableIfAttr>();
6467
0
  auto BEnableIfAttrs = B->specific_attrs<EnableIfAttr>();
6468
6469
0
  for (auto Pair : zip_longest(AEnableIfAttrs, BEnableIfAttrs)) {
6470
0
    std::optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
6471
0
    std::optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
6472
6473
    // Return false if the number of enable_if attributes is different.
6474
0
    if (!Cand1A || !Cand2A)
6475
0
      return false;
6476
6477
0
    Cand1ID.clear();
6478
0
    Cand2ID.clear();
6479
6480
0
    (*Cand1A)->getCond()->Profile(Cand1ID, A->getASTContext(), true);
6481
0
    (*Cand2A)->getCond()->Profile(Cand2ID, B->getASTContext(), true);
6482
6483
    // Return false if any of the enable_if expressions of A and B are
6484
    // different.
6485
0
    if (Cand1ID != Cand2ID)
6486
0
      return false;
6487
0
  }
6488
0
  return true;
6489
0
}
6490
6491
0
bool ASTContext::isSameEntity(const NamedDecl *X, const NamedDecl *Y) const {
6492
  // Caution: this function is called by the AST reader during deserialization,
6493
  // so it cannot rely on AST invariants being met. Non-trivial accessors
6494
  // should be avoided, along with any traversal of redeclaration chains.
6495
6496
0
  if (X == Y)
6497
0
    return true;
6498
6499
0
  if (X->getDeclName() != Y->getDeclName())
6500
0
    return false;
6501
6502
  // Must be in the same context.
6503
  //
6504
  // Note that we can't use DeclContext::Equals here, because the DeclContexts
6505
  // could be two different declarations of the same function. (We will fix the
6506
  // semantic DC to refer to the primary definition after merging.)
6507
0
  if (!declaresSameEntity(cast<Decl>(X->getDeclContext()->getRedeclContext()),
6508
0
                          cast<Decl>(Y->getDeclContext()->getRedeclContext())))
6509
0
    return false;
6510
6511
  // Two typedefs refer to the same entity if they have the same underlying
6512
  // type.
6513
0
  if (const auto *TypedefX = dyn_cast<TypedefNameDecl>(X))
6514
0
    if (const auto *TypedefY = dyn_cast<TypedefNameDecl>(Y))
6515
0
      return hasSameType(TypedefX->getUnderlyingType(),
6516
0
                         TypedefY->getUnderlyingType());
6517
6518
  // Must have the same kind.
6519
0
  if (X->getKind() != Y->getKind())
6520
0
    return false;
6521
6522
  // Objective-C classes and protocols with the same name always match.
6523
0
  if (isa<ObjCInterfaceDecl>(X) || isa<ObjCProtocolDecl>(X))
6524
0
    return true;
6525
6526
0
  if (isa<ClassTemplateSpecializationDecl>(X)) {
6527
    // No need to handle these here: we merge them when adding them to the
6528
    // template.
6529
0
    return false;
6530
0
  }
6531
6532
  // Compatible tags match.
6533
0
  if (const auto *TagX = dyn_cast<TagDecl>(X)) {
6534
0
    const auto *TagY = cast<TagDecl>(Y);
6535
0
    return (TagX->getTagKind() == TagY->getTagKind()) ||
6536
0
           ((TagX->getTagKind() == TagTypeKind::Struct ||
6537
0
             TagX->getTagKind() == TagTypeKind::Class ||
6538
0
             TagX->getTagKind() == TagTypeKind::Interface) &&
6539
0
            (TagY->getTagKind() == TagTypeKind::Struct ||
6540
0
             TagY->getTagKind() == TagTypeKind::Class ||
6541
0
             TagY->getTagKind() == TagTypeKind::Interface));
6542
0
  }
6543
6544
  // Functions with the same type and linkage match.
6545
  // FIXME: This needs to cope with merging of prototyped/non-prototyped
6546
  // functions, etc.
6547
0
  if (const auto *FuncX = dyn_cast<FunctionDecl>(X)) {
6548
0
    const auto *FuncY = cast<FunctionDecl>(Y);
6549
0
    if (const auto *CtorX = dyn_cast<CXXConstructorDecl>(X)) {
6550
0
      const auto *CtorY = cast<CXXConstructorDecl>(Y);
6551
0
      if (CtorX->getInheritedConstructor() &&
6552
0
          !isSameEntity(CtorX->getInheritedConstructor().getConstructor(),
6553
0
                        CtorY->getInheritedConstructor().getConstructor()))
6554
0
        return false;
6555
0
    }
6556
6557
0
    if (FuncX->isMultiVersion() != FuncY->isMultiVersion())
6558
0
      return false;
6559
6560
    // Multiversioned functions with different feature strings are represented
6561
    // as separate declarations.
6562
0
    if (FuncX->isMultiVersion()) {
6563
0
      const auto *TAX = FuncX->getAttr<TargetAttr>();
6564
0
      const auto *TAY = FuncY->getAttr<TargetAttr>();
6565
0
      assert(TAX && TAY && "Multiversion Function without target attribute");
6566
6567
0
      if (TAX->getFeaturesStr() != TAY->getFeaturesStr())
6568
0
        return false;
6569
0
    }
6570
6571
    // Per C++20 [temp.over.link]/4, friends in different classes are sometimes
6572
    // not the same entity if they are constrained.
6573
0
    if ((FuncX->isMemberLikeConstrainedFriend() ||
6574
0
         FuncY->isMemberLikeConstrainedFriend()) &&
6575
0
        !FuncX->getLexicalDeclContext()->Equals(
6576
0
            FuncY->getLexicalDeclContext())) {
6577
0
      return false;
6578
0
    }
6579
6580
0
    if (!isSameConstraintExpr(FuncX->getTrailingRequiresClause(),
6581
0
                              FuncY->getTrailingRequiresClause()))
6582
0
      return false;
6583
6584
0
    auto GetTypeAsWritten = [](const FunctionDecl *FD) {
6585
      // Map to the first declaration that we've already merged into this one.
6586
      // The TSI of redeclarations might not match (due to calling conventions
6587
      // being inherited onto the type but not the TSI), but the TSI type of
6588
      // the first declaration of the function should match across modules.
6589
0
      FD = FD->getCanonicalDecl();
6590
0
      return FD->getTypeSourceInfo() ? FD->getTypeSourceInfo()->getType()
6591
0
                                     : FD->getType();
6592
0
    };
6593
0
    QualType XT = GetTypeAsWritten(FuncX), YT = GetTypeAsWritten(FuncY);
6594
0
    if (!hasSameType(XT, YT)) {
6595
      // We can get functions with different types on the redecl chain in C++17
6596
      // if they have differing exception specifications and at least one of
6597
      // the excpetion specs is unresolved.
6598
0
      auto *XFPT = XT->getAs<FunctionProtoType>();
6599
0
      auto *YFPT = YT->getAs<FunctionProtoType>();
6600
0
      if (getLangOpts().CPlusPlus17 && XFPT && YFPT &&
6601
0
          (isUnresolvedExceptionSpec(XFPT->getExceptionSpecType()) ||
6602
0
           isUnresolvedExceptionSpec(YFPT->getExceptionSpecType())) &&
6603
0
          hasSameFunctionTypeIgnoringExceptionSpec(XT, YT))
6604
0
        return true;
6605
0
      return false;
6606
0
    }
6607
6608
0
    return FuncX->getLinkageInternal() == FuncY->getLinkageInternal() &&
6609
0
           hasSameOverloadableAttrs(FuncX, FuncY);
6610
0
  }
6611
6612
  // Variables with the same type and linkage match.
6613
0
  if (const auto *VarX = dyn_cast<VarDecl>(X)) {
6614
0
    const auto *VarY = cast<VarDecl>(Y);
6615
0
    if (VarX->getLinkageInternal() == VarY->getLinkageInternal()) {
6616
      // During deserialization, we might compare variables before we load
6617
      // their types. Assume the types will end up being the same.
6618
0
      if (VarX->getType().isNull() || VarY->getType().isNull())
6619
0
        return true;
6620
6621
0
      if (hasSameType(VarX->getType(), VarY->getType()))
6622
0
        return true;
6623
6624
      // We can get decls with different types on the redecl chain. Eg.
6625
      // template <typename T> struct S { static T Var[]; }; // #1
6626
      // template <typename T> T S<T>::Var[sizeof(T)]; // #2
6627
      // Only? happens when completing an incomplete array type. In this case
6628
      // when comparing #1 and #2 we should go through their element type.
6629
0
      const ArrayType *VarXTy = getAsArrayType(VarX->getType());
6630
0
      const ArrayType *VarYTy = getAsArrayType(VarY->getType());
6631
0
      if (!VarXTy || !VarYTy)
6632
0
        return false;
6633
0
      if (VarXTy->isIncompleteArrayType() || VarYTy->isIncompleteArrayType())
6634
0
        return hasSameType(VarXTy->getElementType(), VarYTy->getElementType());
6635
0
    }
6636
0
    return false;
6637
0
  }
6638
6639
  // Namespaces with the same name and inlinedness match.
6640
0
  if (const auto *NamespaceX = dyn_cast<NamespaceDecl>(X)) {
6641
0
    const auto *NamespaceY = cast<NamespaceDecl>(Y);
6642
0
    return NamespaceX->isInline() == NamespaceY->isInline();
6643
0
  }
6644
6645
  // Identical template names and kinds match if their template parameter lists
6646
  // and patterns match.
6647
0
  if (const auto *TemplateX = dyn_cast<TemplateDecl>(X)) {
6648
0
    const auto *TemplateY = cast<TemplateDecl>(Y);
6649
6650
    // ConceptDecl wouldn't be the same if their constraint expression differs.
6651
0
    if (const auto *ConceptX = dyn_cast<ConceptDecl>(X)) {
6652
0
      const auto *ConceptY = cast<ConceptDecl>(Y);
6653
0
      if (!isSameConstraintExpr(ConceptX->getConstraintExpr(),
6654
0
                                ConceptY->getConstraintExpr()))
6655
0
        return false;
6656
0
    }
6657
6658
0
    return isSameEntity(TemplateX->getTemplatedDecl(),
6659
0
                        TemplateY->getTemplatedDecl()) &&
6660
0
           isSameTemplateParameterList(TemplateX->getTemplateParameters(),
6661
0
                                       TemplateY->getTemplateParameters());
6662
0
  }
6663
6664
  // Fields with the same name and the same type match.
6665
0
  if (const auto *FDX = dyn_cast<FieldDecl>(X)) {
6666
0
    const auto *FDY = cast<FieldDecl>(Y);
6667
    // FIXME: Also check the bitwidth is odr-equivalent, if any.
6668
0
    return hasSameType(FDX->getType(), FDY->getType());
6669
0
  }
6670
6671
  // Indirect fields with the same target field match.
6672
0
  if (const auto *IFDX = dyn_cast<IndirectFieldDecl>(X)) {
6673
0
    const auto *IFDY = cast<IndirectFieldDecl>(Y);
6674
0
    return IFDX->getAnonField()->getCanonicalDecl() ==
6675
0
           IFDY->getAnonField()->getCanonicalDecl();
6676
0
  }
6677
6678
  // Enumerators with the same name match.
6679
0
  if (isa<EnumConstantDecl>(X))
6680
    // FIXME: Also check the value is odr-equivalent.
6681
0
    return true;
6682
6683
  // Using shadow declarations with the same target match.
6684
0
  if (const auto *USX = dyn_cast<UsingShadowDecl>(X)) {
6685
0
    const auto *USY = cast<UsingShadowDecl>(Y);
6686
0
    return USX->getTargetDecl() == USY->getTargetDecl();
6687
0
  }
6688
6689
  // Using declarations with the same qualifier match. (We already know that
6690
  // the name matches.)
6691
0
  if (const auto *UX = dyn_cast<UsingDecl>(X)) {
6692
0
    const auto *UY = cast<UsingDecl>(Y);
6693
0
    return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
6694
0
           UX->hasTypename() == UY->hasTypename() &&
6695
0
           UX->isAccessDeclaration() == UY->isAccessDeclaration();
6696
0
  }
6697
0
  if (const auto *UX = dyn_cast<UnresolvedUsingValueDecl>(X)) {
6698
0
    const auto *UY = cast<UnresolvedUsingValueDecl>(Y);
6699
0
    return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
6700
0
           UX->isAccessDeclaration() == UY->isAccessDeclaration();
6701
0
  }
6702
0
  if (const auto *UX = dyn_cast<UnresolvedUsingTypenameDecl>(X)) {
6703
0
    return isSameQualifier(
6704
0
        UX->getQualifier(),
6705
0
        cast<UnresolvedUsingTypenameDecl>(Y)->getQualifier());
6706
0
  }
6707
6708
  // Using-pack declarations are only created by instantiation, and match if
6709
  // they're instantiated from matching UnresolvedUsing...Decls.
6710
0
  if (const auto *UX = dyn_cast<UsingPackDecl>(X)) {
6711
0
    return declaresSameEntity(
6712
0
        UX->getInstantiatedFromUsingDecl(),
6713
0
        cast<UsingPackDecl>(Y)->getInstantiatedFromUsingDecl());
6714
0
  }
6715
6716
  // Namespace alias definitions with the same target match.
6717
0
  if (const auto *NAX = dyn_cast<NamespaceAliasDecl>(X)) {
6718
0
    const auto *NAY = cast<NamespaceAliasDecl>(Y);
6719
0
    return NAX->getNamespace()->Equals(NAY->getNamespace());
6720
0
  }
6721
6722
0
  return false;
6723
0
}
6724
6725
TemplateArgument
6726
0
ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
6727
0
  switch (Arg.getKind()) {
6728
0
    case TemplateArgument::Null:
6729
0
      return Arg;
6730
6731
0
    case TemplateArgument::Expression:
6732
0
      return Arg;
6733
6734
0
    case TemplateArgument::Declaration: {
6735
0
      auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
6736
0
      return TemplateArgument(D, getCanonicalType(Arg.getParamTypeForDecl()),
6737
0
                              Arg.getIsDefaulted());
6738
0
    }
6739
6740
0
    case TemplateArgument::NullPtr:
6741
0
      return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
6742
0
                              /*isNullPtr*/ true, Arg.getIsDefaulted());
6743
6744
0
    case TemplateArgument::Template:
6745
0
      return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()),
6746
0
                              Arg.getIsDefaulted());
6747
6748
0
    case TemplateArgument::TemplateExpansion:
6749
0
      return TemplateArgument(
6750
0
          getCanonicalTemplateName(Arg.getAsTemplateOrTemplatePattern()),
6751
0
          Arg.getNumTemplateExpansions(), Arg.getIsDefaulted());
6752
6753
0
    case TemplateArgument::Integral:
6754
0
      return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
6755
6756
0
    case TemplateArgument::Type:
6757
0
      return TemplateArgument(getCanonicalType(Arg.getAsType()),
6758
0
                              /*isNullPtr*/ false, Arg.getIsDefaulted());
6759
6760
0
    case TemplateArgument::Pack: {
6761
0
      bool AnyNonCanonArgs = false;
6762
0
      auto CanonArgs = ::getCanonicalTemplateArguments(
6763
0
          *this, Arg.pack_elements(), AnyNonCanonArgs);
6764
0
      if (!AnyNonCanonArgs)
6765
0
        return Arg;
6766
0
      return TemplateArgument::CreatePackCopy(const_cast<ASTContext &>(*this),
6767
0
                                              CanonArgs);
6768
0
    }
6769
0
  }
6770
6771
  // Silence GCC warning
6772
0
  llvm_unreachable("Unhandled template argument kind");
6773
0
}
6774
6775
NestedNameSpecifier *
6776
1
ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
6777
1
  if (!NNS)
6778
1
    return nullptr;
6779
6780
0
  switch (NNS->getKind()) {
6781
0
  case NestedNameSpecifier::Identifier:
6782
    // Canonicalize the prefix but keep the identifier the same.
6783
0
    return NestedNameSpecifier::Create(*this,
6784
0
                         getCanonicalNestedNameSpecifier(NNS->getPrefix()),
6785
0
                                       NNS->getAsIdentifier());
6786
6787
0
  case NestedNameSpecifier::Namespace:
6788
    // A namespace is canonical; build a nested-name-specifier with
6789
    // this namespace and no prefix.
6790
0
    return NestedNameSpecifier::Create(*this, nullptr,
6791
0
                                 NNS->getAsNamespace()->getOriginalNamespace());
6792
6793
0
  case NestedNameSpecifier::NamespaceAlias:
6794
    // A namespace is canonical; build a nested-name-specifier with
6795
    // this namespace and no prefix.
6796
0
    return NestedNameSpecifier::Create(*this, nullptr,
6797
0
                                    NNS->getAsNamespaceAlias()->getNamespace()
6798
0
                                                      ->getOriginalNamespace());
6799
6800
  // The difference between TypeSpec and TypeSpecWithTemplate is that the
6801
  // latter will have the 'template' keyword when printed.
6802
0
  case NestedNameSpecifier::TypeSpec:
6803
0
  case NestedNameSpecifier::TypeSpecWithTemplate: {
6804
0
    const Type *T = getCanonicalType(NNS->getAsType());
6805
6806
    // If we have some kind of dependent-named type (e.g., "typename T::type"),
6807
    // break it apart into its prefix and identifier, then reconsititute those
6808
    // as the canonical nested-name-specifier. This is required to canonicalize
6809
    // a dependent nested-name-specifier involving typedefs of dependent-name
6810
    // types, e.g.,
6811
    //   typedef typename T::type T1;
6812
    //   typedef typename T1::type T2;
6813
0
    if (const auto *DNT = T->getAs<DependentNameType>())
6814
0
      return NestedNameSpecifier::Create(
6815
0
          *this, DNT->getQualifier(),
6816
0
          const_cast<IdentifierInfo *>(DNT->getIdentifier()));
6817
0
    if (const auto *DTST = T->getAs<DependentTemplateSpecializationType>())
6818
0
      return NestedNameSpecifier::Create(*this, DTST->getQualifier(), true,
6819
0
                                         const_cast<Type *>(T));
6820
6821
    // TODO: Set 'Template' parameter to true for other template types.
6822
0
    return NestedNameSpecifier::Create(*this, nullptr, false,
6823
0
                                       const_cast<Type *>(T));
6824
0
  }
6825
6826
0
  case NestedNameSpecifier::Global:
6827
0
  case NestedNameSpecifier::Super:
6828
    // The global specifier and __super specifer are canonical and unique.
6829
0
    return NNS;
6830
0
  }
6831
6832
0
  llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
6833
0
}
6834
6835
1.28k
const ArrayType *ASTContext::getAsArrayType(QualType T) const {
6836
  // Handle the non-qualified case efficiently.
6837
1.28k
  if (!T.hasLocalQualifiers()) {
6838
    // Handle the common positive case fast.
6839
1.28k
    if (const auto *AT = dyn_cast<ArrayType>(T))
6840
46
      return AT;
6841
1.28k
  }
6842
6843
  // Handle the common negative case fast.
6844
1.23k
  if (!isa<ArrayType>(T.getCanonicalType()))
6845
1.23k
    return nullptr;
6846
6847
  // Apply any qualifiers from the array type to the element type.  This
6848
  // implements C99 6.7.3p8: "If the specification of an array type includes
6849
  // any type qualifiers, the element type is so qualified, not the array type."
6850
6851
  // If we get here, we either have type qualifiers on the type, or we have
6852
  // sugar such as a typedef in the way.  If we have type qualifiers on the type
6853
  // we must propagate them down into the element type.
6854
6855
0
  SplitQualType split = T.getSplitDesugaredType();
6856
0
  Qualifiers qs = split.Quals;
6857
6858
  // If we have a simple case, just return now.
6859
0
  const auto *ATy = dyn_cast<ArrayType>(split.Ty);
6860
0
  if (!ATy || qs.empty())
6861
0
    return ATy;
6862
6863
  // Otherwise, we have an array and we have qualifiers on it.  Push the
6864
  // qualifiers into the array element type and return a new array type.
6865
0
  QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
6866
6867
0
  if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy))
6868
0
    return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
6869
0
                                                CAT->getSizeExpr(),
6870
0
                                                CAT->getSizeModifier(),
6871
0
                                           CAT->getIndexTypeCVRQualifiers()));
6872
0
  if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy))
6873
0
    return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
6874
0
                                                  IAT->getSizeModifier(),
6875
0
                                           IAT->getIndexTypeCVRQualifiers()));
6876
6877
0
  if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy))
6878
0
    return cast<ArrayType>(
6879
0
                     getDependentSizedArrayType(NewEltTy,
6880
0
                                                DSAT->getSizeExpr(),
6881
0
                                                DSAT->getSizeModifier(),
6882
0
                                              DSAT->getIndexTypeCVRQualifiers(),
6883
0
                                                DSAT->getBracketsRange()));
6884
6885
0
  const auto *VAT = cast<VariableArrayType>(ATy);
6886
0
  return cast<ArrayType>(getVariableArrayType(NewEltTy,
6887
0
                                              VAT->getSizeExpr(),
6888
0
                                              VAT->getSizeModifier(),
6889
0
                                              VAT->getIndexTypeCVRQualifiers(),
6890
0
                                              VAT->getBracketsRange()));
6891
0
}
6892
6893
40
QualType ASTContext::getAdjustedParameterType(QualType T) const {
6894
40
  if (T->isArrayType() || T->isFunctionType())
6895
0
    return getDecayedType(T);
6896
40
  return T;
6897
40
}
6898
6899
0
QualType ASTContext::getSignatureParameterType(QualType T) const {
6900
0
  T = getVariableArrayDecayedType(T);
6901
0
  T = getAdjustedParameterType(T);
6902
0
  return T.getUnqualifiedType();
6903
0
}
6904
6905
0
QualType ASTContext::getExceptionObjectType(QualType T) const {
6906
  // C++ [except.throw]p3:
6907
  //   A throw-expression initializes a temporary object, called the exception
6908
  //   object, the type of which is determined by removing any top-level
6909
  //   cv-qualifiers from the static type of the operand of throw and adjusting
6910
  //   the type from "array of T" or "function returning T" to "pointer to T"
6911
  //   or "pointer to function returning T", [...]
6912
0
  T = getVariableArrayDecayedType(T);
6913
0
  if (T->isArrayType() || T->isFunctionType())
6914
0
    T = getDecayedType(T);
6915
0
  return T.getUnqualifiedType();
6916
0
}
6917
6918
/// getArrayDecayedType - Return the properly qualified result of decaying the
6919
/// specified array type to a pointer.  This operation is non-trivial when
6920
/// handling typedefs etc.  The canonical type of "T" must be an array type,
6921
/// this returns a pointer to a properly qualified element of the array.
6922
///
6923
/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
6924
0
QualType ASTContext::getArrayDecayedType(QualType Ty) const {
6925
  // Get the element type with 'getAsArrayType' so that we don't lose any
6926
  // typedefs in the element type of the array.  This also handles propagation
6927
  // of type qualifiers from the array type into the element type if present
6928
  // (C99 6.7.3p8).
6929
0
  const ArrayType *PrettyArrayType = getAsArrayType(Ty);
6930
0
  assert(PrettyArrayType && "Not an array type!");
6931
6932
0
  QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
6933
6934
  // int x[restrict 4] ->  int *restrict
6935
0
  QualType Result = getQualifiedType(PtrTy,
6936
0
                                     PrettyArrayType->getIndexTypeQualifiers());
6937
6938
  // int x[_Nullable] -> int * _Nullable
6939
0
  if (auto Nullability = Ty->getNullability()) {
6940
0
    Result = const_cast<ASTContext *>(this)->getAttributedType(
6941
0
        AttributedType::getNullabilityAttrKind(*Nullability), Result, Result);
6942
0
  }
6943
0
  return Result;
6944
0
}
6945
6946
0
QualType ASTContext::getBaseElementType(const ArrayType *array) const {
6947
0
  return getBaseElementType(array->getElementType());
6948
0
}
6949
6950
715
QualType ASTContext::getBaseElementType(QualType type) const {
6951
715
  Qualifiers qs;
6952
773
  while (true) {
6953
773
    SplitQualType split = type.getSplitDesugaredType();
6954
773
    const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
6955
773
    if (!array) break;
6956
6957
58
    type = array->getElementType();
6958
58
    qs.addConsistentQualifiers(split.Quals);
6959
58
  }
6960
6961
715
  return getQualifiedType(type, qs);
6962
715
}
6963
6964
/// getConstantArrayElementCount - Returns number of constant array elements.
6965
uint64_t
6966
0
ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA)  const {
6967
0
  uint64_t ElementCount = 1;
6968
0
  do {
6969
0
    ElementCount *= CA->getSize().getZExtValue();
6970
0
    CA = dyn_cast_or_null<ConstantArrayType>(
6971
0
      CA->getElementType()->getAsArrayTypeUnsafe());
6972
0
  } while (CA);
6973
0
  return ElementCount;
6974
0
}
6975
6976
uint64_t ASTContext::getArrayInitLoopExprElementCount(
6977
0
    const ArrayInitLoopExpr *AILE) const {
6978
0
  if (!AILE)
6979
0
    return 0;
6980
6981
0
  uint64_t ElementCount = 1;
6982
6983
0
  do {
6984
0
    ElementCount *= AILE->getArraySize().getZExtValue();
6985
0
    AILE = dyn_cast<ArrayInitLoopExpr>(AILE->getSubExpr());
6986
0
  } while (AILE);
6987
6988
0
  return ElementCount;
6989
0
}
6990
6991
/// getFloatingRank - Return a relative rank for floating point types.
6992
/// This routine will assert if passed a built-in type that isn't a float.
6993
0
static FloatingRank getFloatingRank(QualType T) {
6994
0
  if (const auto *CT = T->getAs<ComplexType>())
6995
0
    return getFloatingRank(CT->getElementType());
6996
6997
0
  switch (T->castAs<BuiltinType>()->getKind()) {
6998
0
  default: llvm_unreachable("getFloatingRank(): not a floating type");
6999
0
  case BuiltinType::Float16:    return Float16Rank;
7000
0
  case BuiltinType::Half:       return HalfRank;
7001
0
  case BuiltinType::Float:      return FloatRank;
7002
0
  case BuiltinType::Double:     return DoubleRank;
7003
0
  case BuiltinType::LongDouble: return LongDoubleRank;
7004
0
  case BuiltinType::Float128:   return Float128Rank;
7005
0
  case BuiltinType::BFloat16:   return BFloat16Rank;
7006
0
  case BuiltinType::Ibm128:     return Ibm128Rank;
7007
0
  }
7008
0
}
7009
7010
/// getFloatingTypeOrder - Compare the rank of the two specified floating
7011
/// point types, ignoring the domain of the type (i.e. 'double' ==
7012
/// '_Complex double').  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
7013
/// LHS < RHS, return -1.
7014
0
int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
7015
0
  FloatingRank LHSR = getFloatingRank(LHS);
7016
0
  FloatingRank RHSR = getFloatingRank(RHS);
7017
7018
0
  if (LHSR == RHSR)
7019
0
    return 0;
7020
0
  if (LHSR > RHSR)
7021
0
    return 1;
7022
0
  return -1;
7023
0
}
7024
7025
0
int ASTContext::getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const {
7026
0
  if (&getFloatTypeSemantics(LHS) == &getFloatTypeSemantics(RHS))
7027
0
    return 0;
7028
0
  return getFloatingTypeOrder(LHS, RHS);
7029
0
}
7030
7031
/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
7032
/// routine will assert if passed a built-in type that isn't an integer or enum,
7033
/// or if it is not canonicalized.
7034
0
unsigned ASTContext::getIntegerRank(const Type *T) const {
7035
0
  assert(T->isCanonicalUnqualified() && "T should be canonicalized");
7036
7037
  // Results in this 'losing' to any type of the same size, but winning if
7038
  // larger.
7039
0
  if (const auto *EIT = dyn_cast<BitIntType>(T))
7040
0
    return 0 + (EIT->getNumBits() << 3);
7041
7042
0
  switch (cast<BuiltinType>(T)->getKind()) {
7043
0
  default: llvm_unreachable("getIntegerRank(): not a built-in integer");
7044
0
  case BuiltinType::Bool:
7045
0
    return 1 + (getIntWidth(BoolTy) << 3);
7046
0
  case BuiltinType::Char_S:
7047
0
  case BuiltinType::Char_U:
7048
0
  case BuiltinType::SChar:
7049
0
  case BuiltinType::UChar:
7050
0
    return 2 + (getIntWidth(CharTy) << 3);
7051
0
  case BuiltinType::Short:
7052
0
  case BuiltinType::UShort:
7053
0
    return 3 + (getIntWidth(ShortTy) << 3);
7054
0
  case BuiltinType::Int:
7055
0
  case BuiltinType::UInt:
7056
0
    return 4 + (getIntWidth(IntTy) << 3);
7057
0
  case BuiltinType::Long:
7058
0
  case BuiltinType::ULong:
7059
0
    return 5 + (getIntWidth(LongTy) << 3);
7060
0
  case BuiltinType::LongLong:
7061
0
  case BuiltinType::ULongLong:
7062
0
    return 6 + (getIntWidth(LongLongTy) << 3);
7063
0
  case BuiltinType::Int128:
7064
0
  case BuiltinType::UInt128:
7065
0
    return 7 + (getIntWidth(Int128Ty) << 3);
7066
7067
  // "The ranks of char8_t, char16_t, char32_t, and wchar_t equal the ranks of
7068
  // their underlying types" [c++20 conv.rank]
7069
0
  case BuiltinType::Char8:
7070
0
    return getIntegerRank(UnsignedCharTy.getTypePtr());
7071
0
  case BuiltinType::Char16:
7072
0
    return getIntegerRank(
7073
0
        getFromTargetType(Target->getChar16Type()).getTypePtr());
7074
0
  case BuiltinType::Char32:
7075
0
    return getIntegerRank(
7076
0
        getFromTargetType(Target->getChar32Type()).getTypePtr());
7077
0
  case BuiltinType::WChar_S:
7078
0
  case BuiltinType::WChar_U:
7079
0
    return getIntegerRank(
7080
0
        getFromTargetType(Target->getWCharType()).getTypePtr());
7081
0
  }
7082
0
}
7083
7084
/// Whether this is a promotable bitfield reference according
7085
/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
7086
///
7087
/// \returns the type this bit-field will promote to, or NULL if no
7088
/// promotion occurs.
7089
2
QualType ASTContext::isPromotableBitField(Expr *E) const {
7090
2
  if (E->isTypeDependent() || E->isValueDependent())
7091
0
    return {};
7092
7093
  // C++ [conv.prom]p5:
7094
  //    If the bit-field has an enumerated type, it is treated as any other
7095
  //    value of that type for promotion purposes.
7096
2
  if (getLangOpts().CPlusPlus && E->getType()->isEnumeralType())
7097
0
    return {};
7098
7099
  // FIXME: We should not do this unless E->refersToBitField() is true. This
7100
  // matters in C where getSourceBitField() will find bit-fields for various
7101
  // cases where the source expression is not a bit-field designator.
7102
7103
2
  FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
7104
2
  if (!Field)
7105
2
    return {};
7106
7107
0
  QualType FT = Field->getType();
7108
7109
0
  uint64_t BitWidth = Field->getBitWidthValue(*this);
7110
0
  uint64_t IntSize = getTypeSize(IntTy);
7111
  // C++ [conv.prom]p5:
7112
  //   A prvalue for an integral bit-field can be converted to a prvalue of type
7113
  //   int if int can represent all the values of the bit-field; otherwise, it
7114
  //   can be converted to unsigned int if unsigned int can represent all the
7115
  //   values of the bit-field. If the bit-field is larger yet, no integral
7116
  //   promotion applies to it.
7117
  // C11 6.3.1.1/2:
7118
  //   [For a bit-field of type _Bool, int, signed int, or unsigned int:]
7119
  //   If an int can represent all values of the original type (as restricted by
7120
  //   the width, for a bit-field), the value is converted to an int; otherwise,
7121
  //   it is converted to an unsigned int.
7122
  //
7123
  // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
7124
  //        We perform that promotion here to match GCC and C++.
7125
  // FIXME: C does not permit promotion of an enum bit-field whose rank is
7126
  //        greater than that of 'int'. We perform that promotion to match GCC.
7127
0
  if (BitWidth < IntSize)
7128
0
    return IntTy;
7129
7130
0
  if (BitWidth == IntSize)
7131
0
    return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
7132
7133
  // Bit-fields wider than int are not subject to promotions, and therefore act
7134
  // like the base type. GCC has some weird bugs in this area that we
7135
  // deliberately do not follow (GCC follows a pre-standard resolution to
7136
  // C's DR315 which treats bit-width as being part of the type, and this leaks
7137
  // into their semantics in some cases).
7138
0
  return {};
7139
0
}
7140
7141
/// getPromotedIntegerType - Returns the type that Promotable will
7142
/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
7143
/// integer type.
7144
0
QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
7145
0
  assert(!Promotable.isNull());
7146
0
  assert(isPromotableIntegerType(Promotable));
7147
0
  if (const auto *ET = Promotable->getAs<EnumType>())
7148
0
    return ET->getDecl()->getPromotionType();
7149
7150
0
  if (const auto *BT = Promotable->getAs<BuiltinType>()) {
7151
    // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
7152
    // (3.9.1) can be converted to a prvalue of the first of the following
7153
    // types that can represent all the values of its underlying type:
7154
    // int, unsigned int, long int, unsigned long int, long long int, or
7155
    // unsigned long long int [...]
7156
    // FIXME: Is there some better way to compute this?
7157
0
    if (BT->getKind() == BuiltinType::WChar_S ||
7158
0
        BT->getKind() == BuiltinType::WChar_U ||
7159
0
        BT->getKind() == BuiltinType::Char8 ||
7160
0
        BT->getKind() == BuiltinType::Char16 ||
7161
0
        BT->getKind() == BuiltinType::Char32) {
7162
0
      bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
7163
0
      uint64_t FromSize = getTypeSize(BT);
7164
0
      QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
7165
0
                                  LongLongTy, UnsignedLongLongTy };
7166
0
      for (const auto &PT : PromoteTypes) {
7167
0
        uint64_t ToSize = getTypeSize(PT);
7168
0
        if (FromSize < ToSize ||
7169
0
            (FromSize == ToSize && FromIsSigned == PT->isSignedIntegerType()))
7170
0
          return PT;
7171
0
      }
7172
0
      llvm_unreachable("char type should fit into long long");
7173
0
    }
7174
0
  }
7175
7176
  // At this point, we should have a signed or unsigned integer type.
7177
0
  if (Promotable->isSignedIntegerType())
7178
0
    return IntTy;
7179
0
  uint64_t PromotableSize = getIntWidth(Promotable);
7180
0
  uint64_t IntSize = getIntWidth(IntTy);
7181
0
  assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
7182
0
  return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
7183
0
}
7184
7185
/// Recurses in pointer/array types until it finds an objc retainable
7186
/// type and returns its ownership.
7187
0
Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
7188
0
  while (!T.isNull()) {
7189
0
    if (T.getObjCLifetime() != Qualifiers::OCL_None)
7190
0
      return T.getObjCLifetime();
7191
0
    if (T->isArrayType())
7192
0
      T = getBaseElementType(T);
7193
0
    else if (const auto *PT = T->getAs<PointerType>())
7194
0
      T = PT->getPointeeType();
7195
0
    else if (const auto *RT = T->getAs<ReferenceType>())
7196
0
      T = RT->getPointeeType();
7197
0
    else
7198
0
      break;
7199
0
  }
7200
7201
0
  return Qualifiers::OCL_None;
7202
0
}
7203
7204
0
static const Type *getIntegerTypeForEnum(const EnumType *ET) {
7205
  // Incomplete enum types are not treated as integer types.
7206
  // FIXME: In C++, enum types are never integer types.
7207
0
  if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
7208
0
    return ET->getDecl()->getIntegerType().getTypePtr();
7209
0
  return nullptr;
7210
0
}
7211
7212
/// getIntegerTypeOrder - Returns the highest ranked integer type:
7213
/// C99 6.3.1.8p1.  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
7214
/// LHS < RHS, return -1.
7215
0
int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
7216
0
  const Type *LHSC = getCanonicalType(LHS).getTypePtr();
7217
0
  const Type *RHSC = getCanonicalType(RHS).getTypePtr();
7218
7219
  // Unwrap enums to their underlying type.
7220
0
  if (const auto *ET = dyn_cast<EnumType>(LHSC))
7221
0
    LHSC = getIntegerTypeForEnum(ET);
7222
0
  if (const auto *ET = dyn_cast<EnumType>(RHSC))
7223
0
    RHSC = getIntegerTypeForEnum(ET);
7224
7225
0
  if (LHSC == RHSC) return 0;
7226
7227
0
  bool LHSUnsigned = LHSC->isUnsignedIntegerType();
7228
0
  bool RHSUnsigned = RHSC->isUnsignedIntegerType();
7229
7230
0
  unsigned LHSRank = getIntegerRank(LHSC);
7231
0
  unsigned RHSRank = getIntegerRank(RHSC);
7232
7233
0
  if (LHSUnsigned == RHSUnsigned) {  // Both signed or both unsigned.
7234
0
    if (LHSRank == RHSRank) return 0;
7235
0
    return LHSRank > RHSRank ? 1 : -1;
7236
0
  }
7237
7238
  // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
7239
0
  if (LHSUnsigned) {
7240
    // If the unsigned [LHS] type is larger, return it.
7241
0
    if (LHSRank >= RHSRank)
7242
0
      return 1;
7243
7244
    // If the signed type can represent all values of the unsigned type, it
7245
    // wins.  Because we are dealing with 2's complement and types that are
7246
    // powers of two larger than each other, this is always safe.
7247
0
    return -1;
7248
0
  }
7249
7250
  // If the unsigned [RHS] type is larger, return it.
7251
0
  if (RHSRank >= LHSRank)
7252
0
    return -1;
7253
7254
  // If the signed type can represent all values of the unsigned type, it
7255
  // wins.  Because we are dealing with 2's complement and types that are
7256
  // powers of two larger than each other, this is always safe.
7257
0
  return 1;
7258
0
}
7259
7260
46
TypedefDecl *ASTContext::getCFConstantStringDecl() const {
7261
46
  if (CFConstantStringTypeDecl)
7262
0
    return CFConstantStringTypeDecl;
7263
7264
46
  assert(!CFConstantStringTagDecl &&
7265
46
         "tag and typedef should be initialized together");
7266
0
  CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
7267
46
  CFConstantStringTagDecl->startDefinition();
7268
7269
46
  struct {
7270
46
    QualType Type;
7271
46
    const char *Name;
7272
46
  } Fields[5];
7273
46
  unsigned Count = 0;
7274
7275
  /// Objective-C ABI
7276
  ///
7277
  ///    typedef struct __NSConstantString_tag {
7278
  ///      const int *isa;
7279
  ///      int flags;
7280
  ///      const char *str;
7281
  ///      long length;
7282
  ///    } __NSConstantString;
7283
  ///
7284
  /// Swift ABI (4.1, 4.2)
7285
  ///
7286
  ///    typedef struct __NSConstantString_tag {
7287
  ///      uintptr_t _cfisa;
7288
  ///      uintptr_t _swift_rc;
7289
  ///      _Atomic(uint64_t) _cfinfoa;
7290
  ///      const char *_ptr;
7291
  ///      uint32_t _length;
7292
  ///    } __NSConstantString;
7293
  ///
7294
  /// Swift ABI (5.0)
7295
  ///
7296
  ///    typedef struct __NSConstantString_tag {
7297
  ///      uintptr_t _cfisa;
7298
  ///      uintptr_t _swift_rc;
7299
  ///      _Atomic(uint64_t) _cfinfoa;
7300
  ///      const char *_ptr;
7301
  ///      uintptr_t _length;
7302
  ///    } __NSConstantString;
7303
7304
46
  const auto CFRuntime = getLangOpts().CFRuntime;
7305
46
  if (static_cast<unsigned>(CFRuntime) <
7306
46
      static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) {
7307
46
    Fields[Count++] = { getPointerType(IntTy.withConst()), "isa" };
7308
46
    Fields[Count++] = { IntTy, "flags" };
7309
46
    Fields[Count++] = { getPointerType(CharTy.withConst()), "str" };
7310
46
    Fields[Count++] = { LongTy, "length" };
7311
46
  } else {
7312
0
    Fields[Count++] = { getUIntPtrType(), "_cfisa" };
7313
0
    Fields[Count++] = { getUIntPtrType(), "_swift_rc" };
7314
0
    Fields[Count++] = { getFromTargetType(Target->getUInt64Type()), "_swift_rc" };
7315
0
    Fields[Count++] = { getPointerType(CharTy.withConst()), "_ptr" };
7316
0
    if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 ||
7317
0
        CFRuntime == LangOptions::CoreFoundationABI::Swift4_2)
7318
0
      Fields[Count++] = { IntTy, "_ptr" };
7319
0
    else
7320
0
      Fields[Count++] = { getUIntPtrType(), "_ptr" };
7321
0
  }
7322
7323
  // Create fields
7324
230
  for (unsigned i = 0; i < Count; ++i) {
7325
184
    FieldDecl *Field =
7326
184
        FieldDecl::Create(*this, CFConstantStringTagDecl, SourceLocation(),
7327
184
                          SourceLocation(), &Idents.get(Fields[i].Name),
7328
184
                          Fields[i].Type, /*TInfo=*/nullptr,
7329
184
                          /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
7330
184
    Field->setAccess(AS_public);
7331
184
    CFConstantStringTagDecl->addDecl(Field);
7332
184
  }
7333
7334
46
  CFConstantStringTagDecl->completeDefinition();
7335
  // This type is designed to be compatible with NSConstantString, but cannot
7336
  // use the same name, since NSConstantString is an interface.
7337
46
  auto tagType = getTagDeclType(CFConstantStringTagDecl);
7338
46
  CFConstantStringTypeDecl =
7339
46
      buildImplicitTypedef(tagType, "__NSConstantString");
7340
7341
46
  return CFConstantStringTypeDecl;
7342
46
}
7343
7344
0
RecordDecl *ASTContext::getCFConstantStringTagDecl() const {
7345
0
  if (!CFConstantStringTagDecl)
7346
0
    getCFConstantStringDecl(); // Build the tag and the typedef.
7347
0
  return CFConstantStringTagDecl;
7348
0
}
7349
7350
// getCFConstantStringType - Return the type used for constant CFStrings.
7351
0
QualType ASTContext::getCFConstantStringType() const {
7352
0
  return getTypedefType(getCFConstantStringDecl());
7353
0
}
7354
7355
0
QualType ASTContext::getObjCSuperType() const {
7356
0
  if (ObjCSuperType.isNull()) {
7357
0
    RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
7358
0
    getTranslationUnitDecl()->addDecl(ObjCSuperTypeDecl);
7359
0
    ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
7360
0
  }
7361
0
  return ObjCSuperType;
7362
0
}
7363
7364
0
void ASTContext::setCFConstantStringType(QualType T) {
7365
0
  const auto *TD = T->castAs<TypedefType>();
7366
0
  CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl());
7367
0
  const auto *TagType =
7368
0
      CFConstantStringTypeDecl->getUnderlyingType()->castAs<RecordType>();
7369
0
  CFConstantStringTagDecl = TagType->getDecl();
7370
0
}
7371
7372
0
QualType ASTContext::getBlockDescriptorType() const {
7373
0
  if (BlockDescriptorType)
7374
0
    return getTagDeclType(BlockDescriptorType);
7375
7376
0
  RecordDecl *RD;
7377
  // FIXME: Needs the FlagAppleBlock bit.
7378
0
  RD = buildImplicitRecord("__block_descriptor");
7379
0
  RD->startDefinition();
7380
7381
0
  QualType FieldTypes[] = {
7382
0
    UnsignedLongTy,
7383
0
    UnsignedLongTy,
7384
0
  };
7385
7386
0
  static const char *const FieldNames[] = {
7387
0
    "reserved",
7388
0
    "Size"
7389
0
  };
7390
7391
0
  for (size_t i = 0; i < 2; ++i) {
7392
0
    FieldDecl *Field = FieldDecl::Create(
7393
0
        *this, RD, SourceLocation(), SourceLocation(),
7394
0
        &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
7395
0
        /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
7396
0
    Field->setAccess(AS_public);
7397
0
    RD->addDecl(Field);
7398
0
  }
7399
7400
0
  RD->completeDefinition();
7401
7402
0
  BlockDescriptorType = RD;
7403
7404
0
  return getTagDeclType(BlockDescriptorType);
7405
0
}
7406
7407
0
QualType ASTContext::getBlockDescriptorExtendedType() const {
7408
0
  if (BlockDescriptorExtendedType)
7409
0
    return getTagDeclType(BlockDescriptorExtendedType);
7410
7411
0
  RecordDecl *RD;
7412
  // FIXME: Needs the FlagAppleBlock bit.
7413
0
  RD = buildImplicitRecord("__block_descriptor_withcopydispose");
7414
0
  RD->startDefinition();
7415
7416
0
  QualType FieldTypes[] = {
7417
0
    UnsignedLongTy,
7418
0
    UnsignedLongTy,
7419
0
    getPointerType(VoidPtrTy),
7420
0
    getPointerType(VoidPtrTy)
7421
0
  };
7422
7423
0
  static const char *const FieldNames[] = {
7424
0
    "reserved",
7425
0
    "Size",
7426
0
    "CopyFuncPtr",
7427
0
    "DestroyFuncPtr"
7428
0
  };
7429
7430
0
  for (size_t i = 0; i < 4; ++i) {
7431
0
    FieldDecl *Field = FieldDecl::Create(
7432
0
        *this, RD, SourceLocation(), SourceLocation(),
7433
0
        &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
7434
0
        /*BitWidth=*/nullptr,
7435
0
        /*Mutable=*/false, ICIS_NoInit);
7436
0
    Field->setAccess(AS_public);
7437
0
    RD->addDecl(Field);
7438
0
  }
7439
7440
0
  RD->completeDefinition();
7441
7442
0
  BlockDescriptorExtendedType = RD;
7443
0
  return getTagDeclType(BlockDescriptorExtendedType);
7444
0
}
7445
7446
0
OpenCLTypeKind ASTContext::getOpenCLTypeKind(const Type *T) const {
7447
0
  const auto *BT = dyn_cast<BuiltinType>(T);
7448
7449
0
  if (!BT) {
7450
0
    if (isa<PipeType>(T))
7451
0
      return OCLTK_Pipe;
7452
7453
0
    return OCLTK_Default;
7454
0
  }
7455
7456
0
  switch (BT->getKind()) {
7457
0
#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix)                   \
7458
0
  case BuiltinType::Id:                                                        \
7459
0
    return OCLTK_Image;
7460
0
#include "clang/Basic/OpenCLImageTypes.def"
7461
7462
0
  case BuiltinType::OCLClkEvent:
7463
0
    return OCLTK_ClkEvent;
7464
7465
0
  case BuiltinType::OCLEvent:
7466
0
    return OCLTK_Event;
7467
7468
0
  case BuiltinType::OCLQueue:
7469
0
    return OCLTK_Queue;
7470
7471
0
  case BuiltinType::OCLReserveID:
7472
0
    return OCLTK_ReserveID;
7473
7474
0
  case BuiltinType::OCLSampler:
7475
0
    return OCLTK_Sampler;
7476
7477
0
  default:
7478
0
    return OCLTK_Default;
7479
0
  }
7480
0
}
7481
7482
0
LangAS ASTContext::getOpenCLTypeAddrSpace(const Type *T) const {
7483
0
  return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
7484
0
}
7485
7486
/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
7487
/// requires copy/dispose. Note that this must match the logic
7488
/// in buildByrefHelpers.
7489
bool ASTContext::BlockRequiresCopying(QualType Ty,
7490
0
                                      const VarDecl *D) {
7491
0
  if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
7492
0
    const Expr *copyExpr = getBlockVarCopyInit(D).getCopyExpr();
7493
0
    if (!copyExpr && record->hasTrivialDestructor()) return false;
7494
7495
0
    return true;
7496
0
  }
7497
7498
  // The block needs copy/destroy helpers if Ty is non-trivial to destructively
7499
  // move or destroy.
7500
0
  if (Ty.isNonTrivialToPrimitiveDestructiveMove() || Ty.isDestructedType())
7501
0
    return true;
7502
7503
0
  if (!Ty->isObjCRetainableType()) return false;
7504
7505
0
  Qualifiers qs = Ty.getQualifiers();
7506
7507
  // If we have lifetime, that dominates.
7508
0
  if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
7509
0
    switch (lifetime) {
7510
0
      case Qualifiers::OCL_None: llvm_unreachable("impossible");
7511
7512
      // These are just bits as far as the runtime is concerned.
7513
0
      case Qualifiers::OCL_ExplicitNone:
7514
0
      case Qualifiers::OCL_Autoreleasing:
7515
0
        return false;
7516
7517
      // These cases should have been taken care of when checking the type's
7518
      // non-triviality.
7519
0
      case Qualifiers::OCL_Weak:
7520
0
      case Qualifiers::OCL_Strong:
7521
0
        llvm_unreachable("impossible");
7522
0
    }
7523
0
    llvm_unreachable("fell out of lifetime switch!");
7524
0
  }
7525
0
  return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
7526
0
          Ty->isObjCObjectPointerType());
7527
0
}
7528
7529
bool ASTContext::getByrefLifetime(QualType Ty,
7530
                              Qualifiers::ObjCLifetime &LifeTime,
7531
0
                              bool &HasByrefExtendedLayout) const {
7532
0
  if (!getLangOpts().ObjC ||
7533
0
      getLangOpts().getGC() != LangOptions::NonGC)
7534
0
    return false;
7535
7536
0
  HasByrefExtendedLayout = false;
7537
0
  if (Ty->isRecordType()) {
7538
0
    HasByrefExtendedLayout = true;
7539
0
    LifeTime = Qualifiers::OCL_None;
7540
0
  } else if ((LifeTime = Ty.getObjCLifetime())) {
7541
    // Honor the ARC qualifiers.
7542
0
  } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
7543
    // The MRR rule.
7544
0
    LifeTime = Qualifiers::OCL_ExplicitNone;
7545
0
  } else {
7546
0
    LifeTime = Qualifiers::OCL_None;
7547
0
  }
7548
0
  return true;
7549
0
}
7550
7551
0
CanQualType ASTContext::getNSUIntegerType() const {
7552
0
  assert(Target && "Expected target to be initialized");
7553
0
  const llvm::Triple &T = Target->getTriple();
7554
  // Windows is LLP64 rather than LP64
7555
0
  if (T.isOSWindows() && T.isArch64Bit())
7556
0
    return UnsignedLongLongTy;
7557
0
  return UnsignedLongTy;
7558
0
}
7559
7560
0
CanQualType ASTContext::getNSIntegerType() const {
7561
0
  assert(Target && "Expected target to be initialized");
7562
0
  const llvm::Triple &T = Target->getTriple();
7563
  // Windows is LLP64 rather than LP64
7564
0
  if (T.isOSWindows() && T.isArch64Bit())
7565
0
    return LongLongTy;
7566
0
  return LongTy;
7567
0
}
7568
7569
0
TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
7570
0
  if (!ObjCInstanceTypeDecl)
7571
0
    ObjCInstanceTypeDecl =
7572
0
        buildImplicitTypedef(getObjCIdType(), "instancetype");
7573
0
  return ObjCInstanceTypeDecl;
7574
0
}
7575
7576
// This returns true if a type has been typedefed to BOOL:
7577
// typedef <type> BOOL;
7578
0
static bool isTypeTypedefedAsBOOL(QualType T) {
7579
0
  if (const auto *TT = dyn_cast<TypedefType>(T))
7580
0
    if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
7581
0
      return II->isStr("BOOL");
7582
7583
0
  return false;
7584
0
}
7585
7586
/// getObjCEncodingTypeSize returns size of type for objective-c encoding
7587
/// purpose.
7588
0
CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
7589
0
  if (!type->isIncompleteArrayType() && type->isIncompleteType())
7590
0
    return CharUnits::Zero();
7591
7592
0
  CharUnits sz = getTypeSizeInChars(type);
7593
7594
  // Make all integer and enum types at least as large as an int
7595
0
  if (sz.isPositive() && type->isIntegralOrEnumerationType())
7596
0
    sz = std::max(sz, getTypeSizeInChars(IntTy));
7597
  // Treat arrays as pointers, since that's how they're passed in.
7598
0
  else if (type->isArrayType())
7599
0
    sz = getTypeSizeInChars(VoidPtrTy);
7600
0
  return sz;
7601
0
}
7602
7603
889
bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
7604
889
  return getTargetInfo().getCXXABI().isMicrosoft() &&
7605
889
         VD->isStaticDataMember() &&
7606
889
         VD->getType()->isIntegralOrEnumerationType() &&
7607
889
         !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
7608
889
}
7609
7610
ASTContext::InlineVariableDefinitionKind
7611
889
ASTContext::getInlineVariableDefinitionKind(const VarDecl *VD) const {
7612
889
  if (!VD->isInline())
7613
889
    return InlineVariableDefinitionKind::None;
7614
7615
  // In almost all cases, it's a weak definition.
7616
0
  auto *First = VD->getFirstDecl();
7617
0
  if (First->isInlineSpecified() || !First->isStaticDataMember())
7618
0
    return InlineVariableDefinitionKind::Weak;
7619
7620
  // If there's a file-context declaration in this translation unit, it's a
7621
  // non-discardable definition.
7622
0
  for (auto *D : VD->redecls())
7623
0
    if (D->getLexicalDeclContext()->isFileContext() &&
7624
0
        !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr()))
7625
0
      return InlineVariableDefinitionKind::Strong;
7626
7627
  // If we've not seen one yet, we don't know.
7628
0
  return InlineVariableDefinitionKind::WeakUnknown;
7629
0
}
7630
7631
0
static std::string charUnitsToString(const CharUnits &CU) {
7632
0
  return llvm::itostr(CU.getQuantity());
7633
0
}
7634
7635
/// getObjCEncodingForBlock - Return the encoded type for this block
7636
/// declaration.
7637
0
std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
7638
0
  std::string S;
7639
7640
0
  const BlockDecl *Decl = Expr->getBlockDecl();
7641
0
  QualType BlockTy =
7642
0
      Expr->getType()->castAs<BlockPointerType>()->getPointeeType();
7643
0
  QualType BlockReturnTy = BlockTy->castAs<FunctionType>()->getReturnType();
7644
  // Encode result type.
7645
0
  if (getLangOpts().EncodeExtendedBlockSig)
7646
0
    getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, BlockReturnTy, S,
7647
0
                                      true /*Extended*/);
7648
0
  else
7649
0
    getObjCEncodingForType(BlockReturnTy, S);
7650
  // Compute size of all parameters.
7651
  // Start with computing size of a pointer in number of bytes.
7652
  // FIXME: There might(should) be a better way of doing this computation!
7653
0
  CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
7654
0
  CharUnits ParmOffset = PtrSize;
7655
0
  for (auto *PI : Decl->parameters()) {
7656
0
    QualType PType = PI->getType();
7657
0
    CharUnits sz = getObjCEncodingTypeSize(PType);
7658
0
    if (sz.isZero())
7659
0
      continue;
7660
0
    assert(sz.isPositive() && "BlockExpr - Incomplete param type");
7661
0
    ParmOffset += sz;
7662
0
  }
7663
  // Size of the argument frame
7664
0
  S += charUnitsToString(ParmOffset);
7665
  // Block pointer and offset.
7666
0
  S += "@?0";
7667
7668
  // Argument types.
7669
0
  ParmOffset = PtrSize;
7670
0
  for (auto *PVDecl : Decl->parameters()) {
7671
0
    QualType PType = PVDecl->getOriginalType();
7672
0
    if (const auto *AT =
7673
0
            dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
7674
      // Use array's original type only if it has known number of
7675
      // elements.
7676
0
      if (!isa<ConstantArrayType>(AT))
7677
0
        PType = PVDecl->getType();
7678
0
    } else if (PType->isFunctionType())
7679
0
      PType = PVDecl->getType();
7680
0
    if (getLangOpts().EncodeExtendedBlockSig)
7681
0
      getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
7682
0
                                      S, true /*Extended*/);
7683
0
    else
7684
0
      getObjCEncodingForType(PType, S);
7685
0
    S += charUnitsToString(ParmOffset);
7686
0
    ParmOffset += getObjCEncodingTypeSize(PType);
7687
0
  }
7688
7689
0
  return S;
7690
0
}
7691
7692
std::string
7693
0
ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const {
7694
0
  std::string S;
7695
  // Encode result type.
7696
0
  getObjCEncodingForType(Decl->getReturnType(), S);
7697
0
  CharUnits ParmOffset;
7698
  // Compute size of all parameters.
7699
0
  for (auto *PI : Decl->parameters()) {
7700
0
    QualType PType = PI->getType();
7701
0
    CharUnits sz = getObjCEncodingTypeSize(PType);
7702
0
    if (sz.isZero())
7703
0
      continue;
7704
7705
0
    assert(sz.isPositive() &&
7706
0
           "getObjCEncodingForFunctionDecl - Incomplete param type");
7707
0
    ParmOffset += sz;
7708
0
  }
7709
0
  S += charUnitsToString(ParmOffset);
7710
0
  ParmOffset = CharUnits::Zero();
7711
7712
  // Argument types.
7713
0
  for (auto *PVDecl : Decl->parameters()) {
7714
0
    QualType PType = PVDecl->getOriginalType();
7715
0
    if (const auto *AT =
7716
0
            dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
7717
      // Use array's original type only if it has known number of
7718
      // elements.
7719
0
      if (!isa<ConstantArrayType>(AT))
7720
0
        PType = PVDecl->getType();
7721
0
    } else if (PType->isFunctionType())
7722
0
      PType = PVDecl->getType();
7723
0
    getObjCEncodingForType(PType, S);
7724
0
    S += charUnitsToString(ParmOffset);
7725
0
    ParmOffset += getObjCEncodingTypeSize(PType);
7726
0
  }
7727
7728
0
  return S;
7729
0
}
7730
7731
/// getObjCEncodingForMethodParameter - Return the encoded type for a single
7732
/// method parameter or return type. If Extended, include class names and
7733
/// block object types.
7734
void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
7735
                                                   QualType T, std::string& S,
7736
0
                                                   bool Extended) const {
7737
  // Encode type qualifier, 'in', 'inout', etc. for the parameter.
7738
0
  getObjCEncodingForTypeQualifier(QT, S);
7739
  // Encode parameter type.
7740
0
  ObjCEncOptions Options = ObjCEncOptions()
7741
0
                               .setExpandPointedToStructures()
7742
0
                               .setExpandStructures()
7743
0
                               .setIsOutermostType();
7744
0
  if (Extended)
7745
0
    Options.setEncodeBlockParameters().setEncodeClassNames();
7746
0
  getObjCEncodingForTypeImpl(T, S, Options, /*Field=*/nullptr);
7747
0
}
7748
7749
/// getObjCEncodingForMethodDecl - Return the encoded type for this method
7750
/// declaration.
7751
std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
7752
0
                                                     bool Extended) const {
7753
  // FIXME: This is not very efficient.
7754
  // Encode return type.
7755
0
  std::string S;
7756
0
  getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
7757
0
                                    Decl->getReturnType(), S, Extended);
7758
  // Compute size of all parameters.
7759
  // Start with computing size of a pointer in number of bytes.
7760
  // FIXME: There might(should) be a better way of doing this computation!
7761
0
  CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
7762
  // The first two arguments (self and _cmd) are pointers; account for
7763
  // their size.
7764
0
  CharUnits ParmOffset = 2 * PtrSize;
7765
0
  for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
7766
0
       E = Decl->sel_param_end(); PI != E; ++PI) {
7767
0
    QualType PType = (*PI)->getType();
7768
0
    CharUnits sz = getObjCEncodingTypeSize(PType);
7769
0
    if (sz.isZero())
7770
0
      continue;
7771
7772
0
    assert(sz.isPositive() &&
7773
0
           "getObjCEncodingForMethodDecl - Incomplete param type");
7774
0
    ParmOffset += sz;
7775
0
  }
7776
0
  S += charUnitsToString(ParmOffset);
7777
0
  S += "@0:";
7778
0
  S += charUnitsToString(PtrSize);
7779
7780
  // Argument types.
7781
0
  ParmOffset = 2 * PtrSize;
7782
0
  for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
7783
0
       E = Decl->sel_param_end(); PI != E; ++PI) {
7784
0
    const ParmVarDecl *PVDecl = *PI;
7785
0
    QualType PType = PVDecl->getOriginalType();
7786
0
    if (const auto *AT =
7787
0
            dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
7788
      // Use array's original type only if it has known number of
7789
      // elements.
7790
0
      if (!isa<ConstantArrayType>(AT))
7791
0
        PType = PVDecl->getType();
7792
0
    } else if (PType->isFunctionType())
7793
0
      PType = PVDecl->getType();
7794
0
    getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
7795
0
                                      PType, S, Extended);
7796
0
    S += charUnitsToString(ParmOffset);
7797
0
    ParmOffset += getObjCEncodingTypeSize(PType);
7798
0
  }
7799
7800
0
  return S;
7801
0
}
7802
7803
ObjCPropertyImplDecl *
7804
ASTContext::getObjCPropertyImplDeclForPropertyDecl(
7805
                                      const ObjCPropertyDecl *PD,
7806
0
                                      const Decl *Container) const {
7807
0
  if (!Container)
7808
0
    return nullptr;
7809
0
  if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) {
7810
0
    for (auto *PID : CID->property_impls())
7811
0
      if (PID->getPropertyDecl() == PD)
7812
0
        return PID;
7813
0
  } else {
7814
0
    const auto *OID = cast<ObjCImplementationDecl>(Container);
7815
0
    for (auto *PID : OID->property_impls())
7816
0
      if (PID->getPropertyDecl() == PD)
7817
0
        return PID;
7818
0
  }
7819
0
  return nullptr;
7820
0
}
7821
7822
/// getObjCEncodingForPropertyDecl - Return the encoded type for this
7823
/// property declaration. If non-NULL, Container must be either an
7824
/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
7825
/// NULL when getting encodings for protocol properties.
7826
/// Property attributes are stored as a comma-delimited C string. The simple
7827
/// attributes readonly and bycopy are encoded as single characters. The
7828
/// parametrized attributes, getter=name, setter=name, and ivar=name, are
7829
/// encoded as single characters, followed by an identifier. Property types
7830
/// are also encoded as a parametrized attribute. The characters used to encode
7831
/// these attributes are defined by the following enumeration:
7832
/// @code
7833
/// enum PropertyAttributes {
7834
/// kPropertyReadOnly = 'R',   // property is read-only.
7835
/// kPropertyBycopy = 'C',     // property is a copy of the value last assigned
7836
/// kPropertyByref = '&',  // property is a reference to the value last assigned
7837
/// kPropertyDynamic = 'D',    // property is dynamic
7838
/// kPropertyGetter = 'G',     // followed by getter selector name
7839
/// kPropertySetter = 'S',     // followed by setter selector name
7840
/// kPropertyInstanceVariable = 'V'  // followed by instance variable  name
7841
/// kPropertyType = 'T'              // followed by old-style type encoding.
7842
/// kPropertyWeak = 'W'              // 'weak' property
7843
/// kPropertyStrong = 'P'            // property GC'able
7844
/// kPropertyNonAtomic = 'N'         // property non-atomic
7845
/// kPropertyOptional = '?'          // property optional
7846
/// };
7847
/// @endcode
7848
std::string
7849
ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
7850
0
                                           const Decl *Container) const {
7851
  // Collect information from the property implementation decl(s).
7852
0
  bool Dynamic = false;
7853
0
  ObjCPropertyImplDecl *SynthesizePID = nullptr;
7854
7855
0
  if (ObjCPropertyImplDecl *PropertyImpDecl =
7856
0
      getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
7857
0
    if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
7858
0
      Dynamic = true;
7859
0
    else
7860
0
      SynthesizePID = PropertyImpDecl;
7861
0
  }
7862
7863
  // FIXME: This is not very efficient.
7864
0
  std::string S = "T";
7865
7866
  // Encode result type.
7867
  // GCC has some special rules regarding encoding of properties which
7868
  // closely resembles encoding of ivars.
7869
0
  getObjCEncodingForPropertyType(PD->getType(), S);
7870
7871
0
  if (PD->isOptional())
7872
0
    S += ",?";
7873
7874
0
  if (PD->isReadOnly()) {
7875
0
    S += ",R";
7876
0
    if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_copy)
7877
0
      S += ",C";
7878
0
    if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_retain)
7879
0
      S += ",&";
7880
0
    if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_weak)
7881
0
      S += ",W";
7882
0
  } else {
7883
0
    switch (PD->getSetterKind()) {
7884
0
    case ObjCPropertyDecl::Assign: break;
7885
0
    case ObjCPropertyDecl::Copy:   S += ",C"; break;
7886
0
    case ObjCPropertyDecl::Retain: S += ",&"; break;
7887
0
    case ObjCPropertyDecl::Weak:   S += ",W"; break;
7888
0
    }
7889
0
  }
7890
7891
  // It really isn't clear at all what this means, since properties
7892
  // are "dynamic by default".
7893
0
  if (Dynamic)
7894
0
    S += ",D";
7895
7896
0
  if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_nonatomic)
7897
0
    S += ",N";
7898
7899
0
  if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_getter) {
7900
0
    S += ",G";
7901
0
    S += PD->getGetterName().getAsString();
7902
0
  }
7903
7904
0
  if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_setter) {
7905
0
    S += ",S";
7906
0
    S += PD->getSetterName().getAsString();
7907
0
  }
7908
7909
0
  if (SynthesizePID) {
7910
0
    const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
7911
0
    S += ",V";
7912
0
    S += OID->getNameAsString();
7913
0
  }
7914
7915
  // FIXME: OBJCGC: weak & strong
7916
0
  return S;
7917
0
}
7918
7919
/// getLegacyIntegralTypeEncoding -
7920
/// Another legacy compatibility encoding: 32-bit longs are encoded as
7921
/// 'l' or 'L' , but not always.  For typedefs, we need to use
7922
/// 'i' or 'I' instead if encoding a struct field, or a pointer!
7923
0
void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
7924
0
  if (PointeeTy->getAs<TypedefType>()) {
7925
0
    if (const auto *BT = PointeeTy->getAs<BuiltinType>()) {
7926
0
      if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
7927
0
        PointeeTy = UnsignedIntTy;
7928
0
      else
7929
0
        if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
7930
0
          PointeeTy = IntTy;
7931
0
    }
7932
0
  }
7933
0
}
7934
7935
void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
7936
                                        const FieldDecl *Field,
7937
0
                                        QualType *NotEncodedT) const {
7938
  // We follow the behavior of gcc, expanding structures which are
7939
  // directly pointed to, and expanding embedded structures. Note that
7940
  // these rules are sufficient to prevent recursive encoding of the
7941
  // same type.
7942
0
  getObjCEncodingForTypeImpl(T, S,
7943
0
                             ObjCEncOptions()
7944
0
                                 .setExpandPointedToStructures()
7945
0
                                 .setExpandStructures()
7946
0
                                 .setIsOutermostType(),
7947
0
                             Field, NotEncodedT);
7948
0
}
7949
7950
void ASTContext::getObjCEncodingForPropertyType(QualType T,
7951
0
                                                std::string& S) const {
7952
  // Encode result type.
7953
  // GCC has some special rules regarding encoding of properties which
7954
  // closely resembles encoding of ivars.
7955
0
  getObjCEncodingForTypeImpl(T, S,
7956
0
                             ObjCEncOptions()
7957
0
                                 .setExpandPointedToStructures()
7958
0
                                 .setExpandStructures()
7959
0
                                 .setIsOutermostType()
7960
0
                                 .setEncodingProperty(),
7961
0
                             /*Field=*/nullptr);
7962
0
}
7963
7964
static char getObjCEncodingForPrimitiveType(const ASTContext *C,
7965
0
                                            const BuiltinType *BT) {
7966
0
    BuiltinType::Kind kind = BT->getKind();
7967
0
    switch (kind) {
7968
0
    case BuiltinType::Void:       return 'v';
7969
0
    case BuiltinType::Bool:       return 'B';
7970
0
    case BuiltinType::Char8:
7971
0
    case BuiltinType::Char_U:
7972
0
    case BuiltinType::UChar:      return 'C';
7973
0
    case BuiltinType::Char16:
7974
0
    case BuiltinType::UShort:     return 'S';
7975
0
    case BuiltinType::Char32:
7976
0
    case BuiltinType::UInt:       return 'I';
7977
0
    case BuiltinType::ULong:
7978
0
        return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
7979
0
    case BuiltinType::UInt128:    return 'T';
7980
0
    case BuiltinType::ULongLong:  return 'Q';
7981
0
    case BuiltinType::Char_S:
7982
0
    case BuiltinType::SChar:      return 'c';
7983
0
    case BuiltinType::Short:      return 's';
7984
0
    case BuiltinType::WChar_S:
7985
0
    case BuiltinType::WChar_U:
7986
0
    case BuiltinType::Int:        return 'i';
7987
0
    case BuiltinType::Long:
7988
0
      return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
7989
0
    case BuiltinType::LongLong:   return 'q';
7990
0
    case BuiltinType::Int128:     return 't';
7991
0
    case BuiltinType::Float:      return 'f';
7992
0
    case BuiltinType::Double:     return 'd';
7993
0
    case BuiltinType::LongDouble: return 'D';
7994
0
    case BuiltinType::NullPtr:    return '*'; // like char*
7995
7996
0
    case BuiltinType::BFloat16:
7997
0
    case BuiltinType::Float16:
7998
0
    case BuiltinType::Float128:
7999
0
    case BuiltinType::Ibm128:
8000
0
    case BuiltinType::Half:
8001
0
    case BuiltinType::ShortAccum:
8002
0
    case BuiltinType::Accum:
8003
0
    case BuiltinType::LongAccum:
8004
0
    case BuiltinType::UShortAccum:
8005
0
    case BuiltinType::UAccum:
8006
0
    case BuiltinType::ULongAccum:
8007
0
    case BuiltinType::ShortFract:
8008
0
    case BuiltinType::Fract:
8009
0
    case BuiltinType::LongFract:
8010
0
    case BuiltinType::UShortFract:
8011
0
    case BuiltinType::UFract:
8012
0
    case BuiltinType::ULongFract:
8013
0
    case BuiltinType::SatShortAccum:
8014
0
    case BuiltinType::SatAccum:
8015
0
    case BuiltinType::SatLongAccum:
8016
0
    case BuiltinType::SatUShortAccum:
8017
0
    case BuiltinType::SatUAccum:
8018
0
    case BuiltinType::SatULongAccum:
8019
0
    case BuiltinType::SatShortFract:
8020
0
    case BuiltinType::SatFract:
8021
0
    case BuiltinType::SatLongFract:
8022
0
    case BuiltinType::SatUShortFract:
8023
0
    case BuiltinType::SatUFract:
8024
0
    case BuiltinType::SatULongFract:
8025
      // FIXME: potentially need @encodes for these!
8026
0
      return ' ';
8027
8028
0
#define SVE_TYPE(Name, Id, SingletonId) \
8029
0
    case BuiltinType::Id:
8030
0
#include "clang/Basic/AArch64SVEACLETypes.def"
8031
0
#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
8032
0
#include "clang/Basic/RISCVVTypes.def"
8033
0
#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
8034
0
#include "clang/Basic/WebAssemblyReferenceTypes.def"
8035
0
      {
8036
0
        DiagnosticsEngine &Diags = C->getDiagnostics();
8037
0
        unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
8038
0
                                                "cannot yet @encode type %0");
8039
0
        Diags.Report(DiagID) << BT->getName(C->getPrintingPolicy());
8040
0
        return ' ';
8041
0
      }
8042
8043
0
    case BuiltinType::ObjCId:
8044
0
    case BuiltinType::ObjCClass:
8045
0
    case BuiltinType::ObjCSel:
8046
0
      llvm_unreachable("@encoding ObjC primitive type");
8047
8048
    // OpenCL and placeholder types don't need @encodings.
8049
0
#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
8050
0
    case BuiltinType::Id:
8051
0
#include "clang/Basic/OpenCLImageTypes.def"
8052
0
#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
8053
0
    case BuiltinType::Id:
8054
0
#include "clang/Basic/OpenCLExtensionTypes.def"
8055
0
    case BuiltinType::OCLEvent:
8056
0
    case BuiltinType::OCLClkEvent:
8057
0
    case BuiltinType::OCLQueue:
8058
0
    case BuiltinType::OCLReserveID:
8059
0
    case BuiltinType::OCLSampler:
8060
0
    case BuiltinType::Dependent:
8061
0
#define PPC_VECTOR_TYPE(Name, Id, Size) \
8062
0
    case BuiltinType::Id:
8063
0
#include "clang/Basic/PPCTypes.def"
8064
0
#define BUILTIN_TYPE(KIND, ID)
8065
0
#define PLACEHOLDER_TYPE(KIND, ID) \
8066
0
    case BuiltinType::KIND:
8067
0
#include "clang/AST/BuiltinTypes.def"
8068
0
      llvm_unreachable("invalid builtin type for @encode");
8069
0
    }
8070
0
    llvm_unreachable("invalid BuiltinType::Kind value");
8071
0
}
8072
8073
0
static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
8074
0
  EnumDecl *Enum = ET->getDecl();
8075
8076
  // The encoding of an non-fixed enum type is always 'i', regardless of size.
8077
0
  if (!Enum->isFixed())
8078
0
    return 'i';
8079
8080
  // The encoding of a fixed enum type matches its fixed underlying type.
8081
0
  const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>();
8082
0
  return getObjCEncodingForPrimitiveType(C, BT);
8083
0
}
8084
8085
static void EncodeBitField(const ASTContext *Ctx, std::string& S,
8086
0
                           QualType T, const FieldDecl *FD) {
8087
0
  assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
8088
0
  S += 'b';
8089
  // The NeXT runtime encodes bit fields as b followed by the number of bits.
8090
  // The GNU runtime requires more information; bitfields are encoded as b,
8091
  // then the offset (in bits) of the first element, then the type of the
8092
  // bitfield, then the size in bits.  For example, in this structure:
8093
  //
8094
  // struct
8095
  // {
8096
  //    int integer;
8097
  //    int flags:2;
8098
  // };
8099
  // On a 32-bit system, the encoding for flags would be b2 for the NeXT
8100
  // runtime, but b32i2 for the GNU runtime.  The reason for this extra
8101
  // information is not especially sensible, but we're stuck with it for
8102
  // compatibility with GCC, although providing it breaks anything that
8103
  // actually uses runtime introspection and wants to work on both runtimes...
8104
0
  if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
8105
0
    uint64_t Offset;
8106
8107
0
    if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) {
8108
0
      Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), nullptr,
8109
0
                                         IVD);
8110
0
    } else {
8111
0
      const RecordDecl *RD = FD->getParent();
8112
0
      const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
8113
0
      Offset = RL.getFieldOffset(FD->getFieldIndex());
8114
0
    }
8115
8116
0
    S += llvm::utostr(Offset);
8117
8118
0
    if (const auto *ET = T->getAs<EnumType>())
8119
0
      S += ObjCEncodingForEnumType(Ctx, ET);
8120
0
    else {
8121
0
      const auto *BT = T->castAs<BuiltinType>();
8122
0
      S += getObjCEncodingForPrimitiveType(Ctx, BT);
8123
0
    }
8124
0
  }
8125
0
  S += llvm::utostr(FD->getBitWidthValue(*Ctx));
8126
0
}
8127
8128
// Helper function for determining whether the encoded type string would include
8129
// a template specialization type.
8130
static bool hasTemplateSpecializationInEncodedString(const Type *T,
8131
0
                                                     bool VisitBasesAndFields) {
8132
0
  T = T->getBaseElementTypeUnsafe();
8133
8134
0
  if (auto *PT = T->getAs<PointerType>())
8135
0
    return hasTemplateSpecializationInEncodedString(
8136
0
        PT->getPointeeType().getTypePtr(), false);
8137
8138
0
  auto *CXXRD = T->getAsCXXRecordDecl();
8139
8140
0
  if (!CXXRD)
8141
0
    return false;
8142
8143
0
  if (isa<ClassTemplateSpecializationDecl>(CXXRD))
8144
0
    return true;
8145
8146
0
  if (!CXXRD->hasDefinition() || !VisitBasesAndFields)
8147
0
    return false;
8148
8149
0
  for (const auto &B : CXXRD->bases())
8150
0
    if (hasTemplateSpecializationInEncodedString(B.getType().getTypePtr(),
8151
0
                                                 true))
8152
0
      return true;
8153
8154
0
  for (auto *FD : CXXRD->fields())
8155
0
    if (hasTemplateSpecializationInEncodedString(FD->getType().getTypePtr(),
8156
0
                                                 true))
8157
0
      return true;
8158
8159
0
  return false;
8160
0
}
8161
8162
// FIXME: Use SmallString for accumulating string.
8163
void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S,
8164
                                            const ObjCEncOptions Options,
8165
                                            const FieldDecl *FD,
8166
0
                                            QualType *NotEncodedT) const {
8167
0
  CanQualType CT = getCanonicalType(T);
8168
0
  switch (CT->getTypeClass()) {
8169
0
  case Type::Builtin:
8170
0
  case Type::Enum:
8171
0
    if (FD && FD->isBitField())
8172
0
      return EncodeBitField(this, S, T, FD);
8173
0
    if (const auto *BT = dyn_cast<BuiltinType>(CT))
8174
0
      S += getObjCEncodingForPrimitiveType(this, BT);
8175
0
    else
8176
0
      S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
8177
0
    return;
8178
8179
0
  case Type::Complex:
8180
0
    S += 'j';
8181
0
    getObjCEncodingForTypeImpl(T->castAs<ComplexType>()->getElementType(), S,
8182
0
                               ObjCEncOptions(),
8183
0
                               /*Field=*/nullptr);
8184
0
    return;
8185
8186
0
  case Type::Atomic:
8187
0
    S += 'A';
8188
0
    getObjCEncodingForTypeImpl(T->castAs<AtomicType>()->getValueType(), S,
8189
0
                               ObjCEncOptions(),
8190
0
                               /*Field=*/nullptr);
8191
0
    return;
8192
8193
  // encoding for pointer or reference types.
8194
0
  case Type::Pointer:
8195
0
  case Type::LValueReference:
8196
0
  case Type::RValueReference: {
8197
0
    QualType PointeeTy;
8198
0
    if (isa<PointerType>(CT)) {
8199
0
      const auto *PT = T->castAs<PointerType>();
8200
0
      if (PT->isObjCSelType()) {
8201
0
        S += ':';
8202
0
        return;
8203
0
      }
8204
0
      PointeeTy = PT->getPointeeType();
8205
0
    } else {
8206
0
      PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
8207
0
    }
8208
8209
0
    bool isReadOnly = false;
8210
    // For historical/compatibility reasons, the read-only qualifier of the
8211
    // pointee gets emitted _before_ the '^'.  The read-only qualifier of
8212
    // the pointer itself gets ignored, _unless_ we are looking at a typedef!
8213
    // Also, do not emit the 'r' for anything but the outermost type!
8214
0
    if (T->getAs<TypedefType>()) {
8215
0
      if (Options.IsOutermostType() && T.isConstQualified()) {
8216
0
        isReadOnly = true;
8217
0
        S += 'r';
8218
0
      }
8219
0
    } else if (Options.IsOutermostType()) {
8220
0
      QualType P = PointeeTy;
8221
0
      while (auto PT = P->getAs<PointerType>())
8222
0
        P = PT->getPointeeType();
8223
0
      if (P.isConstQualified()) {
8224
0
        isReadOnly = true;
8225
0
        S += 'r';
8226
0
      }
8227
0
    }
8228
0
    if (isReadOnly) {
8229
      // Another legacy compatibility encoding. Some ObjC qualifier and type
8230
      // combinations need to be rearranged.
8231
      // Rewrite "in const" from "nr" to "rn"
8232
0
      if (StringRef(S).ends_with("nr"))
8233
0
        S.replace(S.end()-2, S.end(), "rn");
8234
0
    }
8235
8236
0
    if (PointeeTy->isCharType()) {
8237
      // char pointer types should be encoded as '*' unless it is a
8238
      // type that has been typedef'd to 'BOOL'.
8239
0
      if (!isTypeTypedefedAsBOOL(PointeeTy)) {
8240
0
        S += '*';
8241
0
        return;
8242
0
      }
8243
0
    } else if (const auto *RTy = PointeeTy->getAs<RecordType>()) {
8244
      // GCC binary compat: Need to convert "struct objc_class *" to "#".
8245
0
      if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
8246
0
        S += '#';
8247
0
        return;
8248
0
      }
8249
      // GCC binary compat: Need to convert "struct objc_object *" to "@".
8250
0
      if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
8251
0
        S += '@';
8252
0
        return;
8253
0
      }
8254
      // If the encoded string for the class includes template names, just emit
8255
      // "^v" for pointers to the class.
8256
0
      if (getLangOpts().CPlusPlus &&
8257
0
          (!getLangOpts().EncodeCXXClassTemplateSpec &&
8258
0
           hasTemplateSpecializationInEncodedString(
8259
0
               RTy, Options.ExpandPointedToStructures()))) {
8260
0
        S += "^v";
8261
0
        return;
8262
0
      }
8263
      // fall through...
8264
0
    }
8265
0
    S += '^';
8266
0
    getLegacyIntegralTypeEncoding(PointeeTy);
8267
8268
0
    ObjCEncOptions NewOptions;
8269
0
    if (Options.ExpandPointedToStructures())
8270
0
      NewOptions.setExpandStructures();
8271
0
    getObjCEncodingForTypeImpl(PointeeTy, S, NewOptions,
8272
0
                               /*Field=*/nullptr, NotEncodedT);
8273
0
    return;
8274
0
  }
8275
8276
0
  case Type::ConstantArray:
8277
0
  case Type::IncompleteArray:
8278
0
  case Type::VariableArray: {
8279
0
    const auto *AT = cast<ArrayType>(CT);
8280
8281
0
    if (isa<IncompleteArrayType>(AT) && !Options.IsStructField()) {
8282
      // Incomplete arrays are encoded as a pointer to the array element.
8283
0
      S += '^';
8284
8285
0
      getObjCEncodingForTypeImpl(
8286
0
          AT->getElementType(), S,
8287
0
          Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD);
8288
0
    } else {
8289
0
      S += '[';
8290
8291
0
      if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
8292
0
        S += llvm::utostr(CAT->getSize().getZExtValue());
8293
0
      else {
8294
        //Variable length arrays are encoded as a regular array with 0 elements.
8295
0
        assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
8296
0
               "Unknown array type!");
8297
0
        S += '0';
8298
0
      }
8299
8300
0
      getObjCEncodingForTypeImpl(
8301
0
          AT->getElementType(), S,
8302
0
          Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD,
8303
0
          NotEncodedT);
8304
0
      S += ']';
8305
0
    }
8306
0
    return;
8307
0
  }
8308
8309
0
  case Type::FunctionNoProto:
8310
0
  case Type::FunctionProto:
8311
0
    S += '?';
8312
0
    return;
8313
8314
0
  case Type::Record: {
8315
0
    RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
8316
0
    S += RDecl->isUnion() ? '(' : '{';
8317
    // Anonymous structures print as '?'
8318
0
    if (const IdentifierInfo *II = RDecl->getIdentifier()) {
8319
0
      S += II->getName();
8320
0
      if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
8321
0
        const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
8322
0
        llvm::raw_string_ostream OS(S);
8323
0
        printTemplateArgumentList(OS, TemplateArgs.asArray(),
8324
0
                                  getPrintingPolicy());
8325
0
      }
8326
0
    } else {
8327
0
      S += '?';
8328
0
    }
8329
0
    if (Options.ExpandStructures()) {
8330
0
      S += '=';
8331
0
      if (!RDecl->isUnion()) {
8332
0
        getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
8333
0
      } else {
8334
0
        for (const auto *Field : RDecl->fields()) {
8335
0
          if (FD) {
8336
0
            S += '"';
8337
0
            S += Field->getNameAsString();
8338
0
            S += '"';
8339
0
          }
8340
8341
          // Special case bit-fields.
8342
0
          if (Field->isBitField()) {
8343
0
            getObjCEncodingForTypeImpl(Field->getType(), S,
8344
0
                                       ObjCEncOptions().setExpandStructures(),
8345
0
                                       Field);
8346
0
          } else {
8347
0
            QualType qt = Field->getType();
8348
0
            getLegacyIntegralTypeEncoding(qt);
8349
0
            getObjCEncodingForTypeImpl(
8350
0
                qt, S,
8351
0
                ObjCEncOptions().setExpandStructures().setIsStructField(), FD,
8352
0
                NotEncodedT);
8353
0
          }
8354
0
        }
8355
0
      }
8356
0
    }
8357
0
    S += RDecl->isUnion() ? ')' : '}';
8358
0
    return;
8359
0
  }
8360
8361
0
  case Type::BlockPointer: {
8362
0
    const auto *BT = T->castAs<BlockPointerType>();
8363
0
    S += "@?"; // Unlike a pointer-to-function, which is "^?".
8364
0
    if (Options.EncodeBlockParameters()) {
8365
0
      const auto *FT = BT->getPointeeType()->castAs<FunctionType>();
8366
8367
0
      S += '<';
8368
      // Block return type
8369
0
      getObjCEncodingForTypeImpl(FT->getReturnType(), S,
8370
0
                                 Options.forComponentType(), FD, NotEncodedT);
8371
      // Block self
8372
0
      S += "@?";
8373
      // Block parameters
8374
0
      if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) {
8375
0
        for (const auto &I : FPT->param_types())
8376
0
          getObjCEncodingForTypeImpl(I, S, Options.forComponentType(), FD,
8377
0
                                     NotEncodedT);
8378
0
      }
8379
0
      S += '>';
8380
0
    }
8381
0
    return;
8382
0
  }
8383
8384
0
  case Type::ObjCObject: {
8385
    // hack to match legacy encoding of *id and *Class
8386
0
    QualType Ty = getObjCObjectPointerType(CT);
8387
0
    if (Ty->isObjCIdType()) {
8388
0
      S += "{objc_object=}";
8389
0
      return;
8390
0
    }
8391
0
    else if (Ty->isObjCClassType()) {
8392
0
      S += "{objc_class=}";
8393
0
      return;
8394
0
    }
8395
    // TODO: Double check to make sure this intentionally falls through.
8396
0
    [[fallthrough]];
8397
0
  }
8398
8399
0
  case Type::ObjCInterface: {
8400
    // Ignore protocol qualifiers when mangling at this level.
8401
    // @encode(class_name)
8402
0
    ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
8403
0
    S += '{';
8404
0
    S += OI->getObjCRuntimeNameAsString();
8405
0
    if (Options.ExpandStructures()) {
8406
0
      S += '=';
8407
0
      SmallVector<const ObjCIvarDecl*, 32> Ivars;
8408
0
      DeepCollectObjCIvars(OI, true, Ivars);
8409
0
      for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
8410
0
        const FieldDecl *Field = Ivars[i];
8411
0
        if (Field->isBitField())
8412
0
          getObjCEncodingForTypeImpl(Field->getType(), S,
8413
0
                                     ObjCEncOptions().setExpandStructures(),
8414
0
                                     Field);
8415
0
        else
8416
0
          getObjCEncodingForTypeImpl(Field->getType(), S,
8417
0
                                     ObjCEncOptions().setExpandStructures(), FD,
8418
0
                                     NotEncodedT);
8419
0
      }
8420
0
    }
8421
0
    S += '}';
8422
0
    return;
8423
0
  }
8424
8425
0
  case Type::ObjCObjectPointer: {
8426
0
    const auto *OPT = T->castAs<ObjCObjectPointerType>();
8427
0
    if (OPT->isObjCIdType()) {
8428
0
      S += '@';
8429
0
      return;
8430
0
    }
8431
8432
0
    if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
8433
      // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
8434
      // Since this is a binary compatibility issue, need to consult with
8435
      // runtime folks. Fortunately, this is a *very* obscure construct.
8436
0
      S += '#';
8437
0
      return;
8438
0
    }
8439
8440
0
    if (OPT->isObjCQualifiedIdType()) {
8441
0
      getObjCEncodingForTypeImpl(
8442
0
          getObjCIdType(), S,
8443
0
          Options.keepingOnly(ObjCEncOptions()
8444
0
                                  .setExpandPointedToStructures()
8445
0
                                  .setExpandStructures()),
8446
0
          FD);
8447
0
      if (FD || Options.EncodingProperty() || Options.EncodeClassNames()) {
8448
        // Note that we do extended encoding of protocol qualifier list
8449
        // Only when doing ivar or property encoding.
8450
0
        S += '"';
8451
0
        for (const auto *I : OPT->quals()) {
8452
0
          S += '<';
8453
0
          S += I->getObjCRuntimeNameAsString();
8454
0
          S += '>';
8455
0
        }
8456
0
        S += '"';
8457
0
      }
8458
0
      return;
8459
0
    }
8460
8461
0
    S += '@';
8462
0
    if (OPT->getInterfaceDecl() &&
8463
0
        (FD || Options.EncodingProperty() || Options.EncodeClassNames())) {
8464
0
      S += '"';
8465
0
      S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
8466
0
      for (const auto *I : OPT->quals()) {
8467
0
        S += '<';
8468
0
        S += I->getObjCRuntimeNameAsString();
8469
0
        S += '>';
8470
0
      }
8471
0
      S += '"';
8472
0
    }
8473
0
    return;
8474
0
  }
8475
8476
  // gcc just blithely ignores member pointers.
8477
  // FIXME: we should do better than that.  'M' is available.
8478
0
  case Type::MemberPointer:
8479
  // This matches gcc's encoding, even though technically it is insufficient.
8480
  //FIXME. We should do a better job than gcc.
8481
0
  case Type::Vector:
8482
0
  case Type::ExtVector:
8483
  // Until we have a coherent encoding of these three types, issue warning.
8484
0
    if (NotEncodedT)
8485
0
      *NotEncodedT = T;
8486
0
    return;
8487
8488
0
  case Type::ConstantMatrix:
8489
0
    if (NotEncodedT)
8490
0
      *NotEncodedT = T;
8491
0
    return;
8492
8493
0
  case Type::BitInt:
8494
0
    if (NotEncodedT)
8495
0
      *NotEncodedT = T;
8496
0
    return;
8497
8498
  // We could see an undeduced auto type here during error recovery.
8499
  // Just ignore it.
8500
0
  case Type::Auto:
8501
0
  case Type::DeducedTemplateSpecialization:
8502
0
    return;
8503
8504
0
  case Type::Pipe:
8505
0
#define ABSTRACT_TYPE(KIND, BASE)
8506
0
#define TYPE(KIND, BASE)
8507
0
#define DEPENDENT_TYPE(KIND, BASE) \
8508
0
  case Type::KIND:
8509
0
#define NON_CANONICAL_TYPE(KIND, BASE) \
8510
0
  case Type::KIND:
8511
0
#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
8512
0
  case Type::KIND:
8513
0
#include "clang/AST/TypeNodes.inc"
8514
0
    llvm_unreachable("@encode for dependent type!");
8515
0
  }
8516
0
  llvm_unreachable("bad type kind!");
8517
0
}
8518
8519
void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
8520
                                                 std::string &S,
8521
                                                 const FieldDecl *FD,
8522
                                                 bool includeVBases,
8523
0
                                                 QualType *NotEncodedT) const {
8524
0
  assert(RDecl && "Expected non-null RecordDecl");
8525
0
  assert(!RDecl->isUnion() && "Should not be called for unions");
8526
0
  if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
8527
0
    return;
8528
8529
0
  const auto *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
8530
0
  std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
8531
0
  const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
8532
8533
0
  if (CXXRec) {
8534
0
    for (const auto &BI : CXXRec->bases()) {
8535
0
      if (!BI.isVirtual()) {
8536
0
        CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
8537
0
        if (base->isEmpty())
8538
0
          continue;
8539
0
        uint64_t offs = toBits(layout.getBaseClassOffset(base));
8540
0
        FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
8541
0
                                  std::make_pair(offs, base));
8542
0
      }
8543
0
    }
8544
0
  }
8545
8546
0
  for (FieldDecl *Field : RDecl->fields()) {
8547
0
    if (!Field->isZeroLengthBitField(*this) && Field->isZeroSize(*this))
8548
0
      continue;
8549
0
    uint64_t offs = layout.getFieldOffset(Field->getFieldIndex());
8550
0
    FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
8551
0
                              std::make_pair(offs, Field));
8552
0
  }
8553
8554
0
  if (CXXRec && includeVBases) {
8555
0
    for (const auto &BI : CXXRec->vbases()) {
8556
0
      CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
8557
0
      if (base->isEmpty())
8558
0
        continue;
8559
0
      uint64_t offs = toBits(layout.getVBaseClassOffset(base));
8560
0
      if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
8561
0
          FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
8562
0
        FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
8563
0
                                  std::make_pair(offs, base));
8564
0
    }
8565
0
  }
8566
8567
0
  CharUnits size;
8568
0
  if (CXXRec) {
8569
0
    size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
8570
0
  } else {
8571
0
    size = layout.getSize();
8572
0
  }
8573
8574
0
#ifndef NDEBUG
8575
0
  uint64_t CurOffs = 0;
8576
0
#endif
8577
0
  std::multimap<uint64_t, NamedDecl *>::iterator
8578
0
    CurLayObj = FieldOrBaseOffsets.begin();
8579
8580
0
  if (CXXRec && CXXRec->isDynamicClass() &&
8581
0
      (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
8582
0
    if (FD) {
8583
0
      S += "\"_vptr$";
8584
0
      std::string recname = CXXRec->getNameAsString();
8585
0
      if (recname.empty()) recname = "?";
8586
0
      S += recname;
8587
0
      S += '"';
8588
0
    }
8589
0
    S += "^^?";
8590
0
#ifndef NDEBUG
8591
0
    CurOffs += getTypeSize(VoidPtrTy);
8592
0
#endif
8593
0
  }
8594
8595
0
  if (!RDecl->hasFlexibleArrayMember()) {
8596
    // Mark the end of the structure.
8597
0
    uint64_t offs = toBits(size);
8598
0
    FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
8599
0
                              std::make_pair(offs, nullptr));
8600
0
  }
8601
8602
0
  for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
8603
0
#ifndef NDEBUG
8604
0
    assert(CurOffs <= CurLayObj->first);
8605
0
    if (CurOffs < CurLayObj->first) {
8606
0
      uint64_t padding = CurLayObj->first - CurOffs;
8607
      // FIXME: There doesn't seem to be a way to indicate in the encoding that
8608
      // packing/alignment of members is different that normal, in which case
8609
      // the encoding will be out-of-sync with the real layout.
8610
      // If the runtime switches to just consider the size of types without
8611
      // taking into account alignment, we could make padding explicit in the
8612
      // encoding (e.g. using arrays of chars). The encoding strings would be
8613
      // longer then though.
8614
0
      CurOffs += padding;
8615
0
    }
8616
0
#endif
8617
8618
0
    NamedDecl *dcl = CurLayObj->second;
8619
0
    if (!dcl)
8620
0
      break; // reached end of structure.
8621
8622
0
    if (auto *base = dyn_cast<CXXRecordDecl>(dcl)) {
8623
      // We expand the bases without their virtual bases since those are going
8624
      // in the initial structure. Note that this differs from gcc which
8625
      // expands virtual bases each time one is encountered in the hierarchy,
8626
      // making the encoding type bigger than it really is.
8627
0
      getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
8628
0
                                      NotEncodedT);
8629
0
      assert(!base->isEmpty());
8630
0
#ifndef NDEBUG
8631
0
      CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
8632
0
#endif
8633
0
    } else {
8634
0
      const auto *field = cast<FieldDecl>(dcl);
8635
0
      if (FD) {
8636
0
        S += '"';
8637
0
        S += field->getNameAsString();
8638
0
        S += '"';
8639
0
      }
8640
8641
0
      if (field->isBitField()) {
8642
0
        EncodeBitField(this, S, field->getType(), field);
8643
0
#ifndef NDEBUG
8644
0
        CurOffs += field->getBitWidthValue(*this);
8645
0
#endif
8646
0
      } else {
8647
0
        QualType qt = field->getType();
8648
0
        getLegacyIntegralTypeEncoding(qt);
8649
0
        getObjCEncodingForTypeImpl(
8650
0
            qt, S, ObjCEncOptions().setExpandStructures().setIsStructField(),
8651
0
            FD, NotEncodedT);
8652
0
#ifndef NDEBUG
8653
0
        CurOffs += getTypeSize(field->getType());
8654
0
#endif
8655
0
      }
8656
0
    }
8657
0
  }
8658
0
}
8659
8660
void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
8661
0
                                                 std::string& S) const {
8662
0
  if (QT & Decl::OBJC_TQ_In)
8663
0
    S += 'n';
8664
0
  if (QT & Decl::OBJC_TQ_Inout)
8665
0
    S += 'N';
8666
0
  if (QT & Decl::OBJC_TQ_Out)
8667
0
    S += 'o';
8668
0
  if (QT & Decl::OBJC_TQ_Bycopy)
8669
0
    S += 'O';
8670
0
  if (QT & Decl::OBJC_TQ_Byref)
8671
0
    S += 'R';
8672
0
  if (QT & Decl::OBJC_TQ_Oneway)
8673
0
    S += 'V';
8674
0
}
8675
8676
69
TypedefDecl *ASTContext::getObjCIdDecl() const {
8677
69
  if (!ObjCIdDecl) {
8678
23
    QualType T = getObjCObjectType(ObjCBuiltinIdTy, {}, {});
8679
23
    T = getObjCObjectPointerType(T);
8680
23
    ObjCIdDecl = buildImplicitTypedef(T, "id");
8681
23
  }
8682
69
  return ObjCIdDecl;
8683
69
}
8684
8685
69
TypedefDecl *ASTContext::getObjCSelDecl() const {
8686
69
  if (!ObjCSelDecl) {
8687
23
    QualType T = getPointerType(ObjCBuiltinSelTy);
8688
23
    ObjCSelDecl = buildImplicitTypedef(T, "SEL");
8689
23
  }
8690
69
  return ObjCSelDecl;
8691
69
}
8692
8693
46
TypedefDecl *ASTContext::getObjCClassDecl() const {
8694
46
  if (!ObjCClassDecl) {
8695
23
    QualType T = getObjCObjectType(ObjCBuiltinClassTy, {}, {});
8696
23
    T = getObjCObjectPointerType(T);
8697
23
    ObjCClassDecl = buildImplicitTypedef(T, "Class");
8698
23
  }
8699
46
  return ObjCClassDecl;
8700
46
}
8701
8702
23
ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
8703
23
  if (!ObjCProtocolClassDecl) {
8704
23
    ObjCProtocolClassDecl
8705
23
      = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
8706
23
                                  SourceLocation(),
8707
23
                                  &Idents.get("Protocol"),
8708
23
                                  /*typeParamList=*/nullptr,
8709
23
                                  /*PrevDecl=*/nullptr,
8710
23
                                  SourceLocation(), true);
8711
23
  }
8712
8713
23
  return ObjCProtocolClassDecl;
8714
23
}
8715
8716
//===----------------------------------------------------------------------===//
8717
// __builtin_va_list Construction Functions
8718
//===----------------------------------------------------------------------===//
8719
8720
static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context,
8721
46
                                                 StringRef Name) {
8722
  // typedef char* __builtin[_ms]_va_list;
8723
46
  QualType T = Context->getPointerType(Context->CharTy);
8724
46
  return Context->buildImplicitTypedef(T, Name);
8725
46
}
8726
8727
46
static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
8728
46
  return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
8729
46
}
8730
8731
0
static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
8732
0
  return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
8733
0
}
8734
8735
0
static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
8736
  // typedef void* __builtin_va_list;
8737
0
  QualType T = Context->getPointerType(Context->VoidTy);
8738
0
  return Context->buildImplicitTypedef(T, "__builtin_va_list");
8739
0
}
8740
8741
static TypedefDecl *
8742
0
CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
8743
  // struct __va_list
8744
0
  RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
8745
0
  if (Context->getLangOpts().CPlusPlus) {
8746
    // namespace std { struct __va_list {
8747
0
    auto *NS = NamespaceDecl::Create(
8748
0
        const_cast<ASTContext &>(*Context), Context->getTranslationUnitDecl(),
8749
0
        /*Inline=*/false, SourceLocation(), SourceLocation(),
8750
0
        &Context->Idents.get("std"),
8751
0
        /*PrevDecl=*/nullptr, /*Nested=*/false);
8752
0
    NS->setImplicit();
8753
0
    VaListTagDecl->setDeclContext(NS);
8754
0
  }
8755
8756
0
  VaListTagDecl->startDefinition();
8757
8758
0
  const size_t NumFields = 5;
8759
0
  QualType FieldTypes[NumFields];
8760
0
  const char *FieldNames[NumFields];
8761
8762
  // void *__stack;
8763
0
  FieldTypes[0] = Context->getPointerType(Context->VoidTy);
8764
0
  FieldNames[0] = "__stack";
8765
8766
  // void *__gr_top;
8767
0
  FieldTypes[1] = Context->getPointerType(Context->VoidTy);
8768
0
  FieldNames[1] = "__gr_top";
8769
8770
  // void *__vr_top;
8771
0
  FieldTypes[2] = Context->getPointerType(Context->VoidTy);
8772
0
  FieldNames[2] = "__vr_top";
8773
8774
  // int __gr_offs;
8775
0
  FieldTypes[3] = Context->IntTy;
8776
0
  FieldNames[3] = "__gr_offs";
8777
8778
  // int __vr_offs;
8779
0
  FieldTypes[4] = Context->IntTy;
8780
0
  FieldNames[4] = "__vr_offs";
8781
8782
  // Create fields
8783
0
  for (unsigned i = 0; i < NumFields; ++i) {
8784
0
    FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
8785
0
                                         VaListTagDecl,
8786
0
                                         SourceLocation(),
8787
0
                                         SourceLocation(),
8788
0
                                         &Context->Idents.get(FieldNames[i]),
8789
0
                                         FieldTypes[i], /*TInfo=*/nullptr,
8790
0
                                         /*BitWidth=*/nullptr,
8791
0
                                         /*Mutable=*/false,
8792
0
                                         ICIS_NoInit);
8793
0
    Field->setAccess(AS_public);
8794
0
    VaListTagDecl->addDecl(Field);
8795
0
  }
8796
0
  VaListTagDecl->completeDefinition();
8797
0
  Context->VaListTagDecl = VaListTagDecl;
8798
0
  QualType VaListTagType = Context->getRecordType(VaListTagDecl);
8799
8800
  // } __builtin_va_list;
8801
0
  return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
8802
0
}
8803
8804
0
static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
8805
  // typedef struct __va_list_tag {
8806
0
  RecordDecl *VaListTagDecl;
8807
8808
0
  VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
8809
0
  VaListTagDecl->startDefinition();
8810
8811
0
  const size_t NumFields = 5;
8812
0
  QualType FieldTypes[NumFields];
8813
0
  const char *FieldNames[NumFields];
8814
8815
  //   unsigned char gpr;
8816
0
  FieldTypes[0] = Context->UnsignedCharTy;
8817
0
  FieldNames[0] = "gpr";
8818
8819
  //   unsigned char fpr;
8820
0
  FieldTypes[1] = Context->UnsignedCharTy;
8821
0
  FieldNames[1] = "fpr";
8822
8823
  //   unsigned short reserved;
8824
0
  FieldTypes[2] = Context->UnsignedShortTy;
8825
0
  FieldNames[2] = "reserved";
8826
8827
  //   void* overflow_arg_area;
8828
0
  FieldTypes[3] = Context->getPointerType(Context->VoidTy);
8829
0
  FieldNames[3] = "overflow_arg_area";
8830
8831
  //   void* reg_save_area;
8832
0
  FieldTypes[4] = Context->getPointerType(Context->VoidTy);
8833
0
  FieldNames[4] = "reg_save_area";
8834
8835
  // Create fields
8836
0
  for (unsigned i = 0; i < NumFields; ++i) {
8837
0
    FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
8838
0
                                         SourceLocation(),
8839
0
                                         SourceLocation(),
8840
0
                                         &Context->Idents.get(FieldNames[i]),
8841
0
                                         FieldTypes[i], /*TInfo=*/nullptr,
8842
0
                                         /*BitWidth=*/nullptr,
8843
0
                                         /*Mutable=*/false,
8844
0
                                         ICIS_NoInit);
8845
0
    Field->setAccess(AS_public);
8846
0
    VaListTagDecl->addDecl(Field);
8847
0
  }
8848
0
  VaListTagDecl->completeDefinition();
8849
0
  Context->VaListTagDecl = VaListTagDecl;
8850
0
  QualType VaListTagType = Context->getRecordType(VaListTagDecl);
8851
8852
  // } __va_list_tag;
8853
0
  TypedefDecl *VaListTagTypedefDecl =
8854
0
      Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
8855
8856
0
  QualType VaListTagTypedefType =
8857
0
    Context->getTypedefType(VaListTagTypedefDecl);
8858
8859
  // typedef __va_list_tag __builtin_va_list[1];
8860
0
  llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
8861
0
  QualType VaListTagArrayType = Context->getConstantArrayType(
8862
0
      VaListTagTypedefType, Size, nullptr, ArraySizeModifier::Normal, 0);
8863
0
  return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
8864
0
}
8865
8866
static TypedefDecl *
8867
46
CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
8868
  // struct __va_list_tag {
8869
46
  RecordDecl *VaListTagDecl;
8870
46
  VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
8871
46
  VaListTagDecl->startDefinition();
8872
8873
46
  const size_t NumFields = 4;
8874
46
  QualType FieldTypes[NumFields];
8875
46
  const char *FieldNames[NumFields];
8876
8877
  //   unsigned gp_offset;
8878
46
  FieldTypes[0] = Context->UnsignedIntTy;
8879
46
  FieldNames[0] = "gp_offset";
8880
8881
  //   unsigned fp_offset;
8882
46
  FieldTypes[1] = Context->UnsignedIntTy;
8883
46
  FieldNames[1] = "fp_offset";
8884
8885
  //   void* overflow_arg_area;
8886
46
  FieldTypes[2] = Context->getPointerType(Context->VoidTy);
8887
46
  FieldNames[2] = "overflow_arg_area";
8888
8889
  //   void* reg_save_area;
8890
46
  FieldTypes[3] = Context->getPointerType(Context->VoidTy);
8891
46
  FieldNames[3] = "reg_save_area";
8892
8893
  // Create fields
8894
230
  for (unsigned i = 0; i < NumFields; ++i) {
8895
184
    FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
8896
184
                                         VaListTagDecl,
8897
184
                                         SourceLocation(),
8898
184
                                         SourceLocation(),
8899
184
                                         &Context->Idents.get(FieldNames[i]),
8900
184
                                         FieldTypes[i], /*TInfo=*/nullptr,
8901
184
                                         /*BitWidth=*/nullptr,
8902
184
                                         /*Mutable=*/false,
8903
184
                                         ICIS_NoInit);
8904
184
    Field->setAccess(AS_public);
8905
184
    VaListTagDecl->addDecl(Field);
8906
184
  }
8907
46
  VaListTagDecl->completeDefinition();
8908
46
  Context->VaListTagDecl = VaListTagDecl;
8909
46
  QualType VaListTagType = Context->getRecordType(VaListTagDecl);
8910
8911
  // };
8912
8913
  // typedef struct __va_list_tag __builtin_va_list[1];
8914
46
  llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
8915
46
  QualType VaListTagArrayType = Context->getConstantArrayType(
8916
46
      VaListTagType, Size, nullptr, ArraySizeModifier::Normal, 0);
8917
46
  return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
8918
46
}
8919
8920
0
static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
8921
  // typedef int __builtin_va_list[4];
8922
0
  llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
8923
0
  QualType IntArrayType = Context->getConstantArrayType(
8924
0
      Context->IntTy, Size, nullptr, ArraySizeModifier::Normal, 0);
8925
0
  return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
8926
0
}
8927
8928
static TypedefDecl *
8929
0
CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
8930
  // struct __va_list
8931
0
  RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
8932
0
  if (Context->getLangOpts().CPlusPlus) {
8933
    // namespace std { struct __va_list {
8934
0
    NamespaceDecl *NS;
8935
0
    NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
8936
0
                               Context->getTranslationUnitDecl(),
8937
0
                               /*Inline=*/false, SourceLocation(),
8938
0
                               SourceLocation(), &Context->Idents.get("std"),
8939
0
                               /*PrevDecl=*/nullptr, /*Nested=*/false);
8940
0
    NS->setImplicit();
8941
0
    VaListDecl->setDeclContext(NS);
8942
0
  }
8943
8944
0
  VaListDecl->startDefinition();
8945
8946
  // void * __ap;
8947
0
  FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
8948
0
                                       VaListDecl,
8949
0
                                       SourceLocation(),
8950
0
                                       SourceLocation(),
8951
0
                                       &Context->Idents.get("__ap"),
8952
0
                                       Context->getPointerType(Context->VoidTy),
8953
0
                                       /*TInfo=*/nullptr,
8954
0
                                       /*BitWidth=*/nullptr,
8955
0
                                       /*Mutable=*/false,
8956
0
                                       ICIS_NoInit);
8957
0
  Field->setAccess(AS_public);
8958
0
  VaListDecl->addDecl(Field);
8959
8960
  // };
8961
0
  VaListDecl->completeDefinition();
8962
0
  Context->VaListTagDecl = VaListDecl;
8963
8964
  // typedef struct __va_list __builtin_va_list;
8965
0
  QualType T = Context->getRecordType(VaListDecl);
8966
0
  return Context->buildImplicitTypedef(T, "__builtin_va_list");
8967
0
}
8968
8969
static TypedefDecl *
8970
0
CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
8971
  // struct __va_list_tag {
8972
0
  RecordDecl *VaListTagDecl;
8973
0
  VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
8974
0
  VaListTagDecl->startDefinition();
8975
8976
0
  const size_t NumFields = 4;
8977
0
  QualType FieldTypes[NumFields];
8978
0
  const char *FieldNames[NumFields];
8979
8980
  //   long __gpr;
8981
0
  FieldTypes[0] = Context->LongTy;
8982
0
  FieldNames[0] = "__gpr";
8983
8984
  //   long __fpr;
8985
0
  FieldTypes[1] = Context->LongTy;
8986
0
  FieldNames[1] = "__fpr";
8987
8988
  //   void *__overflow_arg_area;
8989
0
  FieldTypes[2] = Context->getPointerType(Context->VoidTy);
8990
0
  FieldNames[2] = "__overflow_arg_area";
8991
8992
  //   void *__reg_save_area;
8993
0
  FieldTypes[3] = Context->getPointerType(Context->VoidTy);
8994
0
  FieldNames[3] = "__reg_save_area";
8995
8996
  // Create fields
8997
0
  for (unsigned i = 0; i < NumFields; ++i) {
8998
0
    FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
8999
0
                                         VaListTagDecl,
9000
0
                                         SourceLocation(),
9001
0
                                         SourceLocation(),
9002
0
                                         &Context->Idents.get(FieldNames[i]),
9003
0
                                         FieldTypes[i], /*TInfo=*/nullptr,
9004
0
                                         /*BitWidth=*/nullptr,
9005
0
                                         /*Mutable=*/false,
9006
0
                                         ICIS_NoInit);
9007
0
    Field->setAccess(AS_public);
9008
0
    VaListTagDecl->addDecl(Field);
9009
0
  }
9010
0
  VaListTagDecl->completeDefinition();
9011
0
  Context->VaListTagDecl = VaListTagDecl;
9012
0
  QualType VaListTagType = Context->getRecordType(VaListTagDecl);
9013
9014
  // };
9015
9016
  // typedef __va_list_tag __builtin_va_list[1];
9017
0
  llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
9018
0
  QualType VaListTagArrayType = Context->getConstantArrayType(
9019
0
      VaListTagType, Size, nullptr, ArraySizeModifier::Normal, 0);
9020
9021
0
  return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
9022
0
}
9023
9024
0
static TypedefDecl *CreateHexagonBuiltinVaListDecl(const ASTContext *Context) {
9025
  // typedef struct __va_list_tag {
9026
0
  RecordDecl *VaListTagDecl;
9027
0
  VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
9028
0
  VaListTagDecl->startDefinition();
9029
9030
0
  const size_t NumFields = 3;
9031
0
  QualType FieldTypes[NumFields];
9032
0
  const char *FieldNames[NumFields];
9033
9034
  //   void *CurrentSavedRegisterArea;
9035
0
  FieldTypes[0] = Context->getPointerType(Context->VoidTy);
9036
0
  FieldNames[0] = "__current_saved_reg_area_pointer";
9037
9038
  //   void *SavedRegAreaEnd;
9039
0
  FieldTypes[1] = Context->getPointerType(Context->VoidTy);
9040
0
  FieldNames[1] = "__saved_reg_area_end_pointer";
9041
9042
  //   void *OverflowArea;
9043
0
  FieldTypes[2] = Context->getPointerType(Context->VoidTy);
9044
0
  FieldNames[2] = "__overflow_area_pointer";
9045
9046
  // Create fields
9047
0
  for (unsigned i = 0; i < NumFields; ++i) {
9048
0
    FieldDecl *Field = FieldDecl::Create(
9049
0
        const_cast<ASTContext &>(*Context), VaListTagDecl, SourceLocation(),
9050
0
        SourceLocation(), &Context->Idents.get(FieldNames[i]), FieldTypes[i],
9051
0
        /*TInfo=*/nullptr,
9052
0
        /*BitWidth=*/nullptr,
9053
0
        /*Mutable=*/false, ICIS_NoInit);
9054
0
    Field->setAccess(AS_public);
9055
0
    VaListTagDecl->addDecl(Field);
9056
0
  }
9057
0
  VaListTagDecl->completeDefinition();
9058
0
  Context->VaListTagDecl = VaListTagDecl;
9059
0
  QualType VaListTagType = Context->getRecordType(VaListTagDecl);
9060
9061
  // } __va_list_tag;
9062
0
  TypedefDecl *VaListTagTypedefDecl =
9063
0
      Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
9064
9065
0
  QualType VaListTagTypedefType = Context->getTypedefType(VaListTagTypedefDecl);
9066
9067
  // typedef __va_list_tag __builtin_va_list[1];
9068
0
  llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
9069
0
  QualType VaListTagArrayType = Context->getConstantArrayType(
9070
0
      VaListTagTypedefType, Size, nullptr, ArraySizeModifier::Normal, 0);
9071
9072
0
  return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
9073
0
}
9074
9075
static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
9076
46
                                     TargetInfo::BuiltinVaListKind Kind) {
9077
46
  switch (Kind) {
9078
0
  case TargetInfo::CharPtrBuiltinVaList:
9079
0
    return CreateCharPtrBuiltinVaListDecl(Context);
9080
0
  case TargetInfo::VoidPtrBuiltinVaList:
9081
0
    return CreateVoidPtrBuiltinVaListDecl(Context);
9082
0
  case TargetInfo::AArch64ABIBuiltinVaList:
9083
0
    return CreateAArch64ABIBuiltinVaListDecl(Context);
9084
0
  case TargetInfo::PowerABIBuiltinVaList:
9085
0
    return CreatePowerABIBuiltinVaListDecl(Context);
9086
46
  case TargetInfo::X86_64ABIBuiltinVaList:
9087
46
    return CreateX86_64ABIBuiltinVaListDecl(Context);
9088
0
  case TargetInfo::PNaClABIBuiltinVaList:
9089
0
    return CreatePNaClABIBuiltinVaListDecl(Context);
9090
0
  case TargetInfo::AAPCSABIBuiltinVaList:
9091
0
    return CreateAAPCSABIBuiltinVaListDecl(Context);
9092
0
  case TargetInfo::SystemZBuiltinVaList:
9093
0
    return CreateSystemZBuiltinVaListDecl(Context);
9094
0
  case TargetInfo::HexagonBuiltinVaList:
9095
0
    return CreateHexagonBuiltinVaListDecl(Context);
9096
46
  }
9097
9098
0
  llvm_unreachable("Unhandled __builtin_va_list type kind");
9099
0
}
9100
9101
46
TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
9102
46
  if (!BuiltinVaListDecl) {
9103
46
    BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
9104
46
    assert(BuiltinVaListDecl->isImplicit());
9105
46
  }
9106
9107
0
  return BuiltinVaListDecl;
9108
46
}
9109
9110
0
Decl *ASTContext::getVaListTagDecl() const {
9111
  // Force the creation of VaListTagDecl by building the __builtin_va_list
9112
  // declaration.
9113
0
  if (!VaListTagDecl)
9114
0
    (void)getBuiltinVaListDecl();
9115
9116
0
  return VaListTagDecl;
9117
0
}
9118
9119
46
TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const {
9120
46
  if (!BuiltinMSVaListDecl)
9121
46
    BuiltinMSVaListDecl = CreateMSVaListDecl(this);
9122
9123
46
  return BuiltinMSVaListDecl;
9124
46
}
9125
9126
0
bool ASTContext::canBuiltinBeRedeclared(const FunctionDecl *FD) const {
9127
  // Allow redecl custom type checking builtin for HLSL.
9128
0
  if (LangOpts.HLSL && FD->getBuiltinID() != Builtin::NotBuiltin &&
9129
0
      BuiltinInfo.hasCustomTypechecking(FD->getBuiltinID()))
9130
0
    return true;
9131
0
  return BuiltinInfo.canBeRedeclared(FD->getBuiltinID());
9132
0
}
9133
9134
0
void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
9135
0
  assert(ObjCConstantStringType.isNull() &&
9136
0
         "'NSConstantString' type already set!");
9137
9138
0
  ObjCConstantStringType = getObjCInterfaceType(Decl);
9139
0
}
9140
9141
/// Retrieve the template name that corresponds to a non-empty
9142
/// lookup.
9143
TemplateName
9144
ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
9145
0
                                      UnresolvedSetIterator End) const {
9146
0
  unsigned size = End - Begin;
9147
0
  assert(size > 1 && "set is not overloaded!");
9148
9149
0
  void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
9150
0
                          size * sizeof(FunctionTemplateDecl*));
9151
0
  auto *OT = new (memory) OverloadedTemplateStorage(size);
9152
9153
0
  NamedDecl **Storage = OT->getStorage();
9154
0
  for (UnresolvedSetIterator I = Begin; I != End; ++I) {
9155
0
    NamedDecl *D = *I;
9156
0
    assert(isa<FunctionTemplateDecl>(D) ||
9157
0
           isa<UnresolvedUsingValueDecl>(D) ||
9158
0
           (isa<UsingShadowDecl>(D) &&
9159
0
            isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
9160
0
    *Storage++ = D;
9161
0
  }
9162
9163
0
  return TemplateName(OT);
9164
0
}
9165
9166
/// Retrieve a template name representing an unqualified-id that has been
9167
/// assumed to name a template for ADL purposes.
9168
3.06k
TemplateName ASTContext::getAssumedTemplateName(DeclarationName Name) const {
9169
3.06k
  auto *OT = new (*this) AssumedTemplateStorage(Name);
9170
3.06k
  return TemplateName(OT);
9171
3.06k
}
9172
9173
/// Retrieve the template name that represents a qualified
9174
/// template name such as \c std::vector.
9175
TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
9176
                                                  bool TemplateKeyword,
9177
0
                                                  TemplateName Template) const {
9178
0
  assert(NNS && "Missing nested-name-specifier in qualified template name");
9179
9180
  // FIXME: Canonicalization?
9181
0
  llvm::FoldingSetNodeID ID;
9182
0
  QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
9183
9184
0
  void *InsertPos = nullptr;
9185
0
  QualifiedTemplateName *QTN =
9186
0
    QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
9187
0
  if (!QTN) {
9188
0
    QTN = new (*this, alignof(QualifiedTemplateName))
9189
0
        QualifiedTemplateName(NNS, TemplateKeyword, Template);
9190
0
    QualifiedTemplateNames.InsertNode(QTN, InsertPos);
9191
0
  }
9192
9193
0
  return TemplateName(QTN);
9194
0
}
9195
9196
/// Retrieve the template name that represents a dependent
9197
/// template name such as \c MetaFun::template apply.
9198
TemplateName
9199
ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
9200
0
                                     const IdentifierInfo *Name) const {
9201
0
  assert((!NNS || NNS->isDependent()) &&
9202
0
         "Nested name specifier must be dependent");
9203
9204
0
  llvm::FoldingSetNodeID ID;
9205
0
  DependentTemplateName::Profile(ID, NNS, Name);
9206
9207
0
  void *InsertPos = nullptr;
9208
0
  DependentTemplateName *QTN =
9209
0
    DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
9210
9211
0
  if (QTN)
9212
0
    return TemplateName(QTN);
9213
9214
0
  NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
9215
0
  if (CanonNNS == NNS) {
9216
0
    QTN = new (*this, alignof(DependentTemplateName))
9217
0
        DependentTemplateName(NNS, Name);
9218
0
  } else {
9219
0
    TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
9220
0
    QTN = new (*this, alignof(DependentTemplateName))
9221
0
        DependentTemplateName(NNS, Name, Canon);
9222
0
    DependentTemplateName *CheckQTN =
9223
0
      DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
9224
0
    assert(!CheckQTN && "Dependent type name canonicalization broken");
9225
0
    (void)CheckQTN;
9226
0
  }
9227
9228
0
  DependentTemplateNames.InsertNode(QTN, InsertPos);
9229
0
  return TemplateName(QTN);
9230
0
}
9231
9232
/// Retrieve the template name that represents a dependent
9233
/// template name such as \c MetaFun::template operator+.
9234
TemplateName
9235
ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
9236
0
                                     OverloadedOperatorKind Operator) const {
9237
0
  assert((!NNS || NNS->isDependent()) &&
9238
0
         "Nested name specifier must be dependent");
9239
9240
0
  llvm::FoldingSetNodeID ID;
9241
0
  DependentTemplateName::Profile(ID, NNS, Operator);
9242
9243
0
  void *InsertPos = nullptr;
9244
0
  DependentTemplateName *QTN
9245
0
    = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
9246
9247
0
  if (QTN)
9248
0
    return TemplateName(QTN);
9249
9250
0
  NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
9251
0
  if (CanonNNS == NNS) {
9252
0
    QTN = new (*this, alignof(DependentTemplateName))
9253
0
        DependentTemplateName(NNS, Operator);
9254
0
  } else {
9255
0
    TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
9256
0
    QTN = new (*this, alignof(DependentTemplateName))
9257
0
        DependentTemplateName(NNS, Operator, Canon);
9258
9259
0
    DependentTemplateName *CheckQTN
9260
0
      = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
9261
0
    assert(!CheckQTN && "Dependent template name canonicalization broken");
9262
0
    (void)CheckQTN;
9263
0
  }
9264
9265
0
  DependentTemplateNames.InsertNode(QTN, InsertPos);
9266
0
  return TemplateName(QTN);
9267
0
}
9268
9269
TemplateName ASTContext::getSubstTemplateTemplateParm(
9270
    TemplateName Replacement, Decl *AssociatedDecl, unsigned Index,
9271
0
    std::optional<unsigned> PackIndex) const {
9272
0
  llvm::FoldingSetNodeID ID;
9273
0
  SubstTemplateTemplateParmStorage::Profile(ID, Replacement, AssociatedDecl,
9274
0
                                            Index, PackIndex);
9275
9276
0
  void *insertPos = nullptr;
9277
0
  SubstTemplateTemplateParmStorage *subst
9278
0
    = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
9279
9280
0
  if (!subst) {
9281
0
    subst = new (*this) SubstTemplateTemplateParmStorage(
9282
0
        Replacement, AssociatedDecl, Index, PackIndex);
9283
0
    SubstTemplateTemplateParms.InsertNode(subst, insertPos);
9284
0
  }
9285
9286
0
  return TemplateName(subst);
9287
0
}
9288
9289
TemplateName
9290
ASTContext::getSubstTemplateTemplateParmPack(const TemplateArgument &ArgPack,
9291
                                             Decl *AssociatedDecl,
9292
0
                                             unsigned Index, bool Final) const {
9293
0
  auto &Self = const_cast<ASTContext &>(*this);
9294
0
  llvm::FoldingSetNodeID ID;
9295
0
  SubstTemplateTemplateParmPackStorage::Profile(ID, Self, ArgPack,
9296
0
                                                AssociatedDecl, Index, Final);
9297
9298
0
  void *InsertPos = nullptr;
9299
0
  SubstTemplateTemplateParmPackStorage *Subst
9300
0
    = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
9301
9302
0
  if (!Subst) {
9303
0
    Subst = new (*this) SubstTemplateTemplateParmPackStorage(
9304
0
        ArgPack.pack_elements(), AssociatedDecl, Index, Final);
9305
0
    SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
9306
0
  }
9307
9308
0
  return TemplateName(Subst);
9309
0
}
9310
9311
/// getFromTargetType - Given one of the integer types provided by
9312
/// TargetInfo, produce the corresponding type. The unsigned @p Type
9313
/// is actually a value of type @c TargetInfo::IntType.
9314
214
CanQualType ASTContext::getFromTargetType(unsigned Type) const {
9315
214
  switch (Type) {
9316
0
  case TargetInfo::NoInt: return {};
9317
0
  case TargetInfo::SignedChar: return SignedCharTy;
9318
0
  case TargetInfo::UnsignedChar: return UnsignedCharTy;
9319
0
  case TargetInfo::SignedShort: return ShortTy;
9320
23
  case TargetInfo::UnsignedShort: return UnsignedShortTy;
9321
23
  case TargetInfo::SignedInt: return IntTy;
9322
69
  case TargetInfo::UnsignedInt: return UnsignedIntTy;
9323
2
  case TargetInfo::SignedLong: return LongTy;
9324
97
  case TargetInfo::UnsignedLong: return UnsignedLongTy;
9325
0
  case TargetInfo::SignedLongLong: return LongLongTy;
9326
0
  case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
9327
214
  }
9328
9329
0
  llvm_unreachable("Unhandled TargetInfo::IntType value");
9330
0
}
9331
9332
//===----------------------------------------------------------------------===//
9333
//                        Type Predicates.
9334
//===----------------------------------------------------------------------===//
9335
9336
/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
9337
/// garbage collection attribute.
9338
///
9339
0
Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
9340
0
  if (getLangOpts().getGC() == LangOptions::NonGC)
9341
0
    return Qualifiers::GCNone;
9342
9343
0
  assert(getLangOpts().ObjC);
9344
0
  Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
9345
9346
  // Default behaviour under objective-C's gc is for ObjC pointers
9347
  // (or pointers to them) be treated as though they were declared
9348
  // as __strong.
9349
0
  if (GCAttrs == Qualifiers::GCNone) {
9350
0
    if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
9351
0
      return Qualifiers::Strong;
9352
0
    else if (Ty->isPointerType())
9353
0
      return getObjCGCAttrKind(Ty->castAs<PointerType>()->getPointeeType());
9354
0
  } else {
9355
    // It's not valid to set GC attributes on anything that isn't a
9356
    // pointer.
9357
0
#ifndef NDEBUG
9358
0
    QualType CT = Ty->getCanonicalTypeInternal();
9359
0
    while (const auto *AT = dyn_cast<ArrayType>(CT))
9360
0
      CT = AT->getElementType();
9361
0
    assert(CT->isAnyPointerType() || CT->isBlockPointerType());
9362
0
#endif
9363
0
  }
9364
0
  return GCAttrs;
9365
0
}
9366
9367
//===----------------------------------------------------------------------===//
9368
//                        Type Compatibility Testing
9369
//===----------------------------------------------------------------------===//
9370
9371
/// areCompatVectorTypes - Return true if the two specified vector types are
9372
/// compatible.
9373
static bool areCompatVectorTypes(const VectorType *LHS,
9374
0
                                 const VectorType *RHS) {
9375
0
  assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
9376
0
  return LHS->getElementType() == RHS->getElementType() &&
9377
0
         LHS->getNumElements() == RHS->getNumElements();
9378
0
}
9379
9380
/// areCompatMatrixTypes - Return true if the two specified matrix types are
9381
/// compatible.
9382
static bool areCompatMatrixTypes(const ConstantMatrixType *LHS,
9383
0
                                 const ConstantMatrixType *RHS) {
9384
0
  assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
9385
0
  return LHS->getElementType() == RHS->getElementType() &&
9386
0
         LHS->getNumRows() == RHS->getNumRows() &&
9387
0
         LHS->getNumColumns() == RHS->getNumColumns();
9388
0
}
9389
9390
bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
9391
0
                                          QualType SecondVec) {
9392
0
  assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
9393
0
  assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
9394
9395
0
  if (hasSameUnqualifiedType(FirstVec, SecondVec))
9396
0
    return true;
9397
9398
  // Treat Neon vector types and most AltiVec vector types as if they are the
9399
  // equivalent GCC vector types.
9400
0
  const auto *First = FirstVec->castAs<VectorType>();
9401
0
  const auto *Second = SecondVec->castAs<VectorType>();
9402
0
  if (First->getNumElements() == Second->getNumElements() &&
9403
0
      hasSameType(First->getElementType(), Second->getElementType()) &&
9404
0
      First->getVectorKind() != VectorKind::AltiVecPixel &&
9405
0
      First->getVectorKind() != VectorKind::AltiVecBool &&
9406
0
      Second->getVectorKind() != VectorKind::AltiVecPixel &&
9407
0
      Second->getVectorKind() != VectorKind::AltiVecBool &&
9408
0
      First->getVectorKind() != VectorKind::SveFixedLengthData &&
9409
0
      First->getVectorKind() != VectorKind::SveFixedLengthPredicate &&
9410
0
      Second->getVectorKind() != VectorKind::SveFixedLengthData &&
9411
0
      Second->getVectorKind() != VectorKind::SveFixedLengthPredicate &&
9412
0
      First->getVectorKind() != VectorKind::RVVFixedLengthData &&
9413
0
      Second->getVectorKind() != VectorKind::RVVFixedLengthData)
9414
0
    return true;
9415
9416
0
  return false;
9417
0
}
9418
9419
/// getSVETypeSize - Return SVE vector or predicate register size.
9420
0
static uint64_t getSVETypeSize(ASTContext &Context, const BuiltinType *Ty) {
9421
0
  assert(Ty->isSveVLSBuiltinType() && "Invalid SVE Type");
9422
0
  if (Ty->getKind() == BuiltinType::SveBool ||
9423
0
      Ty->getKind() == BuiltinType::SveCount)
9424
0
    return (Context.getLangOpts().VScaleMin * 128) / Context.getCharWidth();
9425
0
  return Context.getLangOpts().VScaleMin * 128;
9426
0
}
9427
9428
bool ASTContext::areCompatibleSveTypes(QualType FirstType,
9429
0
                                       QualType SecondType) {
9430
0
  assert(
9431
0
      ((FirstType->isSVESizelessBuiltinType() && SecondType->isVectorType()) ||
9432
0
       (FirstType->isVectorType() && SecondType->isSVESizelessBuiltinType())) &&
9433
0
      "Expected SVE builtin type and vector type!");
9434
9435
0
  auto IsValidCast = [this](QualType FirstType, QualType SecondType) {
9436
0
    if (const auto *BT = FirstType->getAs<BuiltinType>()) {
9437
0
      if (const auto *VT = SecondType->getAs<VectorType>()) {
9438
        // Predicates have the same representation as uint8 so we also have to
9439
        // check the kind to make these types incompatible.
9440
0
        if (VT->getVectorKind() == VectorKind::SveFixedLengthPredicate)
9441
0
          return BT->getKind() == BuiltinType::SveBool;
9442
0
        else if (VT->getVectorKind() == VectorKind::SveFixedLengthData)
9443
0
          return VT->getElementType().getCanonicalType() ==
9444
0
                 FirstType->getSveEltType(*this);
9445
0
        else if (VT->getVectorKind() == VectorKind::Generic)
9446
0
          return getTypeSize(SecondType) == getSVETypeSize(*this, BT) &&
9447
0
                 hasSameType(VT->getElementType(),
9448
0
                             getBuiltinVectorTypeInfo(BT).ElementType);
9449
0
      }
9450
0
    }
9451
0
    return false;
9452
0
  };
9453
9454
0
  return IsValidCast(FirstType, SecondType) ||
9455
0
         IsValidCast(SecondType, FirstType);
9456
0
}
9457
9458
bool ASTContext::areLaxCompatibleSveTypes(QualType FirstType,
9459
0
                                          QualType SecondType) {
9460
0
  assert(
9461
0
      ((FirstType->isSVESizelessBuiltinType() && SecondType->isVectorType()) ||
9462
0
       (FirstType->isVectorType() && SecondType->isSVESizelessBuiltinType())) &&
9463
0
      "Expected SVE builtin type and vector type!");
9464
9465
0
  auto IsLaxCompatible = [this](QualType FirstType, QualType SecondType) {
9466
0
    const auto *BT = FirstType->getAs<BuiltinType>();
9467
0
    if (!BT)
9468
0
      return false;
9469
9470
0
    const auto *VecTy = SecondType->getAs<VectorType>();
9471
0
    if (VecTy && (VecTy->getVectorKind() == VectorKind::SveFixedLengthData ||
9472
0
                  VecTy->getVectorKind() == VectorKind::Generic)) {
9473
0
      const LangOptions::LaxVectorConversionKind LVCKind =
9474
0
          getLangOpts().getLaxVectorConversions();
9475
9476
      // Can not convert between sve predicates and sve vectors because of
9477
      // different size.
9478
0
      if (BT->getKind() == BuiltinType::SveBool &&
9479
0
          VecTy->getVectorKind() == VectorKind::SveFixedLengthData)
9480
0
        return false;
9481
9482
      // If __ARM_FEATURE_SVE_BITS != N do not allow GNU vector lax conversion.
9483
      // "Whenever __ARM_FEATURE_SVE_BITS==N, GNUT implicitly
9484
      // converts to VLAT and VLAT implicitly converts to GNUT."
9485
      // ACLE Spec Version 00bet6, 3.7.3.2. Behavior common to vectors and
9486
      // predicates.
9487
0
      if (VecTy->getVectorKind() == VectorKind::Generic &&
9488
0
          getTypeSize(SecondType) != getSVETypeSize(*this, BT))
9489
0
        return false;
9490
9491
      // If -flax-vector-conversions=all is specified, the types are
9492
      // certainly compatible.
9493
0
      if (LVCKind == LangOptions::LaxVectorConversionKind::All)
9494
0
        return true;
9495
9496
      // If -flax-vector-conversions=integer is specified, the types are
9497
      // compatible if the elements are integer types.
9498
0
      if (LVCKind == LangOptions::LaxVectorConversionKind::Integer)
9499
0
        return VecTy->getElementType().getCanonicalType()->isIntegerType() &&
9500
0
               FirstType->getSveEltType(*this)->isIntegerType();
9501
0
    }
9502
9503
0
    return false;
9504
0
  };
9505
9506
0
  return IsLaxCompatible(FirstType, SecondType) ||
9507
0
         IsLaxCompatible(SecondType, FirstType);
9508
0
}
9509
9510
/// getRVVTypeSize - Return RVV vector register size.
9511
0
static uint64_t getRVVTypeSize(ASTContext &Context, const BuiltinType *Ty) {
9512
0
  assert(Ty->isRVVVLSBuiltinType() && "Invalid RVV Type");
9513
0
  auto VScale = Context.getTargetInfo().getVScaleRange(Context.getLangOpts());
9514
0
  if (!VScale)
9515
0
    return 0;
9516
9517
0
  ASTContext::BuiltinVectorTypeInfo Info = Context.getBuiltinVectorTypeInfo(Ty);
9518
9519
0
  uint64_t EltSize = Context.getTypeSize(Info.ElementType);
9520
0
  uint64_t MinElts = Info.EC.getKnownMinValue();
9521
0
  return VScale->first * MinElts * EltSize;
9522
0
}
9523
9524
bool ASTContext::areCompatibleRVVTypes(QualType FirstType,
9525
0
                                       QualType SecondType) {
9526
0
  assert(
9527
0
      ((FirstType->isRVVSizelessBuiltinType() && SecondType->isVectorType()) ||
9528
0
       (FirstType->isVectorType() && SecondType->isRVVSizelessBuiltinType())) &&
9529
0
      "Expected RVV builtin type and vector type!");
9530
9531
0
  auto IsValidCast = [this](QualType FirstType, QualType SecondType) {
9532
0
    if (const auto *BT = FirstType->getAs<BuiltinType>()) {
9533
0
      if (const auto *VT = SecondType->getAs<VectorType>()) {
9534
0
        if (VT->getVectorKind() == VectorKind::RVVFixedLengthData ||
9535
0
            VT->getVectorKind() == VectorKind::Generic)
9536
0
          return FirstType->isRVVVLSBuiltinType() &&
9537
0
                 getTypeSize(SecondType) == getRVVTypeSize(*this, BT) &&
9538
0
                 hasSameType(VT->getElementType(),
9539
0
                             getBuiltinVectorTypeInfo(BT).ElementType);
9540
0
      }
9541
0
    }
9542
0
    return false;
9543
0
  };
9544
9545
0
  return IsValidCast(FirstType, SecondType) ||
9546
0
         IsValidCast(SecondType, FirstType);
9547
0
}
9548
9549
bool ASTContext::areLaxCompatibleRVVTypes(QualType FirstType,
9550
0
                                          QualType SecondType) {
9551
0
  assert(
9552
0
      ((FirstType->isRVVSizelessBuiltinType() && SecondType->isVectorType()) ||
9553
0
       (FirstType->isVectorType() && SecondType->isRVVSizelessBuiltinType())) &&
9554
0
      "Expected RVV builtin type and vector type!");
9555
9556
0
  auto IsLaxCompatible = [this](QualType FirstType, QualType SecondType) {
9557
0
    const auto *BT = FirstType->getAs<BuiltinType>();
9558
0
    if (!BT)
9559
0
      return false;
9560
9561
0
    if (!BT->isRVVVLSBuiltinType())
9562
0
      return false;
9563
9564
0
    const auto *VecTy = SecondType->getAs<VectorType>();
9565
0
    if (VecTy && VecTy->getVectorKind() == VectorKind::Generic) {
9566
0
      const LangOptions::LaxVectorConversionKind LVCKind =
9567
0
          getLangOpts().getLaxVectorConversions();
9568
9569
      // If __riscv_v_fixed_vlen != N do not allow vector lax conversion.
9570
0
      if (getTypeSize(SecondType) != getRVVTypeSize(*this, BT))
9571
0
        return false;
9572
9573
      // If -flax-vector-conversions=all is specified, the types are
9574
      // certainly compatible.
9575
0
      if (LVCKind == LangOptions::LaxVectorConversionKind::All)
9576
0
        return true;
9577
9578
      // If -flax-vector-conversions=integer is specified, the types are
9579
      // compatible if the elements are integer types.
9580
0
      if (LVCKind == LangOptions::LaxVectorConversionKind::Integer)
9581
0
        return VecTy->getElementType().getCanonicalType()->isIntegerType() &&
9582
0
               FirstType->getRVVEltType(*this)->isIntegerType();
9583
0
    }
9584
9585
0
    return false;
9586
0
  };
9587
9588
0
  return IsLaxCompatible(FirstType, SecondType) ||
9589
0
         IsLaxCompatible(SecondType, FirstType);
9590
0
}
9591
9592
0
bool ASTContext::hasDirectOwnershipQualifier(QualType Ty) const {
9593
0
  while (true) {
9594
    // __strong id
9595
0
    if (const AttributedType *Attr = dyn_cast<AttributedType>(Ty)) {
9596
0
      if (Attr->getAttrKind() == attr::ObjCOwnership)
9597
0
        return true;
9598
9599
0
      Ty = Attr->getModifiedType();
9600
9601
    // X *__strong (...)
9602
0
    } else if (const ParenType *Paren = dyn_cast<ParenType>(Ty)) {
9603
0
      Ty = Paren->getInnerType();
9604
9605
    // We do not want to look through typedefs, typeof(expr),
9606
    // typeof(type), or any other way that the type is somehow
9607
    // abstracted.
9608
0
    } else {
9609
0
      return false;
9610
0
    }
9611
0
  }
9612
0
}
9613
9614
//===----------------------------------------------------------------------===//
9615
// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
9616
//===----------------------------------------------------------------------===//
9617
9618
/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
9619
/// inheritance hierarchy of 'rProto'.
9620
bool
9621
ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
9622
0
                                           ObjCProtocolDecl *rProto) const {
9623
0
  if (declaresSameEntity(lProto, rProto))
9624
0
    return true;
9625
0
  for (auto *PI : rProto->protocols())
9626
0
    if (ProtocolCompatibleWithProtocol(lProto, PI))
9627
0
      return true;
9628
0
  return false;
9629
0
}
9630
9631
/// ObjCQualifiedClassTypesAreCompatible - compare  Class<pr,...> and
9632
/// Class<pr1, ...>.
9633
bool ASTContext::ObjCQualifiedClassTypesAreCompatible(
9634
0
    const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs) {
9635
0
  for (auto *lhsProto : lhs->quals()) {
9636
0
    bool match = false;
9637
0
    for (auto *rhsProto : rhs->quals()) {
9638
0
      if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
9639
0
        match = true;
9640
0
        break;
9641
0
      }
9642
0
    }
9643
0
    if (!match)
9644
0
      return false;
9645
0
  }
9646
0
  return true;
9647
0
}
9648
9649
/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
9650
/// ObjCQualifiedIDType.
9651
bool ASTContext::ObjCQualifiedIdTypesAreCompatible(
9652
    const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs,
9653
0
    bool compare) {
9654
  // Allow id<P..> and an 'id' in all cases.
9655
0
  if (lhs->isObjCIdType() || rhs->isObjCIdType())
9656
0
    return true;
9657
9658
  // Don't allow id<P..> to convert to Class or Class<P..> in either direction.
9659
0
  if (lhs->isObjCClassType() || lhs->isObjCQualifiedClassType() ||
9660
0
      rhs->isObjCClassType() || rhs->isObjCQualifiedClassType())
9661
0
    return false;
9662
9663
0
  if (lhs->isObjCQualifiedIdType()) {
9664
0
    if (rhs->qual_empty()) {
9665
      // If the RHS is a unqualified interface pointer "NSString*",
9666
      // make sure we check the class hierarchy.
9667
0
      if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
9668
0
        for (auto *I : lhs->quals()) {
9669
          // when comparing an id<P> on lhs with a static type on rhs,
9670
          // see if static class implements all of id's protocols, directly or
9671
          // through its super class and categories.
9672
0
          if (!rhsID->ClassImplementsProtocol(I, true))
9673
0
            return false;
9674
0
        }
9675
0
      }
9676
      // If there are no qualifiers and no interface, we have an 'id'.
9677
0
      return true;
9678
0
    }
9679
    // Both the right and left sides have qualifiers.
9680
0
    for (auto *lhsProto : lhs->quals()) {
9681
0
      bool match = false;
9682
9683
      // when comparing an id<P> on lhs with a static type on rhs,
9684
      // see if static class implements all of id's protocols, directly or
9685
      // through its super class and categories.
9686
0
      for (auto *rhsProto : rhs->quals()) {
9687
0
        if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
9688
0
            (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
9689
0
          match = true;
9690
0
          break;
9691
0
        }
9692
0
      }
9693
      // If the RHS is a qualified interface pointer "NSString<P>*",
9694
      // make sure we check the class hierarchy.
9695
0
      if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
9696
0
        for (auto *I : lhs->quals()) {
9697
          // when comparing an id<P> on lhs with a static type on rhs,
9698
          // see if static class implements all of id's protocols, directly or
9699
          // through its super class and categories.
9700
0
          if (rhsID->ClassImplementsProtocol(I, true)) {
9701
0
            match = true;
9702
0
            break;
9703
0
          }
9704
0
        }
9705
0
      }
9706
0
      if (!match)
9707
0
        return false;
9708
0
    }
9709
9710
0
    return true;
9711
0
  }
9712
9713
0
  assert(rhs->isObjCQualifiedIdType() && "One of the LHS/RHS should be id<x>");
9714
9715
0
  if (lhs->getInterfaceType()) {
9716
    // If both the right and left sides have qualifiers.
9717
0
    for (auto *lhsProto : lhs->quals()) {
9718
0
      bool match = false;
9719
9720
      // when comparing an id<P> on rhs with a static type on lhs,
9721
      // see if static class implements all of id's protocols, directly or
9722
      // through its super class and categories.
9723
      // First, lhs protocols in the qualifier list must be found, direct
9724
      // or indirect in rhs's qualifier list or it is a mismatch.
9725
0
      for (auto *rhsProto : rhs->quals()) {
9726
0
        if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
9727
0
            (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
9728
0
          match = true;
9729
0
          break;
9730
0
        }
9731
0
      }
9732
0
      if (!match)
9733
0
        return false;
9734
0
    }
9735
9736
    // Static class's protocols, or its super class or category protocols
9737
    // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
9738
0
    if (ObjCInterfaceDecl *lhsID = lhs->getInterfaceDecl()) {
9739
0
      llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
9740
0
      CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
9741
      // This is rather dubious but matches gcc's behavior. If lhs has
9742
      // no type qualifier and its class has no static protocol(s)
9743
      // assume that it is mismatch.
9744
0
      if (LHSInheritedProtocols.empty() && lhs->qual_empty())
9745
0
        return false;
9746
0
      for (auto *lhsProto : LHSInheritedProtocols) {
9747
0
        bool match = false;
9748
0
        for (auto *rhsProto : rhs->quals()) {
9749
0
          if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
9750
0
              (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
9751
0
            match = true;
9752
0
            break;
9753
0
          }
9754
0
        }
9755
0
        if (!match)
9756
0
          return false;
9757
0
      }
9758
0
    }
9759
0
    return true;
9760
0
  }
9761
0
  return false;
9762
0
}
9763
9764
/// canAssignObjCInterfaces - Return true if the two interface types are
9765
/// compatible for assignment from RHS to LHS.  This handles validation of any
9766
/// protocol qualifiers on the LHS or RHS.
9767
bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
9768
0
                                         const ObjCObjectPointerType *RHSOPT) {
9769
0
  const ObjCObjectType* LHS = LHSOPT->getObjectType();
9770
0
  const ObjCObjectType* RHS = RHSOPT->getObjectType();
9771
9772
  // If either type represents the built-in 'id' type, return true.
9773
0
  if (LHS->isObjCUnqualifiedId() || RHS->isObjCUnqualifiedId())
9774
0
    return true;
9775
9776
  // Function object that propagates a successful result or handles
9777
  // __kindof types.
9778
0
  auto finish = [&](bool succeeded) -> bool {
9779
0
    if (succeeded)
9780
0
      return true;
9781
9782
0
    if (!RHS->isKindOfType())
9783
0
      return false;
9784
9785
    // Strip off __kindof and protocol qualifiers, then check whether
9786
    // we can assign the other way.
9787
0
    return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this),
9788
0
                                   LHSOPT->stripObjCKindOfTypeAndQuals(*this));
9789
0
  };
9790
9791
  // Casts from or to id<P> are allowed when the other side has compatible
9792
  // protocols.
9793
0
  if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
9794
0
    return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false));
9795
0
  }
9796
9797
  // Verify protocol compatibility for casts from Class<P1> to Class<P2>.
9798
0
  if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
9799
0
    return finish(ObjCQualifiedClassTypesAreCompatible(LHSOPT, RHSOPT));
9800
0
  }
9801
9802
  // Casts from Class to Class<Foo>, or vice-versa, are allowed.
9803
0
  if (LHS->isObjCClass() && RHS->isObjCClass()) {
9804
0
    return true;
9805
0
  }
9806
9807
  // If we have 2 user-defined types, fall into that path.
9808
0
  if (LHS->getInterface() && RHS->getInterface()) {
9809
0
    return finish(canAssignObjCInterfaces(LHS, RHS));
9810
0
  }
9811
9812
0
  return false;
9813
0
}
9814
9815
/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
9816
/// for providing type-safety for objective-c pointers used to pass/return
9817
/// arguments in block literals. When passed as arguments, passing 'A*' where
9818
/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
9819
/// not OK. For the return type, the opposite is not OK.
9820
bool ASTContext::canAssignObjCInterfacesInBlockPointer(
9821
                                         const ObjCObjectPointerType *LHSOPT,
9822
                                         const ObjCObjectPointerType *RHSOPT,
9823
0
                                         bool BlockReturnType) {
9824
9825
  // Function object that propagates a successful result or handles
9826
  // __kindof types.
9827
0
  auto finish = [&](bool succeeded) -> bool {
9828
0
    if (succeeded)
9829
0
      return true;
9830
9831
0
    const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
9832
0
    if (!Expected->isKindOfType())
9833
0
      return false;
9834
9835
    // Strip off __kindof and protocol qualifiers, then check whether
9836
    // we can assign the other way.
9837
0
    return canAssignObjCInterfacesInBlockPointer(
9838
0
             RHSOPT->stripObjCKindOfTypeAndQuals(*this),
9839
0
             LHSOPT->stripObjCKindOfTypeAndQuals(*this),
9840
0
             BlockReturnType);
9841
0
  };
9842
9843
0
  if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
9844
0
    return true;
9845
9846
0
  if (LHSOPT->isObjCBuiltinType()) {
9847
0
    return finish(RHSOPT->isObjCBuiltinType() ||
9848
0
                  RHSOPT->isObjCQualifiedIdType());
9849
0
  }
9850
9851
0
  if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) {
9852
0
    if (getLangOpts().CompatibilityQualifiedIdBlockParamTypeChecking)
9853
      // Use for block parameters previous type checking for compatibility.
9854
0
      return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false) ||
9855
                    // Or corrected type checking as in non-compat mode.
9856
0
                    (!BlockReturnType &&
9857
0
                     ObjCQualifiedIdTypesAreCompatible(RHSOPT, LHSOPT, false)));
9858
0
    else
9859
0
      return finish(ObjCQualifiedIdTypesAreCompatible(
9860
0
          (BlockReturnType ? LHSOPT : RHSOPT),
9861
0
          (BlockReturnType ? RHSOPT : LHSOPT), false));
9862
0
  }
9863
9864
0
  const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
9865
0
  const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
9866
0
  if (LHS && RHS)  { // We have 2 user-defined types.
9867
0
    if (LHS != RHS) {
9868
0
      if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
9869
0
        return finish(BlockReturnType);
9870
0
      if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
9871
0
        return finish(!BlockReturnType);
9872
0
    }
9873
0
    else
9874
0
      return true;
9875
0
  }
9876
0
  return false;
9877
0
}
9878
9879
/// Comparison routine for Objective-C protocols to be used with
9880
/// llvm::array_pod_sort.
9881
static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
9882
0
                                      ObjCProtocolDecl * const *rhs) {
9883
0
  return (*lhs)->getName().compare((*rhs)->getName());
9884
0
}
9885
9886
/// getIntersectionOfProtocols - This routine finds the intersection of set
9887
/// of protocols inherited from two distinct objective-c pointer objects with
9888
/// the given common base.
9889
/// It is used to build composite qualifier list of the composite type of
9890
/// the conditional expression involving two objective-c pointer objects.
9891
static
9892
void getIntersectionOfProtocols(ASTContext &Context,
9893
                                const ObjCInterfaceDecl *CommonBase,
9894
                                const ObjCObjectPointerType *LHSOPT,
9895
                                const ObjCObjectPointerType *RHSOPT,
9896
0
      SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
9897
9898
0
  const ObjCObjectType* LHS = LHSOPT->getObjectType();
9899
0
  const ObjCObjectType* RHS = RHSOPT->getObjectType();
9900
0
  assert(LHS->getInterface() && "LHS must have an interface base");
9901
0
  assert(RHS->getInterface() && "RHS must have an interface base");
9902
9903
  // Add all of the protocols for the LHS.
9904
0
  llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
9905
9906
  // Start with the protocol qualifiers.
9907
0
  for (auto *proto : LHS->quals()) {
9908
0
    Context.CollectInheritedProtocols(proto, LHSProtocolSet);
9909
0
  }
9910
9911
  // Also add the protocols associated with the LHS interface.
9912
0
  Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
9913
9914
  // Add all of the protocols for the RHS.
9915
0
  llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
9916
9917
  // Start with the protocol qualifiers.
9918
0
  for (auto *proto : RHS->quals()) {
9919
0
    Context.CollectInheritedProtocols(proto, RHSProtocolSet);
9920
0
  }
9921
9922
  // Also add the protocols associated with the RHS interface.
9923
0
  Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
9924
9925
  // Compute the intersection of the collected protocol sets.
9926
0
  for (auto *proto : LHSProtocolSet) {
9927
0
    if (RHSProtocolSet.count(proto))
9928
0
      IntersectionSet.push_back(proto);
9929
0
  }
9930
9931
  // Compute the set of protocols that is implied by either the common type or
9932
  // the protocols within the intersection.
9933
0
  llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
9934
0
  Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
9935
9936
  // Remove any implied protocols from the list of inherited protocols.
9937
0
  if (!ImpliedProtocols.empty()) {
9938
0
    llvm::erase_if(IntersectionSet, [&](ObjCProtocolDecl *proto) -> bool {
9939
0
      return ImpliedProtocols.contains(proto);
9940
0
    });
9941
0
  }
9942
9943
  // Sort the remaining protocols by name.
9944
0
  llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
9945
0
                       compareObjCProtocolsByName);
9946
0
}
9947
9948
/// Determine whether the first type is a subtype of the second.
9949
static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
9950
0
                                     QualType rhs) {
9951
  // Common case: two object pointers.
9952
0
  const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
9953
0
  const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
9954
0
  if (lhsOPT && rhsOPT)
9955
0
    return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
9956
9957
  // Two block pointers.
9958
0
  const auto *lhsBlock = lhs->getAs<BlockPointerType>();
9959
0
  const auto *rhsBlock = rhs->getAs<BlockPointerType>();
9960
0
  if (lhsBlock && rhsBlock)
9961
0
    return ctx.typesAreBlockPointerCompatible(lhs, rhs);
9962
9963
  // If either is an unqualified 'id' and the other is a block, it's
9964
  // acceptable.
9965
0
  if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
9966
0
      (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
9967
0
    return true;
9968
9969
0
  return false;
9970
0
}
9971
9972
// Check that the given Objective-C type argument lists are equivalent.
9973
static bool sameObjCTypeArgs(ASTContext &ctx,
9974
                             const ObjCInterfaceDecl *iface,
9975
                             ArrayRef<QualType> lhsArgs,
9976
                             ArrayRef<QualType> rhsArgs,
9977
0
                             bool stripKindOf) {
9978
0
  if (lhsArgs.size() != rhsArgs.size())
9979
0
    return false;
9980
9981
0
  ObjCTypeParamList *typeParams = iface->getTypeParamList();
9982
0
  if (!typeParams)
9983
0
    return false;
9984
9985
0
  for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
9986
0
    if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
9987
0
      continue;
9988
9989
0
    switch (typeParams->begin()[i]->getVariance()) {
9990
0
    case ObjCTypeParamVariance::Invariant:
9991
0
      if (!stripKindOf ||
9992
0
          !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
9993
0
                           rhsArgs[i].stripObjCKindOfType(ctx))) {
9994
0
        return false;
9995
0
      }
9996
0
      break;
9997
9998
0
    case ObjCTypeParamVariance::Covariant:
9999
0
      if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
10000
0
        return false;
10001
0
      break;
10002
10003
0
    case ObjCTypeParamVariance::Contravariant:
10004
0
      if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
10005
0
        return false;
10006
0
      break;
10007
0
    }
10008
0
  }
10009
10010
0
  return true;
10011
0
}
10012
10013
QualType ASTContext::areCommonBaseCompatible(
10014
           const ObjCObjectPointerType *Lptr,
10015
0
           const ObjCObjectPointerType *Rptr) {
10016
0
  const ObjCObjectType *LHS = Lptr->getObjectType();
10017
0
  const ObjCObjectType *RHS = Rptr->getObjectType();
10018
0
  const ObjCInterfaceDecl* LDecl = LHS->getInterface();
10019
0
  const ObjCInterfaceDecl* RDecl = RHS->getInterface();
10020
10021
0
  if (!LDecl || !RDecl)
10022
0
    return {};
10023
10024
  // When either LHS or RHS is a kindof type, we should return a kindof type.
10025
  // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
10026
  // kindof(A).
10027
0
  bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
10028
10029
  // Follow the left-hand side up the class hierarchy until we either hit a
10030
  // root or find the RHS. Record the ancestors in case we don't find it.
10031
0
  llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
10032
0
    LHSAncestors;
10033
0
  while (true) {
10034
    // Record this ancestor. We'll need this if the common type isn't in the
10035
    // path from the LHS to the root.
10036
0
    LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
10037
10038
0
    if (declaresSameEntity(LHS->getInterface(), RDecl)) {
10039
      // Get the type arguments.
10040
0
      ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
10041
0
      bool anyChanges = false;
10042
0
      if (LHS->isSpecialized() && RHS->isSpecialized()) {
10043
        // Both have type arguments, compare them.
10044
0
        if (!sameObjCTypeArgs(*this, LHS->getInterface(),
10045
0
                              LHS->getTypeArgs(), RHS->getTypeArgs(),
10046
0
                              /*stripKindOf=*/true))
10047
0
          return {};
10048
0
      } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
10049
        // If only one has type arguments, the result will not have type
10050
        // arguments.
10051
0
        LHSTypeArgs = {};
10052
0
        anyChanges = true;
10053
0
      }
10054
10055
      // Compute the intersection of protocols.
10056
0
      SmallVector<ObjCProtocolDecl *, 8> Protocols;
10057
0
      getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
10058
0
                                 Protocols);
10059
0
      if (!Protocols.empty())
10060
0
        anyChanges = true;
10061
10062
      // If anything in the LHS will have changed, build a new result type.
10063
      // If we need to return a kindof type but LHS is not a kindof type, we
10064
      // build a new result type.
10065
0
      if (anyChanges || LHS->isKindOfType() != anyKindOf) {
10066
0
        QualType Result = getObjCInterfaceType(LHS->getInterface());
10067
0
        Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
10068
0
                                   anyKindOf || LHS->isKindOfType());
10069
0
        return getObjCObjectPointerType(Result);
10070
0
      }
10071
10072
0
      return getObjCObjectPointerType(QualType(LHS, 0));
10073
0
    }
10074
10075
    // Find the superclass.
10076
0
    QualType LHSSuperType = LHS->getSuperClassType();
10077
0
    if (LHSSuperType.isNull())
10078
0
      break;
10079
10080
0
    LHS = LHSSuperType->castAs<ObjCObjectType>();
10081
0
  }
10082
10083
  // We didn't find anything by following the LHS to its root; now check
10084
  // the RHS against the cached set of ancestors.
10085
0
  while (true) {
10086
0
    auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
10087
0
    if (KnownLHS != LHSAncestors.end()) {
10088
0
      LHS = KnownLHS->second;
10089
10090
      // Get the type arguments.
10091
0
      ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
10092
0
      bool anyChanges = false;
10093
0
      if (LHS->isSpecialized() && RHS->isSpecialized()) {
10094
        // Both have type arguments, compare them.
10095
0
        if (!sameObjCTypeArgs(*this, LHS->getInterface(),
10096
0
                              LHS->getTypeArgs(), RHS->getTypeArgs(),
10097
0
                              /*stripKindOf=*/true))
10098
0
          return {};
10099
0
      } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
10100
        // If only one has type arguments, the result will not have type
10101
        // arguments.
10102
0
        RHSTypeArgs = {};
10103
0
        anyChanges = true;
10104
0
      }
10105
10106
      // Compute the intersection of protocols.
10107
0
      SmallVector<ObjCProtocolDecl *, 8> Protocols;
10108
0
      getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
10109
0
                                 Protocols);
10110
0
      if (!Protocols.empty())
10111
0
        anyChanges = true;
10112
10113
      // If we need to return a kindof type but RHS is not a kindof type, we
10114
      // build a new result type.
10115
0
      if (anyChanges || RHS->isKindOfType() != anyKindOf) {
10116
0
        QualType Result = getObjCInterfaceType(RHS->getInterface());
10117
0
        Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
10118
0
                                   anyKindOf || RHS->isKindOfType());
10119
0
        return getObjCObjectPointerType(Result);
10120
0
      }
10121
10122
0
      return getObjCObjectPointerType(QualType(RHS, 0));
10123
0
    }
10124
10125
    // Find the superclass of the RHS.
10126
0
    QualType RHSSuperType = RHS->getSuperClassType();
10127
0
    if (RHSSuperType.isNull())
10128
0
      break;
10129
10130
0
    RHS = RHSSuperType->castAs<ObjCObjectType>();
10131
0
  }
10132
10133
0
  return {};
10134
0
}
10135
10136
bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
10137
0
                                         const ObjCObjectType *RHS) {
10138
0
  assert(LHS->getInterface() && "LHS is not an interface type");
10139
0
  assert(RHS->getInterface() && "RHS is not an interface type");
10140
10141
  // Verify that the base decls are compatible: the RHS must be a subclass of
10142
  // the LHS.
10143
0
  ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
10144
0
  bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
10145
0
  if (!IsSuperClass)
10146
0
    return false;
10147
10148
  // If the LHS has protocol qualifiers, determine whether all of them are
10149
  // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
10150
  // LHS).
10151
0
  if (LHS->getNumProtocols() > 0) {
10152
    // OK if conversion of LHS to SuperClass results in narrowing of types
10153
    // ; i.e., SuperClass may implement at least one of the protocols
10154
    // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
10155
    // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
10156
0
    llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
10157
0
    CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
10158
    // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
10159
    // qualifiers.
10160
0
    for (auto *RHSPI : RHS->quals())
10161
0
      CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
10162
    // If there is no protocols associated with RHS, it is not a match.
10163
0
    if (SuperClassInheritedProtocols.empty())
10164
0
      return false;
10165
10166
0
    for (const auto *LHSProto : LHS->quals()) {
10167
0
      bool SuperImplementsProtocol = false;
10168
0
      for (auto *SuperClassProto : SuperClassInheritedProtocols)
10169
0
        if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
10170
0
          SuperImplementsProtocol = true;
10171
0
          break;
10172
0
        }
10173
0
      if (!SuperImplementsProtocol)
10174
0
        return false;
10175
0
    }
10176
0
  }
10177
10178
  // If the LHS is specialized, we may need to check type arguments.
10179
0
  if (LHS->isSpecialized()) {
10180
    // Follow the superclass chain until we've matched the LHS class in the
10181
    // hierarchy. This substitutes type arguments through.
10182
0
    const ObjCObjectType *RHSSuper = RHS;
10183
0
    while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
10184
0
      RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
10185
10186
    // If the RHS is specializd, compare type arguments.
10187
0
    if (RHSSuper->isSpecialized() &&
10188
0
        !sameObjCTypeArgs(*this, LHS->getInterface(),
10189
0
                          LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
10190
0
                          /*stripKindOf=*/true)) {
10191
0
      return false;
10192
0
    }
10193
0
  }
10194
10195
0
  return true;
10196
0
}
10197
10198
0
bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
10199
  // get the "pointed to" types
10200
0
  const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
10201
0
  const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
10202
10203
0
  if (!LHSOPT || !RHSOPT)
10204
0
    return false;
10205
10206
0
  return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
10207
0
         canAssignObjCInterfaces(RHSOPT, LHSOPT);
10208
0
}
10209
10210
0
bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
10211
0
  return canAssignObjCInterfaces(
10212
0
      getObjCObjectPointerType(To)->castAs<ObjCObjectPointerType>(),
10213
0
      getObjCObjectPointerType(From)->castAs<ObjCObjectPointerType>());
10214
0
}
10215
10216
/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
10217
/// both shall have the identically qualified version of a compatible type.
10218
/// C99 6.2.7p1: Two types have compatible types if their types are the
10219
/// same. See 6.7.[2,3,5] for additional rules.
10220
bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
10221
0
                                    bool CompareUnqualified) {
10222
0
  if (getLangOpts().CPlusPlus)
10223
0
    return hasSameType(LHS, RHS);
10224
10225
0
  return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
10226
0
}
10227
10228
0
bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
10229
0
  return typesAreCompatible(LHS, RHS);
10230
0
}
10231
10232
0
bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
10233
0
  return !mergeTypes(LHS, RHS, true).isNull();
10234
0
}
10235
10236
/// mergeTransparentUnionType - if T is a transparent union type and a member
10237
/// of T is compatible with SubType, return the merged type, else return
10238
/// QualType()
10239
QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
10240
                                               bool OfBlockPointer,
10241
0
                                               bool Unqualified) {
10242
0
  if (const RecordType *UT = T->getAsUnionType()) {
10243
0
    RecordDecl *UD = UT->getDecl();
10244
0
    if (UD->hasAttr<TransparentUnionAttr>()) {
10245
0
      for (const auto *I : UD->fields()) {
10246
0
        QualType ET = I->getType().getUnqualifiedType();
10247
0
        QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
10248
0
        if (!MT.isNull())
10249
0
          return MT;
10250
0
      }
10251
0
    }
10252
0
  }
10253
10254
0
  return {};
10255
0
}
10256
10257
/// mergeFunctionParameterTypes - merge two types which appear as function
10258
/// parameter types
10259
QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
10260
                                                 bool OfBlockPointer,
10261
0
                                                 bool Unqualified) {
10262
  // GNU extension: two types are compatible if they appear as a function
10263
  // argument, one of the types is a transparent union type and the other
10264
  // type is compatible with a union member
10265
0
  QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
10266
0
                                              Unqualified);
10267
0
  if (!lmerge.isNull())
10268
0
    return lmerge;
10269
10270
0
  QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
10271
0
                                              Unqualified);
10272
0
  if (!rmerge.isNull())
10273
0
    return rmerge;
10274
10275
0
  return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
10276
0
}
10277
10278
QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
10279
                                        bool OfBlockPointer, bool Unqualified,
10280
                                        bool AllowCXX,
10281
0
                                        bool IsConditionalOperator) {
10282
0
  const auto *lbase = lhs->castAs<FunctionType>();
10283
0
  const auto *rbase = rhs->castAs<FunctionType>();
10284
0
  const auto *lproto = dyn_cast<FunctionProtoType>(lbase);
10285
0
  const auto *rproto = dyn_cast<FunctionProtoType>(rbase);
10286
0
  bool allLTypes = true;
10287
0
  bool allRTypes = true;
10288
10289
  // Check return type
10290
0
  QualType retType;
10291
0
  if (OfBlockPointer) {
10292
0
    QualType RHS = rbase->getReturnType();
10293
0
    QualType LHS = lbase->getReturnType();
10294
0
    bool UnqualifiedResult = Unqualified;
10295
0
    if (!UnqualifiedResult)
10296
0
      UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
10297
0
    retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
10298
0
  }
10299
0
  else
10300
0
    retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
10301
0
                         Unqualified);
10302
0
  if (retType.isNull())
10303
0
    return {};
10304
10305
0
  if (Unqualified)
10306
0
    retType = retType.getUnqualifiedType();
10307
10308
0
  CanQualType LRetType = getCanonicalType(lbase->getReturnType());
10309
0
  CanQualType RRetType = getCanonicalType(rbase->getReturnType());
10310
0
  if (Unqualified) {
10311
0
    LRetType = LRetType.getUnqualifiedType();
10312
0
    RRetType = RRetType.getUnqualifiedType();
10313
0
  }
10314
10315
0
  if (getCanonicalType(retType) != LRetType)
10316
0
    allLTypes = false;
10317
0
  if (getCanonicalType(retType) != RRetType)
10318
0
    allRTypes = false;
10319
10320
  // FIXME: double check this
10321
  // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
10322
  //                           rbase->getRegParmAttr() != 0 &&
10323
  //                           lbase->getRegParmAttr() != rbase->getRegParmAttr()?
10324
0
  FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
10325
0
  FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
10326
10327
  // Compatible functions must have compatible calling conventions
10328
0
  if (lbaseInfo.getCC() != rbaseInfo.getCC())
10329
0
    return {};
10330
10331
  // Regparm is part of the calling convention.
10332
0
  if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
10333
0
    return {};
10334
0
  if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
10335
0
    return {};
10336
10337
0
  if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
10338
0
    return {};
10339
0
  if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs())
10340
0
    return {};
10341
0
  if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck())
10342
0
    return {};
10343
10344
  // When merging declarations, it's common for supplemental information like
10345
  // attributes to only be present in one of the declarations, and we generally
10346
  // want type merging to preserve the union of information.  So a merged
10347
  // function type should be noreturn if it was noreturn in *either* operand
10348
  // type.
10349
  //
10350
  // But for the conditional operator, this is backwards.  The result of the
10351
  // operator could be either operand, and its type should conservatively
10352
  // reflect that.  So a function type in a composite type is noreturn only
10353
  // if it's noreturn in *both* operand types.
10354
  //
10355
  // Arguably, noreturn is a kind of subtype, and the conditional operator
10356
  // ought to produce the most specific common supertype of its operand types.
10357
  // That would differ from this rule in contravariant positions.  However,
10358
  // neither C nor C++ generally uses this kind of subtype reasoning.  Also,
10359
  // as a practical matter, it would only affect C code that does abstraction of
10360
  // higher-order functions (taking noreturn callbacks!), which is uncommon to
10361
  // say the least.  So we use the simpler rule.
10362
0
  bool NoReturn = IsConditionalOperator
10363
0
                      ? lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn()
10364
0
                      : lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
10365
0
  if (lbaseInfo.getNoReturn() != NoReturn)
10366
0
    allLTypes = false;
10367
0
  if (rbaseInfo.getNoReturn() != NoReturn)
10368
0
    allRTypes = false;
10369
10370
0
  FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
10371
10372
0
  if (lproto && rproto) { // two C99 style function prototypes
10373
0
    assert((AllowCXX ||
10374
0
            (!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec())) &&
10375
0
           "C++ shouldn't be here");
10376
    // Compatible functions must have the same number of parameters
10377
0
    if (lproto->getNumParams() != rproto->getNumParams())
10378
0
      return {};
10379
10380
    // Variadic and non-variadic functions aren't compatible
10381
0
    if (lproto->isVariadic() != rproto->isVariadic())
10382
0
      return {};
10383
10384
0
    if (lproto->getMethodQuals() != rproto->getMethodQuals())
10385
0
      return {};
10386
10387
0
    SmallVector<FunctionProtoType::ExtParameterInfo, 4> newParamInfos;
10388
0
    bool canUseLeft, canUseRight;
10389
0
    if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight,
10390
0
                               newParamInfos))
10391
0
      return {};
10392
10393
0
    if (!canUseLeft)
10394
0
      allLTypes = false;
10395
0
    if (!canUseRight)
10396
0
      allRTypes = false;
10397
10398
    // Check parameter type compatibility
10399
0
    SmallVector<QualType, 10> types;
10400
0
    for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
10401
0
      QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
10402
0
      QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
10403
0
      QualType paramType = mergeFunctionParameterTypes(
10404
0
          lParamType, rParamType, OfBlockPointer, Unqualified);
10405
0
      if (paramType.isNull())
10406
0
        return {};
10407
10408
0
      if (Unqualified)
10409
0
        paramType = paramType.getUnqualifiedType();
10410
10411
0
      types.push_back(paramType);
10412
0
      if (Unqualified) {
10413
0
        lParamType = lParamType.getUnqualifiedType();
10414
0
        rParamType = rParamType.getUnqualifiedType();
10415
0
      }
10416
10417
0
      if (getCanonicalType(paramType) != getCanonicalType(lParamType))
10418
0
        allLTypes = false;
10419
0
      if (getCanonicalType(paramType) != getCanonicalType(rParamType))
10420
0
        allRTypes = false;
10421
0
    }
10422
10423
0
    if (allLTypes) return lhs;
10424
0
    if (allRTypes) return rhs;
10425
10426
0
    FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
10427
0
    EPI.ExtInfo = einfo;
10428
0
    EPI.ExtParameterInfos =
10429
0
        newParamInfos.empty() ? nullptr : newParamInfos.data();
10430
0
    return getFunctionType(retType, types, EPI);
10431
0
  }
10432
10433
0
  if (lproto) allRTypes = false;
10434
0
  if (rproto) allLTypes = false;
10435
10436
0
  const FunctionProtoType *proto = lproto ? lproto : rproto;
10437
0
  if (proto) {
10438
0
    assert((AllowCXX || !proto->hasExceptionSpec()) && "C++ shouldn't be here");
10439
0
    if (proto->isVariadic())
10440
0
      return {};
10441
    // Check that the types are compatible with the types that
10442
    // would result from default argument promotions (C99 6.7.5.3p15).
10443
    // The only types actually affected are promotable integer
10444
    // types and floats, which would be passed as a different
10445
    // type depending on whether the prototype is visible.
10446
0
    for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
10447
0
      QualType paramTy = proto->getParamType(i);
10448
10449
      // Look at the converted type of enum types, since that is the type used
10450
      // to pass enum values.
10451
0
      if (const auto *Enum = paramTy->getAs<EnumType>()) {
10452
0
        paramTy = Enum->getDecl()->getIntegerType();
10453
0
        if (paramTy.isNull())
10454
0
          return {};
10455
0
      }
10456
10457
0
      if (isPromotableIntegerType(paramTy) ||
10458
0
          getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
10459
0
        return {};
10460
0
    }
10461
10462
0
    if (allLTypes) return lhs;
10463
0
    if (allRTypes) return rhs;
10464
10465
0
    FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
10466
0
    EPI.ExtInfo = einfo;
10467
0
    return getFunctionType(retType, proto->getParamTypes(), EPI);
10468
0
  }
10469
10470
0
  if (allLTypes) return lhs;
10471
0
  if (allRTypes) return rhs;
10472
0
  return getFunctionNoProtoType(retType, einfo);
10473
0
}
10474
10475
/// Given that we have an enum type and a non-enum type, try to merge them.
10476
static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
10477
0
                                     QualType other, bool isBlockReturnType) {
10478
  // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
10479
  // a signed integer type, or an unsigned integer type.
10480
  // Compatibility is based on the underlying type, not the promotion
10481
  // type.
10482
0
  QualType underlyingType = ET->getDecl()->getIntegerType();
10483
0
  if (underlyingType.isNull())
10484
0
    return {};
10485
0
  if (Context.hasSameType(underlyingType, other))
10486
0
    return other;
10487
10488
  // In block return types, we're more permissive and accept any
10489
  // integral type of the same size.
10490
0
  if (isBlockReturnType && other->isIntegerType() &&
10491
0
      Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
10492
0
    return other;
10493
10494
0
  return {};
10495
0
}
10496
10497
QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, bool OfBlockPointer,
10498
                                bool Unqualified, bool BlockReturnType,
10499
64
                                bool IsConditionalOperator) {
10500
  // For C++ we will not reach this code with reference types (see below),
10501
  // for OpenMP variant call overloading we might.
10502
  //
10503
  // C++ [expr]: If an expression initially has the type "reference to T", the
10504
  // type is adjusted to "T" prior to any further analysis, the expression
10505
  // designates the object or function denoted by the reference, and the
10506
  // expression is an lvalue unless the reference is an rvalue reference and
10507
  // the expression is a function call (possibly inside parentheses).
10508
64
  auto *LHSRefTy = LHS->getAs<ReferenceType>();
10509
64
  auto *RHSRefTy = RHS->getAs<ReferenceType>();
10510
64
  if (LangOpts.OpenMP && LHSRefTy && RHSRefTy &&
10511
64
      LHS->getTypeClass() == RHS->getTypeClass())
10512
0
    return mergeTypes(LHSRefTy->getPointeeType(), RHSRefTy->getPointeeType(),
10513
0
                      OfBlockPointer, Unqualified, BlockReturnType);
10514
64
  if (LHSRefTy || RHSRefTy)
10515
0
    return {};
10516
10517
64
  if (Unqualified) {
10518
0
    LHS = LHS.getUnqualifiedType();
10519
0
    RHS = RHS.getUnqualifiedType();
10520
0
  }
10521
10522
64
  QualType LHSCan = getCanonicalType(LHS),
10523
64
           RHSCan = getCanonicalType(RHS);
10524
10525
  // If two types are identical, they are compatible.
10526
64
  if (LHSCan == RHSCan)
10527
54
    return LHS;
10528
10529
  // If the qualifiers are different, the types aren't compatible... mostly.
10530
10
  Qualifiers LQuals = LHSCan.getLocalQualifiers();
10531
10
  Qualifiers RQuals = RHSCan.getLocalQualifiers();
10532
10
  if (LQuals != RQuals) {
10533
    // If any of these qualifiers are different, we have a type
10534
    // mismatch.
10535
0
    if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
10536
0
        LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
10537
0
        LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
10538
0
        LQuals.hasUnaligned() != RQuals.hasUnaligned())
10539
0
      return {};
10540
10541
    // Exactly one GC qualifier difference is allowed: __strong is
10542
    // okay if the other type has no GC qualifier but is an Objective
10543
    // C object pointer (i.e. implicitly strong by default).  We fix
10544
    // this by pretending that the unqualified type was actually
10545
    // qualified __strong.
10546
0
    Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
10547
0
    Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
10548
0
    assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
10549
10550
0
    if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
10551
0
      return {};
10552
10553
0
    if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
10554
0
      return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
10555
0
    }
10556
0
    if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
10557
0
      return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
10558
0
    }
10559
0
    return {};
10560
0
  }
10561
10562
  // Okay, qualifiers are equal.
10563
10564
10
  Type::TypeClass LHSClass = LHSCan->getTypeClass();
10565
10
  Type::TypeClass RHSClass = RHSCan->getTypeClass();
10566
10567
  // We want to consider the two function types to be the same for these
10568
  // comparisons, just force one to the other.
10569
10
  if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
10570
10
  if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
10571
10572
  // Same as above for arrays
10573
10
  if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
10574
0
    LHSClass = Type::ConstantArray;
10575
10
  if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
10576
0
    RHSClass = Type::ConstantArray;
10577
10578
  // ObjCInterfaces are just specialized ObjCObjects.
10579
10
  if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
10580
10
  if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
10581
10582
  // Canonicalize ExtVector -> Vector.
10583
10
  if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
10584
10
  if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
10585
10586
  // If the canonical type classes don't match.
10587
10
  if (LHSClass != RHSClass) {
10588
    // Note that we only have special rules for turning block enum
10589
    // returns into block int returns, not vice-versa.
10590
10
    if (const auto *ETy = LHS->getAs<EnumType>()) {
10591
0
      return mergeEnumWithInteger(*this, ETy, RHS, false);
10592
0
    }
10593
10
    if (const EnumType* ETy = RHS->getAs<EnumType>()) {
10594
0
      return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
10595
0
    }
10596
    // allow block pointer type to match an 'id' type.
10597
10
    if (OfBlockPointer && !BlockReturnType) {
10598
0
       if (LHS->isObjCIdType() && RHS->isBlockPointerType())
10599
0
         return LHS;
10600
0
      if (RHS->isObjCIdType() && LHS->isBlockPointerType())
10601
0
        return RHS;
10602
0
    }
10603
    // Allow __auto_type to match anything; it merges to the type with more
10604
    // information.
10605
10
    if (const auto *AT = LHS->getAs<AutoType>()) {
10606
0
      if (!AT->isDeduced() && AT->isGNUAutoType())
10607
0
        return RHS;
10608
0
    }
10609
10
    if (const auto *AT = RHS->getAs<AutoType>()) {
10610
0
      if (!AT->isDeduced() && AT->isGNUAutoType())
10611
0
        return LHS;
10612
0
    }
10613
10
    return {};
10614
10
  }
10615
10616
  // The canonical type classes match.
10617
0
  switch (LHSClass) {
10618
0
#define TYPE(Class, Base)
10619
0
#define ABSTRACT_TYPE(Class, Base)
10620
0
#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
10621
0
#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
10622
0
#define DEPENDENT_TYPE(Class, Base) case Type::Class:
10623
0
#include "clang/AST/TypeNodes.inc"
10624
0
    llvm_unreachable("Non-canonical and dependent types shouldn't get here");
10625
10626
0
  case Type::Auto:
10627
0
  case Type::DeducedTemplateSpecialization:
10628
0
  case Type::LValueReference:
10629
0
  case Type::RValueReference:
10630
0
  case Type::MemberPointer:
10631
0
    llvm_unreachable("C++ should never be in mergeTypes");
10632
10633
0
  case Type::ObjCInterface:
10634
0
  case Type::IncompleteArray:
10635
0
  case Type::VariableArray:
10636
0
  case Type::FunctionProto:
10637
0
  case Type::ExtVector:
10638
0
    llvm_unreachable("Types are eliminated above");
10639
10640
0
  case Type::Pointer:
10641
0
  {
10642
    // Merge two pointer types, while trying to preserve typedef info
10643
0
    QualType LHSPointee = LHS->castAs<PointerType>()->getPointeeType();
10644
0
    QualType RHSPointee = RHS->castAs<PointerType>()->getPointeeType();
10645
0
    if (Unqualified) {
10646
0
      LHSPointee = LHSPointee.getUnqualifiedType();
10647
0
      RHSPointee = RHSPointee.getUnqualifiedType();
10648
0
    }
10649
0
    QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
10650
0
                                     Unqualified);
10651
0
    if (ResultType.isNull())
10652
0
      return {};
10653
0
    if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
10654
0
      return LHS;
10655
0
    if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
10656
0
      return RHS;
10657
0
    return getPointerType(ResultType);
10658
0
  }
10659
0
  case Type::BlockPointer:
10660
0
  {
10661
    // Merge two block pointer types, while trying to preserve typedef info
10662
0
    QualType LHSPointee = LHS->castAs<BlockPointerType>()->getPointeeType();
10663
0
    QualType RHSPointee = RHS->castAs<BlockPointerType>()->getPointeeType();
10664
0
    if (Unqualified) {
10665
0
      LHSPointee = LHSPointee.getUnqualifiedType();
10666
0
      RHSPointee = RHSPointee.getUnqualifiedType();
10667
0
    }
10668
0
    if (getLangOpts().OpenCL) {
10669
0
      Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
10670
0
      Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
10671
      // Blocks can't be an expression in a ternary operator (OpenCL v2.0
10672
      // 6.12.5) thus the following check is asymmetric.
10673
0
      if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual))
10674
0
        return {};
10675
0
      LHSPteeQual.removeAddressSpace();
10676
0
      RHSPteeQual.removeAddressSpace();
10677
0
      LHSPointee =
10678
0
          QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
10679
0
      RHSPointee =
10680
0
          QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
10681
0
    }
10682
0
    QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
10683
0
                                     Unqualified);
10684
0
    if (ResultType.isNull())
10685
0
      return {};
10686
0
    if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
10687
0
      return LHS;
10688
0
    if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
10689
0
      return RHS;
10690
0
    return getBlockPointerType(ResultType);
10691
0
  }
10692
0
  case Type::Atomic:
10693
0
  {
10694
    // Merge two pointer types, while trying to preserve typedef info
10695
0
    QualType LHSValue = LHS->castAs<AtomicType>()->getValueType();
10696
0
    QualType RHSValue = RHS->castAs<AtomicType>()->getValueType();
10697
0
    if (Unqualified) {
10698
0
      LHSValue = LHSValue.getUnqualifiedType();
10699
0
      RHSValue = RHSValue.getUnqualifiedType();
10700
0
    }
10701
0
    QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
10702
0
                                     Unqualified);
10703
0
    if (ResultType.isNull())
10704
0
      return {};
10705
0
    if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
10706
0
      return LHS;
10707
0
    if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
10708
0
      return RHS;
10709
0
    return getAtomicType(ResultType);
10710
0
  }
10711
0
  case Type::ConstantArray:
10712
0
  {
10713
0
    const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
10714
0
    const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
10715
0
    if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
10716
0
      return {};
10717
10718
0
    QualType LHSElem = getAsArrayType(LHS)->getElementType();
10719
0
    QualType RHSElem = getAsArrayType(RHS)->getElementType();
10720
0
    if (Unqualified) {
10721
0
      LHSElem = LHSElem.getUnqualifiedType();
10722
0
      RHSElem = RHSElem.getUnqualifiedType();
10723
0
    }
10724
10725
0
    QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
10726
0
    if (ResultType.isNull())
10727
0
      return {};
10728
10729
0
    const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
10730
0
    const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
10731
10732
    // If either side is a variable array, and both are complete, check whether
10733
    // the current dimension is definite.
10734
0
    if (LVAT || RVAT) {
10735
0
      auto SizeFetch = [this](const VariableArrayType* VAT,
10736
0
          const ConstantArrayType* CAT)
10737
0
          -> std::pair<bool,llvm::APInt> {
10738
0
        if (VAT) {
10739
0
          std::optional<llvm::APSInt> TheInt;
10740
0
          Expr *E = VAT->getSizeExpr();
10741
0
          if (E && (TheInt = E->getIntegerConstantExpr(*this)))
10742
0
            return std::make_pair(true, *TheInt);
10743
0
          return std::make_pair(false, llvm::APSInt());
10744
0
        }
10745
0
        if (CAT)
10746
0
          return std::make_pair(true, CAT->getSize());
10747
0
        return std::make_pair(false, llvm::APInt());
10748
0
      };
10749
10750
0
      bool HaveLSize, HaveRSize;
10751
0
      llvm::APInt LSize, RSize;
10752
0
      std::tie(HaveLSize, LSize) = SizeFetch(LVAT, LCAT);
10753
0
      std::tie(HaveRSize, RSize) = SizeFetch(RVAT, RCAT);
10754
0
      if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(LSize, RSize))
10755
0
        return {}; // Definite, but unequal, array dimension
10756
0
    }
10757
10758
0
    if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
10759
0
      return LHS;
10760
0
    if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
10761
0
      return RHS;
10762
0
    if (LCAT)
10763
0
      return getConstantArrayType(ResultType, LCAT->getSize(),
10764
0
                                  LCAT->getSizeExpr(), ArraySizeModifier(), 0);
10765
0
    if (RCAT)
10766
0
      return getConstantArrayType(ResultType, RCAT->getSize(),
10767
0
                                  RCAT->getSizeExpr(), ArraySizeModifier(), 0);
10768
0
    if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
10769
0
      return LHS;
10770
0
    if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
10771
0
      return RHS;
10772
0
    if (LVAT) {
10773
      // FIXME: This isn't correct! But tricky to implement because
10774
      // the array's size has to be the size of LHS, but the type
10775
      // has to be different.
10776
0
      return LHS;
10777
0
    }
10778
0
    if (RVAT) {
10779
      // FIXME: This isn't correct! But tricky to implement because
10780
      // the array's size has to be the size of RHS, but the type
10781
      // has to be different.
10782
0
      return RHS;
10783
0
    }
10784
0
    if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
10785
0
    if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
10786
0
    return getIncompleteArrayType(ResultType, ArraySizeModifier(), 0);
10787
0
  }
10788
0
  case Type::FunctionNoProto:
10789
0
    return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified,
10790
0
                              /*AllowCXX=*/false, IsConditionalOperator);
10791
0
  case Type::Record:
10792
0
  case Type::Enum:
10793
0
    return {};
10794
0
  case Type::Builtin:
10795
    // Only exactly equal builtin types are compatible, which is tested above.
10796
0
    return {};
10797
0
  case Type::Complex:
10798
    // Distinct complex types are incompatible.
10799
0
    return {};
10800
0
  case Type::Vector:
10801
    // FIXME: The merged type should be an ExtVector!
10802
0
    if (areCompatVectorTypes(LHSCan->castAs<VectorType>(),
10803
0
                             RHSCan->castAs<VectorType>()))
10804
0
      return LHS;
10805
0
    return {};
10806
0
  case Type::ConstantMatrix:
10807
0
    if (areCompatMatrixTypes(LHSCan->castAs<ConstantMatrixType>(),
10808
0
                             RHSCan->castAs<ConstantMatrixType>()))
10809
0
      return LHS;
10810
0
    return {};
10811
0
  case Type::ObjCObject: {
10812
    // Check if the types are assignment compatible.
10813
    // FIXME: This should be type compatibility, e.g. whether
10814
    // "LHS x; RHS x;" at global scope is legal.
10815
0
    if (canAssignObjCInterfaces(LHS->castAs<ObjCObjectType>(),
10816
0
                                RHS->castAs<ObjCObjectType>()))
10817
0
      return LHS;
10818
0
    return {};
10819
0
  }
10820
0
  case Type::ObjCObjectPointer:
10821
0
    if (OfBlockPointer) {
10822
0
      if (canAssignObjCInterfacesInBlockPointer(
10823
0
              LHS->castAs<ObjCObjectPointerType>(),
10824
0
              RHS->castAs<ObjCObjectPointerType>(), BlockReturnType))
10825
0
        return LHS;
10826
0
      return {};
10827
0
    }
10828
0
    if (canAssignObjCInterfaces(LHS->castAs<ObjCObjectPointerType>(),
10829
0
                                RHS->castAs<ObjCObjectPointerType>()))
10830
0
      return LHS;
10831
0
    return {};
10832
0
  case Type::Pipe:
10833
0
    assert(LHS != RHS &&
10834
0
           "Equivalent pipe types should have already been handled!");
10835
0
    return {};
10836
0
  case Type::BitInt: {
10837
    // Merge two bit-precise int types, while trying to preserve typedef info.
10838
0
    bool LHSUnsigned = LHS->castAs<BitIntType>()->isUnsigned();
10839
0
    bool RHSUnsigned = RHS->castAs<BitIntType>()->isUnsigned();
10840
0
    unsigned LHSBits = LHS->castAs<BitIntType>()->getNumBits();
10841
0
    unsigned RHSBits = RHS->castAs<BitIntType>()->getNumBits();
10842
10843
    // Like unsigned/int, shouldn't have a type if they don't match.
10844
0
    if (LHSUnsigned != RHSUnsigned)
10845
0
      return {};
10846
10847
0
    if (LHSBits != RHSBits)
10848
0
      return {};
10849
0
    return LHS;
10850
0
  }
10851
0
  }
10852
10853
0
  llvm_unreachable("Invalid Type::Class!");
10854
0
}
10855
10856
bool ASTContext::mergeExtParameterInfo(
10857
    const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType,
10858
    bool &CanUseFirst, bool &CanUseSecond,
10859
0
    SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &NewParamInfos) {
10860
0
  assert(NewParamInfos.empty() && "param info list not empty");
10861
0
  CanUseFirst = CanUseSecond = true;
10862
0
  bool FirstHasInfo = FirstFnType->hasExtParameterInfos();
10863
0
  bool SecondHasInfo = SecondFnType->hasExtParameterInfos();
10864
10865
  // Fast path: if the first type doesn't have ext parameter infos,
10866
  // we match if and only if the second type also doesn't have them.
10867
0
  if (!FirstHasInfo && !SecondHasInfo)
10868
0
    return true;
10869
10870
0
  bool NeedParamInfo = false;
10871
0
  size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size()
10872
0
                          : SecondFnType->getExtParameterInfos().size();
10873
10874
0
  for (size_t I = 0; I < E; ++I) {
10875
0
    FunctionProtoType::ExtParameterInfo FirstParam, SecondParam;
10876
0
    if (FirstHasInfo)
10877
0
      FirstParam = FirstFnType->getExtParameterInfo(I);
10878
0
    if (SecondHasInfo)
10879
0
      SecondParam = SecondFnType->getExtParameterInfo(I);
10880
10881
    // Cannot merge unless everything except the noescape flag matches.
10882
0
    if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false))
10883
0
      return false;
10884
10885
0
    bool FirstNoEscape = FirstParam.isNoEscape();
10886
0
    bool SecondNoEscape = SecondParam.isNoEscape();
10887
0
    bool IsNoEscape = FirstNoEscape && SecondNoEscape;
10888
0
    NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape));
10889
0
    if (NewParamInfos.back().getOpaqueValue())
10890
0
      NeedParamInfo = true;
10891
0
    if (FirstNoEscape != IsNoEscape)
10892
0
      CanUseFirst = false;
10893
0
    if (SecondNoEscape != IsNoEscape)
10894
0
      CanUseSecond = false;
10895
0
  }
10896
10897
0
  if (!NeedParamInfo)
10898
0
    NewParamInfos.clear();
10899
10900
0
  return true;
10901
0
}
10902
10903
0
void ASTContext::ResetObjCLayout(const ObjCContainerDecl *CD) {
10904
0
  ObjCLayouts[CD] = nullptr;
10905
0
}
10906
10907
/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
10908
/// 'RHS' attributes and returns the merged version; including for function
10909
/// return types.
10910
0
QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
10911
0
  QualType LHSCan = getCanonicalType(LHS),
10912
0
  RHSCan = getCanonicalType(RHS);
10913
  // If two types are identical, they are compatible.
10914
0
  if (LHSCan == RHSCan)
10915
0
    return LHS;
10916
0
  if (RHSCan->isFunctionType()) {
10917
0
    if (!LHSCan->isFunctionType())
10918
0
      return {};
10919
0
    QualType OldReturnType =
10920
0
        cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
10921
0
    QualType NewReturnType =
10922
0
        cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
10923
0
    QualType ResReturnType =
10924
0
      mergeObjCGCQualifiers(NewReturnType, OldReturnType);
10925
0
    if (ResReturnType.isNull())
10926
0
      return {};
10927
0
    if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
10928
      // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
10929
      // In either case, use OldReturnType to build the new function type.
10930
0
      const auto *F = LHS->castAs<FunctionType>();
10931
0
      if (const auto *FPT = cast<FunctionProtoType>(F)) {
10932
0
        FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10933
0
        EPI.ExtInfo = getFunctionExtInfo(LHS);
10934
0
        QualType ResultType =
10935
0
            getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
10936
0
        return ResultType;
10937
0
      }
10938
0
    }
10939
0
    return {};
10940
0
  }
10941
10942
  // If the qualifiers are different, the types can still be merged.
10943
0
  Qualifiers LQuals = LHSCan.getLocalQualifiers();
10944
0
  Qualifiers RQuals = RHSCan.getLocalQualifiers();
10945
0
  if (LQuals != RQuals) {
10946
    // If any of these qualifiers are different, we have a type mismatch.
10947
0
    if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
10948
0
        LQuals.getAddressSpace() != RQuals.getAddressSpace())
10949
0
      return {};
10950
10951
    // Exactly one GC qualifier difference is allowed: __strong is
10952
    // okay if the other type has no GC qualifier but is an Objective
10953
    // C object pointer (i.e. implicitly strong by default).  We fix
10954
    // this by pretending that the unqualified type was actually
10955
    // qualified __strong.
10956
0
    Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
10957
0
    Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
10958
0
    assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
10959
10960
0
    if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
10961
0
      return {};
10962
10963
0
    if (GC_L == Qualifiers::Strong)
10964
0
      return LHS;
10965
0
    if (GC_R == Qualifiers::Strong)
10966
0
      return RHS;
10967
0
    return {};
10968
0
  }
10969
10970
0
  if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
10971
0
    QualType LHSBaseQT = LHS->castAs<ObjCObjectPointerType>()->getPointeeType();
10972
0
    QualType RHSBaseQT = RHS->castAs<ObjCObjectPointerType>()->getPointeeType();
10973
0
    QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
10974
0
    if (ResQT == LHSBaseQT)
10975
0
      return LHS;
10976
0
    if (ResQT == RHSBaseQT)
10977
0
      return RHS;
10978
0
  }
10979
0
  return {};
10980
0
}
10981
10982
//===----------------------------------------------------------------------===//
10983
//                         Integer Predicates
10984
//===----------------------------------------------------------------------===//
10985
10986
53
unsigned ASTContext::getIntWidth(QualType T) const {
10987
53
  if (const auto *ET = T->getAs<EnumType>())
10988
0
    T = ET->getDecl()->getIntegerType();
10989
53
  if (T->isBooleanType())
10990
0
    return 1;
10991
53
  if (const auto *EIT = T->getAs<BitIntType>())
10992
0
    return EIT->getNumBits();
10993
  // For builtin types, just use the standard type sizing method
10994
53
  return (unsigned)getTypeSize(T);
10995
53
}
10996
10997
0
QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
10998
0
  assert((T->hasIntegerRepresentation() || T->isEnumeralType() ||
10999
0
          T->isFixedPointType()) &&
11000
0
         "Unexpected type");
11001
11002
  // Turn <4 x signed int> -> <4 x unsigned int>
11003
0
  if (const auto *VTy = T->getAs<VectorType>())
11004
0
    return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
11005
0
                         VTy->getNumElements(), VTy->getVectorKind());
11006
11007
  // For _BitInt, return an unsigned _BitInt with same width.
11008
0
  if (const auto *EITy = T->getAs<BitIntType>())
11009
0
    return getBitIntType(/*Unsigned=*/true, EITy->getNumBits());
11010
11011
  // For enums, get the underlying integer type of the enum, and let the general
11012
  // integer type signchanging code handle it.
11013
0
  if (const auto *ETy = T->getAs<EnumType>())
11014
0
    T = ETy->getDecl()->getIntegerType();
11015
11016
0
  switch (T->castAs<BuiltinType>()->getKind()) {
11017
0
  case BuiltinType::Char_U:
11018
    // Plain `char` is mapped to `unsigned char` even if it's already unsigned
11019
0
  case BuiltinType::Char_S:
11020
0
  case BuiltinType::SChar:
11021
0
  case BuiltinType::Char8:
11022
0
    return UnsignedCharTy;
11023
0
  case BuiltinType::Short:
11024
0
    return UnsignedShortTy;
11025
0
  case BuiltinType::Int:
11026
0
    return UnsignedIntTy;
11027
0
  case BuiltinType::Long:
11028
0
    return UnsignedLongTy;
11029
0
  case BuiltinType::LongLong:
11030
0
    return UnsignedLongLongTy;
11031
0
  case BuiltinType::Int128:
11032
0
    return UnsignedInt128Ty;
11033
  // wchar_t is special. It is either signed or not, but when it's signed,
11034
  // there's no matching "unsigned wchar_t". Therefore we return the unsigned
11035
  // version of its underlying type instead.
11036
0
  case BuiltinType::WChar_S:
11037
0
    return getUnsignedWCharType();
11038
11039
0
  case BuiltinType::ShortAccum:
11040
0
    return UnsignedShortAccumTy;
11041
0
  case BuiltinType::Accum:
11042
0
    return UnsignedAccumTy;
11043
0
  case BuiltinType::LongAccum:
11044
0
    return UnsignedLongAccumTy;
11045
0
  case BuiltinType::SatShortAccum:
11046
0
    return SatUnsignedShortAccumTy;
11047
0
  case BuiltinType::SatAccum:
11048
0
    return SatUnsignedAccumTy;
11049
0
  case BuiltinType::SatLongAccum:
11050
0
    return SatUnsignedLongAccumTy;
11051
0
  case BuiltinType::ShortFract:
11052
0
    return UnsignedShortFractTy;
11053
0
  case BuiltinType::Fract:
11054
0
    return UnsignedFractTy;
11055
0
  case BuiltinType::LongFract:
11056
0
    return UnsignedLongFractTy;
11057
0
  case BuiltinType::SatShortFract:
11058
0
    return SatUnsignedShortFractTy;
11059
0
  case BuiltinType::SatFract:
11060
0
    return SatUnsignedFractTy;
11061
0
  case BuiltinType::SatLongFract:
11062
0
    return SatUnsignedLongFractTy;
11063
0
  default:
11064
0
    assert((T->hasUnsignedIntegerRepresentation() ||
11065
0
            T->isUnsignedFixedPointType()) &&
11066
0
           "Unexpected signed integer or fixed point type");
11067
0
    return T;
11068
0
  }
11069
0
}
11070
11071
0
QualType ASTContext::getCorrespondingSignedType(QualType T) const {
11072
0
  assert((T->hasIntegerRepresentation() || T->isEnumeralType() ||
11073
0
          T->isFixedPointType()) &&
11074
0
         "Unexpected type");
11075
11076
  // Turn <4 x unsigned int> -> <4 x signed int>
11077
0
  if (const auto *VTy = T->getAs<VectorType>())
11078
0
    return getVectorType(getCorrespondingSignedType(VTy->getElementType()),
11079
0
                         VTy->getNumElements(), VTy->getVectorKind());
11080
11081
  // For _BitInt, return a signed _BitInt with same width.
11082
0
  if (const auto *EITy = T->getAs<BitIntType>())
11083
0
    return getBitIntType(/*Unsigned=*/false, EITy->getNumBits());
11084
11085
  // For enums, get the underlying integer type of the enum, and let the general
11086
  // integer type signchanging code handle it.
11087
0
  if (const auto *ETy = T->getAs<EnumType>())
11088
0
    T = ETy->getDecl()->getIntegerType();
11089
11090
0
  switch (T->castAs<BuiltinType>()->getKind()) {
11091
0
  case BuiltinType::Char_S:
11092
    // Plain `char` is mapped to `signed char` even if it's already signed
11093
0
  case BuiltinType::Char_U:
11094
0
  case BuiltinType::UChar:
11095
0
  case BuiltinType::Char8:
11096
0
    return SignedCharTy;
11097
0
  case BuiltinType::UShort:
11098
0
    return ShortTy;
11099
0
  case BuiltinType::UInt:
11100
0
    return IntTy;
11101
0
  case BuiltinType::ULong:
11102
0
    return LongTy;
11103
0
  case BuiltinType::ULongLong:
11104
0
    return LongLongTy;
11105
0
  case BuiltinType::UInt128:
11106
0
    return Int128Ty;
11107
  // wchar_t is special. It is either unsigned or not, but when it's unsigned,
11108
  // there's no matching "signed wchar_t". Therefore we return the signed
11109
  // version of its underlying type instead.
11110
0
  case BuiltinType::WChar_U:
11111
0
    return getSignedWCharType();
11112
11113
0
  case BuiltinType::UShortAccum:
11114
0
    return ShortAccumTy;
11115
0
  case BuiltinType::UAccum:
11116
0
    return AccumTy;
11117
0
  case BuiltinType::ULongAccum:
11118
0
    return LongAccumTy;
11119
0
  case BuiltinType::SatUShortAccum:
11120
0
    return SatShortAccumTy;
11121
0
  case BuiltinType::SatUAccum:
11122
0
    return SatAccumTy;
11123
0
  case BuiltinType::SatULongAccum:
11124
0
    return SatLongAccumTy;
11125
0
  case BuiltinType::UShortFract:
11126
0
    return ShortFractTy;
11127
0
  case BuiltinType::UFract:
11128
0
    return FractTy;
11129
0
  case BuiltinType::ULongFract:
11130
0
    return LongFractTy;
11131
0
  case BuiltinType::SatUShortFract:
11132
0
    return SatShortFractTy;
11133
0
  case BuiltinType::SatUFract:
11134
0
    return SatFractTy;
11135
0
  case BuiltinType::SatULongFract:
11136
0
    return SatLongFractTy;
11137
0
  default:
11138
0
    assert(
11139
0
        (T->hasSignedIntegerRepresentation() || T->isSignedFixedPointType()) &&
11140
0
        "Unexpected signed integer or fixed point type");
11141
0
    return T;
11142
0
  }
11143
0
}
11144
11145
0
ASTMutationListener::~ASTMutationListener() = default;
11146
11147
void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
11148
0
                                            QualType ReturnType) {}
11149
11150
//===----------------------------------------------------------------------===//
11151
//                          Builtin Type Computation
11152
//===----------------------------------------------------------------------===//
11153
11154
/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
11155
/// pointer over the consumed characters.  This returns the resultant type.  If
11156
/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
11157
/// types.  This allows "v2i*" to be parsed as a pointer to a v2i instead of
11158
/// a vector of "i*".
11159
///
11160
/// RequiresICE is filled in on return to indicate whether the value is required
11161
/// to be an Integer Constant Expression.
11162
static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
11163
                                  ASTContext::GetBuiltinTypeError &Error,
11164
                                  bool &RequiresICE,
11165
0
                                  bool AllowTypeModifiers) {
11166
  // Modifiers.
11167
0
  int HowLong = 0;
11168
0
  bool Signed = false, Unsigned = false;
11169
0
  RequiresICE = false;
11170
11171
  // Read the prefixed modifiers first.
11172
0
  bool Done = false;
11173
0
  #ifndef NDEBUG
11174
0
  bool IsSpecial = false;
11175
0
  #endif
11176
0
  while (!Done) {
11177
0
    switch (*Str++) {
11178
0
    default: Done = true; --Str; break;
11179
0
    case 'I':
11180
0
      RequiresICE = true;
11181
0
      break;
11182
0
    case 'S':
11183
0
      assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
11184
0
      assert(!Signed && "Can't use 'S' modifier multiple times!");
11185
0
      Signed = true;
11186
0
      break;
11187
0
    case 'U':
11188
0
      assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
11189
0
      assert(!Unsigned && "Can't use 'U' modifier multiple times!");
11190
0
      Unsigned = true;
11191
0
      break;
11192
0
    case 'L':
11193
0
      assert(!IsSpecial && "Can't use 'L' with 'W', 'N', 'Z' or 'O' modifiers");
11194
0
      assert(HowLong <= 2 && "Can't have LLLL modifier");
11195
0
      ++HowLong;
11196
0
      break;
11197
0
    case 'N':
11198
      // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
11199
0
      assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
11200
0
      assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
11201
0
      #ifndef NDEBUG
11202
0
      IsSpecial = true;
11203
0
      #endif
11204
0
      if (Context.getTargetInfo().getLongWidth() == 32)
11205
0
        ++HowLong;
11206
0
      break;
11207
0
    case 'W':
11208
      // This modifier represents int64 type.
11209
0
      assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
11210
0
      assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
11211
0
      #ifndef NDEBUG
11212
0
      IsSpecial = true;
11213
0
      #endif
11214
0
      switch (Context.getTargetInfo().getInt64Type()) {
11215
0
      default:
11216
0
        llvm_unreachable("Unexpected integer type");
11217
0
      case TargetInfo::SignedLong:
11218
0
        HowLong = 1;
11219
0
        break;
11220
0
      case TargetInfo::SignedLongLong:
11221
0
        HowLong = 2;
11222
0
        break;
11223
0
      }
11224
0
      break;
11225
0
    case 'Z':
11226
      // This modifier represents int32 type.
11227
0
      assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
11228
0
      assert(HowLong == 0 && "Can't use both 'L' and 'Z' modifiers!");
11229
0
      #ifndef NDEBUG
11230
0
      IsSpecial = true;
11231
0
      #endif
11232
0
      switch (Context.getTargetInfo().getIntTypeByWidth(32, true)) {
11233
0
      default:
11234
0
        llvm_unreachable("Unexpected integer type");
11235
0
      case TargetInfo::SignedInt:
11236
0
        HowLong = 0;
11237
0
        break;
11238
0
      case TargetInfo::SignedLong:
11239
0
        HowLong = 1;
11240
0
        break;
11241
0
      case TargetInfo::SignedLongLong:
11242
0
        HowLong = 2;
11243
0
        break;
11244
0
      }
11245
0
      break;
11246
0
    case 'O':
11247
0
      assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
11248
0
      assert(HowLong == 0 && "Can't use both 'L' and 'O' modifiers!");
11249
0
      #ifndef NDEBUG
11250
0
      IsSpecial = true;
11251
0
      #endif
11252
0
      if (Context.getLangOpts().OpenCL)
11253
0
        HowLong = 1;
11254
0
      else
11255
0
        HowLong = 2;
11256
0
      break;
11257
0
    }
11258
0
  }
11259
11260
0
  QualType Type;
11261
11262
  // Read the base type.
11263
0
  switch (*Str++) {
11264
0
  default: llvm_unreachable("Unknown builtin type letter!");
11265
0
  case 'x':
11266
0
    assert(HowLong == 0 && !Signed && !Unsigned &&
11267
0
           "Bad modifiers used with 'x'!");
11268
0
    Type = Context.Float16Ty;
11269
0
    break;
11270
0
  case 'y':
11271
0
    assert(HowLong == 0 && !Signed && !Unsigned &&
11272
0
           "Bad modifiers used with 'y'!");
11273
0
    Type = Context.BFloat16Ty;
11274
0
    break;
11275
0
  case 'v':
11276
0
    assert(HowLong == 0 && !Signed && !Unsigned &&
11277
0
           "Bad modifiers used with 'v'!");
11278
0
    Type = Context.VoidTy;
11279
0
    break;
11280
0
  case 'h':
11281
0
    assert(HowLong == 0 && !Signed && !Unsigned &&
11282
0
           "Bad modifiers used with 'h'!");
11283
0
    Type = Context.HalfTy;
11284
0
    break;
11285
0
  case 'f':
11286
0
    assert(HowLong == 0 && !Signed && !Unsigned &&
11287
0
           "Bad modifiers used with 'f'!");
11288
0
    Type = Context.FloatTy;
11289
0
    break;
11290
0
  case 'd':
11291
0
    assert(HowLong < 3 && !Signed && !Unsigned &&
11292
0
           "Bad modifiers used with 'd'!");
11293
0
    if (HowLong == 1)
11294
0
      Type = Context.LongDoubleTy;
11295
0
    else if (HowLong == 2)
11296
0
      Type = Context.Float128Ty;
11297
0
    else
11298
0
      Type = Context.DoubleTy;
11299
0
    break;
11300
0
  case 's':
11301
0
    assert(HowLong == 0 && "Bad modifiers used with 's'!");
11302
0
    if (Unsigned)
11303
0
      Type = Context.UnsignedShortTy;
11304
0
    else
11305
0
      Type = Context.ShortTy;
11306
0
    break;
11307
0
  case 'i':
11308
0
    if (HowLong == 3)
11309
0
      Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
11310
0
    else if (HowLong == 2)
11311
0
      Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
11312
0
    else if (HowLong == 1)
11313
0
      Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
11314
0
    else
11315
0
      Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
11316
0
    break;
11317
0
  case 'c':
11318
0
    assert(HowLong == 0 && "Bad modifiers used with 'c'!");
11319
0
    if (Signed)
11320
0
      Type = Context.SignedCharTy;
11321
0
    else if (Unsigned)
11322
0
      Type = Context.UnsignedCharTy;
11323
0
    else
11324
0
      Type = Context.CharTy;
11325
0
    break;
11326
0
  case 'b': // boolean
11327
0
    assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
11328
0
    Type = Context.BoolTy;
11329
0
    break;
11330
0
  case 'z':  // size_t.
11331
0
    assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
11332
0
    Type = Context.getSizeType();
11333
0
    break;
11334
0
  case 'w':  // wchar_t.
11335
0
    assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
11336
0
    Type = Context.getWideCharType();
11337
0
    break;
11338
0
  case 'F':
11339
0
    Type = Context.getCFConstantStringType();
11340
0
    break;
11341
0
  case 'G':
11342
0
    Type = Context.getObjCIdType();
11343
0
    break;
11344
0
  case 'H':
11345
0
    Type = Context.getObjCSelType();
11346
0
    break;
11347
0
  case 'M':
11348
0
    Type = Context.getObjCSuperType();
11349
0
    break;
11350
0
  case 'a':
11351
0
    Type = Context.getBuiltinVaListType();
11352
0
    assert(!Type.isNull() && "builtin va list type not initialized!");
11353
0
    break;
11354
0
  case 'A':
11355
    // This is a "reference" to a va_list; however, what exactly
11356
    // this means depends on how va_list is defined. There are two
11357
    // different kinds of va_list: ones passed by value, and ones
11358
    // passed by reference.  An example of a by-value va_list is
11359
    // x86, where va_list is a char*. An example of by-ref va_list
11360
    // is x86-64, where va_list is a __va_list_tag[1]. For x86,
11361
    // we want this argument to be a char*&; for x86-64, we want
11362
    // it to be a __va_list_tag*.
11363
0
    Type = Context.getBuiltinVaListType();
11364
0
    assert(!Type.isNull() && "builtin va list type not initialized!");
11365
0
    if (Type->isArrayType())
11366
0
      Type = Context.getArrayDecayedType(Type);
11367
0
    else
11368
0
      Type = Context.getLValueReferenceType(Type);
11369
0
    break;
11370
0
  case 'q': {
11371
0
    char *End;
11372
0
    unsigned NumElements = strtoul(Str, &End, 10);
11373
0
    assert(End != Str && "Missing vector size");
11374
0
    Str = End;
11375
11376
0
    QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
11377
0
                                             RequiresICE, false);
11378
0
    assert(!RequiresICE && "Can't require vector ICE");
11379
11380
0
    Type = Context.getScalableVectorType(ElementType, NumElements);
11381
0
    break;
11382
0
  }
11383
0
  case 'Q': {
11384
0
    switch (*Str++) {
11385
0
    case 'a': {
11386
0
      Type = Context.SveCountTy;
11387
0
      break;
11388
0
    }
11389
0
    default:
11390
0
      llvm_unreachable("Unexpected target builtin type");
11391
0
    }
11392
0
    break;
11393
0
  }
11394
0
  case 'V': {
11395
0
    char *End;
11396
0
    unsigned NumElements = strtoul(Str, &End, 10);
11397
0
    assert(End != Str && "Missing vector size");
11398
0
    Str = End;
11399
11400
0
    QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
11401
0
                                             RequiresICE, false);
11402
0
    assert(!RequiresICE && "Can't require vector ICE");
11403
11404
    // TODO: No way to make AltiVec vectors in builtins yet.
11405
0
    Type = Context.getVectorType(ElementType, NumElements, VectorKind::Generic);
11406
0
    break;
11407
0
  }
11408
0
  case 'E': {
11409
0
    char *End;
11410
11411
0
    unsigned NumElements = strtoul(Str, &End, 10);
11412
0
    assert(End != Str && "Missing vector size");
11413
11414
0
    Str = End;
11415
11416
0
    QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
11417
0
                                             false);
11418
0
    Type = Context.getExtVectorType(ElementType, NumElements);
11419
0
    break;
11420
0
  }
11421
0
  case 'X': {
11422
0
    QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
11423
0
                                             false);
11424
0
    assert(!RequiresICE && "Can't require complex ICE");
11425
0
    Type = Context.getComplexType(ElementType);
11426
0
    break;
11427
0
  }
11428
0
  case 'Y':
11429
0
    Type = Context.getPointerDiffType();
11430
0
    break;
11431
0
  case 'P':
11432
0
    Type = Context.getFILEType();
11433
0
    if (Type.isNull()) {
11434
0
      Error = ASTContext::GE_Missing_stdio;
11435
0
      return {};
11436
0
    }
11437
0
    break;
11438
0
  case 'J':
11439
0
    if (Signed)
11440
0
      Type = Context.getsigjmp_bufType();
11441
0
    else
11442
0
      Type = Context.getjmp_bufType();
11443
11444
0
    if (Type.isNull()) {
11445
0
      Error = ASTContext::GE_Missing_setjmp;
11446
0
      return {};
11447
0
    }
11448
0
    break;
11449
0
  case 'K':
11450
0
    assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
11451
0
    Type = Context.getucontext_tType();
11452
11453
0
    if (Type.isNull()) {
11454
0
      Error = ASTContext::GE_Missing_ucontext;
11455
0
      return {};
11456
0
    }
11457
0
    break;
11458
0
  case 'p':
11459
0
    Type = Context.getProcessIDType();
11460
0
    break;
11461
0
  }
11462
11463
  // If there are modifiers and if we're allowed to parse them, go for it.
11464
0
  Done = !AllowTypeModifiers;
11465
0
  while (!Done) {
11466
0
    switch (char c = *Str++) {
11467
0
    default: Done = true; --Str; break;
11468
0
    case '*':
11469
0
    case '&': {
11470
      // Both pointers and references can have their pointee types
11471
      // qualified with an address space.
11472
0
      char *End;
11473
0
      unsigned AddrSpace = strtoul(Str, &End, 10);
11474
0
      if (End != Str) {
11475
        // Note AddrSpace == 0 is not the same as an unspecified address space.
11476
0
        Type = Context.getAddrSpaceQualType(
11477
0
          Type,
11478
0
          Context.getLangASForBuiltinAddressSpace(AddrSpace));
11479
0
        Str = End;
11480
0
      }
11481
0
      if (c == '*')
11482
0
        Type = Context.getPointerType(Type);
11483
0
      else
11484
0
        Type = Context.getLValueReferenceType(Type);
11485
0
      break;
11486
0
    }
11487
    // FIXME: There's no way to have a built-in with an rvalue ref arg.
11488
0
    case 'C':
11489
0
      Type = Type.withConst();
11490
0
      break;
11491
0
    case 'D':
11492
0
      Type = Context.getVolatileType(Type);
11493
0
      break;
11494
0
    case 'R':
11495
0
      Type = Type.withRestrict();
11496
0
      break;
11497
0
    }
11498
0
  }
11499
11500
0
  assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
11501
0
         "Integer constant 'I' type must be an integer");
11502
11503
0
  return Type;
11504
0
}
11505
11506
// On some targets such as PowerPC, some of the builtins are defined with custom
11507
// type descriptors for target-dependent types. These descriptors are decoded in
11508
// other functions, but it may be useful to be able to fall back to default
11509
// descriptor decoding to define builtins mixing target-dependent and target-
11510
// independent types. This function allows decoding one type descriptor with
11511
// default decoding.
11512
QualType ASTContext::DecodeTypeStr(const char *&Str, const ASTContext &Context,
11513
                                   GetBuiltinTypeError &Error, bool &RequireICE,
11514
0
                                   bool AllowTypeModifiers) const {
11515
0
  return DecodeTypeFromStr(Str, Context, Error, RequireICE, AllowTypeModifiers);
11516
0
}
11517
11518
/// GetBuiltinType - Return the type for the specified builtin.
11519
QualType ASTContext::GetBuiltinType(unsigned Id,
11520
                                    GetBuiltinTypeError &Error,
11521
0
                                    unsigned *IntegerConstantArgs) const {
11522
0
  const char *TypeStr = BuiltinInfo.getTypeString(Id);
11523
0
  if (TypeStr[0] == '\0') {
11524
0
    Error = GE_Missing_type;
11525
0
    return {};
11526
0
  }
11527
11528
0
  SmallVector<QualType, 8> ArgTypes;
11529
11530
0
  bool RequiresICE = false;
11531
0
  Error = GE_None;
11532
0
  QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
11533
0
                                       RequiresICE, true);
11534
0
  if (Error != GE_None)
11535
0
    return {};
11536
11537
0
  assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
11538
11539
0
  while (TypeStr[0] && TypeStr[0] != '.') {
11540
0
    QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
11541
0
    if (Error != GE_None)
11542
0
      return {};
11543
11544
    // If this argument is required to be an IntegerConstantExpression and the
11545
    // caller cares, fill in the bitmask we return.
11546
0
    if (RequiresICE && IntegerConstantArgs)
11547
0
      *IntegerConstantArgs |= 1 << ArgTypes.size();
11548
11549
    // Do array -> pointer decay.  The builtin should use the decayed type.
11550
0
    if (Ty->isArrayType())
11551
0
      Ty = getArrayDecayedType(Ty);
11552
11553
0
    ArgTypes.push_back(Ty);
11554
0
  }
11555
11556
0
  if (Id == Builtin::BI__GetExceptionInfo)
11557
0
    return {};
11558
11559
0
  assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
11560
0
         "'.' should only occur at end of builtin type list!");
11561
11562
0
  bool Variadic = (TypeStr[0] == '.');
11563
11564
0
  FunctionType::ExtInfo EI(getDefaultCallingConvention(
11565
0
      Variadic, /*IsCXXMethod=*/false, /*IsBuiltin=*/true));
11566
0
  if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
11567
11568
11569
  // We really shouldn't be making a no-proto type here.
11570
0
  if (ArgTypes.empty() && Variadic && !getLangOpts().requiresStrictPrototypes())
11571
0
    return getFunctionNoProtoType(ResType, EI);
11572
11573
0
  FunctionProtoType::ExtProtoInfo EPI;
11574
0
  EPI.ExtInfo = EI;
11575
0
  EPI.Variadic = Variadic;
11576
0
  if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id))
11577
0
    EPI.ExceptionSpec.Type =
11578
0
        getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
11579
11580
0
  return getFunctionType(ResType, ArgTypes, EPI);
11581
0
}
11582
11583
static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
11584
0
                                             const FunctionDecl *FD) {
11585
0
  if (!FD->isExternallyVisible())
11586
0
    return GVA_Internal;
11587
11588
  // Non-user-provided functions get emitted as weak definitions with every
11589
  // use, no matter whether they've been explicitly instantiated etc.
11590
0
  if (!FD->isUserProvided())
11591
0
    return GVA_DiscardableODR;
11592
11593
0
  GVALinkage External;
11594
0
  switch (FD->getTemplateSpecializationKind()) {
11595
0
  case TSK_Undeclared:
11596
0
  case TSK_ExplicitSpecialization:
11597
0
    External = GVA_StrongExternal;
11598
0
    break;
11599
11600
0
  case TSK_ExplicitInstantiationDefinition:
11601
0
    return GVA_StrongODR;
11602
11603
  // C++11 [temp.explicit]p10:
11604
  //   [ Note: The intent is that an inline function that is the subject of
11605
  //   an explicit instantiation declaration will still be implicitly
11606
  //   instantiated when used so that the body can be considered for
11607
  //   inlining, but that no out-of-line copy of the inline function would be
11608
  //   generated in the translation unit. -- end note ]
11609
0
  case TSK_ExplicitInstantiationDeclaration:
11610
0
    return GVA_AvailableExternally;
11611
11612
0
  case TSK_ImplicitInstantiation:
11613
0
    External = GVA_DiscardableODR;
11614
0
    break;
11615
0
  }
11616
11617
0
  if (!FD->isInlined())
11618
0
    return External;
11619
11620
0
  if ((!Context.getLangOpts().CPlusPlus &&
11621
0
       !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
11622
0
       !FD->hasAttr<DLLExportAttr>()) ||
11623
0
      FD->hasAttr<GNUInlineAttr>()) {
11624
    // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
11625
11626
    // GNU or C99 inline semantics. Determine whether this symbol should be
11627
    // externally visible.
11628
0
    if (FD->isInlineDefinitionExternallyVisible())
11629
0
      return External;
11630
11631
    // C99 inline semantics, where the symbol is not externally visible.
11632
0
    return GVA_AvailableExternally;
11633
0
  }
11634
11635
  // Functions specified with extern and inline in -fms-compatibility mode
11636
  // forcibly get emitted.  While the body of the function cannot be later
11637
  // replaced, the function definition cannot be discarded.
11638
0
  if (FD->isMSExternInline())
11639
0
    return GVA_StrongODR;
11640
11641
0
  if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
11642
0
      isa<CXXConstructorDecl>(FD) &&
11643
0
      cast<CXXConstructorDecl>(FD)->isInheritingConstructor())
11644
    // Our approach to inheriting constructors is fundamentally different from
11645
    // that used by the MS ABI, so keep our inheriting constructor thunks
11646
    // internal rather than trying to pick an unambiguous mangling for them.
11647
0
    return GVA_Internal;
11648
11649
0
  return GVA_DiscardableODR;
11650
0
}
11651
11652
static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context,
11653
889
                                                const Decl *D, GVALinkage L) {
11654
  // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
11655
  // dllexport/dllimport on inline functions.
11656
889
  if (D->hasAttr<DLLImportAttr>()) {
11657
0
    if (L == GVA_DiscardableODR || L == GVA_StrongODR)
11658
0
      return GVA_AvailableExternally;
11659
889
  } else if (D->hasAttr<DLLExportAttr>()) {
11660
0
    if (L == GVA_DiscardableODR)
11661
0
      return GVA_StrongODR;
11662
889
  } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice) {
11663
    // Device-side functions with __global__ attribute must always be
11664
    // visible externally so they can be launched from host.
11665
0
    if (D->hasAttr<CUDAGlobalAttr>() &&
11666
0
        (L == GVA_DiscardableODR || L == GVA_Internal))
11667
0
      return GVA_StrongODR;
11668
    // Single source offloading languages like CUDA/HIP need to be able to
11669
    // access static device variables from host code of the same compilation
11670
    // unit. This is done by externalizing the static variable with a shared
11671
    // name between the host and device compilation which is the same for the
11672
    // same compilation unit whereas different among different compilation
11673
    // units.
11674
0
    if (Context.shouldExternalize(D))
11675
0
      return GVA_StrongExternal;
11676
0
  }
11677
889
  return L;
11678
889
}
11679
11680
/// Adjust the GVALinkage for a declaration based on what an external AST source
11681
/// knows about whether there can be other definitions of this declaration.
11682
static GVALinkage
11683
adjustGVALinkageForExternalDefinitionKind(const ASTContext &Ctx, const Decl *D,
11684
889
                                          GVALinkage L) {
11685
889
  ExternalASTSource *Source = Ctx.getExternalSource();
11686
889
  if (!Source)
11687
889
    return L;
11688
11689
0
  switch (Source->hasExternalDefinitions(D)) {
11690
0
  case ExternalASTSource::EK_Never:
11691
    // Other translation units rely on us to provide the definition.
11692
0
    if (L == GVA_DiscardableODR)
11693
0
      return GVA_StrongODR;
11694
0
    break;
11695
11696
0
  case ExternalASTSource::EK_Always:
11697
0
    return GVA_AvailableExternally;
11698
11699
0
  case ExternalASTSource::EK_ReplyHazy:
11700
0
    break;
11701
0
  }
11702
0
  return L;
11703
0
}
11704
11705
0
GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
11706
0
  return adjustGVALinkageForExternalDefinitionKind(*this, FD,
11707
0
           adjustGVALinkageForAttributes(*this, FD,
11708
0
             basicGVALinkageForFunction(*this, FD)));
11709
0
}
11710
11711
static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
11712
889
                                             const VarDecl *VD) {
11713
  // As an extension for interactive REPLs, make sure constant variables are
11714
  // only emitted once instead of LinkageComputer::getLVForNamespaceScopeDecl
11715
  // marking them as internal.
11716
889
  if (Context.getLangOpts().CPlusPlus &&
11717
889
      Context.getLangOpts().IncrementalExtensions &&
11718
889
      VD->getType().isConstQualified() &&
11719
889
      !VD->getType().isVolatileQualified() && !VD->isInline() &&
11720
889
      !isa<VarTemplateSpecializationDecl>(VD) && !VD->getDescribedVarTemplate())
11721
0
    return GVA_DiscardableODR;
11722
11723
889
  if (!VD->isExternallyVisible())
11724
0
    return GVA_Internal;
11725
11726
889
  if (VD->isStaticLocal()) {
11727
0
    const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
11728
0
    while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
11729
0
      LexicalContext = LexicalContext->getLexicalParent();
11730
11731
    // ObjC Blocks can create local variables that don't have a FunctionDecl
11732
    // LexicalContext.
11733
0
    if (!LexicalContext)
11734
0
      return GVA_DiscardableODR;
11735
11736
    // Otherwise, let the static local variable inherit its linkage from the
11737
    // nearest enclosing function.
11738
0
    auto StaticLocalLinkage =
11739
0
        Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
11740
11741
    // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
11742
    // be emitted in any object with references to the symbol for the object it
11743
    // contains, whether inline or out-of-line."
11744
    // Similar behavior is observed with MSVC. An alternative ABI could use
11745
    // StrongODR/AvailableExternally to match the function, but none are
11746
    // known/supported currently.
11747
0
    if (StaticLocalLinkage == GVA_StrongODR ||
11748
0
        StaticLocalLinkage == GVA_AvailableExternally)
11749
0
      return GVA_DiscardableODR;
11750
0
    return StaticLocalLinkage;
11751
0
  }
11752
11753
  // MSVC treats in-class initialized static data members as definitions.
11754
  // By giving them non-strong linkage, out-of-line definitions won't
11755
  // cause link errors.
11756
889
  if (Context.isMSStaticDataMemberInlineDefinition(VD))
11757
0
    return GVA_DiscardableODR;
11758
11759
  // Most non-template variables have strong linkage; inline variables are
11760
  // linkonce_odr or (occasionally, for compatibility) weak_odr.
11761
889
  GVALinkage StrongLinkage;
11762
889
  switch (Context.getInlineVariableDefinitionKind(VD)) {
11763
889
  case ASTContext::InlineVariableDefinitionKind::None:
11764
889
    StrongLinkage = GVA_StrongExternal;
11765
889
    break;
11766
0
  case ASTContext::InlineVariableDefinitionKind::Weak:
11767
0
  case ASTContext::InlineVariableDefinitionKind::WeakUnknown:
11768
0
    StrongLinkage = GVA_DiscardableODR;
11769
0
    break;
11770
0
  case ASTContext::InlineVariableDefinitionKind::Strong:
11771
0
    StrongLinkage = GVA_StrongODR;
11772
0
    break;
11773
889
  }
11774
11775
889
  switch (VD->getTemplateSpecializationKind()) {
11776
889
  case TSK_Undeclared:
11777
889
    return StrongLinkage;
11778
11779
0
  case TSK_ExplicitSpecialization:
11780
0
    return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
11781
0
                   VD->isStaticDataMember()
11782
0
               ? GVA_StrongODR
11783
0
               : StrongLinkage;
11784
11785
0
  case TSK_ExplicitInstantiationDefinition:
11786
0
    return GVA_StrongODR;
11787
11788
0
  case TSK_ExplicitInstantiationDeclaration:
11789
0
    return GVA_AvailableExternally;
11790
11791
0
  case TSK_ImplicitInstantiation:
11792
0
    return GVA_DiscardableODR;
11793
889
  }
11794
11795
0
  llvm_unreachable("Invalid Linkage!");
11796
0
}
11797
11798
889
GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) const {
11799
889
  return adjustGVALinkageForExternalDefinitionKind(*this, VD,
11800
889
           adjustGVALinkageForAttributes(*this, VD,
11801
889
             basicGVALinkageForVariable(*this, VD)));
11802
889
}
11803
11804
889
bool ASTContext::DeclMustBeEmitted(const Decl *D) {
11805
889
  if (const auto *VD = dyn_cast<VarDecl>(D)) {
11806
889
    if (!VD->isFileVarDecl())
11807
0
      return false;
11808
    // Global named register variables (GNU extension) are never emitted.
11809
889
    if (VD->getStorageClass() == SC_Register)
11810
0
      return false;
11811
889
    if (VD->getDescribedVarTemplate() ||
11812
889
        isa<VarTemplatePartialSpecializationDecl>(VD))
11813
0
      return false;
11814
889
  } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
11815
    // We never need to emit an uninstantiated function template.
11816
0
    if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
11817
0
      return false;
11818
0
  } else if (isa<PragmaCommentDecl>(D))
11819
0
    return true;
11820
0
  else if (isa<PragmaDetectMismatchDecl>(D))
11821
0
    return true;
11822
0
  else if (isa<OMPRequiresDecl>(D))
11823
0
    return true;
11824
0
  else if (isa<OMPThreadPrivateDecl>(D))
11825
0
    return !D->getDeclContext()->isDependentContext();
11826
0
  else if (isa<OMPAllocateDecl>(D))
11827
0
    return !D->getDeclContext()->isDependentContext();
11828
0
  else if (isa<OMPDeclareReductionDecl>(D) || isa<OMPDeclareMapperDecl>(D))
11829
0
    return !D->getDeclContext()->isDependentContext();
11830
0
  else if (isa<ImportDecl>(D))
11831
0
    return true;
11832
0
  else
11833
0
    return false;
11834
11835
  // If this is a member of a class template, we do not need to emit it.
11836
889
  if (D->getDeclContext()->isDependentContext())
11837
0
    return false;
11838
11839
  // Weak references don't produce any output by themselves.
11840
889
  if (D->hasAttr<WeakRefAttr>())
11841
0
    return false;
11842
11843
  // Aliases and used decls are required.
11844
889
  if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
11845
0
    return true;
11846
11847
889
  if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
11848
    // Forward declarations aren't required.
11849
0
    if (!FD->doesThisDeclarationHaveABody())
11850
0
      return FD->doesDeclarationForceExternallyVisibleDefinition();
11851
11852
    // Constructors and destructors are required.
11853
0
    if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
11854
0
      return true;
11855
11856
    // The key function for a class is required.  This rule only comes
11857
    // into play when inline functions can be key functions, though.
11858
0
    if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
11859
0
      if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
11860
0
        const CXXRecordDecl *RD = MD->getParent();
11861
0
        if (MD->isOutOfLine() && RD->isDynamicClass()) {
11862
0
          const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
11863
0
          if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
11864
0
            return true;
11865
0
        }
11866
0
      }
11867
0
    }
11868
11869
0
    GVALinkage Linkage = GetGVALinkageForFunction(FD);
11870
11871
    // static, static inline, always_inline, and extern inline functions can
11872
    // always be deferred.  Normal inline functions can be deferred in C99/C++.
11873
    // Implicit template instantiations can also be deferred in C++.
11874
0
    return !isDiscardableGVALinkage(Linkage);
11875
0
  }
11876
11877
889
  const auto *VD = cast<VarDecl>(D);
11878
889
  assert(VD->isFileVarDecl() && "Expected file scoped var");
11879
11880
  // If the decl is marked as `declare target to`, it should be emitted for the
11881
  // host and for the device.
11882
889
  if (LangOpts.OpenMP &&
11883
889
      OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
11884
0
    return true;
11885
11886
889
  if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
11887
889
      !isMSStaticDataMemberInlineDefinition(VD))
11888
0
    return false;
11889
11890
  // Variables in other module units shouldn't be forced to be emitted.
11891
889
  if (VD->isInAnotherModuleUnit())
11892
0
    return false;
11893
11894
  // Variables that can be needed in other TUs are required.
11895
889
  auto Linkage = GetGVALinkageForVariable(VD);
11896
889
  if (!isDiscardableGVALinkage(Linkage))
11897
889
    return true;
11898
11899
  // We never need to emit a variable that is available in another TU.
11900
0
  if (Linkage == GVA_AvailableExternally)
11901
0
    return false;
11902
11903
  // Variables that have destruction with side-effects are required.
11904
0
  if (VD->needsDestruction(*this))
11905
0
    return true;
11906
11907
  // Variables that have initialization with side-effects are required.
11908
0
  if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
11909
      // We can get a value-dependent initializer during error recovery.
11910
0
      (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
11911
0
    return true;
11912
11913
  // Likewise, variables with tuple-like bindings are required if their
11914
  // bindings have side-effects.
11915
0
  if (const auto *DD = dyn_cast<DecompositionDecl>(VD))
11916
0
    for (const auto *BD : DD->bindings())
11917
0
      if (const auto *BindingVD = BD->getHoldingVar())
11918
0
        if (DeclMustBeEmitted(BindingVD))
11919
0
          return true;
11920
11921
0
  return false;
11922
0
}
11923
11924
void ASTContext::forEachMultiversionedFunctionVersion(
11925
    const FunctionDecl *FD,
11926
0
    llvm::function_ref<void(FunctionDecl *)> Pred) const {
11927
0
  assert(FD->isMultiVersion() && "Only valid for multiversioned functions");
11928
0
  llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls;
11929
0
  FD = FD->getMostRecentDecl();
11930
  // FIXME: The order of traversal here matters and depends on the order of
11931
  // lookup results, which happens to be (mostly) oldest-to-newest, but we
11932
  // shouldn't rely on that.
11933
0
  for (auto *CurDecl :
11934
0
       FD->getDeclContext()->getRedeclContext()->lookup(FD->getDeclName())) {
11935
0
    FunctionDecl *CurFD = CurDecl->getAsFunction()->getMostRecentDecl();
11936
0
    if (CurFD && hasSameType(CurFD->getType(), FD->getType()) &&
11937
0
        !SeenDecls.contains(CurFD)) {
11938
0
      SeenDecls.insert(CurFD);
11939
0
      Pred(CurFD);
11940
0
    }
11941
0
  }
11942
0
}
11943
11944
CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
11945
                                                    bool IsCXXMethod,
11946
24
                                                    bool IsBuiltin) const {
11947
  // Pass through to the C++ ABI object
11948
24
  if (IsCXXMethod)
11949
0
    return ABI->getDefaultMethodCallConv(IsVariadic);
11950
11951
  // Builtins ignore user-specified default calling convention and remain the
11952
  // Target's default calling convention.
11953
24
  if (!IsBuiltin) {
11954
24
    switch (LangOpts.getDefaultCallingConv()) {
11955
24
    case LangOptions::DCC_None:
11956
24
      break;
11957
0
    case LangOptions::DCC_CDecl:
11958
0
      return CC_C;
11959
0
    case LangOptions::DCC_FastCall:
11960
0
      if (getTargetInfo().hasFeature("sse2") && !IsVariadic)
11961
0
        return CC_X86FastCall;
11962
0
      break;
11963
0
    case LangOptions::DCC_StdCall:
11964
0
      if (!IsVariadic)
11965
0
        return CC_X86StdCall;
11966
0
      break;
11967
0
    case LangOptions::DCC_VectorCall:
11968
      // __vectorcall cannot be applied to variadic functions.
11969
0
      if (!IsVariadic)
11970
0
        return CC_X86VectorCall;
11971
0
      break;
11972
0
    case LangOptions::DCC_RegCall:
11973
      // __regcall cannot be applied to variadic functions.
11974
0
      if (!IsVariadic)
11975
0
        return CC_X86RegCall;
11976
0
      break;
11977
0
    case LangOptions::DCC_RtdCall:
11978
0
      if (!IsVariadic)
11979
0
        return CC_M68kRTD;
11980
0
      break;
11981
24
    }
11982
24
  }
11983
24
  return Target->getDefaultCallingConv();
11984
24
}
11985
11986
0
bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
11987
  // Pass through to the C++ ABI object
11988
0
  return ABI->isNearlyEmpty(RD);
11989
0
}
11990
11991
46
VTableContextBase *ASTContext::getVTableContext() {
11992
46
  if (!VTContext.get()) {
11993
46
    auto ABI = Target->getCXXABI();
11994
46
    if (ABI.isMicrosoft())
11995
0
      VTContext.reset(new MicrosoftVTableContext(*this));
11996
46
    else {
11997
46
      auto ComponentLayout = getLangOpts().RelativeCXXABIVTables
11998
46
                                 ? ItaniumVTableContext::Relative
11999
46
                                 : ItaniumVTableContext::Pointer;
12000
46
      VTContext.reset(new ItaniumVTableContext(*this, ComponentLayout));
12001
46
    }
12002
46
  }
12003
46
  return VTContext.get();
12004
46
}
12005
12006
69
MangleContext *ASTContext::createMangleContext(const TargetInfo *T) {
12007
69
  if (!T)
12008
69
    T = Target;
12009
69
  switch (T->getCXXABI().getKind()) {
12010
0
  case TargetCXXABI::AppleARM64:
12011
0
  case TargetCXXABI::Fuchsia:
12012
0
  case TargetCXXABI::GenericAArch64:
12013
69
  case TargetCXXABI::GenericItanium:
12014
69
  case TargetCXXABI::GenericARM:
12015
69
  case TargetCXXABI::GenericMIPS:
12016
69
  case TargetCXXABI::iOS:
12017
69
  case TargetCXXABI::WebAssembly:
12018
69
  case TargetCXXABI::WatchOS:
12019
69
  case TargetCXXABI::XL:
12020
69
    return ItaniumMangleContext::create(*this, getDiagnostics());
12021
0
  case TargetCXXABI::Microsoft:
12022
0
    return MicrosoftMangleContext::create(*this, getDiagnostics());
12023
69
  }
12024
0
  llvm_unreachable("Unsupported ABI");
12025
0
}
12026
12027
0
MangleContext *ASTContext::createDeviceMangleContext(const TargetInfo &T) {
12028
0
  assert(T.getCXXABI().getKind() != TargetCXXABI::Microsoft &&
12029
0
         "Device mangle context does not support Microsoft mangling.");
12030
0
  switch (T.getCXXABI().getKind()) {
12031
0
  case TargetCXXABI::AppleARM64:
12032
0
  case TargetCXXABI::Fuchsia:
12033
0
  case TargetCXXABI::GenericAArch64:
12034
0
  case TargetCXXABI::GenericItanium:
12035
0
  case TargetCXXABI::GenericARM:
12036
0
  case TargetCXXABI::GenericMIPS:
12037
0
  case TargetCXXABI::iOS:
12038
0
  case TargetCXXABI::WebAssembly:
12039
0
  case TargetCXXABI::WatchOS:
12040
0
  case TargetCXXABI::XL:
12041
0
    return ItaniumMangleContext::create(
12042
0
        *this, getDiagnostics(),
12043
0
        [](ASTContext &, const NamedDecl *ND) -> std::optional<unsigned> {
12044
0
          if (const auto *RD = dyn_cast<CXXRecordDecl>(ND))
12045
0
            return RD->getDeviceLambdaManglingNumber();
12046
0
          return std::nullopt;
12047
0
        },
12048
0
        /*IsAux=*/true);
12049
0
  case TargetCXXABI::Microsoft:
12050
0
    return MicrosoftMangleContext::create(*this, getDiagnostics(),
12051
0
                                          /*IsAux=*/true);
12052
0
  }
12053
0
  llvm_unreachable("Unsupported ABI");
12054
0
}
12055
12056
23
CXXABI::~CXXABI() = default;
12057
12058
0
size_t ASTContext::getSideTableAllocatedMemory() const {
12059
0
  return ASTRecordLayouts.getMemorySize() +
12060
0
         llvm::capacity_in_bytes(ObjCLayouts) +
12061
0
         llvm::capacity_in_bytes(KeyFunctions) +
12062
0
         llvm::capacity_in_bytes(ObjCImpls) +
12063
0
         llvm::capacity_in_bytes(BlockVarCopyInits) +
12064
0
         llvm::capacity_in_bytes(DeclAttrs) +
12065
0
         llvm::capacity_in_bytes(TemplateOrInstantiation) +
12066
0
         llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
12067
0
         llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
12068
0
         llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
12069
0
         llvm::capacity_in_bytes(OverriddenMethods) +
12070
0
         llvm::capacity_in_bytes(Types) +
12071
0
         llvm::capacity_in_bytes(VariableArrayTypes);
12072
0
}
12073
12074
/// getIntTypeForBitwidth -
12075
/// sets integer QualTy according to specified details:
12076
/// bitwidth, signed/unsigned.
12077
/// Returns empty type if there is no appropriate target types.
12078
QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
12079
0
                                           unsigned Signed) const {
12080
0
  TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
12081
0
  CanQualType QualTy = getFromTargetType(Ty);
12082
0
  if (!QualTy && DestWidth == 128)
12083
0
    return Signed ? Int128Ty : UnsignedInt128Ty;
12084
0
  return QualTy;
12085
0
}
12086
12087
/// getRealTypeForBitwidth -
12088
/// sets floating point QualTy according to specified bitwidth.
12089
/// Returns empty type if there is no appropriate target types.
12090
QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth,
12091
0
                                            FloatModeKind ExplicitType) const {
12092
0
  FloatModeKind Ty =
12093
0
      getTargetInfo().getRealTypeByWidth(DestWidth, ExplicitType);
12094
0
  switch (Ty) {
12095
0
  case FloatModeKind::Half:
12096
0
    return HalfTy;
12097
0
  case FloatModeKind::Float:
12098
0
    return FloatTy;
12099
0
  case FloatModeKind::Double:
12100
0
    return DoubleTy;
12101
0
  case FloatModeKind::LongDouble:
12102
0
    return LongDoubleTy;
12103
0
  case FloatModeKind::Float128:
12104
0
    return Float128Ty;
12105
0
  case FloatModeKind::Ibm128:
12106
0
    return Ibm128Ty;
12107
0
  case FloatModeKind::NoFloat:
12108
0
    return {};
12109
0
  }
12110
12111
0
  llvm_unreachable("Unhandled TargetInfo::RealType value");
12112
0
}
12113
12114
0
void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
12115
0
  if (Number > 1)
12116
0
    MangleNumbers[ND] = Number;
12117
0
}
12118
12119
unsigned ASTContext::getManglingNumber(const NamedDecl *ND,
12120
0
                                       bool ForAuxTarget) const {
12121
0
  auto I = MangleNumbers.find(ND);
12122
0
  unsigned Res = I != MangleNumbers.end() ? I->second : 1;
12123
  // CUDA/HIP host compilation encodes host and device mangling numbers
12124
  // as lower and upper half of 32 bit integer.
12125
0
  if (LangOpts.CUDA && !LangOpts.CUDAIsDevice) {
12126
0
    Res = ForAuxTarget ? Res >> 16 : Res & 0xFFFF;
12127
0
  } else {
12128
0
    assert(!ForAuxTarget && "Only CUDA/HIP host compilation supports mangling "
12129
0
                            "number for aux target");
12130
0
  }
12131
0
  return Res > 1 ? Res : 1;
12132
0
}
12133
12134
0
void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
12135
0
  if (Number > 1)
12136
0
    StaticLocalNumbers[VD] = Number;
12137
0
}
12138
12139
0
unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
12140
0
  auto I = StaticLocalNumbers.find(VD);
12141
0
  return I != StaticLocalNumbers.end() ? I->second : 1;
12142
0
}
12143
12144
MangleNumberingContext &
12145
0
ASTContext::getManglingNumberContext(const DeclContext *DC) {
12146
0
  assert(LangOpts.CPlusPlus);  // We don't need mangling numbers for plain C.
12147
0
  std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
12148
0
  if (!MCtx)
12149
0
    MCtx = createMangleNumberingContext();
12150
0
  return *MCtx;
12151
0
}
12152
12153
MangleNumberingContext &
12154
0
ASTContext::getManglingNumberContext(NeedExtraManglingDecl_t, const Decl *D) {
12155
0
  assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
12156
0
  std::unique_ptr<MangleNumberingContext> &MCtx =
12157
0
      ExtraMangleNumberingContexts[D];
12158
0
  if (!MCtx)
12159
0
    MCtx = createMangleNumberingContext();
12160
0
  return *MCtx;
12161
0
}
12162
12163
std::unique_ptr<MangleNumberingContext>
12164
0
ASTContext::createMangleNumberingContext() const {
12165
0
  return ABI->createMangleNumberingContext();
12166
0
}
12167
12168
const CXXConstructorDecl *
12169
0
ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
12170
0
  return ABI->getCopyConstructorForExceptionObject(
12171
0
      cast<CXXRecordDecl>(RD->getFirstDecl()));
12172
0
}
12173
12174
void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
12175
0
                                                      CXXConstructorDecl *CD) {
12176
0
  return ABI->addCopyConstructorForExceptionObject(
12177
0
      cast<CXXRecordDecl>(RD->getFirstDecl()),
12178
0
      cast<CXXConstructorDecl>(CD->getFirstDecl()));
12179
0
}
12180
12181
void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD,
12182
0
                                                 TypedefNameDecl *DD) {
12183
0
  return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
12184
0
}
12185
12186
TypedefNameDecl *
12187
0
ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) {
12188
0
  return ABI->getTypedefNameForUnnamedTagDecl(TD);
12189
0
}
12190
12191
void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD,
12192
0
                                                DeclaratorDecl *DD) {
12193
0
  return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
12194
0
}
12195
12196
0
DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) {
12197
0
  return ABI->getDeclaratorForUnnamedTagDecl(TD);
12198
0
}
12199
12200
0
void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
12201
0
  ParamIndices[D] = index;
12202
0
}
12203
12204
0
unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
12205
0
  ParameterIndexTable::const_iterator I = ParamIndices.find(D);
12206
0
  assert(I != ParamIndices.end() &&
12207
0
         "ParmIndices lacks entry set by ParmVarDecl");
12208
0
  return I->second;
12209
0
}
12210
12211
QualType ASTContext::getStringLiteralArrayType(QualType EltTy,
12212
1
                                               unsigned Length) const {
12213
  // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
12214
1
  if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
12215
1
    EltTy = EltTy.withConst();
12216
12217
1
  EltTy = adjustStringLiteralBaseType(EltTy);
12218
12219
  // Get an array type for the string, according to C99 6.4.5. This includes
12220
  // the null terminator character.
12221
1
  return getConstantArrayType(EltTy, llvm::APInt(32, Length + 1), nullptr,
12222
1
                              ArraySizeModifier::Normal, /*IndexTypeQuals*/ 0);
12223
1
}
12224
12225
StringLiteral *
12226
0
ASTContext::getPredefinedStringLiteralFromCache(StringRef Key) const {
12227
0
  StringLiteral *&Result = StringLiteralCache[Key];
12228
0
  if (!Result)
12229
0
    Result = StringLiteral::Create(
12230
0
        *this, Key, StringLiteralKind::Ordinary,
12231
0
        /*Pascal*/ false, getStringLiteralArrayType(CharTy, Key.size()),
12232
0
        SourceLocation());
12233
0
  return Result;
12234
0
}
12235
12236
MSGuidDecl *
12237
0
ASTContext::getMSGuidDecl(MSGuidDecl::Parts Parts) const {
12238
0
  assert(MSGuidTagDecl && "building MS GUID without MS extensions?");
12239
12240
0
  llvm::FoldingSetNodeID ID;
12241
0
  MSGuidDecl::Profile(ID, Parts);
12242
12243
0
  void *InsertPos;
12244
0
  if (MSGuidDecl *Existing = MSGuidDecls.FindNodeOrInsertPos(ID, InsertPos))
12245
0
    return Existing;
12246
12247
0
  QualType GUIDType = getMSGuidType().withConst();
12248
0
  MSGuidDecl *New = MSGuidDecl::Create(*this, GUIDType, Parts);
12249
0
  MSGuidDecls.InsertNode(New, InsertPos);
12250
0
  return New;
12251
0
}
12252
12253
UnnamedGlobalConstantDecl *
12254
ASTContext::getUnnamedGlobalConstantDecl(QualType Ty,
12255
0
                                         const APValue &APVal) const {
12256
0
  llvm::FoldingSetNodeID ID;
12257
0
  UnnamedGlobalConstantDecl::Profile(ID, Ty, APVal);
12258
12259
0
  void *InsertPos;
12260
0
  if (UnnamedGlobalConstantDecl *Existing =
12261
0
          UnnamedGlobalConstantDecls.FindNodeOrInsertPos(ID, InsertPos))
12262
0
    return Existing;
12263
12264
0
  UnnamedGlobalConstantDecl *New =
12265
0
      UnnamedGlobalConstantDecl::Create(*this, Ty, APVal);
12266
0
  UnnamedGlobalConstantDecls.InsertNode(New, InsertPos);
12267
0
  return New;
12268
0
}
12269
12270
TemplateParamObjectDecl *
12271
0
ASTContext::getTemplateParamObjectDecl(QualType T, const APValue &V) const {
12272
0
  assert(T->isRecordType() && "template param object of unexpected type");
12273
12274
  // C++ [temp.param]p8:
12275
  //   [...] a static storage duration object of type 'const T' [...]
12276
0
  T.addConst();
12277
12278
0
  llvm::FoldingSetNodeID ID;
12279
0
  TemplateParamObjectDecl::Profile(ID, T, V);
12280
12281
0
  void *InsertPos;
12282
0
  if (TemplateParamObjectDecl *Existing =
12283
0
          TemplateParamObjectDecls.FindNodeOrInsertPos(ID, InsertPos))
12284
0
    return Existing;
12285
12286
0
  TemplateParamObjectDecl *New = TemplateParamObjectDecl::Create(*this, T, V);
12287
0
  TemplateParamObjectDecls.InsertNode(New, InsertPos);
12288
0
  return New;
12289
0
}
12290
12291
0
bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
12292
0
  const llvm::Triple &T = getTargetInfo().getTriple();
12293
0
  if (!T.isOSDarwin())
12294
0
    return false;
12295
12296
0
  if (!(T.isiOS() && T.isOSVersionLT(7)) &&
12297
0
      !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
12298
0
    return false;
12299
12300
0
  QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
12301
0
  CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
12302
0
  uint64_t Size = sizeChars.getQuantity();
12303
0
  CharUnits alignChars = getTypeAlignInChars(AtomicTy);
12304
0
  unsigned Align = alignChars.getQuantity();
12305
0
  unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
12306
0
  return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
12307
0
}
12308
12309
bool
12310
ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
12311
0
                                const ObjCMethodDecl *MethodImpl) {
12312
  // No point trying to match an unavailable/deprecated mothod.
12313
0
  if (MethodDecl->hasAttr<UnavailableAttr>()
12314
0
      || MethodDecl->hasAttr<DeprecatedAttr>())
12315
0
    return false;
12316
0
  if (MethodDecl->getObjCDeclQualifier() !=
12317
0
      MethodImpl->getObjCDeclQualifier())
12318
0
    return false;
12319
0
  if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
12320
0
    return false;
12321
12322
0
  if (MethodDecl->param_size() != MethodImpl->param_size())
12323
0
    return false;
12324
12325
0
  for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
12326
0
       IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
12327
0
       EF = MethodDecl->param_end();
12328
0
       IM != EM && IF != EF; ++IM, ++IF) {
12329
0
    const ParmVarDecl *DeclVar = (*IF);
12330
0
    const ParmVarDecl *ImplVar = (*IM);
12331
0
    if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
12332
0
      return false;
12333
0
    if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
12334
0
      return false;
12335
0
  }
12336
12337
0
  return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
12338
0
}
12339
12340
46
uint64_t ASTContext::getTargetNullPointerValue(QualType QT) const {
12341
46
  LangAS AS;
12342
46
  if (QT->getUnqualifiedDesugaredType()->isNullPtrType())
12343
0
    AS = LangAS::Default;
12344
46
  else
12345
46
    AS = QT->getPointeeType().getAddressSpace();
12346
12347
46
  return getTargetInfo().getNullPointerValue(AS);
12348
46
}
12349
12350
92
unsigned ASTContext::getTargetAddressSpace(LangAS AS) const {
12351
92
  return getTargetInfo().getTargetAddressSpace(AS);
12352
92
}
12353
12354
0
bool ASTContext::hasSameExpr(const Expr *X, const Expr *Y) const {
12355
0
  if (X == Y)
12356
0
    return true;
12357
0
  if (!X || !Y)
12358
0
    return false;
12359
0
  llvm::FoldingSetNodeID IDX, IDY;
12360
0
  X->Profile(IDX, *this, /*Canonical=*/true);
12361
0
  Y->Profile(IDY, *this, /*Canonical=*/true);
12362
0
  return IDX == IDY;
12363
0
}
12364
12365
// The getCommon* helpers return, for given 'same' X and Y entities given as
12366
// inputs, another entity which is also the 'same' as the inputs, but which
12367
// is closer to the canonical form of the inputs, each according to a given
12368
// criteria.
12369
// The getCommon*Checked variants are 'null inputs not-allowed' equivalents of
12370
// the regular ones.
12371
12372
0
static Decl *getCommonDecl(Decl *X, Decl *Y) {
12373
0
  if (!declaresSameEntity(X, Y))
12374
0
    return nullptr;
12375
0
  for (const Decl *DX : X->redecls()) {
12376
    // If we reach Y before reaching the first decl, that means X is older.
12377
0
    if (DX == Y)
12378
0
      return X;
12379
    // If we reach the first decl, then Y is older.
12380
0
    if (DX->isFirstDecl())
12381
0
      return Y;
12382
0
  }
12383
0
  llvm_unreachable("Corrupt redecls chain");
12384
0
}
12385
12386
template <class T, std::enable_if_t<std::is_base_of_v<Decl, T>, bool> = true>
12387
0
static T *getCommonDecl(T *X, T *Y) {
12388
0
  return cast_or_null<T>(
12389
0
      getCommonDecl(const_cast<Decl *>(cast_or_null<Decl>(X)),
12390
0
                    const_cast<Decl *>(cast_or_null<Decl>(Y))));
12391
0
}
Unexecuted instantiation: ASTContext.cpp:clang::TemplateTypeParmDecl* getCommonDecl<clang::TemplateTypeParmDecl, true>(clang::TemplateTypeParmDecl*, clang::TemplateTypeParmDecl*)
Unexecuted instantiation: ASTContext.cpp:clang::ConceptDecl* getCommonDecl<clang::ConceptDecl, true>(clang::ConceptDecl*, clang::ConceptDecl*)
Unexecuted instantiation: ASTContext.cpp:clang::TagDecl* getCommonDecl<clang::TagDecl, true>(clang::TagDecl*, clang::TagDecl*)
Unexecuted instantiation: ASTContext.cpp:clang::TypedefNameDecl* getCommonDecl<clang::TypedefNameDecl, true>(clang::TypedefNameDecl*, clang::TypedefNameDecl*)
Unexecuted instantiation: ASTContext.cpp:clang::UsingShadowDecl* getCommonDecl<clang::UsingShadowDecl, true>(clang::UsingShadowDecl*, clang::UsingShadowDecl*)
12392
12393
template <class T, std::enable_if_t<std::is_base_of_v<Decl, T>, bool> = true>
12394
0
static T *getCommonDeclChecked(T *X, T *Y) {
12395
0
  return cast<T>(getCommonDecl(const_cast<Decl *>(cast<Decl>(X)),
12396
0
                               const_cast<Decl *>(cast<Decl>(Y))));
12397
0
}
Unexecuted instantiation: ASTContext.cpp:clang::ConceptDecl* getCommonDeclChecked<clang::ConceptDecl, true>(clang::ConceptDecl*, clang::ConceptDecl*)
Unexecuted instantiation: ASTContext.cpp:clang::CXXRecordDecl* getCommonDeclChecked<clang::CXXRecordDecl, true>(clang::CXXRecordDecl*, clang::CXXRecordDecl*)
12398
12399
static TemplateName getCommonTemplateName(ASTContext &Ctx, TemplateName X,
12400
0
                                          TemplateName Y) {
12401
0
  if (X.getAsVoidPointer() == Y.getAsVoidPointer())
12402
0
    return X;
12403
  // FIXME: There are cases here where we could find a common template name
12404
  //        with more sugar. For example one could be a SubstTemplateTemplate*
12405
  //        replacing the other.
12406
0
  TemplateName CX = Ctx.getCanonicalTemplateName(X);
12407
0
  if (CX.getAsVoidPointer() !=
12408
0
      Ctx.getCanonicalTemplateName(Y).getAsVoidPointer())
12409
0
    return TemplateName();
12410
0
  return CX;
12411
0
}
12412
12413
static TemplateName
12414
0
getCommonTemplateNameChecked(ASTContext &Ctx, TemplateName X, TemplateName Y) {
12415
0
  TemplateName R = getCommonTemplateName(Ctx, X, Y);
12416
0
  assert(R.getAsVoidPointer() != nullptr);
12417
0
  return R;
12418
0
}
12419
12420
static auto getCommonTypes(ASTContext &Ctx, ArrayRef<QualType> Xs,
12421
0
                           ArrayRef<QualType> Ys, bool Unqualified = false) {
12422
0
  assert(Xs.size() == Ys.size());
12423
0
  SmallVector<QualType, 8> Rs(Xs.size());
12424
0
  for (size_t I = 0; I < Rs.size(); ++I)
12425
0
    Rs[I] = Ctx.getCommonSugaredType(Xs[I], Ys[I], Unqualified);
12426
0
  return Rs;
12427
0
}
12428
12429
template <class T>
12430
0
static SourceLocation getCommonAttrLoc(const T *X, const T *Y) {
12431
0
  return X->getAttributeLoc() == Y->getAttributeLoc() ? X->getAttributeLoc()
12432
0
                                                      : SourceLocation();
12433
0
}
Unexecuted instantiation: ASTContext.cpp:clang::SourceLocation getCommonAttrLoc<clang::DependentAddressSpaceType>(clang::DependentAddressSpaceType const*, clang::DependentAddressSpaceType const*)
Unexecuted instantiation: ASTContext.cpp:clang::SourceLocation getCommonAttrLoc<clang::DependentSizedMatrixType>(clang::DependentSizedMatrixType const*, clang::DependentSizedMatrixType const*)
Unexecuted instantiation: ASTContext.cpp:clang::SourceLocation getCommonAttrLoc<clang::DependentSizedExtVectorType>(clang::DependentSizedExtVectorType const*, clang::DependentSizedExtVectorType const*)
Unexecuted instantiation: ASTContext.cpp:clang::SourceLocation getCommonAttrLoc<clang::DependentVectorType>(clang::DependentVectorType const*, clang::DependentVectorType const*)
12434
12435
static TemplateArgument getCommonTemplateArgument(ASTContext &Ctx,
12436
                                                  const TemplateArgument &X,
12437
0
                                                  const TemplateArgument &Y) {
12438
0
  if (X.getKind() != Y.getKind())
12439
0
    return TemplateArgument();
12440
12441
0
  switch (X.getKind()) {
12442
0
  case TemplateArgument::ArgKind::Type:
12443
0
    if (!Ctx.hasSameType(X.getAsType(), Y.getAsType()))
12444
0
      return TemplateArgument();
12445
0
    return TemplateArgument(
12446
0
        Ctx.getCommonSugaredType(X.getAsType(), Y.getAsType()));
12447
0
  case TemplateArgument::ArgKind::NullPtr:
12448
0
    if (!Ctx.hasSameType(X.getNullPtrType(), Y.getNullPtrType()))
12449
0
      return TemplateArgument();
12450
0
    return TemplateArgument(
12451
0
        Ctx.getCommonSugaredType(X.getNullPtrType(), Y.getNullPtrType()),
12452
0
        /*Unqualified=*/true);
12453
0
  case TemplateArgument::ArgKind::Expression:
12454
0
    if (!Ctx.hasSameType(X.getAsExpr()->getType(), Y.getAsExpr()->getType()))
12455
0
      return TemplateArgument();
12456
    // FIXME: Try to keep the common sugar.
12457
0
    return X;
12458
0
  case TemplateArgument::ArgKind::Template: {
12459
0
    TemplateName TX = X.getAsTemplate(), TY = Y.getAsTemplate();
12460
0
    TemplateName CTN = ::getCommonTemplateName(Ctx, TX, TY);
12461
0
    if (!CTN.getAsVoidPointer())
12462
0
      return TemplateArgument();
12463
0
    return TemplateArgument(CTN);
12464
0
  }
12465
0
  case TemplateArgument::ArgKind::TemplateExpansion: {
12466
0
    TemplateName TX = X.getAsTemplateOrTemplatePattern(),
12467
0
                 TY = Y.getAsTemplateOrTemplatePattern();
12468
0
    TemplateName CTN = ::getCommonTemplateName(Ctx, TX, TY);
12469
0
    if (!CTN.getAsVoidPointer())
12470
0
      return TemplateName();
12471
0
    auto NExpX = X.getNumTemplateExpansions();
12472
0
    assert(NExpX == Y.getNumTemplateExpansions());
12473
0
    return TemplateArgument(CTN, NExpX);
12474
0
  }
12475
0
  default:
12476
    // FIXME: Handle the other argument kinds.
12477
0
    return X;
12478
0
  }
12479
0
}
12480
12481
static bool getCommonTemplateArguments(ASTContext &Ctx,
12482
                                       SmallVectorImpl<TemplateArgument> &R,
12483
                                       ArrayRef<TemplateArgument> Xs,
12484
0
                                       ArrayRef<TemplateArgument> Ys) {
12485
0
  if (Xs.size() != Ys.size())
12486
0
    return true;
12487
0
  R.resize(Xs.size());
12488
0
  for (size_t I = 0; I < R.size(); ++I) {
12489
0
    R[I] = getCommonTemplateArgument(Ctx, Xs[I], Ys[I]);
12490
0
    if (R[I].isNull())
12491
0
      return true;
12492
0
  }
12493
0
  return false;
12494
0
}
12495
12496
static auto getCommonTemplateArguments(ASTContext &Ctx,
12497
                                       ArrayRef<TemplateArgument> Xs,
12498
0
                                       ArrayRef<TemplateArgument> Ys) {
12499
0
  SmallVector<TemplateArgument, 8> R;
12500
0
  bool Different = getCommonTemplateArguments(Ctx, R, Xs, Ys);
12501
0
  assert(!Different);
12502
0
  (void)Different;
12503
0
  return R;
12504
0
}
12505
12506
template <class T>
12507
0
static ElaboratedTypeKeyword getCommonTypeKeyword(const T *X, const T *Y) {
12508
0
  return X->getKeyword() == Y->getKeyword() ? X->getKeyword()
12509
0
                                            : ElaboratedTypeKeyword::None;
12510
0
}
Unexecuted instantiation: ASTContext.cpp:clang::ElaboratedTypeKeyword getCommonTypeKeyword<clang::DependentNameType>(clang::DependentNameType const*, clang::DependentNameType const*)
Unexecuted instantiation: ASTContext.cpp:clang::ElaboratedTypeKeyword getCommonTypeKeyword<clang::DependentTemplateSpecializationType>(clang::DependentTemplateSpecializationType const*, clang::DependentTemplateSpecializationType const*)
Unexecuted instantiation: ASTContext.cpp:clang::ElaboratedTypeKeyword getCommonTypeKeyword<clang::ElaboratedType>(clang::ElaboratedType const*, clang::ElaboratedType const*)
12511
12512
template <class T>
12513
static NestedNameSpecifier *getCommonNNS(ASTContext &Ctx, const T *X,
12514
0
                                         const T *Y) {
12515
  // FIXME: Try to keep the common NNS sugar.
12516
0
  return X->getQualifier() == Y->getQualifier()
12517
0
             ? X->getQualifier()
12518
0
             : Ctx.getCanonicalNestedNameSpecifier(X->getQualifier());
12519
0
}
Unexecuted instantiation: ASTContext.cpp:clang::NestedNameSpecifier* getCommonNNS<clang::DependentNameType>(clang::ASTContext&, clang::DependentNameType const*, clang::DependentNameType const*)
Unexecuted instantiation: ASTContext.cpp:clang::NestedNameSpecifier* getCommonNNS<clang::DependentTemplateSpecializationType>(clang::ASTContext&, clang::DependentTemplateSpecializationType const*, clang::DependentTemplateSpecializationType const*)
Unexecuted instantiation: ASTContext.cpp:clang::NestedNameSpecifier* getCommonNNS<clang::ElaboratedType>(clang::ASTContext&, clang::ElaboratedType const*, clang::ElaboratedType const*)
12520
12521
template <class T>
12522
0
static QualType getCommonElementType(ASTContext &Ctx, const T *X, const T *Y) {
12523
0
  return Ctx.getCommonSugaredType(X->getElementType(), Y->getElementType());
12524
0
}
Unexecuted instantiation: ASTContext.cpp:clang::QualType getCommonElementType<clang::ConstantMatrixType>(clang::ASTContext&, clang::ConstantMatrixType const*, clang::ConstantMatrixType const*)
Unexecuted instantiation: ASTContext.cpp:clang::QualType getCommonElementType<clang::DependentSizedMatrixType>(clang::ASTContext&, clang::DependentSizedMatrixType const*, clang::DependentSizedMatrixType const*)
Unexecuted instantiation: ASTContext.cpp:clang::QualType getCommonElementType<clang::VectorType>(clang::ASTContext&, clang::VectorType const*, clang::VectorType const*)
Unexecuted instantiation: ASTContext.cpp:clang::QualType getCommonElementType<clang::ExtVectorType>(clang::ASTContext&, clang::ExtVectorType const*, clang::ExtVectorType const*)
Unexecuted instantiation: ASTContext.cpp:clang::QualType getCommonElementType<clang::DependentSizedExtVectorType>(clang::ASTContext&, clang::DependentSizedExtVectorType const*, clang::DependentSizedExtVectorType const*)
Unexecuted instantiation: ASTContext.cpp:clang::QualType getCommonElementType<clang::DependentVectorType>(clang::ASTContext&, clang::DependentVectorType const*, clang::DependentVectorType const*)
Unexecuted instantiation: ASTContext.cpp:clang::QualType getCommonElementType<clang::PipeType>(clang::ASTContext&, clang::PipeType const*, clang::PipeType const*)
12525
12526
template <class T>
12527
static QualType getCommonArrayElementType(ASTContext &Ctx, const T *X,
12528
                                          Qualifiers &QX, const T *Y,
12529
0
                                          Qualifiers &QY) {
12530
0
  QualType EX = X->getElementType(), EY = Y->getElementType();
12531
0
  QualType R = Ctx.getCommonSugaredType(EX, EY,
12532
0
                                        /*Unqualified=*/true);
12533
0
  Qualifiers RQ = R.getQualifiers();
12534
0
  QX += EX.getQualifiers() - RQ;
12535
0
  QY += EY.getQualifiers() - RQ;
12536
0
  return R;
12537
0
}
Unexecuted instantiation: ASTContext.cpp:clang::QualType getCommonArrayElementType<clang::IncompleteArrayType>(clang::ASTContext&, clang::IncompleteArrayType const*, clang::Qualifiers&, clang::IncompleteArrayType const*, clang::Qualifiers&)
Unexecuted instantiation: ASTContext.cpp:clang::QualType getCommonArrayElementType<clang::DependentSizedArrayType>(clang::ASTContext&, clang::DependentSizedArrayType const*, clang::Qualifiers&, clang::DependentSizedArrayType const*, clang::Qualifiers&)
Unexecuted instantiation: ASTContext.cpp:clang::QualType getCommonArrayElementType<clang::ConstantArrayType>(clang::ASTContext&, clang::ConstantArrayType const*, clang::Qualifiers&, clang::ConstantArrayType const*, clang::Qualifiers&)
Unexecuted instantiation: ASTContext.cpp:clang::QualType getCommonArrayElementType<clang::ComplexType>(clang::ASTContext&, clang::ComplexType const*, clang::Qualifiers&, clang::ComplexType const*, clang::Qualifiers&)
12538
12539
template <class T>
12540
0
static QualType getCommonPointeeType(ASTContext &Ctx, const T *X, const T *Y) {
12541
0
  return Ctx.getCommonSugaredType(X->getPointeeType(), Y->getPointeeType());
12542
0
}
Unexecuted instantiation: ASTContext.cpp:clang::QualType getCommonPointeeType<clang::PointerType>(clang::ASTContext&, clang::PointerType const*, clang::PointerType const*)
Unexecuted instantiation: ASTContext.cpp:clang::QualType getCommonPointeeType<clang::BlockPointerType>(clang::ASTContext&, clang::BlockPointerType const*, clang::BlockPointerType const*)
Unexecuted instantiation: ASTContext.cpp:clang::QualType getCommonPointeeType<clang::ObjCObjectPointerType>(clang::ASTContext&, clang::ObjCObjectPointerType const*, clang::ObjCObjectPointerType const*)
Unexecuted instantiation: ASTContext.cpp:clang::QualType getCommonPointeeType<clang::MemberPointerType>(clang::ASTContext&, clang::MemberPointerType const*, clang::MemberPointerType const*)
Unexecuted instantiation: ASTContext.cpp:clang::QualType getCommonPointeeType<clang::LValueReferenceType>(clang::ASTContext&, clang::LValueReferenceType const*, clang::LValueReferenceType const*)
Unexecuted instantiation: ASTContext.cpp:clang::QualType getCommonPointeeType<clang::RValueReferenceType>(clang::ASTContext&, clang::RValueReferenceType const*, clang::RValueReferenceType const*)
Unexecuted instantiation: ASTContext.cpp:clang::QualType getCommonPointeeType<clang::DependentAddressSpaceType>(clang::ASTContext&, clang::DependentAddressSpaceType const*, clang::DependentAddressSpaceType const*)
12543
12544
0
template <class T> static auto *getCommonSizeExpr(ASTContext &Ctx, T *X, T *Y) {
12545
0
  assert(Ctx.hasSameExpr(X->getSizeExpr(), Y->getSizeExpr()));
12546
0
  return X->getSizeExpr();
12547
0
}
Unexecuted instantiation: ASTContext.cpp:auto* getCommonSizeExpr<clang::DependentSizedArrayType const>(clang::ASTContext&, clang::DependentSizedArrayType const*, clang::DependentSizedArrayType const*)
Unexecuted instantiation: ASTContext.cpp:auto* getCommonSizeExpr<clang::DependentSizedExtVectorType const>(clang::ASTContext&, clang::DependentSizedExtVectorType const*, clang::DependentSizedExtVectorType const*)
Unexecuted instantiation: ASTContext.cpp:auto* getCommonSizeExpr<clang::DependentVectorType const>(clang::ASTContext&, clang::DependentVectorType const*, clang::DependentVectorType const*)
12548
12549
0
static auto getCommonSizeModifier(const ArrayType *X, const ArrayType *Y) {
12550
0
  assert(X->getSizeModifier() == Y->getSizeModifier());
12551
0
  return X->getSizeModifier();
12552
0
}
12553
12554
static auto getCommonIndexTypeCVRQualifiers(const ArrayType *X,
12555
0
                                            const ArrayType *Y) {
12556
0
  assert(X->getIndexTypeCVRQualifiers() == Y->getIndexTypeCVRQualifiers());
12557
0
  return X->getIndexTypeCVRQualifiers();
12558
0
}
12559
12560
// Merges two type lists such that the resulting vector will contain
12561
// each type (in a canonical sense) only once, in the order they appear
12562
// from X to Y. If they occur in both X and Y, the result will contain
12563
// the common sugared type between them.
12564
static void mergeTypeLists(ASTContext &Ctx, SmallVectorImpl<QualType> &Out,
12565
0
                           ArrayRef<QualType> X, ArrayRef<QualType> Y) {
12566
0
  llvm::DenseMap<QualType, unsigned> Found;
12567
0
  for (auto Ts : {X, Y}) {
12568
0
    for (QualType T : Ts) {
12569
0
      auto Res = Found.try_emplace(Ctx.getCanonicalType(T), Out.size());
12570
0
      if (!Res.second) {
12571
0
        QualType &U = Out[Res.first->second];
12572
0
        U = Ctx.getCommonSugaredType(U, T);
12573
0
      } else {
12574
0
        Out.emplace_back(T);
12575
0
      }
12576
0
    }
12577
0
  }
12578
0
}
12579
12580
FunctionProtoType::ExceptionSpecInfo
12581
ASTContext::mergeExceptionSpecs(FunctionProtoType::ExceptionSpecInfo ESI1,
12582
                                FunctionProtoType::ExceptionSpecInfo ESI2,
12583
                                SmallVectorImpl<QualType> &ExceptionTypeStorage,
12584
0
                                bool AcceptDependent) {
12585
0
  ExceptionSpecificationType EST1 = ESI1.Type, EST2 = ESI2.Type;
12586
12587
  // If either of them can throw anything, that is the result.
12588
0
  for (auto I : {EST_None, EST_MSAny, EST_NoexceptFalse}) {
12589
0
    if (EST1 == I)
12590
0
      return ESI1;
12591
0
    if (EST2 == I)
12592
0
      return ESI2;
12593
0
  }
12594
12595
  // If either of them is non-throwing, the result is the other.
12596
0
  for (auto I :
12597
0
       {EST_NoThrow, EST_DynamicNone, EST_BasicNoexcept, EST_NoexceptTrue}) {
12598
0
    if (EST1 == I)
12599
0
      return ESI2;
12600
0
    if (EST2 == I)
12601
0
      return ESI1;
12602
0
  }
12603
12604
  // If we're left with value-dependent computed noexcept expressions, we're
12605
  // stuck. Before C++17, we can just drop the exception specification entirely,
12606
  // since it's not actually part of the canonical type. And this should never
12607
  // happen in C++17, because it would mean we were computing the composite
12608
  // pointer type of dependent types, which should never happen.
12609
0
  if (EST1 == EST_DependentNoexcept || EST2 == EST_DependentNoexcept) {
12610
0
    assert(AcceptDependent &&
12611
0
           "computing composite pointer type of dependent types");
12612
0
    return FunctionProtoType::ExceptionSpecInfo();
12613
0
  }
12614
12615
  // Switch over the possibilities so that people adding new values know to
12616
  // update this function.
12617
0
  switch (EST1) {
12618
0
  case EST_None:
12619
0
  case EST_DynamicNone:
12620
0
  case EST_MSAny:
12621
0
  case EST_BasicNoexcept:
12622
0
  case EST_DependentNoexcept:
12623
0
  case EST_NoexceptFalse:
12624
0
  case EST_NoexceptTrue:
12625
0
  case EST_NoThrow:
12626
0
    llvm_unreachable("These ESTs should be handled above");
12627
12628
0
  case EST_Dynamic: {
12629
    // This is the fun case: both exception specifications are dynamic. Form
12630
    // the union of the two lists.
12631
0
    assert(EST2 == EST_Dynamic && "other cases should already be handled");
12632
0
    mergeTypeLists(*this, ExceptionTypeStorage, ESI1.Exceptions,
12633
0
                   ESI2.Exceptions);
12634
0
    FunctionProtoType::ExceptionSpecInfo Result(EST_Dynamic);
12635
0
    Result.Exceptions = ExceptionTypeStorage;
12636
0
    return Result;
12637
0
  }
12638
12639
0
  case EST_Unevaluated:
12640
0
  case EST_Uninstantiated:
12641
0
  case EST_Unparsed:
12642
0
    llvm_unreachable("shouldn't see unresolved exception specifications here");
12643
0
  }
12644
12645
0
  llvm_unreachable("invalid ExceptionSpecificationType");
12646
0
}
12647
12648
static QualType getCommonNonSugarTypeNode(ASTContext &Ctx, const Type *X,
12649
                                          Qualifiers &QX, const Type *Y,
12650
0
                                          Qualifiers &QY) {
12651
0
  Type::TypeClass TC = X->getTypeClass();
12652
0
  assert(TC == Y->getTypeClass());
12653
0
  switch (TC) {
12654
0
#define UNEXPECTED_TYPE(Class, Kind)                                           \
12655
0
  case Type::Class:                                                            \
12656
0
    llvm_unreachable("Unexpected " Kind ": " #Class);
12657
12658
0
#define NON_CANONICAL_TYPE(Class, Base) UNEXPECTED_TYPE(Class, "non-canonical")
12659
0
#define TYPE(Class, Base)
12660
0
#include "clang/AST/TypeNodes.inc"
12661
12662
0
#define SUGAR_FREE_TYPE(Class) UNEXPECTED_TYPE(Class, "sugar-free")
12663
0
    SUGAR_FREE_TYPE(Builtin)
12664
0
    SUGAR_FREE_TYPE(DeducedTemplateSpecialization)
12665
0
    SUGAR_FREE_TYPE(DependentBitInt)
12666
0
    SUGAR_FREE_TYPE(Enum)
12667
0
    SUGAR_FREE_TYPE(BitInt)
12668
0
    SUGAR_FREE_TYPE(ObjCInterface)
12669
0
    SUGAR_FREE_TYPE(Record)
12670
0
    SUGAR_FREE_TYPE(SubstTemplateTypeParmPack)
12671
0
    SUGAR_FREE_TYPE(UnresolvedUsing)
12672
0
#undef SUGAR_FREE_TYPE
12673
0
#define NON_UNIQUE_TYPE(Class) UNEXPECTED_TYPE(Class, "non-unique")
12674
0
    NON_UNIQUE_TYPE(TypeOfExpr)
12675
0
    NON_UNIQUE_TYPE(VariableArray)
12676
0
#undef NON_UNIQUE_TYPE
12677
12678
0
    UNEXPECTED_TYPE(TypeOf, "sugar")
12679
12680
0
#undef UNEXPECTED_TYPE
12681
12682
0
  case Type::Auto: {
12683
0
    const auto *AX = cast<AutoType>(X), *AY = cast<AutoType>(Y);
12684
0
    assert(AX->getDeducedType().isNull());
12685
0
    assert(AY->getDeducedType().isNull());
12686
0
    assert(AX->getKeyword() == AY->getKeyword());
12687
0
    assert(AX->isInstantiationDependentType() ==
12688
0
           AY->isInstantiationDependentType());
12689
0
    auto As = getCommonTemplateArguments(Ctx, AX->getTypeConstraintArguments(),
12690
0
                                         AY->getTypeConstraintArguments());
12691
0
    return Ctx.getAutoType(QualType(), AX->getKeyword(),
12692
0
                           AX->isInstantiationDependentType(),
12693
0
                           AX->containsUnexpandedParameterPack(),
12694
0
                           getCommonDeclChecked(AX->getTypeConstraintConcept(),
12695
0
                                                AY->getTypeConstraintConcept()),
12696
0
                           As);
12697
0
  }
12698
0
  case Type::IncompleteArray: {
12699
0
    const auto *AX = cast<IncompleteArrayType>(X),
12700
0
               *AY = cast<IncompleteArrayType>(Y);
12701
0
    return Ctx.getIncompleteArrayType(
12702
0
        getCommonArrayElementType(Ctx, AX, QX, AY, QY),
12703
0
        getCommonSizeModifier(AX, AY), getCommonIndexTypeCVRQualifiers(AX, AY));
12704
0
  }
12705
0
  case Type::DependentSizedArray: {
12706
0
    const auto *AX = cast<DependentSizedArrayType>(X),
12707
0
               *AY = cast<DependentSizedArrayType>(Y);
12708
0
    return Ctx.getDependentSizedArrayType(
12709
0
        getCommonArrayElementType(Ctx, AX, QX, AY, QY),
12710
0
        getCommonSizeExpr(Ctx, AX, AY), getCommonSizeModifier(AX, AY),
12711
0
        getCommonIndexTypeCVRQualifiers(AX, AY),
12712
0
        AX->getBracketsRange() == AY->getBracketsRange()
12713
0
            ? AX->getBracketsRange()
12714
0
            : SourceRange());
12715
0
  }
12716
0
  case Type::ConstantArray: {
12717
0
    const auto *AX = cast<ConstantArrayType>(X),
12718
0
               *AY = cast<ConstantArrayType>(Y);
12719
0
    assert(AX->getSize() == AY->getSize());
12720
0
    const Expr *SizeExpr = Ctx.hasSameExpr(AX->getSizeExpr(), AY->getSizeExpr())
12721
0
                               ? AX->getSizeExpr()
12722
0
                               : nullptr;
12723
0
    return Ctx.getConstantArrayType(
12724
0
        getCommonArrayElementType(Ctx, AX, QX, AY, QY), AX->getSize(), SizeExpr,
12725
0
        getCommonSizeModifier(AX, AY), getCommonIndexTypeCVRQualifiers(AX, AY));
12726
0
  }
12727
0
  case Type::Atomic: {
12728
0
    const auto *AX = cast<AtomicType>(X), *AY = cast<AtomicType>(Y);
12729
0
    return Ctx.getAtomicType(
12730
0
        Ctx.getCommonSugaredType(AX->getValueType(), AY->getValueType()));
12731
0
  }
12732
0
  case Type::Complex: {
12733
0
    const auto *CX = cast<ComplexType>(X), *CY = cast<ComplexType>(Y);
12734
0
    return Ctx.getComplexType(getCommonArrayElementType(Ctx, CX, QX, CY, QY));
12735
0
  }
12736
0
  case Type::Pointer: {
12737
0
    const auto *PX = cast<PointerType>(X), *PY = cast<PointerType>(Y);
12738
0
    return Ctx.getPointerType(getCommonPointeeType(Ctx, PX, PY));
12739
0
  }
12740
0
  case Type::BlockPointer: {
12741
0
    const auto *PX = cast<BlockPointerType>(X), *PY = cast<BlockPointerType>(Y);
12742
0
    return Ctx.getBlockPointerType(getCommonPointeeType(Ctx, PX, PY));
12743
0
  }
12744
0
  case Type::ObjCObjectPointer: {
12745
0
    const auto *PX = cast<ObjCObjectPointerType>(X),
12746
0
               *PY = cast<ObjCObjectPointerType>(Y);
12747
0
    return Ctx.getObjCObjectPointerType(getCommonPointeeType(Ctx, PX, PY));
12748
0
  }
12749
0
  case Type::MemberPointer: {
12750
0
    const auto *PX = cast<MemberPointerType>(X),
12751
0
               *PY = cast<MemberPointerType>(Y);
12752
0
    return Ctx.getMemberPointerType(
12753
0
        getCommonPointeeType(Ctx, PX, PY),
12754
0
        Ctx.getCommonSugaredType(QualType(PX->getClass(), 0),
12755
0
                                 QualType(PY->getClass(), 0))
12756
0
            .getTypePtr());
12757
0
  }
12758
0
  case Type::LValueReference: {
12759
0
    const auto *PX = cast<LValueReferenceType>(X),
12760
0
               *PY = cast<LValueReferenceType>(Y);
12761
    // FIXME: Preserve PointeeTypeAsWritten.
12762
0
    return Ctx.getLValueReferenceType(getCommonPointeeType(Ctx, PX, PY),
12763
0
                                      PX->isSpelledAsLValue() ||
12764
0
                                          PY->isSpelledAsLValue());
12765
0
  }
12766
0
  case Type::RValueReference: {
12767
0
    const auto *PX = cast<RValueReferenceType>(X),
12768
0
               *PY = cast<RValueReferenceType>(Y);
12769
    // FIXME: Preserve PointeeTypeAsWritten.
12770
0
    return Ctx.getRValueReferenceType(getCommonPointeeType(Ctx, PX, PY));
12771
0
  }
12772
0
  case Type::DependentAddressSpace: {
12773
0
    const auto *PX = cast<DependentAddressSpaceType>(X),
12774
0
               *PY = cast<DependentAddressSpaceType>(Y);
12775
0
    assert(Ctx.hasSameExpr(PX->getAddrSpaceExpr(), PY->getAddrSpaceExpr()));
12776
0
    return Ctx.getDependentAddressSpaceType(getCommonPointeeType(Ctx, PX, PY),
12777
0
                                            PX->getAddrSpaceExpr(),
12778
0
                                            getCommonAttrLoc(PX, PY));
12779
0
  }
12780
0
  case Type::FunctionNoProto: {
12781
0
    const auto *FX = cast<FunctionNoProtoType>(X),
12782
0
               *FY = cast<FunctionNoProtoType>(Y);
12783
0
    assert(FX->getExtInfo() == FY->getExtInfo());
12784
0
    return Ctx.getFunctionNoProtoType(
12785
0
        Ctx.getCommonSugaredType(FX->getReturnType(), FY->getReturnType()),
12786
0
        FX->getExtInfo());
12787
0
  }
12788
0
  case Type::FunctionProto: {
12789
0
    const auto *FX = cast<FunctionProtoType>(X),
12790
0
               *FY = cast<FunctionProtoType>(Y);
12791
0
    FunctionProtoType::ExtProtoInfo EPIX = FX->getExtProtoInfo(),
12792
0
                                    EPIY = FY->getExtProtoInfo();
12793
0
    assert(EPIX.ExtInfo == EPIY.ExtInfo);
12794
0
    assert(EPIX.ExtParameterInfos == EPIY.ExtParameterInfos);
12795
0
    assert(EPIX.RefQualifier == EPIY.RefQualifier);
12796
0
    assert(EPIX.TypeQuals == EPIY.TypeQuals);
12797
0
    assert(EPIX.Variadic == EPIY.Variadic);
12798
12799
    // FIXME: Can we handle an empty EllipsisLoc?
12800
    //        Use emtpy EllipsisLoc if X and Y differ.
12801
12802
0
    EPIX.HasTrailingReturn = EPIX.HasTrailingReturn && EPIY.HasTrailingReturn;
12803
12804
0
    QualType R =
12805
0
        Ctx.getCommonSugaredType(FX->getReturnType(), FY->getReturnType());
12806
0
    auto P = getCommonTypes(Ctx, FX->param_types(), FY->param_types(),
12807
0
                            /*Unqualified=*/true);
12808
12809
0
    SmallVector<QualType, 8> Exceptions;
12810
0
    EPIX.ExceptionSpec = Ctx.mergeExceptionSpecs(
12811
0
        EPIX.ExceptionSpec, EPIY.ExceptionSpec, Exceptions, true);
12812
0
    return Ctx.getFunctionType(R, P, EPIX);
12813
0
  }
12814
0
  case Type::ObjCObject: {
12815
0
    const auto *OX = cast<ObjCObjectType>(X), *OY = cast<ObjCObjectType>(Y);
12816
0
    assert(
12817
0
        std::equal(OX->getProtocols().begin(), OX->getProtocols().end(),
12818
0
                   OY->getProtocols().begin(), OY->getProtocols().end(),
12819
0
                   [](const ObjCProtocolDecl *P0, const ObjCProtocolDecl *P1) {
12820
0
                     return P0->getCanonicalDecl() == P1->getCanonicalDecl();
12821
0
                   }) &&
12822
0
        "protocol lists must be the same");
12823
0
    auto TAs = getCommonTypes(Ctx, OX->getTypeArgsAsWritten(),
12824
0
                              OY->getTypeArgsAsWritten());
12825
0
    return Ctx.getObjCObjectType(
12826
0
        Ctx.getCommonSugaredType(OX->getBaseType(), OY->getBaseType()), TAs,
12827
0
        OX->getProtocols(),
12828
0
        OX->isKindOfTypeAsWritten() && OY->isKindOfTypeAsWritten());
12829
0
  }
12830
0
  case Type::ConstantMatrix: {
12831
0
    const auto *MX = cast<ConstantMatrixType>(X),
12832
0
               *MY = cast<ConstantMatrixType>(Y);
12833
0
    assert(MX->getNumRows() == MY->getNumRows());
12834
0
    assert(MX->getNumColumns() == MY->getNumColumns());
12835
0
    return Ctx.getConstantMatrixType(getCommonElementType(Ctx, MX, MY),
12836
0
                                     MX->getNumRows(), MX->getNumColumns());
12837
0
  }
12838
0
  case Type::DependentSizedMatrix: {
12839
0
    const auto *MX = cast<DependentSizedMatrixType>(X),
12840
0
               *MY = cast<DependentSizedMatrixType>(Y);
12841
0
    assert(Ctx.hasSameExpr(MX->getRowExpr(), MY->getRowExpr()));
12842
0
    assert(Ctx.hasSameExpr(MX->getColumnExpr(), MY->getColumnExpr()));
12843
0
    return Ctx.getDependentSizedMatrixType(
12844
0
        getCommonElementType(Ctx, MX, MY), MX->getRowExpr(),
12845
0
        MX->getColumnExpr(), getCommonAttrLoc(MX, MY));
12846
0
  }
12847
0
  case Type::Vector: {
12848
0
    const auto *VX = cast<VectorType>(X), *VY = cast<VectorType>(Y);
12849
0
    assert(VX->getNumElements() == VY->getNumElements());
12850
0
    assert(VX->getVectorKind() == VY->getVectorKind());
12851
0
    return Ctx.getVectorType(getCommonElementType(Ctx, VX, VY),
12852
0
                             VX->getNumElements(), VX->getVectorKind());
12853
0
  }
12854
0
  case Type::ExtVector: {
12855
0
    const auto *VX = cast<ExtVectorType>(X), *VY = cast<ExtVectorType>(Y);
12856
0
    assert(VX->getNumElements() == VY->getNumElements());
12857
0
    return Ctx.getExtVectorType(getCommonElementType(Ctx, VX, VY),
12858
0
                                VX->getNumElements());
12859
0
  }
12860
0
  case Type::DependentSizedExtVector: {
12861
0
    const auto *VX = cast<DependentSizedExtVectorType>(X),
12862
0
               *VY = cast<DependentSizedExtVectorType>(Y);
12863
0
    return Ctx.getDependentSizedExtVectorType(getCommonElementType(Ctx, VX, VY),
12864
0
                                              getCommonSizeExpr(Ctx, VX, VY),
12865
0
                                              getCommonAttrLoc(VX, VY));
12866
0
  }
12867
0
  case Type::DependentVector: {
12868
0
    const auto *VX = cast<DependentVectorType>(X),
12869
0
               *VY = cast<DependentVectorType>(Y);
12870
0
    assert(VX->getVectorKind() == VY->getVectorKind());
12871
0
    return Ctx.getDependentVectorType(
12872
0
        getCommonElementType(Ctx, VX, VY), getCommonSizeExpr(Ctx, VX, VY),
12873
0
        getCommonAttrLoc(VX, VY), VX->getVectorKind());
12874
0
  }
12875
0
  case Type::InjectedClassName: {
12876
0
    const auto *IX = cast<InjectedClassNameType>(X),
12877
0
               *IY = cast<InjectedClassNameType>(Y);
12878
0
    return Ctx.getInjectedClassNameType(
12879
0
        getCommonDeclChecked(IX->getDecl(), IY->getDecl()),
12880
0
        Ctx.getCommonSugaredType(IX->getInjectedSpecializationType(),
12881
0
                                 IY->getInjectedSpecializationType()));
12882
0
  }
12883
0
  case Type::TemplateSpecialization: {
12884
0
    const auto *TX = cast<TemplateSpecializationType>(X),
12885
0
               *TY = cast<TemplateSpecializationType>(Y);
12886
0
    auto As = getCommonTemplateArguments(Ctx, TX->template_arguments(),
12887
0
                                         TY->template_arguments());
12888
0
    return Ctx.getTemplateSpecializationType(
12889
0
        ::getCommonTemplateNameChecked(Ctx, TX->getTemplateName(),
12890
0
                                       TY->getTemplateName()),
12891
0
        As, X->getCanonicalTypeInternal());
12892
0
  }
12893
0
  case Type::Decltype: {
12894
0
    const auto *DX = cast<DecltypeType>(X);
12895
0
    [[maybe_unused]] const auto *DY = cast<DecltypeType>(Y);
12896
0
    assert(DX->isDependentType());
12897
0
    assert(DY->isDependentType());
12898
0
    assert(Ctx.hasSameExpr(DX->getUnderlyingExpr(), DY->getUnderlyingExpr()));
12899
    // As Decltype is not uniqued, building a common type would be wasteful.
12900
0
    return QualType(DX, 0);
12901
0
  }
12902
0
  case Type::DependentName: {
12903
0
    const auto *NX = cast<DependentNameType>(X),
12904
0
               *NY = cast<DependentNameType>(Y);
12905
0
    assert(NX->getIdentifier() == NY->getIdentifier());
12906
0
    return Ctx.getDependentNameType(
12907
0
        getCommonTypeKeyword(NX, NY), getCommonNNS(Ctx, NX, NY),
12908
0
        NX->getIdentifier(), NX->getCanonicalTypeInternal());
12909
0
  }
12910
0
  case Type::DependentTemplateSpecialization: {
12911
0
    const auto *TX = cast<DependentTemplateSpecializationType>(X),
12912
0
               *TY = cast<DependentTemplateSpecializationType>(Y);
12913
0
    assert(TX->getIdentifier() == TY->getIdentifier());
12914
0
    auto As = getCommonTemplateArguments(Ctx, TX->template_arguments(),
12915
0
                                         TY->template_arguments());
12916
0
    return Ctx.getDependentTemplateSpecializationType(
12917
0
        getCommonTypeKeyword(TX, TY), getCommonNNS(Ctx, TX, TY),
12918
0
        TX->getIdentifier(), As);
12919
0
  }
12920
0
  case Type::UnaryTransform: {
12921
0
    const auto *TX = cast<UnaryTransformType>(X),
12922
0
               *TY = cast<UnaryTransformType>(Y);
12923
0
    assert(TX->getUTTKind() == TY->getUTTKind());
12924
0
    return Ctx.getUnaryTransformType(
12925
0
        Ctx.getCommonSugaredType(TX->getBaseType(), TY->getBaseType()),
12926
0
        Ctx.getCommonSugaredType(TX->getUnderlyingType(),
12927
0
                                 TY->getUnderlyingType()),
12928
0
        TX->getUTTKind());
12929
0
  }
12930
0
  case Type::PackExpansion: {
12931
0
    const auto *PX = cast<PackExpansionType>(X),
12932
0
               *PY = cast<PackExpansionType>(Y);
12933
0
    assert(PX->getNumExpansions() == PY->getNumExpansions());
12934
0
    return Ctx.getPackExpansionType(
12935
0
        Ctx.getCommonSugaredType(PX->getPattern(), PY->getPattern()),
12936
0
        PX->getNumExpansions(), false);
12937
0
  }
12938
0
  case Type::Pipe: {
12939
0
    const auto *PX = cast<PipeType>(X), *PY = cast<PipeType>(Y);
12940
0
    assert(PX->isReadOnly() == PY->isReadOnly());
12941
0
    auto MP = PX->isReadOnly() ? &ASTContext::getReadPipeType
12942
0
                               : &ASTContext::getWritePipeType;
12943
0
    return (Ctx.*MP)(getCommonElementType(Ctx, PX, PY));
12944
0
  }
12945
0
  case Type::TemplateTypeParm: {
12946
0
    const auto *TX = cast<TemplateTypeParmType>(X),
12947
0
               *TY = cast<TemplateTypeParmType>(Y);
12948
0
    assert(TX->getDepth() == TY->getDepth());
12949
0
    assert(TX->getIndex() == TY->getIndex());
12950
0
    assert(TX->isParameterPack() == TY->isParameterPack());
12951
0
    return Ctx.getTemplateTypeParmType(
12952
0
        TX->getDepth(), TX->getIndex(), TX->isParameterPack(),
12953
0
        getCommonDecl(TX->getDecl(), TY->getDecl()));
12954
0
  }
12955
0
  }
12956
0
  llvm_unreachable("Unknown Type Class");
12957
0
}
12958
12959
static QualType getCommonSugarTypeNode(ASTContext &Ctx, const Type *X,
12960
                                       const Type *Y,
12961
0
                                       SplitQualType Underlying) {
12962
0
  Type::TypeClass TC = X->getTypeClass();
12963
0
  if (TC != Y->getTypeClass())
12964
0
    return QualType();
12965
0
  switch (TC) {
12966
0
#define UNEXPECTED_TYPE(Class, Kind)                                           \
12967
0
  case Type::Class:                                                            \
12968
0
    llvm_unreachable("Unexpected " Kind ": " #Class);
12969
0
#define TYPE(Class, Base)
12970
0
#define DEPENDENT_TYPE(Class, Base) UNEXPECTED_TYPE(Class, "dependent")
12971
0
#include "clang/AST/TypeNodes.inc"
12972
12973
0
#define CANONICAL_TYPE(Class) UNEXPECTED_TYPE(Class, "canonical")
12974
0
    CANONICAL_TYPE(Atomic)
12975
0
    CANONICAL_TYPE(BitInt)
12976
0
    CANONICAL_TYPE(BlockPointer)
12977
0
    CANONICAL_TYPE(Builtin)
12978
0
    CANONICAL_TYPE(Complex)
12979
0
    CANONICAL_TYPE(ConstantArray)
12980
0
    CANONICAL_TYPE(ConstantMatrix)
12981
0
    CANONICAL_TYPE(Enum)
12982
0
    CANONICAL_TYPE(ExtVector)
12983
0
    CANONICAL_TYPE(FunctionNoProto)
12984
0
    CANONICAL_TYPE(FunctionProto)
12985
0
    CANONICAL_TYPE(IncompleteArray)
12986
0
    CANONICAL_TYPE(LValueReference)
12987
0
    CANONICAL_TYPE(MemberPointer)
12988
0
    CANONICAL_TYPE(ObjCInterface)
12989
0
    CANONICAL_TYPE(ObjCObject)
12990
0
    CANONICAL_TYPE(ObjCObjectPointer)
12991
0
    CANONICAL_TYPE(Pipe)
12992
0
    CANONICAL_TYPE(Pointer)
12993
0
    CANONICAL_TYPE(Record)
12994
0
    CANONICAL_TYPE(RValueReference)
12995
0
    CANONICAL_TYPE(VariableArray)
12996
0
    CANONICAL_TYPE(Vector)
12997
0
#undef CANONICAL_TYPE
12998
12999
0
#undef UNEXPECTED_TYPE
13000
13001
0
  case Type::Adjusted: {
13002
0
    const auto *AX = cast<AdjustedType>(X), *AY = cast<AdjustedType>(Y);
13003
0
    QualType OX = AX->getOriginalType(), OY = AY->getOriginalType();
13004
0
    if (!Ctx.hasSameType(OX, OY))
13005
0
      return QualType();
13006
    // FIXME: It's inefficient to have to unify the original types.
13007
0
    return Ctx.getAdjustedType(Ctx.getCommonSugaredType(OX, OY),
13008
0
                               Ctx.getQualifiedType(Underlying));
13009
0
  }
13010
0
  case Type::Decayed: {
13011
0
    const auto *DX = cast<DecayedType>(X), *DY = cast<DecayedType>(Y);
13012
0
    QualType OX = DX->getOriginalType(), OY = DY->getOriginalType();
13013
0
    if (!Ctx.hasSameType(OX, OY))
13014
0
      return QualType();
13015
    // FIXME: It's inefficient to have to unify the original types.
13016
0
    return Ctx.getDecayedType(Ctx.getCommonSugaredType(OX, OY),
13017
0
                              Ctx.getQualifiedType(Underlying));
13018
0
  }
13019
0
  case Type::Attributed: {
13020
0
    const auto *AX = cast<AttributedType>(X), *AY = cast<AttributedType>(Y);
13021
0
    AttributedType::Kind Kind = AX->getAttrKind();
13022
0
    if (Kind != AY->getAttrKind())
13023
0
      return QualType();
13024
0
    QualType MX = AX->getModifiedType(), MY = AY->getModifiedType();
13025
0
    if (!Ctx.hasSameType(MX, MY))
13026
0
      return QualType();
13027
    // FIXME: It's inefficient to have to unify the modified types.
13028
0
    return Ctx.getAttributedType(Kind, Ctx.getCommonSugaredType(MX, MY),
13029
0
                                 Ctx.getQualifiedType(Underlying));
13030
0
  }
13031
0
  case Type::BTFTagAttributed: {
13032
0
    const auto *BX = cast<BTFTagAttributedType>(X);
13033
0
    const BTFTypeTagAttr *AX = BX->getAttr();
13034
    // The attribute is not uniqued, so just compare the tag.
13035
0
    if (AX->getBTFTypeTag() !=
13036
0
        cast<BTFTagAttributedType>(Y)->getAttr()->getBTFTypeTag())
13037
0
      return QualType();
13038
0
    return Ctx.getBTFTagAttributedType(AX, Ctx.getQualifiedType(Underlying));
13039
0
  }
13040
0
  case Type::Auto: {
13041
0
    const auto *AX = cast<AutoType>(X), *AY = cast<AutoType>(Y);
13042
13043
0
    AutoTypeKeyword KW = AX->getKeyword();
13044
0
    if (KW != AY->getKeyword())
13045
0
      return QualType();
13046
13047
0
    ConceptDecl *CD = ::getCommonDecl(AX->getTypeConstraintConcept(),
13048
0
                                      AY->getTypeConstraintConcept());
13049
0
    SmallVector<TemplateArgument, 8> As;
13050
0
    if (CD &&
13051
0
        getCommonTemplateArguments(Ctx, As, AX->getTypeConstraintArguments(),
13052
0
                                   AY->getTypeConstraintArguments())) {
13053
0
      CD = nullptr; // The arguments differ, so make it unconstrained.
13054
0
      As.clear();
13055
0
    }
13056
13057
    // Both auto types can't be dependent, otherwise they wouldn't have been
13058
    // sugar. This implies they can't contain unexpanded packs either.
13059
0
    return Ctx.getAutoType(Ctx.getQualifiedType(Underlying), AX->getKeyword(),
13060
0
                           /*IsDependent=*/false, /*IsPack=*/false, CD, As);
13061
0
  }
13062
0
  case Type::Decltype:
13063
0
    return QualType();
13064
0
  case Type::DeducedTemplateSpecialization:
13065
    // FIXME: Try to merge these.
13066
0
    return QualType();
13067
13068
0
  case Type::Elaborated: {
13069
0
    const auto *EX = cast<ElaboratedType>(X), *EY = cast<ElaboratedType>(Y);
13070
0
    return Ctx.getElaboratedType(
13071
0
        ::getCommonTypeKeyword(EX, EY), ::getCommonNNS(Ctx, EX, EY),
13072
0
        Ctx.getQualifiedType(Underlying),
13073
0
        ::getCommonDecl(EX->getOwnedTagDecl(), EY->getOwnedTagDecl()));
13074
0
  }
13075
0
  case Type::MacroQualified: {
13076
0
    const auto *MX = cast<MacroQualifiedType>(X),
13077
0
               *MY = cast<MacroQualifiedType>(Y);
13078
0
    const IdentifierInfo *IX = MX->getMacroIdentifier();
13079
0
    if (IX != MY->getMacroIdentifier())
13080
0
      return QualType();
13081
0
    return Ctx.getMacroQualifiedType(Ctx.getQualifiedType(Underlying), IX);
13082
0
  }
13083
0
  case Type::SubstTemplateTypeParm: {
13084
0
    const auto *SX = cast<SubstTemplateTypeParmType>(X),
13085
0
               *SY = cast<SubstTemplateTypeParmType>(Y);
13086
0
    Decl *CD =
13087
0
        ::getCommonDecl(SX->getAssociatedDecl(), SY->getAssociatedDecl());
13088
0
    if (!CD)
13089
0
      return QualType();
13090
0
    unsigned Index = SX->getIndex();
13091
0
    if (Index != SY->getIndex())
13092
0
      return QualType();
13093
0
    auto PackIndex = SX->getPackIndex();
13094
0
    if (PackIndex != SY->getPackIndex())
13095
0
      return QualType();
13096
0
    return Ctx.getSubstTemplateTypeParmType(Ctx.getQualifiedType(Underlying),
13097
0
                                            CD, Index, PackIndex);
13098
0
  }
13099
0
  case Type::ObjCTypeParam:
13100
    // FIXME: Try to merge these.
13101
0
    return QualType();
13102
0
  case Type::Paren:
13103
0
    return Ctx.getParenType(Ctx.getQualifiedType(Underlying));
13104
13105
0
  case Type::TemplateSpecialization: {
13106
0
    const auto *TX = cast<TemplateSpecializationType>(X),
13107
0
               *TY = cast<TemplateSpecializationType>(Y);
13108
0
    TemplateName CTN = ::getCommonTemplateName(Ctx, TX->getTemplateName(),
13109
0
                                               TY->getTemplateName());
13110
0
    if (!CTN.getAsVoidPointer())
13111
0
      return QualType();
13112
0
    SmallVector<TemplateArgument, 8> Args;
13113
0
    if (getCommonTemplateArguments(Ctx, Args, TX->template_arguments(),
13114
0
                                   TY->template_arguments()))
13115
0
      return QualType();
13116
0
    return Ctx.getTemplateSpecializationType(CTN, Args,
13117
0
                                             Ctx.getQualifiedType(Underlying));
13118
0
  }
13119
0
  case Type::Typedef: {
13120
0
    const auto *TX = cast<TypedefType>(X), *TY = cast<TypedefType>(Y);
13121
0
    const TypedefNameDecl *CD = ::getCommonDecl(TX->getDecl(), TY->getDecl());
13122
0
    if (!CD)
13123
0
      return QualType();
13124
0
    return Ctx.getTypedefType(CD, Ctx.getQualifiedType(Underlying));
13125
0
  }
13126
0
  case Type::TypeOf: {
13127
    // The common sugar between two typeof expressions, where one is
13128
    // potentially a typeof_unqual and the other is not, we unify to the
13129
    // qualified type as that retains the most information along with the type.
13130
    // We only return a typeof_unqual type when both types are unqual types.
13131
0
    TypeOfKind Kind = TypeOfKind::Qualified;
13132
0
    if (cast<TypeOfType>(X)->getKind() == cast<TypeOfType>(Y)->getKind() &&
13133
0
        cast<TypeOfType>(X)->getKind() == TypeOfKind::Unqualified)
13134
0
      Kind = TypeOfKind::Unqualified;
13135
0
    return Ctx.getTypeOfType(Ctx.getQualifiedType(Underlying), Kind);
13136
0
  }
13137
0
  case Type::TypeOfExpr:
13138
0
    return QualType();
13139
13140
0
  case Type::UnaryTransform: {
13141
0
    const auto *UX = cast<UnaryTransformType>(X),
13142
0
               *UY = cast<UnaryTransformType>(Y);
13143
0
    UnaryTransformType::UTTKind KX = UX->getUTTKind();
13144
0
    if (KX != UY->getUTTKind())
13145
0
      return QualType();
13146
0
    QualType BX = UX->getBaseType(), BY = UY->getBaseType();
13147
0
    if (!Ctx.hasSameType(BX, BY))
13148
0
      return QualType();
13149
    // FIXME: It's inefficient to have to unify the base types.
13150
0
    return Ctx.getUnaryTransformType(Ctx.getCommonSugaredType(BX, BY),
13151
0
                                     Ctx.getQualifiedType(Underlying), KX);
13152
0
  }
13153
0
  case Type::Using: {
13154
0
    const auto *UX = cast<UsingType>(X), *UY = cast<UsingType>(Y);
13155
0
    const UsingShadowDecl *CD =
13156
0
        ::getCommonDecl(UX->getFoundDecl(), UY->getFoundDecl());
13157
0
    if (!CD)
13158
0
      return QualType();
13159
0
    return Ctx.getUsingType(CD, Ctx.getQualifiedType(Underlying));
13160
0
  }
13161
0
  }
13162
0
  llvm_unreachable("Unhandled Type Class");
13163
0
}
13164
13165
0
static auto unwrapSugar(SplitQualType &T, Qualifiers &QTotal) {
13166
0
  SmallVector<SplitQualType, 8> R;
13167
0
  while (true) {
13168
0
    QTotal.addConsistentQualifiers(T.Quals);
13169
0
    QualType NT = T.Ty->getLocallyUnqualifiedSingleStepDesugaredType();
13170
0
    if (NT == QualType(T.Ty, 0))
13171
0
      break;
13172
0
    R.push_back(T);
13173
0
    T = NT.split();
13174
0
  }
13175
0
  return R;
13176
0
}
13177
13178
QualType ASTContext::getCommonSugaredType(QualType X, QualType Y,
13179
0
                                          bool Unqualified) {
13180
0
  assert(Unqualified ? hasSameUnqualifiedType(X, Y) : hasSameType(X, Y));
13181
0
  if (X == Y)
13182
0
    return X;
13183
0
  if (!Unqualified) {
13184
0
    if (X.isCanonical())
13185
0
      return X;
13186
0
    if (Y.isCanonical())
13187
0
      return Y;
13188
0
  }
13189
13190
0
  SplitQualType SX = X.split(), SY = Y.split();
13191
0
  Qualifiers QX, QY;
13192
  // Desugar SX and SY, setting the sugar and qualifiers aside into Xs and Ys,
13193
  // until we reach their underlying "canonical nodes". Note these are not
13194
  // necessarily canonical types, as they may still have sugared properties.
13195
  // QX and QY will store the sum of all qualifiers in Xs and Ys respectively.
13196
0
  auto Xs = ::unwrapSugar(SX, QX), Ys = ::unwrapSugar(SY, QY);
13197
0
  if (SX.Ty != SY.Ty) {
13198
    // The canonical nodes differ. Build a common canonical node out of the two,
13199
    // unifying their sugar. This may recurse back here.
13200
0
    SX.Ty =
13201
0
        ::getCommonNonSugarTypeNode(*this, SX.Ty, QX, SY.Ty, QY).getTypePtr();
13202
0
  } else {
13203
    // The canonical nodes were identical: We may have desugared too much.
13204
    // Add any common sugar back in.
13205
0
    while (!Xs.empty() && !Ys.empty() && Xs.back().Ty == Ys.back().Ty) {
13206
0
      QX -= SX.Quals;
13207
0
      QY -= SY.Quals;
13208
0
      SX = Xs.pop_back_val();
13209
0
      SY = Ys.pop_back_val();
13210
0
    }
13211
0
  }
13212
0
  if (Unqualified)
13213
0
    QX = Qualifiers::removeCommonQualifiers(QX, QY);
13214
0
  else
13215
0
    assert(QX == QY);
13216
13217
  // Even though the remaining sugar nodes in Xs and Ys differ, some may be
13218
  // related. Walk up these nodes, unifying them and adding the result.
13219
0
  while (!Xs.empty() && !Ys.empty()) {
13220
0
    auto Underlying = SplitQualType(
13221
0
        SX.Ty, Qualifiers::removeCommonQualifiers(SX.Quals, SY.Quals));
13222
0
    SX = Xs.pop_back_val();
13223
0
    SY = Ys.pop_back_val();
13224
0
    SX.Ty = ::getCommonSugarTypeNode(*this, SX.Ty, SY.Ty, Underlying)
13225
0
                .getTypePtrOrNull();
13226
    // Stop at the first pair which is unrelated.
13227
0
    if (!SX.Ty) {
13228
0
      SX.Ty = Underlying.Ty;
13229
0
      break;
13230
0
    }
13231
0
    QX -= Underlying.Quals;
13232
0
  };
13233
13234
  // Add back the missing accumulated qualifiers, which were stripped off
13235
  // with the sugar nodes we could not unify.
13236
0
  QualType R = getQualifiedType(SX.Ty, QX);
13237
0
  assert(Unqualified ? hasSameUnqualifiedType(R, X) : hasSameType(R, X));
13238
0
  return R;
13239
0
}
13240
13241
0
QualType ASTContext::getCorrespondingSaturatedType(QualType Ty) const {
13242
0
  assert(Ty->isFixedPointType());
13243
13244
0
  if (Ty->isSaturatedFixedPointType()) return Ty;
13245
13246
0
  switch (Ty->castAs<BuiltinType>()->getKind()) {
13247
0
    default:
13248
0
      llvm_unreachable("Not a fixed point type!");
13249
0
    case BuiltinType::ShortAccum:
13250
0
      return SatShortAccumTy;
13251
0
    case BuiltinType::Accum:
13252
0
      return SatAccumTy;
13253
0
    case BuiltinType::LongAccum:
13254
0
      return SatLongAccumTy;
13255
0
    case BuiltinType::UShortAccum:
13256
0
      return SatUnsignedShortAccumTy;
13257
0
    case BuiltinType::UAccum:
13258
0
      return SatUnsignedAccumTy;
13259
0
    case BuiltinType::ULongAccum:
13260
0
      return SatUnsignedLongAccumTy;
13261
0
    case BuiltinType::ShortFract:
13262
0
      return SatShortFractTy;
13263
0
    case BuiltinType::Fract:
13264
0
      return SatFractTy;
13265
0
    case BuiltinType::LongFract:
13266
0
      return SatLongFractTy;
13267
0
    case BuiltinType::UShortFract:
13268
0
      return SatUnsignedShortFractTy;
13269
0
    case BuiltinType::UFract:
13270
0
      return SatUnsignedFractTy;
13271
0
    case BuiltinType::ULongFract:
13272
0
      return SatUnsignedLongFractTy;
13273
0
  }
13274
0
}
13275
13276
0
LangAS ASTContext::getLangASForBuiltinAddressSpace(unsigned AS) const {
13277
0
  if (LangOpts.OpenCL)
13278
0
    return getTargetInfo().getOpenCLBuiltinAddressSpace(AS);
13279
13280
0
  if (LangOpts.CUDA)
13281
0
    return getTargetInfo().getCUDABuiltinAddressSpace(AS);
13282
13283
0
  return getLangASFromTargetAS(AS);
13284
0
}
13285
13286
// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
13287
// doesn't include ASTContext.h
13288
template
13289
clang::LazyGenerationalUpdatePtr<
13290
    const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
13291
clang::LazyGenerationalUpdatePtr<
13292
    const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
13293
        const clang::ASTContext &Ctx, Decl *Value);
13294
13295
0
unsigned char ASTContext::getFixedPointScale(QualType Ty) const {
13296
0
  assert(Ty->isFixedPointType());
13297
13298
0
  const TargetInfo &Target = getTargetInfo();
13299
0
  switch (Ty->castAs<BuiltinType>()->getKind()) {
13300
0
    default:
13301
0
      llvm_unreachable("Not a fixed point type!");
13302
0
    case BuiltinType::ShortAccum:
13303
0
    case BuiltinType::SatShortAccum:
13304
0
      return Target.getShortAccumScale();
13305
0
    case BuiltinType::Accum:
13306
0
    case BuiltinType::SatAccum:
13307
0
      return Target.getAccumScale();
13308
0
    case BuiltinType::LongAccum:
13309
0
    case BuiltinType::SatLongAccum:
13310
0
      return Target.getLongAccumScale();
13311
0
    case BuiltinType::UShortAccum:
13312
0
    case BuiltinType::SatUShortAccum:
13313
0
      return Target.getUnsignedShortAccumScale();
13314
0
    case BuiltinType::UAccum:
13315
0
    case BuiltinType::SatUAccum:
13316
0
      return Target.getUnsignedAccumScale();
13317
0
    case BuiltinType::ULongAccum:
13318
0
    case BuiltinType::SatULongAccum:
13319
0
      return Target.getUnsignedLongAccumScale();
13320
0
    case BuiltinType::ShortFract:
13321
0
    case BuiltinType::SatShortFract:
13322
0
      return Target.getShortFractScale();
13323
0
    case BuiltinType::Fract:
13324
0
    case BuiltinType::SatFract:
13325
0
      return Target.getFractScale();
13326
0
    case BuiltinType::LongFract:
13327
0
    case BuiltinType::SatLongFract:
13328
0
      return Target.getLongFractScale();
13329
0
    case BuiltinType::UShortFract:
13330
0
    case BuiltinType::SatUShortFract:
13331
0
      return Target.getUnsignedShortFractScale();
13332
0
    case BuiltinType::UFract:
13333
0
    case BuiltinType::SatUFract:
13334
0
      return Target.getUnsignedFractScale();
13335
0
    case BuiltinType::ULongFract:
13336
0
    case BuiltinType::SatULongFract:
13337
0
      return Target.getUnsignedLongFractScale();
13338
0
  }
13339
0
}
13340
13341
0
unsigned char ASTContext::getFixedPointIBits(QualType Ty) const {
13342
0
  assert(Ty->isFixedPointType());
13343
13344
0
  const TargetInfo &Target = getTargetInfo();
13345
0
  switch (Ty->castAs<BuiltinType>()->getKind()) {
13346
0
    default:
13347
0
      llvm_unreachable("Not a fixed point type!");
13348
0
    case BuiltinType::ShortAccum:
13349
0
    case BuiltinType::SatShortAccum:
13350
0
      return Target.getShortAccumIBits();
13351
0
    case BuiltinType::Accum:
13352
0
    case BuiltinType::SatAccum:
13353
0
      return Target.getAccumIBits();
13354
0
    case BuiltinType::LongAccum:
13355
0
    case BuiltinType::SatLongAccum:
13356
0
      return Target.getLongAccumIBits();
13357
0
    case BuiltinType::UShortAccum:
13358
0
    case BuiltinType::SatUShortAccum:
13359
0
      return Target.getUnsignedShortAccumIBits();
13360
0
    case BuiltinType::UAccum:
13361
0
    case BuiltinType::SatUAccum:
13362
0
      return Target.getUnsignedAccumIBits();
13363
0
    case BuiltinType::ULongAccum:
13364
0
    case BuiltinType::SatULongAccum:
13365
0
      return Target.getUnsignedLongAccumIBits();
13366
0
    case BuiltinType::ShortFract:
13367
0
    case BuiltinType::SatShortFract:
13368
0
    case BuiltinType::Fract:
13369
0
    case BuiltinType::SatFract:
13370
0
    case BuiltinType::LongFract:
13371
0
    case BuiltinType::SatLongFract:
13372
0
    case BuiltinType::UShortFract:
13373
0
    case BuiltinType::SatUShortFract:
13374
0
    case BuiltinType::UFract:
13375
0
    case BuiltinType::SatUFract:
13376
0
    case BuiltinType::ULongFract:
13377
0
    case BuiltinType::SatULongFract:
13378
0
      return 0;
13379
0
  }
13380
0
}
13381
13382
llvm::FixedPointSemantics
13383
0
ASTContext::getFixedPointSemantics(QualType Ty) const {
13384
0
  assert((Ty->isFixedPointType() || Ty->isIntegerType()) &&
13385
0
         "Can only get the fixed point semantics for a "
13386
0
         "fixed point or integer type.");
13387
0
  if (Ty->isIntegerType())
13388
0
    return llvm::FixedPointSemantics::GetIntegerSemantics(
13389
0
        getIntWidth(Ty), Ty->isSignedIntegerType());
13390
13391
0
  bool isSigned = Ty->isSignedFixedPointType();
13392
0
  return llvm::FixedPointSemantics(
13393
0
      static_cast<unsigned>(getTypeSize(Ty)), getFixedPointScale(Ty), isSigned,
13394
0
      Ty->isSaturatedFixedPointType(),
13395
0
      !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding());
13396
0
}
13397
13398
0
llvm::APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const {
13399
0
  assert(Ty->isFixedPointType());
13400
0
  return llvm::APFixedPoint::getMax(getFixedPointSemantics(Ty));
13401
0
}
13402
13403
0
llvm::APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const {
13404
0
  assert(Ty->isFixedPointType());
13405
0
  return llvm::APFixedPoint::getMin(getFixedPointSemantics(Ty));
13406
0
}
13407
13408
0
QualType ASTContext::getCorrespondingSignedFixedPointType(QualType Ty) const {
13409
0
  assert(Ty->isUnsignedFixedPointType() &&
13410
0
         "Expected unsigned fixed point type");
13411
13412
0
  switch (Ty->castAs<BuiltinType>()->getKind()) {
13413
0
  case BuiltinType::UShortAccum:
13414
0
    return ShortAccumTy;
13415
0
  case BuiltinType::UAccum:
13416
0
    return AccumTy;
13417
0
  case BuiltinType::ULongAccum:
13418
0
    return LongAccumTy;
13419
0
  case BuiltinType::SatUShortAccum:
13420
0
    return SatShortAccumTy;
13421
0
  case BuiltinType::SatUAccum:
13422
0
    return SatAccumTy;
13423
0
  case BuiltinType::SatULongAccum:
13424
0
    return SatLongAccumTy;
13425
0
  case BuiltinType::UShortFract:
13426
0
    return ShortFractTy;
13427
0
  case BuiltinType::UFract:
13428
0
    return FractTy;
13429
0
  case BuiltinType::ULongFract:
13430
0
    return LongFractTy;
13431
0
  case BuiltinType::SatUShortFract:
13432
0
    return SatShortFractTy;
13433
0
  case BuiltinType::SatUFract:
13434
0
    return SatFractTy;
13435
0
  case BuiltinType::SatULongFract:
13436
0
    return SatLongFractTy;
13437
0
  default:
13438
0
    llvm_unreachable("Unexpected unsigned fixed point type");
13439
0
  }
13440
0
}
13441
13442
std::vector<std::string> ASTContext::filterFunctionTargetVersionAttrs(
13443
0
    const TargetVersionAttr *TV) const {
13444
0
  assert(TV != nullptr);
13445
0
  llvm::SmallVector<StringRef, 8> Feats;
13446
0
  std::vector<std::string> ResFeats;
13447
0
  TV->getFeatures(Feats);
13448
0
  for (auto &Feature : Feats)
13449
0
    if (Target->validateCpuSupports(Feature.str()))
13450
      // Use '?' to mark features that came from TargetVersion.
13451
0
      ResFeats.push_back("?" + Feature.str());
13452
0
  return ResFeats;
13453
0
}
13454
13455
ParsedTargetAttr
13456
0
ASTContext::filterFunctionTargetAttrs(const TargetAttr *TD) const {
13457
0
  assert(TD != nullptr);
13458
0
  ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(TD->getFeaturesStr());
13459
13460
0
  llvm::erase_if(ParsedAttr.Features, [&](const std::string &Feat) {
13461
0
    return !Target->isValidFeatureName(StringRef{Feat}.substr(1));
13462
0
  });
13463
0
  return ParsedAttr;
13464
0
}
13465
13466
void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
13467
0
                                       const FunctionDecl *FD) const {
13468
0
  if (FD)
13469
0
    getFunctionFeatureMap(FeatureMap, GlobalDecl().getWithDecl(FD));
13470
0
  else
13471
0
    Target->initFeatureMap(FeatureMap, getDiagnostics(),
13472
0
                           Target->getTargetOpts().CPU,
13473
0
                           Target->getTargetOpts().Features);
13474
0
}
13475
13476
// Fills in the supplied string map with the set of target features for the
13477
// passed in function.
13478
void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
13479
0
                                       GlobalDecl GD) const {
13480
0
  StringRef TargetCPU = Target->getTargetOpts().CPU;
13481
0
  const FunctionDecl *FD = GD.getDecl()->getAsFunction();
13482
0
  if (const auto *TD = FD->getAttr<TargetAttr>()) {
13483
0
    ParsedTargetAttr ParsedAttr = filterFunctionTargetAttrs(TD);
13484
13485
    // Make a copy of the features as passed on the command line into the
13486
    // beginning of the additional features from the function to override.
13487
0
    ParsedAttr.Features.insert(
13488
0
        ParsedAttr.Features.begin(),
13489
0
        Target->getTargetOpts().FeaturesAsWritten.begin(),
13490
0
        Target->getTargetOpts().FeaturesAsWritten.end());
13491
13492
0
    if (ParsedAttr.CPU != "" && Target->isValidCPUName(ParsedAttr.CPU))
13493
0
      TargetCPU = ParsedAttr.CPU;
13494
13495
    // Now populate the feature map, first with the TargetCPU which is either
13496
    // the default or a new one from the target attribute string. Then we'll use
13497
    // the passed in features (FeaturesAsWritten) along with the new ones from
13498
    // the attribute.
13499
0
    Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU,
13500
0
                           ParsedAttr.Features);
13501
0
  } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) {
13502
0
    llvm::SmallVector<StringRef, 32> FeaturesTmp;
13503
0
    Target->getCPUSpecificCPUDispatchFeatures(
13504
0
        SD->getCPUName(GD.getMultiVersionIndex())->getName(), FeaturesTmp);
13505
0
    std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end());
13506
0
    Features.insert(Features.begin(),
13507
0
                    Target->getTargetOpts().FeaturesAsWritten.begin(),
13508
0
                    Target->getTargetOpts().FeaturesAsWritten.end());
13509
0
    Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
13510
0
  } else if (const auto *TC = FD->getAttr<TargetClonesAttr>()) {
13511
0
    std::vector<std::string> Features;
13512
0
    StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
13513
0
    if (Target->getTriple().isAArch64()) {
13514
      // TargetClones for AArch64
13515
0
      if (VersionStr != "default") {
13516
0
        SmallVector<StringRef, 1> VersionFeatures;
13517
0
        VersionStr.split(VersionFeatures, "+");
13518
0
        for (auto &VFeature : VersionFeatures) {
13519
0
          VFeature = VFeature.trim();
13520
          // Use '?' to mark features that came from AArch64 TargetClones.
13521
0
          Features.push_back((StringRef{"?"} + VFeature).str());
13522
0
        }
13523
0
      }
13524
0
      Features.insert(Features.begin(),
13525
0
                      Target->getTargetOpts().FeaturesAsWritten.begin(),
13526
0
                      Target->getTargetOpts().FeaturesAsWritten.end());
13527
0
    } else {
13528
0
      if (VersionStr.starts_with("arch="))
13529
0
        TargetCPU = VersionStr.drop_front(sizeof("arch=") - 1);
13530
0
      else if (VersionStr != "default")
13531
0
        Features.push_back((StringRef{"+"} + VersionStr).str());
13532
0
    }
13533
0
    Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
13534
0
  } else if (const auto *TV = FD->getAttr<TargetVersionAttr>()) {
13535
0
    std::vector<std::string> Feats = filterFunctionTargetVersionAttrs(TV);
13536
0
    Feats.insert(Feats.begin(),
13537
0
                 Target->getTargetOpts().FeaturesAsWritten.begin(),
13538
0
                 Target->getTargetOpts().FeaturesAsWritten.end());
13539
0
    Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Feats);
13540
0
  } else {
13541
0
    FeatureMap = Target->getTargetOpts().FeatureMap;
13542
0
  }
13543
0
}
13544
13545
0
OMPTraitInfo &ASTContext::getNewOMPTraitInfo() {
13546
0
  OMPTraitInfoVector.emplace_back(new OMPTraitInfo());
13547
0
  return *OMPTraitInfoVector.back();
13548
0
}
13549
13550
const StreamingDiagnostic &clang::
13551
operator<<(const StreamingDiagnostic &DB,
13552
0
           const ASTContext::SectionInfo &Section) {
13553
0
  if (Section.Decl)
13554
0
    return DB << Section.Decl;
13555
0
  return DB << "a prior #pragma section";
13556
0
}
13557
13558
0
bool ASTContext::mayExternalize(const Decl *D) const {
13559
0
  bool IsInternalVar =
13560
0
      isa<VarDecl>(D) &&
13561
0
      basicGVALinkageForVariable(*this, cast<VarDecl>(D)) == GVA_Internal;
13562
0
  bool IsExplicitDeviceVar = (D->hasAttr<CUDADeviceAttr>() &&
13563
0
                              !D->getAttr<CUDADeviceAttr>()->isImplicit()) ||
13564
0
                             (D->hasAttr<CUDAConstantAttr>() &&
13565
0
                              !D->getAttr<CUDAConstantAttr>()->isImplicit());
13566
  // CUDA/HIP: managed variables need to be externalized since it is
13567
  // a declaration in IR, therefore cannot have internal linkage. Kernels in
13568
  // anonymous name space needs to be externalized to avoid duplicate symbols.
13569
0
  return (IsInternalVar &&
13570
0
          (D->hasAttr<HIPManagedAttr>() || IsExplicitDeviceVar)) ||
13571
0
         (D->hasAttr<CUDAGlobalAttr>() &&
13572
0
          basicGVALinkageForFunction(*this, cast<FunctionDecl>(D)) ==
13573
0
              GVA_Internal);
13574
0
}
13575
13576
0
bool ASTContext::shouldExternalize(const Decl *D) const {
13577
0
  return mayExternalize(D) &&
13578
0
         (D->hasAttr<HIPManagedAttr>() || D->hasAttr<CUDAGlobalAttr>() ||
13579
0
          CUDADeviceVarODRUsedByHost.count(cast<VarDecl>(D)));
13580
0
}
13581
13582
0
StringRef ASTContext::getCUIDHash() const {
13583
0
  if (!CUIDHash.empty())
13584
0
    return CUIDHash;
13585
0
  if (LangOpts.CUID.empty())
13586
0
    return StringRef();
13587
0
  CUIDHash = llvm::utohexstr(llvm::MD5Hash(LangOpts.CUID), /*LowerCase=*/true);
13588
0
  return CUIDHash;
13589
0
}