blob: ab2a95e577f0936106d76c9e42ba33c8ce10bf5d [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//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerddc135e2006-11-10 06:34:16 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000015#include "CXXABI.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000016#include "clang/AST/APValue.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000017#include "clang/AST/ASTMutationListener.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000018#include "clang/AST/ASTTypeTraits.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000019#include "clang/AST/Attr.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000020#include "clang/AST/AttrIterator.h"
Ken Dyck8c89d592009-12-22 14:23:30 +000021#include "clang/AST/CharUnits.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000022#include "clang/AST/Comment.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000023#include "clang/AST/Decl.h"
24#include "clang/AST/DeclBase.h"
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +000025#include "clang/AST/DeclCXX.h"
Chandler Carruthaa36b892015-12-30 03:40:23 +000026#include "clang/AST/DeclContextInternals.h"
Steve Naroff67391b82007-10-01 19:00:59 +000027#include "clang/AST/DeclObjC.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000028#include "clang/AST/DeclOpenMP.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000029#include "clang/AST/DeclTemplate.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000030#include "clang/AST/DeclarationName.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000031#include "clang/AST/Expr.h"
John McCall87fe5d52010-05-20 01:18:31 +000032#include "clang/AST/ExprCXX.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000033#include "clang/AST/ExternalASTSource.h"
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000034#include "clang/AST/Mangle.h"
Reid Klecknerd8110b62013-09-10 20:14:30 +000035#include "clang/AST/MangleNumberingContext.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000036#include "clang/AST/NestedNameSpecifier.h"
37#include "clang/AST/RawCommentList.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000038#include "clang/AST/RecordLayout.h"
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000039#include "clang/AST/RecursiveASTVisitor.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000040#include "clang/AST/Stmt.h"
41#include "clang/AST/TemplateBase.h"
42#include "clang/AST/TemplateName.h"
43#include "clang/AST/Type.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000044#include "clang/AST/TypeLoc.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000045#include "clang/AST/UnresolvedSet.h"
Reid Kleckner96f8f932014-02-05 17:27:08 +000046#include "clang/AST/VTableBuilder.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000047#include "clang/Basic/AddressSpaces.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000048#include "clang/Basic/Builtins.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000049#include "clang/Basic/CommentOptions.h"
Eugene Zelenko7855e772018-04-03 00:11:50 +000050#include "clang/Basic/ExceptionSpecificationType.h"
Leonard Chana6779422018-08-06 16:42:37 +000051#include "clang/Basic/FixedPoint.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000052#include "clang/Basic/IdentifierTable.h"
53#include "clang/Basic/LLVM.h"
54#include "clang/Basic/LangOptions.h"
55#include "clang/Basic/Linkage.h"
56#include "clang/Basic/ObjCRuntime.h"
57#include "clang/Basic/SanitizerBlacklist.h"
58#include "clang/Basic/SourceLocation.h"
Chris Lattnerd2868512009-03-28 03:45:20 +000059#include "clang/Basic/SourceManager.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000060#include "clang/Basic/Specifiers.h"
61#include "clang/Basic/TargetCXXABI.h"
Chris Lattner4dc8a6f2007-05-20 23:50:58 +000062#include "clang/Basic/TargetInfo.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000063#include "clang/Basic/XRayLists.h"
64#include "llvm/ADT/APInt.h"
65#include "llvm/ADT/APSInt.h"
66#include "llvm/ADT/ArrayRef.h"
67#include "llvm/ADT/DenseMap.h"
68#include "llvm/ADT/DenseSet.h"
69#include "llvm/ADT/FoldingSet.h"
70#include "llvm/ADT/None.h"
71#include "llvm/ADT/Optional.h"
72#include "llvm/ADT/PointerUnion.h"
73#include "llvm/ADT/STLExtras.h"
74#include "llvm/ADT/SmallPtrSet.h"
75#include "llvm/ADT/SmallVector.h"
Anders Carlssond8499822007-10-29 05:01:08 +000076#include "llvm/ADT/StringExtras.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000077#include "llvm/ADT/StringRef.h"
Robert Lyttoneaf6f362013-11-12 10:09:34 +000078#include "llvm/ADT/Triple.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000079#include "llvm/Support/Capacity.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000080#include "llvm/Support/Casting.h"
81#include "llvm/Support/Compiler.h"
82#include "llvm/Support/ErrorHandling.h"
Nate Begemanb699c9b2009-01-18 06:42:49 +000083#include "llvm/Support/MathExtras.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000084#include "llvm/Support/raw_ostream.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000085#include <algorithm>
86#include <cassert>
87#include <cstddef>
88#include <cstdint>
89#include <cstdlib>
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +000090#include <map>
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000091#include <memory>
92#include <string>
93#include <tuple>
94#include <utility>
Anders Carlssona4267a62009-07-18 21:19:52 +000095
Chris Lattnerddc135e2006-11-10 06:34:16 +000096using namespace clang;
97
Douglas Gregor9672f922010-07-03 00:47:00 +000098unsigned ASTContext::NumImplicitDefaultConstructors;
99unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregora6d69502010-07-02 23:41:54 +0000100unsigned ASTContext::NumImplicitCopyConstructors;
101unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +0000102unsigned ASTContext::NumImplicitMoveConstructors;
103unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000104unsigned ASTContext::NumImplicitCopyAssignmentOperators;
105unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +0000106unsigned ASTContext::NumImplicitMoveAssignmentOperators;
107unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
Douglas Gregor7454c562010-07-02 20:37:36 +0000108unsigned ASTContext::NumImplicitDestructors;
109unsigned ASTContext::NumImplicitDestructorsDeclared;
110
Steve Naroff0af91202007-04-27 21:51:21 +0000111enum FloatingRank {
Sjoerd Meijercc623ad2017-09-08 15:15:00 +0000112 Float16Rank, HalfRank, FloatRank, DoubleRank, LongDoubleRank, Float128Rank
Steve Naroff0af91202007-04-27 21:51:21 +0000113};
114
Dmitri Gribenkof26054f2012-07-11 21:38:39 +0000115RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000116 if (!CommentsLoaded && ExternalSource) {
117 ExternalSource->ReadComments();
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +0000118
119#ifndef NDEBUG
120 ArrayRef<RawComment *> RawComments = Comments.getComments();
121 assert(std::is_sorted(RawComments.begin(), RawComments.end(),
122 BeforeThanCompare<RawComment>(SourceMgr)));
123#endif
124
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000125 CommentsLoaded = true;
126 }
127
128 assert(D);
129
Dmitri Gribenkodf17d642012-06-28 16:19:39 +0000130 // User can not attach documentation to implicit declarations.
131 if (D->isImplicit())
Craig Topper36250ad2014-05-12 05:36:57 +0000132 return nullptr;
Dmitri Gribenkodf17d642012-06-28 16:19:39 +0000133
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000134 // User can not attach documentation to implicit instantiations.
Eugene Zelenko7855e772018-04-03 00:11:50 +0000135 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000136 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +0000137 return nullptr;
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000138 }
139
Eugene Zelenko7855e772018-04-03 00:11:50 +0000140 if (const auto *VD = dyn_cast<VarDecl>(D)) {
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000141 if (VD->isStaticDataMember() &&
142 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +0000143 return nullptr;
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000144 }
145
Eugene Zelenko7855e772018-04-03 00:11:50 +0000146 if (const auto *CRD = dyn_cast<CXXRecordDecl>(D)) {
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000147 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +0000148 return nullptr;
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000149 }
150
Eugene Zelenko7855e772018-04-03 00:11:50 +0000151 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000152 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
153 if (TSK == TSK_ImplicitInstantiation ||
154 TSK == TSK_Undeclared)
Craig Topper36250ad2014-05-12 05:36:57 +0000155 return nullptr;
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000156 }
157
Eugene Zelenko7855e772018-04-03 00:11:50 +0000158 if (const auto *ED = dyn_cast<EnumDecl>(D)) {
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000159 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +0000160 return nullptr;
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000161 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000162 if (const auto *TD = dyn_cast<TagDecl>(D)) {
Fariborz Jahanian799a4032013-04-17 21:05:20 +0000163 // When tag declaration (but not definition!) is part of the
164 // decl-specifier-seq of some other declaration, it doesn't get comment
165 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
Craig Topper36250ad2014-05-12 05:36:57 +0000166 return nullptr;
Fariborz Jahanian799a4032013-04-17 21:05:20 +0000167 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000168 // TODO: handle comments for function parameters properly.
169 if (isa<ParmVarDecl>(D))
Craig Topper36250ad2014-05-12 05:36:57 +0000170 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000171
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000172 // TODO: we could look up template parameter documentation in the template
173 // documentation.
174 if (isa<TemplateTypeParmDecl>(D) ||
175 isa<NonTypeTemplateParmDecl>(D) ||
176 isa<TemplateTemplateParmDecl>(D))
Craig Topper36250ad2014-05-12 05:36:57 +0000177 return nullptr;
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000178
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000179 ArrayRef<RawComment *> RawComments = Comments.getComments();
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000180
181 // If there are no comments anywhere, we won't find anything.
182 if (RawComments.empty())
Craig Topper36250ad2014-05-12 05:36:57 +0000183 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000184
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000185 // Find declaration location.
186 // For Objective-C declarations we generally don't expect to have multiple
187 // declarators, thus use declaration starting location as the "declaration
188 // location".
189 // For all other declarations multiple declarators are used quite frequently,
190 // so we use the location of the identifier as the "declaration location".
191 SourceLocation DeclLoc;
192 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000193 isa<ObjCPropertyDecl>(D) ||
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +0000194 isa<RedeclarableTemplateDecl>(D) ||
195 isa<ClassTemplateSpecializationDecl>(D))
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000196 DeclLoc = D->getBeginLoc();
Fariborz Jahanianb64e95f2013-07-24 22:58:51 +0000197 else {
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000198 DeclLoc = D->getLocation();
Dmitri Gribenkoef099dc2014-03-27 16:40:51 +0000199 if (DeclLoc.isMacroID()) {
200 if (isa<TypedefDecl>(D)) {
201 // If location of the typedef name is in a macro, it is because being
202 // declared via a macro. Try using declaration's starting location as
203 // the "declaration location".
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000204 DeclLoc = D->getBeginLoc();
Eugene Zelenko7855e772018-04-03 00:11:50 +0000205 } else if (const auto *TD = dyn_cast<TagDecl>(D)) {
Dmitri Gribenkoef099dc2014-03-27 16:40:51 +0000206 // If location of the tag decl is inside a macro, but the spelling of
207 // the tag name comes from a macro argument, it looks like a special
208 // macro like NS_ENUM is being used to define the tag decl. In that
209 // case, adjust the source location to the expansion loc so that we can
210 // attach the comment to the tag decl.
211 if (SourceMgr.isMacroArgExpansion(DeclLoc) &&
212 TD->isCompleteDefinition())
213 DeclLoc = SourceMgr.getExpansionLoc(DeclLoc);
214 }
215 }
Fariborz Jahanianb64e95f2013-07-24 22:58:51 +0000216 }
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000217
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000218 // If the declaration doesn't map directly to a location in a file, we
219 // can't find the comment.
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000220 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
Craig Topper36250ad2014-05-12 05:36:57 +0000221 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000222
223 // Find the comment that occurs just after this declaration.
Dmitri Gribenko82ea9472012-07-17 22:01:09 +0000224 ArrayRef<RawComment *>::iterator Comment;
225 {
226 // When searching for comments during parsing, the comment we are looking
227 // for is usually among the last two comments we parsed -- check them
228 // first.
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +0000229 RawComment CommentAtDeclLoc(
David L. Jones13d5a872018-03-02 00:07:45 +0000230 SourceMgr, SourceRange(DeclLoc), LangOpts.CommentOpts, false);
Dmitri Gribenko82ea9472012-07-17 22:01:09 +0000231 BeforeThanCompare<RawComment> Compare(SourceMgr);
232 ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1;
233 bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
234 if (!Found && RawComments.size() >= 2) {
235 MaybeBeforeDecl--;
236 Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
237 }
238
239 if (Found) {
240 Comment = MaybeBeforeDecl + 1;
241 assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(),
242 &CommentAtDeclLoc, Compare));
243 } else {
244 // Slow path.
245 Comment = std::lower_bound(RawComments.begin(), RawComments.end(),
246 &CommentAtDeclLoc, Compare);
247 }
248 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000249
250 // Decompose the location for the declaration and find the beginning of the
251 // file buffer.
252 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
253
254 // First check whether we have a trailing comment.
255 if (Comment != RawComments.end() &&
David L. Jones13d5a872018-03-02 00:07:45 +0000256 ((*Comment)->isDocumentation() || LangOpts.CommentOpts.ParseAllComments)
257 && (*Comment)->isTrailingComment() &&
Fariborz Jahanianfad28542013-08-06 23:29:00 +0000258 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
Fariborz Jahanian3ab62222013-08-07 16:40:29 +0000259 isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000260 std::pair<FileID, unsigned> CommentBeginDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000261 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000262 // Check that Doxygen trailing comment comes after the declaration, starts
263 // on the same line and in the same file as the declaration.
264 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
265 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
266 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
267 CommentBeginDecomp.second)) {
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000268 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000269 }
270 }
271
272 // The comment just after the declaration was not a trailing comment.
273 // Let's look at the previous comment.
274 if (Comment == RawComments.begin())
Craig Topper36250ad2014-05-12 05:36:57 +0000275 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000276 --Comment;
277
278 // Check that we actually have a non-member Doxygen comment.
David L. Jones13d5a872018-03-02 00:07:45 +0000279 if (!((*Comment)->isDocumentation() ||
280 LangOpts.CommentOpts.ParseAllComments) ||
281 (*Comment)->isTrailingComment())
Craig Topper36250ad2014-05-12 05:36:57 +0000282 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000283
284 // Decompose the end of the comment.
285 std::pair<FileID, unsigned> CommentEndDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000286 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000287
288 // If the comment and the declaration aren't in the same file, then they
289 // aren't related.
290 if (DeclLocDecomp.first != CommentEndDecomp.first)
Craig Topper36250ad2014-05-12 05:36:57 +0000291 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000292
293 // Get the corresponding buffer.
294 bool Invalid = false;
295 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
296 &Invalid).data();
297 if (Invalid)
Craig Topper36250ad2014-05-12 05:36:57 +0000298 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000299
300 // Extract text between the comment and declaration.
301 StringRef Text(Buffer + CommentEndDecomp.second,
302 DeclLocDecomp.second - CommentEndDecomp.second);
303
Dmitri Gribenko7e8729b2012-06-27 23:43:37 +0000304 // There should be no other declarations or preprocessor directives between
305 // comment and declaration.
Argyrios Kyrtzidisb534d3a2013-07-26 18:38:12 +0000306 if (Text.find_first_of(";{}#@") != StringRef::npos)
Craig Topper36250ad2014-05-12 05:36:57 +0000307 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000308
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000309 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000310}
311
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000312/// If we have a 'templated' declaration for a template, adjust 'D' to
313/// refer to the actual template.
Dmitri Gribenko90631802012-08-22 17:44:32 +0000314/// If we have an implicit instantiation, adjust 'D' to refer to template.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +0000315static const Decl *adjustDeclToTemplate(const Decl *D) {
Eugene Zelenko7855e772018-04-03 00:11:50 +0000316 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000317 // Is this function declaration part of a function template?
Douglas Gregor35ceb272012-08-13 16:37:30 +0000318 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
Dmitri Gribenko90631802012-08-22 17:44:32 +0000319 return FTD;
320
321 // Nothing to do if function is not an implicit instantiation.
322 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
323 return D;
324
325 // Function is an implicit instantiation of a function template?
326 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
327 return FTD;
328
329 // Function is instantiated from a member definition of a class template?
330 if (const FunctionDecl *MemberDecl =
331 FD->getInstantiatedFromMemberFunction())
332 return MemberDecl;
333
334 return D;
Douglas Gregor35ceb272012-08-13 16:37:30 +0000335 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000336 if (const auto *VD = dyn_cast<VarDecl>(D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000337 // Static data member is instantiated from a member definition of a class
338 // template?
339 if (VD->isStaticDataMember())
340 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
341 return MemberDecl;
342
343 return D;
344 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000345 if (const auto *CRD = dyn_cast<CXXRecordDecl>(D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000346 // Is this class declaration part of a class template?
347 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
348 return CTD;
349
350 // Class is an implicit instantiation of a class template or partial
351 // specialization?
Eugene Zelenko7855e772018-04-03 00:11:50 +0000352 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000353 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
354 return D;
355 llvm::PointerUnion<ClassTemplateDecl *,
356 ClassTemplatePartialSpecializationDecl *>
357 PU = CTSD->getSpecializedTemplateOrPartial();
358 return PU.is<ClassTemplateDecl*>() ?
359 static_cast<const Decl*>(PU.get<ClassTemplateDecl *>()) :
360 static_cast<const Decl*>(
361 PU.get<ClassTemplatePartialSpecializationDecl *>());
362 }
363
364 // Class is instantiated from a member definition of a class template?
365 if (const MemberSpecializationInfo *Info =
366 CRD->getMemberSpecializationInfo())
367 return Info->getInstantiatedFrom();
368
369 return D;
370 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000371 if (const auto *ED = dyn_cast<EnumDecl>(D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000372 // Enum is instantiated from a member definition of a class template?
373 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
374 return MemberDecl;
375
376 return D;
377 }
378 // FIXME: Adjust alias templates?
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000379 return D;
380}
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000381
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000382const RawComment *ASTContext::getRawCommentForAnyRedecl(
383 const Decl *D,
384 const Decl **OriginalDecl) const {
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000385 D = adjustDeclToTemplate(D);
Douglas Gregor35ceb272012-08-13 16:37:30 +0000386
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000387 // Check whether we have cached a comment for this declaration already.
388 {
389 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
390 RedeclComments.find(D);
391 if (Pos != RedeclComments.end()) {
392 const RawCommentAndCacheFlags &Raw = Pos->second;
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000393 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
394 if (OriginalDecl)
395 *OriginalDecl = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000396 return Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000397 }
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000398 }
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000399 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000400
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000401 // Search for comments attached to declarations in the redeclaration chain.
Craig Topper36250ad2014-05-12 05:36:57 +0000402 const RawComment *RC = nullptr;
403 const Decl *OriginalDeclForRC = nullptr;
Aaron Ballman86c93902014-03-06 23:45:36 +0000404 for (auto I : D->redecls()) {
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000405 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
Aaron Ballman86c93902014-03-06 23:45:36 +0000406 RedeclComments.find(I);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000407 if (Pos != RedeclComments.end()) {
408 const RawCommentAndCacheFlags &Raw = Pos->second;
409 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
410 RC = Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000411 OriginalDeclForRC = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000412 break;
413 }
414 } else {
Aaron Ballman86c93902014-03-06 23:45:36 +0000415 RC = getRawCommentForDeclNoCache(I);
416 OriginalDeclForRC = I;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000417 RawCommentAndCacheFlags Raw;
418 if (RC) {
Will Wilsonf9de5362015-10-27 17:01:10 +0000419 // Call order swapped to work around ICE in VS2015 RTM (Release Win32)
420 // https://connect.microsoft.com/VisualStudio/feedback/details/1741530
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000421 Raw.setKind(RawCommentAndCacheFlags::FromDecl);
Will Wilsonf9de5362015-10-27 17:01:10 +0000422 Raw.setRaw(RC);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000423 } else
424 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
Aaron Ballman86c93902014-03-06 23:45:36 +0000425 Raw.setOriginalDecl(I);
426 RedeclComments[I] = Raw;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000427 if (RC)
428 break;
429 }
430 }
431
Dmitri Gribenko5c8897d2012-06-28 16:25:36 +0000432 // If we found a comment, it should be a documentation comment.
David L. Jones13d5a872018-03-02 00:07:45 +0000433 assert(!RC || RC->isDocumentation() || LangOpts.CommentOpts.ParseAllComments);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000434
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000435 if (OriginalDecl)
436 *OriginalDecl = OriginalDeclForRC;
437
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000438 // Update cache for every declaration in the redeclaration chain.
439 RawCommentAndCacheFlags Raw;
440 Raw.setRaw(RC);
441 Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000442 Raw.setOriginalDecl(OriginalDeclForRC);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000443
Aaron Ballman86c93902014-03-06 23:45:36 +0000444 for (auto I : D->redecls()) {
445 RawCommentAndCacheFlags &R = RedeclComments[I];
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000446 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
447 R = Raw;
448 }
449
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000450 return RC;
451}
452
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000453static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
454 SmallVectorImpl<const NamedDecl *> &Redeclared) {
455 const DeclContext *DC = ObjCMethod->getDeclContext();
Eugene Zelenko7855e772018-04-03 00:11:50 +0000456 if (const auto *IMD = dyn_cast<ObjCImplDecl>(DC)) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000457 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
458 if (!ID)
459 return;
460 // Add redeclared method here.
Aaron Ballmanb4a53452014-03-13 21:57:01 +0000461 for (const auto *Ext : ID->known_extensions()) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000462 if (ObjCMethodDecl *RedeclaredMethod =
Douglas Gregor048fbfa2013-01-16 23:00:23 +0000463 Ext->getMethod(ObjCMethod->getSelector(),
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000464 ObjCMethod->isInstanceMethod()))
465 Redeclared.push_back(RedeclaredMethod);
466 }
467 }
468}
469
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000470comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
471 const Decl *D) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +0000472 auto *ThisDeclInfo = new (*this) comments::DeclInfo;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000473 ThisDeclInfo->CommentDecl = D;
474 ThisDeclInfo->IsFilled = false;
475 ThisDeclInfo->fill();
476 ThisDeclInfo->CommentDecl = FC->getDecl();
Argyrios Kyrtzidis7daabbd2014-04-27 22:53:03 +0000477 if (!ThisDeclInfo->TemplateParameters)
478 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000479 comments::FullComment *CFC =
480 new (*this) comments::FullComment(FC->getBlocks(),
481 ThisDeclInfo);
482 return CFC;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000483}
484
Richard Smithb39b9d52013-05-21 05:24:00 +0000485comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
486 const RawComment *RC = getRawCommentForDeclNoCache(D);
Craig Topper36250ad2014-05-12 05:36:57 +0000487 return RC ? RC->parse(*this, nullptr, D) : nullptr;
Richard Smithb39b9d52013-05-21 05:24:00 +0000488}
489
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000490comments::FullComment *ASTContext::getCommentForDecl(
491 const Decl *D,
492 const Preprocessor *PP) const {
Fariborz Jahanian096f7c12013-05-13 17:27:00 +0000493 if (D->isInvalidDecl())
Craig Topper36250ad2014-05-12 05:36:57 +0000494 return nullptr;
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000495 D = adjustDeclToTemplate(D);
Fangrui Song6907ce22018-07-30 19:24:48 +0000496
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000497 const Decl *Canonical = D->getCanonicalDecl();
498 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
499 ParsedComments.find(Canonical);
Fangrui Song6907ce22018-07-30 19:24:48 +0000500
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000501 if (Pos != ParsedComments.end()) {
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000502 if (Canonical != D) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000503 comments::FullComment *FC = Pos->second;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000504 comments::FullComment *CFC = cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000505 return CFC;
506 }
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000507 return Pos->second;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000508 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000509
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000510 const Decl *OriginalDecl;
Fangrui Song6907ce22018-07-30 19:24:48 +0000511
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000512 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000513 if (!RC) {
514 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000515 SmallVector<const NamedDecl*, 8> Overridden;
Eugene Zelenko7855e772018-04-03 00:11:50 +0000516 const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000517 if (OMD && OMD->isPropertyAccessor())
518 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
519 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
520 return cloneFullComment(FC, D);
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000521 if (OMD)
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000522 addRedeclaredMethods(OMD, Overridden);
523 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000524 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
525 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
526 return cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000527 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000528 else if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000529 // Attach any tag type's documentation to its typedef if latter
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000530 // does not have one of its own.
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000531 QualType QT = TD->getUnderlyingType();
Eugene Zelenko7855e772018-04-03 00:11:50 +0000532 if (const auto *TT = QT->getAs<TagType>())
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000533 if (const Decl *TD = TT->getDecl())
534 if (comments::FullComment *FC = getCommentForDecl(TD, PP))
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000535 return cloneFullComment(FC, D);
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000536 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000537 else if (const auto *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000538 while (IC->getSuperClass()) {
539 IC = IC->getSuperClass();
540 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
541 return cloneFullComment(FC, D);
542 }
543 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000544 else if (const auto *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000545 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
546 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
547 return cloneFullComment(FC, D);
548 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000549 else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000550 if (!(RD = RD->getDefinition()))
Craig Topper36250ad2014-05-12 05:36:57 +0000551 return nullptr;
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000552 // Check non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +0000553 for (const auto &I : RD->bases()) {
554 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000555 continue;
Aaron Ballman574705e2014-03-13 15:41:46 +0000556 QualType Ty = I.getType();
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000557 if (Ty.isNull())
558 continue;
559 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
560 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
561 continue;
Fangrui Song6907ce22018-07-30 19:24:48 +0000562
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000563 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
564 return cloneFullComment(FC, D);
565 }
566 }
567 // Check virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +0000568 for (const auto &I : RD->vbases()) {
569 if (I.getAccessSpecifier() != AS_public)
Fariborz Jahanian5a2e4a22013-04-26 23:34:36 +0000570 continue;
Aaron Ballman445a9392014-03-13 16:15:17 +0000571 QualType Ty = I.getType();
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000572 if (Ty.isNull())
573 continue;
574 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
575 if (!(VirtualBase= VirtualBase->getDefinition()))
576 continue;
577 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
578 return cloneFullComment(FC, D);
579 }
580 }
581 }
Craig Topper36250ad2014-05-12 05:36:57 +0000582 return nullptr;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000583 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000584
Dmitri Gribenkobfda9f72012-08-22 18:12:19 +0000585 // If the RawComment was attached to other redeclaration of this Decl, we
586 // should parse the comment in context of that other Decl. This is important
587 // because comments can contain references to parameter names which can be
588 // different across redeclarations.
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000589 if (D != OriginalDecl)
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000590 return getCommentForDecl(OriginalDecl, PP);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000591
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000592 comments::FullComment *FC = RC->parse(*this, PP, D);
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000593 ParsedComments[Canonical] = FC;
594 return FC;
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000595}
596
Fangrui Song6907ce22018-07-30 19:24:48 +0000597void
598ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000599 TemplateTemplateParmDecl *Parm) {
600 ID.AddInteger(Parm->getDepth());
601 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +0000602 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000603
604 TemplateParameterList *Params = Parm->getTemplateParameters();
605 ID.AddInteger(Params->size());
Fangrui Song6907ce22018-07-30 19:24:48 +0000606 for (TemplateParameterList::const_iterator P = Params->begin(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000607 PEnd = Params->end();
608 P != PEnd; ++P) {
Eugene Zelenko7855e772018-04-03 00:11:50 +0000609 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000610 ID.AddInteger(0);
611 ID.AddBoolean(TTP->isParameterPack());
612 continue;
613 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000614
Eugene Zelenko7855e772018-04-03 00:11:50 +0000615 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000616 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +0000617 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman205a4292012-03-07 01:09:33 +0000618 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000619 if (NTTP->isExpandedParameterPack()) {
620 ID.AddBoolean(true);
621 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman205a4292012-03-07 01:09:33 +0000622 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
623 QualType T = NTTP->getExpansionType(I);
624 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
625 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000626 } else
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000627 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000628 continue;
629 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000630
Eugene Zelenko7855e772018-04-03 00:11:50 +0000631 auto *TTP = cast<TemplateTemplateParmDecl>(*P);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000632 ID.AddInteger(2);
633 Profile(ID, TTP);
634 }
635}
636
637TemplateTemplateParmDecl *
638ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +0000639 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000640 // Check if we already have a canonical template template parameter.
641 llvm::FoldingSetNodeID ID;
642 CanonicalTemplateTemplateParm::Profile(ID, TTP);
Craig Topper36250ad2014-05-12 05:36:57 +0000643 void *InsertPos = nullptr;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000644 CanonicalTemplateTemplateParm *Canonical
645 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
646 if (Canonical)
647 return Canonical->getParam();
Fangrui Song6907ce22018-07-30 19:24:48 +0000648
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000649 // Build a canonical template parameter list.
650 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000651 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000652 CanonParams.reserve(Params->size());
Fangrui Song6907ce22018-07-30 19:24:48 +0000653 for (TemplateParameterList::const_iterator P = Params->begin(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000654 PEnd = Params->end();
655 P != PEnd; ++P) {
Eugene Zelenko7855e772018-04-03 00:11:50 +0000656 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000657 CanonParams.push_back(
Fangrui Song6907ce22018-07-30 19:24:48 +0000658 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000659 SourceLocation(),
660 SourceLocation(),
661 TTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000662 TTP->getIndex(), nullptr, false,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000663 TTP->isParameterPack()));
Eugene Zelenko7855e772018-04-03 00:11:50 +0000664 else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000665 QualType T = getCanonicalType(NTTP->getType());
666 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
667 NonTypeTemplateParmDecl *Param;
668 if (NTTP->isExpandedParameterPack()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000669 SmallVector<QualType, 2> ExpandedTypes;
670 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000671 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
672 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
673 ExpandedTInfos.push_back(
674 getTrivialTypeSourceInfo(ExpandedTypes.back()));
675 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000676
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000677 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000678 SourceLocation(),
679 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000680 NTTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000681 NTTP->getPosition(), nullptr,
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000682 T,
683 TInfo,
David Majnemerdfecf1a2016-07-06 04:19:16 +0000684 ExpandedTypes,
685 ExpandedTInfos);
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000686 } else {
687 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000688 SourceLocation(),
689 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000690 NTTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000691 NTTP->getPosition(), nullptr,
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000692 T,
693 NTTP->isParameterPack(),
694 TInfo);
695 }
696 CanonParams.push_back(Param);
697
698 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000699 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
700 cast<TemplateTemplateParmDecl>(*P)));
701 }
702
Hubert Tonge4a0c0e2016-07-30 22:33:34 +0000703 assert(!TTP->getRequiresClause() &&
704 "Unexpected requires-clause on template template-parameter");
George Burgess IVb7e4e482016-08-25 01:54:37 +0000705 Expr *const CanonRequiresClause = nullptr;
Hubert Tonge4a0c0e2016-07-30 22:33:34 +0000706
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000707 TemplateTemplateParmDecl *CanonTTP
Fangrui Song6907ce22018-07-30 19:24:48 +0000708 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000709 SourceLocation(), TTP->getDepth(),
Fangrui Song6907ce22018-07-30 19:24:48 +0000710 TTP->getPosition(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000711 TTP->isParameterPack(),
Craig Topper36250ad2014-05-12 05:36:57 +0000712 nullptr,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000713 TemplateParameterList::Create(*this, SourceLocation(),
714 SourceLocation(),
David Majnemer902f8c62015-12-27 07:16:27 +0000715 CanonParams,
Hubert Tonge4a0c0e2016-07-30 22:33:34 +0000716 SourceLocation(),
717 CanonRequiresClause));
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000718
719 // Get the new insert position for the node we care about.
720 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +0000721 assert(!Canonical && "Shouldn't be in the map!");
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000722 (void)Canonical;
723
724 // Create the canonical template template parameter entry.
725 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
726 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
727 return CanonTTP;
728}
729
Charles Davis53c59df2010-08-16 03:33:14 +0000730CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
Craig Topper36250ad2014-05-12 05:36:57 +0000731 if (!LangOpts.CPlusPlus) return nullptr;
John McCall86353412010-08-21 22:46:04 +0000732
John McCall359b8852013-01-25 22:30:49 +0000733 switch (T.getCXXABI().getKind()) {
Joerg Sonnenbergerdaa13aa2014-05-13 11:20:16 +0000734 case TargetCXXABI::GenericARM: // Same as Itanium at this level
John McCall359b8852013-01-25 22:30:49 +0000735 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +0000736 case TargetCXXABI::iOS64:
Tim Northover756447a2015-10-30 16:30:36 +0000737 case TargetCXXABI::WatchOS:
Joerg Sonnenbergerdaa13aa2014-05-13 11:20:16 +0000738 case TargetCXXABI::GenericAArch64:
Zoran Jovanovic26a12162015-02-18 15:21:35 +0000739 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +0000740 case TargetCXXABI::GenericItanium:
Dan Gohmanc2853072015-09-03 22:51:53 +0000741 case TargetCXXABI::WebAssembly:
Charles Davis53c59df2010-08-16 03:33:14 +0000742 return CreateItaniumCXXABI(*this);
John McCall359b8852013-01-25 22:30:49 +0000743 case TargetCXXABI::Microsoft:
Charles Davis6bcb07a2010-08-19 02:18:14 +0000744 return CreateMicrosoftCXXABI(*this);
745 }
David Blaikie8a40f702012-01-17 06:56:22 +0000746 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000747}
748
Alexander Richardson6d989432017-10-15 18:48:14 +0000749static const LangASMap *getAddressSpaceMap(const TargetInfo &T,
750 const LangOptions &LOpts) {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000751 if (LOpts.FakeAddressSpaceMap) {
752 // The fake address space map must have a distinct entry for each
753 // language-specific address space.
754 static const unsigned FakeAddrSpaceMap[] = {
Yaxun Liub34ec822017-04-11 17:24:23 +0000755 0, // Default
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000756 1, // opencl_global
Egor Churaev28f00aa2016-12-23 16:11:25 +0000757 3, // opencl_local
758 2, // opencl_constant
Yaxun Liub7318e02017-10-13 03:37:48 +0000759 0, // opencl_private
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +0000760 4, // opencl_generic
761 5, // cuda_device
762 6, // cuda_constant
763 7 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000764 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000765 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000766 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000767 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000768 }
769}
770
David Tweed31d09b02013-09-13 12:04:22 +0000771static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
772 const LangOptions &LangOpts) {
773 switch (LangOpts.getAddressSpaceMapMangling()) {
David Tweed31d09b02013-09-13 12:04:22 +0000774 case LangOptions::ASMM_Target:
775 return TI.useAddressSpaceMapMangling();
776 case LangOptions::ASMM_On:
777 return true;
778 case LangOptions::ASMM_Off:
779 return false;
780 }
NAKAMURA Takumi5c81ca42013-09-13 17:12:09 +0000781 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
David Tweed31d09b02013-09-13 12:04:22 +0000782}
783
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000784ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000785 IdentifierTable &idents, SelectorTable &sels,
Alp Toker08043432014-05-03 03:46:04 +0000786 Builtin::Context &builtins)
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000787 : FunctionProtoTypes(this_()), TemplateSpecializationTypes(this_()),
788 DependentTemplateSpecializationTypes(this_()),
Eugene Zelenko5e5e5642017-11-23 01:20:07 +0000789 SubstTemplateTemplateParmPacks(this_()), SourceMgr(SM), LangOpts(LOpts),
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000790 SanitizerBL(new SanitizerBlacklist(LangOpts.SanitizerBlacklistFiles, SM)),
Dean Michael Berris835832d2017-03-30 00:29:36 +0000791 XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles,
Dean Michael Berris20dc6ef2018-04-09 04:02:09 +0000792 LangOpts.XRayNeverInstrumentFiles,
793 LangOpts.XRayAttrListFiles, SM)),
Artem Belevichb5bc9232015-09-22 17:23:22 +0000794 PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
Eugene Zelenko5e5e5642017-11-23 01:20:07 +0000795 BuiltinInfo(builtins), DeclarationNames(*this), Comments(SM),
Eric Fiselier0683c0e2018-05-07 21:07:10 +0000796 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
797 CompCategories(this_()), LastSDM(nullptr, 0) {
Daniel Dunbar221fa942008-08-11 04:54:23 +0000798 TUDecl = TranslationUnitDecl::Create(*this);
799}
800
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000801ASTContext::~ASTContext() {
Manuel Klimek95403e62014-05-21 13:28:59 +0000802 ReleaseParentMapEntries();
803
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000804 // Release the DenseMaps associated with DeclContext objects.
805 // FIXME: Is this the ideal solution?
806 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000807
Manuel Klimeka7328992013-06-03 13:51:33 +0000808 // Call all of the deallocation functions on all of their targets.
Chandler Carruthff5a01a2015-12-30 03:00:23 +0000809 for (auto &Pair : Deallocations)
810 (Pair.first)(Pair.second);
Manuel Klimeka7328992013-06-03 13:51:33 +0000811
Ted Kremenek076baeb2010-06-08 23:00:58 +0000812 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000813 // because they can contain DenseMaps.
814 for (llvm::DenseMap<const ObjCContainerDecl*,
815 const ASTRecordLayout*>::iterator
816 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
817 // Increment in loop to prevent using deallocated memory.
Eugene Zelenko7855e772018-04-03 00:11:50 +0000818 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
Douglas Gregor5b11d492010-07-25 17:53:33 +0000819 R->Destroy(*this);
820
Ted Kremenek076baeb2010-06-08 23:00:58 +0000821 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
822 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
823 // Increment in loop to prevent using deallocated memory.
Eugene Zelenko7855e772018-04-03 00:11:50 +0000824 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
Ted Kremenek076baeb2010-06-08 23:00:58 +0000825 R->Destroy(*this);
826 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000827
Douglas Gregor561eceb2010-08-30 16:49:28 +0000828 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
829 AEnd = DeclAttrs.end();
830 A != AEnd; ++A)
831 A->second->~AttrVec();
Reid Klecknerd8110b62013-09-10 20:14:30 +0000832
David Majnemere694f3e2015-08-14 14:43:50 +0000833 for (std::pair<const MaterializeTemporaryExpr *, APValue *> &MTVPair :
834 MaterializedTemporaryValues)
835 MTVPair.second->~APValue();
836
Richard Smith423f46f2016-07-20 21:38:26 +0000837 for (const auto &Value : ModuleInitializers)
838 Value.second->~PerModuleInitializers();
Douglas Gregor561eceb2010-08-30 16:49:28 +0000839}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000840
Manuel Klimek95403e62014-05-21 13:28:59 +0000841void ASTContext::ReleaseParentMapEntries() {
Benjamin Kramer94355ae2015-10-23 09:04:55 +0000842 if (!PointerParents) return;
843 for (const auto &Entry : *PointerParents) {
844 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
845 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
846 } else if (Entry.second.is<ParentVector *>()) {
847 delete Entry.second.get<ParentVector *>();
848 }
849 }
850 for (const auto &Entry : *OtherParents) {
Manuel Klimek95403e62014-05-21 13:28:59 +0000851 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
852 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
Benjamin Kramer8e4a1762015-10-22 11:21:40 +0000853 } else if (Entry.second.is<ParentVector *>()) {
Manuel Klimek95403e62014-05-21 13:28:59 +0000854 delete Entry.second.get<ParentVector *>();
855 }
856 }
857}
858
Douglas Gregor1a809332010-05-23 18:26:36 +0000859void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
Chandler Carruthff5a01a2015-12-30 03:00:23 +0000860 Deallocations.push_back({Callback, Data});
Douglas Gregor1a809332010-05-23 18:26:36 +0000861}
862
Mike Stump11289f42009-09-09 15:08:12 +0000863void
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000864ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
Benjamin Kramerd6da1a02016-06-12 20:05:23 +0000865 ExternalSource = std::move(Source);
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000866}
867
Chris Lattner4eb445d2007-01-26 01:27:23 +0000868void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000869 llvm::errs() << "\n*** AST Context Stats:\n";
870 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000871
Douglas Gregora30d0462009-05-26 14:40:08 +0000872 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000873#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000874#define ABSTRACT_TYPE(Name, Parent)
875#include "clang/AST/TypeNodes.def"
876 0 // Extra
877 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000878
Chris Lattner4eb445d2007-01-26 01:27:23 +0000879 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
880 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000881 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000882 }
883
Douglas Gregora30d0462009-05-26 14:40:08 +0000884 unsigned Idx = 0;
885 unsigned TotalBytes = 0;
886#define TYPE(Name, Parent) \
887 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000888 llvm::errs() << " " << counts[Idx] << " " << #Name \
Bruno Ricci58e03222018-08-06 15:17:32 +0000889 << " types, " << sizeof(Name##Type) << " each " \
890 << "(" << counts[Idx] * sizeof(Name##Type) \
891 << " bytes)\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000892 TotalBytes += counts[Idx] * sizeof(Name##Type); \
893 ++Idx;
894#define ABSTRACT_TYPE(Name, Parent)
895#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000896
Chandler Carruth3c147a72011-07-04 05:32:14 +0000897 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
898
Douglas Gregor7454c562010-07-02 20:37:36 +0000899 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000900 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
901 << NumImplicitDefaultConstructors
902 << " implicit default constructors created\n";
903 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
904 << NumImplicitCopyConstructors
905 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000906 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000907 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
908 << NumImplicitMoveConstructors
909 << " implicit move constructors created\n";
910 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
911 << NumImplicitCopyAssignmentOperators
912 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000913 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000914 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
915 << NumImplicitMoveAssignmentOperators
916 << " implicit move assignment operators created\n";
917 llvm::errs() << NumImplicitDestructorsDeclared << "/"
918 << NumImplicitDestructors
919 << " implicit destructors created\n";
920
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000921 if (ExternalSource) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000922 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000923 ExternalSource->PrintStats();
924 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000925
Douglas Gregor5b11d492010-07-25 17:53:33 +0000926 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000927}
928
Richard Smith42413142015-05-15 20:05:43 +0000929void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
930 bool NotifyListeners) {
931 if (NotifyListeners)
932 if (auto *Listener = getASTMutationListener())
933 Listener->RedefinedHiddenDefinition(ND, M);
934
Benjamin Kramera72a70a2016-10-17 13:00:44 +0000935 if (getLangOpts().ModulesLocalVisibility)
936 MergedDefModules[ND].push_back(M);
937 else
Richard Smith90dc5252017-06-23 01:04:34 +0000938 ND->setVisibleDespiteOwningModule();
Richard Smith42413142015-05-15 20:05:43 +0000939}
940
941void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) {
942 auto It = MergedDefModules.find(ND);
943 if (It == MergedDefModules.end())
944 return;
945
Benjamin Kramera72a70a2016-10-17 13:00:44 +0000946 auto &Merged = It->second;
Richard Smith42413142015-05-15 20:05:43 +0000947 llvm::DenseSet<Module*> Found;
948 for (Module *&M : Merged)
949 if (!Found.insert(M).second)
950 M = nullptr;
951 Merged.erase(std::remove(Merged.begin(), Merged.end(), nullptr), Merged.end());
952}
953
Richard Smithdc1f0422016-07-20 19:10:16 +0000954void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
955 if (LazyInitializers.empty())
956 return;
957
958 auto *Source = Ctx.getExternalSource();
959 assert(Source && "lazy initializers but no external source");
960
961 auto LazyInits = std::move(LazyInitializers);
962 LazyInitializers.clear();
963
964 for (auto ID : LazyInits)
965 Initializers.push_back(Source->GetExternalDecl(ID));
966
967 assert(LazyInitializers.empty() &&
968 "GetExternalDecl for lazy module initializer added more inits");
969}
970
971void ASTContext::addModuleInitializer(Module *M, Decl *D) {
972 // One special case: if we add a module initializer that imports another
973 // module, and that module's only initializer is an ImportDecl, simplify.
Eugene Zelenko7855e772018-04-03 00:11:50 +0000974 if (const auto *ID = dyn_cast<ImportDecl>(D)) {
Richard Smithdc1f0422016-07-20 19:10:16 +0000975 auto It = ModuleInitializers.find(ID->getImportedModule());
976
977 // Maybe the ImportDecl does nothing at all. (Common case.)
978 if (It == ModuleInitializers.end())
979 return;
980
981 // Maybe the ImportDecl only imports another ImportDecl.
982 auto &Imported = *It->second;
983 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
984 Imported.resolve(*this);
985 auto *OnlyDecl = Imported.Initializers.front();
986 if (isa<ImportDecl>(OnlyDecl))
987 D = OnlyDecl;
988 }
989 }
990
991 auto *&Inits = ModuleInitializers[M];
992 if (!Inits)
993 Inits = new (*this) PerModuleInitializers;
994 Inits->Initializers.push_back(D);
995}
996
997void ASTContext::addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs) {
998 auto *&Inits = ModuleInitializers[M];
999 if (!Inits)
1000 Inits = new (*this) PerModuleInitializers;
1001 Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
1002 IDs.begin(), IDs.end());
1003}
1004
Eugene Zelenko7855e772018-04-03 00:11:50 +00001005ArrayRef<Decl *> ASTContext::getModuleInitializers(Module *M) {
Richard Smithdc1f0422016-07-20 19:10:16 +00001006 auto It = ModuleInitializers.find(M);
Fangrui Song6907ce22018-07-30 19:24:48 +00001007 if (It == ModuleInitializers.end())
Richard Smithdc1f0422016-07-20 19:10:16 +00001008 return None;
1009
1010 auto *Inits = It->second;
1011 Inits->resolve(*this);
1012 return Inits->Initializers;
1013}
1014
Richard Smithf19e1272015-03-07 00:04:49 +00001015ExternCContextDecl *ASTContext::getExternCContextDecl() const {
1016 if (!ExternCContext)
1017 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
1018
1019 return ExternCContext;
1020}
1021
David Majnemerd9b1a4f2015-11-04 03:40:30 +00001022BuiltinTemplateDecl *
1023ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
1024 const IdentifierInfo *II) const {
1025 auto *BuiltinTemplate = BuiltinTemplateDecl::Create(*this, TUDecl, II, BTK);
1026 BuiltinTemplate->setImplicit();
1027 TUDecl->addDecl(BuiltinTemplate);
1028
1029 return BuiltinTemplate;
1030}
1031
1032BuiltinTemplateDecl *
1033ASTContext::getMakeIntegerSeqDecl() const {
1034 if (!MakeIntegerSeqDecl)
1035 MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq,
1036 getMakeIntegerSeqName());
1037 return MakeIntegerSeqDecl;
1038}
1039
Eric Fiselier6ad68552016-07-01 01:24:09 +00001040BuiltinTemplateDecl *
1041ASTContext::getTypePackElementDecl() const {
1042 if (!TypePackElementDecl)
1043 TypePackElementDecl = buildBuiltinTemplateDecl(BTK__type_pack_element,
1044 getTypePackElementName());
1045 return TypePackElementDecl;
1046}
1047
Alp Toker2dea15b2013-12-17 01:22:38 +00001048RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
1049 RecordDecl::TagKind TK) const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001050 SourceLocation Loc;
1051 RecordDecl *NewDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00001052 if (getLangOpts().CPlusPlus)
1053 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
1054 Loc, &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +00001055 else
Alp Toker2dea15b2013-12-17 01:22:38 +00001056 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
1057 &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +00001058 NewDecl->setImplicit();
David Majnemerf8637362015-01-15 08:41:25 +00001059 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
1060 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
Alp Toker56b5cc92013-12-15 10:36:26 +00001061 return NewDecl;
1062}
1063
1064TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
1065 StringRef Name) const {
1066 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
1067 TypedefDecl *NewDecl = TypedefDecl::Create(
1068 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
1069 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
1070 NewDecl->setImplicit();
1071 return NewDecl;
1072}
1073
Douglas Gregor801c99d2011-08-12 06:49:56 +00001074TypedefDecl *ASTContext::getInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001075 if (!Int128Decl)
1076 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +00001077 return Int128Decl;
1078}
1079
1080TypedefDecl *ASTContext::getUInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001081 if (!UInt128Decl)
1082 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +00001083 return UInt128Decl;
1084}
Chris Lattner4eb445d2007-01-26 01:27:23 +00001085
John McCall48f2d582009-10-23 23:03:21 +00001086void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001087 auto *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +00001088 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +00001089 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001090}
1091
Artem Belevichb5bc9232015-09-22 17:23:22 +00001092void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
1093 const TargetInfo *AuxTarget) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001094 assert((!this->Target || this->Target == &Target) &&
1095 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +00001096 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +00001097
Douglas Gregore8bbc122011-09-02 00:18:52 +00001098 this->Target = &Target;
Artem Belevichb5bc9232015-09-22 17:23:22 +00001099 this->AuxTarget = AuxTarget;
1100
Douglas Gregore8bbc122011-09-02 00:18:52 +00001101 ABI.reset(createCXXABI(Target));
1102 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
David Tweed31d09b02013-09-13 12:04:22 +00001103 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
Fangrui Song6907ce22018-07-30 19:24:48 +00001104
Chris Lattner970e54e2006-11-12 00:37:36 +00001105 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +00001106 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +00001107
Chris Lattner970e54e2006-11-12 00:37:36 +00001108 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +00001109 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +00001110 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +00001111 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +00001112 InitBuiltinType(CharTy, BuiltinType::Char_S);
1113 else
1114 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +00001115 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +00001116 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
1117 InitBuiltinType(ShortTy, BuiltinType::Short);
1118 InitBuiltinType(IntTy, BuiltinType::Int);
1119 InitBuiltinType(LongTy, BuiltinType::Long);
1120 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +00001121
Chris Lattner970e54e2006-11-12 00:37:36 +00001122 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +00001123 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
1124 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
1125 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
1126 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
1127 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +00001128
Chris Lattner970e54e2006-11-12 00:37:36 +00001129 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +00001130 InitBuiltinType(FloatTy, BuiltinType::Float);
1131 InitBuiltinType(DoubleTy, BuiltinType::Double);
1132 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001133
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001134 // GNU extension, __float128 for IEEE quadruple precision
1135 InitBuiltinType(Float128Ty, BuiltinType::Float128);
1136
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00001137 // C11 extension ISO/IEC TS 18661-3
1138 InitBuiltinType(Float16Ty, BuiltinType::Float16);
1139
Leonard Chanf921d852018-06-04 16:07:52 +00001140 // ISO/IEC JTC1 SC22 WG14 N1169 Extension
Leonard Chanab80f3c2018-06-14 14:53:51 +00001141 InitBuiltinType(ShortAccumTy, BuiltinType::ShortAccum);
1142 InitBuiltinType(AccumTy, BuiltinType::Accum);
1143 InitBuiltinType(LongAccumTy, BuiltinType::LongAccum);
1144 InitBuiltinType(UnsignedShortAccumTy, BuiltinType::UShortAccum);
1145 InitBuiltinType(UnsignedAccumTy, BuiltinType::UAccum);
1146 InitBuiltinType(UnsignedLongAccumTy, BuiltinType::ULongAccum);
1147 InitBuiltinType(ShortFractTy, BuiltinType::ShortFract);
1148 InitBuiltinType(FractTy, BuiltinType::Fract);
1149 InitBuiltinType(LongFractTy, BuiltinType::LongFract);
1150 InitBuiltinType(UnsignedShortFractTy, BuiltinType::UShortFract);
1151 InitBuiltinType(UnsignedFractTy, BuiltinType::UFract);
1152 InitBuiltinType(UnsignedLongFractTy, BuiltinType::ULongFract);
1153 InitBuiltinType(SatShortAccumTy, BuiltinType::SatShortAccum);
1154 InitBuiltinType(SatAccumTy, BuiltinType::SatAccum);
1155 InitBuiltinType(SatLongAccumTy, BuiltinType::SatLongAccum);
1156 InitBuiltinType(SatUnsignedShortAccumTy, BuiltinType::SatUShortAccum);
1157 InitBuiltinType(SatUnsignedAccumTy, BuiltinType::SatUAccum);
1158 InitBuiltinType(SatUnsignedLongAccumTy, BuiltinType::SatULongAccum);
1159 InitBuiltinType(SatShortFractTy, BuiltinType::SatShortFract);
1160 InitBuiltinType(SatFractTy, BuiltinType::SatFract);
1161 InitBuiltinType(SatLongFractTy, BuiltinType::SatLongFract);
1162 InitBuiltinType(SatUnsignedShortFractTy, BuiltinType::SatUShortFract);
1163 InitBuiltinType(SatUnsignedFractTy, BuiltinType::SatUFract);
1164 InitBuiltinType(SatUnsignedLongFractTy, BuiltinType::SatULongFract);
Leonard Chanf921d852018-06-04 16:07:52 +00001165
Chris Lattnerf122cef2009-04-30 02:43:43 +00001166 // GNU extension, 128-bit integers.
1167 InitBuiltinType(Int128Ty, BuiltinType::Int128);
1168 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
1169
Hans Wennborg0d81e012013-05-10 10:08:40 +00001170 // C++ 3.9.1p5
1171 if (TargetInfo::isTypeSigned(Target.getWCharType()))
1172 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1173 else // -fshort-wchar makes wchar_t be unsigned.
1174 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1175 if (LangOpts.CPlusPlus && LangOpts.WChar)
1176 WideCharTy = WCharTy;
1177 else {
1178 // C99 (or C++ using -fno-wchar).
1179 WideCharTy = getFromTargetType(Target.getWCharType());
1180 }
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001181
James Molloy36365542012-05-04 10:55:22 +00001182 WIntTy = getFromTargetType(Target.getWIntType());
1183
Richard Smith3a8244d2018-05-01 05:02:45 +00001184 // C++20 (proposed)
1185 InitBuiltinType(Char8Ty, BuiltinType::Char8);
1186
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001187 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1188 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1189 else // C99
1190 Char16Ty = getFromTargetType(Target.getChar16Type());
1191
1192 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1193 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1194 else // C99
1195 Char32Ty = getFromTargetType(Target.getChar32Type());
1196
Douglas Gregor4619e432008-12-05 23:32:09 +00001197 // Placeholder type for type-dependent expressions whose type is
1198 // completely unknown. No code should ever check a type against
1199 // DependentTy and users should never see it; however, it is here to
1200 // help diagnose failures to properly check for type-dependent
1201 // expressions.
1202 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001203
John McCall36e7fe32010-10-12 00:20:44 +00001204 // Placeholder type for functions.
1205 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1206
John McCall0009fcc2011-04-26 20:42:42 +00001207 // Placeholder type for bound members.
1208 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1209
John McCall526ab472011-10-25 17:37:35 +00001210 // Placeholder type for pseudo-objects.
1211 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1212
John McCall31996342011-04-07 08:22:57 +00001213 // "any" type; useful for debugger-like clients.
1214 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1215
John McCall8a6b59a2011-10-17 18:09:15 +00001216 // Placeholder type for unbridged ARC casts.
1217 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1218
Eli Friedman34866c72012-08-31 00:14:07 +00001219 // Placeholder type for builtin functions.
1220 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1221
Alexey Bataev1a3320e2015-08-25 14:24:04 +00001222 // Placeholder type for OMP array sections.
1223 if (LangOpts.OpenMP)
1224 InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection);
1225
Chris Lattner970e54e2006-11-12 00:37:36 +00001226 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +00001227 FloatComplexTy = getComplexType(FloatTy);
1228 DoubleComplexTy = getComplexType(DoubleTy);
1229 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001230 Float128ComplexTy = getComplexType(Float128Ty);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001231
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001232 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +00001233 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1234 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001235 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001236
Alexey Bader954ba212016-04-08 13:40:33 +00001237 if (LangOpts.OpenCL) {
1238#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1239 InitBuiltinType(SingletonId, BuiltinType::Id);
Alexey Baderb62f1442016-04-13 08:33:41 +00001240#include "clang/Basic/OpenCLImageTypes.def"
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001241
Guy Benyei61054192013-02-07 10:55:47 +00001242 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001243 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Alexey Bader9c8453f2015-09-15 11:18:52 +00001244 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1245 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
Alexey Bader9c8453f2015-09-15 11:18:52 +00001246 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001247 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001248
Ted Kremeneke65b0862012-03-06 20:05:56 +00001249 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +00001250 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1251 SignedCharTy : BoolTy);
Fangrui Song6907ce22018-07-30 19:24:48 +00001252
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001253 ObjCConstantStringType = QualType();
Fangrui Song6907ce22018-07-30 19:24:48 +00001254
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001255 ObjCSuperType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +00001256
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00001257 // void * type
Yaxun Liu39195062017-08-04 18:16:31 +00001258 if (LangOpts.OpenCLVersion >= 200) {
1259 auto Q = VoidTy.getQualifiers();
1260 Q.setAddressSpace(LangAS::opencl_generic);
1261 VoidPtrTy = getPointerType(getCanonicalType(
1262 getQualifiedType(VoidTy.getUnqualifiedType(), Q)));
1263 } else {
1264 VoidPtrTy = getPointerType(VoidTy);
1265 }
Sebastian Redl576fd422009-05-10 18:38:11 +00001266
1267 // nullptr type (C++0x 2.14.7)
1268 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001269
1270 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1271 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +00001272
1273 // Builtin type used to help define __builtin_va_list.
Richard Smith9b88a4c2015-07-27 05:40:23 +00001274 VaListTagDecl = nullptr;
Chris Lattner970e54e2006-11-12 00:37:36 +00001275}
1276
David Blaikie9c902b52011-09-25 23:23:43 +00001277DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001278 return SourceMgr.getDiagnostics();
1279}
1280
Douglas Gregor561eceb2010-08-30 16:49:28 +00001281AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1282 AttrVec *&Result = DeclAttrs[D];
1283 if (!Result) {
1284 void *Mem = Allocate(sizeof(AttrVec));
1285 Result = new (Mem) AttrVec;
1286 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001287
Douglas Gregor561eceb2010-08-30 16:49:28 +00001288 return *Result;
1289}
1290
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001291/// Erase the attributes corresponding to the given declaration.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00001292void ASTContext::eraseDeclAttrs(const Decl *D) {
Douglas Gregor561eceb2010-08-30 16:49:28 +00001293 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1294 if (Pos != DeclAttrs.end()) {
1295 Pos->second->~AttrVec();
1296 DeclAttrs.erase(Pos);
1297 }
1298}
1299
Larisse Voufo39a1e502013-08-06 01:03:05 +00001300// FIXME: Remove ?
Douglas Gregor86d142a2009-10-08 07:24:58 +00001301MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +00001302ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001303 assert(Var->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001304 return getTemplateOrSpecializationInfo(Var)
1305 .dyn_cast<MemberSpecializationInfo *>();
1306}
1307
1308ASTContext::TemplateOrSpecializationInfo
1309ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1310 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1311 TemplateOrInstantiation.find(Var);
1312 if (Pos == TemplateOrInstantiation.end())
Eugene Zelenko7855e772018-04-03 00:11:50 +00001313 return {};
Mike Stump11289f42009-09-09 15:08:12 +00001314
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001315 return Pos->second;
1316}
1317
Mike Stump11289f42009-09-09 15:08:12 +00001318void
Douglas Gregor86d142a2009-10-08 07:24:58 +00001319ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +00001320 TemplateSpecializationKind TSK,
1321 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001322 assert(Inst->isStaticDataMember() && "Not a static data member");
1323 assert(Tmpl->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001324 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1325 Tmpl, TSK, PointOfInstantiation));
1326}
1327
1328void
1329ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1330 TemplateOrSpecializationInfo TSI) {
1331 assert(!TemplateOrInstantiation[Inst] &&
1332 "Already noted what the variable was instantiated from");
1333 TemplateOrInstantiation[Inst] = TSI;
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001334}
1335
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001336FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1337 const FunctionDecl *FD){
1338 assert(FD && "Specialization is 0");
1339 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +00001340 = ClassScopeSpecializationPattern.find(FD);
1341 if (Pos == ClassScopeSpecializationPattern.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001342 return nullptr;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001343
1344 return Pos->second;
1345}
1346
1347void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1348 FunctionDecl *Pattern) {
1349 assert(FD && "Specialization is 0");
1350 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +00001351 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001352}
1353
John McCalle61f2ba2009-11-18 02:36:19 +00001354NamedDecl *
Richard Smithd8a9e372016-12-18 21:39:37 +00001355ASTContext::getInstantiatedFromUsingDecl(NamedDecl *UUD) {
1356 auto Pos = InstantiatedFromUsingDecl.find(UUD);
John McCallb96ec562009-12-04 22:46:56 +00001357 if (Pos == InstantiatedFromUsingDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001358 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001359
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001360 return Pos->second;
1361}
1362
1363void
Richard Smithd8a9e372016-12-18 21:39:37 +00001364ASTContext::setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern) {
John McCallb96ec562009-12-04 22:46:56 +00001365 assert((isa<UsingDecl>(Pattern) ||
1366 isa<UnresolvedUsingValueDecl>(Pattern) ||
Fangrui Song6907ce22018-07-30 19:24:48 +00001367 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
John McCallb96ec562009-12-04 22:46:56 +00001368 "pattern decl is not a using decl");
Richard Smithd8a9e372016-12-18 21:39:37 +00001369 assert((isa<UsingDecl>(Inst) ||
1370 isa<UnresolvedUsingValueDecl>(Inst) ||
Fangrui Song6907ce22018-07-30 19:24:48 +00001371 isa<UnresolvedUsingTypenameDecl>(Inst)) &&
Richard Smithd8a9e372016-12-18 21:39:37 +00001372 "instantiation did not produce a using decl");
John McCallb96ec562009-12-04 22:46:56 +00001373 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1374 InstantiatedFromUsingDecl[Inst] = Pattern;
1375}
1376
1377UsingShadowDecl *
1378ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1379 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1380 = InstantiatedFromUsingShadowDecl.find(Inst);
1381 if (Pos == InstantiatedFromUsingShadowDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001382 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00001383
1384 return Pos->second;
1385}
1386
1387void
1388ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1389 UsingShadowDecl *Pattern) {
1390 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1391 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001392}
1393
Anders Carlsson5da84842009-09-01 04:26:58 +00001394FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1395 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1396 = InstantiatedFromUnnamedFieldDecl.find(Field);
1397 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001398 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001399
Anders Carlsson5da84842009-09-01 04:26:58 +00001400 return Pos->second;
1401}
1402
1403void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1404 FieldDecl *Tmpl) {
1405 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1406 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1407 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1408 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +00001409
Anders Carlsson5da84842009-09-01 04:26:58 +00001410 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1411}
1412
Douglas Gregor832940b2010-03-02 23:58:15 +00001413ASTContext::overridden_cxx_method_iterator
1414ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
Benjamin Krameracfa3392017-12-17 23:52:45 +00001415 return overridden_methods(Method).begin();
Douglas Gregor832940b2010-03-02 23:58:15 +00001416}
1417
1418ASTContext::overridden_cxx_method_iterator
1419ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
Benjamin Krameracfa3392017-12-17 23:52:45 +00001420 return overridden_methods(Method).end();
Douglas Gregor832940b2010-03-02 23:58:15 +00001421}
1422
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001423unsigned
1424ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
Benjamin Krameracfa3392017-12-17 23:52:45 +00001425 auto Range = overridden_methods(Method);
1426 return Range.end() - Range.begin();
Clement Courbet8251ebf2016-06-10 11:54:43 +00001427}
1428
Clement Courbet6ecaec82016-07-05 07:49:31 +00001429ASTContext::overridden_method_range
1430ASTContext::overridden_methods(const CXXMethodDecl *Method) const {
Benjamin Krameracfa3392017-12-17 23:52:45 +00001431 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1432 OverriddenMethods.find(Method->getCanonicalDecl());
1433 if (Pos == OverriddenMethods.end())
1434 return overridden_method_range(nullptr, nullptr);
1435 return overridden_method_range(Pos->second.begin(), Pos->second.end());
Clement Courbet6ecaec82016-07-05 07:49:31 +00001436}
1437
Fangrui Song6907ce22018-07-30 19:24:48 +00001438void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
Douglas Gregor832940b2010-03-02 23:58:15 +00001439 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001440 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001441 OverriddenMethods[Method].push_back(Overridden);
1442}
1443
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +00001444void ASTContext::getOverriddenMethods(
1445 const NamedDecl *D,
1446 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001447 assert(D);
1448
Eugene Zelenko7855e772018-04-03 00:11:50 +00001449 if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisc8e70082013-04-17 00:09:03 +00001450 Overridden.append(overridden_methods_begin(CXXMethod),
1451 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001452 return;
1453 }
1454
Eugene Zelenko7855e772018-04-03 00:11:50 +00001455 const auto *Method = dyn_cast<ObjCMethodDecl>(D);
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001456 if (!Method)
1457 return;
1458
Argyrios Kyrtzidis353f6a42012-10-09 18:19:01 +00001459 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1460 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001461 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001462}
1463
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001464void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1465 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1466 assert(!Import->isFromASTFile() && "Non-local import declaration");
1467 if (!FirstLocalImport) {
1468 FirstLocalImport = Import;
1469 LastLocalImport = Import;
1470 return;
1471 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001472
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001473 LastLocalImport->NextLocalImport = Import;
1474 LastLocalImport = Import;
1475}
1476
Chris Lattner53cfe802007-07-18 17:52:12 +00001477//===----------------------------------------------------------------------===//
1478// Type Sizing and Analysis
1479//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001480
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001481/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1482/// scalar floating point type.
1483const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001484 const auto *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001485 assert(BT && "Not a floating point type!");
1486 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001487 default: llvm_unreachable("Not a floating point type!");
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00001488 case BuiltinType::Float16:
1489 case BuiltinType::Half:
1490 return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001491 case BuiltinType::Float: return Target->getFloatFormat();
1492 case BuiltinType::Double: return Target->getDoubleFormat();
1493 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001494 case BuiltinType::Float128: return Target->getFloat128Format();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001495 }
1496}
1497
Rafael Espindola71eccb32013-08-08 19:53:46 +00001498CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001499 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001500
John McCall94268702010-10-08 18:24:19 +00001501 bool UseAlignAttrOnly = false;
1502 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1503 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001504
John McCall94268702010-10-08 18:24:19 +00001505 // __attribute__((aligned)) can increase or decrease alignment
1506 // *except* on a struct or struct member, where it only increases
1507 // alignment unless 'packed' is also specified.
1508 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001509 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001510 // ignore that possibility; Sema should diagnose it.
1511 if (isa<FieldDecl>(D)) {
1512 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1513 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1514 } else {
1515 UseAlignAttrOnly = true;
1516 }
1517 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001518 else if (isa<FieldDecl>(D))
Fangrui Song6907ce22018-07-30 19:24:48 +00001519 UseAlignAttrOnly =
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001520 D->hasAttr<PackedAttr>() ||
1521 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001522
John McCall4e819612011-01-20 07:57:12 +00001523 // If we're using the align attribute only, just ignore everything
1524 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001525 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001526 // do nothing
Eugene Zelenko7855e772018-04-03 00:11:50 +00001527 } else if (const auto *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001528 QualType T = VD->getType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00001529 if (const auto *RT = T->getAs<ReferenceType>()) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001530 if (ForAlignof)
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001531 T = RT->getPointeeType();
1532 else
1533 T = getPointerType(RT->getPointeeType());
1534 }
Richard Smithf6d70302014-06-10 23:34:28 +00001535 QualType BaseT = getBaseElementType(T);
Akira Hatanakad62f2c82017-01-06 17:56:15 +00001536 if (T->isFunctionType())
1537 Align = getTypeInfoImpl(T.getTypePtr()).Align;
1538 else if (!BaseT->isIncompleteType()) {
John McCall33ddac02011-01-19 10:06:00 +00001539 // Adjust alignments of declarations with array type by the
1540 // large-array alignment on the target.
Rafael Espindola88572752013-08-07 18:08:19 +00001541 if (const ArrayType *arrayType = getAsArrayType(T)) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001542 unsigned MinWidth = Target->getLargeArrayMinWidth();
1543 if (!ForAlignof && MinWidth) {
Rafael Espindola88572752013-08-07 18:08:19 +00001544 if (isa<VariableArrayType>(arrayType))
1545 Align = std::max(Align, Target->getLargeArrayAlign());
1546 else if (isa<ConstantArrayType>(arrayType) &&
1547 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1548 Align = std::max(Align, Target->getLargeArrayAlign());
1549 }
John McCall33ddac02011-01-19 10:06:00 +00001550 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001551 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Roger Ferrer Ibanez3fa38a12017-03-08 14:00:44 +00001552 if (BaseT.getQualifiers().hasUnaligned())
1553 Align = Target->getCharWidth();
Eugene Zelenko7855e772018-04-03 00:11:50 +00001554 if (const auto *VD = dyn_cast<VarDecl>(D)) {
Ulrich Weigandb63f7792015-04-21 17:26:18 +00001555 if (VD->hasGlobalStorage() && !ForAlignof)
Ulrich Weigandfa806422013-05-06 16:23:57 +00001556 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1557 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001558 }
John McCall4e819612011-01-20 07:57:12 +00001559
1560 // Fields can be subject to extra alignment constraints, like if
1561 // the field is packed, the struct is packed, or the struct has a
1562 // a max-field-alignment constraint (#pragma pack). So calculate
1563 // the actual alignment of the field within the struct, and then
1564 // (as we're expected to) constrain that by the alignment of the type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00001565 if (const auto *Field = dyn_cast<FieldDecl>(VD)) {
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001566 const RecordDecl *Parent = Field->getParent();
1567 // We can only produce a sensible answer if the record is valid.
1568 if (!Parent->isInvalidDecl()) {
1569 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
John McCall4e819612011-01-20 07:57:12 +00001570
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001571 // Start with the record's overall alignment.
1572 unsigned FieldAlign = toBits(Layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001573
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001574 // Use the GCD of that and the offset within the record.
1575 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1576 if (Offset > 0) {
1577 // Alignment is always a power of 2, so the GCD will be a power of 2,
1578 // which means we get to do this crazy thing instead of Euclid's.
1579 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1580 if (LowBitOfOffset < FieldAlign)
1581 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1582 }
1583
1584 Align = std::min(Align, FieldAlign);
John McCall4e819612011-01-20 07:57:12 +00001585 }
Charles Davis3fc51072010-02-23 04:52:00 +00001586 }
Chris Lattner68061312009-01-24 21:53:27 +00001587 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001588
Ken Dyckcc56c542011-01-15 18:38:59 +00001589 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001590}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001591
John McCallf1249922012-08-21 04:10:00 +00001592// getTypeInfoDataSizeInChars - Return the size of a type, in
1593// chars. If the type is a record, its data size is returned. This is
1594// the size of the memcpy that's performed when assigning this type
1595// using a trivial copy/move assignment operator.
1596std::pair<CharUnits, CharUnits>
1597ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1598 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1599
1600 // In C++, objects can sometimes be allocated into the tail padding
1601 // of a base-class subobject. We decide whether that's possible
1602 // during class layout, so here we can just trust the layout results.
1603 if (getLangOpts().CPlusPlus) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001604 if (const auto *RT = T->getAs<RecordType>()) {
John McCallf1249922012-08-21 04:10:00 +00001605 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1606 sizeAndAlign.first = layout.getDataSize();
1607 }
1608 }
1609
1610 return sizeAndAlign;
1611}
1612
Richard Trieu04d2d942013-05-14 21:59:17 +00001613/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1614/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1615std::pair<CharUnits, CharUnits>
1616static getConstantArrayInfoInChars(const ASTContext &Context,
1617 const ConstantArrayType *CAT) {
1618 std::pair<CharUnits, CharUnits> EltInfo =
1619 Context.getTypeInfoInChars(CAT->getElementType());
1620 uint64_t Size = CAT->getSize().getZExtValue();
Richard Trieuc7509072013-05-14 23:41:50 +00001621 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1622 (uint64_t)(-1)/Size) &&
Richard Trieu04d2d942013-05-14 21:59:17 +00001623 "Overflow in array type char size evaluation");
1624 uint64_t Width = EltInfo.first.getQuantity() * Size;
1625 unsigned Align = EltInfo.second.getQuantity();
Warren Hunt5ae586a2013-11-01 23:59:41 +00001626 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1627 Context.getTargetInfo().getPointerWidth(0) == 64)
Rui Ueyama83aa9792016-01-14 21:00:27 +00001628 Width = llvm::alignTo(Width, Align);
Richard Trieu04d2d942013-05-14 21:59:17 +00001629 return std::make_pair(CharUnits::fromQuantity(Width),
1630 CharUnits::fromQuantity(Align));
1631}
1632
John McCall87fe5d52010-05-20 01:18:31 +00001633std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001634ASTContext::getTypeInfoInChars(const Type *T) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001635 if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
Richard Trieu04d2d942013-05-14 21:59:17 +00001636 return getConstantArrayInfoInChars(*this, CAT);
David Majnemer34b57492014-07-30 01:30:47 +00001637 TypeInfo Info = getTypeInfo(T);
1638 return std::make_pair(toCharUnitsFromBits(Info.Width),
1639 toCharUnitsFromBits(Info.Align));
John McCall87fe5d52010-05-20 01:18:31 +00001640}
1641
1642std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001643ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001644 return getTypeInfoInChars(T.getTypePtr());
1645}
1646
David Majnemer34b57492014-07-30 01:30:47 +00001647bool ASTContext::isAlignmentRequired(const Type *T) const {
1648 return getTypeInfo(T).AlignIsRequired;
1649}
Daniel Dunbarc6475872012-03-09 04:12:54 +00001650
David Majnemer34b57492014-07-30 01:30:47 +00001651bool ASTContext::isAlignmentRequired(QualType T) const {
1652 return isAlignmentRequired(T.getTypePtr());
1653}
1654
Richard Smithb2f0f052016-10-10 18:54:32 +00001655unsigned ASTContext::getTypeAlignIfKnown(QualType T) const {
1656 // An alignment on a typedef overrides anything else.
Eugene Zelenko7855e772018-04-03 00:11:50 +00001657 if (const auto *TT = T->getAs<TypedefType>())
Richard Smithb2f0f052016-10-10 18:54:32 +00001658 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1659 return Align;
1660
1661 // If we have an (array of) complete type, we're done.
1662 T = getBaseElementType(T);
1663 if (!T->isIncompleteType())
1664 return getTypeAlign(T);
1665
1666 // If we had an array type, its element type might be a typedef
1667 // type with an alignment attribute.
Eugene Zelenko7855e772018-04-03 00:11:50 +00001668 if (const auto *TT = T->getAs<TypedefType>())
Richard Smithb2f0f052016-10-10 18:54:32 +00001669 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1670 return Align;
1671
1672 // Otherwise, see if the declaration of the type had an attribute.
Eugene Zelenko7855e772018-04-03 00:11:50 +00001673 if (const auto *TT = T->getAs<TagType>())
Richard Smithb2f0f052016-10-10 18:54:32 +00001674 return TT->getDecl()->getMaxAlignment();
1675
1676 return 0;
1677}
1678
David Majnemer34b57492014-07-30 01:30:47 +00001679TypeInfo ASTContext::getTypeInfo(const Type *T) const {
David Majnemerf8d38642014-07-30 08:42:33 +00001680 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1681 if (I != MemoizedTypeInfo.end())
1682 return I->second;
1683
1684 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1685 TypeInfo TI = getTypeInfoImpl(T);
1686 MemoizedTypeInfo[T] = TI;
Rafael Espindolaeaa88c12014-07-30 04:40:23 +00001687 return TI;
Daniel Dunbarc6475872012-03-09 04:12:54 +00001688}
1689
1690/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1691/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001692///
1693/// FIXME: Pointers into different addr spaces could have different sizes and
1694/// alignment requirements: getPointerInfo should take an AddrSpace, this
1695/// should take a QualType, &c.
David Majnemer34b57492014-07-30 01:30:47 +00001696TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1697 uint64_t Width = 0;
1698 unsigned Align = 8;
1699 bool AlignIsRequired = false;
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001700 unsigned AS = 0;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001701 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001702#define TYPE(Class, Base)
1703#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001704#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001705#define DEPENDENT_TYPE(Class, Base) case Type::Class:
David Blaikieab277d62013-07-13 21:08:03 +00001706#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1707 case Type::Class: \
1708 assert(!T->isDependentType() && "should not see dependent types here"); \
1709 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001710#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001711 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001712
Chris Lattner355332d2007-07-13 22:27:08 +00001713 case Type::FunctionNoProto:
1714 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001715 // GCC extension: alignof(function) = 32 bits
1716 Width = 0;
1717 Align = 32;
1718 break;
1719
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001720 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001721 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001722 Width = 0;
1723 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1724 break;
1725
Steve Naroff5c131802007-08-30 01:06:46 +00001726 case Type::ConstantArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001727 const auto *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001728
David Majnemer34b57492014-07-30 01:30:47 +00001729 TypeInfo EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001730 uint64_t Size = CAT->getSize().getZExtValue();
David Majnemer34b57492014-07-30 01:30:47 +00001731 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
Daniel Dunbarc6475872012-03-09 04:12:54 +00001732 "Overflow in array type bit size evaluation");
David Majnemer34b57492014-07-30 01:30:47 +00001733 Width = EltInfo.Width * Size;
1734 Align = EltInfo.Align;
Warren Hunt5ae586a2013-11-01 23:59:41 +00001735 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1736 getTargetInfo().getPointerWidth(0) == 64)
Rui Ueyama83aa9792016-01-14 21:00:27 +00001737 Width = llvm::alignTo(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001738 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001739 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001740 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001741 case Type::Vector: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001742 const auto *VT = cast<VectorType>(T);
David Majnemer34b57492014-07-30 01:30:47 +00001743 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1744 Width = EltInfo.Width * VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001745 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001746 // If the alignment is not a power of 2, round up to the next power of 2.
1747 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001748 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001749 Align = llvm::NextPowerOf2(Align);
Rui Ueyama83aa9792016-01-14 21:00:27 +00001750 Width = llvm::alignTo(Width, Align);
Chris Lattner63d2b362009-10-22 05:17:15 +00001751 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001752 // Adjust the alignment based on the target max.
1753 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1754 if (TargetVectorAlign && TargetVectorAlign < Align)
1755 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001756 break;
1757 }
Chris Lattner647fb222007-07-18 18:26:58 +00001758
Chris Lattner7570e9c2008-03-08 08:52:55 +00001759 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001760 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001761 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001762 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001763 // GCC extension: alignof(void) = 8 bits.
1764 Width = 0;
1765 Align = 8;
1766 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001767 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001768 Width = Target->getBoolWidth();
1769 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001770 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001771 case BuiltinType::Char_S:
1772 case BuiltinType::Char_U:
1773 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001774 case BuiltinType::SChar:
Richard Smith3a8244d2018-05-01 05:02:45 +00001775 case BuiltinType::Char8:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001776 Width = Target->getCharWidth();
1777 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001778 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001779 case BuiltinType::WChar_S:
1780 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001781 Width = Target->getWCharWidth();
1782 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001783 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001784 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001785 Width = Target->getChar16Width();
1786 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001787 break;
1788 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001789 Width = Target->getChar32Width();
1790 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001791 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001792 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001793 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001794 Width = Target->getShortWidth();
1795 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001796 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001797 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001798 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001799 Width = Target->getIntWidth();
1800 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001801 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001802 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001803 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001804 Width = Target->getLongWidth();
1805 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001806 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001807 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001808 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001809 Width = Target->getLongLongWidth();
1810 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001811 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001812 case BuiltinType::Int128:
1813 case BuiltinType::UInt128:
1814 Width = 128;
1815 Align = 128; // int128_t is 128-bit aligned on all targets.
1816 break;
Leonard Chanf921d852018-06-04 16:07:52 +00001817 case BuiltinType::ShortAccum:
1818 case BuiltinType::UShortAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00001819 case BuiltinType::SatShortAccum:
1820 case BuiltinType::SatUShortAccum:
Leonard Chanf921d852018-06-04 16:07:52 +00001821 Width = Target->getShortAccumWidth();
1822 Align = Target->getShortAccumAlign();
1823 break;
1824 case BuiltinType::Accum:
1825 case BuiltinType::UAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00001826 case BuiltinType::SatAccum:
1827 case BuiltinType::SatUAccum:
Leonard Chanf921d852018-06-04 16:07:52 +00001828 Width = Target->getAccumWidth();
1829 Align = Target->getAccumAlign();
1830 break;
1831 case BuiltinType::LongAccum:
1832 case BuiltinType::ULongAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00001833 case BuiltinType::SatLongAccum:
1834 case BuiltinType::SatULongAccum:
Leonard Chanf921d852018-06-04 16:07:52 +00001835 Width = Target->getLongAccumWidth();
1836 Align = Target->getLongAccumAlign();
1837 break;
Leonard Chanab80f3c2018-06-14 14:53:51 +00001838 case BuiltinType::ShortFract:
1839 case BuiltinType::UShortFract:
1840 case BuiltinType::SatShortFract:
1841 case BuiltinType::SatUShortFract:
1842 Width = Target->getShortFractWidth();
1843 Align = Target->getShortFractAlign();
1844 break;
1845 case BuiltinType::Fract:
1846 case BuiltinType::UFract:
1847 case BuiltinType::SatFract:
1848 case BuiltinType::SatUFract:
1849 Width = Target->getFractWidth();
1850 Align = Target->getFractAlign();
1851 break;
1852 case BuiltinType::LongFract:
1853 case BuiltinType::ULongFract:
1854 case BuiltinType::SatLongFract:
1855 case BuiltinType::SatULongFract:
1856 Width = Target->getLongFractWidth();
1857 Align = Target->getLongFractAlign();
1858 break;
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00001859 case BuiltinType::Float16:
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001860 case BuiltinType::Half:
1861 Width = Target->getHalfWidth();
1862 Align = Target->getHalfAlign();
1863 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001864 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001865 Width = Target->getFloatWidth();
1866 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001867 break;
1868 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001869 Width = Target->getDoubleWidth();
1870 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001871 break;
1872 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001873 Width = Target->getLongDoubleWidth();
1874 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001875 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001876 case BuiltinType::Float128:
1877 Width = Target->getFloat128Width();
1878 Align = Target->getFloat128Align();
1879 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001880 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001881 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1882 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001883 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001884 case BuiltinType::ObjCId:
1885 case BuiltinType::ObjCClass:
1886 case BuiltinType::ObjCSel:
Fangrui Song6907ce22018-07-30 19:24:48 +00001887 Width = Target->getPointerWidth(0);
Douglas Gregore8bbc122011-09-02 00:18:52 +00001888 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001889 break;
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001890 case BuiltinType::OCLSampler:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001891 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001892 case BuiltinType::OCLClkEvent:
1893 case BuiltinType::OCLQueue:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001894 case BuiltinType::OCLReserveID:
Yaxun Liu99444cb2016-08-03 20:38:06 +00001895#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1896 case BuiltinType::Id:
1897#include "clang/Basic/OpenCLImageTypes.def"
Sven van Haastregt3bb7eaf2017-12-06 10:11:28 +00001898 AS = getTargetAddressSpace(
1899 Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T)));
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001900 Width = Target->getPointerWidth(AS);
1901 Align = Target->getPointerAlign(AS);
1902 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001903 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001904 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001905 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001906 Width = Target->getPointerWidth(0);
1907 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001908 break;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00001909 case Type::BlockPointer:
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001910 AS = getTargetAddressSpace(cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001911 Width = Target->getPointerWidth(AS);
1912 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001913 break;
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001914 case Type::LValueReference:
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00001915 case Type::RValueReference:
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001916 // alignof and sizeof should never enter this code path here, so we go
1917 // the pointer route.
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001918 AS = getTargetAddressSpace(cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001919 Width = Target->getPointerWidth(AS);
1920 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001921 break;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00001922 case Type::Pointer:
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001923 AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001924 Width = Target->getPointerWidth(AS);
1925 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001926 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001927 case Type::MemberPointer: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001928 const auto *MPT = cast<MemberPointerType>(T);
Erich Keane8a6b7402017-11-30 16:37:02 +00001929 CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT);
1930 Width = MPI.Width;
1931 Align = MPI.Align;
Anders Carlsson32440a02009-05-17 02:06:04 +00001932 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001933 }
Chris Lattner647fb222007-07-18 18:26:58 +00001934 case Type::Complex: {
1935 // Complex types have the same alignment as their elements, but twice the
1936 // size.
David Majnemer34b57492014-07-30 01:30:47 +00001937 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
1938 Width = EltInfo.Width * 2;
1939 Align = EltInfo.Align;
Chris Lattner647fb222007-07-18 18:26:58 +00001940 break;
1941 }
John McCall8b07ec22010-05-15 11:32:37 +00001942 case Type::ObjCObject:
1943 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Reid Kleckner0503a872013-12-05 01:23:43 +00001944 case Type::Adjusted:
Reid Kleckner8a365022013-06-24 17:51:48 +00001945 case Type::Decayed:
Reid Kleckner0503a872013-12-05 01:23:43 +00001946 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001947 case Type::ObjCInterface: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001948 const auto *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001949 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001950 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001951 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001952 break;
1953 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001954 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001955 case Type::Enum: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001956 const auto *TT = cast<TagType>(T);
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001957
1958 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001959 Width = 8;
1960 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001961 break;
1962 }
Mike Stump11289f42009-09-09 15:08:12 +00001963
Eugene Zelenko7855e772018-04-03 00:11:50 +00001964 if (const auto *ET = dyn_cast<EnumType>(TT)) {
David Majnemer475b25e2015-01-21 10:54:38 +00001965 const EnumDecl *ED = ET->getDecl();
1966 TypeInfo Info =
1967 getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType());
1968 if (unsigned AttrAlign = ED->getMaxAlignment()) {
1969 Info.Align = AttrAlign;
1970 Info.AlignIsRequired = true;
1971 }
1972 return Info;
1973 }
Chris Lattner8b23c252008-04-06 22:05:18 +00001974
Eugene Zelenko7855e772018-04-03 00:11:50 +00001975 const auto *RT = cast<RecordType>(TT);
David Majnemer5821ff72015-02-03 08:49:29 +00001976 const RecordDecl *RD = RT->getDecl();
1977 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
Ken Dyckb0fcc592011-02-11 01:54:29 +00001978 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001979 Align = toBits(Layout.getAlignment());
David Majnemer5821ff72015-02-03 08:49:29 +00001980 AlignIsRequired = RD->hasAttr<AlignedAttr>();
Chris Lattner49a953a2007-07-23 22:46:22 +00001981 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001982 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001983
Chris Lattner63d2b362009-10-22 05:17:15 +00001984 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001985 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1986 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001987
Richard Smith600b5262017-01-26 20:40:47 +00001988 case Type::Auto:
1989 case Type::DeducedTemplateSpecialization: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001990 const auto *A = cast<DeducedType>(T);
Richard Smith27d807c2013-04-30 13:56:41 +00001991 assert(!A->getDeducedType().isNull() &&
1992 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001993 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001994 }
1995
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001996 case Type::Paren:
1997 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1998
Manman Rene6be26c2016-09-13 17:25:08 +00001999 case Type::ObjCTypeParam:
2000 return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr());
2001
Douglas Gregoref462e62009-04-30 17:32:17 +00002002 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00002003 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
David Majnemer34b57492014-07-30 01:30:47 +00002004 TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00002005 // If the typedef has an aligned attribute on it, it overrides any computed
2006 // alignment we have. This violates the GCC documentation (which says that
2007 // attribute(aligned) can only round up) but matches its implementation.
David Majnemer34b57492014-07-30 01:30:47 +00002008 if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
Chris Lattner29eb47b2011-02-19 22:55:41 +00002009 Align = AttrAlign;
David Majnemer34b57492014-07-30 01:30:47 +00002010 AlignIsRequired = true;
David Majnemer37bffb62014-08-04 05:11:01 +00002011 } else {
David Majnemer34b57492014-07-30 01:30:47 +00002012 Align = Info.Align;
David Majnemer37bffb62014-08-04 05:11:01 +00002013 AlignIsRequired = Info.AlignIsRequired;
2014 }
David Majnemer34b57492014-07-30 01:30:47 +00002015 Width = Info.Width;
Douglas Gregordc572a32009-03-30 22:58:21 +00002016 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00002017 }
Douglas Gregoref462e62009-04-30 17:32:17 +00002018
Abramo Bagnara6150c882010-05-11 21:36:43 +00002019 case Type::Elaborated:
2020 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00002021
John McCall81904512011-01-06 01:58:22 +00002022 case Type::Attributed:
2023 return getTypeInfo(
2024 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
2025
Eli Friedman0dfb8892011-10-06 23:00:33 +00002026 case Type::Atomic: {
John McCalla8ec7eb2013-03-07 21:37:17 +00002027 // Start with the base type information.
David Majnemer34b57492014-07-30 01:30:47 +00002028 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
2029 Width = Info.Width;
2030 Align = Info.Align;
John McCalla8ec7eb2013-03-07 21:37:17 +00002031
JF Bastien801fca22018-05-09 03:51:12 +00002032 if (!Width) {
2033 // An otherwise zero-sized type should still generate an
2034 // atomic operation.
2035 Width = Target->getCharWidth();
2036 assert(Align);
2037 } else if (Width <= Target->getMaxAtomicPromoteWidth()) {
2038 // If the size of the type doesn't exceed the platform's max
2039 // atomic promotion width, make the size and alignment more
2040 // favorable to atomic operations:
2041
John McCalla8ec7eb2013-03-07 21:37:17 +00002042 // Round the size up to a power of 2.
2043 if (!llvm::isPowerOf2_64(Width))
2044 Width = llvm::NextPowerOf2(Width);
2045
2046 // Set the alignment equal to the size.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00002047 Align = static_cast<unsigned>(Width);
2048 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00002049 }
Xiuli Pan9c14e282016-01-09 12:53:17 +00002050 break;
2051
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002052 case Type::Pipe:
Anastasia Stulovab3398932017-06-05 11:27:03 +00002053 Width = Target->getPointerWidth(getTargetAddressSpace(LangAS::opencl_global));
2054 Align = Target->getPointerAlign(getTargetAddressSpace(LangAS::opencl_global));
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002055 break;
Douglas Gregoref462e62009-04-30 17:32:17 +00002056 }
Mike Stump11289f42009-09-09 15:08:12 +00002057
Eli Friedman4b72fdd2011-10-14 20:59:01 +00002058 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
David Majnemer34b57492014-07-30 01:30:47 +00002059 return TypeInfo(Width, Align, AlignIsRequired);
Chris Lattner983a8bb2007-07-13 22:13:22 +00002060}
2061
Momchil Velikov20208cc2018-07-30 17:48:23 +00002062unsigned ASTContext::getTypeUnadjustedAlign(const Type *T) const {
2063 UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(T);
2064 if (I != MemoizedUnadjustedAlign.end())
2065 return I->second;
2066
2067 unsigned UnadjustedAlign;
2068 if (const auto *RT = T->getAs<RecordType>()) {
2069 const RecordDecl *RD = RT->getDecl();
2070 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2071 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2072 } else if (const auto *ObjCI = T->getAs<ObjCInterfaceType>()) {
2073 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2074 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2075 } else {
2076 UnadjustedAlign = getTypeAlign(T);
2077 }
2078
2079 MemoizedUnadjustedAlign[T] = UnadjustedAlign;
2080 return UnadjustedAlign;
2081}
2082
Alexey Bataev00396512015-07-02 03:40:19 +00002083unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
2084 unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign();
2085 // Target ppc64 with QPX: simd default alignment for pointer to double is 32.
2086 if ((getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64 ||
2087 getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64le) &&
2088 getTargetInfo().getABI() == "elfv1-qpx" &&
2089 T->isSpecificBuiltinType(BuiltinType::Double))
2090 SimdAlign = 256;
2091 return SimdAlign;
2092}
2093
Ken Dyckcc56c542011-01-15 18:38:59 +00002094/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
2095CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
2096 return CharUnits::fromQuantity(BitSize / getCharWidth());
2097}
2098
Ken Dyckb0fcc592011-02-11 01:54:29 +00002099/// toBits - Convert a size in characters to a size in characters.
2100int64_t ASTContext::toBits(CharUnits CharSize) const {
2101 return CharSize.getQuantity() * getCharWidth();
2102}
2103
Ken Dyck8c89d592009-12-22 14:23:30 +00002104/// getTypeSizeInChars - Return the size of the specified type, in characters.
2105/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00002106CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00002107 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00002108}
Jay Foad39c79802011-01-12 09:06:06 +00002109CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00002110 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00002111}
2112
Fangrui Song6907ce22018-07-30 19:24:48 +00002113/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00002114/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00002115CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00002116 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00002117}
Jay Foad39c79802011-01-12 09:06:06 +00002118CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00002119 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00002120}
2121
Momchil Velikov20208cc2018-07-30 17:48:23 +00002122/// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a
2123/// type, in characters, before alignment adustments. This method does
2124/// not work on incomplete types.
2125CharUnits ASTContext::getTypeUnadjustedAlignInChars(QualType T) const {
2126 return toCharUnitsFromBits(getTypeUnadjustedAlign(T));
2127}
2128CharUnits ASTContext::getTypeUnadjustedAlignInChars(const Type *T) const {
2129 return toCharUnitsFromBits(getTypeUnadjustedAlign(T));
2130}
2131
Chris Lattnera3402cd2009-01-27 18:08:34 +00002132/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
2133/// type for the current target in bits. This can be different than the ABI
2134/// alignment in cases where it is beneficial for performance to overalign
2135/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00002136unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
David Majnemer34b57492014-07-30 01:30:47 +00002137 TypeInfo TI = getTypeInfo(T);
2138 unsigned ABIAlign = TI.Align;
Eli Friedman7ab09572009-05-25 21:27:19 +00002139
David Majnemere1544562015-04-24 01:25:05 +00002140 T = T->getBaseElementTypeUnsafe();
2141
2142 // The preferred alignment of member pointers is that of a pointer.
2143 if (T->isMemberPointerType())
2144 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
2145
Andrey Turetskiydb6655f2016-02-10 11:58:46 +00002146 if (!Target->allowsLargerPreferedTypeAlignment())
2147 return ABIAlign;
Robert Lyttoneaf6f362013-11-12 10:09:34 +00002148
Eli Friedman7ab09572009-05-25 21:27:19 +00002149 // Double and long long should be naturally aligned if possible.
Eugene Zelenko7855e772018-04-03 00:11:50 +00002150 if (const auto *CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00002151 T = CT->getElementType().getTypePtr();
Eugene Zelenko7855e772018-04-03 00:11:50 +00002152 if (const auto *ET = T->getAs<EnumType>())
David Majnemer475b25e2015-01-21 10:54:38 +00002153 T = ET->getDecl()->getIntegerType().getTypePtr();
Eli Friedman7ab09572009-05-25 21:27:19 +00002154 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00002155 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
2156 T->isSpecificBuiltinType(BuiltinType::ULongLong))
David Majnemer8b6bd572014-02-24 23:34:17 +00002157 // Don't increase the alignment if an alignment attribute was specified on a
2158 // typedef declaration.
David Majnemer34b57492014-07-30 01:30:47 +00002159 if (!TI.AlignIsRequired)
David Majnemer8b6bd572014-02-24 23:34:17 +00002160 return std::max(ABIAlign, (unsigned)getTypeSize(T));
Eli Friedman7ab09572009-05-25 21:27:19 +00002161
Chris Lattnera3402cd2009-01-27 18:08:34 +00002162 return ABIAlign;
2163}
2164
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00002165/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2166/// for __attribute__((aligned)) on this target, to be used if no alignment
2167/// value is specified.
Eugene Zelenkod4304d22015-11-04 21:37:17 +00002168unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const {
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00002169 return getTargetInfo().getDefaultAlignForAttributeAligned();
2170}
2171
Ulrich Weigandfa806422013-05-06 16:23:57 +00002172/// getAlignOfGlobalVar - Return the alignment in bits that should be given
2173/// to a global variable of the specified type.
2174unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
2175 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
2176}
2177
2178/// getAlignOfGlobalVarInChars - Return the alignment in characters that
2179/// should be given to a global variable of the specified type.
2180CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
2181 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
2182}
2183
David Majnemer08ef2ba2015-06-23 20:34:18 +00002184CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
2185 CharUnits Offset = CharUnits::Zero();
2186 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
2187 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2188 Offset += Layout->getBaseClassOffset(Base);
2189 Layout = &getASTRecordLayout(Base);
2190 }
2191 return Offset;
2192}
2193
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002194/// DeepCollectObjCIvars -
2195/// This routine first collects all declared, but not synthesized, ivars in
2196/// super class and then collects all ivars, including those synthesized for
2197/// current class. This routine is used for implementation of current class
2198/// when all ivars, declared and synthesized are known.
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002199void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
2200 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00002201 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002202 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2203 DeepCollectObjCIvars(SuperClass, false, Ivars);
2204 if (!leafClass) {
Aaron Ballman59abbd42014-03-13 21:09:43 +00002205 for (const auto *I : OI->ivars())
2206 Ivars.push_back(I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00002207 } else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002208 auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Fangrui Song6907ce22018-07-30 19:24:48 +00002209 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00002210 Iv= Iv->getNextIvar())
2211 Ivars.push_back(Iv);
2212 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00002213}
2214
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002215/// CollectInheritedProtocols - Collect all protocols in current class and
2216/// those inherited by it.
2217void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00002218 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002219 if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00002220 // We can use protocol_iterator here instead of
Fangrui Song6907ce22018-07-30 19:24:48 +00002221 // all_referenced_protocol_iterator since we are walking all categories.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002222 for (auto *Proto : OI->all_referenced_protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002223 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00002224 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002225
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002226 // Categories of this Interface.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00002227 for (const auto *Cat : OI->visible_categories())
2228 CollectInheritedProtocols(Cat, Protocols);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002229
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002230 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2231 while (SD) {
2232 CollectInheritedProtocols(SD, Protocols);
2233 SD = SD->getSuperClass();
2234 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00002235 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00002236 for (auto *Proto : OC->protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002237 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002238 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00002239 } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002240 // Insert the protocol.
2241 if (!Protocols.insert(
2242 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2243 return;
2244
2245 for (auto *Proto : OP->protocols())
2246 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002247 }
2248}
2249
Erich Keane8a6b7402017-11-30 16:37:02 +00002250static bool unionHasUniqueObjectRepresentations(const ASTContext &Context,
2251 const RecordDecl *RD) {
2252 assert(RD->isUnion() && "Must be union type");
2253 CharUnits UnionSize = Context.getTypeSizeInChars(RD->getTypeForDecl());
2254
2255 for (const auto *Field : RD->fields()) {
2256 if (!Context.hasUniqueObjectRepresentations(Field->getType()))
2257 return false;
2258 CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType());
2259 if (FieldSize != UnionSize)
2260 return false;
2261 }
Eric Fiselier12a9f342018-02-02 20:30:39 +00002262 return !RD->field_empty();
Erich Keane8a6b7402017-11-30 16:37:02 +00002263}
2264
Benjamin Kramer802e6252017-12-24 12:46:22 +00002265static bool isStructEmpty(QualType Ty) {
Erich Keane8a6b7402017-11-30 16:37:02 +00002266 const RecordDecl *RD = Ty->castAs<RecordType>()->getDecl();
2267
2268 if (!RD->field_empty())
2269 return false;
2270
2271 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD))
2272 return ClassDecl->isEmpty();
2273
2274 return true;
2275}
2276
2277static llvm::Optional<int64_t>
2278structHasUniqueObjectRepresentations(const ASTContext &Context,
2279 const RecordDecl *RD) {
2280 assert(!RD->isUnion() && "Must be struct/class type");
2281 const auto &Layout = Context.getASTRecordLayout(RD);
2282
2283 int64_t CurOffsetInBits = 0;
2284 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) {
2285 if (ClassDecl->isDynamicClass())
2286 return llvm::None;
2287
2288 SmallVector<std::pair<QualType, int64_t>, 4> Bases;
2289 for (const auto Base : ClassDecl->bases()) {
2290 // Empty types can be inherited from, and non-empty types can potentially
2291 // have tail padding, so just make sure there isn't an error.
2292 if (!isStructEmpty(Base.getType())) {
2293 llvm::Optional<int64_t> Size = structHasUniqueObjectRepresentations(
2294 Context, Base.getType()->getAs<RecordType>()->getDecl());
2295 if (!Size)
2296 return llvm::None;
2297 Bases.emplace_back(Base.getType(), Size.getValue());
2298 }
2299 }
2300
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +00002301 llvm::sort(
Erich Keane8a6b7402017-11-30 16:37:02 +00002302 Bases.begin(), Bases.end(), [&](const std::pair<QualType, int64_t> &L,
2303 const std::pair<QualType, int64_t> &R) {
2304 return Layout.getBaseClassOffset(L.first->getAsCXXRecordDecl()) <
2305 Layout.getBaseClassOffset(R.first->getAsCXXRecordDecl());
2306 });
2307
2308 for (const auto Base : Bases) {
2309 int64_t BaseOffset = Context.toBits(
2310 Layout.getBaseClassOffset(Base.first->getAsCXXRecordDecl()));
2311 int64_t BaseSize = Base.second;
2312 if (BaseOffset != CurOffsetInBits)
2313 return llvm::None;
2314 CurOffsetInBits = BaseOffset + BaseSize;
2315 }
2316 }
2317
2318 for (const auto *Field : RD->fields()) {
2319 if (!Field->getType()->isReferenceType() &&
2320 !Context.hasUniqueObjectRepresentations(Field->getType()))
2321 return llvm::None;
2322
2323 int64_t FieldSizeInBits =
2324 Context.toBits(Context.getTypeSizeInChars(Field->getType()));
2325 if (Field->isBitField()) {
2326 int64_t BitfieldSize = Field->getBitWidthValue(Context);
2327
2328 if (BitfieldSize > FieldSizeInBits)
2329 return llvm::None;
2330 FieldSizeInBits = BitfieldSize;
2331 }
2332
2333 int64_t FieldOffsetInBits = Context.getFieldOffset(Field);
2334
2335 if (FieldOffsetInBits != CurOffsetInBits)
2336 return llvm::None;
2337
2338 CurOffsetInBits = FieldSizeInBits + FieldOffsetInBits;
2339 }
2340
2341 return CurOffsetInBits;
2342}
2343
2344bool ASTContext::hasUniqueObjectRepresentations(QualType Ty) const {
2345 // C++17 [meta.unary.prop]:
2346 // The predicate condition for a template specialization
2347 // has_unique_object_representations<T> shall be
2348 // satisfied if and only if:
2349 // (9.1) - T is trivially copyable, and
2350 // (9.2) - any two objects of type T with the same value have the same
2351 // object representation, where two objects
2352 // of array or non-union class type are considered to have the same value
2353 // if their respective sequences of
2354 // direct subobjects have the same values, and two objects of union type
2355 // are considered to have the same
2356 // value if they have the same active member and the corresponding members
2357 // have the same value.
2358 // The set of scalar types for which this condition holds is
2359 // implementation-defined. [ Note: If a type has padding
2360 // bits, the condition does not hold; otherwise, the condition holds true
2361 // for unsigned integral types. -- end note ]
2362 assert(!Ty.isNull() && "Null QualType sent to unique object rep check");
2363
2364 // Arrays are unique only if their element type is unique.
2365 if (Ty->isArrayType())
2366 return hasUniqueObjectRepresentations(getBaseElementType(Ty));
2367
2368 // (9.1) - T is trivially copyable...
2369 if (!Ty.isTriviallyCopyableType(*this))
2370 return false;
2371
2372 // All integrals and enums are unique.
2373 if (Ty->isIntegralOrEnumerationType())
2374 return true;
2375
2376 // All other pointers are unique.
2377 if (Ty->isPointerType())
2378 return true;
2379
2380 if (Ty->isMemberPointerType()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002381 const auto *MPT = Ty->getAs<MemberPointerType>();
Erich Keane8a6b7402017-11-30 16:37:02 +00002382 return !ABI->getMemberPointerInfo(MPT).HasPadding;
2383 }
2384
2385 if (Ty->isRecordType()) {
2386 const RecordDecl *Record = Ty->getAs<RecordType>()->getDecl();
2387
Erich Keanebd2197c2017-12-12 16:02:06 +00002388 if (Record->isInvalidDecl())
2389 return false;
2390
Erich Keane8a6b7402017-11-30 16:37:02 +00002391 if (Record->isUnion())
2392 return unionHasUniqueObjectRepresentations(*this, Record);
2393
2394 Optional<int64_t> StructSize =
2395 structHasUniqueObjectRepresentations(*this, Record);
2396
2397 return StructSize &&
2398 StructSize.getValue() == static_cast<int64_t>(getTypeSize(Ty));
2399 }
2400
2401 // FIXME: More cases to handle here (list by rsmith):
2402 // vectors (careful about, eg, vector of 3 foo)
2403 // _Complex int and friends
2404 // _Atomic T
2405 // Obj-C block pointers
2406 // Obj-C object pointers
2407 // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t,
2408 // clk_event_t, queue_t, reserve_id_t)
2409 // There're also Obj-C class types and the Obj-C selector type, but I think it
2410 // makes sense for those to return false here.
2411
2412 return false;
2413}
2414
Jay Foad39c79802011-01-12 09:06:06 +00002415unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00002416 unsigned count = 0;
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00002417 // Count ivars declared in class extension.
Aaron Ballmanb4a53452014-03-13 21:57:01 +00002418 for (const auto *Ext : OI->known_extensions())
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002419 count += Ext->ivar_size();
Fangrui Song6907ce22018-07-30 19:24:48 +00002420
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00002421 // Count ivar defined in this class's implementation. This
2422 // includes synthesized ivars.
2423 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00002424 count += ImplDecl->ivar_size();
2425
Fariborz Jahanian7c809592009-06-04 01:19:09 +00002426 return count;
2427}
2428
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00002429bool ASTContext::isSentinelNullExpr(const Expr *E) {
2430 if (!E)
2431 return false;
2432
2433 // nullptr_t is always treated as null.
2434 if (E->getType()->isNullPtrType()) return true;
2435
2436 if (E->getType()->isAnyPointerType() &&
2437 E->IgnoreParenCasts()->isNullPointerConstant(*this,
2438 Expr::NPC_ValueDependentIsNull))
2439 return true;
2440
2441 // Unfortunately, __null has type 'int'.
2442 if (isa<GNUNullExpr>(E)) return true;
2443
2444 return false;
2445}
2446
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002447/// Get the implementation of ObjCInterfaceDecl, or nullptr if none
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002448/// exists.
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002449ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
2450 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2451 I = ObjCImpls.find(D);
2452 if (I != ObjCImpls.end())
2453 return cast<ObjCImplementationDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002454 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002455}
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002456
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002457/// Get the implementation of ObjCCategoryDecl, or nullptr if none
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002458/// exists.
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002459ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
2460 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2461 I = ObjCImpls.find(D);
2462 if (I != ObjCImpls.end())
2463 return cast<ObjCCategoryImplDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002464 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002465}
2466
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002467/// Set the implementation of ObjCInterfaceDecl.
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002468void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2469 ObjCImplementationDecl *ImplD) {
2470 assert(IFaceD && ImplD && "Passed null params");
2471 ObjCImpls[IFaceD] = ImplD;
2472}
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002473
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002474/// Set the implementation of ObjCCategoryDecl.
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002475void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
2476 ObjCCategoryImplDecl *ImplD) {
2477 assert(CatD && ImplD && "Passed null params");
2478 ObjCImpls[CatD] = ImplD;
2479}
2480
Chandler Carruth21c90602015-12-30 03:24:14 +00002481const ObjCMethodDecl *
2482ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const {
2483 return ObjCMethodRedecls.lookup(MD);
2484}
2485
2486void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
2487 const ObjCMethodDecl *Redecl) {
2488 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
2489 ObjCMethodRedecls[MD] = Redecl;
2490}
2491
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002492const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
2493 const NamedDecl *ND) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002494 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002495 return ID;
Eugene Zelenko7855e772018-04-03 00:11:50 +00002496 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002497 return CD->getClassInterface();
Eugene Zelenko7855e772018-04-03 00:11:50 +00002498 if (const auto *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002499 return IMD->getClassInterface();
2500
Craig Topper36250ad2014-05-12 05:36:57 +00002501 return nullptr;
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002502}
2503
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002504/// Get the copy initialization expression of VarDecl, or nullptr if
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002505/// none exists.
Akira Hatanaka9978da32018-08-10 15:09:24 +00002506ASTContext::BlockVarCopyInit
2507ASTContext::getBlockVarCopyInit(const VarDecl*VD) const {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002508 assert(VD && "Passed null params");
Fangrui Song6907ce22018-07-30 19:24:48 +00002509 assert(VD->hasAttr<BlocksAttr>() &&
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002510 "getBlockVarCopyInits - not __block var");
Akira Hatanaka9978da32018-08-10 15:09:24 +00002511 auto I = BlockVarCopyInits.find(VD);
2512 if (I != BlockVarCopyInits.end())
2513 return I->second;
2514 return {nullptr, false};
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002515}
2516
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002517/// Set the copy inialization expression of a block var decl.
Akira Hatanaka9978da32018-08-10 15:09:24 +00002518void ASTContext::setBlockVarCopyInit(const VarDecl*VD, Expr *CopyExpr,
2519 bool CanThrow) {
2520 assert(VD && CopyExpr && "Passed null params");
Fangrui Song6907ce22018-07-30 19:24:48 +00002521 assert(VD->hasAttr<BlocksAttr>() &&
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002522 "setBlockVarCopyInits - not __block var");
Akira Hatanaka9978da32018-08-10 15:09:24 +00002523 BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002524}
2525
John McCallbcd03502009-12-07 02:54:59 +00002526TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002527 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00002528 if (!DataSize)
2529 DataSize = TypeLoc::getFullDataSizeForType(T);
2530 else
2531 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00002532 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00002533
Eugene Zelenko7855e772018-04-03 00:11:50 +00002534 auto *TInfo =
John McCallbcd03502009-12-07 02:54:59 +00002535 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
2536 new (TInfo) TypeSourceInfo(T);
2537 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00002538}
2539
John McCallbcd03502009-12-07 02:54:59 +00002540TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002541 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00002542 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00002543 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00002544 return DI;
2545}
2546
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002547const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002548ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Craig Topper36250ad2014-05-12 05:36:57 +00002549 return getObjCLayout(D, nullptr);
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002550}
2551
2552const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002553ASTContext::getASTObjCImplementationLayout(
2554 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002555 return getObjCLayout(D->getClassInterface(), D);
2556}
2557
Chris Lattner983a8bb2007-07-13 22:13:22 +00002558//===----------------------------------------------------------------------===//
2559// Type creation/memoization methods
2560//===----------------------------------------------------------------------===//
2561
Jay Foad39c79802011-01-12 09:06:06 +00002562QualType
John McCall33ddac02011-01-19 10:06:00 +00002563ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2564 unsigned fastQuals = quals.getFastQualifiers();
2565 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00002566
2567 // Check if we've already instantiated this type.
2568 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002569 ExtQuals::Profile(ID, baseType, quals);
Craig Topper36250ad2014-05-12 05:36:57 +00002570 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002571 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2572 assert(eq->getQualifiers() == quals);
2573 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002574 }
2575
John McCall33ddac02011-01-19 10:06:00 +00002576 // If the base type is not canonical, make the appropriate canonical type.
2577 QualType canon;
2578 if (!baseType->isCanonicalUnqualified()) {
2579 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00002580 canonSplit.Quals.addConsistentQualifiers(quals);
2581 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002582
2583 // Re-find the insert position.
2584 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2585 }
2586
Eugene Zelenko7855e772018-04-03 00:11:50 +00002587 auto *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
John McCall33ddac02011-01-19 10:06:00 +00002588 ExtQualNodes.InsertNode(eq, insertPos);
2589 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002590}
2591
Alexander Richardson6d989432017-10-15 18:48:14 +00002592QualType ASTContext::getAddrSpaceQualType(QualType T,
2593 LangAS AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002594 QualType CanT = getCanonicalType(T);
2595 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00002596 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00002597
John McCall8ccfcb52009-09-24 19:53:00 +00002598 // If we are composing extended qualifiers together, merge together
2599 // into one ExtQuals node.
2600 QualifierCollector Quals;
2601 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002602
John McCall8ccfcb52009-09-24 19:53:00 +00002603 // If this type already has an address space specified, it cannot get
2604 // another one.
2605 assert(!Quals.hasAddressSpace() &&
2606 "Type cannot be in multiple addr spaces!");
2607 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00002608
John McCall8ccfcb52009-09-24 19:53:00 +00002609 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00002610}
2611
Andrew Gozillon572bbb02017-10-02 06:25:51 +00002612QualType ASTContext::removeAddrSpaceQualType(QualType T) const {
2613 // If we are composing extended qualifiers together, merge together
2614 // into one ExtQuals node.
2615 QualifierCollector Quals;
2616 const Type *TypeNode = Quals.strip(T);
2617
2618 // If the qualifier doesn't have an address space just return it.
2619 if (!Quals.hasAddressSpace())
2620 return T;
2621
2622 Quals.removeAddressSpace();
2623
2624 // Removal of the address space can mean there are no longer any
2625 // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts)
2626 // or required.
2627 if (Quals.hasNonFastQualifiers())
2628 return getExtQualType(TypeNode, Quals);
2629 else
2630 return QualType(TypeNode, Quals.getFastQualifiers());
2631}
2632
Chris Lattnerd60183d2009-02-18 22:53:11 +00002633QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002634 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002635 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00002636 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002637 return T;
Mike Stump11289f42009-09-09 15:08:12 +00002638
Eugene Zelenko7855e772018-04-03 00:11:50 +00002639 if (const auto *ptr = T->getAs<PointerType>()) {
John McCall53fa7142010-12-24 02:08:15 +00002640 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00002641 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00002642 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2643 return getPointerType(ResultType);
2644 }
2645 }
Mike Stump11289f42009-09-09 15:08:12 +00002646
John McCall8ccfcb52009-09-24 19:53:00 +00002647 // If we are composing extended qualifiers together, merge together
2648 // into one ExtQuals node.
2649 QualifierCollector Quals;
2650 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002651
John McCall8ccfcb52009-09-24 19:53:00 +00002652 // If this type already has an ObjCGC specified, it cannot get
2653 // another one.
2654 assert(!Quals.hasObjCGCAttr() &&
2655 "Type cannot have multiple ObjCGCs!");
2656 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00002657
John McCall8ccfcb52009-09-24 19:53:00 +00002658 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002659}
Chris Lattner983a8bb2007-07-13 22:13:22 +00002660
John McCall4f5019e2010-12-19 02:44:49 +00002661const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2662 FunctionType::ExtInfo Info) {
2663 if (T->getExtInfo() == Info)
2664 return T;
2665
2666 QualType Result;
Eugene Zelenko7855e772018-04-03 00:11:50 +00002667 if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
Alp Toker314cc812014-01-25 16:55:45 +00002668 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
John McCall4f5019e2010-12-19 02:44:49 +00002669 } else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002670 const auto *FPT = cast<FunctionProtoType>(T);
John McCall4f5019e2010-12-19 02:44:49 +00002671 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2672 EPI.ExtInfo = Info;
Alp Toker314cc812014-01-25 16:55:45 +00002673 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
John McCall4f5019e2010-12-19 02:44:49 +00002674 }
2675
2676 return cast<FunctionType>(Result.getTypePtr());
2677}
2678
Richard Smith2a7d4812013-05-04 07:00:32 +00002679void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2680 QualType ResultType) {
Richard Smith1fa5d642013-05-11 05:45:24 +00002681 FD = FD->getMostRecentDecl();
2682 while (true) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002683 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
Richard Smith2a7d4812013-05-04 07:00:32 +00002684 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Alp Toker9cacbab2014-01-20 20:26:09 +00002685 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
Richard Smith1fa5d642013-05-11 05:45:24 +00002686 if (FunctionDecl *Next = FD->getPreviousDecl())
2687 FD = Next;
2688 else
2689 break;
Richard Smith2a7d4812013-05-04 07:00:32 +00002690 }
Richard Smith1fa5d642013-05-11 05:45:24 +00002691 if (ASTMutationListener *L = getASTMutationListener())
2692 L->DeducedReturnType(FD, ResultType);
Richard Smith2a7d4812013-05-04 07:00:32 +00002693}
2694
Richard Smith0b3a4622014-11-13 20:01:57 +00002695/// Get a function type and produce the equivalent function type with the
2696/// specified exception specification. Type sugar that can be present on a
2697/// declaration of a function with an exception specification is permitted
2698/// and preserved. Other type sugar (for instance, typedefs) is not.
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002699QualType ASTContext::getFunctionTypeWithExceptionSpec(
2700 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) {
Richard Smith0b3a4622014-11-13 20:01:57 +00002701 // Might have some parens.
Eugene Zelenko7855e772018-04-03 00:11:50 +00002702 if (const auto *PT = dyn_cast<ParenType>(Orig))
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002703 return getParenType(
2704 getFunctionTypeWithExceptionSpec(PT->getInnerType(), ESI));
Richard Smith0b3a4622014-11-13 20:01:57 +00002705
2706 // Might have a calling-convention attribute.
Eugene Zelenko7855e772018-04-03 00:11:50 +00002707 if (const auto *AT = dyn_cast<AttributedType>(Orig))
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002708 return getAttributedType(
Richard Smith0b3a4622014-11-13 20:01:57 +00002709 AT->getAttrKind(),
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002710 getFunctionTypeWithExceptionSpec(AT->getModifiedType(), ESI),
2711 getFunctionTypeWithExceptionSpec(AT->getEquivalentType(), ESI));
Richard Smith0b3a4622014-11-13 20:01:57 +00002712
2713 // Anything else must be a function type. Rebuild it with the new exception
2714 // specification.
Eugene Zelenko7855e772018-04-03 00:11:50 +00002715 const auto *Proto = cast<FunctionProtoType>(Orig);
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002716 return getFunctionType(
Richard Smith0b3a4622014-11-13 20:01:57 +00002717 Proto->getReturnType(), Proto->getParamTypes(),
2718 Proto->getExtProtoInfo().withExceptionSpec(ESI));
2719}
2720
Richard Smithdfe85e22016-12-15 02:35:39 +00002721bool ASTContext::hasSameFunctionTypeIgnoringExceptionSpec(QualType T,
2722 QualType U) {
2723 return hasSameType(T, U) ||
Aaron Ballmanc351fba2017-12-04 20:27:34 +00002724 (getLangOpts().CPlusPlus17 &&
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002725 hasSameType(getFunctionTypeWithExceptionSpec(T, EST_None),
2726 getFunctionTypeWithExceptionSpec(U, EST_None)));
Richard Smithdfe85e22016-12-15 02:35:39 +00002727}
2728
Richard Smith0b3a4622014-11-13 20:01:57 +00002729void ASTContext::adjustExceptionSpec(
2730 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
2731 bool AsWritten) {
2732 // Update the type.
2733 QualType Updated =
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002734 getFunctionTypeWithExceptionSpec(FD->getType(), ESI);
Richard Smith0b3a4622014-11-13 20:01:57 +00002735 FD->setType(Updated);
2736
2737 if (!AsWritten)
2738 return;
2739
2740 // Update the type in the type source information too.
2741 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
2742 // If the type and the type-as-written differ, we may need to update
2743 // the type-as-written too.
2744 if (TSInfo->getType() != FD->getType())
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002745 Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI);
Richard Smith0b3a4622014-11-13 20:01:57 +00002746
2747 // FIXME: When we get proper type location information for exceptions,
2748 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
2749 // up the TypeSourceInfo;
2750 assert(TypeLoc::getFullDataSizeForType(Updated) ==
2751 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
2752 "TypeLoc size mismatch from updating exception specification");
2753 TSInfo->overrideType(Updated);
2754 }
2755}
2756
Chris Lattnerc6395932007-06-22 20:56:16 +00002757/// getComplexType - Return the uniqued reference to the type for a complex
2758/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00002759QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00002760 // Unique pointers, to guarantee there is only one pointer of a particular
2761 // structure.
2762 llvm::FoldingSetNodeID ID;
2763 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002764
Craig Topper36250ad2014-05-12 05:36:57 +00002765 void *InsertPos = nullptr;
Chris Lattnerc6395932007-06-22 20:56:16 +00002766 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2767 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002768
Chris Lattnerc6395932007-06-22 20:56:16 +00002769 // If the pointee type isn't canonical, this won't be a canonical type either,
2770 // so fill in the canonical type field.
2771 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002772 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002773 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002774
Chris Lattnerc6395932007-06-22 20:56:16 +00002775 // Get the new insert position for the node we care about.
2776 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002777 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00002778 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00002779 auto *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00002780 Types.push_back(New);
2781 ComplexTypes.InsertNode(New, InsertPos);
2782 return QualType(New, 0);
2783}
2784
Chris Lattner970e54e2006-11-12 00:37:36 +00002785/// getPointerType - Return the uniqued reference to the type for a pointer to
2786/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002787QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00002788 // Unique pointers, to guarantee there is only one pointer of a particular
2789 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002790 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00002791 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002792
Craig Topper36250ad2014-05-12 05:36:57 +00002793 void *InsertPos = nullptr;
Chris Lattner67521df2007-01-27 01:29:36 +00002794 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002795 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002796
Chris Lattner7ccecb92006-11-12 08:50:50 +00002797 // If the pointee type isn't canonical, this won't be a canonical type either,
2798 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002799 QualType Canonical;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002800 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002801 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002802
Bob Wilsonc8541f22013-03-15 17:12:43 +00002803 // Get the new insert position for the node we care about.
2804 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002805 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002806 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00002807 auto *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00002808 Types.push_back(New);
2809 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002810 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00002811}
2812
Reid Kleckner0503a872013-12-05 01:23:43 +00002813QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
2814 llvm::FoldingSetNodeID ID;
2815 AdjustedType::Profile(ID, Orig, New);
Craig Topper36250ad2014-05-12 05:36:57 +00002816 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002817 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2818 if (AT)
2819 return QualType(AT, 0);
2820
2821 QualType Canonical = getCanonicalType(New);
2822
2823 // Get the new insert position for the node we care about.
2824 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002825 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner0503a872013-12-05 01:23:43 +00002826
2827 AT = new (*this, TypeAlignment)
2828 AdjustedType(Type::Adjusted, Orig, New, Canonical);
2829 Types.push_back(AT);
2830 AdjustedTypes.InsertNode(AT, InsertPos);
2831 return QualType(AT, 0);
2832}
2833
Reid Kleckner8a365022013-06-24 17:51:48 +00002834QualType ASTContext::getDecayedType(QualType T) const {
2835 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2836
Reid Kleckner8a365022013-06-24 17:51:48 +00002837 QualType Decayed;
2838
2839 // C99 6.7.5.3p7:
2840 // A declaration of a parameter as "array of type" shall be
2841 // adjusted to "qualified pointer to type", where the type
2842 // qualifiers (if any) are those specified within the [ and ] of
2843 // the array type derivation.
2844 if (T->isArrayType())
2845 Decayed = getArrayDecayedType(T);
2846
2847 // C99 6.7.5.3p8:
2848 // A declaration of a parameter as "function returning type"
2849 // shall be adjusted to "pointer to function returning type", as
2850 // in 6.3.2.1.
2851 if (T->isFunctionType())
2852 Decayed = getPointerType(T);
2853
Reid Kleckner0503a872013-12-05 01:23:43 +00002854 llvm::FoldingSetNodeID ID;
2855 AdjustedType::Profile(ID, T, Decayed);
Craig Topper36250ad2014-05-12 05:36:57 +00002856 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002857 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2858 if (AT)
2859 return QualType(AT, 0);
2860
Reid Kleckner8a365022013-06-24 17:51:48 +00002861 QualType Canonical = getCanonicalType(Decayed);
2862
2863 // Get the new insert position for the node we care about.
Reid Kleckner0503a872013-12-05 01:23:43 +00002864 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002865 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner8a365022013-06-24 17:51:48 +00002866
Reid Kleckner0503a872013-12-05 01:23:43 +00002867 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2868 Types.push_back(AT);
2869 AdjustedTypes.InsertNode(AT, InsertPos);
2870 return QualType(AT, 0);
Reid Kleckner8a365022013-06-24 17:51:48 +00002871}
2872
Mike Stump11289f42009-09-09 15:08:12 +00002873/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00002874/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00002875QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00002876 assert(T->isFunctionType() && "block of function types only");
2877 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00002878 // structure.
2879 llvm::FoldingSetNodeID ID;
2880 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002881
Craig Topper36250ad2014-05-12 05:36:57 +00002882 void *InsertPos = nullptr;
Steve Naroffec33ed92008-08-27 16:04:49 +00002883 if (BlockPointerType *PT =
2884 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2885 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002886
2887 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00002888 // type either so fill in the canonical type field.
2889 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002890 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00002891 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002892
Steve Naroffec33ed92008-08-27 16:04:49 +00002893 // Get the new insert position for the node we care about.
2894 BlockPointerType *NewIP =
2895 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002896 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00002897 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00002898 auto *New = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00002899 Types.push_back(New);
2900 BlockPointerTypes.InsertNode(New, InsertPos);
2901 return QualType(New, 0);
2902}
2903
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002904/// getLValueReferenceType - Return the uniqued reference to the type for an
2905/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002906QualType
2907ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00002908 assert(getCanonicalType(T) != OverloadTy &&
Douglas Gregor291e8ee2011-05-21 22:16:50 +00002909 "Unresolved overloaded function type");
Fangrui Song6907ce22018-07-30 19:24:48 +00002910
Bill Wendling3708c182007-05-27 10:15:43 +00002911 // Unique pointers, to guarantee there is only one pointer of a particular
2912 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002913 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002914 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002915
Craig Topper36250ad2014-05-12 05:36:57 +00002916 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002917 if (LValueReferenceType *RT =
2918 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00002919 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002920
Eugene Zelenko7855e772018-04-03 00:11:50 +00002921 const auto *InnerRef = T->getAs<ReferenceType>();
John McCallfc93cf92009-10-22 22:37:11 +00002922
Bill Wendling3708c182007-05-27 10:15:43 +00002923 // If the referencee type isn't canonical, this won't be a canonical type
2924 // either, so fill in the canonical type field.
2925 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002926 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2927 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2928 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002929
Bill Wendling3708c182007-05-27 10:15:43 +00002930 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002931 LValueReferenceType *NewIP =
2932 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002933 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00002934 }
2935
Eugene Zelenko7855e772018-04-03 00:11:50 +00002936 auto *New = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2937 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002938 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002939 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00002940
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002941 return QualType(New, 0);
2942}
2943
2944/// getRValueReferenceType - Return the uniqued reference to the type for an
2945/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002946QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002947 // Unique pointers, to guarantee there is only one pointer of a particular
2948 // structure.
2949 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002950 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002951
Craig Topper36250ad2014-05-12 05:36:57 +00002952 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002953 if (RValueReferenceType *RT =
2954 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2955 return QualType(RT, 0);
2956
Eugene Zelenko7855e772018-04-03 00:11:50 +00002957 const auto *InnerRef = T->getAs<ReferenceType>();
John McCallfc93cf92009-10-22 22:37:11 +00002958
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002959 // If the referencee type isn't canonical, this won't be a canonical type
2960 // either, so fill in the canonical type field.
2961 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002962 if (InnerRef || !T.isCanonical()) {
2963 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2964 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002965
2966 // Get the new insert position for the node we care about.
2967 RValueReferenceType *NewIP =
2968 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002969 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002970 }
2971
Eugene Zelenko7855e772018-04-03 00:11:50 +00002972 auto *New = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002973 Types.push_back(New);
2974 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00002975 return QualType(New, 0);
2976}
2977
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002978/// getMemberPointerType - Return the uniqued reference to the type for a
2979/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00002980QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002981 // Unique pointers, to guarantee there is only one pointer of a particular
2982 // structure.
2983 llvm::FoldingSetNodeID ID;
2984 MemberPointerType::Profile(ID, T, Cls);
2985
Craig Topper36250ad2014-05-12 05:36:57 +00002986 void *InsertPos = nullptr;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002987 if (MemberPointerType *PT =
2988 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2989 return QualType(PT, 0);
2990
2991 // If the pointee or class type isn't canonical, this won't be a canonical
2992 // type either, so fill in the canonical type field.
2993 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00002994 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002995 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2996
2997 // Get the new insert position for the node we care about.
2998 MemberPointerType *NewIP =
2999 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003000 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00003001 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00003002 auto *New = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00003003 Types.push_back(New);
3004 MemberPointerTypes.InsertNode(New, InsertPos);
3005 return QualType(New, 0);
3006}
3007
Mike Stump11289f42009-09-09 15:08:12 +00003008/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00003009/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00003010QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00003011 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00003012 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00003013 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00003014 assert((EltTy->isDependentType() ||
3015 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00003016 "Constant array of VLAs is illegal!");
3017
Chris Lattnere2df3f92009-05-13 04:12:56 +00003018 // Convert the array size into a canonical width matching the pointer size for
3019 // the target.
3020 llvm::APInt ArySize(ArySizeIn);
Konstantin Zhuravlyov9c1e3102017-03-21 18:55:39 +00003021 ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth());
Mike Stump11289f42009-09-09 15:08:12 +00003022
Chris Lattner23b7eb62007-06-15 23:05:46 +00003023 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00003024 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00003025
Craig Topper36250ad2014-05-12 05:36:57 +00003026 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003027 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00003028 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003029 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003030
John McCall33ddac02011-01-19 10:06:00 +00003031 // If the element type isn't canonical or has qualifiers, this won't
3032 // be a canonical type either, so fill in the canonical type field.
3033 QualType Canon;
3034 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
3035 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00003036 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00003037 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00003038 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00003039
Chris Lattner36f8e652007-01-27 08:31:04 +00003040 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00003041 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00003042 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003043 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00003044 }
Mike Stump11289f42009-09-09 15:08:12 +00003045
Eugene Zelenko7855e772018-04-03 00:11:50 +00003046 auto *New = new (*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00003047 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00003048 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00003049 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003050 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00003051}
3052
John McCall06549462011-01-18 08:40:38 +00003053/// getVariableArrayDecayedType - Turns the given type, which may be
3054/// variably-modified, into the corresponding type with all the known
3055/// sizes replaced with [*].
3056QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
3057 // Vastly most common case.
3058 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003059
John McCall06549462011-01-18 08:40:38 +00003060 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003061
John McCall06549462011-01-18 08:40:38 +00003062 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00003063 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00003064 switch (ty->getTypeClass()) {
3065#define TYPE(Class, Base)
3066#define ABSTRACT_TYPE(Class, Base)
3067#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3068#include "clang/AST/TypeNodes.def"
3069 llvm_unreachable("didn't desugar past all non-canonical types?");
3070
3071 // These types should never be variably-modified.
3072 case Type::Builtin:
3073 case Type::Complex:
3074 case Type::Vector:
Erich Keanef702b022018-07-13 19:46:04 +00003075 case Type::DependentVector:
John McCall06549462011-01-18 08:40:38 +00003076 case Type::ExtVector:
3077 case Type::DependentSizedExtVector:
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003078 case Type::DependentAddressSpace:
John McCall06549462011-01-18 08:40:38 +00003079 case Type::ObjCObject:
3080 case Type::ObjCInterface:
3081 case Type::ObjCObjectPointer:
3082 case Type::Record:
3083 case Type::Enum:
3084 case Type::UnresolvedUsing:
3085 case Type::TypeOfExpr:
3086 case Type::TypeOf:
3087 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00003088 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00003089 case Type::DependentName:
3090 case Type::InjectedClassName:
3091 case Type::TemplateSpecialization:
3092 case Type::DependentTemplateSpecialization:
3093 case Type::TemplateTypeParm:
3094 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00003095 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00003096 case Type::DeducedTemplateSpecialization:
John McCall06549462011-01-18 08:40:38 +00003097 case Type::PackExpansion:
3098 llvm_unreachable("type should never be variably-modified");
3099
3100 // These types can be variably-modified but should never need to
3101 // further decay.
3102 case Type::FunctionNoProto:
3103 case Type::FunctionProto:
3104 case Type::BlockPointer:
3105 case Type::MemberPointer:
Xiuli Pan9c14e282016-01-09 12:53:17 +00003106 case Type::Pipe:
John McCall06549462011-01-18 08:40:38 +00003107 return type;
3108
3109 // These types can be variably-modified. All these modifications
3110 // preserve structure except as noted by comments.
3111 // TODO: if we ever care about optimizing VLAs, there are no-op
3112 // optimizations available here.
3113 case Type::Pointer:
3114 result = getPointerType(getVariableArrayDecayedType(
3115 cast<PointerType>(ty)->getPointeeType()));
3116 break;
3117
3118 case Type::LValueReference: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003119 const auto *lv = cast<LValueReferenceType>(ty);
John McCall06549462011-01-18 08:40:38 +00003120 result = getLValueReferenceType(
3121 getVariableArrayDecayedType(lv->getPointeeType()),
3122 lv->isSpelledAsLValue());
3123 break;
3124 }
3125
3126 case Type::RValueReference: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003127 const auto *lv = cast<RValueReferenceType>(ty);
John McCall06549462011-01-18 08:40:38 +00003128 result = getRValueReferenceType(
3129 getVariableArrayDecayedType(lv->getPointeeType()));
3130 break;
3131 }
3132
Eli Friedman0dfb8892011-10-06 23:00:33 +00003133 case Type::Atomic: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003134 const auto *at = cast<AtomicType>(ty);
Eli Friedman0dfb8892011-10-06 23:00:33 +00003135 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
3136 break;
3137 }
3138
John McCall06549462011-01-18 08:40:38 +00003139 case Type::ConstantArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003140 const auto *cat = cast<ConstantArrayType>(ty);
John McCall06549462011-01-18 08:40:38 +00003141 result = getConstantArrayType(
3142 getVariableArrayDecayedType(cat->getElementType()),
3143 cat->getSize(),
3144 cat->getSizeModifier(),
3145 cat->getIndexTypeCVRQualifiers());
3146 break;
3147 }
3148
3149 case Type::DependentSizedArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003150 const auto *dat = cast<DependentSizedArrayType>(ty);
John McCall06549462011-01-18 08:40:38 +00003151 result = getDependentSizedArrayType(
3152 getVariableArrayDecayedType(dat->getElementType()),
3153 dat->getSizeExpr(),
3154 dat->getSizeModifier(),
3155 dat->getIndexTypeCVRQualifiers(),
3156 dat->getBracketsRange());
3157 break;
3158 }
3159
3160 // Turn incomplete types into [*] types.
3161 case Type::IncompleteArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003162 const auto *iat = cast<IncompleteArrayType>(ty);
John McCall06549462011-01-18 08:40:38 +00003163 result = getVariableArrayType(
3164 getVariableArrayDecayedType(iat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00003165 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00003166 ArrayType::Normal,
3167 iat->getIndexTypeCVRQualifiers(),
3168 SourceRange());
3169 break;
3170 }
3171
3172 // Turn VLA types into [*] types.
3173 case Type::VariableArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003174 const auto *vat = cast<VariableArrayType>(ty);
John McCall06549462011-01-18 08:40:38 +00003175 result = getVariableArrayType(
3176 getVariableArrayDecayedType(vat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00003177 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00003178 ArrayType::Star,
3179 vat->getIndexTypeCVRQualifiers(),
3180 vat->getBracketsRange());
3181 break;
3182 }
3183 }
3184
3185 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00003186 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00003187}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003188
Steve Naroffcadebd02007-08-30 18:14:25 +00003189/// getVariableArrayType - Returns a non-unique reference to the type for a
3190/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00003191QualType ASTContext::getVariableArrayType(QualType EltTy,
3192 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00003193 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00003194 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00003195 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00003196 // Since we don't unique expressions, it isn't possible to unique VLA's
3197 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00003198 QualType Canon;
Fangrui Song6907ce22018-07-30 19:24:48 +00003199
John McCall33ddac02011-01-19 10:06:00 +00003200 // Be sure to pull qualifiers off the element type.
3201 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
3202 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00003203 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00003204 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00003205 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00003206 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003207
Eugene Zelenko7855e772018-04-03 00:11:50 +00003208 auto *New = new (*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00003209 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00003210
3211 VariableArrayTypes.push_back(New);
3212 Types.push_back(New);
3213 return QualType(New, 0);
3214}
3215
Douglas Gregor4619e432008-12-05 23:32:09 +00003216/// getDependentSizedArrayType - Returns a non-unique reference to
3217/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00003218/// type.
John McCall33ddac02011-01-19 10:06:00 +00003219QualType ASTContext::getDependentSizedArrayType(QualType elementType,
3220 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00003221 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00003222 unsigned elementTypeQuals,
3223 SourceRange brackets) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00003224 assert((!numElements || numElements->isTypeDependent() ||
John McCall33ddac02011-01-19 10:06:00 +00003225 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00003226 "Size must be type- or value-dependent!");
3227
John McCall33ddac02011-01-19 10:06:00 +00003228 // Dependently-sized array types that do not have a specified number
3229 // of elements will have their sizes deduced from a dependent
3230 // initializer. We do no canonicalization here at all, which is okay
3231 // because they can't be used in most locations.
3232 if (!numElements) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003233 auto *newType
John McCall33ddac02011-01-19 10:06:00 +00003234 = new (*this, TypeAlignment)
3235 DependentSizedArrayType(*this, elementType, QualType(),
3236 numElements, ASM, elementTypeQuals,
3237 brackets);
3238 Types.push_back(newType);
3239 return QualType(newType, 0);
3240 }
3241
3242 // Otherwise, we actually build a new type every time, but we
3243 // also build a canonical type.
3244
3245 SplitQualType canonElementType = getCanonicalType(elementType).split();
3246
Craig Topper36250ad2014-05-12 05:36:57 +00003247 void *insertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00003248 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00003249 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00003250 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00003251 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00003252
John McCall33ddac02011-01-19 10:06:00 +00003253 // Look for an existing type with these properties.
3254 DependentSizedArrayType *canonTy =
3255 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00003256
John McCall33ddac02011-01-19 10:06:00 +00003257 // If we don't have one, build one.
3258 if (!canonTy) {
3259 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00003260 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00003261 QualType(), numElements, ASM, elementTypeQuals,
3262 brackets);
3263 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
3264 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00003265 }
3266
John McCall33ddac02011-01-19 10:06:00 +00003267 // Apply qualifiers from the element type to the array.
3268 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00003269 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00003270
David Majnemer16a74702015-07-24 05:54:19 +00003271 // If we didn't need extra canonicalization for the element type or the size
3272 // expression, then just use that as our result.
3273 if (QualType(canonElementType.Ty, 0) == elementType &&
3274 canonTy->getSizeExpr() == numElements)
John McCall33ddac02011-01-19 10:06:00 +00003275 return canon;
3276
3277 // Otherwise, we need to build a type which follows the spelling
3278 // of the element type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00003279 auto *sugaredType
John McCall33ddac02011-01-19 10:06:00 +00003280 = new (*this, TypeAlignment)
3281 DependentSizedArrayType(*this, elementType, canon, numElements,
3282 ASM, elementTypeQuals, brackets);
3283 Types.push_back(sugaredType);
3284 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00003285}
3286
John McCall33ddac02011-01-19 10:06:00 +00003287QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00003288 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00003289 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00003290 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00003291 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00003292
Craig Topper36250ad2014-05-12 05:36:57 +00003293 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00003294 if (IncompleteArrayType *iat =
3295 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
3296 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00003297
3298 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00003299 // either, so fill in the canonical type field. We also have to pull
3300 // qualifiers off the element type.
3301 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00003302
John McCall33ddac02011-01-19 10:06:00 +00003303 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
3304 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00003305 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00003306 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00003307 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00003308
3309 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00003310 IncompleteArrayType *existing =
3311 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
3312 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00003313 }
Eli Friedmanbd258282008-02-15 18:16:39 +00003314
Eugene Zelenko7855e772018-04-03 00:11:50 +00003315 auto *newType = new (*this, TypeAlignment)
John McCall33ddac02011-01-19 10:06:00 +00003316 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00003317
John McCall33ddac02011-01-19 10:06:00 +00003318 IncompleteArrayTypes.InsertNode(newType, insertPos);
3319 Types.push_back(newType);
3320 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00003321}
3322
Steve Naroff91fcddb2007-07-18 18:00:27 +00003323/// getVectorType - Return the unique reference to a vector type of
3324/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00003325QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00003326 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00003327 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00003328
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003329 // Check if we've already instantiated a vector of this type.
3330 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00003331 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00003332
Craig Topper36250ad2014-05-12 05:36:57 +00003333 void *InsertPos = nullptr;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003334 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3335 return QualType(VTP, 0);
3336
3337 // If the element type isn't canonical, this won't be a canonical type either,
3338 // so fill in the canonical type field.
3339 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00003340 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00003341 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00003342
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003343 // Get the new insert position for the node we care about.
3344 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003345 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003346 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00003347 auto *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00003348 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003349 VectorTypes.InsertNode(New, InsertPos);
3350 Types.push_back(New);
3351 return QualType(New, 0);
3352}
3353
Erich Keanef702b022018-07-13 19:46:04 +00003354QualType
3355ASTContext::getDependentVectorType(QualType VecType, Expr *SizeExpr,
3356 SourceLocation AttrLoc,
3357 VectorType::VectorKind VecKind) const {
3358 llvm::FoldingSetNodeID ID;
3359 DependentVectorType::Profile(ID, *this, getCanonicalType(VecType), SizeExpr,
3360 VecKind);
3361 void *InsertPos = nullptr;
3362 DependentVectorType *Canon =
3363 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3364 DependentVectorType *New;
3365
3366 if (Canon) {
3367 New = new (*this, TypeAlignment) DependentVectorType(
3368 *this, VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind);
3369 } else {
3370 QualType CanonVecTy = getCanonicalType(VecType);
3371 if (CanonVecTy == VecType) {
3372 New = new (*this, TypeAlignment) DependentVectorType(
3373 *this, VecType, QualType(), SizeExpr, AttrLoc, VecKind);
3374
3375 DependentVectorType *CanonCheck =
3376 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3377 assert(!CanonCheck &&
3378 "Dependent-sized vector_size canonical type broken");
3379 (void)CanonCheck;
3380 DependentVectorTypes.InsertNode(New, InsertPos);
3381 } else {
3382 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
3383 SourceLocation());
3384 New = new (*this, TypeAlignment) DependentVectorType(
3385 *this, VecType, Canon, SizeExpr, AttrLoc, VecKind);
3386 }
3387 }
3388
3389 Types.push_back(New);
3390 return QualType(New, 0);
3391}
3392
Nate Begemance4d7fc2008-04-18 23:10:10 +00003393/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00003394/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00003395QualType
3396ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00003397 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00003398
Steve Naroff91fcddb2007-07-18 18:00:27 +00003399 // Check if we've already instantiated a vector of this type.
3400 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00003401 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00003402 VectorType::GenericVector);
Craig Topper36250ad2014-05-12 05:36:57 +00003403 void *InsertPos = nullptr;
Steve Naroff91fcddb2007-07-18 18:00:27 +00003404 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3405 return QualType(VTP, 0);
3406
3407 // If the element type isn't canonical, this won't be a canonical type either,
3408 // so fill in the canonical type field.
3409 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00003410 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00003411 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00003412
Steve Naroff91fcddb2007-07-18 18:00:27 +00003413 // Get the new insert position for the node we care about.
3414 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003415 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00003416 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00003417 auto *New = new (*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00003418 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00003419 VectorTypes.InsertNode(New, InsertPos);
3420 Types.push_back(New);
3421 return QualType(New, 0);
3422}
3423
Jay Foad39c79802011-01-12 09:06:06 +00003424QualType
3425ASTContext::getDependentSizedExtVectorType(QualType vecType,
3426 Expr *SizeExpr,
3427 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00003428 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00003429 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00003430 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003431
Craig Topper36250ad2014-05-12 05:36:57 +00003432 void *InsertPos = nullptr;
Douglas Gregor352169a2009-07-31 03:54:25 +00003433 DependentSizedExtVectorType *Canon
3434 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3435 DependentSizedExtVectorType *New;
3436 if (Canon) {
3437 // We already have a canonical version of this array type; use it as
3438 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00003439 New = new (*this, TypeAlignment)
3440 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
3441 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00003442 } else {
3443 QualType CanonVecTy = getCanonicalType(vecType);
3444 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00003445 New = new (*this, TypeAlignment)
3446 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
3447 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003448
3449 DependentSizedExtVectorType *CanonCheck
3450 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3451 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
3452 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00003453 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
3454 } else {
3455 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
3456 SourceLocation());
Fangrui Song6907ce22018-07-30 19:24:48 +00003457 New = new (*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00003458 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00003459 }
3460 }
Mike Stump11289f42009-09-09 15:08:12 +00003461
Douglas Gregor758a8692009-06-17 21:51:59 +00003462 Types.push_back(New);
3463 return QualType(New, 0);
3464}
3465
Fangrui Song6907ce22018-07-30 19:24:48 +00003466QualType ASTContext::getDependentAddressSpaceType(QualType PointeeType,
3467 Expr *AddrSpaceExpr,
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003468 SourceLocation AttrLoc) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00003469 assert(AddrSpaceExpr->isInstantiationDependent());
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003470
3471 QualType canonPointeeType = getCanonicalType(PointeeType);
3472
3473 void *insertPos = nullptr;
3474 llvm::FoldingSetNodeID ID;
3475 DependentAddressSpaceType::Profile(ID, *this, canonPointeeType,
3476 AddrSpaceExpr);
3477
3478 DependentAddressSpaceType *canonTy =
3479 DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos);
3480
3481 if (!canonTy) {
3482 canonTy = new (*this, TypeAlignment)
Fangrui Song6907ce22018-07-30 19:24:48 +00003483 DependentAddressSpaceType(*this, canonPointeeType,
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003484 QualType(), AddrSpaceExpr, AttrLoc);
3485 DependentAddressSpaceTypes.InsertNode(canonTy, insertPos);
3486 Types.push_back(canonTy);
3487 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003488
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003489 if (canonPointeeType == PointeeType &&
3490 canonTy->getAddrSpaceExpr() == AddrSpaceExpr)
Fangrui Song6907ce22018-07-30 19:24:48 +00003491 return QualType(canonTy, 0);
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003492
Eugene Zelenko7855e772018-04-03 00:11:50 +00003493 auto *sugaredType
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003494 = new (*this, TypeAlignment)
Fangrui Song6907ce22018-07-30 19:24:48 +00003495 DependentAddressSpaceType(*this, PointeeType, QualType(canonTy, 0),
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003496 AddrSpaceExpr, AttrLoc);
3497 Types.push_back(sugaredType);
Fangrui Song6907ce22018-07-30 19:24:48 +00003498 return QualType(sugaredType, 0);
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003499}
3500
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003501/// Determine whether \p T is canonical as the result type of a function.
John McCall18afab72016-03-01 00:49:02 +00003502static bool isCanonicalResultType(QualType T) {
3503 return T.isCanonical() &&
3504 (T.getObjCLifetime() == Qualifiers::OCL_None ||
3505 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
3506}
3507
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003508/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Jay Foad39c79802011-01-12 09:06:06 +00003509QualType
3510ASTContext::getFunctionNoProtoType(QualType ResultTy,
3511 const FunctionType::ExtInfo &Info) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003512 // Unique functions, to guarantee there is only one function of a particular
3513 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00003514 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00003515 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00003516
Craig Topper36250ad2014-05-12 05:36:57 +00003517 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003518 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003519 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003520 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003521
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003522 QualType Canonical;
John McCall18afab72016-03-01 00:49:02 +00003523 if (!isCanonicalResultType(ResultTy)) {
3524 Canonical =
3525 getFunctionNoProtoType(getCanonicalFunctionResultType(ResultTy), Info);
Mike Stump11289f42009-09-09 15:08:12 +00003526
Chris Lattner47955de2007-01-27 08:37:20 +00003527 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003528 FunctionNoProtoType *NewIP =
3529 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003530 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00003531 }
Mike Stump11289f42009-09-09 15:08:12 +00003532
Eugene Zelenko7855e772018-04-03 00:11:50 +00003533 auto *New = new (*this, TypeAlignment)
John McCall18afab72016-03-01 00:49:02 +00003534 FunctionNoProtoType(ResultTy, Canonical, Info);
Chris Lattner47955de2007-01-27 08:37:20 +00003535 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003536 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003537 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003538}
3539
Douglas Gregora602a152015-10-01 20:20:47 +00003540CanQualType
3541ASTContext::getCanonicalFunctionResultType(QualType ResultType) const {
3542 CanQualType CanResultType = getCanonicalType(ResultType);
3543
3544 // Canonical result types do not have ARC lifetime qualifiers.
3545 if (CanResultType.getQualifiers().hasObjCLifetime()) {
3546 Qualifiers Qs = CanResultType.getQualifiers();
3547 Qs.removeObjCLifetime();
3548 return CanQualType::CreateUnsafe(
3549 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
3550 }
3551
3552 return CanResultType;
3553}
3554
Richard Smith3c4f8d22016-10-16 17:54:23 +00003555static bool isCanonicalExceptionSpecification(
3556 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
3557 if (ESI.Type == EST_None)
3558 return true;
3559 if (!NoexceptInType)
3560 return false;
3561
3562 // C++17 onwards: exception specification is part of the type, as a simple
3563 // boolean "can this function type throw".
3564 if (ESI.Type == EST_BasicNoexcept)
3565 return true;
3566
Richard Smitheaf11ad2018-05-03 03:58:32 +00003567 // A noexcept(expr) specification is (possibly) canonical if expr is
3568 // value-dependent.
3569 if (ESI.Type == EST_DependentNoexcept)
3570 return true;
3571
Richard Smith3c4f8d22016-10-16 17:54:23 +00003572 // A dynamic exception specification is canonical if it only contains pack
Richard Smith2a2cda52016-10-18 19:29:18 +00003573 // expansions (so we can't tell whether it's non-throwing) and all its
3574 // contained types are canonical.
Richard Smith3c4f8d22016-10-16 17:54:23 +00003575 if (ESI.Type == EST_Dynamic) {
Richard Smithfda59e52016-10-26 01:05:54 +00003576 bool AnyPackExpansions = false;
3577 for (QualType ET : ESI.Exceptions) {
3578 if (!ET.isCanonical())
Richard Smith3c4f8d22016-10-16 17:54:23 +00003579 return false;
Richard Smithfda59e52016-10-26 01:05:54 +00003580 if (ET->getAs<PackExpansionType>())
3581 AnyPackExpansions = true;
3582 }
3583 return AnyPackExpansions;
Richard Smith3c4f8d22016-10-16 17:54:23 +00003584 }
3585
Richard Smith3c4f8d22016-10-16 17:54:23 +00003586 return false;
3587}
3588
Richard Smith304b1242016-10-18 20:13:25 +00003589QualType ASTContext::getFunctionTypeInternal(
3590 QualType ResultTy, ArrayRef<QualType> ArgArray,
3591 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
Jordan Rose5c382722013-03-08 21:51:21 +00003592 size_t NumArgs = ArgArray.size();
3593
Richard Smith2a2cda52016-10-18 19:29:18 +00003594 // Unique functions, to guarantee there is only one function of a particular
3595 // structure.
3596 llvm::FoldingSetNodeID ID;
3597 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
3598 *this, true);
Richard Smith3c4f8d22016-10-16 17:54:23 +00003599
Richard Smith2a2cda52016-10-18 19:29:18 +00003600 QualType Canonical;
3601 bool Unique = false;
3602
3603 void *InsertPos = nullptr;
3604 if (FunctionProtoType *FPT =
3605 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
3606 QualType Existing = QualType(FPT, 0);
3607
3608 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
3609 // it so long as our exception specification doesn't contain a dependent
Richard Smith304b1242016-10-18 20:13:25 +00003610 // noexcept expression, or we're just looking for a canonical type.
3611 // Otherwise, we're going to need to create a type
Richard Smith2a2cda52016-10-18 19:29:18 +00003612 // sugar node to hold the concrete expression.
Richard Smitheaf11ad2018-05-03 03:58:32 +00003613 if (OnlyWantCanonical || !isComputedNoexcept(EPI.ExceptionSpec.Type) ||
Richard Smith2a2cda52016-10-18 19:29:18 +00003614 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
3615 return Existing;
3616
3617 // We need a new type sugar node for this one, to hold the new noexcept
3618 // expression. We do no canonicalization here, but that's OK since we don't
3619 // expect to see the same noexcept expression much more than once.
3620 Canonical = getCanonicalType(Existing);
3621 Unique = true;
3622 }
3623
Aaron Ballmanc351fba2017-12-04 20:27:34 +00003624 bool NoexceptInType = getLangOpts().CPlusPlus17;
Richard Smith3c4f8d22016-10-16 17:54:23 +00003625 bool IsCanonicalExceptionSpec =
3626 isCanonicalExceptionSpecification(EPI.ExceptionSpec, NoexceptInType);
3627
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003628 // Determine whether the type being created is already canonical or not.
Richard Smith2a2cda52016-10-18 19:29:18 +00003629 bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
Richard Smith3c4f8d22016-10-16 17:54:23 +00003630 isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003631 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003632 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003633 isCanonical = false;
3634
Richard Smith304b1242016-10-18 20:13:25 +00003635 if (OnlyWantCanonical)
3636 assert(isCanonical &&
3637 "given non-canonical parameters constructing canonical type");
3638
Richard Smith2a2cda52016-10-18 19:29:18 +00003639 // If this type isn't canonical, get the canonical version of it if we don't
3640 // already have it. The exception spec is only partially part of the
3641 // canonical type, and only in C++17 onwards.
3642 if (!isCanonical && Canonical.isNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003643 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003644 CanonicalArgs.reserve(NumArgs);
3645 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003646 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003647
Benjamin Kramer3f515cd2016-10-26 12:51:45 +00003648 llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
John McCalldb40c7f2010-12-14 08:05:40 +00003649 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00003650 CanonicalEPI.HasTrailingReturn = false;
Richard Smith3c4f8d22016-10-16 17:54:23 +00003651
3652 if (IsCanonicalExceptionSpec) {
3653 // Exception spec is already OK.
3654 } else if (NoexceptInType) {
3655 switch (EPI.ExceptionSpec.Type) {
3656 case EST_Unparsed: case EST_Unevaluated: case EST_Uninstantiated:
3657 // We don't know yet. It shouldn't matter what we pick here; no-one
3658 // should ever look at this.
3659 LLVM_FALLTHROUGH;
Richard Smitheaf11ad2018-05-03 03:58:32 +00003660 case EST_None: case EST_MSAny: case EST_NoexceptFalse:
Richard Smith3c4f8d22016-10-16 17:54:23 +00003661 CanonicalEPI.ExceptionSpec.Type = EST_None;
3662 break;
3663
Richard Smith2a2cda52016-10-18 19:29:18 +00003664 // A dynamic exception specification is almost always "not noexcept",
3665 // with the exception that a pack expansion might expand to no types.
3666 case EST_Dynamic: {
3667 bool AnyPacks = false;
3668 for (QualType ET : EPI.ExceptionSpec.Exceptions) {
3669 if (ET->getAs<PackExpansionType>())
3670 AnyPacks = true;
3671 ExceptionTypeStorage.push_back(getCanonicalType(ET));
3672 }
3673 if (!AnyPacks)
3674 CanonicalEPI.ExceptionSpec.Type = EST_None;
3675 else {
3676 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
3677 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
3678 }
3679 break;
3680 }
3681
Richard Smitheaf11ad2018-05-03 03:58:32 +00003682 case EST_DynamicNone: case EST_BasicNoexcept: case EST_NoexceptTrue:
Richard Smith3c4f8d22016-10-16 17:54:23 +00003683 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
3684 break;
3685
Richard Smitheaf11ad2018-05-03 03:58:32 +00003686 case EST_DependentNoexcept:
3687 llvm_unreachable("dependent noexcept is already canonical");
Richard Smith3c4f8d22016-10-16 17:54:23 +00003688 }
Richard Smith3c4f8d22016-10-16 17:54:23 +00003689 } else {
3690 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
3691 }
John McCalldb40c7f2010-12-14 08:05:40 +00003692
Douglas Gregora602a152015-10-01 20:20:47 +00003693 // Adjust the canonical function result type.
3694 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
Richard Smith304b1242016-10-18 20:13:25 +00003695 Canonical =
3696 getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003697
Chris Lattnerfd4de792007-01-27 01:15:32 +00003698 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003699 FunctionProtoType *NewIP =
3700 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003701 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003702 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003703
John McCall31168b02011-06-15 23:02:42 +00003704 // FunctionProtoType objects are allocated with extra bytes after
3705 // them for three variable size arrays at the end:
3706 // - parameter types
3707 // - exception types
John McCall18afab72016-03-01 00:49:02 +00003708 // - extended parameter information
John McCall31168b02011-06-15 23:02:42 +00003709 // Instead of the exception types, there could be a noexcept
Richard Smithd3b5c9082012-07-27 04:22:15 +00003710 // expression, or information used to resolve the exception
3711 // specification.
Richard Smitheaf11ad2018-05-03 03:58:32 +00003712 size_t Size =
3713 sizeof(FunctionProtoType) + NumArgs * sizeof(QualType) +
3714 FunctionProtoType::getExceptionSpecSize(
3715 EPI.ExceptionSpec.Type, EPI.ExceptionSpec.Exceptions.size());
John McCall18afab72016-03-01 00:49:02 +00003716
3717 // Put the ExtParameterInfos last. If all were equal, it would make
3718 // more sense to put these before the exception specification, because
3719 // it's much easier to skip past them compared to the elaborate switch
3720 // required to skip the exception specification. However, all is not
3721 // equal; ExtParameterInfos are used to model very uncommon features,
3722 // and it's better not to burden the more common paths.
3723 if (EPI.ExtParameterInfos) {
3724 Size += NumArgs * sizeof(FunctionProtoType::ExtParameterInfo);
3725 }
John McCall31168b02011-06-15 23:02:42 +00003726
Eugene Zelenko7855e772018-04-03 00:11:50 +00003727 auto *FTP = (FunctionProtoType *) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00003728 FunctionProtoType::ExtProtoInfo newEPI = EPI;
Jordan Rose5c382722013-03-08 21:51:21 +00003729 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003730 Types.push_back(FTP);
Richard Smith2a2cda52016-10-18 19:29:18 +00003731 if (!Unique)
3732 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003733 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003734}
Chris Lattneref51c202006-11-10 07:17:23 +00003735
Joey Goulye3c85de2016-12-01 11:30:49 +00003736QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
Xiuli Pan9c14e282016-01-09 12:53:17 +00003737 llvm::FoldingSetNodeID ID;
Joey Goulye3c85de2016-12-01 11:30:49 +00003738 PipeType::Profile(ID, T, ReadOnly);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003739
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00003740 void *InsertPos = nullptr;
Joey Goulye3c85de2016-12-01 11:30:49 +00003741 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
Xiuli Pan9c14e282016-01-09 12:53:17 +00003742 return QualType(PT, 0);
3743
3744 // If the pipe element type isn't canonical, this won't be a canonical type
3745 // either, so fill in the canonical type field.
3746 QualType Canonical;
3747 if (!T.isCanonical()) {
Joey Goulye3c85de2016-12-01 11:30:49 +00003748 Canonical = getPipeType(getCanonicalType(T), ReadOnly);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003749
3750 // Get the new insert position for the node we care about.
Joey Goulye3c85de2016-12-01 11:30:49 +00003751 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003752 assert(!NewIP && "Shouldn't be in the map!");
3753 (void)NewIP;
3754 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00003755 auto *New = new (*this, TypeAlignment) PipeType(T, Canonical, ReadOnly);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003756 Types.push_back(New);
Joey Goulye3c85de2016-12-01 11:30:49 +00003757 PipeTypes.InsertNode(New, InsertPos);
Joey Gouly5788b782016-11-18 14:10:54 +00003758 return QualType(New, 0);
3759}
3760
Anastasia Stulova59055b92018-05-09 13:23:26 +00003761QualType ASTContext::adjustStringLiteralBaseType(QualType Ty) const {
3762 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
3763 return LangOpts.OpenCL ? getAddrSpaceQualType(Ty, LangAS::opencl_constant)
3764 : Ty;
3765}
3766
Joey Goulye3c85de2016-12-01 11:30:49 +00003767QualType ASTContext::getReadPipeType(QualType T) const {
3768 return getPipeType(T, true);
3769}
3770
Joey Gouly5788b782016-11-18 14:10:54 +00003771QualType ASTContext::getWritePipeType(QualType T) const {
Joey Goulye3c85de2016-12-01 11:30:49 +00003772 return getPipeType(T, false);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003773}
3774
John McCalle78aac42010-03-10 03:28:59 +00003775#ifndef NDEBUG
3776static bool NeedsInjectedClassNameType(const RecordDecl *D) {
3777 if (!isa<CXXRecordDecl>(D)) return false;
Eugene Zelenko7855e772018-04-03 00:11:50 +00003778 const auto *RD = cast<CXXRecordDecl>(D);
John McCalle78aac42010-03-10 03:28:59 +00003779 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
3780 return true;
3781 if (RD->getDescribedClassTemplate() &&
3782 !isa<ClassTemplateSpecializationDecl>(RD))
3783 return true;
3784 return false;
3785}
3786#endif
3787
3788/// getInjectedClassNameType - Return the unique reference to the
3789/// injected class name type for the specified templated declaration.
3790QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00003791 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00003792 assert(NeedsInjectedClassNameType(Decl));
3793 if (Decl->TypeForDecl) {
3794 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00003795 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00003796 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
3797 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3798 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
3799 } else {
John McCall424cec92011-01-19 06:33:43 +00003800 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00003801 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00003802 Decl->TypeForDecl = newType;
3803 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00003804 }
3805 return QualType(Decl->TypeForDecl, 0);
3806}
3807
Douglas Gregor83a586e2008-04-13 21:07:44 +00003808/// getTypeDeclType - Return the unique reference to the type for the
3809/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00003810QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00003811 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00003812 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00003813
Eugene Zelenko7855e772018-04-03 00:11:50 +00003814 if (const auto *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00003815 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00003816
John McCall96f0b5f2010-03-10 06:48:02 +00003817 assert(!isa<TemplateTypeParmDecl>(Decl) &&
3818 "Template type parameter types are always available.");
3819
Eugene Zelenko7855e772018-04-03 00:11:50 +00003820 if (const auto *Record = dyn_cast<RecordDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003821 assert(Record->isFirstDecl() && "struct/union has previous declaration");
John McCall96f0b5f2010-03-10 06:48:02 +00003822 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003823 return getRecordType(Record);
Eugene Zelenko7855e772018-04-03 00:11:50 +00003824 } else if (const auto *Enum = dyn_cast<EnumDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003825 assert(Enum->isFirstDecl() && "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003826 return getEnumType(Enum);
Eugene Zelenko7855e772018-04-03 00:11:50 +00003827 } else if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00003828 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
3829 Decl->TypeForDecl = newType;
3830 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00003831 } else
John McCall96f0b5f2010-03-10 06:48:02 +00003832 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003833
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003834 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00003835}
3836
Chris Lattner32d920b2007-01-26 02:01:53 +00003837/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00003838/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003839QualType
Richard Smithdda56e42011-04-15 14:24:37 +00003840ASTContext::getTypedefType(const TypedefNameDecl *Decl,
3841 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003842 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003843
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003844 if (Canonical.isNull())
3845 Canonical = getCanonicalType(Decl->getUnderlyingType());
Eugene Zelenko7855e772018-04-03 00:11:50 +00003846 auto *newType = new (*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00003847 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00003848 Decl->TypeForDecl = newType;
3849 Types.push_back(newType);
3850 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00003851}
3852
Jay Foad39c79802011-01-12 09:06:06 +00003853QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003854 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3855
Douglas Gregorec9fd132012-01-14 16:38:05 +00003856 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003857 if (PrevDecl->TypeForDecl)
Fangrui Song6907ce22018-07-30 19:24:48 +00003858 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003859
Eugene Zelenko7855e772018-04-03 00:11:50 +00003860 auto *newType = new (*this, TypeAlignment) RecordType(Decl);
John McCall424cec92011-01-19 06:33:43 +00003861 Decl->TypeForDecl = newType;
3862 Types.push_back(newType);
3863 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003864}
3865
Jay Foad39c79802011-01-12 09:06:06 +00003866QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003867 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3868
Douglas Gregorec9fd132012-01-14 16:38:05 +00003869 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003870 if (PrevDecl->TypeForDecl)
Fangrui Song6907ce22018-07-30 19:24:48 +00003871 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003872
Eugene Zelenko7855e772018-04-03 00:11:50 +00003873 auto *newType = new (*this, TypeAlignment) EnumType(Decl);
John McCall424cec92011-01-19 06:33:43 +00003874 Decl->TypeForDecl = newType;
3875 Types.push_back(newType);
3876 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003877}
3878
Richard Smithe43e2b32018-08-20 21:47:29 +00003879QualType ASTContext::getAttributedType(attr::Kind attrKind,
John McCall81904512011-01-06 01:58:22 +00003880 QualType modifiedType,
3881 QualType equivalentType) {
3882 llvm::FoldingSetNodeID id;
3883 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
3884
Craig Topper36250ad2014-05-12 05:36:57 +00003885 void *insertPos = nullptr;
John McCall81904512011-01-06 01:58:22 +00003886 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3887 if (type) return QualType(type, 0);
3888
3889 QualType canon = getCanonicalType(equivalentType);
3890 type = new (*this, TypeAlignment)
3891 AttributedType(canon, attrKind, modifiedType, equivalentType);
3892
3893 Types.push_back(type);
3894 AttributedTypes.InsertNode(type, insertPos);
3895
3896 return QualType(type, 0);
3897}
3898
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003899/// Retrieve a substitution-result type.
John McCallcebee162009-10-18 09:09:24 +00003900QualType
3901ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00003902 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00003903 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00003904 && "replacement types must always be canonical");
3905
3906 llvm::FoldingSetNodeID ID;
3907 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00003908 void *InsertPos = nullptr;
John McCallcebee162009-10-18 09:09:24 +00003909 SubstTemplateTypeParmType *SubstParm
3910 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3911
3912 if (!SubstParm) {
3913 SubstParm = new (*this, TypeAlignment)
3914 SubstTemplateTypeParmType(Parm, Replacement);
3915 Types.push_back(SubstParm);
3916 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3917 }
3918
3919 return QualType(SubstParm, 0);
3920}
3921
Fangrui Song6907ce22018-07-30 19:24:48 +00003922/// Retrieve a
Douglas Gregorada4b792011-01-14 02:55:32 +00003923QualType ASTContext::getSubstTemplateTypeParmPackType(
3924 const TemplateTypeParmType *Parm,
3925 const TemplateArgument &ArgPack) {
3926#ifndef NDEBUG
Aaron Ballman2a89e852014-07-15 21:32:31 +00003927 for (const auto &P : ArgPack.pack_elements()) {
3928 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3929 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
Douglas Gregorada4b792011-01-14 02:55:32 +00003930 }
3931#endif
Fangrui Song6907ce22018-07-30 19:24:48 +00003932
Douglas Gregorada4b792011-01-14 02:55:32 +00003933 llvm::FoldingSetNodeID ID;
3934 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00003935 void *InsertPos = nullptr;
Douglas Gregorada4b792011-01-14 02:55:32 +00003936 if (SubstTemplateTypeParmPackType *SubstParm
3937 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3938 return QualType(SubstParm, 0);
Fangrui Song6907ce22018-07-30 19:24:48 +00003939
Douglas Gregorada4b792011-01-14 02:55:32 +00003940 QualType Canon;
3941 if (!Parm->isCanonicalUnqualified()) {
3942 Canon = getCanonicalType(QualType(Parm, 0));
3943 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3944 ArgPack);
3945 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3946 }
3947
Eugene Zelenko7855e772018-04-03 00:11:50 +00003948 auto *SubstParm
Douglas Gregorada4b792011-01-14 02:55:32 +00003949 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3950 ArgPack);
3951 Types.push_back(SubstParm);
George Burgess IVb5fe8552017-06-12 17:44:30 +00003952 SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos);
Fangrui Song6907ce22018-07-30 19:24:48 +00003953 return QualType(SubstParm, 0);
Douglas Gregorada4b792011-01-14 02:55:32 +00003954}
3955
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003956/// Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00003957/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00003958/// name.
Mike Stump11289f42009-09-09 15:08:12 +00003959QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00003960 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00003961 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00003962 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00003963 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Craig Topper36250ad2014-05-12 05:36:57 +00003964 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003965 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00003966 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3967
3968 if (TypeParm)
3969 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003970
Chandler Carruth08836322011-05-01 00:51:33 +00003971 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00003972 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00003973 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003974
Fangrui Song6907ce22018-07-30 19:24:48 +00003975 TemplateTypeParmType *TypeCheck
Douglas Gregorc42075a2010-02-04 18:10:26 +00003976 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3977 assert(!TypeCheck && "Template type parameter canonical type broken");
3978 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00003979 } else
John McCall90d1c2d2009-09-24 23:30:46 +00003980 TypeParm = new (*this, TypeAlignment)
3981 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00003982
3983 Types.push_back(TypeParm);
3984 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3985
3986 return QualType(TypeParm, 0);
3987}
3988
John McCalle78aac42010-03-10 03:28:59 +00003989TypeSourceInfo *
3990ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3991 SourceLocation NameLoc,
3992 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003993 QualType Underlying) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00003994 assert(!Name.getAsDependentTemplateName() &&
Douglas Gregore16af532011-02-28 18:50:33 +00003995 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003996 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00003997
3998 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie6adc78e2013-02-18 22:06:02 +00003999 TemplateSpecializationTypeLoc TL =
4000 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara48c05be2012-02-06 14:41:24 +00004001 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00004002 TL.setTemplateNameLoc(NameLoc);
4003 TL.setLAngleLoc(Args.getLAngleLoc());
4004 TL.setRAngleLoc(Args.getRAngleLoc());
4005 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
4006 TL.setArgLocInfo(i, Args[i].getLocInfo());
4007 return DI;
4008}
4009
Mike Stump11289f42009-09-09 15:08:12 +00004010QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00004011ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00004012 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00004013 QualType Underlying) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00004014 assert(!Template.getAsDependentTemplateName() &&
Douglas Gregore16af532011-02-28 18:50:33 +00004015 "No dependent template names here!");
John McCall6b51f282009-11-23 01:53:49 +00004016
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004017 SmallVector<TemplateArgument, 4> ArgVec;
David Majnemer6fbeee32016-07-07 04:43:07 +00004018 ArgVec.reserve(Args.size());
4019 for (const TemplateArgumentLoc &Arg : Args.arguments())
4020 ArgVec.push_back(Arg.getArgument());
John McCall0ad16662009-10-29 08:12:44 +00004021
David Majnemer6fbeee32016-07-07 04:43:07 +00004022 return getTemplateSpecializationType(Template, ArgVec, Underlying);
John McCall0ad16662009-10-29 08:12:44 +00004023}
4024
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004025#ifndef NDEBUG
David Majnemer6fbeee32016-07-07 04:43:07 +00004026static bool hasAnyPackExpansions(ArrayRef<TemplateArgument> Args) {
4027 for (const TemplateArgument &Arg : Args)
4028 if (Arg.isPackExpansion())
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004029 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00004030
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004031 return true;
4032}
4033#endif
4034
John McCall0ad16662009-10-29 08:12:44 +00004035QualType
4036ASTContext::getTemplateSpecializationType(TemplateName Template,
David Majnemer6fbeee32016-07-07 04:43:07 +00004037 ArrayRef<TemplateArgument> Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00004038 QualType Underlying) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00004039 assert(!Template.getAsDependentTemplateName() &&
Douglas Gregore16af532011-02-28 18:50:33 +00004040 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00004041 // Look through qualified template names.
4042 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
4043 Template = TemplateName(QTN->getTemplateDecl());
Fangrui Song6907ce22018-07-30 19:24:48 +00004044
4045 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00004046 Template.getAsTemplateDecl() &&
4047 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00004048 QualType CanonType;
4049 if (!Underlying.isNull())
4050 CanonType = getCanonicalType(Underlying);
4051 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004052 // We can get here with an alias template when the specialization contains
4053 // a pack expansion that does not match up with a parameter pack.
David Majnemer6fbeee32016-07-07 04:43:07 +00004054 assert((!IsTypeAlias || hasAnyPackExpansions(Args)) &&
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004055 "Caller must compute aliased type");
4056 IsTypeAlias = false;
David Majnemer6fbeee32016-07-07 04:43:07 +00004057 CanonType = getCanonicalTemplateSpecializationType(Template, Args);
Richard Smith3f1b5d02011-05-05 21:57:07 +00004058 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00004059
Douglas Gregora8e02e72009-07-28 23:00:59 +00004060 // Allocate the (non-canonical) template specialization type, but don't
4061 // try to unique it: these types typically have location information that
4062 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00004063 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
David Majnemer6fbeee32016-07-07 04:43:07 +00004064 sizeof(TemplateArgument) * Args.size() +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004065 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00004066 TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004067 auto *Spec
David Majnemer6fbeee32016-07-07 04:43:07 +00004068 = new (Mem) TemplateSpecializationType(Template, Args, CanonType,
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004069 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00004070
Douglas Gregor8bf42052009-02-09 18:46:07 +00004071 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00004072 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00004073}
4074
David Majnemer6fbeee32016-07-07 04:43:07 +00004075QualType ASTContext::getCanonicalTemplateSpecializationType(
4076 TemplateName Template, ArrayRef<TemplateArgument> Args) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00004077 assert(!Template.getAsDependentTemplateName() &&
Douglas Gregore16af532011-02-28 18:50:33 +00004078 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00004079
Douglas Gregore29139c2011-03-03 17:04:51 +00004080 // Look through qualified template names.
4081 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
4082 Template = TemplateName(QTN->getTemplateDecl());
Fangrui Song6907ce22018-07-30 19:24:48 +00004083
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004084 // Build the canonical template specialization type.
4085 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004086 SmallVector<TemplateArgument, 4> CanonArgs;
David Majnemer6fbeee32016-07-07 04:43:07 +00004087 unsigned NumArgs = Args.size();
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004088 CanonArgs.reserve(NumArgs);
David Majnemer6fbeee32016-07-07 04:43:07 +00004089 for (const TemplateArgument &Arg : Args)
4090 CanonArgs.push_back(getCanonicalTemplateArgument(Arg));
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004091
4092 // Determine whether this canonical template specialization type already
4093 // exists.
4094 llvm::FoldingSetNodeID ID;
4095 TemplateSpecializationType::Profile(ID, CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00004096 CanonArgs, *this);
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004097
Craig Topper36250ad2014-05-12 05:36:57 +00004098 void *InsertPos = nullptr;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004099 TemplateSpecializationType *Spec
4100 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
4101
4102 if (!Spec) {
4103 // Allocate a new canonical template specialization type.
4104 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
4105 sizeof(TemplateArgument) * NumArgs),
4106 TypeAlignment);
4107 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00004108 CanonArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00004109 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004110 Types.push_back(Spec);
4111 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
4112 }
4113
4114 assert(Spec->isDependentType() &&
4115 "Non-dependent template-id type must have a canonical type");
4116 return QualType(Spec, 0);
4117}
4118
Joel E. Denny7509a2f2018-05-14 19:36:45 +00004119QualType ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
4120 NestedNameSpecifier *NNS,
4121 QualType NamedType,
4122 TagDecl *OwnedTagDecl) const {
Douglas Gregor52537682009-03-19 00:18:19 +00004123 llvm::FoldingSetNodeID ID;
Joel E. Denny7509a2f2018-05-14 19:36:45 +00004124 ElaboratedType::Profile(ID, Keyword, NNS, NamedType, OwnedTagDecl);
Douglas Gregor52537682009-03-19 00:18:19 +00004125
Craig Topper36250ad2014-05-12 05:36:57 +00004126 void *InsertPos = nullptr;
Abramo Bagnara6150c882010-05-11 21:36:43 +00004127 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00004128 if (T)
4129 return QualType(T, 0);
4130
Douglas Gregorc42075a2010-02-04 18:10:26 +00004131 QualType Canon = NamedType;
4132 if (!Canon.isCanonical()) {
4133 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00004134 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
4135 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00004136 (void)CheckT;
4137 }
4138
Bruno Riccid6bd5982018-08-16 10:48:16 +00004139 void *Mem = Allocate(ElaboratedType::totalSizeToAlloc<TagDecl *>(!!OwnedTagDecl),
4140 TypeAlignment);
4141 T = new (Mem) ElaboratedType(Keyword, NNS, NamedType, Canon, OwnedTagDecl);
4142
Douglas Gregor52537682009-03-19 00:18:19 +00004143 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00004144 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00004145 return QualType(T, 0);
4146}
4147
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004148QualType
Jay Foad39c79802011-01-12 09:06:06 +00004149ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004150 llvm::FoldingSetNodeID ID;
4151 ParenType::Profile(ID, InnerType);
4152
Craig Topper36250ad2014-05-12 05:36:57 +00004153 void *InsertPos = nullptr;
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004154 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
4155 if (T)
4156 return QualType(T, 0);
4157
4158 QualType Canon = InnerType;
4159 if (!Canon.isCanonical()) {
4160 Canon = getCanonicalType(InnerType);
4161 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
4162 assert(!CheckT && "Paren canonical type broken");
4163 (void)CheckT;
4164 }
4165
Benjamin Kramer8adeef92015-04-02 16:19:54 +00004166 T = new (*this, TypeAlignment) ParenType(InnerType, Canon);
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004167 Types.push_back(T);
4168 ParenTypes.InsertNode(T, InsertPos);
4169 return QualType(T, 0);
4170}
4171
Douglas Gregor02085352010-03-31 20:19:30 +00004172QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
4173 NestedNameSpecifier *NNS,
4174 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00004175 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00004176 if (Canon.isNull()) {
4177 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Richard Smith74f02342017-01-19 21:00:13 +00004178 if (CanonNNS != NNS)
4179 Canon = getDependentNameType(Keyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00004180 }
4181
4182 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00004183 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00004184
Craig Topper36250ad2014-05-12 05:36:57 +00004185 void *InsertPos = nullptr;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00004186 DependentNameType *T
4187 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00004188 if (T)
4189 return QualType(T, 0);
4190
Benjamin Kramer8adeef92015-04-02 16:19:54 +00004191 T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00004192 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00004193 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00004194 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00004195}
4196
Mike Stump11289f42009-09-09 15:08:12 +00004197QualType
John McCallc392f372010-06-11 00:33:02 +00004198ASTContext::getDependentTemplateSpecializationType(
4199 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00004200 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00004201 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00004202 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00004203 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004204 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00004205 for (unsigned I = 0, E = Args.size(); I != E; ++I)
4206 ArgCopy.push_back(Args[I].getArgument());
David Majnemer6fbeee32016-07-07 04:43:07 +00004207 return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy);
John McCallc392f372010-06-11 00:33:02 +00004208}
4209
4210QualType
4211ASTContext::getDependentTemplateSpecializationType(
4212 ElaboratedTypeKeyword Keyword,
4213 NestedNameSpecifier *NNS,
4214 const IdentifierInfo *Name,
David Majnemer6fbeee32016-07-07 04:43:07 +00004215 ArrayRef<TemplateArgument> Args) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00004216 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor6e068012011-02-28 00:04:36 +00004217 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00004218
Douglas Gregorc42075a2010-02-04 18:10:26 +00004219 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00004220 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00004221 Name, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004222
Craig Topper36250ad2014-05-12 05:36:57 +00004223 void *InsertPos = nullptr;
John McCallc392f372010-06-11 00:33:02 +00004224 DependentTemplateSpecializationType *T
4225 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004226 if (T)
4227 return QualType(T, 0);
4228
John McCallc392f372010-06-11 00:33:02 +00004229 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004230
John McCallc392f372010-06-11 00:33:02 +00004231 ElaboratedTypeKeyword CanonKeyword = Keyword;
4232 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
4233
4234 bool AnyNonCanonArgs = false;
David Majnemer6fbeee32016-07-07 04:43:07 +00004235 unsigned NumArgs = Args.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004236 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00004237 for (unsigned I = 0; I != NumArgs; ++I) {
4238 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
4239 if (!CanonArgs[I].structurallyEquals(Args[I]))
4240 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00004241 }
4242
John McCallc392f372010-06-11 00:33:02 +00004243 QualType Canon;
4244 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
4245 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00004246 Name,
4247 CanonArgs);
John McCallc392f372010-06-11 00:33:02 +00004248
4249 // Find the insert position again.
4250 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
4251 }
4252
4253 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
4254 sizeof(TemplateArgument) * NumArgs),
4255 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00004256 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00004257 Name, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00004258 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00004259 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00004260 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00004261}
4262
Richard Smith32918772017-02-14 00:25:28 +00004263TemplateArgument ASTContext::getInjectedTemplateArg(NamedDecl *Param) {
4264 TemplateArgument Arg;
Eugene Zelenko7855e772018-04-03 00:11:50 +00004265 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
Richard Smith32918772017-02-14 00:25:28 +00004266 QualType ArgType = getTypeDeclType(TTP);
4267 if (TTP->isParameterPack())
4268 ArgType = getPackExpansionType(ArgType, None);
4269
4270 Arg = TemplateArgument(ArgType);
4271 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4272 Expr *E = new (*this) DeclRefExpr(
4273 NTTP, /*enclosing*/false,
4274 NTTP->getType().getNonLValueExprType(*this),
4275 Expr::getValueKindForType(NTTP->getType()), NTTP->getLocation());
4276
4277 if (NTTP->isParameterPack())
4278 E = new (*this) PackExpansionExpr(DependentTy, E, NTTP->getLocation(),
4279 None);
4280 Arg = TemplateArgument(E);
4281 } else {
4282 auto *TTP = cast<TemplateTemplateParmDecl>(Param);
4283 if (TTP->isParameterPack())
4284 Arg = TemplateArgument(TemplateName(TTP), Optional<unsigned>());
4285 else
4286 Arg = TemplateArgument(TemplateName(TTP));
4287 }
4288
4289 if (Param->isTemplateParameterPack())
4290 Arg = TemplateArgument::CreatePackCopy(*this, Arg);
4291
4292 return Arg;
4293}
4294
Richard Smith43e14d22016-12-23 02:10:11 +00004295void
4296ASTContext::getInjectedTemplateArgs(const TemplateParameterList *Params,
4297 SmallVectorImpl<TemplateArgument> &Args) {
4298 Args.reserve(Args.size() + Params->size());
4299
Richard Smith32918772017-02-14 00:25:28 +00004300 for (NamedDecl *Param : *Params)
4301 Args.push_back(getInjectedTemplateArg(Param));
Richard Smith43e14d22016-12-23 02:10:11 +00004302}
4303
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00004304QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikie05785d12013-02-20 22:23:23 +00004305 Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00004306 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00004307 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00004308
4309 assert(Pattern->containsUnexpandedParameterPack() &&
4310 "Pack expansions must expand one or more parameter packs");
Craig Topper36250ad2014-05-12 05:36:57 +00004311 void *InsertPos = nullptr;
Douglas Gregord2fa7662010-12-20 02:24:11 +00004312 PackExpansionType *T
4313 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
4314 if (T)
4315 return QualType(T, 0);
4316
4317 QualType Canon;
4318 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00004319 Canon = getCanonicalType(Pattern);
4320 // The canonical type might not contain an unexpanded parameter pack, if it
4321 // contains an alias template specialization which ignores one of its
4322 // parameters.
4323 if (Canon->containsUnexpandedParameterPack()) {
Richard Smith8b4e1e22014-07-10 01:20:17 +00004324 Canon = getPackExpansionType(Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00004325
Richard Smith68eea502012-07-16 00:20:35 +00004326 // Find the insert position again, in case we inserted an element into
4327 // PackExpansionTypes and invalidated our insert position.
4328 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
4329 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00004330 }
4331
Benjamin Kramer8adeef92015-04-02 16:19:54 +00004332 T = new (*this, TypeAlignment)
4333 PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00004334 Types.push_back(T);
4335 PackExpansionTypes.InsertNode(T, InsertPos);
Richard Smith8b4e1e22014-07-10 01:20:17 +00004336 return QualType(T, 0);
Douglas Gregord2fa7662010-12-20 02:24:11 +00004337}
4338
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004339/// CmpProtocolNames - Comparison predicate for sorting protocols
4340/// alphabetically.
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00004341static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
4342 ObjCProtocolDecl *const *RHS) {
4343 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004344}
4345
Craig Topper1f26d5b2016-01-03 19:43:23 +00004346static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) {
4347 if (Protocols.empty()) return true;
John McCallfc93cf92009-10-22 22:37:11 +00004348
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00004349 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
4350 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00004351
Craig Topper1f26d5b2016-01-03 19:43:23 +00004352 for (unsigned i = 1; i != Protocols.size(); ++i)
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00004353 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00004354 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00004355 return false;
4356 return true;
4357}
4358
Craig Topper6a8c1512015-10-22 01:56:18 +00004359static void
4360SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) {
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004361 // Sort protocols, keyed by name.
Craig Topper6a8c1512015-10-22 01:56:18 +00004362 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004363
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00004364 // Canonicalize.
Craig Topper6a8c1512015-10-22 01:56:18 +00004365 for (ObjCProtocolDecl *&P : Protocols)
4366 P = P->getCanonicalDecl();
4367
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004368 // Remove duplicates.
Craig Topper6a8c1512015-10-22 01:56:18 +00004369 auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end());
4370 Protocols.erase(ProtocolsEnd, Protocols.end());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004371}
4372
John McCall8b07ec22010-05-15 11:32:37 +00004373QualType ASTContext::getObjCObjectType(QualType BaseType,
4374 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00004375 unsigned NumProtocols) const {
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004376 return getObjCObjectType(BaseType, {},
Douglas Gregorab209d82015-07-07 03:58:42 +00004377 llvm::makeArrayRef(Protocols, NumProtocols),
4378 /*isKindOf=*/false);
Douglas Gregore9d95f12015-07-07 03:57:35 +00004379}
4380
4381QualType ASTContext::getObjCObjectType(
4382 QualType baseType,
4383 ArrayRef<QualType> typeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00004384 ArrayRef<ObjCProtocolDecl *> protocols,
4385 bool isKindOf) const {
Douglas Gregore9d95f12015-07-07 03:57:35 +00004386 // If the base type is an interface and there aren't any protocols or
4387 // type arguments to add, then the interface type will do just fine.
Douglas Gregorab209d82015-07-07 03:58:42 +00004388 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
4389 isa<ObjCInterfaceType>(baseType))
Douglas Gregore9d95f12015-07-07 03:57:35 +00004390 return baseType;
John McCall8b07ec22010-05-15 11:32:37 +00004391
4392 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00004393 llvm::FoldingSetNodeID ID;
Douglas Gregorab209d82015-07-07 03:58:42 +00004394 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
Craig Topper36250ad2014-05-12 05:36:57 +00004395 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00004396 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
4397 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00004398
Douglas Gregore9d95f12015-07-07 03:57:35 +00004399 // Determine the type arguments to be used for canonicalization,
4400 // which may be explicitly specified here or written on the base
4401 // type.
4402 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
4403 if (effectiveTypeArgs.empty()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00004404 if (const auto *baseObject = baseType->getAs<ObjCObjectType>())
Douglas Gregore9d95f12015-07-07 03:57:35 +00004405 effectiveTypeArgs = baseObject->getTypeArgs();
4406 }
John McCallfc93cf92009-10-22 22:37:11 +00004407
Douglas Gregore9d95f12015-07-07 03:57:35 +00004408 // Build the canonical type, which has the canonical base type and a
4409 // sorted-and-uniqued list of protocols and the type arguments
4410 // canonicalized.
4411 QualType canonical;
4412 bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(),
4413 effectiveTypeArgs.end(),
4414 [&](QualType type) {
4415 return type.isCanonical();
4416 });
Craig Topper1f26d5b2016-01-03 19:43:23 +00004417 bool protocolsSorted = areSortedAndUniqued(protocols);
Douglas Gregore9d95f12015-07-07 03:57:35 +00004418 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
4419 // Determine the canonical type arguments.
4420 ArrayRef<QualType> canonTypeArgs;
4421 SmallVector<QualType, 4> canonTypeArgsVec;
4422 if (!typeArgsAreCanonical) {
4423 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
4424 for (auto typeArg : effectiveTypeArgs)
4425 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
4426 canonTypeArgs = canonTypeArgsVec;
John McCallfc93cf92009-10-22 22:37:11 +00004427 } else {
Douglas Gregore9d95f12015-07-07 03:57:35 +00004428 canonTypeArgs = effectiveTypeArgs;
John McCallfc93cf92009-10-22 22:37:11 +00004429 }
4430
Douglas Gregore9d95f12015-07-07 03:57:35 +00004431 ArrayRef<ObjCProtocolDecl *> canonProtocols;
4432 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
4433 if (!protocolsSorted) {
Craig Topper6a8c1512015-10-22 01:56:18 +00004434 canonProtocolsVec.append(protocols.begin(), protocols.end());
4435 SortAndUniqueProtocols(canonProtocolsVec);
4436 canonProtocols = canonProtocolsVec;
Douglas Gregore9d95f12015-07-07 03:57:35 +00004437 } else {
4438 canonProtocols = protocols;
4439 }
4440
4441 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00004442 canonProtocols, isKindOf);
Douglas Gregore9d95f12015-07-07 03:57:35 +00004443
John McCallfc93cf92009-10-22 22:37:11 +00004444 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00004445 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
4446 }
4447
Douglas Gregore9d95f12015-07-07 03:57:35 +00004448 unsigned size = sizeof(ObjCObjectTypeImpl);
4449 size += typeArgs.size() * sizeof(QualType);
4450 size += protocols.size() * sizeof(ObjCProtocolDecl *);
4451 void *mem = Allocate(size, TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004452 auto *T =
Douglas Gregorab209d82015-07-07 03:58:42 +00004453 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
4454 isKindOf);
John McCall8b07ec22010-05-15 11:32:37 +00004455
4456 Types.push_back(T);
4457 ObjCObjectTypes.InsertNode(T, InsertPos);
4458 return QualType(T, 0);
4459}
4460
Manman Ren3569eb52016-09-13 17:03:12 +00004461/// Apply Objective-C protocol qualifiers to the given type.
4462/// If this is for the canonical type of a type parameter, we can apply
4463/// protocol qualifiers on the ObjCObjectPointerType.
4464QualType
4465ASTContext::applyObjCProtocolQualifiers(QualType type,
4466 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
4467 bool allowOnPointerType) const {
4468 hasError = false;
4469
Eugene Zelenko7855e772018-04-03 00:11:50 +00004470 if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
Manman Renc5705ba2016-09-13 17:41:05 +00004471 return getObjCTypeParamType(objT->getDecl(), protocols);
4472 }
4473
Manman Ren3569eb52016-09-13 17:03:12 +00004474 // Apply protocol qualifiers to ObjCObjectPointerType.
4475 if (allowOnPointerType) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00004476 if (const auto *objPtr =
4477 dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
Manman Ren3569eb52016-09-13 17:03:12 +00004478 const ObjCObjectType *objT = objPtr->getObjectType();
4479 // Merge protocol lists and construct ObjCObjectType.
4480 SmallVector<ObjCProtocolDecl*, 8> protocolsVec;
4481 protocolsVec.append(objT->qual_begin(),
4482 objT->qual_end());
4483 protocolsVec.append(protocols.begin(), protocols.end());
4484 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
4485 type = getObjCObjectType(
4486 objT->getBaseType(),
4487 objT->getTypeArgsAsWritten(),
4488 protocols,
4489 objT->isKindOfTypeAsWritten());
4490 return getObjCObjectPointerType(type);
4491 }
4492 }
4493
4494 // Apply protocol qualifiers to ObjCObjectType.
Eugene Zelenko7855e772018-04-03 00:11:50 +00004495 if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
Manman Ren3569eb52016-09-13 17:03:12 +00004496 // FIXME: Check for protocols to which the class type is already
4497 // known to conform.
4498
4499 return getObjCObjectType(objT->getBaseType(),
4500 objT->getTypeArgsAsWritten(),
4501 protocols,
4502 objT->isKindOfTypeAsWritten());
4503 }
4504
4505 // If the canonical type is ObjCObjectType, ...
4506 if (type->isObjCObjectType()) {
4507 // Silently overwrite any existing protocol qualifiers.
4508 // TODO: determine whether that's the right thing to do.
4509
4510 // FIXME: Check for protocols to which the class type is already
4511 // known to conform.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004512 return getObjCObjectType(type, {}, protocols, false);
Manman Ren3569eb52016-09-13 17:03:12 +00004513 }
4514
4515 // id<protocol-list>
4516 if (type->isObjCIdType()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00004517 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004518 type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols,
Manman Ren3569eb52016-09-13 17:03:12 +00004519 objPtr->isKindOfType());
4520 return getObjCObjectPointerType(type);
4521 }
4522
4523 // Class<protocol-list>
4524 if (type->isObjCClassType()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00004525 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004526 type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols,
Manman Ren3569eb52016-09-13 17:03:12 +00004527 objPtr->isKindOfType());
4528 return getObjCObjectPointerType(type);
4529 }
4530
4531 hasError = true;
4532 return type;
4533}
4534
Manman Rene6be26c2016-09-13 17:25:08 +00004535QualType
4536ASTContext::getObjCTypeParamType(const ObjCTypeParamDecl *Decl,
4537 ArrayRef<ObjCProtocolDecl *> protocols,
4538 QualType Canonical) const {
4539 // Look in the folding set for an existing type.
4540 llvm::FoldingSetNodeID ID;
4541 ObjCTypeParamType::Profile(ID, Decl, protocols);
4542 void *InsertPos = nullptr;
4543 if (ObjCTypeParamType *TypeParam =
4544 ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
4545 return QualType(TypeParam, 0);
4546
4547 if (Canonical.isNull()) {
4548 // We canonicalize to the underlying type.
4549 Canonical = getCanonicalType(Decl->getUnderlyingType());
4550 if (!protocols.empty()) {
4551 // Apply the protocol qualifers.
4552 bool hasError;
Richard Trieua986a312018-08-30 01:57:52 +00004553 Canonical = getCanonicalType(applyObjCProtocolQualifiers(
4554 Canonical, protocols, hasError, true /*allowOnPointerType*/));
Manman Rene6be26c2016-09-13 17:25:08 +00004555 assert(!hasError && "Error when apply protocol qualifier to bound type");
4556 }
4557 }
4558
4559 unsigned size = sizeof(ObjCTypeParamType);
4560 size += protocols.size() * sizeof(ObjCProtocolDecl *);
4561 void *mem = Allocate(size, TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004562 auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols);
Manman Rene6be26c2016-09-13 17:25:08 +00004563
4564 Types.push_back(newType);
4565 ObjCTypeParamTypes.InsertNode(newType, InsertPos);
4566 return QualType(newType, 0);
4567}
4568
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004569/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
4570/// protocol list adopt all protocols in QT's qualified-id protocol
4571/// list.
4572bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
4573 ObjCInterfaceDecl *IC) {
4574 if (!QT->isObjCQualifiedIdType())
4575 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00004576
Eugene Zelenko7855e772018-04-03 00:11:50 +00004577 if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004578 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00004579 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004580 if (!IC->ClassImplementsProtocol(Proto, false))
4581 return false;
4582 }
4583 return true;
4584 }
4585 return false;
4586}
4587
4588/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
4589/// QT's qualified-id protocol list adopt all protocols in IDecl's list
4590/// of protocols.
4591bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
4592 ObjCInterfaceDecl *IDecl) {
4593 if (!QT->isObjCQualifiedIdType())
4594 return false;
Eugene Zelenko7855e772018-04-03 00:11:50 +00004595 const auto *OPT = QT->getAs<ObjCObjectPointerType>();
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004596 if (!OPT)
4597 return false;
4598 if (!IDecl->hasDefinition())
4599 return false;
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00004600 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
4601 CollectInheritedProtocols(IDecl, InheritedProtocols);
4602 if (InheritedProtocols.empty())
4603 return false;
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00004604 // Check that if every protocol in list of id<plist> conforms to a protocol
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00004605 // of IDecl's, then bridge casting is ok.
4606 bool Conforms = false;
4607 for (auto *Proto : OPT->quals()) {
4608 Conforms = false;
4609 for (auto *PI : InheritedProtocols) {
4610 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
4611 Conforms = true;
4612 break;
4613 }
4614 }
4615 if (!Conforms)
4616 break;
4617 }
4618 if (Conforms)
4619 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00004620
Aaron Ballman83731462014-03-17 16:14:00 +00004621 for (auto *PI : InheritedProtocols) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004622 // If both the right and left sides have qualifiers.
4623 bool Adopts = false;
Aaron Ballman83731462014-03-17 16:14:00 +00004624 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00004625 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
Aaron Ballman83731462014-03-17 16:14:00 +00004626 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004627 break;
4628 }
4629 if (!Adopts)
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00004630 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004631 }
4632 return true;
4633}
4634
John McCall8b07ec22010-05-15 11:32:37 +00004635/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
4636/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00004637QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00004638 llvm::FoldingSetNodeID ID;
4639 ObjCObjectPointerType::Profile(ID, ObjectT);
4640
Craig Topper36250ad2014-05-12 05:36:57 +00004641 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00004642 if (ObjCObjectPointerType *QT =
4643 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
4644 return QualType(QT, 0);
4645
4646 // Find the canonical object type.
4647 QualType Canonical;
4648 if (!ObjectT.isCanonical()) {
4649 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
4650
4651 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00004652 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
4653 }
4654
Douglas Gregorf85bee62010-02-08 22:59:26 +00004655 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00004656 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004657 auto *QType =
John McCall8b07ec22010-05-15 11:32:37 +00004658 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00004659
Steve Narofffb4330f2009-06-17 22:40:22 +00004660 Types.push_back(QType);
4661 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00004662 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00004663}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004664
Douglas Gregor1c283312010-08-11 12:19:30 +00004665/// getObjCInterfaceType - Return the unique reference to the type for the
4666/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00004667QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
4668 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00004669 if (Decl->TypeForDecl)
4670 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004671
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00004672 if (PrevDecl) {
4673 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
4674 Decl->TypeForDecl = PrevDecl->TypeForDecl;
4675 return QualType(PrevDecl->TypeForDecl, 0);
4676 }
4677
Douglas Gregor7671e532011-12-16 16:34:57 +00004678 // Prefer the definition, if there is one.
4679 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
4680 Decl = Def;
Fangrui Song6907ce22018-07-30 19:24:48 +00004681
Douglas Gregor1c283312010-08-11 12:19:30 +00004682 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004683 auto *T = new (Mem) ObjCInterfaceType(Decl);
Douglas Gregor1c283312010-08-11 12:19:30 +00004684 Decl->TypeForDecl = T;
4685 Types.push_back(T);
4686 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00004687}
4688
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004689/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
4690/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00004691/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00004692/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00004693/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00004694QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00004695 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004696 if (tofExpr->isTypeDependent()) {
4697 llvm::FoldingSetNodeID ID;
4698 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00004699
Craig Topper36250ad2014-05-12 05:36:57 +00004700 void *InsertPos = nullptr;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004701 DependentTypeOfExprType *Canon
4702 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
4703 if (Canon) {
4704 // We already have a "canonical" version of an identical, dependent
4705 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00004706 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004707 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00004708 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004709 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00004710 Canon
4711 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004712 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
4713 toe = Canon;
4714 }
4715 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00004716 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00004717 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00004718 }
Steve Naroffa773cd52007-08-01 18:02:17 +00004719 Types.push_back(toe);
4720 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00004721}
4722
Steve Naroffa773cd52007-08-01 18:02:17 +00004723/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
Richard Smith8eb1d322014-06-05 20:13:13 +00004724/// TypeOfType nodes. The only motivation to unique these nodes would be
Steve Naroffa773cd52007-08-01 18:02:17 +00004725/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Richard Smith8eb1d322014-06-05 20:13:13 +00004726/// an issue. This doesn't affect the type checker, since it operates
4727/// on canonical types (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00004728QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00004729 QualType Canonical = getCanonicalType(tofType);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004730 auto *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00004731 Types.push_back(tot);
4732 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00004733}
4734
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004735/// Unlike many "get<Type>" functions, we don't unique DecltypeType
Richard Smith8eb1d322014-06-05 20:13:13 +00004736/// nodes. This would never be helpful, since each such type has its own
4737/// expression, and would not give a significant memory saving, since there
4738/// is an Expr tree under each such type.
Douglas Gregor81495f32012-02-12 18:42:33 +00004739QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00004740 DecltypeType *dt;
Richard Smith8eb1d322014-06-05 20:13:13 +00004741
4742 // C++11 [temp.type]p2:
Douglas Gregor678d76c2011-07-01 01:22:09 +00004743 // If an expression e involves a template parameter, decltype(e) denotes a
Richard Smith8eb1d322014-06-05 20:13:13 +00004744 // unique dependent type. Two such decltype-specifiers refer to the same
4745 // type only if their expressions are equivalent (14.5.6.1).
Douglas Gregor678d76c2011-07-01 01:22:09 +00004746 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00004747 llvm::FoldingSetNodeID ID;
4748 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00004749
Craig Topper36250ad2014-05-12 05:36:57 +00004750 void *InsertPos = nullptr;
Douglas Gregora21f6c32009-07-30 23:36:40 +00004751 DependentDecltypeType *Canon
4752 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
Richard Smith8eb1d322014-06-05 20:13:13 +00004753 if (!Canon) {
Yaron Keren633e14a2016-11-29 10:08:20 +00004754 // Build a new, canonical decltype(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00004755 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00004756 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
Douglas Gregora21f6c32009-07-30 23:36:40 +00004757 }
Richard Smith8eb1d322014-06-05 20:13:13 +00004758 dt = new (*this, TypeAlignment)
4759 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
Douglas Gregora21f6c32009-07-30 23:36:40 +00004760 } else {
Richard Smith8eb1d322014-06-05 20:13:13 +00004761 dt = new (*this, TypeAlignment)
4762 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00004763 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00004764 Types.push_back(dt);
4765 return QualType(dt, 0);
4766}
4767
Alexis Hunte852b102011-05-24 22:41:36 +00004768/// getUnaryTransformationType - We don't unique these, since the memory
4769/// savings are minimal and these are rare.
4770QualType ASTContext::getUnaryTransformType(QualType BaseType,
4771 QualType UnderlyingType,
4772 UnaryTransformType::UTTKind Kind)
4773 const {
Vassil Vassilevbab6f962016-03-30 22:18:29 +00004774 UnaryTransformType *ut = nullptr;
4775
4776 if (BaseType->isDependentType()) {
4777 // Look in the folding set for an existing type.
4778 llvm::FoldingSetNodeID ID;
4779 DependentUnaryTransformType::Profile(ID, getCanonicalType(BaseType), Kind);
4780
4781 void *InsertPos = nullptr;
4782 DependentUnaryTransformType *Canon
4783 = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
4784
4785 if (!Canon) {
4786 // Build a new, canonical __underlying_type(type) type.
4787 Canon = new (*this, TypeAlignment)
4788 DependentUnaryTransformType(*this, getCanonicalType(BaseType),
4789 Kind);
4790 DependentUnaryTransformTypes.InsertNode(Canon, InsertPos);
4791 }
4792 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4793 QualType(), Kind,
4794 QualType(Canon, 0));
4795 } else {
4796 QualType CanonType = getCanonicalType(UnderlyingType);
4797 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4798 UnderlyingType, Kind,
4799 CanonType);
4800 }
4801 Types.push_back(ut);
4802 return QualType(ut, 0);
Alexis Hunte852b102011-05-24 22:41:36 +00004803}
4804
Richard Smith2a7d4812013-05-04 07:00:32 +00004805/// getAutoType - Return the uniqued reference to the 'auto' type which has been
4806/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
4807/// canonical deduced-but-dependent 'auto' type.
Richard Smithe301ba22015-11-11 02:02:15 +00004808QualType ASTContext::getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004809 bool IsDependent) const {
Richard Smithe301ba22015-11-11 02:02:15 +00004810 if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto && !IsDependent)
Richard Smith2a7d4812013-05-04 07:00:32 +00004811 return getAutoDeductType();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004812
Richard Smith2a7d4812013-05-04 07:00:32 +00004813 // Look in the folding set for an existing type.
Craig Topper36250ad2014-05-12 05:36:57 +00004814 void *InsertPos = nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +00004815 llvm::FoldingSetNodeID ID;
Richard Smithe301ba22015-11-11 02:02:15 +00004816 AutoType::Profile(ID, DeducedType, Keyword, IsDependent);
Richard Smith2a7d4812013-05-04 07:00:32 +00004817 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
4818 return QualType(AT, 0);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004819
Eugene Zelenko7855e772018-04-03 00:11:50 +00004820 auto *AT = new (*this, TypeAlignment)
4821 AutoType(DeducedType, Keyword, IsDependent);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004822 Types.push_back(AT);
4823 if (InsertPos)
4824 AutoTypes.InsertNode(AT, InsertPos);
4825 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00004826}
4827
Richard Smith600b5262017-01-26 20:40:47 +00004828/// Return the uniqued reference to the deduced template specialization type
4829/// which has been deduced to the given type, or to the canonical undeduced
4830/// such type, or the canonical deduced-but-dependent such type.
4831QualType ASTContext::getDeducedTemplateSpecializationType(
4832 TemplateName Template, QualType DeducedType, bool IsDependent) const {
4833 // Look in the folding set for an existing type.
4834 void *InsertPos = nullptr;
4835 llvm::FoldingSetNodeID ID;
4836 DeducedTemplateSpecializationType::Profile(ID, Template, DeducedType,
4837 IsDependent);
4838 if (DeducedTemplateSpecializationType *DTST =
4839 DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
4840 return QualType(DTST, 0);
4841
Eugene Zelenko7855e772018-04-03 00:11:50 +00004842 auto *DTST = new (*this, TypeAlignment)
Richard Smith600b5262017-01-26 20:40:47 +00004843 DeducedTemplateSpecializationType(Template, DeducedType, IsDependent);
4844 Types.push_back(DTST);
4845 if (InsertPos)
4846 DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos);
4847 return QualType(DTST, 0);
4848}
4849
Eli Friedman0dfb8892011-10-06 23:00:33 +00004850/// getAtomicType - Return the uniqued reference to the atomic type for
4851/// the given value type.
4852QualType ASTContext::getAtomicType(QualType T) const {
4853 // Unique pointers, to guarantee there is only one pointer of a particular
4854 // structure.
4855 llvm::FoldingSetNodeID ID;
4856 AtomicType::Profile(ID, T);
4857
Craig Topper36250ad2014-05-12 05:36:57 +00004858 void *InsertPos = nullptr;
Eli Friedman0dfb8892011-10-06 23:00:33 +00004859 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
4860 return QualType(AT, 0);
4861
4862 // If the atomic value type isn't canonical, this won't be a canonical type
4863 // either, so fill in the canonical type field.
4864 QualType Canonical;
4865 if (!T.isCanonical()) {
4866 Canonical = getAtomicType(getCanonicalType(T));
4867
4868 // Get the new insert position for the node we care about.
4869 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00004870 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Eli Friedman0dfb8892011-10-06 23:00:33 +00004871 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00004872 auto *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
Eli Friedman0dfb8892011-10-06 23:00:33 +00004873 Types.push_back(New);
4874 AtomicTypes.InsertNode(New, InsertPos);
4875 return QualType(New, 0);
4876}
4877
Richard Smith02e85f32011-04-14 22:09:26 +00004878/// getAutoDeductType - Get type pattern for deducing against 'auto'.
4879QualType ASTContext::getAutoDeductType() const {
4880 if (AutoDeductTy.isNull())
Richard Smith2a7d4812013-05-04 07:00:32 +00004881 AutoDeductTy = QualType(
Richard Smithe301ba22015-11-11 02:02:15 +00004882 new (*this, TypeAlignment) AutoType(QualType(), AutoTypeKeyword::Auto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004883 /*dependent*/false),
Richard Smith2a7d4812013-05-04 07:00:32 +00004884 0);
Richard Smith02e85f32011-04-14 22:09:26 +00004885 return AutoDeductTy;
4886}
4887
4888/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
4889QualType ASTContext::getAutoRRefDeductType() const {
4890 if (AutoRRefDeductTy.isNull())
4891 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
4892 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
4893 return AutoRRefDeductTy;
4894}
4895
Chris Lattnerfb072462007-01-23 05:45:31 +00004896/// getTagDeclType - Return the unique reference to the type for the
4897/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00004898QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004899 assert(Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00004900 // FIXME: What is the design on getTagDeclType when it requires casting
4901 // away const? mutable?
4902 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00004903}
4904
Mike Stump11289f42009-09-09 15:08:12 +00004905/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
4906/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
4907/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00004908CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00004909 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00004910}
Chris Lattnerfb072462007-01-23 05:45:31 +00004911
Fangrui Song6907ce22018-07-30 19:24:48 +00004912/// Return the unique signed counterpart of the integer type
Alexander Shaposhnikov1e898d92017-07-14 17:30:14 +00004913/// corresponding to size_t.
4914CanQualType ASTContext::getSignedSizeType() const {
4915 return getFromTargetType(Target->getSignedSizeType());
4916}
4917
Hans Wennborg27541db2011-10-27 08:29:09 +00004918/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
4919CanQualType ASTContext::getIntMaxType() const {
4920 return getFromTargetType(Target->getIntMaxType());
4921}
4922
4923/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
4924CanQualType ASTContext::getUIntMaxType() const {
4925 return getFromTargetType(Target->getUIntMaxType());
4926}
4927
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00004928/// getSignedWCharType - Return the type of "signed wchar_t".
4929/// Used when in C++, as a GCC extension.
4930QualType ASTContext::getSignedWCharType() const {
4931 // FIXME: derive from "Target" ?
4932 return WCharTy;
4933}
4934
4935/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
4936/// Used when in C++, as a GCC extension.
4937QualType ASTContext::getUnsignedWCharType() const {
4938 // FIXME: derive from "Target" ?
4939 return UnsignedIntTy;
4940}
4941
Enea Zaffanellaf11ceb62013-01-26 17:08:37 +00004942QualType ASTContext::getIntPtrType() const {
4943 return getFromTargetType(Target->getIntPtrType());
4944}
4945
4946QualType ASTContext::getUIntPtrType() const {
4947 return getCorrespondingUnsignedType(getIntPtrType());
4948}
4949
Hans Wennborg27541db2011-10-27 08:29:09 +00004950/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00004951/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
4952QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00004953 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00004954}
4955
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004956/// Return the unique unsigned counterpart of "ptrdiff_t"
Alexander Shaposhnikov195b25c2017-09-28 23:11:31 +00004957/// integer type. The standard (C11 7.21.6.1p7) refers to this type
4958/// in the definition of %tu format specifier.
4959QualType ASTContext::getUnsignedPointerDiffType() const {
4960 return getFromTargetType(Target->getUnsignedPtrDiffType(0));
4961}
4962
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004963/// Return the unique type for "pid_t" defined in
Eli Friedman4e91899e2012-11-27 02:58:24 +00004964/// <sys/types.h>. We need this to compute the correct type for vfork().
4965QualType ASTContext::getProcessIDType() const {
4966 return getFromTargetType(Target->getProcessIDType());
4967}
4968
Chris Lattnera21ad802008-04-02 05:18:44 +00004969//===----------------------------------------------------------------------===//
4970// Type Operators
4971//===----------------------------------------------------------------------===//
4972
Jay Foad39c79802011-01-12 09:06:06 +00004973CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00004974 // Push qualifiers into arrays, and then discard any remaining
4975 // qualifiers.
4976 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00004977 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00004978 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00004979 QualType Result;
4980 if (isa<ArrayType>(Ty)) {
4981 Result = getArrayDecayedType(QualType(Ty,0));
4982 } else if (isa<FunctionType>(Ty)) {
4983 Result = getPointerType(QualType(Ty, 0));
4984 } else {
4985 Result = QualType(Ty, 0);
4986 }
4987
4988 return CanQualType::CreateUnsafe(Result);
4989}
4990
John McCall6c9dd522011-01-18 07:41:22 +00004991QualType ASTContext::getUnqualifiedArrayType(QualType type,
4992 Qualifiers &quals) {
4993 SplitQualType splitType = type.getSplitUnqualifiedType();
4994
4995 // FIXME: getSplitUnqualifiedType() actually walks all the way to
4996 // the unqualified desugared type and then drops it on the floor.
4997 // We then have to strip that sugar back off with
4998 // getUnqualifiedDesugaredType(), which is silly.
Eugene Zelenko7855e772018-04-03 00:11:50 +00004999 const auto *AT =
5000 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00005001
5002 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00005003 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00005004 quals = splitType.Quals;
5005 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00005006 }
5007
John McCall6c9dd522011-01-18 07:41:22 +00005008 // Otherwise, recurse on the array's element type.
5009 QualType elementType = AT->getElementType();
5010 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
5011
5012 // If that didn't change the element type, AT has no qualifiers, so we
5013 // can just use the results in splitType.
5014 if (elementType == unqualElementType) {
5015 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00005016 quals = splitType.Quals;
5017 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00005018 }
5019
5020 // Otherwise, add in the qualifiers from the outermost type, then
5021 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00005022 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00005023
Eugene Zelenko7855e772018-04-03 00:11:50 +00005024 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00005025 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00005026 CAT->getSizeModifier(), 0);
5027 }
5028
Eugene Zelenko7855e772018-04-03 00:11:50 +00005029 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00005030 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00005031 }
5032
Eugene Zelenko7855e772018-04-03 00:11:50 +00005033 if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00005034 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00005035 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00005036 VAT->getSizeModifier(),
5037 VAT->getIndexTypeCVRQualifiers(),
5038 VAT->getBracketsRange());
5039 }
5040
Eugene Zelenko7855e772018-04-03 00:11:50 +00005041 const auto *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00005042 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00005043 DSAT->getSizeModifier(), 0,
5044 SourceRange());
5045}
5046
Richard Smitha3405ff2018-07-11 00:19:19 +00005047/// Attempt to unwrap two types that may both be array types with the same bound
5048/// (or both be array types of unknown bound) for the purpose of comparing the
5049/// cv-decomposition of two types per C++ [conv.qual].
Richard Smith5407d4f2018-07-18 20:13:36 +00005050bool ASTContext::UnwrapSimilarArrayTypes(QualType &T1, QualType &T2) {
5051 bool UnwrappedAny = false;
Richard Smitha3405ff2018-07-11 00:19:19 +00005052 while (true) {
Richard Smith5407d4f2018-07-18 20:13:36 +00005053 auto *AT1 = getAsArrayType(T1);
5054 if (!AT1) return UnwrappedAny;
Richard Smitha3405ff2018-07-11 00:19:19 +00005055
Richard Smith5407d4f2018-07-18 20:13:36 +00005056 auto *AT2 = getAsArrayType(T2);
5057 if (!AT2) return UnwrappedAny;
Richard Smitha3405ff2018-07-11 00:19:19 +00005058
5059 // If we don't have two array types with the same constant bound nor two
5060 // incomplete array types, we've unwrapped everything we can.
5061 if (auto *CAT1 = dyn_cast<ConstantArrayType>(AT1)) {
5062 auto *CAT2 = dyn_cast<ConstantArrayType>(AT2);
5063 if (!CAT2 || CAT1->getSize() != CAT2->getSize())
Richard Smith5407d4f2018-07-18 20:13:36 +00005064 return UnwrappedAny;
Richard Smitha3405ff2018-07-11 00:19:19 +00005065 } else if (!isa<IncompleteArrayType>(AT1) ||
5066 !isa<IncompleteArrayType>(AT2)) {
Richard Smith5407d4f2018-07-18 20:13:36 +00005067 return UnwrappedAny;
Richard Smitha3405ff2018-07-11 00:19:19 +00005068 }
5069
5070 T1 = AT1->getElementType();
5071 T2 = AT2->getElementType();
Richard Smith5407d4f2018-07-18 20:13:36 +00005072 UnwrappedAny = true;
Richard Smitha3405ff2018-07-11 00:19:19 +00005073 }
5074}
5075
5076/// Attempt to unwrap two types that may be similar (C++ [conv.qual]).
5077///
5078/// If T1 and T2 are both pointer types of the same kind, or both array types
5079/// with the same bound, unwraps layers from T1 and T2 until a pointer type is
5080/// unwrapped. Top-level qualifiers on T1 and T2 are ignored.
5081///
5082/// This function will typically be called in a loop that successively
5083/// "unwraps" pointer and pointer-to-member types to compare them at each
5084/// level.
5085///
5086/// \return \c true if a pointer type was unwrapped, \c false if we reached a
5087/// pair of types that can't be unwrapped further.
5088bool ASTContext::UnwrapSimilarTypes(QualType &T1, QualType &T2) {
Richard Smith5407d4f2018-07-18 20:13:36 +00005089 UnwrapSimilarArrayTypes(T1, T2);
Richard Smitha3405ff2018-07-11 00:19:19 +00005090
Eugene Zelenko7855e772018-04-03 00:11:50 +00005091 const auto *T1PtrType = T1->getAs<PointerType>();
5092 const auto *T2PtrType = T2->getAs<PointerType>();
Douglas Gregor1fc3d662010-06-09 03:53:18 +00005093 if (T1PtrType && T2PtrType) {
5094 T1 = T1PtrType->getPointeeType();
5095 T2 = T2PtrType->getPointeeType();
5096 return true;
5097 }
Richard Smith5407d4f2018-07-18 20:13:36 +00005098
Eugene Zelenko7855e772018-04-03 00:11:50 +00005099 const auto *T1MPType = T1->getAs<MemberPointerType>();
5100 const auto *T2MPType = T2->getAs<MemberPointerType>();
Fangrui Song6907ce22018-07-30 19:24:48 +00005101 if (T1MPType && T2MPType &&
5102 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
Douglas Gregor1fc3d662010-06-09 03:53:18 +00005103 QualType(T2MPType->getClass(), 0))) {
5104 T1 = T1MPType->getPointeeType();
5105 T2 = T2MPType->getPointeeType();
5106 return true;
5107 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005108
David Blaikiebbafb8a2012-03-11 07:00:24 +00005109 if (getLangOpts().ObjC1) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00005110 const auto *T1OPType = T1->getAs<ObjCObjectPointerType>();
5111 const auto *T2OPType = T2->getAs<ObjCObjectPointerType>();
Douglas Gregor1fc3d662010-06-09 03:53:18 +00005112 if (T1OPType && T2OPType) {
5113 T1 = T1OPType->getPointeeType();
5114 T2 = T2OPType->getPointeeType();
5115 return true;
5116 }
5117 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005118
Douglas Gregor1fc3d662010-06-09 03:53:18 +00005119 // FIXME: Block pointers, too?
Fangrui Song6907ce22018-07-30 19:24:48 +00005120
Douglas Gregor1fc3d662010-06-09 03:53:18 +00005121 return false;
5122}
5123
Richard Smitha3405ff2018-07-11 00:19:19 +00005124bool ASTContext::hasSimilarType(QualType T1, QualType T2) {
5125 while (true) {
5126 Qualifiers Quals;
5127 T1 = getUnqualifiedArrayType(T1, Quals);
5128 T2 = getUnqualifiedArrayType(T2, Quals);
5129 if (hasSameType(T1, T2))
5130 return true;
5131 if (!UnwrapSimilarTypes(T1, T2))
5132 return false;
5133 }
5134}
5135
5136bool ASTContext::hasCvrSimilarType(QualType T1, QualType T2) {
5137 while (true) {
5138 Qualifiers Quals1, Quals2;
5139 T1 = getUnqualifiedArrayType(T1, Quals1);
5140 T2 = getUnqualifiedArrayType(T2, Quals2);
5141
5142 Quals1.removeCVRQualifiers();
5143 Quals2.removeCVRQualifiers();
5144 if (Quals1 != Quals2)
5145 return false;
5146
5147 if (hasSameType(T1, T2))
5148 return true;
5149
5150 if (!UnwrapSimilarTypes(T1, T2))
5151 return false;
5152 }
5153}
5154
Jay Foad39c79802011-01-12 09:06:06 +00005155DeclarationNameInfo
5156ASTContext::getNameForTemplate(TemplateName Name,
5157 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00005158 switch (Name.getKind()) {
5159 case TemplateName::QualifiedTemplate:
5160 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005161 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00005162 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
5163 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005164
John McCalld9dfe3a2011-06-30 08:33:18 +00005165 case TemplateName::OverloadedTemplate: {
5166 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
5167 // DNInfo work in progress: CHECKME: what about DNLoc?
5168 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
5169 }
5170
5171 case TemplateName::DependentTemplate: {
5172 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005173 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00005174 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005175 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
5176 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00005177 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005178 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
5179 // DNInfo work in progress: FIXME: source locations?
5180 DeclarationNameLoc DNLoc;
5181 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
5182 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
5183 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00005184 }
5185 }
5186
John McCalld9dfe3a2011-06-30 08:33:18 +00005187 case TemplateName::SubstTemplateTemplateParm: {
5188 SubstTemplateTemplateParmStorage *subst
5189 = Name.getAsSubstTemplateTemplateParm();
5190 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
5191 NameLoc);
5192 }
5193
5194 case TemplateName::SubstTemplateTemplateParmPack: {
5195 SubstTemplateTemplateParmPackStorage *subst
5196 = Name.getAsSubstTemplateTemplateParmPack();
5197 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
5198 NameLoc);
5199 }
5200 }
5201
5202 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00005203}
5204
Jay Foad39c79802011-01-12 09:06:06 +00005205TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00005206 switch (Name.getKind()) {
5207 case TemplateName::QualifiedTemplate:
5208 case TemplateName::Template: {
5209 TemplateDecl *Template = Name.getAsTemplateDecl();
Eugene Zelenko7855e772018-04-03 00:11:50 +00005210 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00005211 Template = getCanonicalTemplateTemplateParmDecl(TTP);
Fangrui Song6907ce22018-07-30 19:24:48 +00005212
Douglas Gregor7dbfb462010-06-16 21:09:37 +00005213 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00005214 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00005215 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00005216
John McCalld9dfe3a2011-06-30 08:33:18 +00005217 case TemplateName::OverloadedTemplate:
5218 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00005219
John McCalld9dfe3a2011-06-30 08:33:18 +00005220 case TemplateName::DependentTemplate: {
5221 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
5222 assert(DTN && "Non-dependent template names must refer to template decls.");
5223 return DTN->CanonicalTemplateName;
5224 }
5225
5226 case TemplateName::SubstTemplateTemplateParm: {
5227 SubstTemplateTemplateParmStorage *subst
5228 = Name.getAsSubstTemplateTemplateParm();
5229 return getCanonicalTemplateName(subst->getReplacement());
5230 }
5231
5232 case TemplateName::SubstTemplateTemplateParmPack: {
5233 SubstTemplateTemplateParmPackStorage *subst
5234 = Name.getAsSubstTemplateTemplateParmPack();
5235 TemplateTemplateParmDecl *canonParameter
5236 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
5237 TemplateArgument canonArgPack
5238 = getCanonicalTemplateArgument(subst->getArgumentPack());
5239 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
5240 }
5241 }
5242
5243 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00005244}
5245
Douglas Gregoradee3e32009-11-11 23:06:43 +00005246bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
5247 X = getCanonicalTemplateName(X);
5248 Y = getCanonicalTemplateName(Y);
5249 return X.getAsVoidPointer() == Y.getAsVoidPointer();
5250}
5251
Mike Stump11289f42009-09-09 15:08:12 +00005252TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00005253ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00005254 switch (Arg.getKind()) {
5255 case TemplateArgument::Null:
5256 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00005257
Douglas Gregora8e02e72009-07-28 23:00:59 +00005258 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00005259 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00005260
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005261 case TemplateArgument::Declaration: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00005262 auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
David Blaikie952a9b12014-10-17 18:00:12 +00005263 return TemplateArgument(D, Arg.getParamTypeForDecl());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005264 }
Mike Stump11289f42009-09-09 15:08:12 +00005265
Eli Friedmanb826a002012-09-26 02:36:12 +00005266 case TemplateArgument::NullPtr:
5267 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
5268 /*isNullPtr*/true);
5269
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005270 case TemplateArgument::Template:
5271 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005272
5273 case TemplateArgument::TemplateExpansion:
5274 return TemplateArgument(getCanonicalTemplateName(
5275 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00005276 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005277
Douglas Gregora8e02e72009-07-28 23:00:59 +00005278 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00005279 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00005280
Douglas Gregora8e02e72009-07-28 23:00:59 +00005281 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00005282 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00005283
Douglas Gregora8e02e72009-07-28 23:00:59 +00005284 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00005285 if (Arg.pack_size() == 0)
5286 return Arg;
Fangrui Song6907ce22018-07-30 19:24:48 +00005287
Eugene Zelenko7855e772018-04-03 00:11:50 +00005288 auto *CanonArgs = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00005289 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00005290 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00005291 AEnd = Arg.pack_end();
5292 A != AEnd; (void)++A, ++Idx)
5293 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00005294
Benjamin Kramercce63472015-08-05 09:40:22 +00005295 return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size()));
Douglas Gregora8e02e72009-07-28 23:00:59 +00005296 }
5297 }
5298
5299 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00005300 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00005301}
5302
Douglas Gregor333489b2009-03-27 23:10:48 +00005303NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00005304ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00005305 if (!NNS)
Craig Topper36250ad2014-05-12 05:36:57 +00005306 return nullptr;
Douglas Gregor333489b2009-03-27 23:10:48 +00005307
5308 switch (NNS->getKind()) {
5309 case NestedNameSpecifier::Identifier:
5310 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00005311 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00005312 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
5313 NNS->getAsIdentifier());
5314
5315 case NestedNameSpecifier::Namespace:
5316 // A namespace is canonical; build a nested-name-specifier with
5317 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00005318 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00005319 NNS->getAsNamespace()->getOriginalNamespace());
5320
5321 case NestedNameSpecifier::NamespaceAlias:
5322 // A namespace is canonical; build a nested-name-specifier with
5323 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00005324 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00005325 NNS->getAsNamespaceAlias()->getNamespace()
5326 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00005327
5328 case NestedNameSpecifier::TypeSpec:
5329 case NestedNameSpecifier::TypeSpecWithTemplate: {
5330 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Fangrui Song6907ce22018-07-30 19:24:48 +00005331
Douglas Gregor3ade5702010-11-04 00:09:33 +00005332 // If we have some kind of dependent-named type (e.g., "typename T::type"),
5333 // break it apart into its prefix and identifier, then reconsititute those
5334 // as the canonical nested-name-specifier. This is required to canonicalize
5335 // a dependent nested-name-specifier involving typedefs of dependent-name
5336 // types, e.g.,
5337 // typedef typename T::type T1;
5338 // typedef typename T1::type T2;
Eugene Zelenko7855e772018-04-03 00:11:50 +00005339 if (const auto *DNT = T->getAs<DependentNameType>())
Fangrui Song6907ce22018-07-30 19:24:48 +00005340 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00005341 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00005342
Eli Friedman5358a0a2012-03-03 04:09:56 +00005343 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
5344 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
5345 // first place?
Craig Topper36250ad2014-05-12 05:36:57 +00005346 return NestedNameSpecifier::Create(*this, nullptr, false,
5347 const_cast<Type *>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00005348 }
5349
5350 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00005351 case NestedNameSpecifier::Super:
5352 // The global specifier and __super specifer are canonical and unique.
Douglas Gregor333489b2009-03-27 23:10:48 +00005353 return NNS;
5354 }
5355
David Blaikie8a40f702012-01-17 06:56:22 +00005356 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00005357}
5358
Jay Foad39c79802011-01-12 09:06:06 +00005359const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00005360 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005361 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00005362 // Handle the common positive case fast.
Eugene Zelenko7855e772018-04-03 00:11:50 +00005363 if (const auto *AT = dyn_cast<ArrayType>(T))
Chris Lattner7adf0762008-08-04 07:31:14 +00005364 return AT;
5365 }
Mike Stump11289f42009-09-09 15:08:12 +00005366
John McCall8ccfcb52009-09-24 19:53:00 +00005367 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00005368 if (!isa<ArrayType>(T.getCanonicalType()))
Craig Topper36250ad2014-05-12 05:36:57 +00005369 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00005370
John McCall8ccfcb52009-09-24 19:53:00 +00005371 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00005372 // implements C99 6.7.3p8: "If the specification of an array type includes
5373 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00005374
Chris Lattner7adf0762008-08-04 07:31:14 +00005375 // If we get here, we either have type qualifiers on the type, or we have
5376 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00005377 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00005378
John McCall33ddac02011-01-19 10:06:00 +00005379 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00005380 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00005381
Chris Lattner7adf0762008-08-04 07:31:14 +00005382 // If we have a simple case, just return now.
Eugene Zelenko7855e772018-04-03 00:11:50 +00005383 const auto *ATy = dyn_cast<ArrayType>(split.Ty);
Craig Topper36250ad2014-05-12 05:36:57 +00005384 if (!ATy || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00005385 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00005386
Chris Lattner7adf0762008-08-04 07:31:14 +00005387 // Otherwise, we have an array and we have qualifiers on it. Push the
5388 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00005389 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00005390
Eugene Zelenko7855e772018-04-03 00:11:50 +00005391 if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy))
Chris Lattner7adf0762008-08-04 07:31:14 +00005392 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
5393 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00005394 CAT->getIndexTypeCVRQualifiers()));
Eugene Zelenko7855e772018-04-03 00:11:50 +00005395 if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy))
Chris Lattner7adf0762008-08-04 07:31:14 +00005396 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
5397 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00005398 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00005399
Eugene Zelenko7855e772018-04-03 00:11:50 +00005400 if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy))
Douglas Gregor4619e432008-12-05 23:32:09 +00005401 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00005402 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00005403 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00005404 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00005405 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00005406 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00005407
Eugene Zelenko7855e772018-04-03 00:11:50 +00005408 const auto *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00005409 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00005410 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00005411 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00005412 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00005413 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00005414}
5415
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00005416QualType ASTContext::getAdjustedParameterType(QualType T) const {
Reid Kleckner8a365022013-06-24 17:51:48 +00005417 if (T->isArrayType() || T->isFunctionType())
5418 return getDecayedType(T);
5419 return T;
Douglas Gregor84280642011-07-12 04:42:08 +00005420}
5421
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00005422QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00005423 T = getVariableArrayDecayedType(T);
5424 T = getAdjustedParameterType(T);
5425 return T.getUnqualifiedType();
5426}
5427
David Majnemerd09a51c2015-03-03 01:50:05 +00005428QualType ASTContext::getExceptionObjectType(QualType T) const {
5429 // C++ [except.throw]p3:
5430 // A throw-expression initializes a temporary object, called the exception
5431 // object, the type of which is determined by removing any top-level
5432 // cv-qualifiers from the static type of the operand of throw and adjusting
5433 // the type from "array of T" or "function returning T" to "pointer to T"
5434 // or "pointer to function returning T", [...]
5435 T = getVariableArrayDecayedType(T);
5436 if (T->isArrayType() || T->isFunctionType())
5437 T = getDecayedType(T);
5438 return T.getUnqualifiedType();
5439}
5440
Chris Lattnera21ad802008-04-02 05:18:44 +00005441/// getArrayDecayedType - Return the properly qualified result of decaying the
5442/// specified array type to a pointer. This operation is non-trivial when
5443/// handling typedefs etc. The canonical type of "T" must be an array type,
5444/// this returns a pointer to a properly qualified element of the array.
5445///
5446/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00005447QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00005448 // Get the element type with 'getAsArrayType' so that we don't lose any
5449 // typedefs in the element type of the array. This also handles propagation
5450 // of type qualifiers from the array type into the element type if present
5451 // (C99 6.7.3p8).
5452 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
5453 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00005454
Chris Lattner7adf0762008-08-04 07:31:14 +00005455 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00005456
5457 // int x[restrict 4] -> int *restrict
Jordan Rose303e2f12016-11-10 23:28:17 +00005458 QualType Result = getQualifiedType(PtrTy,
5459 PrettyArrayType->getIndexTypeQualifiers());
5460
5461 // int x[_Nullable] -> int * _Nullable
5462 if (auto Nullability = Ty->getNullability(*this)) {
5463 Result = const_cast<ASTContext *>(this)->getAttributedType(
5464 AttributedType::getNullabilityAttrKind(*Nullability), Result, Result);
5465 }
5466 return Result;
Chris Lattnera21ad802008-04-02 05:18:44 +00005467}
5468
John McCall33ddac02011-01-19 10:06:00 +00005469QualType ASTContext::getBaseElementType(const ArrayType *array) const {
5470 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00005471}
5472
John McCall33ddac02011-01-19 10:06:00 +00005473QualType ASTContext::getBaseElementType(QualType type) const {
5474 Qualifiers qs;
5475 while (true) {
5476 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00005477 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00005478 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00005479
John McCall33ddac02011-01-19 10:06:00 +00005480 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00005481 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00005482 }
Mike Stump11289f42009-09-09 15:08:12 +00005483
John McCall33ddac02011-01-19 10:06:00 +00005484 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00005485}
5486
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00005487/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00005488uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00005489ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
5490 uint64_t ElementCount = 1;
5491 do {
5492 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00005493 CA = dyn_cast_or_null<ConstantArrayType>(
5494 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00005495 } while (CA);
5496 return ElementCount;
5497}
5498
Steve Naroff0af91202007-04-27 21:51:21 +00005499/// getFloatingRank - Return a relative rank for floating point types.
5500/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00005501static FloatingRank getFloatingRank(QualType T) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00005502 if (const auto *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00005503 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00005504
John McCall9dd450b2009-09-21 23:43:11 +00005505 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
5506 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00005507 default: llvm_unreachable("getFloatingRank(): not a floating type");
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00005508 case BuiltinType::Float16: return Float16Rank;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00005509 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00005510 case BuiltinType::Float: return FloatRank;
5511 case BuiltinType::Double: return DoubleRank;
5512 case BuiltinType::LongDouble: return LongDoubleRank;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005513 case BuiltinType::Float128: return Float128Rank;
Steve Naroffe4718892007-04-27 18:30:00 +00005514 }
5515}
5516
Mike Stump11289f42009-09-09 15:08:12 +00005517/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
5518/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00005519/// 'typeDomain' is a real floating point or complex type.
5520/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00005521QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
5522 QualType Domain) const {
5523 FloatingRank EltRank = getFloatingRank(Size);
5524 if (Domain->isComplexType()) {
5525 switch (EltRank) {
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00005526 case Float16Rank:
David Blaikief47fa302012-01-17 02:30:50 +00005527 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00005528 case FloatRank: return FloatComplexTy;
5529 case DoubleRank: return DoubleComplexTy;
5530 case LongDoubleRank: return LongDoubleComplexTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005531 case Float128Rank: return Float128ComplexTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00005532 }
Steve Naroff0af91202007-04-27 21:51:21 +00005533 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00005534
5535 assert(Domain->isRealFloatingType() && "Unknown domain!");
5536 switch (EltRank) {
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00005537 case Float16Rank: return HalfTy;
Joey Goulydd7f4562013-01-23 11:56:20 +00005538 case HalfRank: return HalfTy;
Chris Lattnerb9dfb032008-04-06 23:58:54 +00005539 case FloatRank: return FloatTy;
5540 case DoubleRank: return DoubleTy;
5541 case LongDoubleRank: return LongDoubleTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005542 case Float128Rank: return Float128Ty;
Steve Naroff9091ef72007-08-27 01:27:54 +00005543 }
David Blaikief47fa302012-01-17 02:30:50 +00005544 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00005545}
5546
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005547/// getFloatingTypeOrder - Compare the rank of the two specified floating
5548/// point types, ignoring the domain of the type (i.e. 'double' ==
5549/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00005550/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00005551int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00005552 FloatingRank LHSR = getFloatingRank(LHS);
5553 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00005554
Chris Lattnerb90739d2008-04-06 23:38:49 +00005555 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00005556 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00005557 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00005558 return 1;
5559 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00005560}
5561
Chris Lattner76a00cf2008-04-06 22:59:24 +00005562/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
5563/// routine will assert if passed a built-in type that isn't an integer or enum,
5564/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00005565unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00005566 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00005567
Chris Lattner76a00cf2008-04-06 22:59:24 +00005568 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00005569 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005570 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005571 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005572 case BuiltinType::Char_S:
5573 case BuiltinType::Char_U:
5574 case BuiltinType::SChar:
5575 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005576 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005577 case BuiltinType::Short:
5578 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005579 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005580 case BuiltinType::Int:
5581 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005582 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005583 case BuiltinType::Long:
5584 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005585 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005586 case BuiltinType::LongLong:
5587 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005588 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00005589 case BuiltinType::Int128:
5590 case BuiltinType::UInt128:
5591 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00005592 }
5593}
5594
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005595/// Whether this is a promotable bitfield reference according
Eli Friedman629ffb92009-08-20 04:21:42 +00005596/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
5597///
5598/// \returns the type this bit-field will promote to, or NULL if no
5599/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00005600QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00005601 if (E->isTypeDependent() || E->isValueDependent())
Eugene Zelenko7855e772018-04-03 00:11:50 +00005602 return {};
Richard Smith5b571672014-09-24 23:55:00 +00005603
Richard Smithaadb2542018-06-28 21:17:55 +00005604 // C++ [conv.prom]p5:
5605 // If the bit-field has an enumerated type, it is treated as any other
5606 // value of that type for promotion purposes.
5607 if (getLangOpts().CPlusPlus && E->getType()->isEnumeralType())
5608 return {};
5609
Richard Smith5b571672014-09-24 23:55:00 +00005610 // FIXME: We should not do this unless E->refersToBitField() is true. This
5611 // matters in C where getSourceBitField() will find bit-fields for various
5612 // cases where the source expression is not a bit-field designator.
5613
John McCalld25db7e2013-05-06 21:39:12 +00005614 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman629ffb92009-08-20 04:21:42 +00005615 if (!Field)
Eugene Zelenko7855e772018-04-03 00:11:50 +00005616 return {};
Eli Friedman629ffb92009-08-20 04:21:42 +00005617
5618 QualType FT = Field->getType();
5619
Richard Smithcaf33902011-10-10 18:28:20 +00005620 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00005621 uint64_t IntSize = getTypeSize(IntTy);
Richard Smith5b571672014-09-24 23:55:00 +00005622 // C++ [conv.prom]p5:
5623 // A prvalue for an integral bit-field can be converted to a prvalue of type
5624 // int if int can represent all the values of the bit-field; otherwise, it
5625 // can be converted to unsigned int if unsigned int can represent all the
5626 // values of the bit-field. If the bit-field is larger yet, no integral
5627 // promotion applies to it.
5628 // C11 6.3.1.1/2:
5629 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
5630 // If an int can represent all values of the original type (as restricted by
5631 // the width, for a bit-field), the value is converted to an int; otherwise,
5632 // it is converted to an unsigned int.
5633 //
5634 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
5635 // We perform that promotion here to match GCC and C++.
Richard Smithaadb2542018-06-28 21:17:55 +00005636 // FIXME: C does not permit promotion of an enum bit-field whose rank is
5637 // greater than that of 'int'. We perform that promotion to match GCC.
Eli Friedman629ffb92009-08-20 04:21:42 +00005638 if (BitWidth < IntSize)
5639 return IntTy;
5640
5641 if (BitWidth == IntSize)
5642 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
5643
Richard Smithaadb2542018-06-28 21:17:55 +00005644 // Bit-fields wider than int are not subject to promotions, and therefore act
Richard Smith5b571672014-09-24 23:55:00 +00005645 // like the base type. GCC has some weird bugs in this area that we
5646 // deliberately do not follow (GCC follows a pre-standard resolution to
5647 // C's DR315 which treats bit-width as being part of the type, and this leaks
5648 // into their semantics in some cases).
Eugene Zelenko7855e772018-04-03 00:11:50 +00005649 return {};
Eli Friedman629ffb92009-08-20 04:21:42 +00005650}
5651
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005652/// getPromotedIntegerType - Returns the type that Promotable will
5653/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
5654/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00005655QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005656 assert(!Promotable.isNull());
5657 assert(Promotable->isPromotableIntegerType());
Eugene Zelenko7855e772018-04-03 00:11:50 +00005658 if (const auto *ET = Promotable->getAs<EnumType>())
John McCall56774992009-12-09 09:09:27 +00005659 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00005660
Eugene Zelenko7855e772018-04-03 00:11:50 +00005661 if (const auto *BT = Promotable->getAs<BuiltinType>()) {
Eli Friedman3f37c1c2011-10-26 07:22:48 +00005662 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
5663 // (3.9.1) can be converted to a prvalue of the first of the following
5664 // types that can represent all the values of its underlying type:
5665 // int, unsigned int, long int, unsigned long int, long long int, or
5666 // unsigned long long int [...]
5667 // FIXME: Is there some better way to compute this?
5668 if (BT->getKind() == BuiltinType::WChar_S ||
5669 BT->getKind() == BuiltinType::WChar_U ||
Richard Smith3a8244d2018-05-01 05:02:45 +00005670 BT->getKind() == BuiltinType::Char8 ||
Eli Friedman3f37c1c2011-10-26 07:22:48 +00005671 BT->getKind() == BuiltinType::Char16 ||
5672 BT->getKind() == BuiltinType::Char32) {
5673 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
5674 uint64_t FromSize = getTypeSize(BT);
5675 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
5676 LongLongTy, UnsignedLongLongTy };
5677 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
5678 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
5679 if (FromSize < ToSize ||
5680 (FromSize == ToSize &&
5681 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
5682 return PromoteTypes[Idx];
5683 }
5684 llvm_unreachable("char type should fit into long long");
5685 }
5686 }
5687
5688 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005689 if (Promotable->isSignedIntegerType())
5690 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00005691 uint64_t PromotableSize = getIntWidth(Promotable);
5692 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005693 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
5694 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
5695}
5696
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005697/// Recurses in pointer/array types until it finds an objc retainable
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00005698/// type and returns its ownership.
5699Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
5700 while (!T.isNull()) {
5701 if (T.getObjCLifetime() != Qualifiers::OCL_None)
5702 return T.getObjCLifetime();
5703 if (T->isArrayType())
5704 T = getBaseElementType(T);
Eugene Zelenko7855e772018-04-03 00:11:50 +00005705 else if (const auto *PT = T->getAs<PointerType>())
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00005706 T = PT->getPointeeType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00005707 else if (const auto *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00005708 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00005709 else
5710 break;
5711 }
5712
5713 return Qualifiers::OCL_None;
5714}
5715
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005716static const Type *getIntegerTypeForEnum(const EnumType *ET) {
5717 // Incomplete enum types are not treated as integer types.
5718 // FIXME: In C++, enum types are never integer types.
5719 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
5720 return ET->getDecl()->getIntegerType().getTypePtr();
Craig Topper36250ad2014-05-12 05:36:57 +00005721 return nullptr;
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005722}
5723
Mike Stump11289f42009-09-09 15:08:12 +00005724/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005725/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00005726/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00005727int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00005728 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
5729 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005730
5731 // Unwrap enums to their underlying type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00005732 if (const auto *ET = dyn_cast<EnumType>(LHSC))
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005733 LHSC = getIntegerTypeForEnum(ET);
Eugene Zelenko7855e772018-04-03 00:11:50 +00005734 if (const auto *ET = dyn_cast<EnumType>(RHSC))
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005735 RHSC = getIntegerTypeForEnum(ET);
5736
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005737 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00005738
Chris Lattner76a00cf2008-04-06 22:59:24 +00005739 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
5740 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00005741
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005742 unsigned LHSRank = getIntegerRank(LHSC);
5743 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00005744
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005745 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
5746 if (LHSRank == RHSRank) return 0;
5747 return LHSRank > RHSRank ? 1 : -1;
5748 }
Mike Stump11289f42009-09-09 15:08:12 +00005749
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005750 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
5751 if (LHSUnsigned) {
5752 // If the unsigned [LHS] type is larger, return it.
5753 if (LHSRank >= RHSRank)
5754 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00005755
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005756 // If the signed type can represent all values of the unsigned type, it
5757 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00005758 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005759 return -1;
5760 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00005761
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005762 // If the unsigned [RHS] type is larger, return it.
5763 if (RHSRank >= LHSRank)
5764 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00005765
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005766 // If the signed type can represent all values of the unsigned type, it
5767 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00005768 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005769 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00005770}
Anders Carlsson98f07902007-08-17 05:31:46 +00005771
Ben Langmuirf5416742016-02-04 00:55:24 +00005772TypedefDecl *ASTContext::getCFConstantStringDecl() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00005773 if (!CFConstantStringTypeDecl) {
Ben Langmuirf5416742016-02-04 00:55:24 +00005774 assert(!CFConstantStringTagDecl &&
5775 "tag and typedef should be initialized together");
5776 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
5777 CFConstantStringTagDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00005778
Anders Carlsson9c1011c2007-11-19 00:25:30 +00005779 QualType FieldTypes[4];
Ben Langmuir4791a802016-02-25 16:36:26 +00005780 const char *FieldNames[4];
Mike Stump11289f42009-09-09 15:08:12 +00005781
Anders Carlsson98f07902007-08-17 05:31:46 +00005782 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00005783 FieldTypes[0] = getPointerType(IntTy.withConst());
Ben Langmuir4791a802016-02-25 16:36:26 +00005784 FieldNames[0] = "isa";
Anders Carlsson9c1011c2007-11-19 00:25:30 +00005785 // int flags;
5786 FieldTypes[1] = IntTy;
Ben Langmuir4791a802016-02-25 16:36:26 +00005787 FieldNames[1] = "flags";
Anders Carlsson98f07902007-08-17 05:31:46 +00005788 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00005789 FieldTypes[2] = getPointerType(CharTy.withConst());
Ben Langmuir4791a802016-02-25 16:36:26 +00005790 FieldNames[2] = "str";
Anders Carlsson98f07902007-08-17 05:31:46 +00005791 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00005792 FieldTypes[3] = LongTy;
Ben Langmuir4791a802016-02-25 16:36:26 +00005793 FieldNames[3] = "length";
Mike Stump11289f42009-09-09 15:08:12 +00005794
Anders Carlsson98f07902007-08-17 05:31:46 +00005795 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00005796 for (unsigned i = 0; i < 4; ++i) {
Ben Langmuirf5416742016-02-04 00:55:24 +00005797 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTagDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00005798 SourceLocation(),
Ben Langmuir4791a802016-02-25 16:36:26 +00005799 SourceLocation(),
5800 &Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00005801 FieldTypes[i], /*TInfo=*/nullptr,
5802 /*BitWidth=*/nullptr,
Richard Smith938f40b2011-06-11 17:19:42 +00005803 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00005804 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00005805 Field->setAccess(AS_public);
Ben Langmuirf5416742016-02-04 00:55:24 +00005806 CFConstantStringTagDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00005807 }
5808
Ben Langmuirf5416742016-02-04 00:55:24 +00005809 CFConstantStringTagDecl->completeDefinition();
5810 // This type is designed to be compatible with NSConstantString, but cannot
5811 // use the same name, since NSConstantString is an interface.
5812 auto tagType = getTagDeclType(CFConstantStringTagDecl);
5813 CFConstantStringTypeDecl =
5814 buildImplicitTypedef(tagType, "__NSConstantString");
Anders Carlsson98f07902007-08-17 05:31:46 +00005815 }
Mike Stump11289f42009-09-09 15:08:12 +00005816
Quentin Colombet043406b2016-02-03 22:41:00 +00005817 return CFConstantStringTypeDecl;
5818}
5819
Ben Langmuirf5416742016-02-04 00:55:24 +00005820RecordDecl *ASTContext::getCFConstantStringTagDecl() const {
5821 if (!CFConstantStringTagDecl)
5822 getCFConstantStringDecl(); // Build the tag and the typedef.
5823 return CFConstantStringTagDecl;
5824}
5825
Quentin Colombet043406b2016-02-03 22:41:00 +00005826// getCFConstantStringType - Return the type used for constant CFStrings.
5827QualType ASTContext::getCFConstantStringType() const {
Ben Langmuirf5416742016-02-04 00:55:24 +00005828 return getTypedefType(getCFConstantStringDecl());
Gabor Greif412af032007-09-11 15:32:40 +00005829}
Anders Carlsson87c149b2007-10-11 01:00:40 +00005830
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00005831QualType ASTContext::getObjCSuperType() const {
5832 if (ObjCSuperType.isNull()) {
Alp Toker2dea15b2013-12-17 01:22:38 +00005833 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00005834 TUDecl->addDecl(ObjCSuperTypeDecl);
5835 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
5836 }
5837 return ObjCSuperType;
5838}
5839
Douglas Gregor512b0772009-04-23 22:29:11 +00005840void ASTContext::setCFConstantStringType(QualType T) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00005841 const auto *TD = T->getAs<TypedefType>();
Ben Langmuirf5416742016-02-04 00:55:24 +00005842 assert(TD && "Invalid CFConstantStringType");
5843 CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl());
Eugene Zelenko7855e772018-04-03 00:11:50 +00005844 const auto *TagType =
Ben Langmuirf5416742016-02-04 00:55:24 +00005845 CFConstantStringTypeDecl->getUnderlyingType()->getAs<RecordType>();
5846 assert(TagType && "Invalid CFConstantStringType");
5847 CFConstantStringTagDecl = TagType->getDecl();
Douglas Gregor512b0772009-04-23 22:29:11 +00005848}
5849
Jay Foad39c79802011-01-12 09:06:06 +00005850QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00005851 if (BlockDescriptorType)
5852 return getTagDeclType(BlockDescriptorType);
5853
Alp Toker2dea15b2013-12-17 01:22:38 +00005854 RecordDecl *RD;
Mike Stumpd0153282009-10-20 02:12:22 +00005855 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00005856 RD = buildImplicitRecord("__block_descriptor");
5857 RD->startDefinition();
5858
Mike Stumpd0153282009-10-20 02:12:22 +00005859 QualType FieldTypes[] = {
5860 UnsignedLongTy,
5861 UnsignedLongTy,
5862 };
5863
Craig Topperd6d31ac2013-07-15 08:24:27 +00005864 static const char *const FieldNames[] = {
Mike Stumpd0153282009-10-20 02:12:22 +00005865 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005866 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00005867 };
5868
5869 for (size_t i = 0; i < 2; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00005870 FieldDecl *Field = FieldDecl::Create(
5871 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00005872 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
5873 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00005874 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00005875 RD->addDecl(Field);
Mike Stumpd0153282009-10-20 02:12:22 +00005876 }
5877
Alp Toker2dea15b2013-12-17 01:22:38 +00005878 RD->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00005879
Alp Toker2dea15b2013-12-17 01:22:38 +00005880 BlockDescriptorType = RD;
Mike Stumpd0153282009-10-20 02:12:22 +00005881
5882 return getTagDeclType(BlockDescriptorType);
5883}
5884
Jay Foad39c79802011-01-12 09:06:06 +00005885QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005886 if (BlockDescriptorExtendedType)
5887 return getTagDeclType(BlockDescriptorExtendedType);
5888
Alp Toker2dea15b2013-12-17 01:22:38 +00005889 RecordDecl *RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005890 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00005891 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
5892 RD->startDefinition();
5893
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005894 QualType FieldTypes[] = {
5895 UnsignedLongTy,
5896 UnsignedLongTy,
5897 getPointerType(VoidPtrTy),
5898 getPointerType(VoidPtrTy)
5899 };
5900
Craig Topperd6d31ac2013-07-15 08:24:27 +00005901 static const char *const FieldNames[] = {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005902 "reserved",
5903 "Size",
5904 "CopyFuncPtr",
5905 "DestroyFuncPtr"
5906 };
5907
5908 for (size_t i = 0; i < 4; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00005909 FieldDecl *Field = FieldDecl::Create(
5910 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00005911 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
5912 /*BitWidth=*/nullptr,
Alp Toker2dea15b2013-12-17 01:22:38 +00005913 /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00005914 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00005915 RD->addDecl(Field);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005916 }
5917
Alp Toker2dea15b2013-12-17 01:22:38 +00005918 RD->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005919
Alp Toker2dea15b2013-12-17 01:22:38 +00005920 BlockDescriptorExtendedType = RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005921 return getTagDeclType(BlockDescriptorExtendedType);
5922}
5923
Sven van Haastregt3bb7eaf2017-12-06 10:11:28 +00005924TargetInfo::OpenCLTypeKind ASTContext::getOpenCLTypeKind(const Type *T) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00005925 const auto *BT = dyn_cast<BuiltinType>(T);
Sven van Haastregt3bb7eaf2017-12-06 10:11:28 +00005926
5927 if (!BT) {
5928 if (isa<PipeType>(T))
5929 return TargetInfo::OCLTK_Pipe;
5930
5931 return TargetInfo::OCLTK_Default;
5932 }
5933
5934 switch (BT->getKind()) {
5935#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5936 case BuiltinType::Id: \
5937 return TargetInfo::OCLTK_Image;
5938#include "clang/Basic/OpenCLImageTypes.def"
5939
5940 case BuiltinType::OCLClkEvent:
5941 return TargetInfo::OCLTK_ClkEvent;
5942
5943 case BuiltinType::OCLEvent:
5944 return TargetInfo::OCLTK_Event;
5945
5946 case BuiltinType::OCLQueue:
5947 return TargetInfo::OCLTK_Queue;
5948
5949 case BuiltinType::OCLReserveID:
5950 return TargetInfo::OCLTK_ReserveID;
5951
5952 case BuiltinType::OCLSampler:
5953 return TargetInfo::OCLTK_Sampler;
5954
5955 default:
5956 return TargetInfo::OCLTK_Default;
5957 }
5958}
5959
5960LangAS ASTContext::getOpenCLTypeAddrSpace(const Type *T) const {
5961 return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
5962}
5963
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005964/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
5965/// requires copy/dispose. Note that this must match the logic
5966/// in buildByrefHelpers.
5967bool ASTContext::BlockRequiresCopying(QualType Ty,
5968 const VarDecl *D) {
5969 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
Akira Hatanaka9978da32018-08-10 15:09:24 +00005970 const Expr *copyExpr = getBlockVarCopyInit(D).getCopyExpr();
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005971 if (!copyExpr && record->hasTrivialDestructor()) return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00005972
Mike Stump94967902009-10-21 18:16:27 +00005973 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00005974 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005975
Akira Hatanaka7275da02018-02-28 07:15:55 +00005976 // The block needs copy/destroy helpers if Ty is non-trivial to destructively
5977 // move or destroy.
5978 if (Ty.isNonTrivialToPrimitiveDestructiveMove() || Ty.isDestructedType())
5979 return true;
5980
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005981 if (!Ty->isObjCRetainableType()) return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00005982
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005983 Qualifiers qs = Ty.getQualifiers();
Fangrui Song6907ce22018-07-30 19:24:48 +00005984
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005985 // If we have lifetime, that dominates.
5986 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005987 switch (lifetime) {
5988 case Qualifiers::OCL_None: llvm_unreachable("impossible");
Fangrui Song6907ce22018-07-30 19:24:48 +00005989
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005990 // These are just bits as far as the runtime is concerned.
5991 case Qualifiers::OCL_ExplicitNone:
5992 case Qualifiers::OCL_Autoreleasing:
5993 return false;
Akira Hatanaka7275da02018-02-28 07:15:55 +00005994
5995 // These cases should have been taken care of when checking the type's
5996 // non-triviality.
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005997 case Qualifiers::OCL_Weak:
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005998 case Qualifiers::OCL_Strong:
Akira Hatanaka7275da02018-02-28 07:15:55 +00005999 llvm_unreachable("impossible");
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006000 }
6001 llvm_unreachable("fell out of lifetime switch!");
6002 }
6003 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
6004 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00006005}
6006
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006007bool ASTContext::getByrefLifetime(QualType Ty,
6008 Qualifiers::ObjCLifetime &LifeTime,
6009 bool &HasByrefExtendedLayout) const {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006010 if (!getLangOpts().ObjC1 ||
6011 getLangOpts().getGC() != LangOptions::NonGC)
6012 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00006013
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006014 HasByrefExtendedLayout = false;
Fariborz Jahanianf762b722012-12-11 19:58:01 +00006015 if (Ty->isRecordType()) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006016 HasByrefExtendedLayout = true;
6017 LifeTime = Qualifiers::OCL_None;
John McCall460ce582015-10-22 18:38:17 +00006018 } else if ((LifeTime = Ty.getObjCLifetime())) {
6019 // Honor the ARC qualifiers.
6020 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
6021 // The MRR rule.
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006022 LifeTime = Qualifiers::OCL_ExplicitNone;
John McCall460ce582015-10-22 18:38:17 +00006023 } else {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006024 LifeTime = Qualifiers::OCL_None;
John McCall460ce582015-10-22 18:38:17 +00006025 }
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006026 return true;
6027}
6028
Douglas Gregorbab8a962011-09-08 01:46:34 +00006029TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
6030 if (!ObjCInstanceTypeDecl)
Alp Toker56b5cc92013-12-15 10:36:26 +00006031 ObjCInstanceTypeDecl =
6032 buildImplicitTypedef(getObjCIdType(), "instancetype");
Douglas Gregorbab8a962011-09-08 01:46:34 +00006033 return ObjCInstanceTypeDecl;
6034}
6035
Anders Carlsson18acd442007-10-29 06:33:42 +00006036// This returns true if a type has been typedefed to BOOL:
6037// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00006038static bool isTypeTypedefedAsBOOL(QualType T) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006039 if (const auto *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00006040 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
6041 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00006042
Anders Carlssond8499822007-10-29 05:01:08 +00006043 return false;
6044}
6045
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006046/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006047/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00006048CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00006049 if (!type->isIncompleteArrayType() && type->isIncompleteType())
6050 return CharUnits::Zero();
Fangrui Song6907ce22018-07-30 19:24:48 +00006051
Ken Dyck40775002010-01-11 17:06:35 +00006052 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00006053
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006054 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00006055 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00006056 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006057 // Treat arrays as pointers, since that's how they're passed in.
6058 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00006059 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00006060 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00006061}
6062
Hans Wennborg56fc62b2014-07-17 20:25:23 +00006063bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
David Majnemer3f021502015-10-08 04:53:31 +00006064 return getTargetInfo().getCXXABI().isMicrosoft() &&
6065 VD->isStaticDataMember() &&
Hans Wennborgb18da9b2018-02-20 12:43:02 +00006066 VD->getType()->isIntegralOrEnumerationType() &&
David Majnemerfac52432015-10-19 23:22:49 +00006067 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
Hans Wennborg56fc62b2014-07-17 20:25:23 +00006068}
6069
Richard Smithd9b90092016-07-02 01:32:16 +00006070ASTContext::InlineVariableDefinitionKind
6071ASTContext::getInlineVariableDefinitionKind(const VarDecl *VD) const {
6072 if (!VD->isInline())
6073 return InlineVariableDefinitionKind::None;
6074
6075 // In almost all cases, it's a weak definition.
6076 auto *First = VD->getFirstDecl();
Richard Smith8910fe62017-10-23 03:58:34 +00006077 if (First->isInlineSpecified() || !First->isStaticDataMember())
Richard Smithd9b90092016-07-02 01:32:16 +00006078 return InlineVariableDefinitionKind::Weak;
6079
6080 // If there's a file-context declaration in this translation unit, it's a
6081 // non-discardable definition.
6082 for (auto *D : VD->redecls())
Richard Smith8910fe62017-10-23 03:58:34 +00006083 if (D->getLexicalDeclContext()->isFileContext() &&
6084 !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr()))
Richard Smithd9b90092016-07-02 01:32:16 +00006085 return InlineVariableDefinitionKind::Strong;
6086
6087 // If we've not seen one yet, we don't know.
6088 return InlineVariableDefinitionKind::WeakUnknown;
6089}
6090
Eugene Zelenko7855e772018-04-03 00:11:50 +00006091static std::string charUnitsToString(const CharUnits &CU) {
Ken Dyck40775002010-01-11 17:06:35 +00006092 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006093}
6094
John McCall351762c2011-02-07 10:33:21 +00006095/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00006096/// declaration.
John McCall351762c2011-02-07 10:33:21 +00006097std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
6098 std::string S;
6099
David Chisnall950a9512009-11-17 19:33:30 +00006100 const BlockDecl *Decl = Expr->getBlockDecl();
6101 QualType BlockTy =
6102 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
6103 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00006104 if (getLangOpts().EncodeExtendedBlockSig)
Alp Toker314cc812014-01-25 16:55:45 +00006105 getObjCEncodingForMethodParameter(
6106 Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
6107 true /*Extended*/);
Fariborz Jahanian64223e62012-11-14 23:11:38 +00006108 else
Alp Toker314cc812014-01-25 16:55:45 +00006109 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00006110 // Compute size of all parameters.
6111 // Start with computing size of a pointer in number of bytes.
6112 // FIXME: There might(should) be a better way of doing this computation!
Ken Dyck40775002010-01-11 17:06:35 +00006113 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
6114 CharUnits ParmOffset = PtrSize;
David Majnemer59f77922016-06-24 04:05:48 +00006115 for (auto PI : Decl->parameters()) {
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00006116 QualType PType = PI->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00006117 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00006118 if (sz.isZero())
6119 continue;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00006120 assert(sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00006121 ParmOffset += sz;
6122 }
6123 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00006124 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00006125 // Block pointer and offset.
6126 S += "@?0";
Fangrui Song6907ce22018-07-30 19:24:48 +00006127
David Chisnall950a9512009-11-17 19:33:30 +00006128 // Argument types.
6129 ParmOffset = PtrSize;
David Majnemer59f77922016-06-24 04:05:48 +00006130 for (auto PVDecl : Decl->parameters()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00006131 QualType PType = PVDecl->getOriginalType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00006132 if (const auto *AT =
6133 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
David Chisnall950a9512009-11-17 19:33:30 +00006134 // Use array's original type only if it has known number of
6135 // elements.
6136 if (!isa<ConstantArrayType>(AT))
6137 PType = PVDecl->getType();
6138 } else if (PType->isFunctionType())
6139 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00006140 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00006141 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
6142 S, true /*Extended*/);
6143 else
6144 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00006145 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00006146 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00006147 }
John McCall351762c2011-02-07 10:33:21 +00006148
6149 return S;
David Chisnall950a9512009-11-17 19:33:30 +00006150}
6151
John McCall843dfcc2016-11-29 21:57:00 +00006152std::string
6153ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const {
6154 std::string S;
David Chisnall50e4eba2010-12-30 14:05:53 +00006155 // Encode result type.
Alp Toker314cc812014-01-25 16:55:45 +00006156 getObjCEncodingForType(Decl->getReturnType(), S);
David Chisnall50e4eba2010-12-30 14:05:53 +00006157 CharUnits ParmOffset;
6158 // Compute size of all parameters.
David Majnemer59f77922016-06-24 04:05:48 +00006159 for (auto PI : Decl->parameters()) {
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00006160 QualType PType = PI->getType();
David Chisnall50e4eba2010-12-30 14:05:53 +00006161 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00006162 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00006163 continue;
Fangrui Song6907ce22018-07-30 19:24:48 +00006164
6165 assert(sz.isPositive() &&
John McCall843dfcc2016-11-29 21:57:00 +00006166 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00006167 ParmOffset += sz;
6168 }
6169 S += charUnitsToString(ParmOffset);
6170 ParmOffset = CharUnits::Zero();
6171
6172 // Argument types.
David Majnemer59f77922016-06-24 04:05:48 +00006173 for (auto PVDecl : Decl->parameters()) {
David Chisnall50e4eba2010-12-30 14:05:53 +00006174 QualType PType = PVDecl->getOriginalType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00006175 if (const auto *AT =
6176 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
David Chisnall50e4eba2010-12-30 14:05:53 +00006177 // Use array's original type only if it has known number of
6178 // elements.
6179 if (!isa<ConstantArrayType>(AT))
6180 PType = PVDecl->getType();
6181 } else if (PType->isFunctionType())
6182 PType = PVDecl->getType();
6183 getObjCEncodingForType(PType, S);
6184 S += charUnitsToString(ParmOffset);
6185 ParmOffset += getObjCEncodingTypeSize(PType);
6186 }
Fangrui Song6907ce22018-07-30 19:24:48 +00006187
John McCall843dfcc2016-11-29 21:57:00 +00006188 return S;
David Chisnall50e4eba2010-12-30 14:05:53 +00006189}
6190
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006191/// getObjCEncodingForMethodParameter - Return the encoded type for a single
Fangrui Song6907ce22018-07-30 19:24:48 +00006192/// method parameter or return type. If Extended, include class names and
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006193/// block object types.
6194void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
6195 QualType T, std::string& S,
6196 bool Extended) const {
6197 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
6198 getObjCEncodingForTypeQualifier(QT, S);
6199 // Encode parameter type.
Craig Topper36250ad2014-05-12 05:36:57 +00006200 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006201 true /*OutermostType*/,
Fangrui Song6907ce22018-07-30 19:24:48 +00006202 false /*EncodingProperty*/,
6203 false /*StructField*/,
6204 Extended /*EncodeBlockParameters*/,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006205 Extended /*EncodeClassNames*/);
6206}
6207
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006208/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006209/// declaration.
John McCall843dfcc2016-11-29 21:57:00 +00006210std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
6211 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00006212 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006213 // Encode return type.
John McCall843dfcc2016-11-29 21:57:00 +00006214 std::string S;
Alp Toker314cc812014-01-25 16:55:45 +00006215 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
6216 Decl->getReturnType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006217 // Compute size of all parameters.
6218 // Start with computing size of a pointer in number of bytes.
6219 // FIXME: There might(should) be a better way of doing this computation!
Ken Dyck40775002010-01-11 17:06:35 +00006220 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006221 // The first two arguments (self and _cmd) are pointers; account for
6222 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00006223 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00006224 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00006225 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00006226 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00006227 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00006228 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00006229 continue;
Fangrui Song6907ce22018-07-30 19:24:48 +00006230
6231 assert(sz.isPositive() &&
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00006232 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006233 ParmOffset += sz;
6234 }
Ken Dyck40775002010-01-11 17:06:35 +00006235 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006236 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00006237 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00006238
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006239 // Argument types.
6240 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00006241 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00006242 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00006243 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00006244 QualType PType = PVDecl->getOriginalType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00006245 if (const auto *AT =
6246 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
Steve Naroffe4e55d22009-04-14 00:03:58 +00006247 // Use array's original type only if it has known number of
6248 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00006249 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00006250 PType = PVDecl->getType();
6251 } else if (PType->isFunctionType())
6252 PType = PVDecl->getType();
Fangrui Song6907ce22018-07-30 19:24:48 +00006253 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006254 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00006255 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00006256 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006257 }
Fangrui Song6907ce22018-07-30 19:24:48 +00006258
John McCall843dfcc2016-11-29 21:57:00 +00006259 return S;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006260}
6261
Fariborz Jahaniandad96302014-01-22 19:02:20 +00006262ObjCPropertyImplDecl *
6263ASTContext::getObjCPropertyImplDeclForPropertyDecl(
6264 const ObjCPropertyDecl *PD,
6265 const Decl *Container) const {
6266 if (!Container)
Craig Topper36250ad2014-05-12 05:36:57 +00006267 return nullptr;
Eugene Zelenko7855e772018-04-03 00:11:50 +00006268 if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) {
Aaron Ballmand85eff42014-03-14 15:02:45 +00006269 for (auto *PID : CID->property_impls())
6270 if (PID->getPropertyDecl() == PD)
6271 return PID;
Craig Topper36250ad2014-05-12 05:36:57 +00006272 } else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006273 const auto *OID = cast<ObjCImplementationDecl>(Container);
Craig Topper36250ad2014-05-12 05:36:57 +00006274 for (auto *PID : OID->property_impls())
6275 if (PID->getPropertyDecl() == PD)
6276 return PID;
6277 }
6278 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00006279}
6280
Daniel Dunbar4932b362008-08-28 04:38:10 +00006281/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00006282/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00006283/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
6284/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00006285/// Property attributes are stored as a comma-delimited C string. The simple
6286/// attributes readonly and bycopy are encoded as single characters. The
6287/// parametrized attributes, getter=name, setter=name, and ivar=name, are
6288/// encoded as single characters, followed by an identifier. Property types
6289/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00006290/// these attributes are defined by the following enumeration:
6291/// @code
6292/// enum PropertyAttributes {
6293/// kPropertyReadOnly = 'R', // property is read-only.
6294/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
6295/// kPropertyByref = '&', // property is a reference to the value last assigned
6296/// kPropertyDynamic = 'D', // property is dynamic
6297/// kPropertyGetter = 'G', // followed by getter selector name
6298/// kPropertySetter = 'S', // followed by setter selector name
6299/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00006300/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00006301/// kPropertyWeak = 'W' // 'weak' property
6302/// kPropertyStrong = 'P' // property GC'able
6303/// kPropertyNonAtomic = 'N' // property non-atomic
6304/// };
6305/// @endcode
John McCall843dfcc2016-11-29 21:57:00 +00006306std::string
6307ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
6308 const Decl *Container) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00006309 // Collect information from the property implementation decl(s).
6310 bool Dynamic = false;
Craig Topper36250ad2014-05-12 05:36:57 +00006311 ObjCPropertyImplDecl *SynthesizePID = nullptr;
Daniel Dunbar4932b362008-08-28 04:38:10 +00006312
Fariborz Jahaniandad96302014-01-22 19:02:20 +00006313 if (ObjCPropertyImplDecl *PropertyImpDecl =
6314 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
6315 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
6316 Dynamic = true;
6317 else
6318 SynthesizePID = PropertyImpDecl;
Daniel Dunbar4932b362008-08-28 04:38:10 +00006319 }
6320
6321 // FIXME: This is not very efficient.
John McCall843dfcc2016-11-29 21:57:00 +00006322 std::string S = "T";
Daniel Dunbar4932b362008-08-28 04:38:10 +00006323
6324 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00006325 // GCC has some special rules regarding encoding of properties which
6326 // closely resembles encoding of ivars.
Joe Groff98ac7d22014-07-07 22:25:15 +00006327 getObjCEncodingForPropertyType(PD->getType(), S);
Daniel Dunbar4932b362008-08-28 04:38:10 +00006328
6329 if (PD->isReadOnly()) {
6330 S += ",R";
Nico Weber4e8626f2013-05-08 23:47:40 +00006331 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
6332 S += ",C";
6333 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
6334 S += ",&";
Fariborz Jahanian33079ee2014-04-02 22:49:42 +00006335 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
6336 S += ",W";
Daniel Dunbar4932b362008-08-28 04:38:10 +00006337 } else {
6338 switch (PD->getSetterKind()) {
6339 case ObjCPropertyDecl::Assign: break;
6340 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00006341 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00006342 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00006343 }
6344 }
6345
6346 // It really isn't clear at all what this means, since properties
6347 // are "dynamic by default".
6348 if (Dynamic)
6349 S += ",D";
6350
Fariborz Jahanian218c6302009-01-20 19:14:18 +00006351 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
6352 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00006353
Daniel Dunbar4932b362008-08-28 04:38:10 +00006354 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
6355 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00006356 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00006357 }
6358
6359 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
6360 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00006361 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00006362 }
6363
6364 if (SynthesizePID) {
6365 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
6366 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00006367 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00006368 }
6369
6370 // FIXME: OBJCGC: weak & strong
John McCall843dfcc2016-11-29 21:57:00 +00006371 return S;
Daniel Dunbar4932b362008-08-28 04:38:10 +00006372}
6373
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006374/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00006375/// Another legacy compatibility encoding: 32-bit longs are encoded as
6376/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006377/// 'i' or 'I' instead if encoding a struct field, or a pointer!
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006378void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00006379 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006380 if (const auto *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00006381 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006382 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00006383 else
Jay Foad39c79802011-01-12 09:06:06 +00006384 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006385 PointeeTy = IntTy;
6386 }
6387 }
6388}
6389
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00006390void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006391 const FieldDecl *Field,
6392 QualType *NotEncodedT) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00006393 // We follow the behavior of gcc, expanding structures which are
6394 // directly pointed to, and expanding embedded structures. Note that
6395 // these rules are sufficient to prevent recursive encoding of the
6396 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00006397 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006398 true /* outermost type */, false, false,
6399 false, false, false, NotEncodedT);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00006400}
6401
Joe Groff98ac7d22014-07-07 22:25:15 +00006402void ASTContext::getObjCEncodingForPropertyType(QualType T,
6403 std::string& S) const {
6404 // Encode result type.
6405 // GCC has some special rules regarding encoding of properties which
6406 // closely resembles encoding of ivars.
6407 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
6408 true /* outermost type */,
6409 true /* encoding property */);
6410}
6411
John McCall393a78d2012-12-20 02:45:14 +00006412static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
6413 BuiltinType::Kind kind) {
6414 switch (kind) {
David Chisnallb190a2c2010-06-04 01:10:52 +00006415 case BuiltinType::Void: return 'v';
6416 case BuiltinType::Bool: return 'B';
Richard Smith3a8244d2018-05-01 05:02:45 +00006417 case BuiltinType::Char8:
David Chisnallb190a2c2010-06-04 01:10:52 +00006418 case BuiltinType::Char_U:
6419 case BuiltinType::UChar: return 'C';
John McCall393a78d2012-12-20 02:45:14 +00006420 case BuiltinType::Char16:
David Chisnallb190a2c2010-06-04 01:10:52 +00006421 case BuiltinType::UShort: return 'S';
John McCall393a78d2012-12-20 02:45:14 +00006422 case BuiltinType::Char32:
David Chisnallb190a2c2010-06-04 01:10:52 +00006423 case BuiltinType::UInt: return 'I';
6424 case BuiltinType::ULong:
John McCall393a78d2012-12-20 02:45:14 +00006425 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00006426 case BuiltinType::UInt128: return 'T';
6427 case BuiltinType::ULongLong: return 'Q';
6428 case BuiltinType::Char_S:
6429 case BuiltinType::SChar: return 'c';
6430 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00006431 case BuiltinType::WChar_S:
6432 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00006433 case BuiltinType::Int: return 'i';
6434 case BuiltinType::Long:
John McCall393a78d2012-12-20 02:45:14 +00006435 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00006436 case BuiltinType::LongLong: return 'q';
6437 case BuiltinType::Int128: return 't';
6438 case BuiltinType::Float: return 'f';
6439 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00006440 case BuiltinType::LongDouble: return 'D';
John McCall393a78d2012-12-20 02:45:14 +00006441 case BuiltinType::NullPtr: return '*'; // like char*
6442
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00006443 case BuiltinType::Float16:
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00006444 case BuiltinType::Float128:
John McCall393a78d2012-12-20 02:45:14 +00006445 case BuiltinType::Half:
Leonard Chanf921d852018-06-04 16:07:52 +00006446 case BuiltinType::ShortAccum:
6447 case BuiltinType::Accum:
6448 case BuiltinType::LongAccum:
6449 case BuiltinType::UShortAccum:
6450 case BuiltinType::UAccum:
6451 case BuiltinType::ULongAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00006452 case BuiltinType::ShortFract:
6453 case BuiltinType::Fract:
6454 case BuiltinType::LongFract:
6455 case BuiltinType::UShortFract:
6456 case BuiltinType::UFract:
6457 case BuiltinType::ULongFract:
6458 case BuiltinType::SatShortAccum:
6459 case BuiltinType::SatAccum:
6460 case BuiltinType::SatLongAccum:
6461 case BuiltinType::SatUShortAccum:
6462 case BuiltinType::SatUAccum:
6463 case BuiltinType::SatULongAccum:
6464 case BuiltinType::SatShortFract:
6465 case BuiltinType::SatFract:
6466 case BuiltinType::SatLongFract:
6467 case BuiltinType::SatUShortFract:
6468 case BuiltinType::SatUFract:
6469 case BuiltinType::SatULongFract:
John McCall393a78d2012-12-20 02:45:14 +00006470 // FIXME: potentially need @encodes for these!
6471 return ' ';
6472
6473 case BuiltinType::ObjCId:
6474 case BuiltinType::ObjCClass:
6475 case BuiltinType::ObjCSel:
6476 llvm_unreachable("@encoding ObjC primitive type");
6477
6478 // OpenCL and placeholder types don't need @encodings.
Alexey Bader954ba212016-04-08 13:40:33 +00006479#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6480 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00006481#include "clang/Basic/OpenCLImageTypes.def"
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006482 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00006483 case BuiltinType::OCLClkEvent:
6484 case BuiltinType::OCLQueue:
Alexey Bader9c8453f2015-09-15 11:18:52 +00006485 case BuiltinType::OCLReserveID:
Guy Benyei61054192013-02-07 10:55:47 +00006486 case BuiltinType::OCLSampler:
John McCall393a78d2012-12-20 02:45:14 +00006487 case BuiltinType::Dependent:
6488#define BUILTIN_TYPE(KIND, ID)
6489#define PLACEHOLDER_TYPE(KIND, ID) \
6490 case BuiltinType::KIND:
6491#include "clang/AST/BuiltinTypes.def"
6492 llvm_unreachable("invalid builtin type for @encode");
David Chisnallb190a2c2010-06-04 01:10:52 +00006493 }
David Blaikie5a6a0202013-01-09 17:48:41 +00006494 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnallb190a2c2010-06-04 01:10:52 +00006495}
6496
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006497static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
6498 EnumDecl *Enum = ET->getDecl();
Fangrui Song6907ce22018-07-30 19:24:48 +00006499
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006500 // The encoding of an non-fixed enum type is always 'i', regardless of size.
6501 if (!Enum->isFixed())
6502 return 'i';
Fangrui Song6907ce22018-07-30 19:24:48 +00006503
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006504 // The encoding of a fixed enum type matches its fixed underlying type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00006505 const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>();
John McCall393a78d2012-12-20 02:45:14 +00006506 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006507}
6508
Jay Foad39c79802011-01-12 09:06:06 +00006509static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00006510 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00006511 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00006512 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00006513 // The NeXT runtime encodes bit fields as b followed by the number of bits.
6514 // The GNU runtime requires more information; bitfields are encoded as b,
6515 // then the offset (in bits) of the first element, then the type of the
6516 // bitfield, then the size in bits. For example, in this structure:
6517 //
6518 // struct
6519 // {
6520 // int integer;
6521 // int flags:2;
6522 // };
6523 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
6524 // runtime, but b32i2 for the GNU runtime. The reason for this extra
6525 // information is not especially sensible, but we're stuck with it for
6526 // compatibility with GCC, although providing it breaks anything that
6527 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00006528 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
Akira Hatanaka4b1c4842017-06-27 04:34:04 +00006529 uint64_t Offset;
6530
6531 if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) {
6532 Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), nullptr,
6533 IVD);
6534 } else {
6535 const RecordDecl *RD = FD->getParent();
6536 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
6537 Offset = RL.getFieldOffset(FD->getFieldIndex());
6538 }
6539
6540 S += llvm::utostr(Offset);
6541
Eugene Zelenko7855e772018-04-03 00:11:50 +00006542 if (const auto *ET = T->getAs<EnumType>())
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006543 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall393a78d2012-12-20 02:45:14 +00006544 else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006545 const auto *BT = T->castAs<BuiltinType>();
John McCall393a78d2012-12-20 02:45:14 +00006546 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
6547 }
David Chisnallb190a2c2010-06-04 01:10:52 +00006548 }
Richard Smithcaf33902011-10-10 18:28:20 +00006549 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00006550}
6551
Daniel Dunbar07d07852009-10-18 21:17:35 +00006552// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00006553void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
6554 bool ExpandPointedToStructures,
6555 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00006556 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00006557 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006558 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006559 bool StructField,
6560 bool EncodeBlockParameters,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00006561 bool EncodeClassNames,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006562 bool EncodePointerToObjCTypedef,
6563 QualType *NotEncodedT) const {
John McCall393a78d2012-12-20 02:45:14 +00006564 CanQualType CT = getCanonicalType(T);
6565 switch (CT->getTypeClass()) {
6566 case Type::Builtin:
6567 case Type::Enum:
Chris Lattnere7cabb92009-07-13 00:10:46 +00006568 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00006569 return EncodeBitField(this, S, T, FD);
Eugene Zelenko7855e772018-04-03 00:11:50 +00006570 if (const auto *BT = dyn_cast<BuiltinType>(CT))
John McCall393a78d2012-12-20 02:45:14 +00006571 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
6572 else
6573 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnere7cabb92009-07-13 00:10:46 +00006574 return;
Mike Stump11289f42009-09-09 15:08:12 +00006575
John McCall393a78d2012-12-20 02:45:14 +00006576 case Type::Complex: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006577 const auto *CT = T->castAs<ComplexType>();
Anders Carlsson39b2e132009-04-09 21:55:45 +00006578 S += 'j';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006579 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, nullptr);
Chris Lattnere7cabb92009-07-13 00:10:46 +00006580 return;
6581 }
John McCall393a78d2012-12-20 02:45:14 +00006582
6583 case Type::Atomic: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006584 const auto *AT = T->castAs<AtomicType>();
John McCall393a78d2012-12-20 02:45:14 +00006585 S += 'A';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006586 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, nullptr);
John McCall393a78d2012-12-20 02:45:14 +00006587 return;
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00006588 }
John McCall393a78d2012-12-20 02:45:14 +00006589
6590 // encoding for pointer or reference types.
6591 case Type::Pointer:
6592 case Type::LValueReference:
6593 case Type::RValueReference: {
6594 QualType PointeeTy;
6595 if (isa<PointerType>(CT)) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006596 const auto *PT = T->castAs<PointerType>();
John McCall393a78d2012-12-20 02:45:14 +00006597 if (PT->isObjCSelType()) {
6598 S += ':';
6599 return;
6600 }
6601 PointeeTy = PT->getPointeeType();
6602 } else {
6603 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
6604 }
6605
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006606 bool isReadOnly = false;
6607 // For historical/compatibility reasons, the read-only qualifier of the
6608 // pointee gets emitted _before_ the '^'. The read-only qualifier of
6609 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00006610 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00006611 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006612 if (OutermostType && T.isConstQualified()) {
6613 isReadOnly = true;
6614 S += 'r';
6615 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00006616 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006617 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006618 while (P->getAs<PointerType>())
6619 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006620 if (P.isConstQualified()) {
6621 isReadOnly = true;
6622 S += 'r';
6623 }
6624 }
6625 if (isReadOnly) {
6626 // Another legacy compatibility encoding. Some ObjC qualifier and type
6627 // combinations need to be rearranged.
6628 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006629 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00006630 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006631 }
Mike Stump11289f42009-09-09 15:08:12 +00006632
Anders Carlssond8499822007-10-29 05:01:08 +00006633 if (PointeeTy->isCharType()) {
6634 // char pointer types should be encoded as '*' unless it is a
6635 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00006636 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00006637 S += '*';
6638 return;
6639 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00006640 } else if (const auto *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00006641 // GCC binary compat: Need to convert "struct objc_class *" to "#".
6642 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
6643 S += '#';
6644 return;
6645 }
6646 // GCC binary compat: Need to convert "struct objc_object *" to "@".
6647 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
6648 S += '@';
6649 return;
6650 }
6651 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00006652 }
Anders Carlssond8499822007-10-29 05:01:08 +00006653 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006654 getLegacyIntegralTypeEncoding(PointeeTy);
6655
Mike Stump11289f42009-09-09 15:08:12 +00006656 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006657 nullptr, false, false, false, false, false, false,
6658 NotEncodedT);
Chris Lattnere7cabb92009-07-13 00:10:46 +00006659 return;
6660 }
John McCall393a78d2012-12-20 02:45:14 +00006661
6662 case Type::ConstantArray:
6663 case Type::IncompleteArray:
6664 case Type::VariableArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006665 const auto *AT = cast<ArrayType>(CT);
John McCall393a78d2012-12-20 02:45:14 +00006666
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006667 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00006668 // Incomplete arrays are encoded as a pointer to the array element.
6669 S += '^';
6670
Mike Stump11289f42009-09-09 15:08:12 +00006671 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00006672 false, ExpandStructures, FD);
6673 } else {
6674 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00006675
Eugene Zelenko7855e772018-04-03 00:11:50 +00006676 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
Fariborz Jahanianf0dc11a2013-06-04 16:04:37 +00006677 S += llvm::utostr(CAT->getSize().getZExtValue());
6678 else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00006679 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006680 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
6681 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00006682 S += '0';
6683 }
Mike Stump11289f42009-09-09 15:08:12 +00006684
6685 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006686 false, ExpandStructures, FD,
6687 false, false, false, false, false, false,
6688 NotEncodedT);
Anders Carlssond05f44b2009-02-22 01:38:57 +00006689 S += ']';
6690 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006691 return;
6692 }
Mike Stump11289f42009-09-09 15:08:12 +00006693
John McCall393a78d2012-12-20 02:45:14 +00006694 case Type::FunctionNoProto:
6695 case Type::FunctionProto:
Anders Carlssondf4cc612007-10-30 00:06:20 +00006696 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00006697 return;
Mike Stump11289f42009-09-09 15:08:12 +00006698
John McCall393a78d2012-12-20 02:45:14 +00006699 case Type::Record: {
6700 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00006701 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00006702 // Anonymous structures print as '?'
6703 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
6704 S += II->getName();
Eugene Zelenko7855e772018-04-03 00:11:50 +00006705 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
Fariborz Jahanianc5158202010-05-07 00:28:49 +00006706 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00006707 llvm::raw_string_ostream OS(S);
Serge Pavlov03e672c2017-11-28 16:14:14 +00006708 printTemplateArgumentList(OS, TemplateArgs.asArray(),
6709 getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00006710 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00006711 } else {
6712 S += '?';
6713 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00006714 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00006715 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006716 if (!RDecl->isUnion()) {
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006717 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006718 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006719 for (const auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006720 if (FD) {
6721 S += '"';
6722 S += Field->getNameAsString();
6723 S += '"';
6724 }
Mike Stump11289f42009-09-09 15:08:12 +00006725
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006726 // Special case bit-fields.
6727 if (Field->isBitField()) {
6728 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006729 Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006730 } else {
6731 QualType qt = Field->getType();
6732 getLegacyIntegralTypeEncoding(qt);
6733 getObjCEncodingForTypeImpl(qt, S, false, true,
6734 FD, /*OutermostType*/false,
6735 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006736 /*StructField*/true,
6737 false, false, false, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006738 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00006739 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00006740 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00006741 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00006742 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00006743 return;
6744 }
Mike Stump11289f42009-09-09 15:08:12 +00006745
John McCall393a78d2012-12-20 02:45:14 +00006746 case Type::BlockPointer: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006747 const auto *BT = T->castAs<BlockPointerType>();
Steve Naroff49140cb2009-02-02 18:24:29 +00006748 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006749 if (EncodeBlockParameters) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006750 const auto *FT = BT->getPointeeType()->castAs<FunctionType>();
Fangrui Song6907ce22018-07-30 19:24:48 +00006751
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006752 S += '<';
6753 // Block return type
Alp Toker314cc812014-01-25 16:55:45 +00006754 getObjCEncodingForTypeImpl(
6755 FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures,
6756 FD, false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006757 false /* StructField */, EncodeBlockParameters, EncodeClassNames, false,
6758 NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006759 // Block self
6760 S += "@?";
6761 // Block parameters
Eugene Zelenko7855e772018-04-03 00:11:50 +00006762 if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00006763 for (const auto &I : FPT->param_types())
6764 getObjCEncodingForTypeImpl(
6765 I, S, ExpandPointedToStructures, ExpandStructures, FD,
6766 false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006767 false /* StructField */, EncodeBlockParameters, EncodeClassNames,
6768 false, NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006769 }
6770 S += '>';
6771 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006772 return;
6773 }
Mike Stump11289f42009-09-09 15:08:12 +00006774
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00006775 case Type::ObjCObject: {
6776 // hack to match legacy encoding of *id and *Class
6777 QualType Ty = getObjCObjectPointerType(CT);
6778 if (Ty->isObjCIdType()) {
6779 S += "{objc_object=}";
6780 return;
6781 }
6782 else if (Ty->isObjCClassType()) {
6783 S += "{objc_class=}";
6784 return;
6785 }
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00006786 // TODO: Double check to make sure this intentionally falls through.
Galina Kistanovaf87496d2017-06-03 06:31:42 +00006787 LLVM_FALLTHROUGH;
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00006788 }
Fangrui Song6907ce22018-07-30 19:24:48 +00006789
John McCall393a78d2012-12-20 02:45:14 +00006790 case Type::ObjCInterface: {
6791 // Ignore protocol qualifiers when mangling at this level.
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006792 // @encode(class_name)
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006793 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006794 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006795 S += OI->getObjCRuntimeNameAsString();
Akira Hatanakafd0fb202016-08-17 19:42:22 +00006796 if (ExpandStructures) {
6797 S += '=';
6798 SmallVector<const ObjCIvarDecl*, 32> Ivars;
6799 DeepCollectObjCIvars(OI, true, Ivars);
6800 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
George Burgess IV00f70bd2018-03-01 05:43:23 +00006801 const FieldDecl *Field = Ivars[i];
Akira Hatanakafd0fb202016-08-17 19:42:22 +00006802 if (Field->isBitField())
6803 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
6804 else
6805 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
6806 false, false, false, false, false,
6807 EncodePointerToObjCTypedef,
6808 NotEncodedT);
6809 }
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006810 }
6811 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00006812 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006813 }
Mike Stump11289f42009-09-09 15:08:12 +00006814
John McCall393a78d2012-12-20 02:45:14 +00006815 case Type::ObjCObjectPointer: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006816 const auto *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00006817 if (OPT->isObjCIdType()) {
6818 S += '@';
6819 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00006820 }
Mike Stump11289f42009-09-09 15:08:12 +00006821
Steve Narofff0c86112009-10-28 22:03:49 +00006822 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
6823 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
6824 // Since this is a binary compatibility issue, need to consult with runtime
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00006825 // folks. Fortunately, this is a *very* obscure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00006826 S += '#';
6827 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00006828 }
Mike Stump11289f42009-09-09 15:08:12 +00006829
Chris Lattnere7cabb92009-07-13 00:10:46 +00006830 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00006831 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00006832 ExpandPointedToStructures,
6833 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006834 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00006835 // Note that we do extended encoding of protocol qualifer list
6836 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00006837 S += '"';
Aaron Ballman83731462014-03-17 16:14:00 +00006838 for (const auto *I : OPT->quals()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00006839 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006840 S += I->getObjCRuntimeNameAsString();
Steve Naroff7cae42b2009-07-10 23:34:53 +00006841 S += '>';
6842 }
6843 S += '"';
6844 }
6845 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00006846 }
Mike Stump11289f42009-09-09 15:08:12 +00006847
Chris Lattnere7cabb92009-07-13 00:10:46 +00006848 QualType PointeeTy = OPT->getPointeeType();
6849 if (!EncodingProperty &&
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00006850 isa<TypedefType>(PointeeTy.getTypePtr()) &&
6851 !EncodePointerToObjCTypedef) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00006852 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00006853 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00006854 // {...};
6855 S += '^';
Fariborz Jahanian88890e72013-07-12 16:19:11 +00006856 if (FD && OPT->getInterfaceDecl()) {
Fariborz Jahanianc682ef52013-07-12 16:41:56 +00006857 // Prevent recursive encoding of fields in some rare cases.
Fariborz Jahanian88890e72013-07-12 16:19:11 +00006858 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
6859 SmallVector<const ObjCIvarDecl*, 32> Ivars;
6860 DeepCollectObjCIvars(OI, true, Ivars);
6861 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
George Burgess IV00f70bd2018-03-01 05:43:23 +00006862 if (Ivars[i] == FD) {
Fariborz Jahanian88890e72013-07-12 16:19:11 +00006863 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006864 S += OI->getObjCRuntimeNameAsString();
Fariborz Jahanian88890e72013-07-12 16:19:11 +00006865 S += '}';
6866 return;
6867 }
6868 }
6869 }
Mike Stump11289f42009-09-09 15:08:12 +00006870 getObjCEncodingForTypeImpl(PointeeTy, S,
6871 false, ExpandPointedToStructures,
Craig Topper36250ad2014-05-12 05:36:57 +00006872 nullptr,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00006873 false, false, false, false, false,
6874 /*EncodePointerToObjCTypedef*/true);
Steve Naroff7cae42b2009-07-10 23:34:53 +00006875 return;
6876 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006877
6878 S += '@';
Fangrui Song6907ce22018-07-30 19:24:48 +00006879 if (OPT->getInterfaceDecl() &&
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006880 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00006881 S += '"';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006882 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
Aaron Ballman83731462014-03-17 16:14:00 +00006883 for (const auto *I : OPT->quals()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00006884 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006885 S += I->getObjCRuntimeNameAsString();
Chris Lattnere7cabb92009-07-13 00:10:46 +00006886 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00006887 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006888 S += '"';
6889 }
6890 return;
6891 }
Mike Stump11289f42009-09-09 15:08:12 +00006892
John McCalla9e6e8d2010-05-17 23:56:34 +00006893 // gcc just blithely ignores member pointers.
John McCall393a78d2012-12-20 02:45:14 +00006894 // FIXME: we shoul do better than that. 'M' is available.
6895 case Type::MemberPointer:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006896 // This matches gcc's encoding, even though technically it is insufficient.
6897 //FIXME. We should do a better job than gcc.
John McCall393a78d2012-12-20 02:45:14 +00006898 case Type::Vector:
6899 case Type::ExtVector:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006900 // Until we have a coherent encoding of these three types, issue warning.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00006901 if (NotEncodedT)
6902 *NotEncodedT = T;
6903 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00006904
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006905 // We could see an undeduced auto type here during error recovery.
6906 // Just ignore it.
Richard Smith27d807c2013-04-30 13:56:41 +00006907 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00006908 case Type::DeducedTemplateSpecialization:
Richard Smith27d807c2013-04-30 13:56:41 +00006909 return;
6910
Xiuli Pan9c14e282016-01-09 12:53:17 +00006911 case Type::Pipe:
John McCall393a78d2012-12-20 02:45:14 +00006912#define ABSTRACT_TYPE(KIND, BASE)
6913#define TYPE(KIND, BASE)
6914#define DEPENDENT_TYPE(KIND, BASE) \
6915 case Type::KIND:
6916#define NON_CANONICAL_TYPE(KIND, BASE) \
6917 case Type::KIND:
6918#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
6919 case Type::KIND:
6920#include "clang/AST/TypeNodes.def"
6921 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00006922 }
John McCall393a78d2012-12-20 02:45:14 +00006923 llvm_unreachable("bad type kind!");
Anders Carlssond8499822007-10-29 05:01:08 +00006924}
6925
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006926void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
6927 std::string &S,
6928 const FieldDecl *FD,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006929 bool includeVBases,
6930 QualType *NotEncodedT) const {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006931 assert(RDecl && "Expected non-null RecordDecl");
6932 assert(!RDecl->isUnion() && "Should not be called for unions");
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00006933 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006934 return;
6935
Eugene Zelenko7855e772018-04-03 00:11:50 +00006936 const auto *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006937 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
6938 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
6939
6940 if (CXXRec) {
Aaron Ballman574705e2014-03-13 15:41:46 +00006941 for (const auto &BI : CXXRec->bases()) {
6942 if (!BI.isVirtual()) {
6943 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006944 if (base->isEmpty())
6945 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00006946 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006947 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
6948 std::make_pair(offs, base));
6949 }
6950 }
6951 }
Fangrui Song6907ce22018-07-30 19:24:48 +00006952
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006953 unsigned i = 0;
Hans Wennborga302cd92014-08-21 16:06:57 +00006954 for (auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006955 uint64_t offs = layout.getFieldOffset(i);
6956 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Hans Wennborga302cd92014-08-21 16:06:57 +00006957 std::make_pair(offs, Field));
6958 ++i;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006959 }
6960
6961 if (CXXRec && includeVBases) {
Aaron Ballman445a9392014-03-13 16:15:17 +00006962 for (const auto &BI : CXXRec->vbases()) {
6963 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006964 if (base->isEmpty())
6965 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00006966 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Eli Friedman1d24af82013-09-18 01:59:16 +00006967 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
6968 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00006969 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
6970 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006971 }
6972 }
6973
6974 CharUnits size;
6975 if (CXXRec) {
6976 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
6977 } else {
6978 size = layout.getSize();
6979 }
6980
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006981#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006982 uint64_t CurOffs = 0;
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006983#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006984 std::multimap<uint64_t, NamedDecl *>::iterator
6985 CurLayObj = FieldOrBaseOffsets.begin();
6986
Douglas Gregorf5d6c742012-04-27 22:30:01 +00006987 if (CXXRec && CXXRec->isDynamicClass() &&
6988 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006989 if (FD) {
6990 S += "\"_vptr$";
6991 std::string recname = CXXRec->getNameAsString();
6992 if (recname.empty()) recname = "?";
6993 S += recname;
6994 S += '"';
6995 }
6996 S += "^^?";
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006997#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006998 CurOffs += getTypeSize(VoidPtrTy);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006999#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007000 }
7001
7002 if (!RDecl->hasFlexibleArrayMember()) {
7003 // Mark the end of the structure.
7004 uint64_t offs = toBits(size);
7005 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Craig Topper36250ad2014-05-12 05:36:57 +00007006 std::make_pair(offs, nullptr));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007007 }
7008
7009 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007010#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007011 assert(CurOffs <= CurLayObj->first);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007012 if (CurOffs < CurLayObj->first) {
Fangrui Song6907ce22018-07-30 19:24:48 +00007013 uint64_t padding = CurLayObj->first - CurOffs;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007014 // FIXME: There doesn't seem to be a way to indicate in the encoding that
7015 // packing/alignment of members is different that normal, in which case
7016 // the encoding will be out-of-sync with the real layout.
7017 // If the runtime switches to just consider the size of types without
7018 // taking into account alignment, we could make padding explicit in the
7019 // encoding (e.g. using arrays of chars). The encoding strings would be
7020 // longer then though.
7021 CurOffs += padding;
7022 }
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007023#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007024
7025 NamedDecl *dcl = CurLayObj->second;
Craig Topper36250ad2014-05-12 05:36:57 +00007026 if (!dcl)
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007027 break; // reached end of structure.
7028
Eugene Zelenko7855e772018-04-03 00:11:50 +00007029 if (auto *base = dyn_cast<CXXRecordDecl>(dcl)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007030 // We expand the bases without their virtual bases since those are going
7031 // in the initial structure. Note that this differs from gcc which
7032 // expands virtual bases each time one is encountered in the hierarchy,
7033 // making the encoding type bigger than it really is.
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00007034 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
7035 NotEncodedT);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00007036 assert(!base->isEmpty());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007037#ifndef NDEBUG
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00007038 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007039#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007040 } else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00007041 const auto *field = cast<FieldDecl>(dcl);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007042 if (FD) {
7043 S += '"';
7044 S += field->getNameAsString();
7045 S += '"';
7046 }
7047
7048 if (field->isBitField()) {
7049 EncodeBitField(this, S, field->getType(), field);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007050#ifndef NDEBUG
Richard Smithcaf33902011-10-10 18:28:20 +00007051 CurOffs += field->getBitWidthValue(*this);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007052#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007053 } else {
7054 QualType qt = field->getType();
7055 getLegacyIntegralTypeEncoding(qt);
7056 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
7057 /*OutermostType*/false,
7058 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00007059 /*StructField*/true,
7060 false, false, false, NotEncodedT);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007061#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007062 CurOffs += getTypeSize(field->getType());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007063#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007064 }
7065 }
7066 }
7067}
7068
Mike Stump11289f42009-09-09 15:08:12 +00007069void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00007070 std::string& S) const {
7071 if (QT & Decl::OBJC_TQ_In)
7072 S += 'n';
7073 if (QT & Decl::OBJC_TQ_Inout)
7074 S += 'N';
7075 if (QT & Decl::OBJC_TQ_Out)
7076 S += 'o';
7077 if (QT & Decl::OBJC_TQ_Bycopy)
7078 S += 'O';
7079 if (QT & Decl::OBJC_TQ_Byref)
7080 S += 'R';
7081 if (QT & Decl::OBJC_TQ_Oneway)
7082 S += 'V';
7083}
7084
Douglas Gregor3ea72692011-08-12 05:46:01 +00007085TypedefDecl *ASTContext::getObjCIdDecl() const {
7086 if (!ObjCIdDecl) {
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00007087 QualType T = getObjCObjectType(ObjCBuiltinIdTy, {}, {});
Douglas Gregor3ea72692011-08-12 05:46:01 +00007088 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00007089 ObjCIdDecl = buildImplicitTypedef(T, "id");
Douglas Gregor3ea72692011-08-12 05:46:01 +00007090 }
Douglas Gregor3ea72692011-08-12 05:46:01 +00007091 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00007092}
7093
Douglas Gregor52e02802011-08-12 06:17:30 +00007094TypedefDecl *ASTContext::getObjCSelDecl() const {
7095 if (!ObjCSelDecl) {
Alp Toker56b5cc92013-12-15 10:36:26 +00007096 QualType T = getPointerType(ObjCBuiltinSelTy);
7097 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
Douglas Gregor52e02802011-08-12 06:17:30 +00007098 }
7099 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00007100}
7101
Douglas Gregor0a586182011-08-12 05:59:41 +00007102TypedefDecl *ASTContext::getObjCClassDecl() const {
7103 if (!ObjCClassDecl) {
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00007104 QualType T = getObjCObjectType(ObjCBuiltinClassTy, {}, {});
Douglas Gregor0a586182011-08-12 05:59:41 +00007105 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00007106 ObjCClassDecl = buildImplicitTypedef(T, "Class");
Douglas Gregor0a586182011-08-12 05:59:41 +00007107 }
Douglas Gregor0a586182011-08-12 05:59:41 +00007108 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00007109}
7110
Douglas Gregord53ae832012-01-17 18:09:05 +00007111ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
7112 if (!ObjCProtocolClassDecl) {
Fangrui Song6907ce22018-07-30 19:24:48 +00007113 ObjCProtocolClassDecl
7114 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
Douglas Gregord53ae832012-01-17 18:09:05 +00007115 SourceLocation(),
7116 &Idents.get("Protocol"),
Douglas Gregor85f3f952015-07-07 03:57:15 +00007117 /*typeParamList=*/nullptr,
Craig Topper36250ad2014-05-12 05:36:57 +00007118 /*PrevDecl=*/nullptr,
Fangrui Song6907ce22018-07-30 19:24:48 +00007119 SourceLocation(), true);
Douglas Gregord53ae832012-01-17 18:09:05 +00007120 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007121
Douglas Gregord53ae832012-01-17 18:09:05 +00007122 return ObjCProtocolClassDecl;
7123}
7124
Meador Inge5d3fb222012-06-16 03:34:49 +00007125//===----------------------------------------------------------------------===//
7126// __builtin_va_list Construction Functions
7127//===----------------------------------------------------------------------===//
7128
Charles Davisc7d5c942015-09-17 20:55:33 +00007129static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context,
7130 StringRef Name) {
7131 // typedef char* __builtin[_ms]_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00007132 QualType T = Context->getPointerType(Context->CharTy);
Charles Davisc7d5c942015-09-17 20:55:33 +00007133 return Context->buildImplicitTypedef(T, Name);
7134}
7135
7136static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
7137 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
7138}
7139
7140static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
7141 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007142}
7143
7144static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
7145 // typedef void* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00007146 QualType T = Context->getPointerType(Context->VoidTy);
7147 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007148}
7149
Tim Northover9bb857a2013-01-31 12:13:10 +00007150static TypedefDecl *
7151CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00007152 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00007153 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00007154 if (Context->getLangOpts().CPlusPlus) {
7155 // namespace std { struct __va_list {
7156 NamespaceDecl *NS;
7157 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
7158 Context->getTranslationUnitDecl(),
Craig Topper36250ad2014-05-12 05:36:57 +00007159 /*Inline*/ false, SourceLocation(),
Tim Northover9bb857a2013-01-31 12:13:10 +00007160 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00007161 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00007162 NS->setImplicit();
Tim Northover9bb857a2013-01-31 12:13:10 +00007163 VaListTagDecl->setDeclContext(NS);
Tim Northover9bb857a2013-01-31 12:13:10 +00007164 }
7165
7166 VaListTagDecl->startDefinition();
7167
7168 const size_t NumFields = 5;
7169 QualType FieldTypes[NumFields];
7170 const char *FieldNames[NumFields];
7171
7172 // void *__stack;
7173 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
7174 FieldNames[0] = "__stack";
7175
7176 // void *__gr_top;
7177 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
7178 FieldNames[1] = "__gr_top";
7179
7180 // void *__vr_top;
7181 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
7182 FieldNames[2] = "__vr_top";
7183
7184 // int __gr_offs;
7185 FieldTypes[3] = Context->IntTy;
7186 FieldNames[3] = "__gr_offs";
7187
7188 // int __vr_offs;
7189 FieldTypes[4] = Context->IntTy;
7190 FieldNames[4] = "__vr_offs";
7191
7192 // Create fields
7193 for (unsigned i = 0; i < NumFields; ++i) {
7194 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7195 VaListTagDecl,
7196 SourceLocation(),
7197 SourceLocation(),
7198 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00007199 FieldTypes[i], /*TInfo=*/nullptr,
7200 /*BitWidth=*/nullptr,
Tim Northover9bb857a2013-01-31 12:13:10 +00007201 /*Mutable=*/false,
7202 ICIS_NoInit);
7203 Field->setAccess(AS_public);
7204 VaListTagDecl->addDecl(Field);
7205 }
7206 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00007207 Context->VaListTagDecl = VaListTagDecl;
Tim Northover9bb857a2013-01-31 12:13:10 +00007208 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Tim Northover9bb857a2013-01-31 12:13:10 +00007209
7210 // } __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00007211 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00007212}
7213
Meador Inge5d3fb222012-06-16 03:34:49 +00007214static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
7215 // typedef struct __va_list_tag {
7216 RecordDecl *VaListTagDecl;
7217
Alp Toker2dea15b2013-12-17 01:22:38 +00007218 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00007219 VaListTagDecl->startDefinition();
7220
7221 const size_t NumFields = 5;
7222 QualType FieldTypes[NumFields];
7223 const char *FieldNames[NumFields];
7224
7225 // unsigned char gpr;
7226 FieldTypes[0] = Context->UnsignedCharTy;
7227 FieldNames[0] = "gpr";
7228
7229 // unsigned char fpr;
7230 FieldTypes[1] = Context->UnsignedCharTy;
7231 FieldNames[1] = "fpr";
7232
7233 // unsigned short reserved;
7234 FieldTypes[2] = Context->UnsignedShortTy;
7235 FieldNames[2] = "reserved";
7236
7237 // void* overflow_arg_area;
7238 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
7239 FieldNames[3] = "overflow_arg_area";
7240
7241 // void* reg_save_area;
7242 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
7243 FieldNames[4] = "reg_save_area";
7244
7245 // Create fields
7246 for (unsigned i = 0; i < NumFields; ++i) {
7247 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
7248 SourceLocation(),
7249 SourceLocation(),
7250 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00007251 FieldTypes[i], /*TInfo=*/nullptr,
7252 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00007253 /*Mutable=*/false,
7254 ICIS_NoInit);
7255 Field->setAccess(AS_public);
7256 VaListTagDecl->addDecl(Field);
7257 }
7258 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00007259 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00007260 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
7261
7262 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00007263 TypedefDecl *VaListTagTypedefDecl =
7264 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
7265
Meador Inge5d3fb222012-06-16 03:34:49 +00007266 QualType VaListTagTypedefType =
7267 Context->getTypedefType(VaListTagTypedefDecl);
7268
7269 // typedef __va_list_tag __builtin_va_list[1];
7270 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
7271 QualType VaListTagArrayType
7272 = Context->getConstantArrayType(VaListTagTypedefType,
7273 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00007274 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007275}
7276
7277static TypedefDecl *
7278CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00007279 // struct __va_list_tag {
Meador Inge5d3fb222012-06-16 03:34:49 +00007280 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00007281 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00007282 VaListTagDecl->startDefinition();
7283
7284 const size_t NumFields = 4;
7285 QualType FieldTypes[NumFields];
7286 const char *FieldNames[NumFields];
7287
7288 // unsigned gp_offset;
7289 FieldTypes[0] = Context->UnsignedIntTy;
7290 FieldNames[0] = "gp_offset";
7291
7292 // unsigned fp_offset;
7293 FieldTypes[1] = Context->UnsignedIntTy;
7294 FieldNames[1] = "fp_offset";
7295
7296 // void* overflow_arg_area;
7297 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
7298 FieldNames[2] = "overflow_arg_area";
7299
7300 // void* reg_save_area;
7301 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
7302 FieldNames[3] = "reg_save_area";
7303
7304 // Create fields
7305 for (unsigned i = 0; i < NumFields; ++i) {
7306 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7307 VaListTagDecl,
7308 SourceLocation(),
7309 SourceLocation(),
7310 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00007311 FieldTypes[i], /*TInfo=*/nullptr,
7312 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00007313 /*Mutable=*/false,
7314 ICIS_NoInit);
7315 Field->setAccess(AS_public);
7316 VaListTagDecl->addDecl(Field);
7317 }
7318 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00007319 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00007320 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
7321
Richard Smith9b88a4c2015-07-27 05:40:23 +00007322 // };
Alp Toker56b5cc92013-12-15 10:36:26 +00007323
Richard Smith9b88a4c2015-07-27 05:40:23 +00007324 // typedef struct __va_list_tag __builtin_va_list[1];
Meador Inge5d3fb222012-06-16 03:34:49 +00007325 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00007326 QualType VaListTagArrayType =
7327 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00007328 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007329}
7330
7331static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
7332 // typedef int __builtin_va_list[4];
7333 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
Yaron Kerene0bcdd42016-10-08 06:45:10 +00007334 QualType IntArrayType =
7335 Context->getConstantArrayType(Context->IntTy, Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00007336 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007337}
7338
Logan Chien57086ce2012-10-10 06:56:20 +00007339static TypedefDecl *
7340CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00007341 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00007342 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00007343 if (Context->getLangOpts().CPlusPlus) {
7344 // namespace std { struct __va_list {
7345 NamespaceDecl *NS;
7346 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
7347 Context->getTranslationUnitDecl(),
7348 /*Inline*/false, SourceLocation(),
7349 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00007350 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00007351 NS->setImplicit();
Logan Chien57086ce2012-10-10 06:56:20 +00007352 VaListDecl->setDeclContext(NS);
Logan Chien57086ce2012-10-10 06:56:20 +00007353 }
7354
7355 VaListDecl->startDefinition();
7356
7357 // void * __ap;
7358 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7359 VaListDecl,
7360 SourceLocation(),
7361 SourceLocation(),
7362 &Context->Idents.get("__ap"),
7363 Context->getPointerType(Context->VoidTy),
Craig Topper36250ad2014-05-12 05:36:57 +00007364 /*TInfo=*/nullptr,
7365 /*BitWidth=*/nullptr,
Logan Chien57086ce2012-10-10 06:56:20 +00007366 /*Mutable=*/false,
7367 ICIS_NoInit);
7368 Field->setAccess(AS_public);
7369 VaListDecl->addDecl(Field);
7370
7371 // };
7372 VaListDecl->completeDefinition();
Oleg Ranevskyyb88d2472016-03-30 21:30:30 +00007373 Context->VaListTagDecl = VaListDecl;
Logan Chien57086ce2012-10-10 06:56:20 +00007374
7375 // typedef struct __va_list __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00007376 QualType T = Context->getRecordType(VaListDecl);
7377 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00007378}
7379
Ulrich Weigand47445072013-05-06 16:26:41 +00007380static TypedefDecl *
7381CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00007382 // struct __va_list_tag {
Ulrich Weigand47445072013-05-06 16:26:41 +00007383 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00007384 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00007385 VaListTagDecl->startDefinition();
7386
7387 const size_t NumFields = 4;
7388 QualType FieldTypes[NumFields];
7389 const char *FieldNames[NumFields];
7390
7391 // long __gpr;
7392 FieldTypes[0] = Context->LongTy;
7393 FieldNames[0] = "__gpr";
7394
7395 // long __fpr;
7396 FieldTypes[1] = Context->LongTy;
7397 FieldNames[1] = "__fpr";
7398
7399 // void *__overflow_arg_area;
7400 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
7401 FieldNames[2] = "__overflow_arg_area";
7402
7403 // void *__reg_save_area;
7404 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
7405 FieldNames[3] = "__reg_save_area";
7406
7407 // Create fields
7408 for (unsigned i = 0; i < NumFields; ++i) {
7409 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7410 VaListTagDecl,
7411 SourceLocation(),
7412 SourceLocation(),
7413 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00007414 FieldTypes[i], /*TInfo=*/nullptr,
7415 /*BitWidth=*/nullptr,
Ulrich Weigand47445072013-05-06 16:26:41 +00007416 /*Mutable=*/false,
7417 ICIS_NoInit);
7418 Field->setAccess(AS_public);
7419 VaListTagDecl->addDecl(Field);
7420 }
7421 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00007422 Context->VaListTagDecl = VaListTagDecl;
Ulrich Weigand47445072013-05-06 16:26:41 +00007423 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Ulrich Weigand47445072013-05-06 16:26:41 +00007424
Richard Smith9b88a4c2015-07-27 05:40:23 +00007425 // };
Ulrich Weigand47445072013-05-06 16:26:41 +00007426
7427 // typedef __va_list_tag __builtin_va_list[1];
7428 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00007429 QualType VaListTagArrayType =
7430 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Ulrich Weigand47445072013-05-06 16:26:41 +00007431
Alp Toker56b5cc92013-12-15 10:36:26 +00007432 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Ulrich Weigand47445072013-05-06 16:26:41 +00007433}
7434
Meador Inge5d3fb222012-06-16 03:34:49 +00007435static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
7436 TargetInfo::BuiltinVaListKind Kind) {
7437 switch (Kind) {
7438 case TargetInfo::CharPtrBuiltinVaList:
7439 return CreateCharPtrBuiltinVaListDecl(Context);
7440 case TargetInfo::VoidPtrBuiltinVaList:
7441 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northover9bb857a2013-01-31 12:13:10 +00007442 case TargetInfo::AArch64ABIBuiltinVaList:
7443 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00007444 case TargetInfo::PowerABIBuiltinVaList:
7445 return CreatePowerABIBuiltinVaListDecl(Context);
7446 case TargetInfo::X86_64ABIBuiltinVaList:
7447 return CreateX86_64ABIBuiltinVaListDecl(Context);
7448 case TargetInfo::PNaClABIBuiltinVaList:
7449 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00007450 case TargetInfo::AAPCSABIBuiltinVaList:
7451 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigand47445072013-05-06 16:26:41 +00007452 case TargetInfo::SystemZBuiltinVaList:
7453 return CreateSystemZBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00007454 }
7455
7456 llvm_unreachable("Unhandled __builtin_va_list type kind");
7457}
7458
7459TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00007460 if (!BuiltinVaListDecl) {
Meador Inge5d3fb222012-06-16 03:34:49 +00007461 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
Alp Toker56b5cc92013-12-15 10:36:26 +00007462 assert(BuiltinVaListDecl->isImplicit());
7463 }
Meador Inge5d3fb222012-06-16 03:34:49 +00007464
7465 return BuiltinVaListDecl;
7466}
7467
Richard Smith9b88a4c2015-07-27 05:40:23 +00007468Decl *ASTContext::getVaListTagDecl() const {
7469 // Force the creation of VaListTagDecl by building the __builtin_va_list
Meador Ingecfb60902012-07-01 15:57:25 +00007470 // declaration.
Richard Smith9b88a4c2015-07-27 05:40:23 +00007471 if (!VaListTagDecl)
7472 (void)getBuiltinVaListDecl();
Meador Ingecfb60902012-07-01 15:57:25 +00007473
Richard Smith9b88a4c2015-07-27 05:40:23 +00007474 return VaListTagDecl;
Meador Ingecfb60902012-07-01 15:57:25 +00007475}
7476
Charles Davisc7d5c942015-09-17 20:55:33 +00007477TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const {
7478 if (!BuiltinMSVaListDecl)
7479 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
7480
7481 return BuiltinMSVaListDecl;
7482}
7483
Erich Keane41af9712018-04-16 21:30:08 +00007484bool ASTContext::canBuiltinBeRedeclared(const FunctionDecl *FD) const {
7485 return BuiltinInfo.canBeRedeclared(FD->getBuiltinID());
7486}
7487
Ted Kremenek1b0ea822008-01-07 19:49:32 +00007488void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00007489 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00007490 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00007491
Ted Kremenek1b0ea822008-01-07 19:49:32 +00007492 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00007493}
7494
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007495/// Retrieve the template name that corresponds to a non-empty
John McCalld28ae272009-12-02 08:04:21 +00007496/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00007497TemplateName
7498ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
7499 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00007500 unsigned size = End - Begin;
7501 assert(size > 1 && "set is not overloaded!");
7502
7503 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
7504 size * sizeof(FunctionTemplateDecl*));
Eugene Zelenko7855e772018-04-03 00:11:50 +00007505 auto *OT = new (memory) OverloadedTemplateStorage(size);
John McCalld28ae272009-12-02 08:04:21 +00007506
7507 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00007508 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00007509 NamedDecl *D = *I;
7510 assert(isa<FunctionTemplateDecl>(D) ||
Richard Smithef53a3e2018-06-06 16:36:56 +00007511 isa<UnresolvedUsingValueDecl>(D) ||
John McCalld28ae272009-12-02 08:04:21 +00007512 (isa<UsingShadowDecl>(D) &&
7513 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
7514 *Storage++ = D;
7515 }
7516
7517 return TemplateName(OT);
7518}
7519
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007520/// Retrieve the template name that represents a qualified
Douglas Gregordc572a32009-03-30 22:58:21 +00007521/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00007522TemplateName
7523ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
7524 bool TemplateKeyword,
7525 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00007526 assert(NNS && "Missing nested-name-specifier in qualified template name");
Fangrui Song6907ce22018-07-30 19:24:48 +00007527
Douglas Gregorc42075a2010-02-04 18:10:26 +00007528 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00007529 llvm::FoldingSetNodeID ID;
7530 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
7531
Craig Topper36250ad2014-05-12 05:36:57 +00007532 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00007533 QualifiedTemplateName *QTN =
7534 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7535 if (!QTN) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007536 QTN = new (*this, alignof(QualifiedTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007537 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00007538 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
7539 }
7540
7541 return TemplateName(QTN);
7542}
7543
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007544/// Retrieve the template name that represents a dependent
Douglas Gregordc572a32009-03-30 22:58:21 +00007545/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00007546TemplateName
7547ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
7548 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00007549 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00007550 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00007551
7552 llvm::FoldingSetNodeID ID;
7553 DependentTemplateName::Profile(ID, NNS, Name);
7554
Craig Topper36250ad2014-05-12 05:36:57 +00007555 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00007556 DependentTemplateName *QTN =
7557 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7558
7559 if (QTN)
7560 return TemplateName(QTN);
7561
7562 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
7563 if (CanonNNS == NNS) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007564 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007565 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00007566 } else {
7567 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007568 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007569 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00007570 DependentTemplateName *CheckQTN =
7571 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7572 assert(!CheckQTN && "Dependent type name canonicalization broken");
7573 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00007574 }
7575
7576 DependentTemplateNames.InsertNode(QTN, InsertPos);
7577 return TemplateName(QTN);
7578}
7579
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007580/// Retrieve the template name that represents a dependent
Douglas Gregor71395fa2009-11-04 00:56:37 +00007581/// template name such as \c MetaFun::template operator+.
Fangrui Song6907ce22018-07-30 19:24:48 +00007582TemplateName
Douglas Gregor71395fa2009-11-04 00:56:37 +00007583ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00007584 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00007585 assert((!NNS || NNS->isDependent()) &&
7586 "Nested name specifier must be dependent");
Fangrui Song6907ce22018-07-30 19:24:48 +00007587
Douglas Gregor71395fa2009-11-04 00:56:37 +00007588 llvm::FoldingSetNodeID ID;
7589 DependentTemplateName::Profile(ID, NNS, Operator);
Craig Topper36250ad2014-05-12 05:36:57 +00007590
7591 void *InsertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00007592 DependentTemplateName *QTN
7593 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Fangrui Song6907ce22018-07-30 19:24:48 +00007594
Douglas Gregor71395fa2009-11-04 00:56:37 +00007595 if (QTN)
7596 return TemplateName(QTN);
Fangrui Song6907ce22018-07-30 19:24:48 +00007597
Douglas Gregor71395fa2009-11-04 00:56:37 +00007598 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
7599 if (CanonNNS == NNS) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007600 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007601 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00007602 } else {
7603 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007604 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007605 DependentTemplateName(NNS, Operator, Canon);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007606
Douglas Gregorc42075a2010-02-04 18:10:26 +00007607 DependentTemplateName *CheckQTN
7608 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7609 assert(!CheckQTN && "Dependent template name canonicalization broken");
7610 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00007611 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007612
Douglas Gregor71395fa2009-11-04 00:56:37 +00007613 DependentTemplateNames.InsertNode(QTN, InsertPos);
7614 return TemplateName(QTN);
7615}
7616
Fangrui Song6907ce22018-07-30 19:24:48 +00007617TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00007618ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
7619 TemplateName replacement) const {
7620 llvm::FoldingSetNodeID ID;
7621 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00007622
7623 void *insertPos = nullptr;
John McCalld9dfe3a2011-06-30 08:33:18 +00007624 SubstTemplateTemplateParmStorage *subst
7625 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
Fangrui Song6907ce22018-07-30 19:24:48 +00007626
John McCalld9dfe3a2011-06-30 08:33:18 +00007627 if (!subst) {
7628 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
7629 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
7630 }
7631
7632 return TemplateName(subst);
7633}
7634
Fangrui Song6907ce22018-07-30 19:24:48 +00007635TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00007636ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
7637 const TemplateArgument &ArgPack) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00007638 auto &Self = const_cast<ASTContext &>(*this);
Douglas Gregor5590be02011-01-15 06:45:20 +00007639 llvm::FoldingSetNodeID ID;
7640 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00007641
7642 void *InsertPos = nullptr;
Douglas Gregor5590be02011-01-15 06:45:20 +00007643 SubstTemplateTemplateParmPackStorage *Subst
7644 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
Fangrui Song6907ce22018-07-30 19:24:48 +00007645
Douglas Gregor5590be02011-01-15 06:45:20 +00007646 if (!Subst) {
Fangrui Song6907ce22018-07-30 19:24:48 +00007647 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00007648 ArgPack.pack_size(),
7649 ArgPack.pack_begin());
7650 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
7651 }
7652
7653 return TemplateName(Subst);
7654}
7655
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007656/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00007657/// TargetInfo, produce the corresponding type. The unsigned @p Type
7658/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00007659CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007660 switch (Type) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00007661 case TargetInfo::NoInt: return {};
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00007662 case TargetInfo::SignedChar: return SignedCharTy;
7663 case TargetInfo::UnsignedChar: return UnsignedCharTy;
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007664 case TargetInfo::SignedShort: return ShortTy;
7665 case TargetInfo::UnsignedShort: return UnsignedShortTy;
7666 case TargetInfo::SignedInt: return IntTy;
7667 case TargetInfo::UnsignedInt: return UnsignedIntTy;
7668 case TargetInfo::SignedLong: return LongTy;
7669 case TargetInfo::UnsignedLong: return UnsignedLongTy;
7670 case TargetInfo::SignedLongLong: return LongLongTy;
7671 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
7672 }
7673
David Blaikie83d382b2011-09-23 05:06:16 +00007674 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007675}
Ted Kremenek77c51b22008-07-24 23:58:27 +00007676
7677//===----------------------------------------------------------------------===//
7678// Type Predicates.
7679//===----------------------------------------------------------------------===//
7680
Fariborz Jahanian96207692009-02-18 21:49:28 +00007681/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
7682/// garbage collection attribute.
7683///
John McCall553d45a2011-01-12 00:34:59 +00007684Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007685 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00007686 return Qualifiers::GCNone;
7687
David Blaikiebbafb8a2012-03-11 07:00:24 +00007688 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00007689 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
7690
7691 // Default behaviour under objective-C's gc is for ObjC pointers
7692 // (or pointers to them) be treated as though they were declared
7693 // as __strong.
7694 if (GCAttrs == Qualifiers::GCNone) {
7695 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
7696 return Qualifiers::Strong;
7697 else if (Ty->isPointerType())
7698 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
7699 } else {
7700 // It's not valid to set GC attributes on anything that isn't a
7701 // pointer.
7702#ifndef NDEBUG
7703 QualType CT = Ty->getCanonicalTypeInternal();
Eugene Zelenko7855e772018-04-03 00:11:50 +00007704 while (const auto *AT = dyn_cast<ArrayType>(CT))
John McCall553d45a2011-01-12 00:34:59 +00007705 CT = AT->getElementType();
7706 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
7707#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00007708 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00007709 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00007710}
7711
Chris Lattner49af6a42008-04-07 06:51:04 +00007712//===----------------------------------------------------------------------===//
7713// Type Compatibility Testing
7714//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00007715
Mike Stump11289f42009-09-09 15:08:12 +00007716/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00007717/// compatible.
7718static bool areCompatVectorTypes(const VectorType *LHS,
7719 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00007720 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00007721 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00007722 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00007723}
7724
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007725bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
7726 QualType SecondVec) {
7727 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
7728 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
7729
7730 if (hasSameUnqualifiedType(FirstVec, SecondVec))
7731 return true;
7732
Bob Wilsone6aeebb2010-11-12 17:24:54 +00007733 // Treat Neon vector types and most AltiVec vector types as if they are the
7734 // equivalent GCC vector types.
Eugene Zelenko7855e772018-04-03 00:11:50 +00007735 const auto *First = FirstVec->getAs<VectorType>();
7736 const auto *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00007737 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007738 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00007739 First->getVectorKind() != VectorType::AltiVecPixel &&
7740 First->getVectorKind() != VectorType::AltiVecBool &&
7741 Second->getVectorKind() != VectorType::AltiVecPixel &&
7742 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007743 return true;
7744
7745 return false;
7746}
7747
Steve Naroff8e6aee52009-07-23 01:01:38 +00007748//===----------------------------------------------------------------------===//
7749// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
7750//===----------------------------------------------------------------------===//
7751
7752/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
7753/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00007754bool
7755ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
7756 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00007757 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00007758 return true;
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00007759 for (auto *PI : rProto->protocols())
7760 if (ProtocolCompatibleWithProtocol(lProto, PI))
Steve Naroff8e6aee52009-07-23 01:01:38 +00007761 return true;
7762 return false;
7763}
7764
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00007765/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
7766/// Class<pr1, ...>.
Fangrui Song6907ce22018-07-30 19:24:48 +00007767bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007768 QualType rhs) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00007769 const auto *lhsQID = lhs->getAs<ObjCObjectPointerType>();
7770 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00007771 assert((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
Fangrui Song6907ce22018-07-30 19:24:48 +00007772
Aaron Ballman83731462014-03-17 16:14:00 +00007773 for (auto *lhsProto : lhsQID->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007774 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00007775 for (auto *rhsProto : rhsOPT->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007776 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
7777 match = true;
7778 break;
7779 }
7780 }
7781 if (!match)
7782 return false;
7783 }
7784 return true;
7785}
7786
Steve Naroff8e6aee52009-07-23 01:01:38 +00007787/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
7788/// ObjCQualifiedIDType.
7789bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
7790 bool compare) {
7791 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00007792 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00007793 lhs->isObjCIdType() || lhs->isObjCClassType())
7794 return true;
Mike Stump11289f42009-09-09 15:08:12 +00007795 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00007796 rhs->isObjCIdType() || rhs->isObjCClassType())
7797 return true;
7798
7799 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00007800 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00007801
Steve Naroff8e6aee52009-07-23 01:01:38 +00007802 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00007803
Steve Naroff8e6aee52009-07-23 01:01:38 +00007804 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00007805 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00007806 // make sure we check the class hierarchy.
7807 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00007808 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007809 // when comparing an id<P> on lhs with a static type on rhs,
7810 // see if static class implements all of id's protocols, directly or
7811 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00007812 if (!rhsID->ClassImplementsProtocol(I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00007813 return false;
7814 }
7815 }
7816 // If there are no qualifiers and no interface, we have an 'id'.
7817 return true;
7818 }
Mike Stump11289f42009-09-09 15:08:12 +00007819 // Both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00007820 for (auto *lhsProto : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007821 bool match = false;
7822
7823 // when comparing an id<P> on lhs with a static type on rhs,
7824 // see if static class implements all of id's protocols, directly or
7825 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00007826 for (auto *rhsProto : rhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007827 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7828 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7829 match = true;
7830 break;
7831 }
7832 }
Mike Stump11289f42009-09-09 15:08:12 +00007833 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00007834 // make sure we check the class hierarchy.
7835 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00007836 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007837 // when comparing an id<P> on lhs with a static type on rhs,
7838 // see if static class implements all of id's protocols, directly or
7839 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00007840 if (rhsID->ClassImplementsProtocol(I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007841 match = true;
7842 break;
7843 }
7844 }
7845 }
7846 if (!match)
7847 return false;
7848 }
Mike Stump11289f42009-09-09 15:08:12 +00007849
Steve Naroff8e6aee52009-07-23 01:01:38 +00007850 return true;
7851 }
Mike Stump11289f42009-09-09 15:08:12 +00007852
Steve Naroff8e6aee52009-07-23 01:01:38 +00007853 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
7854 assert(rhsQID && "One of the LHS/RHS should be id<x>");
7855
Mike Stump11289f42009-09-09 15:08:12 +00007856 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00007857 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007858 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00007859 for (auto *lhsProto : lhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007860 bool match = false;
7861
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007862 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00007863 // see if static class implements all of id's protocols, directly or
7864 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007865 // First, lhs protocols in the qualifier list must be found, direct
7866 // or indirect in rhs's qualifier list or it is a mismatch.
Aaron Ballman83731462014-03-17 16:14:00 +00007867 for (auto *rhsProto : rhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007868 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7869 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7870 match = true;
7871 break;
7872 }
7873 }
7874 if (!match)
7875 return false;
7876 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007877
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007878 // Static class's protocols, or its super class or category protocols
7879 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
7880 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
7881 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
7882 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
7883 // This is rather dubious but matches gcc's behavior. If lhs has
7884 // no type qualifier and its class has no static protocol(s)
7885 // assume that it is mismatch.
7886 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
7887 return false;
Aaron Ballman83731462014-03-17 16:14:00 +00007888 for (auto *lhsProto : LHSInheritedProtocols) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007889 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00007890 for (auto *rhsProto : rhsQID->quals()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007891 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7892 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7893 match = true;
7894 break;
7895 }
7896 }
7897 if (!match)
7898 return false;
7899 }
7900 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00007901 return true;
7902 }
7903 return false;
7904}
7905
Eli Friedman47f77112008-08-22 00:56:42 +00007906/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00007907/// compatible for assignment from RHS to LHS. This handles validation of any
7908/// protocol qualifiers on the LHS or RHS.
Steve Naroff7cae42b2009-07-10 23:34:53 +00007909bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
7910 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00007911 const ObjCObjectType* LHS = LHSOPT->getObjectType();
7912 const ObjCObjectType* RHS = RHSOPT->getObjectType();
7913
Steve Naroff1329fa02009-07-15 18:40:39 +00007914 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00007915 if (LHS->isObjCUnqualifiedIdOrClass() ||
7916 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00007917 return true;
7918
Douglas Gregorab209d82015-07-07 03:58:42 +00007919 // Function object that propagates a successful result or handles
7920 // __kindof types.
7921 auto finish = [&](bool succeeded) -> bool {
7922 if (succeeded)
7923 return true;
7924
7925 if (!RHS->isKindOfType())
7926 return false;
7927
7928 // Strip off __kindof and protocol qualifiers, then check whether
7929 // we can assign the other way.
7930 return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this),
7931 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
7932 };
7933
7934 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
7935 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
7936 QualType(RHSOPT,0),
7937 false));
7938 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007939
Douglas Gregorab209d82015-07-07 03:58:42 +00007940 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
7941 return finish(ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
7942 QualType(RHSOPT,0)));
7943 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007944
John McCall8b07ec22010-05-15 11:32:37 +00007945 // If we have 2 user-defined types, fall into that path.
Douglas Gregorab209d82015-07-07 03:58:42 +00007946 if (LHS->getInterface() && RHS->getInterface()) {
7947 return finish(canAssignObjCInterfaces(LHS, RHS));
7948 }
Mike Stump11289f42009-09-09 15:08:12 +00007949
Steve Naroff8e6aee52009-07-23 01:01:38 +00007950 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00007951}
7952
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007953/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Fangrui Song6907ce22018-07-30 19:24:48 +00007954/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007955/// arguments in block literals. When passed as arguments, passing 'A*' where
7956/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
7957/// not OK. For the return type, the opposite is not OK.
7958bool ASTContext::canAssignObjCInterfacesInBlockPointer(
7959 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007960 const ObjCObjectPointerType *RHSOPT,
7961 bool BlockReturnType) {
Douglas Gregorab209d82015-07-07 03:58:42 +00007962
7963 // Function object that propagates a successful result or handles
7964 // __kindof types.
7965 auto finish = [&](bool succeeded) -> bool {
7966 if (succeeded)
7967 return true;
7968
7969 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
7970 if (!Expected->isKindOfType())
7971 return false;
7972
7973 // Strip off __kindof and protocol qualifiers, then check whether
7974 // we can assign the other way.
7975 return canAssignObjCInterfacesInBlockPointer(
7976 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
7977 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
7978 BlockReturnType);
7979 };
7980
Fariborz Jahanian440a6832010-04-06 17:23:39 +00007981 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007982 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00007983
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007984 if (LHSOPT->isObjCBuiltinType()) {
Douglas Gregorab209d82015-07-07 03:58:42 +00007985 return finish(RHSOPT->isObjCBuiltinType() ||
7986 RHSOPT->isObjCQualifiedIdType());
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007987 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007988
Fariborz Jahanian440a6832010-04-06 17:23:39 +00007989 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Douglas Gregorab209d82015-07-07 03:58:42 +00007990 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
7991 QualType(RHSOPT,0),
7992 false));
Fangrui Song6907ce22018-07-30 19:24:48 +00007993
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007994 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
7995 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
7996 if (LHS && RHS) { // We have 2 user-defined types.
7997 if (LHS != RHS) {
7998 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00007999 return finish(BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008000 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00008001 return finish(!BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008002 }
8003 else
8004 return true;
8005 }
8006 return false;
8007}
8008
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008009/// Comparison routine for Objective-C protocols to be used with
8010/// llvm::array_pod_sort.
8011static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
8012 ObjCProtocolDecl * const *rhs) {
8013 return (*lhs)->getName().compare((*rhs)->getName());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008014}
8015
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008016/// getIntersectionOfProtocols - This routine finds the intersection of set
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008017/// of protocols inherited from two distinct objective-c pointer objects with
8018/// the given common base.
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008019/// It is used to build composite qualifier list of the composite type of
8020/// the conditional expression involving two objective-c pointer objects.
Fangrui Song6907ce22018-07-30 19:24:48 +00008021static
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008022void getIntersectionOfProtocols(ASTContext &Context,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008023 const ObjCInterfaceDecl *CommonBase,
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008024 const ObjCObjectPointerType *LHSOPT,
8025 const ObjCObjectPointerType *RHSOPT,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008026 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
Fangrui Song6907ce22018-07-30 19:24:48 +00008027
John McCall8b07ec22010-05-15 11:32:37 +00008028 const ObjCObjectType* LHS = LHSOPT->getObjectType();
8029 const ObjCObjectType* RHS = RHSOPT->getObjectType();
8030 assert(LHS->getInterface() && "LHS must have an interface base");
8031 assert(RHS->getInterface() && "RHS must have an interface base");
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008032
8033 // Add all of the protocols for the LHS.
8034 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
8035
8036 // Start with the protocol qualifiers.
8037 for (auto proto : LHS->quals()) {
8038 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008039 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008040
8041 // Also add the protocols associated with the LHS interface.
8042 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
8043
8044 // Add all of the protocls for the RHS.
8045 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
8046
8047 // Start with the protocol qualifiers.
8048 for (auto proto : RHS->quals()) {
8049 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008050 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008051
8052 // Also add the protocols associated with the RHS interface.
8053 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
8054
8055 // Compute the intersection of the collected protocol sets.
8056 for (auto proto : LHSProtocolSet) {
8057 if (RHSProtocolSet.count(proto))
8058 IntersectionSet.push_back(proto);
8059 }
8060
8061 // Compute the set of protocols that is implied by either the common type or
8062 // the protocols within the intersection.
8063 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
8064 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
8065
8066 // Remove any implied protocols from the list of inherited protocols.
8067 if (!ImpliedProtocols.empty()) {
8068 IntersectionSet.erase(
8069 std::remove_if(IntersectionSet.begin(),
8070 IntersectionSet.end(),
8071 [&](ObjCProtocolDecl *proto) -> bool {
8072 return ImpliedProtocols.count(proto) > 0;
8073 }),
8074 IntersectionSet.end());
8075 }
8076
8077 // Sort the remaining protocols by name.
8078 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
8079 compareObjCProtocolsByName);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008080}
8081
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008082/// Determine whether the first type is a subtype of the second.
8083static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
8084 QualType rhs) {
8085 // Common case: two object pointers.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008086 const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
8087 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008088 if (lhsOPT && rhsOPT)
8089 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
8090
8091 // Two block pointers.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008092 const auto *lhsBlock = lhs->getAs<BlockPointerType>();
8093 const auto *rhsBlock = rhs->getAs<BlockPointerType>();
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008094 if (lhsBlock && rhsBlock)
8095 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
8096
8097 // If either is an unqualified 'id' and the other is a block, it's
8098 // acceptable.
8099 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
8100 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
8101 return true;
8102
8103 return false;
8104}
8105
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008106// Check that the given Objective-C type argument lists are equivalent.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008107static bool sameObjCTypeArgs(ASTContext &ctx,
8108 const ObjCInterfaceDecl *iface,
8109 ArrayRef<QualType> lhsArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00008110 ArrayRef<QualType> rhsArgs,
8111 bool stripKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008112 if (lhsArgs.size() != rhsArgs.size())
8113 return false;
8114
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008115 ObjCTypeParamList *typeParams = iface->getTypeParamList();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008116 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008117 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
8118 continue;
8119
8120 switch (typeParams->begin()[i]->getVariance()) {
8121 case ObjCTypeParamVariance::Invariant:
Douglas Gregorab209d82015-07-07 03:58:42 +00008122 if (!stripKindOf ||
8123 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
8124 rhsArgs[i].stripObjCKindOfType(ctx))) {
8125 return false;
8126 }
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008127 break;
8128
8129 case ObjCTypeParamVariance::Covariant:
8130 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
8131 return false;
8132 break;
8133
8134 case ObjCTypeParamVariance::Contravariant:
8135 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
8136 return false;
8137 break;
Douglas Gregorab209d82015-07-07 03:58:42 +00008138 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008139 }
8140
8141 return true;
8142}
8143
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00008144QualType ASTContext::areCommonBaseCompatible(
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008145 const ObjCObjectPointerType *Lptr,
8146 const ObjCObjectPointerType *Rptr) {
John McCall8b07ec22010-05-15 11:32:37 +00008147 const ObjCObjectType *LHS = Lptr->getObjectType();
8148 const ObjCObjectType *RHS = Rptr->getObjectType();
8149 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
8150 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008151
8152 if (!LDecl || !RDecl)
Eugene Zelenko7855e772018-04-03 00:11:50 +00008153 return {};
Douglas Gregore83b9562015-07-07 03:57:53 +00008154
Manman Renc46f7d12016-05-06 19:35:02 +00008155 // When either LHS or RHS is a kindof type, we should return a kindof type.
8156 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
8157 // kindof(A).
8158 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
8159
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008160 // Follow the left-hand side up the class hierarchy until we either hit a
8161 // root or find the RHS. Record the ancestors in case we don't find it.
8162 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
8163 LHSAncestors;
8164 while (true) {
8165 // Record this ancestor. We'll need this if the common type isn't in the
8166 // path from the LHS to the root.
8167 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
Douglas Gregore83b9562015-07-07 03:57:53 +00008168
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008169 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
8170 // Get the type arguments.
8171 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
8172 bool anyChanges = false;
8173 if (LHS->isSpecialized() && RHS->isSpecialized()) {
8174 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008175 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
8176 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00008177 /*stripKindOf=*/true))
Eugene Zelenko7855e772018-04-03 00:11:50 +00008178 return {};
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008179 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
8180 // If only one has type arguments, the result will not have type
8181 // arguments.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00008182 LHSTypeArgs = {};
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008183 anyChanges = true;
8184 }
8185
8186 // Compute the intersection of protocols.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008187 SmallVector<ObjCProtocolDecl *, 8> Protocols;
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008188 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
8189 Protocols);
John McCall8b07ec22010-05-15 11:32:37 +00008190 if (!Protocols.empty())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008191 anyChanges = true;
8192
8193 // If anything in the LHS will have changed, build a new result type.
Manman Renc46f7d12016-05-06 19:35:02 +00008194 // If we need to return a kindof type but LHS is not a kindof type, we
8195 // build a new result type.
8196 if (anyChanges || LHS->isKindOfType() != anyKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008197 QualType Result = getObjCInterfaceType(LHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00008198 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
Manman Renc46f7d12016-05-06 19:35:02 +00008199 anyKindOf || LHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008200 return getObjCObjectPointerType(Result);
8201 }
8202
8203 return getObjCObjectPointerType(QualType(LHS, 0));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008204 }
Douglas Gregore83b9562015-07-07 03:57:53 +00008205
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008206 // Find the superclass.
Douglas Gregore83b9562015-07-07 03:57:53 +00008207 QualType LHSSuperType = LHS->getSuperClassType();
8208 if (LHSSuperType.isNull())
8209 break;
8210
8211 LHS = LHSSuperType->castAs<ObjCObjectType>();
8212 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008213
8214 // We didn't find anything by following the LHS to its root; now check
8215 // the RHS against the cached set of ancestors.
8216 while (true) {
8217 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
8218 if (KnownLHS != LHSAncestors.end()) {
8219 LHS = KnownLHS->second;
8220
8221 // Get the type arguments.
8222 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
8223 bool anyChanges = false;
8224 if (LHS->isSpecialized() && RHS->isSpecialized()) {
8225 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008226 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
8227 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00008228 /*stripKindOf=*/true))
Eugene Zelenko7855e772018-04-03 00:11:50 +00008229 return {};
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008230 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
8231 // If only one has type arguments, the result will not have type
8232 // arguments.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00008233 RHSTypeArgs = {};
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008234 anyChanges = true;
8235 }
8236
8237 // Compute the intersection of protocols.
8238 SmallVector<ObjCProtocolDecl *, 8> Protocols;
8239 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
8240 Protocols);
8241 if (!Protocols.empty())
8242 anyChanges = true;
8243
Manman Renc46f7d12016-05-06 19:35:02 +00008244 // If we need to return a kindof type but RHS is not a kindof type, we
8245 // build a new result type.
8246 if (anyChanges || RHS->isKindOfType() != anyKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008247 QualType Result = getObjCInterfaceType(RHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00008248 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
Manman Renc46f7d12016-05-06 19:35:02 +00008249 anyKindOf || RHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008250 return getObjCObjectPointerType(Result);
8251 }
8252
8253 return getObjCObjectPointerType(QualType(RHS, 0));
8254 }
8255
8256 // Find the superclass of the RHS.
8257 QualType RHSSuperType = RHS->getSuperClassType();
8258 if (RHSSuperType.isNull())
8259 break;
8260
8261 RHS = RHSSuperType->castAs<ObjCObjectType>();
8262 }
8263
Eugene Zelenko7855e772018-04-03 00:11:50 +00008264 return {};
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00008265}
8266
John McCall8b07ec22010-05-15 11:32:37 +00008267bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
8268 const ObjCObjectType *RHS) {
8269 assert(LHS->getInterface() && "LHS is not an interface type");
8270 assert(RHS->getInterface() && "RHS is not an interface type");
8271
Chris Lattner49af6a42008-04-07 06:51:04 +00008272 // Verify that the base decls are compatible: the RHS must be a subclass of
8273 // the LHS.
Douglas Gregore83b9562015-07-07 03:57:53 +00008274 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
8275 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
8276 if (!IsSuperClass)
Chris Lattner49af6a42008-04-07 06:51:04 +00008277 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008278
Douglas Gregore83b9562015-07-07 03:57:53 +00008279 // If the LHS has protocol qualifiers, determine whether all of them are
8280 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
8281 // LHS).
8282 if (LHS->getNumProtocols() > 0) {
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00008283 // OK if conversion of LHS to SuperClass results in narrowing of types
8284 // ; i.e., SuperClass may implement at least one of the protocols
8285 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
8286 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
8287 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
8288 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
8289 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
8290 // qualifiers.
8291 for (auto *RHSPI : RHS->quals())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008292 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00008293 // If there is no protocols associated with RHS, it is not a match.
8294 if (SuperClassInheritedProtocols.empty())
Steve Naroff114aecb2009-03-01 16:12:44 +00008295 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00008296
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00008297 for (const auto *LHSProto : LHS->quals()) {
8298 bool SuperImplementsProtocol = false;
8299 for (auto *SuperClassProto : SuperClassInheritedProtocols)
8300 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
8301 SuperImplementsProtocol = true;
8302 break;
8303 }
8304 if (!SuperImplementsProtocol)
8305 return false;
8306 }
Chris Lattner49af6a42008-04-07 06:51:04 +00008307 }
Douglas Gregore83b9562015-07-07 03:57:53 +00008308
8309 // If the LHS is specialized, we may need to check type arguments.
8310 if (LHS->isSpecialized()) {
8311 // Follow the superclass chain until we've matched the LHS class in the
8312 // hierarchy. This substitutes type arguments through.
8313 const ObjCObjectType *RHSSuper = RHS;
8314 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
8315 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
8316
8317 // If the RHS is specializd, compare type arguments.
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008318 if (RHSSuper->isSpecialized() &&
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008319 !sameObjCTypeArgs(*this, LHS->getInterface(),
8320 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00008321 /*stripKindOf=*/true)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008322 return false;
Douglas Gregore83b9562015-07-07 03:57:53 +00008323 }
8324 }
8325
8326 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00008327}
8328
Steve Naroffb7605152009-02-12 17:52:19 +00008329bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
8330 // get the "pointed to" types
Eugene Zelenko7855e772018-04-03 00:11:50 +00008331 const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
8332 const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00008333
Steve Naroff7cae42b2009-07-10 23:34:53 +00008334 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00008335 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00008336
8337 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
8338 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00008339}
8340
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00008341bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
8342 return canAssignObjCInterfaces(
8343 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
8344 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
8345}
8346
Mike Stump11289f42009-09-09 15:08:12 +00008347/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00008348/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00008349/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00008350/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008351bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
8352 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00008353 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00008354 return hasSameType(LHS, RHS);
Joey Gouly5788b782016-11-18 14:10:54 +00008355
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008356 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00008357}
8358
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00008359bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00008360 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00008361}
8362
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008363bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
8364 return !mergeTypes(LHS, RHS, true).isNull();
8365}
8366
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00008367/// mergeTransparentUnionType - if T is a transparent union type and a member
8368/// of T is compatible with SubType, return the merged type, else return
8369/// QualType()
8370QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
8371 bool OfBlockPointer,
8372 bool Unqualified) {
8373 if (const RecordType *UT = T->getAsUnionType()) {
8374 RecordDecl *UD = UT->getDecl();
8375 if (UD->hasAttr<TransparentUnionAttr>()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008376 for (const auto *I : UD->fields()) {
8377 QualType ET = I->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00008378 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
8379 if (!MT.isNull())
8380 return MT;
8381 }
8382 }
8383 }
8384
Eugene Zelenko7855e772018-04-03 00:11:50 +00008385 return {};
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00008386}
8387
Alp Toker9cacbab2014-01-20 20:26:09 +00008388/// mergeFunctionParameterTypes - merge two types which appear as function
8389/// parameter types
8390QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
8391 bool OfBlockPointer,
8392 bool Unqualified) {
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00008393 // GNU extension: two types are compatible if they appear as a function
8394 // argument, one of the types is a transparent union type and the other
8395 // type is compatible with a union member
8396 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
8397 Unqualified);
8398 if (!lmerge.isNull())
8399 return lmerge;
8400
8401 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
8402 Unqualified);
8403 if (!rmerge.isNull())
8404 return rmerge;
8405
8406 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
8407}
8408
Fangrui Song6907ce22018-07-30 19:24:48 +00008409QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008410 bool OfBlockPointer,
8411 bool Unqualified) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00008412 const auto *lbase = lhs->getAs<FunctionType>();
8413 const auto *rbase = rhs->getAs<FunctionType>();
8414 const auto *lproto = dyn_cast<FunctionProtoType>(lbase);
8415 const auto *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00008416 bool allLTypes = true;
8417 bool allRTypes = true;
8418
8419 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008420 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00008421 if (OfBlockPointer) {
Alp Toker314cc812014-01-25 16:55:45 +00008422 QualType RHS = rbase->getReturnType();
8423 QualType LHS = lbase->getReturnType();
Fariborz Jahanian17825972011-02-11 18:46:17 +00008424 bool UnqualifiedResult = Unqualified;
8425 if (!UnqualifiedResult)
8426 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00008427 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00008428 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008429 else
Alp Toker314cc812014-01-25 16:55:45 +00008430 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
John McCall8c6b56f2010-12-15 01:06:38 +00008431 Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00008432 if (retType.isNull())
8433 return {};
Fangrui Song6907ce22018-07-30 19:24:48 +00008434
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008435 if (Unqualified)
8436 retType = retType.getUnqualifiedType();
8437
Alp Toker314cc812014-01-25 16:55:45 +00008438 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
8439 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008440 if (Unqualified) {
8441 LRetType = LRetType.getUnqualifiedType();
8442 RRetType = RRetType.getUnqualifiedType();
8443 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008444
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008445 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00008446 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008447 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00008448 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00008449
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00008450 // FIXME: double check this
8451 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
8452 // rbase->getRegParmAttr() != 0 &&
8453 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00008454 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
8455 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00008456
Douglas Gregor8c940862010-01-18 17:14:39 +00008457 // Compatible functions must have compatible calling conventions
Reid Kleckner78af0702013-08-27 23:08:25 +00008458 if (lbaseInfo.getCC() != rbaseInfo.getCC())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008459 return {};
Mike Stump11289f42009-09-09 15:08:12 +00008460
John McCall8c6b56f2010-12-15 01:06:38 +00008461 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00008462 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008463 return {};
John McCall8c6b56f2010-12-15 01:06:38 +00008464 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008465 return {};
John McCall8c6b56f2010-12-15 01:06:38 +00008466
John McCall31168b02011-06-15 23:02:42 +00008467 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008468 return {};
Oren Ben Simhon318a6ea2017-04-27 12:01:00 +00008469 if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008470 return {};
Oren Ben Simhon220671a2018-03-17 13:31:35 +00008471 if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008472 return {};
John McCall31168b02011-06-15 23:02:42 +00008473
John McCall8c6b56f2010-12-15 01:06:38 +00008474 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
8475 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00008476
Rafael Espindola8778c282012-11-29 16:09:03 +00008477 if (lbaseInfo.getNoReturn() != NoReturn)
8478 allLTypes = false;
8479 if (rbaseInfo.getNoReturn() != NoReturn)
8480 allRTypes = false;
8481
John McCall31168b02011-06-15 23:02:42 +00008482 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00008483
Eli Friedman47f77112008-08-22 00:56:42 +00008484 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00008485 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
8486 "C++ shouldn't be here");
Alp Toker601b22c2014-01-21 23:35:24 +00008487 // Compatible functions must have the same number of parameters
8488 if (lproto->getNumParams() != rproto->getNumParams())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008489 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00008490
8491 // Variadic and non-variadic functions aren't compatible
8492 if (lproto->isVariadic() != rproto->isVariadic())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008493 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00008494
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00008495 if (lproto->getTypeQuals() != rproto->getTypeQuals())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008496 return {};
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00008497
Akira Hatanaka98a49332017-09-22 00:41:05 +00008498 SmallVector<FunctionProtoType::ExtParameterInfo, 4> newParamInfos;
8499 bool canUseLeft, canUseRight;
8500 if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight,
8501 newParamInfos))
Eugene Zelenko7855e772018-04-03 00:11:50 +00008502 return {};
Alp Toker601b22c2014-01-21 23:35:24 +00008503
Akira Hatanaka98a49332017-09-22 00:41:05 +00008504 if (!canUseLeft)
8505 allLTypes = false;
8506 if (!canUseRight)
8507 allRTypes = false;
8508
Alp Toker601b22c2014-01-21 23:35:24 +00008509 // Check parameter type compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008510 SmallVector<QualType, 10> types;
Alp Toker601b22c2014-01-21 23:35:24 +00008511 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
8512 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
8513 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
8514 QualType paramType = mergeFunctionParameterTypes(
8515 lParamType, rParamType, OfBlockPointer, Unqualified);
8516 if (paramType.isNull())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008517 return {};
Alp Toker601b22c2014-01-21 23:35:24 +00008518
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008519 if (Unqualified)
Alp Toker601b22c2014-01-21 23:35:24 +00008520 paramType = paramType.getUnqualifiedType();
8521
8522 types.push_back(paramType);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008523 if (Unqualified) {
Alp Toker601b22c2014-01-21 23:35:24 +00008524 lParamType = lParamType.getUnqualifiedType();
8525 rParamType = rParamType.getUnqualifiedType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008526 }
Alp Toker601b22c2014-01-21 23:35:24 +00008527
8528 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00008529 allLTypes = false;
Alp Toker601b22c2014-01-21 23:35:24 +00008530 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00008531 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00008532 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008533
Eli Friedman47f77112008-08-22 00:56:42 +00008534 if (allLTypes) return lhs;
8535 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00008536
8537 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
8538 EPI.ExtInfo = einfo;
Akira Hatanaka98a49332017-09-22 00:41:05 +00008539 EPI.ExtParameterInfos =
8540 newParamInfos.empty() ? nullptr : newParamInfos.data();
Jordan Rose5c382722013-03-08 21:51:21 +00008541 return getFunctionType(retType, types, EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00008542 }
8543
8544 if (lproto) allRTypes = false;
8545 if (rproto) allLTypes = false;
8546
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008547 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00008548 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00008549 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eugene Zelenko7855e772018-04-03 00:11:50 +00008550 if (proto->isVariadic())
8551 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00008552 // Check that the types are compatible with the types that
8553 // would result from default argument promotions (C99 6.7.5.3p15).
8554 // The only types actually affected are promotable integer
8555 // types and floats, which would be passed as a different
8556 // type depending on whether the prototype is visible.
Alp Toker601b22c2014-01-21 23:35:24 +00008557 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
8558 QualType paramTy = proto->getParamType(i);
Alp Toker9cacbab2014-01-20 20:26:09 +00008559
Eli Friedman448ce402012-08-30 00:44:15 +00008560 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00008561 // to pass enum values.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008562 if (const auto *Enum = paramTy->getAs<EnumType>()) {
Alp Toker601b22c2014-01-21 23:35:24 +00008563 paramTy = Enum->getDecl()->getIntegerType();
8564 if (paramTy.isNull())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008565 return {};
Eli Friedman448ce402012-08-30 00:44:15 +00008566 }
Alp Toker601b22c2014-01-21 23:35:24 +00008567
8568 if (paramTy->isPromotableIntegerType() ||
8569 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
Eugene Zelenko7855e772018-04-03 00:11:50 +00008570 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00008571 }
8572
8573 if (allLTypes) return lhs;
8574 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00008575
8576 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
8577 EPI.ExtInfo = einfo;
Alp Toker9cacbab2014-01-20 20:26:09 +00008578 return getFunctionType(retType, proto->getParamTypes(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00008579 }
8580
8581 if (allLTypes) return lhs;
8582 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00008583 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00008584}
8585
John McCall433c2e62013-03-21 00:10:07 +00008586/// Given that we have an enum type and a non-enum type, try to merge them.
8587static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
8588 QualType other, bool isBlockReturnType) {
8589 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
8590 // a signed integer type, or an unsigned integer type.
8591 // Compatibility is based on the underlying type, not the promotion
8592 // type.
8593 QualType underlyingType = ET->getDecl()->getIntegerType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00008594 if (underlyingType.isNull())
8595 return {};
John McCall433c2e62013-03-21 00:10:07 +00008596 if (Context.hasSameType(underlyingType, other))
8597 return other;
8598
8599 // In block return types, we're more permissive and accept any
8600 // integral type of the same size.
8601 if (isBlockReturnType && other->isIntegerType() &&
8602 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
8603 return other;
8604
Eugene Zelenko7855e772018-04-03 00:11:50 +00008605 return {};
John McCall433c2e62013-03-21 00:10:07 +00008606}
8607
Fangrui Song6907ce22018-07-30 19:24:48 +00008608QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008609 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00008610 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00008611 // C++ [expr]: If an expression initially has the type "reference to T", the
8612 // type is adjusted to "T" prior to any further analysis, the expression
8613 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00008614 // expression is an lvalue unless the reference is an rvalue reference and
8615 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00008616 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
8617 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008618
8619 if (Unqualified) {
8620 LHS = LHS.getUnqualifiedType();
8621 RHS = RHS.getUnqualifiedType();
8622 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008623
Eli Friedman47f77112008-08-22 00:56:42 +00008624 QualType LHSCan = getCanonicalType(LHS),
8625 RHSCan = getCanonicalType(RHS);
8626
8627 // If two types are identical, they are compatible.
8628 if (LHSCan == RHSCan)
8629 return LHS;
8630
John McCall8ccfcb52009-09-24 19:53:00 +00008631 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00008632 Qualifiers LQuals = LHSCan.getLocalQualifiers();
8633 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00008634 if (LQuals != RQuals) {
8635 // If any of these qualifiers are different, we have a type
8636 // mismatch.
8637 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00008638 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
Roger Ferrer Ibanezd93add32017-02-24 08:41:09 +00008639 LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
8640 LQuals.hasUnaligned() != RQuals.hasUnaligned())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008641 return {};
John McCall8ccfcb52009-09-24 19:53:00 +00008642
8643 // Exactly one GC qualifier difference is allowed: __strong is
8644 // okay if the other type has no GC qualifier but is an Objective
8645 // C object pointer (i.e. implicitly strong by default). We fix
8646 // this by pretending that the unqualified type was actually
8647 // qualified __strong.
8648 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
8649 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
8650 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
8651
8652 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
Eugene Zelenko7855e772018-04-03 00:11:50 +00008653 return {};
John McCall8ccfcb52009-09-24 19:53:00 +00008654
8655 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
8656 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
8657 }
8658 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
8659 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
8660 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00008661 return {};
John McCall8ccfcb52009-09-24 19:53:00 +00008662 }
8663
8664 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00008665
Eli Friedmandcca6332009-06-01 01:22:52 +00008666 Type::TypeClass LHSClass = LHSCan->getTypeClass();
8667 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00008668
Chris Lattnerfd652912008-01-14 05:45:46 +00008669 // We want to consider the two function types to be the same for these
8670 // comparisons, just force one to the other.
8671 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
8672 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00008673
8674 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00008675 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
8676 LHSClass = Type::ConstantArray;
8677 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
8678 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00008679
John McCall8b07ec22010-05-15 11:32:37 +00008680 // ObjCInterfaces are just specialized ObjCObjects.
8681 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
8682 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
8683
Nate Begemance4d7fc2008-04-18 23:10:10 +00008684 // Canonicalize ExtVector -> Vector.
8685 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
8686 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00008687
Chris Lattner95554662008-04-07 05:43:21 +00008688 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00008689 if (LHSClass != RHSClass) {
John McCall433c2e62013-03-21 00:10:07 +00008690 // Note that we only have special rules for turning block enum
8691 // returns into block int returns, not vice-versa.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008692 if (const auto *ETy = LHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00008693 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00008694 }
John McCall9dd450b2009-09-21 23:43:11 +00008695 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00008696 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00008697 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00008698 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00008699 if (OfBlockPointer && !BlockReturnType) {
8700 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
8701 return LHS;
8702 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
8703 return RHS;
8704 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008705
Eugene Zelenko7855e772018-04-03 00:11:50 +00008706 return {};
Steve Naroff32e44c02007-10-15 20:41:53 +00008707 }
Eli Friedman47f77112008-08-22 00:56:42 +00008708
Steve Naroffc6edcbd2008-01-09 22:43:08 +00008709 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00008710 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008711#define TYPE(Class, Base)
8712#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00008713#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008714#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
8715#define DEPENDENT_TYPE(Class, Base) case Type::Class:
8716#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00008717 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008718
Richard Smith27d807c2013-04-30 13:56:41 +00008719 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00008720 case Type::DeducedTemplateSpecialization:
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00008721 case Type::LValueReference:
8722 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008723 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00008724 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008725
John McCall8b07ec22010-05-15 11:32:37 +00008726 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008727 case Type::IncompleteArray:
8728 case Type::VariableArray:
8729 case Type::FunctionProto:
8730 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00008731 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008732
Chris Lattnerfd652912008-01-14 05:45:46 +00008733 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00008734 {
8735 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008736 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
8737 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008738 if (Unqualified) {
8739 LHSPointee = LHSPointee.getUnqualifiedType();
8740 RHSPointee = RHSPointee.getUnqualifiedType();
8741 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008742 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008743 Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00008744 if (ResultType.isNull())
8745 return {};
Eli Friedman091a9ac2009-06-02 05:28:56 +00008746 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00008747 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00008748 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00008749 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00008750 return getPointerType(ResultType);
8751 }
Steve Naroff68e167d2008-12-10 17:49:55 +00008752 case Type::BlockPointer:
8753 {
8754 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008755 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
8756 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008757 if (Unqualified) {
8758 LHSPointee = LHSPointee.getUnqualifiedType();
8759 RHSPointee = RHSPointee.getUnqualifiedType();
8760 }
Anastasia Stulova81a25e352017-03-10 15:23:07 +00008761 if (getLangOpts().OpenCL) {
8762 Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
8763 Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
8764 // Blocks can't be an expression in a ternary operator (OpenCL v2.0
8765 // 6.12.5) thus the following check is asymmetric.
8766 if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual))
Eugene Zelenko7855e772018-04-03 00:11:50 +00008767 return {};
Anastasia Stulova81a25e352017-03-10 15:23:07 +00008768 LHSPteeQual.removeAddressSpace();
8769 RHSPteeQual.removeAddressSpace();
8770 LHSPointee =
8771 QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
8772 RHSPointee =
8773 QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
8774 }
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008775 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
8776 Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00008777 if (ResultType.isNull())
8778 return {};
Steve Naroff68e167d2008-12-10 17:49:55 +00008779 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
8780 return LHS;
8781 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
8782 return RHS;
8783 return getBlockPointerType(ResultType);
8784 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00008785 case Type::Atomic:
8786 {
8787 // Merge two pointer types, while trying to preserve typedef info
8788 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
8789 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
8790 if (Unqualified) {
8791 LHSValue = LHSValue.getUnqualifiedType();
8792 RHSValue = RHSValue.getUnqualifiedType();
8793 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008794 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
Eli Friedman0dfb8892011-10-06 23:00:33 +00008795 Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00008796 if (ResultType.isNull())
8797 return {};
Eli Friedman0dfb8892011-10-06 23:00:33 +00008798 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
8799 return LHS;
8800 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
8801 return RHS;
8802 return getAtomicType(ResultType);
8803 }
Chris Lattnerfd652912008-01-14 05:45:46 +00008804 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00008805 {
8806 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
8807 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
8808 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008809 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00008810
8811 QualType LHSElem = getAsArrayType(LHS)->getElementType();
8812 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008813 if (Unqualified) {
8814 LHSElem = LHSElem.getUnqualifiedType();
8815 RHSElem = RHSElem.getUnqualifiedType();
8816 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008817
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008818 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00008819 if (ResultType.isNull())
8820 return {};
Jeremy Morse8129c5c2018-06-05 09:18:26 +00008821
8822 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
8823 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
8824
8825 // If either side is a variable array, and both are complete, check whether
8826 // the current dimension is definite.
8827 if (LVAT || RVAT) {
8828 auto SizeFetch = [this](const VariableArrayType* VAT,
8829 const ConstantArrayType* CAT)
8830 -> std::pair<bool,llvm::APInt> {
8831 if (VAT) {
8832 llvm::APSInt TheInt;
8833 Expr *E = VAT->getSizeExpr();
8834 if (E && E->isIntegerConstantExpr(TheInt, *this))
8835 return std::make_pair(true, TheInt);
8836 else
8837 return std::make_pair(false, TheInt);
8838 } else if (CAT) {
8839 return std::make_pair(true, CAT->getSize());
8840 } else {
8841 return std::make_pair(false, llvm::APInt());
8842 }
8843 };
8844
8845 bool HaveLSize, HaveRSize;
8846 llvm::APInt LSize, RSize;
8847 std::tie(HaveLSize, LSize) = SizeFetch(LVAT, LCAT);
8848 std::tie(HaveRSize, RSize) = SizeFetch(RVAT, RCAT);
8849 if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(LSize, RSize))
8850 return {}; // Definite, but unequal, array dimension
8851 }
8852
Chris Lattner465fa322008-10-05 17:34:18 +00008853 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
8854 return LHS;
8855 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
8856 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00008857 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
8858 ArrayType::ArraySizeModifier(), 0);
8859 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
8860 ArrayType::ArraySizeModifier(), 0);
Chris Lattner465fa322008-10-05 17:34:18 +00008861 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
8862 return LHS;
8863 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
8864 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00008865 if (LVAT) {
8866 // FIXME: This isn't correct! But tricky to implement because
8867 // the array's size has to be the size of LHS, but the type
8868 // has to be different.
8869 return LHS;
8870 }
8871 if (RVAT) {
8872 // FIXME: This isn't correct! But tricky to implement because
8873 // the array's size has to be the size of RHS, but the type
8874 // has to be different.
8875 return RHS;
8876 }
Eli Friedman3e62c212008-08-22 01:48:21 +00008877 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
8878 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00008879 return getIncompleteArrayType(ResultType,
8880 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00008881 }
Chris Lattnerfd652912008-01-14 05:45:46 +00008882 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008883 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008884 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008885 case Type::Enum:
Eugene Zelenko7855e772018-04-03 00:11:50 +00008886 return {};
Chris Lattnerfd652912008-01-14 05:45:46 +00008887 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00008888 // Only exactly equal builtin types are compatible, which is tested above.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008889 return {};
Daniel Dunbar804c0442009-01-28 21:22:12 +00008890 case Type::Complex:
8891 // Distinct complex types are incompatible.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008892 return {};
Chris Lattner7bbd3d72008-04-07 05:55:38 +00008893 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00008894 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00008895 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
8896 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00008897 return LHS;
Eugene Zelenko7855e772018-04-03 00:11:50 +00008898 return {};
John McCall8b07ec22010-05-15 11:32:37 +00008899 case Type::ObjCObject: {
8900 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00008901 // FIXME: This should be type compatibility, e.g. whether
8902 // "LHS x; RHS x;" at global scope is legal.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008903 const auto *LHSIface = LHS->getAs<ObjCObjectType>();
8904 const auto *RHSIface = RHS->getAs<ObjCObjectType>();
John McCall8b07ec22010-05-15 11:32:37 +00008905 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00008906 return LHS;
8907
Eugene Zelenko7855e772018-04-03 00:11:50 +00008908 return {};
Cedric Venet4fc88b72009-02-21 17:14:49 +00008909 }
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00008910 case Type::ObjCObjectPointer:
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008911 if (OfBlockPointer) {
8912 if (canAssignObjCInterfacesInBlockPointer(
8913 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00008914 RHS->getAs<ObjCObjectPointerType>(),
8915 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00008916 return LHS;
Eugene Zelenko7855e772018-04-03 00:11:50 +00008917 return {};
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008918 }
John McCall9dd450b2009-09-21 23:43:11 +00008919 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
8920 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00008921 return LHS;
8922
Eugene Zelenko7855e772018-04-03 00:11:50 +00008923 return {};
Xiuli Pan9c14e282016-01-09 12:53:17 +00008924 case Type::Pipe:
Joey Goulye3c85de2016-12-01 11:30:49 +00008925 assert(LHS != RHS &&
8926 "Equivalent pipe types should have already been handled!");
Eugene Zelenko7855e772018-04-03 00:11:50 +00008927 return {};
Xiuli Pan9c14e282016-01-09 12:53:17 +00008928 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008929
David Blaikie8a40f702012-01-17 06:56:22 +00008930 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00008931}
Ted Kremenekfc581a92007-10-31 17:10:13 +00008932
Akira Hatanaka98a49332017-09-22 00:41:05 +00008933bool ASTContext::mergeExtParameterInfo(
8934 const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType,
8935 bool &CanUseFirst, bool &CanUseSecond,
8936 SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &NewParamInfos) {
8937 assert(NewParamInfos.empty() && "param info list not empty");
8938 CanUseFirst = CanUseSecond = true;
8939 bool FirstHasInfo = FirstFnType->hasExtParameterInfos();
8940 bool SecondHasInfo = SecondFnType->hasExtParameterInfos();
8941
John McCall18afab72016-03-01 00:49:02 +00008942 // Fast path: if the first type doesn't have ext parameter infos,
Akira Hatanaka98a49332017-09-22 00:41:05 +00008943 // we match if and only if the second type also doesn't have them.
8944 if (!FirstHasInfo && !SecondHasInfo)
8945 return true;
John McCall18afab72016-03-01 00:49:02 +00008946
Akira Hatanaka98a49332017-09-22 00:41:05 +00008947 bool NeedParamInfo = false;
8948 size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size()
8949 : SecondFnType->getExtParameterInfos().size();
John McCall18afab72016-03-01 00:49:02 +00008950
Akira Hatanaka98a49332017-09-22 00:41:05 +00008951 for (size_t I = 0; I < E; ++I) {
8952 FunctionProtoType::ExtParameterInfo FirstParam, SecondParam;
8953 if (FirstHasInfo)
8954 FirstParam = FirstFnType->getExtParameterInfo(I);
8955 if (SecondHasInfo)
8956 SecondParam = SecondFnType->getExtParameterInfo(I);
John McCall18afab72016-03-01 00:49:02 +00008957
Akira Hatanaka98a49332017-09-22 00:41:05 +00008958 // Cannot merge unless everything except the noescape flag matches.
8959 if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false))
John McCall18afab72016-03-01 00:49:02 +00008960 return false;
Akira Hatanaka98a49332017-09-22 00:41:05 +00008961
8962 bool FirstNoEscape = FirstParam.isNoEscape();
8963 bool SecondNoEscape = SecondParam.isNoEscape();
8964 bool IsNoEscape = FirstNoEscape && SecondNoEscape;
8965 NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape));
8966 if (NewParamInfos.back().getOpaqueValue())
8967 NeedParamInfo = true;
8968 if (FirstNoEscape != IsNoEscape)
8969 CanUseFirst = false;
8970 if (SecondNoEscape != IsNoEscape)
8971 CanUseSecond = false;
John McCall18afab72016-03-01 00:49:02 +00008972 }
Akira Hatanaka98a49332017-09-22 00:41:05 +00008973
8974 if (!NeedParamInfo)
8975 NewParamInfos.clear();
8976
Fariborz Jahanian97676972011-09-28 21:52:05 +00008977 return true;
8978}
8979
Chandler Carruth21c90602015-12-30 03:24:14 +00008980void ASTContext::ResetObjCLayout(const ObjCContainerDecl *CD) {
8981 ObjCLayouts[CD] = nullptr;
8982}
8983
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008984/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
8985/// 'RHS' attributes and returns the merged version; including for function
8986/// return types.
8987QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
8988 QualType LHSCan = getCanonicalType(LHS),
8989 RHSCan = getCanonicalType(RHS);
8990 // If two types are identical, they are compatible.
8991 if (LHSCan == RHSCan)
8992 return LHS;
8993 if (RHSCan->isFunctionType()) {
8994 if (!LHSCan->isFunctionType())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008995 return {};
Alp Toker314cc812014-01-25 16:55:45 +00008996 QualType OldReturnType =
8997 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008998 QualType NewReturnType =
Alp Toker314cc812014-01-25 16:55:45 +00008999 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
Fangrui Song6907ce22018-07-30 19:24:48 +00009000 QualType ResReturnType =
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009001 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
9002 if (ResReturnType.isNull())
Eugene Zelenko7855e772018-04-03 00:11:50 +00009003 return {};
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009004 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
9005 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
9006 // In either case, use OldReturnType to build the new function type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00009007 const auto *F = LHS->getAs<FunctionType>();
9008 if (const auto *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00009009 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9010 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner896b32f2013-06-10 20:51:09 +00009011 QualType ResultType =
Alp Toker9cacbab2014-01-20 20:26:09 +00009012 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009013 return ResultType;
9014 }
9015 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00009016 return {};
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009017 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009018
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009019 // If the qualifiers are different, the types can still be merged.
9020 Qualifiers LQuals = LHSCan.getLocalQualifiers();
9021 Qualifiers RQuals = RHSCan.getLocalQualifiers();
9022 if (LQuals != RQuals) {
9023 // If any of these qualifiers are different, we have a type mismatch.
9024 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
9025 LQuals.getAddressSpace() != RQuals.getAddressSpace())
Eugene Zelenko7855e772018-04-03 00:11:50 +00009026 return {};
Fangrui Song6907ce22018-07-30 19:24:48 +00009027
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009028 // Exactly one GC qualifier difference is allowed: __strong is
9029 // okay if the other type has no GC qualifier but is an Objective
9030 // C object pointer (i.e. implicitly strong by default). We fix
9031 // this by pretending that the unqualified type was actually
9032 // qualified __strong.
9033 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
9034 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
9035 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
Fangrui Song6907ce22018-07-30 19:24:48 +00009036
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009037 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
Eugene Zelenko7855e772018-04-03 00:11:50 +00009038 return {};
Fangrui Song6907ce22018-07-30 19:24:48 +00009039
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009040 if (GC_L == Qualifiers::Strong)
9041 return LHS;
9042 if (GC_R == Qualifiers::Strong)
9043 return RHS;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009044 return {};
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009045 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009046
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009047 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
9048 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
9049 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
9050 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
9051 if (ResQT == LHSBaseQT)
9052 return LHS;
9053 if (ResQT == RHSBaseQT)
9054 return RHS;
9055 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00009056 return {};
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009057}
9058
Chris Lattner4ba0cef2008-04-07 07:01:58 +00009059//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009060// Integer Predicates
9061//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00009062
Jay Foad39c79802011-01-12 09:06:06 +00009063unsigned ASTContext::getIntWidth(QualType T) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00009064 if (const auto *ET = T->getAs<EnumType>())
Eli Friedmanee275c82009-12-10 22:29:29 +00009065 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00009066 if (T->isBooleanType())
9067 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00009068 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009069 return (unsigned)getTypeSize(T);
9070}
9071
Abramo Bagnara13640492012-09-09 10:21:24 +00009072QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Leonard Chanab80f3c2018-06-14 14:53:51 +00009073 assert((T->hasSignedIntegerRepresentation() || T->isSignedFixedPointType()) &&
9074 "Unexpected type");
Fangrui Song6907ce22018-07-30 19:24:48 +00009075
Chris Lattnerec3a1562009-10-17 20:33:28 +00009076 // Turn <4 x signed int> -> <4 x unsigned int>
Eugene Zelenko7855e772018-04-03 00:11:50 +00009077 if (const auto *VTy = T->getAs<VectorType>())
Chris Lattnerec3a1562009-10-17 20:33:28 +00009078 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00009079 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00009080
9081 // For enums, we return the unsigned version of the base type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00009082 if (const auto *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009083 T = ETy->getDecl()->getIntegerType();
Fangrui Song6907ce22018-07-30 19:24:48 +00009084
Eugene Zelenko7855e772018-04-03 00:11:50 +00009085 const auto *BTy = T->getAs<BuiltinType>();
Leonard Chanab80f3c2018-06-14 14:53:51 +00009086 assert(BTy && "Unexpected signed integer or fixed point type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009087 switch (BTy->getKind()) {
9088 case BuiltinType::Char_S:
9089 case BuiltinType::SChar:
9090 return UnsignedCharTy;
9091 case BuiltinType::Short:
9092 return UnsignedShortTy;
9093 case BuiltinType::Int:
9094 return UnsignedIntTy;
9095 case BuiltinType::Long:
9096 return UnsignedLongTy;
9097 case BuiltinType::LongLong:
9098 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00009099 case BuiltinType::Int128:
9100 return UnsignedInt128Ty;
Leonard Chanab80f3c2018-06-14 14:53:51 +00009101
9102 case BuiltinType::ShortAccum:
9103 return UnsignedShortAccumTy;
9104 case BuiltinType::Accum:
9105 return UnsignedAccumTy;
9106 case BuiltinType::LongAccum:
9107 return UnsignedLongAccumTy;
9108 case BuiltinType::SatShortAccum:
9109 return SatUnsignedShortAccumTy;
9110 case BuiltinType::SatAccum:
9111 return SatUnsignedAccumTy;
9112 case BuiltinType::SatLongAccum:
9113 return SatUnsignedLongAccumTy;
9114 case BuiltinType::ShortFract:
9115 return UnsignedShortFractTy;
9116 case BuiltinType::Fract:
9117 return UnsignedFractTy;
9118 case BuiltinType::LongFract:
9119 return UnsignedLongFractTy;
9120 case BuiltinType::SatShortFract:
9121 return SatUnsignedShortFractTy;
9122 case BuiltinType::SatFract:
9123 return SatUnsignedFractTy;
9124 case BuiltinType::SatLongFract:
9125 return SatUnsignedLongFractTy;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009126 default:
Leonard Chanab80f3c2018-06-14 14:53:51 +00009127 llvm_unreachable("Unexpected signed integer or fixed point type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009128 }
9129}
9130
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009131ASTMutationListener::~ASTMutationListener() = default;
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00009132
Richard Smith1fa5d642013-05-11 05:45:24 +00009133void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
9134 QualType ReturnType) {}
Chris Lattnerecd79c62009-06-14 00:45:47 +00009135
9136//===----------------------------------------------------------------------===//
9137// Builtin Type Computation
9138//===----------------------------------------------------------------------===//
9139
9140/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00009141/// pointer over the consumed characters. This returns the resultant type. If
9142/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
9143/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
9144/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009145///
9146/// RequiresICE is filled in on return to indicate whether the value is required
9147/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00009148static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00009149 ASTContext::GetBuiltinTypeError &Error,
Chandler Carruth45bbe012017-03-24 09:11:57 +00009150 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00009151 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00009152 // Modifiers.
9153 int HowLong = 0;
9154 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009155 RequiresICE = false;
Fangrui Song6907ce22018-07-30 19:24:48 +00009156
Chris Lattnerdc226c22010-10-01 22:42:38 +00009157 // Read the prefixed modifiers first.
Eric Christopher50daf5f2017-07-10 21:28:54 +00009158 bool Done = false;
9159 #ifndef NDEBUG
9160 bool IsSpecialLong = false;
9161 #endif
Chris Lattnerecd79c62009-06-14 00:45:47 +00009162 while (!Done) {
9163 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00009164 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00009165 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009166 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00009167 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009168 case 'S':
9169 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
9170 assert(!Signed && "Can't use 'S' modifier multiple times!");
9171 Signed = true;
9172 break;
9173 case 'U':
9174 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
Sean Silva2a995142015-01-16 21:44:26 +00009175 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00009176 Unsigned = true;
9177 break;
9178 case 'L':
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00009179 assert(!IsSpecialLong && "Can't use 'L' with 'W' or 'N' modifiers");
Chris Lattnerecd79c62009-06-14 00:45:47 +00009180 assert(HowLong <= 2 && "Can't have LLLL modifier");
9181 ++HowLong;
9182 break;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009183 case 'N':
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00009184 // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
9185 assert(!IsSpecialLong && "Can't use two 'N' or 'W' modifiers!");
9186 assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
Eric Christopher50daf5f2017-07-10 21:28:54 +00009187 #ifndef NDEBUG
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00009188 IsSpecialLong = true;
Eric Christopher50daf5f2017-07-10 21:28:54 +00009189 #endif
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00009190 if (Context.getTargetInfo().getLongWidth() == 32)
9191 ++HowLong;
9192 break;
Kevin Qinad64f6d2014-02-24 02:45:03 +00009193 case 'W':
9194 // This modifier represents int64 type.
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00009195 assert(!IsSpecialLong && "Can't use two 'N' or 'W' modifiers!");
Kevin Qinad64f6d2014-02-24 02:45:03 +00009196 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
Eric Christopher50daf5f2017-07-10 21:28:54 +00009197 #ifndef NDEBUG
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00009198 IsSpecialLong = true;
Eric Christopher50daf5f2017-07-10 21:28:54 +00009199 #endif
Kevin Qinad64f6d2014-02-24 02:45:03 +00009200 switch (Context.getTargetInfo().getInt64Type()) {
9201 default:
9202 llvm_unreachable("Unexpected integer type");
9203 case TargetInfo::SignedLong:
9204 HowLong = 1;
9205 break;
9206 case TargetInfo::SignedLongLong:
9207 HowLong = 2;
9208 break;
9209 }
Duncan P. N. Exon Smitheae8caa2017-06-14 21:26:31 +00009210 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009211 }
9212 }
9213
9214 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00009215
Chris Lattnerecd79c62009-06-14 00:45:47 +00009216 // Read the base type.
9217 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00009218 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00009219 case 'v':
9220 assert(HowLong == 0 && !Signed && !Unsigned &&
9221 "Bad modifiers used with 'v'!");
9222 Type = Context.VoidTy;
9223 break;
Jack Carter24bef982013-08-15 15:16:57 +00009224 case 'h':
9225 assert(HowLong == 0 && !Signed && !Unsigned &&
Sean Silva2a995142015-01-16 21:44:26 +00009226 "Bad modifiers used with 'h'!");
Jack Carter24bef982013-08-15 15:16:57 +00009227 Type = Context.HalfTy;
9228 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009229 case 'f':
9230 assert(HowLong == 0 && !Signed && !Unsigned &&
9231 "Bad modifiers used with 'f'!");
9232 Type = Context.FloatTy;
9233 break;
9234 case 'd':
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009235 assert(HowLong < 3 && !Signed && !Unsigned &&
Chris Lattnerecd79c62009-06-14 00:45:47 +00009236 "Bad modifiers used with 'd'!");
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009237 if (HowLong == 1)
Chris Lattnerecd79c62009-06-14 00:45:47 +00009238 Type = Context.LongDoubleTy;
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009239 else if (HowLong == 2)
9240 Type = Context.Float128Ty;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009241 else
9242 Type = Context.DoubleTy;
9243 break;
9244 case 's':
9245 assert(HowLong == 0 && "Bad modifiers used with 's'!");
9246 if (Unsigned)
9247 Type = Context.UnsignedShortTy;
9248 else
9249 Type = Context.ShortTy;
9250 break;
9251 case 'i':
9252 if (HowLong == 3)
9253 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
9254 else if (HowLong == 2)
9255 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
9256 else if (HowLong == 1)
9257 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
9258 else
9259 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
9260 break;
9261 case 'c':
9262 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
9263 if (Signed)
9264 Type = Context.SignedCharTy;
9265 else if (Unsigned)
9266 Type = Context.UnsignedCharTy;
9267 else
9268 Type = Context.CharTy;
9269 break;
9270 case 'b': // boolean
9271 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
9272 Type = Context.BoolTy;
9273 break;
9274 case 'z': // size_t.
9275 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
9276 Type = Context.getSizeType();
9277 break;
Richard Smith8110c9d2016-11-29 19:45:17 +00009278 case 'w': // wchar_t.
9279 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
9280 Type = Context.getWideCharType();
9281 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009282 case 'F':
9283 Type = Context.getCFConstantStringType();
9284 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00009285 case 'G':
9286 Type = Context.getObjCIdType();
9287 break;
9288 case 'H':
9289 Type = Context.getObjCSelType();
9290 break;
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00009291 case 'M':
9292 Type = Context.getObjCSuperType();
9293 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009294 case 'a':
9295 Type = Context.getBuiltinVaListType();
9296 assert(!Type.isNull() && "builtin va list type not initialized!");
9297 break;
9298 case 'A':
9299 // This is a "reference" to a va_list; however, what exactly
9300 // this means depends on how va_list is defined. There are two
9301 // different kinds of va_list: ones passed by value, and ones
9302 // passed by reference. An example of a by-value va_list is
9303 // x86, where va_list is a char*. An example of by-ref va_list
9304 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
9305 // we want this argument to be a char*&; for x86-64, we want
9306 // it to be a __va_list_tag*.
9307 Type = Context.getBuiltinVaListType();
9308 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009309 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00009310 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009311 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00009312 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009313 break;
9314 case 'V': {
9315 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009316 unsigned NumElements = strtoul(Str, &End, 10);
9317 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00009318 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00009319
Fangrui Song6907ce22018-07-30 19:24:48 +00009320 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
Chandler Carruth45bbe012017-03-24 09:11:57 +00009321 RequiresICE, false);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009322 assert(!RequiresICE && "Can't require vector ICE");
Fangrui Song6907ce22018-07-30 19:24:48 +00009323
Chris Lattnerdc226c22010-10-01 22:42:38 +00009324 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00009325 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00009326 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009327 break;
9328 }
Douglas Gregorfed66992012-06-07 18:08:25 +00009329 case 'E': {
9330 char *End;
Fangrui Song6907ce22018-07-30 19:24:48 +00009331
Douglas Gregorfed66992012-06-07 18:08:25 +00009332 unsigned NumElements = strtoul(Str, &End, 10);
9333 assert(End != Str && "Missing vector size");
Fangrui Song6907ce22018-07-30 19:24:48 +00009334
Douglas Gregorfed66992012-06-07 18:08:25 +00009335 Str = End;
Fangrui Song6907ce22018-07-30 19:24:48 +00009336
Douglas Gregorfed66992012-06-07 18:08:25 +00009337 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
Chandler Carruth45bbe012017-03-24 09:11:57 +00009338 false);
Douglas Gregorfed66992012-06-07 18:08:25 +00009339 Type = Context.getExtVectorType(ElementType, NumElements);
Fangrui Song6907ce22018-07-30 19:24:48 +00009340 break;
Douglas Gregorfed66992012-06-07 18:08:25 +00009341 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00009342 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009343 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
Chandler Carruth45bbe012017-03-24 09:11:57 +00009344 false);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009345 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00009346 Type = Context.getComplexType(ElementType);
9347 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00009348 }
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009349 case 'Y':
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00009350 Type = Context.getPointerDiffType();
9351 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00009352 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00009353 Type = Context.getFILEType();
9354 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00009355 Error = ASTContext::GE_Missing_stdio;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009356 return {};
Chris Lattnerecd79c62009-06-14 00:45:47 +00009357 }
Mike Stump2adb4da2009-07-28 23:47:15 +00009358 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00009359 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00009360 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00009361 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00009362 else
9363 Type = Context.getjmp_bufType();
9364
Mike Stump2adb4da2009-07-28 23:47:15 +00009365 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00009366 Error = ASTContext::GE_Missing_setjmp;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009367 return {};
Mike Stump2adb4da2009-07-28 23:47:15 +00009368 }
9369 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00009370 case 'K':
9371 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
9372 Type = Context.getucontext_tType();
9373
9374 if (Type.isNull()) {
9375 Error = ASTContext::GE_Missing_ucontext;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009376 return {};
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00009377 }
9378 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00009379 case 'p':
9380 Type = Context.getProcessIDType();
9381 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00009382 }
Mike Stump11289f42009-09-09 15:08:12 +00009383
Chris Lattnerdc226c22010-10-01 22:42:38 +00009384 // If there are modifiers and if we're allowed to parse them, go for it.
9385 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009386 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00009387 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00009388 default: Done = true; --Str; break;
9389 case '*':
9390 case '&': {
9391 // Both pointers and references can have their pointee types
9392 // qualified with an address space.
9393 char *End;
9394 unsigned AddrSpace = strtoul(Str, &End, 10);
Matt Arsenaultc65f9662018-08-02 12:14:28 +00009395 if (End != Str) {
9396 // Note AddrSpace == 0 is not the same as an unspecified address space.
9397 Type = Context.getAddrSpaceQualType(
9398 Type,
9399 Context.getLangASForBuiltinAddressSpace(AddrSpace));
Chris Lattnerdc226c22010-10-01 22:42:38 +00009400 Str = End;
9401 }
9402 if (c == '*')
9403 Type = Context.getPointerType(Type);
9404 else
9405 Type = Context.getLValueReferenceType(Type);
9406 break;
9407 }
9408 // FIXME: There's no way to have a built-in with an rvalue ref arg.
9409 case 'C':
9410 Type = Type.withConst();
9411 break;
9412 case 'D':
9413 Type = Context.getVolatileType(Type);
9414 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00009415 case 'R':
9416 Type = Type.withRestrict();
9417 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009418 }
9419 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009420
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009421 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Fangrui Song6907ce22018-07-30 19:24:48 +00009422 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00009423
Chris Lattnerecd79c62009-06-14 00:45:47 +00009424 return Type;
9425}
9426
9427/// GetBuiltinType - Return the type for the specified builtin.
Chandler Carruth45bbe012017-03-24 09:11:57 +00009428QualType ASTContext::GetBuiltinType(unsigned Id,
9429 GetBuiltinTypeError &Error,
9430 unsigned *IntegerConstantArgs) const {
Eric Christopher02d5d862015-08-06 01:01:12 +00009431 const char *TypeStr = BuiltinInfo.getTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00009432
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009433 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00009434
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009435 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009436 Error = GE_None;
Chandler Carruth45bbe012017-03-24 09:11:57 +00009437 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
9438 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009439 if (Error != GE_None)
Eugene Zelenko7855e772018-04-03 00:11:50 +00009440 return {};
Fangrui Song6907ce22018-07-30 19:24:48 +00009441
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009442 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
Fangrui Song6907ce22018-07-30 19:24:48 +00009443
Chris Lattnerecd79c62009-06-14 00:45:47 +00009444 while (TypeStr[0] && TypeStr[0] != '.') {
Chandler Carruth45bbe012017-03-24 09:11:57 +00009445 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009446 if (Error != GE_None)
Eugene Zelenko7855e772018-04-03 00:11:50 +00009447 return {};
Chris Lattnerecd79c62009-06-14 00:45:47 +00009448
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009449 // If this argument is required to be an IntegerConstantExpression and the
9450 // caller cares, fill in the bitmask we return.
9451 if (RequiresICE && IntegerConstantArgs)
9452 *IntegerConstantArgs |= 1 << ArgTypes.size();
Fangrui Song6907ce22018-07-30 19:24:48 +00009453
Chris Lattnerecd79c62009-06-14 00:45:47 +00009454 // Do array -> pointer decay. The builtin should use the decayed type.
9455 if (Ty->isArrayType())
9456 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00009457
Chris Lattnerecd79c62009-06-14 00:45:47 +00009458 ArgTypes.push_back(Ty);
9459 }
9460
David Majnemerba3e5ec2015-03-13 18:26:17 +00009461 if (Id == Builtin::BI__GetExceptionInfo)
Eugene Zelenko7855e772018-04-03 00:11:50 +00009462 return {};
David Majnemerba3e5ec2015-03-13 18:26:17 +00009463
Chris Lattnerecd79c62009-06-14 00:45:47 +00009464 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
9465 "'.' should only occur at end of builtin type list!");
9466
Reid Kleckner78af0702013-08-27 23:08:25 +00009467 FunctionType::ExtInfo EI(CC_C);
John McCall991eb4b2010-12-21 00:44:39 +00009468 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
9469
9470 bool Variadic = (TypeStr[0] == '.');
9471
Richard Smith836de6b2016-12-19 23:59:34 +00009472 // We really shouldn't be making a no-proto type here.
9473 if (ArgTypes.empty() && Variadic && !getLangOpts().CPlusPlus)
John McCall991eb4b2010-12-21 00:44:39 +00009474 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00009475
John McCalldb40c7f2010-12-14 08:05:40 +00009476 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00009477 EPI.ExtInfo = EI;
9478 EPI.Variadic = Variadic;
Richard Smith391fb862016-10-18 07:13:55 +00009479 if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id))
9480 EPI.ExceptionSpec.Type =
9481 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
John McCalldb40c7f2010-12-14 08:05:40 +00009482
Jordan Rose5c382722013-03-08 21:51:21 +00009483 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009484}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00009485
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009486static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
9487 const FunctionDecl *FD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00009488 if (!FD->isExternallyVisible())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009489 return GVA_Internal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009490
Richard Smithe2467b72017-11-16 23:54:56 +00009491 // Non-user-provided functions get emitted as weak definitions with every
9492 // use, no matter whether they've been explicitly instantiated etc.
Eugene Zelenko7855e772018-04-03 00:11:50 +00009493 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
Richard Smithe2467b72017-11-16 23:54:56 +00009494 if (!MD->isUserProvided())
9495 return GVA_DiscardableODR;
9496
Yaron Keren4cd211b2017-02-22 14:32:39 +00009497 GVALinkage External;
Rafael Espindola3ae00052013-05-13 00:12:11 +00009498 switch (FD->getTemplateSpecializationKind()) {
9499 case TSK_Undeclared:
9500 case TSK_ExplicitSpecialization:
9501 External = GVA_StrongExternal;
9502 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009503
Rafael Espindola3ae00052013-05-13 00:12:11 +00009504 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00009505 return GVA_StrongODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00009506
David Majnemerc3d07332014-05-15 06:25:57 +00009507 // C++11 [temp.explicit]p10:
9508 // [ Note: The intent is that an inline function that is the subject of
9509 // an explicit instantiation declaration will still be implicitly
9510 // instantiated when used so that the body can be considered for
9511 // inlining, but that no out-of-line copy of the inline function would be
9512 // generated in the translation unit. -- end note ]
Rafael Espindola3ae00052013-05-13 00:12:11 +00009513 case TSK_ExplicitInstantiationDeclaration:
David Majnemer27d69db2014-04-28 22:17:59 +00009514 return GVA_AvailableExternally;
9515
Rafael Espindola3ae00052013-05-13 00:12:11 +00009516 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00009517 External = GVA_DiscardableODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00009518 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009519 }
9520
9521 if (!FD->isInlined())
9522 return External;
David Majnemer62f0ffd2013-08-01 17:26:42 +00009523
David Majnemer3f021502015-10-08 04:53:31 +00009524 if ((!Context.getLangOpts().CPlusPlus &&
9525 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009526 !FD->hasAttr<DLLExportAttr>()) ||
David Majnemer62f0ffd2013-08-01 17:26:42 +00009527 FD->hasAttr<GNUInlineAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009528 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
9529
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009530 // GNU or C99 inline semantics. Determine whether this symbol should be
9531 // externally visible.
9532 if (FD->isInlineDefinitionExternallyVisible())
9533 return External;
9534
9535 // C99 inline semantics, where the symbol is not externally visible.
David Majnemer27d69db2014-04-28 22:17:59 +00009536 return GVA_AvailableExternally;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009537 }
9538
David Majnemer54e3ba52014-04-02 23:17:29 +00009539 // Functions specified with extern and inline in -fms-compatibility mode
9540 // forcibly get emitted. While the body of the function cannot be later
9541 // replaced, the function definition cannot be discarded.
David Majnemer73768702015-03-20 00:02:27 +00009542 if (FD->isMSExternInline())
David Majnemer54e3ba52014-04-02 23:17:29 +00009543 return GVA_StrongODR;
9544
David Majnemer27d69db2014-04-28 22:17:59 +00009545 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009546}
9547
Artem Belevichca2b9512016-05-02 20:30:03 +00009548static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context,
Richard Smitha4653622017-09-06 20:01:14 +00009549 const Decl *D, GVALinkage L) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009550 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
9551 // dllexport/dllimport on inline functions.
9552 if (D->hasAttr<DLLImportAttr>()) {
9553 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
9554 return GVA_AvailableExternally;
Artem Belevichca2b9512016-05-02 20:30:03 +00009555 } else if (D->hasAttr<DLLExportAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009556 if (L == GVA_DiscardableODR)
9557 return GVA_StrongODR;
Artem Belevichca2b9512016-05-02 20:30:03 +00009558 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice &&
9559 D->hasAttr<CUDAGlobalAttr>()) {
9560 // Device-side functions with __global__ attribute must always be
9561 // visible externally so they can be launched from host.
9562 if (L == GVA_DiscardableODR || L == GVA_Internal)
9563 return GVA_StrongODR;
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009564 }
9565 return L;
9566}
9567
Richard Smitha4653622017-09-06 20:01:14 +00009568/// Adjust the GVALinkage for a declaration based on what an external AST source
9569/// knows about whether there can be other definitions of this declaration.
9570static GVALinkage
9571adjustGVALinkageForExternalDefinitionKind(const ASTContext &Ctx, const Decl *D,
9572 GVALinkage L) {
9573 ExternalASTSource *Source = Ctx.getExternalSource();
9574 if (!Source)
9575 return L;
9576
9577 switch (Source->hasExternalDefinitions(D)) {
David Blaikie9ffe5a32017-01-30 05:00:26 +00009578 case ExternalASTSource::EK_Never:
Richard Smitha4653622017-09-06 20:01:14 +00009579 // Other translation units rely on us to provide the definition.
David Blaikie9ffe5a32017-01-30 05:00:26 +00009580 if (L == GVA_DiscardableODR)
9581 return GVA_StrongODR;
9582 break;
Richard Smitha4653622017-09-06 20:01:14 +00009583
David Blaikie9ffe5a32017-01-30 05:00:26 +00009584 case ExternalASTSource::EK_Always:
9585 return GVA_AvailableExternally;
Richard Smitha4653622017-09-06 20:01:14 +00009586
David Blaikie9ffe5a32017-01-30 05:00:26 +00009587 case ExternalASTSource::EK_ReplyHazy:
9588 break;
9589 }
9590 return L;
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009591}
9592
Richard Smitha4653622017-09-06 20:01:14 +00009593GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
9594 return adjustGVALinkageForExternalDefinitionKind(*this, FD,
9595 adjustGVALinkageForAttributes(*this, FD,
9596 basicGVALinkageForFunction(*this, FD)));
9597}
9598
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009599static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
9600 const VarDecl *VD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00009601 if (!VD->isExternallyVisible())
9602 return GVA_Internal;
9603
David Majnemer27d69db2014-04-28 22:17:59 +00009604 if (VD->isStaticLocal()) {
David Majnemer27d69db2014-04-28 22:17:59 +00009605 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
9606 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
9607 LexicalContext = LexicalContext->getLexicalParent();
9608
David Blaikieeb210012017-01-27 23:11:10 +00009609 // ObjC Blocks can create local variables that don't have a FunctionDecl
9610 // LexicalContext.
9611 if (!LexicalContext)
9612 return GVA_DiscardableODR;
David Majnemer27d69db2014-04-28 22:17:59 +00009613
David Blaikieeb210012017-01-27 23:11:10 +00009614 // Otherwise, let the static local variable inherit its linkage from the
9615 // nearest enclosing function.
9616 auto StaticLocalLinkage =
9617 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
9618
9619 // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
9620 // be emitted in any object with references to the symbol for the object it
9621 // contains, whether inline or out-of-line."
9622 // Similar behavior is observed with MSVC. An alternative ABI could use
9623 // StrongODR/AvailableExternally to match the function, but none are
9624 // known/supported currently.
9625 if (StaticLocalLinkage == GVA_StrongODR ||
9626 StaticLocalLinkage == GVA_AvailableExternally)
9627 return GVA_DiscardableODR;
9628 return StaticLocalLinkage;
David Majnemer27d69db2014-04-28 22:17:59 +00009629 }
9630
Hans Wennborg56fc62b2014-07-17 20:25:23 +00009631 // MSVC treats in-class initialized static data members as definitions.
9632 // By giving them non-strong linkage, out-of-line definitions won't
9633 // cause link errors.
9634 if (Context.isMSStaticDataMemberInlineDefinition(VD))
9635 return GVA_DiscardableODR;
9636
Richard Smithd9b90092016-07-02 01:32:16 +00009637 // Most non-template variables have strong linkage; inline variables are
9638 // linkonce_odr or (occasionally, for compatibility) weak_odr.
9639 GVALinkage StrongLinkage;
9640 switch (Context.getInlineVariableDefinitionKind(VD)) {
9641 case ASTContext::InlineVariableDefinitionKind::None:
9642 StrongLinkage = GVA_StrongExternal;
9643 break;
9644 case ASTContext::InlineVariableDefinitionKind::Weak:
9645 case ASTContext::InlineVariableDefinitionKind::WeakUnknown:
Richard Smith62f19e72016-06-25 00:15:56 +00009646 StrongLinkage = GVA_DiscardableODR;
Richard Smithd9b90092016-07-02 01:32:16 +00009647 break;
9648 case ASTContext::InlineVariableDefinitionKind::Strong:
9649 StrongLinkage = GVA_StrongODR;
9650 break;
9651 }
Richard Smith62f19e72016-06-25 00:15:56 +00009652
Richard Smith8809a0c2013-09-27 20:14:12 +00009653 switch (VD->getTemplateSpecializationKind()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00009654 case TSK_Undeclared:
Richard Smith62f19e72016-06-25 00:15:56 +00009655 return StrongLinkage;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009656
David Majnemer6d1780c2015-07-17 23:36:49 +00009657 case TSK_ExplicitSpecialization:
David Majnemer3f021502015-10-08 04:53:31 +00009658 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
9659 VD->isStaticDataMember()
David Majnemer6d1780c2015-07-17 23:36:49 +00009660 ? GVA_StrongODR
Richard Smith62f19e72016-06-25 00:15:56 +00009661 : StrongLinkage;
David Majnemer6d1780c2015-07-17 23:36:49 +00009662
Rafael Espindola3ae00052013-05-13 00:12:11 +00009663 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00009664 return GVA_StrongODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009665
David Majnemer27d69db2014-04-28 22:17:59 +00009666 case TSK_ExplicitInstantiationDeclaration:
9667 return GVA_AvailableExternally;
9668
Rafael Espindola3ae00052013-05-13 00:12:11 +00009669 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00009670 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009671 }
Rafael Espindola27699c82013-05-13 14:05:53 +00009672
9673 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009674}
9675
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009676GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
Richard Smitha4653622017-09-06 20:01:14 +00009677 return adjustGVALinkageForExternalDefinitionKind(*this, VD,
9678 adjustGVALinkageForAttributes(*this, VD,
9679 basicGVALinkageForVariable(*this, VD)));
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009680}
9681
David Blaikiee6b7c282017-04-11 20:46:34 +00009682bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00009683 if (const auto *VD = dyn_cast<VarDecl>(D)) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009684 if (!VD->isFileVarDecl())
9685 return false;
Renato Golin9258aa52014-05-21 10:40:27 +00009686 // Global named register variables (GNU extension) are never emitted.
9687 if (VD->getStorageClass() == SC_Register)
9688 return false;
Richard Smith7747ce22015-08-19 20:49:38 +00009689 if (VD->getDescribedVarTemplate() ||
9690 isa<VarTemplatePartialSpecializationDecl>(VD))
9691 return false;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009692 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
Richard Smith5205a8c2013-04-01 20:22:16 +00009693 // We never need to emit an uninstantiated function template.
9694 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
9695 return false;
Nico Weber66220292016-03-02 17:28:48 +00009696 } else if (isa<PragmaCommentDecl>(D))
9697 return true;
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00009698 else if (isa<OMPThreadPrivateDecl>(D))
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00009699 return true;
Nico Webercbbaeb12016-03-02 19:28:54 +00009700 else if (isa<PragmaDetectMismatchDecl>(D))
9701 return true;
Nico Weber66220292016-03-02 17:28:48 +00009702 else if (isa<OMPThreadPrivateDecl>(D))
Alexey Bataevc5b1d322016-03-04 09:22:22 +00009703 return !D->getDeclContext()->isDependentContext();
9704 else if (isa<OMPDeclareReductionDecl>(D))
9705 return !D->getDeclContext()->isDependentContext();
Richard Smithdc1f0422016-07-20 19:10:16 +00009706 else if (isa<ImportDecl>(D))
9707 return true;
Alexey Bataev97720002014-11-11 04:05:39 +00009708 else
Richard Smith5205a8c2013-04-01 20:22:16 +00009709 return false;
9710
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00009711 if (D->isFromASTFile() && !LangOpts.BuildingPCHWithObjectFile) {
9712 assert(getExternalSource() && "It's from an AST file; must have a source.");
9713 // On Windows, PCH files are built together with an object file. If this
9714 // declaration comes from such a PCH and DeclMustBeEmitted would return
9715 // true, it would have returned true and the decl would have been emitted
9716 // into that object file, so it doesn't need to be emitted here.
9717 // Note that decls are still emitted if they're referenced, as usual;
9718 // DeclMustBeEmitted is used to decide whether a decl must be emitted even
9719 // if it's not referenced.
9720 //
9721 // Explicit template instantiation definitions are tricky. If there was an
9722 // explicit template instantiation decl in the PCH before, it will look like
9723 // the definition comes from there, even if that was just the declaration.
9724 // (Explicit instantiation defs of variable templates always get emitted.)
9725 bool IsExpInstDef =
9726 isa<FunctionDecl>(D) &&
9727 cast<FunctionDecl>(D)->getTemplateSpecializationKind() ==
9728 TSK_ExplicitInstantiationDefinition;
9729
9730 if (getExternalSource()->DeclIsFromPCHWithObjectFile(D) && !IsExpInstDef)
9731 return false;
9732 }
9733
Richard Smith5205a8c2013-04-01 20:22:16 +00009734 // If this is a member of a class template, we do not need to emit it.
9735 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009736 return false;
9737
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00009738 // Weak references don't produce any output by themselves.
9739 if (D->hasAttr<WeakRefAttr>())
9740 return false;
9741
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009742 // Aliases and used decls are required.
9743 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
9744 return true;
9745
Eugene Zelenko7855e772018-04-03 00:11:50 +00009746 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009747 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00009748 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00009749 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009750
9751 // Constructors and destructors are required.
9752 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
9753 return true;
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00009754
John McCall6bd2a892013-01-25 22:31:03 +00009755 // The key function for a class is required. This rule only comes
9756 // into play when inline functions can be key functions, though.
9757 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00009758 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
John McCall6bd2a892013-01-25 22:31:03 +00009759 const CXXRecordDecl *RD = MD->getParent();
9760 if (MD->isOutOfLine() && RD->isDynamicClass()) {
9761 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
9762 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
9763 return true;
9764 }
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009765 }
9766 }
9767
David Blaikie9ffe5a32017-01-30 05:00:26 +00009768 GVALinkage Linkage = GetGVALinkageForFunction(FD);
9769
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009770 // static, static inline, always_inline, and extern inline functions can
9771 // always be deferred. Normal inline functions can be deferred in C99/C++.
9772 // Implicit template instantiations can also be deferred in C++.
David Blaikie9ffe5a32017-01-30 05:00:26 +00009773 return !isDiscardableGVALinkage(Linkage);
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009774 }
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00009775
Eugene Zelenko7855e772018-04-03 00:11:50 +00009776 const auto *VD = cast<VarDecl>(D);
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009777 assert(VD->isFileVarDecl() && "Expected file scoped var");
9778
Alexey Bataevd01b7492018-08-15 19:45:12 +00009779 // If the decl is marked as `declare target to`, it should be emitted for the
9780 // host and for the device.
9781 if (LangOpts.OpenMP &&
9782 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
9783 return true;
9784
Hans Wennborg56fc62b2014-07-17 20:25:23 +00009785 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
9786 !isMSStaticDataMemberInlineDefinition(VD))
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00009787 return false;
9788
Richard Smitha0e5e542012-11-12 21:38:00 +00009789 // Variables that can be needed in other TUs are required.
Richard Smitha4653622017-09-06 20:01:14 +00009790 auto Linkage = GetGVALinkageForVariable(VD);
9791 if (!isDiscardableGVALinkage(Linkage))
Richard Smitha0e5e542012-11-12 21:38:00 +00009792 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009793
Richard Smitha4653622017-09-06 20:01:14 +00009794 // We never need to emit a variable that is available in another TU.
9795 if (Linkage == GVA_AvailableExternally)
9796 return false;
9797
Richard Smitha0e5e542012-11-12 21:38:00 +00009798 // Variables that have destruction with side-effects are required.
9799 if (VD->getType().isDestructedType())
9800 return true;
9801
9802 // Variables that have initialization with side-effects are required.
Richard Smith7747ce22015-08-19 20:49:38 +00009803 if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
Richard Smith187ffb42017-01-20 01:19:46 +00009804 // We can get a value-dependent initializer during error recovery.
9805 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
Richard Smitha0e5e542012-11-12 21:38:00 +00009806 return true;
9807
Richard Smithda383632016-08-15 01:33:41 +00009808 // Likewise, variables with tuple-like bindings are required if their
9809 // bindings have side-effects.
Eugene Zelenko7855e772018-04-03 00:11:50 +00009810 if (const auto *DD = dyn_cast<DecompositionDecl>(VD))
9811 for (const auto *BD : DD->bindings())
9812 if (const auto *BindingVD = BD->getHoldingVar())
Richard Smithda383632016-08-15 01:33:41 +00009813 if (DeclMustBeEmitted(BindingVD))
9814 return true;
9815
Richard Smitha0e5e542012-11-12 21:38:00 +00009816 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009817}
Charles Davis53c59df2010-08-16 03:33:14 +00009818
Erich Keane281d20b2018-01-08 21:34:17 +00009819void ASTContext::forEachMultiversionedFunctionVersion(
9820 const FunctionDecl *FD,
Erich Keane0fb16482018-08-13 18:33:20 +00009821 llvm::function_ref<void(FunctionDecl *)> Pred) const {
Erich Keane281d20b2018-01-08 21:34:17 +00009822 assert(FD->isMultiVersion() && "Only valid for multiversioned functions");
9823 llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls;
9824 FD = FD->getCanonicalDecl();
9825 for (auto *CurDecl :
9826 FD->getDeclContext()->getRedeclContext()->lookup(FD->getDeclName())) {
9827 FunctionDecl *CurFD = CurDecl->getAsFunction()->getCanonicalDecl();
9828 if (CurFD && hasSameType(CurFD->getType(), FD->getType()) &&
9829 std::end(SeenDecls) == llvm::find(SeenDecls, CurFD)) {
9830 SeenDecls.insert(CurFD);
9831 Pred(CurFD);
9832 }
9833 }
9834}
9835
Reid Kleckner78af0702013-08-27 23:08:25 +00009836CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
9837 bool IsCXXMethod) const {
Charles Davis99202b32010-11-09 18:04:24 +00009838 // Pass through to the C++ ABI object
Reid Kleckner78af0702013-08-27 23:08:25 +00009839 if (IsCXXMethod)
9840 return ABI->getDefaultMethodCallConv(IsVariadic);
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00009841
Alexey Bataeva7547182016-05-18 09:06:38 +00009842 switch (LangOpts.getDefaultCallingConv()) {
9843 case LangOptions::DCC_None:
9844 break;
9845 case LangOptions::DCC_CDecl:
9846 return CC_C;
9847 case LangOptions::DCC_FastCall:
Erich Keane5759fa72017-10-24 23:12:01 +00009848 if (getTargetInfo().hasFeature("sse2") && !IsVariadic)
Alexey Bataeva7547182016-05-18 09:06:38 +00009849 return CC_X86FastCall;
9850 break;
9851 case LangOptions::DCC_StdCall:
9852 if (!IsVariadic)
9853 return CC_X86StdCall;
9854 break;
9855 case LangOptions::DCC_VectorCall:
9856 // __vectorcall cannot be applied to variadic functions.
9857 if (!IsVariadic)
9858 return CC_X86VectorCall;
9859 break;
Erich Keanea957ffb2017-11-02 21:08:00 +00009860 case LangOptions::DCC_RegCall:
9861 // __regcall cannot be applied to variadic functions.
9862 if (!IsVariadic)
9863 return CC_X86RegCall;
9864 break;
Alexey Bataeva7547182016-05-18 09:06:38 +00009865 }
Alexander Kornienko21de0ae2015-01-20 11:20:41 +00009866 return Target->getDefaultCallingConv(TargetInfo::CCMT_Unknown);
Charles Davis99202b32010-11-09 18:04:24 +00009867}
9868
Jay Foad39c79802011-01-12 09:06:06 +00009869bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00009870 // Pass through to the C++ ABI object
9871 return ABI->isNearlyEmpty(RD);
9872}
9873
Reid Kleckner96f8f932014-02-05 17:27:08 +00009874VTableContextBase *ASTContext::getVTableContext() {
9875 if (!VTContext.get()) {
9876 if (Target->getCXXABI().isMicrosoft())
9877 VTContext.reset(new MicrosoftVTableContext(*this));
9878 else
9879 VTContext.reset(new ItaniumVTableContext(*this));
9880 }
9881 return VTContext.get();
9882}
9883
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00009884MangleContext *ASTContext::createMangleContext() {
John McCall359b8852013-01-25 22:30:49 +00009885 switch (Target->getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +00009886 case TargetCXXABI::GenericAArch64:
John McCall359b8852013-01-25 22:30:49 +00009887 case TargetCXXABI::GenericItanium:
9888 case TargetCXXABI::GenericARM:
Zoran Jovanovic26a12162015-02-18 15:21:35 +00009889 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +00009890 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +00009891 case TargetCXXABI::iOS64:
Dan Gohmanc2853072015-09-03 22:51:53 +00009892 case TargetCXXABI::WebAssembly:
Tim Northover756447a2015-10-30 16:30:36 +00009893 case TargetCXXABI::WatchOS:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00009894 return ItaniumMangleContext::create(*this, getDiagnostics());
John McCall359b8852013-01-25 22:30:49 +00009895 case TargetCXXABI::Microsoft:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00009896 return MicrosoftMangleContext::create(*this, getDiagnostics());
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00009897 }
David Blaikie83d382b2011-09-23 05:06:16 +00009898 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00009899}
9900
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009901CXXABI::~CXXABI() = default;
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00009902
9903size_t ASTContext::getSideTableAllocatedMemory() const {
Larisse Voufo39a1e502013-08-06 01:03:05 +00009904 return ASTRecordLayouts.getMemorySize() +
9905 llvm::capacity_in_bytes(ObjCLayouts) +
9906 llvm::capacity_in_bytes(KeyFunctions) +
9907 llvm::capacity_in_bytes(ObjCImpls) +
9908 llvm::capacity_in_bytes(BlockVarCopyInits) +
9909 llvm::capacity_in_bytes(DeclAttrs) +
9910 llvm::capacity_in_bytes(TemplateOrInstantiation) +
9911 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
9912 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
9913 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
9914 llvm::capacity_in_bytes(OverriddenMethods) +
9915 llvm::capacity_in_bytes(Types) +
9916 llvm::capacity_in_bytes(VariableArrayTypes) +
9917 llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00009918}
Ted Kremenek540017e2011-10-06 05:00:56 +00009919
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00009920/// getIntTypeForBitwidth -
9921/// sets integer QualTy according to specified details:
9922/// bitwidth, signed/unsigned.
9923/// Returns empty type if there is no appropriate target types.
9924QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
9925 unsigned Signed) const {
9926 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
9927 CanQualType QualTy = getFromTargetType(Ty);
9928 if (!QualTy && DestWidth == 128)
9929 return Signed ? Int128Ty : UnsignedInt128Ty;
9930 return QualTy;
9931}
9932
9933/// getRealTypeForBitwidth -
9934/// sets floating point QualTy according to specified bitwidth.
9935/// Returns empty type if there is no appropriate target types.
9936QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
9937 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
9938 switch (Ty) {
9939 case TargetInfo::Float:
9940 return FloatTy;
9941 case TargetInfo::Double:
9942 return DoubleTy;
9943 case TargetInfo::LongDouble:
9944 return LongDoubleTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00009945 case TargetInfo::Float128:
9946 return Float128Ty;
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00009947 case TargetInfo::NoFloat:
Eugene Zelenko7855e772018-04-03 00:11:50 +00009948 return {};
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00009949 }
9950
9951 llvm_unreachable("Unhandled TargetInfo::RealType value");
9952}
9953
Eli Friedman3b7d46c2013-07-10 00:30:46 +00009954void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
9955 if (Number > 1)
9956 MangleNumbers[ND] = Number;
David Blaikie095deba2012-11-14 01:52:05 +00009957}
9958
Eli Friedman3b7d46c2013-07-10 00:30:46 +00009959unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
Richard Smithe9b02d62016-03-21 22:33:02 +00009960 auto I = MangleNumbers.find(ND);
Eli Friedman3b7d46c2013-07-10 00:30:46 +00009961 return I != MangleNumbers.end() ? I->second : 1;
David Blaikie095deba2012-11-14 01:52:05 +00009962}
9963
David Majnemer2206bf52014-03-05 08:57:59 +00009964void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
9965 if (Number > 1)
9966 StaticLocalNumbers[VD] = Number;
9967}
9968
9969unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
Richard Smithe9b02d62016-03-21 22:33:02 +00009970 auto I = StaticLocalNumbers.find(VD);
David Majnemer2206bf52014-03-05 08:57:59 +00009971 return I != StaticLocalNumbers.end() ? I->second : 1;
9972}
9973
Eli Friedman3b7d46c2013-07-10 00:30:46 +00009974MangleNumberingContext &
9975ASTContext::getManglingNumberContext(const DeclContext *DC) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00009976 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
Justin Lebar20ebffc2016-10-10 16:26:19 +00009977 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
Reid Klecknerd8110b62013-09-10 20:14:30 +00009978 if (!MCtx)
9979 MCtx = createMangleNumberingContext();
9980 return *MCtx;
9981}
9982
Justin Lebar20ebffc2016-10-10 16:26:19 +00009983std::unique_ptr<MangleNumberingContext>
9984ASTContext::createMangleNumberingContext() const {
Reid Klecknerd8110b62013-09-10 20:14:30 +00009985 return ABI->createMangleNumberingContext();
Douglas Gregor63798542012-02-20 19:44:39 +00009986}
9987
David Majnemere7a818f2015-03-06 18:53:55 +00009988const CXXConstructorDecl *
9989ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
9990 return ABI->getCopyConstructorForExceptionObject(
9991 cast<CXXRecordDecl>(RD->getFirstDecl()));
9992}
9993
9994void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
9995 CXXConstructorDecl *CD) {
9996 return ABI->addCopyConstructorForExceptionObject(
9997 cast<CXXRecordDecl>(RD->getFirstDecl()),
9998 cast<CXXConstructorDecl>(CD->getFirstDecl()));
9999}
10000
David Majnemer00350522015-08-31 18:48:39 +000010001void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD,
10002 TypedefNameDecl *DD) {
10003 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
10004}
10005
10006TypedefNameDecl *
10007ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) {
10008 return ABI->getTypedefNameForUnnamedTagDecl(TD);
10009}
10010
10011void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD,
10012 DeclaratorDecl *DD) {
10013 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
10014}
10015
10016DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) {
10017 return ABI->getDeclaratorForUnnamedTagDecl(TD);
10018}
10019
Ted Kremenek540017e2011-10-06 05:00:56 +000010020void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
10021 ParamIndices[D] = index;
10022}
10023
10024unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
10025 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
Fangrui Song6907ce22018-07-30 19:24:48 +000010026 assert(I != ParamIndices.end() &&
Ted Kremenek540017e2011-10-06 05:00:56 +000010027 "ParmIndices lacks entry set by ParmVarDecl");
10028 return I->second;
10029}
Fariborz Jahanian615de762013-05-28 17:37:39 +000010030
Richard Smithe6c01442013-06-05 00:46:14 +000010031APValue *
10032ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
10033 bool MayCreate) {
10034 assert(E && E->getStorageDuration() == SD_Static &&
10035 "don't need to cache the computed value for this temporary");
David Majnemer2dcef9e2015-08-13 23:50:15 +000010036 if (MayCreate) {
10037 APValue *&MTVI = MaterializedTemporaryValues[E];
10038 if (!MTVI)
10039 MTVI = new (*this) APValue;
10040 return MTVI;
10041 }
Richard Smithe6c01442013-06-05 00:46:14 +000010042
David Majnemer2dcef9e2015-08-13 23:50:15 +000010043 return MaterializedTemporaryValues.lookup(E);
Richard Smithe6c01442013-06-05 00:46:14 +000010044}
10045
Fariborz Jahanian615de762013-05-28 17:37:39 +000010046bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
10047 const llvm::Triple &T = getTargetInfo().getTriple();
10048 if (!T.isOSDarwin())
10049 return false;
10050
Bob Wilson2c82c3d2013-11-02 23:27:49 +000010051 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
10052 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
10053 return false;
10054
Fariborz Jahanian615de762013-05-28 17:37:39 +000010055 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
10056 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
10057 uint64_t Size = sizeChars.getQuantity();
10058 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
10059 unsigned Align = alignChars.getQuantity();
10060 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
10061 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
10062}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010063
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000010064static ast_type_traits::DynTypedNode getSingleDynTypedNodeFromParentMap(
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010065 ASTContext::ParentMapPointers::mapped_type U) {
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +000010066 if (const auto *D = U.dyn_cast<const Decl *>())
Benjamin Kramer8e4a1762015-10-22 11:21:40 +000010067 return ast_type_traits::DynTypedNode::create(*D);
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +000010068 if (const auto *S = U.dyn_cast<const Stmt *>())
Benjamin Kramer8e4a1762015-10-22 11:21:40 +000010069 return ast_type_traits::DynTypedNode::create(*S);
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +000010070 return *U.get<ast_type_traits::DynTypedNode *>();
Benjamin Kramer8e4a1762015-10-22 11:21:40 +000010071}
10072
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000010073namespace {
10074
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010075/// Template specializations to abstract away from pointers and TypeLocs.
10076/// @{
10077template <typename T>
10078ast_type_traits::DynTypedNode createDynTypedNode(const T &Node) {
10079 return ast_type_traits::DynTypedNode::create(*Node);
10080}
10081template <>
10082ast_type_traits::DynTypedNode createDynTypedNode(const TypeLoc &Node) {
10083 return ast_type_traits::DynTypedNode::create(Node);
10084}
10085template <>
10086ast_type_traits::DynTypedNode
10087createDynTypedNode(const NestedNameSpecifierLoc &Node) {
10088 return ast_type_traits::DynTypedNode::create(Node);
10089}
10090/// @}
10091
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010092 /// A \c RecursiveASTVisitor that builds a map from nodes to their
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010093 /// parents as defined by the \c RecursiveASTVisitor.
10094 ///
10095 /// Note that the relationship described here is purely in terms of AST
10096 /// traversal - there are other relationships (for example declaration context)
10097 /// in the AST that are better modeled by special matchers.
10098 ///
Benjamin Kramere8c51fd2015-10-21 10:07:26 +000010099 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010100 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010101 public:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010102 /// Builds and returns the translation unit's parent map.
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010103 ///
10104 /// The caller takes ownership of the returned \c ParentMap.
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010105 static std::pair<ASTContext::ParentMapPointers *,
10106 ASTContext::ParentMapOtherNodes *>
10107 buildMap(TranslationUnitDecl &TU) {
10108 ParentMapASTVisitor Visitor(new ASTContext::ParentMapPointers,
10109 new ASTContext::ParentMapOtherNodes);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010110 Visitor.TraverseDecl(&TU);
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010111 return std::make_pair(Visitor.Parents, Visitor.OtherParents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010112 }
10113
10114 private:
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000010115 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
10116
10117 using VisitorBase = RecursiveASTVisitor<ParentMapASTVisitor>;
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010118
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010119 ParentMapASTVisitor(ASTContext::ParentMapPointers *Parents,
10120 ASTContext::ParentMapOtherNodes *OtherParents)
10121 : Parents(Parents), OtherParents(OtherParents) {}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010122
10123 bool shouldVisitTemplateInstantiations() const {
10124 return true;
10125 }
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000010126
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010127 bool shouldVisitImplicitCode() const {
10128 return true;
10129 }
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010130
Richard Smith85838722015-11-24 03:09:01 +000010131 template <typename T, typename MapNodeTy, typename BaseTraverseFn,
10132 typename MapTy>
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010133 bool TraverseNode(T Node, MapNodeTy MapNode,
Richard Smith85838722015-11-24 03:09:01 +000010134 BaseTraverseFn BaseTraverse, MapTy *Parents) {
Craig Topper36250ad2014-05-12 05:36:57 +000010135 if (!Node)
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010136 return true;
Manuel Klimek95403e62014-05-21 13:28:59 +000010137 if (ParentStack.size() > 0) {
Benjamin Kramere8c51fd2015-10-21 10:07:26 +000010138 // FIXME: Currently we add the same parent multiple times, but only
10139 // when no memoization data is available for the type.
10140 // For example when we visit all subexpressions of template
10141 // instantiations; this is suboptimal, but benign: the only way to
10142 // visit those is with hasAncestor / hasParent, and those do not create
10143 // new matches.
10144 // The plan is to enable DynTypedNode to be storable in a map or hash
10145 // map. The main problem there is to implement hash functions /
10146 // comparison operators for all types that DynTypedNode supports that
10147 // do not have pointer identity.
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010148 auto &NodeOrVector = (*Parents)[MapNode];
Manuel Klimek95403e62014-05-21 13:28:59 +000010149 if (NodeOrVector.isNull()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +000010150 if (const auto *D = ParentStack.back().get<Decl>())
10151 NodeOrVector = D;
10152 else if (const auto *S = ParentStack.back().get<Stmt>())
10153 NodeOrVector = S;
10154 else
10155 NodeOrVector =
10156 new ast_type_traits::DynTypedNode(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +000010157 } else {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +000010158 if (!NodeOrVector.template is<ASTContext::ParentVector *>()) {
10159 auto *Vector = new ASTContext::ParentVector(
10160 1, getSingleDynTypedNodeFromParentMap(NodeOrVector));
Gabor Horvath10a837a2017-04-19 15:11:10 +000010161 delete NodeOrVector
10162 .template dyn_cast<ast_type_traits::DynTypedNode *>();
Benjamin Kramer422b3ff2015-10-23 13:24:18 +000010163 NodeOrVector = Vector;
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +000010164 }
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +000010165
10166 auto *Vector =
10167 NodeOrVector.template get<ASTContext::ParentVector *>();
10168 // Skip duplicates for types that have memoization data.
10169 // We must check that the type has memoization data before calling
10170 // std::find() because DynTypedNode::operator== can't compare all
10171 // types.
10172 bool Found = ParentStack.back().getMemoizationData() &&
10173 std::find(Vector->begin(), Vector->end(),
10174 ParentStack.back()) != Vector->end();
10175 if (!Found)
10176 Vector->push_back(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +000010177 }
10178 }
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010179 ParentStack.push_back(createDynTypedNode(Node));
Richard Smith85838722015-11-24 03:09:01 +000010180 bool Result = BaseTraverse();
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010181 ParentStack.pop_back();
10182 return Result;
10183 }
10184
10185 bool TraverseDecl(Decl *DeclNode) {
Richard Smith85838722015-11-24 03:09:01 +000010186 return TraverseNode(DeclNode, DeclNode,
10187 [&] { return VisitorBase::TraverseDecl(DeclNode); },
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010188 Parents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010189 }
10190
10191 bool TraverseStmt(Stmt *StmtNode) {
Richard Smith85838722015-11-24 03:09:01 +000010192 return TraverseNode(StmtNode, StmtNode,
10193 [&] { return VisitorBase::TraverseStmt(StmtNode); },
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010194 Parents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010195 }
10196
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010197 bool TraverseTypeLoc(TypeLoc TypeLocNode) {
Richard Smith85838722015-11-24 03:09:01 +000010198 return TraverseNode(
10199 TypeLocNode, ast_type_traits::DynTypedNode::create(TypeLocNode),
10200 [&] { return VisitorBase::TraverseTypeLoc(TypeLocNode); },
10201 OtherParents);
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010202 }
10203
10204 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNSLocNode) {
10205 return TraverseNode(
10206 NNSLocNode, ast_type_traits::DynTypedNode::create(NNSLocNode),
Richard Smith85838722015-11-24 03:09:01 +000010207 [&] {
10208 return VisitorBase::TraverseNestedNameSpecifierLoc(NNSLocNode);
10209 },
10210 OtherParents);
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010211 }
10212
10213 ASTContext::ParentMapPointers *Parents;
10214 ASTContext::ParentMapOtherNodes *OtherParents;
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010215 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010216 };
10217
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000010218} // namespace
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010219
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010220template <typename NodeTy, typename MapTy>
10221static ASTContext::DynTypedNodeList getDynNodeFromMap(const NodeTy &Node,
10222 const MapTy &Map) {
10223 auto I = Map.find(Node);
10224 if (I == Map.end()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +000010225 return llvm::ArrayRef<ast_type_traits::DynTypedNode>();
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010226 }
Eugene Zelenko7855e772018-04-03 00:11:50 +000010227 if (const auto *V =
10228 I->second.template dyn_cast<ASTContext::ParentVector *>()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +000010229 return llvm::makeArrayRef(*V);
Manuel Klimek95403e62014-05-21 13:28:59 +000010230 }
Benjamin Kramer8e4a1762015-10-22 11:21:40 +000010231 return getSingleDynTypedNodeFromParentMap(I->second);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010232}
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010233
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010234ASTContext::DynTypedNodeList
10235ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
10236 if (!PointerParents) {
10237 // We always need to run over the whole translation unit, as
10238 // hasAncestor can escape any subtree.
10239 auto Maps = ParentMapASTVisitor::buildMap(*getTranslationUnitDecl());
10240 PointerParents.reset(Maps.first);
10241 OtherParents.reset(Maps.second);
10242 }
10243 if (Node.getNodeKind().hasPointerIdentity())
10244 return getDynNodeFromMap(Node.getMemoizationData(), *PointerParents);
10245 return getDynNodeFromMap(Node, *OtherParents);
10246}
10247
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010248bool
10249ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
10250 const ObjCMethodDecl *MethodImpl) {
10251 // No point trying to match an unavailable/deprecated mothod.
10252 if (MethodDecl->hasAttr<UnavailableAttr>()
10253 || MethodDecl->hasAttr<DeprecatedAttr>())
10254 return false;
10255 if (MethodDecl->getObjCDeclQualifier() !=
10256 MethodImpl->getObjCDeclQualifier())
10257 return false;
Alp Toker314cc812014-01-25 16:55:45 +000010258 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010259 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +000010260
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010261 if (MethodDecl->param_size() != MethodImpl->param_size())
10262 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +000010263
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010264 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
10265 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
10266 EF = MethodDecl->param_end();
10267 IM != EM && IF != EF; ++IM, ++IF) {
10268 const ParmVarDecl *DeclVar = (*IF);
10269 const ParmVarDecl *ImplVar = (*IM);
10270 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
10271 return false;
10272 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
10273 return false;
10274 }
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000010275
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010276 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010277}
Richard Smith053f6c62014-05-16 23:01:30 +000010278
Yaxun Liu402804b2016-12-15 08:09:08 +000010279uint64_t ASTContext::getTargetNullPointerValue(QualType QT) const {
Alexander Richardson6d989432017-10-15 18:48:14 +000010280 LangAS AS;
Yaxun Liu402804b2016-12-15 08:09:08 +000010281 if (QT->getUnqualifiedDesugaredType()->isNullPtrType())
Alexander Richardson6d989432017-10-15 18:48:14 +000010282 AS = LangAS::Default;
Yaxun Liu402804b2016-12-15 08:09:08 +000010283 else
10284 AS = QT->getPointeeType().getAddressSpace();
10285
10286 return getTargetInfo().getNullPointerValue(AS);
10287}
10288
Alexander Richardson6d989432017-10-15 18:48:14 +000010289unsigned ASTContext::getTargetAddressSpace(LangAS AS) const {
10290 if (isTargetAddressSpace(AS))
10291 return toTargetAddressSpace(AS);
Yaxun Liub34ec822017-04-11 17:24:23 +000010292 else
Alexander Richardson6d989432017-10-15 18:48:14 +000010293 return (*AddrSpaceMap)[(unsigned)AS];
Yaxun Liub34ec822017-04-11 17:24:23 +000010294}
10295
Leonard Chanab80f3c2018-06-14 14:53:51 +000010296QualType ASTContext::getCorrespondingSaturatedType(QualType Ty) const {
10297 assert(Ty->isFixedPointType());
10298
10299 if (Ty->isSaturatedFixedPointType()) return Ty;
10300
10301 const auto &BT = Ty->getAs<BuiltinType>();
10302 switch (BT->getKind()) {
10303 default:
10304 llvm_unreachable("Not a fixed point type!");
10305 case BuiltinType::ShortAccum:
10306 return SatShortAccumTy;
10307 case BuiltinType::Accum:
10308 return SatAccumTy;
10309 case BuiltinType::LongAccum:
10310 return SatLongAccumTy;
10311 case BuiltinType::UShortAccum:
10312 return SatUnsignedShortAccumTy;
10313 case BuiltinType::UAccum:
10314 return SatUnsignedAccumTy;
10315 case BuiltinType::ULongAccum:
10316 return SatUnsignedLongAccumTy;
10317 case BuiltinType::ShortFract:
10318 return SatShortFractTy;
10319 case BuiltinType::Fract:
10320 return SatFractTy;
10321 case BuiltinType::LongFract:
10322 return SatLongFractTy;
10323 case BuiltinType::UShortFract:
10324 return SatUnsignedShortFractTy;
10325 case BuiltinType::UFract:
10326 return SatUnsignedFractTy;
10327 case BuiltinType::ULongFract:
10328 return SatUnsignedLongFractTy;
10329 }
10330}
10331
Matt Arsenaultc65f9662018-08-02 12:14:28 +000010332LangAS ASTContext::getLangASForBuiltinAddressSpace(unsigned AS) const {
10333 if (LangOpts.OpenCL)
10334 return getTargetInfo().getOpenCLBuiltinAddressSpace(AS);
10335
10336 if (LangOpts.CUDA)
10337 return getTargetInfo().getCUDABuiltinAddressSpace(AS);
10338
10339 return getLangASFromTargetAS(AS);
10340}
10341
Richard Smith053f6c62014-05-16 23:01:30 +000010342// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
10343// doesn't include ASTContext.h
10344template
10345clang::LazyGenerationalUpdatePtr<
10346 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
10347clang::LazyGenerationalUpdatePtr<
10348 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
10349 const clang::ASTContext &Ctx, Decl *Value);
Leonard Chandb01c3a2018-06-20 17:19:40 +000010350
10351unsigned char ASTContext::getFixedPointScale(QualType Ty) const {
10352 assert(Ty->isFixedPointType());
10353
10354 const auto *BT = Ty->getAs<BuiltinType>();
10355 const TargetInfo &Target = getTargetInfo();
10356 switch (BT->getKind()) {
10357 default:
10358 llvm_unreachable("Not a fixed point type!");
10359 case BuiltinType::ShortAccum:
10360 case BuiltinType::SatShortAccum:
10361 return Target.getShortAccumScale();
10362 case BuiltinType::Accum:
10363 case BuiltinType::SatAccum:
10364 return Target.getAccumScale();
10365 case BuiltinType::LongAccum:
10366 case BuiltinType::SatLongAccum:
10367 return Target.getLongAccumScale();
10368 case BuiltinType::UShortAccum:
10369 case BuiltinType::SatUShortAccum:
10370 return Target.getUnsignedShortAccumScale();
10371 case BuiltinType::UAccum:
10372 case BuiltinType::SatUAccum:
10373 return Target.getUnsignedAccumScale();
10374 case BuiltinType::ULongAccum:
10375 case BuiltinType::SatULongAccum:
10376 return Target.getUnsignedLongAccumScale();
10377 case BuiltinType::ShortFract:
10378 case BuiltinType::SatShortFract:
10379 return Target.getShortFractScale();
10380 case BuiltinType::Fract:
10381 case BuiltinType::SatFract:
10382 return Target.getFractScale();
10383 case BuiltinType::LongFract:
10384 case BuiltinType::SatLongFract:
10385 return Target.getLongFractScale();
10386 case BuiltinType::UShortFract:
10387 case BuiltinType::SatUShortFract:
10388 return Target.getUnsignedShortFractScale();
10389 case BuiltinType::UFract:
10390 case BuiltinType::SatUFract:
10391 return Target.getUnsignedFractScale();
10392 case BuiltinType::ULongFract:
10393 case BuiltinType::SatULongFract:
10394 return Target.getUnsignedLongFractScale();
10395 }
10396}
10397
10398unsigned char ASTContext::getFixedPointIBits(QualType Ty) const {
10399 assert(Ty->isFixedPointType());
10400
10401 const auto *BT = Ty->getAs<BuiltinType>();
10402 const TargetInfo &Target = getTargetInfo();
10403 switch (BT->getKind()) {
10404 default:
10405 llvm_unreachable("Not a fixed point type!");
10406 case BuiltinType::ShortAccum:
10407 case BuiltinType::SatShortAccum:
10408 return Target.getShortAccumIBits();
10409 case BuiltinType::Accum:
10410 case BuiltinType::SatAccum:
10411 return Target.getAccumIBits();
10412 case BuiltinType::LongAccum:
10413 case BuiltinType::SatLongAccum:
10414 return Target.getLongAccumIBits();
10415 case BuiltinType::UShortAccum:
10416 case BuiltinType::SatUShortAccum:
10417 return Target.getUnsignedShortAccumIBits();
10418 case BuiltinType::UAccum:
10419 case BuiltinType::SatUAccum:
10420 return Target.getUnsignedAccumIBits();
10421 case BuiltinType::ULongAccum:
10422 case BuiltinType::SatULongAccum:
10423 return Target.getUnsignedLongAccumIBits();
10424 case BuiltinType::ShortFract:
10425 case BuiltinType::SatShortFract:
10426 case BuiltinType::Fract:
10427 case BuiltinType::SatFract:
10428 case BuiltinType::LongFract:
10429 case BuiltinType::SatLongFract:
10430 case BuiltinType::UShortFract:
10431 case BuiltinType::SatUShortFract:
10432 case BuiltinType::UFract:
10433 case BuiltinType::SatUFract:
10434 case BuiltinType::ULongFract:
10435 case BuiltinType::SatULongFract:
10436 return 0;
10437 }
10438}
Leonard Chana6779422018-08-06 16:42:37 +000010439
10440FixedPointSemantics ASTContext::getFixedPointSemantics(QualType Ty) const {
10441 assert(Ty->isFixedPointType());
10442 bool isSigned = Ty->isSignedFixedPointType();
10443 return FixedPointSemantics(
10444 static_cast<unsigned>(getTypeSize(Ty)), getFixedPointScale(Ty), isSigned,
10445 Ty->isSaturatedFixedPointType(),
10446 !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding());
10447}
10448
10449APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const {
10450 assert(Ty->isFixedPointType());
10451 return APFixedPoint::getMax(getFixedPointSemantics(Ty));
10452}
10453
10454APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const {
10455 assert(Ty->isFixedPointType());
10456 return APFixedPoint::getMin(getFixedPointSemantics(Ty));
10457}