blob: 24392321f95aba06c7de3a2fb51139e35bbaadb6 [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"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000015#include "clang/AST/APValue.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000016#include "clang/AST/ASTMutationListener.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000017#include "clang/AST/ASTTypeTraits.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000018#include "clang/AST/Attr.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000019#include "clang/AST/AttrIterator.h"
Ken Dyck8c89d592009-12-22 14:23:30 +000020#include "clang/AST/CharUnits.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000021#include "clang/AST/Comment.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000022#include "clang/AST/Decl.h"
23#include "clang/AST/DeclBase.h"
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +000024#include "clang/AST/DeclCXX.h"
Chandler Carruthaa36b892015-12-30 03:40:23 +000025#include "clang/AST/DeclContextInternals.h"
Steve Naroff67391b82007-10-01 19:00:59 +000026#include "clang/AST/DeclObjC.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000027#include "clang/AST/DeclOpenMP.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000028#include "clang/AST/DeclTemplate.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000029#include "clang/AST/DeclarationName.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000030#include "clang/AST/Expr.h"
John McCall87fe5d52010-05-20 01:18:31 +000031#include "clang/AST/ExprCXX.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000032#include "clang/AST/ExternalASTSource.h"
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000033#include "clang/AST/Mangle.h"
Reid Klecknerd8110b62013-09-10 20:14:30 +000034#include "clang/AST/MangleNumberingContext.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000035#include "clang/AST/NestedNameSpecifier.h"
36#include "clang/AST/RawCommentList.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000037#include "clang/AST/RecordLayout.h"
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000038#include "clang/AST/RecursiveASTVisitor.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000039#include "clang/AST/Stmt.h"
40#include "clang/AST/TemplateBase.h"
41#include "clang/AST/TemplateName.h"
42#include "clang/AST/Type.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000043#include "clang/AST/TypeLoc.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000044#include "clang/AST/UnresolvedSet.h"
Reid Kleckner96f8f932014-02-05 17:27:08 +000045#include "clang/AST/VTableBuilder.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000046#include "clang/Basic/AddressSpaces.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000047#include "clang/Basic/Builtins.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000048#include "clang/Basic/CommentOptions.h"
Eugene Zelenko7855e772018-04-03 00:11:50 +000049#include "clang/Basic/ExceptionSpecificationType.h"
Leonard Chana6779422018-08-06 16:42:37 +000050#include "clang/Basic/FixedPoint.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000051#include "clang/Basic/IdentifierTable.h"
52#include "clang/Basic/LLVM.h"
53#include "clang/Basic/LangOptions.h"
54#include "clang/Basic/Linkage.h"
55#include "clang/Basic/ObjCRuntime.h"
56#include "clang/Basic/SanitizerBlacklist.h"
57#include "clang/Basic/SourceLocation.h"
Chris Lattnerd2868512009-03-28 03:45:20 +000058#include "clang/Basic/SourceManager.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000059#include "clang/Basic/Specifiers.h"
60#include "clang/Basic/TargetCXXABI.h"
Chris Lattner4dc8a6f2007-05-20 23:50:58 +000061#include "clang/Basic/TargetInfo.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000062#include "clang/Basic/XRayLists.h"
63#include "llvm/ADT/APInt.h"
64#include "llvm/ADT/APSInt.h"
65#include "llvm/ADT/ArrayRef.h"
66#include "llvm/ADT/DenseMap.h"
67#include "llvm/ADT/DenseSet.h"
68#include "llvm/ADT/FoldingSet.h"
69#include "llvm/ADT/None.h"
70#include "llvm/ADT/Optional.h"
71#include "llvm/ADT/PointerUnion.h"
72#include "llvm/ADT/STLExtras.h"
73#include "llvm/ADT/SmallPtrSet.h"
74#include "llvm/ADT/SmallVector.h"
Anders Carlssond8499822007-10-29 05:01:08 +000075#include "llvm/ADT/StringExtras.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000076#include "llvm/ADT/StringRef.h"
Robert Lyttoneaf6f362013-11-12 10:09:34 +000077#include "llvm/ADT/Triple.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000078#include "llvm/Support/Capacity.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000079#include "llvm/Support/Casting.h"
80#include "llvm/Support/Compiler.h"
81#include "llvm/Support/ErrorHandling.h"
Nate Begemanb699c9b2009-01-18 06:42:49 +000082#include "llvm/Support/MathExtras.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000083#include "llvm/Support/raw_ostream.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000084#include <algorithm>
85#include <cassert>
86#include <cstddef>
87#include <cstdint>
88#include <cstdlib>
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +000089#include <map>
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000090#include <memory>
91#include <string>
92#include <tuple>
93#include <utility>
Anders Carlssona4267a62009-07-18 21:19:52 +000094
Chris Lattnerddc135e2006-11-10 06:34:16 +000095using namespace clang;
96
Steve Naroff0af91202007-04-27 21:51:21 +000097enum FloatingRank {
Sjoerd Meijercc623ad2017-09-08 15:15:00 +000098 Float16Rank, HalfRank, FloatRank, DoubleRank, LongDoubleRank, Float128Rank
Steve Naroff0af91202007-04-27 21:51:21 +000099};
100
Jan Korousf31d8df2019-08-13 18:11:44 +0000101/// \returns location that is relevant when searching for Doc comments related
102/// to \p D.
103static SourceLocation getDeclLocForCommentSearch(const Decl *D,
104 SourceManager &SourceMgr) {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000105 assert(D);
106
Dmitri Gribenkodf17d642012-06-28 16:19:39 +0000107 // User can not attach documentation to implicit declarations.
108 if (D->isImplicit())
Jan Korousf31d8df2019-08-13 18:11:44 +0000109 return {};
Dmitri Gribenkodf17d642012-06-28 16:19:39 +0000110
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000111 // User can not attach documentation to implicit instantiations.
Eugene Zelenko7855e772018-04-03 00:11:50 +0000112 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000113 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Jan Korousf31d8df2019-08-13 18:11:44 +0000114 return {};
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000115 }
116
Eugene Zelenko7855e772018-04-03 00:11:50 +0000117 if (const auto *VD = dyn_cast<VarDecl>(D)) {
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000118 if (VD->isStaticDataMember() &&
119 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Jan Korousf31d8df2019-08-13 18:11:44 +0000120 return {};
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000121 }
122
Eugene Zelenko7855e772018-04-03 00:11:50 +0000123 if (const auto *CRD = dyn_cast<CXXRecordDecl>(D)) {
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000124 if (CRD->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 *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000129 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
130 if (TSK == TSK_ImplicitInstantiation ||
131 TSK == TSK_Undeclared)
Jan Korousf31d8df2019-08-13 18:11:44 +0000132 return {};
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000133 }
134
Eugene Zelenko7855e772018-04-03 00:11:50 +0000135 if (const auto *ED = dyn_cast<EnumDecl>(D)) {
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000136 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Jan Korousf31d8df2019-08-13 18:11:44 +0000137 return {};
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000138 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000139 if (const auto *TD = dyn_cast<TagDecl>(D)) {
Fariborz Jahanian799a4032013-04-17 21:05:20 +0000140 // When tag declaration (but not definition!) is part of the
141 // decl-specifier-seq of some other declaration, it doesn't get comment
142 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
Jan Korousf31d8df2019-08-13 18:11:44 +0000143 return {};
Fariborz Jahanian799a4032013-04-17 21:05:20 +0000144 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000145 // TODO: handle comments for function parameters properly.
146 if (isa<ParmVarDecl>(D))
Jan Korousf31d8df2019-08-13 18:11:44 +0000147 return {};
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000148
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000149 // TODO: we could look up template parameter documentation in the template
150 // documentation.
151 if (isa<TemplateTypeParmDecl>(D) ||
152 isa<NonTypeTemplateParmDecl>(D) ||
153 isa<TemplateTemplateParmDecl>(D))
Jan Korousf31d8df2019-08-13 18:11:44 +0000154 return {};
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000155
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000156 // Find declaration location.
157 // For Objective-C declarations we generally don't expect to have multiple
158 // declarators, thus use declaration starting location as the "declaration
159 // location".
160 // For all other declarations multiple declarators are used quite frequently,
161 // so we use the location of the identifier as the "declaration location".
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000162 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000163 isa<ObjCPropertyDecl>(D) ||
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +0000164 isa<RedeclarableTemplateDecl>(D) ||
165 isa<ClassTemplateSpecializationDecl>(D))
Jan Korousf31d8df2019-08-13 18:11:44 +0000166 return D->getBeginLoc();
Fariborz Jahanianb64e95f2013-07-24 22:58:51 +0000167 else {
Jan Korousf31d8df2019-08-13 18:11:44 +0000168 const SourceLocation DeclLoc = D->getLocation();
Dmitri Gribenkoef099dc2014-03-27 16:40:51 +0000169 if (DeclLoc.isMacroID()) {
170 if (isa<TypedefDecl>(D)) {
171 // If location of the typedef name is in a macro, it is because being
172 // declared via a macro. Try using declaration's starting location as
173 // the "declaration location".
Jan Korousf31d8df2019-08-13 18:11:44 +0000174 return D->getBeginLoc();
Eugene Zelenko7855e772018-04-03 00:11:50 +0000175 } else if (const auto *TD = dyn_cast<TagDecl>(D)) {
Dmitri Gribenkoef099dc2014-03-27 16:40:51 +0000176 // If location of the tag decl is inside a macro, but the spelling of
177 // the tag name comes from a macro argument, it looks like a special
178 // macro like NS_ENUM is being used to define the tag decl. In that
179 // case, adjust the source location to the expansion loc so that we can
180 // attach the comment to the tag decl.
181 if (SourceMgr.isMacroArgExpansion(DeclLoc) &&
182 TD->isCompleteDefinition())
Jan Korousf31d8df2019-08-13 18:11:44 +0000183 return SourceMgr.getExpansionLoc(DeclLoc);
Dmitri Gribenkoef099dc2014-03-27 16:40:51 +0000184 }
185 }
Jan Korousf31d8df2019-08-13 18:11:44 +0000186 return DeclLoc;
Fariborz Jahanianb64e95f2013-07-24 22:58:51 +0000187 }
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000188
Jan Korousf31d8df2019-08-13 18:11:44 +0000189 return {};
190}
191
192RawComment *ASTContext::getRawCommentForDeclNoCacheImpl(
193 const Decl *D, const SourceLocation RepresentativeLocForDecl,
194 const std::map<unsigned, RawComment *> &CommentsInTheFile) const {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000195 // If the declaration doesn't map directly to a location in a file, we
196 // can't find the comment.
Jan Korousf31d8df2019-08-13 18:11:44 +0000197 if (RepresentativeLocForDecl.isInvalid() ||
198 !RepresentativeLocForDecl.isFileID())
Craig Topper36250ad2014-05-12 05:36:57 +0000199 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000200
Jan Korous6644d012019-04-10 20:23:33 +0000201 // If there are no comments anywhere, we won't find anything.
Jan Korousf31d8df2019-08-13 18:11:44 +0000202 if (CommentsInTheFile.empty())
Jan Korous6644d012019-04-10 20:23:33 +0000203 return nullptr;
204
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000205 // Decompose the location for the declaration and find the beginning of the
206 // file buffer.
Jan Korousf31d8df2019-08-13 18:11:44 +0000207 const std::pair<FileID, unsigned> DeclLocDecomp =
208 SourceMgr.getDecomposedLoc(RepresentativeLocForDecl);
209
210 // Slow path.
211 auto OffsetCommentBehindDecl =
212 CommentsInTheFile.lower_bound(DeclLocDecomp.second);
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000213
214 // First check whether we have a trailing comment.
Jan Korousf31d8df2019-08-13 18:11:44 +0000215 if (OffsetCommentBehindDecl != CommentsInTheFile.end()) {
216 RawComment *CommentBehindDecl = OffsetCommentBehindDecl->second;
217 if ((CommentBehindDecl->isDocumentation() ||
218 LangOpts.CommentOpts.ParseAllComments) &&
219 CommentBehindDecl->isTrailingComment() &&
220 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
221 isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
222
223 // Check that Doxygen trailing comment comes after the declaration, starts
224 // on the same line and in the same file as the declaration.
225 if (SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second) ==
226 Comments.getCommentBeginLine(CommentBehindDecl, DeclLocDecomp.first,
227 OffsetCommentBehindDecl->first)) {
228 return CommentBehindDecl;
229 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000230 }
231 }
232
233 // The comment just after the declaration was not a trailing comment.
234 // Let's look at the previous comment.
Jan Korousf31d8df2019-08-13 18:11:44 +0000235 if (OffsetCommentBehindDecl == CommentsInTheFile.begin())
Craig Topper36250ad2014-05-12 05:36:57 +0000236 return nullptr;
Jan Korousf31d8df2019-08-13 18:11:44 +0000237
238 auto OffsetCommentBeforeDecl = --OffsetCommentBehindDecl;
239 RawComment *CommentBeforeDecl = OffsetCommentBeforeDecl->second;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000240
241 // Check that we actually have a non-member Doxygen comment.
Jan Korousf31d8df2019-08-13 18:11:44 +0000242 if (!(CommentBeforeDecl->isDocumentation() ||
David L. Jones13d5a872018-03-02 00:07:45 +0000243 LangOpts.CommentOpts.ParseAllComments) ||
Jan Korousf31d8df2019-08-13 18:11:44 +0000244 CommentBeforeDecl->isTrailingComment())
Craig Topper36250ad2014-05-12 05:36:57 +0000245 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000246
247 // Decompose the end of the comment.
Jan Korousf31d8df2019-08-13 18:11:44 +0000248 const unsigned CommentEndOffset =
249 Comments.getCommentEndOffset(CommentBeforeDecl);
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000250
251 // Get the corresponding buffer.
252 bool Invalid = false;
253 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
254 &Invalid).data();
255 if (Invalid)
Craig Topper36250ad2014-05-12 05:36:57 +0000256 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000257
258 // Extract text between the comment and declaration.
Jan Korousf31d8df2019-08-13 18:11:44 +0000259 StringRef Text(Buffer + CommentEndOffset,
260 DeclLocDecomp.second - CommentEndOffset);
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000261
Dmitri Gribenko7e8729b2012-06-27 23:43:37 +0000262 // There should be no other declarations or preprocessor directives between
263 // comment and declaration.
Argyrios Kyrtzidisb534d3a2013-07-26 18:38:12 +0000264 if (Text.find_first_of(";{}#@") != StringRef::npos)
Craig Topper36250ad2014-05-12 05:36:57 +0000265 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000266
Jan Korousf31d8df2019-08-13 18:11:44 +0000267 return CommentBeforeDecl;
268}
269
270RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
271 const SourceLocation DeclLoc = getDeclLocForCommentSearch(D, SourceMgr);
272
273 // If the declaration doesn't map directly to a location in a file, we
274 // can't find the comment.
275 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
276 return nullptr;
277
278 if (ExternalSource && !CommentsLoaded) {
279 ExternalSource->ReadComments();
280 CommentsLoaded = true;
281 }
282
283 if (Comments.empty())
284 return nullptr;
285
286 const FileID File = SourceMgr.getDecomposedLoc(DeclLoc).first;
287 const auto CommentsInThisFile = Comments.getCommentsInFile(File);
288 if (!CommentsInThisFile || CommentsInThisFile->empty())
289 return nullptr;
290
291 return getRawCommentForDeclNoCacheImpl(D, DeclLoc, *CommentsInThisFile);
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000292}
293
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000294/// If we have a 'templated' declaration for a template, adjust 'D' to
295/// refer to the actual template.
Dmitri Gribenko90631802012-08-22 17:44:32 +0000296/// If we have an implicit instantiation, adjust 'D' to refer to template.
Jan Korousf31d8df2019-08-13 18:11:44 +0000297static const Decl &adjustDeclToTemplate(const Decl &D) {
298 if (const auto *FD = dyn_cast<FunctionDecl>(&D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000299 // Is this function declaration part of a function template?
Douglas Gregor35ceb272012-08-13 16:37:30 +0000300 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
Jan Korousf31d8df2019-08-13 18:11:44 +0000301 return *FTD;
Dmitri Gribenko90631802012-08-22 17:44:32 +0000302
303 // Nothing to do if function is not an implicit instantiation.
304 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
305 return D;
306
307 // Function is an implicit instantiation of a function template?
308 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
Jan Korousf31d8df2019-08-13 18:11:44 +0000309 return *FTD;
Dmitri Gribenko90631802012-08-22 17:44:32 +0000310
311 // Function is instantiated from a member definition of a class template?
312 if (const FunctionDecl *MemberDecl =
313 FD->getInstantiatedFromMemberFunction())
Jan Korousf31d8df2019-08-13 18:11:44 +0000314 return *MemberDecl;
Dmitri Gribenko90631802012-08-22 17:44:32 +0000315
316 return D;
Douglas Gregor35ceb272012-08-13 16:37:30 +0000317 }
Jan Korousf31d8df2019-08-13 18:11:44 +0000318 if (const auto *VD = dyn_cast<VarDecl>(&D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000319 // Static data member is instantiated from a member definition of a class
320 // template?
321 if (VD->isStaticDataMember())
322 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
Jan Korousf31d8df2019-08-13 18:11:44 +0000323 return *MemberDecl;
Dmitri Gribenko90631802012-08-22 17:44:32 +0000324
325 return D;
326 }
Jan Korousf31d8df2019-08-13 18:11:44 +0000327 if (const auto *CRD = dyn_cast<CXXRecordDecl>(&D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000328 // Is this class declaration part of a class template?
329 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
Jan Korousf31d8df2019-08-13 18:11:44 +0000330 return *CTD;
Dmitri Gribenko90631802012-08-22 17:44:32 +0000331
332 // Class is an implicit instantiation of a class template or partial
333 // specialization?
Eugene Zelenko7855e772018-04-03 00:11:50 +0000334 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000335 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
336 return D;
337 llvm::PointerUnion<ClassTemplateDecl *,
338 ClassTemplatePartialSpecializationDecl *>
339 PU = CTSD->getSpecializedTemplateOrPartial();
Jan Korousf31d8df2019-08-13 18:11:44 +0000340 return PU.is<ClassTemplateDecl *>()
341 ? *static_cast<const Decl *>(PU.get<ClassTemplateDecl *>())
342 : *static_cast<const Decl *>(
343 PU.get<ClassTemplatePartialSpecializationDecl *>());
Dmitri Gribenko90631802012-08-22 17:44:32 +0000344 }
345
346 // Class is instantiated from a member definition of a class template?
347 if (const MemberSpecializationInfo *Info =
Jan Korousf31d8df2019-08-13 18:11:44 +0000348 CRD->getMemberSpecializationInfo())
349 return *Info->getInstantiatedFrom();
Dmitri Gribenko90631802012-08-22 17:44:32 +0000350
351 return D;
352 }
Jan Korousf31d8df2019-08-13 18:11:44 +0000353 if (const auto *ED = dyn_cast<EnumDecl>(&D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000354 // Enum is instantiated from a member definition of a class template?
355 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
Jan Korousf31d8df2019-08-13 18:11:44 +0000356 return *MemberDecl;
Dmitri Gribenko90631802012-08-22 17:44:32 +0000357
358 return D;
359 }
360 // FIXME: Adjust alias templates?
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000361 return D;
362}
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000363
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000364const RawComment *ASTContext::getRawCommentForAnyRedecl(
365 const Decl *D,
366 const Decl **OriginalDecl) const {
Jan Korousf31d8df2019-08-13 18:11:44 +0000367 if (!D) {
368 if (OriginalDecl)
369 OriginalDecl = nullptr;
370 return nullptr;
371 }
Douglas Gregor35ceb272012-08-13 16:37:30 +0000372
Jan Korousf31d8df2019-08-13 18:11:44 +0000373 D = &adjustDeclToTemplate(*D);
374
375 // Any comment directly attached to D?
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000376 {
Jan Korousf31d8df2019-08-13 18:11:44 +0000377 auto DeclComment = DeclRawComments.find(D);
378 if (DeclComment != DeclRawComments.end()) {
379 if (OriginalDecl)
380 *OriginalDecl = D;
381 return DeclComment->second;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000382 }
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000383 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000384
Jan Korousf31d8df2019-08-13 18:11:44 +0000385 // Any comment attached to any redeclaration of D?
386 const Decl *CanonicalD = D->getCanonicalDecl();
387 if (!CanonicalD)
388 return nullptr;
389
390 {
391 auto RedeclComment = RedeclChainComments.find(CanonicalD);
392 if (RedeclComment != RedeclChainComments.end()) {
393 if (OriginalDecl)
394 *OriginalDecl = RedeclComment->second;
395 auto CommentAtRedecl = DeclRawComments.find(RedeclComment->second);
396 assert(CommentAtRedecl != DeclRawComments.end() &&
397 "This decl is supposed to have comment attached.");
398 return CommentAtRedecl->second;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000399 }
400 }
401
Jan Korousf31d8df2019-08-13 18:11:44 +0000402 // Any redeclarations of D that we haven't checked for comments yet?
403 // We can't use DenseMap::iterator directly since it'd get invalid.
404 auto LastCheckedRedecl = [this, CanonicalD]() -> const Decl * {
405 auto LookupRes = CommentlessRedeclChains.find(CanonicalD);
406 if (LookupRes != CommentlessRedeclChains.end())
407 return LookupRes->second;
408 return nullptr;
409 }();
410
411 for (const auto Redecl : D->redecls()) {
412 assert(Redecl);
413 // Skip all redeclarations that have been checked previously.
414 if (LastCheckedRedecl) {
415 if (LastCheckedRedecl == Redecl) {
416 LastCheckedRedecl = nullptr;
417 }
418 continue;
419 }
420 const RawComment *RedeclComment = getRawCommentForDeclNoCache(Redecl);
421 if (RedeclComment) {
422 cacheRawCommentForDecl(*Redecl, *RedeclComment);
423 if (OriginalDecl)
424 *OriginalDecl = Redecl;
425 return RedeclComment;
426 }
427 CommentlessRedeclChains[CanonicalD] = Redecl;
428 }
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000429
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000430 if (OriginalDecl)
Jan Korousf31d8df2019-08-13 18:11:44 +0000431 *OriginalDecl = nullptr;
432 return nullptr;
433}
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000434
Jan Korousf31d8df2019-08-13 18:11:44 +0000435void ASTContext::cacheRawCommentForDecl(const Decl &OriginalD,
436 const RawComment &Comment) const {
437 assert(Comment.isDocumentation() || LangOpts.CommentOpts.ParseAllComments);
438 DeclRawComments.try_emplace(&OriginalD, &Comment);
439 const Decl *const CanonicalDecl = OriginalD.getCanonicalDecl();
440 RedeclChainComments.try_emplace(CanonicalDecl, &OriginalD);
441 CommentlessRedeclChains.erase(CanonicalDecl);
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000442}
443
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000444static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
445 SmallVectorImpl<const NamedDecl *> &Redeclared) {
446 const DeclContext *DC = ObjCMethod->getDeclContext();
Eugene Zelenko7855e772018-04-03 00:11:50 +0000447 if (const auto *IMD = dyn_cast<ObjCImplDecl>(DC)) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000448 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
449 if (!ID)
450 return;
451 // Add redeclared method here.
Aaron Ballmanb4a53452014-03-13 21:57:01 +0000452 for (const auto *Ext : ID->known_extensions()) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000453 if (ObjCMethodDecl *RedeclaredMethod =
Douglas Gregor048fbfa2013-01-16 23:00:23 +0000454 Ext->getMethod(ObjCMethod->getSelector(),
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000455 ObjCMethod->isInstanceMethod()))
456 Redeclared.push_back(RedeclaredMethod);
457 }
458 }
459}
460
Jan Korousf31d8df2019-08-13 18:11:44 +0000461void ASTContext::attachCommentsToJustParsedDecls(ArrayRef<Decl *> Decls,
462 const Preprocessor *PP) {
463 if (Comments.empty() || Decls.empty())
464 return;
465
466 // See if there are any new comments that are not attached to a decl.
467 // The location doesn't have to be precise - we care only about the file.
468 const FileID File =
469 SourceMgr.getDecomposedLoc((*Decls.begin())->getLocation()).first;
470 auto CommentsInThisFile = Comments.getCommentsInFile(File);
471 if (!CommentsInThisFile || CommentsInThisFile->empty() ||
472 CommentsInThisFile->rbegin()->second->isAttached())
473 return;
474
475 // There is at least one comment not attached to a decl.
476 // Maybe it should be attached to one of Decls?
477 //
478 // Note that this way we pick up not only comments that precede the
479 // declaration, but also comments that *follow* the declaration -- thanks to
480 // the lookahead in the lexer: we've consumed the semicolon and looked
481 // ahead through comments.
482
483 for (const Decl *D : Decls) {
484 assert(D);
485 if (D->isInvalidDecl())
486 continue;
487
488 D = &adjustDeclToTemplate(*D);
489
490 const SourceLocation DeclLoc = getDeclLocForCommentSearch(D, SourceMgr);
491
492 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
493 continue;
494
495 if (DeclRawComments.count(D) > 0)
496 continue;
497
498 if (RawComment *const DocComment =
499 getRawCommentForDeclNoCacheImpl(D, DeclLoc, *CommentsInThisFile)) {
500 cacheRawCommentForDecl(*D, *DocComment);
501 comments::FullComment *FC = DocComment->parse(*this, PP, D);
502 ParsedComments[D->getCanonicalDecl()] = FC;
503 }
504 }
505}
506
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000507comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
508 const Decl *D) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +0000509 auto *ThisDeclInfo = new (*this) comments::DeclInfo;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000510 ThisDeclInfo->CommentDecl = D;
511 ThisDeclInfo->IsFilled = false;
512 ThisDeclInfo->fill();
513 ThisDeclInfo->CommentDecl = FC->getDecl();
Argyrios Kyrtzidis7daabbd2014-04-27 22:53:03 +0000514 if (!ThisDeclInfo->TemplateParameters)
515 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000516 comments::FullComment *CFC =
517 new (*this) comments::FullComment(FC->getBlocks(),
518 ThisDeclInfo);
519 return CFC;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000520}
521
Richard Smithb39b9d52013-05-21 05:24:00 +0000522comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
523 const RawComment *RC = getRawCommentForDeclNoCache(D);
Craig Topper36250ad2014-05-12 05:36:57 +0000524 return RC ? RC->parse(*this, nullptr, D) : nullptr;
Richard Smithb39b9d52013-05-21 05:24:00 +0000525}
526
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000527comments::FullComment *ASTContext::getCommentForDecl(
528 const Decl *D,
529 const Preprocessor *PP) const {
Jan Korousf31d8df2019-08-13 18:11:44 +0000530 if (!D || D->isInvalidDecl())
Craig Topper36250ad2014-05-12 05:36:57 +0000531 return nullptr;
Jan Korousf31d8df2019-08-13 18:11:44 +0000532 D = &adjustDeclToTemplate(*D);
Fangrui Song6907ce22018-07-30 19:24:48 +0000533
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000534 const Decl *Canonical = D->getCanonicalDecl();
535 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
536 ParsedComments.find(Canonical);
Fangrui Song6907ce22018-07-30 19:24:48 +0000537
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000538 if (Pos != ParsedComments.end()) {
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000539 if (Canonical != D) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000540 comments::FullComment *FC = Pos->second;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000541 comments::FullComment *CFC = cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000542 return CFC;
543 }
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000544 return Pos->second;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000545 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000546
Jan Korousf31d8df2019-08-13 18:11:44 +0000547 const Decl *OriginalDecl = nullptr;
Fangrui Song6907ce22018-07-30 19:24:48 +0000548
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000549 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000550 if (!RC) {
551 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000552 SmallVector<const NamedDecl*, 8> Overridden;
Eugene Zelenko7855e772018-04-03 00:11:50 +0000553 const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000554 if (OMD && OMD->isPropertyAccessor())
555 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
556 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
557 return cloneFullComment(FC, D);
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000558 if (OMD)
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000559 addRedeclaredMethods(OMD, Overridden);
560 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000561 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
562 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
563 return cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000564 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000565 else if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000566 // Attach any tag type's documentation to its typedef if latter
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000567 // does not have one of its own.
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000568 QualType QT = TD->getUnderlyingType();
Eugene Zelenko7855e772018-04-03 00:11:50 +0000569 if (const auto *TT = QT->getAs<TagType>())
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000570 if (const Decl *TD = TT->getDecl())
571 if (comments::FullComment *FC = getCommentForDecl(TD, PP))
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000572 return cloneFullComment(FC, D);
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000573 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000574 else if (const auto *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000575 while (IC->getSuperClass()) {
576 IC = IC->getSuperClass();
577 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
578 return cloneFullComment(FC, D);
579 }
580 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000581 else if (const auto *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000582 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
583 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
584 return cloneFullComment(FC, D);
585 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000586 else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000587 if (!(RD = RD->getDefinition()))
Craig Topper36250ad2014-05-12 05:36:57 +0000588 return nullptr;
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000589 // Check non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +0000590 for (const auto &I : RD->bases()) {
591 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000592 continue;
Aaron Ballman574705e2014-03-13 15:41:46 +0000593 QualType Ty = I.getType();
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000594 if (Ty.isNull())
595 continue;
596 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
597 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
598 continue;
Fangrui Song6907ce22018-07-30 19:24:48 +0000599
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000600 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
601 return cloneFullComment(FC, D);
602 }
603 }
604 // Check virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +0000605 for (const auto &I : RD->vbases()) {
606 if (I.getAccessSpecifier() != AS_public)
Fariborz Jahanian5a2e4a22013-04-26 23:34:36 +0000607 continue;
Aaron Ballman445a9392014-03-13 16:15:17 +0000608 QualType Ty = I.getType();
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000609 if (Ty.isNull())
610 continue;
611 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
612 if (!(VirtualBase= VirtualBase->getDefinition()))
613 continue;
614 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
615 return cloneFullComment(FC, D);
616 }
617 }
618 }
Craig Topper36250ad2014-05-12 05:36:57 +0000619 return nullptr;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000620 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000621
Dmitri Gribenkobfda9f72012-08-22 18:12:19 +0000622 // If the RawComment was attached to other redeclaration of this Decl, we
623 // should parse the comment in context of that other Decl. This is important
624 // because comments can contain references to parameter names which can be
625 // different across redeclarations.
Jan Korousf31d8df2019-08-13 18:11:44 +0000626 if (D != OriginalDecl && OriginalDecl)
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000627 return getCommentForDecl(OriginalDecl, PP);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000628
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000629 comments::FullComment *FC = RC->parse(*this, PP, D);
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000630 ParsedComments[Canonical] = FC;
631 return FC;
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000632}
633
Fangrui Song6907ce22018-07-30 19:24:48 +0000634void
635ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000636 TemplateTemplateParmDecl *Parm) {
637 ID.AddInteger(Parm->getDepth());
638 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +0000639 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000640
641 TemplateParameterList *Params = Parm->getTemplateParameters();
642 ID.AddInteger(Params->size());
Fangrui Song6907ce22018-07-30 19:24:48 +0000643 for (TemplateParameterList::const_iterator P = Params->begin(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000644 PEnd = Params->end();
645 P != PEnd; ++P) {
Eugene Zelenko7855e772018-04-03 00:11:50 +0000646 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000647 ID.AddInteger(0);
648 ID.AddBoolean(TTP->isParameterPack());
649 continue;
650 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000651
Eugene Zelenko7855e772018-04-03 00:11:50 +0000652 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000653 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +0000654 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman205a4292012-03-07 01:09:33 +0000655 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000656 if (NTTP->isExpandedParameterPack()) {
657 ID.AddBoolean(true);
658 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman205a4292012-03-07 01:09:33 +0000659 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
660 QualType T = NTTP->getExpansionType(I);
661 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
662 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000663 } else
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000664 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000665 continue;
666 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000667
Eugene Zelenko7855e772018-04-03 00:11:50 +0000668 auto *TTP = cast<TemplateTemplateParmDecl>(*P);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000669 ID.AddInteger(2);
670 Profile(ID, TTP);
671 }
672}
673
674TemplateTemplateParmDecl *
675ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +0000676 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000677 // Check if we already have a canonical template template parameter.
678 llvm::FoldingSetNodeID ID;
679 CanonicalTemplateTemplateParm::Profile(ID, TTP);
Craig Topper36250ad2014-05-12 05:36:57 +0000680 void *InsertPos = nullptr;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000681 CanonicalTemplateTemplateParm *Canonical
682 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
683 if (Canonical)
684 return Canonical->getParam();
Fangrui Song6907ce22018-07-30 19:24:48 +0000685
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000686 // Build a canonical template parameter list.
687 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000688 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000689 CanonParams.reserve(Params->size());
Fangrui Song6907ce22018-07-30 19:24:48 +0000690 for (TemplateParameterList::const_iterator P = Params->begin(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000691 PEnd = Params->end();
692 P != PEnd; ++P) {
Eugene Zelenko7855e772018-04-03 00:11:50 +0000693 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000694 CanonParams.push_back(
Fangrui Song6907ce22018-07-30 19:24:48 +0000695 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000696 SourceLocation(),
697 SourceLocation(),
698 TTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000699 TTP->getIndex(), nullptr, false,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000700 TTP->isParameterPack()));
Eugene Zelenko7855e772018-04-03 00:11:50 +0000701 else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000702 QualType T = getCanonicalType(NTTP->getType());
703 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
704 NonTypeTemplateParmDecl *Param;
705 if (NTTP->isExpandedParameterPack()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000706 SmallVector<QualType, 2> ExpandedTypes;
707 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000708 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
709 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
710 ExpandedTInfos.push_back(
711 getTrivialTypeSourceInfo(ExpandedTypes.back()));
712 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000713
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000714 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000715 SourceLocation(),
716 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000717 NTTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000718 NTTP->getPosition(), nullptr,
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000719 T,
720 TInfo,
David Majnemerdfecf1a2016-07-06 04:19:16 +0000721 ExpandedTypes,
722 ExpandedTInfos);
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000723 } else {
724 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000725 SourceLocation(),
726 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000727 NTTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000728 NTTP->getPosition(), nullptr,
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000729 T,
730 NTTP->isParameterPack(),
731 TInfo);
732 }
733 CanonParams.push_back(Param);
734
735 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000736 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
737 cast<TemplateTemplateParmDecl>(*P)));
738 }
739
Hubert Tonge4a0c0e2016-07-30 22:33:34 +0000740 assert(!TTP->getRequiresClause() &&
741 "Unexpected requires-clause on template template-parameter");
George Burgess IVb7e4e482016-08-25 01:54:37 +0000742 Expr *const CanonRequiresClause = nullptr;
Hubert Tonge4a0c0e2016-07-30 22:33:34 +0000743
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000744 TemplateTemplateParmDecl *CanonTTP
Fangrui Song6907ce22018-07-30 19:24:48 +0000745 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000746 SourceLocation(), TTP->getDepth(),
Fangrui Song6907ce22018-07-30 19:24:48 +0000747 TTP->getPosition(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000748 TTP->isParameterPack(),
Craig Topper36250ad2014-05-12 05:36:57 +0000749 nullptr,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000750 TemplateParameterList::Create(*this, SourceLocation(),
751 SourceLocation(),
David Majnemer902f8c62015-12-27 07:16:27 +0000752 CanonParams,
Hubert Tonge4a0c0e2016-07-30 22:33:34 +0000753 SourceLocation(),
754 CanonRequiresClause));
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000755
756 // Get the new insert position for the node we care about.
757 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +0000758 assert(!Canonical && "Shouldn't be in the map!");
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000759 (void)Canonical;
760
761 // Create the canonical template template parameter entry.
762 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
763 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
764 return CanonTTP;
765}
766
Charles Davis53c59df2010-08-16 03:33:14 +0000767CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
Craig Topper36250ad2014-05-12 05:36:57 +0000768 if (!LangOpts.CPlusPlus) return nullptr;
John McCall86353412010-08-21 22:46:04 +0000769
John McCall359b8852013-01-25 22:30:49 +0000770 switch (T.getCXXABI().getKind()) {
Joerg Sonnenbergerdaa13aa2014-05-13 11:20:16 +0000771 case TargetCXXABI::GenericARM: // Same as Itanium at this level
John McCall359b8852013-01-25 22:30:49 +0000772 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +0000773 case TargetCXXABI::iOS64:
Tim Northover756447a2015-10-30 16:30:36 +0000774 case TargetCXXABI::WatchOS:
Joerg Sonnenbergerdaa13aa2014-05-13 11:20:16 +0000775 case TargetCXXABI::GenericAArch64:
Zoran Jovanovic26a12162015-02-18 15:21:35 +0000776 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +0000777 case TargetCXXABI::GenericItanium:
Dan Gohmanc2853072015-09-03 22:51:53 +0000778 case TargetCXXABI::WebAssembly:
Charles Davis53c59df2010-08-16 03:33:14 +0000779 return CreateItaniumCXXABI(*this);
John McCall359b8852013-01-25 22:30:49 +0000780 case TargetCXXABI::Microsoft:
Charles Davis6bcb07a2010-08-19 02:18:14 +0000781 return CreateMicrosoftCXXABI(*this);
782 }
David Blaikie8a40f702012-01-17 06:56:22 +0000783 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000784}
785
Alexander Richardson6d989432017-10-15 18:48:14 +0000786static const LangASMap *getAddressSpaceMap(const TargetInfo &T,
787 const LangOptions &LOpts) {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000788 if (LOpts.FakeAddressSpaceMap) {
789 // The fake address space map must have a distinct entry for each
790 // language-specific address space.
791 static const unsigned FakeAddrSpaceMap[] = {
Yaxun Liub34ec822017-04-11 17:24:23 +0000792 0, // Default
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000793 1, // opencl_global
Egor Churaev28f00aa2016-12-23 16:11:25 +0000794 3, // opencl_local
795 2, // opencl_constant
Yaxun Liub7318e02017-10-13 03:37:48 +0000796 0, // opencl_private
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +0000797 4, // opencl_generic
798 5, // cuda_device
799 6, // cuda_constant
800 7 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000801 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000802 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000803 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000804 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000805 }
806}
807
David Tweed31d09b02013-09-13 12:04:22 +0000808static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
809 const LangOptions &LangOpts) {
810 switch (LangOpts.getAddressSpaceMapMangling()) {
David Tweed31d09b02013-09-13 12:04:22 +0000811 case LangOptions::ASMM_Target:
812 return TI.useAddressSpaceMapMangling();
813 case LangOptions::ASMM_On:
814 return true;
815 case LangOptions::ASMM_Off:
816 return false;
817 }
NAKAMURA Takumi5c81ca42013-09-13 17:12:09 +0000818 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
David Tweed31d09b02013-09-13 12:04:22 +0000819}
820
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000821ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000822 IdentifierTable &idents, SelectorTable &sels,
Alp Toker08043432014-05-03 03:46:04 +0000823 Builtin::Context &builtins)
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000824 : FunctionProtoTypes(this_()), TemplateSpecializationTypes(this_()),
825 DependentTemplateSpecializationTypes(this_()),
Eugene Zelenko5e5e5642017-11-23 01:20:07 +0000826 SubstTemplateTemplateParmPacks(this_()), SourceMgr(SM), LangOpts(LOpts),
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000827 SanitizerBL(new SanitizerBlacklist(LangOpts.SanitizerBlacklistFiles, SM)),
Dean Michael Berris835832d2017-03-30 00:29:36 +0000828 XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles,
Dean Michael Berris20dc6ef2018-04-09 04:02:09 +0000829 LangOpts.XRayNeverInstrumentFiles,
830 LangOpts.XRayAttrListFiles, SM)),
Artem Belevichb5bc9232015-09-22 17:23:22 +0000831 PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
Eugene Zelenko5e5e5642017-11-23 01:20:07 +0000832 BuiltinInfo(builtins), DeclarationNames(*this), Comments(SM),
Eric Fiselier0683c0e2018-05-07 21:07:10 +0000833 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
834 CompCategories(this_()), LastSDM(nullptr, 0) {
Daniel Dunbar221fa942008-08-11 04:54:23 +0000835 TUDecl = TranslationUnitDecl::Create(*this);
Sam McCall814e7972018-11-14 10:33:30 +0000836 TraversalScope = {TUDecl};
Daniel Dunbar221fa942008-08-11 04:54:23 +0000837}
838
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000839ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000840 // Release the DenseMaps associated with DeclContext objects.
841 // FIXME: Is this the ideal solution?
842 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000843
Manuel Klimeka7328992013-06-03 13:51:33 +0000844 // Call all of the deallocation functions on all of their targets.
Chandler Carruthff5a01a2015-12-30 03:00:23 +0000845 for (auto &Pair : Deallocations)
846 (Pair.first)(Pair.second);
Manuel Klimeka7328992013-06-03 13:51:33 +0000847
Ted Kremenek076baeb2010-06-08 23:00:58 +0000848 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000849 // because they can contain DenseMaps.
850 for (llvm::DenseMap<const ObjCContainerDecl*,
851 const ASTRecordLayout*>::iterator
852 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
853 // Increment in loop to prevent using deallocated memory.
Eugene Zelenko7855e772018-04-03 00:11:50 +0000854 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
Douglas Gregor5b11d492010-07-25 17:53:33 +0000855 R->Destroy(*this);
856
Ted Kremenek076baeb2010-06-08 23:00:58 +0000857 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
858 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
859 // Increment in loop to prevent using deallocated memory.
Eugene Zelenko7855e772018-04-03 00:11:50 +0000860 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
Ted Kremenek076baeb2010-06-08 23:00:58 +0000861 R->Destroy(*this);
862 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000863
Douglas Gregor561eceb2010-08-30 16:49:28 +0000864 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
865 AEnd = DeclAttrs.end();
866 A != AEnd; ++A)
867 A->second->~AttrVec();
Reid Klecknerd8110b62013-09-10 20:14:30 +0000868
David Majnemere694f3e2015-08-14 14:43:50 +0000869 for (std::pair<const MaterializeTemporaryExpr *, APValue *> &MTVPair :
870 MaterializedTemporaryValues)
871 MTVPair.second->~APValue();
872
Richard Smith423f46f2016-07-20 21:38:26 +0000873 for (const auto &Value : ModuleInitializers)
874 Value.second->~PerModuleInitializers();
Gauthier Harnisch83c7b612019-06-15 10:24:47 +0000875
876 for (APValue *Value : APValueCleanups)
877 Value->~APValue();
Douglas Gregor561eceb2010-08-30 16:49:28 +0000878}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000879
Sam McCall814e7972018-11-14 10:33:30 +0000880class ASTContext::ParentMap {
881 /// Contains parents of a node.
882 using ParentVector = llvm::SmallVector<ast_type_traits::DynTypedNode, 2>;
883
884 /// Maps from a node to its parents. This is used for nodes that have
885 /// pointer identity only, which are more common and we can save space by
886 /// only storing a unique pointer to them.
887 using ParentMapPointers = llvm::DenseMap<
888 const void *,
889 llvm::PointerUnion4<const Decl *, const Stmt *,
890 ast_type_traits::DynTypedNode *, ParentVector *>>;
891
892 /// Parent map for nodes without pointer identity. We store a full
893 /// DynTypedNode for all keys.
894 using ParentMapOtherNodes = llvm::DenseMap<
895 ast_type_traits::DynTypedNode,
896 llvm::PointerUnion4<const Decl *, const Stmt *,
897 ast_type_traits::DynTypedNode *, ParentVector *>>;
898
899 ParentMapPointers PointerParents;
900 ParentMapOtherNodes OtherParents;
901 class ASTVisitor;
902
903 static ast_type_traits::DynTypedNode
904 getSingleDynTypedNodeFromParentMap(ParentMapPointers::mapped_type U) {
905 if (const auto *D = U.dyn_cast<const Decl *>())
906 return ast_type_traits::DynTypedNode::create(*D);
907 if (const auto *S = U.dyn_cast<const Stmt *>())
908 return ast_type_traits::DynTypedNode::create(*S);
909 return *U.get<ast_type_traits::DynTypedNode *>();
910 }
911
912 template <typename NodeTy, typename MapTy>
913 static ASTContext::DynTypedNodeList getDynNodeFromMap(const NodeTy &Node,
914 const MapTy &Map) {
915 auto I = Map.find(Node);
916 if (I == Map.end()) {
917 return llvm::ArrayRef<ast_type_traits::DynTypedNode>();
918 }
919 if (const auto *V = I->second.template dyn_cast<ParentVector *>()) {
920 return llvm::makeArrayRef(*V);
921 }
922 return getSingleDynTypedNodeFromParentMap(I->second);
923 }
924
925public:
926 ParentMap(ASTContext &Ctx);
927 ~ParentMap() {
928 for (const auto &Entry : PointerParents) {
929 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
930 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
931 } else if (Entry.second.is<ParentVector *>()) {
932 delete Entry.second.get<ParentVector *>();
933 }
934 }
935 for (const auto &Entry : OtherParents) {
936 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
937 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
938 } else if (Entry.second.is<ParentVector *>()) {
939 delete Entry.second.get<ParentVector *>();
940 }
Benjamin Kramer94355ae2015-10-23 09:04:55 +0000941 }
942 }
Sam McCall814e7972018-11-14 10:33:30 +0000943
944 DynTypedNodeList getParents(const ast_type_traits::DynTypedNode &Node) {
945 if (Node.getNodeKind().hasPointerIdentity())
946 return getDynNodeFromMap(Node.getMemoizationData(), PointerParents);
947 return getDynNodeFromMap(Node, OtherParents);
Manuel Klimek95403e62014-05-21 13:28:59 +0000948 }
Sam McCall814e7972018-11-14 10:33:30 +0000949};
950
951void ASTContext::setTraversalScope(const std::vector<Decl *> &TopLevelDecls) {
952 TraversalScope = TopLevelDecls;
953 Parents.reset();
Manuel Klimek95403e62014-05-21 13:28:59 +0000954}
955
Gauthier Harnischdea9d572019-06-21 08:26:21 +0000956void ASTContext::AddDeallocation(void (*Callback)(void *), void *Data) const {
Chandler Carruthff5a01a2015-12-30 03:00:23 +0000957 Deallocations.push_back({Callback, Data});
Douglas Gregor1a809332010-05-23 18:26:36 +0000958}
959
Mike Stump11289f42009-09-09 15:08:12 +0000960void
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000961ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
Benjamin Kramerd6da1a02016-06-12 20:05:23 +0000962 ExternalSource = std::move(Source);
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000963}
964
Chris Lattner4eb445d2007-01-26 01:27:23 +0000965void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000966 llvm::errs() << "\n*** AST Context Stats:\n";
967 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000968
Douglas Gregora30d0462009-05-26 14:40:08 +0000969 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000970#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000971#define ABSTRACT_TYPE(Name, Parent)
972#include "clang/AST/TypeNodes.def"
973 0 // Extra
974 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000975
Chris Lattner4eb445d2007-01-26 01:27:23 +0000976 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
977 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000978 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000979 }
980
Douglas Gregora30d0462009-05-26 14:40:08 +0000981 unsigned Idx = 0;
982 unsigned TotalBytes = 0;
983#define TYPE(Name, Parent) \
984 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000985 llvm::errs() << " " << counts[Idx] << " " << #Name \
Bruno Ricci58e03222018-08-06 15:17:32 +0000986 << " types, " << sizeof(Name##Type) << " each " \
987 << "(" << counts[Idx] * sizeof(Name##Type) \
988 << " bytes)\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000989 TotalBytes += counts[Idx] * sizeof(Name##Type); \
990 ++Idx;
991#define ABSTRACT_TYPE(Name, Parent)
992#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000993
Chandler Carruth3c147a72011-07-04 05:32:14 +0000994 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
995
Douglas Gregor7454c562010-07-02 20:37:36 +0000996 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000997 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
998 << NumImplicitDefaultConstructors
999 << " implicit default constructors created\n";
1000 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
1001 << NumImplicitCopyConstructors
1002 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +00001003 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +00001004 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
1005 << NumImplicitMoveConstructors
1006 << " implicit move constructors created\n";
1007 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
1008 << NumImplicitCopyAssignmentOperators
1009 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +00001010 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +00001011 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
1012 << NumImplicitMoveAssignmentOperators
1013 << " implicit move assignment operators created\n";
1014 llvm::errs() << NumImplicitDestructorsDeclared << "/"
1015 << NumImplicitDestructors
1016 << " implicit destructors created\n";
1017
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +00001018 if (ExternalSource) {
Chandler Carruth3c147a72011-07-04 05:32:14 +00001019 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001020 ExternalSource->PrintStats();
1021 }
Chandler Carruth3c147a72011-07-04 05:32:14 +00001022
Douglas Gregor5b11d492010-07-25 17:53:33 +00001023 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +00001024}
1025
Richard Smith42413142015-05-15 20:05:43 +00001026void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
1027 bool NotifyListeners) {
1028 if (NotifyListeners)
1029 if (auto *Listener = getASTMutationListener())
1030 Listener->RedefinedHiddenDefinition(ND, M);
1031
Richard Smith13897eb2018-09-12 23:37:00 +00001032 MergedDefModules[cast<NamedDecl>(ND->getCanonicalDecl())].push_back(M);
Richard Smith42413142015-05-15 20:05:43 +00001033}
1034
1035void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) {
Richard Smith20fbdb32018-09-12 02:13:46 +00001036 auto It = MergedDefModules.find(cast<NamedDecl>(ND->getCanonicalDecl()));
Richard Smith42413142015-05-15 20:05:43 +00001037 if (It == MergedDefModules.end())
1038 return;
1039
Benjamin Kramera72a70a2016-10-17 13:00:44 +00001040 auto &Merged = It->second;
Richard Smith42413142015-05-15 20:05:43 +00001041 llvm::DenseSet<Module*> Found;
1042 for (Module *&M : Merged)
1043 if (!Found.insert(M).second)
1044 M = nullptr;
1045 Merged.erase(std::remove(Merged.begin(), Merged.end(), nullptr), Merged.end());
1046}
1047
Richard Smithdc1f0422016-07-20 19:10:16 +00001048void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
1049 if (LazyInitializers.empty())
1050 return;
1051
1052 auto *Source = Ctx.getExternalSource();
1053 assert(Source && "lazy initializers but no external source");
1054
1055 auto LazyInits = std::move(LazyInitializers);
1056 LazyInitializers.clear();
1057
1058 for (auto ID : LazyInits)
1059 Initializers.push_back(Source->GetExternalDecl(ID));
1060
1061 assert(LazyInitializers.empty() &&
1062 "GetExternalDecl for lazy module initializer added more inits");
1063}
1064
1065void ASTContext::addModuleInitializer(Module *M, Decl *D) {
1066 // One special case: if we add a module initializer that imports another
1067 // module, and that module's only initializer is an ImportDecl, simplify.
Eugene Zelenko7855e772018-04-03 00:11:50 +00001068 if (const auto *ID = dyn_cast<ImportDecl>(D)) {
Richard Smithdc1f0422016-07-20 19:10:16 +00001069 auto It = ModuleInitializers.find(ID->getImportedModule());
1070
1071 // Maybe the ImportDecl does nothing at all. (Common case.)
1072 if (It == ModuleInitializers.end())
1073 return;
1074
1075 // Maybe the ImportDecl only imports another ImportDecl.
1076 auto &Imported = *It->second;
1077 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
1078 Imported.resolve(*this);
1079 auto *OnlyDecl = Imported.Initializers.front();
1080 if (isa<ImportDecl>(OnlyDecl))
1081 D = OnlyDecl;
1082 }
1083 }
1084
1085 auto *&Inits = ModuleInitializers[M];
1086 if (!Inits)
1087 Inits = new (*this) PerModuleInitializers;
1088 Inits->Initializers.push_back(D);
1089}
1090
1091void ASTContext::addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs) {
1092 auto *&Inits = ModuleInitializers[M];
1093 if (!Inits)
1094 Inits = new (*this) PerModuleInitializers;
1095 Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
1096 IDs.begin(), IDs.end());
1097}
1098
Eugene Zelenko7855e772018-04-03 00:11:50 +00001099ArrayRef<Decl *> ASTContext::getModuleInitializers(Module *M) {
Richard Smithdc1f0422016-07-20 19:10:16 +00001100 auto It = ModuleInitializers.find(M);
Fangrui Song6907ce22018-07-30 19:24:48 +00001101 if (It == ModuleInitializers.end())
Richard Smithdc1f0422016-07-20 19:10:16 +00001102 return None;
1103
1104 auto *Inits = It->second;
1105 Inits->resolve(*this);
1106 return Inits->Initializers;
1107}
1108
Richard Smithf19e1272015-03-07 00:04:49 +00001109ExternCContextDecl *ASTContext::getExternCContextDecl() const {
1110 if (!ExternCContext)
1111 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
1112
1113 return ExternCContext;
1114}
1115
David Majnemerd9b1a4f2015-11-04 03:40:30 +00001116BuiltinTemplateDecl *
1117ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
1118 const IdentifierInfo *II) const {
1119 auto *BuiltinTemplate = BuiltinTemplateDecl::Create(*this, TUDecl, II, BTK);
1120 BuiltinTemplate->setImplicit();
1121 TUDecl->addDecl(BuiltinTemplate);
1122
1123 return BuiltinTemplate;
1124}
1125
1126BuiltinTemplateDecl *
1127ASTContext::getMakeIntegerSeqDecl() const {
1128 if (!MakeIntegerSeqDecl)
1129 MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq,
1130 getMakeIntegerSeqName());
1131 return MakeIntegerSeqDecl;
1132}
1133
Eric Fiselier6ad68552016-07-01 01:24:09 +00001134BuiltinTemplateDecl *
1135ASTContext::getTypePackElementDecl() const {
1136 if (!TypePackElementDecl)
1137 TypePackElementDecl = buildBuiltinTemplateDecl(BTK__type_pack_element,
1138 getTypePackElementName());
1139 return TypePackElementDecl;
1140}
1141
Alp Toker2dea15b2013-12-17 01:22:38 +00001142RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
1143 RecordDecl::TagKind TK) const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001144 SourceLocation Loc;
1145 RecordDecl *NewDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00001146 if (getLangOpts().CPlusPlus)
1147 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
1148 Loc, &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +00001149 else
Alp Toker2dea15b2013-12-17 01:22:38 +00001150 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
1151 &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +00001152 NewDecl->setImplicit();
David Majnemerf8637362015-01-15 08:41:25 +00001153 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
1154 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
Alp Toker56b5cc92013-12-15 10:36:26 +00001155 return NewDecl;
1156}
1157
1158TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
1159 StringRef Name) const {
1160 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
1161 TypedefDecl *NewDecl = TypedefDecl::Create(
1162 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
1163 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
1164 NewDecl->setImplicit();
1165 return NewDecl;
1166}
1167
Douglas Gregor801c99d2011-08-12 06:49:56 +00001168TypedefDecl *ASTContext::getInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001169 if (!Int128Decl)
1170 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +00001171 return Int128Decl;
1172}
1173
1174TypedefDecl *ASTContext::getUInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001175 if (!UInt128Decl)
1176 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +00001177 return UInt128Decl;
1178}
Chris Lattner4eb445d2007-01-26 01:27:23 +00001179
John McCall48f2d582009-10-23 23:03:21 +00001180void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001181 auto *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +00001182 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +00001183 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001184}
1185
Artem Belevichb5bc9232015-09-22 17:23:22 +00001186void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
1187 const TargetInfo *AuxTarget) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001188 assert((!this->Target || this->Target == &Target) &&
1189 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +00001190 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +00001191
Douglas Gregore8bbc122011-09-02 00:18:52 +00001192 this->Target = &Target;
Artem Belevichb5bc9232015-09-22 17:23:22 +00001193 this->AuxTarget = AuxTarget;
1194
Douglas Gregore8bbc122011-09-02 00:18:52 +00001195 ABI.reset(createCXXABI(Target));
1196 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
David Tweed31d09b02013-09-13 12:04:22 +00001197 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
Fangrui Song6907ce22018-07-30 19:24:48 +00001198
Chris Lattner970e54e2006-11-12 00:37:36 +00001199 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +00001200 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +00001201
Chris Lattner970e54e2006-11-12 00:37:36 +00001202 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +00001203 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +00001204 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +00001205 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +00001206 InitBuiltinType(CharTy, BuiltinType::Char_S);
1207 else
1208 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +00001209 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +00001210 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
1211 InitBuiltinType(ShortTy, BuiltinType::Short);
1212 InitBuiltinType(IntTy, BuiltinType::Int);
1213 InitBuiltinType(LongTy, BuiltinType::Long);
1214 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +00001215
Chris Lattner970e54e2006-11-12 00:37:36 +00001216 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +00001217 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
1218 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
1219 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
1220 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
1221 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +00001222
Chris Lattner970e54e2006-11-12 00:37:36 +00001223 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +00001224 InitBuiltinType(FloatTy, BuiltinType::Float);
1225 InitBuiltinType(DoubleTy, BuiltinType::Double);
1226 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001227
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001228 // GNU extension, __float128 for IEEE quadruple precision
1229 InitBuiltinType(Float128Ty, BuiltinType::Float128);
1230
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00001231 // C11 extension ISO/IEC TS 18661-3
1232 InitBuiltinType(Float16Ty, BuiltinType::Float16);
1233
Leonard Chanf921d852018-06-04 16:07:52 +00001234 // ISO/IEC JTC1 SC22 WG14 N1169 Extension
Leonard Chanab80f3c2018-06-14 14:53:51 +00001235 InitBuiltinType(ShortAccumTy, BuiltinType::ShortAccum);
1236 InitBuiltinType(AccumTy, BuiltinType::Accum);
1237 InitBuiltinType(LongAccumTy, BuiltinType::LongAccum);
1238 InitBuiltinType(UnsignedShortAccumTy, BuiltinType::UShortAccum);
1239 InitBuiltinType(UnsignedAccumTy, BuiltinType::UAccum);
1240 InitBuiltinType(UnsignedLongAccumTy, BuiltinType::ULongAccum);
1241 InitBuiltinType(ShortFractTy, BuiltinType::ShortFract);
1242 InitBuiltinType(FractTy, BuiltinType::Fract);
1243 InitBuiltinType(LongFractTy, BuiltinType::LongFract);
1244 InitBuiltinType(UnsignedShortFractTy, BuiltinType::UShortFract);
1245 InitBuiltinType(UnsignedFractTy, BuiltinType::UFract);
1246 InitBuiltinType(UnsignedLongFractTy, BuiltinType::ULongFract);
1247 InitBuiltinType(SatShortAccumTy, BuiltinType::SatShortAccum);
1248 InitBuiltinType(SatAccumTy, BuiltinType::SatAccum);
1249 InitBuiltinType(SatLongAccumTy, BuiltinType::SatLongAccum);
1250 InitBuiltinType(SatUnsignedShortAccumTy, BuiltinType::SatUShortAccum);
1251 InitBuiltinType(SatUnsignedAccumTy, BuiltinType::SatUAccum);
1252 InitBuiltinType(SatUnsignedLongAccumTy, BuiltinType::SatULongAccum);
1253 InitBuiltinType(SatShortFractTy, BuiltinType::SatShortFract);
1254 InitBuiltinType(SatFractTy, BuiltinType::SatFract);
1255 InitBuiltinType(SatLongFractTy, BuiltinType::SatLongFract);
1256 InitBuiltinType(SatUnsignedShortFractTy, BuiltinType::SatUShortFract);
1257 InitBuiltinType(SatUnsignedFractTy, BuiltinType::SatUFract);
1258 InitBuiltinType(SatUnsignedLongFractTy, BuiltinType::SatULongFract);
Leonard Chanf921d852018-06-04 16:07:52 +00001259
Chris Lattnerf122cef2009-04-30 02:43:43 +00001260 // GNU extension, 128-bit integers.
1261 InitBuiltinType(Int128Ty, BuiltinType::Int128);
1262 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
1263
Hans Wennborg0d81e012013-05-10 10:08:40 +00001264 // C++ 3.9.1p5
1265 if (TargetInfo::isTypeSigned(Target.getWCharType()))
1266 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1267 else // -fshort-wchar makes wchar_t be unsigned.
1268 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1269 if (LangOpts.CPlusPlus && LangOpts.WChar)
1270 WideCharTy = WCharTy;
1271 else {
1272 // C99 (or C++ using -fno-wchar).
1273 WideCharTy = getFromTargetType(Target.getWCharType());
1274 }
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001275
James Molloy36365542012-05-04 10:55:22 +00001276 WIntTy = getFromTargetType(Target.getWIntType());
1277
Richard Smith3a8244d2018-05-01 05:02:45 +00001278 // C++20 (proposed)
1279 InitBuiltinType(Char8Ty, BuiltinType::Char8);
1280
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001281 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1282 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1283 else // C99
1284 Char16Ty = getFromTargetType(Target.getChar16Type());
1285
1286 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1287 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1288 else // C99
1289 Char32Ty = getFromTargetType(Target.getChar32Type());
1290
Douglas Gregor4619e432008-12-05 23:32:09 +00001291 // Placeholder type for type-dependent expressions whose type is
1292 // completely unknown. No code should ever check a type against
1293 // DependentTy and users should never see it; however, it is here to
1294 // help diagnose failures to properly check for type-dependent
1295 // expressions.
1296 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001297
John McCall36e7fe32010-10-12 00:20:44 +00001298 // Placeholder type for functions.
1299 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1300
John McCall0009fcc2011-04-26 20:42:42 +00001301 // Placeholder type for bound members.
1302 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1303
John McCall526ab472011-10-25 17:37:35 +00001304 // Placeholder type for pseudo-objects.
1305 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1306
John McCall31996342011-04-07 08:22:57 +00001307 // "any" type; useful for debugger-like clients.
1308 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1309
John McCall8a6b59a2011-10-17 18:09:15 +00001310 // Placeholder type for unbridged ARC casts.
1311 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1312
Eli Friedman34866c72012-08-31 00:14:07 +00001313 // Placeholder type for builtin functions.
1314 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1315
Alexey Bataev1a3320e2015-08-25 14:24:04 +00001316 // Placeholder type for OMP array sections.
1317 if (LangOpts.OpenMP)
1318 InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection);
1319
Chris Lattner970e54e2006-11-12 00:37:36 +00001320 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +00001321 FloatComplexTy = getComplexType(FloatTy);
1322 DoubleComplexTy = getComplexType(DoubleTy);
1323 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001324 Float128ComplexTy = getComplexType(Float128Ty);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001325
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001326 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +00001327 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1328 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001329 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001330
Alexey Bader954ba212016-04-08 13:40:33 +00001331 if (LangOpts.OpenCL) {
1332#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1333 InitBuiltinType(SingletonId, BuiltinType::Id);
Alexey Baderb62f1442016-04-13 08:33:41 +00001334#include "clang/Basic/OpenCLImageTypes.def"
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001335
Guy Benyei61054192013-02-07 10:55:47 +00001336 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001337 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Alexey Bader9c8453f2015-09-15 11:18:52 +00001338 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1339 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
Alexey Bader9c8453f2015-09-15 11:18:52 +00001340 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
Andrew Savonichev3fee3512018-11-08 11:25:41 +00001341
1342#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1343 InitBuiltinType(Id##Ty, BuiltinType::Id);
1344#include "clang/Basic/OpenCLExtensionTypes.def"
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001345 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001346
Richard Sandifordeb485fb2019-08-09 08:52:54 +00001347 if (Target.hasAArch64SVETypes()) {
1348#define SVE_TYPE(Name, Id, SingletonId) \
1349 InitBuiltinType(SingletonId, BuiltinType::Id);
1350#include "clang/Basic/AArch64SVEACLETypes.def"
1351 }
1352
Ted Kremeneke65b0862012-03-06 20:05:56 +00001353 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +00001354 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1355 SignedCharTy : BoolTy);
Fangrui Song6907ce22018-07-30 19:24:48 +00001356
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001357 ObjCConstantStringType = QualType();
Fangrui Song6907ce22018-07-30 19:24:48 +00001358
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001359 ObjCSuperType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +00001360
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00001361 // void * type
Yaxun Liu39195062017-08-04 18:16:31 +00001362 if (LangOpts.OpenCLVersion >= 200) {
1363 auto Q = VoidTy.getQualifiers();
1364 Q.setAddressSpace(LangAS::opencl_generic);
1365 VoidPtrTy = getPointerType(getCanonicalType(
1366 getQualifiedType(VoidTy.getUnqualifiedType(), Q)));
1367 } else {
1368 VoidPtrTy = getPointerType(VoidTy);
1369 }
Sebastian Redl576fd422009-05-10 18:38:11 +00001370
1371 // nullptr type (C++0x 2.14.7)
1372 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001373
1374 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1375 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +00001376
1377 // Builtin type used to help define __builtin_va_list.
Richard Smith9b88a4c2015-07-27 05:40:23 +00001378 VaListTagDecl = nullptr;
Chris Lattner970e54e2006-11-12 00:37:36 +00001379}
1380
David Blaikie9c902b52011-09-25 23:23:43 +00001381DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001382 return SourceMgr.getDiagnostics();
1383}
1384
Douglas Gregor561eceb2010-08-30 16:49:28 +00001385AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1386 AttrVec *&Result = DeclAttrs[D];
1387 if (!Result) {
1388 void *Mem = Allocate(sizeof(AttrVec));
1389 Result = new (Mem) AttrVec;
1390 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001391
Douglas Gregor561eceb2010-08-30 16:49:28 +00001392 return *Result;
1393}
1394
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001395/// Erase the attributes corresponding to the given declaration.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00001396void ASTContext::eraseDeclAttrs(const Decl *D) {
Douglas Gregor561eceb2010-08-30 16:49:28 +00001397 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1398 if (Pos != DeclAttrs.end()) {
1399 Pos->second->~AttrVec();
1400 DeclAttrs.erase(Pos);
1401 }
1402}
1403
Larisse Voufo39a1e502013-08-06 01:03:05 +00001404// FIXME: Remove ?
Douglas Gregor86d142a2009-10-08 07:24:58 +00001405MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +00001406ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001407 assert(Var->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001408 return getTemplateOrSpecializationInfo(Var)
1409 .dyn_cast<MemberSpecializationInfo *>();
1410}
1411
1412ASTContext::TemplateOrSpecializationInfo
1413ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1414 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1415 TemplateOrInstantiation.find(Var);
1416 if (Pos == TemplateOrInstantiation.end())
Eugene Zelenko7855e772018-04-03 00:11:50 +00001417 return {};
Mike Stump11289f42009-09-09 15:08:12 +00001418
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001419 return Pos->second;
1420}
1421
Mike Stump11289f42009-09-09 15:08:12 +00001422void
Douglas Gregor86d142a2009-10-08 07:24:58 +00001423ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +00001424 TemplateSpecializationKind TSK,
1425 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001426 assert(Inst->isStaticDataMember() && "Not a static data member");
1427 assert(Tmpl->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001428 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1429 Tmpl, TSK, PointOfInstantiation));
1430}
1431
1432void
1433ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1434 TemplateOrSpecializationInfo TSI) {
1435 assert(!TemplateOrInstantiation[Inst] &&
1436 "Already noted what the variable was instantiated from");
1437 TemplateOrInstantiation[Inst] = TSI;
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001438}
1439
John McCalle61f2ba2009-11-18 02:36:19 +00001440NamedDecl *
Richard Smithd8a9e372016-12-18 21:39:37 +00001441ASTContext::getInstantiatedFromUsingDecl(NamedDecl *UUD) {
1442 auto Pos = InstantiatedFromUsingDecl.find(UUD);
John McCallb96ec562009-12-04 22:46:56 +00001443 if (Pos == InstantiatedFromUsingDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001444 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001445
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001446 return Pos->second;
1447}
1448
1449void
Richard Smithd8a9e372016-12-18 21:39:37 +00001450ASTContext::setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern) {
John McCallb96ec562009-12-04 22:46:56 +00001451 assert((isa<UsingDecl>(Pattern) ||
1452 isa<UnresolvedUsingValueDecl>(Pattern) ||
Fangrui Song6907ce22018-07-30 19:24:48 +00001453 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
John McCallb96ec562009-12-04 22:46:56 +00001454 "pattern decl is not a using decl");
Richard Smithd8a9e372016-12-18 21:39:37 +00001455 assert((isa<UsingDecl>(Inst) ||
1456 isa<UnresolvedUsingValueDecl>(Inst) ||
Fangrui Song6907ce22018-07-30 19:24:48 +00001457 isa<UnresolvedUsingTypenameDecl>(Inst)) &&
Richard Smithd8a9e372016-12-18 21:39:37 +00001458 "instantiation did not produce a using decl");
John McCallb96ec562009-12-04 22:46:56 +00001459 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1460 InstantiatedFromUsingDecl[Inst] = Pattern;
1461}
1462
1463UsingShadowDecl *
1464ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1465 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1466 = InstantiatedFromUsingShadowDecl.find(Inst);
1467 if (Pos == InstantiatedFromUsingShadowDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001468 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00001469
1470 return Pos->second;
1471}
1472
1473void
1474ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1475 UsingShadowDecl *Pattern) {
1476 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1477 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001478}
1479
Anders Carlsson5da84842009-09-01 04:26:58 +00001480FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1481 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1482 = InstantiatedFromUnnamedFieldDecl.find(Field);
1483 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001484 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001485
Anders Carlsson5da84842009-09-01 04:26:58 +00001486 return Pos->second;
1487}
1488
1489void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1490 FieldDecl *Tmpl) {
1491 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1492 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1493 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1494 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +00001495
Anders Carlsson5da84842009-09-01 04:26:58 +00001496 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1497}
1498
Douglas Gregor832940b2010-03-02 23:58:15 +00001499ASTContext::overridden_cxx_method_iterator
1500ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
Benjamin Krameracfa3392017-12-17 23:52:45 +00001501 return overridden_methods(Method).begin();
Douglas Gregor832940b2010-03-02 23:58:15 +00001502}
1503
1504ASTContext::overridden_cxx_method_iterator
1505ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
Benjamin Krameracfa3392017-12-17 23:52:45 +00001506 return overridden_methods(Method).end();
Douglas Gregor832940b2010-03-02 23:58:15 +00001507}
1508
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001509unsigned
1510ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
Benjamin Krameracfa3392017-12-17 23:52:45 +00001511 auto Range = overridden_methods(Method);
1512 return Range.end() - Range.begin();
Clement Courbet8251ebf2016-06-10 11:54:43 +00001513}
1514
Clement Courbet6ecaec82016-07-05 07:49:31 +00001515ASTContext::overridden_method_range
1516ASTContext::overridden_methods(const CXXMethodDecl *Method) const {
Benjamin Krameracfa3392017-12-17 23:52:45 +00001517 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1518 OverriddenMethods.find(Method->getCanonicalDecl());
1519 if (Pos == OverriddenMethods.end())
1520 return overridden_method_range(nullptr, nullptr);
1521 return overridden_method_range(Pos->second.begin(), Pos->second.end());
Clement Courbet6ecaec82016-07-05 07:49:31 +00001522}
1523
Fangrui Song6907ce22018-07-30 19:24:48 +00001524void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
Douglas Gregor832940b2010-03-02 23:58:15 +00001525 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001526 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001527 OverriddenMethods[Method].push_back(Overridden);
1528}
1529
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +00001530void ASTContext::getOverriddenMethods(
1531 const NamedDecl *D,
1532 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001533 assert(D);
1534
Eugene Zelenko7855e772018-04-03 00:11:50 +00001535 if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisc8e70082013-04-17 00:09:03 +00001536 Overridden.append(overridden_methods_begin(CXXMethod),
1537 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001538 return;
1539 }
1540
Eugene Zelenko7855e772018-04-03 00:11:50 +00001541 const auto *Method = dyn_cast<ObjCMethodDecl>(D);
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001542 if (!Method)
1543 return;
1544
Argyrios Kyrtzidis353f6a42012-10-09 18:19:01 +00001545 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1546 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001547 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001548}
1549
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001550void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1551 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1552 assert(!Import->isFromASTFile() && "Non-local import declaration");
1553 if (!FirstLocalImport) {
1554 FirstLocalImport = Import;
1555 LastLocalImport = Import;
1556 return;
1557 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001558
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001559 LastLocalImport->NextLocalImport = Import;
1560 LastLocalImport = Import;
1561}
1562
Chris Lattner53cfe802007-07-18 17:52:12 +00001563//===----------------------------------------------------------------------===//
1564// Type Sizing and Analysis
1565//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001566
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001567/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1568/// scalar floating point type.
1569const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001570 const auto *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001571 assert(BT && "Not a floating point type!");
1572 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001573 default: llvm_unreachable("Not a floating point type!");
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00001574 case BuiltinType::Float16:
1575 case BuiltinType::Half:
1576 return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001577 case BuiltinType::Float: return Target->getFloatFormat();
1578 case BuiltinType::Double: return Target->getDoubleFormat();
Alexey Bataeve509af32019-07-09 14:09:53 +00001579 case BuiltinType::LongDouble:
Fangrui Song3fbd8fd2019-07-09 19:36:22 +00001580 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice)
Alexey Bataeve509af32019-07-09 14:09:53 +00001581 return AuxTarget->getLongDoubleFormat();
1582 return Target->getLongDoubleFormat();
1583 case BuiltinType::Float128:
Fangrui Song3fbd8fd2019-07-09 19:36:22 +00001584 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice)
Alexey Bataeve509af32019-07-09 14:09:53 +00001585 return AuxTarget->getFloat128Format();
1586 return Target->getFloat128Format();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001587 }
1588}
1589
Rafael Espindola71eccb32013-08-08 19:53:46 +00001590CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001591 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001592
John McCall94268702010-10-08 18:24:19 +00001593 bool UseAlignAttrOnly = false;
1594 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1595 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001596
John McCall94268702010-10-08 18:24:19 +00001597 // __attribute__((aligned)) can increase or decrease alignment
1598 // *except* on a struct or struct member, where it only increases
1599 // alignment unless 'packed' is also specified.
1600 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001601 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001602 // ignore that possibility; Sema should diagnose it.
1603 if (isa<FieldDecl>(D)) {
1604 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1605 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1606 } else {
1607 UseAlignAttrOnly = true;
1608 }
1609 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001610 else if (isa<FieldDecl>(D))
Fangrui Song6907ce22018-07-30 19:24:48 +00001611 UseAlignAttrOnly =
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001612 D->hasAttr<PackedAttr>() ||
1613 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001614
John McCall4e819612011-01-20 07:57:12 +00001615 // If we're using the align attribute only, just ignore everything
1616 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001617 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001618 // do nothing
Eugene Zelenko7855e772018-04-03 00:11:50 +00001619 } else if (const auto *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001620 QualType T = VD->getType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00001621 if (const auto *RT = T->getAs<ReferenceType>()) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001622 if (ForAlignof)
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001623 T = RT->getPointeeType();
1624 else
1625 T = getPointerType(RT->getPointeeType());
1626 }
Richard Smithf6d70302014-06-10 23:34:28 +00001627 QualType BaseT = getBaseElementType(T);
Akira Hatanakad62f2c82017-01-06 17:56:15 +00001628 if (T->isFunctionType())
1629 Align = getTypeInfoImpl(T.getTypePtr()).Align;
1630 else if (!BaseT->isIncompleteType()) {
John McCall33ddac02011-01-19 10:06:00 +00001631 // Adjust alignments of declarations with array type by the
1632 // large-array alignment on the target.
Rafael Espindola88572752013-08-07 18:08:19 +00001633 if (const ArrayType *arrayType = getAsArrayType(T)) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001634 unsigned MinWidth = Target->getLargeArrayMinWidth();
1635 if (!ForAlignof && MinWidth) {
Rafael Espindola88572752013-08-07 18:08:19 +00001636 if (isa<VariableArrayType>(arrayType))
1637 Align = std::max(Align, Target->getLargeArrayAlign());
1638 else if (isa<ConstantArrayType>(arrayType) &&
1639 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1640 Align = std::max(Align, Target->getLargeArrayAlign());
1641 }
John McCall33ddac02011-01-19 10:06:00 +00001642 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001643 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Roger Ferrer Ibanez3fa38a12017-03-08 14:00:44 +00001644 if (BaseT.getQualifiers().hasUnaligned())
1645 Align = Target->getCharWidth();
Eugene Zelenko7855e772018-04-03 00:11:50 +00001646 if (const auto *VD = dyn_cast<VarDecl>(D)) {
Tom Tanb7c6d952019-05-02 00:38:14 +00001647 if (VD->hasGlobalStorage() && !ForAlignof) {
1648 uint64_t TypeSize = getTypeSize(T.getTypePtr());
1649 Align = std::max(Align, getTargetInfo().getMinGlobalAlign(TypeSize));
1650 }
Ulrich Weigandfa806422013-05-06 16:23:57 +00001651 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001652 }
John McCall4e819612011-01-20 07:57:12 +00001653
1654 // Fields can be subject to extra alignment constraints, like if
1655 // the field is packed, the struct is packed, or the struct has a
1656 // a max-field-alignment constraint (#pragma pack). So calculate
1657 // the actual alignment of the field within the struct, and then
1658 // (as we're expected to) constrain that by the alignment of the type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00001659 if (const auto *Field = dyn_cast<FieldDecl>(VD)) {
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001660 const RecordDecl *Parent = Field->getParent();
1661 // We can only produce a sensible answer if the record is valid.
1662 if (!Parent->isInvalidDecl()) {
1663 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
John McCall4e819612011-01-20 07:57:12 +00001664
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001665 // Start with the record's overall alignment.
1666 unsigned FieldAlign = toBits(Layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001667
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001668 // Use the GCD of that and the offset within the record.
1669 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1670 if (Offset > 0) {
1671 // Alignment is always a power of 2, so the GCD will be a power of 2,
1672 // which means we get to do this crazy thing instead of Euclid's.
1673 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1674 if (LowBitOfOffset < FieldAlign)
1675 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1676 }
1677
1678 Align = std::min(Align, FieldAlign);
John McCall4e819612011-01-20 07:57:12 +00001679 }
Charles Davis3fc51072010-02-23 04:52:00 +00001680 }
Chris Lattner68061312009-01-24 21:53:27 +00001681 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001682
Ken Dyckcc56c542011-01-15 18:38:59 +00001683 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001684}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001685
John McCallf1249922012-08-21 04:10:00 +00001686// getTypeInfoDataSizeInChars - Return the size of a type, in
1687// chars. If the type is a record, its data size is returned. This is
1688// the size of the memcpy that's performed when assigning this type
1689// using a trivial copy/move assignment operator.
1690std::pair<CharUnits, CharUnits>
1691ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1692 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1693
1694 // In C++, objects can sometimes be allocated into the tail padding
1695 // of a base-class subobject. We decide whether that's possible
1696 // during class layout, so here we can just trust the layout results.
1697 if (getLangOpts().CPlusPlus) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001698 if (const auto *RT = T->getAs<RecordType>()) {
John McCallf1249922012-08-21 04:10:00 +00001699 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1700 sizeAndAlign.first = layout.getDataSize();
1701 }
1702 }
1703
1704 return sizeAndAlign;
1705}
1706
Richard Trieu04d2d942013-05-14 21:59:17 +00001707/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1708/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1709std::pair<CharUnits, CharUnits>
1710static getConstantArrayInfoInChars(const ASTContext &Context,
1711 const ConstantArrayType *CAT) {
1712 std::pair<CharUnits, CharUnits> EltInfo =
1713 Context.getTypeInfoInChars(CAT->getElementType());
1714 uint64_t Size = CAT->getSize().getZExtValue();
Richard Trieuc7509072013-05-14 23:41:50 +00001715 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1716 (uint64_t)(-1)/Size) &&
Richard Trieu04d2d942013-05-14 21:59:17 +00001717 "Overflow in array type char size evaluation");
1718 uint64_t Width = EltInfo.first.getQuantity() * Size;
1719 unsigned Align = EltInfo.second.getQuantity();
Warren Hunt5ae586a2013-11-01 23:59:41 +00001720 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1721 Context.getTargetInfo().getPointerWidth(0) == 64)
Rui Ueyama83aa9792016-01-14 21:00:27 +00001722 Width = llvm::alignTo(Width, Align);
Richard Trieu04d2d942013-05-14 21:59:17 +00001723 return std::make_pair(CharUnits::fromQuantity(Width),
1724 CharUnits::fromQuantity(Align));
1725}
1726
John McCall87fe5d52010-05-20 01:18:31 +00001727std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001728ASTContext::getTypeInfoInChars(const Type *T) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001729 if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
Richard Trieu04d2d942013-05-14 21:59:17 +00001730 return getConstantArrayInfoInChars(*this, CAT);
David Majnemer34b57492014-07-30 01:30:47 +00001731 TypeInfo Info = getTypeInfo(T);
1732 return std::make_pair(toCharUnitsFromBits(Info.Width),
1733 toCharUnitsFromBits(Info.Align));
John McCall87fe5d52010-05-20 01:18:31 +00001734}
1735
1736std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001737ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001738 return getTypeInfoInChars(T.getTypePtr());
1739}
1740
David Majnemer34b57492014-07-30 01:30:47 +00001741bool ASTContext::isAlignmentRequired(const Type *T) const {
1742 return getTypeInfo(T).AlignIsRequired;
1743}
Daniel Dunbarc6475872012-03-09 04:12:54 +00001744
David Majnemer34b57492014-07-30 01:30:47 +00001745bool ASTContext::isAlignmentRequired(QualType T) const {
1746 return isAlignmentRequired(T.getTypePtr());
1747}
1748
Richard Smithb2f0f052016-10-10 18:54:32 +00001749unsigned ASTContext::getTypeAlignIfKnown(QualType T) const {
1750 // An alignment on a typedef overrides anything else.
Eugene Zelenko7855e772018-04-03 00:11:50 +00001751 if (const auto *TT = T->getAs<TypedefType>())
Richard Smithb2f0f052016-10-10 18:54:32 +00001752 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1753 return Align;
1754
1755 // If we have an (array of) complete type, we're done.
1756 T = getBaseElementType(T);
1757 if (!T->isIncompleteType())
1758 return getTypeAlign(T);
1759
1760 // If we had an array type, its element type might be a typedef
1761 // type with an alignment attribute.
Eugene Zelenko7855e772018-04-03 00:11:50 +00001762 if (const auto *TT = T->getAs<TypedefType>())
Richard Smithb2f0f052016-10-10 18:54:32 +00001763 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1764 return Align;
1765
1766 // Otherwise, see if the declaration of the type had an attribute.
Eugene Zelenko7855e772018-04-03 00:11:50 +00001767 if (const auto *TT = T->getAs<TagType>())
Richard Smithb2f0f052016-10-10 18:54:32 +00001768 return TT->getDecl()->getMaxAlignment();
1769
1770 return 0;
1771}
1772
David Majnemer34b57492014-07-30 01:30:47 +00001773TypeInfo ASTContext::getTypeInfo(const Type *T) const {
David Majnemerf8d38642014-07-30 08:42:33 +00001774 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1775 if (I != MemoizedTypeInfo.end())
1776 return I->second;
1777
1778 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1779 TypeInfo TI = getTypeInfoImpl(T);
1780 MemoizedTypeInfo[T] = TI;
Rafael Espindolaeaa88c12014-07-30 04:40:23 +00001781 return TI;
Daniel Dunbarc6475872012-03-09 04:12:54 +00001782}
1783
1784/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1785/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001786///
1787/// FIXME: Pointers into different addr spaces could have different sizes and
1788/// alignment requirements: getPointerInfo should take an AddrSpace, this
1789/// should take a QualType, &c.
David Majnemer34b57492014-07-30 01:30:47 +00001790TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1791 uint64_t Width = 0;
1792 unsigned Align = 8;
1793 bool AlignIsRequired = false;
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001794 unsigned AS = 0;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001795 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001796#define TYPE(Class, Base)
1797#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001798#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001799#define DEPENDENT_TYPE(Class, Base) case Type::Class:
David Blaikieab277d62013-07-13 21:08:03 +00001800#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1801 case Type::Class: \
1802 assert(!T->isDependentType() && "should not see dependent types here"); \
1803 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001804#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001805 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001806
Chris Lattner355332d2007-07-13 22:27:08 +00001807 case Type::FunctionNoProto:
1808 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001809 // GCC extension: alignof(function) = 32 bits
1810 Width = 0;
1811 Align = 32;
1812 break;
1813
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001814 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001815 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001816 Width = 0;
1817 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1818 break;
1819
Steve Naroff5c131802007-08-30 01:06:46 +00001820 case Type::ConstantArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001821 const auto *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001822
David Majnemer34b57492014-07-30 01:30:47 +00001823 TypeInfo EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001824 uint64_t Size = CAT->getSize().getZExtValue();
David Majnemer34b57492014-07-30 01:30:47 +00001825 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
Daniel Dunbarc6475872012-03-09 04:12:54 +00001826 "Overflow in array type bit size evaluation");
David Majnemer34b57492014-07-30 01:30:47 +00001827 Width = EltInfo.Width * Size;
1828 Align = EltInfo.Align;
Warren Hunt5ae586a2013-11-01 23:59:41 +00001829 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1830 getTargetInfo().getPointerWidth(0) == 64)
Rui Ueyama83aa9792016-01-14 21:00:27 +00001831 Width = llvm::alignTo(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001832 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001833 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001834 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001835 case Type::Vector: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001836 const auto *VT = cast<VectorType>(T);
David Majnemer34b57492014-07-30 01:30:47 +00001837 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1838 Width = EltInfo.Width * VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001839 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001840 // If the alignment is not a power of 2, round up to the next power of 2.
1841 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001842 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001843 Align = llvm::NextPowerOf2(Align);
Rui Ueyama83aa9792016-01-14 21:00:27 +00001844 Width = llvm::alignTo(Width, Align);
Chris Lattner63d2b362009-10-22 05:17:15 +00001845 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001846 // Adjust the alignment based on the target max.
1847 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1848 if (TargetVectorAlign && TargetVectorAlign < Align)
1849 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001850 break;
1851 }
Chris Lattner647fb222007-07-18 18:26:58 +00001852
Chris Lattner7570e9c2008-03-08 08:52:55 +00001853 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001854 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001855 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001856 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001857 // GCC extension: alignof(void) = 8 bits.
1858 Width = 0;
1859 Align = 8;
1860 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001861 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001862 Width = Target->getBoolWidth();
1863 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001864 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001865 case BuiltinType::Char_S:
1866 case BuiltinType::Char_U:
1867 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001868 case BuiltinType::SChar:
Richard Smith3a8244d2018-05-01 05:02:45 +00001869 case BuiltinType::Char8:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001870 Width = Target->getCharWidth();
1871 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001872 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001873 case BuiltinType::WChar_S:
1874 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001875 Width = Target->getWCharWidth();
1876 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001877 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001878 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001879 Width = Target->getChar16Width();
1880 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001881 break;
1882 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001883 Width = Target->getChar32Width();
1884 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001885 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001886 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001887 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001888 Width = Target->getShortWidth();
1889 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001890 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001891 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001892 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001893 Width = Target->getIntWidth();
1894 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001895 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001896 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001897 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001898 Width = Target->getLongWidth();
1899 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001900 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001901 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001902 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001903 Width = Target->getLongLongWidth();
1904 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001905 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001906 case BuiltinType::Int128:
1907 case BuiltinType::UInt128:
1908 Width = 128;
1909 Align = 128; // int128_t is 128-bit aligned on all targets.
1910 break;
Leonard Chanf921d852018-06-04 16:07:52 +00001911 case BuiltinType::ShortAccum:
1912 case BuiltinType::UShortAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00001913 case BuiltinType::SatShortAccum:
1914 case BuiltinType::SatUShortAccum:
Leonard Chanf921d852018-06-04 16:07:52 +00001915 Width = Target->getShortAccumWidth();
1916 Align = Target->getShortAccumAlign();
1917 break;
1918 case BuiltinType::Accum:
1919 case BuiltinType::UAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00001920 case BuiltinType::SatAccum:
1921 case BuiltinType::SatUAccum:
Leonard Chanf921d852018-06-04 16:07:52 +00001922 Width = Target->getAccumWidth();
1923 Align = Target->getAccumAlign();
1924 break;
1925 case BuiltinType::LongAccum:
1926 case BuiltinType::ULongAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00001927 case BuiltinType::SatLongAccum:
1928 case BuiltinType::SatULongAccum:
Leonard Chanf921d852018-06-04 16:07:52 +00001929 Width = Target->getLongAccumWidth();
1930 Align = Target->getLongAccumAlign();
1931 break;
Leonard Chanab80f3c2018-06-14 14:53:51 +00001932 case BuiltinType::ShortFract:
1933 case BuiltinType::UShortFract:
1934 case BuiltinType::SatShortFract:
1935 case BuiltinType::SatUShortFract:
1936 Width = Target->getShortFractWidth();
1937 Align = Target->getShortFractAlign();
1938 break;
1939 case BuiltinType::Fract:
1940 case BuiltinType::UFract:
1941 case BuiltinType::SatFract:
1942 case BuiltinType::SatUFract:
1943 Width = Target->getFractWidth();
1944 Align = Target->getFractAlign();
1945 break;
1946 case BuiltinType::LongFract:
1947 case BuiltinType::ULongFract:
1948 case BuiltinType::SatLongFract:
1949 case BuiltinType::SatULongFract:
1950 Width = Target->getLongFractWidth();
1951 Align = Target->getLongFractAlign();
1952 break;
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00001953 case BuiltinType::Float16:
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001954 case BuiltinType::Half:
Alexey Bataev123ad192019-02-27 20:29:45 +00001955 if (Target->hasFloat16Type() || !getLangOpts().OpenMP ||
1956 !getLangOpts().OpenMPIsDevice) {
1957 Width = Target->getHalfWidth();
1958 Align = Target->getHalfAlign();
1959 } else {
1960 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
1961 "Expected OpenMP device compilation.");
1962 Width = AuxTarget->getHalfWidth();
1963 Align = AuxTarget->getHalfAlign();
1964 }
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001965 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001966 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001967 Width = Target->getFloatWidth();
1968 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001969 break;
1970 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001971 Width = Target->getDoubleWidth();
1972 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001973 break;
1974 case BuiltinType::LongDouble:
Alexey Bataev8557d1a2019-06-18 18:39:26 +00001975 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
1976 (Target->getLongDoubleWidth() != AuxTarget->getLongDoubleWidth() ||
1977 Target->getLongDoubleAlign() != AuxTarget->getLongDoubleAlign())) {
1978 Width = AuxTarget->getLongDoubleWidth();
1979 Align = AuxTarget->getLongDoubleAlign();
1980 } else {
1981 Width = Target->getLongDoubleWidth();
1982 Align = Target->getLongDoubleAlign();
1983 }
Chris Lattner6a4f7452007-12-19 19:23:28 +00001984 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001985 case BuiltinType::Float128:
Alexey Bataev123ad192019-02-27 20:29:45 +00001986 if (Target->hasFloat128Type() || !getLangOpts().OpenMP ||
1987 !getLangOpts().OpenMPIsDevice) {
1988 Width = Target->getFloat128Width();
1989 Align = Target->getFloat128Align();
1990 } else {
1991 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
1992 "Expected OpenMP device compilation.");
1993 Width = AuxTarget->getFloat128Width();
1994 Align = AuxTarget->getFloat128Align();
1995 }
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001996 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001997 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001998 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1999 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00002000 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00002001 case BuiltinType::ObjCId:
2002 case BuiltinType::ObjCClass:
2003 case BuiltinType::ObjCSel:
Fangrui Song6907ce22018-07-30 19:24:48 +00002004 Width = Target->getPointerWidth(0);
Douglas Gregore8bbc122011-09-02 00:18:52 +00002005 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00002006 break;
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00002007 case BuiltinType::OCLSampler:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00002008 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00002009 case BuiltinType::OCLClkEvent:
2010 case BuiltinType::OCLQueue:
Alexey Bader9c8453f2015-09-15 11:18:52 +00002011 case BuiltinType::OCLReserveID:
Yaxun Liu99444cb2016-08-03 20:38:06 +00002012#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2013 case BuiltinType::Id:
2014#include "clang/Basic/OpenCLImageTypes.def"
Andrew Savonichev3fee3512018-11-08 11:25:41 +00002015#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2016 case BuiltinType::Id:
2017#include "clang/Basic/OpenCLExtensionTypes.def"
Sven van Haastregt3bb7eaf2017-12-06 10:11:28 +00002018 AS = getTargetAddressSpace(
2019 Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T)));
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00002020 Width = Target->getPointerWidth(AS);
2021 Align = Target->getPointerAlign(AS);
2022 break;
Richard Sandifordeb485fb2019-08-09 08:52:54 +00002023 // The SVE types are effectively target-specific. The length of an
2024 // SVE_VECTOR_TYPE is only known at runtime, but it is always a multiple
2025 // of 128 bits. There is one predicate bit for each vector byte, so the
2026 // length of an SVE_PREDICATE_TYPE is always a multiple of 16 bits.
2027 //
2028 // Because the length is only known at runtime, we use a dummy value
2029 // of 0 for the static length. The alignment values are those defined
2030 // by the Procedure Call Standard for the Arm Architecture.
2031#define SVE_VECTOR_TYPE(Name, Id, SingletonId, ElKind, ElBits, IsSigned, IsFP)\
2032 case BuiltinType::Id: \
2033 Width = 0; \
2034 Align = 128; \
2035 break;
2036#define SVE_PREDICATE_TYPE(Name, Id, SingletonId, ElKind) \
2037 case BuiltinType::Id: \
2038 Width = 0; \
2039 Align = 16; \
2040 break;
2041#include "clang/Basic/AArch64SVEACLETypes.def"
Chris Lattner983a8bb2007-07-13 22:13:22 +00002042 }
Chris Lattner48f84b82007-07-15 23:46:53 +00002043 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00002044 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00002045 Width = Target->getPointerWidth(0);
2046 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00002047 break;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002048 case Type::BlockPointer:
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00002049 AS = getTargetAddressSpace(cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00002050 Width = Target->getPointerWidth(AS);
2051 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00002052 break;
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002053 case Type::LValueReference:
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002054 case Type::RValueReference:
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002055 // alignof and sizeof should never enter this code path here, so we go
2056 // the pointer route.
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00002057 AS = getTargetAddressSpace(cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00002058 Width = Target->getPointerWidth(AS);
2059 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002060 break;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002061 case Type::Pointer:
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00002062 AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00002063 Width = Target->getPointerWidth(AS);
2064 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00002065 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002066 case Type::MemberPointer: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002067 const auto *MPT = cast<MemberPointerType>(T);
Erich Keane8a6b7402017-11-30 16:37:02 +00002068 CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT);
2069 Width = MPI.Width;
2070 Align = MPI.Align;
Anders Carlsson32440a02009-05-17 02:06:04 +00002071 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002072 }
Chris Lattner647fb222007-07-18 18:26:58 +00002073 case Type::Complex: {
2074 // Complex types have the same alignment as their elements, but twice the
2075 // size.
David Majnemer34b57492014-07-30 01:30:47 +00002076 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
2077 Width = EltInfo.Width * 2;
2078 Align = EltInfo.Align;
Chris Lattner647fb222007-07-18 18:26:58 +00002079 break;
2080 }
John McCall8b07ec22010-05-15 11:32:37 +00002081 case Type::ObjCObject:
2082 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Reid Kleckner0503a872013-12-05 01:23:43 +00002083 case Type::Adjusted:
Reid Kleckner8a365022013-06-24 17:51:48 +00002084 case Type::Decayed:
Reid Kleckner0503a872013-12-05 01:23:43 +00002085 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00002086 case Type::ObjCInterface: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002087 const auto *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00002088 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00002089 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00002090 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00002091 break;
2092 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002093 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002094 case Type::Enum: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002095 const auto *TT = cast<TagType>(T);
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00002096
2097 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00002098 Width = 8;
2099 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00002100 break;
2101 }
Mike Stump11289f42009-09-09 15:08:12 +00002102
Eugene Zelenko7855e772018-04-03 00:11:50 +00002103 if (const auto *ET = dyn_cast<EnumType>(TT)) {
David Majnemer475b25e2015-01-21 10:54:38 +00002104 const EnumDecl *ED = ET->getDecl();
2105 TypeInfo Info =
2106 getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType());
2107 if (unsigned AttrAlign = ED->getMaxAlignment()) {
2108 Info.Align = AttrAlign;
2109 Info.AlignIsRequired = true;
2110 }
2111 return Info;
2112 }
Chris Lattner8b23c252008-04-06 22:05:18 +00002113
Eugene Zelenko7855e772018-04-03 00:11:50 +00002114 const auto *RT = cast<RecordType>(TT);
David Majnemer5821ff72015-02-03 08:49:29 +00002115 const RecordDecl *RD = RT->getDecl();
2116 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
Ken Dyckb0fcc592011-02-11 01:54:29 +00002117 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00002118 Align = toBits(Layout.getAlignment());
David Majnemer5821ff72015-02-03 08:49:29 +00002119 AlignIsRequired = RD->hasAttr<AlignedAttr>();
Chris Lattner49a953a2007-07-23 22:46:22 +00002120 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00002121 }
Douglas Gregordc572a32009-03-30 22:58:21 +00002122
Chris Lattner63d2b362009-10-22 05:17:15 +00002123 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00002124 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
2125 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00002126
Richard Smith600b5262017-01-26 20:40:47 +00002127 case Type::Auto:
2128 case Type::DeducedTemplateSpecialization: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002129 const auto *A = cast<DeducedType>(T);
Richard Smith27d807c2013-04-30 13:56:41 +00002130 assert(!A->getDeducedType().isNull() &&
2131 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00002132 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00002133 }
2134
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002135 case Type::Paren:
2136 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
2137
Leonard Chanc72aaf62019-05-07 03:20:17 +00002138 case Type::MacroQualified:
2139 return getTypeInfo(
2140 cast<MacroQualifiedType>(T)->getUnderlyingType().getTypePtr());
2141
Manman Rene6be26c2016-09-13 17:25:08 +00002142 case Type::ObjCTypeParam:
2143 return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr());
2144
Douglas Gregoref462e62009-04-30 17:32:17 +00002145 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00002146 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
David Majnemer34b57492014-07-30 01:30:47 +00002147 TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00002148 // If the typedef has an aligned attribute on it, it overrides any computed
2149 // alignment we have. This violates the GCC documentation (which says that
2150 // attribute(aligned) can only round up) but matches its implementation.
David Majnemer34b57492014-07-30 01:30:47 +00002151 if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
Chris Lattner29eb47b2011-02-19 22:55:41 +00002152 Align = AttrAlign;
David Majnemer34b57492014-07-30 01:30:47 +00002153 AlignIsRequired = true;
David Majnemer37bffb62014-08-04 05:11:01 +00002154 } else {
David Majnemer34b57492014-07-30 01:30:47 +00002155 Align = Info.Align;
David Majnemer37bffb62014-08-04 05:11:01 +00002156 AlignIsRequired = Info.AlignIsRequired;
2157 }
David Majnemer34b57492014-07-30 01:30:47 +00002158 Width = Info.Width;
Douglas Gregordc572a32009-03-30 22:58:21 +00002159 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00002160 }
Douglas Gregoref462e62009-04-30 17:32:17 +00002161
Abramo Bagnara6150c882010-05-11 21:36:43 +00002162 case Type::Elaborated:
2163 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00002164
John McCall81904512011-01-06 01:58:22 +00002165 case Type::Attributed:
2166 return getTypeInfo(
2167 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
2168
Eli Friedman0dfb8892011-10-06 23:00:33 +00002169 case Type::Atomic: {
John McCalla8ec7eb2013-03-07 21:37:17 +00002170 // Start with the base type information.
David Majnemer34b57492014-07-30 01:30:47 +00002171 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
2172 Width = Info.Width;
2173 Align = Info.Align;
John McCalla8ec7eb2013-03-07 21:37:17 +00002174
JF Bastien801fca22018-05-09 03:51:12 +00002175 if (!Width) {
2176 // An otherwise zero-sized type should still generate an
2177 // atomic operation.
2178 Width = Target->getCharWidth();
2179 assert(Align);
2180 } else if (Width <= Target->getMaxAtomicPromoteWidth()) {
2181 // If the size of the type doesn't exceed the platform's max
2182 // atomic promotion width, make the size and alignment more
2183 // favorable to atomic operations:
2184
John McCalla8ec7eb2013-03-07 21:37:17 +00002185 // Round the size up to a power of 2.
2186 if (!llvm::isPowerOf2_64(Width))
2187 Width = llvm::NextPowerOf2(Width);
2188
2189 // Set the alignment equal to the size.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00002190 Align = static_cast<unsigned>(Width);
2191 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00002192 }
Xiuli Pan9c14e282016-01-09 12:53:17 +00002193 break;
2194
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002195 case Type::Pipe:
Anastasia Stulovab3398932017-06-05 11:27:03 +00002196 Width = Target->getPointerWidth(getTargetAddressSpace(LangAS::opencl_global));
2197 Align = Target->getPointerAlign(getTargetAddressSpace(LangAS::opencl_global));
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002198 break;
Douglas Gregoref462e62009-04-30 17:32:17 +00002199 }
Mike Stump11289f42009-09-09 15:08:12 +00002200
Eli Friedman4b72fdd2011-10-14 20:59:01 +00002201 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
David Majnemer34b57492014-07-30 01:30:47 +00002202 return TypeInfo(Width, Align, AlignIsRequired);
Chris Lattner983a8bb2007-07-13 22:13:22 +00002203}
2204
Momchil Velikov20208cc2018-07-30 17:48:23 +00002205unsigned ASTContext::getTypeUnadjustedAlign(const Type *T) const {
2206 UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(T);
2207 if (I != MemoizedUnadjustedAlign.end())
2208 return I->second;
2209
2210 unsigned UnadjustedAlign;
2211 if (const auto *RT = T->getAs<RecordType>()) {
2212 const RecordDecl *RD = RT->getDecl();
2213 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2214 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2215 } else if (const auto *ObjCI = T->getAs<ObjCInterfaceType>()) {
2216 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2217 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2218 } else {
John Brawn6c49f582019-05-22 11:42:54 +00002219 UnadjustedAlign = getTypeAlign(T->getUnqualifiedDesugaredType());
Momchil Velikov20208cc2018-07-30 17:48:23 +00002220 }
2221
2222 MemoizedUnadjustedAlign[T] = UnadjustedAlign;
2223 return UnadjustedAlign;
2224}
2225
Alexey Bataev00396512015-07-02 03:40:19 +00002226unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
2227 unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign();
2228 // Target ppc64 with QPX: simd default alignment for pointer to double is 32.
2229 if ((getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64 ||
2230 getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64le) &&
2231 getTargetInfo().getABI() == "elfv1-qpx" &&
2232 T->isSpecificBuiltinType(BuiltinType::Double))
2233 SimdAlign = 256;
2234 return SimdAlign;
2235}
2236
Ken Dyckcc56c542011-01-15 18:38:59 +00002237/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
2238CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
2239 return CharUnits::fromQuantity(BitSize / getCharWidth());
2240}
2241
Ken Dyckb0fcc592011-02-11 01:54:29 +00002242/// toBits - Convert a size in characters to a size in characters.
2243int64_t ASTContext::toBits(CharUnits CharSize) const {
2244 return CharSize.getQuantity() * getCharWidth();
2245}
2246
Ken Dyck8c89d592009-12-22 14:23:30 +00002247/// getTypeSizeInChars - Return the size of the specified type, in characters.
2248/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00002249CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00002250 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00002251}
Jay Foad39c79802011-01-12 09:06:06 +00002252CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00002253 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00002254}
2255
Fangrui Song6907ce22018-07-30 19:24:48 +00002256/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00002257/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00002258CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00002259 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00002260}
Jay Foad39c79802011-01-12 09:06:06 +00002261CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00002262 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00002263}
2264
Momchil Velikov20208cc2018-07-30 17:48:23 +00002265/// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a
2266/// type, in characters, before alignment adustments. This method does
2267/// not work on incomplete types.
2268CharUnits ASTContext::getTypeUnadjustedAlignInChars(QualType T) const {
2269 return toCharUnitsFromBits(getTypeUnadjustedAlign(T));
2270}
2271CharUnits ASTContext::getTypeUnadjustedAlignInChars(const Type *T) const {
2272 return toCharUnitsFromBits(getTypeUnadjustedAlign(T));
2273}
2274
Chris Lattnera3402cd2009-01-27 18:08:34 +00002275/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
2276/// type for the current target in bits. This can be different than the ABI
2277/// alignment in cases where it is beneficial for performance to overalign
2278/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00002279unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
David Majnemer34b57492014-07-30 01:30:47 +00002280 TypeInfo TI = getTypeInfo(T);
2281 unsigned ABIAlign = TI.Align;
Eli Friedman7ab09572009-05-25 21:27:19 +00002282
David Majnemere1544562015-04-24 01:25:05 +00002283 T = T->getBaseElementTypeUnsafe();
2284
2285 // The preferred alignment of member pointers is that of a pointer.
2286 if (T->isMemberPointerType())
2287 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
2288
Andrey Turetskiydb6655f2016-02-10 11:58:46 +00002289 if (!Target->allowsLargerPreferedTypeAlignment())
2290 return ABIAlign;
Robert Lyttoneaf6f362013-11-12 10:09:34 +00002291
Eli Friedman7ab09572009-05-25 21:27:19 +00002292 // Double and long long should be naturally aligned if possible.
Eugene Zelenko7855e772018-04-03 00:11:50 +00002293 if (const auto *CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00002294 T = CT->getElementType().getTypePtr();
Eugene Zelenko7855e772018-04-03 00:11:50 +00002295 if (const auto *ET = T->getAs<EnumType>())
David Majnemer475b25e2015-01-21 10:54:38 +00002296 T = ET->getDecl()->getIntegerType().getTypePtr();
Eli Friedman7ab09572009-05-25 21:27:19 +00002297 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00002298 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
2299 T->isSpecificBuiltinType(BuiltinType::ULongLong))
David Majnemer8b6bd572014-02-24 23:34:17 +00002300 // Don't increase the alignment if an alignment attribute was specified on a
2301 // typedef declaration.
David Majnemer34b57492014-07-30 01:30:47 +00002302 if (!TI.AlignIsRequired)
David Majnemer8b6bd572014-02-24 23:34:17 +00002303 return std::max(ABIAlign, (unsigned)getTypeSize(T));
Eli Friedman7ab09572009-05-25 21:27:19 +00002304
Chris Lattnera3402cd2009-01-27 18:08:34 +00002305 return ABIAlign;
2306}
2307
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00002308/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2309/// for __attribute__((aligned)) on this target, to be used if no alignment
2310/// value is specified.
Eugene Zelenkod4304d22015-11-04 21:37:17 +00002311unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const {
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00002312 return getTargetInfo().getDefaultAlignForAttributeAligned();
2313}
2314
Ulrich Weigandfa806422013-05-06 16:23:57 +00002315/// getAlignOfGlobalVar - Return the alignment in bits that should be given
2316/// to a global variable of the specified type.
2317unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
Tom Tanb7c6d952019-05-02 00:38:14 +00002318 uint64_t TypeSize = getTypeSize(T.getTypePtr());
2319 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign(TypeSize));
Ulrich Weigandfa806422013-05-06 16:23:57 +00002320}
2321
2322/// getAlignOfGlobalVarInChars - Return the alignment in characters that
2323/// should be given to a global variable of the specified type.
2324CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
2325 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
2326}
2327
David Majnemer08ef2ba2015-06-23 20:34:18 +00002328CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
2329 CharUnits Offset = CharUnits::Zero();
2330 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
2331 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2332 Offset += Layout->getBaseClassOffset(Base);
2333 Layout = &getASTRecordLayout(Base);
2334 }
2335 return Offset;
2336}
2337
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002338/// DeepCollectObjCIvars -
2339/// This routine first collects all declared, but not synthesized, ivars in
2340/// super class and then collects all ivars, including those synthesized for
2341/// current class. This routine is used for implementation of current class
2342/// when all ivars, declared and synthesized are known.
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002343void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
2344 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00002345 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002346 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2347 DeepCollectObjCIvars(SuperClass, false, Ivars);
2348 if (!leafClass) {
Aaron Ballman59abbd42014-03-13 21:09:43 +00002349 for (const auto *I : OI->ivars())
2350 Ivars.push_back(I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00002351 } else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002352 auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Fangrui Song6907ce22018-07-30 19:24:48 +00002353 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00002354 Iv= Iv->getNextIvar())
2355 Ivars.push_back(Iv);
2356 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00002357}
2358
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002359/// CollectInheritedProtocols - Collect all protocols in current class and
2360/// those inherited by it.
2361void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00002362 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002363 if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00002364 // We can use protocol_iterator here instead of
Fangrui Song6907ce22018-07-30 19:24:48 +00002365 // all_referenced_protocol_iterator since we are walking all categories.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002366 for (auto *Proto : OI->all_referenced_protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002367 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00002368 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002369
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002370 // Categories of this Interface.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00002371 for (const auto *Cat : OI->visible_categories())
2372 CollectInheritedProtocols(Cat, Protocols);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002373
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002374 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2375 while (SD) {
2376 CollectInheritedProtocols(SD, Protocols);
2377 SD = SD->getSuperClass();
2378 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00002379 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00002380 for (auto *Proto : OC->protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002381 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002382 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00002383 } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002384 // Insert the protocol.
2385 if (!Protocols.insert(
2386 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2387 return;
2388
2389 for (auto *Proto : OP->protocols())
2390 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002391 }
2392}
2393
Erich Keane8a6b7402017-11-30 16:37:02 +00002394static bool unionHasUniqueObjectRepresentations(const ASTContext &Context,
2395 const RecordDecl *RD) {
2396 assert(RD->isUnion() && "Must be union type");
2397 CharUnits UnionSize = Context.getTypeSizeInChars(RD->getTypeForDecl());
2398
2399 for (const auto *Field : RD->fields()) {
2400 if (!Context.hasUniqueObjectRepresentations(Field->getType()))
2401 return false;
2402 CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType());
2403 if (FieldSize != UnionSize)
2404 return false;
2405 }
Eric Fiselier12a9f342018-02-02 20:30:39 +00002406 return !RD->field_empty();
Erich Keane8a6b7402017-11-30 16:37:02 +00002407}
2408
Benjamin Kramer802e6252017-12-24 12:46:22 +00002409static bool isStructEmpty(QualType Ty) {
Erich Keane8a6b7402017-11-30 16:37:02 +00002410 const RecordDecl *RD = Ty->castAs<RecordType>()->getDecl();
2411
2412 if (!RD->field_empty())
2413 return false;
2414
2415 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD))
2416 return ClassDecl->isEmpty();
2417
2418 return true;
2419}
2420
2421static llvm::Optional<int64_t>
2422structHasUniqueObjectRepresentations(const ASTContext &Context,
2423 const RecordDecl *RD) {
2424 assert(!RD->isUnion() && "Must be struct/class type");
2425 const auto &Layout = Context.getASTRecordLayout(RD);
2426
2427 int64_t CurOffsetInBits = 0;
2428 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) {
2429 if (ClassDecl->isDynamicClass())
2430 return llvm::None;
2431
2432 SmallVector<std::pair<QualType, int64_t>, 4> Bases;
2433 for (const auto Base : ClassDecl->bases()) {
2434 // Empty types can be inherited from, and non-empty types can potentially
2435 // have tail padding, so just make sure there isn't an error.
2436 if (!isStructEmpty(Base.getType())) {
2437 llvm::Optional<int64_t> Size = structHasUniqueObjectRepresentations(
2438 Context, Base.getType()->getAs<RecordType>()->getDecl());
2439 if (!Size)
2440 return llvm::None;
2441 Bases.emplace_back(Base.getType(), Size.getValue());
2442 }
2443 }
2444
Fangrui Song1d38c132018-09-30 21:41:11 +00002445 llvm::sort(Bases, [&](const std::pair<QualType, int64_t> &L,
2446 const std::pair<QualType, int64_t> &R) {
2447 return Layout.getBaseClassOffset(L.first->getAsCXXRecordDecl()) <
2448 Layout.getBaseClassOffset(R.first->getAsCXXRecordDecl());
2449 });
Erich Keane8a6b7402017-11-30 16:37:02 +00002450
2451 for (const auto Base : Bases) {
2452 int64_t BaseOffset = Context.toBits(
2453 Layout.getBaseClassOffset(Base.first->getAsCXXRecordDecl()));
2454 int64_t BaseSize = Base.second;
2455 if (BaseOffset != CurOffsetInBits)
2456 return llvm::None;
2457 CurOffsetInBits = BaseOffset + BaseSize;
2458 }
2459 }
2460
2461 for (const auto *Field : RD->fields()) {
2462 if (!Field->getType()->isReferenceType() &&
2463 !Context.hasUniqueObjectRepresentations(Field->getType()))
2464 return llvm::None;
2465
2466 int64_t FieldSizeInBits =
2467 Context.toBits(Context.getTypeSizeInChars(Field->getType()));
2468 if (Field->isBitField()) {
2469 int64_t BitfieldSize = Field->getBitWidthValue(Context);
2470
2471 if (BitfieldSize > FieldSizeInBits)
2472 return llvm::None;
2473 FieldSizeInBits = BitfieldSize;
2474 }
2475
2476 int64_t FieldOffsetInBits = Context.getFieldOffset(Field);
2477
2478 if (FieldOffsetInBits != CurOffsetInBits)
2479 return llvm::None;
2480
2481 CurOffsetInBits = FieldSizeInBits + FieldOffsetInBits;
2482 }
2483
2484 return CurOffsetInBits;
2485}
2486
2487bool ASTContext::hasUniqueObjectRepresentations(QualType Ty) const {
2488 // C++17 [meta.unary.prop]:
2489 // The predicate condition for a template specialization
2490 // has_unique_object_representations<T> shall be
2491 // satisfied if and only if:
2492 // (9.1) - T is trivially copyable, and
2493 // (9.2) - any two objects of type T with the same value have the same
2494 // object representation, where two objects
2495 // of array or non-union class type are considered to have the same value
2496 // if their respective sequences of
2497 // direct subobjects have the same values, and two objects of union type
2498 // are considered to have the same
2499 // value if they have the same active member and the corresponding members
2500 // have the same value.
2501 // The set of scalar types for which this condition holds is
2502 // implementation-defined. [ Note: If a type has padding
2503 // bits, the condition does not hold; otherwise, the condition holds true
2504 // for unsigned integral types. -- end note ]
2505 assert(!Ty.isNull() && "Null QualType sent to unique object rep check");
2506
2507 // Arrays are unique only if their element type is unique.
2508 if (Ty->isArrayType())
2509 return hasUniqueObjectRepresentations(getBaseElementType(Ty));
2510
2511 // (9.1) - T is trivially copyable...
2512 if (!Ty.isTriviallyCopyableType(*this))
2513 return false;
2514
2515 // All integrals and enums are unique.
2516 if (Ty->isIntegralOrEnumerationType())
2517 return true;
2518
2519 // All other pointers are unique.
2520 if (Ty->isPointerType())
2521 return true;
2522
2523 if (Ty->isMemberPointerType()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002524 const auto *MPT = Ty->getAs<MemberPointerType>();
Erich Keane8a6b7402017-11-30 16:37:02 +00002525 return !ABI->getMemberPointerInfo(MPT).HasPadding;
2526 }
2527
2528 if (Ty->isRecordType()) {
2529 const RecordDecl *Record = Ty->getAs<RecordType>()->getDecl();
2530
Erich Keanebd2197c2017-12-12 16:02:06 +00002531 if (Record->isInvalidDecl())
2532 return false;
2533
Erich Keane8a6b7402017-11-30 16:37:02 +00002534 if (Record->isUnion())
2535 return unionHasUniqueObjectRepresentations(*this, Record);
2536
2537 Optional<int64_t> StructSize =
2538 structHasUniqueObjectRepresentations(*this, Record);
2539
2540 return StructSize &&
2541 StructSize.getValue() == static_cast<int64_t>(getTypeSize(Ty));
2542 }
2543
2544 // FIXME: More cases to handle here (list by rsmith):
2545 // vectors (careful about, eg, vector of 3 foo)
2546 // _Complex int and friends
2547 // _Atomic T
2548 // Obj-C block pointers
2549 // Obj-C object pointers
2550 // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t,
2551 // clk_event_t, queue_t, reserve_id_t)
2552 // There're also Obj-C class types and the Obj-C selector type, but I think it
2553 // makes sense for those to return false here.
2554
2555 return false;
2556}
2557
Jay Foad39c79802011-01-12 09:06:06 +00002558unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00002559 unsigned count = 0;
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00002560 // Count ivars declared in class extension.
Aaron Ballmanb4a53452014-03-13 21:57:01 +00002561 for (const auto *Ext : OI->known_extensions())
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002562 count += Ext->ivar_size();
Fangrui Song6907ce22018-07-30 19:24:48 +00002563
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00002564 // Count ivar defined in this class's implementation. This
2565 // includes synthesized ivars.
2566 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00002567 count += ImplDecl->ivar_size();
2568
Fariborz Jahanian7c809592009-06-04 01:19:09 +00002569 return count;
2570}
2571
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00002572bool ASTContext::isSentinelNullExpr(const Expr *E) {
2573 if (!E)
2574 return false;
2575
2576 // nullptr_t is always treated as null.
2577 if (E->getType()->isNullPtrType()) return true;
2578
2579 if (E->getType()->isAnyPointerType() &&
2580 E->IgnoreParenCasts()->isNullPointerConstant(*this,
2581 Expr::NPC_ValueDependentIsNull))
2582 return true;
2583
2584 // Unfortunately, __null has type 'int'.
2585 if (isa<GNUNullExpr>(E)) return true;
2586
2587 return false;
2588}
2589
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002590/// Get the implementation of ObjCInterfaceDecl, or nullptr if none
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002591/// exists.
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002592ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
2593 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2594 I = ObjCImpls.find(D);
2595 if (I != ObjCImpls.end())
2596 return cast<ObjCImplementationDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002597 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002598}
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002599
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002600/// Get the implementation of ObjCCategoryDecl, or nullptr if none
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002601/// exists.
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002602ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
2603 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2604 I = ObjCImpls.find(D);
2605 if (I != ObjCImpls.end())
2606 return cast<ObjCCategoryImplDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002607 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002608}
2609
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002610/// Set the implementation of ObjCInterfaceDecl.
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002611void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2612 ObjCImplementationDecl *ImplD) {
2613 assert(IFaceD && ImplD && "Passed null params");
2614 ObjCImpls[IFaceD] = ImplD;
2615}
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002616
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002617/// Set the implementation of ObjCCategoryDecl.
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002618void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
2619 ObjCCategoryImplDecl *ImplD) {
2620 assert(CatD && ImplD && "Passed null params");
2621 ObjCImpls[CatD] = ImplD;
2622}
2623
Chandler Carruth21c90602015-12-30 03:24:14 +00002624const ObjCMethodDecl *
2625ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const {
2626 return ObjCMethodRedecls.lookup(MD);
2627}
2628
2629void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
2630 const ObjCMethodDecl *Redecl) {
2631 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
2632 ObjCMethodRedecls[MD] = Redecl;
2633}
2634
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002635const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
2636 const NamedDecl *ND) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002637 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002638 return ID;
Eugene Zelenko7855e772018-04-03 00:11:50 +00002639 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002640 return CD->getClassInterface();
Eugene Zelenko7855e772018-04-03 00:11:50 +00002641 if (const auto *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002642 return IMD->getClassInterface();
2643
Craig Topper36250ad2014-05-12 05:36:57 +00002644 return nullptr;
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002645}
2646
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002647/// Get the copy initialization expression of VarDecl, or nullptr if
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002648/// none exists.
Akira Hatanaka9978da32018-08-10 15:09:24 +00002649ASTContext::BlockVarCopyInit
2650ASTContext::getBlockVarCopyInit(const VarDecl*VD) const {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002651 assert(VD && "Passed null params");
Fangrui Song6907ce22018-07-30 19:24:48 +00002652 assert(VD->hasAttr<BlocksAttr>() &&
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002653 "getBlockVarCopyInits - not __block var");
Akira Hatanaka9978da32018-08-10 15:09:24 +00002654 auto I = BlockVarCopyInits.find(VD);
2655 if (I != BlockVarCopyInits.end())
2656 return I->second;
2657 return {nullptr, false};
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002658}
2659
JF Bastien0d702a72019-04-30 00:11:53 +00002660/// Set the copy initialization expression of a block var decl.
Akira Hatanaka9978da32018-08-10 15:09:24 +00002661void ASTContext::setBlockVarCopyInit(const VarDecl*VD, Expr *CopyExpr,
2662 bool CanThrow) {
2663 assert(VD && CopyExpr && "Passed null params");
Fangrui Song6907ce22018-07-30 19:24:48 +00002664 assert(VD->hasAttr<BlocksAttr>() &&
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002665 "setBlockVarCopyInits - not __block var");
Akira Hatanaka9978da32018-08-10 15:09:24 +00002666 BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002667}
2668
John McCallbcd03502009-12-07 02:54:59 +00002669TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002670 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00002671 if (!DataSize)
2672 DataSize = TypeLoc::getFullDataSizeForType(T);
2673 else
2674 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00002675 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00002676
Eugene Zelenko7855e772018-04-03 00:11:50 +00002677 auto *TInfo =
John McCallbcd03502009-12-07 02:54:59 +00002678 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
2679 new (TInfo) TypeSourceInfo(T);
2680 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00002681}
2682
John McCallbcd03502009-12-07 02:54:59 +00002683TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002684 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00002685 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00002686 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00002687 return DI;
2688}
2689
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002690const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002691ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Craig Topper36250ad2014-05-12 05:36:57 +00002692 return getObjCLayout(D, nullptr);
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002693}
2694
2695const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002696ASTContext::getASTObjCImplementationLayout(
2697 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002698 return getObjCLayout(D->getClassInterface(), D);
2699}
2700
Chris Lattner983a8bb2007-07-13 22:13:22 +00002701//===----------------------------------------------------------------------===//
2702// Type creation/memoization methods
2703//===----------------------------------------------------------------------===//
2704
Jay Foad39c79802011-01-12 09:06:06 +00002705QualType
John McCall33ddac02011-01-19 10:06:00 +00002706ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2707 unsigned fastQuals = quals.getFastQualifiers();
2708 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00002709
2710 // Check if we've already instantiated this type.
2711 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002712 ExtQuals::Profile(ID, baseType, quals);
Craig Topper36250ad2014-05-12 05:36:57 +00002713 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002714 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2715 assert(eq->getQualifiers() == quals);
2716 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002717 }
2718
John McCall33ddac02011-01-19 10:06:00 +00002719 // If the base type is not canonical, make the appropriate canonical type.
2720 QualType canon;
2721 if (!baseType->isCanonicalUnqualified()) {
2722 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00002723 canonSplit.Quals.addConsistentQualifiers(quals);
2724 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002725
2726 // Re-find the insert position.
2727 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2728 }
2729
Eugene Zelenko7855e772018-04-03 00:11:50 +00002730 auto *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
John McCall33ddac02011-01-19 10:06:00 +00002731 ExtQualNodes.InsertNode(eq, insertPos);
2732 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002733}
2734
Alexander Richardson6d989432017-10-15 18:48:14 +00002735QualType ASTContext::getAddrSpaceQualType(QualType T,
2736 LangAS AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002737 QualType CanT = getCanonicalType(T);
2738 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00002739 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00002740
John McCall8ccfcb52009-09-24 19:53:00 +00002741 // If we are composing extended qualifiers together, merge together
2742 // into one ExtQuals node.
2743 QualifierCollector Quals;
2744 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002745
John McCall8ccfcb52009-09-24 19:53:00 +00002746 // If this type already has an address space specified, it cannot get
2747 // another one.
2748 assert(!Quals.hasAddressSpace() &&
2749 "Type cannot be in multiple addr spaces!");
2750 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00002751
John McCall8ccfcb52009-09-24 19:53:00 +00002752 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00002753}
2754
Andrew Gozillon572bbb02017-10-02 06:25:51 +00002755QualType ASTContext::removeAddrSpaceQualType(QualType T) const {
2756 // If we are composing extended qualifiers together, merge together
2757 // into one ExtQuals node.
2758 QualifierCollector Quals;
2759 const Type *TypeNode = Quals.strip(T);
2760
2761 // If the qualifier doesn't have an address space just return it.
2762 if (!Quals.hasAddressSpace())
2763 return T;
2764
2765 Quals.removeAddressSpace();
2766
2767 // Removal of the address space can mean there are no longer any
2768 // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts)
2769 // or required.
2770 if (Quals.hasNonFastQualifiers())
2771 return getExtQualType(TypeNode, Quals);
2772 else
2773 return QualType(TypeNode, Quals.getFastQualifiers());
2774}
2775
Chris Lattnerd60183d2009-02-18 22:53:11 +00002776QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002777 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002778 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00002779 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002780 return T;
Mike Stump11289f42009-09-09 15:08:12 +00002781
Eugene Zelenko7855e772018-04-03 00:11:50 +00002782 if (const auto *ptr = T->getAs<PointerType>()) {
John McCall53fa7142010-12-24 02:08:15 +00002783 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00002784 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00002785 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2786 return getPointerType(ResultType);
2787 }
2788 }
Mike Stump11289f42009-09-09 15:08:12 +00002789
John McCall8ccfcb52009-09-24 19:53:00 +00002790 // If we are composing extended qualifiers together, merge together
2791 // into one ExtQuals node.
2792 QualifierCollector Quals;
2793 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002794
John McCall8ccfcb52009-09-24 19:53:00 +00002795 // If this type already has an ObjCGC specified, it cannot get
2796 // another one.
2797 assert(!Quals.hasObjCGCAttr() &&
2798 "Type cannot have multiple ObjCGCs!");
2799 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00002800
John McCall8ccfcb52009-09-24 19:53:00 +00002801 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002802}
Chris Lattner983a8bb2007-07-13 22:13:22 +00002803
John McCall4f5019e2010-12-19 02:44:49 +00002804const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2805 FunctionType::ExtInfo Info) {
2806 if (T->getExtInfo() == Info)
2807 return T;
2808
2809 QualType Result;
Eugene Zelenko7855e772018-04-03 00:11:50 +00002810 if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
Alp Toker314cc812014-01-25 16:55:45 +00002811 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
John McCall4f5019e2010-12-19 02:44:49 +00002812 } else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002813 const auto *FPT = cast<FunctionProtoType>(T);
John McCall4f5019e2010-12-19 02:44:49 +00002814 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2815 EPI.ExtInfo = Info;
Alp Toker314cc812014-01-25 16:55:45 +00002816 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
John McCall4f5019e2010-12-19 02:44:49 +00002817 }
2818
2819 return cast<FunctionType>(Result.getTypePtr());
2820}
2821
Richard Smith2a7d4812013-05-04 07:00:32 +00002822void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2823 QualType ResultType) {
Richard Smith1fa5d642013-05-11 05:45:24 +00002824 FD = FD->getMostRecentDecl();
2825 while (true) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002826 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
Richard Smith2a7d4812013-05-04 07:00:32 +00002827 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Alp Toker9cacbab2014-01-20 20:26:09 +00002828 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
Richard Smith1fa5d642013-05-11 05:45:24 +00002829 if (FunctionDecl *Next = FD->getPreviousDecl())
2830 FD = Next;
2831 else
2832 break;
Richard Smith2a7d4812013-05-04 07:00:32 +00002833 }
Richard Smith1fa5d642013-05-11 05:45:24 +00002834 if (ASTMutationListener *L = getASTMutationListener())
2835 L->DeducedReturnType(FD, ResultType);
Richard Smith2a7d4812013-05-04 07:00:32 +00002836}
2837
Richard Smith0b3a4622014-11-13 20:01:57 +00002838/// Get a function type and produce the equivalent function type with the
2839/// specified exception specification. Type sugar that can be present on a
2840/// declaration of a function with an exception specification is permitted
2841/// and preserved. Other type sugar (for instance, typedefs) is not.
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002842QualType ASTContext::getFunctionTypeWithExceptionSpec(
2843 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) {
Richard Smith0b3a4622014-11-13 20:01:57 +00002844 // Might have some parens.
Eugene Zelenko7855e772018-04-03 00:11:50 +00002845 if (const auto *PT = dyn_cast<ParenType>(Orig))
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002846 return getParenType(
2847 getFunctionTypeWithExceptionSpec(PT->getInnerType(), ESI));
Richard Smith0b3a4622014-11-13 20:01:57 +00002848
Leonard Chandc5d9752019-05-10 18:05:15 +00002849 // Might be wrapped in a macro qualified type.
2850 if (const auto *MQT = dyn_cast<MacroQualifiedType>(Orig))
2851 return getMacroQualifiedType(
2852 getFunctionTypeWithExceptionSpec(MQT->getUnderlyingType(), ESI),
2853 MQT->getMacroIdentifier());
2854
Richard Smith0b3a4622014-11-13 20:01:57 +00002855 // Might have a calling-convention attribute.
Eugene Zelenko7855e772018-04-03 00:11:50 +00002856 if (const auto *AT = dyn_cast<AttributedType>(Orig))
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002857 return getAttributedType(
Richard Smith0b3a4622014-11-13 20:01:57 +00002858 AT->getAttrKind(),
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002859 getFunctionTypeWithExceptionSpec(AT->getModifiedType(), ESI),
2860 getFunctionTypeWithExceptionSpec(AT->getEquivalentType(), ESI));
Richard Smith0b3a4622014-11-13 20:01:57 +00002861
2862 // Anything else must be a function type. Rebuild it with the new exception
2863 // specification.
Stephan Bergmann84dcc8f2019-02-13 09:39:17 +00002864 const auto *Proto = Orig->getAs<FunctionProtoType>();
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002865 return getFunctionType(
Richard Smith0b3a4622014-11-13 20:01:57 +00002866 Proto->getReturnType(), Proto->getParamTypes(),
2867 Proto->getExtProtoInfo().withExceptionSpec(ESI));
2868}
2869
Richard Smithdfe85e22016-12-15 02:35:39 +00002870bool ASTContext::hasSameFunctionTypeIgnoringExceptionSpec(QualType T,
2871 QualType U) {
2872 return hasSameType(T, U) ||
Aaron Ballmanc351fba2017-12-04 20:27:34 +00002873 (getLangOpts().CPlusPlus17 &&
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002874 hasSameType(getFunctionTypeWithExceptionSpec(T, EST_None),
2875 getFunctionTypeWithExceptionSpec(U, EST_None)));
Richard Smithdfe85e22016-12-15 02:35:39 +00002876}
2877
Richard Smith0b3a4622014-11-13 20:01:57 +00002878void ASTContext::adjustExceptionSpec(
2879 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
2880 bool AsWritten) {
2881 // Update the type.
2882 QualType Updated =
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002883 getFunctionTypeWithExceptionSpec(FD->getType(), ESI);
Richard Smith0b3a4622014-11-13 20:01:57 +00002884 FD->setType(Updated);
2885
2886 if (!AsWritten)
2887 return;
2888
2889 // Update the type in the type source information too.
2890 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
2891 // If the type and the type-as-written differ, we may need to update
2892 // the type-as-written too.
2893 if (TSInfo->getType() != FD->getType())
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002894 Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI);
Richard Smith0b3a4622014-11-13 20:01:57 +00002895
2896 // FIXME: When we get proper type location information for exceptions,
2897 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
2898 // up the TypeSourceInfo;
2899 assert(TypeLoc::getFullDataSizeForType(Updated) ==
2900 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
2901 "TypeLoc size mismatch from updating exception specification");
2902 TSInfo->overrideType(Updated);
2903 }
2904}
2905
Chris Lattnerc6395932007-06-22 20:56:16 +00002906/// getComplexType - Return the uniqued reference to the type for a complex
2907/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00002908QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00002909 // Unique pointers, to guarantee there is only one pointer of a particular
2910 // structure.
2911 llvm::FoldingSetNodeID ID;
2912 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002913
Craig Topper36250ad2014-05-12 05:36:57 +00002914 void *InsertPos = nullptr;
Chris Lattnerc6395932007-06-22 20:56:16 +00002915 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2916 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002917
Chris Lattnerc6395932007-06-22 20:56:16 +00002918 // If the pointee type isn't canonical, this won't be a canonical type either,
2919 // so fill in the canonical type field.
2920 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002921 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002922 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002923
Chris Lattnerc6395932007-06-22 20:56:16 +00002924 // Get the new insert position for the node we care about.
2925 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002926 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00002927 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00002928 auto *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00002929 Types.push_back(New);
2930 ComplexTypes.InsertNode(New, InsertPos);
2931 return QualType(New, 0);
2932}
2933
Chris Lattner970e54e2006-11-12 00:37:36 +00002934/// getPointerType - Return the uniqued reference to the type for a pointer to
2935/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002936QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00002937 // Unique pointers, to guarantee there is only one pointer of a particular
2938 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002939 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00002940 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002941
Craig Topper36250ad2014-05-12 05:36:57 +00002942 void *InsertPos = nullptr;
Chris Lattner67521df2007-01-27 01:29:36 +00002943 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002944 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002945
Chris Lattner7ccecb92006-11-12 08:50:50 +00002946 // If the pointee type isn't canonical, this won't be a canonical type either,
2947 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002948 QualType Canonical;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002949 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002950 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002951
Bob Wilsonc8541f22013-03-15 17:12:43 +00002952 // Get the new insert position for the node we care about.
2953 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002954 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002955 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00002956 auto *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00002957 Types.push_back(New);
2958 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002959 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00002960}
2961
Reid Kleckner0503a872013-12-05 01:23:43 +00002962QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
2963 llvm::FoldingSetNodeID ID;
2964 AdjustedType::Profile(ID, Orig, New);
Craig Topper36250ad2014-05-12 05:36:57 +00002965 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002966 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2967 if (AT)
2968 return QualType(AT, 0);
2969
2970 QualType Canonical = getCanonicalType(New);
2971
2972 // Get the new insert position for the node we care about.
2973 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002974 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner0503a872013-12-05 01:23:43 +00002975
2976 AT = new (*this, TypeAlignment)
2977 AdjustedType(Type::Adjusted, Orig, New, Canonical);
2978 Types.push_back(AT);
2979 AdjustedTypes.InsertNode(AT, InsertPos);
2980 return QualType(AT, 0);
2981}
2982
Reid Kleckner8a365022013-06-24 17:51:48 +00002983QualType ASTContext::getDecayedType(QualType T) const {
2984 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2985
Reid Kleckner8a365022013-06-24 17:51:48 +00002986 QualType Decayed;
2987
2988 // C99 6.7.5.3p7:
2989 // A declaration of a parameter as "array of type" shall be
2990 // adjusted to "qualified pointer to type", where the type
2991 // qualifiers (if any) are those specified within the [ and ] of
2992 // the array type derivation.
2993 if (T->isArrayType())
2994 Decayed = getArrayDecayedType(T);
2995
2996 // C99 6.7.5.3p8:
2997 // A declaration of a parameter as "function returning type"
2998 // shall be adjusted to "pointer to function returning type", as
2999 // in 6.3.2.1.
3000 if (T->isFunctionType())
3001 Decayed = getPointerType(T);
3002
Reid Kleckner0503a872013-12-05 01:23:43 +00003003 llvm::FoldingSetNodeID ID;
3004 AdjustedType::Profile(ID, T, Decayed);
Craig Topper36250ad2014-05-12 05:36:57 +00003005 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00003006 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3007 if (AT)
3008 return QualType(AT, 0);
3009
Reid Kleckner8a365022013-06-24 17:51:48 +00003010 QualType Canonical = getCanonicalType(Decayed);
3011
3012 // Get the new insert position for the node we care about.
Reid Kleckner0503a872013-12-05 01:23:43 +00003013 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003014 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner8a365022013-06-24 17:51:48 +00003015
Reid Kleckner0503a872013-12-05 01:23:43 +00003016 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
3017 Types.push_back(AT);
3018 AdjustedTypes.InsertNode(AT, InsertPos);
3019 return QualType(AT, 0);
Reid Kleckner8a365022013-06-24 17:51:48 +00003020}
3021
Mike Stump11289f42009-09-09 15:08:12 +00003022/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00003023/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00003024QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00003025 assert(T->isFunctionType() && "block of function types only");
3026 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00003027 // structure.
3028 llvm::FoldingSetNodeID ID;
3029 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00003030
Craig Topper36250ad2014-05-12 05:36:57 +00003031 void *InsertPos = nullptr;
Steve Naroffec33ed92008-08-27 16:04:49 +00003032 if (BlockPointerType *PT =
3033 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3034 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003035
3036 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00003037 // type either so fill in the canonical type field.
3038 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00003039 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00003040 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00003041
Steve Naroffec33ed92008-08-27 16:04:49 +00003042 // Get the new insert position for the node we care about.
3043 BlockPointerType *NewIP =
3044 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003045 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00003046 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00003047 auto *New = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00003048 Types.push_back(New);
3049 BlockPointerTypes.InsertNode(New, InsertPos);
3050 return QualType(New, 0);
3051}
3052
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003053/// getLValueReferenceType - Return the uniqued reference to the type for an
3054/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00003055QualType
3056ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00003057 assert(getCanonicalType(T) != OverloadTy &&
Douglas Gregor291e8ee2011-05-21 22:16:50 +00003058 "Unresolved overloaded function type");
Fangrui Song6907ce22018-07-30 19:24:48 +00003059
Bill Wendling3708c182007-05-27 10:15:43 +00003060 // Unique pointers, to guarantee there is only one pointer of a particular
3061 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00003062 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00003063 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00003064
Craig Topper36250ad2014-05-12 05:36:57 +00003065 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003066 if (LValueReferenceType *RT =
3067 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00003068 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003069
Eugene Zelenko7855e772018-04-03 00:11:50 +00003070 const auto *InnerRef = T->getAs<ReferenceType>();
John McCallfc93cf92009-10-22 22:37:11 +00003071
Bill Wendling3708c182007-05-27 10:15:43 +00003072 // If the referencee type isn't canonical, this won't be a canonical type
3073 // either, so fill in the canonical type field.
3074 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00003075 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
3076 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
3077 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003078
Bill Wendling3708c182007-05-27 10:15:43 +00003079 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003080 LValueReferenceType *NewIP =
3081 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003082 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00003083 }
3084
Eugene Zelenko7855e772018-04-03 00:11:50 +00003085 auto *New = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
3086 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00003087 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003088 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00003089
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003090 return QualType(New, 0);
3091}
3092
3093/// getRValueReferenceType - Return the uniqued reference to the type for an
3094/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00003095QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003096 // Unique pointers, to guarantee there is only one pointer of a particular
3097 // structure.
3098 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00003099 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003100
Craig Topper36250ad2014-05-12 05:36:57 +00003101 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003102 if (RValueReferenceType *RT =
3103 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
3104 return QualType(RT, 0);
3105
Eugene Zelenko7855e772018-04-03 00:11:50 +00003106 const auto *InnerRef = T->getAs<ReferenceType>();
John McCallfc93cf92009-10-22 22:37:11 +00003107
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003108 // If the referencee type isn't canonical, this won't be a canonical type
3109 // either, so fill in the canonical type field.
3110 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00003111 if (InnerRef || !T.isCanonical()) {
3112 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
3113 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003114
3115 // Get the new insert position for the node we care about.
3116 RValueReferenceType *NewIP =
3117 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003118 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003119 }
3120
Eugene Zelenko7855e772018-04-03 00:11:50 +00003121 auto *New = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003122 Types.push_back(New);
3123 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00003124 return QualType(New, 0);
3125}
3126
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00003127/// getMemberPointerType - Return the uniqued reference to the type for a
3128/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00003129QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00003130 // Unique pointers, to guarantee there is only one pointer of a particular
3131 // structure.
3132 llvm::FoldingSetNodeID ID;
3133 MemberPointerType::Profile(ID, T, Cls);
3134
Craig Topper36250ad2014-05-12 05:36:57 +00003135 void *InsertPos = nullptr;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00003136 if (MemberPointerType *PT =
3137 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3138 return QualType(PT, 0);
3139
3140 // If the pointee or class type isn't canonical, this won't be a canonical
3141 // type either, so fill in the canonical type field.
3142 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00003143 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00003144 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
3145
3146 // Get the new insert position for the node we care about.
3147 MemberPointerType *NewIP =
3148 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003149 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00003150 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00003151 auto *New = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00003152 Types.push_back(New);
3153 MemberPointerTypes.InsertNode(New, InsertPos);
3154 return QualType(New, 0);
3155}
3156
Mike Stump11289f42009-09-09 15:08:12 +00003157/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00003158/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00003159QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00003160 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00003161 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00003162 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00003163 assert((EltTy->isDependentType() ||
3164 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00003165 "Constant array of VLAs is illegal!");
3166
Chris Lattnere2df3f92009-05-13 04:12:56 +00003167 // Convert the array size into a canonical width matching the pointer size for
3168 // the target.
3169 llvm::APInt ArySize(ArySizeIn);
Konstantin Zhuravlyov9c1e3102017-03-21 18:55:39 +00003170 ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth());
Mike Stump11289f42009-09-09 15:08:12 +00003171
Chris Lattner23b7eb62007-06-15 23:05:46 +00003172 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00003173 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00003174
Craig Topper36250ad2014-05-12 05:36:57 +00003175 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003176 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00003177 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003178 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003179
John McCall33ddac02011-01-19 10:06:00 +00003180 // If the element type isn't canonical or has qualifiers, this won't
3181 // be a canonical type either, so fill in the canonical type field.
3182 QualType Canon;
3183 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
3184 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00003185 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00003186 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00003187 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00003188
Chris Lattner36f8e652007-01-27 08:31:04 +00003189 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00003190 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00003191 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003192 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00003193 }
Mike Stump11289f42009-09-09 15:08:12 +00003194
Eugene Zelenko7855e772018-04-03 00:11:50 +00003195 auto *New = new (*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00003196 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00003197 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00003198 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003199 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00003200}
3201
John McCall06549462011-01-18 08:40:38 +00003202/// getVariableArrayDecayedType - Turns the given type, which may be
3203/// variably-modified, into the corresponding type with all the known
3204/// sizes replaced with [*].
3205QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
3206 // Vastly most common case.
3207 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003208
John McCall06549462011-01-18 08:40:38 +00003209 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003210
John McCall06549462011-01-18 08:40:38 +00003211 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00003212 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00003213 switch (ty->getTypeClass()) {
3214#define TYPE(Class, Base)
3215#define ABSTRACT_TYPE(Class, Base)
3216#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3217#include "clang/AST/TypeNodes.def"
3218 llvm_unreachable("didn't desugar past all non-canonical types?");
3219
3220 // These types should never be variably-modified.
3221 case Type::Builtin:
3222 case Type::Complex:
3223 case Type::Vector:
Erich Keanef702b022018-07-13 19:46:04 +00003224 case Type::DependentVector:
John McCall06549462011-01-18 08:40:38 +00003225 case Type::ExtVector:
3226 case Type::DependentSizedExtVector:
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003227 case Type::DependentAddressSpace:
John McCall06549462011-01-18 08:40:38 +00003228 case Type::ObjCObject:
3229 case Type::ObjCInterface:
3230 case Type::ObjCObjectPointer:
3231 case Type::Record:
3232 case Type::Enum:
3233 case Type::UnresolvedUsing:
3234 case Type::TypeOfExpr:
3235 case Type::TypeOf:
3236 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00003237 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00003238 case Type::DependentName:
3239 case Type::InjectedClassName:
3240 case Type::TemplateSpecialization:
3241 case Type::DependentTemplateSpecialization:
3242 case Type::TemplateTypeParm:
3243 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00003244 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00003245 case Type::DeducedTemplateSpecialization:
John McCall06549462011-01-18 08:40:38 +00003246 case Type::PackExpansion:
3247 llvm_unreachable("type should never be variably-modified");
3248
3249 // These types can be variably-modified but should never need to
3250 // further decay.
3251 case Type::FunctionNoProto:
3252 case Type::FunctionProto:
3253 case Type::BlockPointer:
3254 case Type::MemberPointer:
Xiuli Pan9c14e282016-01-09 12:53:17 +00003255 case Type::Pipe:
John McCall06549462011-01-18 08:40:38 +00003256 return type;
3257
3258 // These types can be variably-modified. All these modifications
3259 // preserve structure except as noted by comments.
3260 // TODO: if we ever care about optimizing VLAs, there are no-op
3261 // optimizations available here.
3262 case Type::Pointer:
3263 result = getPointerType(getVariableArrayDecayedType(
3264 cast<PointerType>(ty)->getPointeeType()));
3265 break;
3266
3267 case Type::LValueReference: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003268 const auto *lv = cast<LValueReferenceType>(ty);
John McCall06549462011-01-18 08:40:38 +00003269 result = getLValueReferenceType(
3270 getVariableArrayDecayedType(lv->getPointeeType()),
3271 lv->isSpelledAsLValue());
3272 break;
3273 }
3274
3275 case Type::RValueReference: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003276 const auto *lv = cast<RValueReferenceType>(ty);
John McCall06549462011-01-18 08:40:38 +00003277 result = getRValueReferenceType(
3278 getVariableArrayDecayedType(lv->getPointeeType()));
3279 break;
3280 }
3281
Eli Friedman0dfb8892011-10-06 23:00:33 +00003282 case Type::Atomic: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003283 const auto *at = cast<AtomicType>(ty);
Eli Friedman0dfb8892011-10-06 23:00:33 +00003284 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
3285 break;
3286 }
3287
John McCall06549462011-01-18 08:40:38 +00003288 case Type::ConstantArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003289 const auto *cat = cast<ConstantArrayType>(ty);
John McCall06549462011-01-18 08:40:38 +00003290 result = getConstantArrayType(
3291 getVariableArrayDecayedType(cat->getElementType()),
3292 cat->getSize(),
3293 cat->getSizeModifier(),
3294 cat->getIndexTypeCVRQualifiers());
3295 break;
3296 }
3297
3298 case Type::DependentSizedArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003299 const auto *dat = cast<DependentSizedArrayType>(ty);
John McCall06549462011-01-18 08:40:38 +00003300 result = getDependentSizedArrayType(
3301 getVariableArrayDecayedType(dat->getElementType()),
3302 dat->getSizeExpr(),
3303 dat->getSizeModifier(),
3304 dat->getIndexTypeCVRQualifiers(),
3305 dat->getBracketsRange());
3306 break;
3307 }
3308
3309 // Turn incomplete types into [*] types.
3310 case Type::IncompleteArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003311 const auto *iat = cast<IncompleteArrayType>(ty);
John McCall06549462011-01-18 08:40:38 +00003312 result = getVariableArrayType(
3313 getVariableArrayDecayedType(iat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00003314 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00003315 ArrayType::Normal,
3316 iat->getIndexTypeCVRQualifiers(),
3317 SourceRange());
3318 break;
3319 }
3320
3321 // Turn VLA types into [*] types.
3322 case Type::VariableArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003323 const auto *vat = cast<VariableArrayType>(ty);
John McCall06549462011-01-18 08:40:38 +00003324 result = getVariableArrayType(
3325 getVariableArrayDecayedType(vat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00003326 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00003327 ArrayType::Star,
3328 vat->getIndexTypeCVRQualifiers(),
3329 vat->getBracketsRange());
3330 break;
3331 }
3332 }
3333
3334 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00003335 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00003336}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003337
Steve Naroffcadebd02007-08-30 18:14:25 +00003338/// getVariableArrayType - Returns a non-unique reference to the type for a
3339/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00003340QualType ASTContext::getVariableArrayType(QualType EltTy,
3341 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00003342 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00003343 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00003344 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00003345 // Since we don't unique expressions, it isn't possible to unique VLA's
3346 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00003347 QualType Canon;
Fangrui Song6907ce22018-07-30 19:24:48 +00003348
John McCall33ddac02011-01-19 10:06:00 +00003349 // Be sure to pull qualifiers off the element type.
3350 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
3351 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00003352 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00003353 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00003354 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00003355 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003356
Eugene Zelenko7855e772018-04-03 00:11:50 +00003357 auto *New = new (*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00003358 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00003359
3360 VariableArrayTypes.push_back(New);
3361 Types.push_back(New);
3362 return QualType(New, 0);
3363}
3364
Douglas Gregor4619e432008-12-05 23:32:09 +00003365/// getDependentSizedArrayType - Returns a non-unique reference to
3366/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00003367/// type.
John McCall33ddac02011-01-19 10:06:00 +00003368QualType ASTContext::getDependentSizedArrayType(QualType elementType,
3369 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00003370 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00003371 unsigned elementTypeQuals,
3372 SourceRange brackets) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00003373 assert((!numElements || numElements->isTypeDependent() ||
John McCall33ddac02011-01-19 10:06:00 +00003374 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00003375 "Size must be type- or value-dependent!");
3376
John McCall33ddac02011-01-19 10:06:00 +00003377 // Dependently-sized array types that do not have a specified number
3378 // of elements will have their sizes deduced from a dependent
3379 // initializer. We do no canonicalization here at all, which is okay
3380 // because they can't be used in most locations.
3381 if (!numElements) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003382 auto *newType
John McCall33ddac02011-01-19 10:06:00 +00003383 = new (*this, TypeAlignment)
3384 DependentSizedArrayType(*this, elementType, QualType(),
3385 numElements, ASM, elementTypeQuals,
3386 brackets);
3387 Types.push_back(newType);
3388 return QualType(newType, 0);
3389 }
3390
3391 // Otherwise, we actually build a new type every time, but we
3392 // also build a canonical type.
3393
3394 SplitQualType canonElementType = getCanonicalType(elementType).split();
3395
Craig Topper36250ad2014-05-12 05:36:57 +00003396 void *insertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00003397 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00003398 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00003399 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00003400 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00003401
John McCall33ddac02011-01-19 10:06:00 +00003402 // Look for an existing type with these properties.
3403 DependentSizedArrayType *canonTy =
3404 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00003405
John McCall33ddac02011-01-19 10:06:00 +00003406 // If we don't have one, build one.
3407 if (!canonTy) {
3408 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00003409 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00003410 QualType(), numElements, ASM, elementTypeQuals,
3411 brackets);
3412 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
3413 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00003414 }
3415
John McCall33ddac02011-01-19 10:06:00 +00003416 // Apply qualifiers from the element type to the array.
3417 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00003418 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00003419
David Majnemer16a74702015-07-24 05:54:19 +00003420 // If we didn't need extra canonicalization for the element type or the size
3421 // expression, then just use that as our result.
3422 if (QualType(canonElementType.Ty, 0) == elementType &&
3423 canonTy->getSizeExpr() == numElements)
John McCall33ddac02011-01-19 10:06:00 +00003424 return canon;
3425
3426 // Otherwise, we need to build a type which follows the spelling
3427 // of the element type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00003428 auto *sugaredType
John McCall33ddac02011-01-19 10:06:00 +00003429 = new (*this, TypeAlignment)
3430 DependentSizedArrayType(*this, elementType, canon, numElements,
3431 ASM, elementTypeQuals, brackets);
3432 Types.push_back(sugaredType);
3433 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00003434}
3435
John McCall33ddac02011-01-19 10:06:00 +00003436QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00003437 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00003438 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00003439 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00003440 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00003441
Craig Topper36250ad2014-05-12 05:36:57 +00003442 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00003443 if (IncompleteArrayType *iat =
3444 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
3445 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00003446
3447 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00003448 // either, so fill in the canonical type field. We also have to pull
3449 // qualifiers off the element type.
3450 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00003451
John McCall33ddac02011-01-19 10:06:00 +00003452 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
3453 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00003454 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00003455 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00003456 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00003457
3458 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00003459 IncompleteArrayType *existing =
3460 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
3461 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00003462 }
Eli Friedmanbd258282008-02-15 18:16:39 +00003463
Eugene Zelenko7855e772018-04-03 00:11:50 +00003464 auto *newType = new (*this, TypeAlignment)
John McCall33ddac02011-01-19 10:06:00 +00003465 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00003466
John McCall33ddac02011-01-19 10:06:00 +00003467 IncompleteArrayTypes.InsertNode(newType, insertPos);
3468 Types.push_back(newType);
3469 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00003470}
3471
Steve Naroff91fcddb2007-07-18 18:00:27 +00003472/// getVectorType - Return the unique reference to a vector type of
3473/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00003474QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00003475 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00003476 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00003477
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003478 // Check if we've already instantiated a vector of this type.
3479 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00003480 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00003481
Craig Topper36250ad2014-05-12 05:36:57 +00003482 void *InsertPos = nullptr;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003483 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3484 return QualType(VTP, 0);
3485
3486 // If the element type isn't canonical, this won't be a canonical type either,
3487 // so fill in the canonical type field.
3488 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00003489 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00003490 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00003491
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003492 // Get the new insert position for the node we care about.
3493 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003494 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003495 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00003496 auto *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00003497 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003498 VectorTypes.InsertNode(New, InsertPos);
3499 Types.push_back(New);
3500 return QualType(New, 0);
3501}
3502
Erich Keanef702b022018-07-13 19:46:04 +00003503QualType
3504ASTContext::getDependentVectorType(QualType VecType, Expr *SizeExpr,
3505 SourceLocation AttrLoc,
3506 VectorType::VectorKind VecKind) const {
3507 llvm::FoldingSetNodeID ID;
3508 DependentVectorType::Profile(ID, *this, getCanonicalType(VecType), SizeExpr,
3509 VecKind);
3510 void *InsertPos = nullptr;
3511 DependentVectorType *Canon =
3512 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3513 DependentVectorType *New;
3514
3515 if (Canon) {
3516 New = new (*this, TypeAlignment) DependentVectorType(
3517 *this, VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind);
3518 } else {
3519 QualType CanonVecTy = getCanonicalType(VecType);
3520 if (CanonVecTy == VecType) {
3521 New = new (*this, TypeAlignment) DependentVectorType(
3522 *this, VecType, QualType(), SizeExpr, AttrLoc, VecKind);
3523
3524 DependentVectorType *CanonCheck =
3525 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3526 assert(!CanonCheck &&
3527 "Dependent-sized vector_size canonical type broken");
3528 (void)CanonCheck;
3529 DependentVectorTypes.InsertNode(New, InsertPos);
3530 } else {
3531 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
3532 SourceLocation());
3533 New = new (*this, TypeAlignment) DependentVectorType(
3534 *this, VecType, Canon, SizeExpr, AttrLoc, VecKind);
3535 }
3536 }
3537
3538 Types.push_back(New);
3539 return QualType(New, 0);
3540}
3541
Nate Begemance4d7fc2008-04-18 23:10:10 +00003542/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00003543/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00003544QualType
3545ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00003546 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00003547
Steve Naroff91fcddb2007-07-18 18:00:27 +00003548 // Check if we've already instantiated a vector of this type.
3549 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00003550 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00003551 VectorType::GenericVector);
Craig Topper36250ad2014-05-12 05:36:57 +00003552 void *InsertPos = nullptr;
Steve Naroff91fcddb2007-07-18 18:00:27 +00003553 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3554 return QualType(VTP, 0);
3555
3556 // If the element type isn't canonical, this won't be a canonical type either,
3557 // so fill in the canonical type field.
3558 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00003559 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00003560 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00003561
Steve Naroff91fcddb2007-07-18 18:00:27 +00003562 // Get the new insert position for the node we care about.
3563 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003564 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00003565 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00003566 auto *New = new (*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00003567 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00003568 VectorTypes.InsertNode(New, InsertPos);
3569 Types.push_back(New);
3570 return QualType(New, 0);
3571}
3572
Jay Foad39c79802011-01-12 09:06:06 +00003573QualType
3574ASTContext::getDependentSizedExtVectorType(QualType vecType,
3575 Expr *SizeExpr,
3576 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00003577 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00003578 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00003579 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003580
Craig Topper36250ad2014-05-12 05:36:57 +00003581 void *InsertPos = nullptr;
Douglas Gregor352169a2009-07-31 03:54:25 +00003582 DependentSizedExtVectorType *Canon
3583 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3584 DependentSizedExtVectorType *New;
3585 if (Canon) {
3586 // We already have a canonical version of this array type; use it as
3587 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00003588 New = new (*this, TypeAlignment)
3589 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
3590 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00003591 } else {
3592 QualType CanonVecTy = getCanonicalType(vecType);
3593 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00003594 New = new (*this, TypeAlignment)
3595 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
3596 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003597
3598 DependentSizedExtVectorType *CanonCheck
3599 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3600 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
3601 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00003602 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
3603 } else {
3604 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
3605 SourceLocation());
Fangrui Song6907ce22018-07-30 19:24:48 +00003606 New = new (*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00003607 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00003608 }
3609 }
Mike Stump11289f42009-09-09 15:08:12 +00003610
Douglas Gregor758a8692009-06-17 21:51:59 +00003611 Types.push_back(New);
3612 return QualType(New, 0);
3613}
3614
Fangrui Song6907ce22018-07-30 19:24:48 +00003615QualType ASTContext::getDependentAddressSpaceType(QualType PointeeType,
3616 Expr *AddrSpaceExpr,
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003617 SourceLocation AttrLoc) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00003618 assert(AddrSpaceExpr->isInstantiationDependent());
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003619
3620 QualType canonPointeeType = getCanonicalType(PointeeType);
3621
3622 void *insertPos = nullptr;
3623 llvm::FoldingSetNodeID ID;
3624 DependentAddressSpaceType::Profile(ID, *this, canonPointeeType,
3625 AddrSpaceExpr);
3626
3627 DependentAddressSpaceType *canonTy =
3628 DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos);
3629
3630 if (!canonTy) {
3631 canonTy = new (*this, TypeAlignment)
Fangrui Song6907ce22018-07-30 19:24:48 +00003632 DependentAddressSpaceType(*this, canonPointeeType,
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003633 QualType(), AddrSpaceExpr, AttrLoc);
3634 DependentAddressSpaceTypes.InsertNode(canonTy, insertPos);
3635 Types.push_back(canonTy);
3636 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003637
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003638 if (canonPointeeType == PointeeType &&
3639 canonTy->getAddrSpaceExpr() == AddrSpaceExpr)
Fangrui Song6907ce22018-07-30 19:24:48 +00003640 return QualType(canonTy, 0);
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003641
Eugene Zelenko7855e772018-04-03 00:11:50 +00003642 auto *sugaredType
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003643 = new (*this, TypeAlignment)
Fangrui Song6907ce22018-07-30 19:24:48 +00003644 DependentAddressSpaceType(*this, PointeeType, QualType(canonTy, 0),
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003645 AddrSpaceExpr, AttrLoc);
3646 Types.push_back(sugaredType);
Fangrui Song6907ce22018-07-30 19:24:48 +00003647 return QualType(sugaredType, 0);
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003648}
3649
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003650/// Determine whether \p T is canonical as the result type of a function.
John McCall18afab72016-03-01 00:49:02 +00003651static bool isCanonicalResultType(QualType T) {
3652 return T.isCanonical() &&
3653 (T.getObjCLifetime() == Qualifiers::OCL_None ||
3654 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
3655}
3656
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003657/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Jay Foad39c79802011-01-12 09:06:06 +00003658QualType
3659ASTContext::getFunctionNoProtoType(QualType ResultTy,
3660 const FunctionType::ExtInfo &Info) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003661 // Unique functions, to guarantee there is only one function of a particular
3662 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00003663 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00003664 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00003665
Craig Topper36250ad2014-05-12 05:36:57 +00003666 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003667 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003668 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003669 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003670
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003671 QualType Canonical;
John McCall18afab72016-03-01 00:49:02 +00003672 if (!isCanonicalResultType(ResultTy)) {
3673 Canonical =
3674 getFunctionNoProtoType(getCanonicalFunctionResultType(ResultTy), Info);
Mike Stump11289f42009-09-09 15:08:12 +00003675
Chris Lattner47955de2007-01-27 08:37:20 +00003676 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003677 FunctionNoProtoType *NewIP =
3678 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003679 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00003680 }
Mike Stump11289f42009-09-09 15:08:12 +00003681
Eugene Zelenko7855e772018-04-03 00:11:50 +00003682 auto *New = new (*this, TypeAlignment)
John McCall18afab72016-03-01 00:49:02 +00003683 FunctionNoProtoType(ResultTy, Canonical, Info);
Chris Lattner47955de2007-01-27 08:37:20 +00003684 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003685 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003686 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003687}
3688
Douglas Gregora602a152015-10-01 20:20:47 +00003689CanQualType
3690ASTContext::getCanonicalFunctionResultType(QualType ResultType) const {
3691 CanQualType CanResultType = getCanonicalType(ResultType);
3692
3693 // Canonical result types do not have ARC lifetime qualifiers.
3694 if (CanResultType.getQualifiers().hasObjCLifetime()) {
3695 Qualifiers Qs = CanResultType.getQualifiers();
3696 Qs.removeObjCLifetime();
3697 return CanQualType::CreateUnsafe(
3698 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
3699 }
3700
3701 return CanResultType;
3702}
3703
Richard Smith3c4f8d22016-10-16 17:54:23 +00003704static bool isCanonicalExceptionSpecification(
3705 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
3706 if (ESI.Type == EST_None)
3707 return true;
3708 if (!NoexceptInType)
3709 return false;
3710
3711 // C++17 onwards: exception specification is part of the type, as a simple
3712 // boolean "can this function type throw".
3713 if (ESI.Type == EST_BasicNoexcept)
3714 return true;
3715
Richard Smitheaf11ad2018-05-03 03:58:32 +00003716 // A noexcept(expr) specification is (possibly) canonical if expr is
3717 // value-dependent.
3718 if (ESI.Type == EST_DependentNoexcept)
3719 return true;
3720
Richard Smith3c4f8d22016-10-16 17:54:23 +00003721 // A dynamic exception specification is canonical if it only contains pack
Richard Smith2a2cda52016-10-18 19:29:18 +00003722 // expansions (so we can't tell whether it's non-throwing) and all its
3723 // contained types are canonical.
Richard Smith3c4f8d22016-10-16 17:54:23 +00003724 if (ESI.Type == EST_Dynamic) {
Richard Smithfda59e52016-10-26 01:05:54 +00003725 bool AnyPackExpansions = false;
3726 for (QualType ET : ESI.Exceptions) {
3727 if (!ET.isCanonical())
Richard Smith3c4f8d22016-10-16 17:54:23 +00003728 return false;
Richard Smithfda59e52016-10-26 01:05:54 +00003729 if (ET->getAs<PackExpansionType>())
3730 AnyPackExpansions = true;
3731 }
3732 return AnyPackExpansions;
Richard Smith3c4f8d22016-10-16 17:54:23 +00003733 }
3734
Richard Smith3c4f8d22016-10-16 17:54:23 +00003735 return false;
3736}
3737
Richard Smith304b1242016-10-18 20:13:25 +00003738QualType ASTContext::getFunctionTypeInternal(
3739 QualType ResultTy, ArrayRef<QualType> ArgArray,
3740 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
Jordan Rose5c382722013-03-08 21:51:21 +00003741 size_t NumArgs = ArgArray.size();
3742
Richard Smith2a2cda52016-10-18 19:29:18 +00003743 // Unique functions, to guarantee there is only one function of a particular
3744 // structure.
3745 llvm::FoldingSetNodeID ID;
3746 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
3747 *this, true);
Richard Smith3c4f8d22016-10-16 17:54:23 +00003748
Richard Smith2a2cda52016-10-18 19:29:18 +00003749 QualType Canonical;
3750 bool Unique = false;
3751
3752 void *InsertPos = nullptr;
3753 if (FunctionProtoType *FPT =
3754 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
3755 QualType Existing = QualType(FPT, 0);
3756
3757 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
3758 // it so long as our exception specification doesn't contain a dependent
Richard Smith304b1242016-10-18 20:13:25 +00003759 // noexcept expression, or we're just looking for a canonical type.
3760 // Otherwise, we're going to need to create a type
Richard Smith2a2cda52016-10-18 19:29:18 +00003761 // sugar node to hold the concrete expression.
Richard Smitheaf11ad2018-05-03 03:58:32 +00003762 if (OnlyWantCanonical || !isComputedNoexcept(EPI.ExceptionSpec.Type) ||
Richard Smith2a2cda52016-10-18 19:29:18 +00003763 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
3764 return Existing;
3765
3766 // We need a new type sugar node for this one, to hold the new noexcept
3767 // expression. We do no canonicalization here, but that's OK since we don't
3768 // expect to see the same noexcept expression much more than once.
3769 Canonical = getCanonicalType(Existing);
3770 Unique = true;
3771 }
3772
Aaron Ballmanc351fba2017-12-04 20:27:34 +00003773 bool NoexceptInType = getLangOpts().CPlusPlus17;
Richard Smith3c4f8d22016-10-16 17:54:23 +00003774 bool IsCanonicalExceptionSpec =
3775 isCanonicalExceptionSpecification(EPI.ExceptionSpec, NoexceptInType);
3776
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003777 // Determine whether the type being created is already canonical or not.
Richard Smith2a2cda52016-10-18 19:29:18 +00003778 bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
Richard Smith3c4f8d22016-10-16 17:54:23 +00003779 isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003780 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003781 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003782 isCanonical = false;
3783
Richard Smith304b1242016-10-18 20:13:25 +00003784 if (OnlyWantCanonical)
3785 assert(isCanonical &&
3786 "given non-canonical parameters constructing canonical type");
3787
Richard Smith2a2cda52016-10-18 19:29:18 +00003788 // If this type isn't canonical, get the canonical version of it if we don't
3789 // already have it. The exception spec is only partially part of the
3790 // canonical type, and only in C++17 onwards.
3791 if (!isCanonical && Canonical.isNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003792 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003793 CanonicalArgs.reserve(NumArgs);
3794 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003795 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003796
Benjamin Kramer3f515cd2016-10-26 12:51:45 +00003797 llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
John McCalldb40c7f2010-12-14 08:05:40 +00003798 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00003799 CanonicalEPI.HasTrailingReturn = false;
Richard Smith3c4f8d22016-10-16 17:54:23 +00003800
3801 if (IsCanonicalExceptionSpec) {
3802 // Exception spec is already OK.
3803 } else if (NoexceptInType) {
3804 switch (EPI.ExceptionSpec.Type) {
3805 case EST_Unparsed: case EST_Unevaluated: case EST_Uninstantiated:
3806 // We don't know yet. It shouldn't matter what we pick here; no-one
3807 // should ever look at this.
3808 LLVM_FALLTHROUGH;
Richard Smitheaf11ad2018-05-03 03:58:32 +00003809 case EST_None: case EST_MSAny: case EST_NoexceptFalse:
Richard Smith3c4f8d22016-10-16 17:54:23 +00003810 CanonicalEPI.ExceptionSpec.Type = EST_None;
3811 break;
3812
Richard Smith2a2cda52016-10-18 19:29:18 +00003813 // A dynamic exception specification is almost always "not noexcept",
3814 // with the exception that a pack expansion might expand to no types.
3815 case EST_Dynamic: {
3816 bool AnyPacks = false;
3817 for (QualType ET : EPI.ExceptionSpec.Exceptions) {
3818 if (ET->getAs<PackExpansionType>())
3819 AnyPacks = true;
3820 ExceptionTypeStorage.push_back(getCanonicalType(ET));
3821 }
3822 if (!AnyPacks)
3823 CanonicalEPI.ExceptionSpec.Type = EST_None;
3824 else {
3825 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
3826 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
3827 }
3828 break;
3829 }
3830
Erich Keaned02f4a12019-05-30 17:31:54 +00003831 case EST_DynamicNone:
3832 case EST_BasicNoexcept:
3833 case EST_NoexceptTrue:
3834 case EST_NoThrow:
Richard Smith3c4f8d22016-10-16 17:54:23 +00003835 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
3836 break;
3837
Richard Smitheaf11ad2018-05-03 03:58:32 +00003838 case EST_DependentNoexcept:
3839 llvm_unreachable("dependent noexcept is already canonical");
Richard Smith3c4f8d22016-10-16 17:54:23 +00003840 }
Richard Smith3c4f8d22016-10-16 17:54:23 +00003841 } else {
3842 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
3843 }
John McCalldb40c7f2010-12-14 08:05:40 +00003844
Douglas Gregora602a152015-10-01 20:20:47 +00003845 // Adjust the canonical function result type.
3846 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
Richard Smith304b1242016-10-18 20:13:25 +00003847 Canonical =
3848 getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003849
Chris Lattnerfd4de792007-01-27 01:15:32 +00003850 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003851 FunctionProtoType *NewIP =
3852 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003853 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003854 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003855
Bruno Ricci26a25362018-10-02 11:46:38 +00003856 // Compute the needed size to hold this FunctionProtoType and the
3857 // various trailing objects.
3858 auto ESH = FunctionProtoType::getExceptionSpecSize(
3859 EPI.ExceptionSpec.Type, EPI.ExceptionSpec.Exceptions.size());
3860 size_t Size = FunctionProtoType::totalSizeToAlloc<
3861 QualType, FunctionType::FunctionTypeExtraBitfields,
3862 FunctionType::ExceptionType, Expr *, FunctionDecl *,
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00003863 FunctionProtoType::ExtParameterInfo, Qualifiers>(
Bruno Ricci26a25362018-10-02 11:46:38 +00003864 NumArgs, FunctionProtoType::hasExtraBitfields(EPI.ExceptionSpec.Type),
3865 ESH.NumExceptionType, ESH.NumExprPtr, ESH.NumFunctionDeclPtr,
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00003866 EPI.ExtParameterInfos ? NumArgs : 0,
3867 EPI.TypeQuals.hasNonFastQualifiers() ? 1 : 0);
John McCall18afab72016-03-01 00:49:02 +00003868
Bruno Ricci26a25362018-10-02 11:46:38 +00003869 auto *FTP = (FunctionProtoType *)Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00003870 FunctionProtoType::ExtProtoInfo newEPI = EPI;
Jordan Rose5c382722013-03-08 21:51:21 +00003871 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003872 Types.push_back(FTP);
Richard Smith2a2cda52016-10-18 19:29:18 +00003873 if (!Unique)
3874 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003875 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003876}
Chris Lattneref51c202006-11-10 07:17:23 +00003877
Joey Goulye3c85de2016-12-01 11:30:49 +00003878QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
Xiuli Pan9c14e282016-01-09 12:53:17 +00003879 llvm::FoldingSetNodeID ID;
Joey Goulye3c85de2016-12-01 11:30:49 +00003880 PipeType::Profile(ID, T, ReadOnly);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003881
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00003882 void *InsertPos = nullptr;
Joey Goulye3c85de2016-12-01 11:30:49 +00003883 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
Xiuli Pan9c14e282016-01-09 12:53:17 +00003884 return QualType(PT, 0);
3885
3886 // If the pipe element type isn't canonical, this won't be a canonical type
3887 // either, so fill in the canonical type field.
3888 QualType Canonical;
3889 if (!T.isCanonical()) {
Joey Goulye3c85de2016-12-01 11:30:49 +00003890 Canonical = getPipeType(getCanonicalType(T), ReadOnly);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003891
3892 // Get the new insert position for the node we care about.
Joey Goulye3c85de2016-12-01 11:30:49 +00003893 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003894 assert(!NewIP && "Shouldn't be in the map!");
3895 (void)NewIP;
3896 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00003897 auto *New = new (*this, TypeAlignment) PipeType(T, Canonical, ReadOnly);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003898 Types.push_back(New);
Joey Goulye3c85de2016-12-01 11:30:49 +00003899 PipeTypes.InsertNode(New, InsertPos);
Joey Gouly5788b782016-11-18 14:10:54 +00003900 return QualType(New, 0);
3901}
3902
Anastasia Stulova59055b92018-05-09 13:23:26 +00003903QualType ASTContext::adjustStringLiteralBaseType(QualType Ty) const {
3904 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
3905 return LangOpts.OpenCL ? getAddrSpaceQualType(Ty, LangAS::opencl_constant)
3906 : Ty;
3907}
3908
Joey Goulye3c85de2016-12-01 11:30:49 +00003909QualType ASTContext::getReadPipeType(QualType T) const {
3910 return getPipeType(T, true);
3911}
3912
Joey Gouly5788b782016-11-18 14:10:54 +00003913QualType ASTContext::getWritePipeType(QualType T) const {
Joey Goulye3c85de2016-12-01 11:30:49 +00003914 return getPipeType(T, false);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003915}
3916
John McCalle78aac42010-03-10 03:28:59 +00003917#ifndef NDEBUG
3918static bool NeedsInjectedClassNameType(const RecordDecl *D) {
3919 if (!isa<CXXRecordDecl>(D)) return false;
Eugene Zelenko7855e772018-04-03 00:11:50 +00003920 const auto *RD = cast<CXXRecordDecl>(D);
John McCalle78aac42010-03-10 03:28:59 +00003921 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
3922 return true;
3923 if (RD->getDescribedClassTemplate() &&
3924 !isa<ClassTemplateSpecializationDecl>(RD))
3925 return true;
3926 return false;
3927}
3928#endif
3929
3930/// getInjectedClassNameType - Return the unique reference to the
3931/// injected class name type for the specified templated declaration.
3932QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00003933 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00003934 assert(NeedsInjectedClassNameType(Decl));
3935 if (Decl->TypeForDecl) {
3936 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00003937 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00003938 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
3939 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3940 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
3941 } else {
John McCall424cec92011-01-19 06:33:43 +00003942 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00003943 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00003944 Decl->TypeForDecl = newType;
3945 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00003946 }
3947 return QualType(Decl->TypeForDecl, 0);
3948}
3949
Douglas Gregor83a586e2008-04-13 21:07:44 +00003950/// getTypeDeclType - Return the unique reference to the type for the
3951/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00003952QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00003953 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00003954 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00003955
Eugene Zelenko7855e772018-04-03 00:11:50 +00003956 if (const auto *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00003957 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00003958
John McCall96f0b5f2010-03-10 06:48:02 +00003959 assert(!isa<TemplateTypeParmDecl>(Decl) &&
3960 "Template type parameter types are always available.");
3961
Eugene Zelenko7855e772018-04-03 00:11:50 +00003962 if (const auto *Record = dyn_cast<RecordDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003963 assert(Record->isFirstDecl() && "struct/union has previous declaration");
John McCall96f0b5f2010-03-10 06:48:02 +00003964 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003965 return getRecordType(Record);
Eugene Zelenko7855e772018-04-03 00:11:50 +00003966 } else if (const auto *Enum = dyn_cast<EnumDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003967 assert(Enum->isFirstDecl() && "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003968 return getEnumType(Enum);
Eugene Zelenko7855e772018-04-03 00:11:50 +00003969 } else if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00003970 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
3971 Decl->TypeForDecl = newType;
3972 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00003973 } else
John McCall96f0b5f2010-03-10 06:48:02 +00003974 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003975
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003976 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00003977}
3978
Chris Lattner32d920b2007-01-26 02:01:53 +00003979/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00003980/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003981QualType
Richard Smithdda56e42011-04-15 14:24:37 +00003982ASTContext::getTypedefType(const TypedefNameDecl *Decl,
3983 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003984 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003985
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003986 if (Canonical.isNull())
3987 Canonical = getCanonicalType(Decl->getUnderlyingType());
Eugene Zelenko7855e772018-04-03 00:11:50 +00003988 auto *newType = new (*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00003989 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00003990 Decl->TypeForDecl = newType;
3991 Types.push_back(newType);
3992 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00003993}
3994
Jay Foad39c79802011-01-12 09:06:06 +00003995QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003996 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3997
Douglas Gregorec9fd132012-01-14 16:38:05 +00003998 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003999 if (PrevDecl->TypeForDecl)
Fangrui Song6907ce22018-07-30 19:24:48 +00004000 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00004001
Eugene Zelenko7855e772018-04-03 00:11:50 +00004002 auto *newType = new (*this, TypeAlignment) RecordType(Decl);
John McCall424cec92011-01-19 06:33:43 +00004003 Decl->TypeForDecl = newType;
4004 Types.push_back(newType);
4005 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00004006}
4007
Jay Foad39c79802011-01-12 09:06:06 +00004008QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00004009 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
4010
Douglas Gregorec9fd132012-01-14 16:38:05 +00004011 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00004012 if (PrevDecl->TypeForDecl)
Fangrui Song6907ce22018-07-30 19:24:48 +00004013 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00004014
Eugene Zelenko7855e772018-04-03 00:11:50 +00004015 auto *newType = new (*this, TypeAlignment) EnumType(Decl);
John McCall424cec92011-01-19 06:33:43 +00004016 Decl->TypeForDecl = newType;
4017 Types.push_back(newType);
4018 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00004019}
4020
Richard Smithe43e2b32018-08-20 21:47:29 +00004021QualType ASTContext::getAttributedType(attr::Kind attrKind,
John McCall81904512011-01-06 01:58:22 +00004022 QualType modifiedType,
4023 QualType equivalentType) {
4024 llvm::FoldingSetNodeID id;
4025 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
4026
Craig Topper36250ad2014-05-12 05:36:57 +00004027 void *insertPos = nullptr;
John McCall81904512011-01-06 01:58:22 +00004028 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
4029 if (type) return QualType(type, 0);
4030
4031 QualType canon = getCanonicalType(equivalentType);
4032 type = new (*this, TypeAlignment)
Leonard Chanc72aaf62019-05-07 03:20:17 +00004033 AttributedType(canon, attrKind, modifiedType, equivalentType);
John McCall81904512011-01-06 01:58:22 +00004034
4035 Types.push_back(type);
4036 AttributedTypes.InsertNode(type, insertPos);
4037
4038 return QualType(type, 0);
4039}
4040
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004041/// Retrieve a substitution-result type.
John McCallcebee162009-10-18 09:09:24 +00004042QualType
4043ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00004044 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00004045 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00004046 && "replacement types must always be canonical");
4047
4048 llvm::FoldingSetNodeID ID;
4049 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00004050 void *InsertPos = nullptr;
John McCallcebee162009-10-18 09:09:24 +00004051 SubstTemplateTypeParmType *SubstParm
4052 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4053
4054 if (!SubstParm) {
4055 SubstParm = new (*this, TypeAlignment)
4056 SubstTemplateTypeParmType(Parm, Replacement);
4057 Types.push_back(SubstParm);
4058 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
4059 }
4060
4061 return QualType(SubstParm, 0);
4062}
4063
Fangrui Song6907ce22018-07-30 19:24:48 +00004064/// Retrieve a
Douglas Gregorada4b792011-01-14 02:55:32 +00004065QualType ASTContext::getSubstTemplateTypeParmPackType(
4066 const TemplateTypeParmType *Parm,
4067 const TemplateArgument &ArgPack) {
4068#ifndef NDEBUG
Aaron Ballman2a89e852014-07-15 21:32:31 +00004069 for (const auto &P : ArgPack.pack_elements()) {
4070 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
4071 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
Douglas Gregorada4b792011-01-14 02:55:32 +00004072 }
4073#endif
Fangrui Song6907ce22018-07-30 19:24:48 +00004074
Douglas Gregorada4b792011-01-14 02:55:32 +00004075 llvm::FoldingSetNodeID ID;
4076 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00004077 void *InsertPos = nullptr;
Douglas Gregorada4b792011-01-14 02:55:32 +00004078 if (SubstTemplateTypeParmPackType *SubstParm
4079 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
4080 return QualType(SubstParm, 0);
Fangrui Song6907ce22018-07-30 19:24:48 +00004081
Douglas Gregorada4b792011-01-14 02:55:32 +00004082 QualType Canon;
4083 if (!Parm->isCanonicalUnqualified()) {
4084 Canon = getCanonicalType(QualType(Parm, 0));
4085 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
4086 ArgPack);
4087 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
4088 }
4089
Eugene Zelenko7855e772018-04-03 00:11:50 +00004090 auto *SubstParm
Douglas Gregorada4b792011-01-14 02:55:32 +00004091 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
4092 ArgPack);
4093 Types.push_back(SubstParm);
George Burgess IVb5fe8552017-06-12 17:44:30 +00004094 SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos);
Fangrui Song6907ce22018-07-30 19:24:48 +00004095 return QualType(SubstParm, 0);
Douglas Gregorada4b792011-01-14 02:55:32 +00004096}
4097
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004098/// Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00004099/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00004100/// name.
Mike Stump11289f42009-09-09 15:08:12 +00004101QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00004102 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00004103 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00004104 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00004105 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Craig Topper36250ad2014-05-12 05:36:57 +00004106 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004107 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00004108 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4109
4110 if (TypeParm)
4111 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004112
Chandler Carruth08836322011-05-01 00:51:33 +00004113 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00004114 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00004115 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004116
Fangrui Song6907ce22018-07-30 19:24:48 +00004117 TemplateTypeParmType *TypeCheck
Douglas Gregorc42075a2010-02-04 18:10:26 +00004118 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4119 assert(!TypeCheck && "Template type parameter canonical type broken");
4120 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00004121 } else
John McCall90d1c2d2009-09-24 23:30:46 +00004122 TypeParm = new (*this, TypeAlignment)
4123 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00004124
4125 Types.push_back(TypeParm);
4126 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
4127
4128 return QualType(TypeParm, 0);
4129}
4130
John McCalle78aac42010-03-10 03:28:59 +00004131TypeSourceInfo *
4132ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
4133 SourceLocation NameLoc,
4134 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00004135 QualType Underlying) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00004136 assert(!Name.getAsDependentTemplateName() &&
Douglas Gregore16af532011-02-28 18:50:33 +00004137 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00004138 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00004139
4140 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie6adc78e2013-02-18 22:06:02 +00004141 TemplateSpecializationTypeLoc TL =
4142 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara48c05be2012-02-06 14:41:24 +00004143 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00004144 TL.setTemplateNameLoc(NameLoc);
4145 TL.setLAngleLoc(Args.getLAngleLoc());
4146 TL.setRAngleLoc(Args.getRAngleLoc());
4147 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
4148 TL.setArgLocInfo(i, Args[i].getLocInfo());
4149 return DI;
4150}
4151
Mike Stump11289f42009-09-09 15:08:12 +00004152QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00004153ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00004154 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00004155 QualType Underlying) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00004156 assert(!Template.getAsDependentTemplateName() &&
Douglas Gregore16af532011-02-28 18:50:33 +00004157 "No dependent template names here!");
John McCall6b51f282009-11-23 01:53:49 +00004158
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004159 SmallVector<TemplateArgument, 4> ArgVec;
David Majnemer6fbeee32016-07-07 04:43:07 +00004160 ArgVec.reserve(Args.size());
4161 for (const TemplateArgumentLoc &Arg : Args.arguments())
4162 ArgVec.push_back(Arg.getArgument());
John McCall0ad16662009-10-29 08:12:44 +00004163
David Majnemer6fbeee32016-07-07 04:43:07 +00004164 return getTemplateSpecializationType(Template, ArgVec, Underlying);
John McCall0ad16662009-10-29 08:12:44 +00004165}
4166
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004167#ifndef NDEBUG
David Majnemer6fbeee32016-07-07 04:43:07 +00004168static bool hasAnyPackExpansions(ArrayRef<TemplateArgument> Args) {
4169 for (const TemplateArgument &Arg : Args)
4170 if (Arg.isPackExpansion())
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004171 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00004172
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004173 return true;
4174}
4175#endif
4176
John McCall0ad16662009-10-29 08:12:44 +00004177QualType
4178ASTContext::getTemplateSpecializationType(TemplateName Template,
David Majnemer6fbeee32016-07-07 04:43:07 +00004179 ArrayRef<TemplateArgument> Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00004180 QualType Underlying) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00004181 assert(!Template.getAsDependentTemplateName() &&
Douglas Gregore16af532011-02-28 18:50:33 +00004182 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00004183 // Look through qualified template names.
4184 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
4185 Template = TemplateName(QTN->getTemplateDecl());
Fangrui Song6907ce22018-07-30 19:24:48 +00004186
4187 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00004188 Template.getAsTemplateDecl() &&
4189 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00004190 QualType CanonType;
4191 if (!Underlying.isNull())
4192 CanonType = getCanonicalType(Underlying);
4193 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004194 // We can get here with an alias template when the specialization contains
4195 // a pack expansion that does not match up with a parameter pack.
David Majnemer6fbeee32016-07-07 04:43:07 +00004196 assert((!IsTypeAlias || hasAnyPackExpansions(Args)) &&
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004197 "Caller must compute aliased type");
4198 IsTypeAlias = false;
David Majnemer6fbeee32016-07-07 04:43:07 +00004199 CanonType = getCanonicalTemplateSpecializationType(Template, Args);
Richard Smith3f1b5d02011-05-05 21:57:07 +00004200 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00004201
Douglas Gregora8e02e72009-07-28 23:00:59 +00004202 // Allocate the (non-canonical) template specialization type, but don't
4203 // try to unique it: these types typically have location information that
4204 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00004205 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
David Majnemer6fbeee32016-07-07 04:43:07 +00004206 sizeof(TemplateArgument) * Args.size() +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004207 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00004208 TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004209 auto *Spec
David Majnemer6fbeee32016-07-07 04:43:07 +00004210 = new (Mem) TemplateSpecializationType(Template, Args, CanonType,
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004211 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00004212
Douglas Gregor8bf42052009-02-09 18:46:07 +00004213 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00004214 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00004215}
4216
David Majnemer6fbeee32016-07-07 04:43:07 +00004217QualType ASTContext::getCanonicalTemplateSpecializationType(
4218 TemplateName Template, ArrayRef<TemplateArgument> Args) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00004219 assert(!Template.getAsDependentTemplateName() &&
Douglas Gregore16af532011-02-28 18:50:33 +00004220 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00004221
Douglas Gregore29139c2011-03-03 17:04:51 +00004222 // Look through qualified template names.
4223 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
4224 Template = TemplateName(QTN->getTemplateDecl());
Fangrui Song6907ce22018-07-30 19:24:48 +00004225
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004226 // Build the canonical template specialization type.
4227 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004228 SmallVector<TemplateArgument, 4> CanonArgs;
David Majnemer6fbeee32016-07-07 04:43:07 +00004229 unsigned NumArgs = Args.size();
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004230 CanonArgs.reserve(NumArgs);
David Majnemer6fbeee32016-07-07 04:43:07 +00004231 for (const TemplateArgument &Arg : Args)
4232 CanonArgs.push_back(getCanonicalTemplateArgument(Arg));
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004233
4234 // Determine whether this canonical template specialization type already
4235 // exists.
4236 llvm::FoldingSetNodeID ID;
4237 TemplateSpecializationType::Profile(ID, CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00004238 CanonArgs, *this);
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004239
Craig Topper36250ad2014-05-12 05:36:57 +00004240 void *InsertPos = nullptr;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004241 TemplateSpecializationType *Spec
4242 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
4243
4244 if (!Spec) {
4245 // Allocate a new canonical template specialization type.
4246 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
4247 sizeof(TemplateArgument) * NumArgs),
4248 TypeAlignment);
4249 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00004250 CanonArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00004251 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004252 Types.push_back(Spec);
4253 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
4254 }
4255
4256 assert(Spec->isDependentType() &&
4257 "Non-dependent template-id type must have a canonical type");
4258 return QualType(Spec, 0);
4259}
4260
Joel E. Denny7509a2f2018-05-14 19:36:45 +00004261QualType ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
4262 NestedNameSpecifier *NNS,
4263 QualType NamedType,
4264 TagDecl *OwnedTagDecl) const {
Douglas Gregor52537682009-03-19 00:18:19 +00004265 llvm::FoldingSetNodeID ID;
Joel E. Denny7509a2f2018-05-14 19:36:45 +00004266 ElaboratedType::Profile(ID, Keyword, NNS, NamedType, OwnedTagDecl);
Douglas Gregor52537682009-03-19 00:18:19 +00004267
Craig Topper36250ad2014-05-12 05:36:57 +00004268 void *InsertPos = nullptr;
Abramo Bagnara6150c882010-05-11 21:36:43 +00004269 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00004270 if (T)
4271 return QualType(T, 0);
4272
Douglas Gregorc42075a2010-02-04 18:10:26 +00004273 QualType Canon = NamedType;
4274 if (!Canon.isCanonical()) {
4275 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00004276 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
4277 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00004278 (void)CheckT;
4279 }
4280
Bruno Riccid6bd5982018-08-16 10:48:16 +00004281 void *Mem = Allocate(ElaboratedType::totalSizeToAlloc<TagDecl *>(!!OwnedTagDecl),
4282 TypeAlignment);
4283 T = new (Mem) ElaboratedType(Keyword, NNS, NamedType, Canon, OwnedTagDecl);
4284
Douglas Gregor52537682009-03-19 00:18:19 +00004285 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00004286 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00004287 return QualType(T, 0);
4288}
4289
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004290QualType
Jay Foad39c79802011-01-12 09:06:06 +00004291ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004292 llvm::FoldingSetNodeID ID;
4293 ParenType::Profile(ID, InnerType);
4294
Craig Topper36250ad2014-05-12 05:36:57 +00004295 void *InsertPos = nullptr;
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004296 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
4297 if (T)
4298 return QualType(T, 0);
4299
4300 QualType Canon = InnerType;
4301 if (!Canon.isCanonical()) {
4302 Canon = getCanonicalType(InnerType);
4303 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
4304 assert(!CheckT && "Paren canonical type broken");
4305 (void)CheckT;
4306 }
4307
Benjamin Kramer8adeef92015-04-02 16:19:54 +00004308 T = new (*this, TypeAlignment) ParenType(InnerType, Canon);
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004309 Types.push_back(T);
4310 ParenTypes.InsertNode(T, InsertPos);
4311 return QualType(T, 0);
4312}
4313
Leonard Chanc72aaf62019-05-07 03:20:17 +00004314QualType
4315ASTContext::getMacroQualifiedType(QualType UnderlyingTy,
4316 const IdentifierInfo *MacroII) const {
4317 QualType Canon = UnderlyingTy;
4318 if (!Canon.isCanonical())
4319 Canon = getCanonicalType(UnderlyingTy);
4320
4321 auto *newType = new (*this, TypeAlignment)
4322 MacroQualifiedType(UnderlyingTy, Canon, MacroII);
4323 Types.push_back(newType);
4324 return QualType(newType, 0);
4325}
4326
Douglas Gregor02085352010-03-31 20:19:30 +00004327QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
4328 NestedNameSpecifier *NNS,
4329 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00004330 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00004331 if (Canon.isNull()) {
4332 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Richard Smith74f02342017-01-19 21:00:13 +00004333 if (CanonNNS != NNS)
4334 Canon = getDependentNameType(Keyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00004335 }
4336
4337 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00004338 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00004339
Craig Topper36250ad2014-05-12 05:36:57 +00004340 void *InsertPos = nullptr;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00004341 DependentNameType *T
4342 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00004343 if (T)
4344 return QualType(T, 0);
4345
Benjamin Kramer8adeef92015-04-02 16:19:54 +00004346 T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00004347 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00004348 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00004349 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00004350}
4351
Mike Stump11289f42009-09-09 15:08:12 +00004352QualType
John McCallc392f372010-06-11 00:33:02 +00004353ASTContext::getDependentTemplateSpecializationType(
4354 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00004355 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00004356 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00004357 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00004358 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004359 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00004360 for (unsigned I = 0, E = Args.size(); I != E; ++I)
4361 ArgCopy.push_back(Args[I].getArgument());
David Majnemer6fbeee32016-07-07 04:43:07 +00004362 return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy);
John McCallc392f372010-06-11 00:33:02 +00004363}
4364
4365QualType
4366ASTContext::getDependentTemplateSpecializationType(
4367 ElaboratedTypeKeyword Keyword,
4368 NestedNameSpecifier *NNS,
4369 const IdentifierInfo *Name,
David Majnemer6fbeee32016-07-07 04:43:07 +00004370 ArrayRef<TemplateArgument> Args) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00004371 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor6e068012011-02-28 00:04:36 +00004372 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00004373
Douglas Gregorc42075a2010-02-04 18:10:26 +00004374 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00004375 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00004376 Name, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004377
Craig Topper36250ad2014-05-12 05:36:57 +00004378 void *InsertPos = nullptr;
John McCallc392f372010-06-11 00:33:02 +00004379 DependentTemplateSpecializationType *T
4380 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004381 if (T)
4382 return QualType(T, 0);
4383
John McCallc392f372010-06-11 00:33:02 +00004384 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004385
John McCallc392f372010-06-11 00:33:02 +00004386 ElaboratedTypeKeyword CanonKeyword = Keyword;
4387 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
4388
4389 bool AnyNonCanonArgs = false;
David Majnemer6fbeee32016-07-07 04:43:07 +00004390 unsigned NumArgs = Args.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004391 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00004392 for (unsigned I = 0; I != NumArgs; ++I) {
4393 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
4394 if (!CanonArgs[I].structurallyEquals(Args[I]))
4395 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00004396 }
4397
John McCallc392f372010-06-11 00:33:02 +00004398 QualType Canon;
4399 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
4400 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00004401 Name,
4402 CanonArgs);
John McCallc392f372010-06-11 00:33:02 +00004403
4404 // Find the insert position again.
4405 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
4406 }
4407
4408 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
4409 sizeof(TemplateArgument) * NumArgs),
4410 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00004411 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00004412 Name, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00004413 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00004414 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00004415 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00004416}
4417
Richard Smith32918772017-02-14 00:25:28 +00004418TemplateArgument ASTContext::getInjectedTemplateArg(NamedDecl *Param) {
4419 TemplateArgument Arg;
Eugene Zelenko7855e772018-04-03 00:11:50 +00004420 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
Richard Smith32918772017-02-14 00:25:28 +00004421 QualType ArgType = getTypeDeclType(TTP);
4422 if (TTP->isParameterPack())
4423 ArgType = getPackExpansionType(ArgType, None);
4424
4425 Arg = TemplateArgument(ArgType);
4426 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4427 Expr *E = new (*this) DeclRefExpr(
Bruno Ricci5fc4db72018-12-21 14:10:18 +00004428 *this, NTTP, /*enclosing*/ false,
Richard Smith32918772017-02-14 00:25:28 +00004429 NTTP->getType().getNonLValueExprType(*this),
4430 Expr::getValueKindForType(NTTP->getType()), NTTP->getLocation());
4431
4432 if (NTTP->isParameterPack())
4433 E = new (*this) PackExpansionExpr(DependentTy, E, NTTP->getLocation(),
4434 None);
4435 Arg = TemplateArgument(E);
4436 } else {
4437 auto *TTP = cast<TemplateTemplateParmDecl>(Param);
4438 if (TTP->isParameterPack())
4439 Arg = TemplateArgument(TemplateName(TTP), Optional<unsigned>());
4440 else
4441 Arg = TemplateArgument(TemplateName(TTP));
4442 }
4443
4444 if (Param->isTemplateParameterPack())
4445 Arg = TemplateArgument::CreatePackCopy(*this, Arg);
4446
4447 return Arg;
4448}
4449
Richard Smith43e14d22016-12-23 02:10:11 +00004450void
4451ASTContext::getInjectedTemplateArgs(const TemplateParameterList *Params,
4452 SmallVectorImpl<TemplateArgument> &Args) {
4453 Args.reserve(Args.size() + Params->size());
4454
Richard Smith32918772017-02-14 00:25:28 +00004455 for (NamedDecl *Param : *Params)
4456 Args.push_back(getInjectedTemplateArg(Param));
Richard Smith43e14d22016-12-23 02:10:11 +00004457}
4458
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00004459QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikie05785d12013-02-20 22:23:23 +00004460 Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00004461 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00004462 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00004463
Richard Smithb2997f52019-05-21 20:10:50 +00004464 // A deduced type can deduce to a pack, eg
4465 // auto ...x = some_pack;
4466 // That declaration isn't (yet) valid, but is created as part of building an
4467 // init-capture pack:
4468 // [...x = some_pack] {}
4469 assert((Pattern->containsUnexpandedParameterPack() ||
4470 Pattern->getContainedDeducedType()) &&
Douglas Gregord2fa7662010-12-20 02:24:11 +00004471 "Pack expansions must expand one or more parameter packs");
Craig Topper36250ad2014-05-12 05:36:57 +00004472 void *InsertPos = nullptr;
Douglas Gregord2fa7662010-12-20 02:24:11 +00004473 PackExpansionType *T
4474 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
4475 if (T)
4476 return QualType(T, 0);
4477
4478 QualType Canon;
4479 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00004480 Canon = getCanonicalType(Pattern);
4481 // The canonical type might not contain an unexpanded parameter pack, if it
4482 // contains an alias template specialization which ignores one of its
4483 // parameters.
4484 if (Canon->containsUnexpandedParameterPack()) {
Richard Smith8b4e1e22014-07-10 01:20:17 +00004485 Canon = getPackExpansionType(Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00004486
Richard Smith68eea502012-07-16 00:20:35 +00004487 // Find the insert position again, in case we inserted an element into
4488 // PackExpansionTypes and invalidated our insert position.
4489 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
4490 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00004491 }
4492
Benjamin Kramer8adeef92015-04-02 16:19:54 +00004493 T = new (*this, TypeAlignment)
4494 PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00004495 Types.push_back(T);
4496 PackExpansionTypes.InsertNode(T, InsertPos);
Richard Smith8b4e1e22014-07-10 01:20:17 +00004497 return QualType(T, 0);
Douglas Gregord2fa7662010-12-20 02:24:11 +00004498}
4499
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004500/// CmpProtocolNames - Comparison predicate for sorting protocols
4501/// alphabetically.
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00004502static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
4503 ObjCProtocolDecl *const *RHS) {
4504 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004505}
4506
Craig Topper1f26d5b2016-01-03 19:43:23 +00004507static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) {
4508 if (Protocols.empty()) return true;
John McCallfc93cf92009-10-22 22:37:11 +00004509
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00004510 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
4511 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00004512
Craig Topper1f26d5b2016-01-03 19:43:23 +00004513 for (unsigned i = 1; i != Protocols.size(); ++i)
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00004514 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00004515 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00004516 return false;
4517 return true;
4518}
4519
Craig Topper6a8c1512015-10-22 01:56:18 +00004520static void
4521SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) {
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004522 // Sort protocols, keyed by name.
Craig Topper6a8c1512015-10-22 01:56:18 +00004523 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004524
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00004525 // Canonicalize.
Craig Topper6a8c1512015-10-22 01:56:18 +00004526 for (ObjCProtocolDecl *&P : Protocols)
4527 P = P->getCanonicalDecl();
4528
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004529 // Remove duplicates.
Craig Topper6a8c1512015-10-22 01:56:18 +00004530 auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end());
4531 Protocols.erase(ProtocolsEnd, Protocols.end());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004532}
4533
John McCall8b07ec22010-05-15 11:32:37 +00004534QualType ASTContext::getObjCObjectType(QualType BaseType,
4535 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00004536 unsigned NumProtocols) const {
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004537 return getObjCObjectType(BaseType, {},
Douglas Gregorab209d82015-07-07 03:58:42 +00004538 llvm::makeArrayRef(Protocols, NumProtocols),
4539 /*isKindOf=*/false);
Douglas Gregore9d95f12015-07-07 03:57:35 +00004540}
4541
4542QualType ASTContext::getObjCObjectType(
4543 QualType baseType,
4544 ArrayRef<QualType> typeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00004545 ArrayRef<ObjCProtocolDecl *> protocols,
4546 bool isKindOf) const {
Douglas Gregore9d95f12015-07-07 03:57:35 +00004547 // If the base type is an interface and there aren't any protocols or
4548 // type arguments to add, then the interface type will do just fine.
Douglas Gregorab209d82015-07-07 03:58:42 +00004549 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
4550 isa<ObjCInterfaceType>(baseType))
Douglas Gregore9d95f12015-07-07 03:57:35 +00004551 return baseType;
John McCall8b07ec22010-05-15 11:32:37 +00004552
4553 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00004554 llvm::FoldingSetNodeID ID;
Douglas Gregorab209d82015-07-07 03:58:42 +00004555 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
Craig Topper36250ad2014-05-12 05:36:57 +00004556 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00004557 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
4558 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00004559
Douglas Gregore9d95f12015-07-07 03:57:35 +00004560 // Determine the type arguments to be used for canonicalization,
4561 // which may be explicitly specified here or written on the base
4562 // type.
4563 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
4564 if (effectiveTypeArgs.empty()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00004565 if (const auto *baseObject = baseType->getAs<ObjCObjectType>())
Douglas Gregore9d95f12015-07-07 03:57:35 +00004566 effectiveTypeArgs = baseObject->getTypeArgs();
4567 }
John McCallfc93cf92009-10-22 22:37:11 +00004568
Douglas Gregore9d95f12015-07-07 03:57:35 +00004569 // Build the canonical type, which has the canonical base type and a
4570 // sorted-and-uniqued list of protocols and the type arguments
4571 // canonicalized.
4572 QualType canonical;
4573 bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(),
4574 effectiveTypeArgs.end(),
4575 [&](QualType type) {
4576 return type.isCanonical();
4577 });
Craig Topper1f26d5b2016-01-03 19:43:23 +00004578 bool protocolsSorted = areSortedAndUniqued(protocols);
Douglas Gregore9d95f12015-07-07 03:57:35 +00004579 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
4580 // Determine the canonical type arguments.
4581 ArrayRef<QualType> canonTypeArgs;
4582 SmallVector<QualType, 4> canonTypeArgsVec;
4583 if (!typeArgsAreCanonical) {
4584 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
4585 for (auto typeArg : effectiveTypeArgs)
4586 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
4587 canonTypeArgs = canonTypeArgsVec;
John McCallfc93cf92009-10-22 22:37:11 +00004588 } else {
Douglas Gregore9d95f12015-07-07 03:57:35 +00004589 canonTypeArgs = effectiveTypeArgs;
John McCallfc93cf92009-10-22 22:37:11 +00004590 }
4591
Douglas Gregore9d95f12015-07-07 03:57:35 +00004592 ArrayRef<ObjCProtocolDecl *> canonProtocols;
4593 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
4594 if (!protocolsSorted) {
Craig Topper6a8c1512015-10-22 01:56:18 +00004595 canonProtocolsVec.append(protocols.begin(), protocols.end());
4596 SortAndUniqueProtocols(canonProtocolsVec);
4597 canonProtocols = canonProtocolsVec;
Douglas Gregore9d95f12015-07-07 03:57:35 +00004598 } else {
4599 canonProtocols = protocols;
4600 }
4601
4602 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00004603 canonProtocols, isKindOf);
Douglas Gregore9d95f12015-07-07 03:57:35 +00004604
John McCallfc93cf92009-10-22 22:37:11 +00004605 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00004606 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
4607 }
4608
Douglas Gregore9d95f12015-07-07 03:57:35 +00004609 unsigned size = sizeof(ObjCObjectTypeImpl);
4610 size += typeArgs.size() * sizeof(QualType);
4611 size += protocols.size() * sizeof(ObjCProtocolDecl *);
4612 void *mem = Allocate(size, TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004613 auto *T =
Douglas Gregorab209d82015-07-07 03:58:42 +00004614 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
4615 isKindOf);
John McCall8b07ec22010-05-15 11:32:37 +00004616
4617 Types.push_back(T);
4618 ObjCObjectTypes.InsertNode(T, InsertPos);
4619 return QualType(T, 0);
4620}
4621
Manman Ren3569eb52016-09-13 17:03:12 +00004622/// Apply Objective-C protocol qualifiers to the given type.
4623/// If this is for the canonical type of a type parameter, we can apply
4624/// protocol qualifiers on the ObjCObjectPointerType.
4625QualType
4626ASTContext::applyObjCProtocolQualifiers(QualType type,
4627 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
4628 bool allowOnPointerType) const {
4629 hasError = false;
4630
Eugene Zelenko7855e772018-04-03 00:11:50 +00004631 if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
Manman Renc5705ba2016-09-13 17:41:05 +00004632 return getObjCTypeParamType(objT->getDecl(), protocols);
4633 }
4634
Manman Ren3569eb52016-09-13 17:03:12 +00004635 // Apply protocol qualifiers to ObjCObjectPointerType.
4636 if (allowOnPointerType) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00004637 if (const auto *objPtr =
4638 dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
Manman Ren3569eb52016-09-13 17:03:12 +00004639 const ObjCObjectType *objT = objPtr->getObjectType();
4640 // Merge protocol lists and construct ObjCObjectType.
4641 SmallVector<ObjCProtocolDecl*, 8> protocolsVec;
4642 protocolsVec.append(objT->qual_begin(),
4643 objT->qual_end());
4644 protocolsVec.append(protocols.begin(), protocols.end());
4645 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
4646 type = getObjCObjectType(
4647 objT->getBaseType(),
4648 objT->getTypeArgsAsWritten(),
4649 protocols,
4650 objT->isKindOfTypeAsWritten());
4651 return getObjCObjectPointerType(type);
4652 }
4653 }
4654
4655 // Apply protocol qualifiers to ObjCObjectType.
Eugene Zelenko7855e772018-04-03 00:11:50 +00004656 if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
Manman Ren3569eb52016-09-13 17:03:12 +00004657 // FIXME: Check for protocols to which the class type is already
4658 // known to conform.
4659
4660 return getObjCObjectType(objT->getBaseType(),
4661 objT->getTypeArgsAsWritten(),
4662 protocols,
4663 objT->isKindOfTypeAsWritten());
4664 }
4665
4666 // If the canonical type is ObjCObjectType, ...
4667 if (type->isObjCObjectType()) {
4668 // Silently overwrite any existing protocol qualifiers.
4669 // TODO: determine whether that's the right thing to do.
4670
4671 // FIXME: Check for protocols to which the class type is already
4672 // known to conform.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004673 return getObjCObjectType(type, {}, protocols, false);
Manman Ren3569eb52016-09-13 17:03:12 +00004674 }
4675
4676 // id<protocol-list>
4677 if (type->isObjCIdType()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00004678 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004679 type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols,
Manman Ren3569eb52016-09-13 17:03:12 +00004680 objPtr->isKindOfType());
4681 return getObjCObjectPointerType(type);
4682 }
4683
4684 // Class<protocol-list>
4685 if (type->isObjCClassType()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00004686 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004687 type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols,
Manman Ren3569eb52016-09-13 17:03:12 +00004688 objPtr->isKindOfType());
4689 return getObjCObjectPointerType(type);
4690 }
4691
4692 hasError = true;
4693 return type;
4694}
4695
Manman Rene6be26c2016-09-13 17:25:08 +00004696QualType
4697ASTContext::getObjCTypeParamType(const ObjCTypeParamDecl *Decl,
4698 ArrayRef<ObjCProtocolDecl *> protocols,
4699 QualType Canonical) const {
4700 // Look in the folding set for an existing type.
4701 llvm::FoldingSetNodeID ID;
4702 ObjCTypeParamType::Profile(ID, Decl, protocols);
4703 void *InsertPos = nullptr;
4704 if (ObjCTypeParamType *TypeParam =
4705 ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
4706 return QualType(TypeParam, 0);
4707
4708 if (Canonical.isNull()) {
4709 // We canonicalize to the underlying type.
4710 Canonical = getCanonicalType(Decl->getUnderlyingType());
4711 if (!protocols.empty()) {
4712 // Apply the protocol qualifers.
4713 bool hasError;
Richard Trieua986a312018-08-30 01:57:52 +00004714 Canonical = getCanonicalType(applyObjCProtocolQualifiers(
4715 Canonical, protocols, hasError, true /*allowOnPointerType*/));
Manman Rene6be26c2016-09-13 17:25:08 +00004716 assert(!hasError && "Error when apply protocol qualifier to bound type");
4717 }
4718 }
4719
4720 unsigned size = sizeof(ObjCTypeParamType);
4721 size += protocols.size() * sizeof(ObjCProtocolDecl *);
4722 void *mem = Allocate(size, TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004723 auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols);
Manman Rene6be26c2016-09-13 17:25:08 +00004724
4725 Types.push_back(newType);
4726 ObjCTypeParamTypes.InsertNode(newType, InsertPos);
4727 return QualType(newType, 0);
4728}
4729
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004730/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
4731/// protocol list adopt all protocols in QT's qualified-id protocol
4732/// list.
4733bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
4734 ObjCInterfaceDecl *IC) {
4735 if (!QT->isObjCQualifiedIdType())
4736 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00004737
Eugene Zelenko7855e772018-04-03 00:11:50 +00004738 if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004739 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00004740 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004741 if (!IC->ClassImplementsProtocol(Proto, false))
4742 return false;
4743 }
4744 return true;
4745 }
4746 return false;
4747}
4748
4749/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
4750/// QT's qualified-id protocol list adopt all protocols in IDecl's list
4751/// of protocols.
4752bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
4753 ObjCInterfaceDecl *IDecl) {
4754 if (!QT->isObjCQualifiedIdType())
4755 return false;
Eugene Zelenko7855e772018-04-03 00:11:50 +00004756 const auto *OPT = QT->getAs<ObjCObjectPointerType>();
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004757 if (!OPT)
4758 return false;
4759 if (!IDecl->hasDefinition())
4760 return false;
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00004761 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
4762 CollectInheritedProtocols(IDecl, InheritedProtocols);
4763 if (InheritedProtocols.empty())
4764 return false;
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00004765 // Check that if every protocol in list of id<plist> conforms to a protocol
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00004766 // of IDecl's, then bridge casting is ok.
4767 bool Conforms = false;
4768 for (auto *Proto : OPT->quals()) {
4769 Conforms = false;
4770 for (auto *PI : InheritedProtocols) {
4771 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
4772 Conforms = true;
4773 break;
4774 }
4775 }
4776 if (!Conforms)
4777 break;
4778 }
4779 if (Conforms)
4780 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00004781
Aaron Ballman83731462014-03-17 16:14:00 +00004782 for (auto *PI : InheritedProtocols) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004783 // If both the right and left sides have qualifiers.
4784 bool Adopts = false;
Aaron Ballman83731462014-03-17 16:14:00 +00004785 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00004786 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
Aaron Ballman83731462014-03-17 16:14:00 +00004787 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004788 break;
4789 }
4790 if (!Adopts)
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00004791 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004792 }
4793 return true;
4794}
4795
John McCall8b07ec22010-05-15 11:32:37 +00004796/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
4797/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00004798QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00004799 llvm::FoldingSetNodeID ID;
4800 ObjCObjectPointerType::Profile(ID, ObjectT);
4801
Craig Topper36250ad2014-05-12 05:36:57 +00004802 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00004803 if (ObjCObjectPointerType *QT =
4804 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
4805 return QualType(QT, 0);
4806
4807 // Find the canonical object type.
4808 QualType Canonical;
4809 if (!ObjectT.isCanonical()) {
4810 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
4811
4812 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00004813 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
4814 }
4815
Douglas Gregorf85bee62010-02-08 22:59:26 +00004816 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00004817 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004818 auto *QType =
John McCall8b07ec22010-05-15 11:32:37 +00004819 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00004820
Steve Narofffb4330f2009-06-17 22:40:22 +00004821 Types.push_back(QType);
4822 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00004823 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00004824}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004825
Douglas Gregor1c283312010-08-11 12:19:30 +00004826/// getObjCInterfaceType - Return the unique reference to the type for the
4827/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00004828QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
4829 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00004830 if (Decl->TypeForDecl)
4831 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004832
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00004833 if (PrevDecl) {
4834 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
4835 Decl->TypeForDecl = PrevDecl->TypeForDecl;
4836 return QualType(PrevDecl->TypeForDecl, 0);
4837 }
4838
Douglas Gregor7671e532011-12-16 16:34:57 +00004839 // Prefer the definition, if there is one.
4840 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
4841 Decl = Def;
Fangrui Song6907ce22018-07-30 19:24:48 +00004842
Douglas Gregor1c283312010-08-11 12:19:30 +00004843 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004844 auto *T = new (Mem) ObjCInterfaceType(Decl);
Douglas Gregor1c283312010-08-11 12:19:30 +00004845 Decl->TypeForDecl = T;
4846 Types.push_back(T);
4847 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00004848}
4849
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004850/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
4851/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00004852/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00004853/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00004854/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00004855QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00004856 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004857 if (tofExpr->isTypeDependent()) {
4858 llvm::FoldingSetNodeID ID;
4859 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00004860
Craig Topper36250ad2014-05-12 05:36:57 +00004861 void *InsertPos = nullptr;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004862 DependentTypeOfExprType *Canon
4863 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
4864 if (Canon) {
4865 // We already have a "canonical" version of an identical, dependent
4866 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00004867 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004868 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00004869 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004870 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00004871 Canon
4872 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004873 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
4874 toe = Canon;
4875 }
4876 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00004877 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00004878 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00004879 }
Steve Naroffa773cd52007-08-01 18:02:17 +00004880 Types.push_back(toe);
4881 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00004882}
4883
Steve Naroffa773cd52007-08-01 18:02:17 +00004884/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
Richard Smith8eb1d322014-06-05 20:13:13 +00004885/// TypeOfType nodes. The only motivation to unique these nodes would be
Steve Naroffa773cd52007-08-01 18:02:17 +00004886/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Richard Smith8eb1d322014-06-05 20:13:13 +00004887/// an issue. This doesn't affect the type checker, since it operates
4888/// on canonical types (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00004889QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00004890 QualType Canonical = getCanonicalType(tofType);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004891 auto *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00004892 Types.push_back(tot);
4893 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00004894}
4895
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004896/// Unlike many "get<Type>" functions, we don't unique DecltypeType
Richard Smith8eb1d322014-06-05 20:13:13 +00004897/// nodes. This would never be helpful, since each such type has its own
4898/// expression, and would not give a significant memory saving, since there
4899/// is an Expr tree under each such type.
Douglas Gregor81495f32012-02-12 18:42:33 +00004900QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00004901 DecltypeType *dt;
Richard Smith8eb1d322014-06-05 20:13:13 +00004902
4903 // C++11 [temp.type]p2:
Douglas Gregor678d76c2011-07-01 01:22:09 +00004904 // If an expression e involves a template parameter, decltype(e) denotes a
Richard Smith8eb1d322014-06-05 20:13:13 +00004905 // unique dependent type. Two such decltype-specifiers refer to the same
4906 // type only if their expressions are equivalent (14.5.6.1).
Douglas Gregor678d76c2011-07-01 01:22:09 +00004907 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00004908 llvm::FoldingSetNodeID ID;
4909 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00004910
Craig Topper36250ad2014-05-12 05:36:57 +00004911 void *InsertPos = nullptr;
Douglas Gregora21f6c32009-07-30 23:36:40 +00004912 DependentDecltypeType *Canon
4913 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
Richard Smith8eb1d322014-06-05 20:13:13 +00004914 if (!Canon) {
Yaron Keren633e14a2016-11-29 10:08:20 +00004915 // Build a new, canonical decltype(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00004916 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00004917 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
Douglas Gregora21f6c32009-07-30 23:36:40 +00004918 }
Richard Smith8eb1d322014-06-05 20:13:13 +00004919 dt = new (*this, TypeAlignment)
4920 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
Douglas Gregora21f6c32009-07-30 23:36:40 +00004921 } else {
Richard Smith8eb1d322014-06-05 20:13:13 +00004922 dt = new (*this, TypeAlignment)
4923 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00004924 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00004925 Types.push_back(dt);
4926 return QualType(dt, 0);
4927}
4928
Alexis Hunte852b102011-05-24 22:41:36 +00004929/// getUnaryTransformationType - We don't unique these, since the memory
4930/// savings are minimal and these are rare.
4931QualType ASTContext::getUnaryTransformType(QualType BaseType,
4932 QualType UnderlyingType,
4933 UnaryTransformType::UTTKind Kind)
4934 const {
Vassil Vassilevbab6f962016-03-30 22:18:29 +00004935 UnaryTransformType *ut = nullptr;
4936
4937 if (BaseType->isDependentType()) {
4938 // Look in the folding set for an existing type.
4939 llvm::FoldingSetNodeID ID;
4940 DependentUnaryTransformType::Profile(ID, getCanonicalType(BaseType), Kind);
4941
4942 void *InsertPos = nullptr;
4943 DependentUnaryTransformType *Canon
4944 = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
4945
4946 if (!Canon) {
4947 // Build a new, canonical __underlying_type(type) type.
4948 Canon = new (*this, TypeAlignment)
4949 DependentUnaryTransformType(*this, getCanonicalType(BaseType),
4950 Kind);
4951 DependentUnaryTransformTypes.InsertNode(Canon, InsertPos);
4952 }
4953 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4954 QualType(), Kind,
4955 QualType(Canon, 0));
4956 } else {
4957 QualType CanonType = getCanonicalType(UnderlyingType);
4958 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4959 UnderlyingType, Kind,
4960 CanonType);
4961 }
4962 Types.push_back(ut);
4963 return QualType(ut, 0);
Alexis Hunte852b102011-05-24 22:41:36 +00004964}
4965
Richard Smith2a7d4812013-05-04 07:00:32 +00004966/// getAutoType - Return the uniqued reference to the 'auto' type which has been
4967/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
4968/// canonical deduced-but-dependent 'auto' type.
Richard Smithe301ba22015-11-11 02:02:15 +00004969QualType ASTContext::getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
Richard Smithb2997f52019-05-21 20:10:50 +00004970 bool IsDependent, bool IsPack) const {
4971 assert((!IsPack || IsDependent) && "only use IsPack for a dependent pack");
Richard Smithe301ba22015-11-11 02:02:15 +00004972 if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto && !IsDependent)
Richard Smith2a7d4812013-05-04 07:00:32 +00004973 return getAutoDeductType();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004974
Richard Smith2a7d4812013-05-04 07:00:32 +00004975 // Look in the folding set for an existing type.
Craig Topper36250ad2014-05-12 05:36:57 +00004976 void *InsertPos = nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +00004977 llvm::FoldingSetNodeID ID;
Richard Smithb2997f52019-05-21 20:10:50 +00004978 AutoType::Profile(ID, DeducedType, Keyword, IsDependent, IsPack);
Richard Smith2a7d4812013-05-04 07:00:32 +00004979 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
4980 return QualType(AT, 0);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004981
Eugene Zelenko7855e772018-04-03 00:11:50 +00004982 auto *AT = new (*this, TypeAlignment)
Richard Smithb2997f52019-05-21 20:10:50 +00004983 AutoType(DeducedType, Keyword, IsDependent, IsPack);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004984 Types.push_back(AT);
4985 if (InsertPos)
4986 AutoTypes.InsertNode(AT, InsertPos);
4987 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00004988}
4989
Richard Smith600b5262017-01-26 20:40:47 +00004990/// Return the uniqued reference to the deduced template specialization type
4991/// which has been deduced to the given type, or to the canonical undeduced
4992/// such type, or the canonical deduced-but-dependent such type.
4993QualType ASTContext::getDeducedTemplateSpecializationType(
4994 TemplateName Template, QualType DeducedType, bool IsDependent) const {
4995 // Look in the folding set for an existing type.
4996 void *InsertPos = nullptr;
4997 llvm::FoldingSetNodeID ID;
4998 DeducedTemplateSpecializationType::Profile(ID, Template, DeducedType,
4999 IsDependent);
5000 if (DeducedTemplateSpecializationType *DTST =
5001 DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
5002 return QualType(DTST, 0);
5003
Eugene Zelenko7855e772018-04-03 00:11:50 +00005004 auto *DTST = new (*this, TypeAlignment)
Richard Smith600b5262017-01-26 20:40:47 +00005005 DeducedTemplateSpecializationType(Template, DeducedType, IsDependent);
5006 Types.push_back(DTST);
5007 if (InsertPos)
5008 DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos);
5009 return QualType(DTST, 0);
5010}
5011
Eli Friedman0dfb8892011-10-06 23:00:33 +00005012/// getAtomicType - Return the uniqued reference to the atomic type for
5013/// the given value type.
5014QualType ASTContext::getAtomicType(QualType T) const {
5015 // Unique pointers, to guarantee there is only one pointer of a particular
5016 // structure.
5017 llvm::FoldingSetNodeID ID;
5018 AtomicType::Profile(ID, T);
5019
Craig Topper36250ad2014-05-12 05:36:57 +00005020 void *InsertPos = nullptr;
Eli Friedman0dfb8892011-10-06 23:00:33 +00005021 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
5022 return QualType(AT, 0);
5023
5024 // If the atomic value type isn't canonical, this won't be a canonical type
5025 // either, so fill in the canonical type field.
5026 QualType Canonical;
5027 if (!T.isCanonical()) {
5028 Canonical = getAtomicType(getCanonicalType(T));
5029
5030 // Get the new insert position for the node we care about.
5031 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00005032 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Eli Friedman0dfb8892011-10-06 23:00:33 +00005033 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00005034 auto *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
Eli Friedman0dfb8892011-10-06 23:00:33 +00005035 Types.push_back(New);
5036 AtomicTypes.InsertNode(New, InsertPos);
5037 return QualType(New, 0);
5038}
5039
Richard Smith02e85f32011-04-14 22:09:26 +00005040/// getAutoDeductType - Get type pattern for deducing against 'auto'.
5041QualType ASTContext::getAutoDeductType() const {
5042 if (AutoDeductTy.isNull())
Richard Smith2a7d4812013-05-04 07:00:32 +00005043 AutoDeductTy = QualType(
Richard Smithe301ba22015-11-11 02:02:15 +00005044 new (*this, TypeAlignment) AutoType(QualType(), AutoTypeKeyword::Auto,
Richard Smithb2997f52019-05-21 20:10:50 +00005045 /*dependent*/false, /*pack*/false),
Richard Smith2a7d4812013-05-04 07:00:32 +00005046 0);
Richard Smith02e85f32011-04-14 22:09:26 +00005047 return AutoDeductTy;
5048}
5049
5050/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
5051QualType ASTContext::getAutoRRefDeductType() const {
5052 if (AutoRRefDeductTy.isNull())
5053 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
5054 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
5055 return AutoRRefDeductTy;
5056}
5057
Chris Lattnerfb072462007-01-23 05:45:31 +00005058/// getTagDeclType - Return the unique reference to the type for the
5059/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00005060QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00005061 assert(Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00005062 // FIXME: What is the design on getTagDeclType when it requires casting
5063 // away const? mutable?
5064 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00005065}
5066
Mike Stump11289f42009-09-09 15:08:12 +00005067/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
5068/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
5069/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00005070CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00005071 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00005072}
Chris Lattnerfb072462007-01-23 05:45:31 +00005073
Fangrui Song6907ce22018-07-30 19:24:48 +00005074/// Return the unique signed counterpart of the integer type
Alexander Shaposhnikov1e898d92017-07-14 17:30:14 +00005075/// corresponding to size_t.
5076CanQualType ASTContext::getSignedSizeType() const {
5077 return getFromTargetType(Target->getSignedSizeType());
5078}
5079
Hans Wennborg27541db2011-10-27 08:29:09 +00005080/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
5081CanQualType ASTContext::getIntMaxType() const {
5082 return getFromTargetType(Target->getIntMaxType());
5083}
5084
5085/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
5086CanQualType ASTContext::getUIntMaxType() const {
5087 return getFromTargetType(Target->getUIntMaxType());
5088}
5089
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00005090/// getSignedWCharType - Return the type of "signed wchar_t".
5091/// Used when in C++, as a GCC extension.
5092QualType ASTContext::getSignedWCharType() const {
5093 // FIXME: derive from "Target" ?
5094 return WCharTy;
5095}
5096
5097/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
5098/// Used when in C++, as a GCC extension.
5099QualType ASTContext::getUnsignedWCharType() const {
5100 // FIXME: derive from "Target" ?
5101 return UnsignedIntTy;
5102}
5103
Enea Zaffanellaf11ceb62013-01-26 17:08:37 +00005104QualType ASTContext::getIntPtrType() const {
5105 return getFromTargetType(Target->getIntPtrType());
5106}
5107
5108QualType ASTContext::getUIntPtrType() const {
5109 return getCorrespondingUnsignedType(getIntPtrType());
5110}
5111
Hans Wennborg27541db2011-10-27 08:29:09 +00005112/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00005113/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
5114QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00005115 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00005116}
5117
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005118/// Return the unique unsigned counterpart of "ptrdiff_t"
Alexander Shaposhnikov195b25c2017-09-28 23:11:31 +00005119/// integer type. The standard (C11 7.21.6.1p7) refers to this type
5120/// in the definition of %tu format specifier.
5121QualType ASTContext::getUnsignedPointerDiffType() const {
5122 return getFromTargetType(Target->getUnsignedPtrDiffType(0));
5123}
5124
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005125/// Return the unique type for "pid_t" defined in
Eli Friedman4e91899e2012-11-27 02:58:24 +00005126/// <sys/types.h>. We need this to compute the correct type for vfork().
5127QualType ASTContext::getProcessIDType() const {
5128 return getFromTargetType(Target->getProcessIDType());
5129}
5130
Chris Lattnera21ad802008-04-02 05:18:44 +00005131//===----------------------------------------------------------------------===//
5132// Type Operators
5133//===----------------------------------------------------------------------===//
5134
Jay Foad39c79802011-01-12 09:06:06 +00005135CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00005136 // Push qualifiers into arrays, and then discard any remaining
5137 // qualifiers.
5138 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00005139 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00005140 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00005141 QualType Result;
5142 if (isa<ArrayType>(Ty)) {
5143 Result = getArrayDecayedType(QualType(Ty,0));
5144 } else if (isa<FunctionType>(Ty)) {
5145 Result = getPointerType(QualType(Ty, 0));
5146 } else {
5147 Result = QualType(Ty, 0);
5148 }
5149
5150 return CanQualType::CreateUnsafe(Result);
5151}
5152
John McCall6c9dd522011-01-18 07:41:22 +00005153QualType ASTContext::getUnqualifiedArrayType(QualType type,
5154 Qualifiers &quals) {
5155 SplitQualType splitType = type.getSplitUnqualifiedType();
5156
5157 // FIXME: getSplitUnqualifiedType() actually walks all the way to
5158 // the unqualified desugared type and then drops it on the floor.
5159 // We then have to strip that sugar back off with
5160 // getUnqualifiedDesugaredType(), which is silly.
Eugene Zelenko7855e772018-04-03 00:11:50 +00005161 const auto *AT =
5162 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00005163
5164 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00005165 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00005166 quals = splitType.Quals;
5167 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00005168 }
5169
John McCall6c9dd522011-01-18 07:41:22 +00005170 // Otherwise, recurse on the array's element type.
5171 QualType elementType = AT->getElementType();
5172 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
5173
5174 // If that didn't change the element type, AT has no qualifiers, so we
5175 // can just use the results in splitType.
5176 if (elementType == unqualElementType) {
5177 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00005178 quals = splitType.Quals;
5179 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00005180 }
5181
5182 // Otherwise, add in the qualifiers from the outermost type, then
5183 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00005184 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00005185
Eugene Zelenko7855e772018-04-03 00:11:50 +00005186 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00005187 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00005188 CAT->getSizeModifier(), 0);
5189 }
5190
Eugene Zelenko7855e772018-04-03 00:11:50 +00005191 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00005192 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00005193 }
5194
Eugene Zelenko7855e772018-04-03 00:11:50 +00005195 if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00005196 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00005197 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00005198 VAT->getSizeModifier(),
5199 VAT->getIndexTypeCVRQualifiers(),
5200 VAT->getBracketsRange());
5201 }
5202
Eugene Zelenko7855e772018-04-03 00:11:50 +00005203 const auto *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00005204 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00005205 DSAT->getSizeModifier(), 0,
5206 SourceRange());
5207}
5208
Richard Smitha3405ff2018-07-11 00:19:19 +00005209/// Attempt to unwrap two types that may both be array types with the same bound
5210/// (or both be array types of unknown bound) for the purpose of comparing the
5211/// cv-decomposition of two types per C++ [conv.qual].
Richard Smith5407d4f2018-07-18 20:13:36 +00005212bool ASTContext::UnwrapSimilarArrayTypes(QualType &T1, QualType &T2) {
5213 bool UnwrappedAny = false;
Richard Smitha3405ff2018-07-11 00:19:19 +00005214 while (true) {
Richard Smith5407d4f2018-07-18 20:13:36 +00005215 auto *AT1 = getAsArrayType(T1);
5216 if (!AT1) return UnwrappedAny;
Richard Smitha3405ff2018-07-11 00:19:19 +00005217
Richard Smith5407d4f2018-07-18 20:13:36 +00005218 auto *AT2 = getAsArrayType(T2);
5219 if (!AT2) return UnwrappedAny;
Richard Smitha3405ff2018-07-11 00:19:19 +00005220
5221 // If we don't have two array types with the same constant bound nor two
5222 // incomplete array types, we've unwrapped everything we can.
5223 if (auto *CAT1 = dyn_cast<ConstantArrayType>(AT1)) {
5224 auto *CAT2 = dyn_cast<ConstantArrayType>(AT2);
5225 if (!CAT2 || CAT1->getSize() != CAT2->getSize())
Richard Smith5407d4f2018-07-18 20:13:36 +00005226 return UnwrappedAny;
Richard Smitha3405ff2018-07-11 00:19:19 +00005227 } else if (!isa<IncompleteArrayType>(AT1) ||
5228 !isa<IncompleteArrayType>(AT2)) {
Richard Smith5407d4f2018-07-18 20:13:36 +00005229 return UnwrappedAny;
Richard Smitha3405ff2018-07-11 00:19:19 +00005230 }
5231
5232 T1 = AT1->getElementType();
5233 T2 = AT2->getElementType();
Richard Smith5407d4f2018-07-18 20:13:36 +00005234 UnwrappedAny = true;
Richard Smitha3405ff2018-07-11 00:19:19 +00005235 }
5236}
5237
5238/// Attempt to unwrap two types that may be similar (C++ [conv.qual]).
5239///
5240/// If T1 and T2 are both pointer types of the same kind, or both array types
5241/// with the same bound, unwraps layers from T1 and T2 until a pointer type is
5242/// unwrapped. Top-level qualifiers on T1 and T2 are ignored.
5243///
5244/// This function will typically be called in a loop that successively
5245/// "unwraps" pointer and pointer-to-member types to compare them at each
5246/// level.
5247///
5248/// \return \c true if a pointer type was unwrapped, \c false if we reached a
5249/// pair of types that can't be unwrapped further.
5250bool ASTContext::UnwrapSimilarTypes(QualType &T1, QualType &T2) {
Richard Smith5407d4f2018-07-18 20:13:36 +00005251 UnwrapSimilarArrayTypes(T1, T2);
Richard Smitha3405ff2018-07-11 00:19:19 +00005252
Eugene Zelenko7855e772018-04-03 00:11:50 +00005253 const auto *T1PtrType = T1->getAs<PointerType>();
5254 const auto *T2PtrType = T2->getAs<PointerType>();
Douglas Gregor1fc3d662010-06-09 03:53:18 +00005255 if (T1PtrType && T2PtrType) {
5256 T1 = T1PtrType->getPointeeType();
5257 T2 = T2PtrType->getPointeeType();
5258 return true;
5259 }
Richard Smith5407d4f2018-07-18 20:13:36 +00005260
Eugene Zelenko7855e772018-04-03 00:11:50 +00005261 const auto *T1MPType = T1->getAs<MemberPointerType>();
5262 const auto *T2MPType = T2->getAs<MemberPointerType>();
Fangrui Song6907ce22018-07-30 19:24:48 +00005263 if (T1MPType && T2MPType &&
5264 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
Douglas Gregor1fc3d662010-06-09 03:53:18 +00005265 QualType(T2MPType->getClass(), 0))) {
5266 T1 = T1MPType->getPointeeType();
5267 T2 = T2MPType->getPointeeType();
5268 return true;
5269 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005270
Erik Pilkingtonfa983902018-10-30 20:31:30 +00005271 if (getLangOpts().ObjC) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00005272 const auto *T1OPType = T1->getAs<ObjCObjectPointerType>();
5273 const auto *T2OPType = T2->getAs<ObjCObjectPointerType>();
Douglas Gregor1fc3d662010-06-09 03:53:18 +00005274 if (T1OPType && T2OPType) {
5275 T1 = T1OPType->getPointeeType();
5276 T2 = T2OPType->getPointeeType();
5277 return true;
5278 }
5279 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005280
Douglas Gregor1fc3d662010-06-09 03:53:18 +00005281 // FIXME: Block pointers, too?
Fangrui Song6907ce22018-07-30 19:24:48 +00005282
Douglas Gregor1fc3d662010-06-09 03:53:18 +00005283 return false;
5284}
5285
Richard Smitha3405ff2018-07-11 00:19:19 +00005286bool ASTContext::hasSimilarType(QualType T1, QualType T2) {
5287 while (true) {
5288 Qualifiers Quals;
5289 T1 = getUnqualifiedArrayType(T1, Quals);
5290 T2 = getUnqualifiedArrayType(T2, Quals);
5291 if (hasSameType(T1, T2))
5292 return true;
5293 if (!UnwrapSimilarTypes(T1, T2))
5294 return false;
5295 }
5296}
5297
5298bool ASTContext::hasCvrSimilarType(QualType T1, QualType T2) {
5299 while (true) {
5300 Qualifiers Quals1, Quals2;
5301 T1 = getUnqualifiedArrayType(T1, Quals1);
5302 T2 = getUnqualifiedArrayType(T2, Quals2);
5303
5304 Quals1.removeCVRQualifiers();
5305 Quals2.removeCVRQualifiers();
5306 if (Quals1 != Quals2)
5307 return false;
5308
5309 if (hasSameType(T1, T2))
5310 return true;
5311
5312 if (!UnwrapSimilarTypes(T1, T2))
5313 return false;
5314 }
5315}
5316
Jay Foad39c79802011-01-12 09:06:06 +00005317DeclarationNameInfo
5318ASTContext::getNameForTemplate(TemplateName Name,
5319 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00005320 switch (Name.getKind()) {
5321 case TemplateName::QualifiedTemplate:
5322 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005323 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00005324 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
5325 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005326
John McCalld9dfe3a2011-06-30 08:33:18 +00005327 case TemplateName::OverloadedTemplate: {
5328 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
5329 // DNInfo work in progress: CHECKME: what about DNLoc?
5330 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
5331 }
5332
Richard Smithb23c5e82019-05-09 03:31:27 +00005333 case TemplateName::AssumedTemplate: {
5334 AssumedTemplateStorage *Storage = Name.getAsAssumedTemplateName();
5335 return DeclarationNameInfo(Storage->getDeclName(), NameLoc);
5336 }
5337
John McCalld9dfe3a2011-06-30 08:33:18 +00005338 case TemplateName::DependentTemplate: {
5339 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005340 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00005341 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005342 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
5343 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00005344 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005345 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
5346 // DNInfo work in progress: FIXME: source locations?
5347 DeclarationNameLoc DNLoc;
5348 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
5349 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
5350 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00005351 }
5352 }
5353
John McCalld9dfe3a2011-06-30 08:33:18 +00005354 case TemplateName::SubstTemplateTemplateParm: {
5355 SubstTemplateTemplateParmStorage *subst
5356 = Name.getAsSubstTemplateTemplateParm();
5357 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
5358 NameLoc);
5359 }
5360
5361 case TemplateName::SubstTemplateTemplateParmPack: {
5362 SubstTemplateTemplateParmPackStorage *subst
5363 = Name.getAsSubstTemplateTemplateParmPack();
5364 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
5365 NameLoc);
5366 }
5367 }
5368
5369 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00005370}
5371
Jay Foad39c79802011-01-12 09:06:06 +00005372TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00005373 switch (Name.getKind()) {
5374 case TemplateName::QualifiedTemplate:
5375 case TemplateName::Template: {
5376 TemplateDecl *Template = Name.getAsTemplateDecl();
Eugene Zelenko7855e772018-04-03 00:11:50 +00005377 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00005378 Template = getCanonicalTemplateTemplateParmDecl(TTP);
Fangrui Song6907ce22018-07-30 19:24:48 +00005379
Douglas Gregor7dbfb462010-06-16 21:09:37 +00005380 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00005381 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00005382 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00005383
John McCalld9dfe3a2011-06-30 08:33:18 +00005384 case TemplateName::OverloadedTemplate:
Richard Smithb23c5e82019-05-09 03:31:27 +00005385 case TemplateName::AssumedTemplate:
5386 llvm_unreachable("cannot canonicalize unresolved template");
Mike Stump11289f42009-09-09 15:08:12 +00005387
John McCalld9dfe3a2011-06-30 08:33:18 +00005388 case TemplateName::DependentTemplate: {
5389 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
5390 assert(DTN && "Non-dependent template names must refer to template decls.");
5391 return DTN->CanonicalTemplateName;
5392 }
5393
5394 case TemplateName::SubstTemplateTemplateParm: {
5395 SubstTemplateTemplateParmStorage *subst
5396 = Name.getAsSubstTemplateTemplateParm();
5397 return getCanonicalTemplateName(subst->getReplacement());
5398 }
5399
5400 case TemplateName::SubstTemplateTemplateParmPack: {
5401 SubstTemplateTemplateParmPackStorage *subst
5402 = Name.getAsSubstTemplateTemplateParmPack();
5403 TemplateTemplateParmDecl *canonParameter
5404 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
5405 TemplateArgument canonArgPack
5406 = getCanonicalTemplateArgument(subst->getArgumentPack());
5407 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
5408 }
5409 }
5410
5411 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00005412}
5413
Douglas Gregoradee3e32009-11-11 23:06:43 +00005414bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
5415 X = getCanonicalTemplateName(X);
5416 Y = getCanonicalTemplateName(Y);
5417 return X.getAsVoidPointer() == Y.getAsVoidPointer();
5418}
5419
Mike Stump11289f42009-09-09 15:08:12 +00005420TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00005421ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00005422 switch (Arg.getKind()) {
5423 case TemplateArgument::Null:
5424 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00005425
Douglas Gregora8e02e72009-07-28 23:00:59 +00005426 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00005427 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00005428
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005429 case TemplateArgument::Declaration: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00005430 auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
David Blaikie952a9b12014-10-17 18:00:12 +00005431 return TemplateArgument(D, Arg.getParamTypeForDecl());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005432 }
Mike Stump11289f42009-09-09 15:08:12 +00005433
Eli Friedmanb826a002012-09-26 02:36:12 +00005434 case TemplateArgument::NullPtr:
5435 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
5436 /*isNullPtr*/true);
5437
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005438 case TemplateArgument::Template:
5439 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005440
5441 case TemplateArgument::TemplateExpansion:
5442 return TemplateArgument(getCanonicalTemplateName(
5443 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00005444 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005445
Douglas Gregora8e02e72009-07-28 23:00:59 +00005446 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00005447 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00005448
Douglas Gregora8e02e72009-07-28 23:00:59 +00005449 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00005450 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00005451
Douglas Gregora8e02e72009-07-28 23:00:59 +00005452 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00005453 if (Arg.pack_size() == 0)
5454 return Arg;
Fangrui Song6907ce22018-07-30 19:24:48 +00005455
Eugene Zelenko7855e772018-04-03 00:11:50 +00005456 auto *CanonArgs = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00005457 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00005458 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00005459 AEnd = Arg.pack_end();
5460 A != AEnd; (void)++A, ++Idx)
5461 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00005462
Benjamin Kramercce63472015-08-05 09:40:22 +00005463 return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size()));
Douglas Gregora8e02e72009-07-28 23:00:59 +00005464 }
5465 }
5466
5467 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00005468 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00005469}
5470
Douglas Gregor333489b2009-03-27 23:10:48 +00005471NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00005472ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00005473 if (!NNS)
Craig Topper36250ad2014-05-12 05:36:57 +00005474 return nullptr;
Douglas Gregor333489b2009-03-27 23:10:48 +00005475
5476 switch (NNS->getKind()) {
5477 case NestedNameSpecifier::Identifier:
5478 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00005479 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00005480 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
5481 NNS->getAsIdentifier());
5482
5483 case NestedNameSpecifier::Namespace:
5484 // A namespace is canonical; build a nested-name-specifier with
5485 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00005486 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00005487 NNS->getAsNamespace()->getOriginalNamespace());
5488
5489 case NestedNameSpecifier::NamespaceAlias:
5490 // A namespace is canonical; build a nested-name-specifier with
5491 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00005492 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00005493 NNS->getAsNamespaceAlias()->getNamespace()
5494 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00005495
5496 case NestedNameSpecifier::TypeSpec:
5497 case NestedNameSpecifier::TypeSpecWithTemplate: {
5498 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Fangrui Song6907ce22018-07-30 19:24:48 +00005499
Douglas Gregor3ade5702010-11-04 00:09:33 +00005500 // If we have some kind of dependent-named type (e.g., "typename T::type"),
5501 // break it apart into its prefix and identifier, then reconsititute those
5502 // as the canonical nested-name-specifier. This is required to canonicalize
5503 // a dependent nested-name-specifier involving typedefs of dependent-name
5504 // types, e.g.,
5505 // typedef typename T::type T1;
5506 // typedef typename T1::type T2;
Eugene Zelenko7855e772018-04-03 00:11:50 +00005507 if (const auto *DNT = T->getAs<DependentNameType>())
Fangrui Song6907ce22018-07-30 19:24:48 +00005508 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00005509 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00005510
Eli Friedman5358a0a2012-03-03 04:09:56 +00005511 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
5512 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
5513 // first place?
Craig Topper36250ad2014-05-12 05:36:57 +00005514 return NestedNameSpecifier::Create(*this, nullptr, false,
5515 const_cast<Type *>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00005516 }
5517
5518 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00005519 case NestedNameSpecifier::Super:
5520 // The global specifier and __super specifer are canonical and unique.
Douglas Gregor333489b2009-03-27 23:10:48 +00005521 return NNS;
5522 }
5523
David Blaikie8a40f702012-01-17 06:56:22 +00005524 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00005525}
5526
Jay Foad39c79802011-01-12 09:06:06 +00005527const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00005528 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005529 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00005530 // Handle the common positive case fast.
Eugene Zelenko7855e772018-04-03 00:11:50 +00005531 if (const auto *AT = dyn_cast<ArrayType>(T))
Chris Lattner7adf0762008-08-04 07:31:14 +00005532 return AT;
5533 }
Mike Stump11289f42009-09-09 15:08:12 +00005534
John McCall8ccfcb52009-09-24 19:53:00 +00005535 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00005536 if (!isa<ArrayType>(T.getCanonicalType()))
Craig Topper36250ad2014-05-12 05:36:57 +00005537 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00005538
John McCall8ccfcb52009-09-24 19:53:00 +00005539 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00005540 // implements C99 6.7.3p8: "If the specification of an array type includes
5541 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00005542
Chris Lattner7adf0762008-08-04 07:31:14 +00005543 // If we get here, we either have type qualifiers on the type, or we have
5544 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00005545 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00005546
John McCall33ddac02011-01-19 10:06:00 +00005547 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00005548 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00005549
Chris Lattner7adf0762008-08-04 07:31:14 +00005550 // If we have a simple case, just return now.
Eugene Zelenko7855e772018-04-03 00:11:50 +00005551 const auto *ATy = dyn_cast<ArrayType>(split.Ty);
Craig Topper36250ad2014-05-12 05:36:57 +00005552 if (!ATy || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00005553 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00005554
Chris Lattner7adf0762008-08-04 07:31:14 +00005555 // Otherwise, we have an array and we have qualifiers on it. Push the
5556 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00005557 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00005558
Eugene Zelenko7855e772018-04-03 00:11:50 +00005559 if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy))
Chris Lattner7adf0762008-08-04 07:31:14 +00005560 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
5561 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00005562 CAT->getIndexTypeCVRQualifiers()));
Eugene Zelenko7855e772018-04-03 00:11:50 +00005563 if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy))
Chris Lattner7adf0762008-08-04 07:31:14 +00005564 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
5565 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00005566 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00005567
Eugene Zelenko7855e772018-04-03 00:11:50 +00005568 if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy))
Douglas Gregor4619e432008-12-05 23:32:09 +00005569 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00005570 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00005571 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00005572 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00005573 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00005574 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00005575
Eugene Zelenko7855e772018-04-03 00:11:50 +00005576 const auto *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00005577 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00005578 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00005579 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00005580 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00005581 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00005582}
5583
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00005584QualType ASTContext::getAdjustedParameterType(QualType T) const {
Reid Kleckner8a365022013-06-24 17:51:48 +00005585 if (T->isArrayType() || T->isFunctionType())
5586 return getDecayedType(T);
5587 return T;
Douglas Gregor84280642011-07-12 04:42:08 +00005588}
5589
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00005590QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00005591 T = getVariableArrayDecayedType(T);
5592 T = getAdjustedParameterType(T);
5593 return T.getUnqualifiedType();
5594}
5595
David Majnemerd09a51c2015-03-03 01:50:05 +00005596QualType ASTContext::getExceptionObjectType(QualType T) const {
5597 // C++ [except.throw]p3:
5598 // A throw-expression initializes a temporary object, called the exception
5599 // object, the type of which is determined by removing any top-level
5600 // cv-qualifiers from the static type of the operand of throw and adjusting
5601 // the type from "array of T" or "function returning T" to "pointer to T"
5602 // or "pointer to function returning T", [...]
5603 T = getVariableArrayDecayedType(T);
5604 if (T->isArrayType() || T->isFunctionType())
5605 T = getDecayedType(T);
5606 return T.getUnqualifiedType();
5607}
5608
Chris Lattnera21ad802008-04-02 05:18:44 +00005609/// getArrayDecayedType - Return the properly qualified result of decaying the
5610/// specified array type to a pointer. This operation is non-trivial when
5611/// handling typedefs etc. The canonical type of "T" must be an array type,
5612/// this returns a pointer to a properly qualified element of the array.
5613///
5614/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00005615QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00005616 // Get the element type with 'getAsArrayType' so that we don't lose any
5617 // typedefs in the element type of the array. This also handles propagation
5618 // of type qualifiers from the array type into the element type if present
5619 // (C99 6.7.3p8).
5620 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
5621 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00005622
Chris Lattner7adf0762008-08-04 07:31:14 +00005623 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00005624
5625 // int x[restrict 4] -> int *restrict
Jordan Rose303e2f12016-11-10 23:28:17 +00005626 QualType Result = getQualifiedType(PtrTy,
5627 PrettyArrayType->getIndexTypeQualifiers());
5628
5629 // int x[_Nullable] -> int * _Nullable
5630 if (auto Nullability = Ty->getNullability(*this)) {
5631 Result = const_cast<ASTContext *>(this)->getAttributedType(
5632 AttributedType::getNullabilityAttrKind(*Nullability), Result, Result);
5633 }
5634 return Result;
Chris Lattnera21ad802008-04-02 05:18:44 +00005635}
5636
John McCall33ddac02011-01-19 10:06:00 +00005637QualType ASTContext::getBaseElementType(const ArrayType *array) const {
5638 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00005639}
5640
John McCall33ddac02011-01-19 10:06:00 +00005641QualType ASTContext::getBaseElementType(QualType type) const {
5642 Qualifiers qs;
5643 while (true) {
5644 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00005645 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00005646 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00005647
John McCall33ddac02011-01-19 10:06:00 +00005648 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00005649 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00005650 }
Mike Stump11289f42009-09-09 15:08:12 +00005651
John McCall33ddac02011-01-19 10:06:00 +00005652 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00005653}
5654
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00005655/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00005656uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00005657ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
5658 uint64_t ElementCount = 1;
5659 do {
5660 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00005661 CA = dyn_cast_or_null<ConstantArrayType>(
5662 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00005663 } while (CA);
5664 return ElementCount;
5665}
5666
Steve Naroff0af91202007-04-27 21:51:21 +00005667/// getFloatingRank - Return a relative rank for floating point types.
5668/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00005669static FloatingRank getFloatingRank(QualType T) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00005670 if (const auto *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00005671 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00005672
John McCall9dd450b2009-09-21 23:43:11 +00005673 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
5674 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00005675 default: llvm_unreachable("getFloatingRank(): not a floating type");
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00005676 case BuiltinType::Float16: return Float16Rank;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00005677 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00005678 case BuiltinType::Float: return FloatRank;
5679 case BuiltinType::Double: return DoubleRank;
5680 case BuiltinType::LongDouble: return LongDoubleRank;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005681 case BuiltinType::Float128: return Float128Rank;
Steve Naroffe4718892007-04-27 18:30:00 +00005682 }
5683}
5684
Mike Stump11289f42009-09-09 15:08:12 +00005685/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
5686/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00005687/// 'typeDomain' is a real floating point or complex type.
5688/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00005689QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
5690 QualType Domain) const {
5691 FloatingRank EltRank = getFloatingRank(Size);
5692 if (Domain->isComplexType()) {
5693 switch (EltRank) {
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00005694 case Float16Rank:
David Blaikief47fa302012-01-17 02:30:50 +00005695 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00005696 case FloatRank: return FloatComplexTy;
5697 case DoubleRank: return DoubleComplexTy;
5698 case LongDoubleRank: return LongDoubleComplexTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005699 case Float128Rank: return Float128ComplexTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00005700 }
Steve Naroff0af91202007-04-27 21:51:21 +00005701 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00005702
5703 assert(Domain->isRealFloatingType() && "Unknown domain!");
5704 switch (EltRank) {
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00005705 case Float16Rank: return HalfTy;
Joey Goulydd7f4562013-01-23 11:56:20 +00005706 case HalfRank: return HalfTy;
Chris Lattnerb9dfb032008-04-06 23:58:54 +00005707 case FloatRank: return FloatTy;
5708 case DoubleRank: return DoubleTy;
5709 case LongDoubleRank: return LongDoubleTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005710 case Float128Rank: return Float128Ty;
Steve Naroff9091ef72007-08-27 01:27:54 +00005711 }
David Blaikief47fa302012-01-17 02:30:50 +00005712 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00005713}
5714
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005715/// getFloatingTypeOrder - Compare the rank of the two specified floating
5716/// point types, ignoring the domain of the type (i.e. 'double' ==
5717/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00005718/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00005719int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00005720 FloatingRank LHSR = getFloatingRank(LHS);
5721 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00005722
Chris Lattnerb90739d2008-04-06 23:38:49 +00005723 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00005724 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00005725 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00005726 return 1;
5727 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00005728}
5729
Erik Pilkingtoneac7c3f2019-02-16 01:11:47 +00005730int ASTContext::getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const {
5731 if (&getFloatTypeSemantics(LHS) == &getFloatTypeSemantics(RHS))
5732 return 0;
5733 return getFloatingTypeOrder(LHS, RHS);
5734}
5735
Chris Lattner76a00cf2008-04-06 22:59:24 +00005736/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
5737/// routine will assert if passed a built-in type that isn't an integer or enum,
5738/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00005739unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00005740 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00005741
Chris Lattner76a00cf2008-04-06 22:59:24 +00005742 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00005743 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005744 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005745 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005746 case BuiltinType::Char_S:
5747 case BuiltinType::Char_U:
5748 case BuiltinType::SChar:
5749 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005750 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005751 case BuiltinType::Short:
5752 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005753 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005754 case BuiltinType::Int:
5755 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005756 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005757 case BuiltinType::Long:
5758 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005759 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005760 case BuiltinType::LongLong:
5761 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005762 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00005763 case BuiltinType::Int128:
5764 case BuiltinType::UInt128:
5765 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00005766 }
5767}
5768
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005769/// Whether this is a promotable bitfield reference according
Eli Friedman629ffb92009-08-20 04:21:42 +00005770/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
5771///
5772/// \returns the type this bit-field will promote to, or NULL if no
5773/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00005774QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00005775 if (E->isTypeDependent() || E->isValueDependent())
Eugene Zelenko7855e772018-04-03 00:11:50 +00005776 return {};
Richard Smith5b571672014-09-24 23:55:00 +00005777
Richard Smithaadb2542018-06-28 21:17:55 +00005778 // C++ [conv.prom]p5:
5779 // If the bit-field has an enumerated type, it is treated as any other
5780 // value of that type for promotion purposes.
5781 if (getLangOpts().CPlusPlus && E->getType()->isEnumeralType())
5782 return {};
5783
Richard Smith5b571672014-09-24 23:55:00 +00005784 // FIXME: We should not do this unless E->refersToBitField() is true. This
5785 // matters in C where getSourceBitField() will find bit-fields for various
5786 // cases where the source expression is not a bit-field designator.
5787
John McCalld25db7e2013-05-06 21:39:12 +00005788 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman629ffb92009-08-20 04:21:42 +00005789 if (!Field)
Eugene Zelenko7855e772018-04-03 00:11:50 +00005790 return {};
Eli Friedman629ffb92009-08-20 04:21:42 +00005791
5792 QualType FT = Field->getType();
5793
Richard Smithcaf33902011-10-10 18:28:20 +00005794 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00005795 uint64_t IntSize = getTypeSize(IntTy);
Richard Smith5b571672014-09-24 23:55:00 +00005796 // C++ [conv.prom]p5:
5797 // A prvalue for an integral bit-field can be converted to a prvalue of type
5798 // int if int can represent all the values of the bit-field; otherwise, it
5799 // can be converted to unsigned int if unsigned int can represent all the
5800 // values of the bit-field. If the bit-field is larger yet, no integral
5801 // promotion applies to it.
5802 // C11 6.3.1.1/2:
5803 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
5804 // If an int can represent all values of the original type (as restricted by
5805 // the width, for a bit-field), the value is converted to an int; otherwise,
5806 // it is converted to an unsigned int.
5807 //
5808 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
5809 // We perform that promotion here to match GCC and C++.
Richard Smithaadb2542018-06-28 21:17:55 +00005810 // FIXME: C does not permit promotion of an enum bit-field whose rank is
5811 // greater than that of 'int'. We perform that promotion to match GCC.
Eli Friedman629ffb92009-08-20 04:21:42 +00005812 if (BitWidth < IntSize)
5813 return IntTy;
5814
5815 if (BitWidth == IntSize)
5816 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
5817
Richard Smithaadb2542018-06-28 21:17:55 +00005818 // Bit-fields wider than int are not subject to promotions, and therefore act
Richard Smith5b571672014-09-24 23:55:00 +00005819 // like the base type. GCC has some weird bugs in this area that we
5820 // deliberately do not follow (GCC follows a pre-standard resolution to
5821 // C's DR315 which treats bit-width as being part of the type, and this leaks
5822 // into their semantics in some cases).
Eugene Zelenko7855e772018-04-03 00:11:50 +00005823 return {};
Eli Friedman629ffb92009-08-20 04:21:42 +00005824}
5825
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005826/// getPromotedIntegerType - Returns the type that Promotable will
5827/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
5828/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00005829QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005830 assert(!Promotable.isNull());
5831 assert(Promotable->isPromotableIntegerType());
Eugene Zelenko7855e772018-04-03 00:11:50 +00005832 if (const auto *ET = Promotable->getAs<EnumType>())
John McCall56774992009-12-09 09:09:27 +00005833 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00005834
Eugene Zelenko7855e772018-04-03 00:11:50 +00005835 if (const auto *BT = Promotable->getAs<BuiltinType>()) {
Eli Friedman3f37c1c2011-10-26 07:22:48 +00005836 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
5837 // (3.9.1) can be converted to a prvalue of the first of the following
5838 // types that can represent all the values of its underlying type:
5839 // int, unsigned int, long int, unsigned long int, long long int, or
5840 // unsigned long long int [...]
5841 // FIXME: Is there some better way to compute this?
5842 if (BT->getKind() == BuiltinType::WChar_S ||
5843 BT->getKind() == BuiltinType::WChar_U ||
Richard Smith3a8244d2018-05-01 05:02:45 +00005844 BT->getKind() == BuiltinType::Char8 ||
Eli Friedman3f37c1c2011-10-26 07:22:48 +00005845 BT->getKind() == BuiltinType::Char16 ||
5846 BT->getKind() == BuiltinType::Char32) {
5847 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
5848 uint64_t FromSize = getTypeSize(BT);
5849 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
5850 LongLongTy, UnsignedLongLongTy };
5851 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
5852 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
5853 if (FromSize < ToSize ||
5854 (FromSize == ToSize &&
5855 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
5856 return PromoteTypes[Idx];
5857 }
5858 llvm_unreachable("char type should fit into long long");
5859 }
5860 }
5861
5862 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005863 if (Promotable->isSignedIntegerType())
5864 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00005865 uint64_t PromotableSize = getIntWidth(Promotable);
5866 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005867 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
5868 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
5869}
5870
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005871/// Recurses in pointer/array types until it finds an objc retainable
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00005872/// type and returns its ownership.
5873Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
5874 while (!T.isNull()) {
5875 if (T.getObjCLifetime() != Qualifiers::OCL_None)
5876 return T.getObjCLifetime();
5877 if (T->isArrayType())
5878 T = getBaseElementType(T);
Eugene Zelenko7855e772018-04-03 00:11:50 +00005879 else if (const auto *PT = T->getAs<PointerType>())
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00005880 T = PT->getPointeeType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00005881 else if (const auto *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00005882 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00005883 else
5884 break;
5885 }
5886
5887 return Qualifiers::OCL_None;
5888}
5889
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005890static const Type *getIntegerTypeForEnum(const EnumType *ET) {
5891 // Incomplete enum types are not treated as integer types.
5892 // FIXME: In C++, enum types are never integer types.
5893 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
5894 return ET->getDecl()->getIntegerType().getTypePtr();
Craig Topper36250ad2014-05-12 05:36:57 +00005895 return nullptr;
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005896}
5897
Mike Stump11289f42009-09-09 15:08:12 +00005898/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005899/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00005900/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00005901int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00005902 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
5903 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005904
5905 // Unwrap enums to their underlying type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00005906 if (const auto *ET = dyn_cast<EnumType>(LHSC))
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005907 LHSC = getIntegerTypeForEnum(ET);
Eugene Zelenko7855e772018-04-03 00:11:50 +00005908 if (const auto *ET = dyn_cast<EnumType>(RHSC))
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005909 RHSC = getIntegerTypeForEnum(ET);
5910
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005911 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00005912
Chris Lattner76a00cf2008-04-06 22:59:24 +00005913 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
5914 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00005915
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005916 unsigned LHSRank = getIntegerRank(LHSC);
5917 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00005918
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005919 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
5920 if (LHSRank == RHSRank) return 0;
5921 return LHSRank > RHSRank ? 1 : -1;
5922 }
Mike Stump11289f42009-09-09 15:08:12 +00005923
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005924 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
5925 if (LHSUnsigned) {
5926 // If the unsigned [LHS] type is larger, return it.
5927 if (LHSRank >= RHSRank)
5928 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00005929
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005930 // If the signed type can represent all values of the unsigned type, it
5931 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00005932 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005933 return -1;
5934 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00005935
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005936 // If the unsigned [RHS] type is larger, return it.
5937 if (RHSRank >= LHSRank)
5938 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00005939
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005940 // If the signed type can represent all values of the unsigned type, it
5941 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00005942 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005943 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00005944}
Anders Carlsson98f07902007-08-17 05:31:46 +00005945
Ben Langmuirf5416742016-02-04 00:55:24 +00005946TypedefDecl *ASTContext::getCFConstantStringDecl() const {
Saleem Abdulrasoolef9b88a2018-10-24 16:38:16 +00005947 if (CFConstantStringTypeDecl)
5948 return CFConstantStringTypeDecl;
Anders Carlsson6d417272009-11-14 21:45:58 +00005949
Saleem Abdulrasoolef9b88a2018-10-24 16:38:16 +00005950 assert(!CFConstantStringTagDecl &&
5951 "tag and typedef should be initialized together");
5952 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
5953 CFConstantStringTagDecl->startDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00005954
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00005955 struct {
5956 QualType Type;
5957 const char *Name;
5958 } Fields[5];
5959 unsigned Count = 0;
Mike Stump11289f42009-09-09 15:08:12 +00005960
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00005961 /// Objective-C ABI
5962 ///
5963 /// typedef struct __NSConstantString_tag {
Saleem Abdulrasool1f6c41f2018-10-27 06:12:52 +00005964 /// const int *isa;
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00005965 /// int flags;
5966 /// const char *str;
5967 /// long length;
5968 /// } __NSConstantString;
5969 ///
5970 /// Swift ABI (4.1, 4.2)
5971 ///
5972 /// typedef struct __NSConstantString_tag {
5973 /// uintptr_t _cfisa;
5974 /// uintptr_t _swift_rc;
5975 /// _Atomic(uint64_t) _cfinfoa;
5976 /// const char *_ptr;
5977 /// uint32_t _length;
5978 /// } __NSConstantString;
5979 ///
5980 /// Swift ABI (5.0)
5981 ///
5982 /// typedef struct __NSConstantString_tag {
5983 /// uintptr_t _cfisa;
5984 /// uintptr_t _swift_rc;
5985 /// _Atomic(uint64_t) _cfinfoa;
5986 /// const char *_ptr;
5987 /// uintptr_t _length;
5988 /// } __NSConstantString;
5989
5990 const auto CFRuntime = getLangOpts().CFRuntime;
5991 if (static_cast<unsigned>(CFRuntime) <
5992 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) {
5993 Fields[Count++] = { getPointerType(IntTy.withConst()), "isa" };
5994 Fields[Count++] = { IntTy, "flags" };
5995 Fields[Count++] = { getPointerType(CharTy.withConst()), "str" };
5996 Fields[Count++] = { LongTy, "length" };
5997 } else {
5998 Fields[Count++] = { getUIntPtrType(), "_cfisa" };
5999 Fields[Count++] = { getUIntPtrType(), "_swift_rc" };
6000 Fields[Count++] = { getFromTargetType(Target->getUInt64Type()), "_swift_rc" };
6001 Fields[Count++] = { getPointerType(CharTy.withConst()), "_ptr" };
6002 if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 ||
6003 CFRuntime == LangOptions::CoreFoundationABI::Swift4_2)
6004 Fields[Count++] = { IntTy, "_ptr" };
6005 else
6006 Fields[Count++] = { getUIntPtrType(), "_ptr" };
6007 }
Douglas Gregor91f84212008-12-11 16:49:14 +00006008
Saleem Abdulrasoolef9b88a2018-10-24 16:38:16 +00006009 // Create fields
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00006010 for (unsigned i = 0; i < Count; ++i) {
Saleem Abdulrasoolef9b88a2018-10-24 16:38:16 +00006011 FieldDecl *Field =
6012 FieldDecl::Create(*this, CFConstantStringTagDecl, SourceLocation(),
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00006013 SourceLocation(), &Idents.get(Fields[i].Name),
6014 Fields[i].Type, /*TInfo=*/nullptr,
Saleem Abdulrasoolef9b88a2018-10-24 16:38:16 +00006015 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
6016 Field->setAccess(AS_public);
6017 CFConstantStringTagDecl->addDecl(Field);
Anders Carlsson98f07902007-08-17 05:31:46 +00006018 }
Mike Stump11289f42009-09-09 15:08:12 +00006019
Saleem Abdulrasoolef9b88a2018-10-24 16:38:16 +00006020 CFConstantStringTagDecl->completeDefinition();
6021 // This type is designed to be compatible with NSConstantString, but cannot
6022 // use the same name, since NSConstantString is an interface.
6023 auto tagType = getTagDeclType(CFConstantStringTagDecl);
6024 CFConstantStringTypeDecl =
6025 buildImplicitTypedef(tagType, "__NSConstantString");
6026
Quentin Colombet043406b2016-02-03 22:41:00 +00006027 return CFConstantStringTypeDecl;
6028}
6029
Ben Langmuirf5416742016-02-04 00:55:24 +00006030RecordDecl *ASTContext::getCFConstantStringTagDecl() const {
6031 if (!CFConstantStringTagDecl)
6032 getCFConstantStringDecl(); // Build the tag and the typedef.
6033 return CFConstantStringTagDecl;
6034}
6035
Quentin Colombet043406b2016-02-03 22:41:00 +00006036// getCFConstantStringType - Return the type used for constant CFStrings.
6037QualType ASTContext::getCFConstantStringType() const {
Ben Langmuirf5416742016-02-04 00:55:24 +00006038 return getTypedefType(getCFConstantStringDecl());
Gabor Greif412af032007-09-11 15:32:40 +00006039}
Anders Carlsson87c149b2007-10-11 01:00:40 +00006040
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00006041QualType ASTContext::getObjCSuperType() const {
6042 if (ObjCSuperType.isNull()) {
Alp Toker2dea15b2013-12-17 01:22:38 +00006043 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00006044 TUDecl->addDecl(ObjCSuperTypeDecl);
6045 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
6046 }
6047 return ObjCSuperType;
6048}
6049
Douglas Gregor512b0772009-04-23 22:29:11 +00006050void ASTContext::setCFConstantStringType(QualType T) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006051 const auto *TD = T->getAs<TypedefType>();
Ben Langmuirf5416742016-02-04 00:55:24 +00006052 assert(TD && "Invalid CFConstantStringType");
6053 CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl());
Eugene Zelenko7855e772018-04-03 00:11:50 +00006054 const auto *TagType =
Ben Langmuirf5416742016-02-04 00:55:24 +00006055 CFConstantStringTypeDecl->getUnderlyingType()->getAs<RecordType>();
6056 assert(TagType && "Invalid CFConstantStringType");
6057 CFConstantStringTagDecl = TagType->getDecl();
Douglas Gregor512b0772009-04-23 22:29:11 +00006058}
6059
Jay Foad39c79802011-01-12 09:06:06 +00006060QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00006061 if (BlockDescriptorType)
6062 return getTagDeclType(BlockDescriptorType);
6063
Alp Toker2dea15b2013-12-17 01:22:38 +00006064 RecordDecl *RD;
Mike Stumpd0153282009-10-20 02:12:22 +00006065 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00006066 RD = buildImplicitRecord("__block_descriptor");
6067 RD->startDefinition();
6068
Mike Stumpd0153282009-10-20 02:12:22 +00006069 QualType FieldTypes[] = {
6070 UnsignedLongTy,
6071 UnsignedLongTy,
6072 };
6073
Craig Topperd6d31ac2013-07-15 08:24:27 +00006074 static const char *const FieldNames[] = {
Mike Stumpd0153282009-10-20 02:12:22 +00006075 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00006076 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00006077 };
6078
6079 for (size_t i = 0; i < 2; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00006080 FieldDecl *Field = FieldDecl::Create(
6081 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00006082 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
6083 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00006084 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00006085 RD->addDecl(Field);
Mike Stumpd0153282009-10-20 02:12:22 +00006086 }
6087
Alp Toker2dea15b2013-12-17 01:22:38 +00006088 RD->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00006089
Alp Toker2dea15b2013-12-17 01:22:38 +00006090 BlockDescriptorType = RD;
Mike Stumpd0153282009-10-20 02:12:22 +00006091
6092 return getTagDeclType(BlockDescriptorType);
6093}
6094
Jay Foad39c79802011-01-12 09:06:06 +00006095QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00006096 if (BlockDescriptorExtendedType)
6097 return getTagDeclType(BlockDescriptorExtendedType);
6098
Alp Toker2dea15b2013-12-17 01:22:38 +00006099 RecordDecl *RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00006100 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00006101 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
6102 RD->startDefinition();
6103
Mike Stumpe1b19ba2009-10-22 00:49:09 +00006104 QualType FieldTypes[] = {
6105 UnsignedLongTy,
6106 UnsignedLongTy,
6107 getPointerType(VoidPtrTy),
6108 getPointerType(VoidPtrTy)
6109 };
6110
Craig Topperd6d31ac2013-07-15 08:24:27 +00006111 static const char *const FieldNames[] = {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00006112 "reserved",
6113 "Size",
6114 "CopyFuncPtr",
6115 "DestroyFuncPtr"
6116 };
6117
6118 for (size_t i = 0; i < 4; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00006119 FieldDecl *Field = FieldDecl::Create(
6120 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00006121 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
6122 /*BitWidth=*/nullptr,
Alp Toker2dea15b2013-12-17 01:22:38 +00006123 /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00006124 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00006125 RD->addDecl(Field);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00006126 }
6127
Alp Toker2dea15b2013-12-17 01:22:38 +00006128 RD->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00006129
Alp Toker2dea15b2013-12-17 01:22:38 +00006130 BlockDescriptorExtendedType = RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00006131 return getTagDeclType(BlockDescriptorExtendedType);
6132}
6133
Sven van Haastregt3bb7eaf2017-12-06 10:11:28 +00006134TargetInfo::OpenCLTypeKind ASTContext::getOpenCLTypeKind(const Type *T) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006135 const auto *BT = dyn_cast<BuiltinType>(T);
Sven van Haastregt3bb7eaf2017-12-06 10:11:28 +00006136
6137 if (!BT) {
6138 if (isa<PipeType>(T))
6139 return TargetInfo::OCLTK_Pipe;
6140
6141 return TargetInfo::OCLTK_Default;
6142 }
6143
6144 switch (BT->getKind()) {
6145#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6146 case BuiltinType::Id: \
6147 return TargetInfo::OCLTK_Image;
6148#include "clang/Basic/OpenCLImageTypes.def"
6149
6150 case BuiltinType::OCLClkEvent:
6151 return TargetInfo::OCLTK_ClkEvent;
6152
6153 case BuiltinType::OCLEvent:
6154 return TargetInfo::OCLTK_Event;
6155
6156 case BuiltinType::OCLQueue:
6157 return TargetInfo::OCLTK_Queue;
6158
6159 case BuiltinType::OCLReserveID:
6160 return TargetInfo::OCLTK_ReserveID;
6161
6162 case BuiltinType::OCLSampler:
6163 return TargetInfo::OCLTK_Sampler;
6164
6165 default:
6166 return TargetInfo::OCLTK_Default;
6167 }
6168}
6169
6170LangAS ASTContext::getOpenCLTypeAddrSpace(const Type *T) const {
6171 return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
6172}
6173
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006174/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
6175/// requires copy/dispose. Note that this must match the logic
6176/// in buildByrefHelpers.
6177bool ASTContext::BlockRequiresCopying(QualType Ty,
6178 const VarDecl *D) {
6179 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
Akira Hatanaka9978da32018-08-10 15:09:24 +00006180 const Expr *copyExpr = getBlockVarCopyInit(D).getCopyExpr();
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006181 if (!copyExpr && record->hasTrivialDestructor()) return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00006182
Mike Stump94967902009-10-21 18:16:27 +00006183 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00006184 }
Fangrui Song6907ce22018-07-30 19:24:48 +00006185
Akira Hatanaka7275da02018-02-28 07:15:55 +00006186 // The block needs copy/destroy helpers if Ty is non-trivial to destructively
6187 // move or destroy.
6188 if (Ty.isNonTrivialToPrimitiveDestructiveMove() || Ty.isDestructedType())
6189 return true;
6190
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006191 if (!Ty->isObjCRetainableType()) return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00006192
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006193 Qualifiers qs = Ty.getQualifiers();
Fangrui Song6907ce22018-07-30 19:24:48 +00006194
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006195 // If we have lifetime, that dominates.
6196 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006197 switch (lifetime) {
6198 case Qualifiers::OCL_None: llvm_unreachable("impossible");
Fangrui Song6907ce22018-07-30 19:24:48 +00006199
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006200 // These are just bits as far as the runtime is concerned.
6201 case Qualifiers::OCL_ExplicitNone:
6202 case Qualifiers::OCL_Autoreleasing:
6203 return false;
Akira Hatanaka7275da02018-02-28 07:15:55 +00006204
6205 // These cases should have been taken care of when checking the type's
6206 // non-triviality.
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006207 case Qualifiers::OCL_Weak:
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006208 case Qualifiers::OCL_Strong:
Akira Hatanaka7275da02018-02-28 07:15:55 +00006209 llvm_unreachable("impossible");
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006210 }
6211 llvm_unreachable("fell out of lifetime switch!");
6212 }
6213 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
6214 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00006215}
6216
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006217bool ASTContext::getByrefLifetime(QualType Ty,
6218 Qualifiers::ObjCLifetime &LifeTime,
6219 bool &HasByrefExtendedLayout) const {
Erik Pilkingtonfa983902018-10-30 20:31:30 +00006220 if (!getLangOpts().ObjC ||
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006221 getLangOpts().getGC() != LangOptions::NonGC)
6222 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00006223
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006224 HasByrefExtendedLayout = false;
Fariborz Jahanianf762b722012-12-11 19:58:01 +00006225 if (Ty->isRecordType()) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006226 HasByrefExtendedLayout = true;
6227 LifeTime = Qualifiers::OCL_None;
John McCall460ce582015-10-22 18:38:17 +00006228 } else if ((LifeTime = Ty.getObjCLifetime())) {
6229 // Honor the ARC qualifiers.
6230 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
6231 // The MRR rule.
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006232 LifeTime = Qualifiers::OCL_ExplicitNone;
John McCall460ce582015-10-22 18:38:17 +00006233 } else {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006234 LifeTime = Qualifiers::OCL_None;
John McCall460ce582015-10-22 18:38:17 +00006235 }
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006236 return true;
6237}
6238
Douglas Gregorbab8a962011-09-08 01:46:34 +00006239TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
6240 if (!ObjCInstanceTypeDecl)
Alp Toker56b5cc92013-12-15 10:36:26 +00006241 ObjCInstanceTypeDecl =
6242 buildImplicitTypedef(getObjCIdType(), "instancetype");
Douglas Gregorbab8a962011-09-08 01:46:34 +00006243 return ObjCInstanceTypeDecl;
6244}
6245
Anders Carlsson18acd442007-10-29 06:33:42 +00006246// This returns true if a type has been typedefed to BOOL:
6247// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00006248static bool isTypeTypedefedAsBOOL(QualType T) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006249 if (const auto *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00006250 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
6251 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00006252
Anders Carlssond8499822007-10-29 05:01:08 +00006253 return false;
6254}
6255
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006256/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006257/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00006258CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00006259 if (!type->isIncompleteArrayType() && type->isIncompleteType())
6260 return CharUnits::Zero();
Fangrui Song6907ce22018-07-30 19:24:48 +00006261
Ken Dyck40775002010-01-11 17:06:35 +00006262 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00006263
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006264 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00006265 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00006266 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006267 // Treat arrays as pointers, since that's how they're passed in.
6268 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00006269 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00006270 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00006271}
6272
Hans Wennborg56fc62b2014-07-17 20:25:23 +00006273bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
David Majnemer3f021502015-10-08 04:53:31 +00006274 return getTargetInfo().getCXXABI().isMicrosoft() &&
6275 VD->isStaticDataMember() &&
Hans Wennborgb18da9b2018-02-20 12:43:02 +00006276 VD->getType()->isIntegralOrEnumerationType() &&
David Majnemerfac52432015-10-19 23:22:49 +00006277 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
Hans Wennborg56fc62b2014-07-17 20:25:23 +00006278}
6279
Richard Smithd9b90092016-07-02 01:32:16 +00006280ASTContext::InlineVariableDefinitionKind
6281ASTContext::getInlineVariableDefinitionKind(const VarDecl *VD) const {
6282 if (!VD->isInline())
6283 return InlineVariableDefinitionKind::None;
6284
6285 // In almost all cases, it's a weak definition.
6286 auto *First = VD->getFirstDecl();
Richard Smith8910fe62017-10-23 03:58:34 +00006287 if (First->isInlineSpecified() || !First->isStaticDataMember())
Richard Smithd9b90092016-07-02 01:32:16 +00006288 return InlineVariableDefinitionKind::Weak;
6289
6290 // If there's a file-context declaration in this translation unit, it's a
6291 // non-discardable definition.
6292 for (auto *D : VD->redecls())
Richard Smith8910fe62017-10-23 03:58:34 +00006293 if (D->getLexicalDeclContext()->isFileContext() &&
6294 !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr()))
Richard Smithd9b90092016-07-02 01:32:16 +00006295 return InlineVariableDefinitionKind::Strong;
6296
6297 // If we've not seen one yet, we don't know.
6298 return InlineVariableDefinitionKind::WeakUnknown;
6299}
6300
Eugene Zelenko7855e772018-04-03 00:11:50 +00006301static std::string charUnitsToString(const CharUnits &CU) {
Ken Dyck40775002010-01-11 17:06:35 +00006302 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006303}
6304
John McCall351762c2011-02-07 10:33:21 +00006305/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00006306/// declaration.
John McCall351762c2011-02-07 10:33:21 +00006307std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
6308 std::string S;
6309
David Chisnall950a9512009-11-17 19:33:30 +00006310 const BlockDecl *Decl = Expr->getBlockDecl();
6311 QualType BlockTy =
6312 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
6313 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00006314 if (getLangOpts().EncodeExtendedBlockSig)
Alp Toker314cc812014-01-25 16:55:45 +00006315 getObjCEncodingForMethodParameter(
6316 Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
6317 true /*Extended*/);
Fariborz Jahanian64223e62012-11-14 23:11:38 +00006318 else
Alp Toker314cc812014-01-25 16:55:45 +00006319 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00006320 // Compute size of all parameters.
6321 // Start with computing size of a pointer in number of bytes.
6322 // FIXME: There might(should) be a better way of doing this computation!
Ken Dyck40775002010-01-11 17:06:35 +00006323 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
6324 CharUnits ParmOffset = PtrSize;
David Majnemer59f77922016-06-24 04:05:48 +00006325 for (auto PI : Decl->parameters()) {
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00006326 QualType PType = PI->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00006327 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00006328 if (sz.isZero())
6329 continue;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00006330 assert(sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00006331 ParmOffset += sz;
6332 }
6333 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00006334 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00006335 // Block pointer and offset.
6336 S += "@?0";
Fangrui Song6907ce22018-07-30 19:24:48 +00006337
David Chisnall950a9512009-11-17 19:33:30 +00006338 // Argument types.
6339 ParmOffset = PtrSize;
David Majnemer59f77922016-06-24 04:05:48 +00006340 for (auto PVDecl : Decl->parameters()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00006341 QualType PType = PVDecl->getOriginalType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00006342 if (const auto *AT =
6343 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
David Chisnall950a9512009-11-17 19:33:30 +00006344 // Use array's original type only if it has known number of
6345 // elements.
6346 if (!isa<ConstantArrayType>(AT))
6347 PType = PVDecl->getType();
6348 } else if (PType->isFunctionType())
6349 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00006350 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00006351 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
6352 S, true /*Extended*/);
6353 else
6354 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00006355 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00006356 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00006357 }
John McCall351762c2011-02-07 10:33:21 +00006358
6359 return S;
David Chisnall950a9512009-11-17 19:33:30 +00006360}
6361
John McCall843dfcc2016-11-29 21:57:00 +00006362std::string
6363ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const {
6364 std::string S;
David Chisnall50e4eba2010-12-30 14:05:53 +00006365 // Encode result type.
Alp Toker314cc812014-01-25 16:55:45 +00006366 getObjCEncodingForType(Decl->getReturnType(), S);
David Chisnall50e4eba2010-12-30 14:05:53 +00006367 CharUnits ParmOffset;
6368 // Compute size of all parameters.
David Majnemer59f77922016-06-24 04:05:48 +00006369 for (auto PI : Decl->parameters()) {
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00006370 QualType PType = PI->getType();
David Chisnall50e4eba2010-12-30 14:05:53 +00006371 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00006372 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00006373 continue;
Fangrui Song6907ce22018-07-30 19:24:48 +00006374
6375 assert(sz.isPositive() &&
John McCall843dfcc2016-11-29 21:57:00 +00006376 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00006377 ParmOffset += sz;
6378 }
6379 S += charUnitsToString(ParmOffset);
6380 ParmOffset = CharUnits::Zero();
6381
6382 // Argument types.
David Majnemer59f77922016-06-24 04:05:48 +00006383 for (auto PVDecl : Decl->parameters()) {
David Chisnall50e4eba2010-12-30 14:05:53 +00006384 QualType PType = PVDecl->getOriginalType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00006385 if (const auto *AT =
6386 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
David Chisnall50e4eba2010-12-30 14:05:53 +00006387 // Use array's original type only if it has known number of
6388 // elements.
6389 if (!isa<ConstantArrayType>(AT))
6390 PType = PVDecl->getType();
6391 } else if (PType->isFunctionType())
6392 PType = PVDecl->getType();
6393 getObjCEncodingForType(PType, S);
6394 S += charUnitsToString(ParmOffset);
6395 ParmOffset += getObjCEncodingTypeSize(PType);
6396 }
Fangrui Song6907ce22018-07-30 19:24:48 +00006397
John McCall843dfcc2016-11-29 21:57:00 +00006398 return S;
David Chisnall50e4eba2010-12-30 14:05:53 +00006399}
6400
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006401/// getObjCEncodingForMethodParameter - Return the encoded type for a single
Fangrui Song6907ce22018-07-30 19:24:48 +00006402/// method parameter or return type. If Extended, include class names and
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006403/// block object types.
6404void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
6405 QualType T, std::string& S,
6406 bool Extended) const {
6407 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
6408 getObjCEncodingForTypeQualifier(QT, S);
6409 // Encode parameter type.
Nico Weber2e9591c2019-05-14 12:32:37 +00006410 ObjCEncOptions Options = ObjCEncOptions()
6411 .setExpandPointedToStructures()
6412 .setExpandStructures()
6413 .setIsOutermostType();
6414 if (Extended)
6415 Options.setEncodeBlockParameters().setEncodeClassNames();
6416 getObjCEncodingForTypeImpl(T, S, Options, /*Field=*/nullptr);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006417}
6418
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006419/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006420/// declaration.
John McCall843dfcc2016-11-29 21:57:00 +00006421std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
6422 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00006423 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006424 // Encode return type.
John McCall843dfcc2016-11-29 21:57:00 +00006425 std::string S;
Alp Toker314cc812014-01-25 16:55:45 +00006426 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
6427 Decl->getReturnType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006428 // Compute size of all parameters.
6429 // Start with computing size of a pointer in number of bytes.
6430 // FIXME: There might(should) be a better way of doing this computation!
Ken Dyck40775002010-01-11 17:06:35 +00006431 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006432 // The first two arguments (self and _cmd) are pointers; account for
6433 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00006434 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00006435 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00006436 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00006437 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00006438 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00006439 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00006440 continue;
Fangrui Song6907ce22018-07-30 19:24:48 +00006441
6442 assert(sz.isPositive() &&
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00006443 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006444 ParmOffset += sz;
6445 }
Ken Dyck40775002010-01-11 17:06:35 +00006446 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006447 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00006448 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00006449
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006450 // Argument types.
6451 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00006452 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00006453 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00006454 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00006455 QualType PType = PVDecl->getOriginalType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00006456 if (const auto *AT =
6457 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
Steve Naroffe4e55d22009-04-14 00:03:58 +00006458 // Use array's original type only if it has known number of
6459 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00006460 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00006461 PType = PVDecl->getType();
6462 } else if (PType->isFunctionType())
6463 PType = PVDecl->getType();
Fangrui Song6907ce22018-07-30 19:24:48 +00006464 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006465 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00006466 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00006467 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006468 }
Fangrui Song6907ce22018-07-30 19:24:48 +00006469
John McCall843dfcc2016-11-29 21:57:00 +00006470 return S;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006471}
6472
Fariborz Jahaniandad96302014-01-22 19:02:20 +00006473ObjCPropertyImplDecl *
6474ASTContext::getObjCPropertyImplDeclForPropertyDecl(
6475 const ObjCPropertyDecl *PD,
6476 const Decl *Container) const {
6477 if (!Container)
Craig Topper36250ad2014-05-12 05:36:57 +00006478 return nullptr;
Eugene Zelenko7855e772018-04-03 00:11:50 +00006479 if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) {
Aaron Ballmand85eff42014-03-14 15:02:45 +00006480 for (auto *PID : CID->property_impls())
6481 if (PID->getPropertyDecl() == PD)
6482 return PID;
Craig Topper36250ad2014-05-12 05:36:57 +00006483 } else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006484 const auto *OID = cast<ObjCImplementationDecl>(Container);
Craig Topper36250ad2014-05-12 05:36:57 +00006485 for (auto *PID : OID->property_impls())
6486 if (PID->getPropertyDecl() == PD)
6487 return PID;
6488 }
6489 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00006490}
6491
Daniel Dunbar4932b362008-08-28 04:38:10 +00006492/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00006493/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00006494/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
6495/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00006496/// Property attributes are stored as a comma-delimited C string. The simple
6497/// attributes readonly and bycopy are encoded as single characters. The
6498/// parametrized attributes, getter=name, setter=name, and ivar=name, are
6499/// encoded as single characters, followed by an identifier. Property types
6500/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00006501/// these attributes are defined by the following enumeration:
6502/// @code
6503/// enum PropertyAttributes {
6504/// kPropertyReadOnly = 'R', // property is read-only.
6505/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
6506/// kPropertyByref = '&', // property is a reference to the value last assigned
6507/// kPropertyDynamic = 'D', // property is dynamic
6508/// kPropertyGetter = 'G', // followed by getter selector name
6509/// kPropertySetter = 'S', // followed by setter selector name
6510/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00006511/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00006512/// kPropertyWeak = 'W' // 'weak' property
6513/// kPropertyStrong = 'P' // property GC'able
6514/// kPropertyNonAtomic = 'N' // property non-atomic
6515/// };
6516/// @endcode
John McCall843dfcc2016-11-29 21:57:00 +00006517std::string
6518ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
6519 const Decl *Container) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00006520 // Collect information from the property implementation decl(s).
6521 bool Dynamic = false;
Craig Topper36250ad2014-05-12 05:36:57 +00006522 ObjCPropertyImplDecl *SynthesizePID = nullptr;
Daniel Dunbar4932b362008-08-28 04:38:10 +00006523
Fariborz Jahaniandad96302014-01-22 19:02:20 +00006524 if (ObjCPropertyImplDecl *PropertyImpDecl =
6525 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
6526 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
6527 Dynamic = true;
6528 else
6529 SynthesizePID = PropertyImpDecl;
Daniel Dunbar4932b362008-08-28 04:38:10 +00006530 }
6531
6532 // FIXME: This is not very efficient.
John McCall843dfcc2016-11-29 21:57:00 +00006533 std::string S = "T";
Daniel Dunbar4932b362008-08-28 04:38:10 +00006534
6535 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00006536 // GCC has some special rules regarding encoding of properties which
6537 // closely resembles encoding of ivars.
Joe Groff98ac7d22014-07-07 22:25:15 +00006538 getObjCEncodingForPropertyType(PD->getType(), S);
Daniel Dunbar4932b362008-08-28 04:38:10 +00006539
6540 if (PD->isReadOnly()) {
6541 S += ",R";
Nico Weber4e8626f2013-05-08 23:47:40 +00006542 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
6543 S += ",C";
6544 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
6545 S += ",&";
Fariborz Jahanian33079ee2014-04-02 22:49:42 +00006546 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
6547 S += ",W";
Daniel Dunbar4932b362008-08-28 04:38:10 +00006548 } else {
6549 switch (PD->getSetterKind()) {
6550 case ObjCPropertyDecl::Assign: break;
6551 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00006552 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00006553 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00006554 }
6555 }
6556
6557 // It really isn't clear at all what this means, since properties
6558 // are "dynamic by default".
6559 if (Dynamic)
6560 S += ",D";
6561
Fariborz Jahanian218c6302009-01-20 19:14:18 +00006562 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
6563 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00006564
Daniel Dunbar4932b362008-08-28 04:38:10 +00006565 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
6566 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00006567 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00006568 }
6569
6570 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
6571 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00006572 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00006573 }
6574
6575 if (SynthesizePID) {
6576 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
6577 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00006578 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00006579 }
6580
6581 // FIXME: OBJCGC: weak & strong
John McCall843dfcc2016-11-29 21:57:00 +00006582 return S;
Daniel Dunbar4932b362008-08-28 04:38:10 +00006583}
6584
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006585/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00006586/// Another legacy compatibility encoding: 32-bit longs are encoded as
6587/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006588/// 'i' or 'I' instead if encoding a struct field, or a pointer!
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006589void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00006590 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006591 if (const auto *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00006592 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006593 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00006594 else
Jay Foad39c79802011-01-12 09:06:06 +00006595 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006596 PointeeTy = IntTy;
6597 }
6598 }
6599}
6600
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00006601void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006602 const FieldDecl *Field,
6603 QualType *NotEncodedT) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00006604 // We follow the behavior of gcc, expanding structures which are
6605 // directly pointed to, and expanding embedded structures. Note that
6606 // these rules are sufficient to prevent recursive encoding of the
6607 // same type.
Nico Weber2e9591c2019-05-14 12:32:37 +00006608 getObjCEncodingForTypeImpl(T, S,
6609 ObjCEncOptions()
6610 .setExpandPointedToStructures()
6611 .setExpandStructures()
6612 .setIsOutermostType(),
6613 Field, NotEncodedT);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00006614}
6615
Joe Groff98ac7d22014-07-07 22:25:15 +00006616void ASTContext::getObjCEncodingForPropertyType(QualType T,
6617 std::string& S) const {
6618 // Encode result type.
6619 // GCC has some special rules regarding encoding of properties which
6620 // closely resembles encoding of ivars.
Nico Weber2e9591c2019-05-14 12:32:37 +00006621 getObjCEncodingForTypeImpl(T, S,
6622 ObjCEncOptions()
6623 .setExpandPointedToStructures()
6624 .setExpandStructures()
6625 .setIsOutermostType()
6626 .setEncodingProperty(),
6627 /*Field=*/nullptr);
Joe Groff98ac7d22014-07-07 22:25:15 +00006628}
6629
Richard Sandifordeb485fb2019-08-09 08:52:54 +00006630static char getObjCEncodingForPrimitiveType(const ASTContext *C,
6631 const BuiltinType *BT) {
6632 BuiltinType::Kind kind = BT->getKind();
John McCall393a78d2012-12-20 02:45:14 +00006633 switch (kind) {
David Chisnallb190a2c2010-06-04 01:10:52 +00006634 case BuiltinType::Void: return 'v';
6635 case BuiltinType::Bool: return 'B';
Richard Smith3a8244d2018-05-01 05:02:45 +00006636 case BuiltinType::Char8:
David Chisnallb190a2c2010-06-04 01:10:52 +00006637 case BuiltinType::Char_U:
6638 case BuiltinType::UChar: return 'C';
John McCall393a78d2012-12-20 02:45:14 +00006639 case BuiltinType::Char16:
David Chisnallb190a2c2010-06-04 01:10:52 +00006640 case BuiltinType::UShort: return 'S';
John McCall393a78d2012-12-20 02:45:14 +00006641 case BuiltinType::Char32:
David Chisnallb190a2c2010-06-04 01:10:52 +00006642 case BuiltinType::UInt: return 'I';
6643 case BuiltinType::ULong:
John McCall393a78d2012-12-20 02:45:14 +00006644 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00006645 case BuiltinType::UInt128: return 'T';
6646 case BuiltinType::ULongLong: return 'Q';
6647 case BuiltinType::Char_S:
6648 case BuiltinType::SChar: return 'c';
6649 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00006650 case BuiltinType::WChar_S:
6651 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00006652 case BuiltinType::Int: return 'i';
6653 case BuiltinType::Long:
John McCall393a78d2012-12-20 02:45:14 +00006654 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00006655 case BuiltinType::LongLong: return 'q';
6656 case BuiltinType::Int128: return 't';
6657 case BuiltinType::Float: return 'f';
6658 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00006659 case BuiltinType::LongDouble: return 'D';
John McCall393a78d2012-12-20 02:45:14 +00006660 case BuiltinType::NullPtr: return '*'; // like char*
6661
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00006662 case BuiltinType::Float16:
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00006663 case BuiltinType::Float128:
John McCall393a78d2012-12-20 02:45:14 +00006664 case BuiltinType::Half:
Leonard Chanf921d852018-06-04 16:07:52 +00006665 case BuiltinType::ShortAccum:
6666 case BuiltinType::Accum:
6667 case BuiltinType::LongAccum:
6668 case BuiltinType::UShortAccum:
6669 case BuiltinType::UAccum:
6670 case BuiltinType::ULongAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00006671 case BuiltinType::ShortFract:
6672 case BuiltinType::Fract:
6673 case BuiltinType::LongFract:
6674 case BuiltinType::UShortFract:
6675 case BuiltinType::UFract:
6676 case BuiltinType::ULongFract:
6677 case BuiltinType::SatShortAccum:
6678 case BuiltinType::SatAccum:
6679 case BuiltinType::SatLongAccum:
6680 case BuiltinType::SatUShortAccum:
6681 case BuiltinType::SatUAccum:
6682 case BuiltinType::SatULongAccum:
6683 case BuiltinType::SatShortFract:
6684 case BuiltinType::SatFract:
6685 case BuiltinType::SatLongFract:
6686 case BuiltinType::SatUShortFract:
6687 case BuiltinType::SatUFract:
6688 case BuiltinType::SatULongFract:
John McCall393a78d2012-12-20 02:45:14 +00006689 // FIXME: potentially need @encodes for these!
6690 return ' ';
6691
Richard Sandifordeb485fb2019-08-09 08:52:54 +00006692#define SVE_TYPE(Name, Id, SingletonId) \
6693 case BuiltinType::Id:
6694#include "clang/Basic/AArch64SVEACLETypes.def"
6695 {
6696 DiagnosticsEngine &Diags = C->getDiagnostics();
6697 unsigned DiagID = Diags.getCustomDiagID(
6698 DiagnosticsEngine::Error, "cannot yet @encode type %0");
6699 Diags.Report(DiagID) << BT->getName(C->getPrintingPolicy());
6700 return ' ';
6701 }
6702
John McCall393a78d2012-12-20 02:45:14 +00006703 case BuiltinType::ObjCId:
6704 case BuiltinType::ObjCClass:
6705 case BuiltinType::ObjCSel:
6706 llvm_unreachable("@encoding ObjC primitive type");
6707
6708 // OpenCL and placeholder types don't need @encodings.
Alexey Bader954ba212016-04-08 13:40:33 +00006709#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6710 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00006711#include "clang/Basic/OpenCLImageTypes.def"
Andrew Savonichev3fee3512018-11-08 11:25:41 +00006712#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6713 case BuiltinType::Id:
6714#include "clang/Basic/OpenCLExtensionTypes.def"
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006715 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00006716 case BuiltinType::OCLClkEvent:
6717 case BuiltinType::OCLQueue:
Alexey Bader9c8453f2015-09-15 11:18:52 +00006718 case BuiltinType::OCLReserveID:
Guy Benyei61054192013-02-07 10:55:47 +00006719 case BuiltinType::OCLSampler:
John McCall393a78d2012-12-20 02:45:14 +00006720 case BuiltinType::Dependent:
6721#define BUILTIN_TYPE(KIND, ID)
6722#define PLACEHOLDER_TYPE(KIND, ID) \
6723 case BuiltinType::KIND:
6724#include "clang/AST/BuiltinTypes.def"
6725 llvm_unreachable("invalid builtin type for @encode");
David Chisnallb190a2c2010-06-04 01:10:52 +00006726 }
David Blaikie5a6a0202013-01-09 17:48:41 +00006727 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnallb190a2c2010-06-04 01:10:52 +00006728}
6729
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006730static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
6731 EnumDecl *Enum = ET->getDecl();
Fangrui Song6907ce22018-07-30 19:24:48 +00006732
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006733 // The encoding of an non-fixed enum type is always 'i', regardless of size.
6734 if (!Enum->isFixed())
6735 return 'i';
Fangrui Song6907ce22018-07-30 19:24:48 +00006736
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006737 // The encoding of a fixed enum type matches its fixed underlying type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00006738 const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>();
Richard Sandifordeb485fb2019-08-09 08:52:54 +00006739 return getObjCEncodingForPrimitiveType(C, BT);
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006740}
6741
Jay Foad39c79802011-01-12 09:06:06 +00006742static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00006743 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00006744 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00006745 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00006746 // The NeXT runtime encodes bit fields as b followed by the number of bits.
6747 // The GNU runtime requires more information; bitfields are encoded as b,
6748 // then the offset (in bits) of the first element, then the type of the
6749 // bitfield, then the size in bits. For example, in this structure:
6750 //
6751 // struct
6752 // {
6753 // int integer;
6754 // int flags:2;
6755 // };
6756 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
6757 // runtime, but b32i2 for the GNU runtime. The reason for this extra
6758 // information is not especially sensible, but we're stuck with it for
6759 // compatibility with GCC, although providing it breaks anything that
6760 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00006761 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
Akira Hatanaka4b1c4842017-06-27 04:34:04 +00006762 uint64_t Offset;
6763
6764 if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) {
6765 Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), nullptr,
6766 IVD);
6767 } else {
6768 const RecordDecl *RD = FD->getParent();
6769 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
6770 Offset = RL.getFieldOffset(FD->getFieldIndex());
6771 }
6772
6773 S += llvm::utostr(Offset);
6774
Eugene Zelenko7855e772018-04-03 00:11:50 +00006775 if (const auto *ET = T->getAs<EnumType>())
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006776 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall393a78d2012-12-20 02:45:14 +00006777 else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006778 const auto *BT = T->castAs<BuiltinType>();
Richard Sandifordeb485fb2019-08-09 08:52:54 +00006779 S += getObjCEncodingForPrimitiveType(Ctx, BT);
John McCall393a78d2012-12-20 02:45:14 +00006780 }
David Chisnallb190a2c2010-06-04 01:10:52 +00006781 }
Richard Smithcaf33902011-10-10 18:28:20 +00006782 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00006783}
6784
Daniel Dunbar07d07852009-10-18 21:17:35 +00006785// FIXME: Use SmallString for accumulating string.
Nico Weber2e9591c2019-05-14 12:32:37 +00006786void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S,
6787 const ObjCEncOptions Options,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00006788 const FieldDecl *FD,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006789 QualType *NotEncodedT) const {
John McCall393a78d2012-12-20 02:45:14 +00006790 CanQualType CT = getCanonicalType(T);
6791 switch (CT->getTypeClass()) {
6792 case Type::Builtin:
6793 case Type::Enum:
Chris Lattnere7cabb92009-07-13 00:10:46 +00006794 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00006795 return EncodeBitField(this, S, T, FD);
Eugene Zelenko7855e772018-04-03 00:11:50 +00006796 if (const auto *BT = dyn_cast<BuiltinType>(CT))
Richard Sandifordeb485fb2019-08-09 08:52:54 +00006797 S += getObjCEncodingForPrimitiveType(this, BT);
John McCall393a78d2012-12-20 02:45:14 +00006798 else
6799 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnere7cabb92009-07-13 00:10:46 +00006800 return;
Mike Stump11289f42009-09-09 15:08:12 +00006801
John McCall393a78d2012-12-20 02:45:14 +00006802 case Type::Complex: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006803 const auto *CT = T->castAs<ComplexType>();
Anders Carlsson39b2e132009-04-09 21:55:45 +00006804 S += 'j';
Nico Weber2e9591c2019-05-14 12:32:37 +00006805 getObjCEncodingForTypeImpl(CT->getElementType(), S, ObjCEncOptions(),
6806 /*Field=*/nullptr);
Chris Lattnere7cabb92009-07-13 00:10:46 +00006807 return;
6808 }
John McCall393a78d2012-12-20 02:45:14 +00006809
6810 case Type::Atomic: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006811 const auto *AT = T->castAs<AtomicType>();
John McCall393a78d2012-12-20 02:45:14 +00006812 S += 'A';
Nico Weber2e9591c2019-05-14 12:32:37 +00006813 getObjCEncodingForTypeImpl(AT->getValueType(), S, ObjCEncOptions(),
6814 /*Field=*/nullptr);
John McCall393a78d2012-12-20 02:45:14 +00006815 return;
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00006816 }
John McCall393a78d2012-12-20 02:45:14 +00006817
6818 // encoding for pointer or reference types.
6819 case Type::Pointer:
6820 case Type::LValueReference:
6821 case Type::RValueReference: {
6822 QualType PointeeTy;
6823 if (isa<PointerType>(CT)) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006824 const auto *PT = T->castAs<PointerType>();
John McCall393a78d2012-12-20 02:45:14 +00006825 if (PT->isObjCSelType()) {
6826 S += ':';
6827 return;
6828 }
6829 PointeeTy = PT->getPointeeType();
6830 } else {
6831 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
6832 }
6833
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006834 bool isReadOnly = false;
6835 // For historical/compatibility reasons, the read-only qualifier of the
6836 // pointee gets emitted _before_ the '^'. The read-only qualifier of
6837 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00006838 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00006839 if (isa<TypedefType>(T.getTypePtr())) {
Nico Weber2e9591c2019-05-14 12:32:37 +00006840 if (Options.IsOutermostType() && T.isConstQualified()) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006841 isReadOnly = true;
6842 S += 'r';
6843 }
Nico Weber2e9591c2019-05-14 12:32:37 +00006844 } else if (Options.IsOutermostType()) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006845 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006846 while (P->getAs<PointerType>())
6847 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006848 if (P.isConstQualified()) {
6849 isReadOnly = true;
6850 S += 'r';
6851 }
6852 }
6853 if (isReadOnly) {
6854 // Another legacy compatibility encoding. Some ObjC qualifier and type
6855 // combinations need to be rearranged.
6856 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006857 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00006858 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006859 }
Mike Stump11289f42009-09-09 15:08:12 +00006860
Anders Carlssond8499822007-10-29 05:01:08 +00006861 if (PointeeTy->isCharType()) {
6862 // char pointer types should be encoded as '*' unless it is a
6863 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00006864 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00006865 S += '*';
6866 return;
6867 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00006868 } else if (const auto *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00006869 // GCC binary compat: Need to convert "struct objc_class *" to "#".
6870 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
6871 S += '#';
6872 return;
6873 }
6874 // GCC binary compat: Need to convert "struct objc_object *" to "@".
6875 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
6876 S += '@';
6877 return;
6878 }
6879 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00006880 }
Anders Carlssond8499822007-10-29 05:01:08 +00006881 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006882 getLegacyIntegralTypeEncoding(PointeeTy);
6883
Nico Weber2e9591c2019-05-14 12:32:37 +00006884 ObjCEncOptions NewOptions;
6885 if (Options.ExpandPointedToStructures())
6886 NewOptions.setExpandStructures();
6887 getObjCEncodingForTypeImpl(PointeeTy, S, NewOptions,
6888 /*Field=*/nullptr, NotEncodedT);
Chris Lattnere7cabb92009-07-13 00:10:46 +00006889 return;
6890 }
John McCall393a78d2012-12-20 02:45:14 +00006891
6892 case Type::ConstantArray:
6893 case Type::IncompleteArray:
6894 case Type::VariableArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006895 const auto *AT = cast<ArrayType>(CT);
John McCall393a78d2012-12-20 02:45:14 +00006896
Nico Weber2e9591c2019-05-14 12:32:37 +00006897 if (isa<IncompleteArrayType>(AT) && !Options.IsStructField()) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00006898 // Incomplete arrays are encoded as a pointer to the array element.
6899 S += '^';
6900
Nico Weber2e9591c2019-05-14 12:32:37 +00006901 getObjCEncodingForTypeImpl(
6902 AT->getElementType(), S,
6903 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD);
Anders Carlssond05f44b2009-02-22 01:38:57 +00006904 } else {
6905 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00006906
Eugene Zelenko7855e772018-04-03 00:11:50 +00006907 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
Fariborz Jahanianf0dc11a2013-06-04 16:04:37 +00006908 S += llvm::utostr(CAT->getSize().getZExtValue());
6909 else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00006910 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006911 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
6912 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00006913 S += '0';
6914 }
Mike Stump11289f42009-09-09 15:08:12 +00006915
Nico Weberdf129332019-05-10 13:56:56 +00006916 getObjCEncodingForTypeImpl(
6917 AT->getElementType(), S,
Nico Weber2e9591c2019-05-14 12:32:37 +00006918 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD,
6919 NotEncodedT);
Anders Carlssond05f44b2009-02-22 01:38:57 +00006920 S += ']';
6921 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006922 return;
6923 }
Mike Stump11289f42009-09-09 15:08:12 +00006924
John McCall393a78d2012-12-20 02:45:14 +00006925 case Type::FunctionNoProto:
6926 case Type::FunctionProto:
Anders Carlssondf4cc612007-10-30 00:06:20 +00006927 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00006928 return;
Mike Stump11289f42009-09-09 15:08:12 +00006929
John McCall393a78d2012-12-20 02:45:14 +00006930 case Type::Record: {
6931 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00006932 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00006933 // Anonymous structures print as '?'
6934 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
6935 S += II->getName();
Eugene Zelenko7855e772018-04-03 00:11:50 +00006936 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
Fariborz Jahanianc5158202010-05-07 00:28:49 +00006937 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00006938 llvm::raw_string_ostream OS(S);
Serge Pavlov03e672c2017-11-28 16:14:14 +00006939 printTemplateArgumentList(OS, TemplateArgs.asArray(),
6940 getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00006941 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00006942 } else {
6943 S += '?';
6944 }
Nico Weber2e9591c2019-05-14 12:32:37 +00006945 if (Options.ExpandStructures()) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00006946 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006947 if (!RDecl->isUnion()) {
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006948 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006949 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006950 for (const auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006951 if (FD) {
6952 S += '"';
6953 S += Field->getNameAsString();
6954 S += '"';
6955 }
Mike Stump11289f42009-09-09 15:08:12 +00006956
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006957 // Special case bit-fields.
6958 if (Field->isBitField()) {
Nico Weberdf129332019-05-10 13:56:56 +00006959 getObjCEncodingForTypeImpl(Field->getType(), S,
Nico Weber2e9591c2019-05-14 12:32:37 +00006960 ObjCEncOptions().setExpandStructures(),
6961 Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006962 } else {
6963 QualType qt = Field->getType();
6964 getLegacyIntegralTypeEncoding(qt);
Nico Weberdf129332019-05-10 13:56:56 +00006965 getObjCEncodingForTypeImpl(
Nico Weber2e9591c2019-05-14 12:32:37 +00006966 qt, S,
6967 ObjCEncOptions().setExpandStructures().setIsStructField(), FD,
6968 NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006969 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00006970 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00006971 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00006972 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00006973 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00006974 return;
6975 }
Mike Stump11289f42009-09-09 15:08:12 +00006976
John McCall393a78d2012-12-20 02:45:14 +00006977 case Type::BlockPointer: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006978 const auto *BT = T->castAs<BlockPointerType>();
Steve Naroff49140cb2009-02-02 18:24:29 +00006979 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Nico Weber2e9591c2019-05-14 12:32:37 +00006980 if (Options.EncodeBlockParameters()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006981 const auto *FT = BT->getPointeeType()->castAs<FunctionType>();
Fangrui Song6907ce22018-07-30 19:24:48 +00006982
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006983 S += '<';
6984 // Block return type
Nico Weber2e9591c2019-05-14 12:32:37 +00006985 getObjCEncodingForTypeImpl(FT->getReturnType(), S,
6986 Options.forComponentType(), FD, NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006987 // Block self
6988 S += "@?";
6989 // Block parameters
Eugene Zelenko7855e772018-04-03 00:11:50 +00006990 if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00006991 for (const auto &I : FPT->param_types())
Nico Weber2e9591c2019-05-14 12:32:37 +00006992 getObjCEncodingForTypeImpl(I, S, Options.forComponentType(), FD,
6993 NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006994 }
6995 S += '>';
6996 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006997 return;
6998 }
Mike Stump11289f42009-09-09 15:08:12 +00006999
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00007000 case Type::ObjCObject: {
7001 // hack to match legacy encoding of *id and *Class
7002 QualType Ty = getObjCObjectPointerType(CT);
7003 if (Ty->isObjCIdType()) {
7004 S += "{objc_object=}";
7005 return;
7006 }
7007 else if (Ty->isObjCClassType()) {
7008 S += "{objc_class=}";
7009 return;
7010 }
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00007011 // TODO: Double check to make sure this intentionally falls through.
Galina Kistanovaf87496d2017-06-03 06:31:42 +00007012 LLVM_FALLTHROUGH;
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00007013 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007014
John McCall393a78d2012-12-20 02:45:14 +00007015 case Type::ObjCInterface: {
7016 // Ignore protocol qualifiers when mangling at this level.
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00007017 // @encode(class_name)
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007018 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00007019 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00007020 S += OI->getObjCRuntimeNameAsString();
Nico Weber2e9591c2019-05-14 12:32:37 +00007021 if (Options.ExpandStructures()) {
Akira Hatanakafd0fb202016-08-17 19:42:22 +00007022 S += '=';
7023 SmallVector<const ObjCIvarDecl*, 32> Ivars;
7024 DeepCollectObjCIvars(OI, true, Ivars);
7025 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
George Burgess IV00f70bd2018-03-01 05:43:23 +00007026 const FieldDecl *Field = Ivars[i];
Akira Hatanakafd0fb202016-08-17 19:42:22 +00007027 if (Field->isBitField())
Nico Weberdf129332019-05-10 13:56:56 +00007028 getObjCEncodingForTypeImpl(Field->getType(), S,
Nico Weber2e9591c2019-05-14 12:32:37 +00007029 ObjCEncOptions().setExpandStructures(),
7030 Field);
Akira Hatanakaf3c89b12019-05-29 21:23:30 +00007031 else
7032 getObjCEncodingForTypeImpl(Field->getType(), S,
7033 ObjCEncOptions().setExpandStructures(), FD,
Nico Weber2e9591c2019-05-14 12:32:37 +00007034 NotEncodedT);
Akira Hatanakafd0fb202016-08-17 19:42:22 +00007035 }
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00007036 }
7037 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00007038 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00007039 }
Mike Stump11289f42009-09-09 15:08:12 +00007040
John McCall393a78d2012-12-20 02:45:14 +00007041 case Type::ObjCObjectPointer: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00007042 const auto *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00007043 if (OPT->isObjCIdType()) {
7044 S += '@';
7045 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00007046 }
Mike Stump11289f42009-09-09 15:08:12 +00007047
Steve Narofff0c86112009-10-28 22:03:49 +00007048 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
7049 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
Nico Weberdf129332019-05-10 13:56:56 +00007050 // Since this is a binary compatibility issue, need to consult with
7051 // runtime folks. Fortunately, this is a *very* obscure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00007052 S += '#';
7053 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00007054 }
Mike Stump11289f42009-09-09 15:08:12 +00007055
Chris Lattnere7cabb92009-07-13 00:10:46 +00007056 if (OPT->isObjCQualifiedIdType()) {
Nico Weber2e9591c2019-05-14 12:32:37 +00007057 getObjCEncodingForTypeImpl(
7058 getObjCIdType(), S,
7059 Options.keepingOnly(ObjCEncOptions()
7060 .setExpandPointedToStructures()
7061 .setExpandStructures()),
7062 FD);
7063 if (FD || Options.EncodingProperty() || Options.EncodeClassNames()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00007064 // Note that we do extended encoding of protocol qualifer list
7065 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00007066 S += '"';
Aaron Ballman83731462014-03-17 16:14:00 +00007067 for (const auto *I : OPT->quals()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00007068 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00007069 S += I->getObjCRuntimeNameAsString();
Steve Naroff7cae42b2009-07-10 23:34:53 +00007070 S += '>';
7071 }
7072 S += '"';
7073 }
7074 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00007075 }
Mike Stump11289f42009-09-09 15:08:12 +00007076
Chris Lattnere7cabb92009-07-13 00:10:46 +00007077 S += '@';
Fangrui Song6907ce22018-07-30 19:24:48 +00007078 if (OPT->getInterfaceDecl() &&
Nico Weber2e9591c2019-05-14 12:32:37 +00007079 (FD || Options.EncodingProperty() || Options.EncodeClassNames())) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00007080 S += '"';
Douglas Gregorb32684e2015-06-16 21:04:55 +00007081 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
Aaron Ballman83731462014-03-17 16:14:00 +00007082 for (const auto *I : OPT->quals()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00007083 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00007084 S += I->getObjCRuntimeNameAsString();
Chris Lattnere7cabb92009-07-13 00:10:46 +00007085 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00007086 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00007087 S += '"';
7088 }
7089 return;
7090 }
Mike Stump11289f42009-09-09 15:08:12 +00007091
John McCalla9e6e8d2010-05-17 23:56:34 +00007092 // gcc just blithely ignores member pointers.
Nico Weber2e9591c2019-05-14 12:32:37 +00007093 // FIXME: we should do better than that. 'M' is available.
John McCall393a78d2012-12-20 02:45:14 +00007094 case Type::MemberPointer:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00007095 // This matches gcc's encoding, even though technically it is insufficient.
7096 //FIXME. We should do a better job than gcc.
John McCall393a78d2012-12-20 02:45:14 +00007097 case Type::Vector:
7098 case Type::ExtVector:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00007099 // Until we have a coherent encoding of these three types, issue warning.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00007100 if (NotEncodedT)
7101 *NotEncodedT = T;
7102 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00007103
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00007104 // We could see an undeduced auto type here during error recovery.
7105 // Just ignore it.
Richard Smith27d807c2013-04-30 13:56:41 +00007106 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00007107 case Type::DeducedTemplateSpecialization:
Richard Smith27d807c2013-04-30 13:56:41 +00007108 return;
7109
Xiuli Pan9c14e282016-01-09 12:53:17 +00007110 case Type::Pipe:
John McCall393a78d2012-12-20 02:45:14 +00007111#define ABSTRACT_TYPE(KIND, BASE)
7112#define TYPE(KIND, BASE)
7113#define DEPENDENT_TYPE(KIND, BASE) \
7114 case Type::KIND:
7115#define NON_CANONICAL_TYPE(KIND, BASE) \
7116 case Type::KIND:
7117#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
7118 case Type::KIND:
7119#include "clang/AST/TypeNodes.def"
7120 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00007121 }
John McCall393a78d2012-12-20 02:45:14 +00007122 llvm_unreachable("bad type kind!");
Anders Carlssond8499822007-10-29 05:01:08 +00007123}
7124
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007125void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
7126 std::string &S,
7127 const FieldDecl *FD,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00007128 bool includeVBases,
7129 QualType *NotEncodedT) const {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007130 assert(RDecl && "Expected non-null RecordDecl");
7131 assert(!RDecl->isUnion() && "Should not be called for unions");
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00007132 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007133 return;
7134
Eugene Zelenko7855e772018-04-03 00:11:50 +00007135 const auto *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007136 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
7137 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
7138
7139 if (CXXRec) {
Aaron Ballman574705e2014-03-13 15:41:46 +00007140 for (const auto &BI : CXXRec->bases()) {
7141 if (!BI.isVirtual()) {
7142 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00007143 if (base->isEmpty())
7144 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00007145 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007146 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
7147 std::make_pair(offs, base));
7148 }
7149 }
7150 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007151
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007152 unsigned i = 0;
Hans Wennborga302cd92014-08-21 16:06:57 +00007153 for (auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007154 uint64_t offs = layout.getFieldOffset(i);
7155 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Hans Wennborga302cd92014-08-21 16:06:57 +00007156 std::make_pair(offs, Field));
7157 ++i;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007158 }
7159
7160 if (CXXRec && includeVBases) {
Aaron Ballman445a9392014-03-13 16:15:17 +00007161 for (const auto &BI : CXXRec->vbases()) {
7162 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00007163 if (base->isEmpty())
7164 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00007165 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Eli Friedman1d24af82013-09-18 01:59:16 +00007166 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
7167 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00007168 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
7169 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007170 }
7171 }
7172
7173 CharUnits size;
7174 if (CXXRec) {
7175 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
7176 } else {
7177 size = layout.getSize();
7178 }
7179
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007180#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007181 uint64_t CurOffs = 0;
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007182#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007183 std::multimap<uint64_t, NamedDecl *>::iterator
7184 CurLayObj = FieldOrBaseOffsets.begin();
7185
Douglas Gregorf5d6c742012-04-27 22:30:01 +00007186 if (CXXRec && CXXRec->isDynamicClass() &&
7187 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007188 if (FD) {
7189 S += "\"_vptr$";
7190 std::string recname = CXXRec->getNameAsString();
7191 if (recname.empty()) recname = "?";
7192 S += recname;
7193 S += '"';
7194 }
7195 S += "^^?";
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007196#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007197 CurOffs += getTypeSize(VoidPtrTy);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007198#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007199 }
7200
7201 if (!RDecl->hasFlexibleArrayMember()) {
7202 // Mark the end of the structure.
7203 uint64_t offs = toBits(size);
7204 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Craig Topper36250ad2014-05-12 05:36:57 +00007205 std::make_pair(offs, nullptr));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007206 }
7207
7208 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007209#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007210 assert(CurOffs <= CurLayObj->first);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007211 if (CurOffs < CurLayObj->first) {
Fangrui Song6907ce22018-07-30 19:24:48 +00007212 uint64_t padding = CurLayObj->first - CurOffs;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007213 // FIXME: There doesn't seem to be a way to indicate in the encoding that
7214 // packing/alignment of members is different that normal, in which case
7215 // the encoding will be out-of-sync with the real layout.
7216 // If the runtime switches to just consider the size of types without
7217 // taking into account alignment, we could make padding explicit in the
7218 // encoding (e.g. using arrays of chars). The encoding strings would be
7219 // longer then though.
7220 CurOffs += padding;
7221 }
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007222#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007223
7224 NamedDecl *dcl = CurLayObj->second;
Craig Topper36250ad2014-05-12 05:36:57 +00007225 if (!dcl)
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007226 break; // reached end of structure.
7227
Eugene Zelenko7855e772018-04-03 00:11:50 +00007228 if (auto *base = dyn_cast<CXXRecordDecl>(dcl)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007229 // We expand the bases without their virtual bases since those are going
7230 // in the initial structure. Note that this differs from gcc which
7231 // expands virtual bases each time one is encountered in the hierarchy,
7232 // making the encoding type bigger than it really is.
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00007233 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
7234 NotEncodedT);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00007235 assert(!base->isEmpty());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007236#ifndef NDEBUG
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00007237 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007238#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007239 } else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00007240 const auto *field = cast<FieldDecl>(dcl);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007241 if (FD) {
7242 S += '"';
7243 S += field->getNameAsString();
7244 S += '"';
7245 }
7246
7247 if (field->isBitField()) {
7248 EncodeBitField(this, S, field->getType(), field);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007249#ifndef NDEBUG
Richard Smithcaf33902011-10-10 18:28:20 +00007250 CurOffs += field->getBitWidthValue(*this);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007251#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007252 } else {
7253 QualType qt = field->getType();
7254 getLegacyIntegralTypeEncoding(qt);
Nico Weberdf129332019-05-10 13:56:56 +00007255 getObjCEncodingForTypeImpl(
Nico Weber2e9591c2019-05-14 12:32:37 +00007256 qt, S, ObjCEncOptions().setExpandStructures().setIsStructField(),
7257 FD, NotEncodedT);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007258#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007259 CurOffs += getTypeSize(field->getType());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007260#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007261 }
7262 }
7263 }
7264}
7265
Mike Stump11289f42009-09-09 15:08:12 +00007266void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00007267 std::string& S) const {
7268 if (QT & Decl::OBJC_TQ_In)
7269 S += 'n';
7270 if (QT & Decl::OBJC_TQ_Inout)
7271 S += 'N';
7272 if (QT & Decl::OBJC_TQ_Out)
7273 S += 'o';
7274 if (QT & Decl::OBJC_TQ_Bycopy)
7275 S += 'O';
7276 if (QT & Decl::OBJC_TQ_Byref)
7277 S += 'R';
7278 if (QT & Decl::OBJC_TQ_Oneway)
7279 S += 'V';
7280}
7281
Douglas Gregor3ea72692011-08-12 05:46:01 +00007282TypedefDecl *ASTContext::getObjCIdDecl() const {
7283 if (!ObjCIdDecl) {
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00007284 QualType T = getObjCObjectType(ObjCBuiltinIdTy, {}, {});
Douglas Gregor3ea72692011-08-12 05:46:01 +00007285 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00007286 ObjCIdDecl = buildImplicitTypedef(T, "id");
Douglas Gregor3ea72692011-08-12 05:46:01 +00007287 }
Douglas Gregor3ea72692011-08-12 05:46:01 +00007288 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00007289}
7290
Douglas Gregor52e02802011-08-12 06:17:30 +00007291TypedefDecl *ASTContext::getObjCSelDecl() const {
7292 if (!ObjCSelDecl) {
Alp Toker56b5cc92013-12-15 10:36:26 +00007293 QualType T = getPointerType(ObjCBuiltinSelTy);
7294 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
Douglas Gregor52e02802011-08-12 06:17:30 +00007295 }
7296 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00007297}
7298
Douglas Gregor0a586182011-08-12 05:59:41 +00007299TypedefDecl *ASTContext::getObjCClassDecl() const {
7300 if (!ObjCClassDecl) {
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00007301 QualType T = getObjCObjectType(ObjCBuiltinClassTy, {}, {});
Douglas Gregor0a586182011-08-12 05:59:41 +00007302 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00007303 ObjCClassDecl = buildImplicitTypedef(T, "Class");
Douglas Gregor0a586182011-08-12 05:59:41 +00007304 }
Douglas Gregor0a586182011-08-12 05:59:41 +00007305 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00007306}
7307
Douglas Gregord53ae832012-01-17 18:09:05 +00007308ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
7309 if (!ObjCProtocolClassDecl) {
Fangrui Song6907ce22018-07-30 19:24:48 +00007310 ObjCProtocolClassDecl
7311 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
Douglas Gregord53ae832012-01-17 18:09:05 +00007312 SourceLocation(),
7313 &Idents.get("Protocol"),
Douglas Gregor85f3f952015-07-07 03:57:15 +00007314 /*typeParamList=*/nullptr,
Craig Topper36250ad2014-05-12 05:36:57 +00007315 /*PrevDecl=*/nullptr,
Fangrui Song6907ce22018-07-30 19:24:48 +00007316 SourceLocation(), true);
Douglas Gregord53ae832012-01-17 18:09:05 +00007317 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007318
Douglas Gregord53ae832012-01-17 18:09:05 +00007319 return ObjCProtocolClassDecl;
7320}
7321
Meador Inge5d3fb222012-06-16 03:34:49 +00007322//===----------------------------------------------------------------------===//
7323// __builtin_va_list Construction Functions
7324//===----------------------------------------------------------------------===//
7325
Charles Davisc7d5c942015-09-17 20:55:33 +00007326static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context,
7327 StringRef Name) {
7328 // typedef char* __builtin[_ms]_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00007329 QualType T = Context->getPointerType(Context->CharTy);
Charles Davisc7d5c942015-09-17 20:55:33 +00007330 return Context->buildImplicitTypedef(T, Name);
7331}
7332
7333static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
7334 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
7335}
7336
7337static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
7338 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007339}
7340
7341static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
7342 // typedef void* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00007343 QualType T = Context->getPointerType(Context->VoidTy);
7344 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007345}
7346
Tim Northover9bb857a2013-01-31 12:13:10 +00007347static TypedefDecl *
7348CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00007349 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00007350 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00007351 if (Context->getLangOpts().CPlusPlus) {
7352 // namespace std { struct __va_list {
7353 NamespaceDecl *NS;
7354 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
7355 Context->getTranslationUnitDecl(),
Craig Topper36250ad2014-05-12 05:36:57 +00007356 /*Inline*/ false, SourceLocation(),
Tim Northover9bb857a2013-01-31 12:13:10 +00007357 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00007358 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00007359 NS->setImplicit();
Tim Northover9bb857a2013-01-31 12:13:10 +00007360 VaListTagDecl->setDeclContext(NS);
Tim Northover9bb857a2013-01-31 12:13:10 +00007361 }
7362
7363 VaListTagDecl->startDefinition();
7364
7365 const size_t NumFields = 5;
7366 QualType FieldTypes[NumFields];
7367 const char *FieldNames[NumFields];
7368
7369 // void *__stack;
7370 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
7371 FieldNames[0] = "__stack";
7372
7373 // void *__gr_top;
7374 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
7375 FieldNames[1] = "__gr_top";
7376
7377 // void *__vr_top;
7378 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
7379 FieldNames[2] = "__vr_top";
7380
7381 // int __gr_offs;
7382 FieldTypes[3] = Context->IntTy;
7383 FieldNames[3] = "__gr_offs";
7384
7385 // int __vr_offs;
7386 FieldTypes[4] = Context->IntTy;
7387 FieldNames[4] = "__vr_offs";
7388
7389 // Create fields
7390 for (unsigned i = 0; i < NumFields; ++i) {
7391 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7392 VaListTagDecl,
7393 SourceLocation(),
7394 SourceLocation(),
7395 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00007396 FieldTypes[i], /*TInfo=*/nullptr,
7397 /*BitWidth=*/nullptr,
Tim Northover9bb857a2013-01-31 12:13:10 +00007398 /*Mutable=*/false,
7399 ICIS_NoInit);
7400 Field->setAccess(AS_public);
7401 VaListTagDecl->addDecl(Field);
7402 }
7403 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00007404 Context->VaListTagDecl = VaListTagDecl;
Tim Northover9bb857a2013-01-31 12:13:10 +00007405 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Tim Northover9bb857a2013-01-31 12:13:10 +00007406
7407 // } __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00007408 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00007409}
7410
Meador Inge5d3fb222012-06-16 03:34:49 +00007411static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
7412 // typedef struct __va_list_tag {
7413 RecordDecl *VaListTagDecl;
7414
Alp Toker2dea15b2013-12-17 01:22:38 +00007415 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00007416 VaListTagDecl->startDefinition();
7417
7418 const size_t NumFields = 5;
7419 QualType FieldTypes[NumFields];
7420 const char *FieldNames[NumFields];
7421
7422 // unsigned char gpr;
7423 FieldTypes[0] = Context->UnsignedCharTy;
7424 FieldNames[0] = "gpr";
7425
7426 // unsigned char fpr;
7427 FieldTypes[1] = Context->UnsignedCharTy;
7428 FieldNames[1] = "fpr";
7429
7430 // unsigned short reserved;
7431 FieldTypes[2] = Context->UnsignedShortTy;
7432 FieldNames[2] = "reserved";
7433
7434 // void* overflow_arg_area;
7435 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
7436 FieldNames[3] = "overflow_arg_area";
7437
7438 // void* reg_save_area;
7439 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
7440 FieldNames[4] = "reg_save_area";
7441
7442 // Create fields
7443 for (unsigned i = 0; i < NumFields; ++i) {
7444 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
7445 SourceLocation(),
7446 SourceLocation(),
7447 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00007448 FieldTypes[i], /*TInfo=*/nullptr,
7449 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00007450 /*Mutable=*/false,
7451 ICIS_NoInit);
7452 Field->setAccess(AS_public);
7453 VaListTagDecl->addDecl(Field);
7454 }
7455 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00007456 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00007457 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
7458
7459 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00007460 TypedefDecl *VaListTagTypedefDecl =
7461 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
7462
Meador Inge5d3fb222012-06-16 03:34:49 +00007463 QualType VaListTagTypedefType =
7464 Context->getTypedefType(VaListTagTypedefDecl);
7465
7466 // typedef __va_list_tag __builtin_va_list[1];
7467 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
7468 QualType VaListTagArrayType
7469 = Context->getConstantArrayType(VaListTagTypedefType,
7470 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00007471 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007472}
7473
7474static TypedefDecl *
7475CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00007476 // struct __va_list_tag {
Meador Inge5d3fb222012-06-16 03:34:49 +00007477 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00007478 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00007479 VaListTagDecl->startDefinition();
7480
7481 const size_t NumFields = 4;
7482 QualType FieldTypes[NumFields];
7483 const char *FieldNames[NumFields];
7484
7485 // unsigned gp_offset;
7486 FieldTypes[0] = Context->UnsignedIntTy;
7487 FieldNames[0] = "gp_offset";
7488
7489 // unsigned fp_offset;
7490 FieldTypes[1] = Context->UnsignedIntTy;
7491 FieldNames[1] = "fp_offset";
7492
7493 // void* overflow_arg_area;
7494 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
7495 FieldNames[2] = "overflow_arg_area";
7496
7497 // void* reg_save_area;
7498 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
7499 FieldNames[3] = "reg_save_area";
7500
7501 // Create fields
7502 for (unsigned i = 0; i < NumFields; ++i) {
7503 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7504 VaListTagDecl,
7505 SourceLocation(),
7506 SourceLocation(),
7507 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00007508 FieldTypes[i], /*TInfo=*/nullptr,
7509 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00007510 /*Mutable=*/false,
7511 ICIS_NoInit);
7512 Field->setAccess(AS_public);
7513 VaListTagDecl->addDecl(Field);
7514 }
7515 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00007516 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00007517 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
7518
Richard Smith9b88a4c2015-07-27 05:40:23 +00007519 // };
Alp Toker56b5cc92013-12-15 10:36:26 +00007520
Richard Smith9b88a4c2015-07-27 05:40:23 +00007521 // typedef struct __va_list_tag __builtin_va_list[1];
Meador Inge5d3fb222012-06-16 03:34:49 +00007522 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00007523 QualType VaListTagArrayType =
7524 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00007525 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007526}
7527
7528static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
7529 // typedef int __builtin_va_list[4];
7530 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
Yaron Kerene0bcdd42016-10-08 06:45:10 +00007531 QualType IntArrayType =
7532 Context->getConstantArrayType(Context->IntTy, Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00007533 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007534}
7535
Logan Chien57086ce2012-10-10 06:56:20 +00007536static TypedefDecl *
7537CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00007538 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00007539 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00007540 if (Context->getLangOpts().CPlusPlus) {
7541 // namespace std { struct __va_list {
7542 NamespaceDecl *NS;
7543 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
7544 Context->getTranslationUnitDecl(),
7545 /*Inline*/false, SourceLocation(),
7546 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00007547 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00007548 NS->setImplicit();
Logan Chien57086ce2012-10-10 06:56:20 +00007549 VaListDecl->setDeclContext(NS);
Logan Chien57086ce2012-10-10 06:56:20 +00007550 }
7551
7552 VaListDecl->startDefinition();
7553
7554 // void * __ap;
7555 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7556 VaListDecl,
7557 SourceLocation(),
7558 SourceLocation(),
7559 &Context->Idents.get("__ap"),
7560 Context->getPointerType(Context->VoidTy),
Craig Topper36250ad2014-05-12 05:36:57 +00007561 /*TInfo=*/nullptr,
7562 /*BitWidth=*/nullptr,
Logan Chien57086ce2012-10-10 06:56:20 +00007563 /*Mutable=*/false,
7564 ICIS_NoInit);
7565 Field->setAccess(AS_public);
7566 VaListDecl->addDecl(Field);
7567
7568 // };
7569 VaListDecl->completeDefinition();
Oleg Ranevskyyb88d2472016-03-30 21:30:30 +00007570 Context->VaListTagDecl = VaListDecl;
Logan Chien57086ce2012-10-10 06:56:20 +00007571
7572 // typedef struct __va_list __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00007573 QualType T = Context->getRecordType(VaListDecl);
7574 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00007575}
7576
Ulrich Weigand47445072013-05-06 16:26:41 +00007577static TypedefDecl *
7578CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00007579 // struct __va_list_tag {
Ulrich Weigand47445072013-05-06 16:26:41 +00007580 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00007581 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00007582 VaListTagDecl->startDefinition();
7583
7584 const size_t NumFields = 4;
7585 QualType FieldTypes[NumFields];
7586 const char *FieldNames[NumFields];
7587
7588 // long __gpr;
7589 FieldTypes[0] = Context->LongTy;
7590 FieldNames[0] = "__gpr";
7591
7592 // long __fpr;
7593 FieldTypes[1] = Context->LongTy;
7594 FieldNames[1] = "__fpr";
7595
7596 // void *__overflow_arg_area;
7597 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
7598 FieldNames[2] = "__overflow_arg_area";
7599
7600 // void *__reg_save_area;
7601 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
7602 FieldNames[3] = "__reg_save_area";
7603
7604 // Create fields
7605 for (unsigned i = 0; i < NumFields; ++i) {
7606 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7607 VaListTagDecl,
7608 SourceLocation(),
7609 SourceLocation(),
7610 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00007611 FieldTypes[i], /*TInfo=*/nullptr,
7612 /*BitWidth=*/nullptr,
Ulrich Weigand47445072013-05-06 16:26:41 +00007613 /*Mutable=*/false,
7614 ICIS_NoInit);
7615 Field->setAccess(AS_public);
7616 VaListTagDecl->addDecl(Field);
7617 }
7618 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00007619 Context->VaListTagDecl = VaListTagDecl;
Ulrich Weigand47445072013-05-06 16:26:41 +00007620 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Ulrich Weigand47445072013-05-06 16:26:41 +00007621
Richard Smith9b88a4c2015-07-27 05:40:23 +00007622 // };
Ulrich Weigand47445072013-05-06 16:26:41 +00007623
7624 // typedef __va_list_tag __builtin_va_list[1];
7625 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00007626 QualType VaListTagArrayType =
7627 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Ulrich Weigand47445072013-05-06 16:26:41 +00007628
Alp Toker56b5cc92013-12-15 10:36:26 +00007629 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Ulrich Weigand47445072013-05-06 16:26:41 +00007630}
7631
Meador Inge5d3fb222012-06-16 03:34:49 +00007632static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
7633 TargetInfo::BuiltinVaListKind Kind) {
7634 switch (Kind) {
7635 case TargetInfo::CharPtrBuiltinVaList:
7636 return CreateCharPtrBuiltinVaListDecl(Context);
7637 case TargetInfo::VoidPtrBuiltinVaList:
7638 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northover9bb857a2013-01-31 12:13:10 +00007639 case TargetInfo::AArch64ABIBuiltinVaList:
7640 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00007641 case TargetInfo::PowerABIBuiltinVaList:
7642 return CreatePowerABIBuiltinVaListDecl(Context);
7643 case TargetInfo::X86_64ABIBuiltinVaList:
7644 return CreateX86_64ABIBuiltinVaListDecl(Context);
7645 case TargetInfo::PNaClABIBuiltinVaList:
7646 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00007647 case TargetInfo::AAPCSABIBuiltinVaList:
7648 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigand47445072013-05-06 16:26:41 +00007649 case TargetInfo::SystemZBuiltinVaList:
7650 return CreateSystemZBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00007651 }
7652
7653 llvm_unreachable("Unhandled __builtin_va_list type kind");
7654}
7655
7656TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00007657 if (!BuiltinVaListDecl) {
Meador Inge5d3fb222012-06-16 03:34:49 +00007658 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
Alp Toker56b5cc92013-12-15 10:36:26 +00007659 assert(BuiltinVaListDecl->isImplicit());
7660 }
Meador Inge5d3fb222012-06-16 03:34:49 +00007661
7662 return BuiltinVaListDecl;
7663}
7664
Richard Smith9b88a4c2015-07-27 05:40:23 +00007665Decl *ASTContext::getVaListTagDecl() const {
7666 // Force the creation of VaListTagDecl by building the __builtin_va_list
Meador Ingecfb60902012-07-01 15:57:25 +00007667 // declaration.
Richard Smith9b88a4c2015-07-27 05:40:23 +00007668 if (!VaListTagDecl)
7669 (void)getBuiltinVaListDecl();
Meador Ingecfb60902012-07-01 15:57:25 +00007670
Richard Smith9b88a4c2015-07-27 05:40:23 +00007671 return VaListTagDecl;
Meador Ingecfb60902012-07-01 15:57:25 +00007672}
7673
Charles Davisc7d5c942015-09-17 20:55:33 +00007674TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const {
7675 if (!BuiltinMSVaListDecl)
7676 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
7677
7678 return BuiltinMSVaListDecl;
7679}
7680
Erich Keane41af9712018-04-16 21:30:08 +00007681bool ASTContext::canBuiltinBeRedeclared(const FunctionDecl *FD) const {
7682 return BuiltinInfo.canBeRedeclared(FD->getBuiltinID());
7683}
7684
Ted Kremenek1b0ea822008-01-07 19:49:32 +00007685void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00007686 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00007687 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00007688
Ted Kremenek1b0ea822008-01-07 19:49:32 +00007689 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00007690}
7691
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007692/// Retrieve the template name that corresponds to a non-empty
John McCalld28ae272009-12-02 08:04:21 +00007693/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00007694TemplateName
7695ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
7696 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00007697 unsigned size = End - Begin;
7698 assert(size > 1 && "set is not overloaded!");
7699
7700 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
7701 size * sizeof(FunctionTemplateDecl*));
Eugene Zelenko7855e772018-04-03 00:11:50 +00007702 auto *OT = new (memory) OverloadedTemplateStorage(size);
John McCalld28ae272009-12-02 08:04:21 +00007703
7704 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00007705 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00007706 NamedDecl *D = *I;
7707 assert(isa<FunctionTemplateDecl>(D) ||
Richard Smithef53a3e2018-06-06 16:36:56 +00007708 isa<UnresolvedUsingValueDecl>(D) ||
John McCalld28ae272009-12-02 08:04:21 +00007709 (isa<UsingShadowDecl>(D) &&
7710 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
7711 *Storage++ = D;
7712 }
7713
7714 return TemplateName(OT);
7715}
7716
Richard Smithb23c5e82019-05-09 03:31:27 +00007717/// Retrieve a template name representing an unqualified-id that has been
7718/// assumed to name a template for ADL purposes.
7719TemplateName ASTContext::getAssumedTemplateName(DeclarationName Name) const {
7720 auto *OT = new (*this) AssumedTemplateStorage(Name);
7721 return TemplateName(OT);
7722}
7723
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007724/// Retrieve the template name that represents a qualified
Douglas Gregordc572a32009-03-30 22:58:21 +00007725/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00007726TemplateName
7727ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
7728 bool TemplateKeyword,
7729 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00007730 assert(NNS && "Missing nested-name-specifier in qualified template name");
Fangrui Song6907ce22018-07-30 19:24:48 +00007731
Douglas Gregorc42075a2010-02-04 18:10:26 +00007732 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00007733 llvm::FoldingSetNodeID ID;
7734 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
7735
Craig Topper36250ad2014-05-12 05:36:57 +00007736 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00007737 QualifiedTemplateName *QTN =
7738 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7739 if (!QTN) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007740 QTN = new (*this, alignof(QualifiedTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007741 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00007742 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
7743 }
7744
7745 return TemplateName(QTN);
7746}
7747
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007748/// Retrieve the template name that represents a dependent
Douglas Gregordc572a32009-03-30 22:58:21 +00007749/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00007750TemplateName
7751ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
7752 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00007753 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00007754 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00007755
7756 llvm::FoldingSetNodeID ID;
7757 DependentTemplateName::Profile(ID, NNS, Name);
7758
Craig Topper36250ad2014-05-12 05:36:57 +00007759 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00007760 DependentTemplateName *QTN =
7761 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7762
7763 if (QTN)
7764 return TemplateName(QTN);
7765
7766 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
7767 if (CanonNNS == NNS) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007768 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007769 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00007770 } else {
7771 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007772 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007773 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00007774 DependentTemplateName *CheckQTN =
7775 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7776 assert(!CheckQTN && "Dependent type name canonicalization broken");
7777 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00007778 }
7779
7780 DependentTemplateNames.InsertNode(QTN, InsertPos);
7781 return TemplateName(QTN);
7782}
7783
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007784/// Retrieve the template name that represents a dependent
Douglas Gregor71395fa2009-11-04 00:56:37 +00007785/// template name such as \c MetaFun::template operator+.
Fangrui Song6907ce22018-07-30 19:24:48 +00007786TemplateName
Douglas Gregor71395fa2009-11-04 00:56:37 +00007787ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00007788 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00007789 assert((!NNS || NNS->isDependent()) &&
7790 "Nested name specifier must be dependent");
Fangrui Song6907ce22018-07-30 19:24:48 +00007791
Douglas Gregor71395fa2009-11-04 00:56:37 +00007792 llvm::FoldingSetNodeID ID;
7793 DependentTemplateName::Profile(ID, NNS, Operator);
Craig Topper36250ad2014-05-12 05:36:57 +00007794
7795 void *InsertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00007796 DependentTemplateName *QTN
7797 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Fangrui Song6907ce22018-07-30 19:24:48 +00007798
Douglas Gregor71395fa2009-11-04 00:56:37 +00007799 if (QTN)
7800 return TemplateName(QTN);
Fangrui Song6907ce22018-07-30 19:24:48 +00007801
Douglas Gregor71395fa2009-11-04 00:56:37 +00007802 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
7803 if (CanonNNS == NNS) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007804 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007805 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00007806 } else {
7807 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007808 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007809 DependentTemplateName(NNS, Operator, Canon);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007810
Douglas Gregorc42075a2010-02-04 18:10:26 +00007811 DependentTemplateName *CheckQTN
7812 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7813 assert(!CheckQTN && "Dependent template name canonicalization broken");
7814 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00007815 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007816
Douglas Gregor71395fa2009-11-04 00:56:37 +00007817 DependentTemplateNames.InsertNode(QTN, InsertPos);
7818 return TemplateName(QTN);
7819}
7820
Fangrui Song6907ce22018-07-30 19:24:48 +00007821TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00007822ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
7823 TemplateName replacement) const {
7824 llvm::FoldingSetNodeID ID;
7825 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00007826
7827 void *insertPos = nullptr;
John McCalld9dfe3a2011-06-30 08:33:18 +00007828 SubstTemplateTemplateParmStorage *subst
7829 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
Fangrui Song6907ce22018-07-30 19:24:48 +00007830
John McCalld9dfe3a2011-06-30 08:33:18 +00007831 if (!subst) {
7832 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
7833 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
7834 }
7835
7836 return TemplateName(subst);
7837}
7838
Fangrui Song6907ce22018-07-30 19:24:48 +00007839TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00007840ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
7841 const TemplateArgument &ArgPack) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00007842 auto &Self = const_cast<ASTContext &>(*this);
Douglas Gregor5590be02011-01-15 06:45:20 +00007843 llvm::FoldingSetNodeID ID;
7844 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00007845
7846 void *InsertPos = nullptr;
Douglas Gregor5590be02011-01-15 06:45:20 +00007847 SubstTemplateTemplateParmPackStorage *Subst
7848 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
Fangrui Song6907ce22018-07-30 19:24:48 +00007849
Douglas Gregor5590be02011-01-15 06:45:20 +00007850 if (!Subst) {
Fangrui Song6907ce22018-07-30 19:24:48 +00007851 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00007852 ArgPack.pack_size(),
7853 ArgPack.pack_begin());
7854 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
7855 }
7856
7857 return TemplateName(Subst);
7858}
7859
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007860/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00007861/// TargetInfo, produce the corresponding type. The unsigned @p Type
7862/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00007863CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007864 switch (Type) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00007865 case TargetInfo::NoInt: return {};
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00007866 case TargetInfo::SignedChar: return SignedCharTy;
7867 case TargetInfo::UnsignedChar: return UnsignedCharTy;
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007868 case TargetInfo::SignedShort: return ShortTy;
7869 case TargetInfo::UnsignedShort: return UnsignedShortTy;
7870 case TargetInfo::SignedInt: return IntTy;
7871 case TargetInfo::UnsignedInt: return UnsignedIntTy;
7872 case TargetInfo::SignedLong: return LongTy;
7873 case TargetInfo::UnsignedLong: return UnsignedLongTy;
7874 case TargetInfo::SignedLongLong: return LongLongTy;
7875 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
7876 }
7877
David Blaikie83d382b2011-09-23 05:06:16 +00007878 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007879}
Ted Kremenek77c51b22008-07-24 23:58:27 +00007880
7881//===----------------------------------------------------------------------===//
7882// Type Predicates.
7883//===----------------------------------------------------------------------===//
7884
Fariborz Jahanian96207692009-02-18 21:49:28 +00007885/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
7886/// garbage collection attribute.
7887///
John McCall553d45a2011-01-12 00:34:59 +00007888Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007889 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00007890 return Qualifiers::GCNone;
7891
Erik Pilkingtonfa983902018-10-30 20:31:30 +00007892 assert(getLangOpts().ObjC);
John McCall553d45a2011-01-12 00:34:59 +00007893 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
7894
7895 // Default behaviour under objective-C's gc is for ObjC pointers
7896 // (or pointers to them) be treated as though they were declared
7897 // as __strong.
7898 if (GCAttrs == Qualifiers::GCNone) {
7899 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
7900 return Qualifiers::Strong;
7901 else if (Ty->isPointerType())
7902 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
7903 } else {
7904 // It's not valid to set GC attributes on anything that isn't a
7905 // pointer.
7906#ifndef NDEBUG
7907 QualType CT = Ty->getCanonicalTypeInternal();
Eugene Zelenko7855e772018-04-03 00:11:50 +00007908 while (const auto *AT = dyn_cast<ArrayType>(CT))
John McCall553d45a2011-01-12 00:34:59 +00007909 CT = AT->getElementType();
7910 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
7911#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00007912 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00007913 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00007914}
7915
Chris Lattner49af6a42008-04-07 06:51:04 +00007916//===----------------------------------------------------------------------===//
7917// Type Compatibility Testing
7918//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00007919
Mike Stump11289f42009-09-09 15:08:12 +00007920/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00007921/// compatible.
7922static bool areCompatVectorTypes(const VectorType *LHS,
7923 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00007924 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00007925 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00007926 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00007927}
7928
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007929bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
7930 QualType SecondVec) {
7931 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
7932 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
7933
7934 if (hasSameUnqualifiedType(FirstVec, SecondVec))
7935 return true;
7936
Bob Wilsone6aeebb2010-11-12 17:24:54 +00007937 // Treat Neon vector types and most AltiVec vector types as if they are the
7938 // equivalent GCC vector types.
Eugene Zelenko7855e772018-04-03 00:11:50 +00007939 const auto *First = FirstVec->getAs<VectorType>();
7940 const auto *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00007941 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007942 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00007943 First->getVectorKind() != VectorType::AltiVecPixel &&
7944 First->getVectorKind() != VectorType::AltiVecBool &&
7945 Second->getVectorKind() != VectorType::AltiVecPixel &&
7946 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007947 return true;
7948
7949 return false;
7950}
7951
Steve Naroff8e6aee52009-07-23 01:01:38 +00007952//===----------------------------------------------------------------------===//
7953// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
7954//===----------------------------------------------------------------------===//
7955
7956/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
7957/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00007958bool
7959ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
7960 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00007961 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00007962 return true;
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00007963 for (auto *PI : rProto->protocols())
7964 if (ProtocolCompatibleWithProtocol(lProto, PI))
Steve Naroff8e6aee52009-07-23 01:01:38 +00007965 return true;
7966 return false;
7967}
7968
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00007969/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
7970/// Class<pr1, ...>.
Fangrui Song6907ce22018-07-30 19:24:48 +00007971bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007972 QualType rhs) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00007973 const auto *lhsQID = lhs->getAs<ObjCObjectPointerType>();
7974 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00007975 assert((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
Fangrui Song6907ce22018-07-30 19:24:48 +00007976
Aaron Ballman83731462014-03-17 16:14:00 +00007977 for (auto *lhsProto : lhsQID->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007978 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00007979 for (auto *rhsProto : rhsOPT->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007980 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
7981 match = true;
7982 break;
7983 }
7984 }
7985 if (!match)
7986 return false;
7987 }
7988 return true;
7989}
7990
Steve Naroff8e6aee52009-07-23 01:01:38 +00007991/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
7992/// ObjCQualifiedIDType.
7993bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
7994 bool compare) {
7995 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00007996 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00007997 lhs->isObjCIdType() || lhs->isObjCClassType())
7998 return true;
Mike Stump11289f42009-09-09 15:08:12 +00007999 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00008000 rhs->isObjCIdType() || rhs->isObjCClassType())
8001 return true;
8002
8003 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00008004 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00008005
Steve Naroff8e6aee52009-07-23 01:01:38 +00008006 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00008007
Steve Naroff8e6aee52009-07-23 01:01:38 +00008008 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00008009 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00008010 // make sure we check the class hierarchy.
8011 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00008012 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00008013 // when comparing an id<P> on lhs with a static type on rhs,
8014 // see if static class implements all of id's protocols, directly or
8015 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00008016 if (!rhsID->ClassImplementsProtocol(I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00008017 return false;
8018 }
8019 }
8020 // If there are no qualifiers and no interface, we have an 'id'.
8021 return true;
8022 }
Mike Stump11289f42009-09-09 15:08:12 +00008023 // Both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00008024 for (auto *lhsProto : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00008025 bool match = false;
8026
8027 // when comparing an id<P> on lhs with a static type on rhs,
8028 // see if static class implements all of id's protocols, directly or
8029 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00008030 for (auto *rhsProto : rhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00008031 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
8032 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
8033 match = true;
8034 break;
8035 }
8036 }
Mike Stump11289f42009-09-09 15:08:12 +00008037 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00008038 // make sure we check the class hierarchy.
8039 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00008040 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00008041 // when comparing an id<P> on lhs with a static type on rhs,
8042 // see if static class implements all of id's protocols, directly or
8043 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00008044 if (rhsID->ClassImplementsProtocol(I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00008045 match = true;
8046 break;
8047 }
8048 }
8049 }
8050 if (!match)
8051 return false;
8052 }
Mike Stump11289f42009-09-09 15:08:12 +00008053
Steve Naroff8e6aee52009-07-23 01:01:38 +00008054 return true;
8055 }
Mike Stump11289f42009-09-09 15:08:12 +00008056
Steve Naroff8e6aee52009-07-23 01:01:38 +00008057 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
8058 assert(rhsQID && "One of the LHS/RHS should be id<x>");
8059
Mike Stump11289f42009-09-09 15:08:12 +00008060 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00008061 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00008062 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00008063 for (auto *lhsProto : lhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00008064 bool match = false;
8065
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00008066 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00008067 // see if static class implements all of id's protocols, directly or
8068 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00008069 // First, lhs protocols in the qualifier list must be found, direct
8070 // or indirect in rhs's qualifier list or it is a mismatch.
Aaron Ballman83731462014-03-17 16:14:00 +00008071 for (auto *rhsProto : rhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00008072 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
8073 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
8074 match = true;
8075 break;
8076 }
8077 }
8078 if (!match)
8079 return false;
8080 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008081
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00008082 // Static class's protocols, or its super class or category protocols
8083 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
8084 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
8085 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
8086 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
8087 // This is rather dubious but matches gcc's behavior. If lhs has
8088 // no type qualifier and its class has no static protocol(s)
8089 // assume that it is mismatch.
8090 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
8091 return false;
Aaron Ballman83731462014-03-17 16:14:00 +00008092 for (auto *lhsProto : LHSInheritedProtocols) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00008093 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00008094 for (auto *rhsProto : rhsQID->quals()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00008095 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
8096 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
8097 match = true;
8098 break;
8099 }
8100 }
8101 if (!match)
8102 return false;
8103 }
8104 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00008105 return true;
8106 }
8107 return false;
8108}
8109
Eli Friedman47f77112008-08-22 00:56:42 +00008110/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00008111/// compatible for assignment from RHS to LHS. This handles validation of any
8112/// protocol qualifiers on the LHS or RHS.
Steve Naroff7cae42b2009-07-10 23:34:53 +00008113bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
8114 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00008115 const ObjCObjectType* LHS = LHSOPT->getObjectType();
8116 const ObjCObjectType* RHS = RHSOPT->getObjectType();
8117
Steve Naroff1329fa02009-07-15 18:40:39 +00008118 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00008119 if (LHS->isObjCUnqualifiedIdOrClass() ||
8120 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00008121 return true;
8122
Douglas Gregorab209d82015-07-07 03:58:42 +00008123 // Function object that propagates a successful result or handles
8124 // __kindof types.
8125 auto finish = [&](bool succeeded) -> bool {
8126 if (succeeded)
8127 return true;
8128
8129 if (!RHS->isKindOfType())
8130 return false;
8131
8132 // Strip off __kindof and protocol qualifiers, then check whether
8133 // we can assign the other way.
8134 return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this),
8135 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
8136 };
8137
8138 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
8139 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
8140 QualType(RHSOPT,0),
8141 false));
8142 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008143
Douglas Gregorab209d82015-07-07 03:58:42 +00008144 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
8145 return finish(ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
8146 QualType(RHSOPT,0)));
8147 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008148
John McCall8b07ec22010-05-15 11:32:37 +00008149 // If we have 2 user-defined types, fall into that path.
Douglas Gregorab209d82015-07-07 03:58:42 +00008150 if (LHS->getInterface() && RHS->getInterface()) {
8151 return finish(canAssignObjCInterfaces(LHS, RHS));
8152 }
Mike Stump11289f42009-09-09 15:08:12 +00008153
Steve Naroff8e6aee52009-07-23 01:01:38 +00008154 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00008155}
8156
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008157/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Fangrui Song6907ce22018-07-30 19:24:48 +00008158/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008159/// arguments in block literals. When passed as arguments, passing 'A*' where
8160/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
8161/// not OK. For the return type, the opposite is not OK.
8162bool ASTContext::canAssignObjCInterfacesInBlockPointer(
8163 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00008164 const ObjCObjectPointerType *RHSOPT,
8165 bool BlockReturnType) {
Douglas Gregorab209d82015-07-07 03:58:42 +00008166
8167 // Function object that propagates a successful result or handles
8168 // __kindof types.
8169 auto finish = [&](bool succeeded) -> bool {
8170 if (succeeded)
8171 return true;
8172
8173 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
8174 if (!Expected->isKindOfType())
8175 return false;
8176
8177 // Strip off __kindof and protocol qualifiers, then check whether
8178 // we can assign the other way.
8179 return canAssignObjCInterfacesInBlockPointer(
8180 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
8181 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
8182 BlockReturnType);
8183 };
8184
Fariborz Jahanian440a6832010-04-06 17:23:39 +00008185 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008186 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00008187
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008188 if (LHSOPT->isObjCBuiltinType()) {
Douglas Gregorab209d82015-07-07 03:58:42 +00008189 return finish(RHSOPT->isObjCBuiltinType() ||
8190 RHSOPT->isObjCQualifiedIdType());
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008191 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008192
Fariborz Jahanian440a6832010-04-06 17:23:39 +00008193 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Douglas Gregorab209d82015-07-07 03:58:42 +00008194 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
8195 QualType(RHSOPT,0),
8196 false));
Fangrui Song6907ce22018-07-30 19:24:48 +00008197
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008198 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
8199 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
8200 if (LHS && RHS) { // We have 2 user-defined types.
8201 if (LHS != RHS) {
8202 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00008203 return finish(BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008204 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00008205 return finish(!BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008206 }
8207 else
8208 return true;
8209 }
8210 return false;
8211}
8212
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008213/// Comparison routine for Objective-C protocols to be used with
8214/// llvm::array_pod_sort.
8215static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
8216 ObjCProtocolDecl * const *rhs) {
8217 return (*lhs)->getName().compare((*rhs)->getName());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008218}
8219
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008220/// getIntersectionOfProtocols - This routine finds the intersection of set
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008221/// of protocols inherited from two distinct objective-c pointer objects with
8222/// the given common base.
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008223/// It is used to build composite qualifier list of the composite type of
8224/// the conditional expression involving two objective-c pointer objects.
Fangrui Song6907ce22018-07-30 19:24:48 +00008225static
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008226void getIntersectionOfProtocols(ASTContext &Context,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008227 const ObjCInterfaceDecl *CommonBase,
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008228 const ObjCObjectPointerType *LHSOPT,
8229 const ObjCObjectPointerType *RHSOPT,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008230 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
Fangrui Song6907ce22018-07-30 19:24:48 +00008231
John McCall8b07ec22010-05-15 11:32:37 +00008232 const ObjCObjectType* LHS = LHSOPT->getObjectType();
8233 const ObjCObjectType* RHS = RHSOPT->getObjectType();
8234 assert(LHS->getInterface() && "LHS must have an interface base");
8235 assert(RHS->getInterface() && "RHS must have an interface base");
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008236
8237 // Add all of the protocols for the LHS.
8238 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
8239
8240 // Start with the protocol qualifiers.
8241 for (auto proto : LHS->quals()) {
8242 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008243 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008244
8245 // Also add the protocols associated with the LHS interface.
8246 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
8247
Raphael Isemannb23ccec2018-12-10 12:37:46 +00008248 // Add all of the protocols for the RHS.
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008249 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
8250
8251 // Start with the protocol qualifiers.
8252 for (auto proto : RHS->quals()) {
8253 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008254 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008255
8256 // Also add the protocols associated with the RHS interface.
8257 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
8258
8259 // Compute the intersection of the collected protocol sets.
8260 for (auto proto : LHSProtocolSet) {
8261 if (RHSProtocolSet.count(proto))
8262 IntersectionSet.push_back(proto);
8263 }
8264
8265 // Compute the set of protocols that is implied by either the common type or
8266 // the protocols within the intersection.
8267 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
8268 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
8269
8270 // Remove any implied protocols from the list of inherited protocols.
8271 if (!ImpliedProtocols.empty()) {
8272 IntersectionSet.erase(
8273 std::remove_if(IntersectionSet.begin(),
8274 IntersectionSet.end(),
8275 [&](ObjCProtocolDecl *proto) -> bool {
8276 return ImpliedProtocols.count(proto) > 0;
8277 }),
8278 IntersectionSet.end());
8279 }
8280
8281 // Sort the remaining protocols by name.
8282 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
8283 compareObjCProtocolsByName);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008284}
8285
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008286/// Determine whether the first type is a subtype of the second.
8287static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
8288 QualType rhs) {
8289 // Common case: two object pointers.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008290 const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
8291 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008292 if (lhsOPT && rhsOPT)
8293 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
8294
8295 // Two block pointers.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008296 const auto *lhsBlock = lhs->getAs<BlockPointerType>();
8297 const auto *rhsBlock = rhs->getAs<BlockPointerType>();
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008298 if (lhsBlock && rhsBlock)
8299 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
8300
8301 // If either is an unqualified 'id' and the other is a block, it's
8302 // acceptable.
8303 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
8304 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
8305 return true;
8306
8307 return false;
8308}
8309
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008310// Check that the given Objective-C type argument lists are equivalent.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008311static bool sameObjCTypeArgs(ASTContext &ctx,
8312 const ObjCInterfaceDecl *iface,
8313 ArrayRef<QualType> lhsArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00008314 ArrayRef<QualType> rhsArgs,
8315 bool stripKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008316 if (lhsArgs.size() != rhsArgs.size())
8317 return false;
8318
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008319 ObjCTypeParamList *typeParams = iface->getTypeParamList();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008320 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008321 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
8322 continue;
8323
8324 switch (typeParams->begin()[i]->getVariance()) {
8325 case ObjCTypeParamVariance::Invariant:
Douglas Gregorab209d82015-07-07 03:58:42 +00008326 if (!stripKindOf ||
8327 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
8328 rhsArgs[i].stripObjCKindOfType(ctx))) {
8329 return false;
8330 }
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008331 break;
8332
8333 case ObjCTypeParamVariance::Covariant:
8334 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
8335 return false;
8336 break;
8337
8338 case ObjCTypeParamVariance::Contravariant:
8339 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
8340 return false;
8341 break;
Douglas Gregorab209d82015-07-07 03:58:42 +00008342 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008343 }
8344
8345 return true;
8346}
8347
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00008348QualType ASTContext::areCommonBaseCompatible(
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008349 const ObjCObjectPointerType *Lptr,
8350 const ObjCObjectPointerType *Rptr) {
John McCall8b07ec22010-05-15 11:32:37 +00008351 const ObjCObjectType *LHS = Lptr->getObjectType();
8352 const ObjCObjectType *RHS = Rptr->getObjectType();
8353 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
8354 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008355
8356 if (!LDecl || !RDecl)
Eugene Zelenko7855e772018-04-03 00:11:50 +00008357 return {};
Douglas Gregore83b9562015-07-07 03:57:53 +00008358
Manman Renc46f7d12016-05-06 19:35:02 +00008359 // When either LHS or RHS is a kindof type, we should return a kindof type.
8360 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
8361 // kindof(A).
8362 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
8363
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008364 // Follow the left-hand side up the class hierarchy until we either hit a
8365 // root or find the RHS. Record the ancestors in case we don't find it.
8366 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
8367 LHSAncestors;
8368 while (true) {
8369 // Record this ancestor. We'll need this if the common type isn't in the
8370 // path from the LHS to the root.
8371 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
Douglas Gregore83b9562015-07-07 03:57:53 +00008372
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008373 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
8374 // Get the type arguments.
8375 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
8376 bool anyChanges = false;
8377 if (LHS->isSpecialized() && RHS->isSpecialized()) {
8378 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008379 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
8380 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00008381 /*stripKindOf=*/true))
Eugene Zelenko7855e772018-04-03 00:11:50 +00008382 return {};
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008383 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
8384 // If only one has type arguments, the result will not have type
8385 // arguments.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00008386 LHSTypeArgs = {};
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008387 anyChanges = true;
8388 }
8389
8390 // Compute the intersection of protocols.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008391 SmallVector<ObjCProtocolDecl *, 8> Protocols;
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008392 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
8393 Protocols);
John McCall8b07ec22010-05-15 11:32:37 +00008394 if (!Protocols.empty())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008395 anyChanges = true;
8396
8397 // If anything in the LHS will have changed, build a new result type.
Manman Renc46f7d12016-05-06 19:35:02 +00008398 // If we need to return a kindof type but LHS is not a kindof type, we
8399 // build a new result type.
8400 if (anyChanges || LHS->isKindOfType() != anyKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008401 QualType Result = getObjCInterfaceType(LHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00008402 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
Manman Renc46f7d12016-05-06 19:35:02 +00008403 anyKindOf || LHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008404 return getObjCObjectPointerType(Result);
8405 }
8406
8407 return getObjCObjectPointerType(QualType(LHS, 0));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008408 }
Douglas Gregore83b9562015-07-07 03:57:53 +00008409
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008410 // Find the superclass.
Douglas Gregore83b9562015-07-07 03:57:53 +00008411 QualType LHSSuperType = LHS->getSuperClassType();
8412 if (LHSSuperType.isNull())
8413 break;
8414
8415 LHS = LHSSuperType->castAs<ObjCObjectType>();
8416 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008417
8418 // We didn't find anything by following the LHS to its root; now check
8419 // the RHS against the cached set of ancestors.
8420 while (true) {
8421 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
8422 if (KnownLHS != LHSAncestors.end()) {
8423 LHS = KnownLHS->second;
8424
8425 // Get the type arguments.
8426 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
8427 bool anyChanges = false;
8428 if (LHS->isSpecialized() && RHS->isSpecialized()) {
8429 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008430 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
8431 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00008432 /*stripKindOf=*/true))
Eugene Zelenko7855e772018-04-03 00:11:50 +00008433 return {};
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008434 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
8435 // If only one has type arguments, the result will not have type
8436 // arguments.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00008437 RHSTypeArgs = {};
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008438 anyChanges = true;
8439 }
8440
8441 // Compute the intersection of protocols.
8442 SmallVector<ObjCProtocolDecl *, 8> Protocols;
8443 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
8444 Protocols);
8445 if (!Protocols.empty())
8446 anyChanges = true;
8447
Manman Renc46f7d12016-05-06 19:35:02 +00008448 // If we need to return a kindof type but RHS is not a kindof type, we
8449 // build a new result type.
8450 if (anyChanges || RHS->isKindOfType() != anyKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008451 QualType Result = getObjCInterfaceType(RHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00008452 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
Manman Renc46f7d12016-05-06 19:35:02 +00008453 anyKindOf || RHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008454 return getObjCObjectPointerType(Result);
8455 }
8456
8457 return getObjCObjectPointerType(QualType(RHS, 0));
8458 }
8459
8460 // Find the superclass of the RHS.
8461 QualType RHSSuperType = RHS->getSuperClassType();
8462 if (RHSSuperType.isNull())
8463 break;
8464
8465 RHS = RHSSuperType->castAs<ObjCObjectType>();
8466 }
8467
Eugene Zelenko7855e772018-04-03 00:11:50 +00008468 return {};
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00008469}
8470
John McCall8b07ec22010-05-15 11:32:37 +00008471bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
8472 const ObjCObjectType *RHS) {
8473 assert(LHS->getInterface() && "LHS is not an interface type");
8474 assert(RHS->getInterface() && "RHS is not an interface type");
8475
Chris Lattner49af6a42008-04-07 06:51:04 +00008476 // Verify that the base decls are compatible: the RHS must be a subclass of
8477 // the LHS.
Douglas Gregore83b9562015-07-07 03:57:53 +00008478 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
8479 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
8480 if (!IsSuperClass)
Chris Lattner49af6a42008-04-07 06:51:04 +00008481 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008482
Douglas Gregore83b9562015-07-07 03:57:53 +00008483 // If the LHS has protocol qualifiers, determine whether all of them are
8484 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
8485 // LHS).
8486 if (LHS->getNumProtocols() > 0) {
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00008487 // OK if conversion of LHS to SuperClass results in narrowing of types
8488 // ; i.e., SuperClass may implement at least one of the protocols
8489 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
8490 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
8491 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
8492 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
8493 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
8494 // qualifiers.
8495 for (auto *RHSPI : RHS->quals())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008496 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00008497 // If there is no protocols associated with RHS, it is not a match.
8498 if (SuperClassInheritedProtocols.empty())
Steve Naroff114aecb2009-03-01 16:12:44 +00008499 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00008500
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00008501 for (const auto *LHSProto : LHS->quals()) {
8502 bool SuperImplementsProtocol = false;
8503 for (auto *SuperClassProto : SuperClassInheritedProtocols)
8504 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
8505 SuperImplementsProtocol = true;
8506 break;
8507 }
8508 if (!SuperImplementsProtocol)
8509 return false;
8510 }
Chris Lattner49af6a42008-04-07 06:51:04 +00008511 }
Douglas Gregore83b9562015-07-07 03:57:53 +00008512
8513 // If the LHS is specialized, we may need to check type arguments.
8514 if (LHS->isSpecialized()) {
8515 // Follow the superclass chain until we've matched the LHS class in the
8516 // hierarchy. This substitutes type arguments through.
8517 const ObjCObjectType *RHSSuper = RHS;
8518 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
8519 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
8520
8521 // If the RHS is specializd, compare type arguments.
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008522 if (RHSSuper->isSpecialized() &&
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008523 !sameObjCTypeArgs(*this, LHS->getInterface(),
8524 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00008525 /*stripKindOf=*/true)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008526 return false;
Douglas Gregore83b9562015-07-07 03:57:53 +00008527 }
8528 }
8529
8530 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00008531}
8532
Steve Naroffb7605152009-02-12 17:52:19 +00008533bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
8534 // get the "pointed to" types
Eugene Zelenko7855e772018-04-03 00:11:50 +00008535 const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
8536 const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00008537
Steve Naroff7cae42b2009-07-10 23:34:53 +00008538 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00008539 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00008540
8541 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
8542 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00008543}
8544
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00008545bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
8546 return canAssignObjCInterfaces(
8547 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
8548 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
8549}
8550
Mike Stump11289f42009-09-09 15:08:12 +00008551/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00008552/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00008553/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00008554/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008555bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
8556 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00008557 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00008558 return hasSameType(LHS, RHS);
Joey Gouly5788b782016-11-18 14:10:54 +00008559
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008560 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00008561}
8562
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00008563bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00008564 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00008565}
8566
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008567bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
8568 return !mergeTypes(LHS, RHS, true).isNull();
8569}
8570
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00008571/// mergeTransparentUnionType - if T is a transparent union type and a member
8572/// of T is compatible with SubType, return the merged type, else return
8573/// QualType()
8574QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
8575 bool OfBlockPointer,
8576 bool Unqualified) {
8577 if (const RecordType *UT = T->getAsUnionType()) {
8578 RecordDecl *UD = UT->getDecl();
8579 if (UD->hasAttr<TransparentUnionAttr>()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008580 for (const auto *I : UD->fields()) {
8581 QualType ET = I->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00008582 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
8583 if (!MT.isNull())
8584 return MT;
8585 }
8586 }
8587 }
8588
Eugene Zelenko7855e772018-04-03 00:11:50 +00008589 return {};
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00008590}
8591
Alp Toker9cacbab2014-01-20 20:26:09 +00008592/// mergeFunctionParameterTypes - merge two types which appear as function
8593/// parameter types
8594QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
8595 bool OfBlockPointer,
8596 bool Unqualified) {
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00008597 // GNU extension: two types are compatible if they appear as a function
8598 // argument, one of the types is a transparent union type and the other
8599 // type is compatible with a union member
8600 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
8601 Unqualified);
8602 if (!lmerge.isNull())
8603 return lmerge;
8604
8605 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
8606 Unqualified);
8607 if (!rmerge.isNull())
8608 return rmerge;
8609
8610 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
8611}
8612
Fangrui Song6907ce22018-07-30 19:24:48 +00008613QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008614 bool OfBlockPointer,
8615 bool Unqualified) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00008616 const auto *lbase = lhs->getAs<FunctionType>();
8617 const auto *rbase = rhs->getAs<FunctionType>();
8618 const auto *lproto = dyn_cast<FunctionProtoType>(lbase);
8619 const auto *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00008620 bool allLTypes = true;
8621 bool allRTypes = true;
8622
8623 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008624 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00008625 if (OfBlockPointer) {
Alp Toker314cc812014-01-25 16:55:45 +00008626 QualType RHS = rbase->getReturnType();
8627 QualType LHS = lbase->getReturnType();
Fariborz Jahanian17825972011-02-11 18:46:17 +00008628 bool UnqualifiedResult = Unqualified;
8629 if (!UnqualifiedResult)
8630 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00008631 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00008632 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008633 else
Alp Toker314cc812014-01-25 16:55:45 +00008634 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
John McCall8c6b56f2010-12-15 01:06:38 +00008635 Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00008636 if (retType.isNull())
8637 return {};
Fangrui Song6907ce22018-07-30 19:24:48 +00008638
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008639 if (Unqualified)
8640 retType = retType.getUnqualifiedType();
8641
Alp Toker314cc812014-01-25 16:55:45 +00008642 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
8643 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008644 if (Unqualified) {
8645 LRetType = LRetType.getUnqualifiedType();
8646 RRetType = RRetType.getUnqualifiedType();
8647 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008648
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008649 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00008650 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008651 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00008652 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00008653
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00008654 // FIXME: double check this
8655 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
8656 // rbase->getRegParmAttr() != 0 &&
8657 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00008658 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
8659 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00008660
Douglas Gregor8c940862010-01-18 17:14:39 +00008661 // Compatible functions must have compatible calling conventions
Reid Kleckner78af0702013-08-27 23:08:25 +00008662 if (lbaseInfo.getCC() != rbaseInfo.getCC())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008663 return {};
Mike Stump11289f42009-09-09 15:08:12 +00008664
John McCall8c6b56f2010-12-15 01:06:38 +00008665 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00008666 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008667 return {};
John McCall8c6b56f2010-12-15 01:06:38 +00008668 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008669 return {};
John McCall8c6b56f2010-12-15 01:06:38 +00008670
John McCall31168b02011-06-15 23:02:42 +00008671 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008672 return {};
Oren Ben Simhon318a6ea2017-04-27 12:01:00 +00008673 if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008674 return {};
Oren Ben Simhon220671a2018-03-17 13:31:35 +00008675 if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008676 return {};
John McCall31168b02011-06-15 23:02:42 +00008677
John McCall8c6b56f2010-12-15 01:06:38 +00008678 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
8679 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00008680
Rafael Espindola8778c282012-11-29 16:09:03 +00008681 if (lbaseInfo.getNoReturn() != NoReturn)
8682 allLTypes = false;
8683 if (rbaseInfo.getNoReturn() != NoReturn)
8684 allRTypes = false;
8685
John McCall31168b02011-06-15 23:02:42 +00008686 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00008687
Eli Friedman47f77112008-08-22 00:56:42 +00008688 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00008689 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
8690 "C++ shouldn't be here");
Alp Toker601b22c2014-01-21 23:35:24 +00008691 // Compatible functions must have the same number of parameters
8692 if (lproto->getNumParams() != rproto->getNumParams())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008693 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00008694
8695 // Variadic and non-variadic functions aren't compatible
8696 if (lproto->isVariadic() != rproto->isVariadic())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008697 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00008698
Anastasia Stulovac61eaa52019-01-28 11:37:49 +00008699 if (lproto->getMethodQuals() != rproto->getMethodQuals())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008700 return {};
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00008701
Akira Hatanaka98a49332017-09-22 00:41:05 +00008702 SmallVector<FunctionProtoType::ExtParameterInfo, 4> newParamInfos;
8703 bool canUseLeft, canUseRight;
8704 if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight,
8705 newParamInfos))
Eugene Zelenko7855e772018-04-03 00:11:50 +00008706 return {};
Alp Toker601b22c2014-01-21 23:35:24 +00008707
Akira Hatanaka98a49332017-09-22 00:41:05 +00008708 if (!canUseLeft)
8709 allLTypes = false;
8710 if (!canUseRight)
8711 allRTypes = false;
8712
Alp Toker601b22c2014-01-21 23:35:24 +00008713 // Check parameter type compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008714 SmallVector<QualType, 10> types;
Alp Toker601b22c2014-01-21 23:35:24 +00008715 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
8716 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
8717 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
8718 QualType paramType = mergeFunctionParameterTypes(
8719 lParamType, rParamType, OfBlockPointer, Unqualified);
8720 if (paramType.isNull())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008721 return {};
Alp Toker601b22c2014-01-21 23:35:24 +00008722
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008723 if (Unqualified)
Alp Toker601b22c2014-01-21 23:35:24 +00008724 paramType = paramType.getUnqualifiedType();
8725
8726 types.push_back(paramType);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008727 if (Unqualified) {
Alp Toker601b22c2014-01-21 23:35:24 +00008728 lParamType = lParamType.getUnqualifiedType();
8729 rParamType = rParamType.getUnqualifiedType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008730 }
Alp Toker601b22c2014-01-21 23:35:24 +00008731
8732 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00008733 allLTypes = false;
Alp Toker601b22c2014-01-21 23:35:24 +00008734 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00008735 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00008736 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008737
Eli Friedman47f77112008-08-22 00:56:42 +00008738 if (allLTypes) return lhs;
8739 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00008740
8741 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
8742 EPI.ExtInfo = einfo;
Akira Hatanaka98a49332017-09-22 00:41:05 +00008743 EPI.ExtParameterInfos =
8744 newParamInfos.empty() ? nullptr : newParamInfos.data();
Jordan Rose5c382722013-03-08 21:51:21 +00008745 return getFunctionType(retType, types, EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00008746 }
8747
8748 if (lproto) allRTypes = false;
8749 if (rproto) allLTypes = false;
8750
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008751 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00008752 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00008753 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eugene Zelenko7855e772018-04-03 00:11:50 +00008754 if (proto->isVariadic())
8755 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00008756 // Check that the types are compatible with the types that
8757 // would result from default argument promotions (C99 6.7.5.3p15).
8758 // The only types actually affected are promotable integer
8759 // types and floats, which would be passed as a different
8760 // type depending on whether the prototype is visible.
Alp Toker601b22c2014-01-21 23:35:24 +00008761 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
8762 QualType paramTy = proto->getParamType(i);
Alp Toker9cacbab2014-01-20 20:26:09 +00008763
Eli Friedman448ce402012-08-30 00:44:15 +00008764 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00008765 // to pass enum values.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008766 if (const auto *Enum = paramTy->getAs<EnumType>()) {
Alp Toker601b22c2014-01-21 23:35:24 +00008767 paramTy = Enum->getDecl()->getIntegerType();
8768 if (paramTy.isNull())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008769 return {};
Eli Friedman448ce402012-08-30 00:44:15 +00008770 }
Alp Toker601b22c2014-01-21 23:35:24 +00008771
8772 if (paramTy->isPromotableIntegerType() ||
8773 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
Eugene Zelenko7855e772018-04-03 00:11:50 +00008774 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00008775 }
8776
8777 if (allLTypes) return lhs;
8778 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00008779
8780 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
8781 EPI.ExtInfo = einfo;
Alp Toker9cacbab2014-01-20 20:26:09 +00008782 return getFunctionType(retType, proto->getParamTypes(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00008783 }
8784
8785 if (allLTypes) return lhs;
8786 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00008787 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00008788}
8789
John McCall433c2e62013-03-21 00:10:07 +00008790/// Given that we have an enum type and a non-enum type, try to merge them.
8791static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
8792 QualType other, bool isBlockReturnType) {
8793 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
8794 // a signed integer type, or an unsigned integer type.
8795 // Compatibility is based on the underlying type, not the promotion
8796 // type.
8797 QualType underlyingType = ET->getDecl()->getIntegerType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00008798 if (underlyingType.isNull())
8799 return {};
John McCall433c2e62013-03-21 00:10:07 +00008800 if (Context.hasSameType(underlyingType, other))
8801 return other;
8802
8803 // In block return types, we're more permissive and accept any
8804 // integral type of the same size.
8805 if (isBlockReturnType && other->isIntegerType() &&
8806 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
8807 return other;
8808
Eugene Zelenko7855e772018-04-03 00:11:50 +00008809 return {};
John McCall433c2e62013-03-21 00:10:07 +00008810}
8811
Fangrui Song6907ce22018-07-30 19:24:48 +00008812QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008813 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00008814 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00008815 // C++ [expr]: If an expression initially has the type "reference to T", the
8816 // type is adjusted to "T" prior to any further analysis, the expression
8817 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00008818 // expression is an lvalue unless the reference is an rvalue reference and
8819 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00008820 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
8821 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008822
8823 if (Unqualified) {
8824 LHS = LHS.getUnqualifiedType();
8825 RHS = RHS.getUnqualifiedType();
8826 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008827
Eli Friedman47f77112008-08-22 00:56:42 +00008828 QualType LHSCan = getCanonicalType(LHS),
8829 RHSCan = getCanonicalType(RHS);
8830
8831 // If two types are identical, they are compatible.
8832 if (LHSCan == RHSCan)
8833 return LHS;
8834
John McCall8ccfcb52009-09-24 19:53:00 +00008835 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00008836 Qualifiers LQuals = LHSCan.getLocalQualifiers();
8837 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00008838 if (LQuals != RQuals) {
8839 // If any of these qualifiers are different, we have a type
8840 // mismatch.
8841 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00008842 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
Roger Ferrer Ibanezd93add32017-02-24 08:41:09 +00008843 LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
8844 LQuals.hasUnaligned() != RQuals.hasUnaligned())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008845 return {};
John McCall8ccfcb52009-09-24 19:53:00 +00008846
8847 // Exactly one GC qualifier difference is allowed: __strong is
8848 // okay if the other type has no GC qualifier but is an Objective
8849 // C object pointer (i.e. implicitly strong by default). We fix
8850 // this by pretending that the unqualified type was actually
8851 // qualified __strong.
8852 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
8853 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
8854 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
8855
8856 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
Eugene Zelenko7855e772018-04-03 00:11:50 +00008857 return {};
John McCall8ccfcb52009-09-24 19:53:00 +00008858
8859 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
8860 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
8861 }
8862 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
8863 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
8864 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00008865 return {};
John McCall8ccfcb52009-09-24 19:53:00 +00008866 }
8867
8868 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00008869
Eli Friedmandcca6332009-06-01 01:22:52 +00008870 Type::TypeClass LHSClass = LHSCan->getTypeClass();
8871 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00008872
Chris Lattnerfd652912008-01-14 05:45:46 +00008873 // We want to consider the two function types to be the same for these
8874 // comparisons, just force one to the other.
8875 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
8876 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00008877
8878 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00008879 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
8880 LHSClass = Type::ConstantArray;
8881 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
8882 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00008883
John McCall8b07ec22010-05-15 11:32:37 +00008884 // ObjCInterfaces are just specialized ObjCObjects.
8885 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
8886 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
8887
Nate Begemance4d7fc2008-04-18 23:10:10 +00008888 // Canonicalize ExtVector -> Vector.
8889 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
8890 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00008891
Chris Lattner95554662008-04-07 05:43:21 +00008892 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00008893 if (LHSClass != RHSClass) {
John McCall433c2e62013-03-21 00:10:07 +00008894 // Note that we only have special rules for turning block enum
8895 // returns into block int returns, not vice-versa.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008896 if (const auto *ETy = LHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00008897 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00008898 }
John McCall9dd450b2009-09-21 23:43:11 +00008899 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00008900 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00008901 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00008902 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00008903 if (OfBlockPointer && !BlockReturnType) {
8904 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
8905 return LHS;
8906 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
8907 return RHS;
8908 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008909
Eugene Zelenko7855e772018-04-03 00:11:50 +00008910 return {};
Steve Naroff32e44c02007-10-15 20:41:53 +00008911 }
Eli Friedman47f77112008-08-22 00:56:42 +00008912
Steve Naroffc6edcbd2008-01-09 22:43:08 +00008913 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00008914 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008915#define TYPE(Class, Base)
8916#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00008917#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008918#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
8919#define DEPENDENT_TYPE(Class, Base) case Type::Class:
8920#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00008921 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008922
Richard Smith27d807c2013-04-30 13:56:41 +00008923 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00008924 case Type::DeducedTemplateSpecialization:
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00008925 case Type::LValueReference:
8926 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008927 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00008928 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008929
John McCall8b07ec22010-05-15 11:32:37 +00008930 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008931 case Type::IncompleteArray:
8932 case Type::VariableArray:
8933 case Type::FunctionProto:
8934 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00008935 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008936
Chris Lattnerfd652912008-01-14 05:45:46 +00008937 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00008938 {
8939 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008940 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
8941 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008942 if (Unqualified) {
8943 LHSPointee = LHSPointee.getUnqualifiedType();
8944 RHSPointee = RHSPointee.getUnqualifiedType();
8945 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008946 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008947 Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00008948 if (ResultType.isNull())
8949 return {};
Eli Friedman091a9ac2009-06-02 05:28:56 +00008950 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00008951 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00008952 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00008953 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00008954 return getPointerType(ResultType);
8955 }
Steve Naroff68e167d2008-12-10 17:49:55 +00008956 case Type::BlockPointer:
8957 {
8958 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008959 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
8960 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008961 if (Unqualified) {
8962 LHSPointee = LHSPointee.getUnqualifiedType();
8963 RHSPointee = RHSPointee.getUnqualifiedType();
8964 }
Anastasia Stulova81a25e352017-03-10 15:23:07 +00008965 if (getLangOpts().OpenCL) {
8966 Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
8967 Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
8968 // Blocks can't be an expression in a ternary operator (OpenCL v2.0
8969 // 6.12.5) thus the following check is asymmetric.
8970 if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual))
Eugene Zelenko7855e772018-04-03 00:11:50 +00008971 return {};
Anastasia Stulova81a25e352017-03-10 15:23:07 +00008972 LHSPteeQual.removeAddressSpace();
8973 RHSPteeQual.removeAddressSpace();
8974 LHSPointee =
8975 QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
8976 RHSPointee =
8977 QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
8978 }
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008979 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
8980 Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00008981 if (ResultType.isNull())
8982 return {};
Steve Naroff68e167d2008-12-10 17:49:55 +00008983 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
8984 return LHS;
8985 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
8986 return RHS;
8987 return getBlockPointerType(ResultType);
8988 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00008989 case Type::Atomic:
8990 {
8991 // Merge two pointer types, while trying to preserve typedef info
8992 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
8993 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
8994 if (Unqualified) {
8995 LHSValue = LHSValue.getUnqualifiedType();
8996 RHSValue = RHSValue.getUnqualifiedType();
8997 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008998 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
Eli Friedman0dfb8892011-10-06 23:00:33 +00008999 Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00009000 if (ResultType.isNull())
9001 return {};
Eli Friedman0dfb8892011-10-06 23:00:33 +00009002 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
9003 return LHS;
9004 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
9005 return RHS;
9006 return getAtomicType(ResultType);
9007 }
Chris Lattnerfd652912008-01-14 05:45:46 +00009008 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00009009 {
9010 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
9011 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
9012 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
Eugene Zelenko7855e772018-04-03 00:11:50 +00009013 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00009014
9015 QualType LHSElem = getAsArrayType(LHS)->getElementType();
9016 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00009017 if (Unqualified) {
9018 LHSElem = LHSElem.getUnqualifiedType();
9019 RHSElem = RHSElem.getUnqualifiedType();
9020 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009021
Douglas Gregor17ea3f52010-07-29 15:18:02 +00009022 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00009023 if (ResultType.isNull())
9024 return {};
Jeremy Morse8129c5c2018-06-05 09:18:26 +00009025
9026 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
9027 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
9028
9029 // If either side is a variable array, and both are complete, check whether
9030 // the current dimension is definite.
9031 if (LVAT || RVAT) {
9032 auto SizeFetch = [this](const VariableArrayType* VAT,
9033 const ConstantArrayType* CAT)
9034 -> std::pair<bool,llvm::APInt> {
9035 if (VAT) {
9036 llvm::APSInt TheInt;
9037 Expr *E = VAT->getSizeExpr();
9038 if (E && E->isIntegerConstantExpr(TheInt, *this))
9039 return std::make_pair(true, TheInt);
9040 else
9041 return std::make_pair(false, TheInt);
9042 } else if (CAT) {
9043 return std::make_pair(true, CAT->getSize());
9044 } else {
9045 return std::make_pair(false, llvm::APInt());
9046 }
9047 };
9048
9049 bool HaveLSize, HaveRSize;
9050 llvm::APInt LSize, RSize;
9051 std::tie(HaveLSize, LSize) = SizeFetch(LVAT, LCAT);
9052 std::tie(HaveRSize, RSize) = SizeFetch(RVAT, RCAT);
9053 if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(LSize, RSize))
9054 return {}; // Definite, but unequal, array dimension
9055 }
9056
Chris Lattner465fa322008-10-05 17:34:18 +00009057 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
9058 return LHS;
9059 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
9060 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00009061 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
9062 ArrayType::ArraySizeModifier(), 0);
9063 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
9064 ArrayType::ArraySizeModifier(), 0);
Chris Lattner465fa322008-10-05 17:34:18 +00009065 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
9066 return LHS;
9067 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
9068 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00009069 if (LVAT) {
9070 // FIXME: This isn't correct! But tricky to implement because
9071 // the array's size has to be the size of LHS, but the type
9072 // has to be different.
9073 return LHS;
9074 }
9075 if (RVAT) {
9076 // FIXME: This isn't correct! But tricky to implement because
9077 // the array's size has to be the size of RHS, but the type
9078 // has to be different.
9079 return RHS;
9080 }
Eli Friedman3e62c212008-08-22 01:48:21 +00009081 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
9082 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00009083 return getIncompleteArrayType(ResultType,
9084 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00009085 }
Chris Lattnerfd652912008-01-14 05:45:46 +00009086 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00009087 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00009088 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00009089 case Type::Enum:
Eugene Zelenko7855e772018-04-03 00:11:50 +00009090 return {};
Chris Lattnerfd652912008-01-14 05:45:46 +00009091 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00009092 // Only exactly equal builtin types are compatible, which is tested above.
Eugene Zelenko7855e772018-04-03 00:11:50 +00009093 return {};
Daniel Dunbar804c0442009-01-28 21:22:12 +00009094 case Type::Complex:
9095 // Distinct complex types are incompatible.
Eugene Zelenko7855e772018-04-03 00:11:50 +00009096 return {};
Chris Lattner7bbd3d72008-04-07 05:55:38 +00009097 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00009098 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00009099 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
9100 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00009101 return LHS;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009102 return {};
John McCall8b07ec22010-05-15 11:32:37 +00009103 case Type::ObjCObject: {
9104 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00009105 // FIXME: This should be type compatibility, e.g. whether
9106 // "LHS x; RHS x;" at global scope is legal.
Eugene Zelenko7855e772018-04-03 00:11:50 +00009107 const auto *LHSIface = LHS->getAs<ObjCObjectType>();
9108 const auto *RHSIface = RHS->getAs<ObjCObjectType>();
John McCall8b07ec22010-05-15 11:32:37 +00009109 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00009110 return LHS;
9111
Eugene Zelenko7855e772018-04-03 00:11:50 +00009112 return {};
Cedric Venet4fc88b72009-02-21 17:14:49 +00009113 }
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009114 case Type::ObjCObjectPointer:
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00009115 if (OfBlockPointer) {
9116 if (canAssignObjCInterfacesInBlockPointer(
9117 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00009118 RHS->getAs<ObjCObjectPointerType>(),
9119 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00009120 return LHS;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009121 return {};
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00009122 }
John McCall9dd450b2009-09-21 23:43:11 +00009123 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
9124 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00009125 return LHS;
9126
Eugene Zelenko7855e772018-04-03 00:11:50 +00009127 return {};
Xiuli Pan9c14e282016-01-09 12:53:17 +00009128 case Type::Pipe:
Joey Goulye3c85de2016-12-01 11:30:49 +00009129 assert(LHS != RHS &&
9130 "Equivalent pipe types should have already been handled!");
Eugene Zelenko7855e772018-04-03 00:11:50 +00009131 return {};
Xiuli Pan9c14e282016-01-09 12:53:17 +00009132 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00009133
David Blaikie8a40f702012-01-17 06:56:22 +00009134 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00009135}
Ted Kremenekfc581a92007-10-31 17:10:13 +00009136
Akira Hatanaka98a49332017-09-22 00:41:05 +00009137bool ASTContext::mergeExtParameterInfo(
9138 const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType,
9139 bool &CanUseFirst, bool &CanUseSecond,
9140 SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &NewParamInfos) {
9141 assert(NewParamInfos.empty() && "param info list not empty");
9142 CanUseFirst = CanUseSecond = true;
9143 bool FirstHasInfo = FirstFnType->hasExtParameterInfos();
9144 bool SecondHasInfo = SecondFnType->hasExtParameterInfos();
9145
John McCall18afab72016-03-01 00:49:02 +00009146 // Fast path: if the first type doesn't have ext parameter infos,
Akira Hatanaka98a49332017-09-22 00:41:05 +00009147 // we match if and only if the second type also doesn't have them.
9148 if (!FirstHasInfo && !SecondHasInfo)
9149 return true;
John McCall18afab72016-03-01 00:49:02 +00009150
Akira Hatanaka98a49332017-09-22 00:41:05 +00009151 bool NeedParamInfo = false;
9152 size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size()
9153 : SecondFnType->getExtParameterInfos().size();
John McCall18afab72016-03-01 00:49:02 +00009154
Akira Hatanaka98a49332017-09-22 00:41:05 +00009155 for (size_t I = 0; I < E; ++I) {
9156 FunctionProtoType::ExtParameterInfo FirstParam, SecondParam;
9157 if (FirstHasInfo)
9158 FirstParam = FirstFnType->getExtParameterInfo(I);
9159 if (SecondHasInfo)
9160 SecondParam = SecondFnType->getExtParameterInfo(I);
John McCall18afab72016-03-01 00:49:02 +00009161
Akira Hatanaka98a49332017-09-22 00:41:05 +00009162 // Cannot merge unless everything except the noescape flag matches.
9163 if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false))
John McCall18afab72016-03-01 00:49:02 +00009164 return false;
Akira Hatanaka98a49332017-09-22 00:41:05 +00009165
9166 bool FirstNoEscape = FirstParam.isNoEscape();
9167 bool SecondNoEscape = SecondParam.isNoEscape();
9168 bool IsNoEscape = FirstNoEscape && SecondNoEscape;
9169 NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape));
9170 if (NewParamInfos.back().getOpaqueValue())
9171 NeedParamInfo = true;
9172 if (FirstNoEscape != IsNoEscape)
9173 CanUseFirst = false;
9174 if (SecondNoEscape != IsNoEscape)
9175 CanUseSecond = false;
John McCall18afab72016-03-01 00:49:02 +00009176 }
Akira Hatanaka98a49332017-09-22 00:41:05 +00009177
9178 if (!NeedParamInfo)
9179 NewParamInfos.clear();
9180
Fariborz Jahanian97676972011-09-28 21:52:05 +00009181 return true;
9182}
9183
Chandler Carruth21c90602015-12-30 03:24:14 +00009184void ASTContext::ResetObjCLayout(const ObjCContainerDecl *CD) {
9185 ObjCLayouts[CD] = nullptr;
9186}
9187
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009188/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
9189/// 'RHS' attributes and returns the merged version; including for function
9190/// return types.
9191QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
9192 QualType LHSCan = getCanonicalType(LHS),
9193 RHSCan = getCanonicalType(RHS);
9194 // If two types are identical, they are compatible.
9195 if (LHSCan == RHSCan)
9196 return LHS;
9197 if (RHSCan->isFunctionType()) {
9198 if (!LHSCan->isFunctionType())
Eugene Zelenko7855e772018-04-03 00:11:50 +00009199 return {};
Alp Toker314cc812014-01-25 16:55:45 +00009200 QualType OldReturnType =
9201 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009202 QualType NewReturnType =
Alp Toker314cc812014-01-25 16:55:45 +00009203 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
Fangrui Song6907ce22018-07-30 19:24:48 +00009204 QualType ResReturnType =
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009205 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
9206 if (ResReturnType.isNull())
Eugene Zelenko7855e772018-04-03 00:11:50 +00009207 return {};
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009208 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
9209 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
9210 // In either case, use OldReturnType to build the new function type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00009211 const auto *F = LHS->getAs<FunctionType>();
9212 if (const auto *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00009213 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9214 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner896b32f2013-06-10 20:51:09 +00009215 QualType ResultType =
Alp Toker9cacbab2014-01-20 20:26:09 +00009216 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009217 return ResultType;
9218 }
9219 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00009220 return {};
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009221 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009222
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009223 // If the qualifiers are different, the types can still be merged.
9224 Qualifiers LQuals = LHSCan.getLocalQualifiers();
9225 Qualifiers RQuals = RHSCan.getLocalQualifiers();
9226 if (LQuals != RQuals) {
9227 // If any of these qualifiers are different, we have a type mismatch.
9228 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
9229 LQuals.getAddressSpace() != RQuals.getAddressSpace())
Eugene Zelenko7855e772018-04-03 00:11:50 +00009230 return {};
Fangrui Song6907ce22018-07-30 19:24:48 +00009231
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009232 // Exactly one GC qualifier difference is allowed: __strong is
9233 // okay if the other type has no GC qualifier but is an Objective
9234 // C object pointer (i.e. implicitly strong by default). We fix
9235 // this by pretending that the unqualified type was actually
9236 // qualified __strong.
9237 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
9238 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
9239 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
Fangrui Song6907ce22018-07-30 19:24:48 +00009240
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009241 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
Eugene Zelenko7855e772018-04-03 00:11:50 +00009242 return {};
Fangrui Song6907ce22018-07-30 19:24:48 +00009243
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009244 if (GC_L == Qualifiers::Strong)
9245 return LHS;
9246 if (GC_R == Qualifiers::Strong)
9247 return RHS;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009248 return {};
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009249 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009250
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009251 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
9252 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
9253 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
9254 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
9255 if (ResQT == LHSBaseQT)
9256 return LHS;
9257 if (ResQT == RHSBaseQT)
9258 return RHS;
9259 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00009260 return {};
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009261}
9262
Chris Lattner4ba0cef2008-04-07 07:01:58 +00009263//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009264// Integer Predicates
9265//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00009266
Jay Foad39c79802011-01-12 09:06:06 +00009267unsigned ASTContext::getIntWidth(QualType T) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00009268 if (const auto *ET = T->getAs<EnumType>())
Eli Friedmanee275c82009-12-10 22:29:29 +00009269 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00009270 if (T->isBooleanType())
9271 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00009272 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009273 return (unsigned)getTypeSize(T);
9274}
9275
Abramo Bagnara13640492012-09-09 10:21:24 +00009276QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Leonard Chanab80f3c2018-06-14 14:53:51 +00009277 assert((T->hasSignedIntegerRepresentation() || T->isSignedFixedPointType()) &&
9278 "Unexpected type");
Fangrui Song6907ce22018-07-30 19:24:48 +00009279
Chris Lattnerec3a1562009-10-17 20:33:28 +00009280 // Turn <4 x signed int> -> <4 x unsigned int>
Eugene Zelenko7855e772018-04-03 00:11:50 +00009281 if (const auto *VTy = T->getAs<VectorType>())
Chris Lattnerec3a1562009-10-17 20:33:28 +00009282 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00009283 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00009284
9285 // For enums, we return the unsigned version of the base type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00009286 if (const auto *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009287 T = ETy->getDecl()->getIntegerType();
Fangrui Song6907ce22018-07-30 19:24:48 +00009288
Eugene Zelenko7855e772018-04-03 00:11:50 +00009289 const auto *BTy = T->getAs<BuiltinType>();
Leonard Chanab80f3c2018-06-14 14:53:51 +00009290 assert(BTy && "Unexpected signed integer or fixed point type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009291 switch (BTy->getKind()) {
9292 case BuiltinType::Char_S:
9293 case BuiltinType::SChar:
9294 return UnsignedCharTy;
9295 case BuiltinType::Short:
9296 return UnsignedShortTy;
9297 case BuiltinType::Int:
9298 return UnsignedIntTy;
9299 case BuiltinType::Long:
9300 return UnsignedLongTy;
9301 case BuiltinType::LongLong:
9302 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00009303 case BuiltinType::Int128:
9304 return UnsignedInt128Ty;
Leonard Chanab80f3c2018-06-14 14:53:51 +00009305
9306 case BuiltinType::ShortAccum:
9307 return UnsignedShortAccumTy;
9308 case BuiltinType::Accum:
9309 return UnsignedAccumTy;
9310 case BuiltinType::LongAccum:
9311 return UnsignedLongAccumTy;
9312 case BuiltinType::SatShortAccum:
9313 return SatUnsignedShortAccumTy;
9314 case BuiltinType::SatAccum:
9315 return SatUnsignedAccumTy;
9316 case BuiltinType::SatLongAccum:
9317 return SatUnsignedLongAccumTy;
9318 case BuiltinType::ShortFract:
9319 return UnsignedShortFractTy;
9320 case BuiltinType::Fract:
9321 return UnsignedFractTy;
9322 case BuiltinType::LongFract:
9323 return UnsignedLongFractTy;
9324 case BuiltinType::SatShortFract:
9325 return SatUnsignedShortFractTy;
9326 case BuiltinType::SatFract:
9327 return SatUnsignedFractTy;
9328 case BuiltinType::SatLongFract:
9329 return SatUnsignedLongFractTy;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009330 default:
Leonard Chanab80f3c2018-06-14 14:53:51 +00009331 llvm_unreachable("Unexpected signed integer or fixed point type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009332 }
9333}
9334
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009335ASTMutationListener::~ASTMutationListener() = default;
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00009336
Richard Smith1fa5d642013-05-11 05:45:24 +00009337void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
9338 QualType ReturnType) {}
Chris Lattnerecd79c62009-06-14 00:45:47 +00009339
9340//===----------------------------------------------------------------------===//
9341// Builtin Type Computation
9342//===----------------------------------------------------------------------===//
9343
9344/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00009345/// pointer over the consumed characters. This returns the resultant type. If
9346/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
9347/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
9348/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009349///
9350/// RequiresICE is filled in on return to indicate whether the value is required
9351/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00009352static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00009353 ASTContext::GetBuiltinTypeError &Error,
Chandler Carruth45bbe012017-03-24 09:11:57 +00009354 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00009355 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00009356 // Modifiers.
9357 int HowLong = 0;
9358 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009359 RequiresICE = false;
Fangrui Song6907ce22018-07-30 19:24:48 +00009360
Chris Lattnerdc226c22010-10-01 22:42:38 +00009361 // Read the prefixed modifiers first.
Eric Christopher50daf5f2017-07-10 21:28:54 +00009362 bool Done = false;
9363 #ifndef NDEBUG
Karl-Johan Karlsson0e525a42019-05-16 07:18:02 +00009364 bool IsSpecial = false;
Eric Christopher50daf5f2017-07-10 21:28:54 +00009365 #endif
Chris Lattnerecd79c62009-06-14 00:45:47 +00009366 while (!Done) {
9367 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00009368 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00009369 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009370 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00009371 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009372 case 'S':
9373 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
9374 assert(!Signed && "Can't use 'S' modifier multiple times!");
9375 Signed = true;
9376 break;
9377 case 'U':
9378 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
Sean Silva2a995142015-01-16 21:44:26 +00009379 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00009380 Unsigned = true;
9381 break;
9382 case 'L':
Andrew Savonichevfa8cd762019-06-03 12:34:59 +00009383 assert(!IsSpecial && "Can't use 'L' with 'W', 'N', 'Z' or 'O' modifiers");
Chris Lattnerecd79c62009-06-14 00:45:47 +00009384 assert(HowLong <= 2 && "Can't have LLLL modifier");
9385 ++HowLong;
9386 break;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009387 case 'N':
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00009388 // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
Andrew Savonichevfa8cd762019-06-03 12:34:59 +00009389 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00009390 assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
Eric Christopher50daf5f2017-07-10 21:28:54 +00009391 #ifndef NDEBUG
Karl-Johan Karlsson0e525a42019-05-16 07:18:02 +00009392 IsSpecial = true;
Eric Christopher50daf5f2017-07-10 21:28:54 +00009393 #endif
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00009394 if (Context.getTargetInfo().getLongWidth() == 32)
9395 ++HowLong;
9396 break;
Kevin Qinad64f6d2014-02-24 02:45:03 +00009397 case 'W':
9398 // This modifier represents int64 type.
Andrew Savonichevfa8cd762019-06-03 12:34:59 +00009399 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
Kevin Qinad64f6d2014-02-24 02:45:03 +00009400 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
Eric Christopher50daf5f2017-07-10 21:28:54 +00009401 #ifndef NDEBUG
Karl-Johan Karlsson0e525a42019-05-16 07:18:02 +00009402 IsSpecial = true;
Eric Christopher50daf5f2017-07-10 21:28:54 +00009403 #endif
Kevin Qinad64f6d2014-02-24 02:45:03 +00009404 switch (Context.getTargetInfo().getInt64Type()) {
9405 default:
9406 llvm_unreachable("Unexpected integer type");
9407 case TargetInfo::SignedLong:
9408 HowLong = 1;
9409 break;
9410 case TargetInfo::SignedLongLong:
9411 HowLong = 2;
9412 break;
9413 }
Duncan P. N. Exon Smitheae8caa2017-06-14 21:26:31 +00009414 break;
Karl-Johan Karlsson0e525a42019-05-16 07:18:02 +00009415 case 'Z':
9416 // This modifier represents int32 type.
Andrew Savonichevfa8cd762019-06-03 12:34:59 +00009417 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
Karl-Johan Karlsson0e525a42019-05-16 07:18:02 +00009418 assert(HowLong == 0 && "Can't use both 'L' and 'Z' modifiers!");
9419 #ifndef NDEBUG
9420 IsSpecial = true;
9421 #endif
9422 switch (Context.getTargetInfo().getIntTypeByWidth(32, true)) {
9423 default:
9424 llvm_unreachable("Unexpected integer type");
9425 case TargetInfo::SignedInt:
9426 HowLong = 0;
9427 break;
9428 case TargetInfo::SignedLong:
9429 HowLong = 1;
9430 break;
9431 case TargetInfo::SignedLongLong:
9432 HowLong = 2;
9433 break;
9434 }
9435 break;
Andrew Savonichevfa8cd762019-06-03 12:34:59 +00009436 case 'O':
9437 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
9438 assert(HowLong == 0 && "Can't use both 'L' and 'O' modifiers!");
9439 #ifndef NDEBUG
9440 IsSpecial = true;
9441 #endif
9442 if (Context.getLangOpts().OpenCL)
9443 HowLong = 1;
9444 else
9445 HowLong = 2;
9446 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009447 }
9448 }
9449
9450 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00009451
Chris Lattnerecd79c62009-06-14 00:45:47 +00009452 // Read the base type.
9453 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00009454 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00009455 case 'v':
9456 assert(HowLong == 0 && !Signed && !Unsigned &&
9457 "Bad modifiers used with 'v'!");
9458 Type = Context.VoidTy;
9459 break;
Jack Carter24bef982013-08-15 15:16:57 +00009460 case 'h':
9461 assert(HowLong == 0 && !Signed && !Unsigned &&
Sean Silva2a995142015-01-16 21:44:26 +00009462 "Bad modifiers used with 'h'!");
Jack Carter24bef982013-08-15 15:16:57 +00009463 Type = Context.HalfTy;
9464 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009465 case 'f':
9466 assert(HowLong == 0 && !Signed && !Unsigned &&
9467 "Bad modifiers used with 'f'!");
9468 Type = Context.FloatTy;
9469 break;
9470 case 'd':
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009471 assert(HowLong < 3 && !Signed && !Unsigned &&
Chris Lattnerecd79c62009-06-14 00:45:47 +00009472 "Bad modifiers used with 'd'!");
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009473 if (HowLong == 1)
Chris Lattnerecd79c62009-06-14 00:45:47 +00009474 Type = Context.LongDoubleTy;
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009475 else if (HowLong == 2)
9476 Type = Context.Float128Ty;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009477 else
9478 Type = Context.DoubleTy;
9479 break;
9480 case 's':
9481 assert(HowLong == 0 && "Bad modifiers used with 's'!");
9482 if (Unsigned)
9483 Type = Context.UnsignedShortTy;
9484 else
9485 Type = Context.ShortTy;
9486 break;
9487 case 'i':
9488 if (HowLong == 3)
9489 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
9490 else if (HowLong == 2)
9491 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
9492 else if (HowLong == 1)
9493 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
9494 else
9495 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
9496 break;
9497 case 'c':
9498 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
9499 if (Signed)
9500 Type = Context.SignedCharTy;
9501 else if (Unsigned)
9502 Type = Context.UnsignedCharTy;
9503 else
9504 Type = Context.CharTy;
9505 break;
9506 case 'b': // boolean
9507 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
9508 Type = Context.BoolTy;
9509 break;
9510 case 'z': // size_t.
9511 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
9512 Type = Context.getSizeType();
9513 break;
Richard Smith8110c9d2016-11-29 19:45:17 +00009514 case 'w': // wchar_t.
9515 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
9516 Type = Context.getWideCharType();
9517 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009518 case 'F':
9519 Type = Context.getCFConstantStringType();
9520 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00009521 case 'G':
9522 Type = Context.getObjCIdType();
9523 break;
9524 case 'H':
9525 Type = Context.getObjCSelType();
9526 break;
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00009527 case 'M':
9528 Type = Context.getObjCSuperType();
9529 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009530 case 'a':
9531 Type = Context.getBuiltinVaListType();
9532 assert(!Type.isNull() && "builtin va list type not initialized!");
9533 break;
9534 case 'A':
9535 // This is a "reference" to a va_list; however, what exactly
9536 // this means depends on how va_list is defined. There are two
9537 // different kinds of va_list: ones passed by value, and ones
9538 // passed by reference. An example of a by-value va_list is
9539 // x86, where va_list is a char*. An example of by-ref va_list
9540 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
9541 // we want this argument to be a char*&; for x86-64, we want
9542 // it to be a __va_list_tag*.
9543 Type = Context.getBuiltinVaListType();
9544 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009545 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00009546 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009547 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00009548 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009549 break;
9550 case 'V': {
9551 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009552 unsigned NumElements = strtoul(Str, &End, 10);
9553 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00009554 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00009555
Fangrui Song6907ce22018-07-30 19:24:48 +00009556 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
Chandler Carruth45bbe012017-03-24 09:11:57 +00009557 RequiresICE, false);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009558 assert(!RequiresICE && "Can't require vector ICE");
Fangrui Song6907ce22018-07-30 19:24:48 +00009559
Chris Lattnerdc226c22010-10-01 22:42:38 +00009560 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00009561 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00009562 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009563 break;
9564 }
Douglas Gregorfed66992012-06-07 18:08:25 +00009565 case 'E': {
9566 char *End;
Fangrui Song6907ce22018-07-30 19:24:48 +00009567
Douglas Gregorfed66992012-06-07 18:08:25 +00009568 unsigned NumElements = strtoul(Str, &End, 10);
9569 assert(End != Str && "Missing vector size");
Fangrui Song6907ce22018-07-30 19:24:48 +00009570
Douglas Gregorfed66992012-06-07 18:08:25 +00009571 Str = End;
Fangrui Song6907ce22018-07-30 19:24:48 +00009572
Douglas Gregorfed66992012-06-07 18:08:25 +00009573 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
Chandler Carruth45bbe012017-03-24 09:11:57 +00009574 false);
Douglas Gregorfed66992012-06-07 18:08:25 +00009575 Type = Context.getExtVectorType(ElementType, NumElements);
Fangrui Song6907ce22018-07-30 19:24:48 +00009576 break;
Douglas Gregorfed66992012-06-07 18:08:25 +00009577 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00009578 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009579 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
Chandler Carruth45bbe012017-03-24 09:11:57 +00009580 false);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009581 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00009582 Type = Context.getComplexType(ElementType);
9583 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00009584 }
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009585 case 'Y':
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00009586 Type = Context.getPointerDiffType();
9587 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00009588 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00009589 Type = Context.getFILEType();
9590 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00009591 Error = ASTContext::GE_Missing_stdio;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009592 return {};
Chris Lattnerecd79c62009-06-14 00:45:47 +00009593 }
Mike Stump2adb4da2009-07-28 23:47:15 +00009594 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00009595 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00009596 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00009597 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00009598 else
9599 Type = Context.getjmp_bufType();
9600
Mike Stump2adb4da2009-07-28 23:47:15 +00009601 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00009602 Error = ASTContext::GE_Missing_setjmp;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009603 return {};
Mike Stump2adb4da2009-07-28 23:47:15 +00009604 }
9605 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00009606 case 'K':
9607 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
9608 Type = Context.getucontext_tType();
9609
9610 if (Type.isNull()) {
9611 Error = ASTContext::GE_Missing_ucontext;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009612 return {};
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00009613 }
9614 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00009615 case 'p':
9616 Type = Context.getProcessIDType();
9617 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00009618 }
Mike Stump11289f42009-09-09 15:08:12 +00009619
Chris Lattnerdc226c22010-10-01 22:42:38 +00009620 // If there are modifiers and if we're allowed to parse them, go for it.
9621 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009622 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00009623 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00009624 default: Done = true; --Str; break;
9625 case '*':
9626 case '&': {
9627 // Both pointers and references can have their pointee types
9628 // qualified with an address space.
9629 char *End;
9630 unsigned AddrSpace = strtoul(Str, &End, 10);
Matt Arsenaultc65f9662018-08-02 12:14:28 +00009631 if (End != Str) {
9632 // Note AddrSpace == 0 is not the same as an unspecified address space.
9633 Type = Context.getAddrSpaceQualType(
9634 Type,
9635 Context.getLangASForBuiltinAddressSpace(AddrSpace));
Chris Lattnerdc226c22010-10-01 22:42:38 +00009636 Str = End;
9637 }
9638 if (c == '*')
9639 Type = Context.getPointerType(Type);
9640 else
9641 Type = Context.getLValueReferenceType(Type);
9642 break;
9643 }
9644 // FIXME: There's no way to have a built-in with an rvalue ref arg.
9645 case 'C':
9646 Type = Type.withConst();
9647 break;
9648 case 'D':
9649 Type = Context.getVolatileType(Type);
9650 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00009651 case 'R':
9652 Type = Type.withRestrict();
9653 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009654 }
9655 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009656
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009657 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Fangrui Song6907ce22018-07-30 19:24:48 +00009658 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00009659
Chris Lattnerecd79c62009-06-14 00:45:47 +00009660 return Type;
9661}
9662
9663/// GetBuiltinType - Return the type for the specified builtin.
Chandler Carruth45bbe012017-03-24 09:11:57 +00009664QualType ASTContext::GetBuiltinType(unsigned Id,
9665 GetBuiltinTypeError &Error,
9666 unsigned *IntegerConstantArgs) const {
Eric Christopher02d5d862015-08-06 01:01:12 +00009667 const char *TypeStr = BuiltinInfo.getTypeString(Id);
Johannes Doerfertac991bb2019-01-19 05:36:54 +00009668 if (TypeStr[0] == '\0') {
9669 Error = GE_Missing_type;
9670 return {};
9671 }
Mike Stump11289f42009-09-09 15:08:12 +00009672
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009673 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00009674
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009675 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009676 Error = GE_None;
Chandler Carruth45bbe012017-03-24 09:11:57 +00009677 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
9678 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009679 if (Error != GE_None)
Eugene Zelenko7855e772018-04-03 00:11:50 +00009680 return {};
Fangrui Song6907ce22018-07-30 19:24:48 +00009681
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009682 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
Fangrui Song6907ce22018-07-30 19:24:48 +00009683
Chris Lattnerecd79c62009-06-14 00:45:47 +00009684 while (TypeStr[0] && TypeStr[0] != '.') {
Chandler Carruth45bbe012017-03-24 09:11:57 +00009685 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009686 if (Error != GE_None)
Eugene Zelenko7855e772018-04-03 00:11:50 +00009687 return {};
Chris Lattnerecd79c62009-06-14 00:45:47 +00009688
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009689 // If this argument is required to be an IntegerConstantExpression and the
9690 // caller cares, fill in the bitmask we return.
9691 if (RequiresICE && IntegerConstantArgs)
9692 *IntegerConstantArgs |= 1 << ArgTypes.size();
Fangrui Song6907ce22018-07-30 19:24:48 +00009693
Chris Lattnerecd79c62009-06-14 00:45:47 +00009694 // Do array -> pointer decay. The builtin should use the decayed type.
9695 if (Ty->isArrayType())
9696 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00009697
Chris Lattnerecd79c62009-06-14 00:45:47 +00009698 ArgTypes.push_back(Ty);
9699 }
9700
David Majnemerba3e5ec2015-03-13 18:26:17 +00009701 if (Id == Builtin::BI__GetExceptionInfo)
Eugene Zelenko7855e772018-04-03 00:11:50 +00009702 return {};
David Majnemerba3e5ec2015-03-13 18:26:17 +00009703
Chris Lattnerecd79c62009-06-14 00:45:47 +00009704 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
9705 "'.' should only occur at end of builtin type list!");
9706
Erich Keane881e83d2019-03-04 14:54:52 +00009707 bool Variadic = (TypeStr[0] == '.');
9708
Erich Keane00022812019-05-23 16:05:21 +00009709 FunctionType::ExtInfo EI(getDefaultCallingConvention(
9710 Variadic, /*IsCXXMethod=*/false, /*IsBuiltin=*/true));
John McCall991eb4b2010-12-21 00:44:39 +00009711 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
9712
John McCall991eb4b2010-12-21 00:44:39 +00009713
Richard Smith836de6b2016-12-19 23:59:34 +00009714 // We really shouldn't be making a no-proto type here.
9715 if (ArgTypes.empty() && Variadic && !getLangOpts().CPlusPlus)
John McCall991eb4b2010-12-21 00:44:39 +00009716 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00009717
John McCalldb40c7f2010-12-14 08:05:40 +00009718 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00009719 EPI.ExtInfo = EI;
9720 EPI.Variadic = Variadic;
Richard Smith391fb862016-10-18 07:13:55 +00009721 if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id))
9722 EPI.ExceptionSpec.Type =
9723 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
John McCalldb40c7f2010-12-14 08:05:40 +00009724
Jordan Rose5c382722013-03-08 21:51:21 +00009725 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009726}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00009727
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009728static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
9729 const FunctionDecl *FD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00009730 if (!FD->isExternallyVisible())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009731 return GVA_Internal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009732
Richard Smithe2467b72017-11-16 23:54:56 +00009733 // Non-user-provided functions get emitted as weak definitions with every
9734 // use, no matter whether they've been explicitly instantiated etc.
Eugene Zelenko7855e772018-04-03 00:11:50 +00009735 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
Richard Smithe2467b72017-11-16 23:54:56 +00009736 if (!MD->isUserProvided())
9737 return GVA_DiscardableODR;
9738
Yaron Keren4cd211b2017-02-22 14:32:39 +00009739 GVALinkage External;
Rafael Espindola3ae00052013-05-13 00:12:11 +00009740 switch (FD->getTemplateSpecializationKind()) {
9741 case TSK_Undeclared:
9742 case TSK_ExplicitSpecialization:
9743 External = GVA_StrongExternal;
9744 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009745
Rafael Espindola3ae00052013-05-13 00:12:11 +00009746 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00009747 return GVA_StrongODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00009748
David Majnemerc3d07332014-05-15 06:25:57 +00009749 // C++11 [temp.explicit]p10:
9750 // [ Note: The intent is that an inline function that is the subject of
9751 // an explicit instantiation declaration will still be implicitly
9752 // instantiated when used so that the body can be considered for
9753 // inlining, but that no out-of-line copy of the inline function would be
9754 // generated in the translation unit. -- end note ]
Rafael Espindola3ae00052013-05-13 00:12:11 +00009755 case TSK_ExplicitInstantiationDeclaration:
David Majnemer27d69db2014-04-28 22:17:59 +00009756 return GVA_AvailableExternally;
9757
Rafael Espindola3ae00052013-05-13 00:12:11 +00009758 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00009759 External = GVA_DiscardableODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00009760 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009761 }
9762
9763 if (!FD->isInlined())
9764 return External;
David Majnemer62f0ffd2013-08-01 17:26:42 +00009765
David Majnemer3f021502015-10-08 04:53:31 +00009766 if ((!Context.getLangOpts().CPlusPlus &&
9767 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009768 !FD->hasAttr<DLLExportAttr>()) ||
David Majnemer62f0ffd2013-08-01 17:26:42 +00009769 FD->hasAttr<GNUInlineAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009770 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
9771
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009772 // GNU or C99 inline semantics. Determine whether this symbol should be
9773 // externally visible.
9774 if (FD->isInlineDefinitionExternallyVisible())
9775 return External;
9776
9777 // C99 inline semantics, where the symbol is not externally visible.
David Majnemer27d69db2014-04-28 22:17:59 +00009778 return GVA_AvailableExternally;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009779 }
9780
David Majnemer54e3ba52014-04-02 23:17:29 +00009781 // Functions specified with extern and inline in -fms-compatibility mode
9782 // forcibly get emitted. While the body of the function cannot be later
9783 // replaced, the function definition cannot be discarded.
David Majnemer73768702015-03-20 00:02:27 +00009784 if (FD->isMSExternInline())
David Majnemer54e3ba52014-04-02 23:17:29 +00009785 return GVA_StrongODR;
9786
David Majnemer27d69db2014-04-28 22:17:59 +00009787 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009788}
9789
Artem Belevichca2b9512016-05-02 20:30:03 +00009790static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context,
Richard Smitha4653622017-09-06 20:01:14 +00009791 const Decl *D, GVALinkage L) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009792 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
9793 // dllexport/dllimport on inline functions.
9794 if (D->hasAttr<DLLImportAttr>()) {
9795 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
9796 return GVA_AvailableExternally;
Artem Belevichca2b9512016-05-02 20:30:03 +00009797 } else if (D->hasAttr<DLLExportAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009798 if (L == GVA_DiscardableODR)
9799 return GVA_StrongODR;
Artem Belevichca2b9512016-05-02 20:30:03 +00009800 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice &&
9801 D->hasAttr<CUDAGlobalAttr>()) {
9802 // Device-side functions with __global__ attribute must always be
9803 // visible externally so they can be launched from host.
9804 if (L == GVA_DiscardableODR || L == GVA_Internal)
9805 return GVA_StrongODR;
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009806 }
9807 return L;
9808}
9809
Richard Smitha4653622017-09-06 20:01:14 +00009810/// Adjust the GVALinkage for a declaration based on what an external AST source
9811/// knows about whether there can be other definitions of this declaration.
9812static GVALinkage
9813adjustGVALinkageForExternalDefinitionKind(const ASTContext &Ctx, const Decl *D,
9814 GVALinkage L) {
9815 ExternalASTSource *Source = Ctx.getExternalSource();
9816 if (!Source)
9817 return L;
9818
9819 switch (Source->hasExternalDefinitions(D)) {
David Blaikie9ffe5a32017-01-30 05:00:26 +00009820 case ExternalASTSource::EK_Never:
Richard Smitha4653622017-09-06 20:01:14 +00009821 // Other translation units rely on us to provide the definition.
David Blaikie9ffe5a32017-01-30 05:00:26 +00009822 if (L == GVA_DiscardableODR)
9823 return GVA_StrongODR;
9824 break;
Richard Smitha4653622017-09-06 20:01:14 +00009825
David Blaikie9ffe5a32017-01-30 05:00:26 +00009826 case ExternalASTSource::EK_Always:
9827 return GVA_AvailableExternally;
Richard Smitha4653622017-09-06 20:01:14 +00009828
David Blaikie9ffe5a32017-01-30 05:00:26 +00009829 case ExternalASTSource::EK_ReplyHazy:
9830 break;
9831 }
9832 return L;
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009833}
9834
Richard Smitha4653622017-09-06 20:01:14 +00009835GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
9836 return adjustGVALinkageForExternalDefinitionKind(*this, FD,
9837 adjustGVALinkageForAttributes(*this, FD,
9838 basicGVALinkageForFunction(*this, FD)));
9839}
9840
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009841static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
9842 const VarDecl *VD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00009843 if (!VD->isExternallyVisible())
9844 return GVA_Internal;
9845
David Majnemer27d69db2014-04-28 22:17:59 +00009846 if (VD->isStaticLocal()) {
David Majnemer27d69db2014-04-28 22:17:59 +00009847 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
9848 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
9849 LexicalContext = LexicalContext->getLexicalParent();
9850
David Blaikieeb210012017-01-27 23:11:10 +00009851 // ObjC Blocks can create local variables that don't have a FunctionDecl
9852 // LexicalContext.
9853 if (!LexicalContext)
9854 return GVA_DiscardableODR;
David Majnemer27d69db2014-04-28 22:17:59 +00009855
David Blaikieeb210012017-01-27 23:11:10 +00009856 // Otherwise, let the static local variable inherit its linkage from the
9857 // nearest enclosing function.
9858 auto StaticLocalLinkage =
9859 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
9860
9861 // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
9862 // be emitted in any object with references to the symbol for the object it
9863 // contains, whether inline or out-of-line."
9864 // Similar behavior is observed with MSVC. An alternative ABI could use
9865 // StrongODR/AvailableExternally to match the function, but none are
9866 // known/supported currently.
9867 if (StaticLocalLinkage == GVA_StrongODR ||
9868 StaticLocalLinkage == GVA_AvailableExternally)
9869 return GVA_DiscardableODR;
9870 return StaticLocalLinkage;
David Majnemer27d69db2014-04-28 22:17:59 +00009871 }
9872
Hans Wennborg56fc62b2014-07-17 20:25:23 +00009873 // MSVC treats in-class initialized static data members as definitions.
9874 // By giving them non-strong linkage, out-of-line definitions won't
9875 // cause link errors.
9876 if (Context.isMSStaticDataMemberInlineDefinition(VD))
9877 return GVA_DiscardableODR;
9878
Richard Smithd9b90092016-07-02 01:32:16 +00009879 // Most non-template variables have strong linkage; inline variables are
9880 // linkonce_odr or (occasionally, for compatibility) weak_odr.
9881 GVALinkage StrongLinkage;
9882 switch (Context.getInlineVariableDefinitionKind(VD)) {
9883 case ASTContext::InlineVariableDefinitionKind::None:
9884 StrongLinkage = GVA_StrongExternal;
9885 break;
9886 case ASTContext::InlineVariableDefinitionKind::Weak:
9887 case ASTContext::InlineVariableDefinitionKind::WeakUnknown:
Richard Smith62f19e72016-06-25 00:15:56 +00009888 StrongLinkage = GVA_DiscardableODR;
Richard Smithd9b90092016-07-02 01:32:16 +00009889 break;
9890 case ASTContext::InlineVariableDefinitionKind::Strong:
9891 StrongLinkage = GVA_StrongODR;
9892 break;
9893 }
Richard Smith62f19e72016-06-25 00:15:56 +00009894
Richard Smith8809a0c2013-09-27 20:14:12 +00009895 switch (VD->getTemplateSpecializationKind()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00009896 case TSK_Undeclared:
Richard Smith62f19e72016-06-25 00:15:56 +00009897 return StrongLinkage;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009898
David Majnemer6d1780c2015-07-17 23:36:49 +00009899 case TSK_ExplicitSpecialization:
Reid Klecknere6f2ff22019-06-26 21:16:51 +00009900 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
9901 VD->isStaticDataMember()
9902 ? GVA_StrongODR
9903 : StrongLinkage;
David Majnemer6d1780c2015-07-17 23:36:49 +00009904
Rafael Espindola3ae00052013-05-13 00:12:11 +00009905 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00009906 return GVA_StrongODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009907
David Majnemer27d69db2014-04-28 22:17:59 +00009908 case TSK_ExplicitInstantiationDeclaration:
9909 return GVA_AvailableExternally;
9910
Rafael Espindola3ae00052013-05-13 00:12:11 +00009911 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00009912 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009913 }
Rafael Espindola27699c82013-05-13 14:05:53 +00009914
9915 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009916}
9917
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009918GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
Richard Smitha4653622017-09-06 20:01:14 +00009919 return adjustGVALinkageForExternalDefinitionKind(*this, VD,
9920 adjustGVALinkageForAttributes(*this, VD,
9921 basicGVALinkageForVariable(*this, VD)));
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009922}
9923
David Blaikiee6b7c282017-04-11 20:46:34 +00009924bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00009925 if (const auto *VD = dyn_cast<VarDecl>(D)) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009926 if (!VD->isFileVarDecl())
9927 return false;
Renato Golin9258aa52014-05-21 10:40:27 +00009928 // Global named register variables (GNU extension) are never emitted.
9929 if (VD->getStorageClass() == SC_Register)
9930 return false;
Richard Smith7747ce22015-08-19 20:49:38 +00009931 if (VD->getDescribedVarTemplate() ||
9932 isa<VarTemplatePartialSpecializationDecl>(VD))
9933 return false;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009934 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
Richard Smith5205a8c2013-04-01 20:22:16 +00009935 // We never need to emit an uninstantiated function template.
9936 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
9937 return false;
Nico Weber66220292016-03-02 17:28:48 +00009938 } else if (isa<PragmaCommentDecl>(D))
9939 return true;
Nico Webercbbaeb12016-03-02 19:28:54 +00009940 else if (isa<PragmaDetectMismatchDecl>(D))
9941 return true;
Nico Weber66220292016-03-02 17:28:48 +00009942 else if (isa<OMPThreadPrivateDecl>(D))
Alexey Bataevc5b1d322016-03-04 09:22:22 +00009943 return !D->getDeclContext()->isDependentContext();
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009944 else if (isa<OMPAllocateDecl>(D))
9945 return !D->getDeclContext()->isDependentContext();
Michael Krused47b9432019-08-05 18:43:21 +00009946 else if (isa<OMPDeclareReductionDecl>(D) || isa<OMPDeclareMapperDecl>(D))
Alexey Bataevc5b1d322016-03-04 09:22:22 +00009947 return !D->getDeclContext()->isDependentContext();
Richard Smithdc1f0422016-07-20 19:10:16 +00009948 else if (isa<ImportDecl>(D))
9949 return true;
Alexey Bataev97720002014-11-11 04:05:39 +00009950 else
Richard Smith5205a8c2013-04-01 20:22:16 +00009951 return false;
9952
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00009953 if (D->isFromASTFile() && !LangOpts.BuildingPCHWithObjectFile) {
9954 assert(getExternalSource() && "It's from an AST file; must have a source.");
9955 // On Windows, PCH files are built together with an object file. If this
9956 // declaration comes from such a PCH and DeclMustBeEmitted would return
9957 // true, it would have returned true and the decl would have been emitted
9958 // into that object file, so it doesn't need to be emitted here.
9959 // Note that decls are still emitted if they're referenced, as usual;
9960 // DeclMustBeEmitted is used to decide whether a decl must be emitted even
9961 // if it's not referenced.
9962 //
9963 // Explicit template instantiation definitions are tricky. If there was an
9964 // explicit template instantiation decl in the PCH before, it will look like
9965 // the definition comes from there, even if that was just the declaration.
9966 // (Explicit instantiation defs of variable templates always get emitted.)
9967 bool IsExpInstDef =
9968 isa<FunctionDecl>(D) &&
9969 cast<FunctionDecl>(D)->getTemplateSpecializationKind() ==
9970 TSK_ExplicitInstantiationDefinition;
9971
Hans Wennborgb51a7032018-09-14 15:18:30 +00009972 // Implicit member function definitions, such as operator= might not be
9973 // marked as template specializations, since they're not coming from a
9974 // template but synthesized directly on the class.
9975 IsExpInstDef |=
9976 isa<CXXMethodDecl>(D) &&
9977 cast<CXXMethodDecl>(D)->getParent()->getTemplateSpecializationKind() ==
9978 TSK_ExplicitInstantiationDefinition;
9979
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00009980 if (getExternalSource()->DeclIsFromPCHWithObjectFile(D) && !IsExpInstDef)
9981 return false;
9982 }
9983
Richard Smith5205a8c2013-04-01 20:22:16 +00009984 // If this is a member of a class template, we do not need to emit it.
9985 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009986 return false;
9987
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00009988 // Weak references don't produce any output by themselves.
9989 if (D->hasAttr<WeakRefAttr>())
9990 return false;
9991
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009992 // Aliases and used decls are required.
9993 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
9994 return true;
9995
Eugene Zelenko7855e772018-04-03 00:11:50 +00009996 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009997 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00009998 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00009999 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +000010000
10001 // Constructors and destructors are required.
10002 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
10003 return true;
Hans Wennborg08c5a7b2018-06-25 13:23:49 +000010004
John McCall6bd2a892013-01-25 22:31:03 +000010005 // The key function for a class is required. This rule only comes
10006 // into play when inline functions can be key functions, though.
10007 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +000010008 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
John McCall6bd2a892013-01-25 22:31:03 +000010009 const CXXRecordDecl *RD = MD->getParent();
10010 if (MD->isOutOfLine() && RD->isDynamicClass()) {
10011 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
10012 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
10013 return true;
10014 }
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +000010015 }
10016 }
10017
David Blaikie9ffe5a32017-01-30 05:00:26 +000010018 GVALinkage Linkage = GetGVALinkageForFunction(FD);
10019
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +000010020 // static, static inline, always_inline, and extern inline functions can
10021 // always be deferred. Normal inline functions can be deferred in C99/C++.
10022 // Implicit template instantiations can also be deferred in C++.
David Blaikie9ffe5a32017-01-30 05:00:26 +000010023 return !isDiscardableGVALinkage(Linkage);
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +000010024 }
Hans Wennborg08c5a7b2018-06-25 13:23:49 +000010025
Eugene Zelenko7855e772018-04-03 00:11:50 +000010026 const auto *VD = cast<VarDecl>(D);
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +000010027 assert(VD->isFileVarDecl() && "Expected file scoped var");
10028
Alexey Bataevd01b7492018-08-15 19:45:12 +000010029 // If the decl is marked as `declare target to`, it should be emitted for the
10030 // host and for the device.
10031 if (LangOpts.OpenMP &&
10032 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
10033 return true;
10034
Hans Wennborg56fc62b2014-07-17 20:25:23 +000010035 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
10036 !isMSStaticDataMemberInlineDefinition(VD))
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +000010037 return false;
10038
Richard Smitha0e5e542012-11-12 21:38:00 +000010039 // Variables that can be needed in other TUs are required.
Richard Smitha4653622017-09-06 20:01:14 +000010040 auto Linkage = GetGVALinkageForVariable(VD);
10041 if (!isDiscardableGVALinkage(Linkage))
Richard Smitha0e5e542012-11-12 21:38:00 +000010042 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +000010043
Richard Smitha4653622017-09-06 20:01:14 +000010044 // We never need to emit a variable that is available in another TU.
10045 if (Linkage == GVA_AvailableExternally)
10046 return false;
10047
Richard Smitha0e5e542012-11-12 21:38:00 +000010048 // Variables that have destruction with side-effects are required.
10049 if (VD->getType().isDestructedType())
10050 return true;
10051
10052 // Variables that have initialization with side-effects are required.
Richard Smith7747ce22015-08-19 20:49:38 +000010053 if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
Richard Smith187ffb42017-01-20 01:19:46 +000010054 // We can get a value-dependent initializer during error recovery.
10055 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
Richard Smitha0e5e542012-11-12 21:38:00 +000010056 return true;
10057
Richard Smithda383632016-08-15 01:33:41 +000010058 // Likewise, variables with tuple-like bindings are required if their
10059 // bindings have side-effects.
Eugene Zelenko7855e772018-04-03 00:11:50 +000010060 if (const auto *DD = dyn_cast<DecompositionDecl>(VD))
10061 for (const auto *BD : DD->bindings())
10062 if (const auto *BindingVD = BD->getHoldingVar())
Richard Smithda383632016-08-15 01:33:41 +000010063 if (DeclMustBeEmitted(BindingVD))
10064 return true;
10065
Richard Smitha0e5e542012-11-12 21:38:00 +000010066 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +000010067}
Charles Davis53c59df2010-08-16 03:33:14 +000010068
Erich Keane281d20b2018-01-08 21:34:17 +000010069void ASTContext::forEachMultiversionedFunctionVersion(
10070 const FunctionDecl *FD,
Erich Keane0fb16482018-08-13 18:33:20 +000010071 llvm::function_ref<void(FunctionDecl *)> Pred) const {
Erich Keane281d20b2018-01-08 21:34:17 +000010072 assert(FD->isMultiVersion() && "Only valid for multiversioned functions");
10073 llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls;
Erich Keane7304f0a2018-11-28 20:58:43 +000010074 FD = FD->getMostRecentDecl();
Erich Keane281d20b2018-01-08 21:34:17 +000010075 for (auto *CurDecl :
10076 FD->getDeclContext()->getRedeclContext()->lookup(FD->getDeclName())) {
Erich Keane7304f0a2018-11-28 20:58:43 +000010077 FunctionDecl *CurFD = CurDecl->getAsFunction()->getMostRecentDecl();
Erich Keane281d20b2018-01-08 21:34:17 +000010078 if (CurFD && hasSameType(CurFD->getType(), FD->getType()) &&
10079 std::end(SeenDecls) == llvm::find(SeenDecls, CurFD)) {
10080 SeenDecls.insert(CurFD);
10081 Pred(CurFD);
10082 }
10083 }
10084}
10085
Reid Kleckner78af0702013-08-27 23:08:25 +000010086CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
Erich Keane00022812019-05-23 16:05:21 +000010087 bool IsCXXMethod,
10088 bool IsBuiltin) const {
Charles Davis99202b32010-11-09 18:04:24 +000010089 // Pass through to the C++ ABI object
Reid Kleckner78af0702013-08-27 23:08:25 +000010090 if (IsCXXMethod)
10091 return ABI->getDefaultMethodCallConv(IsVariadic);
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +000010092
Erich Keane00022812019-05-23 16:05:21 +000010093 // Builtins ignore user-specified default calling convention and remain the
10094 // Target's default calling convention.
10095 if (!IsBuiltin) {
10096 switch (LangOpts.getDefaultCallingConv()) {
10097 case LangOptions::DCC_None:
10098 break;
10099 case LangOptions::DCC_CDecl:
10100 return CC_C;
10101 case LangOptions::DCC_FastCall:
10102 if (getTargetInfo().hasFeature("sse2") && !IsVariadic)
10103 return CC_X86FastCall;
10104 break;
10105 case LangOptions::DCC_StdCall:
10106 if (!IsVariadic)
10107 return CC_X86StdCall;
10108 break;
10109 case LangOptions::DCC_VectorCall:
10110 // __vectorcall cannot be applied to variadic functions.
10111 if (!IsVariadic)
10112 return CC_X86VectorCall;
10113 break;
10114 case LangOptions::DCC_RegCall:
10115 // __regcall cannot be applied to variadic functions.
10116 if (!IsVariadic)
10117 return CC_X86RegCall;
10118 break;
10119 }
Alexey Bataeva7547182016-05-18 09:06:38 +000010120 }
Erich Keane39309482019-07-25 17:14:45 +000010121 return Target->getDefaultCallingConv();
Charles Davis99202b32010-11-09 18:04:24 +000010122}
10123
Jay Foad39c79802011-01-12 09:06:06 +000010124bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +000010125 // Pass through to the C++ ABI object
10126 return ABI->isNearlyEmpty(RD);
10127}
10128
Reid Kleckner96f8f932014-02-05 17:27:08 +000010129VTableContextBase *ASTContext::getVTableContext() {
10130 if (!VTContext.get()) {
10131 if (Target->getCXXABI().isMicrosoft())
10132 VTContext.reset(new MicrosoftVTableContext(*this));
10133 else
10134 VTContext.reset(new ItaniumVTableContext(*this));
10135 }
10136 return VTContext.get();
10137}
10138
Yaxun Liuc18e9ec2019-02-14 02:00:09 +000010139MangleContext *ASTContext::createMangleContext(const TargetInfo *T) {
10140 if (!T)
10141 T = Target;
10142 switch (T->getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +000010143 case TargetCXXABI::GenericAArch64:
John McCall359b8852013-01-25 22:30:49 +000010144 case TargetCXXABI::GenericItanium:
10145 case TargetCXXABI::GenericARM:
Zoran Jovanovic26a12162015-02-18 15:21:35 +000010146 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +000010147 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +000010148 case TargetCXXABI::iOS64:
Dan Gohmanc2853072015-09-03 22:51:53 +000010149 case TargetCXXABI::WebAssembly:
Tim Northover756447a2015-10-30 16:30:36 +000010150 case TargetCXXABI::WatchOS:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +000010151 return ItaniumMangleContext::create(*this, getDiagnostics());
John McCall359b8852013-01-25 22:30:49 +000010152 case TargetCXXABI::Microsoft:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +000010153 return MicrosoftMangleContext::create(*this, getDiagnostics());
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000010154 }
David Blaikie83d382b2011-09-23 05:06:16 +000010155 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000010156}
10157
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000010158CXXABI::~CXXABI() = default;
Ted Kremenekf5df0ce2011-04-28 04:53:38 +000010159
10160size_t ASTContext::getSideTableAllocatedMemory() const {
Larisse Voufo39a1e502013-08-06 01:03:05 +000010161 return ASTRecordLayouts.getMemorySize() +
10162 llvm::capacity_in_bytes(ObjCLayouts) +
10163 llvm::capacity_in_bytes(KeyFunctions) +
10164 llvm::capacity_in_bytes(ObjCImpls) +
10165 llvm::capacity_in_bytes(BlockVarCopyInits) +
10166 llvm::capacity_in_bytes(DeclAttrs) +
10167 llvm::capacity_in_bytes(TemplateOrInstantiation) +
10168 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
10169 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
10170 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
10171 llvm::capacity_in_bytes(OverriddenMethods) +
10172 llvm::capacity_in_bytes(Types) +
Richard Smithf19a8b02019-05-02 00:49:14 +000010173 llvm::capacity_in_bytes(VariableArrayTypes);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +000010174}
Ted Kremenek540017e2011-10-06 05:00:56 +000010175
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +000010176/// getIntTypeForBitwidth -
10177/// sets integer QualTy according to specified details:
10178/// bitwidth, signed/unsigned.
10179/// Returns empty type if there is no appropriate target types.
10180QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
10181 unsigned Signed) const {
10182 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
10183 CanQualType QualTy = getFromTargetType(Ty);
10184 if (!QualTy && DestWidth == 128)
10185 return Signed ? Int128Ty : UnsignedInt128Ty;
10186 return QualTy;
10187}
10188
10189/// getRealTypeForBitwidth -
10190/// sets floating point QualTy according to specified bitwidth.
10191/// Returns empty type if there is no appropriate target types.
10192QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
10193 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
10194 switch (Ty) {
10195 case TargetInfo::Float:
10196 return FloatTy;
10197 case TargetInfo::Double:
10198 return DoubleTy;
10199 case TargetInfo::LongDouble:
10200 return LongDoubleTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +000010201 case TargetInfo::Float128:
10202 return Float128Ty;
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +000010203 case TargetInfo::NoFloat:
Eugene Zelenko7855e772018-04-03 00:11:50 +000010204 return {};
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +000010205 }
10206
10207 llvm_unreachable("Unhandled TargetInfo::RealType value");
10208}
10209
Eli Friedman3b7d46c2013-07-10 00:30:46 +000010210void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
10211 if (Number > 1)
10212 MangleNumbers[ND] = Number;
David Blaikie095deba2012-11-14 01:52:05 +000010213}
10214
Eli Friedman3b7d46c2013-07-10 00:30:46 +000010215unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
Richard Smithe9b02d62016-03-21 22:33:02 +000010216 auto I = MangleNumbers.find(ND);
Eli Friedman3b7d46c2013-07-10 00:30:46 +000010217 return I != MangleNumbers.end() ? I->second : 1;
David Blaikie095deba2012-11-14 01:52:05 +000010218}
10219
David Majnemer2206bf52014-03-05 08:57:59 +000010220void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
10221 if (Number > 1)
10222 StaticLocalNumbers[VD] = Number;
10223}
10224
10225unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
Richard Smithe9b02d62016-03-21 22:33:02 +000010226 auto I = StaticLocalNumbers.find(VD);
David Majnemer2206bf52014-03-05 08:57:59 +000010227 return I != StaticLocalNumbers.end() ? I->second : 1;
10228}
10229
Eli Friedman3b7d46c2013-07-10 00:30:46 +000010230MangleNumberingContext &
10231ASTContext::getManglingNumberContext(const DeclContext *DC) {
Reid Klecknerd8110b62013-09-10 20:14:30 +000010232 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
Justin Lebar20ebffc2016-10-10 16:26:19 +000010233 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
Reid Klecknerd8110b62013-09-10 20:14:30 +000010234 if (!MCtx)
10235 MCtx = createMangleNumberingContext();
10236 return *MCtx;
10237}
10238
Justin Lebar20ebffc2016-10-10 16:26:19 +000010239std::unique_ptr<MangleNumberingContext>
10240ASTContext::createMangleNumberingContext() const {
Reid Klecknerd8110b62013-09-10 20:14:30 +000010241 return ABI->createMangleNumberingContext();
Douglas Gregor63798542012-02-20 19:44:39 +000010242}
10243
David Majnemere7a818f2015-03-06 18:53:55 +000010244const CXXConstructorDecl *
10245ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
10246 return ABI->getCopyConstructorForExceptionObject(
10247 cast<CXXRecordDecl>(RD->getFirstDecl()));
10248}
10249
10250void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
10251 CXXConstructorDecl *CD) {
10252 return ABI->addCopyConstructorForExceptionObject(
10253 cast<CXXRecordDecl>(RD->getFirstDecl()),
10254 cast<CXXConstructorDecl>(CD->getFirstDecl()));
10255}
10256
David Majnemer00350522015-08-31 18:48:39 +000010257void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD,
10258 TypedefNameDecl *DD) {
10259 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
10260}
10261
10262TypedefNameDecl *
10263ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) {
10264 return ABI->getTypedefNameForUnnamedTagDecl(TD);
10265}
10266
10267void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD,
10268 DeclaratorDecl *DD) {
10269 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
10270}
10271
10272DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) {
10273 return ABI->getDeclaratorForUnnamedTagDecl(TD);
10274}
10275
Ted Kremenek540017e2011-10-06 05:00:56 +000010276void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
10277 ParamIndices[D] = index;
10278}
10279
10280unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
10281 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
Fangrui Song6907ce22018-07-30 19:24:48 +000010282 assert(I != ParamIndices.end() &&
Ted Kremenek540017e2011-10-06 05:00:56 +000010283 "ParmIndices lacks entry set by ParmVarDecl");
10284 return I->second;
10285}
Fariborz Jahanian615de762013-05-28 17:37:39 +000010286
Richard Smithe6c01442013-06-05 00:46:14 +000010287APValue *
10288ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
10289 bool MayCreate) {
10290 assert(E && E->getStorageDuration() == SD_Static &&
10291 "don't need to cache the computed value for this temporary");
David Majnemer2dcef9e2015-08-13 23:50:15 +000010292 if (MayCreate) {
10293 APValue *&MTVI = MaterializedTemporaryValues[E];
10294 if (!MTVI)
10295 MTVI = new (*this) APValue;
10296 return MTVI;
10297 }
Richard Smithe6c01442013-06-05 00:46:14 +000010298
David Majnemer2dcef9e2015-08-13 23:50:15 +000010299 return MaterializedTemporaryValues.lookup(E);
Richard Smithe6c01442013-06-05 00:46:14 +000010300}
10301
Eric Fiselier708afb52019-05-16 21:04:15 +000010302QualType ASTContext::getStringLiteralArrayType(QualType EltTy,
10303 unsigned Length) const {
10304 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
10305 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
10306 EltTy = EltTy.withConst();
10307
10308 EltTy = adjustStringLiteralBaseType(EltTy);
10309
10310 // Get an array type for the string, according to C99 6.4.5. This includes
10311 // the null terminator character.
10312 return getConstantArrayType(EltTy, llvm::APInt(32, Length + 1),
10313 ArrayType::Normal, /*IndexTypeQuals*/ 0);
10314}
10315
10316StringLiteral *
10317ASTContext::getPredefinedStringLiteralFromCache(StringRef Key) const {
10318 StringLiteral *&Result = StringLiteralCache[Key];
10319 if (!Result)
10320 Result = StringLiteral::Create(
10321 *this, Key, StringLiteral::Ascii,
10322 /*Pascal*/ false, getStringLiteralArrayType(CharTy, Key.size()),
10323 SourceLocation());
10324 return Result;
10325}
10326
Fariborz Jahanian615de762013-05-28 17:37:39 +000010327bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
10328 const llvm::Triple &T = getTargetInfo().getTriple();
10329 if (!T.isOSDarwin())
10330 return false;
10331
Bob Wilson2c82c3d2013-11-02 23:27:49 +000010332 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
10333 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
10334 return false;
10335
Fariborz Jahanian615de762013-05-28 17:37:39 +000010336 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
10337 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
10338 uint64_t Size = sizeChars.getQuantity();
10339 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
10340 unsigned Align = alignChars.getQuantity();
10341 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
10342 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
10343}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010344
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010345/// Template specializations to abstract away from pointers and TypeLocs.
10346/// @{
10347template <typename T>
Sam McCall814e7972018-11-14 10:33:30 +000010348static ast_type_traits::DynTypedNode createDynTypedNode(const T &Node) {
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010349 return ast_type_traits::DynTypedNode::create(*Node);
10350}
10351template <>
10352ast_type_traits::DynTypedNode createDynTypedNode(const TypeLoc &Node) {
10353 return ast_type_traits::DynTypedNode::create(Node);
10354}
10355template <>
10356ast_type_traits::DynTypedNode
10357createDynTypedNode(const NestedNameSpecifierLoc &Node) {
10358 return ast_type_traits::DynTypedNode::create(Node);
10359}
10360/// @}
10361
Sam McCall814e7972018-11-14 10:33:30 +000010362/// A \c RecursiveASTVisitor that builds a map from nodes to their
10363/// parents as defined by the \c RecursiveASTVisitor.
10364///
10365/// Note that the relationship described here is purely in terms of AST
10366/// traversal - there are other relationships (for example declaration context)
10367/// in the AST that are better modeled by special matchers.
10368///
10369/// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
10370class ASTContext::ParentMap::ASTVisitor
10371 : public RecursiveASTVisitor<ASTVisitor> {
10372public:
10373 ASTVisitor(ParentMap &Map) : Map(Map) {}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010374
Sam McCall814e7972018-11-14 10:33:30 +000010375private:
10376 friend class RecursiveASTVisitor<ASTVisitor>;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000010377
Sam McCall814e7972018-11-14 10:33:30 +000010378 using VisitorBase = RecursiveASTVisitor<ASTVisitor>;
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010379
Sam McCall814e7972018-11-14 10:33:30 +000010380 bool shouldVisitTemplateInstantiations() const { return true; }
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010381
Sam McCall814e7972018-11-14 10:33:30 +000010382 bool shouldVisitImplicitCode() const { return true; }
10383
10384 template <typename T, typename MapNodeTy, typename BaseTraverseFn,
10385 typename MapTy>
10386 bool TraverseNode(T Node, MapNodeTy MapNode, BaseTraverseFn BaseTraverse,
10387 MapTy *Parents) {
10388 if (!Node)
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010389 return true;
Sam McCall814e7972018-11-14 10:33:30 +000010390 if (ParentStack.size() > 0) {
10391 // FIXME: Currently we add the same parent multiple times, but only
10392 // when no memoization data is available for the type.
10393 // For example when we visit all subexpressions of template
10394 // instantiations; this is suboptimal, but benign: the only way to
10395 // visit those is with hasAncestor / hasParent, and those do not create
10396 // new matches.
10397 // The plan is to enable DynTypedNode to be storable in a map or hash
10398 // map. The main problem there is to implement hash functions /
10399 // comparison operators for all types that DynTypedNode supports that
10400 // do not have pointer identity.
10401 auto &NodeOrVector = (*Parents)[MapNode];
10402 if (NodeOrVector.isNull()) {
10403 if (const auto *D = ParentStack.back().get<Decl>())
10404 NodeOrVector = D;
10405 else if (const auto *S = ParentStack.back().get<Stmt>())
10406 NodeOrVector = S;
10407 else
10408 NodeOrVector = new ast_type_traits::DynTypedNode(ParentStack.back());
10409 } else {
10410 if (!NodeOrVector.template is<ParentVector *>()) {
10411 auto *Vector = new ParentVector(
10412 1, getSingleDynTypedNodeFromParentMap(NodeOrVector));
10413 delete NodeOrVector
10414 .template dyn_cast<ast_type_traits::DynTypedNode *>();
10415 NodeOrVector = Vector;
Manuel Klimek95403e62014-05-21 13:28:59 +000010416 }
Sam McCall814e7972018-11-14 10:33:30 +000010417
10418 auto *Vector = NodeOrVector.template get<ParentVector *>();
10419 // Skip duplicates for types that have memoization data.
10420 // We must check that the type has memoization data before calling
10421 // std::find() because DynTypedNode::operator== can't compare all
10422 // types.
10423 bool Found = ParentStack.back().getMemoizationData() &&
10424 std::find(Vector->begin(), Vector->end(),
10425 ParentStack.back()) != Vector->end();
10426 if (!Found)
10427 Vector->push_back(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +000010428 }
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010429 }
Sam McCall814e7972018-11-14 10:33:30 +000010430 ParentStack.push_back(createDynTypedNode(Node));
10431 bool Result = BaseTraverse();
10432 ParentStack.pop_back();
10433 return Result;
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010434 }
Sam McCall814e7972018-11-14 10:33:30 +000010435
10436 bool TraverseDecl(Decl *DeclNode) {
10437 return TraverseNode(
10438 DeclNode, DeclNode, [&] { return VisitorBase::TraverseDecl(DeclNode); },
10439 &Map.PointerParents);
Manuel Klimek95403e62014-05-21 13:28:59 +000010440 }
Sam McCall814e7972018-11-14 10:33:30 +000010441
10442 bool TraverseStmt(Stmt *StmtNode) {
10443 return TraverseNode(
10444 StmtNode, StmtNode, [&] { return VisitorBase::TraverseStmt(StmtNode); },
10445 &Map.PointerParents);
10446 }
10447
10448 bool TraverseTypeLoc(TypeLoc TypeLocNode) {
10449 return TraverseNode(
10450 TypeLocNode, ast_type_traits::DynTypedNode::create(TypeLocNode),
10451 [&] { return VisitorBase::TraverseTypeLoc(TypeLocNode); },
10452 &Map.OtherParents);
10453 }
10454
10455 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNSLocNode) {
10456 return TraverseNode(
10457 NNSLocNode, ast_type_traits::DynTypedNode::create(NNSLocNode),
10458 [&] { return VisitorBase::TraverseNestedNameSpecifierLoc(NNSLocNode); },
10459 &Map.OtherParents);
10460 }
10461
10462 ParentMap &Map;
10463 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
10464};
10465
10466ASTContext::ParentMap::ParentMap(ASTContext &Ctx) {
10467 ASTVisitor(*this).TraverseAST(Ctx);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010468}
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010469
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010470ASTContext::DynTypedNodeList
10471ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
Sam McCall814e7972018-11-14 10:33:30 +000010472 if (!Parents)
10473 // We build the parent map for the traversal scope (usually whole TU), as
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010474 // hasAncestor can escape any subtree.
Sam McCall814e7972018-11-14 10:33:30 +000010475 Parents = llvm::make_unique<ParentMap>(*this);
10476 return Parents->getParents(Node);
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010477}
10478
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010479bool
10480ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
10481 const ObjCMethodDecl *MethodImpl) {
10482 // No point trying to match an unavailable/deprecated mothod.
10483 if (MethodDecl->hasAttr<UnavailableAttr>()
10484 || MethodDecl->hasAttr<DeprecatedAttr>())
10485 return false;
10486 if (MethodDecl->getObjCDeclQualifier() !=
10487 MethodImpl->getObjCDeclQualifier())
10488 return false;
Alp Toker314cc812014-01-25 16:55:45 +000010489 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010490 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +000010491
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010492 if (MethodDecl->param_size() != MethodImpl->param_size())
10493 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +000010494
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010495 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
10496 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
10497 EF = MethodDecl->param_end();
10498 IM != EM && IF != EF; ++IM, ++IF) {
10499 const ParmVarDecl *DeclVar = (*IF);
10500 const ParmVarDecl *ImplVar = (*IM);
10501 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
10502 return false;
10503 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
10504 return false;
10505 }
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000010506
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010507 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010508}
Richard Smith053f6c62014-05-16 23:01:30 +000010509
Yaxun Liu402804b2016-12-15 08:09:08 +000010510uint64_t ASTContext::getTargetNullPointerValue(QualType QT) const {
Alexander Richardson6d989432017-10-15 18:48:14 +000010511 LangAS AS;
Yaxun Liu402804b2016-12-15 08:09:08 +000010512 if (QT->getUnqualifiedDesugaredType()->isNullPtrType())
Alexander Richardson6d989432017-10-15 18:48:14 +000010513 AS = LangAS::Default;
Yaxun Liu402804b2016-12-15 08:09:08 +000010514 else
10515 AS = QT->getPointeeType().getAddressSpace();
10516
10517 return getTargetInfo().getNullPointerValue(AS);
10518}
10519
Alexander Richardson6d989432017-10-15 18:48:14 +000010520unsigned ASTContext::getTargetAddressSpace(LangAS AS) const {
10521 if (isTargetAddressSpace(AS))
10522 return toTargetAddressSpace(AS);
Yaxun Liub34ec822017-04-11 17:24:23 +000010523 else
Alexander Richardson6d989432017-10-15 18:48:14 +000010524 return (*AddrSpaceMap)[(unsigned)AS];
Yaxun Liub34ec822017-04-11 17:24:23 +000010525}
10526
Leonard Chanab80f3c2018-06-14 14:53:51 +000010527QualType ASTContext::getCorrespondingSaturatedType(QualType Ty) const {
10528 assert(Ty->isFixedPointType());
10529
10530 if (Ty->isSaturatedFixedPointType()) return Ty;
10531
10532 const auto &BT = Ty->getAs<BuiltinType>();
10533 switch (BT->getKind()) {
10534 default:
10535 llvm_unreachable("Not a fixed point type!");
10536 case BuiltinType::ShortAccum:
10537 return SatShortAccumTy;
10538 case BuiltinType::Accum:
10539 return SatAccumTy;
10540 case BuiltinType::LongAccum:
10541 return SatLongAccumTy;
10542 case BuiltinType::UShortAccum:
10543 return SatUnsignedShortAccumTy;
10544 case BuiltinType::UAccum:
10545 return SatUnsignedAccumTy;
10546 case BuiltinType::ULongAccum:
10547 return SatUnsignedLongAccumTy;
10548 case BuiltinType::ShortFract:
10549 return SatShortFractTy;
10550 case BuiltinType::Fract:
10551 return SatFractTy;
10552 case BuiltinType::LongFract:
10553 return SatLongFractTy;
10554 case BuiltinType::UShortFract:
10555 return SatUnsignedShortFractTy;
10556 case BuiltinType::UFract:
10557 return SatUnsignedFractTy;
10558 case BuiltinType::ULongFract:
10559 return SatUnsignedLongFractTy;
10560 }
10561}
10562
Matt Arsenaultc65f9662018-08-02 12:14:28 +000010563LangAS ASTContext::getLangASForBuiltinAddressSpace(unsigned AS) const {
10564 if (LangOpts.OpenCL)
10565 return getTargetInfo().getOpenCLBuiltinAddressSpace(AS);
10566
10567 if (LangOpts.CUDA)
10568 return getTargetInfo().getCUDABuiltinAddressSpace(AS);
10569
10570 return getLangASFromTargetAS(AS);
10571}
10572
Richard Smith053f6c62014-05-16 23:01:30 +000010573// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
10574// doesn't include ASTContext.h
10575template
10576clang::LazyGenerationalUpdatePtr<
10577 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
10578clang::LazyGenerationalUpdatePtr<
10579 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
10580 const clang::ASTContext &Ctx, Decl *Value);
Leonard Chandb01c3a2018-06-20 17:19:40 +000010581
10582unsigned char ASTContext::getFixedPointScale(QualType Ty) const {
10583 assert(Ty->isFixedPointType());
10584
10585 const auto *BT = Ty->getAs<BuiltinType>();
10586 const TargetInfo &Target = getTargetInfo();
10587 switch (BT->getKind()) {
10588 default:
10589 llvm_unreachable("Not a fixed point type!");
10590 case BuiltinType::ShortAccum:
10591 case BuiltinType::SatShortAccum:
10592 return Target.getShortAccumScale();
10593 case BuiltinType::Accum:
10594 case BuiltinType::SatAccum:
10595 return Target.getAccumScale();
10596 case BuiltinType::LongAccum:
10597 case BuiltinType::SatLongAccum:
10598 return Target.getLongAccumScale();
10599 case BuiltinType::UShortAccum:
10600 case BuiltinType::SatUShortAccum:
10601 return Target.getUnsignedShortAccumScale();
10602 case BuiltinType::UAccum:
10603 case BuiltinType::SatUAccum:
10604 return Target.getUnsignedAccumScale();
10605 case BuiltinType::ULongAccum:
10606 case BuiltinType::SatULongAccum:
10607 return Target.getUnsignedLongAccumScale();
10608 case BuiltinType::ShortFract:
10609 case BuiltinType::SatShortFract:
10610 return Target.getShortFractScale();
10611 case BuiltinType::Fract:
10612 case BuiltinType::SatFract:
10613 return Target.getFractScale();
10614 case BuiltinType::LongFract:
10615 case BuiltinType::SatLongFract:
10616 return Target.getLongFractScale();
10617 case BuiltinType::UShortFract:
10618 case BuiltinType::SatUShortFract:
10619 return Target.getUnsignedShortFractScale();
10620 case BuiltinType::UFract:
10621 case BuiltinType::SatUFract:
10622 return Target.getUnsignedFractScale();
10623 case BuiltinType::ULongFract:
10624 case BuiltinType::SatULongFract:
10625 return Target.getUnsignedLongFractScale();
10626 }
10627}
10628
10629unsigned char ASTContext::getFixedPointIBits(QualType Ty) const {
10630 assert(Ty->isFixedPointType());
10631
10632 const auto *BT = Ty->getAs<BuiltinType>();
10633 const TargetInfo &Target = getTargetInfo();
10634 switch (BT->getKind()) {
10635 default:
10636 llvm_unreachable("Not a fixed point type!");
10637 case BuiltinType::ShortAccum:
10638 case BuiltinType::SatShortAccum:
10639 return Target.getShortAccumIBits();
10640 case BuiltinType::Accum:
10641 case BuiltinType::SatAccum:
10642 return Target.getAccumIBits();
10643 case BuiltinType::LongAccum:
10644 case BuiltinType::SatLongAccum:
10645 return Target.getLongAccumIBits();
10646 case BuiltinType::UShortAccum:
10647 case BuiltinType::SatUShortAccum:
10648 return Target.getUnsignedShortAccumIBits();
10649 case BuiltinType::UAccum:
10650 case BuiltinType::SatUAccum:
10651 return Target.getUnsignedAccumIBits();
10652 case BuiltinType::ULongAccum:
10653 case BuiltinType::SatULongAccum:
10654 return Target.getUnsignedLongAccumIBits();
10655 case BuiltinType::ShortFract:
10656 case BuiltinType::SatShortFract:
10657 case BuiltinType::Fract:
10658 case BuiltinType::SatFract:
10659 case BuiltinType::LongFract:
10660 case BuiltinType::SatLongFract:
10661 case BuiltinType::UShortFract:
10662 case BuiltinType::SatUShortFract:
10663 case BuiltinType::UFract:
10664 case BuiltinType::SatUFract:
10665 case BuiltinType::ULongFract:
10666 case BuiltinType::SatULongFract:
10667 return 0;
10668 }
10669}
Leonard Chana6779422018-08-06 16:42:37 +000010670
10671FixedPointSemantics ASTContext::getFixedPointSemantics(QualType Ty) const {
Erich Keane8e772162019-01-18 19:31:54 +000010672 assert((Ty->isFixedPointType() || Ty->isIntegerType()) &&
10673 "Can only get the fixed point semantics for a "
10674 "fixed point or integer type.");
Leonard Chan2044ac82019-01-16 18:13:59 +000010675 if (Ty->isIntegerType())
10676 return FixedPointSemantics::GetIntegerSemantics(getIntWidth(Ty),
10677 Ty->isSignedIntegerType());
10678
Leonard Chana6779422018-08-06 16:42:37 +000010679 bool isSigned = Ty->isSignedFixedPointType();
10680 return FixedPointSemantics(
10681 static_cast<unsigned>(getTypeSize(Ty)), getFixedPointScale(Ty), isSigned,
10682 Ty->isSaturatedFixedPointType(),
10683 !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding());
10684}
10685
10686APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const {
10687 assert(Ty->isFixedPointType());
10688 return APFixedPoint::getMax(getFixedPointSemantics(Ty));
10689}
10690
10691APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const {
10692 assert(Ty->isFixedPointType());
10693 return APFixedPoint::getMin(getFixedPointSemantics(Ty));
10694}
Leonard Chan2044ac82019-01-16 18:13:59 +000010695
10696QualType ASTContext::getCorrespondingSignedFixedPointType(QualType Ty) const {
10697 assert(Ty->isUnsignedFixedPointType() &&
10698 "Expected unsigned fixed point type");
10699 const auto *BTy = Ty->getAs<BuiltinType>();
10700
10701 switch (BTy->getKind()) {
10702 case BuiltinType::UShortAccum:
10703 return ShortAccumTy;
10704 case BuiltinType::UAccum:
10705 return AccumTy;
10706 case BuiltinType::ULongAccum:
10707 return LongAccumTy;
10708 case BuiltinType::SatUShortAccum:
10709 return SatShortAccumTy;
10710 case BuiltinType::SatUAccum:
10711 return SatAccumTy;
10712 case BuiltinType::SatULongAccum:
10713 return SatLongAccumTy;
10714 case BuiltinType::UShortFract:
10715 return ShortFractTy;
10716 case BuiltinType::UFract:
10717 return FractTy;
10718 case BuiltinType::ULongFract:
10719 return LongFractTy;
10720 case BuiltinType::SatUShortFract:
10721 return SatShortFractTy;
10722 case BuiltinType::SatUFract:
10723 return SatFractTy;
10724 case BuiltinType::SatULongFract:
10725 return SatLongFractTy;
10726 default:
10727 llvm_unreachable("Unexpected unsigned fixed point type");
10728 }
10729}