Coverage Report

Created: 2022-07-16 07:03

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