blob: 10b6718c89b9f4f499b0bcebaa56a4a182e04fa4 [file] [log] [blame]
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00001//===- ASTContext.cpp - Context to hold long-lived AST nodes --------------===//
Chris Lattnerddc135e2006-11-10 06:34:16 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Chris Lattnerddc135e2006-11-10 06:34:16 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the ASTContext interface.
10//
11//===----------------------------------------------------------------------===//
12
13#include "clang/AST/ASTContext.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000014#include "CXXABI.h"
Nandor Licker950b70d2019-09-13 09:46:16 +000015#include "Interp/Context.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000016#include "clang/AST/APValue.h"
Saar Razfdf80e82019-12-06 01:30:21 +020017#include "clang/AST/ASTConcept.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000018#include "clang/AST/ASTMutationListener.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000019#include "clang/AST/ASTTypeTraits.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000020#include "clang/AST/Attr.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000021#include "clang/AST/AttrIterator.h"
Ken Dyck8c89d592009-12-22 14:23:30 +000022#include "clang/AST/CharUnits.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000023#include "clang/AST/Comment.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000024#include "clang/AST/Decl.h"
25#include "clang/AST/DeclBase.h"
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +000026#include "clang/AST/DeclCXX.h"
Chandler Carruthaa36b892015-12-30 03:40:23 +000027#include "clang/AST/DeclContextInternals.h"
Steve Naroff67391b82007-10-01 19:00:59 +000028#include "clang/AST/DeclObjC.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000029#include "clang/AST/DeclOpenMP.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000030#include "clang/AST/DeclTemplate.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000031#include "clang/AST/DeclarationName.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000032#include "clang/AST/Expr.h"
John McCall87fe5d52010-05-20 01:18:31 +000033#include "clang/AST/ExprCXX.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000034#include "clang/AST/ExternalASTSource.h"
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000035#include "clang/AST/Mangle.h"
Reid Klecknerd8110b62013-09-10 20:14:30 +000036#include "clang/AST/MangleNumberingContext.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000037#include "clang/AST/NestedNameSpecifier.h"
38#include "clang/AST/RawCommentList.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000039#include "clang/AST/RecordLayout.h"
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000040#include "clang/AST/RecursiveASTVisitor.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000041#include "clang/AST/Stmt.h"
42#include "clang/AST/TemplateBase.h"
43#include "clang/AST/TemplateName.h"
44#include "clang/AST/Type.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000045#include "clang/AST/TypeLoc.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000046#include "clang/AST/UnresolvedSet.h"
Reid Kleckner96f8f932014-02-05 17:27:08 +000047#include "clang/AST/VTableBuilder.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000048#include "clang/Basic/AddressSpaces.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000049#include "clang/Basic/Builtins.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000050#include "clang/Basic/CommentOptions.h"
Eugene Zelenko7855e772018-04-03 00:11:50 +000051#include "clang/Basic/ExceptionSpecificationType.h"
Leonard Chana6779422018-08-06 16:42:37 +000052#include "clang/Basic/FixedPoint.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000053#include "clang/Basic/IdentifierTable.h"
54#include "clang/Basic/LLVM.h"
55#include "clang/Basic/LangOptions.h"
56#include "clang/Basic/Linkage.h"
57#include "clang/Basic/ObjCRuntime.h"
58#include "clang/Basic/SanitizerBlacklist.h"
59#include "clang/Basic/SourceLocation.h"
Chris Lattnerd2868512009-03-28 03:45:20 +000060#include "clang/Basic/SourceManager.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000061#include "clang/Basic/Specifiers.h"
62#include "clang/Basic/TargetCXXABI.h"
Chris Lattner4dc8a6f2007-05-20 23:50:58 +000063#include "clang/Basic/TargetInfo.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000064#include "clang/Basic/XRayLists.h"
65#include "llvm/ADT/APInt.h"
66#include "llvm/ADT/APSInt.h"
67#include "llvm/ADT/ArrayRef.h"
68#include "llvm/ADT/DenseMap.h"
69#include "llvm/ADT/DenseSet.h"
70#include "llvm/ADT/FoldingSet.h"
71#include "llvm/ADT/None.h"
72#include "llvm/ADT/Optional.h"
73#include "llvm/ADT/PointerUnion.h"
74#include "llvm/ADT/STLExtras.h"
75#include "llvm/ADT/SmallPtrSet.h"
76#include "llvm/ADT/SmallVector.h"
Anders Carlssond8499822007-10-29 05:01:08 +000077#include "llvm/ADT/StringExtras.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000078#include "llvm/ADT/StringRef.h"
Robert Lyttoneaf6f362013-11-12 10:09:34 +000079#include "llvm/ADT/Triple.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000080#include "llvm/Support/Capacity.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000081#include "llvm/Support/Casting.h"
82#include "llvm/Support/Compiler.h"
83#include "llvm/Support/ErrorHandling.h"
Nate Begemanb699c9b2009-01-18 06:42:49 +000084#include "llvm/Support/MathExtras.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000085#include "llvm/Support/raw_ostream.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000086#include <algorithm>
87#include <cassert>
88#include <cstddef>
89#include <cstdint>
90#include <cstdlib>
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +000091#include <map>
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000092#include <memory>
93#include <string>
94#include <tuple>
95#include <utility>
Anders Carlssona4267a62009-07-18 21:19:52 +000096
Chris Lattnerddc135e2006-11-10 06:34:16 +000097using namespace clang;
98
Steve Naroff0af91202007-04-27 21:51:21 +000099enum FloatingRank {
Sjoerd Meijercc623ad2017-09-08 15:15:00 +0000100 Float16Rank, HalfRank, FloatRank, DoubleRank, LongDoubleRank, Float128Rank
Steve Naroff0af91202007-04-27 21:51:21 +0000101};
102
Jan Korousf31d8df2019-08-13 18:11:44 +0000103/// \returns location that is relevant when searching for Doc comments related
104/// to \p D.
105static SourceLocation getDeclLocForCommentSearch(const Decl *D,
106 SourceManager &SourceMgr) {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000107 assert(D);
108
Dmitri Gribenkodf17d642012-06-28 16:19:39 +0000109 // User can not attach documentation to implicit declarations.
110 if (D->isImplicit())
Jan Korousf31d8df2019-08-13 18:11:44 +0000111 return {};
Dmitri Gribenkodf17d642012-06-28 16:19:39 +0000112
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000113 // User can not attach documentation to implicit instantiations.
Eugene Zelenko7855e772018-04-03 00:11:50 +0000114 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000115 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Jan Korousf31d8df2019-08-13 18:11:44 +0000116 return {};
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000117 }
118
Eugene Zelenko7855e772018-04-03 00:11:50 +0000119 if (const auto *VD = dyn_cast<VarDecl>(D)) {
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000120 if (VD->isStaticDataMember() &&
121 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Jan Korousf31d8df2019-08-13 18:11:44 +0000122 return {};
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000123 }
124
Eugene Zelenko7855e772018-04-03 00:11:50 +0000125 if (const auto *CRD = dyn_cast<CXXRecordDecl>(D)) {
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000126 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Jan Korousf31d8df2019-08-13 18:11:44 +0000127 return {};
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000128 }
129
Eugene Zelenko7855e772018-04-03 00:11:50 +0000130 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000131 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
132 if (TSK == TSK_ImplicitInstantiation ||
133 TSK == TSK_Undeclared)
Jan Korousf31d8df2019-08-13 18:11:44 +0000134 return {};
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000135 }
136
Eugene Zelenko7855e772018-04-03 00:11:50 +0000137 if (const auto *ED = dyn_cast<EnumDecl>(D)) {
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000138 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Jan Korousf31d8df2019-08-13 18:11:44 +0000139 return {};
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000140 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000141 if (const auto *TD = dyn_cast<TagDecl>(D)) {
Fariborz Jahanian799a4032013-04-17 21:05:20 +0000142 // When tag declaration (but not definition!) is part of the
143 // decl-specifier-seq of some other declaration, it doesn't get comment
144 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
Jan Korousf31d8df2019-08-13 18:11:44 +0000145 return {};
Fariborz Jahanian799a4032013-04-17 21:05:20 +0000146 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000147 // TODO: handle comments for function parameters properly.
148 if (isa<ParmVarDecl>(D))
Jan Korousf31d8df2019-08-13 18:11:44 +0000149 return {};
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000150
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000151 // TODO: we could look up template parameter documentation in the template
152 // documentation.
153 if (isa<TemplateTypeParmDecl>(D) ||
154 isa<NonTypeTemplateParmDecl>(D) ||
155 isa<TemplateTemplateParmDecl>(D))
Jan Korousf31d8df2019-08-13 18:11:44 +0000156 return {};
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000157
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000158 // Find declaration location.
159 // For Objective-C declarations we generally don't expect to have multiple
160 // declarators, thus use declaration starting location as the "declaration
161 // location".
162 // For all other declarations multiple declarators are used quite frequently,
163 // so we use the location of the identifier as the "declaration location".
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000164 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000165 isa<ObjCPropertyDecl>(D) ||
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +0000166 isa<RedeclarableTemplateDecl>(D) ||
Sam McCalla433e712019-11-13 21:30:31 +0100167 isa<ClassTemplateSpecializationDecl>(D) ||
168 // Allow association with Y across {} in `typedef struct X {} Y`.
169 isa<TypedefDecl>(D))
Jan Korousf31d8df2019-08-13 18:11:44 +0000170 return D->getBeginLoc();
Fariborz Jahanianb64e95f2013-07-24 22:58:51 +0000171 else {
Jan Korousf31d8df2019-08-13 18:11:44 +0000172 const SourceLocation DeclLoc = D->getLocation();
Dmitri Gribenkoef099dc2014-03-27 16:40:51 +0000173 if (DeclLoc.isMacroID()) {
174 if (isa<TypedefDecl>(D)) {
175 // If location of the typedef name is in a macro, it is because being
176 // declared via a macro. Try using declaration's starting location as
177 // the "declaration location".
Jan Korousf31d8df2019-08-13 18:11:44 +0000178 return D->getBeginLoc();
Eugene Zelenko7855e772018-04-03 00:11:50 +0000179 } else if (const auto *TD = dyn_cast<TagDecl>(D)) {
Dmitri Gribenkoef099dc2014-03-27 16:40:51 +0000180 // If location of the tag decl is inside a macro, but the spelling of
181 // the tag name comes from a macro argument, it looks like a special
182 // macro like NS_ENUM is being used to define the tag decl. In that
183 // case, adjust the source location to the expansion loc so that we can
184 // attach the comment to the tag decl.
185 if (SourceMgr.isMacroArgExpansion(DeclLoc) &&
186 TD->isCompleteDefinition())
Jan Korousf31d8df2019-08-13 18:11:44 +0000187 return SourceMgr.getExpansionLoc(DeclLoc);
Dmitri Gribenkoef099dc2014-03-27 16:40:51 +0000188 }
189 }
Jan Korousf31d8df2019-08-13 18:11:44 +0000190 return DeclLoc;
Fariborz Jahanianb64e95f2013-07-24 22:58:51 +0000191 }
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000192
Jan Korousf31d8df2019-08-13 18:11:44 +0000193 return {};
194}
195
196RawComment *ASTContext::getRawCommentForDeclNoCacheImpl(
197 const Decl *D, const SourceLocation RepresentativeLocForDecl,
198 const std::map<unsigned, RawComment *> &CommentsInTheFile) const {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000199 // If the declaration doesn't map directly to a location in a file, we
200 // can't find the comment.
Jan Korousf31d8df2019-08-13 18:11:44 +0000201 if (RepresentativeLocForDecl.isInvalid() ||
202 !RepresentativeLocForDecl.isFileID())
Craig Topper36250ad2014-05-12 05:36:57 +0000203 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000204
Jan Korous6644d012019-04-10 20:23:33 +0000205 // If there are no comments anywhere, we won't find anything.
Jan Korousf31d8df2019-08-13 18:11:44 +0000206 if (CommentsInTheFile.empty())
Jan Korous6644d012019-04-10 20:23:33 +0000207 return nullptr;
208
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000209 // Decompose the location for the declaration and find the beginning of the
210 // file buffer.
Jan Korousf31d8df2019-08-13 18:11:44 +0000211 const std::pair<FileID, unsigned> DeclLocDecomp =
212 SourceMgr.getDecomposedLoc(RepresentativeLocForDecl);
213
214 // Slow path.
215 auto OffsetCommentBehindDecl =
216 CommentsInTheFile.lower_bound(DeclLocDecomp.second);
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000217
218 // First check whether we have a trailing comment.
Jan Korousf31d8df2019-08-13 18:11:44 +0000219 if (OffsetCommentBehindDecl != CommentsInTheFile.end()) {
220 RawComment *CommentBehindDecl = OffsetCommentBehindDecl->second;
221 if ((CommentBehindDecl->isDocumentation() ||
222 LangOpts.CommentOpts.ParseAllComments) &&
223 CommentBehindDecl->isTrailingComment() &&
224 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
225 isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
226
227 // Check that Doxygen trailing comment comes after the declaration, starts
228 // on the same line and in the same file as the declaration.
229 if (SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second) ==
230 Comments.getCommentBeginLine(CommentBehindDecl, DeclLocDecomp.first,
231 OffsetCommentBehindDecl->first)) {
232 return CommentBehindDecl;
233 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000234 }
235 }
236
237 // The comment just after the declaration was not a trailing comment.
238 // Let's look at the previous comment.
Jan Korousf31d8df2019-08-13 18:11:44 +0000239 if (OffsetCommentBehindDecl == CommentsInTheFile.begin())
Craig Topper36250ad2014-05-12 05:36:57 +0000240 return nullptr;
Jan Korousf31d8df2019-08-13 18:11:44 +0000241
242 auto OffsetCommentBeforeDecl = --OffsetCommentBehindDecl;
243 RawComment *CommentBeforeDecl = OffsetCommentBeforeDecl->second;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000244
245 // Check that we actually have a non-member Doxygen comment.
Jan Korousf31d8df2019-08-13 18:11:44 +0000246 if (!(CommentBeforeDecl->isDocumentation() ||
David L. Jones13d5a872018-03-02 00:07:45 +0000247 LangOpts.CommentOpts.ParseAllComments) ||
Jan Korousf31d8df2019-08-13 18:11:44 +0000248 CommentBeforeDecl->isTrailingComment())
Craig Topper36250ad2014-05-12 05:36:57 +0000249 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000250
251 // Decompose the end of the comment.
Jan Korousf31d8df2019-08-13 18:11:44 +0000252 const unsigned CommentEndOffset =
253 Comments.getCommentEndOffset(CommentBeforeDecl);
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000254
255 // Get the corresponding buffer.
256 bool Invalid = false;
257 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
258 &Invalid).data();
259 if (Invalid)
Craig Topper36250ad2014-05-12 05:36:57 +0000260 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000261
262 // Extract text between the comment and declaration.
Jan Korousf31d8df2019-08-13 18:11:44 +0000263 StringRef Text(Buffer + CommentEndOffset,
264 DeclLocDecomp.second - CommentEndOffset);
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000265
Dmitri Gribenko7e8729b2012-06-27 23:43:37 +0000266 // There should be no other declarations or preprocessor directives between
267 // comment and declaration.
Argyrios Kyrtzidisb534d3a2013-07-26 18:38:12 +0000268 if (Text.find_first_of(";{}#@") != StringRef::npos)
Craig Topper36250ad2014-05-12 05:36:57 +0000269 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000270
Jan Korousf31d8df2019-08-13 18:11:44 +0000271 return CommentBeforeDecl;
272}
273
274RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
275 const SourceLocation DeclLoc = getDeclLocForCommentSearch(D, SourceMgr);
276
277 // If the declaration doesn't map directly to a location in a file, we
278 // can't find the comment.
279 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
280 return nullptr;
281
282 if (ExternalSource && !CommentsLoaded) {
283 ExternalSource->ReadComments();
284 CommentsLoaded = true;
285 }
286
287 if (Comments.empty())
288 return nullptr;
289
290 const FileID File = SourceMgr.getDecomposedLoc(DeclLoc).first;
291 const auto CommentsInThisFile = Comments.getCommentsInFile(File);
292 if (!CommentsInThisFile || CommentsInThisFile->empty())
293 return nullptr;
294
295 return getRawCommentForDeclNoCacheImpl(D, DeclLoc, *CommentsInThisFile);
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000296}
297
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000298/// If we have a 'templated' declaration for a template, adjust 'D' to
299/// refer to the actual template.
Dmitri Gribenko90631802012-08-22 17:44:32 +0000300/// If we have an implicit instantiation, adjust 'D' to refer to template.
Jan Korousf31d8df2019-08-13 18:11:44 +0000301static const Decl &adjustDeclToTemplate(const Decl &D) {
302 if (const auto *FD = dyn_cast<FunctionDecl>(&D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000303 // Is this function declaration part of a function template?
Douglas Gregor35ceb272012-08-13 16:37:30 +0000304 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
Jan Korousf31d8df2019-08-13 18:11:44 +0000305 return *FTD;
Dmitri Gribenko90631802012-08-22 17:44:32 +0000306
307 // Nothing to do if function is not an implicit instantiation.
308 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
309 return D;
310
311 // Function is an implicit instantiation of a function template?
312 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
Jan Korousf31d8df2019-08-13 18:11:44 +0000313 return *FTD;
Dmitri Gribenko90631802012-08-22 17:44:32 +0000314
315 // Function is instantiated from a member definition of a class template?
316 if (const FunctionDecl *MemberDecl =
317 FD->getInstantiatedFromMemberFunction())
Jan Korousf31d8df2019-08-13 18:11:44 +0000318 return *MemberDecl;
Dmitri Gribenko90631802012-08-22 17:44:32 +0000319
320 return D;
Douglas Gregor35ceb272012-08-13 16:37:30 +0000321 }
Jan Korousf31d8df2019-08-13 18:11:44 +0000322 if (const auto *VD = dyn_cast<VarDecl>(&D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000323 // Static data member is instantiated from a member definition of a class
324 // template?
325 if (VD->isStaticDataMember())
326 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
Jan Korousf31d8df2019-08-13 18:11:44 +0000327 return *MemberDecl;
Dmitri Gribenko90631802012-08-22 17:44:32 +0000328
329 return D;
330 }
Jan Korousf31d8df2019-08-13 18:11:44 +0000331 if (const auto *CRD = dyn_cast<CXXRecordDecl>(&D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000332 // Is this class declaration part of a class template?
333 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
Jan Korousf31d8df2019-08-13 18:11:44 +0000334 return *CTD;
Dmitri Gribenko90631802012-08-22 17:44:32 +0000335
336 // Class is an implicit instantiation of a class template or partial
337 // specialization?
Eugene Zelenko7855e772018-04-03 00:11:50 +0000338 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000339 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
340 return D;
341 llvm::PointerUnion<ClassTemplateDecl *,
342 ClassTemplatePartialSpecializationDecl *>
343 PU = CTSD->getSpecializedTemplateOrPartial();
Jan Korousf31d8df2019-08-13 18:11:44 +0000344 return PU.is<ClassTemplateDecl *>()
345 ? *static_cast<const Decl *>(PU.get<ClassTemplateDecl *>())
346 : *static_cast<const Decl *>(
347 PU.get<ClassTemplatePartialSpecializationDecl *>());
Dmitri Gribenko90631802012-08-22 17:44:32 +0000348 }
349
350 // Class is instantiated from a member definition of a class template?
351 if (const MemberSpecializationInfo *Info =
Jan Korousf31d8df2019-08-13 18:11:44 +0000352 CRD->getMemberSpecializationInfo())
353 return *Info->getInstantiatedFrom();
Dmitri Gribenko90631802012-08-22 17:44:32 +0000354
355 return D;
356 }
Jan Korousf31d8df2019-08-13 18:11:44 +0000357 if (const auto *ED = dyn_cast<EnumDecl>(&D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000358 // Enum is instantiated from a member definition of a class template?
359 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
Jan Korousf31d8df2019-08-13 18:11:44 +0000360 return *MemberDecl;
Dmitri Gribenko90631802012-08-22 17:44:32 +0000361
362 return D;
363 }
364 // FIXME: Adjust alias templates?
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000365 return D;
366}
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000367
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000368const RawComment *ASTContext::getRawCommentForAnyRedecl(
369 const Decl *D,
370 const Decl **OriginalDecl) const {
Jan Korousf31d8df2019-08-13 18:11:44 +0000371 if (!D) {
372 if (OriginalDecl)
373 OriginalDecl = nullptr;
374 return nullptr;
375 }
Douglas Gregor35ceb272012-08-13 16:37:30 +0000376
Jan Korousf31d8df2019-08-13 18:11:44 +0000377 D = &adjustDeclToTemplate(*D);
378
379 // Any comment directly attached to D?
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000380 {
Jan Korousf31d8df2019-08-13 18:11:44 +0000381 auto DeclComment = DeclRawComments.find(D);
382 if (DeclComment != DeclRawComments.end()) {
383 if (OriginalDecl)
384 *OriginalDecl = D;
385 return DeclComment->second;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000386 }
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000387 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000388
Jan Korousf31d8df2019-08-13 18:11:44 +0000389 // Any comment attached to any redeclaration of D?
390 const Decl *CanonicalD = D->getCanonicalDecl();
391 if (!CanonicalD)
392 return nullptr;
393
394 {
395 auto RedeclComment = RedeclChainComments.find(CanonicalD);
396 if (RedeclComment != RedeclChainComments.end()) {
397 if (OriginalDecl)
398 *OriginalDecl = RedeclComment->second;
399 auto CommentAtRedecl = DeclRawComments.find(RedeclComment->second);
400 assert(CommentAtRedecl != DeclRawComments.end() &&
401 "This decl is supposed to have comment attached.");
402 return CommentAtRedecl->second;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000403 }
404 }
405
Jan Korousf31d8df2019-08-13 18:11:44 +0000406 // Any redeclarations of D that we haven't checked for comments yet?
407 // We can't use DenseMap::iterator directly since it'd get invalid.
408 auto LastCheckedRedecl = [this, CanonicalD]() -> const Decl * {
409 auto LookupRes = CommentlessRedeclChains.find(CanonicalD);
410 if (LookupRes != CommentlessRedeclChains.end())
411 return LookupRes->second;
412 return nullptr;
413 }();
414
415 for (const auto Redecl : D->redecls()) {
416 assert(Redecl);
417 // Skip all redeclarations that have been checked previously.
418 if (LastCheckedRedecl) {
419 if (LastCheckedRedecl == Redecl) {
420 LastCheckedRedecl = nullptr;
421 }
422 continue;
423 }
424 const RawComment *RedeclComment = getRawCommentForDeclNoCache(Redecl);
425 if (RedeclComment) {
426 cacheRawCommentForDecl(*Redecl, *RedeclComment);
427 if (OriginalDecl)
428 *OriginalDecl = Redecl;
429 return RedeclComment;
430 }
431 CommentlessRedeclChains[CanonicalD] = Redecl;
432 }
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000433
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000434 if (OriginalDecl)
Jan Korousf31d8df2019-08-13 18:11:44 +0000435 *OriginalDecl = nullptr;
436 return nullptr;
437}
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000438
Jan Korousf31d8df2019-08-13 18:11:44 +0000439void ASTContext::cacheRawCommentForDecl(const Decl &OriginalD,
440 const RawComment &Comment) const {
441 assert(Comment.isDocumentation() || LangOpts.CommentOpts.ParseAllComments);
442 DeclRawComments.try_emplace(&OriginalD, &Comment);
443 const Decl *const CanonicalDecl = OriginalD.getCanonicalDecl();
444 RedeclChainComments.try_emplace(CanonicalDecl, &OriginalD);
445 CommentlessRedeclChains.erase(CanonicalDecl);
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000446}
447
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000448static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
449 SmallVectorImpl<const NamedDecl *> &Redeclared) {
450 const DeclContext *DC = ObjCMethod->getDeclContext();
Eugene Zelenko7855e772018-04-03 00:11:50 +0000451 if (const auto *IMD = dyn_cast<ObjCImplDecl>(DC)) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000452 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
453 if (!ID)
454 return;
455 // Add redeclared method here.
Aaron Ballmanb4a53452014-03-13 21:57:01 +0000456 for (const auto *Ext : ID->known_extensions()) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000457 if (ObjCMethodDecl *RedeclaredMethod =
Douglas Gregor048fbfa2013-01-16 23:00:23 +0000458 Ext->getMethod(ObjCMethod->getSelector(),
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000459 ObjCMethod->isInstanceMethod()))
460 Redeclared.push_back(RedeclaredMethod);
461 }
462 }
463}
464
Jan Korousf31d8df2019-08-13 18:11:44 +0000465void ASTContext::attachCommentsToJustParsedDecls(ArrayRef<Decl *> Decls,
466 const Preprocessor *PP) {
467 if (Comments.empty() || Decls.empty())
468 return;
469
470 // See if there are any new comments that are not attached to a decl.
471 // The location doesn't have to be precise - we care only about the file.
472 const FileID File =
473 SourceMgr.getDecomposedLoc((*Decls.begin())->getLocation()).first;
474 auto CommentsInThisFile = Comments.getCommentsInFile(File);
475 if (!CommentsInThisFile || CommentsInThisFile->empty() ||
476 CommentsInThisFile->rbegin()->second->isAttached())
477 return;
478
479 // There is at least one comment not attached to a decl.
480 // Maybe it should be attached to one of Decls?
481 //
482 // Note that this way we pick up not only comments that precede the
483 // declaration, but also comments that *follow* the declaration -- thanks to
484 // the lookahead in the lexer: we've consumed the semicolon and looked
485 // ahead through comments.
486
487 for (const Decl *D : Decls) {
488 assert(D);
489 if (D->isInvalidDecl())
490 continue;
491
492 D = &adjustDeclToTemplate(*D);
493
494 const SourceLocation DeclLoc = getDeclLocForCommentSearch(D, SourceMgr);
495
496 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
497 continue;
498
499 if (DeclRawComments.count(D) > 0)
500 continue;
501
502 if (RawComment *const DocComment =
503 getRawCommentForDeclNoCacheImpl(D, DeclLoc, *CommentsInThisFile)) {
504 cacheRawCommentForDecl(*D, *DocComment);
505 comments::FullComment *FC = DocComment->parse(*this, PP, D);
506 ParsedComments[D->getCanonicalDecl()] = FC;
507 }
508 }
509}
510
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000511comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
512 const Decl *D) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +0000513 auto *ThisDeclInfo = new (*this) comments::DeclInfo;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000514 ThisDeclInfo->CommentDecl = D;
515 ThisDeclInfo->IsFilled = false;
516 ThisDeclInfo->fill();
517 ThisDeclInfo->CommentDecl = FC->getDecl();
Argyrios Kyrtzidis7daabbd2014-04-27 22:53:03 +0000518 if (!ThisDeclInfo->TemplateParameters)
519 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000520 comments::FullComment *CFC =
521 new (*this) comments::FullComment(FC->getBlocks(),
522 ThisDeclInfo);
523 return CFC;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000524}
525
Richard Smithb39b9d52013-05-21 05:24:00 +0000526comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
527 const RawComment *RC = getRawCommentForDeclNoCache(D);
Craig Topper36250ad2014-05-12 05:36:57 +0000528 return RC ? RC->parse(*this, nullptr, D) : nullptr;
Richard Smithb39b9d52013-05-21 05:24:00 +0000529}
530
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000531comments::FullComment *ASTContext::getCommentForDecl(
532 const Decl *D,
533 const Preprocessor *PP) const {
Jan Korousf31d8df2019-08-13 18:11:44 +0000534 if (!D || D->isInvalidDecl())
Craig Topper36250ad2014-05-12 05:36:57 +0000535 return nullptr;
Jan Korousf31d8df2019-08-13 18:11:44 +0000536 D = &adjustDeclToTemplate(*D);
Fangrui Song6907ce22018-07-30 19:24:48 +0000537
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000538 const Decl *Canonical = D->getCanonicalDecl();
539 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
540 ParsedComments.find(Canonical);
Fangrui Song6907ce22018-07-30 19:24:48 +0000541
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000542 if (Pos != ParsedComments.end()) {
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000543 if (Canonical != D) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000544 comments::FullComment *FC = Pos->second;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000545 comments::FullComment *CFC = cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000546 return CFC;
547 }
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000548 return Pos->second;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000549 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000550
Jan Korousf31d8df2019-08-13 18:11:44 +0000551 const Decl *OriginalDecl = nullptr;
Fangrui Song6907ce22018-07-30 19:24:48 +0000552
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000553 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000554 if (!RC) {
555 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000556 SmallVector<const NamedDecl*, 8> Overridden;
Eugene Zelenko7855e772018-04-03 00:11:50 +0000557 const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000558 if (OMD && OMD->isPropertyAccessor())
559 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
560 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
561 return cloneFullComment(FC, D);
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000562 if (OMD)
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000563 addRedeclaredMethods(OMD, Overridden);
564 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000565 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
566 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
567 return cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000568 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000569 else if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000570 // Attach any tag type's documentation to its typedef if latter
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000571 // does not have one of its own.
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000572 QualType QT = TD->getUnderlyingType();
Eugene Zelenko7855e772018-04-03 00:11:50 +0000573 if (const auto *TT = QT->getAs<TagType>())
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000574 if (const Decl *TD = TT->getDecl())
575 if (comments::FullComment *FC = getCommentForDecl(TD, PP))
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000576 return cloneFullComment(FC, D);
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000577 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000578 else if (const auto *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000579 while (IC->getSuperClass()) {
580 IC = IC->getSuperClass();
581 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
582 return cloneFullComment(FC, D);
583 }
584 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000585 else if (const auto *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000586 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
587 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
588 return cloneFullComment(FC, D);
589 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000590 else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000591 if (!(RD = RD->getDefinition()))
Craig Topper36250ad2014-05-12 05:36:57 +0000592 return nullptr;
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000593 // Check non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +0000594 for (const auto &I : RD->bases()) {
595 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000596 continue;
Aaron Ballman574705e2014-03-13 15:41:46 +0000597 QualType Ty = I.getType();
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000598 if (Ty.isNull())
599 continue;
600 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
601 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
602 continue;
Fangrui Song6907ce22018-07-30 19:24:48 +0000603
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000604 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
605 return cloneFullComment(FC, D);
606 }
607 }
608 // Check virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +0000609 for (const auto &I : RD->vbases()) {
610 if (I.getAccessSpecifier() != AS_public)
Fariborz Jahanian5a2e4a22013-04-26 23:34:36 +0000611 continue;
Aaron Ballman445a9392014-03-13 16:15:17 +0000612 QualType Ty = I.getType();
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000613 if (Ty.isNull())
614 continue;
615 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
616 if (!(VirtualBase= VirtualBase->getDefinition()))
617 continue;
618 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
619 return cloneFullComment(FC, D);
620 }
621 }
622 }
Craig Topper36250ad2014-05-12 05:36:57 +0000623 return nullptr;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000624 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000625
Dmitri Gribenkobfda9f72012-08-22 18:12:19 +0000626 // If the RawComment was attached to other redeclaration of this Decl, we
627 // should parse the comment in context of that other Decl. This is important
628 // because comments can contain references to parameter names which can be
629 // different across redeclarations.
Jan Korousf31d8df2019-08-13 18:11:44 +0000630 if (D != OriginalDecl && OriginalDecl)
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000631 return getCommentForDecl(OriginalDecl, PP);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000632
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000633 comments::FullComment *FC = RC->parse(*this, PP, D);
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000634 ParsedComments[Canonical] = FC;
635 return FC;
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000636}
637
Fangrui Song6907ce22018-07-30 19:24:48 +0000638void
639ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000640 TemplateTemplateParmDecl *Parm) {
641 ID.AddInteger(Parm->getDepth());
642 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +0000643 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000644
645 TemplateParameterList *Params = Parm->getTemplateParameters();
646 ID.AddInteger(Params->size());
Fangrui Song6907ce22018-07-30 19:24:48 +0000647 for (TemplateParameterList::const_iterator P = Params->begin(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000648 PEnd = Params->end();
649 P != PEnd; ++P) {
Eugene Zelenko7855e772018-04-03 00:11:50 +0000650 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000651 ID.AddInteger(0);
652 ID.AddBoolean(TTP->isParameterPack());
653 continue;
654 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000655
Eugene Zelenko7855e772018-04-03 00:11:50 +0000656 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000657 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +0000658 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman205a4292012-03-07 01:09:33 +0000659 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000660 if (NTTP->isExpandedParameterPack()) {
661 ID.AddBoolean(true);
662 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman205a4292012-03-07 01:09:33 +0000663 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
664 QualType T = NTTP->getExpansionType(I);
665 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
666 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000667 } else
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000668 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000669 continue;
670 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000671
Eugene Zelenko7855e772018-04-03 00:11:50 +0000672 auto *TTP = cast<TemplateTemplateParmDecl>(*P);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000673 ID.AddInteger(2);
674 Profile(ID, TTP);
675 }
676}
677
678TemplateTemplateParmDecl *
679ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +0000680 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000681 // Check if we already have a canonical template template parameter.
682 llvm::FoldingSetNodeID ID;
683 CanonicalTemplateTemplateParm::Profile(ID, TTP);
Craig Topper36250ad2014-05-12 05:36:57 +0000684 void *InsertPos = nullptr;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000685 CanonicalTemplateTemplateParm *Canonical
686 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
687 if (Canonical)
688 return Canonical->getParam();
Fangrui Song6907ce22018-07-30 19:24:48 +0000689
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000690 // Build a canonical template parameter list.
691 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000692 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000693 CanonParams.reserve(Params->size());
Fangrui Song6907ce22018-07-30 19:24:48 +0000694 for (TemplateParameterList::const_iterator P = Params->begin(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000695 PEnd = Params->end();
696 P != PEnd; ++P) {
Eugene Zelenko7855e772018-04-03 00:11:50 +0000697 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000698 CanonParams.push_back(
Fangrui Song6907ce22018-07-30 19:24:48 +0000699 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000700 SourceLocation(),
701 SourceLocation(),
702 TTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000703 TTP->getIndex(), nullptr, false,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000704 TTP->isParameterPack()));
Eugene Zelenko7855e772018-04-03 00:11:50 +0000705 else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000706 QualType T = getCanonicalType(NTTP->getType());
707 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
708 NonTypeTemplateParmDecl *Param;
709 if (NTTP->isExpandedParameterPack()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000710 SmallVector<QualType, 2> ExpandedTypes;
711 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000712 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
713 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
714 ExpandedTInfos.push_back(
715 getTrivialTypeSourceInfo(ExpandedTypes.back()));
716 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000717
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000718 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000719 SourceLocation(),
720 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000721 NTTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000722 NTTP->getPosition(), nullptr,
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000723 T,
724 TInfo,
David Majnemerdfecf1a2016-07-06 04:19:16 +0000725 ExpandedTypes,
726 ExpandedTInfos);
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000727 } else {
728 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000729 SourceLocation(),
730 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000731 NTTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000732 NTTP->getPosition(), nullptr,
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000733 T,
734 NTTP->isParameterPack(),
735 TInfo);
736 }
737 CanonParams.push_back(Param);
738
739 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000740 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
741 cast<TemplateTemplateParmDecl>(*P)));
742 }
743
Saar Raz0330fba2019-10-15 18:44:06 +0000744 assert(!TTP->getTemplateParameters()->getRequiresClause() &&
Hubert Tonge4a0c0e2016-07-30 22:33:34 +0000745 "Unexpected requires-clause on template template-parameter");
George Burgess IVb7e4e482016-08-25 01:54:37 +0000746 Expr *const CanonRequiresClause = nullptr;
Hubert Tonge4a0c0e2016-07-30 22:33:34 +0000747
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000748 TemplateTemplateParmDecl *CanonTTP
Fangrui Song6907ce22018-07-30 19:24:48 +0000749 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000750 SourceLocation(), TTP->getDepth(),
Fangrui Song6907ce22018-07-30 19:24:48 +0000751 TTP->getPosition(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000752 TTP->isParameterPack(),
Craig Topper36250ad2014-05-12 05:36:57 +0000753 nullptr,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000754 TemplateParameterList::Create(*this, SourceLocation(),
755 SourceLocation(),
David Majnemer902f8c62015-12-27 07:16:27 +0000756 CanonParams,
Hubert Tonge4a0c0e2016-07-30 22:33:34 +0000757 SourceLocation(),
758 CanonRequiresClause));
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000759
760 // Get the new insert position for the node we care about.
761 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +0000762 assert(!Canonical && "Shouldn't be in the map!");
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000763 (void)Canonical;
764
765 // Create the canonical template template parameter entry.
766 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
767 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
768 return CanonTTP;
769}
770
Charles Davis53c59df2010-08-16 03:33:14 +0000771CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
Craig Topper36250ad2014-05-12 05:36:57 +0000772 if (!LangOpts.CPlusPlus) return nullptr;
John McCall86353412010-08-21 22:46:04 +0000773
John McCall359b8852013-01-25 22:30:49 +0000774 switch (T.getCXXABI().getKind()) {
Petr Hosek9c3f9b92019-09-06 18:59:43 -0700775 case TargetCXXABI::Fuchsia:
Joerg Sonnenbergerdaa13aa2014-05-13 11:20:16 +0000776 case TargetCXXABI::GenericARM: // Same as Itanium at this level
John McCall359b8852013-01-25 22:30:49 +0000777 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +0000778 case TargetCXXABI::iOS64:
Tim Northover756447a2015-10-30 16:30:36 +0000779 case TargetCXXABI::WatchOS:
Joerg Sonnenbergerdaa13aa2014-05-13 11:20:16 +0000780 case TargetCXXABI::GenericAArch64:
Zoran Jovanovic26a12162015-02-18 15:21:35 +0000781 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +0000782 case TargetCXXABI::GenericItanium:
Dan Gohmanc2853072015-09-03 22:51:53 +0000783 case TargetCXXABI::WebAssembly:
Charles Davis53c59df2010-08-16 03:33:14 +0000784 return CreateItaniumCXXABI(*this);
John McCall359b8852013-01-25 22:30:49 +0000785 case TargetCXXABI::Microsoft:
Charles Davis6bcb07a2010-08-19 02:18:14 +0000786 return CreateMicrosoftCXXABI(*this);
787 }
David Blaikie8a40f702012-01-17 06:56:22 +0000788 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000789}
790
Nandor Licker950b70d2019-09-13 09:46:16 +0000791interp::Context &ASTContext::getInterpContext() {
792 if (!InterpContext) {
793 InterpContext.reset(new interp::Context(*this));
794 }
795 return *InterpContext.get();
796}
797
Alexander Richardson6d989432017-10-15 18:48:14 +0000798static const LangASMap *getAddressSpaceMap(const TargetInfo &T,
799 const LangOptions &LOpts) {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000800 if (LOpts.FakeAddressSpaceMap) {
801 // The fake address space map must have a distinct entry for each
802 // language-specific address space.
803 static const unsigned FakeAddrSpaceMap[] = {
Yaxun Liub34ec822017-04-11 17:24:23 +0000804 0, // Default
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000805 1, // opencl_global
Egor Churaev28f00aa2016-12-23 16:11:25 +0000806 3, // opencl_local
807 2, // opencl_constant
Yaxun Liub7318e02017-10-13 03:37:48 +0000808 0, // opencl_private
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +0000809 4, // opencl_generic
810 5, // cuda_device
811 6, // cuda_constant
812 7 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000813 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000814 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000815 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000816 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000817 }
818}
819
David Tweed31d09b02013-09-13 12:04:22 +0000820static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
821 const LangOptions &LangOpts) {
822 switch (LangOpts.getAddressSpaceMapMangling()) {
David Tweed31d09b02013-09-13 12:04:22 +0000823 case LangOptions::ASMM_Target:
824 return TI.useAddressSpaceMapMangling();
825 case LangOptions::ASMM_On:
826 return true;
827 case LangOptions::ASMM_Off:
828 return false;
829 }
NAKAMURA Takumi5c81ca42013-09-13 17:12:09 +0000830 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
David Tweed31d09b02013-09-13 12:04:22 +0000831}
832
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000833ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000834 IdentifierTable &idents, SelectorTable &sels,
Alp Toker08043432014-05-03 03:46:04 +0000835 Builtin::Context &builtins)
Richard Smith772e2662019-10-04 01:25:59 +0000836 : ConstantArrayTypes(this_()), FunctionProtoTypes(this_()),
837 TemplateSpecializationTypes(this_()),
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000838 DependentTemplateSpecializationTypes(this_()),
Eugene Zelenko5e5e5642017-11-23 01:20:07 +0000839 SubstTemplateTemplateParmPacks(this_()), SourceMgr(SM), LangOpts(LOpts),
Ilya Biryukovdf7ea712019-10-09 09:40:22 +0000840 SanitizerBL(new SanitizerBlacklist(LangOpts.SanitizerBlacklistFiles, SM)),
Dean Michael Berris835832d2017-03-30 00:29:36 +0000841 XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles,
Dean Michael Berris20dc6ef2018-04-09 04:02:09 +0000842 LangOpts.XRayNeverInstrumentFiles,
843 LangOpts.XRayAttrListFiles, SM)),
Artem Belevichb5bc9232015-09-22 17:23:22 +0000844 PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
Eugene Zelenko5e5e5642017-11-23 01:20:07 +0000845 BuiltinInfo(builtins), DeclarationNames(*this), Comments(SM),
Eric Fiselier0683c0e2018-05-07 21:07:10 +0000846 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
847 CompCategories(this_()), LastSDM(nullptr, 0) {
Daniel Dunbar221fa942008-08-11 04:54:23 +0000848 TUDecl = TranslationUnitDecl::Create(*this);
Sam McCall814e7972018-11-14 10:33:30 +0000849 TraversalScope = {TUDecl};
Daniel Dunbar221fa942008-08-11 04:54:23 +0000850}
851
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000852ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000853 // Release the DenseMaps associated with DeclContext objects.
854 // FIXME: Is this the ideal solution?
855 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000856
Manuel Klimeka7328992013-06-03 13:51:33 +0000857 // Call all of the deallocation functions on all of their targets.
Chandler Carruthff5a01a2015-12-30 03:00:23 +0000858 for (auto &Pair : Deallocations)
859 (Pair.first)(Pair.second);
Manuel Klimeka7328992013-06-03 13:51:33 +0000860
Ted Kremenek076baeb2010-06-08 23:00:58 +0000861 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000862 // because they can contain DenseMaps.
863 for (llvm::DenseMap<const ObjCContainerDecl*,
864 const ASTRecordLayout*>::iterator
865 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
866 // Increment in loop to prevent using deallocated memory.
Eugene Zelenko7855e772018-04-03 00:11:50 +0000867 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
Douglas Gregor5b11d492010-07-25 17:53:33 +0000868 R->Destroy(*this);
869
Ted Kremenek076baeb2010-06-08 23:00:58 +0000870 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
871 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
872 // Increment in loop to prevent using deallocated memory.
Eugene Zelenko7855e772018-04-03 00:11:50 +0000873 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
Ted Kremenek076baeb2010-06-08 23:00:58 +0000874 R->Destroy(*this);
875 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000876
Douglas Gregor561eceb2010-08-30 16:49:28 +0000877 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
878 AEnd = DeclAttrs.end();
879 A != AEnd; ++A)
880 A->second->~AttrVec();
Reid Klecknerd8110b62013-09-10 20:14:30 +0000881
Richard Smith423f46f2016-07-20 21:38:26 +0000882 for (const auto &Value : ModuleInitializers)
883 Value.second->~PerModuleInitializers();
Gauthier Harnisch83c7b612019-06-15 10:24:47 +0000884
885 for (APValue *Value : APValueCleanups)
886 Value->~APValue();
Douglas Gregor561eceb2010-08-30 16:49:28 +0000887}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000888
Sam McCall814e7972018-11-14 10:33:30 +0000889class ASTContext::ParentMap {
890 /// Contains parents of a node.
891 using ParentVector = llvm::SmallVector<ast_type_traits::DynTypedNode, 2>;
892
893 /// Maps from a node to its parents. This is used for nodes that have
894 /// pointer identity only, which are more common and we can save space by
895 /// only storing a unique pointer to them.
896 using ParentMapPointers = llvm::DenseMap<
897 const void *,
898 llvm::PointerUnion4<const Decl *, const Stmt *,
899 ast_type_traits::DynTypedNode *, ParentVector *>>;
900
901 /// Parent map for nodes without pointer identity. We store a full
902 /// DynTypedNode for all keys.
903 using ParentMapOtherNodes = llvm::DenseMap<
904 ast_type_traits::DynTypedNode,
905 llvm::PointerUnion4<const Decl *, const Stmt *,
906 ast_type_traits::DynTypedNode *, ParentVector *>>;
907
908 ParentMapPointers PointerParents;
909 ParentMapOtherNodes OtherParents;
910 class ASTVisitor;
911
912 static ast_type_traits::DynTypedNode
913 getSingleDynTypedNodeFromParentMap(ParentMapPointers::mapped_type U) {
914 if (const auto *D = U.dyn_cast<const Decl *>())
915 return ast_type_traits::DynTypedNode::create(*D);
916 if (const auto *S = U.dyn_cast<const Stmt *>())
917 return ast_type_traits::DynTypedNode::create(*S);
918 return *U.get<ast_type_traits::DynTypedNode *>();
919 }
920
921 template <typename NodeTy, typename MapTy>
922 static ASTContext::DynTypedNodeList getDynNodeFromMap(const NodeTy &Node,
923 const MapTy &Map) {
924 auto I = Map.find(Node);
925 if (I == Map.end()) {
926 return llvm::ArrayRef<ast_type_traits::DynTypedNode>();
927 }
928 if (const auto *V = I->second.template dyn_cast<ParentVector *>()) {
929 return llvm::makeArrayRef(*V);
930 }
931 return getSingleDynTypedNodeFromParentMap(I->second);
932 }
933
934public:
935 ParentMap(ASTContext &Ctx);
936 ~ParentMap() {
937 for (const auto &Entry : PointerParents) {
938 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
939 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
940 } else if (Entry.second.is<ParentVector *>()) {
941 delete Entry.second.get<ParentVector *>();
942 }
943 }
944 for (const auto &Entry : OtherParents) {
945 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
946 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
947 } else if (Entry.second.is<ParentVector *>()) {
948 delete Entry.second.get<ParentVector *>();
949 }
Benjamin Kramer94355ae2015-10-23 09:04:55 +0000950 }
951 }
Sam McCall814e7972018-11-14 10:33:30 +0000952
953 DynTypedNodeList getParents(const ast_type_traits::DynTypedNode &Node) {
954 if (Node.getNodeKind().hasPointerIdentity())
955 return getDynNodeFromMap(Node.getMemoizationData(), PointerParents);
956 return getDynNodeFromMap(Node, OtherParents);
Manuel Klimek95403e62014-05-21 13:28:59 +0000957 }
Sam McCall814e7972018-11-14 10:33:30 +0000958};
959
960void ASTContext::setTraversalScope(const std::vector<Decl *> &TopLevelDecls) {
961 TraversalScope = TopLevelDecls;
962 Parents.reset();
Manuel Klimek95403e62014-05-21 13:28:59 +0000963}
964
Gauthier Harnischdea9d572019-06-21 08:26:21 +0000965void ASTContext::AddDeallocation(void (*Callback)(void *), void *Data) const {
Chandler Carruthff5a01a2015-12-30 03:00:23 +0000966 Deallocations.push_back({Callback, Data});
Douglas Gregor1a809332010-05-23 18:26:36 +0000967}
968
Mike Stump11289f42009-09-09 15:08:12 +0000969void
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000970ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
Benjamin Kramerd6da1a02016-06-12 20:05:23 +0000971 ExternalSource = std::move(Source);
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000972}
973
Chris Lattner4eb445d2007-01-26 01:27:23 +0000974void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000975 llvm::errs() << "\n*** AST Context Stats:\n";
976 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000977
Douglas Gregora30d0462009-05-26 14:40:08 +0000978 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000979#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000980#define ABSTRACT_TYPE(Name, Parent)
John McCall36b12a82019-10-02 06:35:23 +0000981#include "clang/AST/TypeNodes.inc"
Douglas Gregora30d0462009-05-26 14:40:08 +0000982 0 // Extra
983 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000984
Chris Lattner4eb445d2007-01-26 01:27:23 +0000985 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
986 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000987 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000988 }
989
Douglas Gregora30d0462009-05-26 14:40:08 +0000990 unsigned Idx = 0;
991 unsigned TotalBytes = 0;
992#define TYPE(Name, Parent) \
993 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000994 llvm::errs() << " " << counts[Idx] << " " << #Name \
Bruno Ricci58e03222018-08-06 15:17:32 +0000995 << " types, " << sizeof(Name##Type) << " each " \
996 << "(" << counts[Idx] * sizeof(Name##Type) \
997 << " bytes)\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000998 TotalBytes += counts[Idx] * sizeof(Name##Type); \
999 ++Idx;
1000#define ABSTRACT_TYPE(Name, Parent)
John McCall36b12a82019-10-02 06:35:23 +00001001#include "clang/AST/TypeNodes.inc"
Mike Stump11289f42009-09-09 15:08:12 +00001002
Chandler Carruth3c147a72011-07-04 05:32:14 +00001003 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
1004
Douglas Gregor7454c562010-07-02 20:37:36 +00001005 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +00001006 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
1007 << NumImplicitDefaultConstructors
1008 << " implicit default constructors created\n";
1009 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
1010 << NumImplicitCopyConstructors
1011 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +00001012 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +00001013 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
1014 << NumImplicitMoveConstructors
1015 << " implicit move constructors created\n";
1016 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
1017 << NumImplicitCopyAssignmentOperators
1018 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +00001019 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +00001020 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
1021 << NumImplicitMoveAssignmentOperators
1022 << " implicit move assignment operators created\n";
1023 llvm::errs() << NumImplicitDestructorsDeclared << "/"
1024 << NumImplicitDestructors
1025 << " implicit destructors created\n";
1026
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +00001027 if (ExternalSource) {
Chandler Carruth3c147a72011-07-04 05:32:14 +00001028 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001029 ExternalSource->PrintStats();
1030 }
Chandler Carruth3c147a72011-07-04 05:32:14 +00001031
Douglas Gregor5b11d492010-07-25 17:53:33 +00001032 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +00001033}
1034
Richard Smith42413142015-05-15 20:05:43 +00001035void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
1036 bool NotifyListeners) {
1037 if (NotifyListeners)
1038 if (auto *Listener = getASTMutationListener())
1039 Listener->RedefinedHiddenDefinition(ND, M);
1040
Richard Smith13897eb2018-09-12 23:37:00 +00001041 MergedDefModules[cast<NamedDecl>(ND->getCanonicalDecl())].push_back(M);
Richard Smith42413142015-05-15 20:05:43 +00001042}
1043
1044void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) {
Richard Smith20fbdb32018-09-12 02:13:46 +00001045 auto It = MergedDefModules.find(cast<NamedDecl>(ND->getCanonicalDecl()));
Richard Smith42413142015-05-15 20:05:43 +00001046 if (It == MergedDefModules.end())
1047 return;
1048
Benjamin Kramera72a70a2016-10-17 13:00:44 +00001049 auto &Merged = It->second;
Richard Smith42413142015-05-15 20:05:43 +00001050 llvm::DenseSet<Module*> Found;
1051 for (Module *&M : Merged)
1052 if (!Found.insert(M).second)
1053 M = nullptr;
1054 Merged.erase(std::remove(Merged.begin(), Merged.end(), nullptr), Merged.end());
1055}
1056
Richard Smithdc1f0422016-07-20 19:10:16 +00001057void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
1058 if (LazyInitializers.empty())
1059 return;
1060
1061 auto *Source = Ctx.getExternalSource();
1062 assert(Source && "lazy initializers but no external source");
1063
1064 auto LazyInits = std::move(LazyInitializers);
1065 LazyInitializers.clear();
1066
1067 for (auto ID : LazyInits)
1068 Initializers.push_back(Source->GetExternalDecl(ID));
1069
1070 assert(LazyInitializers.empty() &&
1071 "GetExternalDecl for lazy module initializer added more inits");
1072}
1073
1074void ASTContext::addModuleInitializer(Module *M, Decl *D) {
1075 // One special case: if we add a module initializer that imports another
1076 // module, and that module's only initializer is an ImportDecl, simplify.
Eugene Zelenko7855e772018-04-03 00:11:50 +00001077 if (const auto *ID = dyn_cast<ImportDecl>(D)) {
Richard Smithdc1f0422016-07-20 19:10:16 +00001078 auto It = ModuleInitializers.find(ID->getImportedModule());
1079
1080 // Maybe the ImportDecl does nothing at all. (Common case.)
1081 if (It == ModuleInitializers.end())
1082 return;
1083
1084 // Maybe the ImportDecl only imports another ImportDecl.
1085 auto &Imported = *It->second;
1086 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
1087 Imported.resolve(*this);
1088 auto *OnlyDecl = Imported.Initializers.front();
1089 if (isa<ImportDecl>(OnlyDecl))
1090 D = OnlyDecl;
1091 }
1092 }
1093
1094 auto *&Inits = ModuleInitializers[M];
1095 if (!Inits)
1096 Inits = new (*this) PerModuleInitializers;
1097 Inits->Initializers.push_back(D);
1098}
1099
1100void ASTContext::addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs) {
1101 auto *&Inits = ModuleInitializers[M];
1102 if (!Inits)
1103 Inits = new (*this) PerModuleInitializers;
1104 Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
1105 IDs.begin(), IDs.end());
1106}
1107
Eugene Zelenko7855e772018-04-03 00:11:50 +00001108ArrayRef<Decl *> ASTContext::getModuleInitializers(Module *M) {
Richard Smithdc1f0422016-07-20 19:10:16 +00001109 auto It = ModuleInitializers.find(M);
Fangrui Song6907ce22018-07-30 19:24:48 +00001110 if (It == ModuleInitializers.end())
Richard Smithdc1f0422016-07-20 19:10:16 +00001111 return None;
1112
1113 auto *Inits = It->second;
1114 Inits->resolve(*this);
1115 return Inits->Initializers;
1116}
1117
Richard Smithf19e1272015-03-07 00:04:49 +00001118ExternCContextDecl *ASTContext::getExternCContextDecl() const {
1119 if (!ExternCContext)
1120 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
1121
1122 return ExternCContext;
1123}
1124
David Majnemerd9b1a4f2015-11-04 03:40:30 +00001125BuiltinTemplateDecl *
1126ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
1127 const IdentifierInfo *II) const {
1128 auto *BuiltinTemplate = BuiltinTemplateDecl::Create(*this, TUDecl, II, BTK);
1129 BuiltinTemplate->setImplicit();
1130 TUDecl->addDecl(BuiltinTemplate);
1131
1132 return BuiltinTemplate;
1133}
1134
1135BuiltinTemplateDecl *
1136ASTContext::getMakeIntegerSeqDecl() const {
1137 if (!MakeIntegerSeqDecl)
1138 MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq,
1139 getMakeIntegerSeqName());
1140 return MakeIntegerSeqDecl;
1141}
1142
Eric Fiselier6ad68552016-07-01 01:24:09 +00001143BuiltinTemplateDecl *
1144ASTContext::getTypePackElementDecl() const {
1145 if (!TypePackElementDecl)
1146 TypePackElementDecl = buildBuiltinTemplateDecl(BTK__type_pack_element,
1147 getTypePackElementName());
1148 return TypePackElementDecl;
1149}
1150
Alp Toker2dea15b2013-12-17 01:22:38 +00001151RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
1152 RecordDecl::TagKind TK) const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001153 SourceLocation Loc;
1154 RecordDecl *NewDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00001155 if (getLangOpts().CPlusPlus)
1156 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
1157 Loc, &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +00001158 else
Alp Toker2dea15b2013-12-17 01:22:38 +00001159 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
1160 &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +00001161 NewDecl->setImplicit();
David Majnemerf8637362015-01-15 08:41:25 +00001162 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
1163 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
Alp Toker56b5cc92013-12-15 10:36:26 +00001164 return NewDecl;
1165}
1166
1167TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
1168 StringRef Name) const {
1169 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
1170 TypedefDecl *NewDecl = TypedefDecl::Create(
1171 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
1172 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
1173 NewDecl->setImplicit();
1174 return NewDecl;
1175}
1176
Douglas Gregor801c99d2011-08-12 06:49:56 +00001177TypedefDecl *ASTContext::getInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001178 if (!Int128Decl)
1179 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +00001180 return Int128Decl;
1181}
1182
1183TypedefDecl *ASTContext::getUInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001184 if (!UInt128Decl)
1185 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +00001186 return UInt128Decl;
1187}
Chris Lattner4eb445d2007-01-26 01:27:23 +00001188
John McCall48f2d582009-10-23 23:03:21 +00001189void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001190 auto *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +00001191 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +00001192 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001193}
1194
Artem Belevichb5bc9232015-09-22 17:23:22 +00001195void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
1196 const TargetInfo *AuxTarget) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001197 assert((!this->Target || this->Target == &Target) &&
1198 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +00001199 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +00001200
Douglas Gregore8bbc122011-09-02 00:18:52 +00001201 this->Target = &Target;
Artem Belevichb5bc9232015-09-22 17:23:22 +00001202 this->AuxTarget = AuxTarget;
1203
Douglas Gregore8bbc122011-09-02 00:18:52 +00001204 ABI.reset(createCXXABI(Target));
1205 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
David Tweed31d09b02013-09-13 12:04:22 +00001206 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
Fangrui Song6907ce22018-07-30 19:24:48 +00001207
Chris Lattner970e54e2006-11-12 00:37:36 +00001208 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +00001209 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +00001210
Chris Lattner970e54e2006-11-12 00:37:36 +00001211 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +00001212 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +00001213 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +00001214 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +00001215 InitBuiltinType(CharTy, BuiltinType::Char_S);
1216 else
1217 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +00001218 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +00001219 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
1220 InitBuiltinType(ShortTy, BuiltinType::Short);
1221 InitBuiltinType(IntTy, BuiltinType::Int);
1222 InitBuiltinType(LongTy, BuiltinType::Long);
1223 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +00001224
Chris Lattner970e54e2006-11-12 00:37:36 +00001225 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +00001226 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
1227 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
1228 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
1229 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
1230 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +00001231
Chris Lattner970e54e2006-11-12 00:37:36 +00001232 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +00001233 InitBuiltinType(FloatTy, BuiltinType::Float);
1234 InitBuiltinType(DoubleTy, BuiltinType::Double);
1235 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001236
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001237 // GNU extension, __float128 for IEEE quadruple precision
1238 InitBuiltinType(Float128Ty, BuiltinType::Float128);
1239
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00001240 // C11 extension ISO/IEC TS 18661-3
1241 InitBuiltinType(Float16Ty, BuiltinType::Float16);
1242
Leonard Chanf921d852018-06-04 16:07:52 +00001243 // ISO/IEC JTC1 SC22 WG14 N1169 Extension
Leonard Chanab80f3c2018-06-14 14:53:51 +00001244 InitBuiltinType(ShortAccumTy, BuiltinType::ShortAccum);
1245 InitBuiltinType(AccumTy, BuiltinType::Accum);
1246 InitBuiltinType(LongAccumTy, BuiltinType::LongAccum);
1247 InitBuiltinType(UnsignedShortAccumTy, BuiltinType::UShortAccum);
1248 InitBuiltinType(UnsignedAccumTy, BuiltinType::UAccum);
1249 InitBuiltinType(UnsignedLongAccumTy, BuiltinType::ULongAccum);
1250 InitBuiltinType(ShortFractTy, BuiltinType::ShortFract);
1251 InitBuiltinType(FractTy, BuiltinType::Fract);
1252 InitBuiltinType(LongFractTy, BuiltinType::LongFract);
1253 InitBuiltinType(UnsignedShortFractTy, BuiltinType::UShortFract);
1254 InitBuiltinType(UnsignedFractTy, BuiltinType::UFract);
1255 InitBuiltinType(UnsignedLongFractTy, BuiltinType::ULongFract);
1256 InitBuiltinType(SatShortAccumTy, BuiltinType::SatShortAccum);
1257 InitBuiltinType(SatAccumTy, BuiltinType::SatAccum);
1258 InitBuiltinType(SatLongAccumTy, BuiltinType::SatLongAccum);
1259 InitBuiltinType(SatUnsignedShortAccumTy, BuiltinType::SatUShortAccum);
1260 InitBuiltinType(SatUnsignedAccumTy, BuiltinType::SatUAccum);
1261 InitBuiltinType(SatUnsignedLongAccumTy, BuiltinType::SatULongAccum);
1262 InitBuiltinType(SatShortFractTy, BuiltinType::SatShortFract);
1263 InitBuiltinType(SatFractTy, BuiltinType::SatFract);
1264 InitBuiltinType(SatLongFractTy, BuiltinType::SatLongFract);
1265 InitBuiltinType(SatUnsignedShortFractTy, BuiltinType::SatUShortFract);
1266 InitBuiltinType(SatUnsignedFractTy, BuiltinType::SatUFract);
1267 InitBuiltinType(SatUnsignedLongFractTy, BuiltinType::SatULongFract);
Leonard Chanf921d852018-06-04 16:07:52 +00001268
Chris Lattnerf122cef2009-04-30 02:43:43 +00001269 // GNU extension, 128-bit integers.
1270 InitBuiltinType(Int128Ty, BuiltinType::Int128);
1271 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
1272
Hans Wennborg0d81e012013-05-10 10:08:40 +00001273 // C++ 3.9.1p5
1274 if (TargetInfo::isTypeSigned(Target.getWCharType()))
1275 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1276 else // -fshort-wchar makes wchar_t be unsigned.
1277 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1278 if (LangOpts.CPlusPlus && LangOpts.WChar)
1279 WideCharTy = WCharTy;
1280 else {
1281 // C99 (or C++ using -fno-wchar).
1282 WideCharTy = getFromTargetType(Target.getWCharType());
1283 }
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001284
James Molloy36365542012-05-04 10:55:22 +00001285 WIntTy = getFromTargetType(Target.getWIntType());
1286
Richard Smith3a8244d2018-05-01 05:02:45 +00001287 // C++20 (proposed)
1288 InitBuiltinType(Char8Ty, BuiltinType::Char8);
1289
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001290 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1291 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1292 else // C99
1293 Char16Ty = getFromTargetType(Target.getChar16Type());
1294
1295 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1296 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1297 else // C99
1298 Char32Ty = getFromTargetType(Target.getChar32Type());
1299
Douglas Gregor4619e432008-12-05 23:32:09 +00001300 // Placeholder type for type-dependent expressions whose type is
1301 // completely unknown. No code should ever check a type against
1302 // DependentTy and users should never see it; however, it is here to
1303 // help diagnose failures to properly check for type-dependent
1304 // expressions.
1305 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001306
John McCall36e7fe32010-10-12 00:20:44 +00001307 // Placeholder type for functions.
1308 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1309
John McCall0009fcc2011-04-26 20:42:42 +00001310 // Placeholder type for bound members.
1311 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1312
John McCall526ab472011-10-25 17:37:35 +00001313 // Placeholder type for pseudo-objects.
1314 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1315
John McCall31996342011-04-07 08:22:57 +00001316 // "any" type; useful for debugger-like clients.
1317 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1318
John McCall8a6b59a2011-10-17 18:09:15 +00001319 // Placeholder type for unbridged ARC casts.
1320 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1321
Eli Friedman34866c72012-08-31 00:14:07 +00001322 // Placeholder type for builtin functions.
1323 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1324
Alexey Bataev1a3320e2015-08-25 14:24:04 +00001325 // Placeholder type for OMP array sections.
1326 if (LangOpts.OpenMP)
1327 InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection);
1328
Chris Lattner970e54e2006-11-12 00:37:36 +00001329 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +00001330 FloatComplexTy = getComplexType(FloatTy);
1331 DoubleComplexTy = getComplexType(DoubleTy);
1332 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001333 Float128ComplexTy = getComplexType(Float128Ty);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001334
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001335 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +00001336 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1337 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001338 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001339
Alexey Bader954ba212016-04-08 13:40:33 +00001340 if (LangOpts.OpenCL) {
1341#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1342 InitBuiltinType(SingletonId, BuiltinType::Id);
Alexey Baderb62f1442016-04-13 08:33:41 +00001343#include "clang/Basic/OpenCLImageTypes.def"
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001344
Guy Benyei61054192013-02-07 10:55:47 +00001345 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001346 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Alexey Bader9c8453f2015-09-15 11:18:52 +00001347 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1348 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
Alexey Bader9c8453f2015-09-15 11:18:52 +00001349 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
Andrew Savonichev3fee3512018-11-08 11:25:41 +00001350
1351#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1352 InitBuiltinType(Id##Ty, BuiltinType::Id);
1353#include "clang/Basic/OpenCLExtensionTypes.def"
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001354 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001355
Richard Sandifordeb485fb2019-08-09 08:52:54 +00001356 if (Target.hasAArch64SVETypes()) {
1357#define SVE_TYPE(Name, Id, SingletonId) \
1358 InitBuiltinType(SingletonId, BuiltinType::Id);
1359#include "clang/Basic/AArch64SVEACLETypes.def"
1360 }
1361
Ted Kremeneke65b0862012-03-06 20:05:56 +00001362 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +00001363 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1364 SignedCharTy : BoolTy);
Fangrui Song6907ce22018-07-30 19:24:48 +00001365
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001366 ObjCConstantStringType = QualType();
Fangrui Song6907ce22018-07-30 19:24:48 +00001367
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001368 ObjCSuperType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +00001369
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00001370 // void * type
Yaxun Liu39195062017-08-04 18:16:31 +00001371 if (LangOpts.OpenCLVersion >= 200) {
1372 auto Q = VoidTy.getQualifiers();
1373 Q.setAddressSpace(LangAS::opencl_generic);
1374 VoidPtrTy = getPointerType(getCanonicalType(
1375 getQualifiedType(VoidTy.getUnqualifiedType(), Q)));
1376 } else {
1377 VoidPtrTy = getPointerType(VoidTy);
1378 }
Sebastian Redl576fd422009-05-10 18:38:11 +00001379
1380 // nullptr type (C++0x 2.14.7)
1381 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001382
1383 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1384 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +00001385
1386 // Builtin type used to help define __builtin_va_list.
Richard Smith9b88a4c2015-07-27 05:40:23 +00001387 VaListTagDecl = nullptr;
Chris Lattner970e54e2006-11-12 00:37:36 +00001388}
1389
David Blaikie9c902b52011-09-25 23:23:43 +00001390DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001391 return SourceMgr.getDiagnostics();
1392}
1393
Douglas Gregor561eceb2010-08-30 16:49:28 +00001394AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1395 AttrVec *&Result = DeclAttrs[D];
1396 if (!Result) {
1397 void *Mem = Allocate(sizeof(AttrVec));
1398 Result = new (Mem) AttrVec;
1399 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001400
Douglas Gregor561eceb2010-08-30 16:49:28 +00001401 return *Result;
1402}
1403
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001404/// Erase the attributes corresponding to the given declaration.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00001405void ASTContext::eraseDeclAttrs(const Decl *D) {
Douglas Gregor561eceb2010-08-30 16:49:28 +00001406 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1407 if (Pos != DeclAttrs.end()) {
1408 Pos->second->~AttrVec();
1409 DeclAttrs.erase(Pos);
1410 }
1411}
1412
Larisse Voufo39a1e502013-08-06 01:03:05 +00001413// FIXME: Remove ?
Douglas Gregor86d142a2009-10-08 07:24:58 +00001414MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +00001415ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001416 assert(Var->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001417 return getTemplateOrSpecializationInfo(Var)
1418 .dyn_cast<MemberSpecializationInfo *>();
1419}
1420
1421ASTContext::TemplateOrSpecializationInfo
1422ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1423 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1424 TemplateOrInstantiation.find(Var);
1425 if (Pos == TemplateOrInstantiation.end())
Eugene Zelenko7855e772018-04-03 00:11:50 +00001426 return {};
Mike Stump11289f42009-09-09 15:08:12 +00001427
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001428 return Pos->second;
1429}
1430
Mike Stump11289f42009-09-09 15:08:12 +00001431void
Douglas Gregor86d142a2009-10-08 07:24:58 +00001432ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +00001433 TemplateSpecializationKind TSK,
1434 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001435 assert(Inst->isStaticDataMember() && "Not a static data member");
1436 assert(Tmpl->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001437 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1438 Tmpl, TSK, PointOfInstantiation));
1439}
1440
1441void
1442ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1443 TemplateOrSpecializationInfo TSI) {
1444 assert(!TemplateOrInstantiation[Inst] &&
1445 "Already noted what the variable was instantiated from");
1446 TemplateOrInstantiation[Inst] = TSI;
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001447}
1448
John McCalle61f2ba2009-11-18 02:36:19 +00001449NamedDecl *
Richard Smithd8a9e372016-12-18 21:39:37 +00001450ASTContext::getInstantiatedFromUsingDecl(NamedDecl *UUD) {
1451 auto Pos = InstantiatedFromUsingDecl.find(UUD);
John McCallb96ec562009-12-04 22:46:56 +00001452 if (Pos == InstantiatedFromUsingDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001453 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001454
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001455 return Pos->second;
1456}
1457
1458void
Richard Smithd8a9e372016-12-18 21:39:37 +00001459ASTContext::setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern) {
John McCallb96ec562009-12-04 22:46:56 +00001460 assert((isa<UsingDecl>(Pattern) ||
1461 isa<UnresolvedUsingValueDecl>(Pattern) ||
Fangrui Song6907ce22018-07-30 19:24:48 +00001462 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
John McCallb96ec562009-12-04 22:46:56 +00001463 "pattern decl is not a using decl");
Richard Smithd8a9e372016-12-18 21:39:37 +00001464 assert((isa<UsingDecl>(Inst) ||
1465 isa<UnresolvedUsingValueDecl>(Inst) ||
Fangrui Song6907ce22018-07-30 19:24:48 +00001466 isa<UnresolvedUsingTypenameDecl>(Inst)) &&
Richard Smithd8a9e372016-12-18 21:39:37 +00001467 "instantiation did not produce a using decl");
John McCallb96ec562009-12-04 22:46:56 +00001468 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1469 InstantiatedFromUsingDecl[Inst] = Pattern;
1470}
1471
1472UsingShadowDecl *
1473ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1474 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1475 = InstantiatedFromUsingShadowDecl.find(Inst);
1476 if (Pos == InstantiatedFromUsingShadowDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001477 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00001478
1479 return Pos->second;
1480}
1481
1482void
1483ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1484 UsingShadowDecl *Pattern) {
1485 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1486 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001487}
1488
Anders Carlsson5da84842009-09-01 04:26:58 +00001489FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1490 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1491 = InstantiatedFromUnnamedFieldDecl.find(Field);
1492 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001493 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001494
Anders Carlsson5da84842009-09-01 04:26:58 +00001495 return Pos->second;
1496}
1497
1498void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1499 FieldDecl *Tmpl) {
1500 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1501 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1502 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1503 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +00001504
Anders Carlsson5da84842009-09-01 04:26:58 +00001505 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1506}
1507
Douglas Gregor832940b2010-03-02 23:58:15 +00001508ASTContext::overridden_cxx_method_iterator
1509ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
Benjamin Krameracfa3392017-12-17 23:52:45 +00001510 return overridden_methods(Method).begin();
Douglas Gregor832940b2010-03-02 23:58:15 +00001511}
1512
1513ASTContext::overridden_cxx_method_iterator
1514ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
Benjamin Krameracfa3392017-12-17 23:52:45 +00001515 return overridden_methods(Method).end();
Douglas Gregor832940b2010-03-02 23:58:15 +00001516}
1517
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001518unsigned
1519ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
Benjamin Krameracfa3392017-12-17 23:52:45 +00001520 auto Range = overridden_methods(Method);
1521 return Range.end() - Range.begin();
Clement Courbet8251ebf2016-06-10 11:54:43 +00001522}
1523
Clement Courbet6ecaec82016-07-05 07:49:31 +00001524ASTContext::overridden_method_range
1525ASTContext::overridden_methods(const CXXMethodDecl *Method) const {
Benjamin Krameracfa3392017-12-17 23:52:45 +00001526 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1527 OverriddenMethods.find(Method->getCanonicalDecl());
1528 if (Pos == OverriddenMethods.end())
1529 return overridden_method_range(nullptr, nullptr);
1530 return overridden_method_range(Pos->second.begin(), Pos->second.end());
Clement Courbet6ecaec82016-07-05 07:49:31 +00001531}
1532
Fangrui Song6907ce22018-07-30 19:24:48 +00001533void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
Douglas Gregor832940b2010-03-02 23:58:15 +00001534 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001535 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001536 OverriddenMethods[Method].push_back(Overridden);
1537}
1538
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +00001539void ASTContext::getOverriddenMethods(
1540 const NamedDecl *D,
1541 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001542 assert(D);
1543
Eugene Zelenko7855e772018-04-03 00:11:50 +00001544 if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisc8e70082013-04-17 00:09:03 +00001545 Overridden.append(overridden_methods_begin(CXXMethod),
1546 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001547 return;
1548 }
1549
Eugene Zelenko7855e772018-04-03 00:11:50 +00001550 const auto *Method = dyn_cast<ObjCMethodDecl>(D);
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001551 if (!Method)
1552 return;
1553
Argyrios Kyrtzidis353f6a42012-10-09 18:19:01 +00001554 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1555 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001556 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001557}
1558
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001559void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1560 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1561 assert(!Import->isFromASTFile() && "Non-local import declaration");
1562 if (!FirstLocalImport) {
1563 FirstLocalImport = Import;
1564 LastLocalImport = Import;
1565 return;
1566 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001567
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001568 LastLocalImport->NextLocalImport = Import;
1569 LastLocalImport = Import;
1570}
1571
Chris Lattner53cfe802007-07-18 17:52:12 +00001572//===----------------------------------------------------------------------===//
1573// Type Sizing and Analysis
1574//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001575
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001576/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1577/// scalar floating point type.
1578const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
Simon Pilgrim9588ae72019-10-03 21:47:42 +00001579 switch (T->castAs<BuiltinType>()->getKind()) {
1580 default:
1581 llvm_unreachable("Not a floating point type!");
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00001582 case BuiltinType::Float16:
1583 case BuiltinType::Half:
1584 return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001585 case BuiltinType::Float: return Target->getFloatFormat();
1586 case BuiltinType::Double: return Target->getDoubleFormat();
Alexey Bataeve509af32019-07-09 14:09:53 +00001587 case BuiltinType::LongDouble:
Fangrui Song3fbd8fd2019-07-09 19:36:22 +00001588 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice)
Alexey Bataeve509af32019-07-09 14:09:53 +00001589 return AuxTarget->getLongDoubleFormat();
1590 return Target->getLongDoubleFormat();
1591 case BuiltinType::Float128:
Fangrui Song3fbd8fd2019-07-09 19:36:22 +00001592 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice)
Alexey Bataeve509af32019-07-09 14:09:53 +00001593 return AuxTarget->getFloat128Format();
1594 return Target->getFloat128Format();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001595 }
1596}
1597
Rafael Espindola71eccb32013-08-08 19:53:46 +00001598CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001599 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001600
John McCall94268702010-10-08 18:24:19 +00001601 bool UseAlignAttrOnly = false;
1602 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1603 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001604
John McCall94268702010-10-08 18:24:19 +00001605 // __attribute__((aligned)) can increase or decrease alignment
1606 // *except* on a struct or struct member, where it only increases
1607 // alignment unless 'packed' is also specified.
1608 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001609 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001610 // ignore that possibility; Sema should diagnose it.
1611 if (isa<FieldDecl>(D)) {
1612 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1613 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1614 } else {
1615 UseAlignAttrOnly = true;
1616 }
1617 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001618 else if (isa<FieldDecl>(D))
Fangrui Song6907ce22018-07-30 19:24:48 +00001619 UseAlignAttrOnly =
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001620 D->hasAttr<PackedAttr>() ||
1621 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001622
John McCall4e819612011-01-20 07:57:12 +00001623 // If we're using the align attribute only, just ignore everything
1624 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001625 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001626 // do nothing
Eugene Zelenko7855e772018-04-03 00:11:50 +00001627 } else if (const auto *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001628 QualType T = VD->getType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00001629 if (const auto *RT = T->getAs<ReferenceType>()) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001630 if (ForAlignof)
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001631 T = RT->getPointeeType();
1632 else
1633 T = getPointerType(RT->getPointeeType());
1634 }
Richard Smithf6d70302014-06-10 23:34:28 +00001635 QualType BaseT = getBaseElementType(T);
Akira Hatanakad62f2c82017-01-06 17:56:15 +00001636 if (T->isFunctionType())
1637 Align = getTypeInfoImpl(T.getTypePtr()).Align;
1638 else if (!BaseT->isIncompleteType()) {
John McCall33ddac02011-01-19 10:06:00 +00001639 // Adjust alignments of declarations with array type by the
1640 // large-array alignment on the target.
Rafael Espindola88572752013-08-07 18:08:19 +00001641 if (const ArrayType *arrayType = getAsArrayType(T)) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001642 unsigned MinWidth = Target->getLargeArrayMinWidth();
1643 if (!ForAlignof && MinWidth) {
Rafael Espindola88572752013-08-07 18:08:19 +00001644 if (isa<VariableArrayType>(arrayType))
1645 Align = std::max(Align, Target->getLargeArrayAlign());
1646 else if (isa<ConstantArrayType>(arrayType) &&
1647 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1648 Align = std::max(Align, Target->getLargeArrayAlign());
1649 }
John McCall33ddac02011-01-19 10:06:00 +00001650 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001651 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Roger Ferrer Ibanez3fa38a12017-03-08 14:00:44 +00001652 if (BaseT.getQualifiers().hasUnaligned())
1653 Align = Target->getCharWidth();
Eugene Zelenko7855e772018-04-03 00:11:50 +00001654 if (const auto *VD = dyn_cast<VarDecl>(D)) {
Tom Tanb7c6d952019-05-02 00:38:14 +00001655 if (VD->hasGlobalStorage() && !ForAlignof) {
1656 uint64_t TypeSize = getTypeSize(T.getTypePtr());
1657 Align = std::max(Align, getTargetInfo().getMinGlobalAlign(TypeSize));
1658 }
Ulrich Weigandfa806422013-05-06 16:23:57 +00001659 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001660 }
John McCall4e819612011-01-20 07:57:12 +00001661
1662 // Fields can be subject to extra alignment constraints, like if
1663 // the field is packed, the struct is packed, or the struct has a
1664 // a max-field-alignment constraint (#pragma pack). So calculate
1665 // the actual alignment of the field within the struct, and then
1666 // (as we're expected to) constrain that by the alignment of the type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00001667 if (const auto *Field = dyn_cast<FieldDecl>(VD)) {
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001668 const RecordDecl *Parent = Field->getParent();
1669 // We can only produce a sensible answer if the record is valid.
1670 if (!Parent->isInvalidDecl()) {
1671 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
John McCall4e819612011-01-20 07:57:12 +00001672
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001673 // Start with the record's overall alignment.
1674 unsigned FieldAlign = toBits(Layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001675
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001676 // Use the GCD of that and the offset within the record.
1677 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1678 if (Offset > 0) {
1679 // Alignment is always a power of 2, so the GCD will be a power of 2,
1680 // which means we get to do this crazy thing instead of Euclid's.
1681 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1682 if (LowBitOfOffset < FieldAlign)
1683 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1684 }
1685
1686 Align = std::min(Align, FieldAlign);
John McCall4e819612011-01-20 07:57:12 +00001687 }
Charles Davis3fc51072010-02-23 04:52:00 +00001688 }
Chris Lattner68061312009-01-24 21:53:27 +00001689 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001690
Ken Dyckcc56c542011-01-15 18:38:59 +00001691 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001692}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001693
John McCallf1249922012-08-21 04:10:00 +00001694// getTypeInfoDataSizeInChars - Return the size of a type, in
1695// chars. If the type is a record, its data size is returned. This is
1696// the size of the memcpy that's performed when assigning this type
1697// using a trivial copy/move assignment operator.
1698std::pair<CharUnits, CharUnits>
1699ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1700 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1701
1702 // In C++, objects can sometimes be allocated into the tail padding
1703 // of a base-class subobject. We decide whether that's possible
1704 // during class layout, so here we can just trust the layout results.
1705 if (getLangOpts().CPlusPlus) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001706 if (const auto *RT = T->getAs<RecordType>()) {
John McCallf1249922012-08-21 04:10:00 +00001707 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1708 sizeAndAlign.first = layout.getDataSize();
1709 }
1710 }
1711
1712 return sizeAndAlign;
1713}
1714
Richard Trieu04d2d942013-05-14 21:59:17 +00001715/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1716/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1717std::pair<CharUnits, CharUnits>
1718static getConstantArrayInfoInChars(const ASTContext &Context,
1719 const ConstantArrayType *CAT) {
1720 std::pair<CharUnits, CharUnits> EltInfo =
1721 Context.getTypeInfoInChars(CAT->getElementType());
1722 uint64_t Size = CAT->getSize().getZExtValue();
Richard Trieuc7509072013-05-14 23:41:50 +00001723 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1724 (uint64_t)(-1)/Size) &&
Richard Trieu04d2d942013-05-14 21:59:17 +00001725 "Overflow in array type char size evaluation");
1726 uint64_t Width = EltInfo.first.getQuantity() * Size;
1727 unsigned Align = EltInfo.second.getQuantity();
Warren Hunt5ae586a2013-11-01 23:59:41 +00001728 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1729 Context.getTargetInfo().getPointerWidth(0) == 64)
Rui Ueyama83aa9792016-01-14 21:00:27 +00001730 Width = llvm::alignTo(Width, Align);
Richard Trieu04d2d942013-05-14 21:59:17 +00001731 return std::make_pair(CharUnits::fromQuantity(Width),
1732 CharUnits::fromQuantity(Align));
1733}
1734
John McCall87fe5d52010-05-20 01:18:31 +00001735std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001736ASTContext::getTypeInfoInChars(const Type *T) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001737 if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
Richard Trieu04d2d942013-05-14 21:59:17 +00001738 return getConstantArrayInfoInChars(*this, CAT);
David Majnemer34b57492014-07-30 01:30:47 +00001739 TypeInfo Info = getTypeInfo(T);
1740 return std::make_pair(toCharUnitsFromBits(Info.Width),
1741 toCharUnitsFromBits(Info.Align));
John McCall87fe5d52010-05-20 01:18:31 +00001742}
1743
1744std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001745ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001746 return getTypeInfoInChars(T.getTypePtr());
1747}
1748
David Majnemer34b57492014-07-30 01:30:47 +00001749bool ASTContext::isAlignmentRequired(const Type *T) const {
1750 return getTypeInfo(T).AlignIsRequired;
1751}
Daniel Dunbarc6475872012-03-09 04:12:54 +00001752
David Majnemer34b57492014-07-30 01:30:47 +00001753bool ASTContext::isAlignmentRequired(QualType T) const {
1754 return isAlignmentRequired(T.getTypePtr());
1755}
1756
Richard Smithb2f0f052016-10-10 18:54:32 +00001757unsigned ASTContext::getTypeAlignIfKnown(QualType T) const {
1758 // An alignment on a typedef overrides anything else.
Eugene Zelenko7855e772018-04-03 00:11:50 +00001759 if (const auto *TT = T->getAs<TypedefType>())
Richard Smithb2f0f052016-10-10 18:54:32 +00001760 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1761 return Align;
1762
1763 // If we have an (array of) complete type, we're done.
1764 T = getBaseElementType(T);
1765 if (!T->isIncompleteType())
1766 return getTypeAlign(T);
1767
1768 // If we had an array type, its element type might be a typedef
1769 // type with an alignment attribute.
Eugene Zelenko7855e772018-04-03 00:11:50 +00001770 if (const auto *TT = T->getAs<TypedefType>())
Richard Smithb2f0f052016-10-10 18:54:32 +00001771 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1772 return Align;
1773
1774 // Otherwise, see if the declaration of the type had an attribute.
Eugene Zelenko7855e772018-04-03 00:11:50 +00001775 if (const auto *TT = T->getAs<TagType>())
Richard Smithb2f0f052016-10-10 18:54:32 +00001776 return TT->getDecl()->getMaxAlignment();
1777
1778 return 0;
1779}
1780
David Majnemer34b57492014-07-30 01:30:47 +00001781TypeInfo ASTContext::getTypeInfo(const Type *T) const {
David Majnemerf8d38642014-07-30 08:42:33 +00001782 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1783 if (I != MemoizedTypeInfo.end())
1784 return I->second;
1785
1786 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1787 TypeInfo TI = getTypeInfoImpl(T);
1788 MemoizedTypeInfo[T] = TI;
Rafael Espindolaeaa88c12014-07-30 04:40:23 +00001789 return TI;
Daniel Dunbarc6475872012-03-09 04:12:54 +00001790}
1791
1792/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1793/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001794///
1795/// FIXME: Pointers into different addr spaces could have different sizes and
1796/// alignment requirements: getPointerInfo should take an AddrSpace, this
1797/// should take a QualType, &c.
David Majnemer34b57492014-07-30 01:30:47 +00001798TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1799 uint64_t Width = 0;
1800 unsigned Align = 8;
1801 bool AlignIsRequired = false;
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001802 unsigned AS = 0;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001803 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001804#define TYPE(Class, Base)
1805#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001806#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001807#define DEPENDENT_TYPE(Class, Base) case Type::Class:
David Blaikieab277d62013-07-13 21:08:03 +00001808#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1809 case Type::Class: \
1810 assert(!T->isDependentType() && "should not see dependent types here"); \
1811 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
John McCall36b12a82019-10-02 06:35:23 +00001812#include "clang/AST/TypeNodes.inc"
John McCall15547bb2011-06-28 16:49:23 +00001813 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001814
Chris Lattner355332d2007-07-13 22:27:08 +00001815 case Type::FunctionNoProto:
1816 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001817 // GCC extension: alignof(function) = 32 bits
1818 Width = 0;
1819 Align = 32;
1820 break;
1821
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001822 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001823 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001824 Width = 0;
1825 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1826 break;
1827
Steve Naroff5c131802007-08-30 01:06:46 +00001828 case Type::ConstantArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001829 const auto *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001830
David Majnemer34b57492014-07-30 01:30:47 +00001831 TypeInfo EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001832 uint64_t Size = CAT->getSize().getZExtValue();
David Majnemer34b57492014-07-30 01:30:47 +00001833 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
Daniel Dunbarc6475872012-03-09 04:12:54 +00001834 "Overflow in array type bit size evaluation");
David Majnemer34b57492014-07-30 01:30:47 +00001835 Width = EltInfo.Width * Size;
1836 Align = EltInfo.Align;
Warren Hunt5ae586a2013-11-01 23:59:41 +00001837 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1838 getTargetInfo().getPointerWidth(0) == 64)
Rui Ueyama83aa9792016-01-14 21:00:27 +00001839 Width = llvm::alignTo(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001840 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001841 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001842 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001843 case Type::Vector: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001844 const auto *VT = cast<VectorType>(T);
David Majnemer34b57492014-07-30 01:30:47 +00001845 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1846 Width = EltInfo.Width * VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001847 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001848 // If the alignment is not a power of 2, round up to the next power of 2.
1849 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001850 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001851 Align = llvm::NextPowerOf2(Align);
Rui Ueyama83aa9792016-01-14 21:00:27 +00001852 Width = llvm::alignTo(Width, Align);
Chris Lattner63d2b362009-10-22 05:17:15 +00001853 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001854 // Adjust the alignment based on the target max.
1855 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1856 if (TargetVectorAlign && TargetVectorAlign < Align)
1857 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001858 break;
1859 }
Chris Lattner647fb222007-07-18 18:26:58 +00001860
Chris Lattner7570e9c2008-03-08 08:52:55 +00001861 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001862 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001863 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001864 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001865 // GCC extension: alignof(void) = 8 bits.
1866 Width = 0;
1867 Align = 8;
1868 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001869 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001870 Width = Target->getBoolWidth();
1871 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001872 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001873 case BuiltinType::Char_S:
1874 case BuiltinType::Char_U:
1875 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001876 case BuiltinType::SChar:
Richard Smith3a8244d2018-05-01 05:02:45 +00001877 case BuiltinType::Char8:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001878 Width = Target->getCharWidth();
1879 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001880 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001881 case BuiltinType::WChar_S:
1882 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001883 Width = Target->getWCharWidth();
1884 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001885 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001886 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001887 Width = Target->getChar16Width();
1888 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001889 break;
1890 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001891 Width = Target->getChar32Width();
1892 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001893 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001894 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001895 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001896 Width = Target->getShortWidth();
1897 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001898 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001899 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001900 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001901 Width = Target->getIntWidth();
1902 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001903 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001904 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001905 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001906 Width = Target->getLongWidth();
1907 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001908 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001909 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001910 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001911 Width = Target->getLongLongWidth();
1912 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001913 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001914 case BuiltinType::Int128:
1915 case BuiltinType::UInt128:
1916 Width = 128;
1917 Align = 128; // int128_t is 128-bit aligned on all targets.
1918 break;
Leonard Chanf921d852018-06-04 16:07:52 +00001919 case BuiltinType::ShortAccum:
1920 case BuiltinType::UShortAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00001921 case BuiltinType::SatShortAccum:
1922 case BuiltinType::SatUShortAccum:
Leonard Chanf921d852018-06-04 16:07:52 +00001923 Width = Target->getShortAccumWidth();
1924 Align = Target->getShortAccumAlign();
1925 break;
1926 case BuiltinType::Accum:
1927 case BuiltinType::UAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00001928 case BuiltinType::SatAccum:
1929 case BuiltinType::SatUAccum:
Leonard Chanf921d852018-06-04 16:07:52 +00001930 Width = Target->getAccumWidth();
1931 Align = Target->getAccumAlign();
1932 break;
1933 case BuiltinType::LongAccum:
1934 case BuiltinType::ULongAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00001935 case BuiltinType::SatLongAccum:
1936 case BuiltinType::SatULongAccum:
Leonard Chanf921d852018-06-04 16:07:52 +00001937 Width = Target->getLongAccumWidth();
1938 Align = Target->getLongAccumAlign();
1939 break;
Leonard Chanab80f3c2018-06-14 14:53:51 +00001940 case BuiltinType::ShortFract:
1941 case BuiltinType::UShortFract:
1942 case BuiltinType::SatShortFract:
1943 case BuiltinType::SatUShortFract:
1944 Width = Target->getShortFractWidth();
1945 Align = Target->getShortFractAlign();
1946 break;
1947 case BuiltinType::Fract:
1948 case BuiltinType::UFract:
1949 case BuiltinType::SatFract:
1950 case BuiltinType::SatUFract:
1951 Width = Target->getFractWidth();
1952 Align = Target->getFractAlign();
1953 break;
1954 case BuiltinType::LongFract:
1955 case BuiltinType::ULongFract:
1956 case BuiltinType::SatLongFract:
1957 case BuiltinType::SatULongFract:
1958 Width = Target->getLongFractWidth();
1959 Align = Target->getLongFractAlign();
1960 break;
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00001961 case BuiltinType::Float16:
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001962 case BuiltinType::Half:
Alexey Bataev123ad192019-02-27 20:29:45 +00001963 if (Target->hasFloat16Type() || !getLangOpts().OpenMP ||
1964 !getLangOpts().OpenMPIsDevice) {
1965 Width = Target->getHalfWidth();
1966 Align = Target->getHalfAlign();
1967 } else {
1968 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
1969 "Expected OpenMP device compilation.");
1970 Width = AuxTarget->getHalfWidth();
1971 Align = AuxTarget->getHalfAlign();
1972 }
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001973 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001974 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001975 Width = Target->getFloatWidth();
1976 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001977 break;
1978 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001979 Width = Target->getDoubleWidth();
1980 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001981 break;
1982 case BuiltinType::LongDouble:
Alexey Bataev8557d1a2019-06-18 18:39:26 +00001983 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
1984 (Target->getLongDoubleWidth() != AuxTarget->getLongDoubleWidth() ||
1985 Target->getLongDoubleAlign() != AuxTarget->getLongDoubleAlign())) {
1986 Width = AuxTarget->getLongDoubleWidth();
1987 Align = AuxTarget->getLongDoubleAlign();
1988 } else {
1989 Width = Target->getLongDoubleWidth();
1990 Align = Target->getLongDoubleAlign();
1991 }
Chris Lattner6a4f7452007-12-19 19:23:28 +00001992 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001993 case BuiltinType::Float128:
Alexey Bataev123ad192019-02-27 20:29:45 +00001994 if (Target->hasFloat128Type() || !getLangOpts().OpenMP ||
1995 !getLangOpts().OpenMPIsDevice) {
1996 Width = Target->getFloat128Width();
1997 Align = Target->getFloat128Align();
1998 } else {
1999 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
2000 "Expected OpenMP device compilation.");
2001 Width = AuxTarget->getFloat128Width();
2002 Align = AuxTarget->getFloat128Align();
2003 }
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00002004 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00002005 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00002006 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
2007 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00002008 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00002009 case BuiltinType::ObjCId:
2010 case BuiltinType::ObjCClass:
2011 case BuiltinType::ObjCSel:
Fangrui Song6907ce22018-07-30 19:24:48 +00002012 Width = Target->getPointerWidth(0);
Douglas Gregore8bbc122011-09-02 00:18:52 +00002013 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00002014 break;
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00002015 case BuiltinType::OCLSampler:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00002016 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00002017 case BuiltinType::OCLClkEvent:
2018 case BuiltinType::OCLQueue:
Alexey Bader9c8453f2015-09-15 11:18:52 +00002019 case BuiltinType::OCLReserveID:
Yaxun Liu99444cb2016-08-03 20:38:06 +00002020#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2021 case BuiltinType::Id:
2022#include "clang/Basic/OpenCLImageTypes.def"
Andrew Savonichev3fee3512018-11-08 11:25:41 +00002023#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2024 case BuiltinType::Id:
2025#include "clang/Basic/OpenCLExtensionTypes.def"
Sven van Haastregt3bb7eaf2017-12-06 10:11:28 +00002026 AS = getTargetAddressSpace(
2027 Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T)));
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00002028 Width = Target->getPointerWidth(AS);
2029 Align = Target->getPointerAlign(AS);
2030 break;
Richard Sandifordeb485fb2019-08-09 08:52:54 +00002031 // The SVE types are effectively target-specific. The length of an
2032 // SVE_VECTOR_TYPE is only known at runtime, but it is always a multiple
2033 // of 128 bits. There is one predicate bit for each vector byte, so the
2034 // length of an SVE_PREDICATE_TYPE is always a multiple of 16 bits.
2035 //
2036 // Because the length is only known at runtime, we use a dummy value
2037 // of 0 for the static length. The alignment values are those defined
2038 // by the Procedure Call Standard for the Arm Architecture.
2039#define SVE_VECTOR_TYPE(Name, Id, SingletonId, ElKind, ElBits, IsSigned, IsFP)\
2040 case BuiltinType::Id: \
2041 Width = 0; \
2042 Align = 128; \
2043 break;
2044#define SVE_PREDICATE_TYPE(Name, Id, SingletonId, ElKind) \
2045 case BuiltinType::Id: \
2046 Width = 0; \
2047 Align = 16; \
2048 break;
2049#include "clang/Basic/AArch64SVEACLETypes.def"
Chris Lattner983a8bb2007-07-13 22:13:22 +00002050 }
Chris Lattner48f84b82007-07-15 23:46:53 +00002051 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00002052 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00002053 Width = Target->getPointerWidth(0);
2054 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00002055 break;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002056 case Type::BlockPointer:
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00002057 AS = getTargetAddressSpace(cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00002058 Width = Target->getPointerWidth(AS);
2059 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00002060 break;
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002061 case Type::LValueReference:
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002062 case Type::RValueReference:
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002063 // alignof and sizeof should never enter this code path here, so we go
2064 // the pointer route.
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00002065 AS = getTargetAddressSpace(cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00002066 Width = Target->getPointerWidth(AS);
2067 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002068 break;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002069 case Type::Pointer:
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00002070 AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00002071 Width = Target->getPointerWidth(AS);
2072 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00002073 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002074 case Type::MemberPointer: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002075 const auto *MPT = cast<MemberPointerType>(T);
Erich Keane8a6b7402017-11-30 16:37:02 +00002076 CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT);
2077 Width = MPI.Width;
2078 Align = MPI.Align;
Anders Carlsson32440a02009-05-17 02:06:04 +00002079 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002080 }
Chris Lattner647fb222007-07-18 18:26:58 +00002081 case Type::Complex: {
2082 // Complex types have the same alignment as their elements, but twice the
2083 // size.
David Majnemer34b57492014-07-30 01:30:47 +00002084 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
2085 Width = EltInfo.Width * 2;
2086 Align = EltInfo.Align;
Chris Lattner647fb222007-07-18 18:26:58 +00002087 break;
2088 }
John McCall8b07ec22010-05-15 11:32:37 +00002089 case Type::ObjCObject:
2090 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Reid Kleckner0503a872013-12-05 01:23:43 +00002091 case Type::Adjusted:
Reid Kleckner8a365022013-06-24 17:51:48 +00002092 case Type::Decayed:
Reid Kleckner0503a872013-12-05 01:23:43 +00002093 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00002094 case Type::ObjCInterface: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002095 const auto *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00002096 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00002097 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00002098 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00002099 break;
2100 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002101 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002102 case Type::Enum: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002103 const auto *TT = cast<TagType>(T);
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00002104
2105 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00002106 Width = 8;
2107 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00002108 break;
2109 }
Mike Stump11289f42009-09-09 15:08:12 +00002110
Eugene Zelenko7855e772018-04-03 00:11:50 +00002111 if (const auto *ET = dyn_cast<EnumType>(TT)) {
David Majnemer475b25e2015-01-21 10:54:38 +00002112 const EnumDecl *ED = ET->getDecl();
2113 TypeInfo Info =
2114 getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType());
2115 if (unsigned AttrAlign = ED->getMaxAlignment()) {
2116 Info.Align = AttrAlign;
2117 Info.AlignIsRequired = true;
2118 }
2119 return Info;
2120 }
Chris Lattner8b23c252008-04-06 22:05:18 +00002121
Eugene Zelenko7855e772018-04-03 00:11:50 +00002122 const auto *RT = cast<RecordType>(TT);
David Majnemer5821ff72015-02-03 08:49:29 +00002123 const RecordDecl *RD = RT->getDecl();
2124 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
Ken Dyckb0fcc592011-02-11 01:54:29 +00002125 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00002126 Align = toBits(Layout.getAlignment());
David Majnemer5821ff72015-02-03 08:49:29 +00002127 AlignIsRequired = RD->hasAttr<AlignedAttr>();
Chris Lattner49a953a2007-07-23 22:46:22 +00002128 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00002129 }
Douglas Gregordc572a32009-03-30 22:58:21 +00002130
Chris Lattner63d2b362009-10-22 05:17:15 +00002131 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00002132 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
2133 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00002134
Richard Smith600b5262017-01-26 20:40:47 +00002135 case Type::Auto:
2136 case Type::DeducedTemplateSpecialization: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002137 const auto *A = cast<DeducedType>(T);
Richard Smith27d807c2013-04-30 13:56:41 +00002138 assert(!A->getDeducedType().isNull() &&
2139 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00002140 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00002141 }
2142
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002143 case Type::Paren:
2144 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
2145
Leonard Chanc72aaf62019-05-07 03:20:17 +00002146 case Type::MacroQualified:
2147 return getTypeInfo(
2148 cast<MacroQualifiedType>(T)->getUnderlyingType().getTypePtr());
2149
Manman Rene6be26c2016-09-13 17:25:08 +00002150 case Type::ObjCTypeParam:
2151 return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr());
2152
Douglas Gregoref462e62009-04-30 17:32:17 +00002153 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00002154 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
David Majnemer34b57492014-07-30 01:30:47 +00002155 TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00002156 // If the typedef has an aligned attribute on it, it overrides any computed
2157 // alignment we have. This violates the GCC documentation (which says that
2158 // attribute(aligned) can only round up) but matches its implementation.
David Majnemer34b57492014-07-30 01:30:47 +00002159 if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
Chris Lattner29eb47b2011-02-19 22:55:41 +00002160 Align = AttrAlign;
David Majnemer34b57492014-07-30 01:30:47 +00002161 AlignIsRequired = true;
David Majnemer37bffb62014-08-04 05:11:01 +00002162 } else {
David Majnemer34b57492014-07-30 01:30:47 +00002163 Align = Info.Align;
David Majnemer37bffb62014-08-04 05:11:01 +00002164 AlignIsRequired = Info.AlignIsRequired;
2165 }
David Majnemer34b57492014-07-30 01:30:47 +00002166 Width = Info.Width;
Douglas Gregordc572a32009-03-30 22:58:21 +00002167 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00002168 }
Douglas Gregoref462e62009-04-30 17:32:17 +00002169
Abramo Bagnara6150c882010-05-11 21:36:43 +00002170 case Type::Elaborated:
2171 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00002172
John McCall81904512011-01-06 01:58:22 +00002173 case Type::Attributed:
2174 return getTypeInfo(
2175 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
2176
Eli Friedman0dfb8892011-10-06 23:00:33 +00002177 case Type::Atomic: {
John McCalla8ec7eb2013-03-07 21:37:17 +00002178 // Start with the base type information.
David Majnemer34b57492014-07-30 01:30:47 +00002179 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
2180 Width = Info.Width;
2181 Align = Info.Align;
John McCalla8ec7eb2013-03-07 21:37:17 +00002182
JF Bastien801fca22018-05-09 03:51:12 +00002183 if (!Width) {
2184 // An otherwise zero-sized type should still generate an
2185 // atomic operation.
2186 Width = Target->getCharWidth();
2187 assert(Align);
2188 } else if (Width <= Target->getMaxAtomicPromoteWidth()) {
2189 // If the size of the type doesn't exceed the platform's max
2190 // atomic promotion width, make the size and alignment more
2191 // favorable to atomic operations:
2192
John McCalla8ec7eb2013-03-07 21:37:17 +00002193 // Round the size up to a power of 2.
2194 if (!llvm::isPowerOf2_64(Width))
2195 Width = llvm::NextPowerOf2(Width);
2196
2197 // Set the alignment equal to the size.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00002198 Align = static_cast<unsigned>(Width);
2199 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00002200 }
Xiuli Pan9c14e282016-01-09 12:53:17 +00002201 break;
2202
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002203 case Type::Pipe:
Anastasia Stulovab3398932017-06-05 11:27:03 +00002204 Width = Target->getPointerWidth(getTargetAddressSpace(LangAS::opencl_global));
2205 Align = Target->getPointerAlign(getTargetAddressSpace(LangAS::opencl_global));
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002206 break;
Douglas Gregoref462e62009-04-30 17:32:17 +00002207 }
Mike Stump11289f42009-09-09 15:08:12 +00002208
Eli Friedman4b72fdd2011-10-14 20:59:01 +00002209 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
David Majnemer34b57492014-07-30 01:30:47 +00002210 return TypeInfo(Width, Align, AlignIsRequired);
Chris Lattner983a8bb2007-07-13 22:13:22 +00002211}
2212
Momchil Velikov20208cc2018-07-30 17:48:23 +00002213unsigned ASTContext::getTypeUnadjustedAlign(const Type *T) const {
2214 UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(T);
2215 if (I != MemoizedUnadjustedAlign.end())
2216 return I->second;
2217
2218 unsigned UnadjustedAlign;
2219 if (const auto *RT = T->getAs<RecordType>()) {
2220 const RecordDecl *RD = RT->getDecl();
2221 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2222 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2223 } else if (const auto *ObjCI = T->getAs<ObjCInterfaceType>()) {
2224 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2225 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2226 } else {
John Brawn6c49f582019-05-22 11:42:54 +00002227 UnadjustedAlign = getTypeAlign(T->getUnqualifiedDesugaredType());
Momchil Velikov20208cc2018-07-30 17:48:23 +00002228 }
2229
2230 MemoizedUnadjustedAlign[T] = UnadjustedAlign;
2231 return UnadjustedAlign;
2232}
2233
Alexey Bataev00396512015-07-02 03:40:19 +00002234unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
2235 unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign();
2236 // Target ppc64 with QPX: simd default alignment for pointer to double is 32.
2237 if ((getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64 ||
2238 getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64le) &&
2239 getTargetInfo().getABI() == "elfv1-qpx" &&
2240 T->isSpecificBuiltinType(BuiltinType::Double))
2241 SimdAlign = 256;
2242 return SimdAlign;
2243}
2244
Ken Dyckcc56c542011-01-15 18:38:59 +00002245/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
2246CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
2247 return CharUnits::fromQuantity(BitSize / getCharWidth());
2248}
2249
Ken Dyckb0fcc592011-02-11 01:54:29 +00002250/// toBits - Convert a size in characters to a size in characters.
2251int64_t ASTContext::toBits(CharUnits CharSize) const {
2252 return CharSize.getQuantity() * getCharWidth();
2253}
2254
Ken Dyck8c89d592009-12-22 14:23:30 +00002255/// getTypeSizeInChars - Return the size of the specified type, in characters.
2256/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00002257CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00002258 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00002259}
Jay Foad39c79802011-01-12 09:06:06 +00002260CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00002261 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00002262}
2263
Fangrui Song6907ce22018-07-30 19:24:48 +00002264/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00002265/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00002266CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00002267 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00002268}
Jay Foad39c79802011-01-12 09:06:06 +00002269CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00002270 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00002271}
2272
Momchil Velikov20208cc2018-07-30 17:48:23 +00002273/// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a
2274/// type, in characters, before alignment adustments. This method does
2275/// not work on incomplete types.
2276CharUnits ASTContext::getTypeUnadjustedAlignInChars(QualType T) const {
2277 return toCharUnitsFromBits(getTypeUnadjustedAlign(T));
2278}
2279CharUnits ASTContext::getTypeUnadjustedAlignInChars(const Type *T) const {
2280 return toCharUnitsFromBits(getTypeUnadjustedAlign(T));
2281}
2282
Chris Lattnera3402cd2009-01-27 18:08:34 +00002283/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
2284/// type for the current target in bits. This can be different than the ABI
2285/// alignment in cases where it is beneficial for performance to overalign
2286/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00002287unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
David Majnemer34b57492014-07-30 01:30:47 +00002288 TypeInfo TI = getTypeInfo(T);
2289 unsigned ABIAlign = TI.Align;
Eli Friedman7ab09572009-05-25 21:27:19 +00002290
David Majnemere1544562015-04-24 01:25:05 +00002291 T = T->getBaseElementTypeUnsafe();
2292
2293 // The preferred alignment of member pointers is that of a pointer.
2294 if (T->isMemberPointerType())
2295 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
2296
Andrey Turetskiydb6655f2016-02-10 11:58:46 +00002297 if (!Target->allowsLargerPreferedTypeAlignment())
2298 return ABIAlign;
Robert Lyttoneaf6f362013-11-12 10:09:34 +00002299
Eli Friedman7ab09572009-05-25 21:27:19 +00002300 // Double and long long should be naturally aligned if possible.
Eugene Zelenko7855e772018-04-03 00:11:50 +00002301 if (const auto *CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00002302 T = CT->getElementType().getTypePtr();
Eugene Zelenko7855e772018-04-03 00:11:50 +00002303 if (const auto *ET = T->getAs<EnumType>())
David Majnemer475b25e2015-01-21 10:54:38 +00002304 T = ET->getDecl()->getIntegerType().getTypePtr();
Eli Friedman7ab09572009-05-25 21:27:19 +00002305 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00002306 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
2307 T->isSpecificBuiltinType(BuiltinType::ULongLong))
David Majnemer8b6bd572014-02-24 23:34:17 +00002308 // Don't increase the alignment if an alignment attribute was specified on a
2309 // typedef declaration.
David Majnemer34b57492014-07-30 01:30:47 +00002310 if (!TI.AlignIsRequired)
David Majnemer8b6bd572014-02-24 23:34:17 +00002311 return std::max(ABIAlign, (unsigned)getTypeSize(T));
Eli Friedman7ab09572009-05-25 21:27:19 +00002312
Chris Lattnera3402cd2009-01-27 18:08:34 +00002313 return ABIAlign;
2314}
2315
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00002316/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2317/// for __attribute__((aligned)) on this target, to be used if no alignment
2318/// value is specified.
Eugene Zelenkod4304d22015-11-04 21:37:17 +00002319unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const {
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00002320 return getTargetInfo().getDefaultAlignForAttributeAligned();
2321}
2322
Ulrich Weigandfa806422013-05-06 16:23:57 +00002323/// getAlignOfGlobalVar - Return the alignment in bits that should be given
2324/// to a global variable of the specified type.
2325unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
Tom Tanb7c6d952019-05-02 00:38:14 +00002326 uint64_t TypeSize = getTypeSize(T.getTypePtr());
2327 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign(TypeSize));
Ulrich Weigandfa806422013-05-06 16:23:57 +00002328}
2329
2330/// getAlignOfGlobalVarInChars - Return the alignment in characters that
2331/// should be given to a global variable of the specified type.
2332CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
2333 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
2334}
2335
David Majnemer08ef2ba2015-06-23 20:34:18 +00002336CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
2337 CharUnits Offset = CharUnits::Zero();
2338 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
2339 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2340 Offset += Layout->getBaseClassOffset(Base);
2341 Layout = &getASTRecordLayout(Base);
2342 }
2343 return Offset;
2344}
2345
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002346/// DeepCollectObjCIvars -
2347/// This routine first collects all declared, but not synthesized, ivars in
2348/// super class and then collects all ivars, including those synthesized for
2349/// current class. This routine is used for implementation of current class
2350/// when all ivars, declared and synthesized are known.
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002351void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
2352 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00002353 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002354 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2355 DeepCollectObjCIvars(SuperClass, false, Ivars);
2356 if (!leafClass) {
Aaron Ballman59abbd42014-03-13 21:09:43 +00002357 for (const auto *I : OI->ivars())
2358 Ivars.push_back(I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00002359 } else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002360 auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Fangrui Song6907ce22018-07-30 19:24:48 +00002361 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00002362 Iv= Iv->getNextIvar())
2363 Ivars.push_back(Iv);
2364 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00002365}
2366
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002367/// CollectInheritedProtocols - Collect all protocols in current class and
2368/// those inherited by it.
2369void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00002370 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002371 if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00002372 // We can use protocol_iterator here instead of
Fangrui Song6907ce22018-07-30 19:24:48 +00002373 // all_referenced_protocol_iterator since we are walking all categories.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002374 for (auto *Proto : OI->all_referenced_protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002375 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00002376 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002377
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002378 // Categories of this Interface.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00002379 for (const auto *Cat : OI->visible_categories())
2380 CollectInheritedProtocols(Cat, Protocols);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002381
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002382 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2383 while (SD) {
2384 CollectInheritedProtocols(SD, Protocols);
2385 SD = SD->getSuperClass();
2386 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00002387 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00002388 for (auto *Proto : OC->protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002389 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002390 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00002391 } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002392 // Insert the protocol.
2393 if (!Protocols.insert(
2394 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2395 return;
2396
2397 for (auto *Proto : OP->protocols())
2398 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002399 }
2400}
2401
Erich Keane8a6b7402017-11-30 16:37:02 +00002402static bool unionHasUniqueObjectRepresentations(const ASTContext &Context,
2403 const RecordDecl *RD) {
2404 assert(RD->isUnion() && "Must be union type");
2405 CharUnits UnionSize = Context.getTypeSizeInChars(RD->getTypeForDecl());
2406
2407 for (const auto *Field : RD->fields()) {
2408 if (!Context.hasUniqueObjectRepresentations(Field->getType()))
2409 return false;
2410 CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType());
2411 if (FieldSize != UnionSize)
2412 return false;
2413 }
Eric Fiselier12a9f342018-02-02 20:30:39 +00002414 return !RD->field_empty();
Erich Keane8a6b7402017-11-30 16:37:02 +00002415}
2416
Benjamin Kramer802e6252017-12-24 12:46:22 +00002417static bool isStructEmpty(QualType Ty) {
Erich Keane8a6b7402017-11-30 16:37:02 +00002418 const RecordDecl *RD = Ty->castAs<RecordType>()->getDecl();
2419
2420 if (!RD->field_empty())
2421 return false;
2422
2423 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD))
2424 return ClassDecl->isEmpty();
2425
2426 return true;
2427}
2428
2429static llvm::Optional<int64_t>
2430structHasUniqueObjectRepresentations(const ASTContext &Context,
2431 const RecordDecl *RD) {
2432 assert(!RD->isUnion() && "Must be struct/class type");
2433 const auto &Layout = Context.getASTRecordLayout(RD);
2434
2435 int64_t CurOffsetInBits = 0;
2436 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) {
2437 if (ClassDecl->isDynamicClass())
2438 return llvm::None;
2439
2440 SmallVector<std::pair<QualType, int64_t>, 4> Bases;
2441 for (const auto Base : ClassDecl->bases()) {
2442 // Empty types can be inherited from, and non-empty types can potentially
2443 // have tail padding, so just make sure there isn't an error.
2444 if (!isStructEmpty(Base.getType())) {
2445 llvm::Optional<int64_t> Size = structHasUniqueObjectRepresentations(
Simon Pilgrimeed4b122019-10-02 11:48:06 +00002446 Context, Base.getType()->castAs<RecordType>()->getDecl());
Erich Keane8a6b7402017-11-30 16:37:02 +00002447 if (!Size)
2448 return llvm::None;
2449 Bases.emplace_back(Base.getType(), Size.getValue());
2450 }
2451 }
2452
Fangrui Song1d38c132018-09-30 21:41:11 +00002453 llvm::sort(Bases, [&](const std::pair<QualType, int64_t> &L,
2454 const std::pair<QualType, int64_t> &R) {
2455 return Layout.getBaseClassOffset(L.first->getAsCXXRecordDecl()) <
2456 Layout.getBaseClassOffset(R.first->getAsCXXRecordDecl());
2457 });
Erich Keane8a6b7402017-11-30 16:37:02 +00002458
2459 for (const auto Base : Bases) {
2460 int64_t BaseOffset = Context.toBits(
2461 Layout.getBaseClassOffset(Base.first->getAsCXXRecordDecl()));
2462 int64_t BaseSize = Base.second;
2463 if (BaseOffset != CurOffsetInBits)
2464 return llvm::None;
2465 CurOffsetInBits = BaseOffset + BaseSize;
2466 }
2467 }
2468
2469 for (const auto *Field : RD->fields()) {
2470 if (!Field->getType()->isReferenceType() &&
2471 !Context.hasUniqueObjectRepresentations(Field->getType()))
2472 return llvm::None;
2473
2474 int64_t FieldSizeInBits =
2475 Context.toBits(Context.getTypeSizeInChars(Field->getType()));
2476 if (Field->isBitField()) {
2477 int64_t BitfieldSize = Field->getBitWidthValue(Context);
2478
2479 if (BitfieldSize > FieldSizeInBits)
2480 return llvm::None;
2481 FieldSizeInBits = BitfieldSize;
2482 }
2483
2484 int64_t FieldOffsetInBits = Context.getFieldOffset(Field);
2485
2486 if (FieldOffsetInBits != CurOffsetInBits)
2487 return llvm::None;
2488
2489 CurOffsetInBits = FieldSizeInBits + FieldOffsetInBits;
2490 }
2491
2492 return CurOffsetInBits;
2493}
2494
2495bool ASTContext::hasUniqueObjectRepresentations(QualType Ty) const {
2496 // C++17 [meta.unary.prop]:
2497 // The predicate condition for a template specialization
2498 // has_unique_object_representations<T> shall be
2499 // satisfied if and only if:
2500 // (9.1) - T is trivially copyable, and
2501 // (9.2) - any two objects of type T with the same value have the same
2502 // object representation, where two objects
2503 // of array or non-union class type are considered to have the same value
2504 // if their respective sequences of
2505 // direct subobjects have the same values, and two objects of union type
2506 // are considered to have the same
2507 // value if they have the same active member and the corresponding members
2508 // have the same value.
2509 // The set of scalar types for which this condition holds is
2510 // implementation-defined. [ Note: If a type has padding
2511 // bits, the condition does not hold; otherwise, the condition holds true
2512 // for unsigned integral types. -- end note ]
2513 assert(!Ty.isNull() && "Null QualType sent to unique object rep check");
2514
2515 // Arrays are unique only if their element type is unique.
2516 if (Ty->isArrayType())
2517 return hasUniqueObjectRepresentations(getBaseElementType(Ty));
2518
2519 // (9.1) - T is trivially copyable...
2520 if (!Ty.isTriviallyCopyableType(*this))
2521 return false;
2522
2523 // All integrals and enums are unique.
2524 if (Ty->isIntegralOrEnumerationType())
2525 return true;
2526
2527 // All other pointers are unique.
2528 if (Ty->isPointerType())
2529 return true;
2530
2531 if (Ty->isMemberPointerType()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002532 const auto *MPT = Ty->getAs<MemberPointerType>();
Erich Keane8a6b7402017-11-30 16:37:02 +00002533 return !ABI->getMemberPointerInfo(MPT).HasPadding;
2534 }
2535
2536 if (Ty->isRecordType()) {
Simon Pilgrimeed4b122019-10-02 11:48:06 +00002537 const RecordDecl *Record = Ty->castAs<RecordType>()->getDecl();
Erich Keane8a6b7402017-11-30 16:37:02 +00002538
Erich Keanebd2197c2017-12-12 16:02:06 +00002539 if (Record->isInvalidDecl())
2540 return false;
2541
Erich Keane8a6b7402017-11-30 16:37:02 +00002542 if (Record->isUnion())
2543 return unionHasUniqueObjectRepresentations(*this, Record);
2544
2545 Optional<int64_t> StructSize =
2546 structHasUniqueObjectRepresentations(*this, Record);
2547
2548 return StructSize &&
2549 StructSize.getValue() == static_cast<int64_t>(getTypeSize(Ty));
2550 }
2551
2552 // FIXME: More cases to handle here (list by rsmith):
2553 // vectors (careful about, eg, vector of 3 foo)
2554 // _Complex int and friends
2555 // _Atomic T
2556 // Obj-C block pointers
2557 // Obj-C object pointers
2558 // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t,
2559 // clk_event_t, queue_t, reserve_id_t)
2560 // There're also Obj-C class types and the Obj-C selector type, but I think it
2561 // makes sense for those to return false here.
2562
2563 return false;
2564}
2565
Jay Foad39c79802011-01-12 09:06:06 +00002566unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00002567 unsigned count = 0;
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00002568 // Count ivars declared in class extension.
Aaron Ballmanb4a53452014-03-13 21:57:01 +00002569 for (const auto *Ext : OI->known_extensions())
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002570 count += Ext->ivar_size();
Fangrui Song6907ce22018-07-30 19:24:48 +00002571
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00002572 // Count ivar defined in this class's implementation. This
2573 // includes synthesized ivars.
2574 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00002575 count += ImplDecl->ivar_size();
2576
Fariborz Jahanian7c809592009-06-04 01:19:09 +00002577 return count;
2578}
2579
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00002580bool ASTContext::isSentinelNullExpr(const Expr *E) {
2581 if (!E)
2582 return false;
2583
2584 // nullptr_t is always treated as null.
2585 if (E->getType()->isNullPtrType()) return true;
2586
2587 if (E->getType()->isAnyPointerType() &&
2588 E->IgnoreParenCasts()->isNullPointerConstant(*this,
2589 Expr::NPC_ValueDependentIsNull))
2590 return true;
2591
2592 // Unfortunately, __null has type 'int'.
2593 if (isa<GNUNullExpr>(E)) return true;
2594
2595 return false;
2596}
2597
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002598/// Get the implementation of ObjCInterfaceDecl, or nullptr if none
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002599/// exists.
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002600ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
2601 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2602 I = ObjCImpls.find(D);
2603 if (I != ObjCImpls.end())
2604 return cast<ObjCImplementationDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002605 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002606}
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002607
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002608/// Get the implementation of ObjCCategoryDecl, or nullptr if none
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002609/// exists.
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002610ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
2611 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2612 I = ObjCImpls.find(D);
2613 if (I != ObjCImpls.end())
2614 return cast<ObjCCategoryImplDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002615 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002616}
2617
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002618/// Set the implementation of ObjCInterfaceDecl.
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002619void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2620 ObjCImplementationDecl *ImplD) {
2621 assert(IFaceD && ImplD && "Passed null params");
2622 ObjCImpls[IFaceD] = ImplD;
2623}
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002624
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002625/// Set the implementation of ObjCCategoryDecl.
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002626void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
2627 ObjCCategoryImplDecl *ImplD) {
2628 assert(CatD && ImplD && "Passed null params");
2629 ObjCImpls[CatD] = ImplD;
2630}
2631
Chandler Carruth21c90602015-12-30 03:24:14 +00002632const ObjCMethodDecl *
2633ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const {
2634 return ObjCMethodRedecls.lookup(MD);
2635}
2636
2637void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
2638 const ObjCMethodDecl *Redecl) {
2639 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
2640 ObjCMethodRedecls[MD] = Redecl;
2641}
2642
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002643const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
2644 const NamedDecl *ND) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002645 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002646 return ID;
Eugene Zelenko7855e772018-04-03 00:11:50 +00002647 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002648 return CD->getClassInterface();
Eugene Zelenko7855e772018-04-03 00:11:50 +00002649 if (const auto *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002650 return IMD->getClassInterface();
2651
Craig Topper36250ad2014-05-12 05:36:57 +00002652 return nullptr;
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002653}
2654
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002655/// Get the copy initialization expression of VarDecl, or nullptr if
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002656/// none exists.
Akira Hatanaka9978da32018-08-10 15:09:24 +00002657ASTContext::BlockVarCopyInit
2658ASTContext::getBlockVarCopyInit(const VarDecl*VD) const {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002659 assert(VD && "Passed null params");
Fangrui Song6907ce22018-07-30 19:24:48 +00002660 assert(VD->hasAttr<BlocksAttr>() &&
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002661 "getBlockVarCopyInits - not __block var");
Akira Hatanaka9978da32018-08-10 15:09:24 +00002662 auto I = BlockVarCopyInits.find(VD);
2663 if (I != BlockVarCopyInits.end())
2664 return I->second;
2665 return {nullptr, false};
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002666}
2667
JF Bastien0d702a72019-04-30 00:11:53 +00002668/// Set the copy initialization expression of a block var decl.
Akira Hatanaka9978da32018-08-10 15:09:24 +00002669void ASTContext::setBlockVarCopyInit(const VarDecl*VD, Expr *CopyExpr,
2670 bool CanThrow) {
2671 assert(VD && CopyExpr && "Passed null params");
Fangrui Song6907ce22018-07-30 19:24:48 +00002672 assert(VD->hasAttr<BlocksAttr>() &&
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002673 "setBlockVarCopyInits - not __block var");
Akira Hatanaka9978da32018-08-10 15:09:24 +00002674 BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002675}
2676
John McCallbcd03502009-12-07 02:54:59 +00002677TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002678 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00002679 if (!DataSize)
2680 DataSize = TypeLoc::getFullDataSizeForType(T);
2681 else
2682 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00002683 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00002684
Eugene Zelenko7855e772018-04-03 00:11:50 +00002685 auto *TInfo =
John McCallbcd03502009-12-07 02:54:59 +00002686 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
2687 new (TInfo) TypeSourceInfo(T);
2688 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00002689}
2690
John McCallbcd03502009-12-07 02:54:59 +00002691TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002692 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00002693 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00002694 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00002695 return DI;
2696}
2697
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002698const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002699ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Craig Topper36250ad2014-05-12 05:36:57 +00002700 return getObjCLayout(D, nullptr);
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002701}
2702
2703const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002704ASTContext::getASTObjCImplementationLayout(
2705 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002706 return getObjCLayout(D->getClassInterface(), D);
2707}
2708
Chris Lattner983a8bb2007-07-13 22:13:22 +00002709//===----------------------------------------------------------------------===//
2710// Type creation/memoization methods
2711//===----------------------------------------------------------------------===//
2712
Jay Foad39c79802011-01-12 09:06:06 +00002713QualType
John McCall33ddac02011-01-19 10:06:00 +00002714ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2715 unsigned fastQuals = quals.getFastQualifiers();
2716 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00002717
2718 // Check if we've already instantiated this type.
2719 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002720 ExtQuals::Profile(ID, baseType, quals);
Craig Topper36250ad2014-05-12 05:36:57 +00002721 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002722 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2723 assert(eq->getQualifiers() == quals);
2724 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002725 }
2726
John McCall33ddac02011-01-19 10:06:00 +00002727 // If the base type is not canonical, make the appropriate canonical type.
2728 QualType canon;
2729 if (!baseType->isCanonicalUnqualified()) {
2730 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00002731 canonSplit.Quals.addConsistentQualifiers(quals);
2732 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002733
2734 // Re-find the insert position.
2735 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2736 }
2737
Eugene Zelenko7855e772018-04-03 00:11:50 +00002738 auto *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
John McCall33ddac02011-01-19 10:06:00 +00002739 ExtQualNodes.InsertNode(eq, insertPos);
2740 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002741}
2742
Alexander Richardson6d989432017-10-15 18:48:14 +00002743QualType ASTContext::getAddrSpaceQualType(QualType T,
2744 LangAS AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002745 QualType CanT = getCanonicalType(T);
2746 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00002747 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00002748
John McCall8ccfcb52009-09-24 19:53:00 +00002749 // If we are composing extended qualifiers together, merge together
2750 // into one ExtQuals node.
2751 QualifierCollector Quals;
2752 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002753
John McCall8ccfcb52009-09-24 19:53:00 +00002754 // If this type already has an address space specified, it cannot get
2755 // another one.
2756 assert(!Quals.hasAddressSpace() &&
2757 "Type cannot be in multiple addr spaces!");
2758 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00002759
John McCall8ccfcb52009-09-24 19:53:00 +00002760 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00002761}
2762
Andrew Gozillon572bbb02017-10-02 06:25:51 +00002763QualType ASTContext::removeAddrSpaceQualType(QualType T) const {
2764 // If we are composing extended qualifiers together, merge together
2765 // into one ExtQuals node.
2766 QualifierCollector Quals;
2767 const Type *TypeNode = Quals.strip(T);
2768
2769 // If the qualifier doesn't have an address space just return it.
2770 if (!Quals.hasAddressSpace())
2771 return T;
2772
2773 Quals.removeAddressSpace();
2774
2775 // Removal of the address space can mean there are no longer any
2776 // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts)
2777 // or required.
2778 if (Quals.hasNonFastQualifiers())
2779 return getExtQualType(TypeNode, Quals);
2780 else
2781 return QualType(TypeNode, Quals.getFastQualifiers());
2782}
2783
Chris Lattnerd60183d2009-02-18 22:53:11 +00002784QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002785 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002786 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00002787 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002788 return T;
Mike Stump11289f42009-09-09 15:08:12 +00002789
Eugene Zelenko7855e772018-04-03 00:11:50 +00002790 if (const auto *ptr = T->getAs<PointerType>()) {
John McCall53fa7142010-12-24 02:08:15 +00002791 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00002792 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00002793 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2794 return getPointerType(ResultType);
2795 }
2796 }
Mike Stump11289f42009-09-09 15:08:12 +00002797
John McCall8ccfcb52009-09-24 19:53:00 +00002798 // If we are composing extended qualifiers together, merge together
2799 // into one ExtQuals node.
2800 QualifierCollector Quals;
2801 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002802
John McCall8ccfcb52009-09-24 19:53:00 +00002803 // If this type already has an ObjCGC specified, it cannot get
2804 // another one.
2805 assert(!Quals.hasObjCGCAttr() &&
2806 "Type cannot have multiple ObjCGCs!");
2807 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00002808
John McCall8ccfcb52009-09-24 19:53:00 +00002809 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002810}
Chris Lattner983a8bb2007-07-13 22:13:22 +00002811
John McCall4f5019e2010-12-19 02:44:49 +00002812const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2813 FunctionType::ExtInfo Info) {
2814 if (T->getExtInfo() == Info)
2815 return T;
2816
2817 QualType Result;
Eugene Zelenko7855e772018-04-03 00:11:50 +00002818 if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
Alp Toker314cc812014-01-25 16:55:45 +00002819 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
John McCall4f5019e2010-12-19 02:44:49 +00002820 } else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002821 const auto *FPT = cast<FunctionProtoType>(T);
John McCall4f5019e2010-12-19 02:44:49 +00002822 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2823 EPI.ExtInfo = Info;
Alp Toker314cc812014-01-25 16:55:45 +00002824 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
John McCall4f5019e2010-12-19 02:44:49 +00002825 }
2826
2827 return cast<FunctionType>(Result.getTypePtr());
2828}
2829
Richard Smith2a7d4812013-05-04 07:00:32 +00002830void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2831 QualType ResultType) {
Richard Smith1fa5d642013-05-11 05:45:24 +00002832 FD = FD->getMostRecentDecl();
2833 while (true) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002834 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
Richard Smith2a7d4812013-05-04 07:00:32 +00002835 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Alp Toker9cacbab2014-01-20 20:26:09 +00002836 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
Richard Smith1fa5d642013-05-11 05:45:24 +00002837 if (FunctionDecl *Next = FD->getPreviousDecl())
2838 FD = Next;
2839 else
2840 break;
Richard Smith2a7d4812013-05-04 07:00:32 +00002841 }
Richard Smith1fa5d642013-05-11 05:45:24 +00002842 if (ASTMutationListener *L = getASTMutationListener())
2843 L->DeducedReturnType(FD, ResultType);
Richard Smith2a7d4812013-05-04 07:00:32 +00002844}
2845
Richard Smith0b3a4622014-11-13 20:01:57 +00002846/// Get a function type and produce the equivalent function type with the
2847/// specified exception specification. Type sugar that can be present on a
2848/// declaration of a function with an exception specification is permitted
2849/// and preserved. Other type sugar (for instance, typedefs) is not.
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002850QualType ASTContext::getFunctionTypeWithExceptionSpec(
2851 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) {
Richard Smith0b3a4622014-11-13 20:01:57 +00002852 // Might have some parens.
Eugene Zelenko7855e772018-04-03 00:11:50 +00002853 if (const auto *PT = dyn_cast<ParenType>(Orig))
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002854 return getParenType(
2855 getFunctionTypeWithExceptionSpec(PT->getInnerType(), ESI));
Richard Smith0b3a4622014-11-13 20:01:57 +00002856
Leonard Chandc5d9752019-05-10 18:05:15 +00002857 // Might be wrapped in a macro qualified type.
2858 if (const auto *MQT = dyn_cast<MacroQualifiedType>(Orig))
2859 return getMacroQualifiedType(
2860 getFunctionTypeWithExceptionSpec(MQT->getUnderlyingType(), ESI),
2861 MQT->getMacroIdentifier());
2862
Richard Smith0b3a4622014-11-13 20:01:57 +00002863 // Might have a calling-convention attribute.
Eugene Zelenko7855e772018-04-03 00:11:50 +00002864 if (const auto *AT = dyn_cast<AttributedType>(Orig))
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002865 return getAttributedType(
Richard Smith0b3a4622014-11-13 20:01:57 +00002866 AT->getAttrKind(),
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002867 getFunctionTypeWithExceptionSpec(AT->getModifiedType(), ESI),
2868 getFunctionTypeWithExceptionSpec(AT->getEquivalentType(), ESI));
Richard Smith0b3a4622014-11-13 20:01:57 +00002869
2870 // Anything else must be a function type. Rebuild it with the new exception
2871 // specification.
Simon Pilgrim9588ae72019-10-03 21:47:42 +00002872 const auto *Proto = Orig->castAs<FunctionProtoType>();
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002873 return getFunctionType(
Richard Smith0b3a4622014-11-13 20:01:57 +00002874 Proto->getReturnType(), Proto->getParamTypes(),
2875 Proto->getExtProtoInfo().withExceptionSpec(ESI));
2876}
2877
Richard Smithdfe85e22016-12-15 02:35:39 +00002878bool ASTContext::hasSameFunctionTypeIgnoringExceptionSpec(QualType T,
2879 QualType U) {
2880 return hasSameType(T, U) ||
Aaron Ballmanc351fba2017-12-04 20:27:34 +00002881 (getLangOpts().CPlusPlus17 &&
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002882 hasSameType(getFunctionTypeWithExceptionSpec(T, EST_None),
2883 getFunctionTypeWithExceptionSpec(U, EST_None)));
Richard Smithdfe85e22016-12-15 02:35:39 +00002884}
2885
Richard Smith0b3a4622014-11-13 20:01:57 +00002886void ASTContext::adjustExceptionSpec(
2887 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
2888 bool AsWritten) {
2889 // Update the type.
2890 QualType Updated =
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002891 getFunctionTypeWithExceptionSpec(FD->getType(), ESI);
Richard Smith0b3a4622014-11-13 20:01:57 +00002892 FD->setType(Updated);
2893
2894 if (!AsWritten)
2895 return;
2896
2897 // Update the type in the type source information too.
2898 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
2899 // If the type and the type-as-written differ, we may need to update
2900 // the type-as-written too.
2901 if (TSInfo->getType() != FD->getType())
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002902 Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI);
Richard Smith0b3a4622014-11-13 20:01:57 +00002903
2904 // FIXME: When we get proper type location information for exceptions,
2905 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
2906 // up the TypeSourceInfo;
2907 assert(TypeLoc::getFullDataSizeForType(Updated) ==
2908 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
2909 "TypeLoc size mismatch from updating exception specification");
2910 TSInfo->overrideType(Updated);
2911 }
2912}
2913
Chris Lattnerc6395932007-06-22 20:56:16 +00002914/// getComplexType - Return the uniqued reference to the type for a complex
2915/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00002916QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00002917 // Unique pointers, to guarantee there is only one pointer of a particular
2918 // structure.
2919 llvm::FoldingSetNodeID ID;
2920 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002921
Craig Topper36250ad2014-05-12 05:36:57 +00002922 void *InsertPos = nullptr;
Chris Lattnerc6395932007-06-22 20:56:16 +00002923 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2924 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002925
Chris Lattnerc6395932007-06-22 20:56:16 +00002926 // If the pointee type isn't canonical, this won't be a canonical type either,
2927 // so fill in the canonical type field.
2928 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002929 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002930 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002931
Chris Lattnerc6395932007-06-22 20:56:16 +00002932 // Get the new insert position for the node we care about.
2933 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002934 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00002935 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00002936 auto *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00002937 Types.push_back(New);
2938 ComplexTypes.InsertNode(New, InsertPos);
2939 return QualType(New, 0);
2940}
2941
Chris Lattner970e54e2006-11-12 00:37:36 +00002942/// getPointerType - Return the uniqued reference to the type for a pointer to
2943/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002944QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00002945 // Unique pointers, to guarantee there is only one pointer of a particular
2946 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002947 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00002948 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002949
Craig Topper36250ad2014-05-12 05:36:57 +00002950 void *InsertPos = nullptr;
Chris Lattner67521df2007-01-27 01:29:36 +00002951 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002952 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002953
Chris Lattner7ccecb92006-11-12 08:50:50 +00002954 // If the pointee type isn't canonical, this won't be a canonical type either,
2955 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002956 QualType Canonical;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002957 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002958 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002959
Bob Wilsonc8541f22013-03-15 17:12:43 +00002960 // Get the new insert position for the node we care about.
2961 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002962 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002963 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00002964 auto *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00002965 Types.push_back(New);
2966 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002967 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00002968}
2969
Reid Kleckner0503a872013-12-05 01:23:43 +00002970QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
2971 llvm::FoldingSetNodeID ID;
2972 AdjustedType::Profile(ID, Orig, New);
Craig Topper36250ad2014-05-12 05:36:57 +00002973 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002974 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2975 if (AT)
2976 return QualType(AT, 0);
2977
2978 QualType Canonical = getCanonicalType(New);
2979
2980 // Get the new insert position for the node we care about.
2981 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002982 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner0503a872013-12-05 01:23:43 +00002983
2984 AT = new (*this, TypeAlignment)
2985 AdjustedType(Type::Adjusted, Orig, New, Canonical);
2986 Types.push_back(AT);
2987 AdjustedTypes.InsertNode(AT, InsertPos);
2988 return QualType(AT, 0);
2989}
2990
Reid Kleckner8a365022013-06-24 17:51:48 +00002991QualType ASTContext::getDecayedType(QualType T) const {
2992 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2993
Reid Kleckner8a365022013-06-24 17:51:48 +00002994 QualType Decayed;
2995
2996 // C99 6.7.5.3p7:
2997 // A declaration of a parameter as "array of type" shall be
2998 // adjusted to "qualified pointer to type", where the type
2999 // qualifiers (if any) are those specified within the [ and ] of
3000 // the array type derivation.
3001 if (T->isArrayType())
3002 Decayed = getArrayDecayedType(T);
3003
3004 // C99 6.7.5.3p8:
3005 // A declaration of a parameter as "function returning type"
3006 // shall be adjusted to "pointer to function returning type", as
3007 // in 6.3.2.1.
3008 if (T->isFunctionType())
3009 Decayed = getPointerType(T);
3010
Reid Kleckner0503a872013-12-05 01:23:43 +00003011 llvm::FoldingSetNodeID ID;
3012 AdjustedType::Profile(ID, T, Decayed);
Craig Topper36250ad2014-05-12 05:36:57 +00003013 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00003014 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3015 if (AT)
3016 return QualType(AT, 0);
3017
Reid Kleckner8a365022013-06-24 17:51:48 +00003018 QualType Canonical = getCanonicalType(Decayed);
3019
3020 // Get the new insert position for the node we care about.
Reid Kleckner0503a872013-12-05 01:23:43 +00003021 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003022 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner8a365022013-06-24 17:51:48 +00003023
Reid Kleckner0503a872013-12-05 01:23:43 +00003024 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
3025 Types.push_back(AT);
3026 AdjustedTypes.InsertNode(AT, InsertPos);
3027 return QualType(AT, 0);
Reid Kleckner8a365022013-06-24 17:51:48 +00003028}
3029
Mike Stump11289f42009-09-09 15:08:12 +00003030/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00003031/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00003032QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00003033 assert(T->isFunctionType() && "block of function types only");
3034 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00003035 // structure.
3036 llvm::FoldingSetNodeID ID;
3037 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00003038
Craig Topper36250ad2014-05-12 05:36:57 +00003039 void *InsertPos = nullptr;
Steve Naroffec33ed92008-08-27 16:04:49 +00003040 if (BlockPointerType *PT =
3041 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3042 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003043
3044 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00003045 // type either so fill in the canonical type field.
3046 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00003047 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00003048 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00003049
Steve Naroffec33ed92008-08-27 16:04:49 +00003050 // Get the new insert position for the node we care about.
3051 BlockPointerType *NewIP =
3052 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003053 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00003054 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00003055 auto *New = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00003056 Types.push_back(New);
3057 BlockPointerTypes.InsertNode(New, InsertPos);
3058 return QualType(New, 0);
3059}
3060
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003061/// getLValueReferenceType - Return the uniqued reference to the type for an
3062/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00003063QualType
3064ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00003065 assert(getCanonicalType(T) != OverloadTy &&
Douglas Gregor291e8ee2011-05-21 22:16:50 +00003066 "Unresolved overloaded function type");
Fangrui Song6907ce22018-07-30 19:24:48 +00003067
Bill Wendling3708c182007-05-27 10:15:43 +00003068 // Unique pointers, to guarantee there is only one pointer of a particular
3069 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00003070 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00003071 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00003072
Craig Topper36250ad2014-05-12 05:36:57 +00003073 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003074 if (LValueReferenceType *RT =
3075 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00003076 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003077
Eugene Zelenko7855e772018-04-03 00:11:50 +00003078 const auto *InnerRef = T->getAs<ReferenceType>();
John McCallfc93cf92009-10-22 22:37:11 +00003079
Bill Wendling3708c182007-05-27 10:15:43 +00003080 // If the referencee type isn't canonical, this won't be a canonical type
3081 // either, so fill in the canonical type field.
3082 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00003083 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
3084 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
3085 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003086
Bill Wendling3708c182007-05-27 10:15:43 +00003087 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003088 LValueReferenceType *NewIP =
3089 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003090 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00003091 }
3092
Eugene Zelenko7855e772018-04-03 00:11:50 +00003093 auto *New = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
3094 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00003095 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003096 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00003097
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003098 return QualType(New, 0);
3099}
3100
3101/// getRValueReferenceType - Return the uniqued reference to the type for an
3102/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00003103QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003104 // Unique pointers, to guarantee there is only one pointer of a particular
3105 // structure.
3106 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00003107 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003108
Craig Topper36250ad2014-05-12 05:36:57 +00003109 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003110 if (RValueReferenceType *RT =
3111 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
3112 return QualType(RT, 0);
3113
Eugene Zelenko7855e772018-04-03 00:11:50 +00003114 const auto *InnerRef = T->getAs<ReferenceType>();
John McCallfc93cf92009-10-22 22:37:11 +00003115
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003116 // If the referencee type isn't canonical, this won't be a canonical type
3117 // either, so fill in the canonical type field.
3118 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00003119 if (InnerRef || !T.isCanonical()) {
3120 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
3121 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003122
3123 // Get the new insert position for the node we care about.
3124 RValueReferenceType *NewIP =
3125 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003126 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003127 }
3128
Eugene Zelenko7855e772018-04-03 00:11:50 +00003129 auto *New = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003130 Types.push_back(New);
3131 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00003132 return QualType(New, 0);
3133}
3134
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00003135/// getMemberPointerType - Return the uniqued reference to the type for a
3136/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00003137QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00003138 // Unique pointers, to guarantee there is only one pointer of a particular
3139 // structure.
3140 llvm::FoldingSetNodeID ID;
3141 MemberPointerType::Profile(ID, T, Cls);
3142
Craig Topper36250ad2014-05-12 05:36:57 +00003143 void *InsertPos = nullptr;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00003144 if (MemberPointerType *PT =
3145 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3146 return QualType(PT, 0);
3147
3148 // If the pointee or class type isn't canonical, this won't be a canonical
3149 // type either, so fill in the canonical type field.
3150 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00003151 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00003152 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
3153
3154 // Get the new insert position for the node we care about.
3155 MemberPointerType *NewIP =
3156 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003157 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00003158 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00003159 auto *New = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00003160 Types.push_back(New);
3161 MemberPointerTypes.InsertNode(New, InsertPos);
3162 return QualType(New, 0);
3163}
3164
Mike Stump11289f42009-09-09 15:08:12 +00003165/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00003166/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00003167QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00003168 const llvm::APInt &ArySizeIn,
Richard Smith772e2662019-10-04 01:25:59 +00003169 const Expr *SizeExpr,
Steve Naroff90dfdd52007-08-30 18:10:14 +00003170 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00003171 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00003172 assert((EltTy->isDependentType() ||
3173 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00003174 "Constant array of VLAs is illegal!");
3175
Richard Smith772e2662019-10-04 01:25:59 +00003176 // We only need the size as part of the type if it's instantiation-dependent.
3177 if (SizeExpr && !SizeExpr->isInstantiationDependent())
3178 SizeExpr = nullptr;
3179
Chris Lattnere2df3f92009-05-13 04:12:56 +00003180 // Convert the array size into a canonical width matching the pointer size for
3181 // the target.
3182 llvm::APInt ArySize(ArySizeIn);
Konstantin Zhuravlyov9c1e3102017-03-21 18:55:39 +00003183 ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth());
Mike Stump11289f42009-09-09 15:08:12 +00003184
Chris Lattner23b7eb62007-06-15 23:05:46 +00003185 llvm::FoldingSetNodeID ID;
Richard Smith772e2662019-10-04 01:25:59 +00003186 ConstantArrayType::Profile(ID, *this, EltTy, ArySize, SizeExpr, ASM,
3187 IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00003188
Craig Topper36250ad2014-05-12 05:36:57 +00003189 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003190 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00003191 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003192 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003193
Richard Smith772e2662019-10-04 01:25:59 +00003194 // If the element type isn't canonical or has qualifiers, or the array bound
3195 // is instantiation-dependent, this won't be a canonical type either, so fill
3196 // in the canonical type field.
John McCall33ddac02011-01-19 10:06:00 +00003197 QualType Canon;
Richard Smith772e2662019-10-04 01:25:59 +00003198 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers() || SizeExpr) {
John McCall33ddac02011-01-19 10:06:00 +00003199 SplitQualType canonSplit = getCanonicalType(EltTy).split();
Richard Smith772e2662019-10-04 01:25:59 +00003200 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize, nullptr,
Abramo Bagnara92141d22011-01-27 19:55:10 +00003201 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00003202 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00003203
Chris Lattner36f8e652007-01-27 08:31:04 +00003204 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00003205 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00003206 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003207 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00003208 }
Mike Stump11289f42009-09-09 15:08:12 +00003209
Richard Smith772e2662019-10-04 01:25:59 +00003210 void *Mem = Allocate(
3211 ConstantArrayType::totalSizeToAlloc<const Expr *>(SizeExpr ? 1 : 0),
3212 TypeAlignment);
3213 auto *New = new (Mem)
3214 ConstantArrayType(EltTy, Canon, ArySize, SizeExpr, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00003215 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00003216 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003217 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00003218}
3219
John McCall06549462011-01-18 08:40:38 +00003220/// getVariableArrayDecayedType - Turns the given type, which may be
3221/// variably-modified, into the corresponding type with all the known
3222/// sizes replaced with [*].
3223QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
3224 // Vastly most common case.
3225 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003226
John McCall06549462011-01-18 08:40:38 +00003227 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003228
John McCall06549462011-01-18 08:40:38 +00003229 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00003230 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00003231 switch (ty->getTypeClass()) {
3232#define TYPE(Class, Base)
3233#define ABSTRACT_TYPE(Class, Base)
3234#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
John McCall36b12a82019-10-02 06:35:23 +00003235#include "clang/AST/TypeNodes.inc"
John McCall06549462011-01-18 08:40:38 +00003236 llvm_unreachable("didn't desugar past all non-canonical types?");
3237
3238 // These types should never be variably-modified.
3239 case Type::Builtin:
3240 case Type::Complex:
3241 case Type::Vector:
Erich Keanef702b022018-07-13 19:46:04 +00003242 case Type::DependentVector:
John McCall06549462011-01-18 08:40:38 +00003243 case Type::ExtVector:
3244 case Type::DependentSizedExtVector:
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003245 case Type::DependentAddressSpace:
John McCall06549462011-01-18 08:40:38 +00003246 case Type::ObjCObject:
3247 case Type::ObjCInterface:
3248 case Type::ObjCObjectPointer:
3249 case Type::Record:
3250 case Type::Enum:
3251 case Type::UnresolvedUsing:
3252 case Type::TypeOfExpr:
3253 case Type::TypeOf:
3254 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00003255 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00003256 case Type::DependentName:
3257 case Type::InjectedClassName:
3258 case Type::TemplateSpecialization:
3259 case Type::DependentTemplateSpecialization:
3260 case Type::TemplateTypeParm:
3261 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00003262 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00003263 case Type::DeducedTemplateSpecialization:
John McCall06549462011-01-18 08:40:38 +00003264 case Type::PackExpansion:
3265 llvm_unreachable("type should never be variably-modified");
3266
3267 // These types can be variably-modified but should never need to
3268 // further decay.
3269 case Type::FunctionNoProto:
3270 case Type::FunctionProto:
3271 case Type::BlockPointer:
3272 case Type::MemberPointer:
Xiuli Pan9c14e282016-01-09 12:53:17 +00003273 case Type::Pipe:
John McCall06549462011-01-18 08:40:38 +00003274 return type;
3275
3276 // These types can be variably-modified. All these modifications
3277 // preserve structure except as noted by comments.
3278 // TODO: if we ever care about optimizing VLAs, there are no-op
3279 // optimizations available here.
3280 case Type::Pointer:
3281 result = getPointerType(getVariableArrayDecayedType(
3282 cast<PointerType>(ty)->getPointeeType()));
3283 break;
3284
3285 case Type::LValueReference: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003286 const auto *lv = cast<LValueReferenceType>(ty);
John McCall06549462011-01-18 08:40:38 +00003287 result = getLValueReferenceType(
3288 getVariableArrayDecayedType(lv->getPointeeType()),
3289 lv->isSpelledAsLValue());
3290 break;
3291 }
3292
3293 case Type::RValueReference: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003294 const auto *lv = cast<RValueReferenceType>(ty);
John McCall06549462011-01-18 08:40:38 +00003295 result = getRValueReferenceType(
3296 getVariableArrayDecayedType(lv->getPointeeType()));
3297 break;
3298 }
3299
Eli Friedman0dfb8892011-10-06 23:00:33 +00003300 case Type::Atomic: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003301 const auto *at = cast<AtomicType>(ty);
Eli Friedman0dfb8892011-10-06 23:00:33 +00003302 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
3303 break;
3304 }
3305
John McCall06549462011-01-18 08:40:38 +00003306 case Type::ConstantArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003307 const auto *cat = cast<ConstantArrayType>(ty);
John McCall06549462011-01-18 08:40:38 +00003308 result = getConstantArrayType(
3309 getVariableArrayDecayedType(cat->getElementType()),
3310 cat->getSize(),
Richard Smith772e2662019-10-04 01:25:59 +00003311 cat->getSizeExpr(),
John McCall06549462011-01-18 08:40:38 +00003312 cat->getSizeModifier(),
3313 cat->getIndexTypeCVRQualifiers());
3314 break;
3315 }
3316
3317 case Type::DependentSizedArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003318 const auto *dat = cast<DependentSizedArrayType>(ty);
John McCall06549462011-01-18 08:40:38 +00003319 result = getDependentSizedArrayType(
3320 getVariableArrayDecayedType(dat->getElementType()),
3321 dat->getSizeExpr(),
3322 dat->getSizeModifier(),
3323 dat->getIndexTypeCVRQualifiers(),
3324 dat->getBracketsRange());
3325 break;
3326 }
3327
3328 // Turn incomplete types into [*] types.
3329 case Type::IncompleteArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003330 const auto *iat = cast<IncompleteArrayType>(ty);
John McCall06549462011-01-18 08:40:38 +00003331 result = getVariableArrayType(
3332 getVariableArrayDecayedType(iat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00003333 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00003334 ArrayType::Normal,
3335 iat->getIndexTypeCVRQualifiers(),
3336 SourceRange());
3337 break;
3338 }
3339
3340 // Turn VLA types into [*] types.
3341 case Type::VariableArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003342 const auto *vat = cast<VariableArrayType>(ty);
John McCall06549462011-01-18 08:40:38 +00003343 result = getVariableArrayType(
3344 getVariableArrayDecayedType(vat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00003345 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00003346 ArrayType::Star,
3347 vat->getIndexTypeCVRQualifiers(),
3348 vat->getBracketsRange());
3349 break;
3350 }
3351 }
3352
3353 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00003354 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00003355}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003356
Steve Naroffcadebd02007-08-30 18:14:25 +00003357/// getVariableArrayType - Returns a non-unique reference to the type for a
3358/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00003359QualType ASTContext::getVariableArrayType(QualType EltTy,
3360 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00003361 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00003362 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00003363 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00003364 // Since we don't unique expressions, it isn't possible to unique VLA's
3365 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00003366 QualType Canon;
Fangrui Song6907ce22018-07-30 19:24:48 +00003367
John McCall33ddac02011-01-19 10:06:00 +00003368 // Be sure to pull qualifiers off the element type.
3369 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
3370 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00003371 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00003372 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00003373 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00003374 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003375
Eugene Zelenko7855e772018-04-03 00:11:50 +00003376 auto *New = new (*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00003377 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00003378
3379 VariableArrayTypes.push_back(New);
3380 Types.push_back(New);
3381 return QualType(New, 0);
3382}
3383
Douglas Gregor4619e432008-12-05 23:32:09 +00003384/// getDependentSizedArrayType - Returns a non-unique reference to
3385/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00003386/// type.
John McCall33ddac02011-01-19 10:06:00 +00003387QualType ASTContext::getDependentSizedArrayType(QualType elementType,
3388 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00003389 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00003390 unsigned elementTypeQuals,
3391 SourceRange brackets) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00003392 assert((!numElements || numElements->isTypeDependent() ||
John McCall33ddac02011-01-19 10:06:00 +00003393 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00003394 "Size must be type- or value-dependent!");
3395
John McCall33ddac02011-01-19 10:06:00 +00003396 // Dependently-sized array types that do not have a specified number
3397 // of elements will have their sizes deduced from a dependent
3398 // initializer. We do no canonicalization here at all, which is okay
3399 // because they can't be used in most locations.
3400 if (!numElements) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003401 auto *newType
John McCall33ddac02011-01-19 10:06:00 +00003402 = new (*this, TypeAlignment)
3403 DependentSizedArrayType(*this, elementType, QualType(),
3404 numElements, ASM, elementTypeQuals,
3405 brackets);
3406 Types.push_back(newType);
3407 return QualType(newType, 0);
3408 }
3409
3410 // Otherwise, we actually build a new type every time, but we
3411 // also build a canonical type.
3412
3413 SplitQualType canonElementType = getCanonicalType(elementType).split();
3414
Craig Topper36250ad2014-05-12 05:36:57 +00003415 void *insertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00003416 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00003417 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00003418 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00003419 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00003420
John McCall33ddac02011-01-19 10:06:00 +00003421 // Look for an existing type with these properties.
3422 DependentSizedArrayType *canonTy =
3423 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00003424
John McCall33ddac02011-01-19 10:06:00 +00003425 // If we don't have one, build one.
3426 if (!canonTy) {
3427 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00003428 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00003429 QualType(), numElements, ASM, elementTypeQuals,
3430 brackets);
3431 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
3432 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00003433 }
3434
John McCall33ddac02011-01-19 10:06:00 +00003435 // Apply qualifiers from the element type to the array.
3436 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00003437 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00003438
David Majnemer16a74702015-07-24 05:54:19 +00003439 // If we didn't need extra canonicalization for the element type or the size
3440 // expression, then just use that as our result.
3441 if (QualType(canonElementType.Ty, 0) == elementType &&
3442 canonTy->getSizeExpr() == numElements)
John McCall33ddac02011-01-19 10:06:00 +00003443 return canon;
3444
3445 // Otherwise, we need to build a type which follows the spelling
3446 // of the element type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00003447 auto *sugaredType
John McCall33ddac02011-01-19 10:06:00 +00003448 = new (*this, TypeAlignment)
3449 DependentSizedArrayType(*this, elementType, canon, numElements,
3450 ASM, elementTypeQuals, brackets);
3451 Types.push_back(sugaredType);
3452 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00003453}
3454
John McCall33ddac02011-01-19 10:06:00 +00003455QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00003456 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00003457 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00003458 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00003459 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00003460
Craig Topper36250ad2014-05-12 05:36:57 +00003461 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00003462 if (IncompleteArrayType *iat =
3463 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
3464 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00003465
3466 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00003467 // either, so fill in the canonical type field. We also have to pull
3468 // qualifiers off the element type.
3469 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00003470
John McCall33ddac02011-01-19 10:06:00 +00003471 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
3472 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00003473 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00003474 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00003475 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00003476
3477 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00003478 IncompleteArrayType *existing =
3479 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
3480 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00003481 }
Eli Friedmanbd258282008-02-15 18:16:39 +00003482
Eugene Zelenko7855e772018-04-03 00:11:50 +00003483 auto *newType = new (*this, TypeAlignment)
John McCall33ddac02011-01-19 10:06:00 +00003484 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00003485
John McCall33ddac02011-01-19 10:06:00 +00003486 IncompleteArrayTypes.InsertNode(newType, insertPos);
3487 Types.push_back(newType);
3488 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00003489}
3490
Steve Naroff91fcddb2007-07-18 18:00:27 +00003491/// getVectorType - Return the unique reference to a vector type of
3492/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00003493QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00003494 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00003495 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00003496
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003497 // Check if we've already instantiated a vector of this type.
3498 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00003499 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00003500
Craig Topper36250ad2014-05-12 05:36:57 +00003501 void *InsertPos = nullptr;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003502 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3503 return QualType(VTP, 0);
3504
3505 // If the element type isn't canonical, this won't be a canonical type either,
3506 // so fill in the canonical type field.
3507 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00003508 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00003509 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00003510
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003511 // Get the new insert position for the node we care about.
3512 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003513 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003514 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00003515 auto *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00003516 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003517 VectorTypes.InsertNode(New, InsertPos);
3518 Types.push_back(New);
3519 return QualType(New, 0);
3520}
3521
Erich Keanef702b022018-07-13 19:46:04 +00003522QualType
3523ASTContext::getDependentVectorType(QualType VecType, Expr *SizeExpr,
3524 SourceLocation AttrLoc,
3525 VectorType::VectorKind VecKind) const {
3526 llvm::FoldingSetNodeID ID;
3527 DependentVectorType::Profile(ID, *this, getCanonicalType(VecType), SizeExpr,
3528 VecKind);
3529 void *InsertPos = nullptr;
3530 DependentVectorType *Canon =
3531 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3532 DependentVectorType *New;
3533
3534 if (Canon) {
3535 New = new (*this, TypeAlignment) DependentVectorType(
3536 *this, VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind);
3537 } else {
3538 QualType CanonVecTy = getCanonicalType(VecType);
3539 if (CanonVecTy == VecType) {
3540 New = new (*this, TypeAlignment) DependentVectorType(
3541 *this, VecType, QualType(), SizeExpr, AttrLoc, VecKind);
3542
3543 DependentVectorType *CanonCheck =
3544 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3545 assert(!CanonCheck &&
3546 "Dependent-sized vector_size canonical type broken");
3547 (void)CanonCheck;
3548 DependentVectorTypes.InsertNode(New, InsertPos);
3549 } else {
3550 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
3551 SourceLocation());
3552 New = new (*this, TypeAlignment) DependentVectorType(
3553 *this, VecType, Canon, SizeExpr, AttrLoc, VecKind);
3554 }
3555 }
3556
3557 Types.push_back(New);
3558 return QualType(New, 0);
3559}
3560
Nate Begemance4d7fc2008-04-18 23:10:10 +00003561/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00003562/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00003563QualType
3564ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00003565 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00003566
Steve Naroff91fcddb2007-07-18 18:00:27 +00003567 // Check if we've already instantiated a vector of this type.
3568 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00003569 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00003570 VectorType::GenericVector);
Craig Topper36250ad2014-05-12 05:36:57 +00003571 void *InsertPos = nullptr;
Steve Naroff91fcddb2007-07-18 18:00:27 +00003572 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3573 return QualType(VTP, 0);
3574
3575 // If the element type isn't canonical, this won't be a canonical type either,
3576 // so fill in the canonical type field.
3577 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00003578 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00003579 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00003580
Steve Naroff91fcddb2007-07-18 18:00:27 +00003581 // Get the new insert position for the node we care about.
3582 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003583 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00003584 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00003585 auto *New = new (*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00003586 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00003587 VectorTypes.InsertNode(New, InsertPos);
3588 Types.push_back(New);
3589 return QualType(New, 0);
3590}
3591
Jay Foad39c79802011-01-12 09:06:06 +00003592QualType
3593ASTContext::getDependentSizedExtVectorType(QualType vecType,
3594 Expr *SizeExpr,
3595 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00003596 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00003597 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00003598 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003599
Craig Topper36250ad2014-05-12 05:36:57 +00003600 void *InsertPos = nullptr;
Douglas Gregor352169a2009-07-31 03:54:25 +00003601 DependentSizedExtVectorType *Canon
3602 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3603 DependentSizedExtVectorType *New;
3604 if (Canon) {
3605 // We already have a canonical version of this array type; use it as
3606 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00003607 New = new (*this, TypeAlignment)
3608 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
3609 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00003610 } else {
3611 QualType CanonVecTy = getCanonicalType(vecType);
3612 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00003613 New = new (*this, TypeAlignment)
3614 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
3615 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003616
3617 DependentSizedExtVectorType *CanonCheck
3618 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3619 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
3620 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00003621 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
3622 } else {
3623 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
3624 SourceLocation());
Fangrui Song6907ce22018-07-30 19:24:48 +00003625 New = new (*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00003626 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00003627 }
3628 }
Mike Stump11289f42009-09-09 15:08:12 +00003629
Douglas Gregor758a8692009-06-17 21:51:59 +00003630 Types.push_back(New);
3631 return QualType(New, 0);
3632}
3633
Fangrui Song6907ce22018-07-30 19:24:48 +00003634QualType ASTContext::getDependentAddressSpaceType(QualType PointeeType,
3635 Expr *AddrSpaceExpr,
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003636 SourceLocation AttrLoc) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00003637 assert(AddrSpaceExpr->isInstantiationDependent());
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003638
3639 QualType canonPointeeType = getCanonicalType(PointeeType);
3640
3641 void *insertPos = nullptr;
3642 llvm::FoldingSetNodeID ID;
3643 DependentAddressSpaceType::Profile(ID, *this, canonPointeeType,
3644 AddrSpaceExpr);
3645
3646 DependentAddressSpaceType *canonTy =
3647 DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos);
3648
3649 if (!canonTy) {
3650 canonTy = new (*this, TypeAlignment)
Fangrui Song6907ce22018-07-30 19:24:48 +00003651 DependentAddressSpaceType(*this, canonPointeeType,
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003652 QualType(), AddrSpaceExpr, AttrLoc);
3653 DependentAddressSpaceTypes.InsertNode(canonTy, insertPos);
3654 Types.push_back(canonTy);
3655 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003656
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003657 if (canonPointeeType == PointeeType &&
3658 canonTy->getAddrSpaceExpr() == AddrSpaceExpr)
Fangrui Song6907ce22018-07-30 19:24:48 +00003659 return QualType(canonTy, 0);
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003660
Eugene Zelenko7855e772018-04-03 00:11:50 +00003661 auto *sugaredType
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003662 = new (*this, TypeAlignment)
Fangrui Song6907ce22018-07-30 19:24:48 +00003663 DependentAddressSpaceType(*this, PointeeType, QualType(canonTy, 0),
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003664 AddrSpaceExpr, AttrLoc);
3665 Types.push_back(sugaredType);
Fangrui Song6907ce22018-07-30 19:24:48 +00003666 return QualType(sugaredType, 0);
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003667}
3668
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003669/// Determine whether \p T is canonical as the result type of a function.
John McCall18afab72016-03-01 00:49:02 +00003670static bool isCanonicalResultType(QualType T) {
3671 return T.isCanonical() &&
3672 (T.getObjCLifetime() == Qualifiers::OCL_None ||
3673 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
3674}
3675
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003676/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Jay Foad39c79802011-01-12 09:06:06 +00003677QualType
3678ASTContext::getFunctionNoProtoType(QualType ResultTy,
3679 const FunctionType::ExtInfo &Info) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003680 // Unique functions, to guarantee there is only one function of a particular
3681 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00003682 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00003683 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00003684
Craig Topper36250ad2014-05-12 05:36:57 +00003685 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003686 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003687 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003688 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003689
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003690 QualType Canonical;
John McCall18afab72016-03-01 00:49:02 +00003691 if (!isCanonicalResultType(ResultTy)) {
3692 Canonical =
3693 getFunctionNoProtoType(getCanonicalFunctionResultType(ResultTy), Info);
Mike Stump11289f42009-09-09 15:08:12 +00003694
Chris Lattner47955de2007-01-27 08:37:20 +00003695 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003696 FunctionNoProtoType *NewIP =
3697 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003698 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00003699 }
Mike Stump11289f42009-09-09 15:08:12 +00003700
Eugene Zelenko7855e772018-04-03 00:11:50 +00003701 auto *New = new (*this, TypeAlignment)
John McCall18afab72016-03-01 00:49:02 +00003702 FunctionNoProtoType(ResultTy, Canonical, Info);
Chris Lattner47955de2007-01-27 08:37:20 +00003703 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003704 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003705 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003706}
3707
Douglas Gregora602a152015-10-01 20:20:47 +00003708CanQualType
3709ASTContext::getCanonicalFunctionResultType(QualType ResultType) const {
3710 CanQualType CanResultType = getCanonicalType(ResultType);
3711
3712 // Canonical result types do not have ARC lifetime qualifiers.
3713 if (CanResultType.getQualifiers().hasObjCLifetime()) {
3714 Qualifiers Qs = CanResultType.getQualifiers();
3715 Qs.removeObjCLifetime();
3716 return CanQualType::CreateUnsafe(
3717 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
3718 }
3719
3720 return CanResultType;
3721}
3722
Richard Smith3c4f8d22016-10-16 17:54:23 +00003723static bool isCanonicalExceptionSpecification(
3724 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
3725 if (ESI.Type == EST_None)
3726 return true;
3727 if (!NoexceptInType)
3728 return false;
3729
3730 // C++17 onwards: exception specification is part of the type, as a simple
3731 // boolean "can this function type throw".
3732 if (ESI.Type == EST_BasicNoexcept)
3733 return true;
3734
Richard Smitheaf11ad2018-05-03 03:58:32 +00003735 // A noexcept(expr) specification is (possibly) canonical if expr is
3736 // value-dependent.
3737 if (ESI.Type == EST_DependentNoexcept)
3738 return true;
3739
Richard Smith3c4f8d22016-10-16 17:54:23 +00003740 // A dynamic exception specification is canonical if it only contains pack
Richard Smith2a2cda52016-10-18 19:29:18 +00003741 // expansions (so we can't tell whether it's non-throwing) and all its
3742 // contained types are canonical.
Richard Smith3c4f8d22016-10-16 17:54:23 +00003743 if (ESI.Type == EST_Dynamic) {
Richard Smithfda59e52016-10-26 01:05:54 +00003744 bool AnyPackExpansions = false;
3745 for (QualType ET : ESI.Exceptions) {
3746 if (!ET.isCanonical())
Richard Smith3c4f8d22016-10-16 17:54:23 +00003747 return false;
Richard Smithfda59e52016-10-26 01:05:54 +00003748 if (ET->getAs<PackExpansionType>())
3749 AnyPackExpansions = true;
3750 }
3751 return AnyPackExpansions;
Richard Smith3c4f8d22016-10-16 17:54:23 +00003752 }
3753
Richard Smith3c4f8d22016-10-16 17:54:23 +00003754 return false;
3755}
3756
Richard Smith304b1242016-10-18 20:13:25 +00003757QualType ASTContext::getFunctionTypeInternal(
3758 QualType ResultTy, ArrayRef<QualType> ArgArray,
3759 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
Jordan Rose5c382722013-03-08 21:51:21 +00003760 size_t NumArgs = ArgArray.size();
3761
Richard Smith2a2cda52016-10-18 19:29:18 +00003762 // Unique functions, to guarantee there is only one function of a particular
3763 // structure.
3764 llvm::FoldingSetNodeID ID;
3765 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
3766 *this, true);
Richard Smith3c4f8d22016-10-16 17:54:23 +00003767
Richard Smith2a2cda52016-10-18 19:29:18 +00003768 QualType Canonical;
3769 bool Unique = false;
3770
3771 void *InsertPos = nullptr;
3772 if (FunctionProtoType *FPT =
3773 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
3774 QualType Existing = QualType(FPT, 0);
3775
3776 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
3777 // it so long as our exception specification doesn't contain a dependent
Richard Smith304b1242016-10-18 20:13:25 +00003778 // noexcept expression, or we're just looking for a canonical type.
3779 // Otherwise, we're going to need to create a type
Richard Smith2a2cda52016-10-18 19:29:18 +00003780 // sugar node to hold the concrete expression.
Richard Smitheaf11ad2018-05-03 03:58:32 +00003781 if (OnlyWantCanonical || !isComputedNoexcept(EPI.ExceptionSpec.Type) ||
Richard Smith2a2cda52016-10-18 19:29:18 +00003782 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
3783 return Existing;
3784
3785 // We need a new type sugar node for this one, to hold the new noexcept
3786 // expression. We do no canonicalization here, but that's OK since we don't
3787 // expect to see the same noexcept expression much more than once.
3788 Canonical = getCanonicalType(Existing);
3789 Unique = true;
3790 }
3791
Aaron Ballmanc351fba2017-12-04 20:27:34 +00003792 bool NoexceptInType = getLangOpts().CPlusPlus17;
Richard Smith3c4f8d22016-10-16 17:54:23 +00003793 bool IsCanonicalExceptionSpec =
3794 isCanonicalExceptionSpecification(EPI.ExceptionSpec, NoexceptInType);
3795
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003796 // Determine whether the type being created is already canonical or not.
Richard Smith2a2cda52016-10-18 19:29:18 +00003797 bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
Richard Smith3c4f8d22016-10-16 17:54:23 +00003798 isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003799 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003800 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003801 isCanonical = false;
3802
Richard Smith304b1242016-10-18 20:13:25 +00003803 if (OnlyWantCanonical)
3804 assert(isCanonical &&
3805 "given non-canonical parameters constructing canonical type");
3806
Richard Smith2a2cda52016-10-18 19:29:18 +00003807 // If this type isn't canonical, get the canonical version of it if we don't
3808 // already have it. The exception spec is only partially part of the
3809 // canonical type, and only in C++17 onwards.
3810 if (!isCanonical && Canonical.isNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003811 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003812 CanonicalArgs.reserve(NumArgs);
3813 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003814 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003815
Benjamin Kramer3f515cd2016-10-26 12:51:45 +00003816 llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
John McCalldb40c7f2010-12-14 08:05:40 +00003817 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00003818 CanonicalEPI.HasTrailingReturn = false;
Richard Smith3c4f8d22016-10-16 17:54:23 +00003819
3820 if (IsCanonicalExceptionSpec) {
3821 // Exception spec is already OK.
3822 } else if (NoexceptInType) {
3823 switch (EPI.ExceptionSpec.Type) {
3824 case EST_Unparsed: case EST_Unevaluated: case EST_Uninstantiated:
3825 // We don't know yet. It shouldn't matter what we pick here; no-one
3826 // should ever look at this.
3827 LLVM_FALLTHROUGH;
Richard Smitheaf11ad2018-05-03 03:58:32 +00003828 case EST_None: case EST_MSAny: case EST_NoexceptFalse:
Richard Smith3c4f8d22016-10-16 17:54:23 +00003829 CanonicalEPI.ExceptionSpec.Type = EST_None;
3830 break;
3831
Richard Smith2a2cda52016-10-18 19:29:18 +00003832 // A dynamic exception specification is almost always "not noexcept",
3833 // with the exception that a pack expansion might expand to no types.
3834 case EST_Dynamic: {
3835 bool AnyPacks = false;
3836 for (QualType ET : EPI.ExceptionSpec.Exceptions) {
3837 if (ET->getAs<PackExpansionType>())
3838 AnyPacks = true;
3839 ExceptionTypeStorage.push_back(getCanonicalType(ET));
3840 }
3841 if (!AnyPacks)
3842 CanonicalEPI.ExceptionSpec.Type = EST_None;
3843 else {
3844 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
3845 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
3846 }
3847 break;
3848 }
3849
Erich Keaned02f4a12019-05-30 17:31:54 +00003850 case EST_DynamicNone:
3851 case EST_BasicNoexcept:
3852 case EST_NoexceptTrue:
3853 case EST_NoThrow:
Richard Smith3c4f8d22016-10-16 17:54:23 +00003854 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
3855 break;
3856
Richard Smitheaf11ad2018-05-03 03:58:32 +00003857 case EST_DependentNoexcept:
3858 llvm_unreachable("dependent noexcept is already canonical");
Richard Smith3c4f8d22016-10-16 17:54:23 +00003859 }
Richard Smith3c4f8d22016-10-16 17:54:23 +00003860 } else {
3861 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
3862 }
John McCalldb40c7f2010-12-14 08:05:40 +00003863
Douglas Gregora602a152015-10-01 20:20:47 +00003864 // Adjust the canonical function result type.
3865 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
Richard Smith304b1242016-10-18 20:13:25 +00003866 Canonical =
3867 getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003868
Chris Lattnerfd4de792007-01-27 01:15:32 +00003869 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003870 FunctionProtoType *NewIP =
3871 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003872 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003873 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003874
Bruno Ricci26a25362018-10-02 11:46:38 +00003875 // Compute the needed size to hold this FunctionProtoType and the
3876 // various trailing objects.
3877 auto ESH = FunctionProtoType::getExceptionSpecSize(
3878 EPI.ExceptionSpec.Type, EPI.ExceptionSpec.Exceptions.size());
3879 size_t Size = FunctionProtoType::totalSizeToAlloc<
Nicolas Manichoncc3c9352019-12-03 08:21:55 -05003880 QualType, SourceLocation, FunctionType::FunctionTypeExtraBitfields,
Bruno Ricci26a25362018-10-02 11:46:38 +00003881 FunctionType::ExceptionType, Expr *, FunctionDecl *,
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00003882 FunctionProtoType::ExtParameterInfo, Qualifiers>(
Nicolas Manichoncc3c9352019-12-03 08:21:55 -05003883 NumArgs, EPI.Variadic,
3884 FunctionProtoType::hasExtraBitfields(EPI.ExceptionSpec.Type),
Bruno Ricci26a25362018-10-02 11:46:38 +00003885 ESH.NumExceptionType, ESH.NumExprPtr, ESH.NumFunctionDeclPtr,
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00003886 EPI.ExtParameterInfos ? NumArgs : 0,
3887 EPI.TypeQuals.hasNonFastQualifiers() ? 1 : 0);
John McCall18afab72016-03-01 00:49:02 +00003888
Bruno Ricci26a25362018-10-02 11:46:38 +00003889 auto *FTP = (FunctionProtoType *)Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00003890 FunctionProtoType::ExtProtoInfo newEPI = EPI;
Jordan Rose5c382722013-03-08 21:51:21 +00003891 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003892 Types.push_back(FTP);
Richard Smith2a2cda52016-10-18 19:29:18 +00003893 if (!Unique)
3894 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003895 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003896}
Chris Lattneref51c202006-11-10 07:17:23 +00003897
Joey Goulye3c85de2016-12-01 11:30:49 +00003898QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
Xiuli Pan9c14e282016-01-09 12:53:17 +00003899 llvm::FoldingSetNodeID ID;
Joey Goulye3c85de2016-12-01 11:30:49 +00003900 PipeType::Profile(ID, T, ReadOnly);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003901
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00003902 void *InsertPos = nullptr;
Joey Goulye3c85de2016-12-01 11:30:49 +00003903 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
Xiuli Pan9c14e282016-01-09 12:53:17 +00003904 return QualType(PT, 0);
3905
3906 // If the pipe element type isn't canonical, this won't be a canonical type
3907 // either, so fill in the canonical type field.
3908 QualType Canonical;
3909 if (!T.isCanonical()) {
Joey Goulye3c85de2016-12-01 11:30:49 +00003910 Canonical = getPipeType(getCanonicalType(T), ReadOnly);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003911
3912 // Get the new insert position for the node we care about.
Joey Goulye3c85de2016-12-01 11:30:49 +00003913 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003914 assert(!NewIP && "Shouldn't be in the map!");
3915 (void)NewIP;
3916 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00003917 auto *New = new (*this, TypeAlignment) PipeType(T, Canonical, ReadOnly);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003918 Types.push_back(New);
Joey Goulye3c85de2016-12-01 11:30:49 +00003919 PipeTypes.InsertNode(New, InsertPos);
Joey Gouly5788b782016-11-18 14:10:54 +00003920 return QualType(New, 0);
3921}
3922
Anastasia Stulova59055b92018-05-09 13:23:26 +00003923QualType ASTContext::adjustStringLiteralBaseType(QualType Ty) const {
3924 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
3925 return LangOpts.OpenCL ? getAddrSpaceQualType(Ty, LangAS::opencl_constant)
3926 : Ty;
3927}
3928
Joey Goulye3c85de2016-12-01 11:30:49 +00003929QualType ASTContext::getReadPipeType(QualType T) const {
3930 return getPipeType(T, true);
3931}
3932
Joey Gouly5788b782016-11-18 14:10:54 +00003933QualType ASTContext::getWritePipeType(QualType T) const {
Joey Goulye3c85de2016-12-01 11:30:49 +00003934 return getPipeType(T, false);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003935}
3936
John McCalle78aac42010-03-10 03:28:59 +00003937#ifndef NDEBUG
3938static bool NeedsInjectedClassNameType(const RecordDecl *D) {
3939 if (!isa<CXXRecordDecl>(D)) return false;
Eugene Zelenko7855e772018-04-03 00:11:50 +00003940 const auto *RD = cast<CXXRecordDecl>(D);
John McCalle78aac42010-03-10 03:28:59 +00003941 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
3942 return true;
3943 if (RD->getDescribedClassTemplate() &&
3944 !isa<ClassTemplateSpecializationDecl>(RD))
3945 return true;
3946 return false;
3947}
3948#endif
3949
3950/// getInjectedClassNameType - Return the unique reference to the
3951/// injected class name type for the specified templated declaration.
3952QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00003953 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00003954 assert(NeedsInjectedClassNameType(Decl));
3955 if (Decl->TypeForDecl) {
3956 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00003957 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00003958 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
3959 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3960 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
3961 } else {
John McCall424cec92011-01-19 06:33:43 +00003962 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00003963 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00003964 Decl->TypeForDecl = newType;
3965 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00003966 }
3967 return QualType(Decl->TypeForDecl, 0);
3968}
3969
Douglas Gregor83a586e2008-04-13 21:07:44 +00003970/// getTypeDeclType - Return the unique reference to the type for the
3971/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00003972QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00003973 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00003974 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00003975
Eugene Zelenko7855e772018-04-03 00:11:50 +00003976 if (const auto *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00003977 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00003978
John McCall96f0b5f2010-03-10 06:48:02 +00003979 assert(!isa<TemplateTypeParmDecl>(Decl) &&
3980 "Template type parameter types are always available.");
3981
Eugene Zelenko7855e772018-04-03 00:11:50 +00003982 if (const auto *Record = dyn_cast<RecordDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003983 assert(Record->isFirstDecl() && "struct/union has previous declaration");
John McCall96f0b5f2010-03-10 06:48:02 +00003984 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003985 return getRecordType(Record);
Eugene Zelenko7855e772018-04-03 00:11:50 +00003986 } else if (const auto *Enum = dyn_cast<EnumDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003987 assert(Enum->isFirstDecl() && "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003988 return getEnumType(Enum);
Eugene Zelenko7855e772018-04-03 00:11:50 +00003989 } else if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00003990 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
3991 Decl->TypeForDecl = newType;
3992 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00003993 } else
John McCall96f0b5f2010-03-10 06:48:02 +00003994 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003995
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003996 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00003997}
3998
Chris Lattner32d920b2007-01-26 02:01:53 +00003999/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00004000/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004001QualType
Richard Smithdda56e42011-04-15 14:24:37 +00004002ASTContext::getTypedefType(const TypedefNameDecl *Decl,
4003 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00004004 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004005
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004006 if (Canonical.isNull())
4007 Canonical = getCanonicalType(Decl->getUnderlyingType());
Eugene Zelenko7855e772018-04-03 00:11:50 +00004008 auto *newType = new (*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00004009 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00004010 Decl->TypeForDecl = newType;
4011 Types.push_back(newType);
4012 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00004013}
4014
Jay Foad39c79802011-01-12 09:06:06 +00004015QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00004016 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
4017
Douglas Gregorec9fd132012-01-14 16:38:05 +00004018 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00004019 if (PrevDecl->TypeForDecl)
Fangrui Song6907ce22018-07-30 19:24:48 +00004020 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00004021
Eugene Zelenko7855e772018-04-03 00:11:50 +00004022 auto *newType = new (*this, TypeAlignment) RecordType(Decl);
John McCall424cec92011-01-19 06:33:43 +00004023 Decl->TypeForDecl = newType;
4024 Types.push_back(newType);
4025 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00004026}
4027
Jay Foad39c79802011-01-12 09:06:06 +00004028QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00004029 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
4030
Douglas Gregorec9fd132012-01-14 16:38:05 +00004031 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00004032 if (PrevDecl->TypeForDecl)
Fangrui Song6907ce22018-07-30 19:24:48 +00004033 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00004034
Eugene Zelenko7855e772018-04-03 00:11:50 +00004035 auto *newType = new (*this, TypeAlignment) EnumType(Decl);
John McCall424cec92011-01-19 06:33:43 +00004036 Decl->TypeForDecl = newType;
4037 Types.push_back(newType);
4038 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00004039}
4040
Richard Smithe43e2b32018-08-20 21:47:29 +00004041QualType ASTContext::getAttributedType(attr::Kind attrKind,
John McCall81904512011-01-06 01:58:22 +00004042 QualType modifiedType,
4043 QualType equivalentType) {
4044 llvm::FoldingSetNodeID id;
4045 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
4046
Craig Topper36250ad2014-05-12 05:36:57 +00004047 void *insertPos = nullptr;
John McCall81904512011-01-06 01:58:22 +00004048 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
4049 if (type) return QualType(type, 0);
4050
4051 QualType canon = getCanonicalType(equivalentType);
4052 type = new (*this, TypeAlignment)
Leonard Chanc72aaf62019-05-07 03:20:17 +00004053 AttributedType(canon, attrKind, modifiedType, equivalentType);
John McCall81904512011-01-06 01:58:22 +00004054
4055 Types.push_back(type);
4056 AttributedTypes.InsertNode(type, insertPos);
4057
4058 return QualType(type, 0);
4059}
4060
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004061/// Retrieve a substitution-result type.
John McCallcebee162009-10-18 09:09:24 +00004062QualType
4063ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00004064 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00004065 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00004066 && "replacement types must always be canonical");
4067
4068 llvm::FoldingSetNodeID ID;
4069 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00004070 void *InsertPos = nullptr;
John McCallcebee162009-10-18 09:09:24 +00004071 SubstTemplateTypeParmType *SubstParm
4072 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4073
4074 if (!SubstParm) {
4075 SubstParm = new (*this, TypeAlignment)
4076 SubstTemplateTypeParmType(Parm, Replacement);
4077 Types.push_back(SubstParm);
4078 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
4079 }
4080
4081 return QualType(SubstParm, 0);
4082}
4083
Fangrui Song6907ce22018-07-30 19:24:48 +00004084/// Retrieve a
Douglas Gregorada4b792011-01-14 02:55:32 +00004085QualType ASTContext::getSubstTemplateTypeParmPackType(
4086 const TemplateTypeParmType *Parm,
4087 const TemplateArgument &ArgPack) {
4088#ifndef NDEBUG
Aaron Ballman2a89e852014-07-15 21:32:31 +00004089 for (const auto &P : ArgPack.pack_elements()) {
4090 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
4091 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
Douglas Gregorada4b792011-01-14 02:55:32 +00004092 }
4093#endif
Fangrui Song6907ce22018-07-30 19:24:48 +00004094
Douglas Gregorada4b792011-01-14 02:55:32 +00004095 llvm::FoldingSetNodeID ID;
4096 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00004097 void *InsertPos = nullptr;
Douglas Gregorada4b792011-01-14 02:55:32 +00004098 if (SubstTemplateTypeParmPackType *SubstParm
4099 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
4100 return QualType(SubstParm, 0);
Fangrui Song6907ce22018-07-30 19:24:48 +00004101
Douglas Gregorada4b792011-01-14 02:55:32 +00004102 QualType Canon;
4103 if (!Parm->isCanonicalUnqualified()) {
4104 Canon = getCanonicalType(QualType(Parm, 0));
4105 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
4106 ArgPack);
4107 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
4108 }
4109
Eugene Zelenko7855e772018-04-03 00:11:50 +00004110 auto *SubstParm
Douglas Gregorada4b792011-01-14 02:55:32 +00004111 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
4112 ArgPack);
4113 Types.push_back(SubstParm);
George Burgess IVb5fe8552017-06-12 17:44:30 +00004114 SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos);
Fangrui Song6907ce22018-07-30 19:24:48 +00004115 return QualType(SubstParm, 0);
Douglas Gregorada4b792011-01-14 02:55:32 +00004116}
4117
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004118/// Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00004119/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00004120/// name.
Mike Stump11289f42009-09-09 15:08:12 +00004121QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00004122 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00004123 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00004124 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00004125 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Craig Topper36250ad2014-05-12 05:36:57 +00004126 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004127 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00004128 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4129
4130 if (TypeParm)
4131 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004132
Chandler Carruth08836322011-05-01 00:51:33 +00004133 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00004134 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00004135 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004136
Fangrui Song6907ce22018-07-30 19:24:48 +00004137 TemplateTypeParmType *TypeCheck
Douglas Gregorc42075a2010-02-04 18:10:26 +00004138 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4139 assert(!TypeCheck && "Template type parameter canonical type broken");
4140 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00004141 } else
John McCall90d1c2d2009-09-24 23:30:46 +00004142 TypeParm = new (*this, TypeAlignment)
4143 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00004144
4145 Types.push_back(TypeParm);
4146 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
4147
4148 return QualType(TypeParm, 0);
4149}
4150
John McCalle78aac42010-03-10 03:28:59 +00004151TypeSourceInfo *
4152ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
4153 SourceLocation NameLoc,
4154 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00004155 QualType Underlying) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00004156 assert(!Name.getAsDependentTemplateName() &&
Douglas Gregore16af532011-02-28 18:50:33 +00004157 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00004158 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00004159
4160 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie6adc78e2013-02-18 22:06:02 +00004161 TemplateSpecializationTypeLoc TL =
4162 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara48c05be2012-02-06 14:41:24 +00004163 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00004164 TL.setTemplateNameLoc(NameLoc);
4165 TL.setLAngleLoc(Args.getLAngleLoc());
4166 TL.setRAngleLoc(Args.getRAngleLoc());
4167 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
4168 TL.setArgLocInfo(i, Args[i].getLocInfo());
4169 return DI;
4170}
4171
Mike Stump11289f42009-09-09 15:08:12 +00004172QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00004173ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00004174 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00004175 QualType Underlying) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00004176 assert(!Template.getAsDependentTemplateName() &&
Douglas Gregore16af532011-02-28 18:50:33 +00004177 "No dependent template names here!");
John McCall6b51f282009-11-23 01:53:49 +00004178
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004179 SmallVector<TemplateArgument, 4> ArgVec;
David Majnemer6fbeee32016-07-07 04:43:07 +00004180 ArgVec.reserve(Args.size());
4181 for (const TemplateArgumentLoc &Arg : Args.arguments())
4182 ArgVec.push_back(Arg.getArgument());
John McCall0ad16662009-10-29 08:12:44 +00004183
David Majnemer6fbeee32016-07-07 04:43:07 +00004184 return getTemplateSpecializationType(Template, ArgVec, Underlying);
John McCall0ad16662009-10-29 08:12:44 +00004185}
4186
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004187#ifndef NDEBUG
David Majnemer6fbeee32016-07-07 04:43:07 +00004188static bool hasAnyPackExpansions(ArrayRef<TemplateArgument> Args) {
4189 for (const TemplateArgument &Arg : Args)
4190 if (Arg.isPackExpansion())
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004191 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00004192
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004193 return true;
4194}
4195#endif
4196
John McCall0ad16662009-10-29 08:12:44 +00004197QualType
4198ASTContext::getTemplateSpecializationType(TemplateName Template,
David Majnemer6fbeee32016-07-07 04:43:07 +00004199 ArrayRef<TemplateArgument> Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00004200 QualType Underlying) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00004201 assert(!Template.getAsDependentTemplateName() &&
Douglas Gregore16af532011-02-28 18:50:33 +00004202 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00004203 // Look through qualified template names.
4204 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
4205 Template = TemplateName(QTN->getTemplateDecl());
Fangrui Song6907ce22018-07-30 19:24:48 +00004206
4207 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00004208 Template.getAsTemplateDecl() &&
4209 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00004210 QualType CanonType;
4211 if (!Underlying.isNull())
4212 CanonType = getCanonicalType(Underlying);
4213 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004214 // We can get here with an alias template when the specialization contains
4215 // a pack expansion that does not match up with a parameter pack.
David Majnemer6fbeee32016-07-07 04:43:07 +00004216 assert((!IsTypeAlias || hasAnyPackExpansions(Args)) &&
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004217 "Caller must compute aliased type");
4218 IsTypeAlias = false;
David Majnemer6fbeee32016-07-07 04:43:07 +00004219 CanonType = getCanonicalTemplateSpecializationType(Template, Args);
Richard Smith3f1b5d02011-05-05 21:57:07 +00004220 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00004221
Douglas Gregora8e02e72009-07-28 23:00:59 +00004222 // Allocate the (non-canonical) template specialization type, but don't
4223 // try to unique it: these types typically have location information that
4224 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00004225 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
David Majnemer6fbeee32016-07-07 04:43:07 +00004226 sizeof(TemplateArgument) * Args.size() +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004227 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00004228 TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004229 auto *Spec
David Majnemer6fbeee32016-07-07 04:43:07 +00004230 = new (Mem) TemplateSpecializationType(Template, Args, CanonType,
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004231 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00004232
Douglas Gregor8bf42052009-02-09 18:46:07 +00004233 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00004234 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00004235}
4236
David Majnemer6fbeee32016-07-07 04:43:07 +00004237QualType ASTContext::getCanonicalTemplateSpecializationType(
4238 TemplateName Template, ArrayRef<TemplateArgument> Args) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00004239 assert(!Template.getAsDependentTemplateName() &&
Douglas Gregore16af532011-02-28 18:50:33 +00004240 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00004241
Douglas Gregore29139c2011-03-03 17:04:51 +00004242 // Look through qualified template names.
4243 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
4244 Template = TemplateName(QTN->getTemplateDecl());
Fangrui Song6907ce22018-07-30 19:24:48 +00004245
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004246 // Build the canonical template specialization type.
4247 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004248 SmallVector<TemplateArgument, 4> CanonArgs;
David Majnemer6fbeee32016-07-07 04:43:07 +00004249 unsigned NumArgs = Args.size();
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004250 CanonArgs.reserve(NumArgs);
David Majnemer6fbeee32016-07-07 04:43:07 +00004251 for (const TemplateArgument &Arg : Args)
4252 CanonArgs.push_back(getCanonicalTemplateArgument(Arg));
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004253
4254 // Determine whether this canonical template specialization type already
4255 // exists.
4256 llvm::FoldingSetNodeID ID;
4257 TemplateSpecializationType::Profile(ID, CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00004258 CanonArgs, *this);
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004259
Craig Topper36250ad2014-05-12 05:36:57 +00004260 void *InsertPos = nullptr;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004261 TemplateSpecializationType *Spec
4262 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
4263
4264 if (!Spec) {
4265 // Allocate a new canonical template specialization type.
4266 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
4267 sizeof(TemplateArgument) * NumArgs),
4268 TypeAlignment);
4269 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00004270 CanonArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00004271 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004272 Types.push_back(Spec);
4273 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
4274 }
4275
4276 assert(Spec->isDependentType() &&
4277 "Non-dependent template-id type must have a canonical type");
4278 return QualType(Spec, 0);
4279}
4280
Joel E. Denny7509a2f2018-05-14 19:36:45 +00004281QualType ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
4282 NestedNameSpecifier *NNS,
4283 QualType NamedType,
4284 TagDecl *OwnedTagDecl) const {
Douglas Gregor52537682009-03-19 00:18:19 +00004285 llvm::FoldingSetNodeID ID;
Joel E. Denny7509a2f2018-05-14 19:36:45 +00004286 ElaboratedType::Profile(ID, Keyword, NNS, NamedType, OwnedTagDecl);
Douglas Gregor52537682009-03-19 00:18:19 +00004287
Craig Topper36250ad2014-05-12 05:36:57 +00004288 void *InsertPos = nullptr;
Abramo Bagnara6150c882010-05-11 21:36:43 +00004289 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00004290 if (T)
4291 return QualType(T, 0);
4292
Douglas Gregorc42075a2010-02-04 18:10:26 +00004293 QualType Canon = NamedType;
4294 if (!Canon.isCanonical()) {
4295 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00004296 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
4297 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00004298 (void)CheckT;
4299 }
4300
Bruno Riccid6bd5982018-08-16 10:48:16 +00004301 void *Mem = Allocate(ElaboratedType::totalSizeToAlloc<TagDecl *>(!!OwnedTagDecl),
4302 TypeAlignment);
4303 T = new (Mem) ElaboratedType(Keyword, NNS, NamedType, Canon, OwnedTagDecl);
4304
Douglas Gregor52537682009-03-19 00:18:19 +00004305 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00004306 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00004307 return QualType(T, 0);
4308}
4309
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004310QualType
Jay Foad39c79802011-01-12 09:06:06 +00004311ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004312 llvm::FoldingSetNodeID ID;
4313 ParenType::Profile(ID, InnerType);
4314
Craig Topper36250ad2014-05-12 05:36:57 +00004315 void *InsertPos = nullptr;
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004316 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
4317 if (T)
4318 return QualType(T, 0);
4319
4320 QualType Canon = InnerType;
4321 if (!Canon.isCanonical()) {
4322 Canon = getCanonicalType(InnerType);
4323 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
4324 assert(!CheckT && "Paren canonical type broken");
4325 (void)CheckT;
4326 }
4327
Benjamin Kramer8adeef92015-04-02 16:19:54 +00004328 T = new (*this, TypeAlignment) ParenType(InnerType, Canon);
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004329 Types.push_back(T);
4330 ParenTypes.InsertNode(T, InsertPos);
4331 return QualType(T, 0);
4332}
4333
Leonard Chanc72aaf62019-05-07 03:20:17 +00004334QualType
4335ASTContext::getMacroQualifiedType(QualType UnderlyingTy,
4336 const IdentifierInfo *MacroII) const {
4337 QualType Canon = UnderlyingTy;
4338 if (!Canon.isCanonical())
4339 Canon = getCanonicalType(UnderlyingTy);
4340
4341 auto *newType = new (*this, TypeAlignment)
4342 MacroQualifiedType(UnderlyingTy, Canon, MacroII);
4343 Types.push_back(newType);
4344 return QualType(newType, 0);
4345}
4346
Douglas Gregor02085352010-03-31 20:19:30 +00004347QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
4348 NestedNameSpecifier *NNS,
4349 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00004350 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00004351 if (Canon.isNull()) {
4352 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Richard Smith74f02342017-01-19 21:00:13 +00004353 if (CanonNNS != NNS)
4354 Canon = getDependentNameType(Keyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00004355 }
4356
4357 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00004358 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00004359
Craig Topper36250ad2014-05-12 05:36:57 +00004360 void *InsertPos = nullptr;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00004361 DependentNameType *T
4362 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00004363 if (T)
4364 return QualType(T, 0);
4365
Benjamin Kramer8adeef92015-04-02 16:19:54 +00004366 T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00004367 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00004368 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00004369 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00004370}
4371
Mike Stump11289f42009-09-09 15:08:12 +00004372QualType
John McCallc392f372010-06-11 00:33:02 +00004373ASTContext::getDependentTemplateSpecializationType(
4374 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00004375 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00004376 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00004377 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00004378 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004379 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00004380 for (unsigned I = 0, E = Args.size(); I != E; ++I)
4381 ArgCopy.push_back(Args[I].getArgument());
David Majnemer6fbeee32016-07-07 04:43:07 +00004382 return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy);
John McCallc392f372010-06-11 00:33:02 +00004383}
4384
4385QualType
4386ASTContext::getDependentTemplateSpecializationType(
4387 ElaboratedTypeKeyword Keyword,
4388 NestedNameSpecifier *NNS,
4389 const IdentifierInfo *Name,
David Majnemer6fbeee32016-07-07 04:43:07 +00004390 ArrayRef<TemplateArgument> Args) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00004391 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor6e068012011-02-28 00:04:36 +00004392 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00004393
Douglas Gregorc42075a2010-02-04 18:10:26 +00004394 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00004395 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00004396 Name, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004397
Craig Topper36250ad2014-05-12 05:36:57 +00004398 void *InsertPos = nullptr;
John McCallc392f372010-06-11 00:33:02 +00004399 DependentTemplateSpecializationType *T
4400 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004401 if (T)
4402 return QualType(T, 0);
4403
John McCallc392f372010-06-11 00:33:02 +00004404 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004405
John McCallc392f372010-06-11 00:33:02 +00004406 ElaboratedTypeKeyword CanonKeyword = Keyword;
4407 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
4408
4409 bool AnyNonCanonArgs = false;
David Majnemer6fbeee32016-07-07 04:43:07 +00004410 unsigned NumArgs = Args.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004411 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00004412 for (unsigned I = 0; I != NumArgs; ++I) {
4413 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
4414 if (!CanonArgs[I].structurallyEquals(Args[I]))
4415 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00004416 }
4417
John McCallc392f372010-06-11 00:33:02 +00004418 QualType Canon;
4419 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
4420 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00004421 Name,
4422 CanonArgs);
John McCallc392f372010-06-11 00:33:02 +00004423
4424 // Find the insert position again.
4425 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
4426 }
4427
4428 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
4429 sizeof(TemplateArgument) * NumArgs),
4430 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00004431 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00004432 Name, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00004433 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00004434 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00004435 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00004436}
4437
Richard Smith32918772017-02-14 00:25:28 +00004438TemplateArgument ASTContext::getInjectedTemplateArg(NamedDecl *Param) {
4439 TemplateArgument Arg;
Eugene Zelenko7855e772018-04-03 00:11:50 +00004440 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
Richard Smith32918772017-02-14 00:25:28 +00004441 QualType ArgType = getTypeDeclType(TTP);
4442 if (TTP->isParameterPack())
4443 ArgType = getPackExpansionType(ArgType, None);
4444
4445 Arg = TemplateArgument(ArgType);
4446 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4447 Expr *E = new (*this) DeclRefExpr(
Bruno Ricci5fc4db72018-12-21 14:10:18 +00004448 *this, NTTP, /*enclosing*/ false,
Richard Smith32918772017-02-14 00:25:28 +00004449 NTTP->getType().getNonLValueExprType(*this),
4450 Expr::getValueKindForType(NTTP->getType()), NTTP->getLocation());
4451
4452 if (NTTP->isParameterPack())
4453 E = new (*this) PackExpansionExpr(DependentTy, E, NTTP->getLocation(),
4454 None);
4455 Arg = TemplateArgument(E);
4456 } else {
4457 auto *TTP = cast<TemplateTemplateParmDecl>(Param);
4458 if (TTP->isParameterPack())
4459 Arg = TemplateArgument(TemplateName(TTP), Optional<unsigned>());
4460 else
4461 Arg = TemplateArgument(TemplateName(TTP));
4462 }
4463
4464 if (Param->isTemplateParameterPack())
4465 Arg = TemplateArgument::CreatePackCopy(*this, Arg);
4466
4467 return Arg;
4468}
4469
Richard Smith43e14d22016-12-23 02:10:11 +00004470void
4471ASTContext::getInjectedTemplateArgs(const TemplateParameterList *Params,
4472 SmallVectorImpl<TemplateArgument> &Args) {
4473 Args.reserve(Args.size() + Params->size());
4474
Richard Smith32918772017-02-14 00:25:28 +00004475 for (NamedDecl *Param : *Params)
4476 Args.push_back(getInjectedTemplateArg(Param));
Richard Smith43e14d22016-12-23 02:10:11 +00004477}
4478
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00004479QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikie05785d12013-02-20 22:23:23 +00004480 Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00004481 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00004482 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00004483
Richard Smithb2997f52019-05-21 20:10:50 +00004484 // A deduced type can deduce to a pack, eg
4485 // auto ...x = some_pack;
4486 // That declaration isn't (yet) valid, but is created as part of building an
4487 // init-capture pack:
4488 // [...x = some_pack] {}
4489 assert((Pattern->containsUnexpandedParameterPack() ||
4490 Pattern->getContainedDeducedType()) &&
Douglas Gregord2fa7662010-12-20 02:24:11 +00004491 "Pack expansions must expand one or more parameter packs");
Craig Topper36250ad2014-05-12 05:36:57 +00004492 void *InsertPos = nullptr;
Douglas Gregord2fa7662010-12-20 02:24:11 +00004493 PackExpansionType *T
4494 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
4495 if (T)
4496 return QualType(T, 0);
4497
4498 QualType Canon;
4499 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00004500 Canon = getCanonicalType(Pattern);
4501 // The canonical type might not contain an unexpanded parameter pack, if it
4502 // contains an alias template specialization which ignores one of its
4503 // parameters.
4504 if (Canon->containsUnexpandedParameterPack()) {
Richard Smith8b4e1e22014-07-10 01:20:17 +00004505 Canon = getPackExpansionType(Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00004506
Richard Smith68eea502012-07-16 00:20:35 +00004507 // Find the insert position again, in case we inserted an element into
4508 // PackExpansionTypes and invalidated our insert position.
4509 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
4510 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00004511 }
4512
Benjamin Kramer8adeef92015-04-02 16:19:54 +00004513 T = new (*this, TypeAlignment)
4514 PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00004515 Types.push_back(T);
4516 PackExpansionTypes.InsertNode(T, InsertPos);
Richard Smith8b4e1e22014-07-10 01:20:17 +00004517 return QualType(T, 0);
Douglas Gregord2fa7662010-12-20 02:24:11 +00004518}
4519
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004520/// CmpProtocolNames - Comparison predicate for sorting protocols
4521/// alphabetically.
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00004522static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
4523 ObjCProtocolDecl *const *RHS) {
4524 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004525}
4526
Craig Topper1f26d5b2016-01-03 19:43:23 +00004527static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) {
4528 if (Protocols.empty()) return true;
John McCallfc93cf92009-10-22 22:37:11 +00004529
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00004530 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
4531 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00004532
Craig Topper1f26d5b2016-01-03 19:43:23 +00004533 for (unsigned i = 1; i != Protocols.size(); ++i)
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00004534 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00004535 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00004536 return false;
4537 return true;
4538}
4539
Craig Topper6a8c1512015-10-22 01:56:18 +00004540static void
4541SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) {
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004542 // Sort protocols, keyed by name.
Craig Topper6a8c1512015-10-22 01:56:18 +00004543 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004544
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00004545 // Canonicalize.
Craig Topper6a8c1512015-10-22 01:56:18 +00004546 for (ObjCProtocolDecl *&P : Protocols)
4547 P = P->getCanonicalDecl();
4548
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004549 // Remove duplicates.
Craig Topper6a8c1512015-10-22 01:56:18 +00004550 auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end());
4551 Protocols.erase(ProtocolsEnd, Protocols.end());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004552}
4553
John McCall8b07ec22010-05-15 11:32:37 +00004554QualType ASTContext::getObjCObjectType(QualType BaseType,
4555 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00004556 unsigned NumProtocols) const {
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004557 return getObjCObjectType(BaseType, {},
Douglas Gregorab209d82015-07-07 03:58:42 +00004558 llvm::makeArrayRef(Protocols, NumProtocols),
4559 /*isKindOf=*/false);
Douglas Gregore9d95f12015-07-07 03:57:35 +00004560}
4561
4562QualType ASTContext::getObjCObjectType(
4563 QualType baseType,
4564 ArrayRef<QualType> typeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00004565 ArrayRef<ObjCProtocolDecl *> protocols,
4566 bool isKindOf) const {
Douglas Gregore9d95f12015-07-07 03:57:35 +00004567 // If the base type is an interface and there aren't any protocols or
4568 // type arguments to add, then the interface type will do just fine.
Douglas Gregorab209d82015-07-07 03:58:42 +00004569 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
4570 isa<ObjCInterfaceType>(baseType))
Douglas Gregore9d95f12015-07-07 03:57:35 +00004571 return baseType;
John McCall8b07ec22010-05-15 11:32:37 +00004572
4573 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00004574 llvm::FoldingSetNodeID ID;
Douglas Gregorab209d82015-07-07 03:58:42 +00004575 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
Craig Topper36250ad2014-05-12 05:36:57 +00004576 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00004577 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
4578 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00004579
Douglas Gregore9d95f12015-07-07 03:57:35 +00004580 // Determine the type arguments to be used for canonicalization,
4581 // which may be explicitly specified here or written on the base
4582 // type.
4583 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
4584 if (effectiveTypeArgs.empty()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00004585 if (const auto *baseObject = baseType->getAs<ObjCObjectType>())
Douglas Gregore9d95f12015-07-07 03:57:35 +00004586 effectiveTypeArgs = baseObject->getTypeArgs();
4587 }
John McCallfc93cf92009-10-22 22:37:11 +00004588
Douglas Gregore9d95f12015-07-07 03:57:35 +00004589 // Build the canonical type, which has the canonical base type and a
4590 // sorted-and-uniqued list of protocols and the type arguments
4591 // canonicalized.
4592 QualType canonical;
4593 bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(),
4594 effectiveTypeArgs.end(),
4595 [&](QualType type) {
4596 return type.isCanonical();
4597 });
Craig Topper1f26d5b2016-01-03 19:43:23 +00004598 bool protocolsSorted = areSortedAndUniqued(protocols);
Douglas Gregore9d95f12015-07-07 03:57:35 +00004599 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
4600 // Determine the canonical type arguments.
4601 ArrayRef<QualType> canonTypeArgs;
4602 SmallVector<QualType, 4> canonTypeArgsVec;
4603 if (!typeArgsAreCanonical) {
4604 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
4605 for (auto typeArg : effectiveTypeArgs)
4606 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
4607 canonTypeArgs = canonTypeArgsVec;
John McCallfc93cf92009-10-22 22:37:11 +00004608 } else {
Douglas Gregore9d95f12015-07-07 03:57:35 +00004609 canonTypeArgs = effectiveTypeArgs;
John McCallfc93cf92009-10-22 22:37:11 +00004610 }
4611
Douglas Gregore9d95f12015-07-07 03:57:35 +00004612 ArrayRef<ObjCProtocolDecl *> canonProtocols;
4613 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
4614 if (!protocolsSorted) {
Craig Topper6a8c1512015-10-22 01:56:18 +00004615 canonProtocolsVec.append(protocols.begin(), protocols.end());
4616 SortAndUniqueProtocols(canonProtocolsVec);
4617 canonProtocols = canonProtocolsVec;
Douglas Gregore9d95f12015-07-07 03:57:35 +00004618 } else {
4619 canonProtocols = protocols;
4620 }
4621
4622 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00004623 canonProtocols, isKindOf);
Douglas Gregore9d95f12015-07-07 03:57:35 +00004624
John McCallfc93cf92009-10-22 22:37:11 +00004625 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00004626 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
4627 }
4628
Douglas Gregore9d95f12015-07-07 03:57:35 +00004629 unsigned size = sizeof(ObjCObjectTypeImpl);
4630 size += typeArgs.size() * sizeof(QualType);
4631 size += protocols.size() * sizeof(ObjCProtocolDecl *);
4632 void *mem = Allocate(size, TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004633 auto *T =
Douglas Gregorab209d82015-07-07 03:58:42 +00004634 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
4635 isKindOf);
John McCall8b07ec22010-05-15 11:32:37 +00004636
4637 Types.push_back(T);
4638 ObjCObjectTypes.InsertNode(T, InsertPos);
4639 return QualType(T, 0);
4640}
4641
Manman Ren3569eb52016-09-13 17:03:12 +00004642/// Apply Objective-C protocol qualifiers to the given type.
4643/// If this is for the canonical type of a type parameter, we can apply
4644/// protocol qualifiers on the ObjCObjectPointerType.
4645QualType
4646ASTContext::applyObjCProtocolQualifiers(QualType type,
4647 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
4648 bool allowOnPointerType) const {
4649 hasError = false;
4650
Eugene Zelenko7855e772018-04-03 00:11:50 +00004651 if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
Manman Renc5705ba2016-09-13 17:41:05 +00004652 return getObjCTypeParamType(objT->getDecl(), protocols);
4653 }
4654
Manman Ren3569eb52016-09-13 17:03:12 +00004655 // Apply protocol qualifiers to ObjCObjectPointerType.
4656 if (allowOnPointerType) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00004657 if (const auto *objPtr =
4658 dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
Manman Ren3569eb52016-09-13 17:03:12 +00004659 const ObjCObjectType *objT = objPtr->getObjectType();
4660 // Merge protocol lists and construct ObjCObjectType.
4661 SmallVector<ObjCProtocolDecl*, 8> protocolsVec;
4662 protocolsVec.append(objT->qual_begin(),
4663 objT->qual_end());
4664 protocolsVec.append(protocols.begin(), protocols.end());
4665 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
4666 type = getObjCObjectType(
4667 objT->getBaseType(),
4668 objT->getTypeArgsAsWritten(),
4669 protocols,
4670 objT->isKindOfTypeAsWritten());
4671 return getObjCObjectPointerType(type);
4672 }
4673 }
4674
4675 // Apply protocol qualifiers to ObjCObjectType.
Eugene Zelenko7855e772018-04-03 00:11:50 +00004676 if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
Manman Ren3569eb52016-09-13 17:03:12 +00004677 // FIXME: Check for protocols to which the class type is already
4678 // known to conform.
4679
4680 return getObjCObjectType(objT->getBaseType(),
4681 objT->getTypeArgsAsWritten(),
4682 protocols,
4683 objT->isKindOfTypeAsWritten());
4684 }
4685
4686 // If the canonical type is ObjCObjectType, ...
4687 if (type->isObjCObjectType()) {
4688 // Silently overwrite any existing protocol qualifiers.
4689 // TODO: determine whether that's the right thing to do.
4690
4691 // FIXME: Check for protocols to which the class type is already
4692 // known to conform.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004693 return getObjCObjectType(type, {}, protocols, false);
Manman Ren3569eb52016-09-13 17:03:12 +00004694 }
4695
4696 // id<protocol-list>
4697 if (type->isObjCIdType()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00004698 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004699 type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols,
Manman Ren3569eb52016-09-13 17:03:12 +00004700 objPtr->isKindOfType());
4701 return getObjCObjectPointerType(type);
4702 }
4703
4704 // Class<protocol-list>
4705 if (type->isObjCClassType()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00004706 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004707 type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols,
Manman Ren3569eb52016-09-13 17:03:12 +00004708 objPtr->isKindOfType());
4709 return getObjCObjectPointerType(type);
4710 }
4711
4712 hasError = true;
4713 return type;
4714}
4715
Manman Rene6be26c2016-09-13 17:25:08 +00004716QualType
4717ASTContext::getObjCTypeParamType(const ObjCTypeParamDecl *Decl,
Volodymyr Sapsaib95d4c32019-10-11 21:21:02 +00004718 ArrayRef<ObjCProtocolDecl *> protocols) const {
Manman Rene6be26c2016-09-13 17:25:08 +00004719 // Look in the folding set for an existing type.
4720 llvm::FoldingSetNodeID ID;
4721 ObjCTypeParamType::Profile(ID, Decl, protocols);
4722 void *InsertPos = nullptr;
4723 if (ObjCTypeParamType *TypeParam =
4724 ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
4725 return QualType(TypeParam, 0);
4726
Volodymyr Sapsaib95d4c32019-10-11 21:21:02 +00004727 // We canonicalize to the underlying type.
4728 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
4729 if (!protocols.empty()) {
4730 // Apply the protocol qualifers.
4731 bool hasError;
4732 Canonical = getCanonicalType(applyObjCProtocolQualifiers(
4733 Canonical, protocols, hasError, true /*allowOnPointerType*/));
4734 assert(!hasError && "Error when apply protocol qualifier to bound type");
Manman Rene6be26c2016-09-13 17:25:08 +00004735 }
4736
4737 unsigned size = sizeof(ObjCTypeParamType);
4738 size += protocols.size() * sizeof(ObjCProtocolDecl *);
4739 void *mem = Allocate(size, TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004740 auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols);
Manman Rene6be26c2016-09-13 17:25:08 +00004741
4742 Types.push_back(newType);
4743 ObjCTypeParamTypes.InsertNode(newType, InsertPos);
4744 return QualType(newType, 0);
4745}
4746
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004747/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
4748/// protocol list adopt all protocols in QT's qualified-id protocol
4749/// list.
4750bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
4751 ObjCInterfaceDecl *IC) {
4752 if (!QT->isObjCQualifiedIdType())
4753 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00004754
Eugene Zelenko7855e772018-04-03 00:11:50 +00004755 if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004756 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00004757 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004758 if (!IC->ClassImplementsProtocol(Proto, false))
4759 return false;
4760 }
4761 return true;
4762 }
4763 return false;
4764}
4765
4766/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
4767/// QT's qualified-id protocol list adopt all protocols in IDecl's list
4768/// of protocols.
4769bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
4770 ObjCInterfaceDecl *IDecl) {
4771 if (!QT->isObjCQualifiedIdType())
4772 return false;
Eugene Zelenko7855e772018-04-03 00:11:50 +00004773 const auto *OPT = QT->getAs<ObjCObjectPointerType>();
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004774 if (!OPT)
4775 return false;
4776 if (!IDecl->hasDefinition())
4777 return false;
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00004778 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
4779 CollectInheritedProtocols(IDecl, InheritedProtocols);
4780 if (InheritedProtocols.empty())
4781 return false;
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00004782 // Check that if every protocol in list of id<plist> conforms to a protocol
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00004783 // of IDecl's, then bridge casting is ok.
4784 bool Conforms = false;
4785 for (auto *Proto : OPT->quals()) {
4786 Conforms = false;
4787 for (auto *PI : InheritedProtocols) {
4788 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
4789 Conforms = true;
4790 break;
4791 }
4792 }
4793 if (!Conforms)
4794 break;
4795 }
4796 if (Conforms)
4797 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00004798
Aaron Ballman83731462014-03-17 16:14:00 +00004799 for (auto *PI : InheritedProtocols) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004800 // If both the right and left sides have qualifiers.
4801 bool Adopts = false;
Aaron Ballman83731462014-03-17 16:14:00 +00004802 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00004803 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
Aaron Ballman83731462014-03-17 16:14:00 +00004804 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004805 break;
4806 }
4807 if (!Adopts)
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00004808 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004809 }
4810 return true;
4811}
4812
John McCall8b07ec22010-05-15 11:32:37 +00004813/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
4814/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00004815QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00004816 llvm::FoldingSetNodeID ID;
4817 ObjCObjectPointerType::Profile(ID, ObjectT);
4818
Craig Topper36250ad2014-05-12 05:36:57 +00004819 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00004820 if (ObjCObjectPointerType *QT =
4821 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
4822 return QualType(QT, 0);
4823
4824 // Find the canonical object type.
4825 QualType Canonical;
4826 if (!ObjectT.isCanonical()) {
4827 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
4828
4829 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00004830 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
4831 }
4832
Douglas Gregorf85bee62010-02-08 22:59:26 +00004833 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00004834 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004835 auto *QType =
John McCall8b07ec22010-05-15 11:32:37 +00004836 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00004837
Steve Narofffb4330f2009-06-17 22:40:22 +00004838 Types.push_back(QType);
4839 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00004840 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00004841}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004842
Douglas Gregor1c283312010-08-11 12:19:30 +00004843/// getObjCInterfaceType - Return the unique reference to the type for the
4844/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00004845QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
4846 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00004847 if (Decl->TypeForDecl)
4848 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004849
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00004850 if (PrevDecl) {
4851 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
4852 Decl->TypeForDecl = PrevDecl->TypeForDecl;
4853 return QualType(PrevDecl->TypeForDecl, 0);
4854 }
4855
Douglas Gregor7671e532011-12-16 16:34:57 +00004856 // Prefer the definition, if there is one.
4857 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
4858 Decl = Def;
Fangrui Song6907ce22018-07-30 19:24:48 +00004859
Douglas Gregor1c283312010-08-11 12:19:30 +00004860 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004861 auto *T = new (Mem) ObjCInterfaceType(Decl);
Douglas Gregor1c283312010-08-11 12:19:30 +00004862 Decl->TypeForDecl = T;
4863 Types.push_back(T);
4864 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00004865}
4866
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004867/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
4868/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00004869/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00004870/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00004871/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00004872QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00004873 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004874 if (tofExpr->isTypeDependent()) {
4875 llvm::FoldingSetNodeID ID;
4876 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00004877
Craig Topper36250ad2014-05-12 05:36:57 +00004878 void *InsertPos = nullptr;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004879 DependentTypeOfExprType *Canon
4880 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
4881 if (Canon) {
4882 // We already have a "canonical" version of an identical, dependent
4883 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00004884 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004885 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00004886 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004887 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00004888 Canon
4889 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004890 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
4891 toe = Canon;
4892 }
4893 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00004894 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00004895 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00004896 }
Steve Naroffa773cd52007-08-01 18:02:17 +00004897 Types.push_back(toe);
4898 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00004899}
4900
Steve Naroffa773cd52007-08-01 18:02:17 +00004901/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
Richard Smith8eb1d322014-06-05 20:13:13 +00004902/// TypeOfType nodes. The only motivation to unique these nodes would be
Steve Naroffa773cd52007-08-01 18:02:17 +00004903/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Richard Smith8eb1d322014-06-05 20:13:13 +00004904/// an issue. This doesn't affect the type checker, since it operates
4905/// on canonical types (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00004906QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00004907 QualType Canonical = getCanonicalType(tofType);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004908 auto *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00004909 Types.push_back(tot);
4910 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00004911}
4912
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004913/// Unlike many "get<Type>" functions, we don't unique DecltypeType
Richard Smith8eb1d322014-06-05 20:13:13 +00004914/// nodes. This would never be helpful, since each such type has its own
4915/// expression, and would not give a significant memory saving, since there
4916/// is an Expr tree under each such type.
Douglas Gregor81495f32012-02-12 18:42:33 +00004917QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00004918 DecltypeType *dt;
Richard Smith8eb1d322014-06-05 20:13:13 +00004919
4920 // C++11 [temp.type]p2:
Douglas Gregor678d76c2011-07-01 01:22:09 +00004921 // If an expression e involves a template parameter, decltype(e) denotes a
Richard Smith8eb1d322014-06-05 20:13:13 +00004922 // unique dependent type. Two such decltype-specifiers refer to the same
4923 // type only if their expressions are equivalent (14.5.6.1).
Douglas Gregor678d76c2011-07-01 01:22:09 +00004924 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00004925 llvm::FoldingSetNodeID ID;
4926 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00004927
Craig Topper36250ad2014-05-12 05:36:57 +00004928 void *InsertPos = nullptr;
Douglas Gregora21f6c32009-07-30 23:36:40 +00004929 DependentDecltypeType *Canon
4930 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
Richard Smith8eb1d322014-06-05 20:13:13 +00004931 if (!Canon) {
Yaron Keren633e14a2016-11-29 10:08:20 +00004932 // Build a new, canonical decltype(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00004933 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00004934 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
Douglas Gregora21f6c32009-07-30 23:36:40 +00004935 }
Richard Smith8eb1d322014-06-05 20:13:13 +00004936 dt = new (*this, TypeAlignment)
4937 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
Douglas Gregora21f6c32009-07-30 23:36:40 +00004938 } else {
Richard Smith8eb1d322014-06-05 20:13:13 +00004939 dt = new (*this, TypeAlignment)
4940 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00004941 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00004942 Types.push_back(dt);
4943 return QualType(dt, 0);
4944}
4945
Alexis Hunte852b102011-05-24 22:41:36 +00004946/// getUnaryTransformationType - We don't unique these, since the memory
4947/// savings are minimal and these are rare.
4948QualType ASTContext::getUnaryTransformType(QualType BaseType,
4949 QualType UnderlyingType,
4950 UnaryTransformType::UTTKind Kind)
4951 const {
Vassil Vassilevbab6f962016-03-30 22:18:29 +00004952 UnaryTransformType *ut = nullptr;
4953
4954 if (BaseType->isDependentType()) {
4955 // Look in the folding set for an existing type.
4956 llvm::FoldingSetNodeID ID;
4957 DependentUnaryTransformType::Profile(ID, getCanonicalType(BaseType), Kind);
4958
4959 void *InsertPos = nullptr;
4960 DependentUnaryTransformType *Canon
4961 = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
4962
4963 if (!Canon) {
4964 // Build a new, canonical __underlying_type(type) type.
4965 Canon = new (*this, TypeAlignment)
4966 DependentUnaryTransformType(*this, getCanonicalType(BaseType),
4967 Kind);
4968 DependentUnaryTransformTypes.InsertNode(Canon, InsertPos);
4969 }
4970 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4971 QualType(), Kind,
4972 QualType(Canon, 0));
4973 } else {
4974 QualType CanonType = getCanonicalType(UnderlyingType);
4975 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4976 UnderlyingType, Kind,
4977 CanonType);
4978 }
4979 Types.push_back(ut);
4980 return QualType(ut, 0);
Alexis Hunte852b102011-05-24 22:41:36 +00004981}
4982
Richard Smith2a7d4812013-05-04 07:00:32 +00004983/// getAutoType - Return the uniqued reference to the 'auto' type which has been
4984/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
4985/// canonical deduced-but-dependent 'auto' type.
Richard Smithe301ba22015-11-11 02:02:15 +00004986QualType ASTContext::getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
Richard Smithb2997f52019-05-21 20:10:50 +00004987 bool IsDependent, bool IsPack) const {
4988 assert((!IsPack || IsDependent) && "only use IsPack for a dependent pack");
Richard Smithe301ba22015-11-11 02:02:15 +00004989 if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto && !IsDependent)
Richard Smith2a7d4812013-05-04 07:00:32 +00004990 return getAutoDeductType();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004991
Richard Smith2a7d4812013-05-04 07:00:32 +00004992 // Look in the folding set for an existing type.
Craig Topper36250ad2014-05-12 05:36:57 +00004993 void *InsertPos = nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +00004994 llvm::FoldingSetNodeID ID;
Richard Smithb2997f52019-05-21 20:10:50 +00004995 AutoType::Profile(ID, DeducedType, Keyword, IsDependent, IsPack);
Richard Smith2a7d4812013-05-04 07:00:32 +00004996 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
4997 return QualType(AT, 0);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004998
Eugene Zelenko7855e772018-04-03 00:11:50 +00004999 auto *AT = new (*this, TypeAlignment)
Richard Smithb2997f52019-05-21 20:10:50 +00005000 AutoType(DeducedType, Keyword, IsDependent, IsPack);
Richard Smithb2bc2e62011-02-21 20:05:19 +00005001 Types.push_back(AT);
5002 if (InsertPos)
5003 AutoTypes.InsertNode(AT, InsertPos);
5004 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00005005}
5006
Richard Smith600b5262017-01-26 20:40:47 +00005007/// Return the uniqued reference to the deduced template specialization type
5008/// which has been deduced to the given type, or to the canonical undeduced
5009/// such type, or the canonical deduced-but-dependent such type.
5010QualType ASTContext::getDeducedTemplateSpecializationType(
5011 TemplateName Template, QualType DeducedType, bool IsDependent) const {
5012 // Look in the folding set for an existing type.
5013 void *InsertPos = nullptr;
5014 llvm::FoldingSetNodeID ID;
5015 DeducedTemplateSpecializationType::Profile(ID, Template, DeducedType,
5016 IsDependent);
5017 if (DeducedTemplateSpecializationType *DTST =
5018 DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
5019 return QualType(DTST, 0);
5020
Eugene Zelenko7855e772018-04-03 00:11:50 +00005021 auto *DTST = new (*this, TypeAlignment)
Richard Smith600b5262017-01-26 20:40:47 +00005022 DeducedTemplateSpecializationType(Template, DeducedType, IsDependent);
5023 Types.push_back(DTST);
5024 if (InsertPos)
5025 DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos);
5026 return QualType(DTST, 0);
5027}
5028
Eli Friedman0dfb8892011-10-06 23:00:33 +00005029/// getAtomicType - Return the uniqued reference to the atomic type for
5030/// the given value type.
5031QualType ASTContext::getAtomicType(QualType T) const {
5032 // Unique pointers, to guarantee there is only one pointer of a particular
5033 // structure.
5034 llvm::FoldingSetNodeID ID;
5035 AtomicType::Profile(ID, T);
5036
Craig Topper36250ad2014-05-12 05:36:57 +00005037 void *InsertPos = nullptr;
Eli Friedman0dfb8892011-10-06 23:00:33 +00005038 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
5039 return QualType(AT, 0);
5040
5041 // If the atomic value type isn't canonical, this won't be a canonical type
5042 // either, so fill in the canonical type field.
5043 QualType Canonical;
5044 if (!T.isCanonical()) {
5045 Canonical = getAtomicType(getCanonicalType(T));
5046
5047 // Get the new insert position for the node we care about.
5048 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00005049 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Eli Friedman0dfb8892011-10-06 23:00:33 +00005050 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00005051 auto *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
Eli Friedman0dfb8892011-10-06 23:00:33 +00005052 Types.push_back(New);
5053 AtomicTypes.InsertNode(New, InsertPos);
5054 return QualType(New, 0);
5055}
5056
Richard Smith02e85f32011-04-14 22:09:26 +00005057/// getAutoDeductType - Get type pattern for deducing against 'auto'.
5058QualType ASTContext::getAutoDeductType() const {
5059 if (AutoDeductTy.isNull())
Richard Smith2a7d4812013-05-04 07:00:32 +00005060 AutoDeductTy = QualType(
Richard Smithe301ba22015-11-11 02:02:15 +00005061 new (*this, TypeAlignment) AutoType(QualType(), AutoTypeKeyword::Auto,
Richard Smithb2997f52019-05-21 20:10:50 +00005062 /*dependent*/false, /*pack*/false),
Richard Smith2a7d4812013-05-04 07:00:32 +00005063 0);
Richard Smith02e85f32011-04-14 22:09:26 +00005064 return AutoDeductTy;
5065}
5066
5067/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
5068QualType ASTContext::getAutoRRefDeductType() const {
5069 if (AutoRRefDeductTy.isNull())
5070 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
5071 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
5072 return AutoRRefDeductTy;
5073}
5074
Chris Lattnerfb072462007-01-23 05:45:31 +00005075/// getTagDeclType - Return the unique reference to the type for the
5076/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00005077QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00005078 assert(Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00005079 // FIXME: What is the design on getTagDeclType when it requires casting
5080 // away const? mutable?
5081 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00005082}
5083
Mike Stump11289f42009-09-09 15:08:12 +00005084/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
5085/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
5086/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00005087CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00005088 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00005089}
Chris Lattnerfb072462007-01-23 05:45:31 +00005090
Fangrui Song6907ce22018-07-30 19:24:48 +00005091/// Return the unique signed counterpart of the integer type
Alexander Shaposhnikov1e898d92017-07-14 17:30:14 +00005092/// corresponding to size_t.
5093CanQualType ASTContext::getSignedSizeType() const {
5094 return getFromTargetType(Target->getSignedSizeType());
5095}
5096
Hans Wennborg27541db2011-10-27 08:29:09 +00005097/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
5098CanQualType ASTContext::getIntMaxType() const {
5099 return getFromTargetType(Target->getIntMaxType());
5100}
5101
5102/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
5103CanQualType ASTContext::getUIntMaxType() const {
5104 return getFromTargetType(Target->getUIntMaxType());
5105}
5106
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00005107/// getSignedWCharType - Return the type of "signed wchar_t".
5108/// Used when in C++, as a GCC extension.
5109QualType ASTContext::getSignedWCharType() const {
5110 // FIXME: derive from "Target" ?
5111 return WCharTy;
5112}
5113
5114/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
5115/// Used when in C++, as a GCC extension.
5116QualType ASTContext::getUnsignedWCharType() const {
5117 // FIXME: derive from "Target" ?
5118 return UnsignedIntTy;
5119}
5120
Enea Zaffanellaf11ceb62013-01-26 17:08:37 +00005121QualType ASTContext::getIntPtrType() const {
5122 return getFromTargetType(Target->getIntPtrType());
5123}
5124
5125QualType ASTContext::getUIntPtrType() const {
5126 return getCorrespondingUnsignedType(getIntPtrType());
5127}
5128
Hans Wennborg27541db2011-10-27 08:29:09 +00005129/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00005130/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
5131QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00005132 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00005133}
5134
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005135/// Return the unique unsigned counterpart of "ptrdiff_t"
Alexander Shaposhnikov195b25c2017-09-28 23:11:31 +00005136/// integer type. The standard (C11 7.21.6.1p7) refers to this type
5137/// in the definition of %tu format specifier.
5138QualType ASTContext::getUnsignedPointerDiffType() const {
5139 return getFromTargetType(Target->getUnsignedPtrDiffType(0));
5140}
5141
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005142/// Return the unique type for "pid_t" defined in
Eli Friedman4e91899e2012-11-27 02:58:24 +00005143/// <sys/types.h>. We need this to compute the correct type for vfork().
5144QualType ASTContext::getProcessIDType() const {
5145 return getFromTargetType(Target->getProcessIDType());
5146}
5147
Chris Lattnera21ad802008-04-02 05:18:44 +00005148//===----------------------------------------------------------------------===//
5149// Type Operators
5150//===----------------------------------------------------------------------===//
5151
Jay Foad39c79802011-01-12 09:06:06 +00005152CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00005153 // Push qualifiers into arrays, and then discard any remaining
5154 // qualifiers.
5155 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00005156 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00005157 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00005158 QualType Result;
5159 if (isa<ArrayType>(Ty)) {
5160 Result = getArrayDecayedType(QualType(Ty,0));
5161 } else if (isa<FunctionType>(Ty)) {
5162 Result = getPointerType(QualType(Ty, 0));
5163 } else {
5164 Result = QualType(Ty, 0);
5165 }
5166
5167 return CanQualType::CreateUnsafe(Result);
5168}
5169
John McCall6c9dd522011-01-18 07:41:22 +00005170QualType ASTContext::getUnqualifiedArrayType(QualType type,
5171 Qualifiers &quals) {
5172 SplitQualType splitType = type.getSplitUnqualifiedType();
5173
5174 // FIXME: getSplitUnqualifiedType() actually walks all the way to
5175 // the unqualified desugared type and then drops it on the floor.
5176 // We then have to strip that sugar back off with
5177 // getUnqualifiedDesugaredType(), which is silly.
Eugene Zelenko7855e772018-04-03 00:11:50 +00005178 const auto *AT =
5179 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00005180
5181 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00005182 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00005183 quals = splitType.Quals;
5184 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00005185 }
5186
John McCall6c9dd522011-01-18 07:41:22 +00005187 // Otherwise, recurse on the array's element type.
5188 QualType elementType = AT->getElementType();
5189 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
5190
5191 // If that didn't change the element type, AT has no qualifiers, so we
5192 // can just use the results in splitType.
5193 if (elementType == unqualElementType) {
5194 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00005195 quals = splitType.Quals;
5196 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00005197 }
5198
5199 // Otherwise, add in the qualifiers from the outermost type, then
5200 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00005201 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00005202
Eugene Zelenko7855e772018-04-03 00:11:50 +00005203 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00005204 return getConstantArrayType(unqualElementType, CAT->getSize(),
Richard Smith772e2662019-10-04 01:25:59 +00005205 CAT->getSizeExpr(), CAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00005206 }
5207
Eugene Zelenko7855e772018-04-03 00:11:50 +00005208 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00005209 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00005210 }
5211
Eugene Zelenko7855e772018-04-03 00:11:50 +00005212 if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00005213 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00005214 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00005215 VAT->getSizeModifier(),
5216 VAT->getIndexTypeCVRQualifiers(),
5217 VAT->getBracketsRange());
5218 }
5219
Eugene Zelenko7855e772018-04-03 00:11:50 +00005220 const auto *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00005221 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00005222 DSAT->getSizeModifier(), 0,
5223 SourceRange());
5224}
5225
Richard Smitha3405ff2018-07-11 00:19:19 +00005226/// Attempt to unwrap two types that may both be array types with the same bound
5227/// (or both be array types of unknown bound) for the purpose of comparing the
5228/// cv-decomposition of two types per C++ [conv.qual].
Richard Smith5407d4f2018-07-18 20:13:36 +00005229bool ASTContext::UnwrapSimilarArrayTypes(QualType &T1, QualType &T2) {
5230 bool UnwrappedAny = false;
Richard Smitha3405ff2018-07-11 00:19:19 +00005231 while (true) {
Richard Smith5407d4f2018-07-18 20:13:36 +00005232 auto *AT1 = getAsArrayType(T1);
5233 if (!AT1) return UnwrappedAny;
Richard Smitha3405ff2018-07-11 00:19:19 +00005234
Richard Smith5407d4f2018-07-18 20:13:36 +00005235 auto *AT2 = getAsArrayType(T2);
5236 if (!AT2) return UnwrappedAny;
Richard Smitha3405ff2018-07-11 00:19:19 +00005237
5238 // If we don't have two array types with the same constant bound nor two
5239 // incomplete array types, we've unwrapped everything we can.
5240 if (auto *CAT1 = dyn_cast<ConstantArrayType>(AT1)) {
5241 auto *CAT2 = dyn_cast<ConstantArrayType>(AT2);
5242 if (!CAT2 || CAT1->getSize() != CAT2->getSize())
Richard Smith5407d4f2018-07-18 20:13:36 +00005243 return UnwrappedAny;
Richard Smitha3405ff2018-07-11 00:19:19 +00005244 } else if (!isa<IncompleteArrayType>(AT1) ||
5245 !isa<IncompleteArrayType>(AT2)) {
Richard Smith5407d4f2018-07-18 20:13:36 +00005246 return UnwrappedAny;
Richard Smitha3405ff2018-07-11 00:19:19 +00005247 }
5248
5249 T1 = AT1->getElementType();
5250 T2 = AT2->getElementType();
Richard Smith5407d4f2018-07-18 20:13:36 +00005251 UnwrappedAny = true;
Richard Smitha3405ff2018-07-11 00:19:19 +00005252 }
5253}
5254
5255/// Attempt to unwrap two types that may be similar (C++ [conv.qual]).
5256///
5257/// If T1 and T2 are both pointer types of the same kind, or both array types
5258/// with the same bound, unwraps layers from T1 and T2 until a pointer type is
5259/// unwrapped. Top-level qualifiers on T1 and T2 are ignored.
5260///
5261/// This function will typically be called in a loop that successively
5262/// "unwraps" pointer and pointer-to-member types to compare them at each
5263/// level.
5264///
5265/// \return \c true if a pointer type was unwrapped, \c false if we reached a
5266/// pair of types that can't be unwrapped further.
5267bool ASTContext::UnwrapSimilarTypes(QualType &T1, QualType &T2) {
Richard Smith5407d4f2018-07-18 20:13:36 +00005268 UnwrapSimilarArrayTypes(T1, T2);
Richard Smitha3405ff2018-07-11 00:19:19 +00005269
Eugene Zelenko7855e772018-04-03 00:11:50 +00005270 const auto *T1PtrType = T1->getAs<PointerType>();
5271 const auto *T2PtrType = T2->getAs<PointerType>();
Douglas Gregor1fc3d662010-06-09 03:53:18 +00005272 if (T1PtrType && T2PtrType) {
5273 T1 = T1PtrType->getPointeeType();
5274 T2 = T2PtrType->getPointeeType();
5275 return true;
5276 }
Richard Smith5407d4f2018-07-18 20:13:36 +00005277
Eugene Zelenko7855e772018-04-03 00:11:50 +00005278 const auto *T1MPType = T1->getAs<MemberPointerType>();
5279 const auto *T2MPType = T2->getAs<MemberPointerType>();
Fangrui Song6907ce22018-07-30 19:24:48 +00005280 if (T1MPType && T2MPType &&
5281 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
Douglas Gregor1fc3d662010-06-09 03:53:18 +00005282 QualType(T2MPType->getClass(), 0))) {
5283 T1 = T1MPType->getPointeeType();
5284 T2 = T2MPType->getPointeeType();
5285 return true;
5286 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005287
Erik Pilkingtonfa983902018-10-30 20:31:30 +00005288 if (getLangOpts().ObjC) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00005289 const auto *T1OPType = T1->getAs<ObjCObjectPointerType>();
5290 const auto *T2OPType = T2->getAs<ObjCObjectPointerType>();
Douglas Gregor1fc3d662010-06-09 03:53:18 +00005291 if (T1OPType && T2OPType) {
5292 T1 = T1OPType->getPointeeType();
5293 T2 = T2OPType->getPointeeType();
5294 return true;
5295 }
5296 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005297
Douglas Gregor1fc3d662010-06-09 03:53:18 +00005298 // FIXME: Block pointers, too?
Fangrui Song6907ce22018-07-30 19:24:48 +00005299
Douglas Gregor1fc3d662010-06-09 03:53:18 +00005300 return false;
5301}
5302
Richard Smitha3405ff2018-07-11 00:19:19 +00005303bool ASTContext::hasSimilarType(QualType T1, QualType T2) {
5304 while (true) {
5305 Qualifiers Quals;
5306 T1 = getUnqualifiedArrayType(T1, Quals);
5307 T2 = getUnqualifiedArrayType(T2, Quals);
5308 if (hasSameType(T1, T2))
5309 return true;
5310 if (!UnwrapSimilarTypes(T1, T2))
5311 return false;
5312 }
5313}
5314
5315bool ASTContext::hasCvrSimilarType(QualType T1, QualType T2) {
5316 while (true) {
5317 Qualifiers Quals1, Quals2;
5318 T1 = getUnqualifiedArrayType(T1, Quals1);
5319 T2 = getUnqualifiedArrayType(T2, Quals2);
5320
5321 Quals1.removeCVRQualifiers();
5322 Quals2.removeCVRQualifiers();
5323 if (Quals1 != Quals2)
5324 return false;
5325
5326 if (hasSameType(T1, T2))
5327 return true;
5328
5329 if (!UnwrapSimilarTypes(T1, T2))
5330 return false;
5331 }
5332}
5333
Jay Foad39c79802011-01-12 09:06:06 +00005334DeclarationNameInfo
5335ASTContext::getNameForTemplate(TemplateName Name,
5336 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00005337 switch (Name.getKind()) {
5338 case TemplateName::QualifiedTemplate:
5339 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005340 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00005341 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
5342 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005343
John McCalld9dfe3a2011-06-30 08:33:18 +00005344 case TemplateName::OverloadedTemplate: {
5345 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
5346 // DNInfo work in progress: CHECKME: what about DNLoc?
5347 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
5348 }
5349
Richard Smithb23c5e82019-05-09 03:31:27 +00005350 case TemplateName::AssumedTemplate: {
5351 AssumedTemplateStorage *Storage = Name.getAsAssumedTemplateName();
5352 return DeclarationNameInfo(Storage->getDeclName(), NameLoc);
5353 }
5354
John McCalld9dfe3a2011-06-30 08:33:18 +00005355 case TemplateName::DependentTemplate: {
5356 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005357 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00005358 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005359 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
5360 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00005361 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005362 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
5363 // DNInfo work in progress: FIXME: source locations?
5364 DeclarationNameLoc DNLoc;
5365 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
5366 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
5367 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00005368 }
5369 }
5370
John McCalld9dfe3a2011-06-30 08:33:18 +00005371 case TemplateName::SubstTemplateTemplateParm: {
5372 SubstTemplateTemplateParmStorage *subst
5373 = Name.getAsSubstTemplateTemplateParm();
5374 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
5375 NameLoc);
5376 }
5377
5378 case TemplateName::SubstTemplateTemplateParmPack: {
5379 SubstTemplateTemplateParmPackStorage *subst
5380 = Name.getAsSubstTemplateTemplateParmPack();
5381 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
5382 NameLoc);
5383 }
5384 }
5385
5386 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00005387}
5388
Jay Foad39c79802011-01-12 09:06:06 +00005389TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00005390 switch (Name.getKind()) {
5391 case TemplateName::QualifiedTemplate:
5392 case TemplateName::Template: {
5393 TemplateDecl *Template = Name.getAsTemplateDecl();
Eugene Zelenko7855e772018-04-03 00:11:50 +00005394 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00005395 Template = getCanonicalTemplateTemplateParmDecl(TTP);
Fangrui Song6907ce22018-07-30 19:24:48 +00005396
Douglas Gregor7dbfb462010-06-16 21:09:37 +00005397 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00005398 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00005399 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00005400
John McCalld9dfe3a2011-06-30 08:33:18 +00005401 case TemplateName::OverloadedTemplate:
Richard Smithb23c5e82019-05-09 03:31:27 +00005402 case TemplateName::AssumedTemplate:
5403 llvm_unreachable("cannot canonicalize unresolved template");
Mike Stump11289f42009-09-09 15:08:12 +00005404
John McCalld9dfe3a2011-06-30 08:33:18 +00005405 case TemplateName::DependentTemplate: {
5406 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
5407 assert(DTN && "Non-dependent template names must refer to template decls.");
5408 return DTN->CanonicalTemplateName;
5409 }
5410
5411 case TemplateName::SubstTemplateTemplateParm: {
5412 SubstTemplateTemplateParmStorage *subst
5413 = Name.getAsSubstTemplateTemplateParm();
5414 return getCanonicalTemplateName(subst->getReplacement());
5415 }
5416
5417 case TemplateName::SubstTemplateTemplateParmPack: {
5418 SubstTemplateTemplateParmPackStorage *subst
5419 = Name.getAsSubstTemplateTemplateParmPack();
5420 TemplateTemplateParmDecl *canonParameter
5421 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
5422 TemplateArgument canonArgPack
5423 = getCanonicalTemplateArgument(subst->getArgumentPack());
5424 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
5425 }
5426 }
5427
5428 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00005429}
5430
Douglas Gregoradee3e32009-11-11 23:06:43 +00005431bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
5432 X = getCanonicalTemplateName(X);
5433 Y = getCanonicalTemplateName(Y);
5434 return X.getAsVoidPointer() == Y.getAsVoidPointer();
5435}
5436
Mike Stump11289f42009-09-09 15:08:12 +00005437TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00005438ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00005439 switch (Arg.getKind()) {
5440 case TemplateArgument::Null:
5441 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00005442
Douglas Gregora8e02e72009-07-28 23:00:59 +00005443 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00005444 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00005445
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005446 case TemplateArgument::Declaration: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00005447 auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
David Blaikie952a9b12014-10-17 18:00:12 +00005448 return TemplateArgument(D, Arg.getParamTypeForDecl());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005449 }
Mike Stump11289f42009-09-09 15:08:12 +00005450
Eli Friedmanb826a002012-09-26 02:36:12 +00005451 case TemplateArgument::NullPtr:
5452 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
5453 /*isNullPtr*/true);
5454
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005455 case TemplateArgument::Template:
5456 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005457
5458 case TemplateArgument::TemplateExpansion:
5459 return TemplateArgument(getCanonicalTemplateName(
5460 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00005461 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005462
Douglas Gregora8e02e72009-07-28 23:00:59 +00005463 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00005464 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00005465
Douglas Gregora8e02e72009-07-28 23:00:59 +00005466 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00005467 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00005468
Douglas Gregora8e02e72009-07-28 23:00:59 +00005469 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00005470 if (Arg.pack_size() == 0)
5471 return Arg;
Fangrui Song6907ce22018-07-30 19:24:48 +00005472
Eugene Zelenko7855e772018-04-03 00:11:50 +00005473 auto *CanonArgs = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00005474 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00005475 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00005476 AEnd = Arg.pack_end();
5477 A != AEnd; (void)++A, ++Idx)
5478 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00005479
Benjamin Kramercce63472015-08-05 09:40:22 +00005480 return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size()));
Douglas Gregora8e02e72009-07-28 23:00:59 +00005481 }
5482 }
5483
5484 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00005485 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00005486}
5487
Douglas Gregor333489b2009-03-27 23:10:48 +00005488NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00005489ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00005490 if (!NNS)
Craig Topper36250ad2014-05-12 05:36:57 +00005491 return nullptr;
Douglas Gregor333489b2009-03-27 23:10:48 +00005492
5493 switch (NNS->getKind()) {
5494 case NestedNameSpecifier::Identifier:
5495 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00005496 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00005497 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
5498 NNS->getAsIdentifier());
5499
5500 case NestedNameSpecifier::Namespace:
5501 // A namespace is canonical; build a nested-name-specifier with
5502 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00005503 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00005504 NNS->getAsNamespace()->getOriginalNamespace());
5505
5506 case NestedNameSpecifier::NamespaceAlias:
5507 // A namespace is canonical; build a nested-name-specifier with
5508 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00005509 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00005510 NNS->getAsNamespaceAlias()->getNamespace()
5511 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00005512
5513 case NestedNameSpecifier::TypeSpec:
5514 case NestedNameSpecifier::TypeSpecWithTemplate: {
5515 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Fangrui Song6907ce22018-07-30 19:24:48 +00005516
Douglas Gregor3ade5702010-11-04 00:09:33 +00005517 // If we have some kind of dependent-named type (e.g., "typename T::type"),
5518 // break it apart into its prefix and identifier, then reconsititute those
5519 // as the canonical nested-name-specifier. This is required to canonicalize
5520 // a dependent nested-name-specifier involving typedefs of dependent-name
5521 // types, e.g.,
5522 // typedef typename T::type T1;
5523 // typedef typename T1::type T2;
Eugene Zelenko7855e772018-04-03 00:11:50 +00005524 if (const auto *DNT = T->getAs<DependentNameType>())
Fangrui Song6907ce22018-07-30 19:24:48 +00005525 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00005526 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00005527
Eli Friedman5358a0a2012-03-03 04:09:56 +00005528 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
5529 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
5530 // first place?
Craig Topper36250ad2014-05-12 05:36:57 +00005531 return NestedNameSpecifier::Create(*this, nullptr, false,
5532 const_cast<Type *>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00005533 }
5534
5535 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00005536 case NestedNameSpecifier::Super:
5537 // The global specifier and __super specifer are canonical and unique.
Douglas Gregor333489b2009-03-27 23:10:48 +00005538 return NNS;
5539 }
5540
David Blaikie8a40f702012-01-17 06:56:22 +00005541 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00005542}
5543
Jay Foad39c79802011-01-12 09:06:06 +00005544const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00005545 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005546 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00005547 // Handle the common positive case fast.
Eugene Zelenko7855e772018-04-03 00:11:50 +00005548 if (const auto *AT = dyn_cast<ArrayType>(T))
Chris Lattner7adf0762008-08-04 07:31:14 +00005549 return AT;
5550 }
Mike Stump11289f42009-09-09 15:08:12 +00005551
John McCall8ccfcb52009-09-24 19:53:00 +00005552 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00005553 if (!isa<ArrayType>(T.getCanonicalType()))
Craig Topper36250ad2014-05-12 05:36:57 +00005554 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00005555
John McCall8ccfcb52009-09-24 19:53:00 +00005556 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00005557 // implements C99 6.7.3p8: "If the specification of an array type includes
5558 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00005559
Chris Lattner7adf0762008-08-04 07:31:14 +00005560 // If we get here, we either have type qualifiers on the type, or we have
5561 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00005562 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00005563
John McCall33ddac02011-01-19 10:06:00 +00005564 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00005565 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00005566
Chris Lattner7adf0762008-08-04 07:31:14 +00005567 // If we have a simple case, just return now.
Eugene Zelenko7855e772018-04-03 00:11:50 +00005568 const auto *ATy = dyn_cast<ArrayType>(split.Ty);
Craig Topper36250ad2014-05-12 05:36:57 +00005569 if (!ATy || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00005570 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00005571
Chris Lattner7adf0762008-08-04 07:31:14 +00005572 // Otherwise, we have an array and we have qualifiers on it. Push the
5573 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00005574 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00005575
Eugene Zelenko7855e772018-04-03 00:11:50 +00005576 if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy))
Chris Lattner7adf0762008-08-04 07:31:14 +00005577 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
Richard Smith772e2662019-10-04 01:25:59 +00005578 CAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00005579 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00005580 CAT->getIndexTypeCVRQualifiers()));
Eugene Zelenko7855e772018-04-03 00:11:50 +00005581 if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy))
Chris Lattner7adf0762008-08-04 07:31:14 +00005582 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
5583 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00005584 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00005585
Eugene Zelenko7855e772018-04-03 00:11:50 +00005586 if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy))
Douglas Gregor4619e432008-12-05 23:32:09 +00005587 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00005588 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00005589 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00005590 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00005591 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00005592 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00005593
Eugene Zelenko7855e772018-04-03 00:11:50 +00005594 const auto *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00005595 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00005596 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00005597 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00005598 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00005599 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00005600}
5601
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00005602QualType ASTContext::getAdjustedParameterType(QualType T) const {
Reid Kleckner8a365022013-06-24 17:51:48 +00005603 if (T->isArrayType() || T->isFunctionType())
5604 return getDecayedType(T);
5605 return T;
Douglas Gregor84280642011-07-12 04:42:08 +00005606}
5607
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00005608QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00005609 T = getVariableArrayDecayedType(T);
5610 T = getAdjustedParameterType(T);
5611 return T.getUnqualifiedType();
5612}
5613
David Majnemerd09a51c2015-03-03 01:50:05 +00005614QualType ASTContext::getExceptionObjectType(QualType T) const {
5615 // C++ [except.throw]p3:
5616 // A throw-expression initializes a temporary object, called the exception
5617 // object, the type of which is determined by removing any top-level
5618 // cv-qualifiers from the static type of the operand of throw and adjusting
5619 // the type from "array of T" or "function returning T" to "pointer to T"
5620 // or "pointer to function returning T", [...]
5621 T = getVariableArrayDecayedType(T);
5622 if (T->isArrayType() || T->isFunctionType())
5623 T = getDecayedType(T);
5624 return T.getUnqualifiedType();
5625}
5626
Chris Lattnera21ad802008-04-02 05:18:44 +00005627/// getArrayDecayedType - Return the properly qualified result of decaying the
5628/// specified array type to a pointer. This operation is non-trivial when
5629/// handling typedefs etc. The canonical type of "T" must be an array type,
5630/// this returns a pointer to a properly qualified element of the array.
5631///
5632/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00005633QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00005634 // Get the element type with 'getAsArrayType' so that we don't lose any
5635 // typedefs in the element type of the array. This also handles propagation
5636 // of type qualifiers from the array type into the element type if present
5637 // (C99 6.7.3p8).
5638 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
5639 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00005640
Chris Lattner7adf0762008-08-04 07:31:14 +00005641 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00005642
5643 // int x[restrict 4] -> int *restrict
Jordan Rose303e2f12016-11-10 23:28:17 +00005644 QualType Result = getQualifiedType(PtrTy,
5645 PrettyArrayType->getIndexTypeQualifiers());
5646
5647 // int x[_Nullable] -> int * _Nullable
5648 if (auto Nullability = Ty->getNullability(*this)) {
5649 Result = const_cast<ASTContext *>(this)->getAttributedType(
5650 AttributedType::getNullabilityAttrKind(*Nullability), Result, Result);
5651 }
5652 return Result;
Chris Lattnera21ad802008-04-02 05:18:44 +00005653}
5654
John McCall33ddac02011-01-19 10:06:00 +00005655QualType ASTContext::getBaseElementType(const ArrayType *array) const {
5656 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00005657}
5658
John McCall33ddac02011-01-19 10:06:00 +00005659QualType ASTContext::getBaseElementType(QualType type) const {
5660 Qualifiers qs;
5661 while (true) {
5662 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00005663 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00005664 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00005665
John McCall33ddac02011-01-19 10:06:00 +00005666 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00005667 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00005668 }
Mike Stump11289f42009-09-09 15:08:12 +00005669
John McCall33ddac02011-01-19 10:06:00 +00005670 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00005671}
5672
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00005673/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00005674uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00005675ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
5676 uint64_t ElementCount = 1;
5677 do {
5678 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00005679 CA = dyn_cast_or_null<ConstantArrayType>(
5680 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00005681 } while (CA);
5682 return ElementCount;
5683}
5684
Steve Naroff0af91202007-04-27 21:51:21 +00005685/// getFloatingRank - Return a relative rank for floating point types.
5686/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00005687static FloatingRank getFloatingRank(QualType T) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00005688 if (const auto *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00005689 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00005690
Simon Pilgrimeed4b122019-10-02 11:48:06 +00005691 switch (T->castAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00005692 default: llvm_unreachable("getFloatingRank(): not a floating type");
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00005693 case BuiltinType::Float16: return Float16Rank;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00005694 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00005695 case BuiltinType::Float: return FloatRank;
5696 case BuiltinType::Double: return DoubleRank;
5697 case BuiltinType::LongDouble: return LongDoubleRank;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005698 case BuiltinType::Float128: return Float128Rank;
Steve Naroffe4718892007-04-27 18:30:00 +00005699 }
5700}
5701
Mike Stump11289f42009-09-09 15:08:12 +00005702/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
5703/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00005704/// 'typeDomain' is a real floating point or complex type.
5705/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00005706QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
5707 QualType Domain) const {
5708 FloatingRank EltRank = getFloatingRank(Size);
5709 if (Domain->isComplexType()) {
5710 switch (EltRank) {
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00005711 case Float16Rank:
David Blaikief47fa302012-01-17 02:30:50 +00005712 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00005713 case FloatRank: return FloatComplexTy;
5714 case DoubleRank: return DoubleComplexTy;
5715 case LongDoubleRank: return LongDoubleComplexTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005716 case Float128Rank: return Float128ComplexTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00005717 }
Steve Naroff0af91202007-04-27 21:51:21 +00005718 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00005719
5720 assert(Domain->isRealFloatingType() && "Unknown domain!");
5721 switch (EltRank) {
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00005722 case Float16Rank: return HalfTy;
Joey Goulydd7f4562013-01-23 11:56:20 +00005723 case HalfRank: return HalfTy;
Chris Lattnerb9dfb032008-04-06 23:58:54 +00005724 case FloatRank: return FloatTy;
5725 case DoubleRank: return DoubleTy;
5726 case LongDoubleRank: return LongDoubleTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005727 case Float128Rank: return Float128Ty;
Steve Naroff9091ef72007-08-27 01:27:54 +00005728 }
David Blaikief47fa302012-01-17 02:30:50 +00005729 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00005730}
5731
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005732/// getFloatingTypeOrder - Compare the rank of the two specified floating
5733/// point types, ignoring the domain of the type (i.e. 'double' ==
5734/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00005735/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00005736int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00005737 FloatingRank LHSR = getFloatingRank(LHS);
5738 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00005739
Chris Lattnerb90739d2008-04-06 23:38:49 +00005740 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00005741 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00005742 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00005743 return 1;
5744 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00005745}
5746
Erik Pilkingtoneac7c3f2019-02-16 01:11:47 +00005747int ASTContext::getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const {
5748 if (&getFloatTypeSemantics(LHS) == &getFloatTypeSemantics(RHS))
5749 return 0;
5750 return getFloatingTypeOrder(LHS, RHS);
5751}
5752
Chris Lattner76a00cf2008-04-06 22:59:24 +00005753/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
5754/// routine will assert if passed a built-in type that isn't an integer or enum,
5755/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00005756unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00005757 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00005758
Chris Lattner76a00cf2008-04-06 22:59:24 +00005759 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00005760 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005761 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005762 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005763 case BuiltinType::Char_S:
5764 case BuiltinType::Char_U:
5765 case BuiltinType::SChar:
5766 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005767 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005768 case BuiltinType::Short:
5769 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005770 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005771 case BuiltinType::Int:
5772 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005773 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005774 case BuiltinType::Long:
5775 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005776 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005777 case BuiltinType::LongLong:
5778 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005779 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00005780 case BuiltinType::Int128:
5781 case BuiltinType::UInt128:
5782 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00005783 }
5784}
5785
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005786/// Whether this is a promotable bitfield reference according
Eli Friedman629ffb92009-08-20 04:21:42 +00005787/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
5788///
5789/// \returns the type this bit-field will promote to, or NULL if no
5790/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00005791QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00005792 if (E->isTypeDependent() || E->isValueDependent())
Eugene Zelenko7855e772018-04-03 00:11:50 +00005793 return {};
Richard Smith5b571672014-09-24 23:55:00 +00005794
Richard Smithaadb2542018-06-28 21:17:55 +00005795 // C++ [conv.prom]p5:
5796 // If the bit-field has an enumerated type, it is treated as any other
5797 // value of that type for promotion purposes.
5798 if (getLangOpts().CPlusPlus && E->getType()->isEnumeralType())
5799 return {};
5800
Richard Smith5b571672014-09-24 23:55:00 +00005801 // FIXME: We should not do this unless E->refersToBitField() is true. This
5802 // matters in C where getSourceBitField() will find bit-fields for various
5803 // cases where the source expression is not a bit-field designator.
5804
John McCalld25db7e2013-05-06 21:39:12 +00005805 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman629ffb92009-08-20 04:21:42 +00005806 if (!Field)
Eugene Zelenko7855e772018-04-03 00:11:50 +00005807 return {};
Eli Friedman629ffb92009-08-20 04:21:42 +00005808
5809 QualType FT = Field->getType();
5810
Richard Smithcaf33902011-10-10 18:28:20 +00005811 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00005812 uint64_t IntSize = getTypeSize(IntTy);
Richard Smith5b571672014-09-24 23:55:00 +00005813 // C++ [conv.prom]p5:
5814 // A prvalue for an integral bit-field can be converted to a prvalue of type
5815 // int if int can represent all the values of the bit-field; otherwise, it
5816 // can be converted to unsigned int if unsigned int can represent all the
5817 // values of the bit-field. If the bit-field is larger yet, no integral
5818 // promotion applies to it.
5819 // C11 6.3.1.1/2:
5820 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
5821 // If an int can represent all values of the original type (as restricted by
5822 // the width, for a bit-field), the value is converted to an int; otherwise,
5823 // it is converted to an unsigned int.
5824 //
5825 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
5826 // We perform that promotion here to match GCC and C++.
Richard Smithaadb2542018-06-28 21:17:55 +00005827 // FIXME: C does not permit promotion of an enum bit-field whose rank is
5828 // greater than that of 'int'. We perform that promotion to match GCC.
Eli Friedman629ffb92009-08-20 04:21:42 +00005829 if (BitWidth < IntSize)
5830 return IntTy;
5831
5832 if (BitWidth == IntSize)
5833 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
5834
Richard Smithaadb2542018-06-28 21:17:55 +00005835 // Bit-fields wider than int are not subject to promotions, and therefore act
Richard Smith5b571672014-09-24 23:55:00 +00005836 // like the base type. GCC has some weird bugs in this area that we
5837 // deliberately do not follow (GCC follows a pre-standard resolution to
5838 // C's DR315 which treats bit-width as being part of the type, and this leaks
5839 // into their semantics in some cases).
Eugene Zelenko7855e772018-04-03 00:11:50 +00005840 return {};
Eli Friedman629ffb92009-08-20 04:21:42 +00005841}
5842
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005843/// getPromotedIntegerType - Returns the type that Promotable will
5844/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
5845/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00005846QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005847 assert(!Promotable.isNull());
5848 assert(Promotable->isPromotableIntegerType());
Eugene Zelenko7855e772018-04-03 00:11:50 +00005849 if (const auto *ET = Promotable->getAs<EnumType>())
John McCall56774992009-12-09 09:09:27 +00005850 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00005851
Eugene Zelenko7855e772018-04-03 00:11:50 +00005852 if (const auto *BT = Promotable->getAs<BuiltinType>()) {
Eli Friedman3f37c1c2011-10-26 07:22:48 +00005853 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
5854 // (3.9.1) can be converted to a prvalue of the first of the following
5855 // types that can represent all the values of its underlying type:
5856 // int, unsigned int, long int, unsigned long int, long long int, or
5857 // unsigned long long int [...]
5858 // FIXME: Is there some better way to compute this?
5859 if (BT->getKind() == BuiltinType::WChar_S ||
5860 BT->getKind() == BuiltinType::WChar_U ||
Richard Smith3a8244d2018-05-01 05:02:45 +00005861 BT->getKind() == BuiltinType::Char8 ||
Eli Friedman3f37c1c2011-10-26 07:22:48 +00005862 BT->getKind() == BuiltinType::Char16 ||
5863 BT->getKind() == BuiltinType::Char32) {
5864 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
5865 uint64_t FromSize = getTypeSize(BT);
5866 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
5867 LongLongTy, UnsignedLongLongTy };
5868 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
5869 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
5870 if (FromSize < ToSize ||
5871 (FromSize == ToSize &&
5872 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
5873 return PromoteTypes[Idx];
5874 }
5875 llvm_unreachable("char type should fit into long long");
5876 }
5877 }
5878
5879 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005880 if (Promotable->isSignedIntegerType())
5881 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00005882 uint64_t PromotableSize = getIntWidth(Promotable);
5883 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005884 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
5885 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
5886}
5887
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005888/// Recurses in pointer/array types until it finds an objc retainable
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00005889/// type and returns its ownership.
5890Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
5891 while (!T.isNull()) {
5892 if (T.getObjCLifetime() != Qualifiers::OCL_None)
5893 return T.getObjCLifetime();
5894 if (T->isArrayType())
5895 T = getBaseElementType(T);
Eugene Zelenko7855e772018-04-03 00:11:50 +00005896 else if (const auto *PT = T->getAs<PointerType>())
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00005897 T = PT->getPointeeType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00005898 else if (const auto *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00005899 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00005900 else
5901 break;
5902 }
5903
5904 return Qualifiers::OCL_None;
5905}
5906
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005907static const Type *getIntegerTypeForEnum(const EnumType *ET) {
5908 // Incomplete enum types are not treated as integer types.
5909 // FIXME: In C++, enum types are never integer types.
5910 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
5911 return ET->getDecl()->getIntegerType().getTypePtr();
Craig Topper36250ad2014-05-12 05:36:57 +00005912 return nullptr;
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005913}
5914
Mike Stump11289f42009-09-09 15:08:12 +00005915/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005916/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00005917/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00005918int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00005919 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
5920 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005921
5922 // Unwrap enums to their underlying type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00005923 if (const auto *ET = dyn_cast<EnumType>(LHSC))
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005924 LHSC = getIntegerTypeForEnum(ET);
Eugene Zelenko7855e772018-04-03 00:11:50 +00005925 if (const auto *ET = dyn_cast<EnumType>(RHSC))
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005926 RHSC = getIntegerTypeForEnum(ET);
5927
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005928 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00005929
Chris Lattner76a00cf2008-04-06 22:59:24 +00005930 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
5931 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00005932
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005933 unsigned LHSRank = getIntegerRank(LHSC);
5934 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00005935
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005936 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
5937 if (LHSRank == RHSRank) return 0;
5938 return LHSRank > RHSRank ? 1 : -1;
5939 }
Mike Stump11289f42009-09-09 15:08:12 +00005940
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005941 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
5942 if (LHSUnsigned) {
5943 // If the unsigned [LHS] type is larger, return it.
5944 if (LHSRank >= RHSRank)
5945 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00005946
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005947 // If the signed type can represent all values of the unsigned type, it
5948 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00005949 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005950 return -1;
5951 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00005952
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005953 // If the unsigned [RHS] type is larger, return it.
5954 if (RHSRank >= LHSRank)
5955 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00005956
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005957 // If the signed type can represent all values of the unsigned type, it
5958 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00005959 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005960 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00005961}
Anders Carlsson98f07902007-08-17 05:31:46 +00005962
Ben Langmuirf5416742016-02-04 00:55:24 +00005963TypedefDecl *ASTContext::getCFConstantStringDecl() const {
Saleem Abdulrasoolef9b88a2018-10-24 16:38:16 +00005964 if (CFConstantStringTypeDecl)
5965 return CFConstantStringTypeDecl;
Anders Carlsson6d417272009-11-14 21:45:58 +00005966
Saleem Abdulrasoolef9b88a2018-10-24 16:38:16 +00005967 assert(!CFConstantStringTagDecl &&
5968 "tag and typedef should be initialized together");
5969 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
5970 CFConstantStringTagDecl->startDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00005971
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00005972 struct {
5973 QualType Type;
5974 const char *Name;
5975 } Fields[5];
5976 unsigned Count = 0;
Mike Stump11289f42009-09-09 15:08:12 +00005977
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00005978 /// Objective-C ABI
5979 ///
5980 /// typedef struct __NSConstantString_tag {
Saleem Abdulrasool1f6c41f2018-10-27 06:12:52 +00005981 /// const int *isa;
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00005982 /// int flags;
5983 /// const char *str;
5984 /// long length;
5985 /// } __NSConstantString;
5986 ///
5987 /// Swift ABI (4.1, 4.2)
5988 ///
5989 /// typedef struct __NSConstantString_tag {
5990 /// uintptr_t _cfisa;
5991 /// uintptr_t _swift_rc;
5992 /// _Atomic(uint64_t) _cfinfoa;
5993 /// const char *_ptr;
5994 /// uint32_t _length;
5995 /// } __NSConstantString;
5996 ///
5997 /// Swift ABI (5.0)
5998 ///
5999 /// typedef struct __NSConstantString_tag {
6000 /// uintptr_t _cfisa;
6001 /// uintptr_t _swift_rc;
6002 /// _Atomic(uint64_t) _cfinfoa;
6003 /// const char *_ptr;
6004 /// uintptr_t _length;
6005 /// } __NSConstantString;
6006
6007 const auto CFRuntime = getLangOpts().CFRuntime;
6008 if (static_cast<unsigned>(CFRuntime) <
6009 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) {
6010 Fields[Count++] = { getPointerType(IntTy.withConst()), "isa" };
6011 Fields[Count++] = { IntTy, "flags" };
6012 Fields[Count++] = { getPointerType(CharTy.withConst()), "str" };
6013 Fields[Count++] = { LongTy, "length" };
6014 } else {
6015 Fields[Count++] = { getUIntPtrType(), "_cfisa" };
6016 Fields[Count++] = { getUIntPtrType(), "_swift_rc" };
6017 Fields[Count++] = { getFromTargetType(Target->getUInt64Type()), "_swift_rc" };
6018 Fields[Count++] = { getPointerType(CharTy.withConst()), "_ptr" };
6019 if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 ||
6020 CFRuntime == LangOptions::CoreFoundationABI::Swift4_2)
6021 Fields[Count++] = { IntTy, "_ptr" };
6022 else
6023 Fields[Count++] = { getUIntPtrType(), "_ptr" };
6024 }
Douglas Gregor91f84212008-12-11 16:49:14 +00006025
Saleem Abdulrasoolef9b88a2018-10-24 16:38:16 +00006026 // Create fields
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00006027 for (unsigned i = 0; i < Count; ++i) {
Saleem Abdulrasoolef9b88a2018-10-24 16:38:16 +00006028 FieldDecl *Field =
6029 FieldDecl::Create(*this, CFConstantStringTagDecl, SourceLocation(),
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00006030 SourceLocation(), &Idents.get(Fields[i].Name),
6031 Fields[i].Type, /*TInfo=*/nullptr,
Saleem Abdulrasoolef9b88a2018-10-24 16:38:16 +00006032 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
6033 Field->setAccess(AS_public);
6034 CFConstantStringTagDecl->addDecl(Field);
Anders Carlsson98f07902007-08-17 05:31:46 +00006035 }
Mike Stump11289f42009-09-09 15:08:12 +00006036
Saleem Abdulrasoolef9b88a2018-10-24 16:38:16 +00006037 CFConstantStringTagDecl->completeDefinition();
6038 // This type is designed to be compatible with NSConstantString, but cannot
6039 // use the same name, since NSConstantString is an interface.
6040 auto tagType = getTagDeclType(CFConstantStringTagDecl);
6041 CFConstantStringTypeDecl =
6042 buildImplicitTypedef(tagType, "__NSConstantString");
6043
Quentin Colombet043406b2016-02-03 22:41:00 +00006044 return CFConstantStringTypeDecl;
6045}
6046
Ben Langmuirf5416742016-02-04 00:55:24 +00006047RecordDecl *ASTContext::getCFConstantStringTagDecl() const {
6048 if (!CFConstantStringTagDecl)
6049 getCFConstantStringDecl(); // Build the tag and the typedef.
6050 return CFConstantStringTagDecl;
6051}
6052
Quentin Colombet043406b2016-02-03 22:41:00 +00006053// getCFConstantStringType - Return the type used for constant CFStrings.
6054QualType ASTContext::getCFConstantStringType() const {
Ben Langmuirf5416742016-02-04 00:55:24 +00006055 return getTypedefType(getCFConstantStringDecl());
Gabor Greif412af032007-09-11 15:32:40 +00006056}
Anders Carlsson87c149b2007-10-11 01:00:40 +00006057
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00006058QualType ASTContext::getObjCSuperType() const {
6059 if (ObjCSuperType.isNull()) {
Alp Toker2dea15b2013-12-17 01:22:38 +00006060 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00006061 TUDecl->addDecl(ObjCSuperTypeDecl);
6062 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
6063 }
6064 return ObjCSuperType;
6065}
6066
Douglas Gregor512b0772009-04-23 22:29:11 +00006067void ASTContext::setCFConstantStringType(QualType T) {
Simon Pilgrim9588ae72019-10-03 21:47:42 +00006068 const auto *TD = T->castAs<TypedefType>();
Ben Langmuirf5416742016-02-04 00:55:24 +00006069 CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl());
Eugene Zelenko7855e772018-04-03 00:11:50 +00006070 const auto *TagType =
Simon Pilgrim9588ae72019-10-03 21:47:42 +00006071 CFConstantStringTypeDecl->getUnderlyingType()->castAs<RecordType>();
Ben Langmuirf5416742016-02-04 00:55:24 +00006072 CFConstantStringTagDecl = TagType->getDecl();
Douglas Gregor512b0772009-04-23 22:29:11 +00006073}
6074
Jay Foad39c79802011-01-12 09:06:06 +00006075QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00006076 if (BlockDescriptorType)
6077 return getTagDeclType(BlockDescriptorType);
6078
Alp Toker2dea15b2013-12-17 01:22:38 +00006079 RecordDecl *RD;
Mike Stumpd0153282009-10-20 02:12:22 +00006080 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00006081 RD = buildImplicitRecord("__block_descriptor");
6082 RD->startDefinition();
6083
Mike Stumpd0153282009-10-20 02:12:22 +00006084 QualType FieldTypes[] = {
6085 UnsignedLongTy,
6086 UnsignedLongTy,
6087 };
6088
Craig Topperd6d31ac2013-07-15 08:24:27 +00006089 static const char *const FieldNames[] = {
Mike Stumpd0153282009-10-20 02:12:22 +00006090 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00006091 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00006092 };
6093
6094 for (size_t i = 0; i < 2; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00006095 FieldDecl *Field = FieldDecl::Create(
6096 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00006097 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
6098 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00006099 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00006100 RD->addDecl(Field);
Mike Stumpd0153282009-10-20 02:12:22 +00006101 }
6102
Alp Toker2dea15b2013-12-17 01:22:38 +00006103 RD->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00006104
Alp Toker2dea15b2013-12-17 01:22:38 +00006105 BlockDescriptorType = RD;
Mike Stumpd0153282009-10-20 02:12:22 +00006106
6107 return getTagDeclType(BlockDescriptorType);
6108}
6109
Jay Foad39c79802011-01-12 09:06:06 +00006110QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00006111 if (BlockDescriptorExtendedType)
6112 return getTagDeclType(BlockDescriptorExtendedType);
6113
Alp Toker2dea15b2013-12-17 01:22:38 +00006114 RecordDecl *RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00006115 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00006116 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
6117 RD->startDefinition();
6118
Mike Stumpe1b19ba2009-10-22 00:49:09 +00006119 QualType FieldTypes[] = {
6120 UnsignedLongTy,
6121 UnsignedLongTy,
6122 getPointerType(VoidPtrTy),
6123 getPointerType(VoidPtrTy)
6124 };
6125
Craig Topperd6d31ac2013-07-15 08:24:27 +00006126 static const char *const FieldNames[] = {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00006127 "reserved",
6128 "Size",
6129 "CopyFuncPtr",
6130 "DestroyFuncPtr"
6131 };
6132
6133 for (size_t i = 0; i < 4; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00006134 FieldDecl *Field = FieldDecl::Create(
6135 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00006136 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
6137 /*BitWidth=*/nullptr,
Alp Toker2dea15b2013-12-17 01:22:38 +00006138 /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00006139 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00006140 RD->addDecl(Field);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00006141 }
6142
Alp Toker2dea15b2013-12-17 01:22:38 +00006143 RD->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00006144
Alp Toker2dea15b2013-12-17 01:22:38 +00006145 BlockDescriptorExtendedType = RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00006146 return getTagDeclType(BlockDescriptorExtendedType);
6147}
6148
Sven van Haastregt3bb7eaf2017-12-06 10:11:28 +00006149TargetInfo::OpenCLTypeKind ASTContext::getOpenCLTypeKind(const Type *T) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006150 const auto *BT = dyn_cast<BuiltinType>(T);
Sven van Haastregt3bb7eaf2017-12-06 10:11:28 +00006151
6152 if (!BT) {
6153 if (isa<PipeType>(T))
6154 return TargetInfo::OCLTK_Pipe;
6155
6156 return TargetInfo::OCLTK_Default;
6157 }
6158
6159 switch (BT->getKind()) {
6160#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6161 case BuiltinType::Id: \
6162 return TargetInfo::OCLTK_Image;
6163#include "clang/Basic/OpenCLImageTypes.def"
6164
6165 case BuiltinType::OCLClkEvent:
6166 return TargetInfo::OCLTK_ClkEvent;
6167
6168 case BuiltinType::OCLEvent:
6169 return TargetInfo::OCLTK_Event;
6170
6171 case BuiltinType::OCLQueue:
6172 return TargetInfo::OCLTK_Queue;
6173
6174 case BuiltinType::OCLReserveID:
6175 return TargetInfo::OCLTK_ReserveID;
6176
6177 case BuiltinType::OCLSampler:
6178 return TargetInfo::OCLTK_Sampler;
6179
6180 default:
6181 return TargetInfo::OCLTK_Default;
6182 }
6183}
6184
6185LangAS ASTContext::getOpenCLTypeAddrSpace(const Type *T) const {
6186 return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
6187}
6188
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006189/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
6190/// requires copy/dispose. Note that this must match the logic
6191/// in buildByrefHelpers.
6192bool ASTContext::BlockRequiresCopying(QualType Ty,
6193 const VarDecl *D) {
6194 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
Akira Hatanaka9978da32018-08-10 15:09:24 +00006195 const Expr *copyExpr = getBlockVarCopyInit(D).getCopyExpr();
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006196 if (!copyExpr && record->hasTrivialDestructor()) return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00006197
Mike Stump94967902009-10-21 18:16:27 +00006198 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00006199 }
Fangrui Song6907ce22018-07-30 19:24:48 +00006200
Akira Hatanaka7275da02018-02-28 07:15:55 +00006201 // The block needs copy/destroy helpers if Ty is non-trivial to destructively
6202 // move or destroy.
6203 if (Ty.isNonTrivialToPrimitiveDestructiveMove() || Ty.isDestructedType())
6204 return true;
6205
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006206 if (!Ty->isObjCRetainableType()) return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00006207
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006208 Qualifiers qs = Ty.getQualifiers();
Fangrui Song6907ce22018-07-30 19:24:48 +00006209
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006210 // If we have lifetime, that dominates.
6211 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006212 switch (lifetime) {
6213 case Qualifiers::OCL_None: llvm_unreachable("impossible");
Fangrui Song6907ce22018-07-30 19:24:48 +00006214
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006215 // These are just bits as far as the runtime is concerned.
6216 case Qualifiers::OCL_ExplicitNone:
6217 case Qualifiers::OCL_Autoreleasing:
6218 return false;
Akira Hatanaka7275da02018-02-28 07:15:55 +00006219
6220 // These cases should have been taken care of when checking the type's
6221 // non-triviality.
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006222 case Qualifiers::OCL_Weak:
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006223 case Qualifiers::OCL_Strong:
Akira Hatanaka7275da02018-02-28 07:15:55 +00006224 llvm_unreachable("impossible");
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006225 }
6226 llvm_unreachable("fell out of lifetime switch!");
6227 }
6228 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
6229 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00006230}
6231
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006232bool ASTContext::getByrefLifetime(QualType Ty,
6233 Qualifiers::ObjCLifetime &LifeTime,
6234 bool &HasByrefExtendedLayout) const {
Erik Pilkingtonfa983902018-10-30 20:31:30 +00006235 if (!getLangOpts().ObjC ||
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006236 getLangOpts().getGC() != LangOptions::NonGC)
6237 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00006238
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006239 HasByrefExtendedLayout = false;
Fariborz Jahanianf762b722012-12-11 19:58:01 +00006240 if (Ty->isRecordType()) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006241 HasByrefExtendedLayout = true;
6242 LifeTime = Qualifiers::OCL_None;
John McCall460ce582015-10-22 18:38:17 +00006243 } else if ((LifeTime = Ty.getObjCLifetime())) {
6244 // Honor the ARC qualifiers.
6245 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
6246 // The MRR rule.
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006247 LifeTime = Qualifiers::OCL_ExplicitNone;
John McCall460ce582015-10-22 18:38:17 +00006248 } else {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006249 LifeTime = Qualifiers::OCL_None;
John McCall460ce582015-10-22 18:38:17 +00006250 }
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006251 return true;
6252}
6253
Douglas Gregorbab8a962011-09-08 01:46:34 +00006254TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
6255 if (!ObjCInstanceTypeDecl)
Alp Toker56b5cc92013-12-15 10:36:26 +00006256 ObjCInstanceTypeDecl =
6257 buildImplicitTypedef(getObjCIdType(), "instancetype");
Douglas Gregorbab8a962011-09-08 01:46:34 +00006258 return ObjCInstanceTypeDecl;
6259}
6260
Anders Carlsson18acd442007-10-29 06:33:42 +00006261// This returns true if a type has been typedefed to BOOL:
6262// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00006263static bool isTypeTypedefedAsBOOL(QualType T) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006264 if (const auto *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00006265 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
6266 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00006267
Anders Carlssond8499822007-10-29 05:01:08 +00006268 return false;
6269}
6270
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006271/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006272/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00006273CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00006274 if (!type->isIncompleteArrayType() && type->isIncompleteType())
6275 return CharUnits::Zero();
Fangrui Song6907ce22018-07-30 19:24:48 +00006276
Ken Dyck40775002010-01-11 17:06:35 +00006277 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00006278
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006279 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00006280 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00006281 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006282 // Treat arrays as pointers, since that's how they're passed in.
6283 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00006284 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00006285 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00006286}
6287
Hans Wennborg56fc62b2014-07-17 20:25:23 +00006288bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
David Majnemer3f021502015-10-08 04:53:31 +00006289 return getTargetInfo().getCXXABI().isMicrosoft() &&
6290 VD->isStaticDataMember() &&
Hans Wennborgb18da9b2018-02-20 12:43:02 +00006291 VD->getType()->isIntegralOrEnumerationType() &&
David Majnemerfac52432015-10-19 23:22:49 +00006292 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
Hans Wennborg56fc62b2014-07-17 20:25:23 +00006293}
6294
Richard Smithd9b90092016-07-02 01:32:16 +00006295ASTContext::InlineVariableDefinitionKind
6296ASTContext::getInlineVariableDefinitionKind(const VarDecl *VD) const {
6297 if (!VD->isInline())
6298 return InlineVariableDefinitionKind::None;
6299
6300 // In almost all cases, it's a weak definition.
6301 auto *First = VD->getFirstDecl();
Richard Smith8910fe62017-10-23 03:58:34 +00006302 if (First->isInlineSpecified() || !First->isStaticDataMember())
Richard Smithd9b90092016-07-02 01:32:16 +00006303 return InlineVariableDefinitionKind::Weak;
6304
6305 // If there's a file-context declaration in this translation unit, it's a
6306 // non-discardable definition.
6307 for (auto *D : VD->redecls())
Richard Smith8910fe62017-10-23 03:58:34 +00006308 if (D->getLexicalDeclContext()->isFileContext() &&
6309 !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr()))
Richard Smithd9b90092016-07-02 01:32:16 +00006310 return InlineVariableDefinitionKind::Strong;
6311
6312 // If we've not seen one yet, we don't know.
6313 return InlineVariableDefinitionKind::WeakUnknown;
6314}
6315
Eugene Zelenko7855e772018-04-03 00:11:50 +00006316static std::string charUnitsToString(const CharUnits &CU) {
Ken Dyck40775002010-01-11 17:06:35 +00006317 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006318}
6319
John McCall351762c2011-02-07 10:33:21 +00006320/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00006321/// declaration.
John McCall351762c2011-02-07 10:33:21 +00006322std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
6323 std::string S;
6324
David Chisnall950a9512009-11-17 19:33:30 +00006325 const BlockDecl *Decl = Expr->getBlockDecl();
6326 QualType BlockTy =
Simon Pilgrimeed4b122019-10-02 11:48:06 +00006327 Expr->getType()->castAs<BlockPointerType>()->getPointeeType();
6328 QualType BlockReturnTy = BlockTy->castAs<FunctionType>()->getReturnType();
David Chisnall950a9512009-11-17 19:33:30 +00006329 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00006330 if (getLangOpts().EncodeExtendedBlockSig)
Simon Pilgrimeed4b122019-10-02 11:48:06 +00006331 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, BlockReturnTy, S,
6332 true /*Extended*/);
Fariborz Jahanian64223e62012-11-14 23:11:38 +00006333 else
Simon Pilgrimeed4b122019-10-02 11:48:06 +00006334 getObjCEncodingForType(BlockReturnTy, S);
David Chisnall950a9512009-11-17 19:33:30 +00006335 // Compute size of all parameters.
6336 // Start with computing size of a pointer in number of bytes.
6337 // FIXME: There might(should) be a better way of doing this computation!
Ken Dyck40775002010-01-11 17:06:35 +00006338 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
6339 CharUnits ParmOffset = PtrSize;
David Majnemer59f77922016-06-24 04:05:48 +00006340 for (auto PI : Decl->parameters()) {
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00006341 QualType PType = PI->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00006342 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00006343 if (sz.isZero())
6344 continue;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00006345 assert(sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00006346 ParmOffset += sz;
6347 }
6348 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00006349 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00006350 // Block pointer and offset.
6351 S += "@?0";
Fangrui Song6907ce22018-07-30 19:24:48 +00006352
David Chisnall950a9512009-11-17 19:33:30 +00006353 // Argument types.
6354 ParmOffset = PtrSize;
David Majnemer59f77922016-06-24 04:05:48 +00006355 for (auto PVDecl : Decl->parameters()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00006356 QualType PType = PVDecl->getOriginalType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00006357 if (const auto *AT =
6358 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
David Chisnall950a9512009-11-17 19:33:30 +00006359 // Use array's original type only if it has known number of
6360 // elements.
6361 if (!isa<ConstantArrayType>(AT))
6362 PType = PVDecl->getType();
6363 } else if (PType->isFunctionType())
6364 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00006365 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00006366 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
6367 S, true /*Extended*/);
6368 else
6369 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00006370 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00006371 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00006372 }
John McCall351762c2011-02-07 10:33:21 +00006373
6374 return S;
David Chisnall950a9512009-11-17 19:33:30 +00006375}
6376
John McCall843dfcc2016-11-29 21:57:00 +00006377std::string
6378ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const {
6379 std::string S;
David Chisnall50e4eba2010-12-30 14:05:53 +00006380 // Encode result type.
Alp Toker314cc812014-01-25 16:55:45 +00006381 getObjCEncodingForType(Decl->getReturnType(), S);
David Chisnall50e4eba2010-12-30 14:05:53 +00006382 CharUnits ParmOffset;
6383 // Compute size of all parameters.
David Majnemer59f77922016-06-24 04:05:48 +00006384 for (auto PI : Decl->parameters()) {
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00006385 QualType PType = PI->getType();
David Chisnall50e4eba2010-12-30 14:05:53 +00006386 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00006387 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00006388 continue;
Fangrui Song6907ce22018-07-30 19:24:48 +00006389
6390 assert(sz.isPositive() &&
John McCall843dfcc2016-11-29 21:57:00 +00006391 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00006392 ParmOffset += sz;
6393 }
6394 S += charUnitsToString(ParmOffset);
6395 ParmOffset = CharUnits::Zero();
6396
6397 // Argument types.
David Majnemer59f77922016-06-24 04:05:48 +00006398 for (auto PVDecl : Decl->parameters()) {
David Chisnall50e4eba2010-12-30 14:05:53 +00006399 QualType PType = PVDecl->getOriginalType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00006400 if (const auto *AT =
6401 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
David Chisnall50e4eba2010-12-30 14:05:53 +00006402 // Use array's original type only if it has known number of
6403 // elements.
6404 if (!isa<ConstantArrayType>(AT))
6405 PType = PVDecl->getType();
6406 } else if (PType->isFunctionType())
6407 PType = PVDecl->getType();
6408 getObjCEncodingForType(PType, S);
6409 S += charUnitsToString(ParmOffset);
6410 ParmOffset += getObjCEncodingTypeSize(PType);
6411 }
Fangrui Song6907ce22018-07-30 19:24:48 +00006412
John McCall843dfcc2016-11-29 21:57:00 +00006413 return S;
David Chisnall50e4eba2010-12-30 14:05:53 +00006414}
6415
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006416/// getObjCEncodingForMethodParameter - Return the encoded type for a single
Fangrui Song6907ce22018-07-30 19:24:48 +00006417/// method parameter or return type. If Extended, include class names and
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006418/// block object types.
6419void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
6420 QualType T, std::string& S,
6421 bool Extended) const {
6422 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
6423 getObjCEncodingForTypeQualifier(QT, S);
6424 // Encode parameter type.
Nico Weber2e9591c2019-05-14 12:32:37 +00006425 ObjCEncOptions Options = ObjCEncOptions()
6426 .setExpandPointedToStructures()
6427 .setExpandStructures()
6428 .setIsOutermostType();
6429 if (Extended)
6430 Options.setEncodeBlockParameters().setEncodeClassNames();
6431 getObjCEncodingForTypeImpl(T, S, Options, /*Field=*/nullptr);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006432}
6433
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006434/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006435/// declaration.
John McCall843dfcc2016-11-29 21:57:00 +00006436std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
6437 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00006438 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006439 // Encode return type.
John McCall843dfcc2016-11-29 21:57:00 +00006440 std::string S;
Alp Toker314cc812014-01-25 16:55:45 +00006441 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
6442 Decl->getReturnType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006443 // Compute size of all parameters.
6444 // Start with computing size of a pointer in number of bytes.
6445 // FIXME: There might(should) be a better way of doing this computation!
Ken Dyck40775002010-01-11 17:06:35 +00006446 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006447 // The first two arguments (self and _cmd) are pointers; account for
6448 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00006449 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00006450 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00006451 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00006452 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00006453 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00006454 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00006455 continue;
Fangrui Song6907ce22018-07-30 19:24:48 +00006456
6457 assert(sz.isPositive() &&
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00006458 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006459 ParmOffset += sz;
6460 }
Ken Dyck40775002010-01-11 17:06:35 +00006461 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006462 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00006463 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00006464
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006465 // Argument types.
6466 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00006467 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00006468 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00006469 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00006470 QualType PType = PVDecl->getOriginalType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00006471 if (const auto *AT =
6472 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
Steve Naroffe4e55d22009-04-14 00:03:58 +00006473 // Use array's original type only if it has known number of
6474 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00006475 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00006476 PType = PVDecl->getType();
6477 } else if (PType->isFunctionType())
6478 PType = PVDecl->getType();
Fangrui Song6907ce22018-07-30 19:24:48 +00006479 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006480 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00006481 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00006482 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006483 }
Fangrui Song6907ce22018-07-30 19:24:48 +00006484
John McCall843dfcc2016-11-29 21:57:00 +00006485 return S;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006486}
6487
Fariborz Jahaniandad96302014-01-22 19:02:20 +00006488ObjCPropertyImplDecl *
6489ASTContext::getObjCPropertyImplDeclForPropertyDecl(
6490 const ObjCPropertyDecl *PD,
6491 const Decl *Container) const {
6492 if (!Container)
Craig Topper36250ad2014-05-12 05:36:57 +00006493 return nullptr;
Eugene Zelenko7855e772018-04-03 00:11:50 +00006494 if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) {
Aaron Ballmand85eff42014-03-14 15:02:45 +00006495 for (auto *PID : CID->property_impls())
6496 if (PID->getPropertyDecl() == PD)
6497 return PID;
Craig Topper36250ad2014-05-12 05:36:57 +00006498 } else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006499 const auto *OID = cast<ObjCImplementationDecl>(Container);
Craig Topper36250ad2014-05-12 05:36:57 +00006500 for (auto *PID : OID->property_impls())
6501 if (PID->getPropertyDecl() == PD)
6502 return PID;
6503 }
6504 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00006505}
6506
Daniel Dunbar4932b362008-08-28 04:38:10 +00006507/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00006508/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00006509/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
6510/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00006511/// Property attributes are stored as a comma-delimited C string. The simple
6512/// attributes readonly and bycopy are encoded as single characters. The
6513/// parametrized attributes, getter=name, setter=name, and ivar=name, are
6514/// encoded as single characters, followed by an identifier. Property types
6515/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00006516/// these attributes are defined by the following enumeration:
6517/// @code
6518/// enum PropertyAttributes {
6519/// kPropertyReadOnly = 'R', // property is read-only.
6520/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
6521/// kPropertyByref = '&', // property is a reference to the value last assigned
6522/// kPropertyDynamic = 'D', // property is dynamic
6523/// kPropertyGetter = 'G', // followed by getter selector name
6524/// kPropertySetter = 'S', // followed by setter selector name
6525/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00006526/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00006527/// kPropertyWeak = 'W' // 'weak' property
6528/// kPropertyStrong = 'P' // property GC'able
6529/// kPropertyNonAtomic = 'N' // property non-atomic
6530/// };
6531/// @endcode
John McCall843dfcc2016-11-29 21:57:00 +00006532std::string
6533ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
6534 const Decl *Container) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00006535 // Collect information from the property implementation decl(s).
6536 bool Dynamic = false;
Craig Topper36250ad2014-05-12 05:36:57 +00006537 ObjCPropertyImplDecl *SynthesizePID = nullptr;
Daniel Dunbar4932b362008-08-28 04:38:10 +00006538
Fariborz Jahaniandad96302014-01-22 19:02:20 +00006539 if (ObjCPropertyImplDecl *PropertyImpDecl =
6540 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
6541 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
6542 Dynamic = true;
6543 else
6544 SynthesizePID = PropertyImpDecl;
Daniel Dunbar4932b362008-08-28 04:38:10 +00006545 }
6546
6547 // FIXME: This is not very efficient.
John McCall843dfcc2016-11-29 21:57:00 +00006548 std::string S = "T";
Daniel Dunbar4932b362008-08-28 04:38:10 +00006549
6550 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00006551 // GCC has some special rules regarding encoding of properties which
6552 // closely resembles encoding of ivars.
Joe Groff98ac7d22014-07-07 22:25:15 +00006553 getObjCEncodingForPropertyType(PD->getType(), S);
Daniel Dunbar4932b362008-08-28 04:38:10 +00006554
6555 if (PD->isReadOnly()) {
6556 S += ",R";
Nico Weber4e8626f2013-05-08 23:47:40 +00006557 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
6558 S += ",C";
6559 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
6560 S += ",&";
Fariborz Jahanian33079ee2014-04-02 22:49:42 +00006561 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
6562 S += ",W";
Daniel Dunbar4932b362008-08-28 04:38:10 +00006563 } else {
6564 switch (PD->getSetterKind()) {
6565 case ObjCPropertyDecl::Assign: break;
6566 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00006567 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00006568 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00006569 }
6570 }
6571
6572 // It really isn't clear at all what this means, since properties
6573 // are "dynamic by default".
6574 if (Dynamic)
6575 S += ",D";
6576
Fariborz Jahanian218c6302009-01-20 19:14:18 +00006577 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
6578 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00006579
Daniel Dunbar4932b362008-08-28 04:38:10 +00006580 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
6581 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00006582 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00006583 }
6584
6585 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
6586 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00006587 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00006588 }
6589
6590 if (SynthesizePID) {
6591 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
6592 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00006593 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00006594 }
6595
6596 // FIXME: OBJCGC: weak & strong
John McCall843dfcc2016-11-29 21:57:00 +00006597 return S;
Daniel Dunbar4932b362008-08-28 04:38:10 +00006598}
6599
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006600/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00006601/// Another legacy compatibility encoding: 32-bit longs are encoded as
6602/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006603/// 'i' or 'I' instead if encoding a struct field, or a pointer!
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006604void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00006605 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006606 if (const auto *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00006607 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006608 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00006609 else
Jay Foad39c79802011-01-12 09:06:06 +00006610 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006611 PointeeTy = IntTy;
6612 }
6613 }
6614}
6615
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00006616void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006617 const FieldDecl *Field,
6618 QualType *NotEncodedT) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00006619 // We follow the behavior of gcc, expanding structures which are
6620 // directly pointed to, and expanding embedded structures. Note that
6621 // these rules are sufficient to prevent recursive encoding of the
6622 // same type.
Nico Weber2e9591c2019-05-14 12:32:37 +00006623 getObjCEncodingForTypeImpl(T, S,
6624 ObjCEncOptions()
6625 .setExpandPointedToStructures()
6626 .setExpandStructures()
6627 .setIsOutermostType(),
6628 Field, NotEncodedT);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00006629}
6630
Joe Groff98ac7d22014-07-07 22:25:15 +00006631void ASTContext::getObjCEncodingForPropertyType(QualType T,
6632 std::string& S) const {
6633 // Encode result type.
6634 // GCC has some special rules regarding encoding of properties which
6635 // closely resembles encoding of ivars.
Nico Weber2e9591c2019-05-14 12:32:37 +00006636 getObjCEncodingForTypeImpl(T, S,
6637 ObjCEncOptions()
6638 .setExpandPointedToStructures()
6639 .setExpandStructures()
6640 .setIsOutermostType()
6641 .setEncodingProperty(),
6642 /*Field=*/nullptr);
Joe Groff98ac7d22014-07-07 22:25:15 +00006643}
6644
Richard Sandifordeb485fb2019-08-09 08:52:54 +00006645static char getObjCEncodingForPrimitiveType(const ASTContext *C,
6646 const BuiltinType *BT) {
6647 BuiltinType::Kind kind = BT->getKind();
John McCall393a78d2012-12-20 02:45:14 +00006648 switch (kind) {
David Chisnallb190a2c2010-06-04 01:10:52 +00006649 case BuiltinType::Void: return 'v';
6650 case BuiltinType::Bool: return 'B';
Richard Smith3a8244d2018-05-01 05:02:45 +00006651 case BuiltinType::Char8:
David Chisnallb190a2c2010-06-04 01:10:52 +00006652 case BuiltinType::Char_U:
6653 case BuiltinType::UChar: return 'C';
John McCall393a78d2012-12-20 02:45:14 +00006654 case BuiltinType::Char16:
David Chisnallb190a2c2010-06-04 01:10:52 +00006655 case BuiltinType::UShort: return 'S';
John McCall393a78d2012-12-20 02:45:14 +00006656 case BuiltinType::Char32:
David Chisnallb190a2c2010-06-04 01:10:52 +00006657 case BuiltinType::UInt: return 'I';
6658 case BuiltinType::ULong:
John McCall393a78d2012-12-20 02:45:14 +00006659 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00006660 case BuiltinType::UInt128: return 'T';
6661 case BuiltinType::ULongLong: return 'Q';
6662 case BuiltinType::Char_S:
6663 case BuiltinType::SChar: return 'c';
6664 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00006665 case BuiltinType::WChar_S:
6666 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00006667 case BuiltinType::Int: return 'i';
6668 case BuiltinType::Long:
John McCall393a78d2012-12-20 02:45:14 +00006669 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00006670 case BuiltinType::LongLong: return 'q';
6671 case BuiltinType::Int128: return 't';
6672 case BuiltinType::Float: return 'f';
6673 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00006674 case BuiltinType::LongDouble: return 'D';
John McCall393a78d2012-12-20 02:45:14 +00006675 case BuiltinType::NullPtr: return '*'; // like char*
6676
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00006677 case BuiltinType::Float16:
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00006678 case BuiltinType::Float128:
John McCall393a78d2012-12-20 02:45:14 +00006679 case BuiltinType::Half:
Leonard Chanf921d852018-06-04 16:07:52 +00006680 case BuiltinType::ShortAccum:
6681 case BuiltinType::Accum:
6682 case BuiltinType::LongAccum:
6683 case BuiltinType::UShortAccum:
6684 case BuiltinType::UAccum:
6685 case BuiltinType::ULongAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00006686 case BuiltinType::ShortFract:
6687 case BuiltinType::Fract:
6688 case BuiltinType::LongFract:
6689 case BuiltinType::UShortFract:
6690 case BuiltinType::UFract:
6691 case BuiltinType::ULongFract:
6692 case BuiltinType::SatShortAccum:
6693 case BuiltinType::SatAccum:
6694 case BuiltinType::SatLongAccum:
6695 case BuiltinType::SatUShortAccum:
6696 case BuiltinType::SatUAccum:
6697 case BuiltinType::SatULongAccum:
6698 case BuiltinType::SatShortFract:
6699 case BuiltinType::SatFract:
6700 case BuiltinType::SatLongFract:
6701 case BuiltinType::SatUShortFract:
6702 case BuiltinType::SatUFract:
6703 case BuiltinType::SatULongFract:
John McCall393a78d2012-12-20 02:45:14 +00006704 // FIXME: potentially need @encodes for these!
6705 return ' ';
6706
Richard Sandifordeb485fb2019-08-09 08:52:54 +00006707#define SVE_TYPE(Name, Id, SingletonId) \
6708 case BuiltinType::Id:
6709#include "clang/Basic/AArch64SVEACLETypes.def"
6710 {
6711 DiagnosticsEngine &Diags = C->getDiagnostics();
6712 unsigned DiagID = Diags.getCustomDiagID(
6713 DiagnosticsEngine::Error, "cannot yet @encode type %0");
6714 Diags.Report(DiagID) << BT->getName(C->getPrintingPolicy());
6715 return ' ';
6716 }
6717
John McCall393a78d2012-12-20 02:45:14 +00006718 case BuiltinType::ObjCId:
6719 case BuiltinType::ObjCClass:
6720 case BuiltinType::ObjCSel:
6721 llvm_unreachable("@encoding ObjC primitive type");
6722
6723 // OpenCL and placeholder types don't need @encodings.
Alexey Bader954ba212016-04-08 13:40:33 +00006724#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6725 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00006726#include "clang/Basic/OpenCLImageTypes.def"
Andrew Savonichev3fee3512018-11-08 11:25:41 +00006727#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6728 case BuiltinType::Id:
6729#include "clang/Basic/OpenCLExtensionTypes.def"
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006730 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00006731 case BuiltinType::OCLClkEvent:
6732 case BuiltinType::OCLQueue:
Alexey Bader9c8453f2015-09-15 11:18:52 +00006733 case BuiltinType::OCLReserveID:
Guy Benyei61054192013-02-07 10:55:47 +00006734 case BuiltinType::OCLSampler:
John McCall393a78d2012-12-20 02:45:14 +00006735 case BuiltinType::Dependent:
6736#define BUILTIN_TYPE(KIND, ID)
6737#define PLACEHOLDER_TYPE(KIND, ID) \
6738 case BuiltinType::KIND:
6739#include "clang/AST/BuiltinTypes.def"
6740 llvm_unreachable("invalid builtin type for @encode");
David Chisnallb190a2c2010-06-04 01:10:52 +00006741 }
David Blaikie5a6a0202013-01-09 17:48:41 +00006742 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnallb190a2c2010-06-04 01:10:52 +00006743}
6744
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006745static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
6746 EnumDecl *Enum = ET->getDecl();
Fangrui Song6907ce22018-07-30 19:24:48 +00006747
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006748 // The encoding of an non-fixed enum type is always 'i', regardless of size.
6749 if (!Enum->isFixed())
6750 return 'i';
Fangrui Song6907ce22018-07-30 19:24:48 +00006751
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006752 // The encoding of a fixed enum type matches its fixed underlying type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00006753 const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>();
Richard Sandifordeb485fb2019-08-09 08:52:54 +00006754 return getObjCEncodingForPrimitiveType(C, BT);
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006755}
6756
Jay Foad39c79802011-01-12 09:06:06 +00006757static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00006758 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00006759 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00006760 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00006761 // The NeXT runtime encodes bit fields as b followed by the number of bits.
6762 // The GNU runtime requires more information; bitfields are encoded as b,
6763 // then the offset (in bits) of the first element, then the type of the
6764 // bitfield, then the size in bits. For example, in this structure:
6765 //
6766 // struct
6767 // {
6768 // int integer;
6769 // int flags:2;
6770 // };
6771 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
6772 // runtime, but b32i2 for the GNU runtime. The reason for this extra
6773 // information is not especially sensible, but we're stuck with it for
6774 // compatibility with GCC, although providing it breaks anything that
6775 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00006776 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
Akira Hatanaka4b1c4842017-06-27 04:34:04 +00006777 uint64_t Offset;
6778
6779 if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) {
6780 Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), nullptr,
6781 IVD);
6782 } else {
6783 const RecordDecl *RD = FD->getParent();
6784 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
6785 Offset = RL.getFieldOffset(FD->getFieldIndex());
6786 }
6787
6788 S += llvm::utostr(Offset);
6789
Eugene Zelenko7855e772018-04-03 00:11:50 +00006790 if (const auto *ET = T->getAs<EnumType>())
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006791 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall393a78d2012-12-20 02:45:14 +00006792 else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006793 const auto *BT = T->castAs<BuiltinType>();
Richard Sandifordeb485fb2019-08-09 08:52:54 +00006794 S += getObjCEncodingForPrimitiveType(Ctx, BT);
John McCall393a78d2012-12-20 02:45:14 +00006795 }
David Chisnallb190a2c2010-06-04 01:10:52 +00006796 }
Richard Smithcaf33902011-10-10 18:28:20 +00006797 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00006798}
6799
Daniel Dunbar07d07852009-10-18 21:17:35 +00006800// FIXME: Use SmallString for accumulating string.
Nico Weber2e9591c2019-05-14 12:32:37 +00006801void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S,
6802 const ObjCEncOptions Options,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00006803 const FieldDecl *FD,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006804 QualType *NotEncodedT) const {
John McCall393a78d2012-12-20 02:45:14 +00006805 CanQualType CT = getCanonicalType(T);
6806 switch (CT->getTypeClass()) {
6807 case Type::Builtin:
6808 case Type::Enum:
Chris Lattnere7cabb92009-07-13 00:10:46 +00006809 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00006810 return EncodeBitField(this, S, T, FD);
Eugene Zelenko7855e772018-04-03 00:11:50 +00006811 if (const auto *BT = dyn_cast<BuiltinType>(CT))
Richard Sandifordeb485fb2019-08-09 08:52:54 +00006812 S += getObjCEncodingForPrimitiveType(this, BT);
John McCall393a78d2012-12-20 02:45:14 +00006813 else
6814 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnere7cabb92009-07-13 00:10:46 +00006815 return;
Mike Stump11289f42009-09-09 15:08:12 +00006816
John McCall393a78d2012-12-20 02:45:14 +00006817 case Type::Complex: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006818 const auto *CT = T->castAs<ComplexType>();
Anders Carlsson39b2e132009-04-09 21:55:45 +00006819 S += 'j';
Nico Weber2e9591c2019-05-14 12:32:37 +00006820 getObjCEncodingForTypeImpl(CT->getElementType(), S, ObjCEncOptions(),
6821 /*Field=*/nullptr);
Chris Lattnere7cabb92009-07-13 00:10:46 +00006822 return;
6823 }
John McCall393a78d2012-12-20 02:45:14 +00006824
6825 case Type::Atomic: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006826 const auto *AT = T->castAs<AtomicType>();
John McCall393a78d2012-12-20 02:45:14 +00006827 S += 'A';
Nico Weber2e9591c2019-05-14 12:32:37 +00006828 getObjCEncodingForTypeImpl(AT->getValueType(), S, ObjCEncOptions(),
6829 /*Field=*/nullptr);
John McCall393a78d2012-12-20 02:45:14 +00006830 return;
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00006831 }
John McCall393a78d2012-12-20 02:45:14 +00006832
6833 // encoding for pointer or reference types.
6834 case Type::Pointer:
6835 case Type::LValueReference:
6836 case Type::RValueReference: {
6837 QualType PointeeTy;
6838 if (isa<PointerType>(CT)) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006839 const auto *PT = T->castAs<PointerType>();
John McCall393a78d2012-12-20 02:45:14 +00006840 if (PT->isObjCSelType()) {
6841 S += ':';
6842 return;
6843 }
6844 PointeeTy = PT->getPointeeType();
6845 } else {
6846 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
6847 }
6848
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006849 bool isReadOnly = false;
6850 // For historical/compatibility reasons, the read-only qualifier of the
6851 // pointee gets emitted _before_ the '^'. The read-only qualifier of
6852 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00006853 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00006854 if (isa<TypedefType>(T.getTypePtr())) {
Nico Weber2e9591c2019-05-14 12:32:37 +00006855 if (Options.IsOutermostType() && T.isConstQualified()) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006856 isReadOnly = true;
6857 S += 'r';
6858 }
Nico Weber2e9591c2019-05-14 12:32:37 +00006859 } else if (Options.IsOutermostType()) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006860 QualType P = PointeeTy;
Simon Pilgrimd834f1f2019-10-03 15:08:20 +00006861 while (auto PT = P->getAs<PointerType>())
6862 P = PT->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006863 if (P.isConstQualified()) {
6864 isReadOnly = true;
6865 S += 'r';
6866 }
6867 }
6868 if (isReadOnly) {
6869 // Another legacy compatibility encoding. Some ObjC qualifier and type
6870 // combinations need to be rearranged.
6871 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006872 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00006873 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006874 }
Mike Stump11289f42009-09-09 15:08:12 +00006875
Anders Carlssond8499822007-10-29 05:01:08 +00006876 if (PointeeTy->isCharType()) {
6877 // char pointer types should be encoded as '*' unless it is a
6878 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00006879 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00006880 S += '*';
6881 return;
6882 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00006883 } else if (const auto *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00006884 // GCC binary compat: Need to convert "struct objc_class *" to "#".
6885 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
6886 S += '#';
6887 return;
6888 }
6889 // GCC binary compat: Need to convert "struct objc_object *" to "@".
6890 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
6891 S += '@';
6892 return;
6893 }
6894 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00006895 }
Anders Carlssond8499822007-10-29 05:01:08 +00006896 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006897 getLegacyIntegralTypeEncoding(PointeeTy);
6898
Nico Weber2e9591c2019-05-14 12:32:37 +00006899 ObjCEncOptions NewOptions;
6900 if (Options.ExpandPointedToStructures())
6901 NewOptions.setExpandStructures();
6902 getObjCEncodingForTypeImpl(PointeeTy, S, NewOptions,
6903 /*Field=*/nullptr, NotEncodedT);
Chris Lattnere7cabb92009-07-13 00:10:46 +00006904 return;
6905 }
John McCall393a78d2012-12-20 02:45:14 +00006906
6907 case Type::ConstantArray:
6908 case Type::IncompleteArray:
6909 case Type::VariableArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006910 const auto *AT = cast<ArrayType>(CT);
John McCall393a78d2012-12-20 02:45:14 +00006911
Nico Weber2e9591c2019-05-14 12:32:37 +00006912 if (isa<IncompleteArrayType>(AT) && !Options.IsStructField()) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00006913 // Incomplete arrays are encoded as a pointer to the array element.
6914 S += '^';
6915
Nico Weber2e9591c2019-05-14 12:32:37 +00006916 getObjCEncodingForTypeImpl(
6917 AT->getElementType(), S,
6918 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD);
Anders Carlssond05f44b2009-02-22 01:38:57 +00006919 } else {
6920 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00006921
Eugene Zelenko7855e772018-04-03 00:11:50 +00006922 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
Fariborz Jahanianf0dc11a2013-06-04 16:04:37 +00006923 S += llvm::utostr(CAT->getSize().getZExtValue());
6924 else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00006925 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006926 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
6927 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00006928 S += '0';
6929 }
Mike Stump11289f42009-09-09 15:08:12 +00006930
Nico Weberdf129332019-05-10 13:56:56 +00006931 getObjCEncodingForTypeImpl(
6932 AT->getElementType(), S,
Nico Weber2e9591c2019-05-14 12:32:37 +00006933 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD,
6934 NotEncodedT);
Anders Carlssond05f44b2009-02-22 01:38:57 +00006935 S += ']';
6936 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006937 return;
6938 }
Mike Stump11289f42009-09-09 15:08:12 +00006939
John McCall393a78d2012-12-20 02:45:14 +00006940 case Type::FunctionNoProto:
6941 case Type::FunctionProto:
Anders Carlssondf4cc612007-10-30 00:06:20 +00006942 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00006943 return;
Mike Stump11289f42009-09-09 15:08:12 +00006944
John McCall393a78d2012-12-20 02:45:14 +00006945 case Type::Record: {
6946 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00006947 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00006948 // Anonymous structures print as '?'
6949 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
6950 S += II->getName();
Eugene Zelenko7855e772018-04-03 00:11:50 +00006951 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
Fariborz Jahanianc5158202010-05-07 00:28:49 +00006952 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00006953 llvm::raw_string_ostream OS(S);
Serge Pavlov03e672c2017-11-28 16:14:14 +00006954 printTemplateArgumentList(OS, TemplateArgs.asArray(),
6955 getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00006956 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00006957 } else {
6958 S += '?';
6959 }
Nico Weber2e9591c2019-05-14 12:32:37 +00006960 if (Options.ExpandStructures()) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00006961 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006962 if (!RDecl->isUnion()) {
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006963 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006964 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006965 for (const auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006966 if (FD) {
6967 S += '"';
6968 S += Field->getNameAsString();
6969 S += '"';
6970 }
Mike Stump11289f42009-09-09 15:08:12 +00006971
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006972 // Special case bit-fields.
6973 if (Field->isBitField()) {
Nico Weberdf129332019-05-10 13:56:56 +00006974 getObjCEncodingForTypeImpl(Field->getType(), S,
Nico Weber2e9591c2019-05-14 12:32:37 +00006975 ObjCEncOptions().setExpandStructures(),
6976 Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006977 } else {
6978 QualType qt = Field->getType();
6979 getLegacyIntegralTypeEncoding(qt);
Nico Weberdf129332019-05-10 13:56:56 +00006980 getObjCEncodingForTypeImpl(
Nico Weber2e9591c2019-05-14 12:32:37 +00006981 qt, S,
6982 ObjCEncOptions().setExpandStructures().setIsStructField(), FD,
6983 NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006984 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00006985 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00006986 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00006987 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00006988 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00006989 return;
6990 }
Mike Stump11289f42009-09-09 15:08:12 +00006991
John McCall393a78d2012-12-20 02:45:14 +00006992 case Type::BlockPointer: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006993 const auto *BT = T->castAs<BlockPointerType>();
Steve Naroff49140cb2009-02-02 18:24:29 +00006994 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Nico Weber2e9591c2019-05-14 12:32:37 +00006995 if (Options.EncodeBlockParameters()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006996 const auto *FT = BT->getPointeeType()->castAs<FunctionType>();
Fangrui Song6907ce22018-07-30 19:24:48 +00006997
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006998 S += '<';
6999 // Block return type
Nico Weber2e9591c2019-05-14 12:32:37 +00007000 getObjCEncodingForTypeImpl(FT->getReturnType(), S,
7001 Options.forComponentType(), FD, NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00007002 // Block self
7003 S += "@?";
7004 // Block parameters
Eugene Zelenko7855e772018-04-03 00:11:50 +00007005 if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00007006 for (const auto &I : FPT->param_types())
Nico Weber2e9591c2019-05-14 12:32:37 +00007007 getObjCEncodingForTypeImpl(I, S, Options.forComponentType(), FD,
7008 NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00007009 }
7010 S += '>';
7011 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00007012 return;
7013 }
Mike Stump11289f42009-09-09 15:08:12 +00007014
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00007015 case Type::ObjCObject: {
7016 // hack to match legacy encoding of *id and *Class
7017 QualType Ty = getObjCObjectPointerType(CT);
7018 if (Ty->isObjCIdType()) {
7019 S += "{objc_object=}";
7020 return;
7021 }
7022 else if (Ty->isObjCClassType()) {
7023 S += "{objc_class=}";
7024 return;
7025 }
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00007026 // TODO: Double check to make sure this intentionally falls through.
Galina Kistanovaf87496d2017-06-03 06:31:42 +00007027 LLVM_FALLTHROUGH;
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00007028 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007029
John McCall393a78d2012-12-20 02:45:14 +00007030 case Type::ObjCInterface: {
7031 // Ignore protocol qualifiers when mangling at this level.
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00007032 // @encode(class_name)
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007033 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00007034 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00007035 S += OI->getObjCRuntimeNameAsString();
Nico Weber2e9591c2019-05-14 12:32:37 +00007036 if (Options.ExpandStructures()) {
Akira Hatanakafd0fb202016-08-17 19:42:22 +00007037 S += '=';
7038 SmallVector<const ObjCIvarDecl*, 32> Ivars;
7039 DeepCollectObjCIvars(OI, true, Ivars);
7040 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
George Burgess IV00f70bd2018-03-01 05:43:23 +00007041 const FieldDecl *Field = Ivars[i];
Akira Hatanakafd0fb202016-08-17 19:42:22 +00007042 if (Field->isBitField())
Nico Weberdf129332019-05-10 13:56:56 +00007043 getObjCEncodingForTypeImpl(Field->getType(), S,
Nico Weber2e9591c2019-05-14 12:32:37 +00007044 ObjCEncOptions().setExpandStructures(),
7045 Field);
Akira Hatanakaf3c89b12019-05-29 21:23:30 +00007046 else
7047 getObjCEncodingForTypeImpl(Field->getType(), S,
7048 ObjCEncOptions().setExpandStructures(), FD,
Nico Weber2e9591c2019-05-14 12:32:37 +00007049 NotEncodedT);
Akira Hatanakafd0fb202016-08-17 19:42:22 +00007050 }
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00007051 }
7052 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00007053 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00007054 }
Mike Stump11289f42009-09-09 15:08:12 +00007055
John McCall393a78d2012-12-20 02:45:14 +00007056 case Type::ObjCObjectPointer: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00007057 const auto *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00007058 if (OPT->isObjCIdType()) {
7059 S += '@';
7060 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00007061 }
Mike Stump11289f42009-09-09 15:08:12 +00007062
Steve Narofff0c86112009-10-28 22:03:49 +00007063 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
7064 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
Nico Weberdf129332019-05-10 13:56:56 +00007065 // Since this is a binary compatibility issue, need to consult with
7066 // runtime folks. Fortunately, this is a *very* obscure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00007067 S += '#';
7068 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00007069 }
Mike Stump11289f42009-09-09 15:08:12 +00007070
Chris Lattnere7cabb92009-07-13 00:10:46 +00007071 if (OPT->isObjCQualifiedIdType()) {
Nico Weber2e9591c2019-05-14 12:32:37 +00007072 getObjCEncodingForTypeImpl(
7073 getObjCIdType(), S,
7074 Options.keepingOnly(ObjCEncOptions()
7075 .setExpandPointedToStructures()
7076 .setExpandStructures()),
7077 FD);
7078 if (FD || Options.EncodingProperty() || Options.EncodeClassNames()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00007079 // Note that we do extended encoding of protocol qualifer list
7080 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00007081 S += '"';
Aaron Ballman83731462014-03-17 16:14:00 +00007082 for (const auto *I : OPT->quals()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00007083 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00007084 S += I->getObjCRuntimeNameAsString();
Steve Naroff7cae42b2009-07-10 23:34:53 +00007085 S += '>';
7086 }
7087 S += '"';
7088 }
7089 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00007090 }
Mike Stump11289f42009-09-09 15:08:12 +00007091
Chris Lattnere7cabb92009-07-13 00:10:46 +00007092 S += '@';
Fangrui Song6907ce22018-07-30 19:24:48 +00007093 if (OPT->getInterfaceDecl() &&
Nico Weber2e9591c2019-05-14 12:32:37 +00007094 (FD || Options.EncodingProperty() || Options.EncodeClassNames())) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00007095 S += '"';
Douglas Gregorb32684e2015-06-16 21:04:55 +00007096 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
Aaron Ballman83731462014-03-17 16:14:00 +00007097 for (const auto *I : OPT->quals()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00007098 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00007099 S += I->getObjCRuntimeNameAsString();
Chris Lattnere7cabb92009-07-13 00:10:46 +00007100 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00007101 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00007102 S += '"';
7103 }
7104 return;
7105 }
Mike Stump11289f42009-09-09 15:08:12 +00007106
John McCalla9e6e8d2010-05-17 23:56:34 +00007107 // gcc just blithely ignores member pointers.
Nico Weber2e9591c2019-05-14 12:32:37 +00007108 // FIXME: we should do better than that. 'M' is available.
John McCall393a78d2012-12-20 02:45:14 +00007109 case Type::MemberPointer:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00007110 // This matches gcc's encoding, even though technically it is insufficient.
7111 //FIXME. We should do a better job than gcc.
John McCall393a78d2012-12-20 02:45:14 +00007112 case Type::Vector:
7113 case Type::ExtVector:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00007114 // Until we have a coherent encoding of these three types, issue warning.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00007115 if (NotEncodedT)
7116 *NotEncodedT = T;
7117 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00007118
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00007119 // We could see an undeduced auto type here during error recovery.
7120 // Just ignore it.
Richard Smith27d807c2013-04-30 13:56:41 +00007121 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00007122 case Type::DeducedTemplateSpecialization:
Richard Smith27d807c2013-04-30 13:56:41 +00007123 return;
7124
Xiuli Pan9c14e282016-01-09 12:53:17 +00007125 case Type::Pipe:
John McCall393a78d2012-12-20 02:45:14 +00007126#define ABSTRACT_TYPE(KIND, BASE)
7127#define TYPE(KIND, BASE)
7128#define DEPENDENT_TYPE(KIND, BASE) \
7129 case Type::KIND:
7130#define NON_CANONICAL_TYPE(KIND, BASE) \
7131 case Type::KIND:
7132#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
7133 case Type::KIND:
John McCall36b12a82019-10-02 06:35:23 +00007134#include "clang/AST/TypeNodes.inc"
John McCall393a78d2012-12-20 02:45:14 +00007135 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00007136 }
John McCall393a78d2012-12-20 02:45:14 +00007137 llvm_unreachable("bad type kind!");
Anders Carlssond8499822007-10-29 05:01:08 +00007138}
7139
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007140void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
7141 std::string &S,
7142 const FieldDecl *FD,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00007143 bool includeVBases,
7144 QualType *NotEncodedT) const {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007145 assert(RDecl && "Expected non-null RecordDecl");
7146 assert(!RDecl->isUnion() && "Should not be called for unions");
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00007147 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007148 return;
7149
Eugene Zelenko7855e772018-04-03 00:11:50 +00007150 const auto *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007151 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
7152 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
7153
7154 if (CXXRec) {
Aaron Ballman574705e2014-03-13 15:41:46 +00007155 for (const auto &BI : CXXRec->bases()) {
7156 if (!BI.isVirtual()) {
7157 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00007158 if (base->isEmpty())
7159 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00007160 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007161 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
7162 std::make_pair(offs, base));
7163 }
7164 }
7165 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007166
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007167 unsigned i = 0;
Hans Wennborga302cd92014-08-21 16:06:57 +00007168 for (auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007169 uint64_t offs = layout.getFieldOffset(i);
7170 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Hans Wennborga302cd92014-08-21 16:06:57 +00007171 std::make_pair(offs, Field));
7172 ++i;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007173 }
7174
7175 if (CXXRec && includeVBases) {
Aaron Ballman445a9392014-03-13 16:15:17 +00007176 for (const auto &BI : CXXRec->vbases()) {
7177 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00007178 if (base->isEmpty())
7179 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00007180 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Eli Friedman1d24af82013-09-18 01:59:16 +00007181 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
7182 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00007183 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
7184 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007185 }
7186 }
7187
7188 CharUnits size;
7189 if (CXXRec) {
7190 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
7191 } else {
7192 size = layout.getSize();
7193 }
7194
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007195#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007196 uint64_t CurOffs = 0;
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007197#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007198 std::multimap<uint64_t, NamedDecl *>::iterator
7199 CurLayObj = FieldOrBaseOffsets.begin();
7200
Douglas Gregorf5d6c742012-04-27 22:30:01 +00007201 if (CXXRec && CXXRec->isDynamicClass() &&
7202 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007203 if (FD) {
7204 S += "\"_vptr$";
7205 std::string recname = CXXRec->getNameAsString();
7206 if (recname.empty()) recname = "?";
7207 S += recname;
7208 S += '"';
7209 }
7210 S += "^^?";
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007211#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007212 CurOffs += getTypeSize(VoidPtrTy);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007213#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007214 }
7215
7216 if (!RDecl->hasFlexibleArrayMember()) {
7217 // Mark the end of the structure.
7218 uint64_t offs = toBits(size);
7219 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Craig Topper36250ad2014-05-12 05:36:57 +00007220 std::make_pair(offs, nullptr));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007221 }
7222
7223 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007224#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007225 assert(CurOffs <= CurLayObj->first);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007226 if (CurOffs < CurLayObj->first) {
Fangrui Song6907ce22018-07-30 19:24:48 +00007227 uint64_t padding = CurLayObj->first - CurOffs;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007228 // FIXME: There doesn't seem to be a way to indicate in the encoding that
7229 // packing/alignment of members is different that normal, in which case
7230 // the encoding will be out-of-sync with the real layout.
7231 // If the runtime switches to just consider the size of types without
7232 // taking into account alignment, we could make padding explicit in the
7233 // encoding (e.g. using arrays of chars). The encoding strings would be
7234 // longer then though.
7235 CurOffs += padding;
7236 }
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007237#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007238
7239 NamedDecl *dcl = CurLayObj->second;
Craig Topper36250ad2014-05-12 05:36:57 +00007240 if (!dcl)
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007241 break; // reached end of structure.
7242
Eugene Zelenko7855e772018-04-03 00:11:50 +00007243 if (auto *base = dyn_cast<CXXRecordDecl>(dcl)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007244 // We expand the bases without their virtual bases since those are going
7245 // in the initial structure. Note that this differs from gcc which
7246 // expands virtual bases each time one is encountered in the hierarchy,
7247 // making the encoding type bigger than it really is.
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00007248 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
7249 NotEncodedT);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00007250 assert(!base->isEmpty());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007251#ifndef NDEBUG
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00007252 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007253#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007254 } else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00007255 const auto *field = cast<FieldDecl>(dcl);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007256 if (FD) {
7257 S += '"';
7258 S += field->getNameAsString();
7259 S += '"';
7260 }
7261
7262 if (field->isBitField()) {
7263 EncodeBitField(this, S, field->getType(), field);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007264#ifndef NDEBUG
Richard Smithcaf33902011-10-10 18:28:20 +00007265 CurOffs += field->getBitWidthValue(*this);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007266#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007267 } else {
7268 QualType qt = field->getType();
7269 getLegacyIntegralTypeEncoding(qt);
Nico Weberdf129332019-05-10 13:56:56 +00007270 getObjCEncodingForTypeImpl(
Nico Weber2e9591c2019-05-14 12:32:37 +00007271 qt, S, ObjCEncOptions().setExpandStructures().setIsStructField(),
7272 FD, NotEncodedT);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007273#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007274 CurOffs += getTypeSize(field->getType());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007275#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007276 }
7277 }
7278 }
7279}
7280
Mike Stump11289f42009-09-09 15:08:12 +00007281void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00007282 std::string& S) const {
7283 if (QT & Decl::OBJC_TQ_In)
7284 S += 'n';
7285 if (QT & Decl::OBJC_TQ_Inout)
7286 S += 'N';
7287 if (QT & Decl::OBJC_TQ_Out)
7288 S += 'o';
7289 if (QT & Decl::OBJC_TQ_Bycopy)
7290 S += 'O';
7291 if (QT & Decl::OBJC_TQ_Byref)
7292 S += 'R';
7293 if (QT & Decl::OBJC_TQ_Oneway)
7294 S += 'V';
7295}
7296
Douglas Gregor3ea72692011-08-12 05:46:01 +00007297TypedefDecl *ASTContext::getObjCIdDecl() const {
7298 if (!ObjCIdDecl) {
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00007299 QualType T = getObjCObjectType(ObjCBuiltinIdTy, {}, {});
Douglas Gregor3ea72692011-08-12 05:46:01 +00007300 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00007301 ObjCIdDecl = buildImplicitTypedef(T, "id");
Douglas Gregor3ea72692011-08-12 05:46:01 +00007302 }
Douglas Gregor3ea72692011-08-12 05:46:01 +00007303 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00007304}
7305
Douglas Gregor52e02802011-08-12 06:17:30 +00007306TypedefDecl *ASTContext::getObjCSelDecl() const {
7307 if (!ObjCSelDecl) {
Alp Toker56b5cc92013-12-15 10:36:26 +00007308 QualType T = getPointerType(ObjCBuiltinSelTy);
7309 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
Douglas Gregor52e02802011-08-12 06:17:30 +00007310 }
7311 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00007312}
7313
Douglas Gregor0a586182011-08-12 05:59:41 +00007314TypedefDecl *ASTContext::getObjCClassDecl() const {
7315 if (!ObjCClassDecl) {
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00007316 QualType T = getObjCObjectType(ObjCBuiltinClassTy, {}, {});
Douglas Gregor0a586182011-08-12 05:59:41 +00007317 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00007318 ObjCClassDecl = buildImplicitTypedef(T, "Class");
Douglas Gregor0a586182011-08-12 05:59:41 +00007319 }
Douglas Gregor0a586182011-08-12 05:59:41 +00007320 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00007321}
7322
Douglas Gregord53ae832012-01-17 18:09:05 +00007323ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
7324 if (!ObjCProtocolClassDecl) {
Fangrui Song6907ce22018-07-30 19:24:48 +00007325 ObjCProtocolClassDecl
7326 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
Douglas Gregord53ae832012-01-17 18:09:05 +00007327 SourceLocation(),
7328 &Idents.get("Protocol"),
Douglas Gregor85f3f952015-07-07 03:57:15 +00007329 /*typeParamList=*/nullptr,
Craig Topper36250ad2014-05-12 05:36:57 +00007330 /*PrevDecl=*/nullptr,
Fangrui Song6907ce22018-07-30 19:24:48 +00007331 SourceLocation(), true);
Douglas Gregord53ae832012-01-17 18:09:05 +00007332 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007333
Douglas Gregord53ae832012-01-17 18:09:05 +00007334 return ObjCProtocolClassDecl;
7335}
7336
Meador Inge5d3fb222012-06-16 03:34:49 +00007337//===----------------------------------------------------------------------===//
7338// __builtin_va_list Construction Functions
7339//===----------------------------------------------------------------------===//
7340
Charles Davisc7d5c942015-09-17 20:55:33 +00007341static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context,
7342 StringRef Name) {
7343 // typedef char* __builtin[_ms]_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00007344 QualType T = Context->getPointerType(Context->CharTy);
Charles Davisc7d5c942015-09-17 20:55:33 +00007345 return Context->buildImplicitTypedef(T, Name);
7346}
7347
7348static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
7349 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
7350}
7351
7352static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
7353 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007354}
7355
7356static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
7357 // typedef void* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00007358 QualType T = Context->getPointerType(Context->VoidTy);
7359 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007360}
7361
Tim Northover9bb857a2013-01-31 12:13:10 +00007362static TypedefDecl *
7363CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00007364 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00007365 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00007366 if (Context->getLangOpts().CPlusPlus) {
7367 // namespace std { struct __va_list {
7368 NamespaceDecl *NS;
7369 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
7370 Context->getTranslationUnitDecl(),
Craig Topper36250ad2014-05-12 05:36:57 +00007371 /*Inline*/ false, SourceLocation(),
Tim Northover9bb857a2013-01-31 12:13:10 +00007372 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00007373 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00007374 NS->setImplicit();
Tim Northover9bb857a2013-01-31 12:13:10 +00007375 VaListTagDecl->setDeclContext(NS);
Tim Northover9bb857a2013-01-31 12:13:10 +00007376 }
7377
7378 VaListTagDecl->startDefinition();
7379
7380 const size_t NumFields = 5;
7381 QualType FieldTypes[NumFields];
7382 const char *FieldNames[NumFields];
7383
7384 // void *__stack;
7385 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
7386 FieldNames[0] = "__stack";
7387
7388 // void *__gr_top;
7389 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
7390 FieldNames[1] = "__gr_top";
7391
7392 // void *__vr_top;
7393 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
7394 FieldNames[2] = "__vr_top";
7395
7396 // int __gr_offs;
7397 FieldTypes[3] = Context->IntTy;
7398 FieldNames[3] = "__gr_offs";
7399
7400 // int __vr_offs;
7401 FieldTypes[4] = Context->IntTy;
7402 FieldNames[4] = "__vr_offs";
7403
7404 // Create fields
7405 for (unsigned i = 0; i < NumFields; ++i) {
7406 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7407 VaListTagDecl,
7408 SourceLocation(),
7409 SourceLocation(),
7410 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00007411 FieldTypes[i], /*TInfo=*/nullptr,
7412 /*BitWidth=*/nullptr,
Tim Northover9bb857a2013-01-31 12:13:10 +00007413 /*Mutable=*/false,
7414 ICIS_NoInit);
7415 Field->setAccess(AS_public);
7416 VaListTagDecl->addDecl(Field);
7417 }
7418 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00007419 Context->VaListTagDecl = VaListTagDecl;
Tim Northover9bb857a2013-01-31 12:13:10 +00007420 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Tim Northover9bb857a2013-01-31 12:13:10 +00007421
7422 // } __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00007423 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00007424}
7425
Meador Inge5d3fb222012-06-16 03:34:49 +00007426static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
7427 // typedef struct __va_list_tag {
7428 RecordDecl *VaListTagDecl;
7429
Alp Toker2dea15b2013-12-17 01:22:38 +00007430 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00007431 VaListTagDecl->startDefinition();
7432
7433 const size_t NumFields = 5;
7434 QualType FieldTypes[NumFields];
7435 const char *FieldNames[NumFields];
7436
7437 // unsigned char gpr;
7438 FieldTypes[0] = Context->UnsignedCharTy;
7439 FieldNames[0] = "gpr";
7440
7441 // unsigned char fpr;
7442 FieldTypes[1] = Context->UnsignedCharTy;
7443 FieldNames[1] = "fpr";
7444
7445 // unsigned short reserved;
7446 FieldTypes[2] = Context->UnsignedShortTy;
7447 FieldNames[2] = "reserved";
7448
7449 // void* overflow_arg_area;
7450 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
7451 FieldNames[3] = "overflow_arg_area";
7452
7453 // void* reg_save_area;
7454 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
7455 FieldNames[4] = "reg_save_area";
7456
7457 // Create fields
7458 for (unsigned i = 0; i < NumFields; ++i) {
7459 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
7460 SourceLocation(),
7461 SourceLocation(),
7462 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00007463 FieldTypes[i], /*TInfo=*/nullptr,
7464 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00007465 /*Mutable=*/false,
7466 ICIS_NoInit);
7467 Field->setAccess(AS_public);
7468 VaListTagDecl->addDecl(Field);
7469 }
7470 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00007471 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00007472 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
7473
7474 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00007475 TypedefDecl *VaListTagTypedefDecl =
7476 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
7477
Meador Inge5d3fb222012-06-16 03:34:49 +00007478 QualType VaListTagTypedefType =
7479 Context->getTypedefType(VaListTagTypedefDecl);
7480
7481 // typedef __va_list_tag __builtin_va_list[1];
7482 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
7483 QualType VaListTagArrayType
7484 = Context->getConstantArrayType(VaListTagTypedefType,
Richard Smith772e2662019-10-04 01:25:59 +00007485 Size, nullptr, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00007486 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007487}
7488
7489static TypedefDecl *
7490CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00007491 // struct __va_list_tag {
Meador Inge5d3fb222012-06-16 03:34:49 +00007492 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00007493 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00007494 VaListTagDecl->startDefinition();
7495
7496 const size_t NumFields = 4;
7497 QualType FieldTypes[NumFields];
7498 const char *FieldNames[NumFields];
7499
7500 // unsigned gp_offset;
7501 FieldTypes[0] = Context->UnsignedIntTy;
7502 FieldNames[0] = "gp_offset";
7503
7504 // unsigned fp_offset;
7505 FieldTypes[1] = Context->UnsignedIntTy;
7506 FieldNames[1] = "fp_offset";
7507
7508 // void* overflow_arg_area;
7509 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
7510 FieldNames[2] = "overflow_arg_area";
7511
7512 // void* reg_save_area;
7513 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
7514 FieldNames[3] = "reg_save_area";
7515
7516 // Create fields
7517 for (unsigned i = 0; i < NumFields; ++i) {
7518 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7519 VaListTagDecl,
7520 SourceLocation(),
7521 SourceLocation(),
7522 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00007523 FieldTypes[i], /*TInfo=*/nullptr,
7524 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00007525 /*Mutable=*/false,
7526 ICIS_NoInit);
7527 Field->setAccess(AS_public);
7528 VaListTagDecl->addDecl(Field);
7529 }
7530 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00007531 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00007532 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
7533
Richard Smith9b88a4c2015-07-27 05:40:23 +00007534 // };
Alp Toker56b5cc92013-12-15 10:36:26 +00007535
Richard Smith9b88a4c2015-07-27 05:40:23 +00007536 // typedef struct __va_list_tag __builtin_va_list[1];
Meador Inge5d3fb222012-06-16 03:34:49 +00007537 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith772e2662019-10-04 01:25:59 +00007538 QualType VaListTagArrayType = Context->getConstantArrayType(
7539 VaListTagType, Size, nullptr, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00007540 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007541}
7542
7543static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
7544 // typedef int __builtin_va_list[4];
7545 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
Richard Smith772e2662019-10-04 01:25:59 +00007546 QualType IntArrayType = Context->getConstantArrayType(
7547 Context->IntTy, Size, nullptr, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00007548 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007549}
7550
Logan Chien57086ce2012-10-10 06:56:20 +00007551static TypedefDecl *
7552CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00007553 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00007554 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00007555 if (Context->getLangOpts().CPlusPlus) {
7556 // namespace std { struct __va_list {
7557 NamespaceDecl *NS;
7558 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
7559 Context->getTranslationUnitDecl(),
7560 /*Inline*/false, SourceLocation(),
7561 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00007562 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00007563 NS->setImplicit();
Logan Chien57086ce2012-10-10 06:56:20 +00007564 VaListDecl->setDeclContext(NS);
Logan Chien57086ce2012-10-10 06:56:20 +00007565 }
7566
7567 VaListDecl->startDefinition();
7568
7569 // void * __ap;
7570 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7571 VaListDecl,
7572 SourceLocation(),
7573 SourceLocation(),
7574 &Context->Idents.get("__ap"),
7575 Context->getPointerType(Context->VoidTy),
Craig Topper36250ad2014-05-12 05:36:57 +00007576 /*TInfo=*/nullptr,
7577 /*BitWidth=*/nullptr,
Logan Chien57086ce2012-10-10 06:56:20 +00007578 /*Mutable=*/false,
7579 ICIS_NoInit);
7580 Field->setAccess(AS_public);
7581 VaListDecl->addDecl(Field);
7582
7583 // };
7584 VaListDecl->completeDefinition();
Oleg Ranevskyyb88d2472016-03-30 21:30:30 +00007585 Context->VaListTagDecl = VaListDecl;
Logan Chien57086ce2012-10-10 06:56:20 +00007586
7587 // typedef struct __va_list __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00007588 QualType T = Context->getRecordType(VaListDecl);
7589 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00007590}
7591
Ulrich Weigand47445072013-05-06 16:26:41 +00007592static TypedefDecl *
7593CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00007594 // struct __va_list_tag {
Ulrich Weigand47445072013-05-06 16:26:41 +00007595 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00007596 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00007597 VaListTagDecl->startDefinition();
7598
7599 const size_t NumFields = 4;
7600 QualType FieldTypes[NumFields];
7601 const char *FieldNames[NumFields];
7602
7603 // long __gpr;
7604 FieldTypes[0] = Context->LongTy;
7605 FieldNames[0] = "__gpr";
7606
7607 // long __fpr;
7608 FieldTypes[1] = Context->LongTy;
7609 FieldNames[1] = "__fpr";
7610
7611 // void *__overflow_arg_area;
7612 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
7613 FieldNames[2] = "__overflow_arg_area";
7614
7615 // void *__reg_save_area;
7616 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
7617 FieldNames[3] = "__reg_save_area";
7618
7619 // Create fields
7620 for (unsigned i = 0; i < NumFields; ++i) {
7621 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7622 VaListTagDecl,
7623 SourceLocation(),
7624 SourceLocation(),
7625 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00007626 FieldTypes[i], /*TInfo=*/nullptr,
7627 /*BitWidth=*/nullptr,
Ulrich Weigand47445072013-05-06 16:26:41 +00007628 /*Mutable=*/false,
7629 ICIS_NoInit);
7630 Field->setAccess(AS_public);
7631 VaListTagDecl->addDecl(Field);
7632 }
7633 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00007634 Context->VaListTagDecl = VaListTagDecl;
Ulrich Weigand47445072013-05-06 16:26:41 +00007635 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Ulrich Weigand47445072013-05-06 16:26:41 +00007636
Richard Smith9b88a4c2015-07-27 05:40:23 +00007637 // };
Ulrich Weigand47445072013-05-06 16:26:41 +00007638
7639 // typedef __va_list_tag __builtin_va_list[1];
7640 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith772e2662019-10-04 01:25:59 +00007641 QualType VaListTagArrayType = Context->getConstantArrayType(
7642 VaListTagType, Size, nullptr, ArrayType::Normal, 0);
Ulrich Weigand47445072013-05-06 16:26:41 +00007643
Alp Toker56b5cc92013-12-15 10:36:26 +00007644 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Ulrich Weigand47445072013-05-06 16:26:41 +00007645}
7646
Meador Inge5d3fb222012-06-16 03:34:49 +00007647static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
7648 TargetInfo::BuiltinVaListKind Kind) {
7649 switch (Kind) {
7650 case TargetInfo::CharPtrBuiltinVaList:
7651 return CreateCharPtrBuiltinVaListDecl(Context);
7652 case TargetInfo::VoidPtrBuiltinVaList:
7653 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northover9bb857a2013-01-31 12:13:10 +00007654 case TargetInfo::AArch64ABIBuiltinVaList:
7655 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00007656 case TargetInfo::PowerABIBuiltinVaList:
7657 return CreatePowerABIBuiltinVaListDecl(Context);
7658 case TargetInfo::X86_64ABIBuiltinVaList:
7659 return CreateX86_64ABIBuiltinVaListDecl(Context);
7660 case TargetInfo::PNaClABIBuiltinVaList:
7661 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00007662 case TargetInfo::AAPCSABIBuiltinVaList:
7663 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigand47445072013-05-06 16:26:41 +00007664 case TargetInfo::SystemZBuiltinVaList:
7665 return CreateSystemZBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00007666 }
7667
7668 llvm_unreachable("Unhandled __builtin_va_list type kind");
7669}
7670
7671TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00007672 if (!BuiltinVaListDecl) {
Meador Inge5d3fb222012-06-16 03:34:49 +00007673 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
Alp Toker56b5cc92013-12-15 10:36:26 +00007674 assert(BuiltinVaListDecl->isImplicit());
7675 }
Meador Inge5d3fb222012-06-16 03:34:49 +00007676
7677 return BuiltinVaListDecl;
7678}
7679
Richard Smith9b88a4c2015-07-27 05:40:23 +00007680Decl *ASTContext::getVaListTagDecl() const {
7681 // Force the creation of VaListTagDecl by building the __builtin_va_list
Meador Ingecfb60902012-07-01 15:57:25 +00007682 // declaration.
Richard Smith9b88a4c2015-07-27 05:40:23 +00007683 if (!VaListTagDecl)
7684 (void)getBuiltinVaListDecl();
Meador Ingecfb60902012-07-01 15:57:25 +00007685
Richard Smith9b88a4c2015-07-27 05:40:23 +00007686 return VaListTagDecl;
Meador Ingecfb60902012-07-01 15:57:25 +00007687}
7688
Charles Davisc7d5c942015-09-17 20:55:33 +00007689TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const {
7690 if (!BuiltinMSVaListDecl)
7691 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
7692
7693 return BuiltinMSVaListDecl;
7694}
7695
Erich Keane41af9712018-04-16 21:30:08 +00007696bool ASTContext::canBuiltinBeRedeclared(const FunctionDecl *FD) const {
7697 return BuiltinInfo.canBeRedeclared(FD->getBuiltinID());
7698}
7699
Ted Kremenek1b0ea822008-01-07 19:49:32 +00007700void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00007701 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00007702 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00007703
Ted Kremenek1b0ea822008-01-07 19:49:32 +00007704 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00007705}
7706
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007707/// Retrieve the template name that corresponds to a non-empty
John McCalld28ae272009-12-02 08:04:21 +00007708/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00007709TemplateName
7710ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
7711 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00007712 unsigned size = End - Begin;
7713 assert(size > 1 && "set is not overloaded!");
7714
7715 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
7716 size * sizeof(FunctionTemplateDecl*));
Eugene Zelenko7855e772018-04-03 00:11:50 +00007717 auto *OT = new (memory) OverloadedTemplateStorage(size);
John McCalld28ae272009-12-02 08:04:21 +00007718
7719 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00007720 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00007721 NamedDecl *D = *I;
7722 assert(isa<FunctionTemplateDecl>(D) ||
Richard Smithef53a3e2018-06-06 16:36:56 +00007723 isa<UnresolvedUsingValueDecl>(D) ||
John McCalld28ae272009-12-02 08:04:21 +00007724 (isa<UsingShadowDecl>(D) &&
7725 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
7726 *Storage++ = D;
7727 }
7728
7729 return TemplateName(OT);
7730}
7731
Richard Smithb23c5e82019-05-09 03:31:27 +00007732/// Retrieve a template name representing an unqualified-id that has been
7733/// assumed to name a template for ADL purposes.
7734TemplateName ASTContext::getAssumedTemplateName(DeclarationName Name) const {
7735 auto *OT = new (*this) AssumedTemplateStorage(Name);
7736 return TemplateName(OT);
7737}
7738
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007739/// Retrieve the template name that represents a qualified
Douglas Gregordc572a32009-03-30 22:58:21 +00007740/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00007741TemplateName
7742ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
7743 bool TemplateKeyword,
7744 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00007745 assert(NNS && "Missing nested-name-specifier in qualified template name");
Fangrui Song6907ce22018-07-30 19:24:48 +00007746
Douglas Gregorc42075a2010-02-04 18:10:26 +00007747 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00007748 llvm::FoldingSetNodeID ID;
7749 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
7750
Craig Topper36250ad2014-05-12 05:36:57 +00007751 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00007752 QualifiedTemplateName *QTN =
7753 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7754 if (!QTN) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007755 QTN = new (*this, alignof(QualifiedTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007756 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00007757 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
7758 }
7759
7760 return TemplateName(QTN);
7761}
7762
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007763/// Retrieve the template name that represents a dependent
Douglas Gregordc572a32009-03-30 22:58:21 +00007764/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00007765TemplateName
7766ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
7767 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00007768 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00007769 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00007770
7771 llvm::FoldingSetNodeID ID;
7772 DependentTemplateName::Profile(ID, NNS, Name);
7773
Craig Topper36250ad2014-05-12 05:36:57 +00007774 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00007775 DependentTemplateName *QTN =
7776 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7777
7778 if (QTN)
7779 return TemplateName(QTN);
7780
7781 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
7782 if (CanonNNS == NNS) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007783 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007784 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00007785 } else {
7786 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007787 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007788 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00007789 DependentTemplateName *CheckQTN =
7790 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7791 assert(!CheckQTN && "Dependent type name canonicalization broken");
7792 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00007793 }
7794
7795 DependentTemplateNames.InsertNode(QTN, InsertPos);
7796 return TemplateName(QTN);
7797}
7798
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007799/// Retrieve the template name that represents a dependent
Douglas Gregor71395fa2009-11-04 00:56:37 +00007800/// template name such as \c MetaFun::template operator+.
Fangrui Song6907ce22018-07-30 19:24:48 +00007801TemplateName
Douglas Gregor71395fa2009-11-04 00:56:37 +00007802ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00007803 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00007804 assert((!NNS || NNS->isDependent()) &&
7805 "Nested name specifier must be dependent");
Fangrui Song6907ce22018-07-30 19:24:48 +00007806
Douglas Gregor71395fa2009-11-04 00:56:37 +00007807 llvm::FoldingSetNodeID ID;
7808 DependentTemplateName::Profile(ID, NNS, Operator);
Craig Topper36250ad2014-05-12 05:36:57 +00007809
7810 void *InsertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00007811 DependentTemplateName *QTN
7812 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Fangrui Song6907ce22018-07-30 19:24:48 +00007813
Douglas Gregor71395fa2009-11-04 00:56:37 +00007814 if (QTN)
7815 return TemplateName(QTN);
Fangrui Song6907ce22018-07-30 19:24:48 +00007816
Douglas Gregor71395fa2009-11-04 00:56:37 +00007817 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
7818 if (CanonNNS == NNS) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007819 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007820 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00007821 } else {
7822 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007823 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007824 DependentTemplateName(NNS, Operator, Canon);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007825
Douglas Gregorc42075a2010-02-04 18:10:26 +00007826 DependentTemplateName *CheckQTN
7827 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7828 assert(!CheckQTN && "Dependent template name canonicalization broken");
7829 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00007830 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007831
Douglas Gregor71395fa2009-11-04 00:56:37 +00007832 DependentTemplateNames.InsertNode(QTN, InsertPos);
7833 return TemplateName(QTN);
7834}
7835
Fangrui Song6907ce22018-07-30 19:24:48 +00007836TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00007837ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
7838 TemplateName replacement) const {
7839 llvm::FoldingSetNodeID ID;
7840 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00007841
7842 void *insertPos = nullptr;
John McCalld9dfe3a2011-06-30 08:33:18 +00007843 SubstTemplateTemplateParmStorage *subst
7844 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
Fangrui Song6907ce22018-07-30 19:24:48 +00007845
John McCalld9dfe3a2011-06-30 08:33:18 +00007846 if (!subst) {
7847 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
7848 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
7849 }
7850
7851 return TemplateName(subst);
7852}
7853
Fangrui Song6907ce22018-07-30 19:24:48 +00007854TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00007855ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
7856 const TemplateArgument &ArgPack) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00007857 auto &Self = const_cast<ASTContext &>(*this);
Douglas Gregor5590be02011-01-15 06:45:20 +00007858 llvm::FoldingSetNodeID ID;
7859 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00007860
7861 void *InsertPos = nullptr;
Douglas Gregor5590be02011-01-15 06:45:20 +00007862 SubstTemplateTemplateParmPackStorage *Subst
7863 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
Fangrui Song6907ce22018-07-30 19:24:48 +00007864
Douglas Gregor5590be02011-01-15 06:45:20 +00007865 if (!Subst) {
Fangrui Song6907ce22018-07-30 19:24:48 +00007866 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00007867 ArgPack.pack_size(),
7868 ArgPack.pack_begin());
7869 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
7870 }
7871
7872 return TemplateName(Subst);
7873}
7874
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007875/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00007876/// TargetInfo, produce the corresponding type. The unsigned @p Type
7877/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00007878CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007879 switch (Type) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00007880 case TargetInfo::NoInt: return {};
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00007881 case TargetInfo::SignedChar: return SignedCharTy;
7882 case TargetInfo::UnsignedChar: return UnsignedCharTy;
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007883 case TargetInfo::SignedShort: return ShortTy;
7884 case TargetInfo::UnsignedShort: return UnsignedShortTy;
7885 case TargetInfo::SignedInt: return IntTy;
7886 case TargetInfo::UnsignedInt: return UnsignedIntTy;
7887 case TargetInfo::SignedLong: return LongTy;
7888 case TargetInfo::UnsignedLong: return UnsignedLongTy;
7889 case TargetInfo::SignedLongLong: return LongLongTy;
7890 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
7891 }
7892
David Blaikie83d382b2011-09-23 05:06:16 +00007893 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007894}
Ted Kremenek77c51b22008-07-24 23:58:27 +00007895
7896//===----------------------------------------------------------------------===//
7897// Type Predicates.
7898//===----------------------------------------------------------------------===//
7899
Fariborz Jahanian96207692009-02-18 21:49:28 +00007900/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
7901/// garbage collection attribute.
7902///
John McCall553d45a2011-01-12 00:34:59 +00007903Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007904 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00007905 return Qualifiers::GCNone;
7906
Erik Pilkingtonfa983902018-10-30 20:31:30 +00007907 assert(getLangOpts().ObjC);
John McCall553d45a2011-01-12 00:34:59 +00007908 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
7909
7910 // Default behaviour under objective-C's gc is for ObjC pointers
7911 // (or pointers to them) be treated as though they were declared
7912 // as __strong.
7913 if (GCAttrs == Qualifiers::GCNone) {
7914 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
7915 return Qualifiers::Strong;
7916 else if (Ty->isPointerType())
Simon Pilgrimeed4b122019-10-02 11:48:06 +00007917 return getObjCGCAttrKind(Ty->castAs<PointerType>()->getPointeeType());
John McCall553d45a2011-01-12 00:34:59 +00007918 } else {
7919 // It's not valid to set GC attributes on anything that isn't a
7920 // pointer.
7921#ifndef NDEBUG
7922 QualType CT = Ty->getCanonicalTypeInternal();
Eugene Zelenko7855e772018-04-03 00:11:50 +00007923 while (const auto *AT = dyn_cast<ArrayType>(CT))
John McCall553d45a2011-01-12 00:34:59 +00007924 CT = AT->getElementType();
7925 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
7926#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00007927 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00007928 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00007929}
7930
Chris Lattner49af6a42008-04-07 06:51:04 +00007931//===----------------------------------------------------------------------===//
7932// Type Compatibility Testing
7933//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00007934
Mike Stump11289f42009-09-09 15:08:12 +00007935/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00007936/// compatible.
7937static bool areCompatVectorTypes(const VectorType *LHS,
7938 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00007939 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00007940 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00007941 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00007942}
7943
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007944bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
7945 QualType SecondVec) {
7946 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
7947 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
7948
7949 if (hasSameUnqualifiedType(FirstVec, SecondVec))
7950 return true;
7951
Bob Wilsone6aeebb2010-11-12 17:24:54 +00007952 // Treat Neon vector types and most AltiVec vector types as if they are the
7953 // equivalent GCC vector types.
Simon Pilgrimeed4b122019-10-02 11:48:06 +00007954 const auto *First = FirstVec->castAs<VectorType>();
7955 const auto *Second = SecondVec->castAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00007956 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007957 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00007958 First->getVectorKind() != VectorType::AltiVecPixel &&
7959 First->getVectorKind() != VectorType::AltiVecBool &&
7960 Second->getVectorKind() != VectorType::AltiVecPixel &&
7961 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007962 return true;
7963
7964 return false;
7965}
7966
Akira Hatanaka3f2c9912019-09-07 00:34:47 +00007967bool ASTContext::hasDirectOwnershipQualifier(QualType Ty) const {
7968 while (true) {
7969 // __strong id
7970 if (const AttributedType *Attr = dyn_cast<AttributedType>(Ty)) {
7971 if (Attr->getAttrKind() == attr::ObjCOwnership)
7972 return true;
7973
7974 Ty = Attr->getModifiedType();
7975
7976 // X *__strong (...)
7977 } else if (const ParenType *Paren = dyn_cast<ParenType>(Ty)) {
7978 Ty = Paren->getInnerType();
7979
7980 // We do not want to look through typedefs, typeof(expr),
7981 // typeof(type), or any other way that the type is somehow
7982 // abstracted.
7983 } else {
7984 return false;
7985 }
7986 }
7987}
7988
Steve Naroff8e6aee52009-07-23 01:01:38 +00007989//===----------------------------------------------------------------------===//
7990// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
7991//===----------------------------------------------------------------------===//
7992
7993/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
7994/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00007995bool
7996ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
7997 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00007998 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00007999 return true;
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00008000 for (auto *PI : rProto->protocols())
8001 if (ProtocolCompatibleWithProtocol(lProto, PI))
Steve Naroff8e6aee52009-07-23 01:01:38 +00008002 return true;
8003 return false;
8004}
8005
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00008006/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
8007/// Class<pr1, ...>.
James Y Knightc2ca0032019-09-21 22:31:28 +00008008bool ASTContext::ObjCQualifiedClassTypesAreCompatible(
8009 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs) {
8010 for (auto *lhsProto : lhs->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00008011 bool match = false;
James Y Knightc2ca0032019-09-21 22:31:28 +00008012 for (auto *rhsProto : rhs->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00008013 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
8014 match = true;
8015 break;
8016 }
8017 }
8018 if (!match)
8019 return false;
8020 }
8021 return true;
8022}
8023
Steve Naroff8e6aee52009-07-23 01:01:38 +00008024/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
8025/// ObjCQualifiedIDType.
James Y Knightc2ca0032019-09-21 22:31:28 +00008026bool ASTContext::ObjCQualifiedIdTypesAreCompatible(
8027 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs,
8028 bool compare) {
James Y Knightccc4d832019-10-17 15:27:04 +00008029 // Allow id<P..> and an 'id' in all cases.
8030 if (lhs->isObjCIdType() || rhs->isObjCIdType())
Steve Naroff8e6aee52009-07-23 01:01:38 +00008031 return true;
James Y Knightccc4d832019-10-17 15:27:04 +00008032
8033 // Don't allow id<P..> to convert to Class or Class<P..> in either direction.
8034 if (lhs->isObjCClassType() || lhs->isObjCQualifiedClassType() ||
8035 rhs->isObjCClassType() || rhs->isObjCQualifiedClassType())
8036 return false;
Steve Naroff8e6aee52009-07-23 01:01:38 +00008037
James Y Knightc2ca0032019-09-21 22:31:28 +00008038 if (lhs->isObjCQualifiedIdType()) {
8039 if (rhs->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00008040 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00008041 // make sure we check the class hierarchy.
James Y Knightc2ca0032019-09-21 22:31:28 +00008042 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
8043 for (auto *I : lhs->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00008044 // when comparing an id<P> on lhs with a static type on rhs,
8045 // see if static class implements all of id's protocols, directly or
8046 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00008047 if (!rhsID->ClassImplementsProtocol(I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00008048 return false;
8049 }
8050 }
8051 // If there are no qualifiers and no interface, we have an 'id'.
8052 return true;
8053 }
Mike Stump11289f42009-09-09 15:08:12 +00008054 // Both the right and left sides have qualifiers.
James Y Knightc2ca0032019-09-21 22:31:28 +00008055 for (auto *lhsProto : lhs->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00008056 bool match = false;
8057
8058 // when comparing an id<P> on lhs with a static type on rhs,
8059 // see if static class implements all of id's protocols, directly or
8060 // through its super class and categories.
James Y Knightc2ca0032019-09-21 22:31:28 +00008061 for (auto *rhsProto : rhs->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00008062 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
8063 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
8064 match = true;
8065 break;
8066 }
8067 }
Mike Stump11289f42009-09-09 15:08:12 +00008068 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00008069 // make sure we check the class hierarchy.
James Y Knightc2ca0032019-09-21 22:31:28 +00008070 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
8071 for (auto *I : lhs->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00008072 // when comparing an id<P> on lhs with a static type on rhs,
8073 // see if static class implements all of id's protocols, directly or
8074 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00008075 if (rhsID->ClassImplementsProtocol(I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00008076 match = true;
8077 break;
8078 }
8079 }
8080 }
8081 if (!match)
8082 return false;
8083 }
Mike Stump11289f42009-09-09 15:08:12 +00008084
Steve Naroff8e6aee52009-07-23 01:01:38 +00008085 return true;
8086 }
Mike Stump11289f42009-09-09 15:08:12 +00008087
James Y Knightc2ca0032019-09-21 22:31:28 +00008088 assert(rhs->isObjCQualifiedIdType() && "One of the LHS/RHS should be id<x>");
Steve Naroff8e6aee52009-07-23 01:01:38 +00008089
James Y Knightc2ca0032019-09-21 22:31:28 +00008090 if (lhs->getInterfaceType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00008091 // If both the right and left sides have qualifiers.
James Y Knightc2ca0032019-09-21 22:31:28 +00008092 for (auto *lhsProto : lhs->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00008093 bool match = false;
8094
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00008095 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00008096 // see if static class implements all of id's protocols, directly or
8097 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00008098 // First, lhs protocols in the qualifier list must be found, direct
8099 // or indirect in rhs's qualifier list or it is a mismatch.
James Y Knightc2ca0032019-09-21 22:31:28 +00008100 for (auto *rhsProto : rhs->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00008101 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
8102 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
8103 match = true;
8104 break;
8105 }
8106 }
8107 if (!match)
8108 return false;
8109 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008110
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00008111 // Static class's protocols, or its super class or category protocols
8112 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
James Y Knightc2ca0032019-09-21 22:31:28 +00008113 if (ObjCInterfaceDecl *lhsID = lhs->getInterfaceDecl()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00008114 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
8115 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
8116 // This is rather dubious but matches gcc's behavior. If lhs has
8117 // no type qualifier and its class has no static protocol(s)
8118 // assume that it is mismatch.
James Y Knightc2ca0032019-09-21 22:31:28 +00008119 if (LHSInheritedProtocols.empty() && lhs->qual_empty())
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00008120 return false;
Aaron Ballman83731462014-03-17 16:14:00 +00008121 for (auto *lhsProto : LHSInheritedProtocols) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00008122 bool match = false;
James Y Knightc2ca0032019-09-21 22:31:28 +00008123 for (auto *rhsProto : rhs->quals()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00008124 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
8125 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
8126 match = true;
8127 break;
8128 }
8129 }
8130 if (!match)
8131 return false;
8132 }
8133 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00008134 return true;
8135 }
8136 return false;
8137}
8138
Eli Friedman47f77112008-08-22 00:56:42 +00008139/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00008140/// compatible for assignment from RHS to LHS. This handles validation of any
8141/// protocol qualifiers on the LHS or RHS.
Steve Naroff7cae42b2009-07-10 23:34:53 +00008142bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
8143 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00008144 const ObjCObjectType* LHS = LHSOPT->getObjectType();
8145 const ObjCObjectType* RHS = RHSOPT->getObjectType();
8146
James Y Knightccc4d832019-10-17 15:27:04 +00008147 // If either type represents the built-in 'id' type, return true.
8148 if (LHS->isObjCUnqualifiedId() || RHS->isObjCUnqualifiedId())
Steve Naroff7cae42b2009-07-10 23:34:53 +00008149 return true;
8150
Douglas Gregorab209d82015-07-07 03:58:42 +00008151 // Function object that propagates a successful result or handles
8152 // __kindof types.
8153 auto finish = [&](bool succeeded) -> bool {
8154 if (succeeded)
8155 return true;
8156
8157 if (!RHS->isKindOfType())
8158 return false;
8159
8160 // Strip off __kindof and protocol qualifiers, then check whether
8161 // we can assign the other way.
8162 return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this),
8163 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
8164 };
8165
James Y Knightccc4d832019-10-17 15:27:04 +00008166 // Casts from or to id<P> are allowed when the other side has compatible
8167 // protocols.
Douglas Gregorab209d82015-07-07 03:58:42 +00008168 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
James Y Knightc2ca0032019-09-21 22:31:28 +00008169 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false));
Douglas Gregorab209d82015-07-07 03:58:42 +00008170 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008171
James Y Knightccc4d832019-10-17 15:27:04 +00008172 // Verify protocol compatibility for casts from Class<P1> to Class<P2>.
Douglas Gregorab209d82015-07-07 03:58:42 +00008173 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
James Y Knightc2ca0032019-09-21 22:31:28 +00008174 return finish(ObjCQualifiedClassTypesAreCompatible(LHSOPT, RHSOPT));
Douglas Gregorab209d82015-07-07 03:58:42 +00008175 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008176
James Y Knightccc4d832019-10-17 15:27:04 +00008177 // Casts from Class to Class<Foo>, or vice-versa, are allowed.
8178 if (LHS->isObjCClass() && RHS->isObjCClass()) {
8179 return true;
8180 }
8181
John McCall8b07ec22010-05-15 11:32:37 +00008182 // If we have 2 user-defined types, fall into that path.
Douglas Gregorab209d82015-07-07 03:58:42 +00008183 if (LHS->getInterface() && RHS->getInterface()) {
8184 return finish(canAssignObjCInterfaces(LHS, RHS));
8185 }
Mike Stump11289f42009-09-09 15:08:12 +00008186
Steve Naroff8e6aee52009-07-23 01:01:38 +00008187 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00008188}
8189
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008190/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Fangrui Song6907ce22018-07-30 19:24:48 +00008191/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008192/// arguments in block literals. When passed as arguments, passing 'A*' where
8193/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
8194/// not OK. For the return type, the opposite is not OK.
8195bool ASTContext::canAssignObjCInterfacesInBlockPointer(
8196 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00008197 const ObjCObjectPointerType *RHSOPT,
8198 bool BlockReturnType) {
Douglas Gregorab209d82015-07-07 03:58:42 +00008199
8200 // Function object that propagates a successful result or handles
8201 // __kindof types.
8202 auto finish = [&](bool succeeded) -> bool {
8203 if (succeeded)
8204 return true;
8205
8206 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
8207 if (!Expected->isKindOfType())
8208 return false;
8209
8210 // Strip off __kindof and protocol qualifiers, then check whether
8211 // we can assign the other way.
8212 return canAssignObjCInterfacesInBlockPointer(
8213 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
8214 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
8215 BlockReturnType);
8216 };
8217
Fariborz Jahanian440a6832010-04-06 17:23:39 +00008218 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008219 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00008220
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008221 if (LHSOPT->isObjCBuiltinType()) {
Douglas Gregorab209d82015-07-07 03:58:42 +00008222 return finish(RHSOPT->isObjCBuiltinType() ||
8223 RHSOPT->isObjCQualifiedIdType());
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008224 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008225
Fariborz Jahanian440a6832010-04-06 17:23:39 +00008226 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Volodymyr Sapsai73152a22019-08-28 00:25:06 +00008227 return finish(ObjCQualifiedIdTypesAreCompatible(
James Y Knightc2ca0032019-09-21 22:31:28 +00008228 (BlockReturnType ? LHSOPT : RHSOPT),
8229 (BlockReturnType ? RHSOPT : LHSOPT), false));
Fangrui Song6907ce22018-07-30 19:24:48 +00008230
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008231 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
8232 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
8233 if (LHS && RHS) { // We have 2 user-defined types.
8234 if (LHS != RHS) {
8235 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00008236 return finish(BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008237 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00008238 return finish(!BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008239 }
8240 else
8241 return true;
8242 }
8243 return false;
8244}
8245
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008246/// Comparison routine for Objective-C protocols to be used with
8247/// llvm::array_pod_sort.
8248static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
8249 ObjCProtocolDecl * const *rhs) {
8250 return (*lhs)->getName().compare((*rhs)->getName());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008251}
8252
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008253/// getIntersectionOfProtocols - This routine finds the intersection of set
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008254/// of protocols inherited from two distinct objective-c pointer objects with
8255/// the given common base.
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008256/// It is used to build composite qualifier list of the composite type of
8257/// the conditional expression involving two objective-c pointer objects.
Fangrui Song6907ce22018-07-30 19:24:48 +00008258static
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008259void getIntersectionOfProtocols(ASTContext &Context,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008260 const ObjCInterfaceDecl *CommonBase,
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008261 const ObjCObjectPointerType *LHSOPT,
8262 const ObjCObjectPointerType *RHSOPT,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008263 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
Fangrui Song6907ce22018-07-30 19:24:48 +00008264
John McCall8b07ec22010-05-15 11:32:37 +00008265 const ObjCObjectType* LHS = LHSOPT->getObjectType();
8266 const ObjCObjectType* RHS = RHSOPT->getObjectType();
8267 assert(LHS->getInterface() && "LHS must have an interface base");
8268 assert(RHS->getInterface() && "RHS must have an interface base");
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008269
8270 // Add all of the protocols for the LHS.
8271 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
8272
8273 // Start with the protocol qualifiers.
8274 for (auto proto : LHS->quals()) {
8275 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008276 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008277
8278 // Also add the protocols associated with the LHS interface.
8279 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
8280
Raphael Isemannb23ccec2018-12-10 12:37:46 +00008281 // Add all of the protocols for the RHS.
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008282 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
8283
8284 // Start with the protocol qualifiers.
8285 for (auto proto : RHS->quals()) {
8286 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008287 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008288
8289 // Also add the protocols associated with the RHS interface.
8290 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
8291
8292 // Compute the intersection of the collected protocol sets.
8293 for (auto proto : LHSProtocolSet) {
8294 if (RHSProtocolSet.count(proto))
8295 IntersectionSet.push_back(proto);
8296 }
8297
8298 // Compute the set of protocols that is implied by either the common type or
8299 // the protocols within the intersection.
8300 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
8301 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
8302
8303 // Remove any implied protocols from the list of inherited protocols.
8304 if (!ImpliedProtocols.empty()) {
8305 IntersectionSet.erase(
8306 std::remove_if(IntersectionSet.begin(),
8307 IntersectionSet.end(),
8308 [&](ObjCProtocolDecl *proto) -> bool {
8309 return ImpliedProtocols.count(proto) > 0;
8310 }),
8311 IntersectionSet.end());
8312 }
8313
8314 // Sort the remaining protocols by name.
8315 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
8316 compareObjCProtocolsByName);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008317}
8318
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008319/// Determine whether the first type is a subtype of the second.
8320static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
8321 QualType rhs) {
8322 // Common case: two object pointers.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008323 const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
8324 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008325 if (lhsOPT && rhsOPT)
8326 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
8327
8328 // Two block pointers.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008329 const auto *lhsBlock = lhs->getAs<BlockPointerType>();
8330 const auto *rhsBlock = rhs->getAs<BlockPointerType>();
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008331 if (lhsBlock && rhsBlock)
8332 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
8333
8334 // If either is an unqualified 'id' and the other is a block, it's
8335 // acceptable.
8336 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
8337 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
8338 return true;
8339
8340 return false;
8341}
8342
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008343// Check that the given Objective-C type argument lists are equivalent.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008344static bool sameObjCTypeArgs(ASTContext &ctx,
8345 const ObjCInterfaceDecl *iface,
8346 ArrayRef<QualType> lhsArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00008347 ArrayRef<QualType> rhsArgs,
8348 bool stripKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008349 if (lhsArgs.size() != rhsArgs.size())
8350 return false;
8351
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008352 ObjCTypeParamList *typeParams = iface->getTypeParamList();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008353 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008354 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
8355 continue;
8356
8357 switch (typeParams->begin()[i]->getVariance()) {
8358 case ObjCTypeParamVariance::Invariant:
Douglas Gregorab209d82015-07-07 03:58:42 +00008359 if (!stripKindOf ||
8360 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
8361 rhsArgs[i].stripObjCKindOfType(ctx))) {
8362 return false;
8363 }
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008364 break;
8365
8366 case ObjCTypeParamVariance::Covariant:
8367 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
8368 return false;
8369 break;
8370
8371 case ObjCTypeParamVariance::Contravariant:
8372 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
8373 return false;
8374 break;
Douglas Gregorab209d82015-07-07 03:58:42 +00008375 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008376 }
8377
8378 return true;
8379}
8380
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00008381QualType ASTContext::areCommonBaseCompatible(
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008382 const ObjCObjectPointerType *Lptr,
8383 const ObjCObjectPointerType *Rptr) {
John McCall8b07ec22010-05-15 11:32:37 +00008384 const ObjCObjectType *LHS = Lptr->getObjectType();
8385 const ObjCObjectType *RHS = Rptr->getObjectType();
8386 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
8387 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008388
8389 if (!LDecl || !RDecl)
Eugene Zelenko7855e772018-04-03 00:11:50 +00008390 return {};
Douglas Gregore83b9562015-07-07 03:57:53 +00008391
Manman Renc46f7d12016-05-06 19:35:02 +00008392 // When either LHS or RHS is a kindof type, we should return a kindof type.
8393 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
8394 // kindof(A).
8395 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
8396
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008397 // Follow the left-hand side up the class hierarchy until we either hit a
8398 // root or find the RHS. Record the ancestors in case we don't find it.
8399 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
8400 LHSAncestors;
8401 while (true) {
8402 // Record this ancestor. We'll need this if the common type isn't in the
8403 // path from the LHS to the root.
8404 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
Douglas Gregore83b9562015-07-07 03:57:53 +00008405
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008406 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
8407 // Get the type arguments.
8408 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
8409 bool anyChanges = false;
8410 if (LHS->isSpecialized() && RHS->isSpecialized()) {
8411 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008412 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
8413 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00008414 /*stripKindOf=*/true))
Eugene Zelenko7855e772018-04-03 00:11:50 +00008415 return {};
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008416 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
8417 // If only one has type arguments, the result will not have type
8418 // arguments.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00008419 LHSTypeArgs = {};
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008420 anyChanges = true;
8421 }
8422
8423 // Compute the intersection of protocols.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008424 SmallVector<ObjCProtocolDecl *, 8> Protocols;
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008425 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
8426 Protocols);
John McCall8b07ec22010-05-15 11:32:37 +00008427 if (!Protocols.empty())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008428 anyChanges = true;
8429
8430 // If anything in the LHS will have changed, build a new result type.
Manman Renc46f7d12016-05-06 19:35:02 +00008431 // If we need to return a kindof type but LHS is not a kindof type, we
8432 // build a new result type.
8433 if (anyChanges || LHS->isKindOfType() != anyKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008434 QualType Result = getObjCInterfaceType(LHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00008435 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
Manman Renc46f7d12016-05-06 19:35:02 +00008436 anyKindOf || LHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008437 return getObjCObjectPointerType(Result);
8438 }
8439
8440 return getObjCObjectPointerType(QualType(LHS, 0));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008441 }
Douglas Gregore83b9562015-07-07 03:57:53 +00008442
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008443 // Find the superclass.
Douglas Gregore83b9562015-07-07 03:57:53 +00008444 QualType LHSSuperType = LHS->getSuperClassType();
8445 if (LHSSuperType.isNull())
8446 break;
8447
8448 LHS = LHSSuperType->castAs<ObjCObjectType>();
8449 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008450
8451 // We didn't find anything by following the LHS to its root; now check
8452 // the RHS against the cached set of ancestors.
8453 while (true) {
8454 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
8455 if (KnownLHS != LHSAncestors.end()) {
8456 LHS = KnownLHS->second;
8457
8458 // Get the type arguments.
8459 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
8460 bool anyChanges = false;
8461 if (LHS->isSpecialized() && RHS->isSpecialized()) {
8462 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008463 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
8464 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00008465 /*stripKindOf=*/true))
Eugene Zelenko7855e772018-04-03 00:11:50 +00008466 return {};
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008467 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
8468 // If only one has type arguments, the result will not have type
8469 // arguments.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00008470 RHSTypeArgs = {};
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008471 anyChanges = true;
8472 }
8473
8474 // Compute the intersection of protocols.
8475 SmallVector<ObjCProtocolDecl *, 8> Protocols;
8476 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
8477 Protocols);
8478 if (!Protocols.empty())
8479 anyChanges = true;
8480
Manman Renc46f7d12016-05-06 19:35:02 +00008481 // If we need to return a kindof type but RHS is not a kindof type, we
8482 // build a new result type.
8483 if (anyChanges || RHS->isKindOfType() != anyKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008484 QualType Result = getObjCInterfaceType(RHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00008485 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
Manman Renc46f7d12016-05-06 19:35:02 +00008486 anyKindOf || RHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008487 return getObjCObjectPointerType(Result);
8488 }
8489
8490 return getObjCObjectPointerType(QualType(RHS, 0));
8491 }
8492
8493 // Find the superclass of the RHS.
8494 QualType RHSSuperType = RHS->getSuperClassType();
8495 if (RHSSuperType.isNull())
8496 break;
8497
8498 RHS = RHSSuperType->castAs<ObjCObjectType>();
8499 }
8500
Eugene Zelenko7855e772018-04-03 00:11:50 +00008501 return {};
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00008502}
8503
John McCall8b07ec22010-05-15 11:32:37 +00008504bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
8505 const ObjCObjectType *RHS) {
8506 assert(LHS->getInterface() && "LHS is not an interface type");
8507 assert(RHS->getInterface() && "RHS is not an interface type");
8508
Chris Lattner49af6a42008-04-07 06:51:04 +00008509 // Verify that the base decls are compatible: the RHS must be a subclass of
8510 // the LHS.
Douglas Gregore83b9562015-07-07 03:57:53 +00008511 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
8512 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
8513 if (!IsSuperClass)
Chris Lattner49af6a42008-04-07 06:51:04 +00008514 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008515
Douglas Gregore83b9562015-07-07 03:57:53 +00008516 // If the LHS has protocol qualifiers, determine whether all of them are
8517 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
8518 // LHS).
8519 if (LHS->getNumProtocols() > 0) {
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00008520 // OK if conversion of LHS to SuperClass results in narrowing of types
8521 // ; i.e., SuperClass may implement at least one of the protocols
8522 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
8523 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
8524 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
8525 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
8526 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
8527 // qualifiers.
8528 for (auto *RHSPI : RHS->quals())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008529 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00008530 // If there is no protocols associated with RHS, it is not a match.
8531 if (SuperClassInheritedProtocols.empty())
Steve Naroff114aecb2009-03-01 16:12:44 +00008532 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00008533
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00008534 for (const auto *LHSProto : LHS->quals()) {
8535 bool SuperImplementsProtocol = false;
8536 for (auto *SuperClassProto : SuperClassInheritedProtocols)
8537 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
8538 SuperImplementsProtocol = true;
8539 break;
8540 }
8541 if (!SuperImplementsProtocol)
8542 return false;
8543 }
Chris Lattner49af6a42008-04-07 06:51:04 +00008544 }
Douglas Gregore83b9562015-07-07 03:57:53 +00008545
8546 // If the LHS is specialized, we may need to check type arguments.
8547 if (LHS->isSpecialized()) {
8548 // Follow the superclass chain until we've matched the LHS class in the
8549 // hierarchy. This substitutes type arguments through.
8550 const ObjCObjectType *RHSSuper = RHS;
8551 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
8552 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
8553
8554 // If the RHS is specializd, compare type arguments.
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008555 if (RHSSuper->isSpecialized() &&
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008556 !sameObjCTypeArgs(*this, LHS->getInterface(),
8557 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00008558 /*stripKindOf=*/true)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008559 return false;
Douglas Gregore83b9562015-07-07 03:57:53 +00008560 }
8561 }
8562
8563 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00008564}
8565
Steve Naroffb7605152009-02-12 17:52:19 +00008566bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
8567 // get the "pointed to" types
Eugene Zelenko7855e772018-04-03 00:11:50 +00008568 const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
8569 const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00008570
Steve Naroff7cae42b2009-07-10 23:34:53 +00008571 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00008572 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00008573
8574 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
8575 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00008576}
8577
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00008578bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
8579 return canAssignObjCInterfaces(
8580 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
8581 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
8582}
8583
Mike Stump11289f42009-09-09 15:08:12 +00008584/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00008585/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00008586/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00008587/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008588bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
8589 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00008590 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00008591 return hasSameType(LHS, RHS);
Joey Gouly5788b782016-11-18 14:10:54 +00008592
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008593 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00008594}
8595
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00008596bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00008597 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00008598}
8599
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008600bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
8601 return !mergeTypes(LHS, RHS, true).isNull();
8602}
8603
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00008604/// mergeTransparentUnionType - if T is a transparent union type and a member
8605/// of T is compatible with SubType, return the merged type, else return
8606/// QualType()
8607QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
8608 bool OfBlockPointer,
8609 bool Unqualified) {
8610 if (const RecordType *UT = T->getAsUnionType()) {
8611 RecordDecl *UD = UT->getDecl();
8612 if (UD->hasAttr<TransparentUnionAttr>()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008613 for (const auto *I : UD->fields()) {
8614 QualType ET = I->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00008615 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
8616 if (!MT.isNull())
8617 return MT;
8618 }
8619 }
8620 }
8621
Eugene Zelenko7855e772018-04-03 00:11:50 +00008622 return {};
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00008623}
8624
Alp Toker9cacbab2014-01-20 20:26:09 +00008625/// mergeFunctionParameterTypes - merge two types which appear as function
8626/// parameter types
8627QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
8628 bool OfBlockPointer,
8629 bool Unqualified) {
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00008630 // GNU extension: two types are compatible if they appear as a function
8631 // argument, one of the types is a transparent union type and the other
8632 // type is compatible with a union member
8633 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
8634 Unqualified);
8635 if (!lmerge.isNull())
8636 return lmerge;
8637
8638 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
8639 Unqualified);
8640 if (!rmerge.isNull())
8641 return rmerge;
8642
8643 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
8644}
8645
Fangrui Song6907ce22018-07-30 19:24:48 +00008646QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008647 bool OfBlockPointer,
8648 bool Unqualified) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00008649 const auto *lbase = lhs->getAs<FunctionType>();
8650 const auto *rbase = rhs->getAs<FunctionType>();
8651 const auto *lproto = dyn_cast<FunctionProtoType>(lbase);
8652 const auto *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00008653 bool allLTypes = true;
8654 bool allRTypes = true;
8655
8656 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008657 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00008658 if (OfBlockPointer) {
Alp Toker314cc812014-01-25 16:55:45 +00008659 QualType RHS = rbase->getReturnType();
8660 QualType LHS = lbase->getReturnType();
Fariborz Jahanian17825972011-02-11 18:46:17 +00008661 bool UnqualifiedResult = Unqualified;
8662 if (!UnqualifiedResult)
8663 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00008664 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00008665 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008666 else
Alp Toker314cc812014-01-25 16:55:45 +00008667 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
John McCall8c6b56f2010-12-15 01:06:38 +00008668 Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00008669 if (retType.isNull())
8670 return {};
Fangrui Song6907ce22018-07-30 19:24:48 +00008671
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008672 if (Unqualified)
8673 retType = retType.getUnqualifiedType();
8674
Alp Toker314cc812014-01-25 16:55:45 +00008675 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
8676 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008677 if (Unqualified) {
8678 LRetType = LRetType.getUnqualifiedType();
8679 RRetType = RRetType.getUnqualifiedType();
8680 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008681
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008682 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00008683 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008684 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00008685 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00008686
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00008687 // FIXME: double check this
8688 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
8689 // rbase->getRegParmAttr() != 0 &&
8690 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00008691 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
8692 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00008693
Douglas Gregor8c940862010-01-18 17:14:39 +00008694 // Compatible functions must have compatible calling conventions
Reid Kleckner78af0702013-08-27 23:08:25 +00008695 if (lbaseInfo.getCC() != rbaseInfo.getCC())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008696 return {};
Mike Stump11289f42009-09-09 15:08:12 +00008697
John McCall8c6b56f2010-12-15 01:06:38 +00008698 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00008699 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008700 return {};
John McCall8c6b56f2010-12-15 01:06:38 +00008701 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008702 return {};
John McCall8c6b56f2010-12-15 01:06:38 +00008703
John McCall31168b02011-06-15 23:02:42 +00008704 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008705 return {};
Oren Ben Simhon318a6ea2017-04-27 12:01:00 +00008706 if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008707 return {};
Oren Ben Simhon220671a2018-03-17 13:31:35 +00008708 if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008709 return {};
John McCall31168b02011-06-15 23:02:42 +00008710
John McCall8c6b56f2010-12-15 01:06:38 +00008711 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
8712 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00008713
Rafael Espindola8778c282012-11-29 16:09:03 +00008714 if (lbaseInfo.getNoReturn() != NoReturn)
8715 allLTypes = false;
8716 if (rbaseInfo.getNoReturn() != NoReturn)
8717 allRTypes = false;
8718
John McCall31168b02011-06-15 23:02:42 +00008719 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00008720
Eli Friedman47f77112008-08-22 00:56:42 +00008721 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00008722 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
8723 "C++ shouldn't be here");
Alp Toker601b22c2014-01-21 23:35:24 +00008724 // Compatible functions must have the same number of parameters
8725 if (lproto->getNumParams() != rproto->getNumParams())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008726 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00008727
8728 // Variadic and non-variadic functions aren't compatible
8729 if (lproto->isVariadic() != rproto->isVariadic())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008730 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00008731
Anastasia Stulovac61eaa52019-01-28 11:37:49 +00008732 if (lproto->getMethodQuals() != rproto->getMethodQuals())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008733 return {};
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00008734
Akira Hatanaka98a49332017-09-22 00:41:05 +00008735 SmallVector<FunctionProtoType::ExtParameterInfo, 4> newParamInfos;
8736 bool canUseLeft, canUseRight;
8737 if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight,
8738 newParamInfos))
Eugene Zelenko7855e772018-04-03 00:11:50 +00008739 return {};
Alp Toker601b22c2014-01-21 23:35:24 +00008740
Akira Hatanaka98a49332017-09-22 00:41:05 +00008741 if (!canUseLeft)
8742 allLTypes = false;
8743 if (!canUseRight)
8744 allRTypes = false;
8745
Alp Toker601b22c2014-01-21 23:35:24 +00008746 // Check parameter type compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008747 SmallVector<QualType, 10> types;
Alp Toker601b22c2014-01-21 23:35:24 +00008748 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
8749 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
8750 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
8751 QualType paramType = mergeFunctionParameterTypes(
8752 lParamType, rParamType, OfBlockPointer, Unqualified);
8753 if (paramType.isNull())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008754 return {};
Alp Toker601b22c2014-01-21 23:35:24 +00008755
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008756 if (Unqualified)
Alp Toker601b22c2014-01-21 23:35:24 +00008757 paramType = paramType.getUnqualifiedType();
8758
8759 types.push_back(paramType);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008760 if (Unqualified) {
Alp Toker601b22c2014-01-21 23:35:24 +00008761 lParamType = lParamType.getUnqualifiedType();
8762 rParamType = rParamType.getUnqualifiedType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008763 }
Alp Toker601b22c2014-01-21 23:35:24 +00008764
8765 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00008766 allLTypes = false;
Alp Toker601b22c2014-01-21 23:35:24 +00008767 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00008768 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00008769 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008770
Eli Friedman47f77112008-08-22 00:56:42 +00008771 if (allLTypes) return lhs;
8772 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00008773
8774 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
8775 EPI.ExtInfo = einfo;
Akira Hatanaka98a49332017-09-22 00:41:05 +00008776 EPI.ExtParameterInfos =
8777 newParamInfos.empty() ? nullptr : newParamInfos.data();
Jordan Rose5c382722013-03-08 21:51:21 +00008778 return getFunctionType(retType, types, EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00008779 }
8780
8781 if (lproto) allRTypes = false;
8782 if (rproto) allLTypes = false;
8783
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008784 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00008785 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00008786 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eugene Zelenko7855e772018-04-03 00:11:50 +00008787 if (proto->isVariadic())
8788 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00008789 // Check that the types are compatible with the types that
8790 // would result from default argument promotions (C99 6.7.5.3p15).
8791 // The only types actually affected are promotable integer
8792 // types and floats, which would be passed as a different
8793 // type depending on whether the prototype is visible.
Alp Toker601b22c2014-01-21 23:35:24 +00008794 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
8795 QualType paramTy = proto->getParamType(i);
Alp Toker9cacbab2014-01-20 20:26:09 +00008796
Eli Friedman448ce402012-08-30 00:44:15 +00008797 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00008798 // to pass enum values.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008799 if (const auto *Enum = paramTy->getAs<EnumType>()) {
Alp Toker601b22c2014-01-21 23:35:24 +00008800 paramTy = Enum->getDecl()->getIntegerType();
8801 if (paramTy.isNull())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008802 return {};
Eli Friedman448ce402012-08-30 00:44:15 +00008803 }
Alp Toker601b22c2014-01-21 23:35:24 +00008804
8805 if (paramTy->isPromotableIntegerType() ||
8806 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
Eugene Zelenko7855e772018-04-03 00:11:50 +00008807 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00008808 }
8809
8810 if (allLTypes) return lhs;
8811 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00008812
8813 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
8814 EPI.ExtInfo = einfo;
Alp Toker9cacbab2014-01-20 20:26:09 +00008815 return getFunctionType(retType, proto->getParamTypes(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00008816 }
8817
8818 if (allLTypes) return lhs;
8819 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00008820 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00008821}
8822
John McCall433c2e62013-03-21 00:10:07 +00008823/// Given that we have an enum type and a non-enum type, try to merge them.
8824static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
8825 QualType other, bool isBlockReturnType) {
8826 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
8827 // a signed integer type, or an unsigned integer type.
8828 // Compatibility is based on the underlying type, not the promotion
8829 // type.
8830 QualType underlyingType = ET->getDecl()->getIntegerType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00008831 if (underlyingType.isNull())
8832 return {};
John McCall433c2e62013-03-21 00:10:07 +00008833 if (Context.hasSameType(underlyingType, other))
8834 return other;
8835
8836 // In block return types, we're more permissive and accept any
8837 // integral type of the same size.
8838 if (isBlockReturnType && other->isIntegerType() &&
8839 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
8840 return other;
8841
Eugene Zelenko7855e772018-04-03 00:11:50 +00008842 return {};
John McCall433c2e62013-03-21 00:10:07 +00008843}
8844
Fangrui Song6907ce22018-07-30 19:24:48 +00008845QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008846 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00008847 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00008848 // C++ [expr]: If an expression initially has the type "reference to T", the
8849 // type is adjusted to "T" prior to any further analysis, the expression
8850 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00008851 // expression is an lvalue unless the reference is an rvalue reference and
8852 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00008853 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
8854 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008855
8856 if (Unqualified) {
8857 LHS = LHS.getUnqualifiedType();
8858 RHS = RHS.getUnqualifiedType();
8859 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008860
Eli Friedman47f77112008-08-22 00:56:42 +00008861 QualType LHSCan = getCanonicalType(LHS),
8862 RHSCan = getCanonicalType(RHS);
8863
8864 // If two types are identical, they are compatible.
8865 if (LHSCan == RHSCan)
8866 return LHS;
8867
John McCall8ccfcb52009-09-24 19:53:00 +00008868 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00008869 Qualifiers LQuals = LHSCan.getLocalQualifiers();
8870 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00008871 if (LQuals != RQuals) {
8872 // If any of these qualifiers are different, we have a type
8873 // mismatch.
8874 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00008875 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
Roger Ferrer Ibanezd93add32017-02-24 08:41:09 +00008876 LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
8877 LQuals.hasUnaligned() != RQuals.hasUnaligned())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008878 return {};
John McCall8ccfcb52009-09-24 19:53:00 +00008879
8880 // Exactly one GC qualifier difference is allowed: __strong is
8881 // okay if the other type has no GC qualifier but is an Objective
8882 // C object pointer (i.e. implicitly strong by default). We fix
8883 // this by pretending that the unqualified type was actually
8884 // qualified __strong.
8885 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
8886 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
8887 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
8888
8889 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
Eugene Zelenko7855e772018-04-03 00:11:50 +00008890 return {};
John McCall8ccfcb52009-09-24 19:53:00 +00008891
8892 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
8893 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
8894 }
8895 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
8896 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
8897 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00008898 return {};
John McCall8ccfcb52009-09-24 19:53:00 +00008899 }
8900
8901 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00008902
Eli Friedmandcca6332009-06-01 01:22:52 +00008903 Type::TypeClass LHSClass = LHSCan->getTypeClass();
8904 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00008905
Chris Lattnerfd652912008-01-14 05:45:46 +00008906 // We want to consider the two function types to be the same for these
8907 // comparisons, just force one to the other.
8908 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
8909 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00008910
8911 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00008912 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
8913 LHSClass = Type::ConstantArray;
8914 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
8915 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00008916
John McCall8b07ec22010-05-15 11:32:37 +00008917 // ObjCInterfaces are just specialized ObjCObjects.
8918 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
8919 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
8920
Nate Begemance4d7fc2008-04-18 23:10:10 +00008921 // Canonicalize ExtVector -> Vector.
8922 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
8923 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00008924
Chris Lattner95554662008-04-07 05:43:21 +00008925 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00008926 if (LHSClass != RHSClass) {
John McCall433c2e62013-03-21 00:10:07 +00008927 // Note that we only have special rules for turning block enum
8928 // returns into block int returns, not vice-versa.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008929 if (const auto *ETy = LHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00008930 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00008931 }
John McCall9dd450b2009-09-21 23:43:11 +00008932 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00008933 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00008934 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00008935 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00008936 if (OfBlockPointer && !BlockReturnType) {
8937 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
8938 return LHS;
8939 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
8940 return RHS;
8941 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008942
Eugene Zelenko7855e772018-04-03 00:11:50 +00008943 return {};
Steve Naroff32e44c02007-10-15 20:41:53 +00008944 }
Eli Friedman47f77112008-08-22 00:56:42 +00008945
Steve Naroffc6edcbd2008-01-09 22:43:08 +00008946 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00008947 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008948#define TYPE(Class, Base)
8949#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00008950#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008951#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
8952#define DEPENDENT_TYPE(Class, Base) case Type::Class:
John McCall36b12a82019-10-02 06:35:23 +00008953#include "clang/AST/TypeNodes.inc"
David Blaikie83d382b2011-09-23 05:06:16 +00008954 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008955
Richard Smith27d807c2013-04-30 13:56:41 +00008956 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00008957 case Type::DeducedTemplateSpecialization:
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00008958 case Type::LValueReference:
8959 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008960 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00008961 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008962
John McCall8b07ec22010-05-15 11:32:37 +00008963 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008964 case Type::IncompleteArray:
8965 case Type::VariableArray:
8966 case Type::FunctionProto:
8967 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00008968 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008969
Chris Lattnerfd652912008-01-14 05:45:46 +00008970 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00008971 {
8972 // Merge two pointer types, while trying to preserve typedef info
Simon Pilgrimeed4b122019-10-02 11:48:06 +00008973 QualType LHSPointee = LHS->castAs<PointerType>()->getPointeeType();
8974 QualType RHSPointee = RHS->castAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008975 if (Unqualified) {
8976 LHSPointee = LHSPointee.getUnqualifiedType();
8977 RHSPointee = RHSPointee.getUnqualifiedType();
8978 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008979 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008980 Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00008981 if (ResultType.isNull())
8982 return {};
Eli Friedman091a9ac2009-06-02 05:28:56 +00008983 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00008984 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00008985 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00008986 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00008987 return getPointerType(ResultType);
8988 }
Steve Naroff68e167d2008-12-10 17:49:55 +00008989 case Type::BlockPointer:
8990 {
8991 // Merge two block pointer types, while trying to preserve typedef info
Simon Pilgrimeed4b122019-10-02 11:48:06 +00008992 QualType LHSPointee = LHS->castAs<BlockPointerType>()->getPointeeType();
8993 QualType RHSPointee = RHS->castAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008994 if (Unqualified) {
8995 LHSPointee = LHSPointee.getUnqualifiedType();
8996 RHSPointee = RHSPointee.getUnqualifiedType();
8997 }
Anastasia Stulova81a25e352017-03-10 15:23:07 +00008998 if (getLangOpts().OpenCL) {
8999 Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
9000 Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
9001 // Blocks can't be an expression in a ternary operator (OpenCL v2.0
9002 // 6.12.5) thus the following check is asymmetric.
9003 if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual))
Eugene Zelenko7855e772018-04-03 00:11:50 +00009004 return {};
Anastasia Stulova81a25e352017-03-10 15:23:07 +00009005 LHSPteeQual.removeAddressSpace();
9006 RHSPteeQual.removeAddressSpace();
9007 LHSPointee =
9008 QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
9009 RHSPointee =
9010 QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
9011 }
Douglas Gregor17ea3f52010-07-29 15:18:02 +00009012 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
9013 Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00009014 if (ResultType.isNull())
9015 return {};
Steve Naroff68e167d2008-12-10 17:49:55 +00009016 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
9017 return LHS;
9018 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
9019 return RHS;
9020 return getBlockPointerType(ResultType);
9021 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00009022 case Type::Atomic:
9023 {
9024 // Merge two pointer types, while trying to preserve typedef info
Simon Pilgrimeed4b122019-10-02 11:48:06 +00009025 QualType LHSValue = LHS->castAs<AtomicType>()->getValueType();
9026 QualType RHSValue = RHS->castAs<AtomicType>()->getValueType();
Eli Friedman0dfb8892011-10-06 23:00:33 +00009027 if (Unqualified) {
9028 LHSValue = LHSValue.getUnqualifiedType();
9029 RHSValue = RHSValue.getUnqualifiedType();
9030 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009031 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
Eli Friedman0dfb8892011-10-06 23:00:33 +00009032 Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00009033 if (ResultType.isNull())
9034 return {};
Eli Friedman0dfb8892011-10-06 23:00:33 +00009035 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
9036 return LHS;
9037 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
9038 return RHS;
9039 return getAtomicType(ResultType);
9040 }
Chris Lattnerfd652912008-01-14 05:45:46 +00009041 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00009042 {
9043 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
9044 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
9045 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
Eugene Zelenko7855e772018-04-03 00:11:50 +00009046 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00009047
9048 QualType LHSElem = getAsArrayType(LHS)->getElementType();
9049 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00009050 if (Unqualified) {
9051 LHSElem = LHSElem.getUnqualifiedType();
9052 RHSElem = RHSElem.getUnqualifiedType();
9053 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009054
Douglas Gregor17ea3f52010-07-29 15:18:02 +00009055 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00009056 if (ResultType.isNull())
9057 return {};
Jeremy Morse8129c5c2018-06-05 09:18:26 +00009058
9059 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
9060 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
9061
9062 // If either side is a variable array, and both are complete, check whether
9063 // the current dimension is definite.
9064 if (LVAT || RVAT) {
9065 auto SizeFetch = [this](const VariableArrayType* VAT,
9066 const ConstantArrayType* CAT)
9067 -> std::pair<bool,llvm::APInt> {
9068 if (VAT) {
9069 llvm::APSInt TheInt;
9070 Expr *E = VAT->getSizeExpr();
9071 if (E && E->isIntegerConstantExpr(TheInt, *this))
9072 return std::make_pair(true, TheInt);
9073 else
9074 return std::make_pair(false, TheInt);
9075 } else if (CAT) {
9076 return std::make_pair(true, CAT->getSize());
9077 } else {
9078 return std::make_pair(false, llvm::APInt());
9079 }
9080 };
9081
9082 bool HaveLSize, HaveRSize;
9083 llvm::APInt LSize, RSize;
9084 std::tie(HaveLSize, LSize) = SizeFetch(LVAT, LCAT);
9085 std::tie(HaveRSize, RSize) = SizeFetch(RVAT, RCAT);
9086 if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(LSize, RSize))
9087 return {}; // Definite, but unequal, array dimension
9088 }
9089
Chris Lattner465fa322008-10-05 17:34:18 +00009090 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
9091 return LHS;
9092 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
9093 return RHS;
Richard Smith772e2662019-10-04 01:25:59 +00009094 if (LCAT)
9095 return getConstantArrayType(ResultType, LCAT->getSize(),
9096 LCAT->getSizeExpr(),
9097 ArrayType::ArraySizeModifier(), 0);
9098 if (RCAT)
9099 return getConstantArrayType(ResultType, RCAT->getSize(),
9100 RCAT->getSizeExpr(),
9101 ArrayType::ArraySizeModifier(), 0);
Chris Lattner465fa322008-10-05 17:34:18 +00009102 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
9103 return LHS;
9104 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
9105 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00009106 if (LVAT) {
9107 // FIXME: This isn't correct! But tricky to implement because
9108 // the array's size has to be the size of LHS, but the type
9109 // has to be different.
9110 return LHS;
9111 }
9112 if (RVAT) {
9113 // FIXME: This isn't correct! But tricky to implement because
9114 // the array's size has to be the size of RHS, but the type
9115 // has to be different.
9116 return RHS;
9117 }
Eli Friedman3e62c212008-08-22 01:48:21 +00009118 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
9119 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00009120 return getIncompleteArrayType(ResultType,
9121 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00009122 }
Chris Lattnerfd652912008-01-14 05:45:46 +00009123 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00009124 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00009125 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00009126 case Type::Enum:
Eugene Zelenko7855e772018-04-03 00:11:50 +00009127 return {};
Chris Lattnerfd652912008-01-14 05:45:46 +00009128 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00009129 // Only exactly equal builtin types are compatible, which is tested above.
Eugene Zelenko7855e772018-04-03 00:11:50 +00009130 return {};
Daniel Dunbar804c0442009-01-28 21:22:12 +00009131 case Type::Complex:
9132 // Distinct complex types are incompatible.
Eugene Zelenko7855e772018-04-03 00:11:50 +00009133 return {};
Chris Lattner7bbd3d72008-04-07 05:55:38 +00009134 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00009135 // FIXME: The merged type should be an ExtVector!
Simon Pilgrim9588ae72019-10-03 21:47:42 +00009136 if (areCompatVectorTypes(LHSCan->castAs<VectorType>(),
9137 RHSCan->castAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00009138 return LHS;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009139 return {};
John McCall8b07ec22010-05-15 11:32:37 +00009140 case Type::ObjCObject: {
9141 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00009142 // FIXME: This should be type compatibility, e.g. whether
9143 // "LHS x; RHS x;" at global scope is legal.
Simon Pilgrim9588ae72019-10-03 21:47:42 +00009144 if (canAssignObjCInterfaces(LHS->castAs<ObjCObjectType>(),
9145 RHS->castAs<ObjCObjectType>()))
Steve Naroff7a7814c2009-02-21 16:18:07 +00009146 return LHS;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009147 return {};
Cedric Venet4fc88b72009-02-21 17:14:49 +00009148 }
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009149 case Type::ObjCObjectPointer:
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00009150 if (OfBlockPointer) {
9151 if (canAssignObjCInterfacesInBlockPointer(
Simon Pilgrim9588ae72019-10-03 21:47:42 +00009152 LHS->castAs<ObjCObjectPointerType>(),
9153 RHS->castAs<ObjCObjectPointerType>(), BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00009154 return LHS;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009155 return {};
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00009156 }
Simon Pilgrim9588ae72019-10-03 21:47:42 +00009157 if (canAssignObjCInterfaces(LHS->castAs<ObjCObjectPointerType>(),
9158 RHS->castAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00009159 return LHS;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009160 return {};
Xiuli Pan9c14e282016-01-09 12:53:17 +00009161 case Type::Pipe:
Joey Goulye3c85de2016-12-01 11:30:49 +00009162 assert(LHS != RHS &&
9163 "Equivalent pipe types should have already been handled!");
Eugene Zelenko7855e772018-04-03 00:11:50 +00009164 return {};
Xiuli Pan9c14e282016-01-09 12:53:17 +00009165 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00009166
David Blaikie8a40f702012-01-17 06:56:22 +00009167 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00009168}
Ted Kremenekfc581a92007-10-31 17:10:13 +00009169
Akira Hatanaka98a49332017-09-22 00:41:05 +00009170bool ASTContext::mergeExtParameterInfo(
9171 const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType,
9172 bool &CanUseFirst, bool &CanUseSecond,
9173 SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &NewParamInfos) {
9174 assert(NewParamInfos.empty() && "param info list not empty");
9175 CanUseFirst = CanUseSecond = true;
9176 bool FirstHasInfo = FirstFnType->hasExtParameterInfos();
9177 bool SecondHasInfo = SecondFnType->hasExtParameterInfos();
9178
John McCall18afab72016-03-01 00:49:02 +00009179 // Fast path: if the first type doesn't have ext parameter infos,
Akira Hatanaka98a49332017-09-22 00:41:05 +00009180 // we match if and only if the second type also doesn't have them.
9181 if (!FirstHasInfo && !SecondHasInfo)
9182 return true;
John McCall18afab72016-03-01 00:49:02 +00009183
Akira Hatanaka98a49332017-09-22 00:41:05 +00009184 bool NeedParamInfo = false;
9185 size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size()
9186 : SecondFnType->getExtParameterInfos().size();
John McCall18afab72016-03-01 00:49:02 +00009187
Akira Hatanaka98a49332017-09-22 00:41:05 +00009188 for (size_t I = 0; I < E; ++I) {
9189 FunctionProtoType::ExtParameterInfo FirstParam, SecondParam;
9190 if (FirstHasInfo)
9191 FirstParam = FirstFnType->getExtParameterInfo(I);
9192 if (SecondHasInfo)
9193 SecondParam = SecondFnType->getExtParameterInfo(I);
John McCall18afab72016-03-01 00:49:02 +00009194
Akira Hatanaka98a49332017-09-22 00:41:05 +00009195 // Cannot merge unless everything except the noescape flag matches.
9196 if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false))
John McCall18afab72016-03-01 00:49:02 +00009197 return false;
Akira Hatanaka98a49332017-09-22 00:41:05 +00009198
9199 bool FirstNoEscape = FirstParam.isNoEscape();
9200 bool SecondNoEscape = SecondParam.isNoEscape();
9201 bool IsNoEscape = FirstNoEscape && SecondNoEscape;
9202 NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape));
9203 if (NewParamInfos.back().getOpaqueValue())
9204 NeedParamInfo = true;
9205 if (FirstNoEscape != IsNoEscape)
9206 CanUseFirst = false;
9207 if (SecondNoEscape != IsNoEscape)
9208 CanUseSecond = false;
John McCall18afab72016-03-01 00:49:02 +00009209 }
Akira Hatanaka98a49332017-09-22 00:41:05 +00009210
9211 if (!NeedParamInfo)
9212 NewParamInfos.clear();
9213
Fariborz Jahanian97676972011-09-28 21:52:05 +00009214 return true;
9215}
9216
Chandler Carruth21c90602015-12-30 03:24:14 +00009217void ASTContext::ResetObjCLayout(const ObjCContainerDecl *CD) {
9218 ObjCLayouts[CD] = nullptr;
9219}
9220
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009221/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
9222/// 'RHS' attributes and returns the merged version; including for function
9223/// return types.
9224QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
9225 QualType LHSCan = getCanonicalType(LHS),
9226 RHSCan = getCanonicalType(RHS);
9227 // If two types are identical, they are compatible.
9228 if (LHSCan == RHSCan)
9229 return LHS;
9230 if (RHSCan->isFunctionType()) {
9231 if (!LHSCan->isFunctionType())
Eugene Zelenko7855e772018-04-03 00:11:50 +00009232 return {};
Alp Toker314cc812014-01-25 16:55:45 +00009233 QualType OldReturnType =
9234 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009235 QualType NewReturnType =
Alp Toker314cc812014-01-25 16:55:45 +00009236 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
Fangrui Song6907ce22018-07-30 19:24:48 +00009237 QualType ResReturnType =
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009238 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
9239 if (ResReturnType.isNull())
Eugene Zelenko7855e772018-04-03 00:11:50 +00009240 return {};
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009241 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
9242 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
9243 // In either case, use OldReturnType to build the new function type.
Simon Pilgrim9588ae72019-10-03 21:47:42 +00009244 const auto *F = LHS->castAs<FunctionType>();
Eugene Zelenko7855e772018-04-03 00:11:50 +00009245 if (const auto *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00009246 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9247 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner896b32f2013-06-10 20:51:09 +00009248 QualType ResultType =
Alp Toker9cacbab2014-01-20 20:26:09 +00009249 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009250 return ResultType;
9251 }
9252 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00009253 return {};
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009254 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009255
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009256 // If the qualifiers are different, the types can still be merged.
9257 Qualifiers LQuals = LHSCan.getLocalQualifiers();
9258 Qualifiers RQuals = RHSCan.getLocalQualifiers();
9259 if (LQuals != RQuals) {
9260 // If any of these qualifiers are different, we have a type mismatch.
9261 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
9262 LQuals.getAddressSpace() != RQuals.getAddressSpace())
Eugene Zelenko7855e772018-04-03 00:11:50 +00009263 return {};
Fangrui Song6907ce22018-07-30 19:24:48 +00009264
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009265 // Exactly one GC qualifier difference is allowed: __strong is
9266 // okay if the other type has no GC qualifier but is an Objective
9267 // C object pointer (i.e. implicitly strong by default). We fix
9268 // this by pretending that the unqualified type was actually
9269 // qualified __strong.
9270 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
9271 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
9272 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
Fangrui Song6907ce22018-07-30 19:24:48 +00009273
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009274 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
Eugene Zelenko7855e772018-04-03 00:11:50 +00009275 return {};
Fangrui Song6907ce22018-07-30 19:24:48 +00009276
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009277 if (GC_L == Qualifiers::Strong)
9278 return LHS;
9279 if (GC_R == Qualifiers::Strong)
9280 return RHS;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009281 return {};
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009282 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009283
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009284 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
Simon Pilgrimeed4b122019-10-02 11:48:06 +00009285 QualType LHSBaseQT = LHS->castAs<ObjCObjectPointerType>()->getPointeeType();
9286 QualType RHSBaseQT = RHS->castAs<ObjCObjectPointerType>()->getPointeeType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009287 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
9288 if (ResQT == LHSBaseQT)
9289 return LHS;
9290 if (ResQT == RHSBaseQT)
9291 return RHS;
9292 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00009293 return {};
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009294}
9295
Chris Lattner4ba0cef2008-04-07 07:01:58 +00009296//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009297// Integer Predicates
9298//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00009299
Jay Foad39c79802011-01-12 09:06:06 +00009300unsigned ASTContext::getIntWidth(QualType T) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00009301 if (const auto *ET = T->getAs<EnumType>())
Eli Friedmanee275c82009-12-10 22:29:29 +00009302 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00009303 if (T->isBooleanType())
9304 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00009305 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009306 return (unsigned)getTypeSize(T);
9307}
9308
Abramo Bagnara13640492012-09-09 10:21:24 +00009309QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Leonard Chanab80f3c2018-06-14 14:53:51 +00009310 assert((T->hasSignedIntegerRepresentation() || T->isSignedFixedPointType()) &&
9311 "Unexpected type");
Fangrui Song6907ce22018-07-30 19:24:48 +00009312
Chris Lattnerec3a1562009-10-17 20:33:28 +00009313 // Turn <4 x signed int> -> <4 x unsigned int>
Eugene Zelenko7855e772018-04-03 00:11:50 +00009314 if (const auto *VTy = T->getAs<VectorType>())
Chris Lattnerec3a1562009-10-17 20:33:28 +00009315 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00009316 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00009317
9318 // For enums, we return the unsigned version of the base type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00009319 if (const auto *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009320 T = ETy->getDecl()->getIntegerType();
Fangrui Song6907ce22018-07-30 19:24:48 +00009321
Simon Pilgrim9588ae72019-10-03 21:47:42 +00009322 switch (T->castAs<BuiltinType>()->getKind()) {
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009323 case BuiltinType::Char_S:
9324 case BuiltinType::SChar:
9325 return UnsignedCharTy;
9326 case BuiltinType::Short:
9327 return UnsignedShortTy;
9328 case BuiltinType::Int:
9329 return UnsignedIntTy;
9330 case BuiltinType::Long:
9331 return UnsignedLongTy;
9332 case BuiltinType::LongLong:
9333 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00009334 case BuiltinType::Int128:
9335 return UnsignedInt128Ty;
Leonard Chanab80f3c2018-06-14 14:53:51 +00009336
9337 case BuiltinType::ShortAccum:
9338 return UnsignedShortAccumTy;
9339 case BuiltinType::Accum:
9340 return UnsignedAccumTy;
9341 case BuiltinType::LongAccum:
9342 return UnsignedLongAccumTy;
9343 case BuiltinType::SatShortAccum:
9344 return SatUnsignedShortAccumTy;
9345 case BuiltinType::SatAccum:
9346 return SatUnsignedAccumTy;
9347 case BuiltinType::SatLongAccum:
9348 return SatUnsignedLongAccumTy;
9349 case BuiltinType::ShortFract:
9350 return UnsignedShortFractTy;
9351 case BuiltinType::Fract:
9352 return UnsignedFractTy;
9353 case BuiltinType::LongFract:
9354 return UnsignedLongFractTy;
9355 case BuiltinType::SatShortFract:
9356 return SatUnsignedShortFractTy;
9357 case BuiltinType::SatFract:
9358 return SatUnsignedFractTy;
9359 case BuiltinType::SatLongFract:
9360 return SatUnsignedLongFractTy;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009361 default:
Leonard Chanab80f3c2018-06-14 14:53:51 +00009362 llvm_unreachable("Unexpected signed integer or fixed point type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009363 }
9364}
9365
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009366ASTMutationListener::~ASTMutationListener() = default;
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00009367
Richard Smith1fa5d642013-05-11 05:45:24 +00009368void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
9369 QualType ReturnType) {}
Chris Lattnerecd79c62009-06-14 00:45:47 +00009370
9371//===----------------------------------------------------------------------===//
9372// Builtin Type Computation
9373//===----------------------------------------------------------------------===//
9374
9375/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00009376/// pointer over the consumed characters. This returns the resultant type. If
9377/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
9378/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
9379/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009380///
9381/// RequiresICE is filled in on return to indicate whether the value is required
9382/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00009383static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00009384 ASTContext::GetBuiltinTypeError &Error,
Chandler Carruth45bbe012017-03-24 09:11:57 +00009385 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00009386 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00009387 // Modifiers.
9388 int HowLong = 0;
9389 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009390 RequiresICE = false;
Fangrui Song6907ce22018-07-30 19:24:48 +00009391
Chris Lattnerdc226c22010-10-01 22:42:38 +00009392 // Read the prefixed modifiers first.
Eric Christopher50daf5f2017-07-10 21:28:54 +00009393 bool Done = false;
9394 #ifndef NDEBUG
Karl-Johan Karlsson0e525a42019-05-16 07:18:02 +00009395 bool IsSpecial = false;
Eric Christopher50daf5f2017-07-10 21:28:54 +00009396 #endif
Chris Lattnerecd79c62009-06-14 00:45:47 +00009397 while (!Done) {
9398 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00009399 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00009400 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009401 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00009402 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009403 case 'S':
9404 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
9405 assert(!Signed && "Can't use 'S' modifier multiple times!");
9406 Signed = true;
9407 break;
9408 case 'U':
9409 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
Sean Silva2a995142015-01-16 21:44:26 +00009410 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00009411 Unsigned = true;
9412 break;
9413 case 'L':
Andrew Savonichevfa8cd762019-06-03 12:34:59 +00009414 assert(!IsSpecial && "Can't use 'L' with 'W', 'N', 'Z' or 'O' modifiers");
Chris Lattnerecd79c62009-06-14 00:45:47 +00009415 assert(HowLong <= 2 && "Can't have LLLL modifier");
9416 ++HowLong;
9417 break;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009418 case 'N':
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00009419 // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
Andrew Savonichevfa8cd762019-06-03 12:34:59 +00009420 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00009421 assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
Eric Christopher50daf5f2017-07-10 21:28:54 +00009422 #ifndef NDEBUG
Karl-Johan Karlsson0e525a42019-05-16 07:18:02 +00009423 IsSpecial = true;
Eric Christopher50daf5f2017-07-10 21:28:54 +00009424 #endif
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00009425 if (Context.getTargetInfo().getLongWidth() == 32)
9426 ++HowLong;
9427 break;
Kevin Qinad64f6d2014-02-24 02:45:03 +00009428 case 'W':
9429 // This modifier represents int64 type.
Andrew Savonichevfa8cd762019-06-03 12:34:59 +00009430 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
Kevin Qinad64f6d2014-02-24 02:45:03 +00009431 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
Eric Christopher50daf5f2017-07-10 21:28:54 +00009432 #ifndef NDEBUG
Karl-Johan Karlsson0e525a42019-05-16 07:18:02 +00009433 IsSpecial = true;
Eric Christopher50daf5f2017-07-10 21:28:54 +00009434 #endif
Kevin Qinad64f6d2014-02-24 02:45:03 +00009435 switch (Context.getTargetInfo().getInt64Type()) {
9436 default:
9437 llvm_unreachable("Unexpected integer type");
9438 case TargetInfo::SignedLong:
9439 HowLong = 1;
9440 break;
9441 case TargetInfo::SignedLongLong:
9442 HowLong = 2;
9443 break;
9444 }
Duncan P. N. Exon Smitheae8caa2017-06-14 21:26:31 +00009445 break;
Karl-Johan Karlsson0e525a42019-05-16 07:18:02 +00009446 case 'Z':
9447 // This modifier represents int32 type.
Andrew Savonichevfa8cd762019-06-03 12:34:59 +00009448 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
Karl-Johan Karlsson0e525a42019-05-16 07:18:02 +00009449 assert(HowLong == 0 && "Can't use both 'L' and 'Z' modifiers!");
9450 #ifndef NDEBUG
9451 IsSpecial = true;
9452 #endif
9453 switch (Context.getTargetInfo().getIntTypeByWidth(32, true)) {
9454 default:
9455 llvm_unreachable("Unexpected integer type");
9456 case TargetInfo::SignedInt:
9457 HowLong = 0;
9458 break;
9459 case TargetInfo::SignedLong:
9460 HowLong = 1;
9461 break;
9462 case TargetInfo::SignedLongLong:
9463 HowLong = 2;
9464 break;
9465 }
9466 break;
Andrew Savonichevfa8cd762019-06-03 12:34:59 +00009467 case 'O':
9468 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
9469 assert(HowLong == 0 && "Can't use both 'L' and 'O' modifiers!");
9470 #ifndef NDEBUG
9471 IsSpecial = true;
9472 #endif
9473 if (Context.getLangOpts().OpenCL)
9474 HowLong = 1;
9475 else
9476 HowLong = 2;
9477 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009478 }
9479 }
9480
9481 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00009482
Chris Lattnerecd79c62009-06-14 00:45:47 +00009483 // Read the base type.
9484 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00009485 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00009486 case 'v':
9487 assert(HowLong == 0 && !Signed && !Unsigned &&
9488 "Bad modifiers used with 'v'!");
9489 Type = Context.VoidTy;
9490 break;
Jack Carter24bef982013-08-15 15:16:57 +00009491 case 'h':
9492 assert(HowLong == 0 && !Signed && !Unsigned &&
Sean Silva2a995142015-01-16 21:44:26 +00009493 "Bad modifiers used with 'h'!");
Jack Carter24bef982013-08-15 15:16:57 +00009494 Type = Context.HalfTy;
9495 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009496 case 'f':
9497 assert(HowLong == 0 && !Signed && !Unsigned &&
9498 "Bad modifiers used with 'f'!");
9499 Type = Context.FloatTy;
9500 break;
9501 case 'd':
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009502 assert(HowLong < 3 && !Signed && !Unsigned &&
Chris Lattnerecd79c62009-06-14 00:45:47 +00009503 "Bad modifiers used with 'd'!");
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009504 if (HowLong == 1)
Chris Lattnerecd79c62009-06-14 00:45:47 +00009505 Type = Context.LongDoubleTy;
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009506 else if (HowLong == 2)
9507 Type = Context.Float128Ty;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009508 else
9509 Type = Context.DoubleTy;
9510 break;
9511 case 's':
9512 assert(HowLong == 0 && "Bad modifiers used with 's'!");
9513 if (Unsigned)
9514 Type = Context.UnsignedShortTy;
9515 else
9516 Type = Context.ShortTy;
9517 break;
9518 case 'i':
9519 if (HowLong == 3)
9520 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
9521 else if (HowLong == 2)
9522 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
9523 else if (HowLong == 1)
9524 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
9525 else
9526 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
9527 break;
9528 case 'c':
9529 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
9530 if (Signed)
9531 Type = Context.SignedCharTy;
9532 else if (Unsigned)
9533 Type = Context.UnsignedCharTy;
9534 else
9535 Type = Context.CharTy;
9536 break;
9537 case 'b': // boolean
9538 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
9539 Type = Context.BoolTy;
9540 break;
9541 case 'z': // size_t.
9542 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
9543 Type = Context.getSizeType();
9544 break;
Richard Smith8110c9d2016-11-29 19:45:17 +00009545 case 'w': // wchar_t.
9546 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
9547 Type = Context.getWideCharType();
9548 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009549 case 'F':
9550 Type = Context.getCFConstantStringType();
9551 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00009552 case 'G':
9553 Type = Context.getObjCIdType();
9554 break;
9555 case 'H':
9556 Type = Context.getObjCSelType();
9557 break;
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00009558 case 'M':
9559 Type = Context.getObjCSuperType();
9560 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009561 case 'a':
9562 Type = Context.getBuiltinVaListType();
9563 assert(!Type.isNull() && "builtin va list type not initialized!");
9564 break;
9565 case 'A':
9566 // This is a "reference" to a va_list; however, what exactly
9567 // this means depends on how va_list is defined. There are two
9568 // different kinds of va_list: ones passed by value, and ones
9569 // passed by reference. An example of a by-value va_list is
9570 // x86, where va_list is a char*. An example of by-ref va_list
9571 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
9572 // we want this argument to be a char*&; for x86-64, we want
9573 // it to be a __va_list_tag*.
9574 Type = Context.getBuiltinVaListType();
9575 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009576 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00009577 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009578 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00009579 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009580 break;
9581 case 'V': {
9582 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009583 unsigned NumElements = strtoul(Str, &End, 10);
9584 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00009585 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00009586
Fangrui Song6907ce22018-07-30 19:24:48 +00009587 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
Chandler Carruth45bbe012017-03-24 09:11:57 +00009588 RequiresICE, false);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009589 assert(!RequiresICE && "Can't require vector ICE");
Fangrui Song6907ce22018-07-30 19:24:48 +00009590
Chris Lattnerdc226c22010-10-01 22:42:38 +00009591 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00009592 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00009593 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009594 break;
9595 }
Douglas Gregorfed66992012-06-07 18:08:25 +00009596 case 'E': {
9597 char *End;
Fangrui Song6907ce22018-07-30 19:24:48 +00009598
Douglas Gregorfed66992012-06-07 18:08:25 +00009599 unsigned NumElements = strtoul(Str, &End, 10);
9600 assert(End != Str && "Missing vector size");
Fangrui Song6907ce22018-07-30 19:24:48 +00009601
Douglas Gregorfed66992012-06-07 18:08:25 +00009602 Str = End;
Fangrui Song6907ce22018-07-30 19:24:48 +00009603
Douglas Gregorfed66992012-06-07 18:08:25 +00009604 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
Chandler Carruth45bbe012017-03-24 09:11:57 +00009605 false);
Douglas Gregorfed66992012-06-07 18:08:25 +00009606 Type = Context.getExtVectorType(ElementType, NumElements);
Fangrui Song6907ce22018-07-30 19:24:48 +00009607 break;
Douglas Gregorfed66992012-06-07 18:08:25 +00009608 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00009609 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009610 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
Chandler Carruth45bbe012017-03-24 09:11:57 +00009611 false);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009612 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00009613 Type = Context.getComplexType(ElementType);
9614 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00009615 }
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009616 case 'Y':
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00009617 Type = Context.getPointerDiffType();
9618 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00009619 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00009620 Type = Context.getFILEType();
9621 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00009622 Error = ASTContext::GE_Missing_stdio;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009623 return {};
Chris Lattnerecd79c62009-06-14 00:45:47 +00009624 }
Mike Stump2adb4da2009-07-28 23:47:15 +00009625 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00009626 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00009627 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00009628 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00009629 else
9630 Type = Context.getjmp_bufType();
9631
Mike Stump2adb4da2009-07-28 23:47:15 +00009632 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00009633 Error = ASTContext::GE_Missing_setjmp;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009634 return {};
Mike Stump2adb4da2009-07-28 23:47:15 +00009635 }
9636 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00009637 case 'K':
9638 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
9639 Type = Context.getucontext_tType();
9640
9641 if (Type.isNull()) {
9642 Error = ASTContext::GE_Missing_ucontext;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009643 return {};
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00009644 }
9645 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00009646 case 'p':
9647 Type = Context.getProcessIDType();
9648 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00009649 }
Mike Stump11289f42009-09-09 15:08:12 +00009650
Chris Lattnerdc226c22010-10-01 22:42:38 +00009651 // If there are modifiers and if we're allowed to parse them, go for it.
9652 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009653 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00009654 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00009655 default: Done = true; --Str; break;
9656 case '*':
9657 case '&': {
9658 // Both pointers and references can have their pointee types
9659 // qualified with an address space.
9660 char *End;
9661 unsigned AddrSpace = strtoul(Str, &End, 10);
Matt Arsenaultc65f9662018-08-02 12:14:28 +00009662 if (End != Str) {
9663 // Note AddrSpace == 0 is not the same as an unspecified address space.
9664 Type = Context.getAddrSpaceQualType(
9665 Type,
9666 Context.getLangASForBuiltinAddressSpace(AddrSpace));
Chris Lattnerdc226c22010-10-01 22:42:38 +00009667 Str = End;
9668 }
9669 if (c == '*')
9670 Type = Context.getPointerType(Type);
9671 else
9672 Type = Context.getLValueReferenceType(Type);
9673 break;
9674 }
9675 // FIXME: There's no way to have a built-in with an rvalue ref arg.
9676 case 'C':
9677 Type = Type.withConst();
9678 break;
9679 case 'D':
9680 Type = Context.getVolatileType(Type);
9681 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00009682 case 'R':
9683 Type = Type.withRestrict();
9684 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009685 }
9686 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009687
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009688 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Fangrui Song6907ce22018-07-30 19:24:48 +00009689 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00009690
Chris Lattnerecd79c62009-06-14 00:45:47 +00009691 return Type;
9692}
9693
9694/// GetBuiltinType - Return the type for the specified builtin.
Chandler Carruth45bbe012017-03-24 09:11:57 +00009695QualType ASTContext::GetBuiltinType(unsigned Id,
9696 GetBuiltinTypeError &Error,
9697 unsigned *IntegerConstantArgs) const {
Eric Christopher02d5d862015-08-06 01:01:12 +00009698 const char *TypeStr = BuiltinInfo.getTypeString(Id);
Johannes Doerfertac991bb2019-01-19 05:36:54 +00009699 if (TypeStr[0] == '\0') {
9700 Error = GE_Missing_type;
9701 return {};
9702 }
Mike Stump11289f42009-09-09 15:08:12 +00009703
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009704 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00009705
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009706 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009707 Error = GE_None;
Chandler Carruth45bbe012017-03-24 09:11:57 +00009708 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
9709 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009710 if (Error != GE_None)
Eugene Zelenko7855e772018-04-03 00:11:50 +00009711 return {};
Fangrui Song6907ce22018-07-30 19:24:48 +00009712
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009713 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
Fangrui Song6907ce22018-07-30 19:24:48 +00009714
Chris Lattnerecd79c62009-06-14 00:45:47 +00009715 while (TypeStr[0] && TypeStr[0] != '.') {
Chandler Carruth45bbe012017-03-24 09:11:57 +00009716 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009717 if (Error != GE_None)
Eugene Zelenko7855e772018-04-03 00:11:50 +00009718 return {};
Chris Lattnerecd79c62009-06-14 00:45:47 +00009719
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009720 // If this argument is required to be an IntegerConstantExpression and the
9721 // caller cares, fill in the bitmask we return.
9722 if (RequiresICE && IntegerConstantArgs)
9723 *IntegerConstantArgs |= 1 << ArgTypes.size();
Fangrui Song6907ce22018-07-30 19:24:48 +00009724
Chris Lattnerecd79c62009-06-14 00:45:47 +00009725 // Do array -> pointer decay. The builtin should use the decayed type.
9726 if (Ty->isArrayType())
9727 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00009728
Chris Lattnerecd79c62009-06-14 00:45:47 +00009729 ArgTypes.push_back(Ty);
9730 }
9731
David Majnemerba3e5ec2015-03-13 18:26:17 +00009732 if (Id == Builtin::BI__GetExceptionInfo)
Eugene Zelenko7855e772018-04-03 00:11:50 +00009733 return {};
David Majnemerba3e5ec2015-03-13 18:26:17 +00009734
Chris Lattnerecd79c62009-06-14 00:45:47 +00009735 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
9736 "'.' should only occur at end of builtin type list!");
9737
Erich Keane881e83d2019-03-04 14:54:52 +00009738 bool Variadic = (TypeStr[0] == '.');
9739
Erich Keane00022812019-05-23 16:05:21 +00009740 FunctionType::ExtInfo EI(getDefaultCallingConvention(
9741 Variadic, /*IsCXXMethod=*/false, /*IsBuiltin=*/true));
John McCall991eb4b2010-12-21 00:44:39 +00009742 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
9743
John McCall991eb4b2010-12-21 00:44:39 +00009744
Richard Smith836de6b2016-12-19 23:59:34 +00009745 // We really shouldn't be making a no-proto type here.
9746 if (ArgTypes.empty() && Variadic && !getLangOpts().CPlusPlus)
John McCall991eb4b2010-12-21 00:44:39 +00009747 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00009748
John McCalldb40c7f2010-12-14 08:05:40 +00009749 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00009750 EPI.ExtInfo = EI;
9751 EPI.Variadic = Variadic;
Richard Smith391fb862016-10-18 07:13:55 +00009752 if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id))
9753 EPI.ExceptionSpec.Type =
9754 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
John McCalldb40c7f2010-12-14 08:05:40 +00009755
Jordan Rose5c382722013-03-08 21:51:21 +00009756 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009757}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00009758
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009759static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
9760 const FunctionDecl *FD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00009761 if (!FD->isExternallyVisible())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009762 return GVA_Internal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009763
Richard Smithe2467b72017-11-16 23:54:56 +00009764 // Non-user-provided functions get emitted as weak definitions with every
9765 // use, no matter whether they've been explicitly instantiated etc.
Eugene Zelenko7855e772018-04-03 00:11:50 +00009766 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
Richard Smithe2467b72017-11-16 23:54:56 +00009767 if (!MD->isUserProvided())
9768 return GVA_DiscardableODR;
9769
Yaron Keren4cd211b2017-02-22 14:32:39 +00009770 GVALinkage External;
Rafael Espindola3ae00052013-05-13 00:12:11 +00009771 switch (FD->getTemplateSpecializationKind()) {
9772 case TSK_Undeclared:
9773 case TSK_ExplicitSpecialization:
9774 External = GVA_StrongExternal;
9775 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009776
Rafael Espindola3ae00052013-05-13 00:12:11 +00009777 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00009778 return GVA_StrongODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00009779
David Majnemerc3d07332014-05-15 06:25:57 +00009780 // C++11 [temp.explicit]p10:
9781 // [ Note: The intent is that an inline function that is the subject of
9782 // an explicit instantiation declaration will still be implicitly
9783 // instantiated when used so that the body can be considered for
9784 // inlining, but that no out-of-line copy of the inline function would be
9785 // generated in the translation unit. -- end note ]
Rafael Espindola3ae00052013-05-13 00:12:11 +00009786 case TSK_ExplicitInstantiationDeclaration:
David Majnemer27d69db2014-04-28 22:17:59 +00009787 return GVA_AvailableExternally;
9788
Rafael Espindola3ae00052013-05-13 00:12:11 +00009789 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00009790 External = GVA_DiscardableODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00009791 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009792 }
9793
9794 if (!FD->isInlined())
9795 return External;
David Majnemer62f0ffd2013-08-01 17:26:42 +00009796
David Majnemer3f021502015-10-08 04:53:31 +00009797 if ((!Context.getLangOpts().CPlusPlus &&
9798 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009799 !FD->hasAttr<DLLExportAttr>()) ||
David Majnemer62f0ffd2013-08-01 17:26:42 +00009800 FD->hasAttr<GNUInlineAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009801 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
9802
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009803 // GNU or C99 inline semantics. Determine whether this symbol should be
9804 // externally visible.
9805 if (FD->isInlineDefinitionExternallyVisible())
9806 return External;
9807
9808 // C99 inline semantics, where the symbol is not externally visible.
David Majnemer27d69db2014-04-28 22:17:59 +00009809 return GVA_AvailableExternally;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009810 }
9811
David Majnemer54e3ba52014-04-02 23:17:29 +00009812 // Functions specified with extern and inline in -fms-compatibility mode
9813 // forcibly get emitted. While the body of the function cannot be later
9814 // replaced, the function definition cannot be discarded.
David Majnemer73768702015-03-20 00:02:27 +00009815 if (FD->isMSExternInline())
David Majnemer54e3ba52014-04-02 23:17:29 +00009816 return GVA_StrongODR;
9817
David Majnemer27d69db2014-04-28 22:17:59 +00009818 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009819}
9820
Artem Belevichca2b9512016-05-02 20:30:03 +00009821static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context,
Richard Smitha4653622017-09-06 20:01:14 +00009822 const Decl *D, GVALinkage L) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009823 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
9824 // dllexport/dllimport on inline functions.
9825 if (D->hasAttr<DLLImportAttr>()) {
9826 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
9827 return GVA_AvailableExternally;
Artem Belevichca2b9512016-05-02 20:30:03 +00009828 } else if (D->hasAttr<DLLExportAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009829 if (L == GVA_DiscardableODR)
9830 return GVA_StrongODR;
Artem Belevichca2b9512016-05-02 20:30:03 +00009831 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice &&
9832 D->hasAttr<CUDAGlobalAttr>()) {
9833 // Device-side functions with __global__ attribute must always be
9834 // visible externally so they can be launched from host.
9835 if (L == GVA_DiscardableODR || L == GVA_Internal)
9836 return GVA_StrongODR;
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009837 }
9838 return L;
9839}
9840
Richard Smitha4653622017-09-06 20:01:14 +00009841/// Adjust the GVALinkage for a declaration based on what an external AST source
9842/// knows about whether there can be other definitions of this declaration.
9843static GVALinkage
9844adjustGVALinkageForExternalDefinitionKind(const ASTContext &Ctx, const Decl *D,
9845 GVALinkage L) {
9846 ExternalASTSource *Source = Ctx.getExternalSource();
9847 if (!Source)
9848 return L;
9849
9850 switch (Source->hasExternalDefinitions(D)) {
David Blaikie9ffe5a32017-01-30 05:00:26 +00009851 case ExternalASTSource::EK_Never:
Richard Smitha4653622017-09-06 20:01:14 +00009852 // Other translation units rely on us to provide the definition.
David Blaikie9ffe5a32017-01-30 05:00:26 +00009853 if (L == GVA_DiscardableODR)
9854 return GVA_StrongODR;
9855 break;
Richard Smitha4653622017-09-06 20:01:14 +00009856
David Blaikie9ffe5a32017-01-30 05:00:26 +00009857 case ExternalASTSource::EK_Always:
9858 return GVA_AvailableExternally;
Richard Smitha4653622017-09-06 20:01:14 +00009859
David Blaikie9ffe5a32017-01-30 05:00:26 +00009860 case ExternalASTSource::EK_ReplyHazy:
9861 break;
9862 }
9863 return L;
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009864}
9865
Richard Smitha4653622017-09-06 20:01:14 +00009866GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
9867 return adjustGVALinkageForExternalDefinitionKind(*this, FD,
9868 adjustGVALinkageForAttributes(*this, FD,
9869 basicGVALinkageForFunction(*this, FD)));
9870}
9871
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009872static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
9873 const VarDecl *VD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00009874 if (!VD->isExternallyVisible())
9875 return GVA_Internal;
9876
David Majnemer27d69db2014-04-28 22:17:59 +00009877 if (VD->isStaticLocal()) {
David Majnemer27d69db2014-04-28 22:17:59 +00009878 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
9879 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
9880 LexicalContext = LexicalContext->getLexicalParent();
9881
David Blaikieeb210012017-01-27 23:11:10 +00009882 // ObjC Blocks can create local variables that don't have a FunctionDecl
9883 // LexicalContext.
9884 if (!LexicalContext)
9885 return GVA_DiscardableODR;
David Majnemer27d69db2014-04-28 22:17:59 +00009886
David Blaikieeb210012017-01-27 23:11:10 +00009887 // Otherwise, let the static local variable inherit its linkage from the
9888 // nearest enclosing function.
9889 auto StaticLocalLinkage =
9890 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
9891
9892 // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
9893 // be emitted in any object with references to the symbol for the object it
9894 // contains, whether inline or out-of-line."
9895 // Similar behavior is observed with MSVC. An alternative ABI could use
9896 // StrongODR/AvailableExternally to match the function, but none are
9897 // known/supported currently.
9898 if (StaticLocalLinkage == GVA_StrongODR ||
9899 StaticLocalLinkage == GVA_AvailableExternally)
9900 return GVA_DiscardableODR;
9901 return StaticLocalLinkage;
David Majnemer27d69db2014-04-28 22:17:59 +00009902 }
9903
Hans Wennborg56fc62b2014-07-17 20:25:23 +00009904 // MSVC treats in-class initialized static data members as definitions.
9905 // By giving them non-strong linkage, out-of-line definitions won't
9906 // cause link errors.
9907 if (Context.isMSStaticDataMemberInlineDefinition(VD))
9908 return GVA_DiscardableODR;
9909
Richard Smithd9b90092016-07-02 01:32:16 +00009910 // Most non-template variables have strong linkage; inline variables are
9911 // linkonce_odr or (occasionally, for compatibility) weak_odr.
9912 GVALinkage StrongLinkage;
9913 switch (Context.getInlineVariableDefinitionKind(VD)) {
9914 case ASTContext::InlineVariableDefinitionKind::None:
9915 StrongLinkage = GVA_StrongExternal;
9916 break;
9917 case ASTContext::InlineVariableDefinitionKind::Weak:
9918 case ASTContext::InlineVariableDefinitionKind::WeakUnknown:
Richard Smith62f19e72016-06-25 00:15:56 +00009919 StrongLinkage = GVA_DiscardableODR;
Richard Smithd9b90092016-07-02 01:32:16 +00009920 break;
9921 case ASTContext::InlineVariableDefinitionKind::Strong:
9922 StrongLinkage = GVA_StrongODR;
9923 break;
9924 }
Richard Smith62f19e72016-06-25 00:15:56 +00009925
Richard Smith8809a0c2013-09-27 20:14:12 +00009926 switch (VD->getTemplateSpecializationKind()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00009927 case TSK_Undeclared:
Richard Smith62f19e72016-06-25 00:15:56 +00009928 return StrongLinkage;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009929
David Majnemer6d1780c2015-07-17 23:36:49 +00009930 case TSK_ExplicitSpecialization:
Hans Wennborg4bdd5132019-09-25 11:09:46 +00009931 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
9932 VD->isStaticDataMember()
9933 ? GVA_StrongODR
9934 : StrongLinkage;
David Majnemer6d1780c2015-07-17 23:36:49 +00009935
Rafael Espindola3ae00052013-05-13 00:12:11 +00009936 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00009937 return GVA_StrongODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009938
David Majnemer27d69db2014-04-28 22:17:59 +00009939 case TSK_ExplicitInstantiationDeclaration:
9940 return GVA_AvailableExternally;
9941
Rafael Espindola3ae00052013-05-13 00:12:11 +00009942 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00009943 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009944 }
Rafael Espindola27699c82013-05-13 14:05:53 +00009945
9946 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009947}
9948
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009949GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
Richard Smitha4653622017-09-06 20:01:14 +00009950 return adjustGVALinkageForExternalDefinitionKind(*this, VD,
9951 adjustGVALinkageForAttributes(*this, VD,
9952 basicGVALinkageForVariable(*this, VD)));
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009953}
9954
David Blaikiee6b7c282017-04-11 20:46:34 +00009955bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00009956 if (const auto *VD = dyn_cast<VarDecl>(D)) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009957 if (!VD->isFileVarDecl())
9958 return false;
Renato Golin9258aa52014-05-21 10:40:27 +00009959 // Global named register variables (GNU extension) are never emitted.
9960 if (VD->getStorageClass() == SC_Register)
9961 return false;
Richard Smith7747ce22015-08-19 20:49:38 +00009962 if (VD->getDescribedVarTemplate() ||
9963 isa<VarTemplatePartialSpecializationDecl>(VD))
9964 return false;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009965 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
Richard Smith5205a8c2013-04-01 20:22:16 +00009966 // We never need to emit an uninstantiated function template.
9967 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
9968 return false;
Nico Weber66220292016-03-02 17:28:48 +00009969 } else if (isa<PragmaCommentDecl>(D))
9970 return true;
Nico Webercbbaeb12016-03-02 19:28:54 +00009971 else if (isa<PragmaDetectMismatchDecl>(D))
9972 return true;
Nico Weber66220292016-03-02 17:28:48 +00009973 else if (isa<OMPThreadPrivateDecl>(D))
Alexey Bataevc5b1d322016-03-04 09:22:22 +00009974 return !D->getDeclContext()->isDependentContext();
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009975 else if (isa<OMPAllocateDecl>(D))
9976 return !D->getDeclContext()->isDependentContext();
Michael Krused47b9432019-08-05 18:43:21 +00009977 else if (isa<OMPDeclareReductionDecl>(D) || isa<OMPDeclareMapperDecl>(D))
Alexey Bataevc5b1d322016-03-04 09:22:22 +00009978 return !D->getDeclContext()->isDependentContext();
Richard Smithdc1f0422016-07-20 19:10:16 +00009979 else if (isa<ImportDecl>(D))
9980 return true;
Alexey Bataev97720002014-11-11 04:05:39 +00009981 else
Richard Smith5205a8c2013-04-01 20:22:16 +00009982 return false;
9983
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00009984 if (D->isFromASTFile() && !LangOpts.BuildingPCHWithObjectFile) {
9985 assert(getExternalSource() && "It's from an AST file; must have a source.");
9986 // On Windows, PCH files are built together with an object file. If this
9987 // declaration comes from such a PCH and DeclMustBeEmitted would return
9988 // true, it would have returned true and the decl would have been emitted
9989 // into that object file, so it doesn't need to be emitted here.
9990 // Note that decls are still emitted if they're referenced, as usual;
9991 // DeclMustBeEmitted is used to decide whether a decl must be emitted even
9992 // if it's not referenced.
9993 //
9994 // Explicit template instantiation definitions are tricky. If there was an
9995 // explicit template instantiation decl in the PCH before, it will look like
9996 // the definition comes from there, even if that was just the declaration.
9997 // (Explicit instantiation defs of variable templates always get emitted.)
9998 bool IsExpInstDef =
9999 isa<FunctionDecl>(D) &&
10000 cast<FunctionDecl>(D)->getTemplateSpecializationKind() ==
10001 TSK_ExplicitInstantiationDefinition;
10002
Hans Wennborgb51a7032018-09-14 15:18:30 +000010003 // Implicit member function definitions, such as operator= might not be
10004 // marked as template specializations, since they're not coming from a
10005 // template but synthesized directly on the class.
10006 IsExpInstDef |=
10007 isa<CXXMethodDecl>(D) &&
10008 cast<CXXMethodDecl>(D)->getParent()->getTemplateSpecializationKind() ==
10009 TSK_ExplicitInstantiationDefinition;
10010
Hans Wennborg08c5a7b2018-06-25 13:23:49 +000010011 if (getExternalSource()->DeclIsFromPCHWithObjectFile(D) && !IsExpInstDef)
10012 return false;
10013 }
10014
Richard Smith5205a8c2013-04-01 20:22:16 +000010015 // If this is a member of a class template, we do not need to emit it.
10016 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +000010017 return false;
10018
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +000010019 // Weak references don't produce any output by themselves.
10020 if (D->hasAttr<WeakRefAttr>())
10021 return false;
10022
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +000010023 // Aliases and used decls are required.
10024 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
10025 return true;
10026
Eugene Zelenko7855e772018-04-03 00:11:50 +000010027 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +000010028 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +000010029 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +000010030 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +000010031
10032 // Constructors and destructors are required.
10033 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
10034 return true;
Hans Wennborg08c5a7b2018-06-25 13:23:49 +000010035
John McCall6bd2a892013-01-25 22:31:03 +000010036 // The key function for a class is required. This rule only comes
10037 // into play when inline functions can be key functions, though.
10038 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +000010039 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
John McCall6bd2a892013-01-25 22:31:03 +000010040 const CXXRecordDecl *RD = MD->getParent();
10041 if (MD->isOutOfLine() && RD->isDynamicClass()) {
10042 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
10043 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
10044 return true;
10045 }
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +000010046 }
10047 }
10048
David Blaikie9ffe5a32017-01-30 05:00:26 +000010049 GVALinkage Linkage = GetGVALinkageForFunction(FD);
10050
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +000010051 // static, static inline, always_inline, and extern inline functions can
10052 // always be deferred. Normal inline functions can be deferred in C99/C++.
10053 // Implicit template instantiations can also be deferred in C++.
David Blaikie9ffe5a32017-01-30 05:00:26 +000010054 return !isDiscardableGVALinkage(Linkage);
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +000010055 }
Hans Wennborg08c5a7b2018-06-25 13:23:49 +000010056
Eugene Zelenko7855e772018-04-03 00:11:50 +000010057 const auto *VD = cast<VarDecl>(D);
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +000010058 assert(VD->isFileVarDecl() && "Expected file scoped var");
10059
Alexey Bataevd01b7492018-08-15 19:45:12 +000010060 // If the decl is marked as `declare target to`, it should be emitted for the
10061 // host and for the device.
10062 if (LangOpts.OpenMP &&
10063 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
10064 return true;
10065
Hans Wennborg56fc62b2014-07-17 20:25:23 +000010066 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
10067 !isMSStaticDataMemberInlineDefinition(VD))
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +000010068 return false;
10069
Richard Smitha0e5e542012-11-12 21:38:00 +000010070 // Variables that can be needed in other TUs are required.
Richard Smitha4653622017-09-06 20:01:14 +000010071 auto Linkage = GetGVALinkageForVariable(VD);
10072 if (!isDiscardableGVALinkage(Linkage))
Richard Smitha0e5e542012-11-12 21:38:00 +000010073 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +000010074
Richard Smitha4653622017-09-06 20:01:14 +000010075 // We never need to emit a variable that is available in another TU.
10076 if (Linkage == GVA_AvailableExternally)
10077 return false;
10078
Richard Smitha0e5e542012-11-12 21:38:00 +000010079 // Variables that have destruction with side-effects are required.
Richard Smith2b4fa532019-09-29 05:08:46 +000010080 if (VD->needsDestruction(*this))
Richard Smitha0e5e542012-11-12 21:38:00 +000010081 return true;
10082
10083 // Variables that have initialization with side-effects are required.
Richard Smith7747ce22015-08-19 20:49:38 +000010084 if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
Richard Smith187ffb42017-01-20 01:19:46 +000010085 // We can get a value-dependent initializer during error recovery.
10086 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
Richard Smitha0e5e542012-11-12 21:38:00 +000010087 return true;
10088
Richard Smithda383632016-08-15 01:33:41 +000010089 // Likewise, variables with tuple-like bindings are required if their
10090 // bindings have side-effects.
Eugene Zelenko7855e772018-04-03 00:11:50 +000010091 if (const auto *DD = dyn_cast<DecompositionDecl>(VD))
10092 for (const auto *BD : DD->bindings())
10093 if (const auto *BindingVD = BD->getHoldingVar())
Richard Smithda383632016-08-15 01:33:41 +000010094 if (DeclMustBeEmitted(BindingVD))
10095 return true;
10096
Richard Smitha0e5e542012-11-12 21:38:00 +000010097 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +000010098}
Charles Davis53c59df2010-08-16 03:33:14 +000010099
Erich Keane281d20b2018-01-08 21:34:17 +000010100void ASTContext::forEachMultiversionedFunctionVersion(
10101 const FunctionDecl *FD,
Erich Keane0fb16482018-08-13 18:33:20 +000010102 llvm::function_ref<void(FunctionDecl *)> Pred) const {
Erich Keane281d20b2018-01-08 21:34:17 +000010103 assert(FD->isMultiVersion() && "Only valid for multiversioned functions");
10104 llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls;
Erich Keane7304f0a2018-11-28 20:58:43 +000010105 FD = FD->getMostRecentDecl();
Erich Keane281d20b2018-01-08 21:34:17 +000010106 for (auto *CurDecl :
10107 FD->getDeclContext()->getRedeclContext()->lookup(FD->getDeclName())) {
Erich Keane7304f0a2018-11-28 20:58:43 +000010108 FunctionDecl *CurFD = CurDecl->getAsFunction()->getMostRecentDecl();
Erich Keane281d20b2018-01-08 21:34:17 +000010109 if (CurFD && hasSameType(CurFD->getType(), FD->getType()) &&
10110 std::end(SeenDecls) == llvm::find(SeenDecls, CurFD)) {
10111 SeenDecls.insert(CurFD);
10112 Pred(CurFD);
10113 }
10114 }
10115}
10116
Reid Kleckner78af0702013-08-27 23:08:25 +000010117CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
Erich Keane00022812019-05-23 16:05:21 +000010118 bool IsCXXMethod,
10119 bool IsBuiltin) const {
Charles Davis99202b32010-11-09 18:04:24 +000010120 // Pass through to the C++ ABI object
Reid Kleckner78af0702013-08-27 23:08:25 +000010121 if (IsCXXMethod)
10122 return ABI->getDefaultMethodCallConv(IsVariadic);
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +000010123
Erich Keane00022812019-05-23 16:05:21 +000010124 // Builtins ignore user-specified default calling convention and remain the
10125 // Target's default calling convention.
10126 if (!IsBuiltin) {
10127 switch (LangOpts.getDefaultCallingConv()) {
10128 case LangOptions::DCC_None:
10129 break;
10130 case LangOptions::DCC_CDecl:
10131 return CC_C;
10132 case LangOptions::DCC_FastCall:
10133 if (getTargetInfo().hasFeature("sse2") && !IsVariadic)
10134 return CC_X86FastCall;
10135 break;
10136 case LangOptions::DCC_StdCall:
10137 if (!IsVariadic)
10138 return CC_X86StdCall;
10139 break;
10140 case LangOptions::DCC_VectorCall:
10141 // __vectorcall cannot be applied to variadic functions.
10142 if (!IsVariadic)
10143 return CC_X86VectorCall;
10144 break;
10145 case LangOptions::DCC_RegCall:
10146 // __regcall cannot be applied to variadic functions.
10147 if (!IsVariadic)
10148 return CC_X86RegCall;
10149 break;
10150 }
Alexey Bataeva7547182016-05-18 09:06:38 +000010151 }
Erich Keane39309482019-07-25 17:14:45 +000010152 return Target->getDefaultCallingConv();
Charles Davis99202b32010-11-09 18:04:24 +000010153}
10154
Jay Foad39c79802011-01-12 09:06:06 +000010155bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +000010156 // Pass through to the C++ ABI object
10157 return ABI->isNearlyEmpty(RD);
10158}
10159
Reid Kleckner96f8f932014-02-05 17:27:08 +000010160VTableContextBase *ASTContext::getVTableContext() {
10161 if (!VTContext.get()) {
10162 if (Target->getCXXABI().isMicrosoft())
10163 VTContext.reset(new MicrosoftVTableContext(*this));
10164 else
10165 VTContext.reset(new ItaniumVTableContext(*this));
10166 }
10167 return VTContext.get();
10168}
10169
Yaxun Liuc18e9ec2019-02-14 02:00:09 +000010170MangleContext *ASTContext::createMangleContext(const TargetInfo *T) {
10171 if (!T)
10172 T = Target;
10173 switch (T->getCXXABI().getKind()) {
Petr Hosek9c3f9b92019-09-06 18:59:43 -070010174 case TargetCXXABI::Fuchsia:
Tim Northover9bb857a2013-01-31 12:13:10 +000010175 case TargetCXXABI::GenericAArch64:
John McCall359b8852013-01-25 22:30:49 +000010176 case TargetCXXABI::GenericItanium:
10177 case TargetCXXABI::GenericARM:
Zoran Jovanovic26a12162015-02-18 15:21:35 +000010178 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +000010179 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +000010180 case TargetCXXABI::iOS64:
Dan Gohmanc2853072015-09-03 22:51:53 +000010181 case TargetCXXABI::WebAssembly:
Tim Northover756447a2015-10-30 16:30:36 +000010182 case TargetCXXABI::WatchOS:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +000010183 return ItaniumMangleContext::create(*this, getDiagnostics());
John McCall359b8852013-01-25 22:30:49 +000010184 case TargetCXXABI::Microsoft:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +000010185 return MicrosoftMangleContext::create(*this, getDiagnostics());
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000010186 }
David Blaikie83d382b2011-09-23 05:06:16 +000010187 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000010188}
10189
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000010190CXXABI::~CXXABI() = default;
Ted Kremenekf5df0ce2011-04-28 04:53:38 +000010191
10192size_t ASTContext::getSideTableAllocatedMemory() const {
Larisse Voufo39a1e502013-08-06 01:03:05 +000010193 return ASTRecordLayouts.getMemorySize() +
10194 llvm::capacity_in_bytes(ObjCLayouts) +
10195 llvm::capacity_in_bytes(KeyFunctions) +
10196 llvm::capacity_in_bytes(ObjCImpls) +
10197 llvm::capacity_in_bytes(BlockVarCopyInits) +
10198 llvm::capacity_in_bytes(DeclAttrs) +
10199 llvm::capacity_in_bytes(TemplateOrInstantiation) +
10200 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
10201 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
10202 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
10203 llvm::capacity_in_bytes(OverriddenMethods) +
10204 llvm::capacity_in_bytes(Types) +
Richard Smithf19a8b02019-05-02 00:49:14 +000010205 llvm::capacity_in_bytes(VariableArrayTypes);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +000010206}
Ted Kremenek540017e2011-10-06 05:00:56 +000010207
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +000010208/// getIntTypeForBitwidth -
10209/// sets integer QualTy according to specified details:
10210/// bitwidth, signed/unsigned.
10211/// Returns empty type if there is no appropriate target types.
10212QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
10213 unsigned Signed) const {
10214 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
10215 CanQualType QualTy = getFromTargetType(Ty);
10216 if (!QualTy && DestWidth == 128)
10217 return Signed ? Int128Ty : UnsignedInt128Ty;
10218 return QualTy;
10219}
10220
10221/// getRealTypeForBitwidth -
10222/// sets floating point QualTy according to specified bitwidth.
10223/// Returns empty type if there is no appropriate target types.
10224QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
10225 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
10226 switch (Ty) {
10227 case TargetInfo::Float:
10228 return FloatTy;
10229 case TargetInfo::Double:
10230 return DoubleTy;
10231 case TargetInfo::LongDouble:
10232 return LongDoubleTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +000010233 case TargetInfo::Float128:
10234 return Float128Ty;
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +000010235 case TargetInfo::NoFloat:
Eugene Zelenko7855e772018-04-03 00:11:50 +000010236 return {};
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +000010237 }
10238
10239 llvm_unreachable("Unhandled TargetInfo::RealType value");
10240}
10241
Eli Friedman3b7d46c2013-07-10 00:30:46 +000010242void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
10243 if (Number > 1)
10244 MangleNumbers[ND] = Number;
David Blaikie095deba2012-11-14 01:52:05 +000010245}
10246
Eli Friedman3b7d46c2013-07-10 00:30:46 +000010247unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
Richard Smithe9b02d62016-03-21 22:33:02 +000010248 auto I = MangleNumbers.find(ND);
Eli Friedman3b7d46c2013-07-10 00:30:46 +000010249 return I != MangleNumbers.end() ? I->second : 1;
David Blaikie095deba2012-11-14 01:52:05 +000010250}
10251
David Majnemer2206bf52014-03-05 08:57:59 +000010252void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
10253 if (Number > 1)
10254 StaticLocalNumbers[VD] = Number;
10255}
10256
10257unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
Richard Smithe9b02d62016-03-21 22:33:02 +000010258 auto I = StaticLocalNumbers.find(VD);
David Majnemer2206bf52014-03-05 08:57:59 +000010259 return I != StaticLocalNumbers.end() ? I->second : 1;
10260}
10261
Eli Friedman3b7d46c2013-07-10 00:30:46 +000010262MangleNumberingContext &
10263ASTContext::getManglingNumberContext(const DeclContext *DC) {
Reid Klecknerd8110b62013-09-10 20:14:30 +000010264 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
Justin Lebar20ebffc2016-10-10 16:26:19 +000010265 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
Reid Klecknerd8110b62013-09-10 20:14:30 +000010266 if (!MCtx)
10267 MCtx = createMangleNumberingContext();
10268 return *MCtx;
10269}
10270
Reid Klecknerda2bde92019-10-10 01:14:22 +000010271MangleNumberingContext &
10272ASTContext::getManglingNumberContext(NeedExtraManglingDecl_t, const Decl *D) {
10273 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
10274 std::unique_ptr<MangleNumberingContext> &MCtx =
10275 ExtraMangleNumberingContexts[D];
10276 if (!MCtx)
10277 MCtx = createMangleNumberingContext();
10278 return *MCtx;
10279}
10280
Justin Lebar20ebffc2016-10-10 16:26:19 +000010281std::unique_ptr<MangleNumberingContext>
10282ASTContext::createMangleNumberingContext() const {
Reid Klecknerd8110b62013-09-10 20:14:30 +000010283 return ABI->createMangleNumberingContext();
Douglas Gregor63798542012-02-20 19:44:39 +000010284}
10285
David Majnemere7a818f2015-03-06 18:53:55 +000010286const CXXConstructorDecl *
10287ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
10288 return ABI->getCopyConstructorForExceptionObject(
10289 cast<CXXRecordDecl>(RD->getFirstDecl()));
10290}
10291
10292void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
10293 CXXConstructorDecl *CD) {
10294 return ABI->addCopyConstructorForExceptionObject(
10295 cast<CXXRecordDecl>(RD->getFirstDecl()),
10296 cast<CXXConstructorDecl>(CD->getFirstDecl()));
10297}
10298
David Majnemer00350522015-08-31 18:48:39 +000010299void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD,
10300 TypedefNameDecl *DD) {
10301 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
10302}
10303
10304TypedefNameDecl *
10305ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) {
10306 return ABI->getTypedefNameForUnnamedTagDecl(TD);
10307}
10308
10309void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD,
10310 DeclaratorDecl *DD) {
10311 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
10312}
10313
10314DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) {
10315 return ABI->getDeclaratorForUnnamedTagDecl(TD);
10316}
10317
Ted Kremenek540017e2011-10-06 05:00:56 +000010318void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
10319 ParamIndices[D] = index;
10320}
10321
10322unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
10323 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
Fangrui Song6907ce22018-07-30 19:24:48 +000010324 assert(I != ParamIndices.end() &&
Ted Kremenek540017e2011-10-06 05:00:56 +000010325 "ParmIndices lacks entry set by ParmVarDecl");
10326 return I->second;
10327}
Fariborz Jahanian615de762013-05-28 17:37:39 +000010328
Eric Fiselier708afb52019-05-16 21:04:15 +000010329QualType ASTContext::getStringLiteralArrayType(QualType EltTy,
10330 unsigned Length) const {
10331 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
10332 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
10333 EltTy = EltTy.withConst();
10334
10335 EltTy = adjustStringLiteralBaseType(EltTy);
10336
10337 // Get an array type for the string, according to C99 6.4.5. This includes
10338 // the null terminator character.
Richard Smith772e2662019-10-04 01:25:59 +000010339 return getConstantArrayType(EltTy, llvm::APInt(32, Length + 1), nullptr,
Eric Fiselier708afb52019-05-16 21:04:15 +000010340 ArrayType::Normal, /*IndexTypeQuals*/ 0);
10341}
10342
10343StringLiteral *
10344ASTContext::getPredefinedStringLiteralFromCache(StringRef Key) const {
10345 StringLiteral *&Result = StringLiteralCache[Key];
10346 if (!Result)
10347 Result = StringLiteral::Create(
10348 *this, Key, StringLiteral::Ascii,
10349 /*Pascal*/ false, getStringLiteralArrayType(CharTy, Key.size()),
10350 SourceLocation());
10351 return Result;
10352}
10353
Fariborz Jahanian615de762013-05-28 17:37:39 +000010354bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
10355 const llvm::Triple &T = getTargetInfo().getTriple();
10356 if (!T.isOSDarwin())
10357 return false;
10358
Bob Wilson2c82c3d2013-11-02 23:27:49 +000010359 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
10360 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
10361 return false;
10362
Fariborz Jahanian615de762013-05-28 17:37:39 +000010363 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
10364 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
10365 uint64_t Size = sizeChars.getQuantity();
10366 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
10367 unsigned Align = alignChars.getQuantity();
10368 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
10369 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
10370}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010371
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010372/// Template specializations to abstract away from pointers and TypeLocs.
10373/// @{
10374template <typename T>
Sam McCall814e7972018-11-14 10:33:30 +000010375static ast_type_traits::DynTypedNode createDynTypedNode(const T &Node) {
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010376 return ast_type_traits::DynTypedNode::create(*Node);
10377}
10378template <>
10379ast_type_traits::DynTypedNode createDynTypedNode(const TypeLoc &Node) {
10380 return ast_type_traits::DynTypedNode::create(Node);
10381}
10382template <>
10383ast_type_traits::DynTypedNode
10384createDynTypedNode(const NestedNameSpecifierLoc &Node) {
10385 return ast_type_traits::DynTypedNode::create(Node);
10386}
10387/// @}
10388
Sam McCall814e7972018-11-14 10:33:30 +000010389/// A \c RecursiveASTVisitor that builds a map from nodes to their
10390/// parents as defined by the \c RecursiveASTVisitor.
10391///
10392/// Note that the relationship described here is purely in terms of AST
10393/// traversal - there are other relationships (for example declaration context)
10394/// in the AST that are better modeled by special matchers.
10395///
10396/// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
10397class ASTContext::ParentMap::ASTVisitor
10398 : public RecursiveASTVisitor<ASTVisitor> {
10399public:
10400 ASTVisitor(ParentMap &Map) : Map(Map) {}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010401
Sam McCall814e7972018-11-14 10:33:30 +000010402private:
10403 friend class RecursiveASTVisitor<ASTVisitor>;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000010404
Sam McCall814e7972018-11-14 10:33:30 +000010405 using VisitorBase = RecursiveASTVisitor<ASTVisitor>;
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010406
Sam McCall814e7972018-11-14 10:33:30 +000010407 bool shouldVisitTemplateInstantiations() const { return true; }
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010408
Sam McCall814e7972018-11-14 10:33:30 +000010409 bool shouldVisitImplicitCode() const { return true; }
10410
10411 template <typename T, typename MapNodeTy, typename BaseTraverseFn,
10412 typename MapTy>
10413 bool TraverseNode(T Node, MapNodeTy MapNode, BaseTraverseFn BaseTraverse,
10414 MapTy *Parents) {
10415 if (!Node)
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010416 return true;
Sam McCall814e7972018-11-14 10:33:30 +000010417 if (ParentStack.size() > 0) {
10418 // FIXME: Currently we add the same parent multiple times, but only
10419 // when no memoization data is available for the type.
10420 // For example when we visit all subexpressions of template
10421 // instantiations; this is suboptimal, but benign: the only way to
10422 // visit those is with hasAncestor / hasParent, and those do not create
10423 // new matches.
10424 // The plan is to enable DynTypedNode to be storable in a map or hash
10425 // map. The main problem there is to implement hash functions /
10426 // comparison operators for all types that DynTypedNode supports that
10427 // do not have pointer identity.
10428 auto &NodeOrVector = (*Parents)[MapNode];
10429 if (NodeOrVector.isNull()) {
10430 if (const auto *D = ParentStack.back().get<Decl>())
10431 NodeOrVector = D;
10432 else if (const auto *S = ParentStack.back().get<Stmt>())
10433 NodeOrVector = S;
10434 else
10435 NodeOrVector = new ast_type_traits::DynTypedNode(ParentStack.back());
10436 } else {
10437 if (!NodeOrVector.template is<ParentVector *>()) {
10438 auto *Vector = new ParentVector(
10439 1, getSingleDynTypedNodeFromParentMap(NodeOrVector));
10440 delete NodeOrVector
10441 .template dyn_cast<ast_type_traits::DynTypedNode *>();
10442 NodeOrVector = Vector;
Manuel Klimek95403e62014-05-21 13:28:59 +000010443 }
Sam McCall814e7972018-11-14 10:33:30 +000010444
10445 auto *Vector = NodeOrVector.template get<ParentVector *>();
10446 // Skip duplicates for types that have memoization data.
10447 // We must check that the type has memoization data before calling
10448 // std::find() because DynTypedNode::operator== can't compare all
10449 // types.
10450 bool Found = ParentStack.back().getMemoizationData() &&
10451 std::find(Vector->begin(), Vector->end(),
10452 ParentStack.back()) != Vector->end();
10453 if (!Found)
10454 Vector->push_back(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +000010455 }
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010456 }
Sam McCall814e7972018-11-14 10:33:30 +000010457 ParentStack.push_back(createDynTypedNode(Node));
10458 bool Result = BaseTraverse();
10459 ParentStack.pop_back();
10460 return Result;
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010461 }
Sam McCall814e7972018-11-14 10:33:30 +000010462
10463 bool TraverseDecl(Decl *DeclNode) {
10464 return TraverseNode(
10465 DeclNode, DeclNode, [&] { return VisitorBase::TraverseDecl(DeclNode); },
10466 &Map.PointerParents);
Manuel Klimek95403e62014-05-21 13:28:59 +000010467 }
Sam McCall814e7972018-11-14 10:33:30 +000010468
10469 bool TraverseStmt(Stmt *StmtNode) {
10470 return TraverseNode(
10471 StmtNode, StmtNode, [&] { return VisitorBase::TraverseStmt(StmtNode); },
10472 &Map.PointerParents);
10473 }
10474
10475 bool TraverseTypeLoc(TypeLoc TypeLocNode) {
10476 return TraverseNode(
10477 TypeLocNode, ast_type_traits::DynTypedNode::create(TypeLocNode),
10478 [&] { return VisitorBase::TraverseTypeLoc(TypeLocNode); },
10479 &Map.OtherParents);
10480 }
10481
10482 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNSLocNode) {
10483 return TraverseNode(
10484 NNSLocNode, ast_type_traits::DynTypedNode::create(NNSLocNode),
10485 [&] { return VisitorBase::TraverseNestedNameSpecifierLoc(NNSLocNode); },
10486 &Map.OtherParents);
10487 }
10488
10489 ParentMap &Map;
10490 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
10491};
10492
10493ASTContext::ParentMap::ParentMap(ASTContext &Ctx) {
10494 ASTVisitor(*this).TraverseAST(Ctx);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010495}
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010496
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010497ASTContext::DynTypedNodeList
10498ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
Sam McCall814e7972018-11-14 10:33:30 +000010499 if (!Parents)
10500 // We build the parent map for the traversal scope (usually whole TU), as
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010501 // hasAncestor can escape any subtree.
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +000010502 Parents = std::make_unique<ParentMap>(*this);
Sam McCall814e7972018-11-14 10:33:30 +000010503 return Parents->getParents(Node);
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010504}
10505
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010506bool
10507ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
10508 const ObjCMethodDecl *MethodImpl) {
10509 // No point trying to match an unavailable/deprecated mothod.
10510 if (MethodDecl->hasAttr<UnavailableAttr>()
10511 || MethodDecl->hasAttr<DeprecatedAttr>())
10512 return false;
10513 if (MethodDecl->getObjCDeclQualifier() !=
10514 MethodImpl->getObjCDeclQualifier())
10515 return false;
Alp Toker314cc812014-01-25 16:55:45 +000010516 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010517 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +000010518
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010519 if (MethodDecl->param_size() != MethodImpl->param_size())
10520 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +000010521
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010522 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
10523 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
10524 EF = MethodDecl->param_end();
10525 IM != EM && IF != EF; ++IM, ++IF) {
10526 const ParmVarDecl *DeclVar = (*IF);
10527 const ParmVarDecl *ImplVar = (*IM);
10528 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
10529 return false;
10530 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
10531 return false;
10532 }
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000010533
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010534 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010535}
Richard Smith053f6c62014-05-16 23:01:30 +000010536
Yaxun Liu402804b2016-12-15 08:09:08 +000010537uint64_t ASTContext::getTargetNullPointerValue(QualType QT) const {
Alexander Richardson6d989432017-10-15 18:48:14 +000010538 LangAS AS;
Yaxun Liu402804b2016-12-15 08:09:08 +000010539 if (QT->getUnqualifiedDesugaredType()->isNullPtrType())
Alexander Richardson6d989432017-10-15 18:48:14 +000010540 AS = LangAS::Default;
Yaxun Liu402804b2016-12-15 08:09:08 +000010541 else
10542 AS = QT->getPointeeType().getAddressSpace();
10543
10544 return getTargetInfo().getNullPointerValue(AS);
10545}
10546
Alexander Richardson6d989432017-10-15 18:48:14 +000010547unsigned ASTContext::getTargetAddressSpace(LangAS AS) const {
10548 if (isTargetAddressSpace(AS))
10549 return toTargetAddressSpace(AS);
Yaxun Liub34ec822017-04-11 17:24:23 +000010550 else
Alexander Richardson6d989432017-10-15 18:48:14 +000010551 return (*AddrSpaceMap)[(unsigned)AS];
Yaxun Liub34ec822017-04-11 17:24:23 +000010552}
10553
Leonard Chanab80f3c2018-06-14 14:53:51 +000010554QualType ASTContext::getCorrespondingSaturatedType(QualType Ty) const {
10555 assert(Ty->isFixedPointType());
10556
10557 if (Ty->isSaturatedFixedPointType()) return Ty;
10558
Simon Pilgrimeed4b122019-10-02 11:48:06 +000010559 switch (Ty->castAs<BuiltinType>()->getKind()) {
Leonard Chanab80f3c2018-06-14 14:53:51 +000010560 default:
10561 llvm_unreachable("Not a fixed point type!");
10562 case BuiltinType::ShortAccum:
10563 return SatShortAccumTy;
10564 case BuiltinType::Accum:
10565 return SatAccumTy;
10566 case BuiltinType::LongAccum:
10567 return SatLongAccumTy;
10568 case BuiltinType::UShortAccum:
10569 return SatUnsignedShortAccumTy;
10570 case BuiltinType::UAccum:
10571 return SatUnsignedAccumTy;
10572 case BuiltinType::ULongAccum:
10573 return SatUnsignedLongAccumTy;
10574 case BuiltinType::ShortFract:
10575 return SatShortFractTy;
10576 case BuiltinType::Fract:
10577 return SatFractTy;
10578 case BuiltinType::LongFract:
10579 return SatLongFractTy;
10580 case BuiltinType::UShortFract:
10581 return SatUnsignedShortFractTy;
10582 case BuiltinType::UFract:
10583 return SatUnsignedFractTy;
10584 case BuiltinType::ULongFract:
10585 return SatUnsignedLongFractTy;
10586 }
10587}
10588
Matt Arsenaultc65f9662018-08-02 12:14:28 +000010589LangAS ASTContext::getLangASForBuiltinAddressSpace(unsigned AS) const {
10590 if (LangOpts.OpenCL)
10591 return getTargetInfo().getOpenCLBuiltinAddressSpace(AS);
10592
10593 if (LangOpts.CUDA)
10594 return getTargetInfo().getCUDABuiltinAddressSpace(AS);
10595
10596 return getLangASFromTargetAS(AS);
10597}
10598
Richard Smith053f6c62014-05-16 23:01:30 +000010599// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
10600// doesn't include ASTContext.h
10601template
10602clang::LazyGenerationalUpdatePtr<
10603 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
10604clang::LazyGenerationalUpdatePtr<
10605 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
10606 const clang::ASTContext &Ctx, Decl *Value);
Leonard Chandb01c3a2018-06-20 17:19:40 +000010607
10608unsigned char ASTContext::getFixedPointScale(QualType Ty) const {
10609 assert(Ty->isFixedPointType());
10610
Leonard Chandb01c3a2018-06-20 17:19:40 +000010611 const TargetInfo &Target = getTargetInfo();
Simon Pilgrim9588ae72019-10-03 21:47:42 +000010612 switch (Ty->castAs<BuiltinType>()->getKind()) {
Leonard Chandb01c3a2018-06-20 17:19:40 +000010613 default:
10614 llvm_unreachable("Not a fixed point type!");
10615 case BuiltinType::ShortAccum:
10616 case BuiltinType::SatShortAccum:
10617 return Target.getShortAccumScale();
10618 case BuiltinType::Accum:
10619 case BuiltinType::SatAccum:
10620 return Target.getAccumScale();
10621 case BuiltinType::LongAccum:
10622 case BuiltinType::SatLongAccum:
10623 return Target.getLongAccumScale();
10624 case BuiltinType::UShortAccum:
10625 case BuiltinType::SatUShortAccum:
10626 return Target.getUnsignedShortAccumScale();
10627 case BuiltinType::UAccum:
10628 case BuiltinType::SatUAccum:
10629 return Target.getUnsignedAccumScale();
10630 case BuiltinType::ULongAccum:
10631 case BuiltinType::SatULongAccum:
10632 return Target.getUnsignedLongAccumScale();
10633 case BuiltinType::ShortFract:
10634 case BuiltinType::SatShortFract:
10635 return Target.getShortFractScale();
10636 case BuiltinType::Fract:
10637 case BuiltinType::SatFract:
10638 return Target.getFractScale();
10639 case BuiltinType::LongFract:
10640 case BuiltinType::SatLongFract:
10641 return Target.getLongFractScale();
10642 case BuiltinType::UShortFract:
10643 case BuiltinType::SatUShortFract:
10644 return Target.getUnsignedShortFractScale();
10645 case BuiltinType::UFract:
10646 case BuiltinType::SatUFract:
10647 return Target.getUnsignedFractScale();
10648 case BuiltinType::ULongFract:
10649 case BuiltinType::SatULongFract:
10650 return Target.getUnsignedLongFractScale();
10651 }
10652}
10653
10654unsigned char ASTContext::getFixedPointIBits(QualType Ty) const {
10655 assert(Ty->isFixedPointType());
10656
Leonard Chandb01c3a2018-06-20 17:19:40 +000010657 const TargetInfo &Target = getTargetInfo();
Simon Pilgrim9588ae72019-10-03 21:47:42 +000010658 switch (Ty->castAs<BuiltinType>()->getKind()) {
Leonard Chandb01c3a2018-06-20 17:19:40 +000010659 default:
10660 llvm_unreachable("Not a fixed point type!");
10661 case BuiltinType::ShortAccum:
10662 case BuiltinType::SatShortAccum:
10663 return Target.getShortAccumIBits();
10664 case BuiltinType::Accum:
10665 case BuiltinType::SatAccum:
10666 return Target.getAccumIBits();
10667 case BuiltinType::LongAccum:
10668 case BuiltinType::SatLongAccum:
10669 return Target.getLongAccumIBits();
10670 case BuiltinType::UShortAccum:
10671 case BuiltinType::SatUShortAccum:
10672 return Target.getUnsignedShortAccumIBits();
10673 case BuiltinType::UAccum:
10674 case BuiltinType::SatUAccum:
10675 return Target.getUnsignedAccumIBits();
10676 case BuiltinType::ULongAccum:
10677 case BuiltinType::SatULongAccum:
10678 return Target.getUnsignedLongAccumIBits();
10679 case BuiltinType::ShortFract:
10680 case BuiltinType::SatShortFract:
10681 case BuiltinType::Fract:
10682 case BuiltinType::SatFract:
10683 case BuiltinType::LongFract:
10684 case BuiltinType::SatLongFract:
10685 case BuiltinType::UShortFract:
10686 case BuiltinType::SatUShortFract:
10687 case BuiltinType::UFract:
10688 case BuiltinType::SatUFract:
10689 case BuiltinType::ULongFract:
10690 case BuiltinType::SatULongFract:
10691 return 0;
10692 }
10693}
Leonard Chana6779422018-08-06 16:42:37 +000010694
10695FixedPointSemantics ASTContext::getFixedPointSemantics(QualType Ty) const {
Erich Keane8e772162019-01-18 19:31:54 +000010696 assert((Ty->isFixedPointType() || Ty->isIntegerType()) &&
10697 "Can only get the fixed point semantics for a "
10698 "fixed point or integer type.");
Leonard Chan2044ac82019-01-16 18:13:59 +000010699 if (Ty->isIntegerType())
10700 return FixedPointSemantics::GetIntegerSemantics(getIntWidth(Ty),
10701 Ty->isSignedIntegerType());
10702
Leonard Chana6779422018-08-06 16:42:37 +000010703 bool isSigned = Ty->isSignedFixedPointType();
10704 return FixedPointSemantics(
10705 static_cast<unsigned>(getTypeSize(Ty)), getFixedPointScale(Ty), isSigned,
10706 Ty->isSaturatedFixedPointType(),
10707 !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding());
10708}
10709
10710APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const {
10711 assert(Ty->isFixedPointType());
10712 return APFixedPoint::getMax(getFixedPointSemantics(Ty));
10713}
10714
10715APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const {
10716 assert(Ty->isFixedPointType());
10717 return APFixedPoint::getMin(getFixedPointSemantics(Ty));
10718}
Leonard Chan2044ac82019-01-16 18:13:59 +000010719
10720QualType ASTContext::getCorrespondingSignedFixedPointType(QualType Ty) const {
10721 assert(Ty->isUnsignedFixedPointType() &&
10722 "Expected unsigned fixed point type");
Leonard Chan2044ac82019-01-16 18:13:59 +000010723
Simon Pilgrim9588ae72019-10-03 21:47:42 +000010724 switch (Ty->castAs<BuiltinType>()->getKind()) {
Leonard Chan2044ac82019-01-16 18:13:59 +000010725 case BuiltinType::UShortAccum:
10726 return ShortAccumTy;
10727 case BuiltinType::UAccum:
10728 return AccumTy;
10729 case BuiltinType::ULongAccum:
10730 return LongAccumTy;
10731 case BuiltinType::SatUShortAccum:
10732 return SatShortAccumTy;
10733 case BuiltinType::SatUAccum:
10734 return SatAccumTy;
10735 case BuiltinType::SatULongAccum:
10736 return SatLongAccumTy;
10737 case BuiltinType::UShortFract:
10738 return ShortFractTy;
10739 case BuiltinType::UFract:
10740 return FractTy;
10741 case BuiltinType::ULongFract:
10742 return LongFractTy;
10743 case BuiltinType::SatUShortFract:
10744 return SatShortFractTy;
10745 case BuiltinType::SatUFract:
10746 return SatFractTy;
10747 case BuiltinType::SatULongFract:
10748 return SatLongFractTy;
10749 default:
10750 llvm_unreachable("Unexpected unsigned fixed point type");
10751 }
10752}