blob: 34bb07cd3f78bab295c85f2572fa4e32aa74a3aa [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"
Sam McCalla2aa9972020-03-19 11:58:00 +010032#include "clang/AST/DependenceFlags.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000033#include "clang/AST/Expr.h"
John McCall87fe5d52010-05-20 01:18:31 +000034#include "clang/AST/ExprCXX.h"
Reid Kleckner8a81daa2019-12-09 17:03:47 -080035#include "clang/AST/ExprConcepts.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000036#include "clang/AST/ExternalASTSource.h"
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000037#include "clang/AST/Mangle.h"
Reid Klecknerd8110b62013-09-10 20:14:30 +000038#include "clang/AST/MangleNumberingContext.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000039#include "clang/AST/NestedNameSpecifier.h"
Reid Kleckner8a81daa2019-12-09 17:03:47 -080040#include "clang/AST/ParentMapContext.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000041#include "clang/AST/RawCommentList.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000042#include "clang/AST/RecordLayout.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000043#include "clang/AST/Stmt.h"
44#include "clang/AST/TemplateBase.h"
45#include "clang/AST/TemplateName.h"
46#include "clang/AST/Type.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000047#include "clang/AST/TypeLoc.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000048#include "clang/AST/UnresolvedSet.h"
Reid Kleckner96f8f932014-02-05 17:27:08 +000049#include "clang/AST/VTableBuilder.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000050#include "clang/Basic/AddressSpaces.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000051#include "clang/Basic/Builtins.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000052#include "clang/Basic/CommentOptions.h"
Eugene Zelenko7855e772018-04-03 00:11:50 +000053#include "clang/Basic/ExceptionSpecificationType.h"
Leonard Chana6779422018-08-06 16:42:37 +000054#include "clang/Basic/FixedPoint.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000055#include "clang/Basic/IdentifierTable.h"
56#include "clang/Basic/LLVM.h"
57#include "clang/Basic/LangOptions.h"
58#include "clang/Basic/Linkage.h"
Reid Klecknerc915cb92020-02-27 18:13:54 -080059#include "clang/Basic/Module.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000060#include "clang/Basic/ObjCRuntime.h"
61#include "clang/Basic/SanitizerBlacklist.h"
62#include "clang/Basic/SourceLocation.h"
Chris Lattnerd2868512009-03-28 03:45:20 +000063#include "clang/Basic/SourceManager.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000064#include "clang/Basic/Specifiers.h"
65#include "clang/Basic/TargetCXXABI.h"
Chris Lattner4dc8a6f2007-05-20 23:50:58 +000066#include "clang/Basic/TargetInfo.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000067#include "clang/Basic/XRayLists.h"
68#include "llvm/ADT/APInt.h"
69#include "llvm/ADT/APSInt.h"
70#include "llvm/ADT/ArrayRef.h"
71#include "llvm/ADT/DenseMap.h"
72#include "llvm/ADT/DenseSet.h"
73#include "llvm/ADT/FoldingSet.h"
74#include "llvm/ADT/None.h"
75#include "llvm/ADT/Optional.h"
76#include "llvm/ADT/PointerUnion.h"
77#include "llvm/ADT/STLExtras.h"
78#include "llvm/ADT/SmallPtrSet.h"
79#include "llvm/ADT/SmallVector.h"
Anders Carlssond8499822007-10-29 05:01:08 +000080#include "llvm/ADT/StringExtras.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000081#include "llvm/ADT/StringRef.h"
Robert Lyttoneaf6f362013-11-12 10:09:34 +000082#include "llvm/ADT/Triple.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000083#include "llvm/Support/Capacity.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000084#include "llvm/Support/Casting.h"
85#include "llvm/Support/Compiler.h"
86#include "llvm/Support/ErrorHandling.h"
Nate Begemanb699c9b2009-01-18 06:42:49 +000087#include "llvm/Support/MathExtras.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000088#include "llvm/Support/raw_ostream.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000089#include <algorithm>
90#include <cassert>
91#include <cstddef>
92#include <cstdint>
93#include <cstdlib>
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +000094#include <map>
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000095#include <memory>
96#include <string>
97#include <tuple>
98#include <utility>
Anders Carlssona4267a62009-07-18 21:19:52 +000099
Chris Lattnerddc135e2006-11-10 06:34:16 +0000100using namespace clang;
101
Steve Naroff0af91202007-04-27 21:51:21 +0000102enum FloatingRank {
Sjoerd Meijercc623ad2017-09-08 15:15:00 +0000103 Float16Rank, HalfRank, FloatRank, DoubleRank, LongDoubleRank, Float128Rank
Steve Naroff0af91202007-04-27 21:51:21 +0000104};
105
Jan Korousf31d8df2019-08-13 18:11:44 +0000106/// \returns location that is relevant when searching for Doc comments related
107/// to \p D.
108static SourceLocation getDeclLocForCommentSearch(const Decl *D,
109 SourceManager &SourceMgr) {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000110 assert(D);
111
Dmitri Gribenkodf17d642012-06-28 16:19:39 +0000112 // User can not attach documentation to implicit declarations.
113 if (D->isImplicit())
Jan Korousf31d8df2019-08-13 18:11:44 +0000114 return {};
Dmitri Gribenkodf17d642012-06-28 16:19:39 +0000115
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000116 // User can not attach documentation to implicit instantiations.
Eugene Zelenko7855e772018-04-03 00:11:50 +0000117 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000118 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Jan Korousf31d8df2019-08-13 18:11:44 +0000119 return {};
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000120 }
121
Eugene Zelenko7855e772018-04-03 00:11:50 +0000122 if (const auto *VD = dyn_cast<VarDecl>(D)) {
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000123 if (VD->isStaticDataMember() &&
124 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Jan Korousf31d8df2019-08-13 18:11:44 +0000125 return {};
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000126 }
127
Eugene Zelenko7855e772018-04-03 00:11:50 +0000128 if (const auto *CRD = dyn_cast<CXXRecordDecl>(D)) {
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000129 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Jan Korousf31d8df2019-08-13 18:11:44 +0000130 return {};
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000131 }
132
Eugene Zelenko7855e772018-04-03 00:11:50 +0000133 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000134 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
135 if (TSK == TSK_ImplicitInstantiation ||
136 TSK == TSK_Undeclared)
Jan Korousf31d8df2019-08-13 18:11:44 +0000137 return {};
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000138 }
139
Eugene Zelenko7855e772018-04-03 00:11:50 +0000140 if (const auto *ED = dyn_cast<EnumDecl>(D)) {
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000141 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Jan Korousf31d8df2019-08-13 18:11:44 +0000142 return {};
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000143 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000144 if (const auto *TD = dyn_cast<TagDecl>(D)) {
Fariborz Jahanian799a4032013-04-17 21:05:20 +0000145 // When tag declaration (but not definition!) is part of the
146 // decl-specifier-seq of some other declaration, it doesn't get comment
147 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
Jan Korousf31d8df2019-08-13 18:11:44 +0000148 return {};
Fariborz Jahanian799a4032013-04-17 21:05:20 +0000149 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000150 // TODO: handle comments for function parameters properly.
151 if (isa<ParmVarDecl>(D))
Jan Korousf31d8df2019-08-13 18:11:44 +0000152 return {};
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000153
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000154 // TODO: we could look up template parameter documentation in the template
155 // documentation.
156 if (isa<TemplateTypeParmDecl>(D) ||
157 isa<NonTypeTemplateParmDecl>(D) ||
158 isa<TemplateTemplateParmDecl>(D))
Jan Korousf31d8df2019-08-13 18:11:44 +0000159 return {};
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000160
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000161 // Find declaration location.
162 // For Objective-C declarations we generally don't expect to have multiple
163 // declarators, thus use declaration starting location as the "declaration
164 // location".
165 // For all other declarations multiple declarators are used quite frequently,
166 // so we use the location of the identifier as the "declaration location".
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000167 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000168 isa<ObjCPropertyDecl>(D) ||
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +0000169 isa<RedeclarableTemplateDecl>(D) ||
Sam McCalla433e712019-11-13 21:30:31 +0100170 isa<ClassTemplateSpecializationDecl>(D) ||
171 // Allow association with Y across {} in `typedef struct X {} Y`.
172 isa<TypedefDecl>(D))
Jan Korousf31d8df2019-08-13 18:11:44 +0000173 return D->getBeginLoc();
Fariborz Jahanianb64e95f2013-07-24 22:58:51 +0000174 else {
Jan Korousf31d8df2019-08-13 18:11:44 +0000175 const SourceLocation DeclLoc = D->getLocation();
Dmitri Gribenkoef099dc2014-03-27 16:40:51 +0000176 if (DeclLoc.isMacroID()) {
177 if (isa<TypedefDecl>(D)) {
178 // If location of the typedef name is in a macro, it is because being
179 // declared via a macro. Try using declaration's starting location as
180 // the "declaration location".
Jan Korousf31d8df2019-08-13 18:11:44 +0000181 return D->getBeginLoc();
Eugene Zelenko7855e772018-04-03 00:11:50 +0000182 } else if (const auto *TD = dyn_cast<TagDecl>(D)) {
Dmitri Gribenkoef099dc2014-03-27 16:40:51 +0000183 // If location of the tag decl is inside a macro, but the spelling of
184 // the tag name comes from a macro argument, it looks like a special
185 // macro like NS_ENUM is being used to define the tag decl. In that
186 // case, adjust the source location to the expansion loc so that we can
187 // attach the comment to the tag decl.
188 if (SourceMgr.isMacroArgExpansion(DeclLoc) &&
189 TD->isCompleteDefinition())
Jan Korousf31d8df2019-08-13 18:11:44 +0000190 return SourceMgr.getExpansionLoc(DeclLoc);
Dmitri Gribenkoef099dc2014-03-27 16:40:51 +0000191 }
192 }
Jan Korousf31d8df2019-08-13 18:11:44 +0000193 return DeclLoc;
Fariborz Jahanianb64e95f2013-07-24 22:58:51 +0000194 }
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000195
Jan Korousf31d8df2019-08-13 18:11:44 +0000196 return {};
197}
198
199RawComment *ASTContext::getRawCommentForDeclNoCacheImpl(
200 const Decl *D, const SourceLocation RepresentativeLocForDecl,
201 const std::map<unsigned, RawComment *> &CommentsInTheFile) const {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000202 // If the declaration doesn't map directly to a location in a file, we
203 // can't find the comment.
Jan Korousf31d8df2019-08-13 18:11:44 +0000204 if (RepresentativeLocForDecl.isInvalid() ||
205 !RepresentativeLocForDecl.isFileID())
Craig Topper36250ad2014-05-12 05:36:57 +0000206 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000207
Jan Korous6644d012019-04-10 20:23:33 +0000208 // If there are no comments anywhere, we won't find anything.
Jan Korousf31d8df2019-08-13 18:11:44 +0000209 if (CommentsInTheFile.empty())
Jan Korous6644d012019-04-10 20:23:33 +0000210 return nullptr;
211
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000212 // Decompose the location for the declaration and find the beginning of the
213 // file buffer.
Jan Korousf31d8df2019-08-13 18:11:44 +0000214 const std::pair<FileID, unsigned> DeclLocDecomp =
215 SourceMgr.getDecomposedLoc(RepresentativeLocForDecl);
216
217 // Slow path.
218 auto OffsetCommentBehindDecl =
219 CommentsInTheFile.lower_bound(DeclLocDecomp.second);
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000220
221 // First check whether we have a trailing comment.
Jan Korousf31d8df2019-08-13 18:11:44 +0000222 if (OffsetCommentBehindDecl != CommentsInTheFile.end()) {
223 RawComment *CommentBehindDecl = OffsetCommentBehindDecl->second;
224 if ((CommentBehindDecl->isDocumentation() ||
225 LangOpts.CommentOpts.ParseAllComments) &&
226 CommentBehindDecl->isTrailingComment() &&
227 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
228 isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
229
230 // Check that Doxygen trailing comment comes after the declaration, starts
231 // on the same line and in the same file as the declaration.
232 if (SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second) ==
233 Comments.getCommentBeginLine(CommentBehindDecl, DeclLocDecomp.first,
234 OffsetCommentBehindDecl->first)) {
235 return CommentBehindDecl;
236 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000237 }
238 }
239
240 // The comment just after the declaration was not a trailing comment.
241 // Let's look at the previous comment.
Jan Korousf31d8df2019-08-13 18:11:44 +0000242 if (OffsetCommentBehindDecl == CommentsInTheFile.begin())
Craig Topper36250ad2014-05-12 05:36:57 +0000243 return nullptr;
Jan Korousf31d8df2019-08-13 18:11:44 +0000244
245 auto OffsetCommentBeforeDecl = --OffsetCommentBehindDecl;
246 RawComment *CommentBeforeDecl = OffsetCommentBeforeDecl->second;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000247
248 // Check that we actually have a non-member Doxygen comment.
Jan Korousf31d8df2019-08-13 18:11:44 +0000249 if (!(CommentBeforeDecl->isDocumentation() ||
David L. Jones13d5a872018-03-02 00:07:45 +0000250 LangOpts.CommentOpts.ParseAllComments) ||
Jan Korousf31d8df2019-08-13 18:11:44 +0000251 CommentBeforeDecl->isTrailingComment())
Craig Topper36250ad2014-05-12 05:36:57 +0000252 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000253
254 // Decompose the end of the comment.
Jan Korousf31d8df2019-08-13 18:11:44 +0000255 const unsigned CommentEndOffset =
256 Comments.getCommentEndOffset(CommentBeforeDecl);
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000257
258 // Get the corresponding buffer.
259 bool Invalid = false;
260 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
261 &Invalid).data();
262 if (Invalid)
Craig Topper36250ad2014-05-12 05:36:57 +0000263 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000264
265 // Extract text between the comment and declaration.
Jan Korousf31d8df2019-08-13 18:11:44 +0000266 StringRef Text(Buffer + CommentEndOffset,
267 DeclLocDecomp.second - CommentEndOffset);
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000268
Dmitri Gribenko7e8729b2012-06-27 23:43:37 +0000269 // There should be no other declarations or preprocessor directives between
270 // comment and declaration.
Argyrios Kyrtzidisb534d3a2013-07-26 18:38:12 +0000271 if (Text.find_first_of(";{}#@") != StringRef::npos)
Craig Topper36250ad2014-05-12 05:36:57 +0000272 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000273
Jan Korousf31d8df2019-08-13 18:11:44 +0000274 return CommentBeforeDecl;
275}
276
277RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
278 const SourceLocation DeclLoc = getDeclLocForCommentSearch(D, SourceMgr);
279
280 // If the declaration doesn't map directly to a location in a file, we
281 // can't find the comment.
282 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
283 return nullptr;
284
285 if (ExternalSource && !CommentsLoaded) {
286 ExternalSource->ReadComments();
287 CommentsLoaded = true;
288 }
289
290 if (Comments.empty())
291 return nullptr;
292
293 const FileID File = SourceMgr.getDecomposedLoc(DeclLoc).first;
294 const auto CommentsInThisFile = Comments.getCommentsInFile(File);
295 if (!CommentsInThisFile || CommentsInThisFile->empty())
296 return nullptr;
297
298 return getRawCommentForDeclNoCacheImpl(D, DeclLoc, *CommentsInThisFile);
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000299}
300
Reid Kleckner86565c12020-02-27 11:01:58 -0800301void ASTContext::addComment(const RawComment &RC) {
302 assert(LangOpts.RetainCommentsFromSystemHeaders ||
303 !SourceMgr.isInSystemHeader(RC.getSourceRange().getBegin()));
304 Comments.addComment(RC, LangOpts.CommentOpts, BumpAlloc);
305}
306
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000307/// If we have a 'templated' declaration for a template, adjust 'D' to
308/// refer to the actual template.
Dmitri Gribenko90631802012-08-22 17:44:32 +0000309/// If we have an implicit instantiation, adjust 'D' to refer to template.
Jan Korousf31d8df2019-08-13 18:11:44 +0000310static const Decl &adjustDeclToTemplate(const Decl &D) {
311 if (const auto *FD = dyn_cast<FunctionDecl>(&D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000312 // Is this function declaration part of a function template?
Douglas Gregor35ceb272012-08-13 16:37:30 +0000313 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
Jan Korousf31d8df2019-08-13 18:11:44 +0000314 return *FTD;
Dmitri Gribenko90631802012-08-22 17:44:32 +0000315
316 // Nothing to do if function is not an implicit instantiation.
317 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
318 return D;
319
320 // Function is an implicit instantiation of a function template?
321 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
Jan Korousf31d8df2019-08-13 18:11:44 +0000322 return *FTD;
Dmitri Gribenko90631802012-08-22 17:44:32 +0000323
324 // Function is instantiated from a member definition of a class template?
325 if (const FunctionDecl *MemberDecl =
326 FD->getInstantiatedFromMemberFunction())
Jan Korousf31d8df2019-08-13 18:11:44 +0000327 return *MemberDecl;
Dmitri Gribenko90631802012-08-22 17:44:32 +0000328
329 return D;
Douglas Gregor35ceb272012-08-13 16:37:30 +0000330 }
Jan Korousf31d8df2019-08-13 18:11:44 +0000331 if (const auto *VD = dyn_cast<VarDecl>(&D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000332 // Static data member is instantiated from a member definition of a class
333 // template?
334 if (VD->isStaticDataMember())
335 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
Jan Korousf31d8df2019-08-13 18:11:44 +0000336 return *MemberDecl;
Dmitri Gribenko90631802012-08-22 17:44:32 +0000337
338 return D;
339 }
Jan Korousf31d8df2019-08-13 18:11:44 +0000340 if (const auto *CRD = dyn_cast<CXXRecordDecl>(&D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000341 // Is this class declaration part of a class template?
342 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
Jan Korousf31d8df2019-08-13 18:11:44 +0000343 return *CTD;
Dmitri Gribenko90631802012-08-22 17:44:32 +0000344
345 // Class is an implicit instantiation of a class template or partial
346 // specialization?
Eugene Zelenko7855e772018-04-03 00:11:50 +0000347 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000348 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
349 return D;
350 llvm::PointerUnion<ClassTemplateDecl *,
351 ClassTemplatePartialSpecializationDecl *>
352 PU = CTSD->getSpecializedTemplateOrPartial();
Jan Korousf31d8df2019-08-13 18:11:44 +0000353 return PU.is<ClassTemplateDecl *>()
354 ? *static_cast<const Decl *>(PU.get<ClassTemplateDecl *>())
355 : *static_cast<const Decl *>(
356 PU.get<ClassTemplatePartialSpecializationDecl *>());
Dmitri Gribenko90631802012-08-22 17:44:32 +0000357 }
358
359 // Class is instantiated from a member definition of a class template?
360 if (const MemberSpecializationInfo *Info =
Jan Korousf31d8df2019-08-13 18:11:44 +0000361 CRD->getMemberSpecializationInfo())
362 return *Info->getInstantiatedFrom();
Dmitri Gribenko90631802012-08-22 17:44:32 +0000363
364 return D;
365 }
Jan Korousf31d8df2019-08-13 18:11:44 +0000366 if (const auto *ED = dyn_cast<EnumDecl>(&D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000367 // Enum is instantiated from a member definition of a class template?
368 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
Jan Korousf31d8df2019-08-13 18:11:44 +0000369 return *MemberDecl;
Dmitri Gribenko90631802012-08-22 17:44:32 +0000370
371 return D;
372 }
373 // FIXME: Adjust alias templates?
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000374 return D;
375}
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000376
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000377const RawComment *ASTContext::getRawCommentForAnyRedecl(
378 const Decl *D,
379 const Decl **OriginalDecl) const {
Jan Korousf31d8df2019-08-13 18:11:44 +0000380 if (!D) {
381 if (OriginalDecl)
382 OriginalDecl = nullptr;
383 return nullptr;
384 }
Douglas Gregor35ceb272012-08-13 16:37:30 +0000385
Jan Korousf31d8df2019-08-13 18:11:44 +0000386 D = &adjustDeclToTemplate(*D);
387
388 // Any comment directly attached to D?
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000389 {
Jan Korousf31d8df2019-08-13 18:11:44 +0000390 auto DeclComment = DeclRawComments.find(D);
391 if (DeclComment != DeclRawComments.end()) {
392 if (OriginalDecl)
393 *OriginalDecl = D;
394 return DeclComment->second;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000395 }
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000396 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000397
Jan Korousf31d8df2019-08-13 18:11:44 +0000398 // Any comment attached to any redeclaration of D?
399 const Decl *CanonicalD = D->getCanonicalDecl();
400 if (!CanonicalD)
401 return nullptr;
402
403 {
404 auto RedeclComment = RedeclChainComments.find(CanonicalD);
405 if (RedeclComment != RedeclChainComments.end()) {
406 if (OriginalDecl)
407 *OriginalDecl = RedeclComment->second;
408 auto CommentAtRedecl = DeclRawComments.find(RedeclComment->second);
409 assert(CommentAtRedecl != DeclRawComments.end() &&
410 "This decl is supposed to have comment attached.");
411 return CommentAtRedecl->second;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000412 }
413 }
414
Jan Korousf31d8df2019-08-13 18:11:44 +0000415 // Any redeclarations of D that we haven't checked for comments yet?
416 // We can't use DenseMap::iterator directly since it'd get invalid.
417 auto LastCheckedRedecl = [this, CanonicalD]() -> const Decl * {
418 auto LookupRes = CommentlessRedeclChains.find(CanonicalD);
419 if (LookupRes != CommentlessRedeclChains.end())
420 return LookupRes->second;
421 return nullptr;
422 }();
423
424 for (const auto Redecl : D->redecls()) {
425 assert(Redecl);
426 // Skip all redeclarations that have been checked previously.
427 if (LastCheckedRedecl) {
428 if (LastCheckedRedecl == Redecl) {
429 LastCheckedRedecl = nullptr;
430 }
431 continue;
432 }
433 const RawComment *RedeclComment = getRawCommentForDeclNoCache(Redecl);
434 if (RedeclComment) {
435 cacheRawCommentForDecl(*Redecl, *RedeclComment);
436 if (OriginalDecl)
437 *OriginalDecl = Redecl;
438 return RedeclComment;
439 }
440 CommentlessRedeclChains[CanonicalD] = Redecl;
441 }
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000442
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000443 if (OriginalDecl)
Jan Korousf31d8df2019-08-13 18:11:44 +0000444 *OriginalDecl = nullptr;
445 return nullptr;
446}
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000447
Jan Korousf31d8df2019-08-13 18:11:44 +0000448void ASTContext::cacheRawCommentForDecl(const Decl &OriginalD,
449 const RawComment &Comment) const {
450 assert(Comment.isDocumentation() || LangOpts.CommentOpts.ParseAllComments);
451 DeclRawComments.try_emplace(&OriginalD, &Comment);
452 const Decl *const CanonicalDecl = OriginalD.getCanonicalDecl();
453 RedeclChainComments.try_emplace(CanonicalDecl, &OriginalD);
454 CommentlessRedeclChains.erase(CanonicalDecl);
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000455}
456
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000457static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
458 SmallVectorImpl<const NamedDecl *> &Redeclared) {
459 const DeclContext *DC = ObjCMethod->getDeclContext();
Eugene Zelenko7855e772018-04-03 00:11:50 +0000460 if (const auto *IMD = dyn_cast<ObjCImplDecl>(DC)) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000461 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
462 if (!ID)
463 return;
464 // Add redeclared method here.
Aaron Ballmanb4a53452014-03-13 21:57:01 +0000465 for (const auto *Ext : ID->known_extensions()) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000466 if (ObjCMethodDecl *RedeclaredMethod =
Douglas Gregor048fbfa2013-01-16 23:00:23 +0000467 Ext->getMethod(ObjCMethod->getSelector(),
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000468 ObjCMethod->isInstanceMethod()))
469 Redeclared.push_back(RedeclaredMethod);
470 }
471 }
472}
473
Jan Korousf31d8df2019-08-13 18:11:44 +0000474void ASTContext::attachCommentsToJustParsedDecls(ArrayRef<Decl *> Decls,
475 const Preprocessor *PP) {
476 if (Comments.empty() || Decls.empty())
477 return;
478
Erik Pilkington29a42392020-03-02 16:30:16 -0800479 FileID File;
480 for (Decl *D : Decls) {
481 SourceLocation Loc = D->getLocation();
482 if (Loc.isValid()) {
483 // See if there are any new comments that are not attached to a decl.
484 // The location doesn't have to be precise - we care only about the file.
485 File = SourceMgr.getDecomposedLoc(Loc).first;
486 break;
487 }
488 }
489
490 if (File.isInvalid())
491 return;
492
Jan Korousf31d8df2019-08-13 18:11:44 +0000493 auto CommentsInThisFile = Comments.getCommentsInFile(File);
494 if (!CommentsInThisFile || CommentsInThisFile->empty() ||
495 CommentsInThisFile->rbegin()->second->isAttached())
496 return;
497
498 // There is at least one comment not attached to a decl.
499 // Maybe it should be attached to one of Decls?
500 //
501 // Note that this way we pick up not only comments that precede the
502 // declaration, but also comments that *follow* the declaration -- thanks to
503 // the lookahead in the lexer: we've consumed the semicolon and looked
504 // ahead through comments.
505
506 for (const Decl *D : Decls) {
507 assert(D);
508 if (D->isInvalidDecl())
509 continue;
510
511 D = &adjustDeclToTemplate(*D);
512
513 const SourceLocation DeclLoc = getDeclLocForCommentSearch(D, SourceMgr);
514
515 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
516 continue;
517
518 if (DeclRawComments.count(D) > 0)
519 continue;
520
521 if (RawComment *const DocComment =
522 getRawCommentForDeclNoCacheImpl(D, DeclLoc, *CommentsInThisFile)) {
523 cacheRawCommentForDecl(*D, *DocComment);
524 comments::FullComment *FC = DocComment->parse(*this, PP, D);
525 ParsedComments[D->getCanonicalDecl()] = FC;
526 }
527 }
528}
529
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000530comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
531 const Decl *D) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +0000532 auto *ThisDeclInfo = new (*this) comments::DeclInfo;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000533 ThisDeclInfo->CommentDecl = D;
534 ThisDeclInfo->IsFilled = false;
535 ThisDeclInfo->fill();
536 ThisDeclInfo->CommentDecl = FC->getDecl();
Argyrios Kyrtzidis7daabbd2014-04-27 22:53:03 +0000537 if (!ThisDeclInfo->TemplateParameters)
538 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000539 comments::FullComment *CFC =
540 new (*this) comments::FullComment(FC->getBlocks(),
541 ThisDeclInfo);
542 return CFC;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000543}
544
Richard Smithb39b9d52013-05-21 05:24:00 +0000545comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
546 const RawComment *RC = getRawCommentForDeclNoCache(D);
Craig Topper36250ad2014-05-12 05:36:57 +0000547 return RC ? RC->parse(*this, nullptr, D) : nullptr;
Richard Smithb39b9d52013-05-21 05:24:00 +0000548}
549
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000550comments::FullComment *ASTContext::getCommentForDecl(
551 const Decl *D,
552 const Preprocessor *PP) const {
Jan Korousf31d8df2019-08-13 18:11:44 +0000553 if (!D || D->isInvalidDecl())
Craig Topper36250ad2014-05-12 05:36:57 +0000554 return nullptr;
Jan Korousf31d8df2019-08-13 18:11:44 +0000555 D = &adjustDeclToTemplate(*D);
Fangrui Song6907ce22018-07-30 19:24:48 +0000556
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000557 const Decl *Canonical = D->getCanonicalDecl();
558 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
559 ParsedComments.find(Canonical);
Fangrui Song6907ce22018-07-30 19:24:48 +0000560
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000561 if (Pos != ParsedComments.end()) {
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000562 if (Canonical != D) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000563 comments::FullComment *FC = Pos->second;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000564 comments::FullComment *CFC = cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000565 return CFC;
566 }
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000567 return Pos->second;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000568 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000569
Jan Korousf31d8df2019-08-13 18:11:44 +0000570 const Decl *OriginalDecl = nullptr;
Fangrui Song6907ce22018-07-30 19:24:48 +0000571
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000572 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000573 if (!RC) {
574 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000575 SmallVector<const NamedDecl*, 8> Overridden;
Eugene Zelenko7855e772018-04-03 00:11:50 +0000576 const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000577 if (OMD && OMD->isPropertyAccessor())
578 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
579 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
580 return cloneFullComment(FC, D);
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000581 if (OMD)
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000582 addRedeclaredMethods(OMD, Overridden);
583 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000584 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
585 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
586 return cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000587 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000588 else if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000589 // Attach any tag type's documentation to its typedef if latter
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000590 // does not have one of its own.
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000591 QualType QT = TD->getUnderlyingType();
Eugene Zelenko7855e772018-04-03 00:11:50 +0000592 if (const auto *TT = QT->getAs<TagType>())
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000593 if (const Decl *TD = TT->getDecl())
594 if (comments::FullComment *FC = getCommentForDecl(TD, PP))
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000595 return cloneFullComment(FC, D);
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000596 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000597 else if (const auto *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000598 while (IC->getSuperClass()) {
599 IC = IC->getSuperClass();
600 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
601 return cloneFullComment(FC, D);
602 }
603 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000604 else if (const auto *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000605 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
606 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
607 return cloneFullComment(FC, D);
608 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000609 else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000610 if (!(RD = RD->getDefinition()))
Craig Topper36250ad2014-05-12 05:36:57 +0000611 return nullptr;
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000612 // Check non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +0000613 for (const auto &I : RD->bases()) {
614 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000615 continue;
Aaron Ballman574705e2014-03-13 15:41:46 +0000616 QualType Ty = I.getType();
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000617 if (Ty.isNull())
618 continue;
619 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
620 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
621 continue;
Fangrui Song6907ce22018-07-30 19:24:48 +0000622
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000623 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
624 return cloneFullComment(FC, D);
625 }
626 }
627 // Check virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +0000628 for (const auto &I : RD->vbases()) {
629 if (I.getAccessSpecifier() != AS_public)
Fariborz Jahanian5a2e4a22013-04-26 23:34:36 +0000630 continue;
Aaron Ballman445a9392014-03-13 16:15:17 +0000631 QualType Ty = I.getType();
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000632 if (Ty.isNull())
633 continue;
634 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
635 if (!(VirtualBase= VirtualBase->getDefinition()))
636 continue;
637 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
638 return cloneFullComment(FC, D);
639 }
640 }
641 }
Craig Topper36250ad2014-05-12 05:36:57 +0000642 return nullptr;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000643 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000644
Dmitri Gribenkobfda9f72012-08-22 18:12:19 +0000645 // If the RawComment was attached to other redeclaration of this Decl, we
646 // should parse the comment in context of that other Decl. This is important
647 // because comments can contain references to parameter names which can be
648 // different across redeclarations.
Jan Korousf31d8df2019-08-13 18:11:44 +0000649 if (D != OriginalDecl && OriginalDecl)
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000650 return getCommentForDecl(OriginalDecl, PP);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000651
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000652 comments::FullComment *FC = RC->parse(*this, PP, D);
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000653 ParsedComments[Canonical] = FC;
654 return FC;
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000655}
656
Jonathan Roelofs39fe4402020-01-26 12:05:46 -0700657void
Fangrui Song6907ce22018-07-30 19:24:48 +0000658ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
Saar Razff1e0fc2020-01-15 02:48:42 +0200659 const ASTContext &C,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000660 TemplateTemplateParmDecl *Parm) {
661 ID.AddInteger(Parm->getDepth());
662 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +0000663 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000664
665 TemplateParameterList *Params = Parm->getTemplateParameters();
666 ID.AddInteger(Params->size());
Fangrui Song6907ce22018-07-30 19:24:48 +0000667 for (TemplateParameterList::const_iterator P = Params->begin(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000668 PEnd = Params->end();
669 P != PEnd; ++P) {
Eugene Zelenko7855e772018-04-03 00:11:50 +0000670 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000671 ID.AddInteger(0);
672 ID.AddBoolean(TTP->isParameterPack());
Saar Razff1e0fc2020-01-15 02:48:42 +0200673 const TypeConstraint *TC = TTP->getTypeConstraint();
674 ID.AddBoolean(TC != nullptr);
675 if (TC)
676 TC->getImmediatelyDeclaredConstraint()->Profile(ID, C,
677 /*Canonical=*/true);
678 if (TTP->isExpandedParameterPack()) {
679 ID.AddBoolean(true);
680 ID.AddInteger(TTP->getNumExpansionParameters());
681 } else
682 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000683 continue;
684 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000685
Eugene Zelenko7855e772018-04-03 00:11:50 +0000686 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000687 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +0000688 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman205a4292012-03-07 01:09:33 +0000689 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000690 if (NTTP->isExpandedParameterPack()) {
691 ID.AddBoolean(true);
692 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman205a4292012-03-07 01:09:33 +0000693 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
694 QualType T = NTTP->getExpansionType(I);
695 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
696 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000697 } else
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000698 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000699 continue;
700 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000701
Eugene Zelenko7855e772018-04-03 00:11:50 +0000702 auto *TTP = cast<TemplateTemplateParmDecl>(*P);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000703 ID.AddInteger(2);
Saar Razff1e0fc2020-01-15 02:48:42 +0200704 Profile(ID, C, TTP);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000705 }
Saar Razff1e0fc2020-01-15 02:48:42 +0200706 Expr *RequiresClause = Parm->getTemplateParameters()->getRequiresClause();
707 ID.AddBoolean(RequiresClause != nullptr);
708 if (RequiresClause)
709 RequiresClause->Profile(ID, C, /*Canonical=*/true);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000710}
711
Saar Razb481f022020-01-22 02:03:05 +0200712static Expr *
713canonicalizeImmediatelyDeclaredConstraint(const ASTContext &C, Expr *IDC,
714 QualType ConstrainedType) {
715 // This is a bit ugly - we need to form a new immediately-declared
716 // constraint that references the new parameter; this would ideally
717 // require semantic analysis (e.g. template<C T> struct S {}; - the
718 // converted arguments of C<T> could be an argument pack if C is
719 // declared as template<typename... T> concept C = ...).
720 // We don't have semantic analysis here so we dig deep into the
721 // ready-made constraint expr and change the thing manually.
722 ConceptSpecializationExpr *CSE;
723 if (const auto *Fold = dyn_cast<CXXFoldExpr>(IDC))
724 CSE = cast<ConceptSpecializationExpr>(Fold->getLHS());
725 else
726 CSE = cast<ConceptSpecializationExpr>(IDC);
727 ArrayRef<TemplateArgument> OldConverted = CSE->getTemplateArguments();
728 SmallVector<TemplateArgument, 3> NewConverted;
729 NewConverted.reserve(OldConverted.size());
730 if (OldConverted.front().getKind() == TemplateArgument::Pack) {
731 // The case:
732 // template<typename... T> concept C = true;
733 // template<C<int> T> struct S; -> constraint is C<{T, int}>
734 NewConverted.push_back(ConstrainedType);
735 for (auto &Arg : OldConverted.front().pack_elements().drop_front(1))
736 NewConverted.push_back(Arg);
737 TemplateArgument NewPack(NewConverted);
738
739 NewConverted.clear();
740 NewConverted.push_back(NewPack);
741 assert(OldConverted.size() == 1 &&
742 "Template parameter pack should be the last parameter");
743 } else {
744 assert(OldConverted.front().getKind() == TemplateArgument::Type &&
745 "Unexpected first argument kind for immediately-declared "
746 "constraint");
747 NewConverted.push_back(ConstrainedType);
748 for (auto &Arg : OldConverted.drop_front(1))
749 NewConverted.push_back(Arg);
750 }
751 Expr *NewIDC = ConceptSpecializationExpr::Create(
Saar Razc83d9be2020-01-30 20:42:28 +0200752 C, CSE->getNamedConcept(), NewConverted, nullptr,
753 CSE->isInstantiationDependent(), CSE->containsUnexpandedParameterPack());
Saar Razb481f022020-01-22 02:03:05 +0200754
755 if (auto *OrigFold = dyn_cast<CXXFoldExpr>(IDC))
756 NewIDC = new (C) CXXFoldExpr(OrigFold->getType(), SourceLocation(), NewIDC,
757 BinaryOperatorKind::BO_LAnd,
758 SourceLocation(), /*RHS=*/nullptr,
759 SourceLocation(), /*NumExpansions=*/None);
760 return NewIDC;
761}
762
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000763TemplateTemplateParmDecl *
764ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +0000765 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000766 // Check if we already have a canonical template template parameter.
767 llvm::FoldingSetNodeID ID;
Saar Razff1e0fc2020-01-15 02:48:42 +0200768 CanonicalTemplateTemplateParm::Profile(ID, *this, TTP);
Craig Topper36250ad2014-05-12 05:36:57 +0000769 void *InsertPos = nullptr;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000770 CanonicalTemplateTemplateParm *Canonical
771 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
772 if (Canonical)
773 return Canonical->getParam();
Fangrui Song6907ce22018-07-30 19:24:48 +0000774
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000775 // Build a canonical template parameter list.
776 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000777 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000778 CanonParams.reserve(Params->size());
Fangrui Song6907ce22018-07-30 19:24:48 +0000779 for (TemplateParameterList::const_iterator P = Params->begin(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000780 PEnd = Params->end();
781 P != PEnd; ++P) {
Saar Razff1e0fc2020-01-15 02:48:42 +0200782 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
783 TemplateTypeParmDecl *NewTTP = TemplateTypeParmDecl::Create(*this,
784 getTranslationUnitDecl(), SourceLocation(), SourceLocation(),
785 TTP->getDepth(), TTP->getIndex(), nullptr, false,
786 TTP->isParameterPack(), TTP->hasTypeConstraint(),
787 TTP->isExpandedParameterPack() ?
788 llvm::Optional<unsigned>(TTP->getNumExpansionParameters()) : None);
789 if (const auto *TC = TTP->getTypeConstraint()) {
Saar Razff1e0fc2020-01-15 02:48:42 +0200790 QualType ParamAsArgument(NewTTP->getTypeForDecl(), 0);
Saar Razb481f022020-01-22 02:03:05 +0200791 Expr *NewIDC = canonicalizeImmediatelyDeclaredConstraint(
792 *this, TC->getImmediatelyDeclaredConstraint(),
793 ParamAsArgument);
794 TemplateArgumentListInfo CanonArgsAsWritten;
795 if (auto *Args = TC->getTemplateArgsAsWritten())
796 for (const auto &ArgLoc : Args->arguments())
797 CanonArgsAsWritten.addArgument(
798 TemplateArgumentLoc(ArgLoc.getArgument(),
799 TemplateArgumentLocInfo()));
Saar Razff1e0fc2020-01-15 02:48:42 +0200800 NewTTP->setTypeConstraint(
801 NestedNameSpecifierLoc(),
802 DeclarationNameInfo(TC->getNamedConcept()->getDeclName(),
803 SourceLocation()), /*FoundDecl=*/nullptr,
804 // Actually canonicalizing a TemplateArgumentLoc is difficult so we
805 // simply omit the ArgsAsWritten
Saar Razb481f022020-01-22 02:03:05 +0200806 TC->getNamedConcept(), /*ArgsAsWritten=*/nullptr, NewIDC);
Saar Razff1e0fc2020-01-15 02:48:42 +0200807 }
808 CanonParams.push_back(NewTTP);
809 } else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000810 QualType T = getCanonicalType(NTTP->getType());
811 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
812 NonTypeTemplateParmDecl *Param;
813 if (NTTP->isExpandedParameterPack()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000814 SmallVector<QualType, 2> ExpandedTypes;
815 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000816 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
817 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
818 ExpandedTInfos.push_back(
819 getTrivialTypeSourceInfo(ExpandedTypes.back()));
820 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000821
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000822 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000823 SourceLocation(),
824 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000825 NTTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000826 NTTP->getPosition(), nullptr,
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000827 T,
828 TInfo,
David Majnemerdfecf1a2016-07-06 04:19:16 +0000829 ExpandedTypes,
830 ExpandedTInfos);
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000831 } else {
832 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000833 SourceLocation(),
834 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000835 NTTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000836 NTTP->getPosition(), nullptr,
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000837 T,
838 NTTP->isParameterPack(),
839 TInfo);
840 }
Saar Razb481f022020-01-22 02:03:05 +0200841 if (AutoType *AT = T->getContainedAutoType()) {
842 if (AT->isConstrained()) {
843 Param->setPlaceholderTypeConstraint(
844 canonicalizeImmediatelyDeclaredConstraint(
845 *this, NTTP->getPlaceholderTypeConstraint(), T));
846 }
847 }
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000848 CanonParams.push_back(Param);
849
850 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000851 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
852 cast<TemplateTemplateParmDecl>(*P)));
853 }
854
Saar Razff1e0fc2020-01-15 02:48:42 +0200855 Expr *CanonRequiresClause = nullptr;
856 if (Expr *RequiresClause = TTP->getTemplateParameters()->getRequiresClause())
857 CanonRequiresClause = RequiresClause;
Hubert Tonge4a0c0e2016-07-30 22:33:34 +0000858
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000859 TemplateTemplateParmDecl *CanonTTP
Fangrui Song6907ce22018-07-30 19:24:48 +0000860 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000861 SourceLocation(), TTP->getDepth(),
Fangrui Song6907ce22018-07-30 19:24:48 +0000862 TTP->getPosition(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000863 TTP->isParameterPack(),
Craig Topper36250ad2014-05-12 05:36:57 +0000864 nullptr,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000865 TemplateParameterList::Create(*this, SourceLocation(),
866 SourceLocation(),
David Majnemer902f8c62015-12-27 07:16:27 +0000867 CanonParams,
Hubert Tonge4a0c0e2016-07-30 22:33:34 +0000868 SourceLocation(),
869 CanonRequiresClause));
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000870
871 // Get the new insert position for the node we care about.
872 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +0000873 assert(!Canonical && "Shouldn't be in the map!");
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000874 (void)Canonical;
875
876 // Create the canonical template template parameter entry.
877 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
878 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
879 return CanonTTP;
880}
881
Charles Davis53c59df2010-08-16 03:33:14 +0000882CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
Craig Topper36250ad2014-05-12 05:36:57 +0000883 if (!LangOpts.CPlusPlus) return nullptr;
John McCall86353412010-08-21 22:46:04 +0000884
John McCall359b8852013-01-25 22:30:49 +0000885 switch (T.getCXXABI().getKind()) {
Petr Hosek9c3f9b92019-09-06 18:59:43 -0700886 case TargetCXXABI::Fuchsia:
Joerg Sonnenbergerdaa13aa2014-05-13 11:20:16 +0000887 case TargetCXXABI::GenericARM: // Same as Itanium at this level
John McCall359b8852013-01-25 22:30:49 +0000888 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +0000889 case TargetCXXABI::iOS64:
Tim Northover756447a2015-10-30 16:30:36 +0000890 case TargetCXXABI::WatchOS:
Joerg Sonnenbergerdaa13aa2014-05-13 11:20:16 +0000891 case TargetCXXABI::GenericAArch64:
Zoran Jovanovic26a12162015-02-18 15:21:35 +0000892 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +0000893 case TargetCXXABI::GenericItanium:
Dan Gohmanc2853072015-09-03 22:51:53 +0000894 case TargetCXXABI::WebAssembly:
Xiangling Liao8bee52b2020-02-24 09:46:00 -0500895 case TargetCXXABI::XL:
Charles Davis53c59df2010-08-16 03:33:14 +0000896 return CreateItaniumCXXABI(*this);
John McCall359b8852013-01-25 22:30:49 +0000897 case TargetCXXABI::Microsoft:
Charles Davis6bcb07a2010-08-19 02:18:14 +0000898 return CreateMicrosoftCXXABI(*this);
899 }
David Blaikie8a40f702012-01-17 06:56:22 +0000900 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000901}
902
Nandor Licker950b70d2019-09-13 09:46:16 +0000903interp::Context &ASTContext::getInterpContext() {
904 if (!InterpContext) {
905 InterpContext.reset(new interp::Context(*this));
906 }
907 return *InterpContext.get();
908}
909
Reid Kleckner8a81daa2019-12-09 17:03:47 -0800910ParentMapContext &ASTContext::getParentMapContext() {
911 if (!ParentMapCtx)
912 ParentMapCtx.reset(new ParentMapContext(*this));
913 return *ParentMapCtx.get();
914}
915
Alexander Richardson6d989432017-10-15 18:48:14 +0000916static const LangASMap *getAddressSpaceMap(const TargetInfo &T,
917 const LangOptions &LOpts) {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000918 if (LOpts.FakeAddressSpaceMap) {
919 // The fake address space map must have a distinct entry for each
920 // language-specific address space.
921 static const unsigned FakeAddrSpaceMap[] = {
Amy Huanga85f5ef2019-10-24 16:34:25 -0700922 0, // Default
923 1, // opencl_global
924 3, // opencl_local
925 2, // opencl_constant
926 0, // opencl_private
927 4, // opencl_generic
928 5, // cuda_device
929 6, // cuda_constant
930 7, // cuda_shared
931 8, // ptr32_sptr
932 9, // ptr32_uptr
933 10 // ptr64
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000934 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000935 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000936 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000937 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000938 }
939}
940
David Tweed31d09b02013-09-13 12:04:22 +0000941static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
942 const LangOptions &LangOpts) {
943 switch (LangOpts.getAddressSpaceMapMangling()) {
David Tweed31d09b02013-09-13 12:04:22 +0000944 case LangOptions::ASMM_Target:
945 return TI.useAddressSpaceMapMangling();
946 case LangOptions::ASMM_On:
947 return true;
948 case LangOptions::ASMM_Off:
949 return false;
950 }
NAKAMURA Takumi5c81ca42013-09-13 17:12:09 +0000951 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
David Tweed31d09b02013-09-13 12:04:22 +0000952}
953
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000954ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000955 IdentifierTable &idents, SelectorTable &sels,
Alp Toker08043432014-05-03 03:46:04 +0000956 Builtin::Context &builtins)
Richard Smith772e2662019-10-04 01:25:59 +0000957 : ConstantArrayTypes(this_()), FunctionProtoTypes(this_()),
958 TemplateSpecializationTypes(this_()),
Saar Razb481f022020-01-22 02:03:05 +0200959 DependentTemplateSpecializationTypes(this_()), AutoTypes(this_()),
Saar Razff1e0fc2020-01-15 02:48:42 +0200960 SubstTemplateTemplateParmPacks(this_()),
961 CanonTemplateTemplateParms(this_()), SourceMgr(SM), LangOpts(LOpts),
Ilya Biryukovdf7ea712019-10-09 09:40:22 +0000962 SanitizerBL(new SanitizerBlacklist(LangOpts.SanitizerBlacklistFiles, SM)),
Dean Michael Berris835832d2017-03-30 00:29:36 +0000963 XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles,
Dean Michael Berris20dc6ef2018-04-09 04:02:09 +0000964 LangOpts.XRayNeverInstrumentFiles,
965 LangOpts.XRayAttrListFiles, SM)),
Artem Belevichb5bc9232015-09-22 17:23:22 +0000966 PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
Eugene Zelenko5e5e5642017-11-23 01:20:07 +0000967 BuiltinInfo(builtins), DeclarationNames(*this), Comments(SM),
Eric Fiselier0683c0e2018-05-07 21:07:10 +0000968 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
969 CompCategories(this_()), LastSDM(nullptr, 0) {
Daniel Dunbar221fa942008-08-11 04:54:23 +0000970 TUDecl = TranslationUnitDecl::Create(*this);
Sam McCall814e7972018-11-14 10:33:30 +0000971 TraversalScope = {TUDecl};
Daniel Dunbar221fa942008-08-11 04:54:23 +0000972}
973
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000974ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000975 // Release the DenseMaps associated with DeclContext objects.
976 // FIXME: Is this the ideal solution?
977 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000978
Manuel Klimeka7328992013-06-03 13:51:33 +0000979 // Call all of the deallocation functions on all of their targets.
Chandler Carruthff5a01a2015-12-30 03:00:23 +0000980 for (auto &Pair : Deallocations)
981 (Pair.first)(Pair.second);
Manuel Klimeka7328992013-06-03 13:51:33 +0000982
Ted Kremenek076baeb2010-06-08 23:00:58 +0000983 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000984 // because they can contain DenseMaps.
985 for (llvm::DenseMap<const ObjCContainerDecl*,
986 const ASTRecordLayout*>::iterator
987 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
988 // Increment in loop to prevent using deallocated memory.
Eugene Zelenko7855e772018-04-03 00:11:50 +0000989 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
Douglas Gregor5b11d492010-07-25 17:53:33 +0000990 R->Destroy(*this);
991
Ted Kremenek076baeb2010-06-08 23:00:58 +0000992 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
993 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
994 // Increment in loop to prevent using deallocated memory.
Eugene Zelenko7855e772018-04-03 00:11:50 +0000995 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
Ted Kremenek076baeb2010-06-08 23:00:58 +0000996 R->Destroy(*this);
997 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000998
Douglas Gregor561eceb2010-08-30 16:49:28 +0000999 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
1000 AEnd = DeclAttrs.end();
1001 A != AEnd; ++A)
1002 A->second->~AttrVec();
Reid Klecknerd8110b62013-09-10 20:14:30 +00001003
Richard Smith423f46f2016-07-20 21:38:26 +00001004 for (const auto &Value : ModuleInitializers)
1005 Value.second->~PerModuleInitializers();
Gauthier Harnisch83c7b612019-06-15 10:24:47 +00001006
1007 for (APValue *Value : APValueCleanups)
1008 Value->~APValue();
Johannes Doerfert55eca282020-03-13 23:42:05 -05001009
1010 // Destroy the OMPTraitInfo objects that life here.
1011 llvm::DeleteContainerPointers(OMPTraitInfoVector);
Douglas Gregor561eceb2010-08-30 16:49:28 +00001012}
Douglas Gregorf21eb492009-03-26 23:50:42 +00001013
Sam McCall814e7972018-11-14 10:33:30 +00001014void ASTContext::setTraversalScope(const std::vector<Decl *> &TopLevelDecls) {
1015 TraversalScope = TopLevelDecls;
Reid Kleckner8a81daa2019-12-09 17:03:47 -08001016 getParentMapContext().clear();
Manuel Klimek95403e62014-05-21 13:28:59 +00001017}
1018
Gauthier Harnischdea9d572019-06-21 08:26:21 +00001019void ASTContext::AddDeallocation(void (*Callback)(void *), void *Data) const {
Chandler Carruthff5a01a2015-12-30 03:00:23 +00001020 Deallocations.push_back({Callback, Data});
Douglas Gregor1a809332010-05-23 18:26:36 +00001021}
1022
Mike Stump11289f42009-09-09 15:08:12 +00001023void
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +00001024ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
Benjamin Kramerd6da1a02016-06-12 20:05:23 +00001025 ExternalSource = std::move(Source);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001026}
1027
Chris Lattner4eb445d2007-01-26 01:27:23 +00001028void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +00001029 llvm::errs() << "\n*** AST Context Stats:\n";
1030 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001031
Douglas Gregora30d0462009-05-26 14:40:08 +00001032 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +00001033#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +00001034#define ABSTRACT_TYPE(Name, Parent)
John McCall36b12a82019-10-02 06:35:23 +00001035#include "clang/AST/TypeNodes.inc"
Douglas Gregora30d0462009-05-26 14:40:08 +00001036 0 // Extra
1037 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +00001038
Chris Lattner4eb445d2007-01-26 01:27:23 +00001039 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
1040 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +00001041 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +00001042 }
1043
Douglas Gregora30d0462009-05-26 14:40:08 +00001044 unsigned Idx = 0;
1045 unsigned TotalBytes = 0;
1046#define TYPE(Name, Parent) \
1047 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +00001048 llvm::errs() << " " << counts[Idx] << " " << #Name \
Bruno Ricci58e03222018-08-06 15:17:32 +00001049 << " types, " << sizeof(Name##Type) << " each " \
1050 << "(" << counts[Idx] * sizeof(Name##Type) \
1051 << " bytes)\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +00001052 TotalBytes += counts[Idx] * sizeof(Name##Type); \
1053 ++Idx;
1054#define ABSTRACT_TYPE(Name, Parent)
John McCall36b12a82019-10-02 06:35:23 +00001055#include "clang/AST/TypeNodes.inc"
Mike Stump11289f42009-09-09 15:08:12 +00001056
Chandler Carruth3c147a72011-07-04 05:32:14 +00001057 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
1058
Douglas Gregor7454c562010-07-02 20:37:36 +00001059 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +00001060 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
1061 << NumImplicitDefaultConstructors
1062 << " implicit default constructors created\n";
1063 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
1064 << NumImplicitCopyConstructors
1065 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +00001066 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +00001067 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
1068 << NumImplicitMoveConstructors
1069 << " implicit move constructors created\n";
1070 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
1071 << NumImplicitCopyAssignmentOperators
1072 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +00001073 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +00001074 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
1075 << NumImplicitMoveAssignmentOperators
1076 << " implicit move assignment operators created\n";
1077 llvm::errs() << NumImplicitDestructorsDeclared << "/"
1078 << NumImplicitDestructors
1079 << " implicit destructors created\n";
1080
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +00001081 if (ExternalSource) {
Chandler Carruth3c147a72011-07-04 05:32:14 +00001082 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001083 ExternalSource->PrintStats();
1084 }
Chandler Carruth3c147a72011-07-04 05:32:14 +00001085
Douglas Gregor5b11d492010-07-25 17:53:33 +00001086 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +00001087}
1088
Richard Smith42413142015-05-15 20:05:43 +00001089void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
1090 bool NotifyListeners) {
1091 if (NotifyListeners)
1092 if (auto *Listener = getASTMutationListener())
1093 Listener->RedefinedHiddenDefinition(ND, M);
1094
Richard Smith13897eb2018-09-12 23:37:00 +00001095 MergedDefModules[cast<NamedDecl>(ND->getCanonicalDecl())].push_back(M);
Richard Smith42413142015-05-15 20:05:43 +00001096}
1097
1098void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) {
Richard Smith20fbdb32018-09-12 02:13:46 +00001099 auto It = MergedDefModules.find(cast<NamedDecl>(ND->getCanonicalDecl()));
Richard Smith42413142015-05-15 20:05:43 +00001100 if (It == MergedDefModules.end())
1101 return;
1102
Benjamin Kramera72a70a2016-10-17 13:00:44 +00001103 auto &Merged = It->second;
Richard Smith42413142015-05-15 20:05:43 +00001104 llvm::DenseSet<Module*> Found;
1105 for (Module *&M : Merged)
1106 if (!Found.insert(M).second)
1107 M = nullptr;
1108 Merged.erase(std::remove(Merged.begin(), Merged.end(), nullptr), Merged.end());
1109}
1110
Reid Klecknerc915cb92020-02-27 18:13:54 -08001111ArrayRef<Module *>
1112ASTContext::getModulesWithMergedDefinition(const NamedDecl *Def) {
1113 auto MergedIt =
1114 MergedDefModules.find(cast<NamedDecl>(Def->getCanonicalDecl()));
1115 if (MergedIt == MergedDefModules.end())
1116 return None;
1117 return MergedIt->second;
1118}
1119
Richard Smithdc1f0422016-07-20 19:10:16 +00001120void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
1121 if (LazyInitializers.empty())
1122 return;
1123
1124 auto *Source = Ctx.getExternalSource();
1125 assert(Source && "lazy initializers but no external source");
1126
1127 auto LazyInits = std::move(LazyInitializers);
1128 LazyInitializers.clear();
1129
1130 for (auto ID : LazyInits)
1131 Initializers.push_back(Source->GetExternalDecl(ID));
1132
1133 assert(LazyInitializers.empty() &&
1134 "GetExternalDecl for lazy module initializer added more inits");
1135}
1136
1137void ASTContext::addModuleInitializer(Module *M, Decl *D) {
1138 // One special case: if we add a module initializer that imports another
1139 // module, and that module's only initializer is an ImportDecl, simplify.
Eugene Zelenko7855e772018-04-03 00:11:50 +00001140 if (const auto *ID = dyn_cast<ImportDecl>(D)) {
Richard Smithdc1f0422016-07-20 19:10:16 +00001141 auto It = ModuleInitializers.find(ID->getImportedModule());
1142
1143 // Maybe the ImportDecl does nothing at all. (Common case.)
1144 if (It == ModuleInitializers.end())
1145 return;
1146
1147 // Maybe the ImportDecl only imports another ImportDecl.
1148 auto &Imported = *It->second;
1149 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
1150 Imported.resolve(*this);
1151 auto *OnlyDecl = Imported.Initializers.front();
1152 if (isa<ImportDecl>(OnlyDecl))
1153 D = OnlyDecl;
1154 }
1155 }
1156
1157 auto *&Inits = ModuleInitializers[M];
1158 if (!Inits)
1159 Inits = new (*this) PerModuleInitializers;
1160 Inits->Initializers.push_back(D);
1161}
1162
1163void ASTContext::addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs) {
1164 auto *&Inits = ModuleInitializers[M];
1165 if (!Inits)
1166 Inits = new (*this) PerModuleInitializers;
1167 Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
1168 IDs.begin(), IDs.end());
1169}
1170
Eugene Zelenko7855e772018-04-03 00:11:50 +00001171ArrayRef<Decl *> ASTContext::getModuleInitializers(Module *M) {
Richard Smithdc1f0422016-07-20 19:10:16 +00001172 auto It = ModuleInitializers.find(M);
Fangrui Song6907ce22018-07-30 19:24:48 +00001173 if (It == ModuleInitializers.end())
Richard Smithdc1f0422016-07-20 19:10:16 +00001174 return None;
1175
1176 auto *Inits = It->second;
1177 Inits->resolve(*this);
1178 return Inits->Initializers;
1179}
1180
Richard Smithf19e1272015-03-07 00:04:49 +00001181ExternCContextDecl *ASTContext::getExternCContextDecl() const {
1182 if (!ExternCContext)
1183 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
1184
1185 return ExternCContext;
1186}
1187
David Majnemerd9b1a4f2015-11-04 03:40:30 +00001188BuiltinTemplateDecl *
1189ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
1190 const IdentifierInfo *II) const {
1191 auto *BuiltinTemplate = BuiltinTemplateDecl::Create(*this, TUDecl, II, BTK);
1192 BuiltinTemplate->setImplicit();
1193 TUDecl->addDecl(BuiltinTemplate);
1194
1195 return BuiltinTemplate;
1196}
1197
1198BuiltinTemplateDecl *
1199ASTContext::getMakeIntegerSeqDecl() const {
1200 if (!MakeIntegerSeqDecl)
1201 MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq,
1202 getMakeIntegerSeqName());
1203 return MakeIntegerSeqDecl;
1204}
1205
Eric Fiselier6ad68552016-07-01 01:24:09 +00001206BuiltinTemplateDecl *
1207ASTContext::getTypePackElementDecl() const {
1208 if (!TypePackElementDecl)
1209 TypePackElementDecl = buildBuiltinTemplateDecl(BTK__type_pack_element,
1210 getTypePackElementName());
1211 return TypePackElementDecl;
1212}
1213
Alp Toker2dea15b2013-12-17 01:22:38 +00001214RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
1215 RecordDecl::TagKind TK) const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001216 SourceLocation Loc;
1217 RecordDecl *NewDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00001218 if (getLangOpts().CPlusPlus)
1219 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
1220 Loc, &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +00001221 else
Alp Toker2dea15b2013-12-17 01:22:38 +00001222 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
1223 &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +00001224 NewDecl->setImplicit();
David Majnemerf8637362015-01-15 08:41:25 +00001225 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
1226 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
Alp Toker56b5cc92013-12-15 10:36:26 +00001227 return NewDecl;
1228}
1229
1230TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
1231 StringRef Name) const {
1232 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
1233 TypedefDecl *NewDecl = TypedefDecl::Create(
1234 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
1235 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
1236 NewDecl->setImplicit();
1237 return NewDecl;
1238}
1239
Douglas Gregor801c99d2011-08-12 06:49:56 +00001240TypedefDecl *ASTContext::getInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001241 if (!Int128Decl)
1242 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +00001243 return Int128Decl;
1244}
1245
1246TypedefDecl *ASTContext::getUInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001247 if (!UInt128Decl)
1248 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +00001249 return UInt128Decl;
1250}
Chris Lattner4eb445d2007-01-26 01:27:23 +00001251
John McCall48f2d582009-10-23 23:03:21 +00001252void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001253 auto *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +00001254 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +00001255 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001256}
1257
Artem Belevichb5bc9232015-09-22 17:23:22 +00001258void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
1259 const TargetInfo *AuxTarget) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001260 assert((!this->Target || this->Target == &Target) &&
1261 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +00001262 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +00001263
Douglas Gregore8bbc122011-09-02 00:18:52 +00001264 this->Target = &Target;
Artem Belevichb5bc9232015-09-22 17:23:22 +00001265 this->AuxTarget = AuxTarget;
1266
Douglas Gregore8bbc122011-09-02 00:18:52 +00001267 ABI.reset(createCXXABI(Target));
1268 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
David Tweed31d09b02013-09-13 12:04:22 +00001269 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
Fangrui Song6907ce22018-07-30 19:24:48 +00001270
Chris Lattner970e54e2006-11-12 00:37:36 +00001271 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +00001272 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +00001273
Chris Lattner970e54e2006-11-12 00:37:36 +00001274 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +00001275 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +00001276 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +00001277 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +00001278 InitBuiltinType(CharTy, BuiltinType::Char_S);
1279 else
1280 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +00001281 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +00001282 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
1283 InitBuiltinType(ShortTy, BuiltinType::Short);
1284 InitBuiltinType(IntTy, BuiltinType::Int);
1285 InitBuiltinType(LongTy, BuiltinType::Long);
1286 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +00001287
Chris Lattner970e54e2006-11-12 00:37:36 +00001288 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +00001289 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
1290 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
1291 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
1292 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
1293 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +00001294
Chris Lattner970e54e2006-11-12 00:37:36 +00001295 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +00001296 InitBuiltinType(FloatTy, BuiltinType::Float);
1297 InitBuiltinType(DoubleTy, BuiltinType::Double);
1298 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001299
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001300 // GNU extension, __float128 for IEEE quadruple precision
1301 InitBuiltinType(Float128Ty, BuiltinType::Float128);
1302
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00001303 // C11 extension ISO/IEC TS 18661-3
1304 InitBuiltinType(Float16Ty, BuiltinType::Float16);
1305
Leonard Chanf921d852018-06-04 16:07:52 +00001306 // ISO/IEC JTC1 SC22 WG14 N1169 Extension
Leonard Chanab80f3c2018-06-14 14:53:51 +00001307 InitBuiltinType(ShortAccumTy, BuiltinType::ShortAccum);
1308 InitBuiltinType(AccumTy, BuiltinType::Accum);
1309 InitBuiltinType(LongAccumTy, BuiltinType::LongAccum);
1310 InitBuiltinType(UnsignedShortAccumTy, BuiltinType::UShortAccum);
1311 InitBuiltinType(UnsignedAccumTy, BuiltinType::UAccum);
1312 InitBuiltinType(UnsignedLongAccumTy, BuiltinType::ULongAccum);
1313 InitBuiltinType(ShortFractTy, BuiltinType::ShortFract);
1314 InitBuiltinType(FractTy, BuiltinType::Fract);
1315 InitBuiltinType(LongFractTy, BuiltinType::LongFract);
1316 InitBuiltinType(UnsignedShortFractTy, BuiltinType::UShortFract);
1317 InitBuiltinType(UnsignedFractTy, BuiltinType::UFract);
1318 InitBuiltinType(UnsignedLongFractTy, BuiltinType::ULongFract);
1319 InitBuiltinType(SatShortAccumTy, BuiltinType::SatShortAccum);
1320 InitBuiltinType(SatAccumTy, BuiltinType::SatAccum);
1321 InitBuiltinType(SatLongAccumTy, BuiltinType::SatLongAccum);
1322 InitBuiltinType(SatUnsignedShortAccumTy, BuiltinType::SatUShortAccum);
1323 InitBuiltinType(SatUnsignedAccumTy, BuiltinType::SatUAccum);
1324 InitBuiltinType(SatUnsignedLongAccumTy, BuiltinType::SatULongAccum);
1325 InitBuiltinType(SatShortFractTy, BuiltinType::SatShortFract);
1326 InitBuiltinType(SatFractTy, BuiltinType::SatFract);
1327 InitBuiltinType(SatLongFractTy, BuiltinType::SatLongFract);
1328 InitBuiltinType(SatUnsignedShortFractTy, BuiltinType::SatUShortFract);
1329 InitBuiltinType(SatUnsignedFractTy, BuiltinType::SatUFract);
1330 InitBuiltinType(SatUnsignedLongFractTy, BuiltinType::SatULongFract);
Leonard Chanf921d852018-06-04 16:07:52 +00001331
Chris Lattnerf122cef2009-04-30 02:43:43 +00001332 // GNU extension, 128-bit integers.
1333 InitBuiltinType(Int128Ty, BuiltinType::Int128);
1334 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
1335
Hans Wennborg0d81e012013-05-10 10:08:40 +00001336 // C++ 3.9.1p5
1337 if (TargetInfo::isTypeSigned(Target.getWCharType()))
1338 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1339 else // -fshort-wchar makes wchar_t be unsigned.
1340 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1341 if (LangOpts.CPlusPlus && LangOpts.WChar)
1342 WideCharTy = WCharTy;
1343 else {
1344 // C99 (or C++ using -fno-wchar).
1345 WideCharTy = getFromTargetType(Target.getWCharType());
1346 }
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001347
James Molloy36365542012-05-04 10:55:22 +00001348 WIntTy = getFromTargetType(Target.getWIntType());
1349
Richard Smith3a8244d2018-05-01 05:02:45 +00001350 // C++20 (proposed)
1351 InitBuiltinType(Char8Ty, BuiltinType::Char8);
1352
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001353 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1354 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1355 else // C99
1356 Char16Ty = getFromTargetType(Target.getChar16Type());
1357
1358 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1359 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1360 else // C99
1361 Char32Ty = getFromTargetType(Target.getChar32Type());
1362
Douglas Gregor4619e432008-12-05 23:32:09 +00001363 // Placeholder type for type-dependent expressions whose type is
1364 // completely unknown. No code should ever check a type against
1365 // DependentTy and users should never see it; however, it is here to
1366 // help diagnose failures to properly check for type-dependent
1367 // expressions.
1368 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001369
John McCall36e7fe32010-10-12 00:20:44 +00001370 // Placeholder type for functions.
1371 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1372
John McCall0009fcc2011-04-26 20:42:42 +00001373 // Placeholder type for bound members.
1374 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1375
John McCall526ab472011-10-25 17:37:35 +00001376 // Placeholder type for pseudo-objects.
1377 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1378
John McCall31996342011-04-07 08:22:57 +00001379 // "any" type; useful for debugger-like clients.
1380 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1381
John McCall8a6b59a2011-10-17 18:09:15 +00001382 // Placeholder type for unbridged ARC casts.
1383 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1384
Eli Friedman34866c72012-08-31 00:14:07 +00001385 // Placeholder type for builtin functions.
1386 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1387
Alexey Bataev1a3320e2015-08-25 14:24:04 +00001388 // Placeholder type for OMP array sections.
Alexey Bataev7ac9efb2020-02-05 09:33:05 -05001389 if (LangOpts.OpenMP) {
Alexey Bataev1a3320e2015-08-25 14:24:04 +00001390 InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection);
Alexey Bataev7ac9efb2020-02-05 09:33:05 -05001391 InitBuiltinType(OMPArrayShapingTy, BuiltinType::OMPArrayShaping);
Alexey Bataev13a15042020-04-01 15:06:38 -04001392 InitBuiltinType(OMPIteratorTy, BuiltinType::OMPIterator);
Alexey Bataev7ac9efb2020-02-05 09:33:05 -05001393 }
Alexey Bataev1a3320e2015-08-25 14:24:04 +00001394
Chris Lattner970e54e2006-11-12 00:37:36 +00001395 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +00001396 FloatComplexTy = getComplexType(FloatTy);
1397 DoubleComplexTy = getComplexType(DoubleTy);
1398 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001399 Float128ComplexTy = getComplexType(Float128Ty);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001400
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001401 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +00001402 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1403 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001404 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001405
Alexey Bader954ba212016-04-08 13:40:33 +00001406 if (LangOpts.OpenCL) {
1407#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1408 InitBuiltinType(SingletonId, BuiltinType::Id);
Alexey Baderb62f1442016-04-13 08:33:41 +00001409#include "clang/Basic/OpenCLImageTypes.def"
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001410
Guy Benyei61054192013-02-07 10:55:47 +00001411 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001412 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Alexey Bader9c8453f2015-09-15 11:18:52 +00001413 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1414 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
Alexey Bader9c8453f2015-09-15 11:18:52 +00001415 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
Andrew Savonichev3fee3512018-11-08 11:25:41 +00001416
1417#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1418 InitBuiltinType(Id##Ty, BuiltinType::Id);
1419#include "clang/Basic/OpenCLExtensionTypes.def"
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001420 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001421
Richard Sandifordeb485fb2019-08-09 08:52:54 +00001422 if (Target.hasAArch64SVETypes()) {
1423#define SVE_TYPE(Name, Id, SingletonId) \
1424 InitBuiltinType(SingletonId, BuiltinType::Id);
1425#include "clang/Basic/AArch64SVEACLETypes.def"
1426 }
1427
Ted Kremeneke65b0862012-03-06 20:05:56 +00001428 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +00001429 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1430 SignedCharTy : BoolTy);
Fangrui Song6907ce22018-07-30 19:24:48 +00001431
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001432 ObjCConstantStringType = QualType();
Fangrui Song6907ce22018-07-30 19:24:48 +00001433
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001434 ObjCSuperType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +00001435
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00001436 // void * type
Yaxun Liu39195062017-08-04 18:16:31 +00001437 if (LangOpts.OpenCLVersion >= 200) {
1438 auto Q = VoidTy.getQualifiers();
1439 Q.setAddressSpace(LangAS::opencl_generic);
1440 VoidPtrTy = getPointerType(getCanonicalType(
1441 getQualifiedType(VoidTy.getUnqualifiedType(), Q)));
1442 } else {
1443 VoidPtrTy = getPointerType(VoidTy);
1444 }
Sebastian Redl576fd422009-05-10 18:38:11 +00001445
1446 // nullptr type (C++0x 2.14.7)
1447 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001448
1449 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1450 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +00001451
1452 // Builtin type used to help define __builtin_va_list.
Richard Smith9b88a4c2015-07-27 05:40:23 +00001453 VaListTagDecl = nullptr;
Richard Smithbab6df82020-04-11 22:15:29 -07001454
1455 // MSVC predeclares struct _GUID, and we need it to create MSGuidDecls.
1456 if (LangOpts.MicrosoftExt || LangOpts.Borland) {
1457 MSGuidTagDecl = buildImplicitRecord("_GUID");
1458 TUDecl->addDecl(MSGuidTagDecl);
1459 }
Chris Lattner970e54e2006-11-12 00:37:36 +00001460}
1461
David Blaikie9c902b52011-09-25 23:23:43 +00001462DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001463 return SourceMgr.getDiagnostics();
1464}
1465
Douglas Gregor561eceb2010-08-30 16:49:28 +00001466AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1467 AttrVec *&Result = DeclAttrs[D];
1468 if (!Result) {
1469 void *Mem = Allocate(sizeof(AttrVec));
1470 Result = new (Mem) AttrVec;
1471 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001472
Douglas Gregor561eceb2010-08-30 16:49:28 +00001473 return *Result;
1474}
1475
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001476/// Erase the attributes corresponding to the given declaration.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00001477void ASTContext::eraseDeclAttrs(const Decl *D) {
Douglas Gregor561eceb2010-08-30 16:49:28 +00001478 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1479 if (Pos != DeclAttrs.end()) {
1480 Pos->second->~AttrVec();
1481 DeclAttrs.erase(Pos);
1482 }
1483}
1484
Larisse Voufo39a1e502013-08-06 01:03:05 +00001485// FIXME: Remove ?
Douglas Gregor86d142a2009-10-08 07:24:58 +00001486MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +00001487ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001488 assert(Var->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001489 return getTemplateOrSpecializationInfo(Var)
1490 .dyn_cast<MemberSpecializationInfo *>();
1491}
1492
1493ASTContext::TemplateOrSpecializationInfo
1494ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1495 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1496 TemplateOrInstantiation.find(Var);
1497 if (Pos == TemplateOrInstantiation.end())
Eugene Zelenko7855e772018-04-03 00:11:50 +00001498 return {};
Mike Stump11289f42009-09-09 15:08:12 +00001499
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001500 return Pos->second;
1501}
1502
Mike Stump11289f42009-09-09 15:08:12 +00001503void
Douglas Gregor86d142a2009-10-08 07:24:58 +00001504ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +00001505 TemplateSpecializationKind TSK,
1506 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001507 assert(Inst->isStaticDataMember() && "Not a static data member");
1508 assert(Tmpl->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001509 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1510 Tmpl, TSK, PointOfInstantiation));
1511}
1512
1513void
1514ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1515 TemplateOrSpecializationInfo TSI) {
1516 assert(!TemplateOrInstantiation[Inst] &&
1517 "Already noted what the variable was instantiated from");
1518 TemplateOrInstantiation[Inst] = TSI;
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001519}
1520
John McCalle61f2ba2009-11-18 02:36:19 +00001521NamedDecl *
Richard Smithd8a9e372016-12-18 21:39:37 +00001522ASTContext::getInstantiatedFromUsingDecl(NamedDecl *UUD) {
1523 auto Pos = InstantiatedFromUsingDecl.find(UUD);
John McCallb96ec562009-12-04 22:46:56 +00001524 if (Pos == InstantiatedFromUsingDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001525 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001526
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001527 return Pos->second;
1528}
1529
1530void
Richard Smithd8a9e372016-12-18 21:39:37 +00001531ASTContext::setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern) {
John McCallb96ec562009-12-04 22:46:56 +00001532 assert((isa<UsingDecl>(Pattern) ||
1533 isa<UnresolvedUsingValueDecl>(Pattern) ||
Fangrui Song6907ce22018-07-30 19:24:48 +00001534 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
John McCallb96ec562009-12-04 22:46:56 +00001535 "pattern decl is not a using decl");
Richard Smithd8a9e372016-12-18 21:39:37 +00001536 assert((isa<UsingDecl>(Inst) ||
1537 isa<UnresolvedUsingValueDecl>(Inst) ||
Fangrui Song6907ce22018-07-30 19:24:48 +00001538 isa<UnresolvedUsingTypenameDecl>(Inst)) &&
Richard Smithd8a9e372016-12-18 21:39:37 +00001539 "instantiation did not produce a using decl");
John McCallb96ec562009-12-04 22:46:56 +00001540 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1541 InstantiatedFromUsingDecl[Inst] = Pattern;
1542}
1543
1544UsingShadowDecl *
1545ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1546 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1547 = InstantiatedFromUsingShadowDecl.find(Inst);
1548 if (Pos == InstantiatedFromUsingShadowDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001549 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00001550
1551 return Pos->second;
1552}
1553
1554void
1555ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1556 UsingShadowDecl *Pattern) {
1557 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1558 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001559}
1560
Anders Carlsson5da84842009-09-01 04:26:58 +00001561FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1562 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1563 = InstantiatedFromUnnamedFieldDecl.find(Field);
1564 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001565 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001566
Anders Carlsson5da84842009-09-01 04:26:58 +00001567 return Pos->second;
1568}
1569
1570void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1571 FieldDecl *Tmpl) {
1572 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1573 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1574 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1575 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +00001576
Anders Carlsson5da84842009-09-01 04:26:58 +00001577 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1578}
1579
Douglas Gregor832940b2010-03-02 23:58:15 +00001580ASTContext::overridden_cxx_method_iterator
1581ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
Benjamin Krameracfa3392017-12-17 23:52:45 +00001582 return overridden_methods(Method).begin();
Douglas Gregor832940b2010-03-02 23:58:15 +00001583}
1584
1585ASTContext::overridden_cxx_method_iterator
1586ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
Benjamin Krameracfa3392017-12-17 23:52:45 +00001587 return overridden_methods(Method).end();
Douglas Gregor832940b2010-03-02 23:58:15 +00001588}
1589
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001590unsigned
1591ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
Benjamin Krameracfa3392017-12-17 23:52:45 +00001592 auto Range = overridden_methods(Method);
1593 return Range.end() - Range.begin();
Clement Courbet8251ebf2016-06-10 11:54:43 +00001594}
1595
Clement Courbet6ecaec82016-07-05 07:49:31 +00001596ASTContext::overridden_method_range
1597ASTContext::overridden_methods(const CXXMethodDecl *Method) const {
Benjamin Krameracfa3392017-12-17 23:52:45 +00001598 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1599 OverriddenMethods.find(Method->getCanonicalDecl());
1600 if (Pos == OverriddenMethods.end())
1601 return overridden_method_range(nullptr, nullptr);
1602 return overridden_method_range(Pos->second.begin(), Pos->second.end());
Clement Courbet6ecaec82016-07-05 07:49:31 +00001603}
1604
Fangrui Song6907ce22018-07-30 19:24:48 +00001605void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
Douglas Gregor832940b2010-03-02 23:58:15 +00001606 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001607 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001608 OverriddenMethods[Method].push_back(Overridden);
1609}
1610
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +00001611void ASTContext::getOverriddenMethods(
1612 const NamedDecl *D,
1613 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001614 assert(D);
1615
Eugene Zelenko7855e772018-04-03 00:11:50 +00001616 if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisc8e70082013-04-17 00:09:03 +00001617 Overridden.append(overridden_methods_begin(CXXMethod),
1618 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001619 return;
1620 }
1621
Eugene Zelenko7855e772018-04-03 00:11:50 +00001622 const auto *Method = dyn_cast<ObjCMethodDecl>(D);
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001623 if (!Method)
1624 return;
1625
Argyrios Kyrtzidis353f6a42012-10-09 18:19:01 +00001626 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1627 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001628 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001629}
1630
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001631void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
Reid Kleckner526a4f2a2020-03-11 13:52:28 -07001632 assert(!Import->getNextLocalImport() &&
1633 "Import declaration already in the chain");
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001634 assert(!Import->isFromASTFile() && "Non-local import declaration");
1635 if (!FirstLocalImport) {
1636 FirstLocalImport = Import;
1637 LastLocalImport = Import;
1638 return;
1639 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001640
Reid Klecknerc915cb92020-02-27 18:13:54 -08001641 LastLocalImport->setNextLocalImport(Import);
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001642 LastLocalImport = Import;
1643}
1644
Chris Lattner53cfe802007-07-18 17:52:12 +00001645//===----------------------------------------------------------------------===//
1646// Type Sizing and Analysis
1647//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001648
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001649/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1650/// scalar floating point type.
1651const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
Simon Pilgrim9588ae72019-10-03 21:47:42 +00001652 switch (T->castAs<BuiltinType>()->getKind()) {
1653 default:
1654 llvm_unreachable("Not a floating point type!");
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00001655 case BuiltinType::Float16:
1656 case BuiltinType::Half:
1657 return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001658 case BuiltinType::Float: return Target->getFloatFormat();
1659 case BuiltinType::Double: return Target->getDoubleFormat();
Alexey Bataeve509af32019-07-09 14:09:53 +00001660 case BuiltinType::LongDouble:
Fangrui Song3fbd8fd2019-07-09 19:36:22 +00001661 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice)
Alexey Bataeve509af32019-07-09 14:09:53 +00001662 return AuxTarget->getLongDoubleFormat();
1663 return Target->getLongDoubleFormat();
1664 case BuiltinType::Float128:
Fangrui Song3fbd8fd2019-07-09 19:36:22 +00001665 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice)
Alexey Bataeve509af32019-07-09 14:09:53 +00001666 return AuxTarget->getFloat128Format();
1667 return Target->getFloat128Format();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001668 }
1669}
1670
Rafael Espindola71eccb32013-08-08 19:53:46 +00001671CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001672 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001673
John McCall94268702010-10-08 18:24:19 +00001674 bool UseAlignAttrOnly = false;
1675 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1676 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001677
John McCall94268702010-10-08 18:24:19 +00001678 // __attribute__((aligned)) can increase or decrease alignment
1679 // *except* on a struct or struct member, where it only increases
1680 // alignment unless 'packed' is also specified.
1681 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001682 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001683 // ignore that possibility; Sema should diagnose it.
1684 if (isa<FieldDecl>(D)) {
1685 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1686 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1687 } else {
1688 UseAlignAttrOnly = true;
1689 }
1690 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001691 else if (isa<FieldDecl>(D))
Fangrui Song6907ce22018-07-30 19:24:48 +00001692 UseAlignAttrOnly =
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001693 D->hasAttr<PackedAttr>() ||
1694 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001695
John McCall4e819612011-01-20 07:57:12 +00001696 // If we're using the align attribute only, just ignore everything
1697 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001698 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001699 // do nothing
Eugene Zelenko7855e772018-04-03 00:11:50 +00001700 } else if (const auto *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001701 QualType T = VD->getType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00001702 if (const auto *RT = T->getAs<ReferenceType>()) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001703 if (ForAlignof)
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001704 T = RT->getPointeeType();
1705 else
1706 T = getPointerType(RT->getPointeeType());
1707 }
Richard Smithf6d70302014-06-10 23:34:28 +00001708 QualType BaseT = getBaseElementType(T);
Akira Hatanakad62f2c82017-01-06 17:56:15 +00001709 if (T->isFunctionType())
1710 Align = getTypeInfoImpl(T.getTypePtr()).Align;
1711 else if (!BaseT->isIncompleteType()) {
John McCall33ddac02011-01-19 10:06:00 +00001712 // Adjust alignments of declarations with array type by the
1713 // large-array alignment on the target.
Rafael Espindola88572752013-08-07 18:08:19 +00001714 if (const ArrayType *arrayType = getAsArrayType(T)) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001715 unsigned MinWidth = Target->getLargeArrayMinWidth();
1716 if (!ForAlignof && MinWidth) {
Rafael Espindola88572752013-08-07 18:08:19 +00001717 if (isa<VariableArrayType>(arrayType))
1718 Align = std::max(Align, Target->getLargeArrayAlign());
1719 else if (isa<ConstantArrayType>(arrayType) &&
1720 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1721 Align = std::max(Align, Target->getLargeArrayAlign());
1722 }
John McCall33ddac02011-01-19 10:06:00 +00001723 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001724 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Roger Ferrer Ibanez3fa38a12017-03-08 14:00:44 +00001725 if (BaseT.getQualifiers().hasUnaligned())
1726 Align = Target->getCharWidth();
Eugene Zelenko7855e772018-04-03 00:11:50 +00001727 if (const auto *VD = dyn_cast<VarDecl>(D)) {
Tom Tanb7c6d952019-05-02 00:38:14 +00001728 if (VD->hasGlobalStorage() && !ForAlignof) {
1729 uint64_t TypeSize = getTypeSize(T.getTypePtr());
1730 Align = std::max(Align, getTargetInfo().getMinGlobalAlign(TypeSize));
1731 }
Ulrich Weigandfa806422013-05-06 16:23:57 +00001732 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001733 }
John McCall4e819612011-01-20 07:57:12 +00001734
1735 // Fields can be subject to extra alignment constraints, like if
1736 // the field is packed, the struct is packed, or the struct has a
1737 // a max-field-alignment constraint (#pragma pack). So calculate
1738 // the actual alignment of the field within the struct, and then
1739 // (as we're expected to) constrain that by the alignment of the type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00001740 if (const auto *Field = dyn_cast<FieldDecl>(VD)) {
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001741 const RecordDecl *Parent = Field->getParent();
1742 // We can only produce a sensible answer if the record is valid.
1743 if (!Parent->isInvalidDecl()) {
1744 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
John McCall4e819612011-01-20 07:57:12 +00001745
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001746 // Start with the record's overall alignment.
1747 unsigned FieldAlign = toBits(Layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001748
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001749 // Use the GCD of that and the offset within the record.
1750 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1751 if (Offset > 0) {
1752 // Alignment is always a power of 2, so the GCD will be a power of 2,
1753 // which means we get to do this crazy thing instead of Euclid's.
1754 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1755 if (LowBitOfOffset < FieldAlign)
1756 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1757 }
1758
1759 Align = std::min(Align, FieldAlign);
John McCall4e819612011-01-20 07:57:12 +00001760 }
Charles Davis3fc51072010-02-23 04:52:00 +00001761 }
Chris Lattner68061312009-01-24 21:53:27 +00001762 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001763
Ken Dyckcc56c542011-01-15 18:38:59 +00001764 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001765}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001766
Reid Kleckner4c2a6562020-02-27 14:16:47 -08001767CharUnits ASTContext::getExnObjectAlignment() const {
1768 return toCharUnitsFromBits(Target->getExnObjectAlignment());
1769}
1770
John McCallf1249922012-08-21 04:10:00 +00001771// getTypeInfoDataSizeInChars - Return the size of a type, in
1772// chars. If the type is a record, its data size is returned. This is
1773// the size of the memcpy that's performed when assigning this type
1774// using a trivial copy/move assignment operator.
1775std::pair<CharUnits, CharUnits>
1776ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1777 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1778
1779 // In C++, objects can sometimes be allocated into the tail padding
1780 // of a base-class subobject. We decide whether that's possible
1781 // during class layout, so here we can just trust the layout results.
1782 if (getLangOpts().CPlusPlus) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001783 if (const auto *RT = T->getAs<RecordType>()) {
John McCallf1249922012-08-21 04:10:00 +00001784 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1785 sizeAndAlign.first = layout.getDataSize();
1786 }
1787 }
1788
1789 return sizeAndAlign;
1790}
1791
Richard Trieu04d2d942013-05-14 21:59:17 +00001792/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1793/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1794std::pair<CharUnits, CharUnits>
1795static getConstantArrayInfoInChars(const ASTContext &Context,
1796 const ConstantArrayType *CAT) {
1797 std::pair<CharUnits, CharUnits> EltInfo =
1798 Context.getTypeInfoInChars(CAT->getElementType());
1799 uint64_t Size = CAT->getSize().getZExtValue();
Richard Trieuc7509072013-05-14 23:41:50 +00001800 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1801 (uint64_t)(-1)/Size) &&
Richard Trieu04d2d942013-05-14 21:59:17 +00001802 "Overflow in array type char size evaluation");
1803 uint64_t Width = EltInfo.first.getQuantity() * Size;
1804 unsigned Align = EltInfo.second.getQuantity();
Warren Hunt5ae586a2013-11-01 23:59:41 +00001805 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1806 Context.getTargetInfo().getPointerWidth(0) == 64)
Rui Ueyama83aa9792016-01-14 21:00:27 +00001807 Width = llvm::alignTo(Width, Align);
Richard Trieu04d2d942013-05-14 21:59:17 +00001808 return std::make_pair(CharUnits::fromQuantity(Width),
1809 CharUnits::fromQuantity(Align));
1810}
1811
John McCall87fe5d52010-05-20 01:18:31 +00001812std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001813ASTContext::getTypeInfoInChars(const Type *T) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001814 if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
Richard Trieu04d2d942013-05-14 21:59:17 +00001815 return getConstantArrayInfoInChars(*this, CAT);
David Majnemer34b57492014-07-30 01:30:47 +00001816 TypeInfo Info = getTypeInfo(T);
1817 return std::make_pair(toCharUnitsFromBits(Info.Width),
1818 toCharUnitsFromBits(Info.Align));
John McCall87fe5d52010-05-20 01:18:31 +00001819}
1820
1821std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001822ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001823 return getTypeInfoInChars(T.getTypePtr());
1824}
1825
David Majnemer34b57492014-07-30 01:30:47 +00001826bool ASTContext::isAlignmentRequired(const Type *T) const {
1827 return getTypeInfo(T).AlignIsRequired;
1828}
Daniel Dunbarc6475872012-03-09 04:12:54 +00001829
David Majnemer34b57492014-07-30 01:30:47 +00001830bool ASTContext::isAlignmentRequired(QualType T) const {
1831 return isAlignmentRequired(T.getTypePtr());
1832}
1833
Richard Smithb2f0f052016-10-10 18:54:32 +00001834unsigned ASTContext::getTypeAlignIfKnown(QualType T) const {
1835 // An alignment on a typedef overrides anything else.
Eugene Zelenko7855e772018-04-03 00:11:50 +00001836 if (const auto *TT = T->getAs<TypedefType>())
Richard Smithb2f0f052016-10-10 18:54:32 +00001837 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1838 return Align;
1839
1840 // If we have an (array of) complete type, we're done.
1841 T = getBaseElementType(T);
1842 if (!T->isIncompleteType())
1843 return getTypeAlign(T);
1844
1845 // If we had an array type, its element type might be a typedef
1846 // type with an alignment attribute.
Eugene Zelenko7855e772018-04-03 00:11:50 +00001847 if (const auto *TT = T->getAs<TypedefType>())
Richard Smithb2f0f052016-10-10 18:54:32 +00001848 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1849 return Align;
1850
1851 // Otherwise, see if the declaration of the type had an attribute.
Eugene Zelenko7855e772018-04-03 00:11:50 +00001852 if (const auto *TT = T->getAs<TagType>())
Richard Smithb2f0f052016-10-10 18:54:32 +00001853 return TT->getDecl()->getMaxAlignment();
1854
1855 return 0;
1856}
1857
David Majnemer34b57492014-07-30 01:30:47 +00001858TypeInfo ASTContext::getTypeInfo(const Type *T) const {
David Majnemerf8d38642014-07-30 08:42:33 +00001859 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1860 if (I != MemoizedTypeInfo.end())
1861 return I->second;
1862
1863 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1864 TypeInfo TI = getTypeInfoImpl(T);
1865 MemoizedTypeInfo[T] = TI;
Rafael Espindolaeaa88c12014-07-30 04:40:23 +00001866 return TI;
Daniel Dunbarc6475872012-03-09 04:12:54 +00001867}
1868
1869/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1870/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001871///
1872/// FIXME: Pointers into different addr spaces could have different sizes and
1873/// alignment requirements: getPointerInfo should take an AddrSpace, this
1874/// should take a QualType, &c.
David Majnemer34b57492014-07-30 01:30:47 +00001875TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1876 uint64_t Width = 0;
1877 unsigned Align = 8;
1878 bool AlignIsRequired = false;
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001879 unsigned AS = 0;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001880 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001881#define TYPE(Class, Base)
1882#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001883#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001884#define DEPENDENT_TYPE(Class, Base) case Type::Class:
David Blaikieab277d62013-07-13 21:08:03 +00001885#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1886 case Type::Class: \
1887 assert(!T->isDependentType() && "should not see dependent types here"); \
1888 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
John McCall36b12a82019-10-02 06:35:23 +00001889#include "clang/AST/TypeNodes.inc"
John McCall15547bb2011-06-28 16:49:23 +00001890 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001891
Chris Lattner355332d2007-07-13 22:27:08 +00001892 case Type::FunctionNoProto:
1893 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001894 // GCC extension: alignof(function) = 32 bits
1895 Width = 0;
1896 Align = 32;
1897 break;
1898
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001899 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001900 case Type::VariableArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001901 case Type::ConstantArray: {
Reid Kleckner8da5b902020-04-08 14:05:54 -07001902 // Model non-constant sized arrays as size zero, but track the alignment.
1903 uint64_t Size = 0;
1904 if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
1905 Size = CAT->getSize().getZExtValue();
Mike Stump11289f42009-09-09 15:08:12 +00001906
Reid Kleckner8da5b902020-04-08 14:05:54 -07001907 TypeInfo EltInfo = getTypeInfo(cast<ArrayType>(T)->getElementType());
David Majnemer34b57492014-07-30 01:30:47 +00001908 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
Daniel Dunbarc6475872012-03-09 04:12:54 +00001909 "Overflow in array type bit size evaluation");
David Majnemer34b57492014-07-30 01:30:47 +00001910 Width = EltInfo.Width * Size;
1911 Align = EltInfo.Align;
Reid Kleckner8da5b902020-04-08 14:05:54 -07001912 AlignIsRequired = EltInfo.AlignIsRequired;
Warren Hunt5ae586a2013-11-01 23:59:41 +00001913 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1914 getTargetInfo().getPointerWidth(0) == 64)
Rui Ueyama83aa9792016-01-14 21:00:27 +00001915 Width = llvm::alignTo(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001916 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001917 }
Reid Kleckner8da5b902020-04-08 14:05:54 -07001918
Nate Begemance4d7fc2008-04-18 23:10:10 +00001919 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001920 case Type::Vector: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001921 const auto *VT = cast<VectorType>(T);
David Majnemer34b57492014-07-30 01:30:47 +00001922 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1923 Width = EltInfo.Width * VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001924 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001925 // If the alignment is not a power of 2, round up to the next power of 2.
1926 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001927 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001928 Align = llvm::NextPowerOf2(Align);
Rui Ueyama83aa9792016-01-14 21:00:27 +00001929 Width = llvm::alignTo(Width, Align);
Chris Lattner63d2b362009-10-22 05:17:15 +00001930 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001931 // Adjust the alignment based on the target max.
1932 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1933 if (TargetVectorAlign && TargetVectorAlign < Align)
1934 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001935 break;
1936 }
Chris Lattner647fb222007-07-18 18:26:58 +00001937
Chris Lattner7570e9c2008-03-08 08:52:55 +00001938 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001939 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001940 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001941 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001942 // GCC extension: alignof(void) = 8 bits.
1943 Width = 0;
1944 Align = 8;
1945 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001946 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001947 Width = Target->getBoolWidth();
1948 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001949 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001950 case BuiltinType::Char_S:
1951 case BuiltinType::Char_U:
1952 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001953 case BuiltinType::SChar:
Richard Smith3a8244d2018-05-01 05:02:45 +00001954 case BuiltinType::Char8:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001955 Width = Target->getCharWidth();
1956 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001957 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001958 case BuiltinType::WChar_S:
1959 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001960 Width = Target->getWCharWidth();
1961 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001962 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001963 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001964 Width = Target->getChar16Width();
1965 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001966 break;
1967 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001968 Width = Target->getChar32Width();
1969 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001970 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001971 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001972 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001973 Width = Target->getShortWidth();
1974 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001975 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001976 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001977 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001978 Width = Target->getIntWidth();
1979 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001980 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001981 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001982 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001983 Width = Target->getLongWidth();
1984 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001985 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001986 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001987 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001988 Width = Target->getLongLongWidth();
1989 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001990 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001991 case BuiltinType::Int128:
1992 case BuiltinType::UInt128:
1993 Width = 128;
1994 Align = 128; // int128_t is 128-bit aligned on all targets.
1995 break;
Leonard Chanf921d852018-06-04 16:07:52 +00001996 case BuiltinType::ShortAccum:
1997 case BuiltinType::UShortAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00001998 case BuiltinType::SatShortAccum:
1999 case BuiltinType::SatUShortAccum:
Leonard Chanf921d852018-06-04 16:07:52 +00002000 Width = Target->getShortAccumWidth();
2001 Align = Target->getShortAccumAlign();
2002 break;
2003 case BuiltinType::Accum:
2004 case BuiltinType::UAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00002005 case BuiltinType::SatAccum:
2006 case BuiltinType::SatUAccum:
Leonard Chanf921d852018-06-04 16:07:52 +00002007 Width = Target->getAccumWidth();
2008 Align = Target->getAccumAlign();
2009 break;
2010 case BuiltinType::LongAccum:
2011 case BuiltinType::ULongAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00002012 case BuiltinType::SatLongAccum:
2013 case BuiltinType::SatULongAccum:
Leonard Chanf921d852018-06-04 16:07:52 +00002014 Width = Target->getLongAccumWidth();
2015 Align = Target->getLongAccumAlign();
2016 break;
Leonard Chanab80f3c2018-06-14 14:53:51 +00002017 case BuiltinType::ShortFract:
2018 case BuiltinType::UShortFract:
2019 case BuiltinType::SatShortFract:
2020 case BuiltinType::SatUShortFract:
2021 Width = Target->getShortFractWidth();
2022 Align = Target->getShortFractAlign();
2023 break;
2024 case BuiltinType::Fract:
2025 case BuiltinType::UFract:
2026 case BuiltinType::SatFract:
2027 case BuiltinType::SatUFract:
2028 Width = Target->getFractWidth();
2029 Align = Target->getFractAlign();
2030 break;
2031 case BuiltinType::LongFract:
2032 case BuiltinType::ULongFract:
2033 case BuiltinType::SatLongFract:
2034 case BuiltinType::SatULongFract:
2035 Width = Target->getLongFractWidth();
2036 Align = Target->getLongFractAlign();
2037 break;
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00002038 case BuiltinType::Float16:
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002039 case BuiltinType::Half:
Alexey Bataev123ad192019-02-27 20:29:45 +00002040 if (Target->hasFloat16Type() || !getLangOpts().OpenMP ||
2041 !getLangOpts().OpenMPIsDevice) {
2042 Width = Target->getHalfWidth();
2043 Align = Target->getHalfAlign();
2044 } else {
2045 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
2046 "Expected OpenMP device compilation.");
2047 Width = AuxTarget->getHalfWidth();
2048 Align = AuxTarget->getHalfAlign();
2049 }
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002050 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00002051 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00002052 Width = Target->getFloatWidth();
2053 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00002054 break;
2055 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00002056 Width = Target->getDoubleWidth();
2057 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00002058 break;
2059 case BuiltinType::LongDouble:
Alexey Bataev8557d1a2019-06-18 18:39:26 +00002060 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
2061 (Target->getLongDoubleWidth() != AuxTarget->getLongDoubleWidth() ||
2062 Target->getLongDoubleAlign() != AuxTarget->getLongDoubleAlign())) {
2063 Width = AuxTarget->getLongDoubleWidth();
2064 Align = AuxTarget->getLongDoubleAlign();
2065 } else {
2066 Width = Target->getLongDoubleWidth();
2067 Align = Target->getLongDoubleAlign();
2068 }
Chris Lattner6a4f7452007-12-19 19:23:28 +00002069 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00002070 case BuiltinType::Float128:
Alexey Bataev123ad192019-02-27 20:29:45 +00002071 if (Target->hasFloat128Type() || !getLangOpts().OpenMP ||
2072 !getLangOpts().OpenMPIsDevice) {
2073 Width = Target->getFloat128Width();
2074 Align = Target->getFloat128Align();
2075 } else {
2076 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
2077 "Expected OpenMP device compilation.");
2078 Width = AuxTarget->getFloat128Width();
2079 Align = AuxTarget->getFloat128Align();
2080 }
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00002081 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00002082 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00002083 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
2084 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00002085 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00002086 case BuiltinType::ObjCId:
2087 case BuiltinType::ObjCClass:
2088 case BuiltinType::ObjCSel:
Fangrui Song6907ce22018-07-30 19:24:48 +00002089 Width = Target->getPointerWidth(0);
Douglas Gregore8bbc122011-09-02 00:18:52 +00002090 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00002091 break;
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00002092 case BuiltinType::OCLSampler:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00002093 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00002094 case BuiltinType::OCLClkEvent:
2095 case BuiltinType::OCLQueue:
Alexey Bader9c8453f2015-09-15 11:18:52 +00002096 case BuiltinType::OCLReserveID:
Yaxun Liu99444cb2016-08-03 20:38:06 +00002097#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2098 case BuiltinType::Id:
2099#include "clang/Basic/OpenCLImageTypes.def"
Andrew Savonichev3fee3512018-11-08 11:25:41 +00002100#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2101 case BuiltinType::Id:
2102#include "clang/Basic/OpenCLExtensionTypes.def"
Sven van Haastregt3bb7eaf2017-12-06 10:11:28 +00002103 AS = getTargetAddressSpace(
2104 Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T)));
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00002105 Width = Target->getPointerWidth(AS);
2106 Align = Target->getPointerAlign(AS);
2107 break;
Richard Sandifordeb485fb2019-08-09 08:52:54 +00002108 // The SVE types are effectively target-specific. The length of an
2109 // SVE_VECTOR_TYPE is only known at runtime, but it is always a multiple
2110 // of 128 bits. There is one predicate bit for each vector byte, so the
2111 // length of an SVE_PREDICATE_TYPE is always a multiple of 16 bits.
2112 //
2113 // Because the length is only known at runtime, we use a dummy value
2114 // of 0 for the static length. The alignment values are those defined
2115 // by the Procedure Call Standard for the Arm Architecture.
Sander de Smalen5087ace2020-03-15 14:29:45 +00002116#define SVE_VECTOR_TYPE(Name, Id, SingletonId, NumEls, ElBits, IsSigned, IsFP) \
2117 case BuiltinType::Id: \
2118 Width = 0; \
2119 Align = 128; \
2120 break;
2121#define SVE_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
2122 case BuiltinType::Id: \
2123 Width = 0; \
2124 Align = 16; \
2125 break;
Richard Sandifordeb485fb2019-08-09 08:52:54 +00002126#include "clang/Basic/AArch64SVEACLETypes.def"
Chris Lattner983a8bb2007-07-13 22:13:22 +00002127 }
Chris Lattner48f84b82007-07-15 23:46:53 +00002128 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00002129 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00002130 Width = Target->getPointerWidth(0);
2131 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00002132 break;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002133 case Type::BlockPointer:
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00002134 AS = getTargetAddressSpace(cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00002135 Width = Target->getPointerWidth(AS);
2136 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00002137 break;
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002138 case Type::LValueReference:
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002139 case Type::RValueReference:
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002140 // alignof and sizeof should never enter this code path here, so we go
2141 // the pointer route.
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00002142 AS = getTargetAddressSpace(cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00002143 Width = Target->getPointerWidth(AS);
2144 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002145 break;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002146 case Type::Pointer:
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00002147 AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00002148 Width = Target->getPointerWidth(AS);
2149 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00002150 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002151 case Type::MemberPointer: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002152 const auto *MPT = cast<MemberPointerType>(T);
Erich Keane8a6b7402017-11-30 16:37:02 +00002153 CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT);
2154 Width = MPI.Width;
2155 Align = MPI.Align;
Anders Carlsson32440a02009-05-17 02:06:04 +00002156 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002157 }
Chris Lattner647fb222007-07-18 18:26:58 +00002158 case Type::Complex: {
2159 // Complex types have the same alignment as their elements, but twice the
2160 // size.
David Majnemer34b57492014-07-30 01:30:47 +00002161 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
2162 Width = EltInfo.Width * 2;
2163 Align = EltInfo.Align;
Chris Lattner647fb222007-07-18 18:26:58 +00002164 break;
2165 }
John McCall8b07ec22010-05-15 11:32:37 +00002166 case Type::ObjCObject:
2167 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Reid Kleckner0503a872013-12-05 01:23:43 +00002168 case Type::Adjusted:
Reid Kleckner8a365022013-06-24 17:51:48 +00002169 case Type::Decayed:
Reid Kleckner0503a872013-12-05 01:23:43 +00002170 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00002171 case Type::ObjCInterface: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002172 const auto *ObjCI = cast<ObjCInterfaceType>(T);
Haojian Wuf757ecb2020-03-27 21:40:30 +01002173 if (ObjCI->getDecl()->isInvalidDecl()) {
2174 Width = 8;
2175 Align = 8;
2176 break;
2177 }
Devang Pateldbb72632008-06-04 21:54:36 +00002178 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00002179 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00002180 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00002181 break;
2182 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002183 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002184 case Type::Enum: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002185 const auto *TT = cast<TagType>(T);
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00002186
2187 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00002188 Width = 8;
2189 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00002190 break;
2191 }
Mike Stump11289f42009-09-09 15:08:12 +00002192
Eugene Zelenko7855e772018-04-03 00:11:50 +00002193 if (const auto *ET = dyn_cast<EnumType>(TT)) {
David Majnemer475b25e2015-01-21 10:54:38 +00002194 const EnumDecl *ED = ET->getDecl();
2195 TypeInfo Info =
2196 getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType());
2197 if (unsigned AttrAlign = ED->getMaxAlignment()) {
2198 Info.Align = AttrAlign;
2199 Info.AlignIsRequired = true;
2200 }
2201 return Info;
2202 }
Chris Lattner8b23c252008-04-06 22:05:18 +00002203
Eugene Zelenko7855e772018-04-03 00:11:50 +00002204 const auto *RT = cast<RecordType>(TT);
David Majnemer5821ff72015-02-03 08:49:29 +00002205 const RecordDecl *RD = RT->getDecl();
2206 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
Ken Dyckb0fcc592011-02-11 01:54:29 +00002207 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00002208 Align = toBits(Layout.getAlignment());
David Majnemer5821ff72015-02-03 08:49:29 +00002209 AlignIsRequired = RD->hasAttr<AlignedAttr>();
Chris Lattner49a953a2007-07-23 22:46:22 +00002210 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00002211 }
Douglas Gregordc572a32009-03-30 22:58:21 +00002212
Chris Lattner63d2b362009-10-22 05:17:15 +00002213 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00002214 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
2215 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00002216
Richard Smith600b5262017-01-26 20:40:47 +00002217 case Type::Auto:
2218 case Type::DeducedTemplateSpecialization: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002219 const auto *A = cast<DeducedType>(T);
Richard Smith27d807c2013-04-30 13:56:41 +00002220 assert(!A->getDeducedType().isNull() &&
2221 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00002222 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00002223 }
2224
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002225 case Type::Paren:
2226 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
2227
Leonard Chanc72aaf62019-05-07 03:20:17 +00002228 case Type::MacroQualified:
2229 return getTypeInfo(
2230 cast<MacroQualifiedType>(T)->getUnderlyingType().getTypePtr());
2231
Manman Rene6be26c2016-09-13 17:25:08 +00002232 case Type::ObjCTypeParam:
2233 return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr());
2234
Douglas Gregoref462e62009-04-30 17:32:17 +00002235 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00002236 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
David Majnemer34b57492014-07-30 01:30:47 +00002237 TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00002238 // If the typedef has an aligned attribute on it, it overrides any computed
2239 // alignment we have. This violates the GCC documentation (which says that
2240 // attribute(aligned) can only round up) but matches its implementation.
David Majnemer34b57492014-07-30 01:30:47 +00002241 if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
Chris Lattner29eb47b2011-02-19 22:55:41 +00002242 Align = AttrAlign;
David Majnemer34b57492014-07-30 01:30:47 +00002243 AlignIsRequired = true;
David Majnemer37bffb62014-08-04 05:11:01 +00002244 } else {
David Majnemer34b57492014-07-30 01:30:47 +00002245 Align = Info.Align;
David Majnemer37bffb62014-08-04 05:11:01 +00002246 AlignIsRequired = Info.AlignIsRequired;
2247 }
David Majnemer34b57492014-07-30 01:30:47 +00002248 Width = Info.Width;
Douglas Gregordc572a32009-03-30 22:58:21 +00002249 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00002250 }
Douglas Gregoref462e62009-04-30 17:32:17 +00002251
Abramo Bagnara6150c882010-05-11 21:36:43 +00002252 case Type::Elaborated:
2253 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00002254
John McCall81904512011-01-06 01:58:22 +00002255 case Type::Attributed:
2256 return getTypeInfo(
2257 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
2258
Eli Friedman0dfb8892011-10-06 23:00:33 +00002259 case Type::Atomic: {
John McCalla8ec7eb2013-03-07 21:37:17 +00002260 // Start with the base type information.
David Majnemer34b57492014-07-30 01:30:47 +00002261 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
2262 Width = Info.Width;
2263 Align = Info.Align;
John McCalla8ec7eb2013-03-07 21:37:17 +00002264
JF Bastien801fca22018-05-09 03:51:12 +00002265 if (!Width) {
2266 // An otherwise zero-sized type should still generate an
2267 // atomic operation.
2268 Width = Target->getCharWidth();
2269 assert(Align);
2270 } else if (Width <= Target->getMaxAtomicPromoteWidth()) {
2271 // If the size of the type doesn't exceed the platform's max
2272 // atomic promotion width, make the size and alignment more
2273 // favorable to atomic operations:
2274
John McCalla8ec7eb2013-03-07 21:37:17 +00002275 // Round the size up to a power of 2.
2276 if (!llvm::isPowerOf2_64(Width))
2277 Width = llvm::NextPowerOf2(Width);
2278
2279 // Set the alignment equal to the size.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00002280 Align = static_cast<unsigned>(Width);
2281 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00002282 }
Xiuli Pan9c14e282016-01-09 12:53:17 +00002283 break;
2284
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002285 case Type::Pipe:
Anastasia Stulovab3398932017-06-05 11:27:03 +00002286 Width = Target->getPointerWidth(getTargetAddressSpace(LangAS::opencl_global));
2287 Align = Target->getPointerAlign(getTargetAddressSpace(LangAS::opencl_global));
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002288 break;
Douglas Gregoref462e62009-04-30 17:32:17 +00002289 }
Mike Stump11289f42009-09-09 15:08:12 +00002290
Eli Friedman4b72fdd2011-10-14 20:59:01 +00002291 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
David Majnemer34b57492014-07-30 01:30:47 +00002292 return TypeInfo(Width, Align, AlignIsRequired);
Chris Lattner983a8bb2007-07-13 22:13:22 +00002293}
2294
Momchil Velikov20208cc2018-07-30 17:48:23 +00002295unsigned ASTContext::getTypeUnadjustedAlign(const Type *T) const {
2296 UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(T);
2297 if (I != MemoizedUnadjustedAlign.end())
2298 return I->second;
2299
2300 unsigned UnadjustedAlign;
2301 if (const auto *RT = T->getAs<RecordType>()) {
2302 const RecordDecl *RD = RT->getDecl();
2303 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2304 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2305 } else if (const auto *ObjCI = T->getAs<ObjCInterfaceType>()) {
2306 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2307 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2308 } else {
John Brawn6c49f582019-05-22 11:42:54 +00002309 UnadjustedAlign = getTypeAlign(T->getUnqualifiedDesugaredType());
Momchil Velikov20208cc2018-07-30 17:48:23 +00002310 }
2311
2312 MemoizedUnadjustedAlign[T] = UnadjustedAlign;
2313 return UnadjustedAlign;
2314}
2315
Alexey Bataev00396512015-07-02 03:40:19 +00002316unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
2317 unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign();
2318 // Target ppc64 with QPX: simd default alignment for pointer to double is 32.
2319 if ((getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64 ||
2320 getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64le) &&
2321 getTargetInfo().getABI() == "elfv1-qpx" &&
2322 T->isSpecificBuiltinType(BuiltinType::Double))
2323 SimdAlign = 256;
2324 return SimdAlign;
2325}
2326
Ken Dyckcc56c542011-01-15 18:38:59 +00002327/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
2328CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
2329 return CharUnits::fromQuantity(BitSize / getCharWidth());
2330}
2331
Ken Dyckb0fcc592011-02-11 01:54:29 +00002332/// toBits - Convert a size in characters to a size in characters.
2333int64_t ASTContext::toBits(CharUnits CharSize) const {
2334 return CharSize.getQuantity() * getCharWidth();
2335}
2336
Ken Dyck8c89d592009-12-22 14:23:30 +00002337/// getTypeSizeInChars - Return the size of the specified type, in characters.
2338/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00002339CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00002340 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00002341}
Jay Foad39c79802011-01-12 09:06:06 +00002342CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00002343 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00002344}
2345
Fangrui Song6907ce22018-07-30 19:24:48 +00002346/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00002347/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00002348CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00002349 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00002350}
Jay Foad39c79802011-01-12 09:06:06 +00002351CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00002352 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00002353}
2354
Momchil Velikov20208cc2018-07-30 17:48:23 +00002355/// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a
2356/// type, in characters, before alignment adustments. This method does
2357/// not work on incomplete types.
2358CharUnits ASTContext::getTypeUnadjustedAlignInChars(QualType T) const {
2359 return toCharUnitsFromBits(getTypeUnadjustedAlign(T));
2360}
2361CharUnits ASTContext::getTypeUnadjustedAlignInChars(const Type *T) const {
2362 return toCharUnitsFromBits(getTypeUnadjustedAlign(T));
2363}
2364
Chris Lattnera3402cd2009-01-27 18:08:34 +00002365/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
2366/// type for the current target in bits. This can be different than the ABI
2367/// alignment in cases where it is beneficial for performance to overalign
2368/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00002369unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
David Majnemer34b57492014-07-30 01:30:47 +00002370 TypeInfo TI = getTypeInfo(T);
2371 unsigned ABIAlign = TI.Align;
Eli Friedman7ab09572009-05-25 21:27:19 +00002372
David Majnemere1544562015-04-24 01:25:05 +00002373 T = T->getBaseElementTypeUnsafe();
2374
2375 // The preferred alignment of member pointers is that of a pointer.
2376 if (T->isMemberPointerType())
2377 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
2378
Andrey Turetskiydb6655f2016-02-10 11:58:46 +00002379 if (!Target->allowsLargerPreferedTypeAlignment())
2380 return ABIAlign;
Robert Lyttoneaf6f362013-11-12 10:09:34 +00002381
Eli Friedman7ab09572009-05-25 21:27:19 +00002382 // Double and long long should be naturally aligned if possible.
Eugene Zelenko7855e772018-04-03 00:11:50 +00002383 if (const auto *CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00002384 T = CT->getElementType().getTypePtr();
Eugene Zelenko7855e772018-04-03 00:11:50 +00002385 if (const auto *ET = T->getAs<EnumType>())
David Majnemer475b25e2015-01-21 10:54:38 +00002386 T = ET->getDecl()->getIntegerType().getTypePtr();
Eli Friedman7ab09572009-05-25 21:27:19 +00002387 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00002388 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
2389 T->isSpecificBuiltinType(BuiltinType::ULongLong))
David Majnemer8b6bd572014-02-24 23:34:17 +00002390 // Don't increase the alignment if an alignment attribute was specified on a
2391 // typedef declaration.
David Majnemer34b57492014-07-30 01:30:47 +00002392 if (!TI.AlignIsRequired)
David Majnemer8b6bd572014-02-24 23:34:17 +00002393 return std::max(ABIAlign, (unsigned)getTypeSize(T));
Eli Friedman7ab09572009-05-25 21:27:19 +00002394
Chris Lattnera3402cd2009-01-27 18:08:34 +00002395 return ABIAlign;
2396}
2397
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00002398/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2399/// for __attribute__((aligned)) on this target, to be used if no alignment
2400/// value is specified.
Eugene Zelenkod4304d22015-11-04 21:37:17 +00002401unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const {
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00002402 return getTargetInfo().getDefaultAlignForAttributeAligned();
2403}
2404
Ulrich Weigandfa806422013-05-06 16:23:57 +00002405/// getAlignOfGlobalVar - Return the alignment in bits that should be given
2406/// to a global variable of the specified type.
2407unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
Tom Tanb7c6d952019-05-02 00:38:14 +00002408 uint64_t TypeSize = getTypeSize(T.getTypePtr());
2409 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign(TypeSize));
Ulrich Weigandfa806422013-05-06 16:23:57 +00002410}
2411
2412/// getAlignOfGlobalVarInChars - Return the alignment in characters that
2413/// should be given to a global variable of the specified type.
2414CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
2415 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
2416}
2417
David Majnemer08ef2ba2015-06-23 20:34:18 +00002418CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
2419 CharUnits Offset = CharUnits::Zero();
2420 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
2421 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2422 Offset += Layout->getBaseClassOffset(Base);
2423 Layout = &getASTRecordLayout(Base);
2424 }
2425 return Offset;
2426}
2427
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002428/// DeepCollectObjCIvars -
2429/// This routine first collects all declared, but not synthesized, ivars in
2430/// super class and then collects all ivars, including those synthesized for
2431/// current class. This routine is used for implementation of current class
2432/// when all ivars, declared and synthesized are known.
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002433void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
2434 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00002435 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002436 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2437 DeepCollectObjCIvars(SuperClass, false, Ivars);
2438 if (!leafClass) {
Aaron Ballman59abbd42014-03-13 21:09:43 +00002439 for (const auto *I : OI->ivars())
2440 Ivars.push_back(I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00002441 } else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002442 auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Fangrui Song6907ce22018-07-30 19:24:48 +00002443 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00002444 Iv= Iv->getNextIvar())
2445 Ivars.push_back(Iv);
2446 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00002447}
2448
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002449/// CollectInheritedProtocols - Collect all protocols in current class and
2450/// those inherited by it.
2451void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00002452 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002453 if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00002454 // We can use protocol_iterator here instead of
Fangrui Song6907ce22018-07-30 19:24:48 +00002455 // all_referenced_protocol_iterator since we are walking all categories.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002456 for (auto *Proto : OI->all_referenced_protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002457 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00002458 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002459
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002460 // Categories of this Interface.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00002461 for (const auto *Cat : OI->visible_categories())
2462 CollectInheritedProtocols(Cat, Protocols);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002463
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002464 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2465 while (SD) {
2466 CollectInheritedProtocols(SD, Protocols);
2467 SD = SD->getSuperClass();
2468 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00002469 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00002470 for (auto *Proto : OC->protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002471 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002472 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00002473 } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002474 // Insert the protocol.
2475 if (!Protocols.insert(
2476 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2477 return;
2478
2479 for (auto *Proto : OP->protocols())
2480 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002481 }
2482}
2483
Erich Keane8a6b7402017-11-30 16:37:02 +00002484static bool unionHasUniqueObjectRepresentations(const ASTContext &Context,
2485 const RecordDecl *RD) {
2486 assert(RD->isUnion() && "Must be union type");
2487 CharUnits UnionSize = Context.getTypeSizeInChars(RD->getTypeForDecl());
2488
2489 for (const auto *Field : RD->fields()) {
2490 if (!Context.hasUniqueObjectRepresentations(Field->getType()))
2491 return false;
2492 CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType());
2493 if (FieldSize != UnionSize)
2494 return false;
2495 }
Eric Fiselier12a9f342018-02-02 20:30:39 +00002496 return !RD->field_empty();
Erich Keane8a6b7402017-11-30 16:37:02 +00002497}
2498
Benjamin Kramer802e6252017-12-24 12:46:22 +00002499static bool isStructEmpty(QualType Ty) {
Erich Keane8a6b7402017-11-30 16:37:02 +00002500 const RecordDecl *RD = Ty->castAs<RecordType>()->getDecl();
2501
2502 if (!RD->field_empty())
2503 return false;
2504
2505 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD))
2506 return ClassDecl->isEmpty();
2507
2508 return true;
2509}
2510
2511static llvm::Optional<int64_t>
2512structHasUniqueObjectRepresentations(const ASTContext &Context,
2513 const RecordDecl *RD) {
2514 assert(!RD->isUnion() && "Must be struct/class type");
2515 const auto &Layout = Context.getASTRecordLayout(RD);
2516
2517 int64_t CurOffsetInBits = 0;
2518 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) {
2519 if (ClassDecl->isDynamicClass())
2520 return llvm::None;
2521
2522 SmallVector<std::pair<QualType, int64_t>, 4> Bases;
Mark de Wever29e78ec2019-12-15 21:17:07 +01002523 for (const auto &Base : ClassDecl->bases()) {
Erich Keane8a6b7402017-11-30 16:37:02 +00002524 // Empty types can be inherited from, and non-empty types can potentially
2525 // have tail padding, so just make sure there isn't an error.
2526 if (!isStructEmpty(Base.getType())) {
2527 llvm::Optional<int64_t> Size = structHasUniqueObjectRepresentations(
Simon Pilgrimeed4b122019-10-02 11:48:06 +00002528 Context, Base.getType()->castAs<RecordType>()->getDecl());
Erich Keane8a6b7402017-11-30 16:37:02 +00002529 if (!Size)
2530 return llvm::None;
2531 Bases.emplace_back(Base.getType(), Size.getValue());
2532 }
2533 }
2534
Fangrui Song1d38c132018-09-30 21:41:11 +00002535 llvm::sort(Bases, [&](const std::pair<QualType, int64_t> &L,
2536 const std::pair<QualType, int64_t> &R) {
2537 return Layout.getBaseClassOffset(L.first->getAsCXXRecordDecl()) <
2538 Layout.getBaseClassOffset(R.first->getAsCXXRecordDecl());
2539 });
Erich Keane8a6b7402017-11-30 16:37:02 +00002540
Mark de Wever29e78ec2019-12-15 21:17:07 +01002541 for (const auto &Base : Bases) {
Erich Keane8a6b7402017-11-30 16:37:02 +00002542 int64_t BaseOffset = Context.toBits(
2543 Layout.getBaseClassOffset(Base.first->getAsCXXRecordDecl()));
2544 int64_t BaseSize = Base.second;
2545 if (BaseOffset != CurOffsetInBits)
2546 return llvm::None;
2547 CurOffsetInBits = BaseOffset + BaseSize;
2548 }
2549 }
2550
2551 for (const auto *Field : RD->fields()) {
2552 if (!Field->getType()->isReferenceType() &&
2553 !Context.hasUniqueObjectRepresentations(Field->getType()))
2554 return llvm::None;
2555
2556 int64_t FieldSizeInBits =
2557 Context.toBits(Context.getTypeSizeInChars(Field->getType()));
2558 if (Field->isBitField()) {
2559 int64_t BitfieldSize = Field->getBitWidthValue(Context);
2560
2561 if (BitfieldSize > FieldSizeInBits)
2562 return llvm::None;
2563 FieldSizeInBits = BitfieldSize;
2564 }
2565
2566 int64_t FieldOffsetInBits = Context.getFieldOffset(Field);
2567
2568 if (FieldOffsetInBits != CurOffsetInBits)
2569 return llvm::None;
2570
2571 CurOffsetInBits = FieldSizeInBits + FieldOffsetInBits;
2572 }
2573
2574 return CurOffsetInBits;
2575}
2576
2577bool ASTContext::hasUniqueObjectRepresentations(QualType Ty) const {
2578 // C++17 [meta.unary.prop]:
2579 // The predicate condition for a template specialization
2580 // has_unique_object_representations<T> shall be
2581 // satisfied if and only if:
2582 // (9.1) - T is trivially copyable, and
2583 // (9.2) - any two objects of type T with the same value have the same
2584 // object representation, where two objects
2585 // of array or non-union class type are considered to have the same value
2586 // if their respective sequences of
2587 // direct subobjects have the same values, and two objects of union type
2588 // are considered to have the same
2589 // value if they have the same active member and the corresponding members
2590 // have the same value.
2591 // The set of scalar types for which this condition holds is
2592 // implementation-defined. [ Note: If a type has padding
2593 // bits, the condition does not hold; otherwise, the condition holds true
2594 // for unsigned integral types. -- end note ]
2595 assert(!Ty.isNull() && "Null QualType sent to unique object rep check");
2596
2597 // Arrays are unique only if their element type is unique.
2598 if (Ty->isArrayType())
2599 return hasUniqueObjectRepresentations(getBaseElementType(Ty));
2600
2601 // (9.1) - T is trivially copyable...
2602 if (!Ty.isTriviallyCopyableType(*this))
2603 return false;
2604
2605 // All integrals and enums are unique.
2606 if (Ty->isIntegralOrEnumerationType())
2607 return true;
2608
2609 // All other pointers are unique.
2610 if (Ty->isPointerType())
2611 return true;
2612
2613 if (Ty->isMemberPointerType()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002614 const auto *MPT = Ty->getAs<MemberPointerType>();
Erich Keane8a6b7402017-11-30 16:37:02 +00002615 return !ABI->getMemberPointerInfo(MPT).HasPadding;
2616 }
2617
2618 if (Ty->isRecordType()) {
Simon Pilgrimeed4b122019-10-02 11:48:06 +00002619 const RecordDecl *Record = Ty->castAs<RecordType>()->getDecl();
Erich Keane8a6b7402017-11-30 16:37:02 +00002620
Erich Keanebd2197c2017-12-12 16:02:06 +00002621 if (Record->isInvalidDecl())
2622 return false;
2623
Erich Keane8a6b7402017-11-30 16:37:02 +00002624 if (Record->isUnion())
2625 return unionHasUniqueObjectRepresentations(*this, Record);
2626
2627 Optional<int64_t> StructSize =
2628 structHasUniqueObjectRepresentations(*this, Record);
2629
2630 return StructSize &&
2631 StructSize.getValue() == static_cast<int64_t>(getTypeSize(Ty));
2632 }
2633
2634 // FIXME: More cases to handle here (list by rsmith):
2635 // vectors (careful about, eg, vector of 3 foo)
2636 // _Complex int and friends
2637 // _Atomic T
2638 // Obj-C block pointers
2639 // Obj-C object pointers
2640 // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t,
2641 // clk_event_t, queue_t, reserve_id_t)
2642 // There're also Obj-C class types and the Obj-C selector type, but I think it
2643 // makes sense for those to return false here.
2644
2645 return false;
2646}
2647
Jay Foad39c79802011-01-12 09:06:06 +00002648unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00002649 unsigned count = 0;
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00002650 // Count ivars declared in class extension.
Aaron Ballmanb4a53452014-03-13 21:57:01 +00002651 for (const auto *Ext : OI->known_extensions())
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002652 count += Ext->ivar_size();
Fangrui Song6907ce22018-07-30 19:24:48 +00002653
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00002654 // Count ivar defined in this class's implementation. This
2655 // includes synthesized ivars.
2656 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00002657 count += ImplDecl->ivar_size();
2658
Fariborz Jahanian7c809592009-06-04 01:19:09 +00002659 return count;
2660}
2661
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00002662bool ASTContext::isSentinelNullExpr(const Expr *E) {
2663 if (!E)
2664 return false;
2665
2666 // nullptr_t is always treated as null.
2667 if (E->getType()->isNullPtrType()) return true;
2668
2669 if (E->getType()->isAnyPointerType() &&
2670 E->IgnoreParenCasts()->isNullPointerConstant(*this,
2671 Expr::NPC_ValueDependentIsNull))
2672 return true;
2673
2674 // Unfortunately, __null has type 'int'.
2675 if (isa<GNUNullExpr>(E)) return true;
2676
2677 return false;
2678}
2679
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002680/// Get the implementation of ObjCInterfaceDecl, or nullptr if none
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002681/// exists.
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002682ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
2683 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2684 I = ObjCImpls.find(D);
2685 if (I != ObjCImpls.end())
2686 return cast<ObjCImplementationDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002687 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002688}
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002689
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002690/// Get the implementation of ObjCCategoryDecl, or nullptr if none
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002691/// exists.
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002692ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
2693 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2694 I = ObjCImpls.find(D);
2695 if (I != ObjCImpls.end())
2696 return cast<ObjCCategoryImplDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002697 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002698}
2699
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002700/// Set the implementation of ObjCInterfaceDecl.
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002701void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2702 ObjCImplementationDecl *ImplD) {
2703 assert(IFaceD && ImplD && "Passed null params");
2704 ObjCImpls[IFaceD] = ImplD;
2705}
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002706
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002707/// Set the implementation of ObjCCategoryDecl.
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002708void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
2709 ObjCCategoryImplDecl *ImplD) {
2710 assert(CatD && ImplD && "Passed null params");
2711 ObjCImpls[CatD] = ImplD;
2712}
2713
Chandler Carruth21c90602015-12-30 03:24:14 +00002714const ObjCMethodDecl *
2715ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const {
2716 return ObjCMethodRedecls.lookup(MD);
2717}
2718
2719void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
2720 const ObjCMethodDecl *Redecl) {
2721 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
2722 ObjCMethodRedecls[MD] = Redecl;
2723}
2724
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002725const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
2726 const NamedDecl *ND) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002727 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002728 return ID;
Eugene Zelenko7855e772018-04-03 00:11:50 +00002729 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002730 return CD->getClassInterface();
Eugene Zelenko7855e772018-04-03 00:11:50 +00002731 if (const auto *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002732 return IMD->getClassInterface();
2733
Craig Topper36250ad2014-05-12 05:36:57 +00002734 return nullptr;
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002735}
2736
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002737/// Get the copy initialization expression of VarDecl, or nullptr if
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002738/// none exists.
Reid Kleckner60573ae2019-11-15 17:31:55 -08002739BlockVarCopyInit ASTContext::getBlockVarCopyInit(const VarDecl *VD) const {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002740 assert(VD && "Passed null params");
Fangrui Song6907ce22018-07-30 19:24:48 +00002741 assert(VD->hasAttr<BlocksAttr>() &&
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002742 "getBlockVarCopyInits - not __block var");
Akira Hatanaka9978da32018-08-10 15:09:24 +00002743 auto I = BlockVarCopyInits.find(VD);
2744 if (I != BlockVarCopyInits.end())
2745 return I->second;
2746 return {nullptr, false};
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002747}
2748
JF Bastien0d702a72019-04-30 00:11:53 +00002749/// Set the copy initialization expression of a block var decl.
Akira Hatanaka9978da32018-08-10 15:09:24 +00002750void ASTContext::setBlockVarCopyInit(const VarDecl*VD, Expr *CopyExpr,
2751 bool CanThrow) {
2752 assert(VD && CopyExpr && "Passed null params");
Fangrui Song6907ce22018-07-30 19:24:48 +00002753 assert(VD->hasAttr<BlocksAttr>() &&
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002754 "setBlockVarCopyInits - not __block var");
Akira Hatanaka9978da32018-08-10 15:09:24 +00002755 BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002756}
2757
John McCallbcd03502009-12-07 02:54:59 +00002758TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002759 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00002760 if (!DataSize)
2761 DataSize = TypeLoc::getFullDataSizeForType(T);
2762 else
2763 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00002764 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00002765
Eugene Zelenko7855e772018-04-03 00:11:50 +00002766 auto *TInfo =
John McCallbcd03502009-12-07 02:54:59 +00002767 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
2768 new (TInfo) TypeSourceInfo(T);
2769 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00002770}
2771
John McCallbcd03502009-12-07 02:54:59 +00002772TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002773 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00002774 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00002775 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00002776 return DI;
2777}
2778
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002779const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002780ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Craig Topper36250ad2014-05-12 05:36:57 +00002781 return getObjCLayout(D, nullptr);
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002782}
2783
2784const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002785ASTContext::getASTObjCImplementationLayout(
2786 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002787 return getObjCLayout(D->getClassInterface(), D);
2788}
2789
Chris Lattner983a8bb2007-07-13 22:13:22 +00002790//===----------------------------------------------------------------------===//
2791// Type creation/memoization methods
2792//===----------------------------------------------------------------------===//
2793
Jay Foad39c79802011-01-12 09:06:06 +00002794QualType
John McCall33ddac02011-01-19 10:06:00 +00002795ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2796 unsigned fastQuals = quals.getFastQualifiers();
2797 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00002798
2799 // Check if we've already instantiated this type.
2800 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002801 ExtQuals::Profile(ID, baseType, quals);
Craig Topper36250ad2014-05-12 05:36:57 +00002802 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002803 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2804 assert(eq->getQualifiers() == quals);
2805 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002806 }
2807
John McCall33ddac02011-01-19 10:06:00 +00002808 // If the base type is not canonical, make the appropriate canonical type.
2809 QualType canon;
2810 if (!baseType->isCanonicalUnqualified()) {
2811 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00002812 canonSplit.Quals.addConsistentQualifiers(quals);
2813 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002814
2815 // Re-find the insert position.
2816 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2817 }
2818
Eugene Zelenko7855e772018-04-03 00:11:50 +00002819 auto *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
John McCall33ddac02011-01-19 10:06:00 +00002820 ExtQualNodes.InsertNode(eq, insertPos);
2821 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002822}
2823
Alexander Richardson6d989432017-10-15 18:48:14 +00002824QualType ASTContext::getAddrSpaceQualType(QualType T,
2825 LangAS AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002826 QualType CanT = getCanonicalType(T);
2827 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00002828 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00002829
John McCall8ccfcb52009-09-24 19:53:00 +00002830 // If we are composing extended qualifiers together, merge together
2831 // into one ExtQuals node.
2832 QualifierCollector Quals;
2833 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002834
John McCall8ccfcb52009-09-24 19:53:00 +00002835 // If this type already has an address space specified, it cannot get
2836 // another one.
2837 assert(!Quals.hasAddressSpace() &&
2838 "Type cannot be in multiple addr spaces!");
2839 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00002840
John McCall8ccfcb52009-09-24 19:53:00 +00002841 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00002842}
2843
Andrew Gozillon572bbb02017-10-02 06:25:51 +00002844QualType ASTContext::removeAddrSpaceQualType(QualType T) const {
2845 // If we are composing extended qualifiers together, merge together
2846 // into one ExtQuals node.
2847 QualifierCollector Quals;
2848 const Type *TypeNode = Quals.strip(T);
2849
2850 // If the qualifier doesn't have an address space just return it.
2851 if (!Quals.hasAddressSpace())
2852 return T;
2853
2854 Quals.removeAddressSpace();
2855
2856 // Removal of the address space can mean there are no longer any
2857 // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts)
2858 // or required.
2859 if (Quals.hasNonFastQualifiers())
2860 return getExtQualType(TypeNode, Quals);
2861 else
2862 return QualType(TypeNode, Quals.getFastQualifiers());
2863}
2864
Chris Lattnerd60183d2009-02-18 22:53:11 +00002865QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002866 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002867 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00002868 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002869 return T;
Mike Stump11289f42009-09-09 15:08:12 +00002870
Eugene Zelenko7855e772018-04-03 00:11:50 +00002871 if (const auto *ptr = T->getAs<PointerType>()) {
John McCall53fa7142010-12-24 02:08:15 +00002872 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00002873 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00002874 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2875 return getPointerType(ResultType);
2876 }
2877 }
Mike Stump11289f42009-09-09 15:08:12 +00002878
John McCall8ccfcb52009-09-24 19:53:00 +00002879 // If we are composing extended qualifiers together, merge together
2880 // into one ExtQuals node.
2881 QualifierCollector Quals;
2882 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002883
John McCall8ccfcb52009-09-24 19:53:00 +00002884 // If this type already has an ObjCGC specified, it cannot get
2885 // another one.
2886 assert(!Quals.hasObjCGCAttr() &&
2887 "Type cannot have multiple ObjCGCs!");
2888 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00002889
John McCall8ccfcb52009-09-24 19:53:00 +00002890 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002891}
Chris Lattner983a8bb2007-07-13 22:13:22 +00002892
Amy Huanga85f5ef2019-10-24 16:34:25 -07002893QualType ASTContext::removePtrSizeAddrSpace(QualType T) const {
2894 if (const PointerType *Ptr = T->getAs<PointerType>()) {
2895 QualType Pointee = Ptr->getPointeeType();
2896 if (isPtrSizeAddressSpace(Pointee.getAddressSpace())) {
2897 return getPointerType(removeAddrSpaceQualType(Pointee));
2898 }
2899 }
2900 return T;
2901}
2902
John McCall4f5019e2010-12-19 02:44:49 +00002903const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2904 FunctionType::ExtInfo Info) {
2905 if (T->getExtInfo() == Info)
2906 return T;
2907
2908 QualType Result;
Eugene Zelenko7855e772018-04-03 00:11:50 +00002909 if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
Alp Toker314cc812014-01-25 16:55:45 +00002910 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
John McCall4f5019e2010-12-19 02:44:49 +00002911 } else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002912 const auto *FPT = cast<FunctionProtoType>(T);
John McCall4f5019e2010-12-19 02:44:49 +00002913 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2914 EPI.ExtInfo = Info;
Alp Toker314cc812014-01-25 16:55:45 +00002915 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
John McCall4f5019e2010-12-19 02:44:49 +00002916 }
2917
2918 return cast<FunctionType>(Result.getTypePtr());
2919}
2920
Richard Smith2a7d4812013-05-04 07:00:32 +00002921void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2922 QualType ResultType) {
Richard Smith1fa5d642013-05-11 05:45:24 +00002923 FD = FD->getMostRecentDecl();
2924 while (true) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002925 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
Richard Smith2a7d4812013-05-04 07:00:32 +00002926 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Alp Toker9cacbab2014-01-20 20:26:09 +00002927 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
Richard Smith1fa5d642013-05-11 05:45:24 +00002928 if (FunctionDecl *Next = FD->getPreviousDecl())
2929 FD = Next;
2930 else
2931 break;
Richard Smith2a7d4812013-05-04 07:00:32 +00002932 }
Richard Smith1fa5d642013-05-11 05:45:24 +00002933 if (ASTMutationListener *L = getASTMutationListener())
2934 L->DeducedReturnType(FD, ResultType);
Richard Smith2a7d4812013-05-04 07:00:32 +00002935}
2936
Richard Smith0b3a4622014-11-13 20:01:57 +00002937/// Get a function type and produce the equivalent function type with the
2938/// specified exception specification. Type sugar that can be present on a
2939/// declaration of a function with an exception specification is permitted
2940/// and preserved. Other type sugar (for instance, typedefs) is not.
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002941QualType ASTContext::getFunctionTypeWithExceptionSpec(
2942 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) {
Richard Smith0b3a4622014-11-13 20:01:57 +00002943 // Might have some parens.
Eugene Zelenko7855e772018-04-03 00:11:50 +00002944 if (const auto *PT = dyn_cast<ParenType>(Orig))
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002945 return getParenType(
2946 getFunctionTypeWithExceptionSpec(PT->getInnerType(), ESI));
Richard Smith0b3a4622014-11-13 20:01:57 +00002947
Leonard Chandc5d9752019-05-10 18:05:15 +00002948 // Might be wrapped in a macro qualified type.
2949 if (const auto *MQT = dyn_cast<MacroQualifiedType>(Orig))
2950 return getMacroQualifiedType(
2951 getFunctionTypeWithExceptionSpec(MQT->getUnderlyingType(), ESI),
2952 MQT->getMacroIdentifier());
2953
Richard Smith0b3a4622014-11-13 20:01:57 +00002954 // Might have a calling-convention attribute.
Eugene Zelenko7855e772018-04-03 00:11:50 +00002955 if (const auto *AT = dyn_cast<AttributedType>(Orig))
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002956 return getAttributedType(
Richard Smith0b3a4622014-11-13 20:01:57 +00002957 AT->getAttrKind(),
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002958 getFunctionTypeWithExceptionSpec(AT->getModifiedType(), ESI),
2959 getFunctionTypeWithExceptionSpec(AT->getEquivalentType(), ESI));
Richard Smith0b3a4622014-11-13 20:01:57 +00002960
2961 // Anything else must be a function type. Rebuild it with the new exception
2962 // specification.
Simon Pilgrim9588ae72019-10-03 21:47:42 +00002963 const auto *Proto = Orig->castAs<FunctionProtoType>();
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002964 return getFunctionType(
Richard Smith0b3a4622014-11-13 20:01:57 +00002965 Proto->getReturnType(), Proto->getParamTypes(),
2966 Proto->getExtProtoInfo().withExceptionSpec(ESI));
2967}
2968
Richard Smithdfe85e22016-12-15 02:35:39 +00002969bool ASTContext::hasSameFunctionTypeIgnoringExceptionSpec(QualType T,
2970 QualType U) {
2971 return hasSameType(T, U) ||
Aaron Ballmanc351fba2017-12-04 20:27:34 +00002972 (getLangOpts().CPlusPlus17 &&
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002973 hasSameType(getFunctionTypeWithExceptionSpec(T, EST_None),
2974 getFunctionTypeWithExceptionSpec(U, EST_None)));
Richard Smithdfe85e22016-12-15 02:35:39 +00002975}
2976
Amy Huanga85f5ef2019-10-24 16:34:25 -07002977QualType ASTContext::getFunctionTypeWithoutPtrSizes(QualType T) {
2978 if (const auto *Proto = T->getAs<FunctionProtoType>()) {
2979 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
2980 SmallVector<QualType, 16> Args(Proto->param_types());
2981 for (unsigned i = 0, n = Args.size(); i != n; ++i)
2982 Args[i] = removePtrSizeAddrSpace(Args[i]);
2983 return getFunctionType(RetTy, Args, Proto->getExtProtoInfo());
2984 }
2985
2986 if (const FunctionNoProtoType *Proto = T->getAs<FunctionNoProtoType>()) {
2987 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
2988 return getFunctionNoProtoType(RetTy, Proto->getExtInfo());
2989 }
2990
2991 return T;
2992}
2993
2994bool ASTContext::hasSameFunctionTypeIgnoringPtrSizes(QualType T, QualType U) {
2995 return hasSameType(T, U) ||
2996 hasSameType(getFunctionTypeWithoutPtrSizes(T),
2997 getFunctionTypeWithoutPtrSizes(U));
2998}
2999
Richard Smith0b3a4622014-11-13 20:01:57 +00003000void ASTContext::adjustExceptionSpec(
3001 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
3002 bool AsWritten) {
3003 // Update the type.
3004 QualType Updated =
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00003005 getFunctionTypeWithExceptionSpec(FD->getType(), ESI);
Richard Smith0b3a4622014-11-13 20:01:57 +00003006 FD->setType(Updated);
3007
3008 if (!AsWritten)
3009 return;
3010
3011 // Update the type in the type source information too.
3012 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
3013 // If the type and the type-as-written differ, we may need to update
3014 // the type-as-written too.
3015 if (TSInfo->getType() != FD->getType())
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00003016 Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI);
Richard Smith0b3a4622014-11-13 20:01:57 +00003017
3018 // FIXME: When we get proper type location information for exceptions,
3019 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
3020 // up the TypeSourceInfo;
3021 assert(TypeLoc::getFullDataSizeForType(Updated) ==
3022 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
3023 "TypeLoc size mismatch from updating exception specification");
3024 TSInfo->overrideType(Updated);
3025 }
3026}
3027
Chris Lattnerc6395932007-06-22 20:56:16 +00003028/// getComplexType - Return the uniqued reference to the type for a complex
3029/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00003030QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00003031 // Unique pointers, to guarantee there is only one pointer of a particular
3032 // structure.
3033 llvm::FoldingSetNodeID ID;
3034 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00003035
Craig Topper36250ad2014-05-12 05:36:57 +00003036 void *InsertPos = nullptr;
Chris Lattnerc6395932007-06-22 20:56:16 +00003037 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
3038 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003039
Chris Lattnerc6395932007-06-22 20:56:16 +00003040 // If the pointee type isn't canonical, this won't be a canonical type either,
3041 // so fill in the canonical type field.
3042 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00003043 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00003044 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00003045
Chris Lattnerc6395932007-06-22 20:56:16 +00003046 // Get the new insert position for the node we care about.
3047 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003048 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00003049 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00003050 auto *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00003051 Types.push_back(New);
3052 ComplexTypes.InsertNode(New, InsertPos);
3053 return QualType(New, 0);
3054}
3055
Chris Lattner970e54e2006-11-12 00:37:36 +00003056/// getPointerType - Return the uniqued reference to the type for a pointer to
3057/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00003058QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00003059 // Unique pointers, to guarantee there is only one pointer of a particular
3060 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00003061 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00003062 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00003063
Craig Topper36250ad2014-05-12 05:36:57 +00003064 void *InsertPos = nullptr;
Chris Lattner67521df2007-01-27 01:29:36 +00003065 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003066 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003067
Chris Lattner7ccecb92006-11-12 08:50:50 +00003068 // If the pointee type isn't canonical, this won't be a canonical type either,
3069 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003070 QualType Canonical;
Bob Wilsonc8541f22013-03-15 17:12:43 +00003071 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00003072 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00003073
Bob Wilsonc8541f22013-03-15 17:12:43 +00003074 // Get the new insert position for the node we care about.
3075 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003076 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bob Wilsonc8541f22013-03-15 17:12:43 +00003077 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00003078 auto *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00003079 Types.push_back(New);
3080 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003081 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00003082}
3083
Reid Kleckner0503a872013-12-05 01:23:43 +00003084QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
3085 llvm::FoldingSetNodeID ID;
3086 AdjustedType::Profile(ID, Orig, New);
Craig Topper36250ad2014-05-12 05:36:57 +00003087 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00003088 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3089 if (AT)
3090 return QualType(AT, 0);
3091
3092 QualType Canonical = getCanonicalType(New);
3093
3094 // Get the new insert position for the node we care about.
3095 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003096 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner0503a872013-12-05 01:23:43 +00003097
3098 AT = new (*this, TypeAlignment)
3099 AdjustedType(Type::Adjusted, Orig, New, Canonical);
3100 Types.push_back(AT);
3101 AdjustedTypes.InsertNode(AT, InsertPos);
3102 return QualType(AT, 0);
3103}
3104
Reid Kleckner8a365022013-06-24 17:51:48 +00003105QualType ASTContext::getDecayedType(QualType T) const {
3106 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
3107
Reid Kleckner8a365022013-06-24 17:51:48 +00003108 QualType Decayed;
3109
3110 // C99 6.7.5.3p7:
3111 // A declaration of a parameter as "array of type" shall be
3112 // adjusted to "qualified pointer to type", where the type
3113 // qualifiers (if any) are those specified within the [ and ] of
3114 // the array type derivation.
3115 if (T->isArrayType())
3116 Decayed = getArrayDecayedType(T);
3117
3118 // C99 6.7.5.3p8:
3119 // A declaration of a parameter as "function returning type"
3120 // shall be adjusted to "pointer to function returning type", as
3121 // in 6.3.2.1.
3122 if (T->isFunctionType())
3123 Decayed = getPointerType(T);
3124
Reid Kleckner0503a872013-12-05 01:23:43 +00003125 llvm::FoldingSetNodeID ID;
3126 AdjustedType::Profile(ID, T, Decayed);
Craig Topper36250ad2014-05-12 05:36:57 +00003127 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00003128 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3129 if (AT)
3130 return QualType(AT, 0);
3131
Reid Kleckner8a365022013-06-24 17:51:48 +00003132 QualType Canonical = getCanonicalType(Decayed);
3133
3134 // Get the new insert position for the node we care about.
Reid Kleckner0503a872013-12-05 01:23:43 +00003135 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003136 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner8a365022013-06-24 17:51:48 +00003137
Reid Kleckner0503a872013-12-05 01:23:43 +00003138 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
3139 Types.push_back(AT);
3140 AdjustedTypes.InsertNode(AT, InsertPos);
3141 return QualType(AT, 0);
Reid Kleckner8a365022013-06-24 17:51:48 +00003142}
3143
Mike Stump11289f42009-09-09 15:08:12 +00003144/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00003145/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00003146QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00003147 assert(T->isFunctionType() && "block of function types only");
3148 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00003149 // structure.
3150 llvm::FoldingSetNodeID ID;
3151 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00003152
Craig Topper36250ad2014-05-12 05:36:57 +00003153 void *InsertPos = nullptr;
Steve Naroffec33ed92008-08-27 16:04:49 +00003154 if (BlockPointerType *PT =
3155 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3156 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003157
3158 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00003159 // type either so fill in the canonical type field.
3160 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00003161 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00003162 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00003163
Steve Naroffec33ed92008-08-27 16:04:49 +00003164 // Get the new insert position for the node we care about.
3165 BlockPointerType *NewIP =
3166 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003167 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00003168 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00003169 auto *New = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00003170 Types.push_back(New);
3171 BlockPointerTypes.InsertNode(New, InsertPos);
3172 return QualType(New, 0);
3173}
3174
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003175/// getLValueReferenceType - Return the uniqued reference to the type for an
3176/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00003177QualType
3178ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00003179 assert(getCanonicalType(T) != OverloadTy &&
Douglas Gregor291e8ee2011-05-21 22:16:50 +00003180 "Unresolved overloaded function type");
Fangrui Song6907ce22018-07-30 19:24:48 +00003181
Bill Wendling3708c182007-05-27 10:15:43 +00003182 // Unique pointers, to guarantee there is only one pointer of a particular
3183 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00003184 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00003185 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00003186
Craig Topper36250ad2014-05-12 05:36:57 +00003187 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003188 if (LValueReferenceType *RT =
3189 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00003190 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003191
Eugene Zelenko7855e772018-04-03 00:11:50 +00003192 const auto *InnerRef = T->getAs<ReferenceType>();
John McCallfc93cf92009-10-22 22:37:11 +00003193
Bill Wendling3708c182007-05-27 10:15:43 +00003194 // If the referencee type isn't canonical, this won't be a canonical type
3195 // either, so fill in the canonical type field.
3196 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00003197 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
3198 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
3199 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003200
Bill Wendling3708c182007-05-27 10:15:43 +00003201 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003202 LValueReferenceType *NewIP =
3203 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003204 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00003205 }
3206
Eugene Zelenko7855e772018-04-03 00:11:50 +00003207 auto *New = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
3208 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00003209 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003210 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00003211
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003212 return QualType(New, 0);
3213}
3214
3215/// getRValueReferenceType - Return the uniqued reference to the type for an
3216/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00003217QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003218 // Unique pointers, to guarantee there is only one pointer of a particular
3219 // structure.
3220 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00003221 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003222
Craig Topper36250ad2014-05-12 05:36:57 +00003223 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003224 if (RValueReferenceType *RT =
3225 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
3226 return QualType(RT, 0);
3227
Eugene Zelenko7855e772018-04-03 00:11:50 +00003228 const auto *InnerRef = T->getAs<ReferenceType>();
John McCallfc93cf92009-10-22 22:37:11 +00003229
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003230 // If the referencee type isn't canonical, this won't be a canonical type
3231 // either, so fill in the canonical type field.
3232 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00003233 if (InnerRef || !T.isCanonical()) {
3234 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
3235 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003236
3237 // Get the new insert position for the node we care about.
3238 RValueReferenceType *NewIP =
3239 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003240 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003241 }
3242
Eugene Zelenko7855e772018-04-03 00:11:50 +00003243 auto *New = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003244 Types.push_back(New);
3245 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00003246 return QualType(New, 0);
3247}
3248
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00003249/// getMemberPointerType - Return the uniqued reference to the type for a
3250/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00003251QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00003252 // Unique pointers, to guarantee there is only one pointer of a particular
3253 // structure.
3254 llvm::FoldingSetNodeID ID;
3255 MemberPointerType::Profile(ID, T, Cls);
3256
Craig Topper36250ad2014-05-12 05:36:57 +00003257 void *InsertPos = nullptr;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00003258 if (MemberPointerType *PT =
3259 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3260 return QualType(PT, 0);
3261
3262 // If the pointee or class type isn't canonical, this won't be a canonical
3263 // type either, so fill in the canonical type field.
3264 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00003265 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00003266 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
3267
3268 // Get the new insert position for the node we care about.
3269 MemberPointerType *NewIP =
3270 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003271 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00003272 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00003273 auto *New = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00003274 Types.push_back(New);
3275 MemberPointerTypes.InsertNode(New, InsertPos);
3276 return QualType(New, 0);
3277}
3278
Mike Stump11289f42009-09-09 15:08:12 +00003279/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00003280/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00003281QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00003282 const llvm::APInt &ArySizeIn,
Richard Smith772e2662019-10-04 01:25:59 +00003283 const Expr *SizeExpr,
Steve Naroff90dfdd52007-08-30 18:10:14 +00003284 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00003285 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00003286 assert((EltTy->isDependentType() ||
3287 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00003288 "Constant array of VLAs is illegal!");
3289
Richard Smith772e2662019-10-04 01:25:59 +00003290 // We only need the size as part of the type if it's instantiation-dependent.
3291 if (SizeExpr && !SizeExpr->isInstantiationDependent())
3292 SizeExpr = nullptr;
3293
Chris Lattnere2df3f92009-05-13 04:12:56 +00003294 // Convert the array size into a canonical width matching the pointer size for
3295 // the target.
3296 llvm::APInt ArySize(ArySizeIn);
Konstantin Zhuravlyov9c1e3102017-03-21 18:55:39 +00003297 ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth());
Mike Stump11289f42009-09-09 15:08:12 +00003298
Chris Lattner23b7eb62007-06-15 23:05:46 +00003299 llvm::FoldingSetNodeID ID;
Richard Smith772e2662019-10-04 01:25:59 +00003300 ConstantArrayType::Profile(ID, *this, EltTy, ArySize, SizeExpr, ASM,
3301 IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00003302
Craig Topper36250ad2014-05-12 05:36:57 +00003303 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003304 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00003305 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003306 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003307
Richard Smith772e2662019-10-04 01:25:59 +00003308 // If the element type isn't canonical or has qualifiers, or the array bound
3309 // is instantiation-dependent, this won't be a canonical type either, so fill
3310 // in the canonical type field.
John McCall33ddac02011-01-19 10:06:00 +00003311 QualType Canon;
Richard Smith772e2662019-10-04 01:25:59 +00003312 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers() || SizeExpr) {
John McCall33ddac02011-01-19 10:06:00 +00003313 SplitQualType canonSplit = getCanonicalType(EltTy).split();
Richard Smith772e2662019-10-04 01:25:59 +00003314 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize, nullptr,
Abramo Bagnara92141d22011-01-27 19:55:10 +00003315 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00003316 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00003317
Chris Lattner36f8e652007-01-27 08:31:04 +00003318 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00003319 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00003320 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003321 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00003322 }
Mike Stump11289f42009-09-09 15:08:12 +00003323
Richard Smith772e2662019-10-04 01:25:59 +00003324 void *Mem = Allocate(
3325 ConstantArrayType::totalSizeToAlloc<const Expr *>(SizeExpr ? 1 : 0),
3326 TypeAlignment);
3327 auto *New = new (Mem)
3328 ConstantArrayType(EltTy, Canon, ArySize, SizeExpr, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00003329 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00003330 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003331 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00003332}
3333
John McCall06549462011-01-18 08:40:38 +00003334/// getVariableArrayDecayedType - Turns the given type, which may be
3335/// variably-modified, into the corresponding type with all the known
3336/// sizes replaced with [*].
3337QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
3338 // Vastly most common case.
3339 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003340
John McCall06549462011-01-18 08:40:38 +00003341 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003342
John McCall06549462011-01-18 08:40:38 +00003343 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00003344 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00003345 switch (ty->getTypeClass()) {
3346#define TYPE(Class, Base)
3347#define ABSTRACT_TYPE(Class, Base)
3348#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
John McCall36b12a82019-10-02 06:35:23 +00003349#include "clang/AST/TypeNodes.inc"
John McCall06549462011-01-18 08:40:38 +00003350 llvm_unreachable("didn't desugar past all non-canonical types?");
3351
3352 // These types should never be variably-modified.
3353 case Type::Builtin:
3354 case Type::Complex:
3355 case Type::Vector:
Erich Keanef702b022018-07-13 19:46:04 +00003356 case Type::DependentVector:
John McCall06549462011-01-18 08:40:38 +00003357 case Type::ExtVector:
3358 case Type::DependentSizedExtVector:
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003359 case Type::DependentAddressSpace:
John McCall06549462011-01-18 08:40:38 +00003360 case Type::ObjCObject:
3361 case Type::ObjCInterface:
3362 case Type::ObjCObjectPointer:
3363 case Type::Record:
3364 case Type::Enum:
3365 case Type::UnresolvedUsing:
3366 case Type::TypeOfExpr:
3367 case Type::TypeOf:
3368 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00003369 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00003370 case Type::DependentName:
3371 case Type::InjectedClassName:
3372 case Type::TemplateSpecialization:
3373 case Type::DependentTemplateSpecialization:
3374 case Type::TemplateTypeParm:
3375 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00003376 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00003377 case Type::DeducedTemplateSpecialization:
John McCall06549462011-01-18 08:40:38 +00003378 case Type::PackExpansion:
3379 llvm_unreachable("type should never be variably-modified");
3380
3381 // These types can be variably-modified but should never need to
3382 // further decay.
3383 case Type::FunctionNoProto:
3384 case Type::FunctionProto:
3385 case Type::BlockPointer:
3386 case Type::MemberPointer:
Xiuli Pan9c14e282016-01-09 12:53:17 +00003387 case Type::Pipe:
John McCall06549462011-01-18 08:40:38 +00003388 return type;
3389
3390 // These types can be variably-modified. All these modifications
3391 // preserve structure except as noted by comments.
3392 // TODO: if we ever care about optimizing VLAs, there are no-op
3393 // optimizations available here.
3394 case Type::Pointer:
3395 result = getPointerType(getVariableArrayDecayedType(
3396 cast<PointerType>(ty)->getPointeeType()));
3397 break;
3398
3399 case Type::LValueReference: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003400 const auto *lv = cast<LValueReferenceType>(ty);
John McCall06549462011-01-18 08:40:38 +00003401 result = getLValueReferenceType(
3402 getVariableArrayDecayedType(lv->getPointeeType()),
3403 lv->isSpelledAsLValue());
3404 break;
3405 }
3406
3407 case Type::RValueReference: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003408 const auto *lv = cast<RValueReferenceType>(ty);
John McCall06549462011-01-18 08:40:38 +00003409 result = getRValueReferenceType(
3410 getVariableArrayDecayedType(lv->getPointeeType()));
3411 break;
3412 }
3413
Eli Friedman0dfb8892011-10-06 23:00:33 +00003414 case Type::Atomic: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003415 const auto *at = cast<AtomicType>(ty);
Eli Friedman0dfb8892011-10-06 23:00:33 +00003416 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
3417 break;
3418 }
3419
John McCall06549462011-01-18 08:40:38 +00003420 case Type::ConstantArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003421 const auto *cat = cast<ConstantArrayType>(ty);
John McCall06549462011-01-18 08:40:38 +00003422 result = getConstantArrayType(
3423 getVariableArrayDecayedType(cat->getElementType()),
3424 cat->getSize(),
Richard Smith772e2662019-10-04 01:25:59 +00003425 cat->getSizeExpr(),
John McCall06549462011-01-18 08:40:38 +00003426 cat->getSizeModifier(),
3427 cat->getIndexTypeCVRQualifiers());
3428 break;
3429 }
3430
3431 case Type::DependentSizedArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003432 const auto *dat = cast<DependentSizedArrayType>(ty);
John McCall06549462011-01-18 08:40:38 +00003433 result = getDependentSizedArrayType(
3434 getVariableArrayDecayedType(dat->getElementType()),
3435 dat->getSizeExpr(),
3436 dat->getSizeModifier(),
3437 dat->getIndexTypeCVRQualifiers(),
3438 dat->getBracketsRange());
3439 break;
3440 }
3441
3442 // Turn incomplete types into [*] types.
3443 case Type::IncompleteArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003444 const auto *iat = cast<IncompleteArrayType>(ty);
John McCall06549462011-01-18 08:40:38 +00003445 result = getVariableArrayType(
3446 getVariableArrayDecayedType(iat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00003447 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00003448 ArrayType::Normal,
3449 iat->getIndexTypeCVRQualifiers(),
3450 SourceRange());
3451 break;
3452 }
3453
3454 // Turn VLA types into [*] types.
3455 case Type::VariableArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003456 const auto *vat = cast<VariableArrayType>(ty);
John McCall06549462011-01-18 08:40:38 +00003457 result = getVariableArrayType(
3458 getVariableArrayDecayedType(vat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00003459 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00003460 ArrayType::Star,
3461 vat->getIndexTypeCVRQualifiers(),
3462 vat->getBracketsRange());
3463 break;
3464 }
3465 }
3466
3467 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00003468 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00003469}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003470
Steve Naroffcadebd02007-08-30 18:14:25 +00003471/// getVariableArrayType - Returns a non-unique reference to the type for a
3472/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00003473QualType ASTContext::getVariableArrayType(QualType EltTy,
3474 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00003475 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00003476 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00003477 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00003478 // Since we don't unique expressions, it isn't possible to unique VLA's
3479 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00003480 QualType Canon;
Fangrui Song6907ce22018-07-30 19:24:48 +00003481
John McCall33ddac02011-01-19 10:06:00 +00003482 // Be sure to pull qualifiers off the element type.
3483 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
3484 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00003485 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00003486 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00003487 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00003488 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003489
Eugene Zelenko7855e772018-04-03 00:11:50 +00003490 auto *New = new (*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00003491 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00003492
3493 VariableArrayTypes.push_back(New);
3494 Types.push_back(New);
3495 return QualType(New, 0);
3496}
3497
Douglas Gregor4619e432008-12-05 23:32:09 +00003498/// getDependentSizedArrayType - Returns a non-unique reference to
3499/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00003500/// type.
John McCall33ddac02011-01-19 10:06:00 +00003501QualType ASTContext::getDependentSizedArrayType(QualType elementType,
3502 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00003503 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00003504 unsigned elementTypeQuals,
3505 SourceRange brackets) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00003506 assert((!numElements || numElements->isTypeDependent() ||
John McCall33ddac02011-01-19 10:06:00 +00003507 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00003508 "Size must be type- or value-dependent!");
3509
John McCall33ddac02011-01-19 10:06:00 +00003510 // Dependently-sized array types that do not have a specified number
3511 // of elements will have their sizes deduced from a dependent
3512 // initializer. We do no canonicalization here at all, which is okay
3513 // because they can't be used in most locations.
3514 if (!numElements) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003515 auto *newType
John McCall33ddac02011-01-19 10:06:00 +00003516 = new (*this, TypeAlignment)
3517 DependentSizedArrayType(*this, elementType, QualType(),
3518 numElements, ASM, elementTypeQuals,
3519 brackets);
3520 Types.push_back(newType);
3521 return QualType(newType, 0);
3522 }
3523
3524 // Otherwise, we actually build a new type every time, but we
3525 // also build a canonical type.
3526
3527 SplitQualType canonElementType = getCanonicalType(elementType).split();
3528
Craig Topper36250ad2014-05-12 05:36:57 +00003529 void *insertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00003530 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00003531 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00003532 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00003533 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00003534
John McCall33ddac02011-01-19 10:06:00 +00003535 // Look for an existing type with these properties.
3536 DependentSizedArrayType *canonTy =
3537 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00003538
John McCall33ddac02011-01-19 10:06:00 +00003539 // If we don't have one, build one.
3540 if (!canonTy) {
3541 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00003542 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00003543 QualType(), numElements, ASM, elementTypeQuals,
3544 brackets);
3545 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
3546 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00003547 }
3548
John McCall33ddac02011-01-19 10:06:00 +00003549 // Apply qualifiers from the element type to the array.
3550 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00003551 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00003552
David Majnemer16a74702015-07-24 05:54:19 +00003553 // If we didn't need extra canonicalization for the element type or the size
3554 // expression, then just use that as our result.
3555 if (QualType(canonElementType.Ty, 0) == elementType &&
3556 canonTy->getSizeExpr() == numElements)
John McCall33ddac02011-01-19 10:06:00 +00003557 return canon;
3558
3559 // Otherwise, we need to build a type which follows the spelling
3560 // of the element type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00003561 auto *sugaredType
John McCall33ddac02011-01-19 10:06:00 +00003562 = new (*this, TypeAlignment)
3563 DependentSizedArrayType(*this, elementType, canon, numElements,
3564 ASM, elementTypeQuals, brackets);
3565 Types.push_back(sugaredType);
3566 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00003567}
3568
John McCall33ddac02011-01-19 10:06:00 +00003569QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00003570 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00003571 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00003572 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00003573 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00003574
Craig Topper36250ad2014-05-12 05:36:57 +00003575 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00003576 if (IncompleteArrayType *iat =
3577 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
3578 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00003579
3580 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00003581 // either, so fill in the canonical type field. We also have to pull
3582 // qualifiers off the element type.
3583 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00003584
John McCall33ddac02011-01-19 10:06:00 +00003585 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
3586 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00003587 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00003588 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00003589 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00003590
3591 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00003592 IncompleteArrayType *existing =
3593 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
3594 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00003595 }
Eli Friedmanbd258282008-02-15 18:16:39 +00003596
Eugene Zelenko7855e772018-04-03 00:11:50 +00003597 auto *newType = new (*this, TypeAlignment)
John McCall33ddac02011-01-19 10:06:00 +00003598 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00003599
John McCall33ddac02011-01-19 10:06:00 +00003600 IncompleteArrayTypes.InsertNode(newType, insertPos);
3601 Types.push_back(newType);
3602 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00003603}
3604
Sander de Smalen5087ace2020-03-15 14:29:45 +00003605/// getScalableVectorType - Return the unique reference to a scalable vector
3606/// type of the specified element type and size. VectorType must be a built-in
3607/// type.
3608QualType ASTContext::getScalableVectorType(QualType EltTy,
3609 unsigned NumElts) const {
3610 if (Target->hasAArch64SVETypes()) {
3611 uint64_t EltTySize = getTypeSize(EltTy);
3612#define SVE_VECTOR_TYPE(Name, Id, SingletonId, NumEls, ElBits, IsSigned, IsFP) \
3613 if (!EltTy->isBooleanType() && \
3614 ((EltTy->hasIntegerRepresentation() && \
3615 EltTy->hasSignedIntegerRepresentation() == IsSigned) || \
3616 (EltTy->hasFloatingRepresentation() && IsFP)) && \
3617 EltTySize == ElBits && NumElts == NumEls) \
3618 return SingletonId;
3619#define SVE_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
3620 if (EltTy->isBooleanType() && NumElts == NumEls) \
3621 return SingletonId;
3622#include "clang/Basic/AArch64SVEACLETypes.def"
3623 }
3624 return QualType();
3625}
3626
Steve Naroff91fcddb2007-07-18 18:00:27 +00003627/// getVectorType - Return the unique reference to a vector type of
3628/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00003629QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00003630 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00003631 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00003632
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003633 // Check if we've already instantiated a vector of this type.
3634 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00003635 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00003636
Craig Topper36250ad2014-05-12 05:36:57 +00003637 void *InsertPos = nullptr;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003638 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3639 return QualType(VTP, 0);
3640
3641 // If the element type isn't canonical, this won't be a canonical type either,
3642 // so fill in the canonical type field.
3643 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00003644 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00003645 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00003646
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003647 // Get the new insert position for the node we care about.
3648 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003649 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003650 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00003651 auto *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00003652 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003653 VectorTypes.InsertNode(New, InsertPos);
3654 Types.push_back(New);
3655 return QualType(New, 0);
3656}
3657
Erich Keanef702b022018-07-13 19:46:04 +00003658QualType
3659ASTContext::getDependentVectorType(QualType VecType, Expr *SizeExpr,
3660 SourceLocation AttrLoc,
3661 VectorType::VectorKind VecKind) const {
3662 llvm::FoldingSetNodeID ID;
3663 DependentVectorType::Profile(ID, *this, getCanonicalType(VecType), SizeExpr,
3664 VecKind);
3665 void *InsertPos = nullptr;
3666 DependentVectorType *Canon =
3667 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3668 DependentVectorType *New;
3669
3670 if (Canon) {
3671 New = new (*this, TypeAlignment) DependentVectorType(
3672 *this, VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind);
3673 } else {
3674 QualType CanonVecTy = getCanonicalType(VecType);
3675 if (CanonVecTy == VecType) {
3676 New = new (*this, TypeAlignment) DependentVectorType(
3677 *this, VecType, QualType(), SizeExpr, AttrLoc, VecKind);
3678
3679 DependentVectorType *CanonCheck =
3680 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3681 assert(!CanonCheck &&
3682 "Dependent-sized vector_size canonical type broken");
3683 (void)CanonCheck;
3684 DependentVectorTypes.InsertNode(New, InsertPos);
3685 } else {
Simon Pilgrim02594172020-01-13 14:41:16 +00003686 QualType CanonExtTy = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
3687 SourceLocation());
Erich Keanef702b022018-07-13 19:46:04 +00003688 New = new (*this, TypeAlignment) DependentVectorType(
Simon Pilgrim02594172020-01-13 14:41:16 +00003689 *this, VecType, CanonExtTy, SizeExpr, AttrLoc, VecKind);
Erich Keanef702b022018-07-13 19:46:04 +00003690 }
3691 }
3692
3693 Types.push_back(New);
3694 return QualType(New, 0);
3695}
3696
Nate Begemance4d7fc2008-04-18 23:10:10 +00003697/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00003698/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00003699QualType
3700ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00003701 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00003702
Steve Naroff91fcddb2007-07-18 18:00:27 +00003703 // Check if we've already instantiated a vector of this type.
3704 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00003705 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00003706 VectorType::GenericVector);
Craig Topper36250ad2014-05-12 05:36:57 +00003707 void *InsertPos = nullptr;
Steve Naroff91fcddb2007-07-18 18:00:27 +00003708 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3709 return QualType(VTP, 0);
3710
3711 // If the element type isn't canonical, this won't be a canonical type either,
3712 // so fill in the canonical type field.
3713 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00003714 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00003715 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00003716
Steve Naroff91fcddb2007-07-18 18:00:27 +00003717 // Get the new insert position for the node we care about.
3718 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003719 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00003720 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00003721 auto *New = new (*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00003722 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00003723 VectorTypes.InsertNode(New, InsertPos);
3724 Types.push_back(New);
3725 return QualType(New, 0);
3726}
3727
Jay Foad39c79802011-01-12 09:06:06 +00003728QualType
3729ASTContext::getDependentSizedExtVectorType(QualType vecType,
3730 Expr *SizeExpr,
3731 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00003732 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00003733 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00003734 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003735
Craig Topper36250ad2014-05-12 05:36:57 +00003736 void *InsertPos = nullptr;
Douglas Gregor352169a2009-07-31 03:54:25 +00003737 DependentSizedExtVectorType *Canon
3738 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3739 DependentSizedExtVectorType *New;
3740 if (Canon) {
3741 // We already have a canonical version of this array type; use it as
3742 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00003743 New = new (*this, TypeAlignment)
3744 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
3745 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00003746 } else {
3747 QualType CanonVecTy = getCanonicalType(vecType);
3748 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00003749 New = new (*this, TypeAlignment)
3750 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
3751 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003752
3753 DependentSizedExtVectorType *CanonCheck
3754 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3755 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
3756 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00003757 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
3758 } else {
Simon Pilgrim02594172020-01-13 14:41:16 +00003759 QualType CanonExtTy = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
3760 SourceLocation());
3761 New = new (*this, TypeAlignment) DependentSizedExtVectorType(
3762 *this, vecType, CanonExtTy, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00003763 }
3764 }
Mike Stump11289f42009-09-09 15:08:12 +00003765
Douglas Gregor758a8692009-06-17 21:51:59 +00003766 Types.push_back(New);
3767 return QualType(New, 0);
3768}
3769
Fangrui Song6907ce22018-07-30 19:24:48 +00003770QualType ASTContext::getDependentAddressSpaceType(QualType PointeeType,
3771 Expr *AddrSpaceExpr,
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003772 SourceLocation AttrLoc) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00003773 assert(AddrSpaceExpr->isInstantiationDependent());
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003774
3775 QualType canonPointeeType = getCanonicalType(PointeeType);
3776
3777 void *insertPos = nullptr;
3778 llvm::FoldingSetNodeID ID;
3779 DependentAddressSpaceType::Profile(ID, *this, canonPointeeType,
3780 AddrSpaceExpr);
3781
3782 DependentAddressSpaceType *canonTy =
3783 DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos);
3784
3785 if (!canonTy) {
3786 canonTy = new (*this, TypeAlignment)
Fangrui Song6907ce22018-07-30 19:24:48 +00003787 DependentAddressSpaceType(*this, canonPointeeType,
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003788 QualType(), AddrSpaceExpr, AttrLoc);
3789 DependentAddressSpaceTypes.InsertNode(canonTy, insertPos);
3790 Types.push_back(canonTy);
3791 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003792
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003793 if (canonPointeeType == PointeeType &&
3794 canonTy->getAddrSpaceExpr() == AddrSpaceExpr)
Fangrui Song6907ce22018-07-30 19:24:48 +00003795 return QualType(canonTy, 0);
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003796
Eugene Zelenko7855e772018-04-03 00:11:50 +00003797 auto *sugaredType
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003798 = new (*this, TypeAlignment)
Fangrui Song6907ce22018-07-30 19:24:48 +00003799 DependentAddressSpaceType(*this, PointeeType, QualType(canonTy, 0),
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003800 AddrSpaceExpr, AttrLoc);
3801 Types.push_back(sugaredType);
Fangrui Song6907ce22018-07-30 19:24:48 +00003802 return QualType(sugaredType, 0);
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003803}
3804
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003805/// Determine whether \p T is canonical as the result type of a function.
John McCall18afab72016-03-01 00:49:02 +00003806static bool isCanonicalResultType(QualType T) {
3807 return T.isCanonical() &&
3808 (T.getObjCLifetime() == Qualifiers::OCL_None ||
3809 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
3810}
3811
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003812/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Jay Foad39c79802011-01-12 09:06:06 +00003813QualType
3814ASTContext::getFunctionNoProtoType(QualType ResultTy,
3815 const FunctionType::ExtInfo &Info) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003816 // Unique functions, to guarantee there is only one function of a particular
3817 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00003818 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00003819 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00003820
Craig Topper36250ad2014-05-12 05:36:57 +00003821 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003822 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003823 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003824 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003825
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003826 QualType Canonical;
John McCall18afab72016-03-01 00:49:02 +00003827 if (!isCanonicalResultType(ResultTy)) {
3828 Canonical =
3829 getFunctionNoProtoType(getCanonicalFunctionResultType(ResultTy), Info);
Mike Stump11289f42009-09-09 15:08:12 +00003830
Chris Lattner47955de2007-01-27 08:37:20 +00003831 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003832 FunctionNoProtoType *NewIP =
3833 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003834 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00003835 }
Mike Stump11289f42009-09-09 15:08:12 +00003836
Eugene Zelenko7855e772018-04-03 00:11:50 +00003837 auto *New = new (*this, TypeAlignment)
John McCall18afab72016-03-01 00:49:02 +00003838 FunctionNoProtoType(ResultTy, Canonical, Info);
Chris Lattner47955de2007-01-27 08:37:20 +00003839 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003840 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003841 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003842}
3843
Douglas Gregora602a152015-10-01 20:20:47 +00003844CanQualType
3845ASTContext::getCanonicalFunctionResultType(QualType ResultType) const {
3846 CanQualType CanResultType = getCanonicalType(ResultType);
3847
3848 // Canonical result types do not have ARC lifetime qualifiers.
3849 if (CanResultType.getQualifiers().hasObjCLifetime()) {
3850 Qualifiers Qs = CanResultType.getQualifiers();
3851 Qs.removeObjCLifetime();
3852 return CanQualType::CreateUnsafe(
3853 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
3854 }
3855
3856 return CanResultType;
3857}
3858
Richard Smith3c4f8d22016-10-16 17:54:23 +00003859static bool isCanonicalExceptionSpecification(
3860 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
3861 if (ESI.Type == EST_None)
3862 return true;
3863 if (!NoexceptInType)
3864 return false;
3865
3866 // C++17 onwards: exception specification is part of the type, as a simple
3867 // boolean "can this function type throw".
3868 if (ESI.Type == EST_BasicNoexcept)
3869 return true;
3870
Richard Smitheaf11ad2018-05-03 03:58:32 +00003871 // A noexcept(expr) specification is (possibly) canonical if expr is
3872 // value-dependent.
3873 if (ESI.Type == EST_DependentNoexcept)
3874 return true;
3875
Richard Smith3c4f8d22016-10-16 17:54:23 +00003876 // A dynamic exception specification is canonical if it only contains pack
Richard Smith2a2cda52016-10-18 19:29:18 +00003877 // expansions (so we can't tell whether it's non-throwing) and all its
3878 // contained types are canonical.
Richard Smith3c4f8d22016-10-16 17:54:23 +00003879 if (ESI.Type == EST_Dynamic) {
Richard Smithfda59e52016-10-26 01:05:54 +00003880 bool AnyPackExpansions = false;
3881 for (QualType ET : ESI.Exceptions) {
3882 if (!ET.isCanonical())
Richard Smith3c4f8d22016-10-16 17:54:23 +00003883 return false;
Richard Smithfda59e52016-10-26 01:05:54 +00003884 if (ET->getAs<PackExpansionType>())
3885 AnyPackExpansions = true;
3886 }
3887 return AnyPackExpansions;
Richard Smith3c4f8d22016-10-16 17:54:23 +00003888 }
3889
Richard Smith3c4f8d22016-10-16 17:54:23 +00003890 return false;
3891}
3892
Richard Smith304b1242016-10-18 20:13:25 +00003893QualType ASTContext::getFunctionTypeInternal(
3894 QualType ResultTy, ArrayRef<QualType> ArgArray,
3895 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
Jordan Rose5c382722013-03-08 21:51:21 +00003896 size_t NumArgs = ArgArray.size();
3897
Richard Smith2a2cda52016-10-18 19:29:18 +00003898 // Unique functions, to guarantee there is only one function of a particular
3899 // structure.
3900 llvm::FoldingSetNodeID ID;
3901 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
3902 *this, true);
Richard Smith3c4f8d22016-10-16 17:54:23 +00003903
Richard Smith2a2cda52016-10-18 19:29:18 +00003904 QualType Canonical;
3905 bool Unique = false;
3906
3907 void *InsertPos = nullptr;
3908 if (FunctionProtoType *FPT =
3909 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
3910 QualType Existing = QualType(FPT, 0);
3911
3912 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
3913 // it so long as our exception specification doesn't contain a dependent
Richard Smith304b1242016-10-18 20:13:25 +00003914 // noexcept expression, or we're just looking for a canonical type.
3915 // Otherwise, we're going to need to create a type
Richard Smith2a2cda52016-10-18 19:29:18 +00003916 // sugar node to hold the concrete expression.
Richard Smitheaf11ad2018-05-03 03:58:32 +00003917 if (OnlyWantCanonical || !isComputedNoexcept(EPI.ExceptionSpec.Type) ||
Richard Smith2a2cda52016-10-18 19:29:18 +00003918 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
3919 return Existing;
3920
3921 // We need a new type sugar node for this one, to hold the new noexcept
3922 // expression. We do no canonicalization here, but that's OK since we don't
3923 // expect to see the same noexcept expression much more than once.
3924 Canonical = getCanonicalType(Existing);
3925 Unique = true;
3926 }
3927
Aaron Ballmanc351fba2017-12-04 20:27:34 +00003928 bool NoexceptInType = getLangOpts().CPlusPlus17;
Richard Smith3c4f8d22016-10-16 17:54:23 +00003929 bool IsCanonicalExceptionSpec =
3930 isCanonicalExceptionSpecification(EPI.ExceptionSpec, NoexceptInType);
3931
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003932 // Determine whether the type being created is already canonical or not.
Richard Smith2a2cda52016-10-18 19:29:18 +00003933 bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
Richard Smith3c4f8d22016-10-16 17:54:23 +00003934 isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003935 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003936 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003937 isCanonical = false;
3938
Richard Smith304b1242016-10-18 20:13:25 +00003939 if (OnlyWantCanonical)
3940 assert(isCanonical &&
3941 "given non-canonical parameters constructing canonical type");
3942
Richard Smith2a2cda52016-10-18 19:29:18 +00003943 // If this type isn't canonical, get the canonical version of it if we don't
3944 // already have it. The exception spec is only partially part of the
3945 // canonical type, and only in C++17 onwards.
3946 if (!isCanonical && Canonical.isNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003947 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003948 CanonicalArgs.reserve(NumArgs);
3949 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003950 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003951
Benjamin Kramer3f515cd2016-10-26 12:51:45 +00003952 llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
John McCalldb40c7f2010-12-14 08:05:40 +00003953 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00003954 CanonicalEPI.HasTrailingReturn = false;
Richard Smith3c4f8d22016-10-16 17:54:23 +00003955
3956 if (IsCanonicalExceptionSpec) {
3957 // Exception spec is already OK.
3958 } else if (NoexceptInType) {
3959 switch (EPI.ExceptionSpec.Type) {
3960 case EST_Unparsed: case EST_Unevaluated: case EST_Uninstantiated:
3961 // We don't know yet. It shouldn't matter what we pick here; no-one
3962 // should ever look at this.
3963 LLVM_FALLTHROUGH;
Richard Smitheaf11ad2018-05-03 03:58:32 +00003964 case EST_None: case EST_MSAny: case EST_NoexceptFalse:
Richard Smith3c4f8d22016-10-16 17:54:23 +00003965 CanonicalEPI.ExceptionSpec.Type = EST_None;
3966 break;
3967
Richard Smith2a2cda52016-10-18 19:29:18 +00003968 // A dynamic exception specification is almost always "not noexcept",
3969 // with the exception that a pack expansion might expand to no types.
3970 case EST_Dynamic: {
3971 bool AnyPacks = false;
3972 for (QualType ET : EPI.ExceptionSpec.Exceptions) {
3973 if (ET->getAs<PackExpansionType>())
3974 AnyPacks = true;
3975 ExceptionTypeStorage.push_back(getCanonicalType(ET));
3976 }
3977 if (!AnyPacks)
3978 CanonicalEPI.ExceptionSpec.Type = EST_None;
3979 else {
3980 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
3981 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
3982 }
3983 break;
3984 }
3985
Erich Keaned02f4a12019-05-30 17:31:54 +00003986 case EST_DynamicNone:
3987 case EST_BasicNoexcept:
3988 case EST_NoexceptTrue:
3989 case EST_NoThrow:
Richard Smith3c4f8d22016-10-16 17:54:23 +00003990 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
3991 break;
3992
Richard Smitheaf11ad2018-05-03 03:58:32 +00003993 case EST_DependentNoexcept:
3994 llvm_unreachable("dependent noexcept is already canonical");
Richard Smith3c4f8d22016-10-16 17:54:23 +00003995 }
Richard Smith3c4f8d22016-10-16 17:54:23 +00003996 } else {
3997 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
3998 }
John McCalldb40c7f2010-12-14 08:05:40 +00003999
Douglas Gregora602a152015-10-01 20:20:47 +00004000 // Adjust the canonical function result type.
4001 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
Richard Smith304b1242016-10-18 20:13:25 +00004002 Canonical =
4003 getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00004004
Chris Lattnerfd4de792007-01-27 01:15:32 +00004005 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004006 FunctionProtoType *NewIP =
4007 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00004008 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00004009 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00004010
Bruno Ricci26a25362018-10-02 11:46:38 +00004011 // Compute the needed size to hold this FunctionProtoType and the
4012 // various trailing objects.
4013 auto ESH = FunctionProtoType::getExceptionSpecSize(
4014 EPI.ExceptionSpec.Type, EPI.ExceptionSpec.Exceptions.size());
4015 size_t Size = FunctionProtoType::totalSizeToAlloc<
Nicolas Manichoncc3c9352019-12-03 08:21:55 -05004016 QualType, SourceLocation, FunctionType::FunctionTypeExtraBitfields,
Bruno Ricci26a25362018-10-02 11:46:38 +00004017 FunctionType::ExceptionType, Expr *, FunctionDecl *,
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00004018 FunctionProtoType::ExtParameterInfo, Qualifiers>(
Nicolas Manichoncc3c9352019-12-03 08:21:55 -05004019 NumArgs, EPI.Variadic,
4020 FunctionProtoType::hasExtraBitfields(EPI.ExceptionSpec.Type),
Bruno Ricci26a25362018-10-02 11:46:38 +00004021 ESH.NumExceptionType, ESH.NumExprPtr, ESH.NumFunctionDeclPtr,
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00004022 EPI.ExtParameterInfos ? NumArgs : 0,
4023 EPI.TypeQuals.hasNonFastQualifiers() ? 1 : 0);
John McCall18afab72016-03-01 00:49:02 +00004024
Bruno Ricci26a25362018-10-02 11:46:38 +00004025 auto *FTP = (FunctionProtoType *)Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00004026 FunctionProtoType::ExtProtoInfo newEPI = EPI;
Jordan Rose5c382722013-03-08 21:51:21 +00004027 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00004028 Types.push_back(FTP);
Richard Smith2a2cda52016-10-18 19:29:18 +00004029 if (!Unique)
4030 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00004031 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00004032}
Chris Lattneref51c202006-11-10 07:17:23 +00004033
Joey Goulye3c85de2016-12-01 11:30:49 +00004034QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
Xiuli Pan9c14e282016-01-09 12:53:17 +00004035 llvm::FoldingSetNodeID ID;
Joey Goulye3c85de2016-12-01 11:30:49 +00004036 PipeType::Profile(ID, T, ReadOnly);
Xiuli Pan9c14e282016-01-09 12:53:17 +00004037
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004038 void *InsertPos = nullptr;
Joey Goulye3c85de2016-12-01 11:30:49 +00004039 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
Xiuli Pan9c14e282016-01-09 12:53:17 +00004040 return QualType(PT, 0);
4041
4042 // If the pipe element type isn't canonical, this won't be a canonical type
4043 // either, so fill in the canonical type field.
4044 QualType Canonical;
4045 if (!T.isCanonical()) {
Joey Goulye3c85de2016-12-01 11:30:49 +00004046 Canonical = getPipeType(getCanonicalType(T), ReadOnly);
Xiuli Pan9c14e282016-01-09 12:53:17 +00004047
4048 // Get the new insert position for the node we care about.
Joey Goulye3c85de2016-12-01 11:30:49 +00004049 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
Xiuli Pan9c14e282016-01-09 12:53:17 +00004050 assert(!NewIP && "Shouldn't be in the map!");
4051 (void)NewIP;
4052 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00004053 auto *New = new (*this, TypeAlignment) PipeType(T, Canonical, ReadOnly);
Xiuli Pan9c14e282016-01-09 12:53:17 +00004054 Types.push_back(New);
Joey Goulye3c85de2016-12-01 11:30:49 +00004055 PipeTypes.InsertNode(New, InsertPos);
Joey Gouly5788b782016-11-18 14:10:54 +00004056 return QualType(New, 0);
4057}
4058
Anastasia Stulova59055b92018-05-09 13:23:26 +00004059QualType ASTContext::adjustStringLiteralBaseType(QualType Ty) const {
4060 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
4061 return LangOpts.OpenCL ? getAddrSpaceQualType(Ty, LangAS::opencl_constant)
4062 : Ty;
4063}
4064
Joey Goulye3c85de2016-12-01 11:30:49 +00004065QualType ASTContext::getReadPipeType(QualType T) const {
4066 return getPipeType(T, true);
4067}
4068
Joey Gouly5788b782016-11-18 14:10:54 +00004069QualType ASTContext::getWritePipeType(QualType T) const {
Joey Goulye3c85de2016-12-01 11:30:49 +00004070 return getPipeType(T, false);
Xiuli Pan9c14e282016-01-09 12:53:17 +00004071}
4072
John McCalle78aac42010-03-10 03:28:59 +00004073#ifndef NDEBUG
4074static bool NeedsInjectedClassNameType(const RecordDecl *D) {
4075 if (!isa<CXXRecordDecl>(D)) return false;
Eugene Zelenko7855e772018-04-03 00:11:50 +00004076 const auto *RD = cast<CXXRecordDecl>(D);
John McCalle78aac42010-03-10 03:28:59 +00004077 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
4078 return true;
4079 if (RD->getDescribedClassTemplate() &&
4080 !isa<ClassTemplateSpecializationDecl>(RD))
4081 return true;
4082 return false;
4083}
4084#endif
4085
4086/// getInjectedClassNameType - Return the unique reference to the
4087/// injected class name type for the specified templated declaration.
4088QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00004089 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00004090 assert(NeedsInjectedClassNameType(Decl));
4091 if (Decl->TypeForDecl) {
4092 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00004093 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00004094 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
4095 Decl->TypeForDecl = PrevDecl->TypeForDecl;
4096 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
4097 } else {
John McCall424cec92011-01-19 06:33:43 +00004098 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00004099 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00004100 Decl->TypeForDecl = newType;
4101 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00004102 }
4103 return QualType(Decl->TypeForDecl, 0);
4104}
4105
Douglas Gregor83a586e2008-04-13 21:07:44 +00004106/// getTypeDeclType - Return the unique reference to the type for the
4107/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00004108QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00004109 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00004110 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00004111
Eugene Zelenko7855e772018-04-03 00:11:50 +00004112 if (const auto *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00004113 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00004114
John McCall96f0b5f2010-03-10 06:48:02 +00004115 assert(!isa<TemplateTypeParmDecl>(Decl) &&
4116 "Template type parameter types are always available.");
4117
Eugene Zelenko7855e772018-04-03 00:11:50 +00004118 if (const auto *Record = dyn_cast<RecordDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00004119 assert(Record->isFirstDecl() && "struct/union has previous declaration");
John McCall96f0b5f2010-03-10 06:48:02 +00004120 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00004121 return getRecordType(Record);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004122 } else if (const auto *Enum = dyn_cast<EnumDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00004123 assert(Enum->isFirstDecl() && "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00004124 return getEnumType(Enum);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004125 } else if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00004126 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
4127 Decl->TypeForDecl = newType;
4128 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00004129 } else
John McCall96f0b5f2010-03-10 06:48:02 +00004130 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00004131
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00004132 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00004133}
4134
Chris Lattner32d920b2007-01-26 02:01:53 +00004135/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00004136/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004137QualType
Richard Smithdda56e42011-04-15 14:24:37 +00004138ASTContext::getTypedefType(const TypedefNameDecl *Decl,
4139 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00004140 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004141
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004142 if (Canonical.isNull())
4143 Canonical = getCanonicalType(Decl->getUnderlyingType());
Eugene Zelenko7855e772018-04-03 00:11:50 +00004144 auto *newType = new (*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00004145 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00004146 Decl->TypeForDecl = newType;
4147 Types.push_back(newType);
4148 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00004149}
4150
Jay Foad39c79802011-01-12 09:06:06 +00004151QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00004152 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
4153
Douglas Gregorec9fd132012-01-14 16:38:05 +00004154 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00004155 if (PrevDecl->TypeForDecl)
Fangrui Song6907ce22018-07-30 19:24:48 +00004156 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00004157
Eugene Zelenko7855e772018-04-03 00:11:50 +00004158 auto *newType = new (*this, TypeAlignment) RecordType(Decl);
John McCall424cec92011-01-19 06:33:43 +00004159 Decl->TypeForDecl = newType;
4160 Types.push_back(newType);
4161 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00004162}
4163
Jay Foad39c79802011-01-12 09:06:06 +00004164QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00004165 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
4166
Douglas Gregorec9fd132012-01-14 16:38:05 +00004167 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00004168 if (PrevDecl->TypeForDecl)
Fangrui Song6907ce22018-07-30 19:24:48 +00004169 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00004170
Eugene Zelenko7855e772018-04-03 00:11:50 +00004171 auto *newType = new (*this, TypeAlignment) EnumType(Decl);
John McCall424cec92011-01-19 06:33:43 +00004172 Decl->TypeForDecl = newType;
4173 Types.push_back(newType);
4174 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00004175}
4176
Richard Smithe43e2b32018-08-20 21:47:29 +00004177QualType ASTContext::getAttributedType(attr::Kind attrKind,
John McCall81904512011-01-06 01:58:22 +00004178 QualType modifiedType,
4179 QualType equivalentType) {
4180 llvm::FoldingSetNodeID id;
4181 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
4182
Craig Topper36250ad2014-05-12 05:36:57 +00004183 void *insertPos = nullptr;
John McCall81904512011-01-06 01:58:22 +00004184 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
4185 if (type) return QualType(type, 0);
4186
4187 QualType canon = getCanonicalType(equivalentType);
4188 type = new (*this, TypeAlignment)
Leonard Chanc72aaf62019-05-07 03:20:17 +00004189 AttributedType(canon, attrKind, modifiedType, equivalentType);
John McCall81904512011-01-06 01:58:22 +00004190
4191 Types.push_back(type);
4192 AttributedTypes.InsertNode(type, insertPos);
4193
4194 return QualType(type, 0);
4195}
4196
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004197/// Retrieve a substitution-result type.
John McCallcebee162009-10-18 09:09:24 +00004198QualType
4199ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00004200 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00004201 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00004202 && "replacement types must always be canonical");
4203
4204 llvm::FoldingSetNodeID ID;
4205 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00004206 void *InsertPos = nullptr;
John McCallcebee162009-10-18 09:09:24 +00004207 SubstTemplateTypeParmType *SubstParm
4208 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4209
4210 if (!SubstParm) {
4211 SubstParm = new (*this, TypeAlignment)
4212 SubstTemplateTypeParmType(Parm, Replacement);
4213 Types.push_back(SubstParm);
4214 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
4215 }
4216
4217 return QualType(SubstParm, 0);
4218}
4219
Fangrui Song6907ce22018-07-30 19:24:48 +00004220/// Retrieve a
Douglas Gregorada4b792011-01-14 02:55:32 +00004221QualType ASTContext::getSubstTemplateTypeParmPackType(
4222 const TemplateTypeParmType *Parm,
4223 const TemplateArgument &ArgPack) {
4224#ifndef NDEBUG
Aaron Ballman2a89e852014-07-15 21:32:31 +00004225 for (const auto &P : ArgPack.pack_elements()) {
4226 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
4227 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
Douglas Gregorada4b792011-01-14 02:55:32 +00004228 }
4229#endif
Fangrui Song6907ce22018-07-30 19:24:48 +00004230
Douglas Gregorada4b792011-01-14 02:55:32 +00004231 llvm::FoldingSetNodeID ID;
4232 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00004233 void *InsertPos = nullptr;
Douglas Gregorada4b792011-01-14 02:55:32 +00004234 if (SubstTemplateTypeParmPackType *SubstParm
4235 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
4236 return QualType(SubstParm, 0);
Fangrui Song6907ce22018-07-30 19:24:48 +00004237
Douglas Gregorada4b792011-01-14 02:55:32 +00004238 QualType Canon;
4239 if (!Parm->isCanonicalUnqualified()) {
4240 Canon = getCanonicalType(QualType(Parm, 0));
4241 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
4242 ArgPack);
4243 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
4244 }
4245
Eugene Zelenko7855e772018-04-03 00:11:50 +00004246 auto *SubstParm
Douglas Gregorada4b792011-01-14 02:55:32 +00004247 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
4248 ArgPack);
4249 Types.push_back(SubstParm);
George Burgess IVb5fe8552017-06-12 17:44:30 +00004250 SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos);
Fangrui Song6907ce22018-07-30 19:24:48 +00004251 return QualType(SubstParm, 0);
Douglas Gregorada4b792011-01-14 02:55:32 +00004252}
4253
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004254/// Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00004255/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00004256/// name.
Mike Stump11289f42009-09-09 15:08:12 +00004257QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00004258 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00004259 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00004260 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00004261 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Craig Topper36250ad2014-05-12 05:36:57 +00004262 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004263 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00004264 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4265
4266 if (TypeParm)
4267 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004268
Chandler Carruth08836322011-05-01 00:51:33 +00004269 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00004270 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00004271 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004272
Fangrui Song6907ce22018-07-30 19:24:48 +00004273 TemplateTypeParmType *TypeCheck
Douglas Gregorc42075a2010-02-04 18:10:26 +00004274 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4275 assert(!TypeCheck && "Template type parameter canonical type broken");
4276 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00004277 } else
John McCall90d1c2d2009-09-24 23:30:46 +00004278 TypeParm = new (*this, TypeAlignment)
4279 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00004280
4281 Types.push_back(TypeParm);
4282 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
4283
4284 return QualType(TypeParm, 0);
4285}
4286
John McCalle78aac42010-03-10 03:28:59 +00004287TypeSourceInfo *
4288ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
4289 SourceLocation NameLoc,
4290 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00004291 QualType Underlying) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00004292 assert(!Name.getAsDependentTemplateName() &&
Douglas Gregore16af532011-02-28 18:50:33 +00004293 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00004294 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00004295
4296 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie6adc78e2013-02-18 22:06:02 +00004297 TemplateSpecializationTypeLoc TL =
4298 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara48c05be2012-02-06 14:41:24 +00004299 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00004300 TL.setTemplateNameLoc(NameLoc);
4301 TL.setLAngleLoc(Args.getLAngleLoc());
4302 TL.setRAngleLoc(Args.getRAngleLoc());
4303 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
4304 TL.setArgLocInfo(i, Args[i].getLocInfo());
4305 return DI;
4306}
4307
Mike Stump11289f42009-09-09 15:08:12 +00004308QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00004309ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00004310 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00004311 QualType Underlying) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00004312 assert(!Template.getAsDependentTemplateName() &&
Douglas Gregore16af532011-02-28 18:50:33 +00004313 "No dependent template names here!");
John McCall6b51f282009-11-23 01:53:49 +00004314
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004315 SmallVector<TemplateArgument, 4> ArgVec;
David Majnemer6fbeee32016-07-07 04:43:07 +00004316 ArgVec.reserve(Args.size());
4317 for (const TemplateArgumentLoc &Arg : Args.arguments())
4318 ArgVec.push_back(Arg.getArgument());
John McCall0ad16662009-10-29 08:12:44 +00004319
David Majnemer6fbeee32016-07-07 04:43:07 +00004320 return getTemplateSpecializationType(Template, ArgVec, Underlying);
John McCall0ad16662009-10-29 08:12:44 +00004321}
4322
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004323#ifndef NDEBUG
David Majnemer6fbeee32016-07-07 04:43:07 +00004324static bool hasAnyPackExpansions(ArrayRef<TemplateArgument> Args) {
4325 for (const TemplateArgument &Arg : Args)
4326 if (Arg.isPackExpansion())
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004327 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00004328
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004329 return true;
4330}
4331#endif
4332
John McCall0ad16662009-10-29 08:12:44 +00004333QualType
4334ASTContext::getTemplateSpecializationType(TemplateName Template,
David Majnemer6fbeee32016-07-07 04:43:07 +00004335 ArrayRef<TemplateArgument> Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00004336 QualType Underlying) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00004337 assert(!Template.getAsDependentTemplateName() &&
Douglas Gregore16af532011-02-28 18:50:33 +00004338 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00004339 // Look through qualified template names.
4340 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
4341 Template = TemplateName(QTN->getTemplateDecl());
Fangrui Song6907ce22018-07-30 19:24:48 +00004342
4343 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00004344 Template.getAsTemplateDecl() &&
4345 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00004346 QualType CanonType;
4347 if (!Underlying.isNull())
4348 CanonType = getCanonicalType(Underlying);
4349 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004350 // We can get here with an alias template when the specialization contains
4351 // a pack expansion that does not match up with a parameter pack.
David Majnemer6fbeee32016-07-07 04:43:07 +00004352 assert((!IsTypeAlias || hasAnyPackExpansions(Args)) &&
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004353 "Caller must compute aliased type");
4354 IsTypeAlias = false;
David Majnemer6fbeee32016-07-07 04:43:07 +00004355 CanonType = getCanonicalTemplateSpecializationType(Template, Args);
Richard Smith3f1b5d02011-05-05 21:57:07 +00004356 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00004357
Douglas Gregora8e02e72009-07-28 23:00:59 +00004358 // Allocate the (non-canonical) template specialization type, but don't
4359 // try to unique it: these types typically have location information that
4360 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00004361 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
David Majnemer6fbeee32016-07-07 04:43:07 +00004362 sizeof(TemplateArgument) * Args.size() +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004363 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00004364 TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004365 auto *Spec
David Majnemer6fbeee32016-07-07 04:43:07 +00004366 = new (Mem) TemplateSpecializationType(Template, Args, CanonType,
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004367 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00004368
Douglas Gregor8bf42052009-02-09 18:46:07 +00004369 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00004370 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00004371}
4372
David Majnemer6fbeee32016-07-07 04:43:07 +00004373QualType ASTContext::getCanonicalTemplateSpecializationType(
4374 TemplateName Template, ArrayRef<TemplateArgument> Args) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00004375 assert(!Template.getAsDependentTemplateName() &&
Douglas Gregore16af532011-02-28 18:50:33 +00004376 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00004377
Douglas Gregore29139c2011-03-03 17:04:51 +00004378 // Look through qualified template names.
4379 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
4380 Template = TemplateName(QTN->getTemplateDecl());
Fangrui Song6907ce22018-07-30 19:24:48 +00004381
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004382 // Build the canonical template specialization type.
4383 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004384 SmallVector<TemplateArgument, 4> CanonArgs;
David Majnemer6fbeee32016-07-07 04:43:07 +00004385 unsigned NumArgs = Args.size();
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004386 CanonArgs.reserve(NumArgs);
David Majnemer6fbeee32016-07-07 04:43:07 +00004387 for (const TemplateArgument &Arg : Args)
4388 CanonArgs.push_back(getCanonicalTemplateArgument(Arg));
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004389
4390 // Determine whether this canonical template specialization type already
4391 // exists.
4392 llvm::FoldingSetNodeID ID;
4393 TemplateSpecializationType::Profile(ID, CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00004394 CanonArgs, *this);
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004395
Craig Topper36250ad2014-05-12 05:36:57 +00004396 void *InsertPos = nullptr;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004397 TemplateSpecializationType *Spec
4398 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
4399
4400 if (!Spec) {
4401 // Allocate a new canonical template specialization type.
4402 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
4403 sizeof(TemplateArgument) * NumArgs),
4404 TypeAlignment);
4405 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00004406 CanonArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00004407 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004408 Types.push_back(Spec);
4409 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
4410 }
4411
4412 assert(Spec->isDependentType() &&
4413 "Non-dependent template-id type must have a canonical type");
4414 return QualType(Spec, 0);
4415}
4416
Joel E. Denny7509a2f2018-05-14 19:36:45 +00004417QualType ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
4418 NestedNameSpecifier *NNS,
4419 QualType NamedType,
4420 TagDecl *OwnedTagDecl) const {
Douglas Gregor52537682009-03-19 00:18:19 +00004421 llvm::FoldingSetNodeID ID;
Joel E. Denny7509a2f2018-05-14 19:36:45 +00004422 ElaboratedType::Profile(ID, Keyword, NNS, NamedType, OwnedTagDecl);
Douglas Gregor52537682009-03-19 00:18:19 +00004423
Craig Topper36250ad2014-05-12 05:36:57 +00004424 void *InsertPos = nullptr;
Abramo Bagnara6150c882010-05-11 21:36:43 +00004425 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00004426 if (T)
4427 return QualType(T, 0);
4428
Douglas Gregorc42075a2010-02-04 18:10:26 +00004429 QualType Canon = NamedType;
4430 if (!Canon.isCanonical()) {
4431 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00004432 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
4433 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00004434 (void)CheckT;
4435 }
4436
Bruno Riccid6bd5982018-08-16 10:48:16 +00004437 void *Mem = Allocate(ElaboratedType::totalSizeToAlloc<TagDecl *>(!!OwnedTagDecl),
4438 TypeAlignment);
4439 T = new (Mem) ElaboratedType(Keyword, NNS, NamedType, Canon, OwnedTagDecl);
4440
Douglas Gregor52537682009-03-19 00:18:19 +00004441 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00004442 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00004443 return QualType(T, 0);
4444}
4445
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004446QualType
Jay Foad39c79802011-01-12 09:06:06 +00004447ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004448 llvm::FoldingSetNodeID ID;
4449 ParenType::Profile(ID, InnerType);
4450
Craig Topper36250ad2014-05-12 05:36:57 +00004451 void *InsertPos = nullptr;
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004452 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
4453 if (T)
4454 return QualType(T, 0);
4455
4456 QualType Canon = InnerType;
4457 if (!Canon.isCanonical()) {
4458 Canon = getCanonicalType(InnerType);
4459 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
4460 assert(!CheckT && "Paren canonical type broken");
4461 (void)CheckT;
4462 }
4463
Benjamin Kramer8adeef92015-04-02 16:19:54 +00004464 T = new (*this, TypeAlignment) ParenType(InnerType, Canon);
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004465 Types.push_back(T);
4466 ParenTypes.InsertNode(T, InsertPos);
4467 return QualType(T, 0);
4468}
4469
Leonard Chanc72aaf62019-05-07 03:20:17 +00004470QualType
4471ASTContext::getMacroQualifiedType(QualType UnderlyingTy,
4472 const IdentifierInfo *MacroII) const {
4473 QualType Canon = UnderlyingTy;
4474 if (!Canon.isCanonical())
4475 Canon = getCanonicalType(UnderlyingTy);
4476
4477 auto *newType = new (*this, TypeAlignment)
4478 MacroQualifiedType(UnderlyingTy, Canon, MacroII);
4479 Types.push_back(newType);
4480 return QualType(newType, 0);
4481}
4482
Douglas Gregor02085352010-03-31 20:19:30 +00004483QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
4484 NestedNameSpecifier *NNS,
4485 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00004486 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00004487 if (Canon.isNull()) {
4488 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Richard Smith74f02342017-01-19 21:00:13 +00004489 if (CanonNNS != NNS)
4490 Canon = getDependentNameType(Keyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00004491 }
4492
4493 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00004494 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00004495
Craig Topper36250ad2014-05-12 05:36:57 +00004496 void *InsertPos = nullptr;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00004497 DependentNameType *T
4498 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00004499 if (T)
4500 return QualType(T, 0);
4501
Benjamin Kramer8adeef92015-04-02 16:19:54 +00004502 T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00004503 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00004504 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00004505 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00004506}
4507
Mike Stump11289f42009-09-09 15:08:12 +00004508QualType
John McCallc392f372010-06-11 00:33:02 +00004509ASTContext::getDependentTemplateSpecializationType(
4510 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00004511 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00004512 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00004513 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00004514 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004515 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00004516 for (unsigned I = 0, E = Args.size(); I != E; ++I)
4517 ArgCopy.push_back(Args[I].getArgument());
David Majnemer6fbeee32016-07-07 04:43:07 +00004518 return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy);
John McCallc392f372010-06-11 00:33:02 +00004519}
4520
4521QualType
4522ASTContext::getDependentTemplateSpecializationType(
4523 ElaboratedTypeKeyword Keyword,
4524 NestedNameSpecifier *NNS,
4525 const IdentifierInfo *Name,
David Majnemer6fbeee32016-07-07 04:43:07 +00004526 ArrayRef<TemplateArgument> Args) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00004527 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor6e068012011-02-28 00:04:36 +00004528 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00004529
Douglas Gregorc42075a2010-02-04 18:10:26 +00004530 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00004531 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00004532 Name, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004533
Craig Topper36250ad2014-05-12 05:36:57 +00004534 void *InsertPos = nullptr;
John McCallc392f372010-06-11 00:33:02 +00004535 DependentTemplateSpecializationType *T
4536 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004537 if (T)
4538 return QualType(T, 0);
4539
John McCallc392f372010-06-11 00:33:02 +00004540 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004541
John McCallc392f372010-06-11 00:33:02 +00004542 ElaboratedTypeKeyword CanonKeyword = Keyword;
4543 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
4544
4545 bool AnyNonCanonArgs = false;
David Majnemer6fbeee32016-07-07 04:43:07 +00004546 unsigned NumArgs = Args.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004547 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00004548 for (unsigned I = 0; I != NumArgs; ++I) {
4549 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
4550 if (!CanonArgs[I].structurallyEquals(Args[I]))
4551 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00004552 }
4553
John McCallc392f372010-06-11 00:33:02 +00004554 QualType Canon;
4555 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
4556 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00004557 Name,
4558 CanonArgs);
John McCallc392f372010-06-11 00:33:02 +00004559
4560 // Find the insert position again.
4561 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
4562 }
4563
4564 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
4565 sizeof(TemplateArgument) * NumArgs),
4566 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00004567 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00004568 Name, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00004569 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00004570 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00004571 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00004572}
4573
Richard Smith32918772017-02-14 00:25:28 +00004574TemplateArgument ASTContext::getInjectedTemplateArg(NamedDecl *Param) {
4575 TemplateArgument Arg;
Eugene Zelenko7855e772018-04-03 00:11:50 +00004576 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
Richard Smith32918772017-02-14 00:25:28 +00004577 QualType ArgType = getTypeDeclType(TTP);
4578 if (TTP->isParameterPack())
4579 ArgType = getPackExpansionType(ArgType, None);
4580
4581 Arg = TemplateArgument(ArgType);
4582 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4583 Expr *E = new (*this) DeclRefExpr(
Bruno Ricci5fc4db72018-12-21 14:10:18 +00004584 *this, NTTP, /*enclosing*/ false,
Richard Smith32918772017-02-14 00:25:28 +00004585 NTTP->getType().getNonLValueExprType(*this),
4586 Expr::getValueKindForType(NTTP->getType()), NTTP->getLocation());
4587
4588 if (NTTP->isParameterPack())
4589 E = new (*this) PackExpansionExpr(DependentTy, E, NTTP->getLocation(),
4590 None);
4591 Arg = TemplateArgument(E);
4592 } else {
4593 auto *TTP = cast<TemplateTemplateParmDecl>(Param);
4594 if (TTP->isParameterPack())
4595 Arg = TemplateArgument(TemplateName(TTP), Optional<unsigned>());
4596 else
4597 Arg = TemplateArgument(TemplateName(TTP));
4598 }
4599
4600 if (Param->isTemplateParameterPack())
4601 Arg = TemplateArgument::CreatePackCopy(*this, Arg);
4602
4603 return Arg;
4604}
4605
Richard Smith43e14d22016-12-23 02:10:11 +00004606void
4607ASTContext::getInjectedTemplateArgs(const TemplateParameterList *Params,
4608 SmallVectorImpl<TemplateArgument> &Args) {
4609 Args.reserve(Args.size() + Params->size());
4610
Richard Smith32918772017-02-14 00:25:28 +00004611 for (NamedDecl *Param : *Params)
4612 Args.push_back(getInjectedTemplateArg(Param));
Richard Smith43e14d22016-12-23 02:10:11 +00004613}
4614
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00004615QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikie05785d12013-02-20 22:23:23 +00004616 Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00004617 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00004618 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00004619
Richard Smithb2997f52019-05-21 20:10:50 +00004620 // A deduced type can deduce to a pack, eg
4621 // auto ...x = some_pack;
4622 // That declaration isn't (yet) valid, but is created as part of building an
4623 // init-capture pack:
4624 // [...x = some_pack] {}
4625 assert((Pattern->containsUnexpandedParameterPack() ||
4626 Pattern->getContainedDeducedType()) &&
Douglas Gregord2fa7662010-12-20 02:24:11 +00004627 "Pack expansions must expand one or more parameter packs");
Craig Topper36250ad2014-05-12 05:36:57 +00004628 void *InsertPos = nullptr;
Douglas Gregord2fa7662010-12-20 02:24:11 +00004629 PackExpansionType *T
4630 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
4631 if (T)
4632 return QualType(T, 0);
4633
4634 QualType Canon;
4635 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00004636 Canon = getCanonicalType(Pattern);
4637 // The canonical type might not contain an unexpanded parameter pack, if it
4638 // contains an alias template specialization which ignores one of its
4639 // parameters.
4640 if (Canon->containsUnexpandedParameterPack()) {
Richard Smith8b4e1e22014-07-10 01:20:17 +00004641 Canon = getPackExpansionType(Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00004642
Richard Smith68eea502012-07-16 00:20:35 +00004643 // Find the insert position again, in case we inserted an element into
4644 // PackExpansionTypes and invalidated our insert position.
4645 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
4646 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00004647 }
4648
Benjamin Kramer8adeef92015-04-02 16:19:54 +00004649 T = new (*this, TypeAlignment)
4650 PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00004651 Types.push_back(T);
4652 PackExpansionTypes.InsertNode(T, InsertPos);
Richard Smith8b4e1e22014-07-10 01:20:17 +00004653 return QualType(T, 0);
Douglas Gregord2fa7662010-12-20 02:24:11 +00004654}
4655
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004656/// CmpProtocolNames - Comparison predicate for sorting protocols
4657/// alphabetically.
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00004658static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
4659 ObjCProtocolDecl *const *RHS) {
4660 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004661}
4662
Craig Topper1f26d5b2016-01-03 19:43:23 +00004663static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) {
4664 if (Protocols.empty()) return true;
John McCallfc93cf92009-10-22 22:37:11 +00004665
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00004666 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
4667 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00004668
Craig Topper1f26d5b2016-01-03 19:43:23 +00004669 for (unsigned i = 1; i != Protocols.size(); ++i)
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00004670 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00004671 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00004672 return false;
4673 return true;
4674}
4675
Craig Topper6a8c1512015-10-22 01:56:18 +00004676static void
4677SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) {
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004678 // Sort protocols, keyed by name.
Craig Topper6a8c1512015-10-22 01:56:18 +00004679 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004680
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00004681 // Canonicalize.
Craig Topper6a8c1512015-10-22 01:56:18 +00004682 for (ObjCProtocolDecl *&P : Protocols)
4683 P = P->getCanonicalDecl();
4684
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004685 // Remove duplicates.
Craig Topper6a8c1512015-10-22 01:56:18 +00004686 auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end());
4687 Protocols.erase(ProtocolsEnd, Protocols.end());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004688}
4689
John McCall8b07ec22010-05-15 11:32:37 +00004690QualType ASTContext::getObjCObjectType(QualType BaseType,
4691 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00004692 unsigned NumProtocols) const {
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004693 return getObjCObjectType(BaseType, {},
Douglas Gregorab209d82015-07-07 03:58:42 +00004694 llvm::makeArrayRef(Protocols, NumProtocols),
4695 /*isKindOf=*/false);
Douglas Gregore9d95f12015-07-07 03:57:35 +00004696}
4697
4698QualType ASTContext::getObjCObjectType(
4699 QualType baseType,
4700 ArrayRef<QualType> typeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00004701 ArrayRef<ObjCProtocolDecl *> protocols,
4702 bool isKindOf) const {
Douglas Gregore9d95f12015-07-07 03:57:35 +00004703 // If the base type is an interface and there aren't any protocols or
4704 // type arguments to add, then the interface type will do just fine.
Douglas Gregorab209d82015-07-07 03:58:42 +00004705 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
4706 isa<ObjCInterfaceType>(baseType))
Douglas Gregore9d95f12015-07-07 03:57:35 +00004707 return baseType;
John McCall8b07ec22010-05-15 11:32:37 +00004708
4709 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00004710 llvm::FoldingSetNodeID ID;
Douglas Gregorab209d82015-07-07 03:58:42 +00004711 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
Craig Topper36250ad2014-05-12 05:36:57 +00004712 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00004713 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
4714 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00004715
Douglas Gregore9d95f12015-07-07 03:57:35 +00004716 // Determine the type arguments to be used for canonicalization,
4717 // which may be explicitly specified here or written on the base
4718 // type.
4719 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
4720 if (effectiveTypeArgs.empty()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00004721 if (const auto *baseObject = baseType->getAs<ObjCObjectType>())
Douglas Gregore9d95f12015-07-07 03:57:35 +00004722 effectiveTypeArgs = baseObject->getTypeArgs();
4723 }
John McCallfc93cf92009-10-22 22:37:11 +00004724
Douglas Gregore9d95f12015-07-07 03:57:35 +00004725 // Build the canonical type, which has the canonical base type and a
4726 // sorted-and-uniqued list of protocols and the type arguments
4727 // canonicalized.
4728 QualType canonical;
4729 bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(),
4730 effectiveTypeArgs.end(),
4731 [&](QualType type) {
4732 return type.isCanonical();
4733 });
Craig Topper1f26d5b2016-01-03 19:43:23 +00004734 bool protocolsSorted = areSortedAndUniqued(protocols);
Douglas Gregore9d95f12015-07-07 03:57:35 +00004735 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
4736 // Determine the canonical type arguments.
4737 ArrayRef<QualType> canonTypeArgs;
4738 SmallVector<QualType, 4> canonTypeArgsVec;
4739 if (!typeArgsAreCanonical) {
4740 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
4741 for (auto typeArg : effectiveTypeArgs)
4742 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
4743 canonTypeArgs = canonTypeArgsVec;
John McCallfc93cf92009-10-22 22:37:11 +00004744 } else {
Douglas Gregore9d95f12015-07-07 03:57:35 +00004745 canonTypeArgs = effectiveTypeArgs;
John McCallfc93cf92009-10-22 22:37:11 +00004746 }
4747
Douglas Gregore9d95f12015-07-07 03:57:35 +00004748 ArrayRef<ObjCProtocolDecl *> canonProtocols;
4749 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
4750 if (!protocolsSorted) {
Craig Topper6a8c1512015-10-22 01:56:18 +00004751 canonProtocolsVec.append(protocols.begin(), protocols.end());
4752 SortAndUniqueProtocols(canonProtocolsVec);
4753 canonProtocols = canonProtocolsVec;
Douglas Gregore9d95f12015-07-07 03:57:35 +00004754 } else {
4755 canonProtocols = protocols;
4756 }
4757
4758 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00004759 canonProtocols, isKindOf);
Douglas Gregore9d95f12015-07-07 03:57:35 +00004760
John McCallfc93cf92009-10-22 22:37:11 +00004761 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00004762 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
4763 }
4764
Douglas Gregore9d95f12015-07-07 03:57:35 +00004765 unsigned size = sizeof(ObjCObjectTypeImpl);
4766 size += typeArgs.size() * sizeof(QualType);
4767 size += protocols.size() * sizeof(ObjCProtocolDecl *);
4768 void *mem = Allocate(size, TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004769 auto *T =
Douglas Gregorab209d82015-07-07 03:58:42 +00004770 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
4771 isKindOf);
John McCall8b07ec22010-05-15 11:32:37 +00004772
4773 Types.push_back(T);
4774 ObjCObjectTypes.InsertNode(T, InsertPos);
4775 return QualType(T, 0);
4776}
4777
Manman Ren3569eb52016-09-13 17:03:12 +00004778/// Apply Objective-C protocol qualifiers to the given type.
4779/// If this is for the canonical type of a type parameter, we can apply
4780/// protocol qualifiers on the ObjCObjectPointerType.
4781QualType
4782ASTContext::applyObjCProtocolQualifiers(QualType type,
4783 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
4784 bool allowOnPointerType) const {
4785 hasError = false;
4786
Eugene Zelenko7855e772018-04-03 00:11:50 +00004787 if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
Manman Renc5705ba2016-09-13 17:41:05 +00004788 return getObjCTypeParamType(objT->getDecl(), protocols);
4789 }
4790
Manman Ren3569eb52016-09-13 17:03:12 +00004791 // Apply protocol qualifiers to ObjCObjectPointerType.
4792 if (allowOnPointerType) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00004793 if (const auto *objPtr =
4794 dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
Manman Ren3569eb52016-09-13 17:03:12 +00004795 const ObjCObjectType *objT = objPtr->getObjectType();
4796 // Merge protocol lists and construct ObjCObjectType.
4797 SmallVector<ObjCProtocolDecl*, 8> protocolsVec;
4798 protocolsVec.append(objT->qual_begin(),
4799 objT->qual_end());
4800 protocolsVec.append(protocols.begin(), protocols.end());
4801 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
4802 type = getObjCObjectType(
4803 objT->getBaseType(),
4804 objT->getTypeArgsAsWritten(),
4805 protocols,
4806 objT->isKindOfTypeAsWritten());
4807 return getObjCObjectPointerType(type);
4808 }
4809 }
4810
4811 // Apply protocol qualifiers to ObjCObjectType.
Eugene Zelenko7855e772018-04-03 00:11:50 +00004812 if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
Manman Ren3569eb52016-09-13 17:03:12 +00004813 // FIXME: Check for protocols to which the class type is already
4814 // known to conform.
4815
4816 return getObjCObjectType(objT->getBaseType(),
4817 objT->getTypeArgsAsWritten(),
4818 protocols,
4819 objT->isKindOfTypeAsWritten());
4820 }
4821
4822 // If the canonical type is ObjCObjectType, ...
4823 if (type->isObjCObjectType()) {
4824 // Silently overwrite any existing protocol qualifiers.
4825 // TODO: determine whether that's the right thing to do.
4826
4827 // FIXME: Check for protocols to which the class type is already
4828 // known to conform.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004829 return getObjCObjectType(type, {}, protocols, false);
Manman Ren3569eb52016-09-13 17:03:12 +00004830 }
4831
4832 // id<protocol-list>
4833 if (type->isObjCIdType()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00004834 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004835 type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols,
Manman Ren3569eb52016-09-13 17:03:12 +00004836 objPtr->isKindOfType());
4837 return getObjCObjectPointerType(type);
4838 }
4839
4840 // Class<protocol-list>
4841 if (type->isObjCClassType()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00004842 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004843 type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols,
Manman Ren3569eb52016-09-13 17:03:12 +00004844 objPtr->isKindOfType());
4845 return getObjCObjectPointerType(type);
4846 }
4847
4848 hasError = true;
4849 return type;
4850}
4851
Manman Rene6be26c2016-09-13 17:25:08 +00004852QualType
4853ASTContext::getObjCTypeParamType(const ObjCTypeParamDecl *Decl,
Volodymyr Sapsaib95d4c32019-10-11 21:21:02 +00004854 ArrayRef<ObjCProtocolDecl *> protocols) const {
Manman Rene6be26c2016-09-13 17:25:08 +00004855 // Look in the folding set for an existing type.
4856 llvm::FoldingSetNodeID ID;
4857 ObjCTypeParamType::Profile(ID, Decl, protocols);
4858 void *InsertPos = nullptr;
4859 if (ObjCTypeParamType *TypeParam =
4860 ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
4861 return QualType(TypeParam, 0);
4862
Volodymyr Sapsaib95d4c32019-10-11 21:21:02 +00004863 // We canonicalize to the underlying type.
4864 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
4865 if (!protocols.empty()) {
4866 // Apply the protocol qualifers.
4867 bool hasError;
4868 Canonical = getCanonicalType(applyObjCProtocolQualifiers(
4869 Canonical, protocols, hasError, true /*allowOnPointerType*/));
4870 assert(!hasError && "Error when apply protocol qualifier to bound type");
Manman Rene6be26c2016-09-13 17:25:08 +00004871 }
4872
4873 unsigned size = sizeof(ObjCTypeParamType);
4874 size += protocols.size() * sizeof(ObjCProtocolDecl *);
4875 void *mem = Allocate(size, TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004876 auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols);
Manman Rene6be26c2016-09-13 17:25:08 +00004877
4878 Types.push_back(newType);
4879 ObjCTypeParamTypes.InsertNode(newType, InsertPos);
4880 return QualType(newType, 0);
4881}
4882
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004883/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
4884/// protocol list adopt all protocols in QT's qualified-id protocol
4885/// list.
4886bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
4887 ObjCInterfaceDecl *IC) {
4888 if (!QT->isObjCQualifiedIdType())
4889 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00004890
Eugene Zelenko7855e772018-04-03 00:11:50 +00004891 if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004892 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00004893 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004894 if (!IC->ClassImplementsProtocol(Proto, false))
4895 return false;
4896 }
4897 return true;
4898 }
4899 return false;
4900}
4901
4902/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
4903/// QT's qualified-id protocol list adopt all protocols in IDecl's list
4904/// of protocols.
4905bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
4906 ObjCInterfaceDecl *IDecl) {
4907 if (!QT->isObjCQualifiedIdType())
4908 return false;
Eugene Zelenko7855e772018-04-03 00:11:50 +00004909 const auto *OPT = QT->getAs<ObjCObjectPointerType>();
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004910 if (!OPT)
4911 return false;
4912 if (!IDecl->hasDefinition())
4913 return false;
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00004914 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
4915 CollectInheritedProtocols(IDecl, InheritedProtocols);
4916 if (InheritedProtocols.empty())
4917 return false;
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00004918 // Check that if every protocol in list of id<plist> conforms to a protocol
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00004919 // of IDecl's, then bridge casting is ok.
4920 bool Conforms = false;
4921 for (auto *Proto : OPT->quals()) {
4922 Conforms = false;
4923 for (auto *PI : InheritedProtocols) {
4924 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
4925 Conforms = true;
4926 break;
4927 }
4928 }
4929 if (!Conforms)
4930 break;
4931 }
4932 if (Conforms)
4933 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00004934
Aaron Ballman83731462014-03-17 16:14:00 +00004935 for (auto *PI : InheritedProtocols) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004936 // If both the right and left sides have qualifiers.
4937 bool Adopts = false;
Aaron Ballman83731462014-03-17 16:14:00 +00004938 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00004939 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
Aaron Ballman83731462014-03-17 16:14:00 +00004940 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004941 break;
4942 }
4943 if (!Adopts)
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00004944 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004945 }
4946 return true;
4947}
4948
John McCall8b07ec22010-05-15 11:32:37 +00004949/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
4950/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00004951QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00004952 llvm::FoldingSetNodeID ID;
4953 ObjCObjectPointerType::Profile(ID, ObjectT);
4954
Craig Topper36250ad2014-05-12 05:36:57 +00004955 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00004956 if (ObjCObjectPointerType *QT =
4957 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
4958 return QualType(QT, 0);
4959
4960 // Find the canonical object type.
4961 QualType Canonical;
4962 if (!ObjectT.isCanonical()) {
4963 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
4964
4965 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00004966 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
4967 }
4968
Douglas Gregorf85bee62010-02-08 22:59:26 +00004969 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00004970 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004971 auto *QType =
John McCall8b07ec22010-05-15 11:32:37 +00004972 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00004973
Steve Narofffb4330f2009-06-17 22:40:22 +00004974 Types.push_back(QType);
4975 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00004976 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00004977}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004978
Douglas Gregor1c283312010-08-11 12:19:30 +00004979/// getObjCInterfaceType - Return the unique reference to the type for the
4980/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00004981QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
4982 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00004983 if (Decl->TypeForDecl)
4984 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004985
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00004986 if (PrevDecl) {
4987 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
4988 Decl->TypeForDecl = PrevDecl->TypeForDecl;
4989 return QualType(PrevDecl->TypeForDecl, 0);
4990 }
4991
Douglas Gregor7671e532011-12-16 16:34:57 +00004992 // Prefer the definition, if there is one.
4993 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
4994 Decl = Def;
Fangrui Song6907ce22018-07-30 19:24:48 +00004995
Douglas Gregor1c283312010-08-11 12:19:30 +00004996 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004997 auto *T = new (Mem) ObjCInterfaceType(Decl);
Douglas Gregor1c283312010-08-11 12:19:30 +00004998 Decl->TypeForDecl = T;
4999 Types.push_back(T);
5000 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00005001}
5002
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005003/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
5004/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00005005/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00005006/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00005007/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00005008QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00005009 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00005010 if (tofExpr->isTypeDependent()) {
5011 llvm::FoldingSetNodeID ID;
5012 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00005013
Craig Topper36250ad2014-05-12 05:36:57 +00005014 void *InsertPos = nullptr;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00005015 DependentTypeOfExprType *Canon
5016 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
5017 if (Canon) {
5018 // We already have a "canonical" version of an identical, dependent
5019 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00005020 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00005021 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00005022 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00005023 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00005024 Canon
5025 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00005026 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
5027 toe = Canon;
5028 }
5029 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00005030 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00005031 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00005032 }
Steve Naroffa773cd52007-08-01 18:02:17 +00005033 Types.push_back(toe);
5034 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00005035}
5036
Steve Naroffa773cd52007-08-01 18:02:17 +00005037/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
Richard Smith8eb1d322014-06-05 20:13:13 +00005038/// TypeOfType nodes. The only motivation to unique these nodes would be
Steve Naroffa773cd52007-08-01 18:02:17 +00005039/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Richard Smith8eb1d322014-06-05 20:13:13 +00005040/// an issue. This doesn't affect the type checker, since it operates
5041/// on canonical types (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00005042QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00005043 QualType Canonical = getCanonicalType(tofType);
Eugene Zelenko7855e772018-04-03 00:11:50 +00005044 auto *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00005045 Types.push_back(tot);
5046 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00005047}
5048
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005049/// Unlike many "get<Type>" functions, we don't unique DecltypeType
Richard Smith8eb1d322014-06-05 20:13:13 +00005050/// nodes. This would never be helpful, since each such type has its own
5051/// expression, and would not give a significant memory saving, since there
5052/// is an Expr tree under each such type.
Douglas Gregor81495f32012-02-12 18:42:33 +00005053QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00005054 DecltypeType *dt;
Richard Smith8eb1d322014-06-05 20:13:13 +00005055
5056 // C++11 [temp.type]p2:
Douglas Gregor678d76c2011-07-01 01:22:09 +00005057 // If an expression e involves a template parameter, decltype(e) denotes a
Richard Smith8eb1d322014-06-05 20:13:13 +00005058 // unique dependent type. Two such decltype-specifiers refer to the same
5059 // type only if their expressions are equivalent (14.5.6.1).
Douglas Gregor678d76c2011-07-01 01:22:09 +00005060 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00005061 llvm::FoldingSetNodeID ID;
5062 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00005063
Craig Topper36250ad2014-05-12 05:36:57 +00005064 void *InsertPos = nullptr;
Douglas Gregora21f6c32009-07-30 23:36:40 +00005065 DependentDecltypeType *Canon
5066 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
Richard Smith8eb1d322014-06-05 20:13:13 +00005067 if (!Canon) {
Yaron Keren633e14a2016-11-29 10:08:20 +00005068 // Build a new, canonical decltype(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00005069 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00005070 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
Douglas Gregora21f6c32009-07-30 23:36:40 +00005071 }
Richard Smith8eb1d322014-06-05 20:13:13 +00005072 dt = new (*this, TypeAlignment)
5073 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
Douglas Gregora21f6c32009-07-30 23:36:40 +00005074 } else {
Richard Smith8eb1d322014-06-05 20:13:13 +00005075 dt = new (*this, TypeAlignment)
5076 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00005077 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00005078 Types.push_back(dt);
5079 return QualType(dt, 0);
5080}
5081
Alexis Hunte852b102011-05-24 22:41:36 +00005082/// getUnaryTransformationType - We don't unique these, since the memory
5083/// savings are minimal and these are rare.
5084QualType ASTContext::getUnaryTransformType(QualType BaseType,
5085 QualType UnderlyingType,
5086 UnaryTransformType::UTTKind Kind)
5087 const {
Vassil Vassilevbab6f962016-03-30 22:18:29 +00005088 UnaryTransformType *ut = nullptr;
5089
5090 if (BaseType->isDependentType()) {
5091 // Look in the folding set for an existing type.
5092 llvm::FoldingSetNodeID ID;
5093 DependentUnaryTransformType::Profile(ID, getCanonicalType(BaseType), Kind);
5094
5095 void *InsertPos = nullptr;
5096 DependentUnaryTransformType *Canon
5097 = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
5098
5099 if (!Canon) {
5100 // Build a new, canonical __underlying_type(type) type.
5101 Canon = new (*this, TypeAlignment)
5102 DependentUnaryTransformType(*this, getCanonicalType(BaseType),
5103 Kind);
5104 DependentUnaryTransformTypes.InsertNode(Canon, InsertPos);
5105 }
5106 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
5107 QualType(), Kind,
5108 QualType(Canon, 0));
5109 } else {
5110 QualType CanonType = getCanonicalType(UnderlyingType);
5111 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
5112 UnderlyingType, Kind,
5113 CanonType);
5114 }
5115 Types.push_back(ut);
5116 return QualType(ut, 0);
Alexis Hunte852b102011-05-24 22:41:36 +00005117}
5118
Richard Smith2a7d4812013-05-04 07:00:32 +00005119/// getAutoType - Return the uniqued reference to the 'auto' type which has been
5120/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
5121/// canonical deduced-but-dependent 'auto' type.
Saar Razb481f022020-01-22 02:03:05 +02005122QualType
5123ASTContext::getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
5124 bool IsDependent, bool IsPack,
5125 ConceptDecl *TypeConstraintConcept,
5126 ArrayRef<TemplateArgument> TypeConstraintArgs) const {
Richard Smithb2997f52019-05-21 20:10:50 +00005127 assert((!IsPack || IsDependent) && "only use IsPack for a dependent pack");
Saar Razb481f022020-01-22 02:03:05 +02005128 if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto &&
5129 !TypeConstraintConcept && !IsDependent)
Richard Smith2a7d4812013-05-04 07:00:32 +00005130 return getAutoDeductType();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00005131
Richard Smith2a7d4812013-05-04 07:00:32 +00005132 // Look in the folding set for an existing type.
Craig Topper36250ad2014-05-12 05:36:57 +00005133 void *InsertPos = nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +00005134 llvm::FoldingSetNodeID ID;
Saar Razb481f022020-01-22 02:03:05 +02005135 AutoType::Profile(ID, *this, DeducedType, Keyword, IsDependent,
5136 TypeConstraintConcept, TypeConstraintArgs);
Richard Smith2a7d4812013-05-04 07:00:32 +00005137 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
5138 return QualType(AT, 0);
Richard Smithb2bc2e62011-02-21 20:05:19 +00005139
Saar Razb481f022020-01-22 02:03:05 +02005140 void *Mem = Allocate(sizeof(AutoType) +
5141 sizeof(TemplateArgument) * TypeConstraintArgs.size(),
5142 TypeAlignment);
Sam McCalla2aa9972020-03-19 11:58:00 +01005143 auto *AT = new (Mem) AutoType(
5144 DeducedType, Keyword,
5145 (IsDependent ? TypeDependence::DependentInstantiation
5146 : TypeDependence::None) |
5147 (IsPack ? TypeDependence::UnexpandedPack : TypeDependence::None),
5148 TypeConstraintConcept, TypeConstraintArgs);
Richard Smithb2bc2e62011-02-21 20:05:19 +00005149 Types.push_back(AT);
5150 if (InsertPos)
5151 AutoTypes.InsertNode(AT, InsertPos);
5152 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00005153}
5154
Richard Smith600b5262017-01-26 20:40:47 +00005155/// Return the uniqued reference to the deduced template specialization type
5156/// which has been deduced to the given type, or to the canonical undeduced
5157/// such type, or the canonical deduced-but-dependent such type.
5158QualType ASTContext::getDeducedTemplateSpecializationType(
5159 TemplateName Template, QualType DeducedType, bool IsDependent) const {
5160 // Look in the folding set for an existing type.
5161 void *InsertPos = nullptr;
5162 llvm::FoldingSetNodeID ID;
5163 DeducedTemplateSpecializationType::Profile(ID, Template, DeducedType,
5164 IsDependent);
5165 if (DeducedTemplateSpecializationType *DTST =
5166 DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
5167 return QualType(DTST, 0);
5168
Eugene Zelenko7855e772018-04-03 00:11:50 +00005169 auto *DTST = new (*this, TypeAlignment)
Richard Smith600b5262017-01-26 20:40:47 +00005170 DeducedTemplateSpecializationType(Template, DeducedType, IsDependent);
5171 Types.push_back(DTST);
5172 if (InsertPos)
5173 DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos);
5174 return QualType(DTST, 0);
5175}
5176
Eli Friedman0dfb8892011-10-06 23:00:33 +00005177/// getAtomicType - Return the uniqued reference to the atomic type for
5178/// the given value type.
5179QualType ASTContext::getAtomicType(QualType T) const {
5180 // Unique pointers, to guarantee there is only one pointer of a particular
5181 // structure.
5182 llvm::FoldingSetNodeID ID;
5183 AtomicType::Profile(ID, T);
5184
Craig Topper36250ad2014-05-12 05:36:57 +00005185 void *InsertPos = nullptr;
Eli Friedman0dfb8892011-10-06 23:00:33 +00005186 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
5187 return QualType(AT, 0);
5188
5189 // If the atomic value type isn't canonical, this won't be a canonical type
5190 // either, so fill in the canonical type field.
5191 QualType Canonical;
5192 if (!T.isCanonical()) {
5193 Canonical = getAtomicType(getCanonicalType(T));
5194
5195 // Get the new insert position for the node we care about.
5196 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00005197 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Eli Friedman0dfb8892011-10-06 23:00:33 +00005198 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00005199 auto *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
Eli Friedman0dfb8892011-10-06 23:00:33 +00005200 Types.push_back(New);
5201 AtomicTypes.InsertNode(New, InsertPos);
5202 return QualType(New, 0);
5203}
5204
Richard Smith02e85f32011-04-14 22:09:26 +00005205/// getAutoDeductType - Get type pattern for deducing against 'auto'.
5206QualType ASTContext::getAutoDeductType() const {
5207 if (AutoDeductTy.isNull())
Sam McCalla2aa9972020-03-19 11:58:00 +01005208 AutoDeductTy = QualType(new (*this, TypeAlignment)
5209 AutoType(QualType(), AutoTypeKeyword::Auto,
5210 TypeDependence::None,
5211 /*concept*/ nullptr, /*args*/ {}),
5212 0);
Richard Smith02e85f32011-04-14 22:09:26 +00005213 return AutoDeductTy;
5214}
5215
5216/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
5217QualType ASTContext::getAutoRRefDeductType() const {
5218 if (AutoRRefDeductTy.isNull())
5219 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
5220 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
5221 return AutoRRefDeductTy;
5222}
5223
Chris Lattnerfb072462007-01-23 05:45:31 +00005224/// getTagDeclType - Return the unique reference to the type for the
5225/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00005226QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00005227 assert(Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00005228 // FIXME: What is the design on getTagDeclType when it requires casting
5229 // away const? mutable?
5230 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00005231}
5232
Mike Stump11289f42009-09-09 15:08:12 +00005233/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
5234/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
5235/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00005236CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00005237 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00005238}
Chris Lattnerfb072462007-01-23 05:45:31 +00005239
Fangrui Song6907ce22018-07-30 19:24:48 +00005240/// Return the unique signed counterpart of the integer type
Alexander Shaposhnikov1e898d92017-07-14 17:30:14 +00005241/// corresponding to size_t.
5242CanQualType ASTContext::getSignedSizeType() const {
5243 return getFromTargetType(Target->getSignedSizeType());
5244}
5245
Hans Wennborg27541db2011-10-27 08:29:09 +00005246/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
5247CanQualType ASTContext::getIntMaxType() const {
5248 return getFromTargetType(Target->getIntMaxType());
5249}
5250
5251/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
5252CanQualType ASTContext::getUIntMaxType() const {
5253 return getFromTargetType(Target->getUIntMaxType());
5254}
5255
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00005256/// getSignedWCharType - Return the type of "signed wchar_t".
5257/// Used when in C++, as a GCC extension.
5258QualType ASTContext::getSignedWCharType() const {
5259 // FIXME: derive from "Target" ?
5260 return WCharTy;
5261}
5262
5263/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
5264/// Used when in C++, as a GCC extension.
5265QualType ASTContext::getUnsignedWCharType() const {
5266 // FIXME: derive from "Target" ?
5267 return UnsignedIntTy;
5268}
5269
Enea Zaffanellaf11ceb62013-01-26 17:08:37 +00005270QualType ASTContext::getIntPtrType() const {
5271 return getFromTargetType(Target->getIntPtrType());
5272}
5273
5274QualType ASTContext::getUIntPtrType() const {
5275 return getCorrespondingUnsignedType(getIntPtrType());
5276}
5277
Hans Wennborg27541db2011-10-27 08:29:09 +00005278/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00005279/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
5280QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00005281 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00005282}
5283
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005284/// Return the unique unsigned counterpart of "ptrdiff_t"
Alexander Shaposhnikov195b25c2017-09-28 23:11:31 +00005285/// integer type. The standard (C11 7.21.6.1p7) refers to this type
5286/// in the definition of %tu format specifier.
5287QualType ASTContext::getUnsignedPointerDiffType() const {
5288 return getFromTargetType(Target->getUnsignedPtrDiffType(0));
5289}
5290
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005291/// Return the unique type for "pid_t" defined in
Eli Friedman4e91899e2012-11-27 02:58:24 +00005292/// <sys/types.h>. We need this to compute the correct type for vfork().
5293QualType ASTContext::getProcessIDType() const {
5294 return getFromTargetType(Target->getProcessIDType());
5295}
5296
Chris Lattnera21ad802008-04-02 05:18:44 +00005297//===----------------------------------------------------------------------===//
5298// Type Operators
5299//===----------------------------------------------------------------------===//
5300
Jay Foad39c79802011-01-12 09:06:06 +00005301CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00005302 // Push qualifiers into arrays, and then discard any remaining
5303 // qualifiers.
5304 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00005305 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00005306 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00005307 QualType Result;
5308 if (isa<ArrayType>(Ty)) {
5309 Result = getArrayDecayedType(QualType(Ty,0));
5310 } else if (isa<FunctionType>(Ty)) {
5311 Result = getPointerType(QualType(Ty, 0));
5312 } else {
5313 Result = QualType(Ty, 0);
5314 }
5315
5316 return CanQualType::CreateUnsafe(Result);
5317}
5318
John McCall6c9dd522011-01-18 07:41:22 +00005319QualType ASTContext::getUnqualifiedArrayType(QualType type,
5320 Qualifiers &quals) {
5321 SplitQualType splitType = type.getSplitUnqualifiedType();
5322
5323 // FIXME: getSplitUnqualifiedType() actually walks all the way to
5324 // the unqualified desugared type and then drops it on the floor.
5325 // We then have to strip that sugar back off with
5326 // getUnqualifiedDesugaredType(), which is silly.
Eugene Zelenko7855e772018-04-03 00:11:50 +00005327 const auto *AT =
5328 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00005329
5330 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00005331 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00005332 quals = splitType.Quals;
5333 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00005334 }
5335
John McCall6c9dd522011-01-18 07:41:22 +00005336 // Otherwise, recurse on the array's element type.
5337 QualType elementType = AT->getElementType();
5338 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
5339
5340 // If that didn't change the element type, AT has no qualifiers, so we
5341 // can just use the results in splitType.
5342 if (elementType == unqualElementType) {
5343 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00005344 quals = splitType.Quals;
5345 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00005346 }
5347
5348 // Otherwise, add in the qualifiers from the outermost type, then
5349 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00005350 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00005351
Eugene Zelenko7855e772018-04-03 00:11:50 +00005352 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00005353 return getConstantArrayType(unqualElementType, CAT->getSize(),
Richard Smith772e2662019-10-04 01:25:59 +00005354 CAT->getSizeExpr(), CAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00005355 }
5356
Eugene Zelenko7855e772018-04-03 00:11:50 +00005357 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00005358 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00005359 }
5360
Eugene Zelenko7855e772018-04-03 00:11:50 +00005361 if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00005362 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00005363 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00005364 VAT->getSizeModifier(),
5365 VAT->getIndexTypeCVRQualifiers(),
5366 VAT->getBracketsRange());
5367 }
5368
Eugene Zelenko7855e772018-04-03 00:11:50 +00005369 const auto *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00005370 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00005371 DSAT->getSizeModifier(), 0,
5372 SourceRange());
5373}
5374
Richard Smitha3405ff2018-07-11 00:19:19 +00005375/// Attempt to unwrap two types that may both be array types with the same bound
5376/// (or both be array types of unknown bound) for the purpose of comparing the
5377/// cv-decomposition of two types per C++ [conv.qual].
Richard Smith5407d4f2018-07-18 20:13:36 +00005378bool ASTContext::UnwrapSimilarArrayTypes(QualType &T1, QualType &T2) {
5379 bool UnwrappedAny = false;
Richard Smitha3405ff2018-07-11 00:19:19 +00005380 while (true) {
Richard Smith5407d4f2018-07-18 20:13:36 +00005381 auto *AT1 = getAsArrayType(T1);
5382 if (!AT1) return UnwrappedAny;
Richard Smitha3405ff2018-07-11 00:19:19 +00005383
Richard Smith5407d4f2018-07-18 20:13:36 +00005384 auto *AT2 = getAsArrayType(T2);
5385 if (!AT2) return UnwrappedAny;
Richard Smitha3405ff2018-07-11 00:19:19 +00005386
5387 // If we don't have two array types with the same constant bound nor two
5388 // incomplete array types, we've unwrapped everything we can.
5389 if (auto *CAT1 = dyn_cast<ConstantArrayType>(AT1)) {
5390 auto *CAT2 = dyn_cast<ConstantArrayType>(AT2);
5391 if (!CAT2 || CAT1->getSize() != CAT2->getSize())
Richard Smith5407d4f2018-07-18 20:13:36 +00005392 return UnwrappedAny;
Richard Smitha3405ff2018-07-11 00:19:19 +00005393 } else if (!isa<IncompleteArrayType>(AT1) ||
5394 !isa<IncompleteArrayType>(AT2)) {
Richard Smith5407d4f2018-07-18 20:13:36 +00005395 return UnwrappedAny;
Richard Smitha3405ff2018-07-11 00:19:19 +00005396 }
5397
5398 T1 = AT1->getElementType();
5399 T2 = AT2->getElementType();
Richard Smith5407d4f2018-07-18 20:13:36 +00005400 UnwrappedAny = true;
Richard Smitha3405ff2018-07-11 00:19:19 +00005401 }
5402}
5403
5404/// Attempt to unwrap two types that may be similar (C++ [conv.qual]).
5405///
5406/// If T1 and T2 are both pointer types of the same kind, or both array types
5407/// with the same bound, unwraps layers from T1 and T2 until a pointer type is
5408/// unwrapped. Top-level qualifiers on T1 and T2 are ignored.
5409///
5410/// This function will typically be called in a loop that successively
5411/// "unwraps" pointer and pointer-to-member types to compare them at each
5412/// level.
5413///
5414/// \return \c true if a pointer type was unwrapped, \c false if we reached a
5415/// pair of types that can't be unwrapped further.
5416bool ASTContext::UnwrapSimilarTypes(QualType &T1, QualType &T2) {
Richard Smith5407d4f2018-07-18 20:13:36 +00005417 UnwrapSimilarArrayTypes(T1, T2);
Richard Smitha3405ff2018-07-11 00:19:19 +00005418
Eugene Zelenko7855e772018-04-03 00:11:50 +00005419 const auto *T1PtrType = T1->getAs<PointerType>();
5420 const auto *T2PtrType = T2->getAs<PointerType>();
Douglas Gregor1fc3d662010-06-09 03:53:18 +00005421 if (T1PtrType && T2PtrType) {
5422 T1 = T1PtrType->getPointeeType();
5423 T2 = T2PtrType->getPointeeType();
5424 return true;
5425 }
Richard Smith5407d4f2018-07-18 20:13:36 +00005426
Eugene Zelenko7855e772018-04-03 00:11:50 +00005427 const auto *T1MPType = T1->getAs<MemberPointerType>();
5428 const auto *T2MPType = T2->getAs<MemberPointerType>();
Fangrui Song6907ce22018-07-30 19:24:48 +00005429 if (T1MPType && T2MPType &&
5430 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
Douglas Gregor1fc3d662010-06-09 03:53:18 +00005431 QualType(T2MPType->getClass(), 0))) {
5432 T1 = T1MPType->getPointeeType();
5433 T2 = T2MPType->getPointeeType();
5434 return true;
5435 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005436
Erik Pilkingtonfa983902018-10-30 20:31:30 +00005437 if (getLangOpts().ObjC) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00005438 const auto *T1OPType = T1->getAs<ObjCObjectPointerType>();
5439 const auto *T2OPType = T2->getAs<ObjCObjectPointerType>();
Douglas Gregor1fc3d662010-06-09 03:53:18 +00005440 if (T1OPType && T2OPType) {
5441 T1 = T1OPType->getPointeeType();
5442 T2 = T2OPType->getPointeeType();
5443 return true;
5444 }
5445 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005446
Douglas Gregor1fc3d662010-06-09 03:53:18 +00005447 // FIXME: Block pointers, too?
Fangrui Song6907ce22018-07-30 19:24:48 +00005448
Douglas Gregor1fc3d662010-06-09 03:53:18 +00005449 return false;
5450}
5451
Richard Smitha3405ff2018-07-11 00:19:19 +00005452bool ASTContext::hasSimilarType(QualType T1, QualType T2) {
5453 while (true) {
5454 Qualifiers Quals;
5455 T1 = getUnqualifiedArrayType(T1, Quals);
5456 T2 = getUnqualifiedArrayType(T2, Quals);
5457 if (hasSameType(T1, T2))
5458 return true;
5459 if (!UnwrapSimilarTypes(T1, T2))
5460 return false;
5461 }
5462}
5463
5464bool ASTContext::hasCvrSimilarType(QualType T1, QualType T2) {
5465 while (true) {
5466 Qualifiers Quals1, Quals2;
5467 T1 = getUnqualifiedArrayType(T1, Quals1);
5468 T2 = getUnqualifiedArrayType(T2, Quals2);
5469
5470 Quals1.removeCVRQualifiers();
5471 Quals2.removeCVRQualifiers();
5472 if (Quals1 != Quals2)
5473 return false;
5474
5475 if (hasSameType(T1, T2))
5476 return true;
5477
5478 if (!UnwrapSimilarTypes(T1, T2))
5479 return false;
5480 }
5481}
5482
Jay Foad39c79802011-01-12 09:06:06 +00005483DeclarationNameInfo
5484ASTContext::getNameForTemplate(TemplateName Name,
5485 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00005486 switch (Name.getKind()) {
5487 case TemplateName::QualifiedTemplate:
5488 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005489 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00005490 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
5491 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005492
John McCalld9dfe3a2011-06-30 08:33:18 +00005493 case TemplateName::OverloadedTemplate: {
5494 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
5495 // DNInfo work in progress: CHECKME: what about DNLoc?
5496 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
5497 }
5498
Richard Smithb23c5e82019-05-09 03:31:27 +00005499 case TemplateName::AssumedTemplate: {
5500 AssumedTemplateStorage *Storage = Name.getAsAssumedTemplateName();
5501 return DeclarationNameInfo(Storage->getDeclName(), NameLoc);
5502 }
5503
John McCalld9dfe3a2011-06-30 08:33:18 +00005504 case TemplateName::DependentTemplate: {
5505 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005506 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00005507 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005508 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
5509 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00005510 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005511 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
5512 // DNInfo work in progress: FIXME: source locations?
5513 DeclarationNameLoc DNLoc;
5514 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
5515 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
5516 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00005517 }
5518 }
5519
John McCalld9dfe3a2011-06-30 08:33:18 +00005520 case TemplateName::SubstTemplateTemplateParm: {
5521 SubstTemplateTemplateParmStorage *subst
5522 = Name.getAsSubstTemplateTemplateParm();
5523 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
5524 NameLoc);
5525 }
5526
5527 case TemplateName::SubstTemplateTemplateParmPack: {
5528 SubstTemplateTemplateParmPackStorage *subst
5529 = Name.getAsSubstTemplateTemplateParmPack();
5530 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
5531 NameLoc);
5532 }
5533 }
5534
5535 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00005536}
5537
Jay Foad39c79802011-01-12 09:06:06 +00005538TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00005539 switch (Name.getKind()) {
5540 case TemplateName::QualifiedTemplate:
5541 case TemplateName::Template: {
5542 TemplateDecl *Template = Name.getAsTemplateDecl();
Eugene Zelenko7855e772018-04-03 00:11:50 +00005543 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00005544 Template = getCanonicalTemplateTemplateParmDecl(TTP);
Fangrui Song6907ce22018-07-30 19:24:48 +00005545
Douglas Gregor7dbfb462010-06-16 21:09:37 +00005546 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00005547 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00005548 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00005549
John McCalld9dfe3a2011-06-30 08:33:18 +00005550 case TemplateName::OverloadedTemplate:
Richard Smithb23c5e82019-05-09 03:31:27 +00005551 case TemplateName::AssumedTemplate:
5552 llvm_unreachable("cannot canonicalize unresolved template");
Mike Stump11289f42009-09-09 15:08:12 +00005553
John McCalld9dfe3a2011-06-30 08:33:18 +00005554 case TemplateName::DependentTemplate: {
5555 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
5556 assert(DTN && "Non-dependent template names must refer to template decls.");
5557 return DTN->CanonicalTemplateName;
5558 }
5559
5560 case TemplateName::SubstTemplateTemplateParm: {
5561 SubstTemplateTemplateParmStorage *subst
5562 = Name.getAsSubstTemplateTemplateParm();
5563 return getCanonicalTemplateName(subst->getReplacement());
5564 }
5565
5566 case TemplateName::SubstTemplateTemplateParmPack: {
5567 SubstTemplateTemplateParmPackStorage *subst
5568 = Name.getAsSubstTemplateTemplateParmPack();
5569 TemplateTemplateParmDecl *canonParameter
5570 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
5571 TemplateArgument canonArgPack
5572 = getCanonicalTemplateArgument(subst->getArgumentPack());
5573 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
5574 }
5575 }
5576
5577 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00005578}
5579
Douglas Gregoradee3e32009-11-11 23:06:43 +00005580bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
5581 X = getCanonicalTemplateName(X);
5582 Y = getCanonicalTemplateName(Y);
5583 return X.getAsVoidPointer() == Y.getAsVoidPointer();
5584}
5585
Mike Stump11289f42009-09-09 15:08:12 +00005586TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00005587ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00005588 switch (Arg.getKind()) {
5589 case TemplateArgument::Null:
5590 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00005591
Douglas Gregora8e02e72009-07-28 23:00:59 +00005592 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00005593 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00005594
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005595 case TemplateArgument::Declaration: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00005596 auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
David Blaikie952a9b12014-10-17 18:00:12 +00005597 return TemplateArgument(D, Arg.getParamTypeForDecl());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005598 }
Mike Stump11289f42009-09-09 15:08:12 +00005599
Eli Friedmanb826a002012-09-26 02:36:12 +00005600 case TemplateArgument::NullPtr:
5601 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
5602 /*isNullPtr*/true);
5603
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005604 case TemplateArgument::Template:
5605 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005606
5607 case TemplateArgument::TemplateExpansion:
5608 return TemplateArgument(getCanonicalTemplateName(
5609 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00005610 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005611
Douglas Gregora8e02e72009-07-28 23:00:59 +00005612 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00005613 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00005614
Douglas Gregora8e02e72009-07-28 23:00:59 +00005615 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00005616 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00005617
Douglas Gregora8e02e72009-07-28 23:00:59 +00005618 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00005619 if (Arg.pack_size() == 0)
5620 return Arg;
Fangrui Song6907ce22018-07-30 19:24:48 +00005621
Eugene Zelenko7855e772018-04-03 00:11:50 +00005622 auto *CanonArgs = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00005623 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00005624 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00005625 AEnd = Arg.pack_end();
5626 A != AEnd; (void)++A, ++Idx)
5627 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00005628
Benjamin Kramercce63472015-08-05 09:40:22 +00005629 return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size()));
Douglas Gregora8e02e72009-07-28 23:00:59 +00005630 }
5631 }
5632
5633 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00005634 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00005635}
5636
Douglas Gregor333489b2009-03-27 23:10:48 +00005637NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00005638ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00005639 if (!NNS)
Craig Topper36250ad2014-05-12 05:36:57 +00005640 return nullptr;
Douglas Gregor333489b2009-03-27 23:10:48 +00005641
5642 switch (NNS->getKind()) {
5643 case NestedNameSpecifier::Identifier:
5644 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00005645 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00005646 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
5647 NNS->getAsIdentifier());
5648
5649 case NestedNameSpecifier::Namespace:
5650 // A namespace is canonical; build a nested-name-specifier with
5651 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00005652 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00005653 NNS->getAsNamespace()->getOriginalNamespace());
5654
5655 case NestedNameSpecifier::NamespaceAlias:
5656 // A namespace is canonical; build a nested-name-specifier with
5657 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00005658 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00005659 NNS->getAsNamespaceAlias()->getNamespace()
5660 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00005661
5662 case NestedNameSpecifier::TypeSpec:
5663 case NestedNameSpecifier::TypeSpecWithTemplate: {
5664 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Fangrui Song6907ce22018-07-30 19:24:48 +00005665
Douglas Gregor3ade5702010-11-04 00:09:33 +00005666 // If we have some kind of dependent-named type (e.g., "typename T::type"),
5667 // break it apart into its prefix and identifier, then reconsititute those
5668 // as the canonical nested-name-specifier. This is required to canonicalize
5669 // a dependent nested-name-specifier involving typedefs of dependent-name
5670 // types, e.g.,
5671 // typedef typename T::type T1;
5672 // typedef typename T1::type T2;
Eugene Zelenko7855e772018-04-03 00:11:50 +00005673 if (const auto *DNT = T->getAs<DependentNameType>())
Fangrui Song6907ce22018-07-30 19:24:48 +00005674 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00005675 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00005676
Eli Friedman5358a0a2012-03-03 04:09:56 +00005677 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
5678 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
5679 // first place?
Craig Topper36250ad2014-05-12 05:36:57 +00005680 return NestedNameSpecifier::Create(*this, nullptr, false,
5681 const_cast<Type *>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00005682 }
5683
5684 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00005685 case NestedNameSpecifier::Super:
5686 // The global specifier and __super specifer are canonical and unique.
Douglas Gregor333489b2009-03-27 23:10:48 +00005687 return NNS;
5688 }
5689
David Blaikie8a40f702012-01-17 06:56:22 +00005690 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00005691}
5692
Jay Foad39c79802011-01-12 09:06:06 +00005693const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00005694 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005695 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00005696 // Handle the common positive case fast.
Eugene Zelenko7855e772018-04-03 00:11:50 +00005697 if (const auto *AT = dyn_cast<ArrayType>(T))
Chris Lattner7adf0762008-08-04 07:31:14 +00005698 return AT;
5699 }
Mike Stump11289f42009-09-09 15:08:12 +00005700
John McCall8ccfcb52009-09-24 19:53:00 +00005701 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00005702 if (!isa<ArrayType>(T.getCanonicalType()))
Craig Topper36250ad2014-05-12 05:36:57 +00005703 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00005704
John McCall8ccfcb52009-09-24 19:53:00 +00005705 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00005706 // implements C99 6.7.3p8: "If the specification of an array type includes
5707 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00005708
Chris Lattner7adf0762008-08-04 07:31:14 +00005709 // If we get here, we either have type qualifiers on the type, or we have
5710 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00005711 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00005712
John McCall33ddac02011-01-19 10:06:00 +00005713 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00005714 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00005715
Chris Lattner7adf0762008-08-04 07:31:14 +00005716 // If we have a simple case, just return now.
Eugene Zelenko7855e772018-04-03 00:11:50 +00005717 const auto *ATy = dyn_cast<ArrayType>(split.Ty);
Craig Topper36250ad2014-05-12 05:36:57 +00005718 if (!ATy || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00005719 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00005720
Chris Lattner7adf0762008-08-04 07:31:14 +00005721 // Otherwise, we have an array and we have qualifiers on it. Push the
5722 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00005723 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00005724
Eugene Zelenko7855e772018-04-03 00:11:50 +00005725 if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy))
Chris Lattner7adf0762008-08-04 07:31:14 +00005726 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
Richard Smith772e2662019-10-04 01:25:59 +00005727 CAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00005728 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00005729 CAT->getIndexTypeCVRQualifiers()));
Eugene Zelenko7855e772018-04-03 00:11:50 +00005730 if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy))
Chris Lattner7adf0762008-08-04 07:31:14 +00005731 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
5732 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00005733 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00005734
Eugene Zelenko7855e772018-04-03 00:11:50 +00005735 if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy))
Douglas Gregor4619e432008-12-05 23:32:09 +00005736 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00005737 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00005738 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00005739 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00005740 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00005741 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00005742
Eugene Zelenko7855e772018-04-03 00:11:50 +00005743 const auto *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00005744 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00005745 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00005746 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00005747 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00005748 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00005749}
5750
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00005751QualType ASTContext::getAdjustedParameterType(QualType T) const {
Reid Kleckner8a365022013-06-24 17:51:48 +00005752 if (T->isArrayType() || T->isFunctionType())
5753 return getDecayedType(T);
5754 return T;
Douglas Gregor84280642011-07-12 04:42:08 +00005755}
5756
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00005757QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00005758 T = getVariableArrayDecayedType(T);
5759 T = getAdjustedParameterType(T);
5760 return T.getUnqualifiedType();
5761}
5762
David Majnemerd09a51c2015-03-03 01:50:05 +00005763QualType ASTContext::getExceptionObjectType(QualType T) const {
5764 // C++ [except.throw]p3:
5765 // A throw-expression initializes a temporary object, called the exception
5766 // object, the type of which is determined by removing any top-level
5767 // cv-qualifiers from the static type of the operand of throw and adjusting
5768 // the type from "array of T" or "function returning T" to "pointer to T"
5769 // or "pointer to function returning T", [...]
5770 T = getVariableArrayDecayedType(T);
5771 if (T->isArrayType() || T->isFunctionType())
5772 T = getDecayedType(T);
5773 return T.getUnqualifiedType();
5774}
5775
Chris Lattnera21ad802008-04-02 05:18:44 +00005776/// getArrayDecayedType - Return the properly qualified result of decaying the
5777/// specified array type to a pointer. This operation is non-trivial when
5778/// handling typedefs etc. The canonical type of "T" must be an array type,
5779/// this returns a pointer to a properly qualified element of the array.
5780///
5781/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00005782QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00005783 // Get the element type with 'getAsArrayType' so that we don't lose any
5784 // typedefs in the element type of the array. This also handles propagation
5785 // of type qualifiers from the array type into the element type if present
5786 // (C99 6.7.3p8).
5787 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
5788 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00005789
Chris Lattner7adf0762008-08-04 07:31:14 +00005790 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00005791
5792 // int x[restrict 4] -> int *restrict
Jordan Rose303e2f12016-11-10 23:28:17 +00005793 QualType Result = getQualifiedType(PtrTy,
5794 PrettyArrayType->getIndexTypeQualifiers());
5795
5796 // int x[_Nullable] -> int * _Nullable
5797 if (auto Nullability = Ty->getNullability(*this)) {
5798 Result = const_cast<ASTContext *>(this)->getAttributedType(
5799 AttributedType::getNullabilityAttrKind(*Nullability), Result, Result);
5800 }
5801 return Result;
Chris Lattnera21ad802008-04-02 05:18:44 +00005802}
5803
John McCall33ddac02011-01-19 10:06:00 +00005804QualType ASTContext::getBaseElementType(const ArrayType *array) const {
5805 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00005806}
5807
John McCall33ddac02011-01-19 10:06:00 +00005808QualType ASTContext::getBaseElementType(QualType type) const {
5809 Qualifiers qs;
5810 while (true) {
5811 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00005812 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00005813 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00005814
John McCall33ddac02011-01-19 10:06:00 +00005815 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00005816 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00005817 }
Mike Stump11289f42009-09-09 15:08:12 +00005818
John McCall33ddac02011-01-19 10:06:00 +00005819 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00005820}
5821
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00005822/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00005823uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00005824ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
5825 uint64_t ElementCount = 1;
5826 do {
5827 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00005828 CA = dyn_cast_or_null<ConstantArrayType>(
5829 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00005830 } while (CA);
5831 return ElementCount;
5832}
5833
Steve Naroff0af91202007-04-27 21:51:21 +00005834/// getFloatingRank - Return a relative rank for floating point types.
5835/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00005836static FloatingRank getFloatingRank(QualType T) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00005837 if (const auto *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00005838 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00005839
Simon Pilgrimeed4b122019-10-02 11:48:06 +00005840 switch (T->castAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00005841 default: llvm_unreachable("getFloatingRank(): not a floating type");
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00005842 case BuiltinType::Float16: return Float16Rank;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00005843 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00005844 case BuiltinType::Float: return FloatRank;
5845 case BuiltinType::Double: return DoubleRank;
5846 case BuiltinType::LongDouble: return LongDoubleRank;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005847 case BuiltinType::Float128: return Float128Rank;
Steve Naroffe4718892007-04-27 18:30:00 +00005848 }
5849}
5850
Mike Stump11289f42009-09-09 15:08:12 +00005851/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
5852/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00005853/// 'typeDomain' is a real floating point or complex type.
5854/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00005855QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
5856 QualType Domain) const {
5857 FloatingRank EltRank = getFloatingRank(Size);
5858 if (Domain->isComplexType()) {
5859 switch (EltRank) {
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00005860 case Float16Rank:
David Blaikief47fa302012-01-17 02:30:50 +00005861 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00005862 case FloatRank: return FloatComplexTy;
5863 case DoubleRank: return DoubleComplexTy;
5864 case LongDoubleRank: return LongDoubleComplexTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005865 case Float128Rank: return Float128ComplexTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00005866 }
Steve Naroff0af91202007-04-27 21:51:21 +00005867 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00005868
5869 assert(Domain->isRealFloatingType() && "Unknown domain!");
5870 switch (EltRank) {
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00005871 case Float16Rank: return HalfTy;
Joey Goulydd7f4562013-01-23 11:56:20 +00005872 case HalfRank: return HalfTy;
Chris Lattnerb9dfb032008-04-06 23:58:54 +00005873 case FloatRank: return FloatTy;
5874 case DoubleRank: return DoubleTy;
5875 case LongDoubleRank: return LongDoubleTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005876 case Float128Rank: return Float128Ty;
Steve Naroff9091ef72007-08-27 01:27:54 +00005877 }
David Blaikief47fa302012-01-17 02:30:50 +00005878 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00005879}
5880
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005881/// getFloatingTypeOrder - Compare the rank of the two specified floating
5882/// point types, ignoring the domain of the type (i.e. 'double' ==
5883/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00005884/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00005885int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00005886 FloatingRank LHSR = getFloatingRank(LHS);
5887 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00005888
Chris Lattnerb90739d2008-04-06 23:38:49 +00005889 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00005890 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00005891 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00005892 return 1;
5893 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00005894}
5895
Erik Pilkingtoneac7c3f2019-02-16 01:11:47 +00005896int ASTContext::getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const {
5897 if (&getFloatTypeSemantics(LHS) == &getFloatTypeSemantics(RHS))
5898 return 0;
5899 return getFloatingTypeOrder(LHS, RHS);
5900}
5901
Chris Lattner76a00cf2008-04-06 22:59:24 +00005902/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
5903/// routine will assert if passed a built-in type that isn't an integer or enum,
5904/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00005905unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00005906 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00005907
Chris Lattner76a00cf2008-04-06 22:59:24 +00005908 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00005909 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005910 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005911 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005912 case BuiltinType::Char_S:
5913 case BuiltinType::Char_U:
5914 case BuiltinType::SChar:
5915 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005916 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005917 case BuiltinType::Short:
5918 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005919 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005920 case BuiltinType::Int:
5921 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005922 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005923 case BuiltinType::Long:
5924 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005925 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005926 case BuiltinType::LongLong:
5927 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005928 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00005929 case BuiltinType::Int128:
5930 case BuiltinType::UInt128:
5931 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00005932 }
5933}
5934
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005935/// Whether this is a promotable bitfield reference according
Eli Friedman629ffb92009-08-20 04:21:42 +00005936/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
5937///
5938/// \returns the type this bit-field will promote to, or NULL if no
5939/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00005940QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00005941 if (E->isTypeDependent() || E->isValueDependent())
Eugene Zelenko7855e772018-04-03 00:11:50 +00005942 return {};
Richard Smith5b571672014-09-24 23:55:00 +00005943
Richard Smithaadb2542018-06-28 21:17:55 +00005944 // C++ [conv.prom]p5:
5945 // If the bit-field has an enumerated type, it is treated as any other
5946 // value of that type for promotion purposes.
5947 if (getLangOpts().CPlusPlus && E->getType()->isEnumeralType())
5948 return {};
5949
Richard Smith5b571672014-09-24 23:55:00 +00005950 // FIXME: We should not do this unless E->refersToBitField() is true. This
5951 // matters in C where getSourceBitField() will find bit-fields for various
5952 // cases where the source expression is not a bit-field designator.
5953
John McCalld25db7e2013-05-06 21:39:12 +00005954 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman629ffb92009-08-20 04:21:42 +00005955 if (!Field)
Eugene Zelenko7855e772018-04-03 00:11:50 +00005956 return {};
Eli Friedman629ffb92009-08-20 04:21:42 +00005957
5958 QualType FT = Field->getType();
5959
Richard Smithcaf33902011-10-10 18:28:20 +00005960 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00005961 uint64_t IntSize = getTypeSize(IntTy);
Richard Smith5b571672014-09-24 23:55:00 +00005962 // C++ [conv.prom]p5:
5963 // A prvalue for an integral bit-field can be converted to a prvalue of type
5964 // int if int can represent all the values of the bit-field; otherwise, it
5965 // can be converted to unsigned int if unsigned int can represent all the
5966 // values of the bit-field. If the bit-field is larger yet, no integral
5967 // promotion applies to it.
5968 // C11 6.3.1.1/2:
5969 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
5970 // If an int can represent all values of the original type (as restricted by
5971 // the width, for a bit-field), the value is converted to an int; otherwise,
5972 // it is converted to an unsigned int.
5973 //
5974 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
5975 // We perform that promotion here to match GCC and C++.
Richard Smithaadb2542018-06-28 21:17:55 +00005976 // FIXME: C does not permit promotion of an enum bit-field whose rank is
5977 // greater than that of 'int'. We perform that promotion to match GCC.
Eli Friedman629ffb92009-08-20 04:21:42 +00005978 if (BitWidth < IntSize)
5979 return IntTy;
5980
5981 if (BitWidth == IntSize)
5982 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
5983
Richard Smithaadb2542018-06-28 21:17:55 +00005984 // Bit-fields wider than int are not subject to promotions, and therefore act
Richard Smith5b571672014-09-24 23:55:00 +00005985 // like the base type. GCC has some weird bugs in this area that we
5986 // deliberately do not follow (GCC follows a pre-standard resolution to
5987 // C's DR315 which treats bit-width as being part of the type, and this leaks
5988 // into their semantics in some cases).
Eugene Zelenko7855e772018-04-03 00:11:50 +00005989 return {};
Eli Friedman629ffb92009-08-20 04:21:42 +00005990}
5991
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005992/// getPromotedIntegerType - Returns the type that Promotable will
5993/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
5994/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00005995QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005996 assert(!Promotable.isNull());
5997 assert(Promotable->isPromotableIntegerType());
Eugene Zelenko7855e772018-04-03 00:11:50 +00005998 if (const auto *ET = Promotable->getAs<EnumType>())
John McCall56774992009-12-09 09:09:27 +00005999 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00006000
Eugene Zelenko7855e772018-04-03 00:11:50 +00006001 if (const auto *BT = Promotable->getAs<BuiltinType>()) {
Eli Friedman3f37c1c2011-10-26 07:22:48 +00006002 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
6003 // (3.9.1) can be converted to a prvalue of the first of the following
6004 // types that can represent all the values of its underlying type:
6005 // int, unsigned int, long int, unsigned long int, long long int, or
6006 // unsigned long long int [...]
6007 // FIXME: Is there some better way to compute this?
6008 if (BT->getKind() == BuiltinType::WChar_S ||
6009 BT->getKind() == BuiltinType::WChar_U ||
Richard Smith3a8244d2018-05-01 05:02:45 +00006010 BT->getKind() == BuiltinType::Char8 ||
Eli Friedman3f37c1c2011-10-26 07:22:48 +00006011 BT->getKind() == BuiltinType::Char16 ||
6012 BT->getKind() == BuiltinType::Char32) {
6013 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
6014 uint64_t FromSize = getTypeSize(BT);
6015 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
6016 LongLongTy, UnsignedLongLongTy };
6017 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
6018 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
6019 if (FromSize < ToSize ||
6020 (FromSize == ToSize &&
6021 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
6022 return PromoteTypes[Idx];
6023 }
6024 llvm_unreachable("char type should fit into long long");
6025 }
6026 }
6027
6028 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00006029 if (Promotable->isSignedIntegerType())
6030 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00006031 uint64_t PromotableSize = getIntWidth(Promotable);
6032 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00006033 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
6034 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
6035}
6036
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006037/// Recurses in pointer/array types until it finds an objc retainable
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00006038/// type and returns its ownership.
6039Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
6040 while (!T.isNull()) {
6041 if (T.getObjCLifetime() != Qualifiers::OCL_None)
6042 return T.getObjCLifetime();
6043 if (T->isArrayType())
6044 T = getBaseElementType(T);
Eugene Zelenko7855e772018-04-03 00:11:50 +00006045 else if (const auto *PT = T->getAs<PointerType>())
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00006046 T = PT->getPointeeType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00006047 else if (const auto *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00006048 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00006049 else
6050 break;
6051 }
6052
6053 return Qualifiers::OCL_None;
6054}
6055
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00006056static const Type *getIntegerTypeForEnum(const EnumType *ET) {
6057 // Incomplete enum types are not treated as integer types.
6058 // FIXME: In C++, enum types are never integer types.
6059 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
6060 return ET->getDecl()->getIntegerType().getTypePtr();
Craig Topper36250ad2014-05-12 05:36:57 +00006061 return nullptr;
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00006062}
6063
Mike Stump11289f42009-09-09 15:08:12 +00006064/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00006065/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00006066/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00006067int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00006068 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
6069 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00006070
6071 // Unwrap enums to their underlying type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00006072 if (const auto *ET = dyn_cast<EnumType>(LHSC))
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00006073 LHSC = getIntegerTypeForEnum(ET);
Eugene Zelenko7855e772018-04-03 00:11:50 +00006074 if (const auto *ET = dyn_cast<EnumType>(RHSC))
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00006075 RHSC = getIntegerTypeForEnum(ET);
6076
Chris Lattnerd4bacd62008-04-06 23:55:33 +00006077 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00006078
Chris Lattner76a00cf2008-04-06 22:59:24 +00006079 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
6080 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00006081
Chris Lattnerd4bacd62008-04-06 23:55:33 +00006082 unsigned LHSRank = getIntegerRank(LHSC);
6083 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00006084
Chris Lattnerd4bacd62008-04-06 23:55:33 +00006085 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
6086 if (LHSRank == RHSRank) return 0;
6087 return LHSRank > RHSRank ? 1 : -1;
6088 }
Mike Stump11289f42009-09-09 15:08:12 +00006089
Chris Lattnerd4bacd62008-04-06 23:55:33 +00006090 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
6091 if (LHSUnsigned) {
6092 // If the unsigned [LHS] type is larger, return it.
6093 if (LHSRank >= RHSRank)
6094 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00006095
Chris Lattnerd4bacd62008-04-06 23:55:33 +00006096 // If the signed type can represent all values of the unsigned type, it
6097 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00006098 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00006099 return -1;
6100 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00006101
Chris Lattnerd4bacd62008-04-06 23:55:33 +00006102 // If the unsigned [RHS] type is larger, return it.
6103 if (RHSRank >= LHSRank)
6104 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00006105
Chris Lattnerd4bacd62008-04-06 23:55:33 +00006106 // If the signed type can represent all values of the unsigned type, it
6107 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00006108 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00006109 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00006110}
Anders Carlsson98f07902007-08-17 05:31:46 +00006111
Ben Langmuirf5416742016-02-04 00:55:24 +00006112TypedefDecl *ASTContext::getCFConstantStringDecl() const {
Saleem Abdulrasoolef9b88a2018-10-24 16:38:16 +00006113 if (CFConstantStringTypeDecl)
6114 return CFConstantStringTypeDecl;
Anders Carlsson6d417272009-11-14 21:45:58 +00006115
Saleem Abdulrasoolef9b88a2018-10-24 16:38:16 +00006116 assert(!CFConstantStringTagDecl &&
6117 "tag and typedef should be initialized together");
6118 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
6119 CFConstantStringTagDecl->startDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00006120
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00006121 struct {
6122 QualType Type;
6123 const char *Name;
6124 } Fields[5];
6125 unsigned Count = 0;
Mike Stump11289f42009-09-09 15:08:12 +00006126
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00006127 /// Objective-C ABI
6128 ///
6129 /// typedef struct __NSConstantString_tag {
Saleem Abdulrasool1f6c41f2018-10-27 06:12:52 +00006130 /// const int *isa;
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00006131 /// int flags;
6132 /// const char *str;
6133 /// long length;
6134 /// } __NSConstantString;
6135 ///
6136 /// Swift ABI (4.1, 4.2)
6137 ///
6138 /// typedef struct __NSConstantString_tag {
6139 /// uintptr_t _cfisa;
6140 /// uintptr_t _swift_rc;
6141 /// _Atomic(uint64_t) _cfinfoa;
6142 /// const char *_ptr;
6143 /// uint32_t _length;
6144 /// } __NSConstantString;
6145 ///
6146 /// Swift ABI (5.0)
6147 ///
6148 /// typedef struct __NSConstantString_tag {
6149 /// uintptr_t _cfisa;
6150 /// uintptr_t _swift_rc;
6151 /// _Atomic(uint64_t) _cfinfoa;
6152 /// const char *_ptr;
6153 /// uintptr_t _length;
6154 /// } __NSConstantString;
6155
6156 const auto CFRuntime = getLangOpts().CFRuntime;
6157 if (static_cast<unsigned>(CFRuntime) <
6158 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) {
6159 Fields[Count++] = { getPointerType(IntTy.withConst()), "isa" };
6160 Fields[Count++] = { IntTy, "flags" };
6161 Fields[Count++] = { getPointerType(CharTy.withConst()), "str" };
6162 Fields[Count++] = { LongTy, "length" };
6163 } else {
6164 Fields[Count++] = { getUIntPtrType(), "_cfisa" };
6165 Fields[Count++] = { getUIntPtrType(), "_swift_rc" };
6166 Fields[Count++] = { getFromTargetType(Target->getUInt64Type()), "_swift_rc" };
6167 Fields[Count++] = { getPointerType(CharTy.withConst()), "_ptr" };
6168 if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 ||
6169 CFRuntime == LangOptions::CoreFoundationABI::Swift4_2)
6170 Fields[Count++] = { IntTy, "_ptr" };
6171 else
6172 Fields[Count++] = { getUIntPtrType(), "_ptr" };
6173 }
Douglas Gregor91f84212008-12-11 16:49:14 +00006174
Saleem Abdulrasoolef9b88a2018-10-24 16:38:16 +00006175 // Create fields
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00006176 for (unsigned i = 0; i < Count; ++i) {
Saleem Abdulrasoolef9b88a2018-10-24 16:38:16 +00006177 FieldDecl *Field =
6178 FieldDecl::Create(*this, CFConstantStringTagDecl, SourceLocation(),
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00006179 SourceLocation(), &Idents.get(Fields[i].Name),
6180 Fields[i].Type, /*TInfo=*/nullptr,
Saleem Abdulrasoolef9b88a2018-10-24 16:38:16 +00006181 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
6182 Field->setAccess(AS_public);
6183 CFConstantStringTagDecl->addDecl(Field);
Anders Carlsson98f07902007-08-17 05:31:46 +00006184 }
Mike Stump11289f42009-09-09 15:08:12 +00006185
Saleem Abdulrasoolef9b88a2018-10-24 16:38:16 +00006186 CFConstantStringTagDecl->completeDefinition();
6187 // This type is designed to be compatible with NSConstantString, but cannot
6188 // use the same name, since NSConstantString is an interface.
6189 auto tagType = getTagDeclType(CFConstantStringTagDecl);
6190 CFConstantStringTypeDecl =
6191 buildImplicitTypedef(tagType, "__NSConstantString");
6192
Quentin Colombet043406b2016-02-03 22:41:00 +00006193 return CFConstantStringTypeDecl;
6194}
6195
Ben Langmuirf5416742016-02-04 00:55:24 +00006196RecordDecl *ASTContext::getCFConstantStringTagDecl() const {
6197 if (!CFConstantStringTagDecl)
6198 getCFConstantStringDecl(); // Build the tag and the typedef.
6199 return CFConstantStringTagDecl;
6200}
6201
Quentin Colombet043406b2016-02-03 22:41:00 +00006202// getCFConstantStringType - Return the type used for constant CFStrings.
6203QualType ASTContext::getCFConstantStringType() const {
Ben Langmuirf5416742016-02-04 00:55:24 +00006204 return getTypedefType(getCFConstantStringDecl());
Gabor Greif412af032007-09-11 15:32:40 +00006205}
Anders Carlsson87c149b2007-10-11 01:00:40 +00006206
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00006207QualType ASTContext::getObjCSuperType() const {
6208 if (ObjCSuperType.isNull()) {
Alp Toker2dea15b2013-12-17 01:22:38 +00006209 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00006210 TUDecl->addDecl(ObjCSuperTypeDecl);
6211 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
6212 }
6213 return ObjCSuperType;
6214}
6215
Douglas Gregor512b0772009-04-23 22:29:11 +00006216void ASTContext::setCFConstantStringType(QualType T) {
Simon Pilgrim9588ae72019-10-03 21:47:42 +00006217 const auto *TD = T->castAs<TypedefType>();
Ben Langmuirf5416742016-02-04 00:55:24 +00006218 CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl());
Eugene Zelenko7855e772018-04-03 00:11:50 +00006219 const auto *TagType =
Simon Pilgrim9588ae72019-10-03 21:47:42 +00006220 CFConstantStringTypeDecl->getUnderlyingType()->castAs<RecordType>();
Ben Langmuirf5416742016-02-04 00:55:24 +00006221 CFConstantStringTagDecl = TagType->getDecl();
Douglas Gregor512b0772009-04-23 22:29:11 +00006222}
6223
Jay Foad39c79802011-01-12 09:06:06 +00006224QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00006225 if (BlockDescriptorType)
6226 return getTagDeclType(BlockDescriptorType);
6227
Alp Toker2dea15b2013-12-17 01:22:38 +00006228 RecordDecl *RD;
Mike Stumpd0153282009-10-20 02:12:22 +00006229 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00006230 RD = buildImplicitRecord("__block_descriptor");
6231 RD->startDefinition();
6232
Mike Stumpd0153282009-10-20 02:12:22 +00006233 QualType FieldTypes[] = {
6234 UnsignedLongTy,
6235 UnsignedLongTy,
6236 };
6237
Craig Topperd6d31ac2013-07-15 08:24:27 +00006238 static const char *const FieldNames[] = {
Mike Stumpd0153282009-10-20 02:12:22 +00006239 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00006240 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00006241 };
6242
6243 for (size_t i = 0; i < 2; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00006244 FieldDecl *Field = FieldDecl::Create(
6245 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00006246 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
6247 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00006248 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00006249 RD->addDecl(Field);
Mike Stumpd0153282009-10-20 02:12:22 +00006250 }
6251
Alp Toker2dea15b2013-12-17 01:22:38 +00006252 RD->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00006253
Alp Toker2dea15b2013-12-17 01:22:38 +00006254 BlockDescriptorType = RD;
Mike Stumpd0153282009-10-20 02:12:22 +00006255
6256 return getTagDeclType(BlockDescriptorType);
6257}
6258
Jay Foad39c79802011-01-12 09:06:06 +00006259QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00006260 if (BlockDescriptorExtendedType)
6261 return getTagDeclType(BlockDescriptorExtendedType);
6262
Alp Toker2dea15b2013-12-17 01:22:38 +00006263 RecordDecl *RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00006264 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00006265 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
6266 RD->startDefinition();
6267
Mike Stumpe1b19ba2009-10-22 00:49:09 +00006268 QualType FieldTypes[] = {
6269 UnsignedLongTy,
6270 UnsignedLongTy,
6271 getPointerType(VoidPtrTy),
6272 getPointerType(VoidPtrTy)
6273 };
6274
Craig Topperd6d31ac2013-07-15 08:24:27 +00006275 static const char *const FieldNames[] = {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00006276 "reserved",
6277 "Size",
6278 "CopyFuncPtr",
6279 "DestroyFuncPtr"
6280 };
6281
6282 for (size_t i = 0; i < 4; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00006283 FieldDecl *Field = FieldDecl::Create(
6284 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00006285 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
6286 /*BitWidth=*/nullptr,
Alp Toker2dea15b2013-12-17 01:22:38 +00006287 /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00006288 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00006289 RD->addDecl(Field);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00006290 }
6291
Alp Toker2dea15b2013-12-17 01:22:38 +00006292 RD->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00006293
Alp Toker2dea15b2013-12-17 01:22:38 +00006294 BlockDescriptorExtendedType = RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00006295 return getTagDeclType(BlockDescriptorExtendedType);
6296}
6297
Reid Kleckner4c2a6562020-02-27 14:16:47 -08006298OpenCLTypeKind ASTContext::getOpenCLTypeKind(const Type *T) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006299 const auto *BT = dyn_cast<BuiltinType>(T);
Sven van Haastregt3bb7eaf2017-12-06 10:11:28 +00006300
6301 if (!BT) {
6302 if (isa<PipeType>(T))
Reid Kleckner4c2a6562020-02-27 14:16:47 -08006303 return OCLTK_Pipe;
Sven van Haastregt3bb7eaf2017-12-06 10:11:28 +00006304
Reid Kleckner4c2a6562020-02-27 14:16:47 -08006305 return OCLTK_Default;
Sven van Haastregt3bb7eaf2017-12-06 10:11:28 +00006306 }
6307
6308 switch (BT->getKind()) {
6309#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6310 case BuiltinType::Id: \
Reid Kleckner4c2a6562020-02-27 14:16:47 -08006311 return OCLTK_Image;
Sven van Haastregt3bb7eaf2017-12-06 10:11:28 +00006312#include "clang/Basic/OpenCLImageTypes.def"
6313
6314 case BuiltinType::OCLClkEvent:
Reid Kleckner4c2a6562020-02-27 14:16:47 -08006315 return OCLTK_ClkEvent;
Sven van Haastregt3bb7eaf2017-12-06 10:11:28 +00006316
6317 case BuiltinType::OCLEvent:
Reid Kleckner4c2a6562020-02-27 14:16:47 -08006318 return OCLTK_Event;
Sven van Haastregt3bb7eaf2017-12-06 10:11:28 +00006319
6320 case BuiltinType::OCLQueue:
Reid Kleckner4c2a6562020-02-27 14:16:47 -08006321 return OCLTK_Queue;
Sven van Haastregt3bb7eaf2017-12-06 10:11:28 +00006322
6323 case BuiltinType::OCLReserveID:
Reid Kleckner4c2a6562020-02-27 14:16:47 -08006324 return OCLTK_ReserveID;
Sven van Haastregt3bb7eaf2017-12-06 10:11:28 +00006325
6326 case BuiltinType::OCLSampler:
Reid Kleckner4c2a6562020-02-27 14:16:47 -08006327 return OCLTK_Sampler;
Sven van Haastregt3bb7eaf2017-12-06 10:11:28 +00006328
6329 default:
Reid Kleckner4c2a6562020-02-27 14:16:47 -08006330 return OCLTK_Default;
Sven van Haastregt3bb7eaf2017-12-06 10:11:28 +00006331 }
6332}
6333
6334LangAS ASTContext::getOpenCLTypeAddrSpace(const Type *T) const {
6335 return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
6336}
6337
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006338/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
6339/// requires copy/dispose. Note that this must match the logic
6340/// in buildByrefHelpers.
6341bool ASTContext::BlockRequiresCopying(QualType Ty,
6342 const VarDecl *D) {
6343 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
Akira Hatanaka9978da32018-08-10 15:09:24 +00006344 const Expr *copyExpr = getBlockVarCopyInit(D).getCopyExpr();
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006345 if (!copyExpr && record->hasTrivialDestructor()) return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00006346
Mike Stump94967902009-10-21 18:16:27 +00006347 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00006348 }
Fangrui Song6907ce22018-07-30 19:24:48 +00006349
Akira Hatanaka7275da02018-02-28 07:15:55 +00006350 // The block needs copy/destroy helpers if Ty is non-trivial to destructively
6351 // move or destroy.
6352 if (Ty.isNonTrivialToPrimitiveDestructiveMove() || Ty.isDestructedType())
6353 return true;
6354
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006355 if (!Ty->isObjCRetainableType()) return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00006356
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006357 Qualifiers qs = Ty.getQualifiers();
Fangrui Song6907ce22018-07-30 19:24:48 +00006358
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006359 // If we have lifetime, that dominates.
6360 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006361 switch (lifetime) {
6362 case Qualifiers::OCL_None: llvm_unreachable("impossible");
Fangrui Song6907ce22018-07-30 19:24:48 +00006363
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006364 // These are just bits as far as the runtime is concerned.
6365 case Qualifiers::OCL_ExplicitNone:
6366 case Qualifiers::OCL_Autoreleasing:
6367 return false;
Akira Hatanaka7275da02018-02-28 07:15:55 +00006368
6369 // These cases should have been taken care of when checking the type's
6370 // non-triviality.
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006371 case Qualifiers::OCL_Weak:
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006372 case Qualifiers::OCL_Strong:
Akira Hatanaka7275da02018-02-28 07:15:55 +00006373 llvm_unreachable("impossible");
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006374 }
6375 llvm_unreachable("fell out of lifetime switch!");
6376 }
6377 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
6378 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00006379}
6380
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006381bool ASTContext::getByrefLifetime(QualType Ty,
6382 Qualifiers::ObjCLifetime &LifeTime,
6383 bool &HasByrefExtendedLayout) const {
Erik Pilkingtonfa983902018-10-30 20:31:30 +00006384 if (!getLangOpts().ObjC ||
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006385 getLangOpts().getGC() != LangOptions::NonGC)
6386 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00006387
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006388 HasByrefExtendedLayout = false;
Fariborz Jahanianf762b722012-12-11 19:58:01 +00006389 if (Ty->isRecordType()) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006390 HasByrefExtendedLayout = true;
6391 LifeTime = Qualifiers::OCL_None;
John McCall460ce582015-10-22 18:38:17 +00006392 } else if ((LifeTime = Ty.getObjCLifetime())) {
6393 // Honor the ARC qualifiers.
6394 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
6395 // The MRR rule.
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006396 LifeTime = Qualifiers::OCL_ExplicitNone;
John McCall460ce582015-10-22 18:38:17 +00006397 } else {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006398 LifeTime = Qualifiers::OCL_None;
John McCall460ce582015-10-22 18:38:17 +00006399 }
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006400 return true;
6401}
6402
Reid Kleckner4c2a6562020-02-27 14:16:47 -08006403CanQualType ASTContext::getNSUIntegerType() const {
6404 assert(Target && "Expected target to be initialized");
6405 const llvm::Triple &T = Target->getTriple();
6406 // Windows is LLP64 rather than LP64
6407 if (T.isOSWindows() && T.isArch64Bit())
6408 return UnsignedLongLongTy;
6409 return UnsignedLongTy;
6410}
6411
6412CanQualType ASTContext::getNSIntegerType() const {
6413 assert(Target && "Expected target to be initialized");
6414 const llvm::Triple &T = Target->getTriple();
6415 // Windows is LLP64 rather than LP64
6416 if (T.isOSWindows() && T.isArch64Bit())
6417 return LongLongTy;
6418 return LongTy;
6419}
6420
Douglas Gregorbab8a962011-09-08 01:46:34 +00006421TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
6422 if (!ObjCInstanceTypeDecl)
Alp Toker56b5cc92013-12-15 10:36:26 +00006423 ObjCInstanceTypeDecl =
6424 buildImplicitTypedef(getObjCIdType(), "instancetype");
Douglas Gregorbab8a962011-09-08 01:46:34 +00006425 return ObjCInstanceTypeDecl;
6426}
6427
Anders Carlsson18acd442007-10-29 06:33:42 +00006428// This returns true if a type has been typedefed to BOOL:
6429// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00006430static bool isTypeTypedefedAsBOOL(QualType T) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006431 if (const auto *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00006432 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
6433 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00006434
Anders Carlssond8499822007-10-29 05:01:08 +00006435 return false;
6436}
6437
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006438/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006439/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00006440CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00006441 if (!type->isIncompleteArrayType() && type->isIncompleteType())
6442 return CharUnits::Zero();
Fangrui Song6907ce22018-07-30 19:24:48 +00006443
Ken Dyck40775002010-01-11 17:06:35 +00006444 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00006445
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006446 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00006447 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00006448 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006449 // Treat arrays as pointers, since that's how they're passed in.
6450 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00006451 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00006452 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00006453}
6454
Hans Wennborg56fc62b2014-07-17 20:25:23 +00006455bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
David Majnemer3f021502015-10-08 04:53:31 +00006456 return getTargetInfo().getCXXABI().isMicrosoft() &&
6457 VD->isStaticDataMember() &&
Hans Wennborgb18da9b2018-02-20 12:43:02 +00006458 VD->getType()->isIntegralOrEnumerationType() &&
David Majnemerfac52432015-10-19 23:22:49 +00006459 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
Hans Wennborg56fc62b2014-07-17 20:25:23 +00006460}
6461
Richard Smithd9b90092016-07-02 01:32:16 +00006462ASTContext::InlineVariableDefinitionKind
6463ASTContext::getInlineVariableDefinitionKind(const VarDecl *VD) const {
6464 if (!VD->isInline())
6465 return InlineVariableDefinitionKind::None;
6466
6467 // In almost all cases, it's a weak definition.
6468 auto *First = VD->getFirstDecl();
Richard Smith8910fe62017-10-23 03:58:34 +00006469 if (First->isInlineSpecified() || !First->isStaticDataMember())
Richard Smithd9b90092016-07-02 01:32:16 +00006470 return InlineVariableDefinitionKind::Weak;
6471
6472 // If there's a file-context declaration in this translation unit, it's a
6473 // non-discardable definition.
6474 for (auto *D : VD->redecls())
Richard Smith8910fe62017-10-23 03:58:34 +00006475 if (D->getLexicalDeclContext()->isFileContext() &&
6476 !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr()))
Richard Smithd9b90092016-07-02 01:32:16 +00006477 return InlineVariableDefinitionKind::Strong;
6478
6479 // If we've not seen one yet, we don't know.
6480 return InlineVariableDefinitionKind::WeakUnknown;
6481}
6482
Eugene Zelenko7855e772018-04-03 00:11:50 +00006483static std::string charUnitsToString(const CharUnits &CU) {
Ken Dyck40775002010-01-11 17:06:35 +00006484 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006485}
6486
John McCall351762c2011-02-07 10:33:21 +00006487/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00006488/// declaration.
John McCall351762c2011-02-07 10:33:21 +00006489std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
6490 std::string S;
6491
David Chisnall950a9512009-11-17 19:33:30 +00006492 const BlockDecl *Decl = Expr->getBlockDecl();
6493 QualType BlockTy =
Simon Pilgrimeed4b122019-10-02 11:48:06 +00006494 Expr->getType()->castAs<BlockPointerType>()->getPointeeType();
6495 QualType BlockReturnTy = BlockTy->castAs<FunctionType>()->getReturnType();
David Chisnall950a9512009-11-17 19:33:30 +00006496 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00006497 if (getLangOpts().EncodeExtendedBlockSig)
Simon Pilgrimeed4b122019-10-02 11:48:06 +00006498 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, BlockReturnTy, S,
6499 true /*Extended*/);
Fariborz Jahanian64223e62012-11-14 23:11:38 +00006500 else
Simon Pilgrimeed4b122019-10-02 11:48:06 +00006501 getObjCEncodingForType(BlockReturnTy, S);
David Chisnall950a9512009-11-17 19:33:30 +00006502 // Compute size of all parameters.
6503 // Start with computing size of a pointer in number of bytes.
6504 // FIXME: There might(should) be a better way of doing this computation!
Ken Dyck40775002010-01-11 17:06:35 +00006505 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
6506 CharUnits ParmOffset = PtrSize;
David Majnemer59f77922016-06-24 04:05:48 +00006507 for (auto PI : Decl->parameters()) {
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00006508 QualType PType = PI->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00006509 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00006510 if (sz.isZero())
6511 continue;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00006512 assert(sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00006513 ParmOffset += sz;
6514 }
6515 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00006516 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00006517 // Block pointer and offset.
6518 S += "@?0";
Fangrui Song6907ce22018-07-30 19:24:48 +00006519
David Chisnall950a9512009-11-17 19:33:30 +00006520 // Argument types.
6521 ParmOffset = PtrSize;
David Majnemer59f77922016-06-24 04:05:48 +00006522 for (auto PVDecl : Decl->parameters()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00006523 QualType PType = PVDecl->getOriginalType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00006524 if (const auto *AT =
6525 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
David Chisnall950a9512009-11-17 19:33:30 +00006526 // Use array's original type only if it has known number of
6527 // elements.
6528 if (!isa<ConstantArrayType>(AT))
6529 PType = PVDecl->getType();
6530 } else if (PType->isFunctionType())
6531 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00006532 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00006533 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
6534 S, true /*Extended*/);
6535 else
6536 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00006537 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00006538 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00006539 }
John McCall351762c2011-02-07 10:33:21 +00006540
6541 return S;
David Chisnall950a9512009-11-17 19:33:30 +00006542}
6543
John McCall843dfcc2016-11-29 21:57:00 +00006544std::string
6545ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const {
6546 std::string S;
David Chisnall50e4eba2010-12-30 14:05:53 +00006547 // Encode result type.
Alp Toker314cc812014-01-25 16:55:45 +00006548 getObjCEncodingForType(Decl->getReturnType(), S);
David Chisnall50e4eba2010-12-30 14:05:53 +00006549 CharUnits ParmOffset;
6550 // Compute size of all parameters.
David Majnemer59f77922016-06-24 04:05:48 +00006551 for (auto PI : Decl->parameters()) {
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00006552 QualType PType = PI->getType();
David Chisnall50e4eba2010-12-30 14:05:53 +00006553 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00006554 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00006555 continue;
Fangrui Song6907ce22018-07-30 19:24:48 +00006556
6557 assert(sz.isPositive() &&
John McCall843dfcc2016-11-29 21:57:00 +00006558 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00006559 ParmOffset += sz;
6560 }
6561 S += charUnitsToString(ParmOffset);
6562 ParmOffset = CharUnits::Zero();
6563
6564 // Argument types.
David Majnemer59f77922016-06-24 04:05:48 +00006565 for (auto PVDecl : Decl->parameters()) {
David Chisnall50e4eba2010-12-30 14:05:53 +00006566 QualType PType = PVDecl->getOriginalType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00006567 if (const auto *AT =
6568 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
David Chisnall50e4eba2010-12-30 14:05:53 +00006569 // Use array's original type only if it has known number of
6570 // elements.
6571 if (!isa<ConstantArrayType>(AT))
6572 PType = PVDecl->getType();
6573 } else if (PType->isFunctionType())
6574 PType = PVDecl->getType();
6575 getObjCEncodingForType(PType, S);
6576 S += charUnitsToString(ParmOffset);
6577 ParmOffset += getObjCEncodingTypeSize(PType);
6578 }
Fangrui Song6907ce22018-07-30 19:24:48 +00006579
John McCall843dfcc2016-11-29 21:57:00 +00006580 return S;
David Chisnall50e4eba2010-12-30 14:05:53 +00006581}
6582
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006583/// getObjCEncodingForMethodParameter - Return the encoded type for a single
Fangrui Song6907ce22018-07-30 19:24:48 +00006584/// method parameter or return type. If Extended, include class names and
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006585/// block object types.
6586void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
6587 QualType T, std::string& S,
6588 bool Extended) const {
6589 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
6590 getObjCEncodingForTypeQualifier(QT, S);
6591 // Encode parameter type.
Nico Weber2e9591c2019-05-14 12:32:37 +00006592 ObjCEncOptions Options = ObjCEncOptions()
6593 .setExpandPointedToStructures()
6594 .setExpandStructures()
6595 .setIsOutermostType();
6596 if (Extended)
6597 Options.setEncodeBlockParameters().setEncodeClassNames();
6598 getObjCEncodingForTypeImpl(T, S, Options, /*Field=*/nullptr);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006599}
6600
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006601/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006602/// declaration.
John McCall843dfcc2016-11-29 21:57:00 +00006603std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
6604 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00006605 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006606 // Encode return type.
John McCall843dfcc2016-11-29 21:57:00 +00006607 std::string S;
Alp Toker314cc812014-01-25 16:55:45 +00006608 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
6609 Decl->getReturnType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006610 // Compute size of all parameters.
6611 // Start with computing size of a pointer in number of bytes.
6612 // FIXME: There might(should) be a better way of doing this computation!
Ken Dyck40775002010-01-11 17:06:35 +00006613 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006614 // The first two arguments (self and _cmd) are pointers; account for
6615 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00006616 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00006617 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00006618 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00006619 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00006620 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00006621 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00006622 continue;
Fangrui Song6907ce22018-07-30 19:24:48 +00006623
6624 assert(sz.isPositive() &&
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00006625 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006626 ParmOffset += sz;
6627 }
Ken Dyck40775002010-01-11 17:06:35 +00006628 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006629 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00006630 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00006631
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006632 // Argument types.
6633 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00006634 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00006635 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00006636 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00006637 QualType PType = PVDecl->getOriginalType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00006638 if (const auto *AT =
6639 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
Steve Naroffe4e55d22009-04-14 00:03:58 +00006640 // Use array's original type only if it has known number of
6641 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00006642 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00006643 PType = PVDecl->getType();
6644 } else if (PType->isFunctionType())
6645 PType = PVDecl->getType();
Fangrui Song6907ce22018-07-30 19:24:48 +00006646 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006647 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00006648 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00006649 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006650 }
Fangrui Song6907ce22018-07-30 19:24:48 +00006651
John McCall843dfcc2016-11-29 21:57:00 +00006652 return S;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006653}
6654
Fariborz Jahaniandad96302014-01-22 19:02:20 +00006655ObjCPropertyImplDecl *
6656ASTContext::getObjCPropertyImplDeclForPropertyDecl(
6657 const ObjCPropertyDecl *PD,
6658 const Decl *Container) const {
6659 if (!Container)
Craig Topper36250ad2014-05-12 05:36:57 +00006660 return nullptr;
Eugene Zelenko7855e772018-04-03 00:11:50 +00006661 if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) {
Aaron Ballmand85eff42014-03-14 15:02:45 +00006662 for (auto *PID : CID->property_impls())
6663 if (PID->getPropertyDecl() == PD)
6664 return PID;
Craig Topper36250ad2014-05-12 05:36:57 +00006665 } else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006666 const auto *OID = cast<ObjCImplementationDecl>(Container);
Craig Topper36250ad2014-05-12 05:36:57 +00006667 for (auto *PID : OID->property_impls())
6668 if (PID->getPropertyDecl() == PD)
6669 return PID;
6670 }
6671 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00006672}
6673
Daniel Dunbar4932b362008-08-28 04:38:10 +00006674/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00006675/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00006676/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
6677/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00006678/// Property attributes are stored as a comma-delimited C string. The simple
6679/// attributes readonly and bycopy are encoded as single characters. The
6680/// parametrized attributes, getter=name, setter=name, and ivar=name, are
6681/// encoded as single characters, followed by an identifier. Property types
6682/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00006683/// these attributes are defined by the following enumeration:
6684/// @code
6685/// enum PropertyAttributes {
6686/// kPropertyReadOnly = 'R', // property is read-only.
6687/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
6688/// kPropertyByref = '&', // property is a reference to the value last assigned
6689/// kPropertyDynamic = 'D', // property is dynamic
6690/// kPropertyGetter = 'G', // followed by getter selector name
6691/// kPropertySetter = 'S', // followed by setter selector name
6692/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00006693/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00006694/// kPropertyWeak = 'W' // 'weak' property
6695/// kPropertyStrong = 'P' // property GC'able
6696/// kPropertyNonAtomic = 'N' // property non-atomic
6697/// };
6698/// @endcode
John McCall843dfcc2016-11-29 21:57:00 +00006699std::string
6700ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
6701 const Decl *Container) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00006702 // Collect information from the property implementation decl(s).
6703 bool Dynamic = false;
Craig Topper36250ad2014-05-12 05:36:57 +00006704 ObjCPropertyImplDecl *SynthesizePID = nullptr;
Daniel Dunbar4932b362008-08-28 04:38:10 +00006705
Fariborz Jahaniandad96302014-01-22 19:02:20 +00006706 if (ObjCPropertyImplDecl *PropertyImpDecl =
6707 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
6708 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
6709 Dynamic = true;
6710 else
6711 SynthesizePID = PropertyImpDecl;
Daniel Dunbar4932b362008-08-28 04:38:10 +00006712 }
6713
6714 // FIXME: This is not very efficient.
John McCall843dfcc2016-11-29 21:57:00 +00006715 std::string S = "T";
Daniel Dunbar4932b362008-08-28 04:38:10 +00006716
6717 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00006718 // GCC has some special rules regarding encoding of properties which
6719 // closely resembles encoding of ivars.
Joe Groff98ac7d22014-07-07 22:25:15 +00006720 getObjCEncodingForPropertyType(PD->getType(), S);
Daniel Dunbar4932b362008-08-28 04:38:10 +00006721
6722 if (PD->isReadOnly()) {
6723 S += ",R";
Nico Weber4e8626f2013-05-08 23:47:40 +00006724 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
6725 S += ",C";
6726 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
6727 S += ",&";
Fariborz Jahanian33079ee2014-04-02 22:49:42 +00006728 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
6729 S += ",W";
Daniel Dunbar4932b362008-08-28 04:38:10 +00006730 } else {
6731 switch (PD->getSetterKind()) {
6732 case ObjCPropertyDecl::Assign: break;
6733 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00006734 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00006735 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00006736 }
6737 }
6738
6739 // It really isn't clear at all what this means, since properties
6740 // are "dynamic by default".
6741 if (Dynamic)
6742 S += ",D";
6743
Fariborz Jahanian218c6302009-01-20 19:14:18 +00006744 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
6745 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00006746
Daniel Dunbar4932b362008-08-28 04:38:10 +00006747 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
6748 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00006749 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00006750 }
6751
6752 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
6753 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00006754 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00006755 }
6756
6757 if (SynthesizePID) {
6758 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
6759 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00006760 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00006761 }
6762
6763 // FIXME: OBJCGC: weak & strong
John McCall843dfcc2016-11-29 21:57:00 +00006764 return S;
Daniel Dunbar4932b362008-08-28 04:38:10 +00006765}
6766
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006767/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00006768/// Another legacy compatibility encoding: 32-bit longs are encoded as
6769/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006770/// 'i' or 'I' instead if encoding a struct field, or a pointer!
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006771void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00006772 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006773 if (const auto *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00006774 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006775 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00006776 else
Jay Foad39c79802011-01-12 09:06:06 +00006777 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006778 PointeeTy = IntTy;
6779 }
6780 }
6781}
6782
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00006783void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006784 const FieldDecl *Field,
6785 QualType *NotEncodedT) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00006786 // We follow the behavior of gcc, expanding structures which are
6787 // directly pointed to, and expanding embedded structures. Note that
6788 // these rules are sufficient to prevent recursive encoding of the
6789 // same type.
Nico Weber2e9591c2019-05-14 12:32:37 +00006790 getObjCEncodingForTypeImpl(T, S,
6791 ObjCEncOptions()
6792 .setExpandPointedToStructures()
6793 .setExpandStructures()
6794 .setIsOutermostType(),
6795 Field, NotEncodedT);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00006796}
6797
Joe Groff98ac7d22014-07-07 22:25:15 +00006798void ASTContext::getObjCEncodingForPropertyType(QualType T,
6799 std::string& S) const {
6800 // Encode result type.
6801 // GCC has some special rules regarding encoding of properties which
6802 // closely resembles encoding of ivars.
Nico Weber2e9591c2019-05-14 12:32:37 +00006803 getObjCEncodingForTypeImpl(T, S,
6804 ObjCEncOptions()
6805 .setExpandPointedToStructures()
6806 .setExpandStructures()
6807 .setIsOutermostType()
6808 .setEncodingProperty(),
6809 /*Field=*/nullptr);
Joe Groff98ac7d22014-07-07 22:25:15 +00006810}
6811
Richard Sandifordeb485fb2019-08-09 08:52:54 +00006812static char getObjCEncodingForPrimitiveType(const ASTContext *C,
6813 const BuiltinType *BT) {
6814 BuiltinType::Kind kind = BT->getKind();
John McCall393a78d2012-12-20 02:45:14 +00006815 switch (kind) {
David Chisnallb190a2c2010-06-04 01:10:52 +00006816 case BuiltinType::Void: return 'v';
6817 case BuiltinType::Bool: return 'B';
Richard Smith3a8244d2018-05-01 05:02:45 +00006818 case BuiltinType::Char8:
David Chisnallb190a2c2010-06-04 01:10:52 +00006819 case BuiltinType::Char_U:
6820 case BuiltinType::UChar: return 'C';
John McCall393a78d2012-12-20 02:45:14 +00006821 case BuiltinType::Char16:
David Chisnallb190a2c2010-06-04 01:10:52 +00006822 case BuiltinType::UShort: return 'S';
John McCall393a78d2012-12-20 02:45:14 +00006823 case BuiltinType::Char32:
David Chisnallb190a2c2010-06-04 01:10:52 +00006824 case BuiltinType::UInt: return 'I';
6825 case BuiltinType::ULong:
John McCall393a78d2012-12-20 02:45:14 +00006826 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00006827 case BuiltinType::UInt128: return 'T';
6828 case BuiltinType::ULongLong: return 'Q';
6829 case BuiltinType::Char_S:
6830 case BuiltinType::SChar: return 'c';
6831 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00006832 case BuiltinType::WChar_S:
6833 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00006834 case BuiltinType::Int: return 'i';
6835 case BuiltinType::Long:
John McCall393a78d2012-12-20 02:45:14 +00006836 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00006837 case BuiltinType::LongLong: return 'q';
6838 case BuiltinType::Int128: return 't';
6839 case BuiltinType::Float: return 'f';
6840 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00006841 case BuiltinType::LongDouble: return 'D';
John McCall393a78d2012-12-20 02:45:14 +00006842 case BuiltinType::NullPtr: return '*'; // like char*
6843
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00006844 case BuiltinType::Float16:
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00006845 case BuiltinType::Float128:
John McCall393a78d2012-12-20 02:45:14 +00006846 case BuiltinType::Half:
Leonard Chanf921d852018-06-04 16:07:52 +00006847 case BuiltinType::ShortAccum:
6848 case BuiltinType::Accum:
6849 case BuiltinType::LongAccum:
6850 case BuiltinType::UShortAccum:
6851 case BuiltinType::UAccum:
6852 case BuiltinType::ULongAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00006853 case BuiltinType::ShortFract:
6854 case BuiltinType::Fract:
6855 case BuiltinType::LongFract:
6856 case BuiltinType::UShortFract:
6857 case BuiltinType::UFract:
6858 case BuiltinType::ULongFract:
6859 case BuiltinType::SatShortAccum:
6860 case BuiltinType::SatAccum:
6861 case BuiltinType::SatLongAccum:
6862 case BuiltinType::SatUShortAccum:
6863 case BuiltinType::SatUAccum:
6864 case BuiltinType::SatULongAccum:
6865 case BuiltinType::SatShortFract:
6866 case BuiltinType::SatFract:
6867 case BuiltinType::SatLongFract:
6868 case BuiltinType::SatUShortFract:
6869 case BuiltinType::SatUFract:
6870 case BuiltinType::SatULongFract:
John McCall393a78d2012-12-20 02:45:14 +00006871 // FIXME: potentially need @encodes for these!
6872 return ' ';
6873
Richard Sandifordeb485fb2019-08-09 08:52:54 +00006874#define SVE_TYPE(Name, Id, SingletonId) \
6875 case BuiltinType::Id:
6876#include "clang/Basic/AArch64SVEACLETypes.def"
6877 {
6878 DiagnosticsEngine &Diags = C->getDiagnostics();
6879 unsigned DiagID = Diags.getCustomDiagID(
6880 DiagnosticsEngine::Error, "cannot yet @encode type %0");
6881 Diags.Report(DiagID) << BT->getName(C->getPrintingPolicy());
6882 return ' ';
6883 }
6884
John McCall393a78d2012-12-20 02:45:14 +00006885 case BuiltinType::ObjCId:
6886 case BuiltinType::ObjCClass:
6887 case BuiltinType::ObjCSel:
6888 llvm_unreachable("@encoding ObjC primitive type");
6889
6890 // OpenCL and placeholder types don't need @encodings.
Alexey Bader954ba212016-04-08 13:40:33 +00006891#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6892 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00006893#include "clang/Basic/OpenCLImageTypes.def"
Andrew Savonichev3fee3512018-11-08 11:25:41 +00006894#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6895 case BuiltinType::Id:
6896#include "clang/Basic/OpenCLExtensionTypes.def"
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006897 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00006898 case BuiltinType::OCLClkEvent:
6899 case BuiltinType::OCLQueue:
Alexey Bader9c8453f2015-09-15 11:18:52 +00006900 case BuiltinType::OCLReserveID:
Guy Benyei61054192013-02-07 10:55:47 +00006901 case BuiltinType::OCLSampler:
John McCall393a78d2012-12-20 02:45:14 +00006902 case BuiltinType::Dependent:
6903#define BUILTIN_TYPE(KIND, ID)
6904#define PLACEHOLDER_TYPE(KIND, ID) \
6905 case BuiltinType::KIND:
6906#include "clang/AST/BuiltinTypes.def"
6907 llvm_unreachable("invalid builtin type for @encode");
David Chisnallb190a2c2010-06-04 01:10:52 +00006908 }
David Blaikie5a6a0202013-01-09 17:48:41 +00006909 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnallb190a2c2010-06-04 01:10:52 +00006910}
6911
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006912static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
6913 EnumDecl *Enum = ET->getDecl();
Fangrui Song6907ce22018-07-30 19:24:48 +00006914
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006915 // The encoding of an non-fixed enum type is always 'i', regardless of size.
6916 if (!Enum->isFixed())
6917 return 'i';
Fangrui Song6907ce22018-07-30 19:24:48 +00006918
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006919 // The encoding of a fixed enum type matches its fixed underlying type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00006920 const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>();
Richard Sandifordeb485fb2019-08-09 08:52:54 +00006921 return getObjCEncodingForPrimitiveType(C, BT);
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006922}
6923
Jay Foad39c79802011-01-12 09:06:06 +00006924static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00006925 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00006926 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00006927 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00006928 // The NeXT runtime encodes bit fields as b followed by the number of bits.
6929 // The GNU runtime requires more information; bitfields are encoded as b,
6930 // then the offset (in bits) of the first element, then the type of the
6931 // bitfield, then the size in bits. For example, in this structure:
6932 //
6933 // struct
6934 // {
6935 // int integer;
6936 // int flags:2;
6937 // };
6938 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
6939 // runtime, but b32i2 for the GNU runtime. The reason for this extra
6940 // information is not especially sensible, but we're stuck with it for
6941 // compatibility with GCC, although providing it breaks anything that
6942 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00006943 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
Akira Hatanaka4b1c4842017-06-27 04:34:04 +00006944 uint64_t Offset;
6945
6946 if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) {
6947 Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), nullptr,
6948 IVD);
6949 } else {
6950 const RecordDecl *RD = FD->getParent();
6951 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
6952 Offset = RL.getFieldOffset(FD->getFieldIndex());
6953 }
6954
6955 S += llvm::utostr(Offset);
6956
Eugene Zelenko7855e772018-04-03 00:11:50 +00006957 if (const auto *ET = T->getAs<EnumType>())
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006958 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall393a78d2012-12-20 02:45:14 +00006959 else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006960 const auto *BT = T->castAs<BuiltinType>();
Richard Sandifordeb485fb2019-08-09 08:52:54 +00006961 S += getObjCEncodingForPrimitiveType(Ctx, BT);
John McCall393a78d2012-12-20 02:45:14 +00006962 }
David Chisnallb190a2c2010-06-04 01:10:52 +00006963 }
Richard Smithcaf33902011-10-10 18:28:20 +00006964 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00006965}
6966
Daniel Dunbar07d07852009-10-18 21:17:35 +00006967// FIXME: Use SmallString for accumulating string.
Nico Weber2e9591c2019-05-14 12:32:37 +00006968void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S,
6969 const ObjCEncOptions Options,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00006970 const FieldDecl *FD,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006971 QualType *NotEncodedT) const {
John McCall393a78d2012-12-20 02:45:14 +00006972 CanQualType CT = getCanonicalType(T);
6973 switch (CT->getTypeClass()) {
6974 case Type::Builtin:
6975 case Type::Enum:
Chris Lattnere7cabb92009-07-13 00:10:46 +00006976 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00006977 return EncodeBitField(this, S, T, FD);
Eugene Zelenko7855e772018-04-03 00:11:50 +00006978 if (const auto *BT = dyn_cast<BuiltinType>(CT))
Richard Sandifordeb485fb2019-08-09 08:52:54 +00006979 S += getObjCEncodingForPrimitiveType(this, BT);
John McCall393a78d2012-12-20 02:45:14 +00006980 else
6981 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnere7cabb92009-07-13 00:10:46 +00006982 return;
Mike Stump11289f42009-09-09 15:08:12 +00006983
Simon Pilgrim02594172020-01-13 14:41:16 +00006984 case Type::Complex:
Anders Carlsson39b2e132009-04-09 21:55:45 +00006985 S += 'j';
Simon Pilgrim02594172020-01-13 14:41:16 +00006986 getObjCEncodingForTypeImpl(T->castAs<ComplexType>()->getElementType(), S,
6987 ObjCEncOptions(),
Nico Weber2e9591c2019-05-14 12:32:37 +00006988 /*Field=*/nullptr);
Chris Lattnere7cabb92009-07-13 00:10:46 +00006989 return;
John McCall393a78d2012-12-20 02:45:14 +00006990
Simon Pilgrim02594172020-01-13 14:41:16 +00006991 case Type::Atomic:
John McCall393a78d2012-12-20 02:45:14 +00006992 S += 'A';
Simon Pilgrim02594172020-01-13 14:41:16 +00006993 getObjCEncodingForTypeImpl(T->castAs<AtomicType>()->getValueType(), S,
6994 ObjCEncOptions(),
Nico Weber2e9591c2019-05-14 12:32:37 +00006995 /*Field=*/nullptr);
John McCall393a78d2012-12-20 02:45:14 +00006996 return;
John McCall393a78d2012-12-20 02:45:14 +00006997
6998 // encoding for pointer or reference types.
6999 case Type::Pointer:
7000 case Type::LValueReference:
7001 case Type::RValueReference: {
7002 QualType PointeeTy;
7003 if (isa<PointerType>(CT)) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00007004 const auto *PT = T->castAs<PointerType>();
John McCall393a78d2012-12-20 02:45:14 +00007005 if (PT->isObjCSelType()) {
7006 S += ':';
7007 return;
7008 }
7009 PointeeTy = PT->getPointeeType();
7010 } else {
7011 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
7012 }
7013
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00007014 bool isReadOnly = false;
7015 // For historical/compatibility reasons, the read-only qualifier of the
7016 // pointee gets emitted _before_ the '^'. The read-only qualifier of
7017 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00007018 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00007019 if (isa<TypedefType>(T.getTypePtr())) {
Nico Weber2e9591c2019-05-14 12:32:37 +00007020 if (Options.IsOutermostType() && T.isConstQualified()) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00007021 isReadOnly = true;
7022 S += 'r';
7023 }
Nico Weber2e9591c2019-05-14 12:32:37 +00007024 } else if (Options.IsOutermostType()) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00007025 QualType P = PointeeTy;
Simon Pilgrimd834f1f2019-10-03 15:08:20 +00007026 while (auto PT = P->getAs<PointerType>())
7027 P = PT->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00007028 if (P.isConstQualified()) {
7029 isReadOnly = true;
7030 S += 'r';
7031 }
7032 }
7033 if (isReadOnly) {
7034 // Another legacy compatibility encoding. Some ObjC qualifier and type
7035 // combinations need to be rearranged.
7036 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007037 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00007038 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00007039 }
Mike Stump11289f42009-09-09 15:08:12 +00007040
Anders Carlssond8499822007-10-29 05:01:08 +00007041 if (PointeeTy->isCharType()) {
7042 // char pointer types should be encoded as '*' unless it is a
7043 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00007044 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00007045 S += '*';
7046 return;
7047 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00007048 } else if (const auto *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00007049 // GCC binary compat: Need to convert "struct objc_class *" to "#".
7050 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
7051 S += '#';
7052 return;
7053 }
7054 // GCC binary compat: Need to convert "struct objc_object *" to "@".
7055 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
7056 S += '@';
7057 return;
7058 }
7059 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00007060 }
Anders Carlssond8499822007-10-29 05:01:08 +00007061 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00007062 getLegacyIntegralTypeEncoding(PointeeTy);
7063
Nico Weber2e9591c2019-05-14 12:32:37 +00007064 ObjCEncOptions NewOptions;
7065 if (Options.ExpandPointedToStructures())
7066 NewOptions.setExpandStructures();
7067 getObjCEncodingForTypeImpl(PointeeTy, S, NewOptions,
7068 /*Field=*/nullptr, NotEncodedT);
Chris Lattnere7cabb92009-07-13 00:10:46 +00007069 return;
7070 }
John McCall393a78d2012-12-20 02:45:14 +00007071
7072 case Type::ConstantArray:
7073 case Type::IncompleteArray:
7074 case Type::VariableArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00007075 const auto *AT = cast<ArrayType>(CT);
John McCall393a78d2012-12-20 02:45:14 +00007076
Nico Weber2e9591c2019-05-14 12:32:37 +00007077 if (isa<IncompleteArrayType>(AT) && !Options.IsStructField()) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00007078 // Incomplete arrays are encoded as a pointer to the array element.
7079 S += '^';
7080
Nico Weber2e9591c2019-05-14 12:32:37 +00007081 getObjCEncodingForTypeImpl(
7082 AT->getElementType(), S,
7083 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD);
Anders Carlssond05f44b2009-02-22 01:38:57 +00007084 } else {
7085 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00007086
Eugene Zelenko7855e772018-04-03 00:11:50 +00007087 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
Fariborz Jahanianf0dc11a2013-06-04 16:04:37 +00007088 S += llvm::utostr(CAT->getSize().getZExtValue());
7089 else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00007090 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007091 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
7092 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00007093 S += '0';
7094 }
Mike Stump11289f42009-09-09 15:08:12 +00007095
Nico Weberdf129332019-05-10 13:56:56 +00007096 getObjCEncodingForTypeImpl(
7097 AT->getElementType(), S,
Nico Weber2e9591c2019-05-14 12:32:37 +00007098 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD,
7099 NotEncodedT);
Anders Carlssond05f44b2009-02-22 01:38:57 +00007100 S += ']';
7101 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00007102 return;
7103 }
Mike Stump11289f42009-09-09 15:08:12 +00007104
John McCall393a78d2012-12-20 02:45:14 +00007105 case Type::FunctionNoProto:
7106 case Type::FunctionProto:
Anders Carlssondf4cc612007-10-30 00:06:20 +00007107 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00007108 return;
Mike Stump11289f42009-09-09 15:08:12 +00007109
John McCall393a78d2012-12-20 02:45:14 +00007110 case Type::Record: {
7111 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00007112 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00007113 // Anonymous structures print as '?'
7114 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
7115 S += II->getName();
Eugene Zelenko7855e772018-04-03 00:11:50 +00007116 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
Fariborz Jahanianc5158202010-05-07 00:28:49 +00007117 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00007118 llvm::raw_string_ostream OS(S);
Serge Pavlov03e672c2017-11-28 16:14:14 +00007119 printTemplateArgumentList(OS, TemplateArgs.asArray(),
7120 getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00007121 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00007122 } else {
7123 S += '?';
7124 }
Nico Weber2e9591c2019-05-14 12:32:37 +00007125 if (Options.ExpandStructures()) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00007126 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007127 if (!RDecl->isUnion()) {
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00007128 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007129 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007130 for (const auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007131 if (FD) {
7132 S += '"';
7133 S += Field->getNameAsString();
7134 S += '"';
7135 }
Mike Stump11289f42009-09-09 15:08:12 +00007136
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007137 // Special case bit-fields.
7138 if (Field->isBitField()) {
Nico Weberdf129332019-05-10 13:56:56 +00007139 getObjCEncodingForTypeImpl(Field->getType(), S,
Nico Weber2e9591c2019-05-14 12:32:37 +00007140 ObjCEncOptions().setExpandStructures(),
7141 Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007142 } else {
7143 QualType qt = Field->getType();
7144 getLegacyIntegralTypeEncoding(qt);
Nico Weberdf129332019-05-10 13:56:56 +00007145 getObjCEncodingForTypeImpl(
Nico Weber2e9591c2019-05-14 12:32:37 +00007146 qt, S,
7147 ObjCEncOptions().setExpandStructures().setIsStructField(), FD,
7148 NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007149 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00007150 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00007151 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00007152 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00007153 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00007154 return;
7155 }
Mike Stump11289f42009-09-09 15:08:12 +00007156
John McCall393a78d2012-12-20 02:45:14 +00007157 case Type::BlockPointer: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00007158 const auto *BT = T->castAs<BlockPointerType>();
Steve Naroff49140cb2009-02-02 18:24:29 +00007159 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Nico Weber2e9591c2019-05-14 12:32:37 +00007160 if (Options.EncodeBlockParameters()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00007161 const auto *FT = BT->getPointeeType()->castAs<FunctionType>();
Fangrui Song6907ce22018-07-30 19:24:48 +00007162
Bob Wilson5f4e3a72011-11-30 01:57:58 +00007163 S += '<';
7164 // Block return type
Nico Weber2e9591c2019-05-14 12:32:37 +00007165 getObjCEncodingForTypeImpl(FT->getReturnType(), S,
7166 Options.forComponentType(), FD, NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00007167 // Block self
7168 S += "@?";
7169 // Block parameters
Eugene Zelenko7855e772018-04-03 00:11:50 +00007170 if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00007171 for (const auto &I : FPT->param_types())
Nico Weber2e9591c2019-05-14 12:32:37 +00007172 getObjCEncodingForTypeImpl(I, S, Options.forComponentType(), FD,
7173 NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00007174 }
7175 S += '>';
7176 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00007177 return;
7178 }
Mike Stump11289f42009-09-09 15:08:12 +00007179
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00007180 case Type::ObjCObject: {
7181 // hack to match legacy encoding of *id and *Class
7182 QualType Ty = getObjCObjectPointerType(CT);
7183 if (Ty->isObjCIdType()) {
7184 S += "{objc_object=}";
7185 return;
7186 }
7187 else if (Ty->isObjCClassType()) {
7188 S += "{objc_class=}";
7189 return;
7190 }
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00007191 // TODO: Double check to make sure this intentionally falls through.
Galina Kistanovaf87496d2017-06-03 06:31:42 +00007192 LLVM_FALLTHROUGH;
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00007193 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007194
John McCall393a78d2012-12-20 02:45:14 +00007195 case Type::ObjCInterface: {
7196 // Ignore protocol qualifiers when mangling at this level.
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00007197 // @encode(class_name)
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007198 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00007199 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00007200 S += OI->getObjCRuntimeNameAsString();
Nico Weber2e9591c2019-05-14 12:32:37 +00007201 if (Options.ExpandStructures()) {
Akira Hatanakafd0fb202016-08-17 19:42:22 +00007202 S += '=';
7203 SmallVector<const ObjCIvarDecl*, 32> Ivars;
7204 DeepCollectObjCIvars(OI, true, Ivars);
7205 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
George Burgess IV00f70bd2018-03-01 05:43:23 +00007206 const FieldDecl *Field = Ivars[i];
Akira Hatanakafd0fb202016-08-17 19:42:22 +00007207 if (Field->isBitField())
Nico Weberdf129332019-05-10 13:56:56 +00007208 getObjCEncodingForTypeImpl(Field->getType(), S,
Nico Weber2e9591c2019-05-14 12:32:37 +00007209 ObjCEncOptions().setExpandStructures(),
7210 Field);
Akira Hatanakaf3c89b12019-05-29 21:23:30 +00007211 else
7212 getObjCEncodingForTypeImpl(Field->getType(), S,
7213 ObjCEncOptions().setExpandStructures(), FD,
Nico Weber2e9591c2019-05-14 12:32:37 +00007214 NotEncodedT);
Akira Hatanakafd0fb202016-08-17 19:42:22 +00007215 }
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00007216 }
7217 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00007218 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00007219 }
Mike Stump11289f42009-09-09 15:08:12 +00007220
John McCall393a78d2012-12-20 02:45:14 +00007221 case Type::ObjCObjectPointer: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00007222 const auto *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00007223 if (OPT->isObjCIdType()) {
7224 S += '@';
7225 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00007226 }
Mike Stump11289f42009-09-09 15:08:12 +00007227
Steve Narofff0c86112009-10-28 22:03:49 +00007228 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
7229 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
Nico Weberdf129332019-05-10 13:56:56 +00007230 // Since this is a binary compatibility issue, need to consult with
7231 // runtime folks. Fortunately, this is a *very* obscure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00007232 S += '#';
7233 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00007234 }
Mike Stump11289f42009-09-09 15:08:12 +00007235
Chris Lattnere7cabb92009-07-13 00:10:46 +00007236 if (OPT->isObjCQualifiedIdType()) {
Nico Weber2e9591c2019-05-14 12:32:37 +00007237 getObjCEncodingForTypeImpl(
7238 getObjCIdType(), S,
7239 Options.keepingOnly(ObjCEncOptions()
7240 .setExpandPointedToStructures()
7241 .setExpandStructures()),
7242 FD);
7243 if (FD || Options.EncodingProperty() || Options.EncodeClassNames()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00007244 // Note that we do extended encoding of protocol qualifer list
7245 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00007246 S += '"';
Aaron Ballman83731462014-03-17 16:14:00 +00007247 for (const auto *I : OPT->quals()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00007248 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00007249 S += I->getObjCRuntimeNameAsString();
Steve Naroff7cae42b2009-07-10 23:34:53 +00007250 S += '>';
7251 }
7252 S += '"';
7253 }
7254 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00007255 }
Mike Stump11289f42009-09-09 15:08:12 +00007256
Chris Lattnere7cabb92009-07-13 00:10:46 +00007257 S += '@';
Fangrui Song6907ce22018-07-30 19:24:48 +00007258 if (OPT->getInterfaceDecl() &&
Nico Weber2e9591c2019-05-14 12:32:37 +00007259 (FD || Options.EncodingProperty() || Options.EncodeClassNames())) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00007260 S += '"';
Douglas Gregorb32684e2015-06-16 21:04:55 +00007261 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
Aaron Ballman83731462014-03-17 16:14:00 +00007262 for (const auto *I : OPT->quals()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00007263 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00007264 S += I->getObjCRuntimeNameAsString();
Chris Lattnere7cabb92009-07-13 00:10:46 +00007265 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00007266 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00007267 S += '"';
7268 }
7269 return;
7270 }
Mike Stump11289f42009-09-09 15:08:12 +00007271
John McCalla9e6e8d2010-05-17 23:56:34 +00007272 // gcc just blithely ignores member pointers.
Nico Weber2e9591c2019-05-14 12:32:37 +00007273 // FIXME: we should do better than that. 'M' is available.
John McCall393a78d2012-12-20 02:45:14 +00007274 case Type::MemberPointer:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00007275 // This matches gcc's encoding, even though technically it is insufficient.
7276 //FIXME. We should do a better job than gcc.
John McCall393a78d2012-12-20 02:45:14 +00007277 case Type::Vector:
7278 case Type::ExtVector:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00007279 // Until we have a coherent encoding of these three types, issue warning.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00007280 if (NotEncodedT)
7281 *NotEncodedT = T;
7282 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00007283
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00007284 // We could see an undeduced auto type here during error recovery.
7285 // Just ignore it.
Richard Smith27d807c2013-04-30 13:56:41 +00007286 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00007287 case Type::DeducedTemplateSpecialization:
Richard Smith27d807c2013-04-30 13:56:41 +00007288 return;
7289
Xiuli Pan9c14e282016-01-09 12:53:17 +00007290 case Type::Pipe:
John McCall393a78d2012-12-20 02:45:14 +00007291#define ABSTRACT_TYPE(KIND, BASE)
7292#define TYPE(KIND, BASE)
7293#define DEPENDENT_TYPE(KIND, BASE) \
7294 case Type::KIND:
7295#define NON_CANONICAL_TYPE(KIND, BASE) \
7296 case Type::KIND:
7297#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
7298 case Type::KIND:
John McCall36b12a82019-10-02 06:35:23 +00007299#include "clang/AST/TypeNodes.inc"
John McCall393a78d2012-12-20 02:45:14 +00007300 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00007301 }
John McCall393a78d2012-12-20 02:45:14 +00007302 llvm_unreachable("bad type kind!");
Anders Carlssond8499822007-10-29 05:01:08 +00007303}
7304
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007305void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
7306 std::string &S,
7307 const FieldDecl *FD,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00007308 bool includeVBases,
7309 QualType *NotEncodedT) const {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007310 assert(RDecl && "Expected non-null RecordDecl");
7311 assert(!RDecl->isUnion() && "Should not be called for unions");
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00007312 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007313 return;
7314
Eugene Zelenko7855e772018-04-03 00:11:50 +00007315 const auto *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007316 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
7317 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
7318
7319 if (CXXRec) {
Aaron Ballman574705e2014-03-13 15:41:46 +00007320 for (const auto &BI : CXXRec->bases()) {
7321 if (!BI.isVirtual()) {
7322 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00007323 if (base->isEmpty())
7324 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00007325 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007326 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
7327 std::make_pair(offs, base));
7328 }
7329 }
7330 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007331
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007332 unsigned i = 0;
Hans Wennborga302cd92014-08-21 16:06:57 +00007333 for (auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007334 uint64_t offs = layout.getFieldOffset(i);
7335 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Hans Wennborga302cd92014-08-21 16:06:57 +00007336 std::make_pair(offs, Field));
7337 ++i;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007338 }
7339
7340 if (CXXRec && includeVBases) {
Aaron Ballman445a9392014-03-13 16:15:17 +00007341 for (const auto &BI : CXXRec->vbases()) {
7342 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00007343 if (base->isEmpty())
7344 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00007345 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Eli Friedman1d24af82013-09-18 01:59:16 +00007346 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
7347 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00007348 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
7349 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007350 }
7351 }
7352
7353 CharUnits size;
7354 if (CXXRec) {
7355 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
7356 } else {
7357 size = layout.getSize();
7358 }
7359
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007360#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007361 uint64_t CurOffs = 0;
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007362#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007363 std::multimap<uint64_t, NamedDecl *>::iterator
7364 CurLayObj = FieldOrBaseOffsets.begin();
7365
Douglas Gregorf5d6c742012-04-27 22:30:01 +00007366 if (CXXRec && CXXRec->isDynamicClass() &&
7367 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007368 if (FD) {
7369 S += "\"_vptr$";
7370 std::string recname = CXXRec->getNameAsString();
7371 if (recname.empty()) recname = "?";
7372 S += recname;
7373 S += '"';
7374 }
7375 S += "^^?";
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007376#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007377 CurOffs += getTypeSize(VoidPtrTy);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007378#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007379 }
7380
7381 if (!RDecl->hasFlexibleArrayMember()) {
7382 // Mark the end of the structure.
7383 uint64_t offs = toBits(size);
7384 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Craig Topper36250ad2014-05-12 05:36:57 +00007385 std::make_pair(offs, nullptr));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007386 }
7387
7388 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007389#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007390 assert(CurOffs <= CurLayObj->first);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007391 if (CurOffs < CurLayObj->first) {
Fangrui Song6907ce22018-07-30 19:24:48 +00007392 uint64_t padding = CurLayObj->first - CurOffs;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007393 // FIXME: There doesn't seem to be a way to indicate in the encoding that
7394 // packing/alignment of members is different that normal, in which case
7395 // the encoding will be out-of-sync with the real layout.
7396 // If the runtime switches to just consider the size of types without
7397 // taking into account alignment, we could make padding explicit in the
7398 // encoding (e.g. using arrays of chars). The encoding strings would be
7399 // longer then though.
7400 CurOffs += padding;
7401 }
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007402#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007403
7404 NamedDecl *dcl = CurLayObj->second;
Craig Topper36250ad2014-05-12 05:36:57 +00007405 if (!dcl)
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007406 break; // reached end of structure.
7407
Eugene Zelenko7855e772018-04-03 00:11:50 +00007408 if (auto *base = dyn_cast<CXXRecordDecl>(dcl)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007409 // We expand the bases without their virtual bases since those are going
7410 // in the initial structure. Note that this differs from gcc which
7411 // expands virtual bases each time one is encountered in the hierarchy,
7412 // making the encoding type bigger than it really is.
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00007413 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
7414 NotEncodedT);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00007415 assert(!base->isEmpty());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007416#ifndef NDEBUG
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00007417 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007418#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007419 } else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00007420 const auto *field = cast<FieldDecl>(dcl);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007421 if (FD) {
7422 S += '"';
7423 S += field->getNameAsString();
7424 S += '"';
7425 }
7426
7427 if (field->isBitField()) {
7428 EncodeBitField(this, S, field->getType(), field);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007429#ifndef NDEBUG
Richard Smithcaf33902011-10-10 18:28:20 +00007430 CurOffs += field->getBitWidthValue(*this);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007431#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007432 } else {
7433 QualType qt = field->getType();
7434 getLegacyIntegralTypeEncoding(qt);
Nico Weberdf129332019-05-10 13:56:56 +00007435 getObjCEncodingForTypeImpl(
Nico Weber2e9591c2019-05-14 12:32:37 +00007436 qt, S, ObjCEncOptions().setExpandStructures().setIsStructField(),
7437 FD, NotEncodedT);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007438#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007439 CurOffs += getTypeSize(field->getType());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007440#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007441 }
7442 }
7443 }
7444}
7445
Mike Stump11289f42009-09-09 15:08:12 +00007446void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00007447 std::string& S) const {
7448 if (QT & Decl::OBJC_TQ_In)
7449 S += 'n';
7450 if (QT & Decl::OBJC_TQ_Inout)
7451 S += 'N';
7452 if (QT & Decl::OBJC_TQ_Out)
7453 S += 'o';
7454 if (QT & Decl::OBJC_TQ_Bycopy)
7455 S += 'O';
7456 if (QT & Decl::OBJC_TQ_Byref)
7457 S += 'R';
7458 if (QT & Decl::OBJC_TQ_Oneway)
7459 S += 'V';
7460}
7461
Douglas Gregor3ea72692011-08-12 05:46:01 +00007462TypedefDecl *ASTContext::getObjCIdDecl() const {
7463 if (!ObjCIdDecl) {
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00007464 QualType T = getObjCObjectType(ObjCBuiltinIdTy, {}, {});
Douglas Gregor3ea72692011-08-12 05:46:01 +00007465 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00007466 ObjCIdDecl = buildImplicitTypedef(T, "id");
Douglas Gregor3ea72692011-08-12 05:46:01 +00007467 }
Douglas Gregor3ea72692011-08-12 05:46:01 +00007468 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00007469}
7470
Douglas Gregor52e02802011-08-12 06:17:30 +00007471TypedefDecl *ASTContext::getObjCSelDecl() const {
7472 if (!ObjCSelDecl) {
Alp Toker56b5cc92013-12-15 10:36:26 +00007473 QualType T = getPointerType(ObjCBuiltinSelTy);
7474 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
Douglas Gregor52e02802011-08-12 06:17:30 +00007475 }
7476 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00007477}
7478
Douglas Gregor0a586182011-08-12 05:59:41 +00007479TypedefDecl *ASTContext::getObjCClassDecl() const {
7480 if (!ObjCClassDecl) {
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00007481 QualType T = getObjCObjectType(ObjCBuiltinClassTy, {}, {});
Douglas Gregor0a586182011-08-12 05:59:41 +00007482 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00007483 ObjCClassDecl = buildImplicitTypedef(T, "Class");
Douglas Gregor0a586182011-08-12 05:59:41 +00007484 }
Douglas Gregor0a586182011-08-12 05:59:41 +00007485 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00007486}
7487
Douglas Gregord53ae832012-01-17 18:09:05 +00007488ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
7489 if (!ObjCProtocolClassDecl) {
Fangrui Song6907ce22018-07-30 19:24:48 +00007490 ObjCProtocolClassDecl
7491 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
Douglas Gregord53ae832012-01-17 18:09:05 +00007492 SourceLocation(),
7493 &Idents.get("Protocol"),
Douglas Gregor85f3f952015-07-07 03:57:15 +00007494 /*typeParamList=*/nullptr,
Craig Topper36250ad2014-05-12 05:36:57 +00007495 /*PrevDecl=*/nullptr,
Fangrui Song6907ce22018-07-30 19:24:48 +00007496 SourceLocation(), true);
Douglas Gregord53ae832012-01-17 18:09:05 +00007497 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007498
Douglas Gregord53ae832012-01-17 18:09:05 +00007499 return ObjCProtocolClassDecl;
7500}
7501
Meador Inge5d3fb222012-06-16 03:34:49 +00007502//===----------------------------------------------------------------------===//
7503// __builtin_va_list Construction Functions
7504//===----------------------------------------------------------------------===//
7505
Charles Davisc7d5c942015-09-17 20:55:33 +00007506static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context,
7507 StringRef Name) {
7508 // typedef char* __builtin[_ms]_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00007509 QualType T = Context->getPointerType(Context->CharTy);
Charles Davisc7d5c942015-09-17 20:55:33 +00007510 return Context->buildImplicitTypedef(T, Name);
7511}
7512
7513static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
7514 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
7515}
7516
7517static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
7518 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007519}
7520
7521static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
7522 // typedef void* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00007523 QualType T = Context->getPointerType(Context->VoidTy);
7524 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007525}
7526
Tim Northover9bb857a2013-01-31 12:13:10 +00007527static TypedefDecl *
7528CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00007529 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00007530 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00007531 if (Context->getLangOpts().CPlusPlus) {
7532 // namespace std { struct __va_list {
7533 NamespaceDecl *NS;
7534 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
7535 Context->getTranslationUnitDecl(),
Craig Topper36250ad2014-05-12 05:36:57 +00007536 /*Inline*/ false, SourceLocation(),
Tim Northover9bb857a2013-01-31 12:13:10 +00007537 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00007538 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00007539 NS->setImplicit();
Tim Northover9bb857a2013-01-31 12:13:10 +00007540 VaListTagDecl->setDeclContext(NS);
Tim Northover9bb857a2013-01-31 12:13:10 +00007541 }
7542
7543 VaListTagDecl->startDefinition();
7544
7545 const size_t NumFields = 5;
7546 QualType FieldTypes[NumFields];
7547 const char *FieldNames[NumFields];
7548
7549 // void *__stack;
7550 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
7551 FieldNames[0] = "__stack";
7552
7553 // void *__gr_top;
7554 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
7555 FieldNames[1] = "__gr_top";
7556
7557 // void *__vr_top;
7558 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
7559 FieldNames[2] = "__vr_top";
7560
7561 // int __gr_offs;
7562 FieldTypes[3] = Context->IntTy;
7563 FieldNames[3] = "__gr_offs";
7564
7565 // int __vr_offs;
7566 FieldTypes[4] = Context->IntTy;
7567 FieldNames[4] = "__vr_offs";
7568
7569 // Create fields
7570 for (unsigned i = 0; i < NumFields; ++i) {
7571 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7572 VaListTagDecl,
7573 SourceLocation(),
7574 SourceLocation(),
7575 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00007576 FieldTypes[i], /*TInfo=*/nullptr,
7577 /*BitWidth=*/nullptr,
Tim Northover9bb857a2013-01-31 12:13:10 +00007578 /*Mutable=*/false,
7579 ICIS_NoInit);
7580 Field->setAccess(AS_public);
7581 VaListTagDecl->addDecl(Field);
7582 }
7583 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00007584 Context->VaListTagDecl = VaListTagDecl;
Tim Northover9bb857a2013-01-31 12:13:10 +00007585 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Tim Northover9bb857a2013-01-31 12:13:10 +00007586
7587 // } __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00007588 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00007589}
7590
Meador Inge5d3fb222012-06-16 03:34:49 +00007591static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
7592 // typedef struct __va_list_tag {
7593 RecordDecl *VaListTagDecl;
7594
Alp Toker2dea15b2013-12-17 01:22:38 +00007595 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00007596 VaListTagDecl->startDefinition();
7597
7598 const size_t NumFields = 5;
7599 QualType FieldTypes[NumFields];
7600 const char *FieldNames[NumFields];
7601
7602 // unsigned char gpr;
7603 FieldTypes[0] = Context->UnsignedCharTy;
7604 FieldNames[0] = "gpr";
7605
7606 // unsigned char fpr;
7607 FieldTypes[1] = Context->UnsignedCharTy;
7608 FieldNames[1] = "fpr";
7609
7610 // unsigned short reserved;
7611 FieldTypes[2] = Context->UnsignedShortTy;
7612 FieldNames[2] = "reserved";
7613
7614 // void* overflow_arg_area;
7615 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
7616 FieldNames[3] = "overflow_arg_area";
7617
7618 // void* reg_save_area;
7619 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
7620 FieldNames[4] = "reg_save_area";
7621
7622 // Create fields
7623 for (unsigned i = 0; i < NumFields; ++i) {
7624 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
7625 SourceLocation(),
7626 SourceLocation(),
7627 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00007628 FieldTypes[i], /*TInfo=*/nullptr,
7629 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00007630 /*Mutable=*/false,
7631 ICIS_NoInit);
7632 Field->setAccess(AS_public);
7633 VaListTagDecl->addDecl(Field);
7634 }
7635 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00007636 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00007637 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
7638
7639 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00007640 TypedefDecl *VaListTagTypedefDecl =
7641 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
7642
Meador Inge5d3fb222012-06-16 03:34:49 +00007643 QualType VaListTagTypedefType =
7644 Context->getTypedefType(VaListTagTypedefDecl);
7645
7646 // typedef __va_list_tag __builtin_va_list[1];
7647 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
7648 QualType VaListTagArrayType
7649 = Context->getConstantArrayType(VaListTagTypedefType,
Richard Smith772e2662019-10-04 01:25:59 +00007650 Size, nullptr, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00007651 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007652}
7653
7654static TypedefDecl *
7655CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00007656 // struct __va_list_tag {
Meador Inge5d3fb222012-06-16 03:34:49 +00007657 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00007658 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00007659 VaListTagDecl->startDefinition();
7660
7661 const size_t NumFields = 4;
7662 QualType FieldTypes[NumFields];
7663 const char *FieldNames[NumFields];
7664
7665 // unsigned gp_offset;
7666 FieldTypes[0] = Context->UnsignedIntTy;
7667 FieldNames[0] = "gp_offset";
7668
7669 // unsigned fp_offset;
7670 FieldTypes[1] = Context->UnsignedIntTy;
7671 FieldNames[1] = "fp_offset";
7672
7673 // void* overflow_arg_area;
7674 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
7675 FieldNames[2] = "overflow_arg_area";
7676
7677 // void* reg_save_area;
7678 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
7679 FieldNames[3] = "reg_save_area";
7680
7681 // Create fields
7682 for (unsigned i = 0; i < NumFields; ++i) {
7683 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7684 VaListTagDecl,
7685 SourceLocation(),
7686 SourceLocation(),
7687 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00007688 FieldTypes[i], /*TInfo=*/nullptr,
7689 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00007690 /*Mutable=*/false,
7691 ICIS_NoInit);
7692 Field->setAccess(AS_public);
7693 VaListTagDecl->addDecl(Field);
7694 }
7695 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00007696 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00007697 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
7698
Richard Smith9b88a4c2015-07-27 05:40:23 +00007699 // };
Alp Toker56b5cc92013-12-15 10:36:26 +00007700
Richard Smith9b88a4c2015-07-27 05:40:23 +00007701 // typedef struct __va_list_tag __builtin_va_list[1];
Meador Inge5d3fb222012-06-16 03:34:49 +00007702 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith772e2662019-10-04 01:25:59 +00007703 QualType VaListTagArrayType = Context->getConstantArrayType(
7704 VaListTagType, Size, nullptr, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00007705 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007706}
7707
7708static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
7709 // typedef int __builtin_va_list[4];
7710 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
Richard Smith772e2662019-10-04 01:25:59 +00007711 QualType IntArrayType = Context->getConstantArrayType(
7712 Context->IntTy, Size, nullptr, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00007713 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007714}
7715
Logan Chien57086ce2012-10-10 06:56:20 +00007716static TypedefDecl *
7717CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00007718 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00007719 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00007720 if (Context->getLangOpts().CPlusPlus) {
7721 // namespace std { struct __va_list {
7722 NamespaceDecl *NS;
7723 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
7724 Context->getTranslationUnitDecl(),
7725 /*Inline*/false, SourceLocation(),
7726 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00007727 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00007728 NS->setImplicit();
Logan Chien57086ce2012-10-10 06:56:20 +00007729 VaListDecl->setDeclContext(NS);
Logan Chien57086ce2012-10-10 06:56:20 +00007730 }
7731
7732 VaListDecl->startDefinition();
7733
7734 // void * __ap;
7735 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7736 VaListDecl,
7737 SourceLocation(),
7738 SourceLocation(),
7739 &Context->Idents.get("__ap"),
7740 Context->getPointerType(Context->VoidTy),
Craig Topper36250ad2014-05-12 05:36:57 +00007741 /*TInfo=*/nullptr,
7742 /*BitWidth=*/nullptr,
Logan Chien57086ce2012-10-10 06:56:20 +00007743 /*Mutable=*/false,
7744 ICIS_NoInit);
7745 Field->setAccess(AS_public);
7746 VaListDecl->addDecl(Field);
7747
7748 // };
7749 VaListDecl->completeDefinition();
Oleg Ranevskyyb88d2472016-03-30 21:30:30 +00007750 Context->VaListTagDecl = VaListDecl;
Logan Chien57086ce2012-10-10 06:56:20 +00007751
7752 // typedef struct __va_list __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00007753 QualType T = Context->getRecordType(VaListDecl);
7754 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00007755}
7756
Ulrich Weigand47445072013-05-06 16:26:41 +00007757static TypedefDecl *
7758CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00007759 // struct __va_list_tag {
Ulrich Weigand47445072013-05-06 16:26:41 +00007760 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00007761 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00007762 VaListTagDecl->startDefinition();
7763
7764 const size_t NumFields = 4;
7765 QualType FieldTypes[NumFields];
7766 const char *FieldNames[NumFields];
7767
7768 // long __gpr;
7769 FieldTypes[0] = Context->LongTy;
7770 FieldNames[0] = "__gpr";
7771
7772 // long __fpr;
7773 FieldTypes[1] = Context->LongTy;
7774 FieldNames[1] = "__fpr";
7775
7776 // void *__overflow_arg_area;
7777 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
7778 FieldNames[2] = "__overflow_arg_area";
7779
7780 // void *__reg_save_area;
7781 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
7782 FieldNames[3] = "__reg_save_area";
7783
7784 // Create fields
7785 for (unsigned i = 0; i < NumFields; ++i) {
7786 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7787 VaListTagDecl,
7788 SourceLocation(),
7789 SourceLocation(),
7790 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00007791 FieldTypes[i], /*TInfo=*/nullptr,
7792 /*BitWidth=*/nullptr,
Ulrich Weigand47445072013-05-06 16:26:41 +00007793 /*Mutable=*/false,
7794 ICIS_NoInit);
7795 Field->setAccess(AS_public);
7796 VaListTagDecl->addDecl(Field);
7797 }
7798 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00007799 Context->VaListTagDecl = VaListTagDecl;
Ulrich Weigand47445072013-05-06 16:26:41 +00007800 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Ulrich Weigand47445072013-05-06 16:26:41 +00007801
Richard Smith9b88a4c2015-07-27 05:40:23 +00007802 // };
Ulrich Weigand47445072013-05-06 16:26:41 +00007803
7804 // typedef __va_list_tag __builtin_va_list[1];
7805 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith772e2662019-10-04 01:25:59 +00007806 QualType VaListTagArrayType = Context->getConstantArrayType(
7807 VaListTagType, Size, nullptr, ArrayType::Normal, 0);
Ulrich Weigand47445072013-05-06 16:26:41 +00007808
Alp Toker56b5cc92013-12-15 10:36:26 +00007809 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Ulrich Weigand47445072013-05-06 16:26:41 +00007810}
7811
Sid Manningb0da0942020-03-03 08:19:59 -06007812static TypedefDecl *CreateHexagonBuiltinVaListDecl(const ASTContext *Context) {
7813 // typedef struct __va_list_tag {
7814 RecordDecl *VaListTagDecl;
7815 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
7816 VaListTagDecl->startDefinition();
7817
7818 const size_t NumFields = 3;
7819 QualType FieldTypes[NumFields];
7820 const char *FieldNames[NumFields];
7821
7822 // void *CurrentSavedRegisterArea;
7823 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
7824 FieldNames[0] = "__current_saved_reg_area_pointer";
7825
7826 // void *SavedRegAreaEnd;
7827 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
7828 FieldNames[1] = "__saved_reg_area_end_pointer";
7829
7830 // void *OverflowArea;
7831 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
7832 FieldNames[2] = "__overflow_area_pointer";
7833
7834 // Create fields
7835 for (unsigned i = 0; i < NumFields; ++i) {
7836 FieldDecl *Field = FieldDecl::Create(
7837 const_cast<ASTContext &>(*Context), VaListTagDecl, SourceLocation(),
7838 SourceLocation(), &Context->Idents.get(FieldNames[i]), FieldTypes[i],
7839 /*TInfo=*/0,
7840 /*BitWidth=*/0,
7841 /*Mutable=*/false, ICIS_NoInit);
7842 Field->setAccess(AS_public);
7843 VaListTagDecl->addDecl(Field);
7844 }
7845 VaListTagDecl->completeDefinition();
7846 Context->VaListTagDecl = VaListTagDecl;
7847 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
7848
7849 // } __va_list_tag;
7850 TypedefDecl *VaListTagTypedefDecl =
7851 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
7852
7853 QualType VaListTagTypedefType = Context->getTypedefType(VaListTagTypedefDecl);
7854
7855 // typedef __va_list_tag __builtin_va_list[1];
7856 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
7857 QualType VaListTagArrayType = Context->getConstantArrayType(
7858 VaListTagTypedefType, Size, nullptr, ArrayType::Normal, 0);
7859
7860 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
7861}
7862
Meador Inge5d3fb222012-06-16 03:34:49 +00007863static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
7864 TargetInfo::BuiltinVaListKind Kind) {
7865 switch (Kind) {
7866 case TargetInfo::CharPtrBuiltinVaList:
7867 return CreateCharPtrBuiltinVaListDecl(Context);
7868 case TargetInfo::VoidPtrBuiltinVaList:
7869 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northover9bb857a2013-01-31 12:13:10 +00007870 case TargetInfo::AArch64ABIBuiltinVaList:
7871 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00007872 case TargetInfo::PowerABIBuiltinVaList:
7873 return CreatePowerABIBuiltinVaListDecl(Context);
7874 case TargetInfo::X86_64ABIBuiltinVaList:
7875 return CreateX86_64ABIBuiltinVaListDecl(Context);
7876 case TargetInfo::PNaClABIBuiltinVaList:
7877 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00007878 case TargetInfo::AAPCSABIBuiltinVaList:
7879 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigand47445072013-05-06 16:26:41 +00007880 case TargetInfo::SystemZBuiltinVaList:
7881 return CreateSystemZBuiltinVaListDecl(Context);
Sid Manningb0da0942020-03-03 08:19:59 -06007882 case TargetInfo::HexagonBuiltinVaList:
7883 return CreateHexagonBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00007884 }
7885
7886 llvm_unreachable("Unhandled __builtin_va_list type kind");
7887}
7888
7889TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00007890 if (!BuiltinVaListDecl) {
Meador Inge5d3fb222012-06-16 03:34:49 +00007891 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
Alp Toker56b5cc92013-12-15 10:36:26 +00007892 assert(BuiltinVaListDecl->isImplicit());
7893 }
Meador Inge5d3fb222012-06-16 03:34:49 +00007894
7895 return BuiltinVaListDecl;
7896}
7897
Richard Smith9b88a4c2015-07-27 05:40:23 +00007898Decl *ASTContext::getVaListTagDecl() const {
7899 // Force the creation of VaListTagDecl by building the __builtin_va_list
Meador Ingecfb60902012-07-01 15:57:25 +00007900 // declaration.
Richard Smith9b88a4c2015-07-27 05:40:23 +00007901 if (!VaListTagDecl)
7902 (void)getBuiltinVaListDecl();
Meador Ingecfb60902012-07-01 15:57:25 +00007903
Richard Smith9b88a4c2015-07-27 05:40:23 +00007904 return VaListTagDecl;
Meador Ingecfb60902012-07-01 15:57:25 +00007905}
7906
Charles Davisc7d5c942015-09-17 20:55:33 +00007907TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const {
7908 if (!BuiltinMSVaListDecl)
7909 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
7910
7911 return BuiltinMSVaListDecl;
7912}
7913
Erich Keane41af9712018-04-16 21:30:08 +00007914bool ASTContext::canBuiltinBeRedeclared(const FunctionDecl *FD) const {
7915 return BuiltinInfo.canBeRedeclared(FD->getBuiltinID());
7916}
7917
Ted Kremenek1b0ea822008-01-07 19:49:32 +00007918void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00007919 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00007920 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00007921
Ted Kremenek1b0ea822008-01-07 19:49:32 +00007922 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00007923}
7924
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007925/// Retrieve the template name that corresponds to a non-empty
John McCalld28ae272009-12-02 08:04:21 +00007926/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00007927TemplateName
7928ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
7929 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00007930 unsigned size = End - Begin;
7931 assert(size > 1 && "set is not overloaded!");
7932
7933 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
7934 size * sizeof(FunctionTemplateDecl*));
Eugene Zelenko7855e772018-04-03 00:11:50 +00007935 auto *OT = new (memory) OverloadedTemplateStorage(size);
John McCalld28ae272009-12-02 08:04:21 +00007936
7937 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00007938 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00007939 NamedDecl *D = *I;
7940 assert(isa<FunctionTemplateDecl>(D) ||
Richard Smithef53a3e2018-06-06 16:36:56 +00007941 isa<UnresolvedUsingValueDecl>(D) ||
John McCalld28ae272009-12-02 08:04:21 +00007942 (isa<UsingShadowDecl>(D) &&
7943 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
7944 *Storage++ = D;
7945 }
7946
7947 return TemplateName(OT);
7948}
7949
Richard Smithb23c5e82019-05-09 03:31:27 +00007950/// Retrieve a template name representing an unqualified-id that has been
7951/// assumed to name a template for ADL purposes.
7952TemplateName ASTContext::getAssumedTemplateName(DeclarationName Name) const {
7953 auto *OT = new (*this) AssumedTemplateStorage(Name);
7954 return TemplateName(OT);
7955}
7956
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007957/// Retrieve the template name that represents a qualified
Douglas Gregordc572a32009-03-30 22:58:21 +00007958/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00007959TemplateName
7960ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
7961 bool TemplateKeyword,
7962 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00007963 assert(NNS && "Missing nested-name-specifier in qualified template name");
Fangrui Song6907ce22018-07-30 19:24:48 +00007964
Douglas Gregorc42075a2010-02-04 18:10:26 +00007965 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00007966 llvm::FoldingSetNodeID ID;
7967 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
7968
Craig Topper36250ad2014-05-12 05:36:57 +00007969 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00007970 QualifiedTemplateName *QTN =
7971 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7972 if (!QTN) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007973 QTN = new (*this, alignof(QualifiedTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007974 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00007975 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
7976 }
7977
7978 return TemplateName(QTN);
7979}
7980
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007981/// Retrieve the template name that represents a dependent
Douglas Gregordc572a32009-03-30 22:58:21 +00007982/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00007983TemplateName
7984ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
7985 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00007986 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00007987 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00007988
7989 llvm::FoldingSetNodeID ID;
7990 DependentTemplateName::Profile(ID, NNS, Name);
7991
Craig Topper36250ad2014-05-12 05:36:57 +00007992 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00007993 DependentTemplateName *QTN =
7994 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7995
7996 if (QTN)
7997 return TemplateName(QTN);
7998
7999 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
8000 if (CanonNNS == NNS) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00008001 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00008002 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00008003 } else {
8004 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00008005 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00008006 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00008007 DependentTemplateName *CheckQTN =
8008 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
8009 assert(!CheckQTN && "Dependent type name canonicalization broken");
8010 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00008011 }
8012
8013 DependentTemplateNames.InsertNode(QTN, InsertPos);
8014 return TemplateName(QTN);
8015}
8016
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008017/// Retrieve the template name that represents a dependent
Douglas Gregor71395fa2009-11-04 00:56:37 +00008018/// template name such as \c MetaFun::template operator+.
Fangrui Song6907ce22018-07-30 19:24:48 +00008019TemplateName
Douglas Gregor71395fa2009-11-04 00:56:37 +00008020ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00008021 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00008022 assert((!NNS || NNS->isDependent()) &&
8023 "Nested name specifier must be dependent");
Fangrui Song6907ce22018-07-30 19:24:48 +00008024
Douglas Gregor71395fa2009-11-04 00:56:37 +00008025 llvm::FoldingSetNodeID ID;
8026 DependentTemplateName::Profile(ID, NNS, Operator);
Craig Topper36250ad2014-05-12 05:36:57 +00008027
8028 void *InsertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00008029 DependentTemplateName *QTN
8030 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Fangrui Song6907ce22018-07-30 19:24:48 +00008031
Douglas Gregor71395fa2009-11-04 00:56:37 +00008032 if (QTN)
8033 return TemplateName(QTN);
Fangrui Song6907ce22018-07-30 19:24:48 +00008034
Douglas Gregor71395fa2009-11-04 00:56:37 +00008035 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
8036 if (CanonNNS == NNS) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00008037 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00008038 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00008039 } else {
8040 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00008041 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00008042 DependentTemplateName(NNS, Operator, Canon);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00008043
Douglas Gregorc42075a2010-02-04 18:10:26 +00008044 DependentTemplateName *CheckQTN
8045 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
8046 assert(!CheckQTN && "Dependent template name canonicalization broken");
8047 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00008048 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008049
Douglas Gregor71395fa2009-11-04 00:56:37 +00008050 DependentTemplateNames.InsertNode(QTN, InsertPos);
8051 return TemplateName(QTN);
8052}
8053
Fangrui Song6907ce22018-07-30 19:24:48 +00008054TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00008055ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
8056 TemplateName replacement) const {
8057 llvm::FoldingSetNodeID ID;
8058 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00008059
8060 void *insertPos = nullptr;
John McCalld9dfe3a2011-06-30 08:33:18 +00008061 SubstTemplateTemplateParmStorage *subst
8062 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
Fangrui Song6907ce22018-07-30 19:24:48 +00008063
John McCalld9dfe3a2011-06-30 08:33:18 +00008064 if (!subst) {
8065 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
8066 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
8067 }
8068
8069 return TemplateName(subst);
8070}
8071
Fangrui Song6907ce22018-07-30 19:24:48 +00008072TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00008073ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
8074 const TemplateArgument &ArgPack) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00008075 auto &Self = const_cast<ASTContext &>(*this);
Douglas Gregor5590be02011-01-15 06:45:20 +00008076 llvm::FoldingSetNodeID ID;
8077 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00008078
8079 void *InsertPos = nullptr;
Douglas Gregor5590be02011-01-15 06:45:20 +00008080 SubstTemplateTemplateParmPackStorage *Subst
8081 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
Fangrui Song6907ce22018-07-30 19:24:48 +00008082
Douglas Gregor5590be02011-01-15 06:45:20 +00008083 if (!Subst) {
Fangrui Song6907ce22018-07-30 19:24:48 +00008084 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00008085 ArgPack.pack_size(),
8086 ArgPack.pack_begin());
8087 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
8088 }
8089
8090 return TemplateName(Subst);
8091}
8092
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00008093/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00008094/// TargetInfo, produce the corresponding type. The unsigned @p Type
8095/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00008096CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00008097 switch (Type) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00008098 case TargetInfo::NoInt: return {};
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00008099 case TargetInfo::SignedChar: return SignedCharTy;
8100 case TargetInfo::UnsignedChar: return UnsignedCharTy;
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00008101 case TargetInfo::SignedShort: return ShortTy;
8102 case TargetInfo::UnsignedShort: return UnsignedShortTy;
8103 case TargetInfo::SignedInt: return IntTy;
8104 case TargetInfo::UnsignedInt: return UnsignedIntTy;
8105 case TargetInfo::SignedLong: return LongTy;
8106 case TargetInfo::UnsignedLong: return UnsignedLongTy;
8107 case TargetInfo::SignedLongLong: return LongLongTy;
8108 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
8109 }
8110
David Blaikie83d382b2011-09-23 05:06:16 +00008111 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00008112}
Ted Kremenek77c51b22008-07-24 23:58:27 +00008113
8114//===----------------------------------------------------------------------===//
8115// Type Predicates.
8116//===----------------------------------------------------------------------===//
8117
Fariborz Jahanian96207692009-02-18 21:49:28 +00008118/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
8119/// garbage collection attribute.
8120///
John McCall553d45a2011-01-12 00:34:59 +00008121Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00008122 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00008123 return Qualifiers::GCNone;
8124
Erik Pilkingtonfa983902018-10-30 20:31:30 +00008125 assert(getLangOpts().ObjC);
John McCall553d45a2011-01-12 00:34:59 +00008126 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
8127
8128 // Default behaviour under objective-C's gc is for ObjC pointers
8129 // (or pointers to them) be treated as though they were declared
8130 // as __strong.
8131 if (GCAttrs == Qualifiers::GCNone) {
8132 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
8133 return Qualifiers::Strong;
8134 else if (Ty->isPointerType())
Simon Pilgrimeed4b122019-10-02 11:48:06 +00008135 return getObjCGCAttrKind(Ty->castAs<PointerType>()->getPointeeType());
John McCall553d45a2011-01-12 00:34:59 +00008136 } else {
8137 // It's not valid to set GC attributes on anything that isn't a
8138 // pointer.
8139#ifndef NDEBUG
8140 QualType CT = Ty->getCanonicalTypeInternal();
Eugene Zelenko7855e772018-04-03 00:11:50 +00008141 while (const auto *AT = dyn_cast<ArrayType>(CT))
John McCall553d45a2011-01-12 00:34:59 +00008142 CT = AT->getElementType();
8143 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
8144#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00008145 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00008146 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00008147}
8148
Chris Lattner49af6a42008-04-07 06:51:04 +00008149//===----------------------------------------------------------------------===//
8150// Type Compatibility Testing
8151//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00008152
Mike Stump11289f42009-09-09 15:08:12 +00008153/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00008154/// compatible.
8155static bool areCompatVectorTypes(const VectorType *LHS,
8156 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00008157 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00008158 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00008159 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00008160}
8161
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00008162bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
8163 QualType SecondVec) {
8164 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
8165 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
8166
8167 if (hasSameUnqualifiedType(FirstVec, SecondVec))
8168 return true;
8169
Bob Wilsone6aeebb2010-11-12 17:24:54 +00008170 // Treat Neon vector types and most AltiVec vector types as if they are the
8171 // equivalent GCC vector types.
Simon Pilgrimeed4b122019-10-02 11:48:06 +00008172 const auto *First = FirstVec->castAs<VectorType>();
8173 const auto *Second = SecondVec->castAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00008174 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00008175 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00008176 First->getVectorKind() != VectorType::AltiVecPixel &&
8177 First->getVectorKind() != VectorType::AltiVecBool &&
8178 Second->getVectorKind() != VectorType::AltiVecPixel &&
8179 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00008180 return true;
8181
8182 return false;
8183}
8184
Akira Hatanaka3f2c9912019-09-07 00:34:47 +00008185bool ASTContext::hasDirectOwnershipQualifier(QualType Ty) const {
8186 while (true) {
8187 // __strong id
8188 if (const AttributedType *Attr = dyn_cast<AttributedType>(Ty)) {
8189 if (Attr->getAttrKind() == attr::ObjCOwnership)
8190 return true;
8191
8192 Ty = Attr->getModifiedType();
8193
8194 // X *__strong (...)
8195 } else if (const ParenType *Paren = dyn_cast<ParenType>(Ty)) {
8196 Ty = Paren->getInnerType();
8197
8198 // We do not want to look through typedefs, typeof(expr),
8199 // typeof(type), or any other way that the type is somehow
8200 // abstracted.
8201 } else {
8202 return false;
8203 }
8204 }
8205}
8206
Steve Naroff8e6aee52009-07-23 01:01:38 +00008207//===----------------------------------------------------------------------===//
8208// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
8209//===----------------------------------------------------------------------===//
8210
8211/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
8212/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00008213bool
8214ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
8215 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00008216 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00008217 return true;
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00008218 for (auto *PI : rProto->protocols())
8219 if (ProtocolCompatibleWithProtocol(lProto, PI))
Steve Naroff8e6aee52009-07-23 01:01:38 +00008220 return true;
8221 return false;
8222}
8223
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00008224/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
8225/// Class<pr1, ...>.
James Y Knightc2ca0032019-09-21 22:31:28 +00008226bool ASTContext::ObjCQualifiedClassTypesAreCompatible(
8227 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs) {
8228 for (auto *lhsProto : lhs->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00008229 bool match = false;
James Y Knightc2ca0032019-09-21 22:31:28 +00008230 for (auto *rhsProto : rhs->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00008231 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
8232 match = true;
8233 break;
8234 }
8235 }
8236 if (!match)
8237 return false;
8238 }
8239 return true;
8240}
8241
Steve Naroff8e6aee52009-07-23 01:01:38 +00008242/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
8243/// ObjCQualifiedIDType.
James Y Knightc2ca0032019-09-21 22:31:28 +00008244bool ASTContext::ObjCQualifiedIdTypesAreCompatible(
8245 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs,
8246 bool compare) {
James Y Knightccc4d832019-10-17 15:27:04 +00008247 // Allow id<P..> and an 'id' in all cases.
8248 if (lhs->isObjCIdType() || rhs->isObjCIdType())
Steve Naroff8e6aee52009-07-23 01:01:38 +00008249 return true;
James Y Knightccc4d832019-10-17 15:27:04 +00008250
8251 // Don't allow id<P..> to convert to Class or Class<P..> in either direction.
8252 if (lhs->isObjCClassType() || lhs->isObjCQualifiedClassType() ||
8253 rhs->isObjCClassType() || rhs->isObjCQualifiedClassType())
8254 return false;
Steve Naroff8e6aee52009-07-23 01:01:38 +00008255
James Y Knightc2ca0032019-09-21 22:31:28 +00008256 if (lhs->isObjCQualifiedIdType()) {
8257 if (rhs->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00008258 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00008259 // make sure we check the class hierarchy.
James Y Knightc2ca0032019-09-21 22:31:28 +00008260 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
8261 for (auto *I : lhs->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00008262 // when comparing an id<P> on lhs with a static type on rhs,
8263 // see if static class implements all of id's protocols, directly or
8264 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00008265 if (!rhsID->ClassImplementsProtocol(I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00008266 return false;
8267 }
8268 }
8269 // If there are no qualifiers and no interface, we have an 'id'.
8270 return true;
8271 }
Mike Stump11289f42009-09-09 15:08:12 +00008272 // Both the right and left sides have qualifiers.
James Y Knightc2ca0032019-09-21 22:31:28 +00008273 for (auto *lhsProto : lhs->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00008274 bool match = false;
8275
8276 // when comparing an id<P> on lhs with a static type on rhs,
8277 // see if static class implements all of id's protocols, directly or
8278 // through its super class and categories.
James Y Knightc2ca0032019-09-21 22:31:28 +00008279 for (auto *rhsProto : rhs->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00008280 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
8281 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
8282 match = true;
8283 break;
8284 }
8285 }
Mike Stump11289f42009-09-09 15:08:12 +00008286 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00008287 // make sure we check the class hierarchy.
James Y Knightc2ca0032019-09-21 22:31:28 +00008288 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
8289 for (auto *I : lhs->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00008290 // when comparing an id<P> on lhs with a static type on rhs,
8291 // see if static class implements all of id's protocols, directly or
8292 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00008293 if (rhsID->ClassImplementsProtocol(I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00008294 match = true;
8295 break;
8296 }
8297 }
8298 }
8299 if (!match)
8300 return false;
8301 }
Mike Stump11289f42009-09-09 15:08:12 +00008302
Steve Naroff8e6aee52009-07-23 01:01:38 +00008303 return true;
8304 }
Mike Stump11289f42009-09-09 15:08:12 +00008305
James Y Knightc2ca0032019-09-21 22:31:28 +00008306 assert(rhs->isObjCQualifiedIdType() && "One of the LHS/RHS should be id<x>");
Steve Naroff8e6aee52009-07-23 01:01:38 +00008307
James Y Knightc2ca0032019-09-21 22:31:28 +00008308 if (lhs->getInterfaceType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00008309 // If both the right and left sides have qualifiers.
James Y Knightc2ca0032019-09-21 22:31:28 +00008310 for (auto *lhsProto : lhs->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00008311 bool match = false;
8312
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00008313 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00008314 // see if static class implements all of id's protocols, directly or
8315 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00008316 // First, lhs protocols in the qualifier list must be found, direct
8317 // or indirect in rhs's qualifier list or it is a mismatch.
James Y Knightc2ca0032019-09-21 22:31:28 +00008318 for (auto *rhsProto : rhs->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00008319 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
8320 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
8321 match = true;
8322 break;
8323 }
8324 }
8325 if (!match)
8326 return false;
8327 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008328
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00008329 // Static class's protocols, or its super class or category protocols
8330 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
James Y Knightc2ca0032019-09-21 22:31:28 +00008331 if (ObjCInterfaceDecl *lhsID = lhs->getInterfaceDecl()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00008332 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
8333 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
8334 // This is rather dubious but matches gcc's behavior. If lhs has
8335 // no type qualifier and its class has no static protocol(s)
8336 // assume that it is mismatch.
James Y Knightc2ca0032019-09-21 22:31:28 +00008337 if (LHSInheritedProtocols.empty() && lhs->qual_empty())
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00008338 return false;
Aaron Ballman83731462014-03-17 16:14:00 +00008339 for (auto *lhsProto : LHSInheritedProtocols) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00008340 bool match = false;
James Y Knightc2ca0032019-09-21 22:31:28 +00008341 for (auto *rhsProto : rhs->quals()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00008342 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
8343 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
8344 match = true;
8345 break;
8346 }
8347 }
8348 if (!match)
8349 return false;
8350 }
8351 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00008352 return true;
8353 }
8354 return false;
8355}
8356
Eli Friedman47f77112008-08-22 00:56:42 +00008357/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00008358/// compatible for assignment from RHS to LHS. This handles validation of any
8359/// protocol qualifiers on the LHS or RHS.
Steve Naroff7cae42b2009-07-10 23:34:53 +00008360bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
8361 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00008362 const ObjCObjectType* LHS = LHSOPT->getObjectType();
8363 const ObjCObjectType* RHS = RHSOPT->getObjectType();
8364
James Y Knightccc4d832019-10-17 15:27:04 +00008365 // If either type represents the built-in 'id' type, return true.
8366 if (LHS->isObjCUnqualifiedId() || RHS->isObjCUnqualifiedId())
Steve Naroff7cae42b2009-07-10 23:34:53 +00008367 return true;
8368
Douglas Gregorab209d82015-07-07 03:58:42 +00008369 // Function object that propagates a successful result or handles
8370 // __kindof types.
8371 auto finish = [&](bool succeeded) -> bool {
8372 if (succeeded)
8373 return true;
8374
8375 if (!RHS->isKindOfType())
8376 return false;
8377
8378 // Strip off __kindof and protocol qualifiers, then check whether
8379 // we can assign the other way.
8380 return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this),
8381 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
8382 };
8383
James Y Knightccc4d832019-10-17 15:27:04 +00008384 // Casts from or to id<P> are allowed when the other side has compatible
8385 // protocols.
Douglas Gregorab209d82015-07-07 03:58:42 +00008386 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
James Y Knightc2ca0032019-09-21 22:31:28 +00008387 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false));
Douglas Gregorab209d82015-07-07 03:58:42 +00008388 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008389
James Y Knightccc4d832019-10-17 15:27:04 +00008390 // Verify protocol compatibility for casts from Class<P1> to Class<P2>.
Douglas Gregorab209d82015-07-07 03:58:42 +00008391 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
James Y Knightc2ca0032019-09-21 22:31:28 +00008392 return finish(ObjCQualifiedClassTypesAreCompatible(LHSOPT, RHSOPT));
Douglas Gregorab209d82015-07-07 03:58:42 +00008393 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008394
James Y Knightccc4d832019-10-17 15:27:04 +00008395 // Casts from Class to Class<Foo>, or vice-versa, are allowed.
8396 if (LHS->isObjCClass() && RHS->isObjCClass()) {
8397 return true;
8398 }
8399
John McCall8b07ec22010-05-15 11:32:37 +00008400 // If we have 2 user-defined types, fall into that path.
Douglas Gregorab209d82015-07-07 03:58:42 +00008401 if (LHS->getInterface() && RHS->getInterface()) {
8402 return finish(canAssignObjCInterfaces(LHS, RHS));
8403 }
Mike Stump11289f42009-09-09 15:08:12 +00008404
Steve Naroff8e6aee52009-07-23 01:01:38 +00008405 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00008406}
8407
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008408/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Fangrui Song6907ce22018-07-30 19:24:48 +00008409/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008410/// arguments in block literals. When passed as arguments, passing 'A*' where
8411/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
8412/// not OK. For the return type, the opposite is not OK.
8413bool ASTContext::canAssignObjCInterfacesInBlockPointer(
8414 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00008415 const ObjCObjectPointerType *RHSOPT,
8416 bool BlockReturnType) {
Douglas Gregorab209d82015-07-07 03:58:42 +00008417
8418 // Function object that propagates a successful result or handles
8419 // __kindof types.
8420 auto finish = [&](bool succeeded) -> bool {
8421 if (succeeded)
8422 return true;
8423
8424 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
8425 if (!Expected->isKindOfType())
8426 return false;
8427
8428 // Strip off __kindof and protocol qualifiers, then check whether
8429 // we can assign the other way.
8430 return canAssignObjCInterfacesInBlockPointer(
8431 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
8432 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
8433 BlockReturnType);
8434 };
8435
Fariborz Jahanian440a6832010-04-06 17:23:39 +00008436 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008437 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00008438
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008439 if (LHSOPT->isObjCBuiltinType()) {
Douglas Gregorab209d82015-07-07 03:58:42 +00008440 return finish(RHSOPT->isObjCBuiltinType() ||
8441 RHSOPT->isObjCQualifiedIdType());
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008442 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008443
Fariborz Jahanian440a6832010-04-06 17:23:39 +00008444 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Volodymyr Sapsai73152a22019-08-28 00:25:06 +00008445 return finish(ObjCQualifiedIdTypesAreCompatible(
James Y Knightc2ca0032019-09-21 22:31:28 +00008446 (BlockReturnType ? LHSOPT : RHSOPT),
8447 (BlockReturnType ? RHSOPT : LHSOPT), false));
Fangrui Song6907ce22018-07-30 19:24:48 +00008448
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008449 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
8450 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
8451 if (LHS && RHS) { // We have 2 user-defined types.
8452 if (LHS != RHS) {
8453 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00008454 return finish(BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008455 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00008456 return finish(!BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008457 }
8458 else
8459 return true;
8460 }
8461 return false;
8462}
8463
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008464/// Comparison routine for Objective-C protocols to be used with
8465/// llvm::array_pod_sort.
8466static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
8467 ObjCProtocolDecl * const *rhs) {
8468 return (*lhs)->getName().compare((*rhs)->getName());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008469}
8470
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008471/// getIntersectionOfProtocols - This routine finds the intersection of set
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008472/// of protocols inherited from two distinct objective-c pointer objects with
8473/// the given common base.
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008474/// It is used to build composite qualifier list of the composite type of
8475/// the conditional expression involving two objective-c pointer objects.
Fangrui Song6907ce22018-07-30 19:24:48 +00008476static
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008477void getIntersectionOfProtocols(ASTContext &Context,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008478 const ObjCInterfaceDecl *CommonBase,
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008479 const ObjCObjectPointerType *LHSOPT,
8480 const ObjCObjectPointerType *RHSOPT,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008481 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
Fangrui Song6907ce22018-07-30 19:24:48 +00008482
John McCall8b07ec22010-05-15 11:32:37 +00008483 const ObjCObjectType* LHS = LHSOPT->getObjectType();
8484 const ObjCObjectType* RHS = RHSOPT->getObjectType();
8485 assert(LHS->getInterface() && "LHS must have an interface base");
8486 assert(RHS->getInterface() && "RHS must have an interface base");
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008487
8488 // Add all of the protocols for the LHS.
8489 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
8490
8491 // Start with the protocol qualifiers.
8492 for (auto proto : LHS->quals()) {
8493 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008494 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008495
8496 // Also add the protocols associated with the LHS interface.
8497 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
8498
Raphael Isemannb23ccec2018-12-10 12:37:46 +00008499 // Add all of the protocols for the RHS.
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008500 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
8501
8502 // Start with the protocol qualifiers.
8503 for (auto proto : RHS->quals()) {
8504 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008505 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008506
8507 // Also add the protocols associated with the RHS interface.
8508 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
8509
8510 // Compute the intersection of the collected protocol sets.
8511 for (auto proto : LHSProtocolSet) {
8512 if (RHSProtocolSet.count(proto))
8513 IntersectionSet.push_back(proto);
8514 }
8515
8516 // Compute the set of protocols that is implied by either the common type or
8517 // the protocols within the intersection.
8518 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
8519 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
8520
8521 // Remove any implied protocols from the list of inherited protocols.
8522 if (!ImpliedProtocols.empty()) {
8523 IntersectionSet.erase(
8524 std::remove_if(IntersectionSet.begin(),
8525 IntersectionSet.end(),
8526 [&](ObjCProtocolDecl *proto) -> bool {
8527 return ImpliedProtocols.count(proto) > 0;
8528 }),
8529 IntersectionSet.end());
8530 }
8531
8532 // Sort the remaining protocols by name.
8533 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
8534 compareObjCProtocolsByName);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008535}
8536
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008537/// Determine whether the first type is a subtype of the second.
8538static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
8539 QualType rhs) {
8540 // Common case: two object pointers.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008541 const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
8542 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008543 if (lhsOPT && rhsOPT)
8544 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
8545
8546 // Two block pointers.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008547 const auto *lhsBlock = lhs->getAs<BlockPointerType>();
8548 const auto *rhsBlock = rhs->getAs<BlockPointerType>();
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008549 if (lhsBlock && rhsBlock)
8550 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
8551
8552 // If either is an unqualified 'id' and the other is a block, it's
8553 // acceptable.
8554 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
8555 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
8556 return true;
8557
8558 return false;
8559}
8560
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008561// Check that the given Objective-C type argument lists are equivalent.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008562static bool sameObjCTypeArgs(ASTContext &ctx,
8563 const ObjCInterfaceDecl *iface,
8564 ArrayRef<QualType> lhsArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00008565 ArrayRef<QualType> rhsArgs,
8566 bool stripKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008567 if (lhsArgs.size() != rhsArgs.size())
8568 return false;
8569
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008570 ObjCTypeParamList *typeParams = iface->getTypeParamList();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008571 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008572 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
8573 continue;
8574
8575 switch (typeParams->begin()[i]->getVariance()) {
8576 case ObjCTypeParamVariance::Invariant:
Douglas Gregorab209d82015-07-07 03:58:42 +00008577 if (!stripKindOf ||
8578 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
8579 rhsArgs[i].stripObjCKindOfType(ctx))) {
8580 return false;
8581 }
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008582 break;
8583
8584 case ObjCTypeParamVariance::Covariant:
8585 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
8586 return false;
8587 break;
8588
8589 case ObjCTypeParamVariance::Contravariant:
8590 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
8591 return false;
8592 break;
Douglas Gregorab209d82015-07-07 03:58:42 +00008593 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008594 }
8595
8596 return true;
8597}
8598
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00008599QualType ASTContext::areCommonBaseCompatible(
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008600 const ObjCObjectPointerType *Lptr,
8601 const ObjCObjectPointerType *Rptr) {
John McCall8b07ec22010-05-15 11:32:37 +00008602 const ObjCObjectType *LHS = Lptr->getObjectType();
8603 const ObjCObjectType *RHS = Rptr->getObjectType();
8604 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
8605 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008606
8607 if (!LDecl || !RDecl)
Eugene Zelenko7855e772018-04-03 00:11:50 +00008608 return {};
Douglas Gregore83b9562015-07-07 03:57:53 +00008609
Manman Renc46f7d12016-05-06 19:35:02 +00008610 // When either LHS or RHS is a kindof type, we should return a kindof type.
8611 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
8612 // kindof(A).
8613 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
8614
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008615 // Follow the left-hand side up the class hierarchy until we either hit a
8616 // root or find the RHS. Record the ancestors in case we don't find it.
8617 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
8618 LHSAncestors;
8619 while (true) {
8620 // Record this ancestor. We'll need this if the common type isn't in the
8621 // path from the LHS to the root.
8622 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
Douglas Gregore83b9562015-07-07 03:57:53 +00008623
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008624 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
8625 // Get the type arguments.
8626 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
8627 bool anyChanges = false;
8628 if (LHS->isSpecialized() && RHS->isSpecialized()) {
8629 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008630 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
8631 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00008632 /*stripKindOf=*/true))
Eugene Zelenko7855e772018-04-03 00:11:50 +00008633 return {};
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008634 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
8635 // If only one has type arguments, the result will not have type
8636 // arguments.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00008637 LHSTypeArgs = {};
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008638 anyChanges = true;
8639 }
8640
8641 // Compute the intersection of protocols.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008642 SmallVector<ObjCProtocolDecl *, 8> Protocols;
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008643 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
8644 Protocols);
John McCall8b07ec22010-05-15 11:32:37 +00008645 if (!Protocols.empty())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008646 anyChanges = true;
8647
8648 // If anything in the LHS will have changed, build a new result type.
Manman Renc46f7d12016-05-06 19:35:02 +00008649 // If we need to return a kindof type but LHS is not a kindof type, we
8650 // build a new result type.
8651 if (anyChanges || LHS->isKindOfType() != anyKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008652 QualType Result = getObjCInterfaceType(LHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00008653 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
Manman Renc46f7d12016-05-06 19:35:02 +00008654 anyKindOf || LHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008655 return getObjCObjectPointerType(Result);
8656 }
8657
8658 return getObjCObjectPointerType(QualType(LHS, 0));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008659 }
Douglas Gregore83b9562015-07-07 03:57:53 +00008660
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008661 // Find the superclass.
Douglas Gregore83b9562015-07-07 03:57:53 +00008662 QualType LHSSuperType = LHS->getSuperClassType();
8663 if (LHSSuperType.isNull())
8664 break;
8665
8666 LHS = LHSSuperType->castAs<ObjCObjectType>();
8667 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008668
8669 // We didn't find anything by following the LHS to its root; now check
8670 // the RHS against the cached set of ancestors.
8671 while (true) {
8672 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
8673 if (KnownLHS != LHSAncestors.end()) {
8674 LHS = KnownLHS->second;
8675
8676 // Get the type arguments.
8677 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
8678 bool anyChanges = false;
8679 if (LHS->isSpecialized() && RHS->isSpecialized()) {
8680 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008681 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
8682 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00008683 /*stripKindOf=*/true))
Eugene Zelenko7855e772018-04-03 00:11:50 +00008684 return {};
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008685 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
8686 // If only one has type arguments, the result will not have type
8687 // arguments.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00008688 RHSTypeArgs = {};
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008689 anyChanges = true;
8690 }
8691
8692 // Compute the intersection of protocols.
8693 SmallVector<ObjCProtocolDecl *, 8> Protocols;
8694 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
8695 Protocols);
8696 if (!Protocols.empty())
8697 anyChanges = true;
8698
Manman Renc46f7d12016-05-06 19:35:02 +00008699 // If we need to return a kindof type but RHS is not a kindof type, we
8700 // build a new result type.
8701 if (anyChanges || RHS->isKindOfType() != anyKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008702 QualType Result = getObjCInterfaceType(RHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00008703 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
Manman Renc46f7d12016-05-06 19:35:02 +00008704 anyKindOf || RHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008705 return getObjCObjectPointerType(Result);
8706 }
8707
8708 return getObjCObjectPointerType(QualType(RHS, 0));
8709 }
8710
8711 // Find the superclass of the RHS.
8712 QualType RHSSuperType = RHS->getSuperClassType();
8713 if (RHSSuperType.isNull())
8714 break;
8715
8716 RHS = RHSSuperType->castAs<ObjCObjectType>();
8717 }
8718
Eugene Zelenko7855e772018-04-03 00:11:50 +00008719 return {};
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00008720}
8721
John McCall8b07ec22010-05-15 11:32:37 +00008722bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
8723 const ObjCObjectType *RHS) {
8724 assert(LHS->getInterface() && "LHS is not an interface type");
8725 assert(RHS->getInterface() && "RHS is not an interface type");
8726
Chris Lattner49af6a42008-04-07 06:51:04 +00008727 // Verify that the base decls are compatible: the RHS must be a subclass of
8728 // the LHS.
Douglas Gregore83b9562015-07-07 03:57:53 +00008729 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
8730 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
8731 if (!IsSuperClass)
Chris Lattner49af6a42008-04-07 06:51:04 +00008732 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008733
Douglas Gregore83b9562015-07-07 03:57:53 +00008734 // If the LHS has protocol qualifiers, determine whether all of them are
8735 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
8736 // LHS).
8737 if (LHS->getNumProtocols() > 0) {
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00008738 // OK if conversion of LHS to SuperClass results in narrowing of types
8739 // ; i.e., SuperClass may implement at least one of the protocols
8740 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
8741 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
8742 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
8743 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
8744 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
8745 // qualifiers.
8746 for (auto *RHSPI : RHS->quals())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008747 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00008748 // If there is no protocols associated with RHS, it is not a match.
8749 if (SuperClassInheritedProtocols.empty())
Steve Naroff114aecb2009-03-01 16:12:44 +00008750 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00008751
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00008752 for (const auto *LHSProto : LHS->quals()) {
8753 bool SuperImplementsProtocol = false;
8754 for (auto *SuperClassProto : SuperClassInheritedProtocols)
8755 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
8756 SuperImplementsProtocol = true;
8757 break;
8758 }
8759 if (!SuperImplementsProtocol)
8760 return false;
8761 }
Chris Lattner49af6a42008-04-07 06:51:04 +00008762 }
Douglas Gregore83b9562015-07-07 03:57:53 +00008763
8764 // If the LHS is specialized, we may need to check type arguments.
8765 if (LHS->isSpecialized()) {
8766 // Follow the superclass chain until we've matched the LHS class in the
8767 // hierarchy. This substitutes type arguments through.
8768 const ObjCObjectType *RHSSuper = RHS;
8769 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
8770 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
8771
8772 // If the RHS is specializd, compare type arguments.
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008773 if (RHSSuper->isSpecialized() &&
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008774 !sameObjCTypeArgs(*this, LHS->getInterface(),
8775 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00008776 /*stripKindOf=*/true)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008777 return false;
Douglas Gregore83b9562015-07-07 03:57:53 +00008778 }
8779 }
8780
8781 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00008782}
8783
Steve Naroffb7605152009-02-12 17:52:19 +00008784bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
8785 // get the "pointed to" types
Eugene Zelenko7855e772018-04-03 00:11:50 +00008786 const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
8787 const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00008788
Steve Naroff7cae42b2009-07-10 23:34:53 +00008789 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00008790 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00008791
8792 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
8793 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00008794}
8795
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00008796bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
8797 return canAssignObjCInterfaces(
Simon Pilgrim5f9fcfb2020-03-12 14:28:16 +00008798 getObjCObjectPointerType(To)->castAs<ObjCObjectPointerType>(),
8799 getObjCObjectPointerType(From)->castAs<ObjCObjectPointerType>());
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00008800}
8801
Mike Stump11289f42009-09-09 15:08:12 +00008802/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00008803/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00008804/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00008805/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008806bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
8807 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00008808 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00008809 return hasSameType(LHS, RHS);
Joey Gouly5788b782016-11-18 14:10:54 +00008810
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008811 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00008812}
8813
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00008814bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00008815 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00008816}
8817
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008818bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
8819 return !mergeTypes(LHS, RHS, true).isNull();
8820}
8821
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00008822/// mergeTransparentUnionType - if T is a transparent union type and a member
8823/// of T is compatible with SubType, return the merged type, else return
8824/// QualType()
8825QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
8826 bool OfBlockPointer,
8827 bool Unqualified) {
8828 if (const RecordType *UT = T->getAsUnionType()) {
8829 RecordDecl *UD = UT->getDecl();
8830 if (UD->hasAttr<TransparentUnionAttr>()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008831 for (const auto *I : UD->fields()) {
8832 QualType ET = I->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00008833 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
8834 if (!MT.isNull())
8835 return MT;
8836 }
8837 }
8838 }
8839
Eugene Zelenko7855e772018-04-03 00:11:50 +00008840 return {};
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00008841}
8842
Alp Toker9cacbab2014-01-20 20:26:09 +00008843/// mergeFunctionParameterTypes - merge two types which appear as function
8844/// parameter types
8845QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
8846 bool OfBlockPointer,
8847 bool Unqualified) {
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00008848 // GNU extension: two types are compatible if they appear as a function
8849 // argument, one of the types is a transparent union type and the other
8850 // type is compatible with a union member
8851 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
8852 Unqualified);
8853 if (!lmerge.isNull())
8854 return lmerge;
8855
8856 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
8857 Unqualified);
8858 if (!rmerge.isNull())
8859 return rmerge;
8860
8861 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
8862}
8863
Fangrui Song6907ce22018-07-30 19:24:48 +00008864QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Johannes Doerfert8f0aa3f2020-04-01 17:07:10 -05008865 bool OfBlockPointer, bool Unqualified,
8866 bool AllowCXX) {
Simon Pilgrim40311f92020-01-13 14:31:03 +00008867 const auto *lbase = lhs->castAs<FunctionType>();
8868 const auto *rbase = rhs->castAs<FunctionType>();
Eugene Zelenko7855e772018-04-03 00:11:50 +00008869 const auto *lproto = dyn_cast<FunctionProtoType>(lbase);
8870 const auto *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00008871 bool allLTypes = true;
8872 bool allRTypes = true;
8873
8874 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008875 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00008876 if (OfBlockPointer) {
Alp Toker314cc812014-01-25 16:55:45 +00008877 QualType RHS = rbase->getReturnType();
8878 QualType LHS = lbase->getReturnType();
Fariborz Jahanian17825972011-02-11 18:46:17 +00008879 bool UnqualifiedResult = Unqualified;
8880 if (!UnqualifiedResult)
8881 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00008882 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00008883 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008884 else
Alp Toker314cc812014-01-25 16:55:45 +00008885 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
John McCall8c6b56f2010-12-15 01:06:38 +00008886 Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00008887 if (retType.isNull())
8888 return {};
Fangrui Song6907ce22018-07-30 19:24:48 +00008889
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008890 if (Unqualified)
8891 retType = retType.getUnqualifiedType();
8892
Alp Toker314cc812014-01-25 16:55:45 +00008893 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
8894 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008895 if (Unqualified) {
8896 LRetType = LRetType.getUnqualifiedType();
8897 RRetType = RRetType.getUnqualifiedType();
8898 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008899
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008900 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00008901 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008902 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00008903 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00008904
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00008905 // FIXME: double check this
8906 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
8907 // rbase->getRegParmAttr() != 0 &&
8908 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00008909 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
8910 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00008911
Douglas Gregor8c940862010-01-18 17:14:39 +00008912 // Compatible functions must have compatible calling conventions
Reid Kleckner78af0702013-08-27 23:08:25 +00008913 if (lbaseInfo.getCC() != rbaseInfo.getCC())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008914 return {};
Mike Stump11289f42009-09-09 15:08:12 +00008915
John McCall8c6b56f2010-12-15 01:06:38 +00008916 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00008917 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008918 return {};
John McCall8c6b56f2010-12-15 01:06:38 +00008919 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008920 return {};
John McCall8c6b56f2010-12-15 01:06:38 +00008921
John McCall31168b02011-06-15 23:02:42 +00008922 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008923 return {};
Oren Ben Simhon318a6ea2017-04-27 12:01:00 +00008924 if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008925 return {};
Oren Ben Simhon220671a2018-03-17 13:31:35 +00008926 if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008927 return {};
John McCall31168b02011-06-15 23:02:42 +00008928
John McCall8c6b56f2010-12-15 01:06:38 +00008929 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
8930 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00008931
Rafael Espindola8778c282012-11-29 16:09:03 +00008932 if (lbaseInfo.getNoReturn() != NoReturn)
8933 allLTypes = false;
8934 if (rbaseInfo.getNoReturn() != NoReturn)
8935 allRTypes = false;
8936
John McCall31168b02011-06-15 23:02:42 +00008937 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00008938
Eli Friedman47f77112008-08-22 00:56:42 +00008939 if (lproto && rproto) { // two C99 style function prototypes
Johannes Doerfert8f0aa3f2020-04-01 17:07:10 -05008940 assert((AllowCXX ||
8941 (!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec())) &&
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00008942 "C++ shouldn't be here");
Alp Toker601b22c2014-01-21 23:35:24 +00008943 // Compatible functions must have the same number of parameters
8944 if (lproto->getNumParams() != rproto->getNumParams())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008945 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00008946
8947 // Variadic and non-variadic functions aren't compatible
8948 if (lproto->isVariadic() != rproto->isVariadic())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008949 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00008950
Anastasia Stulovac61eaa52019-01-28 11:37:49 +00008951 if (lproto->getMethodQuals() != rproto->getMethodQuals())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008952 return {};
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00008953
Akira Hatanaka98a49332017-09-22 00:41:05 +00008954 SmallVector<FunctionProtoType::ExtParameterInfo, 4> newParamInfos;
8955 bool canUseLeft, canUseRight;
8956 if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight,
8957 newParamInfos))
Eugene Zelenko7855e772018-04-03 00:11:50 +00008958 return {};
Alp Toker601b22c2014-01-21 23:35:24 +00008959
Akira Hatanaka98a49332017-09-22 00:41:05 +00008960 if (!canUseLeft)
8961 allLTypes = false;
8962 if (!canUseRight)
8963 allRTypes = false;
8964
Alp Toker601b22c2014-01-21 23:35:24 +00008965 // Check parameter type compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008966 SmallVector<QualType, 10> types;
Alp Toker601b22c2014-01-21 23:35:24 +00008967 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
8968 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
8969 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
8970 QualType paramType = mergeFunctionParameterTypes(
8971 lParamType, rParamType, OfBlockPointer, Unqualified);
8972 if (paramType.isNull())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008973 return {};
Alp Toker601b22c2014-01-21 23:35:24 +00008974
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008975 if (Unqualified)
Alp Toker601b22c2014-01-21 23:35:24 +00008976 paramType = paramType.getUnqualifiedType();
8977
8978 types.push_back(paramType);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008979 if (Unqualified) {
Alp Toker601b22c2014-01-21 23:35:24 +00008980 lParamType = lParamType.getUnqualifiedType();
8981 rParamType = rParamType.getUnqualifiedType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008982 }
Alp Toker601b22c2014-01-21 23:35:24 +00008983
8984 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00008985 allLTypes = false;
Alp Toker601b22c2014-01-21 23:35:24 +00008986 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00008987 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00008988 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008989
Eli Friedman47f77112008-08-22 00:56:42 +00008990 if (allLTypes) return lhs;
8991 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00008992
8993 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
8994 EPI.ExtInfo = einfo;
Akira Hatanaka98a49332017-09-22 00:41:05 +00008995 EPI.ExtParameterInfos =
8996 newParamInfos.empty() ? nullptr : newParamInfos.data();
Jordan Rose5c382722013-03-08 21:51:21 +00008997 return getFunctionType(retType, types, EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00008998 }
8999
9000 if (lproto) allRTypes = false;
9001 if (rproto) allLTypes = false;
9002
Douglas Gregordeaad8c2009-02-26 23:50:07 +00009003 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00009004 if (proto) {
Johannes Doerfert8f0aa3f2020-04-01 17:07:10 -05009005 assert((AllowCXX || !proto->hasExceptionSpec()) && "C++ shouldn't be here");
Eugene Zelenko7855e772018-04-03 00:11:50 +00009006 if (proto->isVariadic())
9007 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00009008 // Check that the types are compatible with the types that
9009 // would result from default argument promotions (C99 6.7.5.3p15).
9010 // The only types actually affected are promotable integer
9011 // types and floats, which would be passed as a different
9012 // type depending on whether the prototype is visible.
Alp Toker601b22c2014-01-21 23:35:24 +00009013 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
9014 QualType paramTy = proto->getParamType(i);
Alp Toker9cacbab2014-01-20 20:26:09 +00009015
Eli Friedman448ce402012-08-30 00:44:15 +00009016 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00009017 // to pass enum values.
Eugene Zelenko7855e772018-04-03 00:11:50 +00009018 if (const auto *Enum = paramTy->getAs<EnumType>()) {
Alp Toker601b22c2014-01-21 23:35:24 +00009019 paramTy = Enum->getDecl()->getIntegerType();
9020 if (paramTy.isNull())
Eugene Zelenko7855e772018-04-03 00:11:50 +00009021 return {};
Eli Friedman448ce402012-08-30 00:44:15 +00009022 }
Alp Toker601b22c2014-01-21 23:35:24 +00009023
9024 if (paramTy->isPromotableIntegerType() ||
9025 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
Eugene Zelenko7855e772018-04-03 00:11:50 +00009026 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00009027 }
9028
9029 if (allLTypes) return lhs;
9030 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00009031
9032 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
9033 EPI.ExtInfo = einfo;
Alp Toker9cacbab2014-01-20 20:26:09 +00009034 return getFunctionType(retType, proto->getParamTypes(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00009035 }
9036
9037 if (allLTypes) return lhs;
9038 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00009039 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00009040}
9041
John McCall433c2e62013-03-21 00:10:07 +00009042/// Given that we have an enum type and a non-enum type, try to merge them.
9043static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
9044 QualType other, bool isBlockReturnType) {
9045 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
9046 // a signed integer type, or an unsigned integer type.
9047 // Compatibility is based on the underlying type, not the promotion
9048 // type.
9049 QualType underlyingType = ET->getDecl()->getIntegerType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00009050 if (underlyingType.isNull())
9051 return {};
John McCall433c2e62013-03-21 00:10:07 +00009052 if (Context.hasSameType(underlyingType, other))
9053 return other;
9054
9055 // In block return types, we're more permissive and accept any
9056 // integral type of the same size.
9057 if (isBlockReturnType && other->isIntegerType() &&
9058 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
9059 return other;
9060
Eugene Zelenko7855e772018-04-03 00:11:50 +00009061 return {};
John McCall433c2e62013-03-21 00:10:07 +00009062}
9063
Fangrui Song6907ce22018-07-30 19:24:48 +00009064QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00009065 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00009066 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00009067 // C++ [expr]: If an expression initially has the type "reference to T", the
9068 // type is adjusted to "T" prior to any further analysis, the expression
9069 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00009070 // expression is an lvalue unless the reference is an rvalue reference and
9071 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00009072 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
9073 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00009074
9075 if (Unqualified) {
9076 LHS = LHS.getUnqualifiedType();
9077 RHS = RHS.getUnqualifiedType();
9078 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009079
Eli Friedman47f77112008-08-22 00:56:42 +00009080 QualType LHSCan = getCanonicalType(LHS),
9081 RHSCan = getCanonicalType(RHS);
9082
9083 // If two types are identical, they are compatible.
9084 if (LHSCan == RHSCan)
9085 return LHS;
9086
John McCall8ccfcb52009-09-24 19:53:00 +00009087 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00009088 Qualifiers LQuals = LHSCan.getLocalQualifiers();
9089 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00009090 if (LQuals != RQuals) {
9091 // If any of these qualifiers are different, we have a type
9092 // mismatch.
9093 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00009094 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
Roger Ferrer Ibanezd93add32017-02-24 08:41:09 +00009095 LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
9096 LQuals.hasUnaligned() != RQuals.hasUnaligned())
Eugene Zelenko7855e772018-04-03 00:11:50 +00009097 return {};
John McCall8ccfcb52009-09-24 19:53:00 +00009098
9099 // Exactly one GC qualifier difference is allowed: __strong is
9100 // okay if the other type has no GC qualifier but is an Objective
9101 // C object pointer (i.e. implicitly strong by default). We fix
9102 // this by pretending that the unqualified type was actually
9103 // qualified __strong.
9104 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
9105 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
9106 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
9107
9108 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
Eugene Zelenko7855e772018-04-03 00:11:50 +00009109 return {};
John McCall8ccfcb52009-09-24 19:53:00 +00009110
9111 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
9112 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
9113 }
9114 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
9115 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
9116 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00009117 return {};
John McCall8ccfcb52009-09-24 19:53:00 +00009118 }
9119
9120 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00009121
Eli Friedmandcca6332009-06-01 01:22:52 +00009122 Type::TypeClass LHSClass = LHSCan->getTypeClass();
9123 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00009124
Chris Lattnerfd652912008-01-14 05:45:46 +00009125 // We want to consider the two function types to be the same for these
9126 // comparisons, just force one to the other.
9127 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
9128 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00009129
9130 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00009131 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
9132 LHSClass = Type::ConstantArray;
9133 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
9134 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00009135
John McCall8b07ec22010-05-15 11:32:37 +00009136 // ObjCInterfaces are just specialized ObjCObjects.
9137 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
9138 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
9139
Nate Begemance4d7fc2008-04-18 23:10:10 +00009140 // Canonicalize ExtVector -> Vector.
9141 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
9142 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00009143
Chris Lattner95554662008-04-07 05:43:21 +00009144 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00009145 if (LHSClass != RHSClass) {
John McCall433c2e62013-03-21 00:10:07 +00009146 // Note that we only have special rules for turning block enum
9147 // returns into block int returns, not vice-versa.
Eugene Zelenko7855e772018-04-03 00:11:50 +00009148 if (const auto *ETy = LHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00009149 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00009150 }
John McCall9dd450b2009-09-21 23:43:11 +00009151 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00009152 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00009153 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00009154 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00009155 if (OfBlockPointer && !BlockReturnType) {
9156 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
9157 return LHS;
9158 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
9159 return RHS;
9160 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009161
Eugene Zelenko7855e772018-04-03 00:11:50 +00009162 return {};
Steve Naroff32e44c02007-10-15 20:41:53 +00009163 }
Eli Friedman47f77112008-08-22 00:56:42 +00009164
Steve Naroffc6edcbd2008-01-09 22:43:08 +00009165 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00009166 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00009167#define TYPE(Class, Base)
9168#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00009169#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00009170#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
9171#define DEPENDENT_TYPE(Class, Base) case Type::Class:
John McCall36b12a82019-10-02 06:35:23 +00009172#include "clang/AST/TypeNodes.inc"
David Blaikie83d382b2011-09-23 05:06:16 +00009173 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00009174
Richard Smith27d807c2013-04-30 13:56:41 +00009175 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00009176 case Type::DeducedTemplateSpecialization:
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00009177 case Type::LValueReference:
9178 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00009179 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00009180 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00009181
John McCall8b07ec22010-05-15 11:32:37 +00009182 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00009183 case Type::IncompleteArray:
9184 case Type::VariableArray:
9185 case Type::FunctionProto:
9186 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00009187 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00009188
Chris Lattnerfd652912008-01-14 05:45:46 +00009189 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00009190 {
9191 // Merge two pointer types, while trying to preserve typedef info
Simon Pilgrimeed4b122019-10-02 11:48:06 +00009192 QualType LHSPointee = LHS->castAs<PointerType>()->getPointeeType();
9193 QualType RHSPointee = RHS->castAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00009194 if (Unqualified) {
9195 LHSPointee = LHSPointee.getUnqualifiedType();
9196 RHSPointee = RHSPointee.getUnqualifiedType();
9197 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009198 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00009199 Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00009200 if (ResultType.isNull())
9201 return {};
Eli Friedman091a9ac2009-06-02 05:28:56 +00009202 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00009203 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00009204 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00009205 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00009206 return getPointerType(ResultType);
9207 }
Steve Naroff68e167d2008-12-10 17:49:55 +00009208 case Type::BlockPointer:
9209 {
9210 // Merge two block pointer types, while trying to preserve typedef info
Simon Pilgrimeed4b122019-10-02 11:48:06 +00009211 QualType LHSPointee = LHS->castAs<BlockPointerType>()->getPointeeType();
9212 QualType RHSPointee = RHS->castAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00009213 if (Unqualified) {
9214 LHSPointee = LHSPointee.getUnqualifiedType();
9215 RHSPointee = RHSPointee.getUnqualifiedType();
9216 }
Anastasia Stulova81a25e352017-03-10 15:23:07 +00009217 if (getLangOpts().OpenCL) {
9218 Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
9219 Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
9220 // Blocks can't be an expression in a ternary operator (OpenCL v2.0
9221 // 6.12.5) thus the following check is asymmetric.
9222 if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual))
Eugene Zelenko7855e772018-04-03 00:11:50 +00009223 return {};
Anastasia Stulova81a25e352017-03-10 15:23:07 +00009224 LHSPteeQual.removeAddressSpace();
9225 RHSPteeQual.removeAddressSpace();
9226 LHSPointee =
9227 QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
9228 RHSPointee =
9229 QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
9230 }
Douglas Gregor17ea3f52010-07-29 15:18:02 +00009231 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
9232 Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00009233 if (ResultType.isNull())
9234 return {};
Steve Naroff68e167d2008-12-10 17:49:55 +00009235 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
9236 return LHS;
9237 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
9238 return RHS;
9239 return getBlockPointerType(ResultType);
9240 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00009241 case Type::Atomic:
9242 {
9243 // Merge two pointer types, while trying to preserve typedef info
Simon Pilgrimeed4b122019-10-02 11:48:06 +00009244 QualType LHSValue = LHS->castAs<AtomicType>()->getValueType();
9245 QualType RHSValue = RHS->castAs<AtomicType>()->getValueType();
Eli Friedman0dfb8892011-10-06 23:00:33 +00009246 if (Unqualified) {
9247 LHSValue = LHSValue.getUnqualifiedType();
9248 RHSValue = RHSValue.getUnqualifiedType();
9249 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009250 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
Eli Friedman0dfb8892011-10-06 23:00:33 +00009251 Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00009252 if (ResultType.isNull())
9253 return {};
Eli Friedman0dfb8892011-10-06 23:00:33 +00009254 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
9255 return LHS;
9256 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
9257 return RHS;
9258 return getAtomicType(ResultType);
9259 }
Chris Lattnerfd652912008-01-14 05:45:46 +00009260 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00009261 {
9262 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
9263 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
9264 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
Eugene Zelenko7855e772018-04-03 00:11:50 +00009265 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00009266
9267 QualType LHSElem = getAsArrayType(LHS)->getElementType();
9268 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00009269 if (Unqualified) {
9270 LHSElem = LHSElem.getUnqualifiedType();
9271 RHSElem = RHSElem.getUnqualifiedType();
9272 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009273
Douglas Gregor17ea3f52010-07-29 15:18:02 +00009274 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00009275 if (ResultType.isNull())
9276 return {};
Jeremy Morse8129c5c2018-06-05 09:18:26 +00009277
9278 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
9279 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
9280
9281 // If either side is a variable array, and both are complete, check whether
9282 // the current dimension is definite.
9283 if (LVAT || RVAT) {
9284 auto SizeFetch = [this](const VariableArrayType* VAT,
9285 const ConstantArrayType* CAT)
9286 -> std::pair<bool,llvm::APInt> {
9287 if (VAT) {
9288 llvm::APSInt TheInt;
9289 Expr *E = VAT->getSizeExpr();
9290 if (E && E->isIntegerConstantExpr(TheInt, *this))
9291 return std::make_pair(true, TheInt);
9292 else
9293 return std::make_pair(false, TheInt);
9294 } else if (CAT) {
9295 return std::make_pair(true, CAT->getSize());
9296 } else {
9297 return std::make_pair(false, llvm::APInt());
9298 }
9299 };
9300
9301 bool HaveLSize, HaveRSize;
9302 llvm::APInt LSize, RSize;
9303 std::tie(HaveLSize, LSize) = SizeFetch(LVAT, LCAT);
9304 std::tie(HaveRSize, RSize) = SizeFetch(RVAT, RCAT);
9305 if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(LSize, RSize))
9306 return {}; // Definite, but unequal, array dimension
9307 }
9308
Chris Lattner465fa322008-10-05 17:34:18 +00009309 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
9310 return LHS;
9311 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
9312 return RHS;
Richard Smith772e2662019-10-04 01:25:59 +00009313 if (LCAT)
9314 return getConstantArrayType(ResultType, LCAT->getSize(),
9315 LCAT->getSizeExpr(),
9316 ArrayType::ArraySizeModifier(), 0);
9317 if (RCAT)
9318 return getConstantArrayType(ResultType, RCAT->getSize(),
9319 RCAT->getSizeExpr(),
9320 ArrayType::ArraySizeModifier(), 0);
Chris Lattner465fa322008-10-05 17:34:18 +00009321 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
9322 return LHS;
9323 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
9324 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00009325 if (LVAT) {
9326 // FIXME: This isn't correct! But tricky to implement because
9327 // the array's size has to be the size of LHS, but the type
9328 // has to be different.
9329 return LHS;
9330 }
9331 if (RVAT) {
9332 // FIXME: This isn't correct! But tricky to implement because
9333 // the array's size has to be the size of RHS, but the type
9334 // has to be different.
9335 return RHS;
9336 }
Eli Friedman3e62c212008-08-22 01:48:21 +00009337 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
9338 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00009339 return getIncompleteArrayType(ResultType,
9340 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00009341 }
Chris Lattnerfd652912008-01-14 05:45:46 +00009342 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00009343 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00009344 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00009345 case Type::Enum:
Eugene Zelenko7855e772018-04-03 00:11:50 +00009346 return {};
Chris Lattnerfd652912008-01-14 05:45:46 +00009347 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00009348 // Only exactly equal builtin types are compatible, which is tested above.
Eugene Zelenko7855e772018-04-03 00:11:50 +00009349 return {};
Daniel Dunbar804c0442009-01-28 21:22:12 +00009350 case Type::Complex:
9351 // Distinct complex types are incompatible.
Eugene Zelenko7855e772018-04-03 00:11:50 +00009352 return {};
Chris Lattner7bbd3d72008-04-07 05:55:38 +00009353 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00009354 // FIXME: The merged type should be an ExtVector!
Simon Pilgrim9588ae72019-10-03 21:47:42 +00009355 if (areCompatVectorTypes(LHSCan->castAs<VectorType>(),
9356 RHSCan->castAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00009357 return LHS;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009358 return {};
John McCall8b07ec22010-05-15 11:32:37 +00009359 case Type::ObjCObject: {
9360 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00009361 // FIXME: This should be type compatibility, e.g. whether
9362 // "LHS x; RHS x;" at global scope is legal.
Simon Pilgrim9588ae72019-10-03 21:47:42 +00009363 if (canAssignObjCInterfaces(LHS->castAs<ObjCObjectType>(),
9364 RHS->castAs<ObjCObjectType>()))
Steve Naroff7a7814c2009-02-21 16:18:07 +00009365 return LHS;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009366 return {};
Cedric Venet4fc88b72009-02-21 17:14:49 +00009367 }
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009368 case Type::ObjCObjectPointer:
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00009369 if (OfBlockPointer) {
9370 if (canAssignObjCInterfacesInBlockPointer(
Simon Pilgrim9588ae72019-10-03 21:47:42 +00009371 LHS->castAs<ObjCObjectPointerType>(),
9372 RHS->castAs<ObjCObjectPointerType>(), BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00009373 return LHS;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009374 return {};
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00009375 }
Simon Pilgrim9588ae72019-10-03 21:47:42 +00009376 if (canAssignObjCInterfaces(LHS->castAs<ObjCObjectPointerType>(),
9377 RHS->castAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00009378 return LHS;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009379 return {};
Xiuli Pan9c14e282016-01-09 12:53:17 +00009380 case Type::Pipe:
Joey Goulye3c85de2016-12-01 11:30:49 +00009381 assert(LHS != RHS &&
9382 "Equivalent pipe types should have already been handled!");
Eugene Zelenko7855e772018-04-03 00:11:50 +00009383 return {};
Xiuli Pan9c14e282016-01-09 12:53:17 +00009384 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00009385
David Blaikie8a40f702012-01-17 06:56:22 +00009386 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00009387}
Ted Kremenekfc581a92007-10-31 17:10:13 +00009388
Akira Hatanaka98a49332017-09-22 00:41:05 +00009389bool ASTContext::mergeExtParameterInfo(
9390 const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType,
9391 bool &CanUseFirst, bool &CanUseSecond,
9392 SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &NewParamInfos) {
9393 assert(NewParamInfos.empty() && "param info list not empty");
9394 CanUseFirst = CanUseSecond = true;
9395 bool FirstHasInfo = FirstFnType->hasExtParameterInfos();
9396 bool SecondHasInfo = SecondFnType->hasExtParameterInfos();
9397
John McCall18afab72016-03-01 00:49:02 +00009398 // Fast path: if the first type doesn't have ext parameter infos,
Akira Hatanaka98a49332017-09-22 00:41:05 +00009399 // we match if and only if the second type also doesn't have them.
9400 if (!FirstHasInfo && !SecondHasInfo)
9401 return true;
John McCall18afab72016-03-01 00:49:02 +00009402
Akira Hatanaka98a49332017-09-22 00:41:05 +00009403 bool NeedParamInfo = false;
9404 size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size()
9405 : SecondFnType->getExtParameterInfos().size();
John McCall18afab72016-03-01 00:49:02 +00009406
Akira Hatanaka98a49332017-09-22 00:41:05 +00009407 for (size_t I = 0; I < E; ++I) {
9408 FunctionProtoType::ExtParameterInfo FirstParam, SecondParam;
9409 if (FirstHasInfo)
9410 FirstParam = FirstFnType->getExtParameterInfo(I);
9411 if (SecondHasInfo)
9412 SecondParam = SecondFnType->getExtParameterInfo(I);
John McCall18afab72016-03-01 00:49:02 +00009413
Akira Hatanaka98a49332017-09-22 00:41:05 +00009414 // Cannot merge unless everything except the noescape flag matches.
9415 if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false))
John McCall18afab72016-03-01 00:49:02 +00009416 return false;
Akira Hatanaka98a49332017-09-22 00:41:05 +00009417
9418 bool FirstNoEscape = FirstParam.isNoEscape();
9419 bool SecondNoEscape = SecondParam.isNoEscape();
9420 bool IsNoEscape = FirstNoEscape && SecondNoEscape;
9421 NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape));
9422 if (NewParamInfos.back().getOpaqueValue())
9423 NeedParamInfo = true;
9424 if (FirstNoEscape != IsNoEscape)
9425 CanUseFirst = false;
9426 if (SecondNoEscape != IsNoEscape)
9427 CanUseSecond = false;
John McCall18afab72016-03-01 00:49:02 +00009428 }
Akira Hatanaka98a49332017-09-22 00:41:05 +00009429
9430 if (!NeedParamInfo)
9431 NewParamInfos.clear();
9432
Fariborz Jahanian97676972011-09-28 21:52:05 +00009433 return true;
9434}
9435
Chandler Carruth21c90602015-12-30 03:24:14 +00009436void ASTContext::ResetObjCLayout(const ObjCContainerDecl *CD) {
9437 ObjCLayouts[CD] = nullptr;
9438}
9439
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009440/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
9441/// 'RHS' attributes and returns the merged version; including for function
9442/// return types.
9443QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
9444 QualType LHSCan = getCanonicalType(LHS),
9445 RHSCan = getCanonicalType(RHS);
9446 // If two types are identical, they are compatible.
9447 if (LHSCan == RHSCan)
9448 return LHS;
9449 if (RHSCan->isFunctionType()) {
9450 if (!LHSCan->isFunctionType())
Eugene Zelenko7855e772018-04-03 00:11:50 +00009451 return {};
Alp Toker314cc812014-01-25 16:55:45 +00009452 QualType OldReturnType =
9453 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009454 QualType NewReturnType =
Alp Toker314cc812014-01-25 16:55:45 +00009455 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
Fangrui Song6907ce22018-07-30 19:24:48 +00009456 QualType ResReturnType =
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009457 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
9458 if (ResReturnType.isNull())
Eugene Zelenko7855e772018-04-03 00:11:50 +00009459 return {};
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009460 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
9461 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
9462 // In either case, use OldReturnType to build the new function type.
Simon Pilgrim9588ae72019-10-03 21:47:42 +00009463 const auto *F = LHS->castAs<FunctionType>();
Eugene Zelenko7855e772018-04-03 00:11:50 +00009464 if (const auto *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00009465 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9466 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner896b32f2013-06-10 20:51:09 +00009467 QualType ResultType =
Alp Toker9cacbab2014-01-20 20:26:09 +00009468 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009469 return ResultType;
9470 }
9471 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00009472 return {};
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009473 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009474
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009475 // If the qualifiers are different, the types can still be merged.
9476 Qualifiers LQuals = LHSCan.getLocalQualifiers();
9477 Qualifiers RQuals = RHSCan.getLocalQualifiers();
9478 if (LQuals != RQuals) {
9479 // If any of these qualifiers are different, we have a type mismatch.
9480 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
9481 LQuals.getAddressSpace() != RQuals.getAddressSpace())
Eugene Zelenko7855e772018-04-03 00:11:50 +00009482 return {};
Fangrui Song6907ce22018-07-30 19:24:48 +00009483
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009484 // Exactly one GC qualifier difference is allowed: __strong is
9485 // okay if the other type has no GC qualifier but is an Objective
9486 // C object pointer (i.e. implicitly strong by default). We fix
9487 // this by pretending that the unqualified type was actually
9488 // qualified __strong.
9489 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
9490 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
9491 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
Fangrui Song6907ce22018-07-30 19:24:48 +00009492
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009493 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
Eugene Zelenko7855e772018-04-03 00:11:50 +00009494 return {};
Fangrui Song6907ce22018-07-30 19:24:48 +00009495
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009496 if (GC_L == Qualifiers::Strong)
9497 return LHS;
9498 if (GC_R == Qualifiers::Strong)
9499 return RHS;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009500 return {};
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009501 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009502
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009503 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
Simon Pilgrimeed4b122019-10-02 11:48:06 +00009504 QualType LHSBaseQT = LHS->castAs<ObjCObjectPointerType>()->getPointeeType();
9505 QualType RHSBaseQT = RHS->castAs<ObjCObjectPointerType>()->getPointeeType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009506 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
9507 if (ResQT == LHSBaseQT)
9508 return LHS;
9509 if (ResQT == RHSBaseQT)
9510 return RHS;
9511 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00009512 return {};
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009513}
9514
Chris Lattner4ba0cef2008-04-07 07:01:58 +00009515//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009516// Integer Predicates
9517//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00009518
Jay Foad39c79802011-01-12 09:06:06 +00009519unsigned ASTContext::getIntWidth(QualType T) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00009520 if (const auto *ET = T->getAs<EnumType>())
Eli Friedmanee275c82009-12-10 22:29:29 +00009521 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00009522 if (T->isBooleanType())
9523 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00009524 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009525 return (unsigned)getTypeSize(T);
9526}
9527
Abramo Bagnara13640492012-09-09 10:21:24 +00009528QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Leonard Chanab80f3c2018-06-14 14:53:51 +00009529 assert((T->hasSignedIntegerRepresentation() || T->isSignedFixedPointType()) &&
9530 "Unexpected type");
Fangrui Song6907ce22018-07-30 19:24:48 +00009531
Chris Lattnerec3a1562009-10-17 20:33:28 +00009532 // Turn <4 x signed int> -> <4 x unsigned int>
Eugene Zelenko7855e772018-04-03 00:11:50 +00009533 if (const auto *VTy = T->getAs<VectorType>())
Chris Lattnerec3a1562009-10-17 20:33:28 +00009534 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00009535 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00009536
9537 // For enums, we return the unsigned version of the base type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00009538 if (const auto *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009539 T = ETy->getDecl()->getIntegerType();
Fangrui Song6907ce22018-07-30 19:24:48 +00009540
Simon Pilgrim9588ae72019-10-03 21:47:42 +00009541 switch (T->castAs<BuiltinType>()->getKind()) {
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009542 case BuiltinType::Char_S:
9543 case BuiltinType::SChar:
9544 return UnsignedCharTy;
9545 case BuiltinType::Short:
9546 return UnsignedShortTy;
9547 case BuiltinType::Int:
9548 return UnsignedIntTy;
9549 case BuiltinType::Long:
9550 return UnsignedLongTy;
9551 case BuiltinType::LongLong:
9552 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00009553 case BuiltinType::Int128:
9554 return UnsignedInt128Ty;
Leonard Chanab80f3c2018-06-14 14:53:51 +00009555
9556 case BuiltinType::ShortAccum:
9557 return UnsignedShortAccumTy;
9558 case BuiltinType::Accum:
9559 return UnsignedAccumTy;
9560 case BuiltinType::LongAccum:
9561 return UnsignedLongAccumTy;
9562 case BuiltinType::SatShortAccum:
9563 return SatUnsignedShortAccumTy;
9564 case BuiltinType::SatAccum:
9565 return SatUnsignedAccumTy;
9566 case BuiltinType::SatLongAccum:
9567 return SatUnsignedLongAccumTy;
9568 case BuiltinType::ShortFract:
9569 return UnsignedShortFractTy;
9570 case BuiltinType::Fract:
9571 return UnsignedFractTy;
9572 case BuiltinType::LongFract:
9573 return UnsignedLongFractTy;
9574 case BuiltinType::SatShortFract:
9575 return SatUnsignedShortFractTy;
9576 case BuiltinType::SatFract:
9577 return SatUnsignedFractTy;
9578 case BuiltinType::SatLongFract:
9579 return SatUnsignedLongFractTy;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009580 default:
Leonard Chanab80f3c2018-06-14 14:53:51 +00009581 llvm_unreachable("Unexpected signed integer or fixed point type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009582 }
9583}
9584
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009585ASTMutationListener::~ASTMutationListener() = default;
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00009586
Richard Smith1fa5d642013-05-11 05:45:24 +00009587void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
9588 QualType ReturnType) {}
Chris Lattnerecd79c62009-06-14 00:45:47 +00009589
9590//===----------------------------------------------------------------------===//
9591// Builtin Type Computation
9592//===----------------------------------------------------------------------===//
9593
9594/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00009595/// pointer over the consumed characters. This returns the resultant type. If
9596/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
9597/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
9598/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009599///
9600/// RequiresICE is filled in on return to indicate whether the value is required
9601/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00009602static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00009603 ASTContext::GetBuiltinTypeError &Error,
Chandler Carruth45bbe012017-03-24 09:11:57 +00009604 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00009605 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00009606 // Modifiers.
9607 int HowLong = 0;
9608 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009609 RequiresICE = false;
Fangrui Song6907ce22018-07-30 19:24:48 +00009610
Chris Lattnerdc226c22010-10-01 22:42:38 +00009611 // Read the prefixed modifiers first.
Eric Christopher50daf5f2017-07-10 21:28:54 +00009612 bool Done = false;
9613 #ifndef NDEBUG
Karl-Johan Karlsson0e525a42019-05-16 07:18:02 +00009614 bool IsSpecial = false;
Eric Christopher50daf5f2017-07-10 21:28:54 +00009615 #endif
Chris Lattnerecd79c62009-06-14 00:45:47 +00009616 while (!Done) {
9617 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00009618 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00009619 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009620 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00009621 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009622 case 'S':
9623 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
9624 assert(!Signed && "Can't use 'S' modifier multiple times!");
9625 Signed = true;
9626 break;
9627 case 'U':
9628 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
Sean Silva2a995142015-01-16 21:44:26 +00009629 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00009630 Unsigned = true;
9631 break;
9632 case 'L':
Andrew Savonichevfa8cd762019-06-03 12:34:59 +00009633 assert(!IsSpecial && "Can't use 'L' with 'W', 'N', 'Z' or 'O' modifiers");
Chris Lattnerecd79c62009-06-14 00:45:47 +00009634 assert(HowLong <= 2 && "Can't have LLLL modifier");
9635 ++HowLong;
9636 break;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009637 case 'N':
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00009638 // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
Andrew Savonichevfa8cd762019-06-03 12:34:59 +00009639 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00009640 assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
Eric Christopher50daf5f2017-07-10 21:28:54 +00009641 #ifndef NDEBUG
Karl-Johan Karlsson0e525a42019-05-16 07:18:02 +00009642 IsSpecial = true;
Eric Christopher50daf5f2017-07-10 21:28:54 +00009643 #endif
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00009644 if (Context.getTargetInfo().getLongWidth() == 32)
9645 ++HowLong;
9646 break;
Kevin Qinad64f6d2014-02-24 02:45:03 +00009647 case 'W':
9648 // This modifier represents int64 type.
Andrew Savonichevfa8cd762019-06-03 12:34:59 +00009649 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
Kevin Qinad64f6d2014-02-24 02:45:03 +00009650 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
Eric Christopher50daf5f2017-07-10 21:28:54 +00009651 #ifndef NDEBUG
Karl-Johan Karlsson0e525a42019-05-16 07:18:02 +00009652 IsSpecial = true;
Eric Christopher50daf5f2017-07-10 21:28:54 +00009653 #endif
Kevin Qinad64f6d2014-02-24 02:45:03 +00009654 switch (Context.getTargetInfo().getInt64Type()) {
9655 default:
9656 llvm_unreachable("Unexpected integer type");
9657 case TargetInfo::SignedLong:
9658 HowLong = 1;
9659 break;
9660 case TargetInfo::SignedLongLong:
9661 HowLong = 2;
9662 break;
9663 }
Duncan P. N. Exon Smitheae8caa2017-06-14 21:26:31 +00009664 break;
Karl-Johan Karlsson0e525a42019-05-16 07:18:02 +00009665 case 'Z':
9666 // This modifier represents int32 type.
Andrew Savonichevfa8cd762019-06-03 12:34:59 +00009667 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
Karl-Johan Karlsson0e525a42019-05-16 07:18:02 +00009668 assert(HowLong == 0 && "Can't use both 'L' and 'Z' modifiers!");
9669 #ifndef NDEBUG
9670 IsSpecial = true;
9671 #endif
9672 switch (Context.getTargetInfo().getIntTypeByWidth(32, true)) {
9673 default:
9674 llvm_unreachable("Unexpected integer type");
9675 case TargetInfo::SignedInt:
9676 HowLong = 0;
9677 break;
9678 case TargetInfo::SignedLong:
9679 HowLong = 1;
9680 break;
9681 case TargetInfo::SignedLongLong:
9682 HowLong = 2;
9683 break;
9684 }
9685 break;
Andrew Savonichevfa8cd762019-06-03 12:34:59 +00009686 case 'O':
9687 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
9688 assert(HowLong == 0 && "Can't use both 'L' and 'O' modifiers!");
9689 #ifndef NDEBUG
9690 IsSpecial = true;
9691 #endif
9692 if (Context.getLangOpts().OpenCL)
9693 HowLong = 1;
9694 else
9695 HowLong = 2;
9696 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009697 }
9698 }
9699
9700 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00009701
Chris Lattnerecd79c62009-06-14 00:45:47 +00009702 // Read the base type.
9703 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00009704 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00009705 case 'v':
9706 assert(HowLong == 0 && !Signed && !Unsigned &&
9707 "Bad modifiers used with 'v'!");
9708 Type = Context.VoidTy;
9709 break;
Jack Carter24bef982013-08-15 15:16:57 +00009710 case 'h':
9711 assert(HowLong == 0 && !Signed && !Unsigned &&
Sean Silva2a995142015-01-16 21:44:26 +00009712 "Bad modifiers used with 'h'!");
Jack Carter24bef982013-08-15 15:16:57 +00009713 Type = Context.HalfTy;
9714 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009715 case 'f':
9716 assert(HowLong == 0 && !Signed && !Unsigned &&
9717 "Bad modifiers used with 'f'!");
9718 Type = Context.FloatTy;
9719 break;
9720 case 'd':
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009721 assert(HowLong < 3 && !Signed && !Unsigned &&
Chris Lattnerecd79c62009-06-14 00:45:47 +00009722 "Bad modifiers used with 'd'!");
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009723 if (HowLong == 1)
Chris Lattnerecd79c62009-06-14 00:45:47 +00009724 Type = Context.LongDoubleTy;
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009725 else if (HowLong == 2)
9726 Type = Context.Float128Ty;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009727 else
9728 Type = Context.DoubleTy;
9729 break;
9730 case 's':
9731 assert(HowLong == 0 && "Bad modifiers used with 's'!");
9732 if (Unsigned)
9733 Type = Context.UnsignedShortTy;
9734 else
9735 Type = Context.ShortTy;
9736 break;
9737 case 'i':
9738 if (HowLong == 3)
9739 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
9740 else if (HowLong == 2)
9741 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
9742 else if (HowLong == 1)
9743 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
9744 else
9745 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
9746 break;
9747 case 'c':
9748 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
9749 if (Signed)
9750 Type = Context.SignedCharTy;
9751 else if (Unsigned)
9752 Type = Context.UnsignedCharTy;
9753 else
9754 Type = Context.CharTy;
9755 break;
9756 case 'b': // boolean
9757 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
9758 Type = Context.BoolTy;
9759 break;
9760 case 'z': // size_t.
9761 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
9762 Type = Context.getSizeType();
9763 break;
Richard Smith8110c9d2016-11-29 19:45:17 +00009764 case 'w': // wchar_t.
9765 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
9766 Type = Context.getWideCharType();
9767 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009768 case 'F':
9769 Type = Context.getCFConstantStringType();
9770 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00009771 case 'G':
9772 Type = Context.getObjCIdType();
9773 break;
9774 case 'H':
9775 Type = Context.getObjCSelType();
9776 break;
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00009777 case 'M':
9778 Type = Context.getObjCSuperType();
9779 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009780 case 'a':
9781 Type = Context.getBuiltinVaListType();
9782 assert(!Type.isNull() && "builtin va list type not initialized!");
9783 break;
9784 case 'A':
9785 // This is a "reference" to a va_list; however, what exactly
9786 // this means depends on how va_list is defined. There are two
9787 // different kinds of va_list: ones passed by value, and ones
9788 // passed by reference. An example of a by-value va_list is
9789 // x86, where va_list is a char*. An example of by-ref va_list
9790 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
9791 // we want this argument to be a char*&; for x86-64, we want
9792 // it to be a __va_list_tag*.
9793 Type = Context.getBuiltinVaListType();
9794 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009795 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00009796 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009797 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00009798 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009799 break;
Sander de Smalen5087ace2020-03-15 14:29:45 +00009800 case 'q': {
9801 char *End;
9802 unsigned NumElements = strtoul(Str, &End, 10);
9803 assert(End != Str && "Missing vector size");
9804 Str = End;
9805
9806 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
9807 RequiresICE, false);
9808 assert(!RequiresICE && "Can't require vector ICE");
9809
9810 Type = Context.getScalableVectorType(ElementType, NumElements);
9811 break;
9812 }
Chris Lattnerecd79c62009-06-14 00:45:47 +00009813 case 'V': {
9814 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009815 unsigned NumElements = strtoul(Str, &End, 10);
9816 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00009817 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00009818
Fangrui Song6907ce22018-07-30 19:24:48 +00009819 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
Chandler Carruth45bbe012017-03-24 09:11:57 +00009820 RequiresICE, false);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009821 assert(!RequiresICE && "Can't require vector ICE");
Fangrui Song6907ce22018-07-30 19:24:48 +00009822
Chris Lattnerdc226c22010-10-01 22:42:38 +00009823 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00009824 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00009825 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009826 break;
9827 }
Douglas Gregorfed66992012-06-07 18:08:25 +00009828 case 'E': {
9829 char *End;
Fangrui Song6907ce22018-07-30 19:24:48 +00009830
Douglas Gregorfed66992012-06-07 18:08:25 +00009831 unsigned NumElements = strtoul(Str, &End, 10);
9832 assert(End != Str && "Missing vector size");
Fangrui Song6907ce22018-07-30 19:24:48 +00009833
Douglas Gregorfed66992012-06-07 18:08:25 +00009834 Str = End;
Fangrui Song6907ce22018-07-30 19:24:48 +00009835
Douglas Gregorfed66992012-06-07 18:08:25 +00009836 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
Chandler Carruth45bbe012017-03-24 09:11:57 +00009837 false);
Douglas Gregorfed66992012-06-07 18:08:25 +00009838 Type = Context.getExtVectorType(ElementType, NumElements);
Fangrui Song6907ce22018-07-30 19:24:48 +00009839 break;
Douglas Gregorfed66992012-06-07 18:08:25 +00009840 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00009841 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009842 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
Chandler Carruth45bbe012017-03-24 09:11:57 +00009843 false);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009844 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00009845 Type = Context.getComplexType(ElementType);
9846 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00009847 }
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009848 case 'Y':
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00009849 Type = Context.getPointerDiffType();
9850 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00009851 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00009852 Type = Context.getFILEType();
9853 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00009854 Error = ASTContext::GE_Missing_stdio;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009855 return {};
Chris Lattnerecd79c62009-06-14 00:45:47 +00009856 }
Mike Stump2adb4da2009-07-28 23:47:15 +00009857 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00009858 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00009859 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00009860 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00009861 else
9862 Type = Context.getjmp_bufType();
9863
Mike Stump2adb4da2009-07-28 23:47:15 +00009864 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00009865 Error = ASTContext::GE_Missing_setjmp;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009866 return {};
Mike Stump2adb4da2009-07-28 23:47:15 +00009867 }
9868 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00009869 case 'K':
9870 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
9871 Type = Context.getucontext_tType();
9872
9873 if (Type.isNull()) {
9874 Error = ASTContext::GE_Missing_ucontext;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009875 return {};
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00009876 }
9877 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00009878 case 'p':
9879 Type = Context.getProcessIDType();
9880 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00009881 }
Mike Stump11289f42009-09-09 15:08:12 +00009882
Chris Lattnerdc226c22010-10-01 22:42:38 +00009883 // If there are modifiers and if we're allowed to parse them, go for it.
9884 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009885 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00009886 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00009887 default: Done = true; --Str; break;
9888 case '*':
9889 case '&': {
9890 // Both pointers and references can have their pointee types
9891 // qualified with an address space.
9892 char *End;
9893 unsigned AddrSpace = strtoul(Str, &End, 10);
Matt Arsenaultc65f9662018-08-02 12:14:28 +00009894 if (End != Str) {
9895 // Note AddrSpace == 0 is not the same as an unspecified address space.
9896 Type = Context.getAddrSpaceQualType(
9897 Type,
9898 Context.getLangASForBuiltinAddressSpace(AddrSpace));
Chris Lattnerdc226c22010-10-01 22:42:38 +00009899 Str = End;
9900 }
9901 if (c == '*')
9902 Type = Context.getPointerType(Type);
9903 else
9904 Type = Context.getLValueReferenceType(Type);
9905 break;
9906 }
9907 // FIXME: There's no way to have a built-in with an rvalue ref arg.
9908 case 'C':
9909 Type = Type.withConst();
9910 break;
9911 case 'D':
9912 Type = Context.getVolatileType(Type);
9913 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00009914 case 'R':
9915 Type = Type.withRestrict();
9916 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009917 }
9918 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009919
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009920 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Fangrui Song6907ce22018-07-30 19:24:48 +00009921 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00009922
Chris Lattnerecd79c62009-06-14 00:45:47 +00009923 return Type;
9924}
9925
9926/// GetBuiltinType - Return the type for the specified builtin.
Chandler Carruth45bbe012017-03-24 09:11:57 +00009927QualType ASTContext::GetBuiltinType(unsigned Id,
9928 GetBuiltinTypeError &Error,
9929 unsigned *IntegerConstantArgs) const {
Eric Christopher02d5d862015-08-06 01:01:12 +00009930 const char *TypeStr = BuiltinInfo.getTypeString(Id);
Johannes Doerfertac991bb2019-01-19 05:36:54 +00009931 if (TypeStr[0] == '\0') {
9932 Error = GE_Missing_type;
9933 return {};
9934 }
Mike Stump11289f42009-09-09 15:08:12 +00009935
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009936 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00009937
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009938 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009939 Error = GE_None;
Chandler Carruth45bbe012017-03-24 09:11:57 +00009940 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
9941 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009942 if (Error != GE_None)
Eugene Zelenko7855e772018-04-03 00:11:50 +00009943 return {};
Fangrui Song6907ce22018-07-30 19:24:48 +00009944
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009945 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
Fangrui Song6907ce22018-07-30 19:24:48 +00009946
Chris Lattnerecd79c62009-06-14 00:45:47 +00009947 while (TypeStr[0] && TypeStr[0] != '.') {
Chandler Carruth45bbe012017-03-24 09:11:57 +00009948 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009949 if (Error != GE_None)
Eugene Zelenko7855e772018-04-03 00:11:50 +00009950 return {};
Chris Lattnerecd79c62009-06-14 00:45:47 +00009951
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009952 // If this argument is required to be an IntegerConstantExpression and the
9953 // caller cares, fill in the bitmask we return.
9954 if (RequiresICE && IntegerConstantArgs)
9955 *IntegerConstantArgs |= 1 << ArgTypes.size();
Fangrui Song6907ce22018-07-30 19:24:48 +00009956
Chris Lattnerecd79c62009-06-14 00:45:47 +00009957 // Do array -> pointer decay. The builtin should use the decayed type.
9958 if (Ty->isArrayType())
9959 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00009960
Chris Lattnerecd79c62009-06-14 00:45:47 +00009961 ArgTypes.push_back(Ty);
9962 }
9963
David Majnemerba3e5ec2015-03-13 18:26:17 +00009964 if (Id == Builtin::BI__GetExceptionInfo)
Eugene Zelenko7855e772018-04-03 00:11:50 +00009965 return {};
David Majnemerba3e5ec2015-03-13 18:26:17 +00009966
Chris Lattnerecd79c62009-06-14 00:45:47 +00009967 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
9968 "'.' should only occur at end of builtin type list!");
9969
Erich Keane881e83d2019-03-04 14:54:52 +00009970 bool Variadic = (TypeStr[0] == '.');
9971
Erich Keane00022812019-05-23 16:05:21 +00009972 FunctionType::ExtInfo EI(getDefaultCallingConvention(
9973 Variadic, /*IsCXXMethod=*/false, /*IsBuiltin=*/true));
John McCall991eb4b2010-12-21 00:44:39 +00009974 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
9975
John McCall991eb4b2010-12-21 00:44:39 +00009976
Richard Smith836de6b2016-12-19 23:59:34 +00009977 // We really shouldn't be making a no-proto type here.
9978 if (ArgTypes.empty() && Variadic && !getLangOpts().CPlusPlus)
John McCall991eb4b2010-12-21 00:44:39 +00009979 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00009980
John McCalldb40c7f2010-12-14 08:05:40 +00009981 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00009982 EPI.ExtInfo = EI;
9983 EPI.Variadic = Variadic;
Richard Smith391fb862016-10-18 07:13:55 +00009984 if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id))
9985 EPI.ExceptionSpec.Type =
9986 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
John McCalldb40c7f2010-12-14 08:05:40 +00009987
Jordan Rose5c382722013-03-08 21:51:21 +00009988 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009989}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00009990
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009991static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
9992 const FunctionDecl *FD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00009993 if (!FD->isExternallyVisible())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009994 return GVA_Internal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009995
Richard Smithe2467b72017-11-16 23:54:56 +00009996 // Non-user-provided functions get emitted as weak definitions with every
9997 // use, no matter whether they've been explicitly instantiated etc.
Eugene Zelenko7855e772018-04-03 00:11:50 +00009998 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
Richard Smithe2467b72017-11-16 23:54:56 +00009999 if (!MD->isUserProvided())
10000 return GVA_DiscardableODR;
10001
Yaron Keren4cd211b2017-02-22 14:32:39 +000010002 GVALinkage External;
Rafael Espindola3ae00052013-05-13 00:12:11 +000010003 switch (FD->getTemplateSpecializationKind()) {
10004 case TSK_Undeclared:
10005 case TSK_ExplicitSpecialization:
10006 External = GVA_StrongExternal;
10007 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +000010008
Rafael Espindola3ae00052013-05-13 00:12:11 +000010009 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +000010010 return GVA_StrongODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +000010011
David Majnemerc3d07332014-05-15 06:25:57 +000010012 // C++11 [temp.explicit]p10:
10013 // [ Note: The intent is that an inline function that is the subject of
10014 // an explicit instantiation declaration will still be implicitly
10015 // instantiated when used so that the body can be considered for
10016 // inlining, but that no out-of-line copy of the inline function would be
10017 // generated in the translation unit. -- end note ]
Rafael Espindola3ae00052013-05-13 00:12:11 +000010018 case TSK_ExplicitInstantiationDeclaration:
David Majnemer27d69db2014-04-28 22:17:59 +000010019 return GVA_AvailableExternally;
10020
Rafael Espindola3ae00052013-05-13 00:12:11 +000010021 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +000010022 External = GVA_DiscardableODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +000010023 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +000010024 }
10025
10026 if (!FD->isInlined())
10027 return External;
David Majnemer62f0ffd2013-08-01 17:26:42 +000010028
David Majnemer3f021502015-10-08 04:53:31 +000010029 if ((!Context.getLangOpts().CPlusPlus &&
10030 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
Hans Wennborgb0f2f142014-05-15 22:07:49 +000010031 !FD->hasAttr<DLLExportAttr>()) ||
David Majnemer62f0ffd2013-08-01 17:26:42 +000010032 FD->hasAttr<GNUInlineAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +000010033 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
10034
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +000010035 // GNU or C99 inline semantics. Determine whether this symbol should be
10036 // externally visible.
10037 if (FD->isInlineDefinitionExternallyVisible())
10038 return External;
10039
10040 // C99 inline semantics, where the symbol is not externally visible.
David Majnemer27d69db2014-04-28 22:17:59 +000010041 return GVA_AvailableExternally;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +000010042 }
10043
David Majnemer54e3ba52014-04-02 23:17:29 +000010044 // Functions specified with extern and inline in -fms-compatibility mode
10045 // forcibly get emitted. While the body of the function cannot be later
10046 // replaced, the function definition cannot be discarded.
David Majnemer73768702015-03-20 00:02:27 +000010047 if (FD->isMSExternInline())
David Majnemer54e3ba52014-04-02 23:17:29 +000010048 return GVA_StrongODR;
10049
David Majnemer27d69db2014-04-28 22:17:59 +000010050 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +000010051}
10052
Artem Belevichca2b9512016-05-02 20:30:03 +000010053static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context,
Richard Smitha4653622017-09-06 20:01:14 +000010054 const Decl *D, GVALinkage L) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +000010055 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
10056 // dllexport/dllimport on inline functions.
10057 if (D->hasAttr<DLLImportAttr>()) {
10058 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
10059 return GVA_AvailableExternally;
Artem Belevichca2b9512016-05-02 20:30:03 +000010060 } else if (D->hasAttr<DLLExportAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +000010061 if (L == GVA_DiscardableODR)
10062 return GVA_StrongODR;
Artem Belevichca2b9512016-05-02 20:30:03 +000010063 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice &&
10064 D->hasAttr<CUDAGlobalAttr>()) {
10065 // Device-side functions with __global__ attribute must always be
10066 // visible externally so they can be launched from host.
10067 if (L == GVA_DiscardableODR || L == GVA_Internal)
10068 return GVA_StrongODR;
Hans Wennborgb0f2f142014-05-15 22:07:49 +000010069 }
10070 return L;
10071}
10072
Richard Smitha4653622017-09-06 20:01:14 +000010073/// Adjust the GVALinkage for a declaration based on what an external AST source
10074/// knows about whether there can be other definitions of this declaration.
10075static GVALinkage
10076adjustGVALinkageForExternalDefinitionKind(const ASTContext &Ctx, const Decl *D,
10077 GVALinkage L) {
10078 ExternalASTSource *Source = Ctx.getExternalSource();
10079 if (!Source)
10080 return L;
10081
10082 switch (Source->hasExternalDefinitions(D)) {
David Blaikie9ffe5a32017-01-30 05:00:26 +000010083 case ExternalASTSource::EK_Never:
Richard Smitha4653622017-09-06 20:01:14 +000010084 // Other translation units rely on us to provide the definition.
David Blaikie9ffe5a32017-01-30 05:00:26 +000010085 if (L == GVA_DiscardableODR)
10086 return GVA_StrongODR;
10087 break;
Richard Smitha4653622017-09-06 20:01:14 +000010088
David Blaikie9ffe5a32017-01-30 05:00:26 +000010089 case ExternalASTSource::EK_Always:
10090 return GVA_AvailableExternally;
Richard Smitha4653622017-09-06 20:01:14 +000010091
David Blaikie9ffe5a32017-01-30 05:00:26 +000010092 case ExternalASTSource::EK_ReplyHazy:
10093 break;
10094 }
10095 return L;
Hans Wennborgb0f2f142014-05-15 22:07:49 +000010096}
10097
Richard Smitha4653622017-09-06 20:01:14 +000010098GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
10099 return adjustGVALinkageForExternalDefinitionKind(*this, FD,
10100 adjustGVALinkageForAttributes(*this, FD,
10101 basicGVALinkageForFunction(*this, FD)));
10102}
10103
Hans Wennborgb0f2f142014-05-15 22:07:49 +000010104static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
10105 const VarDecl *VD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +000010106 if (!VD->isExternallyVisible())
10107 return GVA_Internal;
10108
David Majnemer27d69db2014-04-28 22:17:59 +000010109 if (VD->isStaticLocal()) {
David Majnemer27d69db2014-04-28 22:17:59 +000010110 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
10111 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
10112 LexicalContext = LexicalContext->getLexicalParent();
10113
David Blaikieeb210012017-01-27 23:11:10 +000010114 // ObjC Blocks can create local variables that don't have a FunctionDecl
10115 // LexicalContext.
10116 if (!LexicalContext)
10117 return GVA_DiscardableODR;
David Majnemer27d69db2014-04-28 22:17:59 +000010118
David Blaikieeb210012017-01-27 23:11:10 +000010119 // Otherwise, let the static local variable inherit its linkage from the
10120 // nearest enclosing function.
10121 auto StaticLocalLinkage =
10122 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
10123
10124 // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
10125 // be emitted in any object with references to the symbol for the object it
10126 // contains, whether inline or out-of-line."
10127 // Similar behavior is observed with MSVC. An alternative ABI could use
10128 // StrongODR/AvailableExternally to match the function, but none are
10129 // known/supported currently.
10130 if (StaticLocalLinkage == GVA_StrongODR ||
10131 StaticLocalLinkage == GVA_AvailableExternally)
10132 return GVA_DiscardableODR;
10133 return StaticLocalLinkage;
David Majnemer27d69db2014-04-28 22:17:59 +000010134 }
10135
Hans Wennborg56fc62b2014-07-17 20:25:23 +000010136 // MSVC treats in-class initialized static data members as definitions.
10137 // By giving them non-strong linkage, out-of-line definitions won't
10138 // cause link errors.
10139 if (Context.isMSStaticDataMemberInlineDefinition(VD))
10140 return GVA_DiscardableODR;
10141
Richard Smithd9b90092016-07-02 01:32:16 +000010142 // Most non-template variables have strong linkage; inline variables are
10143 // linkonce_odr or (occasionally, for compatibility) weak_odr.
10144 GVALinkage StrongLinkage;
10145 switch (Context.getInlineVariableDefinitionKind(VD)) {
10146 case ASTContext::InlineVariableDefinitionKind::None:
10147 StrongLinkage = GVA_StrongExternal;
10148 break;
10149 case ASTContext::InlineVariableDefinitionKind::Weak:
10150 case ASTContext::InlineVariableDefinitionKind::WeakUnknown:
Richard Smith62f19e72016-06-25 00:15:56 +000010151 StrongLinkage = GVA_DiscardableODR;
Richard Smithd9b90092016-07-02 01:32:16 +000010152 break;
10153 case ASTContext::InlineVariableDefinitionKind::Strong:
10154 StrongLinkage = GVA_StrongODR;
10155 break;
10156 }
Richard Smith62f19e72016-06-25 00:15:56 +000010157
Richard Smith8809a0c2013-09-27 20:14:12 +000010158 switch (VD->getTemplateSpecializationKind()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +000010159 case TSK_Undeclared:
Richard Smith62f19e72016-06-25 00:15:56 +000010160 return StrongLinkage;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +000010161
David Majnemer6d1780c2015-07-17 23:36:49 +000010162 case TSK_ExplicitSpecialization:
Hans Wennborg4bdd5132019-09-25 11:09:46 +000010163 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
10164 VD->isStaticDataMember()
10165 ? GVA_StrongODR
10166 : StrongLinkage;
David Majnemer6d1780c2015-07-17 23:36:49 +000010167
Rafael Espindola3ae00052013-05-13 00:12:11 +000010168 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +000010169 return GVA_StrongODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +000010170
David Majnemer27d69db2014-04-28 22:17:59 +000010171 case TSK_ExplicitInstantiationDeclaration:
10172 return GVA_AvailableExternally;
10173
Rafael Espindola3ae00052013-05-13 00:12:11 +000010174 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +000010175 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +000010176 }
Rafael Espindola27699c82013-05-13 14:05:53 +000010177
10178 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +000010179}
10180
Hans Wennborgb0f2f142014-05-15 22:07:49 +000010181GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
Richard Smitha4653622017-09-06 20:01:14 +000010182 return adjustGVALinkageForExternalDefinitionKind(*this, VD,
10183 adjustGVALinkageForAttributes(*this, VD,
10184 basicGVALinkageForVariable(*this, VD)));
Hans Wennborgb0f2f142014-05-15 22:07:49 +000010185}
10186
David Blaikiee6b7c282017-04-11 20:46:34 +000010187bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Eugene Zelenko7855e772018-04-03 00:11:50 +000010188 if (const auto *VD = dyn_cast<VarDecl>(D)) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +000010189 if (!VD->isFileVarDecl())
10190 return false;
Renato Golin9258aa52014-05-21 10:40:27 +000010191 // Global named register variables (GNU extension) are never emitted.
10192 if (VD->getStorageClass() == SC_Register)
10193 return false;
Richard Smith7747ce22015-08-19 20:49:38 +000010194 if (VD->getDescribedVarTemplate() ||
10195 isa<VarTemplatePartialSpecializationDecl>(VD))
10196 return false;
Eugene Zelenko7855e772018-04-03 00:11:50 +000010197 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
Richard Smith5205a8c2013-04-01 20:22:16 +000010198 // We never need to emit an uninstantiated function template.
10199 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
10200 return false;
Nico Weber66220292016-03-02 17:28:48 +000010201 } else if (isa<PragmaCommentDecl>(D))
10202 return true;
Nico Webercbbaeb12016-03-02 19:28:54 +000010203 else if (isa<PragmaDetectMismatchDecl>(D))
10204 return true;
Alexey Bataev2d4f80f2020-02-11 15:15:21 -050010205 else if (isa<OMPRequiresDecl>(D))
10206 return true;
Nico Weber66220292016-03-02 17:28:48 +000010207 else if (isa<OMPThreadPrivateDecl>(D))
Alexey Bataevc5b1d322016-03-04 09:22:22 +000010208 return !D->getDeclContext()->isDependentContext();
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010209 else if (isa<OMPAllocateDecl>(D))
10210 return !D->getDeclContext()->isDependentContext();
Michael Krused47b9432019-08-05 18:43:21 +000010211 else if (isa<OMPDeclareReductionDecl>(D) || isa<OMPDeclareMapperDecl>(D))
Alexey Bataevc5b1d322016-03-04 09:22:22 +000010212 return !D->getDeclContext()->isDependentContext();
Richard Smithdc1f0422016-07-20 19:10:16 +000010213 else if (isa<ImportDecl>(D))
10214 return true;
Alexey Bataev97720002014-11-11 04:05:39 +000010215 else
Richard Smith5205a8c2013-04-01 20:22:16 +000010216 return false;
10217
Hans Wennborg08c5a7b2018-06-25 13:23:49 +000010218 if (D->isFromASTFile() && !LangOpts.BuildingPCHWithObjectFile) {
10219 assert(getExternalSource() && "It's from an AST file; must have a source.");
10220 // On Windows, PCH files are built together with an object file. If this
10221 // declaration comes from such a PCH and DeclMustBeEmitted would return
10222 // true, it would have returned true and the decl would have been emitted
10223 // into that object file, so it doesn't need to be emitted here.
10224 // Note that decls are still emitted if they're referenced, as usual;
10225 // DeclMustBeEmitted is used to decide whether a decl must be emitted even
10226 // if it's not referenced.
10227 //
10228 // Explicit template instantiation definitions are tricky. If there was an
10229 // explicit template instantiation decl in the PCH before, it will look like
10230 // the definition comes from there, even if that was just the declaration.
10231 // (Explicit instantiation defs of variable templates always get emitted.)
10232 bool IsExpInstDef =
10233 isa<FunctionDecl>(D) &&
10234 cast<FunctionDecl>(D)->getTemplateSpecializationKind() ==
10235 TSK_ExplicitInstantiationDefinition;
10236
Hans Wennborgb51a7032018-09-14 15:18:30 +000010237 // Implicit member function definitions, such as operator= might not be
10238 // marked as template specializations, since they're not coming from a
10239 // template but synthesized directly on the class.
10240 IsExpInstDef |=
10241 isa<CXXMethodDecl>(D) &&
10242 cast<CXXMethodDecl>(D)->getParent()->getTemplateSpecializationKind() ==
10243 TSK_ExplicitInstantiationDefinition;
10244
Hans Wennborg08c5a7b2018-06-25 13:23:49 +000010245 if (getExternalSource()->DeclIsFromPCHWithObjectFile(D) && !IsExpInstDef)
10246 return false;
10247 }
10248
Richard Smith5205a8c2013-04-01 20:22:16 +000010249 // If this is a member of a class template, we do not need to emit it.
10250 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +000010251 return false;
10252
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +000010253 // Weak references don't produce any output by themselves.
10254 if (D->hasAttr<WeakRefAttr>())
10255 return false;
10256
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +000010257 // Aliases and used decls are required.
10258 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
10259 return true;
10260
Eugene Zelenko7855e772018-04-03 00:11:50 +000010261 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +000010262 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +000010263 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +000010264 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +000010265
10266 // Constructors and destructors are required.
10267 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
10268 return true;
Hans Wennborg08c5a7b2018-06-25 13:23:49 +000010269
John McCall6bd2a892013-01-25 22:31:03 +000010270 // The key function for a class is required. This rule only comes
10271 // into play when inline functions can be key functions, though.
10272 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +000010273 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
John McCall6bd2a892013-01-25 22:31:03 +000010274 const CXXRecordDecl *RD = MD->getParent();
10275 if (MD->isOutOfLine() && RD->isDynamicClass()) {
10276 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
10277 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
10278 return true;
10279 }
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +000010280 }
10281 }
10282
David Blaikie9ffe5a32017-01-30 05:00:26 +000010283 GVALinkage Linkage = GetGVALinkageForFunction(FD);
10284
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +000010285 // static, static inline, always_inline, and extern inline functions can
10286 // always be deferred. Normal inline functions can be deferred in C99/C++.
10287 // Implicit template instantiations can also be deferred in C++.
David Blaikie9ffe5a32017-01-30 05:00:26 +000010288 return !isDiscardableGVALinkage(Linkage);
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +000010289 }
Hans Wennborg08c5a7b2018-06-25 13:23:49 +000010290
Eugene Zelenko7855e772018-04-03 00:11:50 +000010291 const auto *VD = cast<VarDecl>(D);
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +000010292 assert(VD->isFileVarDecl() && "Expected file scoped var");
10293
Alexey Bataevd01b7492018-08-15 19:45:12 +000010294 // If the decl is marked as `declare target to`, it should be emitted for the
10295 // host and for the device.
10296 if (LangOpts.OpenMP &&
10297 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
10298 return true;
10299
Hans Wennborg56fc62b2014-07-17 20:25:23 +000010300 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
10301 !isMSStaticDataMemberInlineDefinition(VD))
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +000010302 return false;
10303
Richard Smitha0e5e542012-11-12 21:38:00 +000010304 // Variables that can be needed in other TUs are required.
Richard Smitha4653622017-09-06 20:01:14 +000010305 auto Linkage = GetGVALinkageForVariable(VD);
10306 if (!isDiscardableGVALinkage(Linkage))
Richard Smitha0e5e542012-11-12 21:38:00 +000010307 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +000010308
Richard Smitha4653622017-09-06 20:01:14 +000010309 // We never need to emit a variable that is available in another TU.
10310 if (Linkage == GVA_AvailableExternally)
10311 return false;
10312
Richard Smitha0e5e542012-11-12 21:38:00 +000010313 // Variables that have destruction with side-effects are required.
Richard Smith2b4fa532019-09-29 05:08:46 +000010314 if (VD->needsDestruction(*this))
Richard Smitha0e5e542012-11-12 21:38:00 +000010315 return true;
10316
10317 // Variables that have initialization with side-effects are required.
Richard Smith7747ce22015-08-19 20:49:38 +000010318 if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
Richard Smith187ffb42017-01-20 01:19:46 +000010319 // We can get a value-dependent initializer during error recovery.
10320 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
Richard Smitha0e5e542012-11-12 21:38:00 +000010321 return true;
10322
Richard Smithda383632016-08-15 01:33:41 +000010323 // Likewise, variables with tuple-like bindings are required if their
10324 // bindings have side-effects.
Eugene Zelenko7855e772018-04-03 00:11:50 +000010325 if (const auto *DD = dyn_cast<DecompositionDecl>(VD))
10326 for (const auto *BD : DD->bindings())
10327 if (const auto *BindingVD = BD->getHoldingVar())
Richard Smithda383632016-08-15 01:33:41 +000010328 if (DeclMustBeEmitted(BindingVD))
10329 return true;
10330
Richard Smitha0e5e542012-11-12 21:38:00 +000010331 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +000010332}
Charles Davis53c59df2010-08-16 03:33:14 +000010333
Erich Keane281d20b2018-01-08 21:34:17 +000010334void ASTContext::forEachMultiversionedFunctionVersion(
10335 const FunctionDecl *FD,
Erich Keane0fb16482018-08-13 18:33:20 +000010336 llvm::function_ref<void(FunctionDecl *)> Pred) const {
Erich Keane281d20b2018-01-08 21:34:17 +000010337 assert(FD->isMultiVersion() && "Only valid for multiversioned functions");
10338 llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls;
Erich Keane7304f0a2018-11-28 20:58:43 +000010339 FD = FD->getMostRecentDecl();
Erich Keane281d20b2018-01-08 21:34:17 +000010340 for (auto *CurDecl :
10341 FD->getDeclContext()->getRedeclContext()->lookup(FD->getDeclName())) {
Erich Keane7304f0a2018-11-28 20:58:43 +000010342 FunctionDecl *CurFD = CurDecl->getAsFunction()->getMostRecentDecl();
Erich Keane281d20b2018-01-08 21:34:17 +000010343 if (CurFD && hasSameType(CurFD->getType(), FD->getType()) &&
10344 std::end(SeenDecls) == llvm::find(SeenDecls, CurFD)) {
10345 SeenDecls.insert(CurFD);
10346 Pred(CurFD);
10347 }
10348 }
10349}
10350
Reid Kleckner78af0702013-08-27 23:08:25 +000010351CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
Erich Keane00022812019-05-23 16:05:21 +000010352 bool IsCXXMethod,
10353 bool IsBuiltin) const {
Charles Davis99202b32010-11-09 18:04:24 +000010354 // Pass through to the C++ ABI object
Reid Kleckner78af0702013-08-27 23:08:25 +000010355 if (IsCXXMethod)
10356 return ABI->getDefaultMethodCallConv(IsVariadic);
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +000010357
Erich Keane00022812019-05-23 16:05:21 +000010358 // Builtins ignore user-specified default calling convention and remain the
10359 // Target's default calling convention.
10360 if (!IsBuiltin) {
10361 switch (LangOpts.getDefaultCallingConv()) {
10362 case LangOptions::DCC_None:
10363 break;
10364 case LangOptions::DCC_CDecl:
10365 return CC_C;
10366 case LangOptions::DCC_FastCall:
10367 if (getTargetInfo().hasFeature("sse2") && !IsVariadic)
10368 return CC_X86FastCall;
10369 break;
10370 case LangOptions::DCC_StdCall:
10371 if (!IsVariadic)
10372 return CC_X86StdCall;
10373 break;
10374 case LangOptions::DCC_VectorCall:
10375 // __vectorcall cannot be applied to variadic functions.
10376 if (!IsVariadic)
10377 return CC_X86VectorCall;
10378 break;
10379 case LangOptions::DCC_RegCall:
10380 // __regcall cannot be applied to variadic functions.
10381 if (!IsVariadic)
10382 return CC_X86RegCall;
10383 break;
10384 }
Alexey Bataeva7547182016-05-18 09:06:38 +000010385 }
Erich Keane39309482019-07-25 17:14:45 +000010386 return Target->getDefaultCallingConv();
Charles Davis99202b32010-11-09 18:04:24 +000010387}
10388
Jay Foad39c79802011-01-12 09:06:06 +000010389bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +000010390 // Pass through to the C++ ABI object
10391 return ABI->isNearlyEmpty(RD);
10392}
10393
Reid Kleckner96f8f932014-02-05 17:27:08 +000010394VTableContextBase *ASTContext::getVTableContext() {
10395 if (!VTContext.get()) {
10396 if (Target->getCXXABI().isMicrosoft())
10397 VTContext.reset(new MicrosoftVTableContext(*this));
10398 else
10399 VTContext.reset(new ItaniumVTableContext(*this));
10400 }
10401 return VTContext.get();
10402}
10403
Yaxun Liuc18e9ec2019-02-14 02:00:09 +000010404MangleContext *ASTContext::createMangleContext(const TargetInfo *T) {
10405 if (!T)
10406 T = Target;
10407 switch (T->getCXXABI().getKind()) {
Petr Hosek9c3f9b92019-09-06 18:59:43 -070010408 case TargetCXXABI::Fuchsia:
Tim Northover9bb857a2013-01-31 12:13:10 +000010409 case TargetCXXABI::GenericAArch64:
John McCall359b8852013-01-25 22:30:49 +000010410 case TargetCXXABI::GenericItanium:
10411 case TargetCXXABI::GenericARM:
Zoran Jovanovic26a12162015-02-18 15:21:35 +000010412 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +000010413 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +000010414 case TargetCXXABI::iOS64:
Dan Gohmanc2853072015-09-03 22:51:53 +000010415 case TargetCXXABI::WebAssembly:
Tim Northover756447a2015-10-30 16:30:36 +000010416 case TargetCXXABI::WatchOS:
Xiangling Liao8bee52b2020-02-24 09:46:00 -050010417 case TargetCXXABI::XL:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +000010418 return ItaniumMangleContext::create(*this, getDiagnostics());
John McCall359b8852013-01-25 22:30:49 +000010419 case TargetCXXABI::Microsoft:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +000010420 return MicrosoftMangleContext::create(*this, getDiagnostics());
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000010421 }
David Blaikie83d382b2011-09-23 05:06:16 +000010422 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000010423}
10424
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000010425CXXABI::~CXXABI() = default;
Ted Kremenekf5df0ce2011-04-28 04:53:38 +000010426
10427size_t ASTContext::getSideTableAllocatedMemory() const {
Larisse Voufo39a1e502013-08-06 01:03:05 +000010428 return ASTRecordLayouts.getMemorySize() +
10429 llvm::capacity_in_bytes(ObjCLayouts) +
10430 llvm::capacity_in_bytes(KeyFunctions) +
10431 llvm::capacity_in_bytes(ObjCImpls) +
10432 llvm::capacity_in_bytes(BlockVarCopyInits) +
10433 llvm::capacity_in_bytes(DeclAttrs) +
10434 llvm::capacity_in_bytes(TemplateOrInstantiation) +
10435 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
10436 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
10437 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
10438 llvm::capacity_in_bytes(OverriddenMethods) +
10439 llvm::capacity_in_bytes(Types) +
Richard Smithf19a8b02019-05-02 00:49:14 +000010440 llvm::capacity_in_bytes(VariableArrayTypes);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +000010441}
Ted Kremenek540017e2011-10-06 05:00:56 +000010442
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +000010443/// getIntTypeForBitwidth -
10444/// sets integer QualTy according to specified details:
10445/// bitwidth, signed/unsigned.
10446/// Returns empty type if there is no appropriate target types.
10447QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
10448 unsigned Signed) const {
10449 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
10450 CanQualType QualTy = getFromTargetType(Ty);
10451 if (!QualTy && DestWidth == 128)
10452 return Signed ? Int128Ty : UnsignedInt128Ty;
10453 return QualTy;
10454}
10455
10456/// getRealTypeForBitwidth -
10457/// sets floating point QualTy according to specified bitwidth.
10458/// Returns empty type if there is no appropriate target types.
10459QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
10460 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
10461 switch (Ty) {
10462 case TargetInfo::Float:
10463 return FloatTy;
10464 case TargetInfo::Double:
10465 return DoubleTy;
10466 case TargetInfo::LongDouble:
10467 return LongDoubleTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +000010468 case TargetInfo::Float128:
10469 return Float128Ty;
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +000010470 case TargetInfo::NoFloat:
Eugene Zelenko7855e772018-04-03 00:11:50 +000010471 return {};
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +000010472 }
10473
10474 llvm_unreachable("Unhandled TargetInfo::RealType value");
10475}
10476
Eli Friedman3b7d46c2013-07-10 00:30:46 +000010477void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
10478 if (Number > 1)
10479 MangleNumbers[ND] = Number;
David Blaikie095deba2012-11-14 01:52:05 +000010480}
10481
Eli Friedman3b7d46c2013-07-10 00:30:46 +000010482unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
Richard Smithe9b02d62016-03-21 22:33:02 +000010483 auto I = MangleNumbers.find(ND);
Eli Friedman3b7d46c2013-07-10 00:30:46 +000010484 return I != MangleNumbers.end() ? I->second : 1;
David Blaikie095deba2012-11-14 01:52:05 +000010485}
10486
David Majnemer2206bf52014-03-05 08:57:59 +000010487void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
10488 if (Number > 1)
10489 StaticLocalNumbers[VD] = Number;
10490}
10491
10492unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
Richard Smithe9b02d62016-03-21 22:33:02 +000010493 auto I = StaticLocalNumbers.find(VD);
David Majnemer2206bf52014-03-05 08:57:59 +000010494 return I != StaticLocalNumbers.end() ? I->second : 1;
10495}
10496
Eli Friedman3b7d46c2013-07-10 00:30:46 +000010497MangleNumberingContext &
10498ASTContext::getManglingNumberContext(const DeclContext *DC) {
Reid Klecknerd8110b62013-09-10 20:14:30 +000010499 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
Justin Lebar20ebffc2016-10-10 16:26:19 +000010500 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
Reid Klecknerd8110b62013-09-10 20:14:30 +000010501 if (!MCtx)
10502 MCtx = createMangleNumberingContext();
10503 return *MCtx;
10504}
10505
Reid Klecknerda2bde92019-10-10 01:14:22 +000010506MangleNumberingContext &
10507ASTContext::getManglingNumberContext(NeedExtraManglingDecl_t, const Decl *D) {
10508 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
10509 std::unique_ptr<MangleNumberingContext> &MCtx =
10510 ExtraMangleNumberingContexts[D];
10511 if (!MCtx)
10512 MCtx = createMangleNumberingContext();
10513 return *MCtx;
10514}
10515
Justin Lebar20ebffc2016-10-10 16:26:19 +000010516std::unique_ptr<MangleNumberingContext>
10517ASTContext::createMangleNumberingContext() const {
Reid Klecknerd8110b62013-09-10 20:14:30 +000010518 return ABI->createMangleNumberingContext();
Douglas Gregor63798542012-02-20 19:44:39 +000010519}
10520
David Majnemere7a818f2015-03-06 18:53:55 +000010521const CXXConstructorDecl *
10522ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
10523 return ABI->getCopyConstructorForExceptionObject(
10524 cast<CXXRecordDecl>(RD->getFirstDecl()));
10525}
10526
10527void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
10528 CXXConstructorDecl *CD) {
10529 return ABI->addCopyConstructorForExceptionObject(
10530 cast<CXXRecordDecl>(RD->getFirstDecl()),
10531 cast<CXXConstructorDecl>(CD->getFirstDecl()));
10532}
10533
David Majnemer00350522015-08-31 18:48:39 +000010534void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD,
10535 TypedefNameDecl *DD) {
10536 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
10537}
10538
10539TypedefNameDecl *
10540ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) {
10541 return ABI->getTypedefNameForUnnamedTagDecl(TD);
10542}
10543
10544void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD,
10545 DeclaratorDecl *DD) {
10546 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
10547}
10548
10549DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) {
10550 return ABI->getDeclaratorForUnnamedTagDecl(TD);
10551}
10552
Ted Kremenek540017e2011-10-06 05:00:56 +000010553void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
10554 ParamIndices[D] = index;
10555}
10556
10557unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
10558 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
Fangrui Song6907ce22018-07-30 19:24:48 +000010559 assert(I != ParamIndices.end() &&
Ted Kremenek540017e2011-10-06 05:00:56 +000010560 "ParmIndices lacks entry set by ParmVarDecl");
10561 return I->second;
10562}
Fariborz Jahanian615de762013-05-28 17:37:39 +000010563
Eric Fiselier708afb52019-05-16 21:04:15 +000010564QualType ASTContext::getStringLiteralArrayType(QualType EltTy,
10565 unsigned Length) const {
10566 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
10567 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
10568 EltTy = EltTy.withConst();
10569
10570 EltTy = adjustStringLiteralBaseType(EltTy);
10571
10572 // Get an array type for the string, according to C99 6.4.5. This includes
10573 // the null terminator character.
Richard Smith772e2662019-10-04 01:25:59 +000010574 return getConstantArrayType(EltTy, llvm::APInt(32, Length + 1), nullptr,
Eric Fiselier708afb52019-05-16 21:04:15 +000010575 ArrayType::Normal, /*IndexTypeQuals*/ 0);
10576}
10577
10578StringLiteral *
10579ASTContext::getPredefinedStringLiteralFromCache(StringRef Key) const {
10580 StringLiteral *&Result = StringLiteralCache[Key];
10581 if (!Result)
10582 Result = StringLiteral::Create(
10583 *this, Key, StringLiteral::Ascii,
10584 /*Pascal*/ false, getStringLiteralArrayType(CharTy, Key.size()),
10585 SourceLocation());
10586 return Result;
10587}
10588
Richard Smithbab6df82020-04-11 22:15:29 -070010589MSGuidDecl *
10590ASTContext::getMSGuidDecl(MSGuidDecl::Parts Parts) const {
10591 assert(MSGuidTagDecl && "building MS GUID without MS extensions?");
10592
10593 llvm::FoldingSetNodeID ID;
10594 MSGuidDecl::Profile(ID, Parts);
10595
10596 void *InsertPos;
10597 if (MSGuidDecl *Existing = MSGuidDecls.FindNodeOrInsertPos(ID, InsertPos))
10598 return Existing;
10599
10600 QualType GUIDType = getMSGuidType().withConst();
10601 MSGuidDecl *New = MSGuidDecl::Create(*this, GUIDType, Parts);
10602 MSGuidDecls.InsertNode(New, InsertPos);
10603 return New;
10604}
10605
Fariborz Jahanian615de762013-05-28 17:37:39 +000010606bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
10607 const llvm::Triple &T = getTargetInfo().getTriple();
10608 if (!T.isOSDarwin())
10609 return false;
10610
Bob Wilson2c82c3d2013-11-02 23:27:49 +000010611 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
10612 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
10613 return false;
10614
Fariborz Jahanian615de762013-05-28 17:37:39 +000010615 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
10616 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
10617 uint64_t Size = sizeChars.getQuantity();
10618 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
10619 unsigned Align = alignChars.getQuantity();
10620 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
10621 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
10622}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010623
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010624bool
10625ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
10626 const ObjCMethodDecl *MethodImpl) {
10627 // No point trying to match an unavailable/deprecated mothod.
10628 if (MethodDecl->hasAttr<UnavailableAttr>()
10629 || MethodDecl->hasAttr<DeprecatedAttr>())
10630 return false;
10631 if (MethodDecl->getObjCDeclQualifier() !=
10632 MethodImpl->getObjCDeclQualifier())
10633 return false;
Alp Toker314cc812014-01-25 16:55:45 +000010634 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010635 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +000010636
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010637 if (MethodDecl->param_size() != MethodImpl->param_size())
10638 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +000010639
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010640 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
10641 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
10642 EF = MethodDecl->param_end();
10643 IM != EM && IF != EF; ++IM, ++IF) {
10644 const ParmVarDecl *DeclVar = (*IF);
10645 const ParmVarDecl *ImplVar = (*IM);
10646 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
10647 return false;
10648 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
10649 return false;
10650 }
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000010651
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010652 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010653}
Richard Smith053f6c62014-05-16 23:01:30 +000010654
Yaxun Liu402804b2016-12-15 08:09:08 +000010655uint64_t ASTContext::getTargetNullPointerValue(QualType QT) const {
Alexander Richardson6d989432017-10-15 18:48:14 +000010656 LangAS AS;
Yaxun Liu402804b2016-12-15 08:09:08 +000010657 if (QT->getUnqualifiedDesugaredType()->isNullPtrType())
Alexander Richardson6d989432017-10-15 18:48:14 +000010658 AS = LangAS::Default;
Yaxun Liu402804b2016-12-15 08:09:08 +000010659 else
10660 AS = QT->getPointeeType().getAddressSpace();
10661
10662 return getTargetInfo().getNullPointerValue(AS);
10663}
10664
Alexander Richardson6d989432017-10-15 18:48:14 +000010665unsigned ASTContext::getTargetAddressSpace(LangAS AS) const {
10666 if (isTargetAddressSpace(AS))
10667 return toTargetAddressSpace(AS);
Yaxun Liub34ec822017-04-11 17:24:23 +000010668 else
Alexander Richardson6d989432017-10-15 18:48:14 +000010669 return (*AddrSpaceMap)[(unsigned)AS];
Yaxun Liub34ec822017-04-11 17:24:23 +000010670}
10671
Leonard Chanab80f3c2018-06-14 14:53:51 +000010672QualType ASTContext::getCorrespondingSaturatedType(QualType Ty) const {
10673 assert(Ty->isFixedPointType());
10674
10675 if (Ty->isSaturatedFixedPointType()) return Ty;
10676
Simon Pilgrimeed4b122019-10-02 11:48:06 +000010677 switch (Ty->castAs<BuiltinType>()->getKind()) {
Leonard Chanab80f3c2018-06-14 14:53:51 +000010678 default:
10679 llvm_unreachable("Not a fixed point type!");
10680 case BuiltinType::ShortAccum:
10681 return SatShortAccumTy;
10682 case BuiltinType::Accum:
10683 return SatAccumTy;
10684 case BuiltinType::LongAccum:
10685 return SatLongAccumTy;
10686 case BuiltinType::UShortAccum:
10687 return SatUnsignedShortAccumTy;
10688 case BuiltinType::UAccum:
10689 return SatUnsignedAccumTy;
10690 case BuiltinType::ULongAccum:
10691 return SatUnsignedLongAccumTy;
10692 case BuiltinType::ShortFract:
10693 return SatShortFractTy;
10694 case BuiltinType::Fract:
10695 return SatFractTy;
10696 case BuiltinType::LongFract:
10697 return SatLongFractTy;
10698 case BuiltinType::UShortFract:
10699 return SatUnsignedShortFractTy;
10700 case BuiltinType::UFract:
10701 return SatUnsignedFractTy;
10702 case BuiltinType::ULongFract:
10703 return SatUnsignedLongFractTy;
10704 }
10705}
10706
Matt Arsenaultc65f9662018-08-02 12:14:28 +000010707LangAS ASTContext::getLangASForBuiltinAddressSpace(unsigned AS) const {
10708 if (LangOpts.OpenCL)
10709 return getTargetInfo().getOpenCLBuiltinAddressSpace(AS);
10710
10711 if (LangOpts.CUDA)
10712 return getTargetInfo().getCUDABuiltinAddressSpace(AS);
10713
10714 return getLangASFromTargetAS(AS);
10715}
10716
Richard Smith053f6c62014-05-16 23:01:30 +000010717// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
10718// doesn't include ASTContext.h
10719template
10720clang::LazyGenerationalUpdatePtr<
10721 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
10722clang::LazyGenerationalUpdatePtr<
10723 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
10724 const clang::ASTContext &Ctx, Decl *Value);
Leonard Chandb01c3a2018-06-20 17:19:40 +000010725
10726unsigned char ASTContext::getFixedPointScale(QualType Ty) const {
10727 assert(Ty->isFixedPointType());
10728
Leonard Chandb01c3a2018-06-20 17:19:40 +000010729 const TargetInfo &Target = getTargetInfo();
Simon Pilgrim9588ae72019-10-03 21:47:42 +000010730 switch (Ty->castAs<BuiltinType>()->getKind()) {
Leonard Chandb01c3a2018-06-20 17:19:40 +000010731 default:
10732 llvm_unreachable("Not a fixed point type!");
10733 case BuiltinType::ShortAccum:
10734 case BuiltinType::SatShortAccum:
10735 return Target.getShortAccumScale();
10736 case BuiltinType::Accum:
10737 case BuiltinType::SatAccum:
10738 return Target.getAccumScale();
10739 case BuiltinType::LongAccum:
10740 case BuiltinType::SatLongAccum:
10741 return Target.getLongAccumScale();
10742 case BuiltinType::UShortAccum:
10743 case BuiltinType::SatUShortAccum:
10744 return Target.getUnsignedShortAccumScale();
10745 case BuiltinType::UAccum:
10746 case BuiltinType::SatUAccum:
10747 return Target.getUnsignedAccumScale();
10748 case BuiltinType::ULongAccum:
10749 case BuiltinType::SatULongAccum:
10750 return Target.getUnsignedLongAccumScale();
10751 case BuiltinType::ShortFract:
10752 case BuiltinType::SatShortFract:
10753 return Target.getShortFractScale();
10754 case BuiltinType::Fract:
10755 case BuiltinType::SatFract:
10756 return Target.getFractScale();
10757 case BuiltinType::LongFract:
10758 case BuiltinType::SatLongFract:
10759 return Target.getLongFractScale();
10760 case BuiltinType::UShortFract:
10761 case BuiltinType::SatUShortFract:
10762 return Target.getUnsignedShortFractScale();
10763 case BuiltinType::UFract:
10764 case BuiltinType::SatUFract:
10765 return Target.getUnsignedFractScale();
10766 case BuiltinType::ULongFract:
10767 case BuiltinType::SatULongFract:
10768 return Target.getUnsignedLongFractScale();
10769 }
10770}
10771
10772unsigned char ASTContext::getFixedPointIBits(QualType Ty) const {
10773 assert(Ty->isFixedPointType());
10774
Leonard Chandb01c3a2018-06-20 17:19:40 +000010775 const TargetInfo &Target = getTargetInfo();
Simon Pilgrim9588ae72019-10-03 21:47:42 +000010776 switch (Ty->castAs<BuiltinType>()->getKind()) {
Leonard Chandb01c3a2018-06-20 17:19:40 +000010777 default:
10778 llvm_unreachable("Not a fixed point type!");
10779 case BuiltinType::ShortAccum:
10780 case BuiltinType::SatShortAccum:
10781 return Target.getShortAccumIBits();
10782 case BuiltinType::Accum:
10783 case BuiltinType::SatAccum:
10784 return Target.getAccumIBits();
10785 case BuiltinType::LongAccum:
10786 case BuiltinType::SatLongAccum:
10787 return Target.getLongAccumIBits();
10788 case BuiltinType::UShortAccum:
10789 case BuiltinType::SatUShortAccum:
10790 return Target.getUnsignedShortAccumIBits();
10791 case BuiltinType::UAccum:
10792 case BuiltinType::SatUAccum:
10793 return Target.getUnsignedAccumIBits();
10794 case BuiltinType::ULongAccum:
10795 case BuiltinType::SatULongAccum:
10796 return Target.getUnsignedLongAccumIBits();
10797 case BuiltinType::ShortFract:
10798 case BuiltinType::SatShortFract:
10799 case BuiltinType::Fract:
10800 case BuiltinType::SatFract:
10801 case BuiltinType::LongFract:
10802 case BuiltinType::SatLongFract:
10803 case BuiltinType::UShortFract:
10804 case BuiltinType::SatUShortFract:
10805 case BuiltinType::UFract:
10806 case BuiltinType::SatUFract:
10807 case BuiltinType::ULongFract:
10808 case BuiltinType::SatULongFract:
10809 return 0;
10810 }
10811}
Leonard Chana6779422018-08-06 16:42:37 +000010812
10813FixedPointSemantics ASTContext::getFixedPointSemantics(QualType Ty) const {
Erich Keane8e772162019-01-18 19:31:54 +000010814 assert((Ty->isFixedPointType() || Ty->isIntegerType()) &&
10815 "Can only get the fixed point semantics for a "
10816 "fixed point or integer type.");
Leonard Chan2044ac82019-01-16 18:13:59 +000010817 if (Ty->isIntegerType())
10818 return FixedPointSemantics::GetIntegerSemantics(getIntWidth(Ty),
10819 Ty->isSignedIntegerType());
10820
Leonard Chana6779422018-08-06 16:42:37 +000010821 bool isSigned = Ty->isSignedFixedPointType();
10822 return FixedPointSemantics(
10823 static_cast<unsigned>(getTypeSize(Ty)), getFixedPointScale(Ty), isSigned,
10824 Ty->isSaturatedFixedPointType(),
10825 !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding());
10826}
10827
10828APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const {
10829 assert(Ty->isFixedPointType());
10830 return APFixedPoint::getMax(getFixedPointSemantics(Ty));
10831}
10832
10833APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const {
10834 assert(Ty->isFixedPointType());
10835 return APFixedPoint::getMin(getFixedPointSemantics(Ty));
10836}
Leonard Chan2044ac82019-01-16 18:13:59 +000010837
10838QualType ASTContext::getCorrespondingSignedFixedPointType(QualType Ty) const {
10839 assert(Ty->isUnsignedFixedPointType() &&
10840 "Expected unsigned fixed point type");
Leonard Chan2044ac82019-01-16 18:13:59 +000010841
Simon Pilgrim9588ae72019-10-03 21:47:42 +000010842 switch (Ty->castAs<BuiltinType>()->getKind()) {
Leonard Chan2044ac82019-01-16 18:13:59 +000010843 case BuiltinType::UShortAccum:
10844 return ShortAccumTy;
10845 case BuiltinType::UAccum:
10846 return AccumTy;
10847 case BuiltinType::ULongAccum:
10848 return LongAccumTy;
10849 case BuiltinType::SatUShortAccum:
10850 return SatShortAccumTy;
10851 case BuiltinType::SatUAccum:
10852 return SatAccumTy;
10853 case BuiltinType::SatULongAccum:
10854 return SatLongAccumTy;
10855 case BuiltinType::UShortFract:
10856 return ShortFractTy;
10857 case BuiltinType::UFract:
10858 return FractTy;
10859 case BuiltinType::ULongFract:
10860 return LongFractTy;
10861 case BuiltinType::SatUShortFract:
10862 return SatShortFractTy;
10863 case BuiltinType::SatUFract:
10864 return SatFractTy;
10865 case BuiltinType::SatULongFract:
10866 return SatLongFractTy;
10867 default:
10868 llvm_unreachable("Unexpected unsigned fixed point type");
10869 }
10870}
Craig Topperd35bcbb2019-12-23 10:38:38 -080010871
10872ParsedTargetAttr
10873ASTContext::filterFunctionTargetAttrs(const TargetAttr *TD) const {
10874 assert(TD != nullptr);
10875 ParsedTargetAttr ParsedAttr = TD->parse();
10876
10877 ParsedAttr.Features.erase(
10878 llvm::remove_if(ParsedAttr.Features,
10879 [&](const std::string &Feat) {
10880 return !Target->isValidFeatureName(
10881 StringRef{Feat}.substr(1));
10882 }),
10883 ParsedAttr.Features.end());
10884 return ParsedAttr;
10885}
10886
10887void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
10888 const FunctionDecl *FD) const {
10889 if (FD)
10890 getFunctionFeatureMap(FeatureMap, GlobalDecl().getWithDecl(FD));
10891 else
10892 Target->initFeatureMap(FeatureMap, getDiagnostics(),
10893 Target->getTargetOpts().CPU,
10894 Target->getTargetOpts().Features);
10895}
10896
10897// Fills in the supplied string map with the set of target features for the
10898// passed in function.
10899void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
10900 GlobalDecl GD) const {
10901 StringRef TargetCPU = Target->getTargetOpts().CPU;
10902 const FunctionDecl *FD = GD.getDecl()->getAsFunction();
10903 if (const auto *TD = FD->getAttr<TargetAttr>()) {
10904 ParsedTargetAttr ParsedAttr = filterFunctionTargetAttrs(TD);
10905
10906 // Make a copy of the features as passed on the command line into the
10907 // beginning of the additional features from the function to override.
10908 ParsedAttr.Features.insert(
10909 ParsedAttr.Features.begin(),
10910 Target->getTargetOpts().FeaturesAsWritten.begin(),
10911 Target->getTargetOpts().FeaturesAsWritten.end());
10912
10913 if (ParsedAttr.Architecture != "" &&
10914 Target->isValidCPUName(ParsedAttr.Architecture))
10915 TargetCPU = ParsedAttr.Architecture;
10916
10917 // Now populate the feature map, first with the TargetCPU which is either
10918 // the default or a new one from the target attribute string. Then we'll use
10919 // the passed in features (FeaturesAsWritten) along with the new ones from
10920 // the attribute.
10921 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU,
10922 ParsedAttr.Features);
10923 } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) {
10924 llvm::SmallVector<StringRef, 32> FeaturesTmp;
10925 Target->getCPUSpecificCPUDispatchFeatures(
10926 SD->getCPUName(GD.getMultiVersionIndex())->getName(), FeaturesTmp);
10927 std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end());
10928 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
10929 } else {
10930 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU,
10931 Target->getTargetOpts().Features);
10932 }
10933}
Johannes Doerfert55eca282020-03-13 23:42:05 -050010934
10935OMPTraitInfo &ASTContext::getNewOMPTraitInfo() {
10936 OMPTraitInfoVector.push_back(new OMPTraitInfo());
10937 return *OMPTraitInfoVector.back();
10938}