blob: 21b6f36e9aa7754003b2db1cfb9a4d032fc72984 [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);
Sam McCall814e7972018-11-14 10:33:30 +0000799 TraversalScope = {TUDecl};
Daniel Dunbar221fa942008-08-11 04:54:23 +0000800}
801
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000802ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000803 // Release the DenseMaps associated with DeclContext objects.
804 // FIXME: Is this the ideal solution?
805 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000806
Manuel Klimeka7328992013-06-03 13:51:33 +0000807 // Call all of the deallocation functions on all of their targets.
Chandler Carruthff5a01a2015-12-30 03:00:23 +0000808 for (auto &Pair : Deallocations)
809 (Pair.first)(Pair.second);
Manuel Klimeka7328992013-06-03 13:51:33 +0000810
Ted Kremenek076baeb2010-06-08 23:00:58 +0000811 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000812 // because they can contain DenseMaps.
813 for (llvm::DenseMap<const ObjCContainerDecl*,
814 const ASTRecordLayout*>::iterator
815 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
816 // Increment in loop to prevent using deallocated memory.
Eugene Zelenko7855e772018-04-03 00:11:50 +0000817 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
Douglas Gregor5b11d492010-07-25 17:53:33 +0000818 R->Destroy(*this);
819
Ted Kremenek076baeb2010-06-08 23:00:58 +0000820 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
821 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
822 // Increment in loop to prevent using deallocated memory.
Eugene Zelenko7855e772018-04-03 00:11:50 +0000823 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
Ted Kremenek076baeb2010-06-08 23:00:58 +0000824 R->Destroy(*this);
825 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000826
Douglas Gregor561eceb2010-08-30 16:49:28 +0000827 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
828 AEnd = DeclAttrs.end();
829 A != AEnd; ++A)
830 A->second->~AttrVec();
Reid Klecknerd8110b62013-09-10 20:14:30 +0000831
David Majnemere694f3e2015-08-14 14:43:50 +0000832 for (std::pair<const MaterializeTemporaryExpr *, APValue *> &MTVPair :
833 MaterializedTemporaryValues)
834 MTVPair.second->~APValue();
835
Richard Smith423f46f2016-07-20 21:38:26 +0000836 for (const auto &Value : ModuleInitializers)
837 Value.second->~PerModuleInitializers();
Douglas Gregor561eceb2010-08-30 16:49:28 +0000838}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000839
Sam McCall814e7972018-11-14 10:33:30 +0000840class ASTContext::ParentMap {
841 /// Contains parents of a node.
842 using ParentVector = llvm::SmallVector<ast_type_traits::DynTypedNode, 2>;
843
844 /// Maps from a node to its parents. This is used for nodes that have
845 /// pointer identity only, which are more common and we can save space by
846 /// only storing a unique pointer to them.
847 using ParentMapPointers = llvm::DenseMap<
848 const void *,
849 llvm::PointerUnion4<const Decl *, const Stmt *,
850 ast_type_traits::DynTypedNode *, ParentVector *>>;
851
852 /// Parent map for nodes without pointer identity. We store a full
853 /// DynTypedNode for all keys.
854 using ParentMapOtherNodes = llvm::DenseMap<
855 ast_type_traits::DynTypedNode,
856 llvm::PointerUnion4<const Decl *, const Stmt *,
857 ast_type_traits::DynTypedNode *, ParentVector *>>;
858
859 ParentMapPointers PointerParents;
860 ParentMapOtherNodes OtherParents;
861 class ASTVisitor;
862
863 static ast_type_traits::DynTypedNode
864 getSingleDynTypedNodeFromParentMap(ParentMapPointers::mapped_type U) {
865 if (const auto *D = U.dyn_cast<const Decl *>())
866 return ast_type_traits::DynTypedNode::create(*D);
867 if (const auto *S = U.dyn_cast<const Stmt *>())
868 return ast_type_traits::DynTypedNode::create(*S);
869 return *U.get<ast_type_traits::DynTypedNode *>();
870 }
871
872 template <typename NodeTy, typename MapTy>
873 static ASTContext::DynTypedNodeList getDynNodeFromMap(const NodeTy &Node,
874 const MapTy &Map) {
875 auto I = Map.find(Node);
876 if (I == Map.end()) {
877 return llvm::ArrayRef<ast_type_traits::DynTypedNode>();
878 }
879 if (const auto *V = I->second.template dyn_cast<ParentVector *>()) {
880 return llvm::makeArrayRef(*V);
881 }
882 return getSingleDynTypedNodeFromParentMap(I->second);
883 }
884
885public:
886 ParentMap(ASTContext &Ctx);
887 ~ParentMap() {
888 for (const auto &Entry : PointerParents) {
889 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
890 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
891 } else if (Entry.second.is<ParentVector *>()) {
892 delete Entry.second.get<ParentVector *>();
893 }
894 }
895 for (const auto &Entry : OtherParents) {
896 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
897 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
898 } else if (Entry.second.is<ParentVector *>()) {
899 delete Entry.second.get<ParentVector *>();
900 }
Benjamin Kramer94355ae2015-10-23 09:04:55 +0000901 }
902 }
Sam McCall814e7972018-11-14 10:33:30 +0000903
904 DynTypedNodeList getParents(const ast_type_traits::DynTypedNode &Node) {
905 if (Node.getNodeKind().hasPointerIdentity())
906 return getDynNodeFromMap(Node.getMemoizationData(), PointerParents);
907 return getDynNodeFromMap(Node, OtherParents);
Manuel Klimek95403e62014-05-21 13:28:59 +0000908 }
Sam McCall814e7972018-11-14 10:33:30 +0000909};
910
911void ASTContext::setTraversalScope(const std::vector<Decl *> &TopLevelDecls) {
912 TraversalScope = TopLevelDecls;
913 Parents.reset();
Manuel Klimek95403e62014-05-21 13:28:59 +0000914}
915
Douglas Gregor1a809332010-05-23 18:26:36 +0000916void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
Chandler Carruthff5a01a2015-12-30 03:00:23 +0000917 Deallocations.push_back({Callback, Data});
Douglas Gregor1a809332010-05-23 18:26:36 +0000918}
919
Mike Stump11289f42009-09-09 15:08:12 +0000920void
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000921ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
Benjamin Kramerd6da1a02016-06-12 20:05:23 +0000922 ExternalSource = std::move(Source);
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000923}
924
Chris Lattner4eb445d2007-01-26 01:27:23 +0000925void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000926 llvm::errs() << "\n*** AST Context Stats:\n";
927 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000928
Douglas Gregora30d0462009-05-26 14:40:08 +0000929 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000930#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000931#define ABSTRACT_TYPE(Name, Parent)
932#include "clang/AST/TypeNodes.def"
933 0 // Extra
934 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000935
Chris Lattner4eb445d2007-01-26 01:27:23 +0000936 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
937 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000938 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000939 }
940
Douglas Gregora30d0462009-05-26 14:40:08 +0000941 unsigned Idx = 0;
942 unsigned TotalBytes = 0;
943#define TYPE(Name, Parent) \
944 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000945 llvm::errs() << " " << counts[Idx] << " " << #Name \
Bruno Ricci58e03222018-08-06 15:17:32 +0000946 << " types, " << sizeof(Name##Type) << " each " \
947 << "(" << counts[Idx] * sizeof(Name##Type) \
948 << " bytes)\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000949 TotalBytes += counts[Idx] * sizeof(Name##Type); \
950 ++Idx;
951#define ABSTRACT_TYPE(Name, Parent)
952#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000953
Chandler Carruth3c147a72011-07-04 05:32:14 +0000954 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
955
Douglas Gregor7454c562010-07-02 20:37:36 +0000956 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000957 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
958 << NumImplicitDefaultConstructors
959 << " implicit default constructors created\n";
960 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
961 << NumImplicitCopyConstructors
962 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000963 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000964 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
965 << NumImplicitMoveConstructors
966 << " implicit move constructors created\n";
967 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
968 << NumImplicitCopyAssignmentOperators
969 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000970 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000971 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
972 << NumImplicitMoveAssignmentOperators
973 << " implicit move assignment operators created\n";
974 llvm::errs() << NumImplicitDestructorsDeclared << "/"
975 << NumImplicitDestructors
976 << " implicit destructors created\n";
977
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000978 if (ExternalSource) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000979 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000980 ExternalSource->PrintStats();
981 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000982
Douglas Gregor5b11d492010-07-25 17:53:33 +0000983 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000984}
985
Richard Smith42413142015-05-15 20:05:43 +0000986void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
987 bool NotifyListeners) {
988 if (NotifyListeners)
989 if (auto *Listener = getASTMutationListener())
990 Listener->RedefinedHiddenDefinition(ND, M);
991
Richard Smith13897eb2018-09-12 23:37:00 +0000992 MergedDefModules[cast<NamedDecl>(ND->getCanonicalDecl())].push_back(M);
Richard Smith42413142015-05-15 20:05:43 +0000993}
994
995void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) {
Richard Smith20fbdb32018-09-12 02:13:46 +0000996 auto It = MergedDefModules.find(cast<NamedDecl>(ND->getCanonicalDecl()));
Richard Smith42413142015-05-15 20:05:43 +0000997 if (It == MergedDefModules.end())
998 return;
999
Benjamin Kramera72a70a2016-10-17 13:00:44 +00001000 auto &Merged = It->second;
Richard Smith42413142015-05-15 20:05:43 +00001001 llvm::DenseSet<Module*> Found;
1002 for (Module *&M : Merged)
1003 if (!Found.insert(M).second)
1004 M = nullptr;
1005 Merged.erase(std::remove(Merged.begin(), Merged.end(), nullptr), Merged.end());
1006}
1007
Richard Smithdc1f0422016-07-20 19:10:16 +00001008void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
1009 if (LazyInitializers.empty())
1010 return;
1011
1012 auto *Source = Ctx.getExternalSource();
1013 assert(Source && "lazy initializers but no external source");
1014
1015 auto LazyInits = std::move(LazyInitializers);
1016 LazyInitializers.clear();
1017
1018 for (auto ID : LazyInits)
1019 Initializers.push_back(Source->GetExternalDecl(ID));
1020
1021 assert(LazyInitializers.empty() &&
1022 "GetExternalDecl for lazy module initializer added more inits");
1023}
1024
1025void ASTContext::addModuleInitializer(Module *M, Decl *D) {
1026 // One special case: if we add a module initializer that imports another
1027 // module, and that module's only initializer is an ImportDecl, simplify.
Eugene Zelenko7855e772018-04-03 00:11:50 +00001028 if (const auto *ID = dyn_cast<ImportDecl>(D)) {
Richard Smithdc1f0422016-07-20 19:10:16 +00001029 auto It = ModuleInitializers.find(ID->getImportedModule());
1030
1031 // Maybe the ImportDecl does nothing at all. (Common case.)
1032 if (It == ModuleInitializers.end())
1033 return;
1034
1035 // Maybe the ImportDecl only imports another ImportDecl.
1036 auto &Imported = *It->second;
1037 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
1038 Imported.resolve(*this);
1039 auto *OnlyDecl = Imported.Initializers.front();
1040 if (isa<ImportDecl>(OnlyDecl))
1041 D = OnlyDecl;
1042 }
1043 }
1044
1045 auto *&Inits = ModuleInitializers[M];
1046 if (!Inits)
1047 Inits = new (*this) PerModuleInitializers;
1048 Inits->Initializers.push_back(D);
1049}
1050
1051void ASTContext::addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs) {
1052 auto *&Inits = ModuleInitializers[M];
1053 if (!Inits)
1054 Inits = new (*this) PerModuleInitializers;
1055 Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
1056 IDs.begin(), IDs.end());
1057}
1058
Eugene Zelenko7855e772018-04-03 00:11:50 +00001059ArrayRef<Decl *> ASTContext::getModuleInitializers(Module *M) {
Richard Smithdc1f0422016-07-20 19:10:16 +00001060 auto It = ModuleInitializers.find(M);
Fangrui Song6907ce22018-07-30 19:24:48 +00001061 if (It == ModuleInitializers.end())
Richard Smithdc1f0422016-07-20 19:10:16 +00001062 return None;
1063
1064 auto *Inits = It->second;
1065 Inits->resolve(*this);
1066 return Inits->Initializers;
1067}
1068
Richard Smithf19e1272015-03-07 00:04:49 +00001069ExternCContextDecl *ASTContext::getExternCContextDecl() const {
1070 if (!ExternCContext)
1071 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
1072
1073 return ExternCContext;
1074}
1075
David Majnemerd9b1a4f2015-11-04 03:40:30 +00001076BuiltinTemplateDecl *
1077ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
1078 const IdentifierInfo *II) const {
1079 auto *BuiltinTemplate = BuiltinTemplateDecl::Create(*this, TUDecl, II, BTK);
1080 BuiltinTemplate->setImplicit();
1081 TUDecl->addDecl(BuiltinTemplate);
1082
1083 return BuiltinTemplate;
1084}
1085
1086BuiltinTemplateDecl *
1087ASTContext::getMakeIntegerSeqDecl() const {
1088 if (!MakeIntegerSeqDecl)
1089 MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq,
1090 getMakeIntegerSeqName());
1091 return MakeIntegerSeqDecl;
1092}
1093
Eric Fiselier6ad68552016-07-01 01:24:09 +00001094BuiltinTemplateDecl *
1095ASTContext::getTypePackElementDecl() const {
1096 if (!TypePackElementDecl)
1097 TypePackElementDecl = buildBuiltinTemplateDecl(BTK__type_pack_element,
1098 getTypePackElementName());
1099 return TypePackElementDecl;
1100}
1101
Alp Toker2dea15b2013-12-17 01:22:38 +00001102RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
1103 RecordDecl::TagKind TK) const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001104 SourceLocation Loc;
1105 RecordDecl *NewDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00001106 if (getLangOpts().CPlusPlus)
1107 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
1108 Loc, &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +00001109 else
Alp Toker2dea15b2013-12-17 01:22:38 +00001110 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
1111 &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +00001112 NewDecl->setImplicit();
David Majnemerf8637362015-01-15 08:41:25 +00001113 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
1114 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
Alp Toker56b5cc92013-12-15 10:36:26 +00001115 return NewDecl;
1116}
1117
1118TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
1119 StringRef Name) const {
1120 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
1121 TypedefDecl *NewDecl = TypedefDecl::Create(
1122 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
1123 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
1124 NewDecl->setImplicit();
1125 return NewDecl;
1126}
1127
Douglas Gregor801c99d2011-08-12 06:49:56 +00001128TypedefDecl *ASTContext::getInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001129 if (!Int128Decl)
1130 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +00001131 return Int128Decl;
1132}
1133
1134TypedefDecl *ASTContext::getUInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001135 if (!UInt128Decl)
1136 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +00001137 return UInt128Decl;
1138}
Chris Lattner4eb445d2007-01-26 01:27:23 +00001139
John McCall48f2d582009-10-23 23:03:21 +00001140void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001141 auto *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +00001142 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +00001143 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001144}
1145
Artem Belevichb5bc9232015-09-22 17:23:22 +00001146void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
1147 const TargetInfo *AuxTarget) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001148 assert((!this->Target || this->Target == &Target) &&
1149 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +00001150 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +00001151
Douglas Gregore8bbc122011-09-02 00:18:52 +00001152 this->Target = &Target;
Artem Belevichb5bc9232015-09-22 17:23:22 +00001153 this->AuxTarget = AuxTarget;
1154
Douglas Gregore8bbc122011-09-02 00:18:52 +00001155 ABI.reset(createCXXABI(Target));
1156 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
David Tweed31d09b02013-09-13 12:04:22 +00001157 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
Fangrui Song6907ce22018-07-30 19:24:48 +00001158
Chris Lattner970e54e2006-11-12 00:37:36 +00001159 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +00001160 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +00001161
Chris Lattner970e54e2006-11-12 00:37:36 +00001162 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +00001163 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +00001164 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +00001165 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +00001166 InitBuiltinType(CharTy, BuiltinType::Char_S);
1167 else
1168 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +00001169 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +00001170 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
1171 InitBuiltinType(ShortTy, BuiltinType::Short);
1172 InitBuiltinType(IntTy, BuiltinType::Int);
1173 InitBuiltinType(LongTy, BuiltinType::Long);
1174 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +00001175
Chris Lattner970e54e2006-11-12 00:37:36 +00001176 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +00001177 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
1178 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
1179 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
1180 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
1181 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +00001182
Chris Lattner970e54e2006-11-12 00:37:36 +00001183 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +00001184 InitBuiltinType(FloatTy, BuiltinType::Float);
1185 InitBuiltinType(DoubleTy, BuiltinType::Double);
1186 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001187
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001188 // GNU extension, __float128 for IEEE quadruple precision
1189 InitBuiltinType(Float128Ty, BuiltinType::Float128);
1190
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00001191 // C11 extension ISO/IEC TS 18661-3
1192 InitBuiltinType(Float16Ty, BuiltinType::Float16);
1193
Leonard Chanf921d852018-06-04 16:07:52 +00001194 // ISO/IEC JTC1 SC22 WG14 N1169 Extension
Leonard Chanab80f3c2018-06-14 14:53:51 +00001195 InitBuiltinType(ShortAccumTy, BuiltinType::ShortAccum);
1196 InitBuiltinType(AccumTy, BuiltinType::Accum);
1197 InitBuiltinType(LongAccumTy, BuiltinType::LongAccum);
1198 InitBuiltinType(UnsignedShortAccumTy, BuiltinType::UShortAccum);
1199 InitBuiltinType(UnsignedAccumTy, BuiltinType::UAccum);
1200 InitBuiltinType(UnsignedLongAccumTy, BuiltinType::ULongAccum);
1201 InitBuiltinType(ShortFractTy, BuiltinType::ShortFract);
1202 InitBuiltinType(FractTy, BuiltinType::Fract);
1203 InitBuiltinType(LongFractTy, BuiltinType::LongFract);
1204 InitBuiltinType(UnsignedShortFractTy, BuiltinType::UShortFract);
1205 InitBuiltinType(UnsignedFractTy, BuiltinType::UFract);
1206 InitBuiltinType(UnsignedLongFractTy, BuiltinType::ULongFract);
1207 InitBuiltinType(SatShortAccumTy, BuiltinType::SatShortAccum);
1208 InitBuiltinType(SatAccumTy, BuiltinType::SatAccum);
1209 InitBuiltinType(SatLongAccumTy, BuiltinType::SatLongAccum);
1210 InitBuiltinType(SatUnsignedShortAccumTy, BuiltinType::SatUShortAccum);
1211 InitBuiltinType(SatUnsignedAccumTy, BuiltinType::SatUAccum);
1212 InitBuiltinType(SatUnsignedLongAccumTy, BuiltinType::SatULongAccum);
1213 InitBuiltinType(SatShortFractTy, BuiltinType::SatShortFract);
1214 InitBuiltinType(SatFractTy, BuiltinType::SatFract);
1215 InitBuiltinType(SatLongFractTy, BuiltinType::SatLongFract);
1216 InitBuiltinType(SatUnsignedShortFractTy, BuiltinType::SatUShortFract);
1217 InitBuiltinType(SatUnsignedFractTy, BuiltinType::SatUFract);
1218 InitBuiltinType(SatUnsignedLongFractTy, BuiltinType::SatULongFract);
Leonard Chanf921d852018-06-04 16:07:52 +00001219
Chris Lattnerf122cef2009-04-30 02:43:43 +00001220 // GNU extension, 128-bit integers.
1221 InitBuiltinType(Int128Ty, BuiltinType::Int128);
1222 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
1223
Hans Wennborg0d81e012013-05-10 10:08:40 +00001224 // C++ 3.9.1p5
1225 if (TargetInfo::isTypeSigned(Target.getWCharType()))
1226 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1227 else // -fshort-wchar makes wchar_t be unsigned.
1228 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1229 if (LangOpts.CPlusPlus && LangOpts.WChar)
1230 WideCharTy = WCharTy;
1231 else {
1232 // C99 (or C++ using -fno-wchar).
1233 WideCharTy = getFromTargetType(Target.getWCharType());
1234 }
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001235
James Molloy36365542012-05-04 10:55:22 +00001236 WIntTy = getFromTargetType(Target.getWIntType());
1237
Richard Smith3a8244d2018-05-01 05:02:45 +00001238 // C++20 (proposed)
1239 InitBuiltinType(Char8Ty, BuiltinType::Char8);
1240
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001241 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1242 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1243 else // C99
1244 Char16Ty = getFromTargetType(Target.getChar16Type());
1245
1246 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1247 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1248 else // C99
1249 Char32Ty = getFromTargetType(Target.getChar32Type());
1250
Douglas Gregor4619e432008-12-05 23:32:09 +00001251 // Placeholder type for type-dependent expressions whose type is
1252 // completely unknown. No code should ever check a type against
1253 // DependentTy and users should never see it; however, it is here to
1254 // help diagnose failures to properly check for type-dependent
1255 // expressions.
1256 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001257
John McCall36e7fe32010-10-12 00:20:44 +00001258 // Placeholder type for functions.
1259 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1260
John McCall0009fcc2011-04-26 20:42:42 +00001261 // Placeholder type for bound members.
1262 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1263
John McCall526ab472011-10-25 17:37:35 +00001264 // Placeholder type for pseudo-objects.
1265 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1266
John McCall31996342011-04-07 08:22:57 +00001267 // "any" type; useful for debugger-like clients.
1268 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1269
John McCall8a6b59a2011-10-17 18:09:15 +00001270 // Placeholder type for unbridged ARC casts.
1271 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1272
Eli Friedman34866c72012-08-31 00:14:07 +00001273 // Placeholder type for builtin functions.
1274 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1275
Alexey Bataev1a3320e2015-08-25 14:24:04 +00001276 // Placeholder type for OMP array sections.
1277 if (LangOpts.OpenMP)
1278 InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection);
1279
Chris Lattner970e54e2006-11-12 00:37:36 +00001280 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +00001281 FloatComplexTy = getComplexType(FloatTy);
1282 DoubleComplexTy = getComplexType(DoubleTy);
1283 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001284 Float128ComplexTy = getComplexType(Float128Ty);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001285
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001286 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +00001287 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1288 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001289 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001290
Alexey Bader954ba212016-04-08 13:40:33 +00001291 if (LangOpts.OpenCL) {
1292#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1293 InitBuiltinType(SingletonId, BuiltinType::Id);
Alexey Baderb62f1442016-04-13 08:33:41 +00001294#include "clang/Basic/OpenCLImageTypes.def"
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001295
Guy Benyei61054192013-02-07 10:55:47 +00001296 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001297 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Alexey Bader9c8453f2015-09-15 11:18:52 +00001298 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1299 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
Alexey Bader9c8453f2015-09-15 11:18:52 +00001300 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
Andrew Savonichev3fee3512018-11-08 11:25:41 +00001301
1302#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1303 InitBuiltinType(Id##Ty, BuiltinType::Id);
1304#include "clang/Basic/OpenCLExtensionTypes.def"
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001305 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001306
Ted Kremeneke65b0862012-03-06 20:05:56 +00001307 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +00001308 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1309 SignedCharTy : BoolTy);
Fangrui Song6907ce22018-07-30 19:24:48 +00001310
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001311 ObjCConstantStringType = QualType();
Fangrui Song6907ce22018-07-30 19:24:48 +00001312
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001313 ObjCSuperType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +00001314
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00001315 // void * type
Yaxun Liu39195062017-08-04 18:16:31 +00001316 if (LangOpts.OpenCLVersion >= 200) {
1317 auto Q = VoidTy.getQualifiers();
1318 Q.setAddressSpace(LangAS::opencl_generic);
1319 VoidPtrTy = getPointerType(getCanonicalType(
1320 getQualifiedType(VoidTy.getUnqualifiedType(), Q)));
1321 } else {
1322 VoidPtrTy = getPointerType(VoidTy);
1323 }
Sebastian Redl576fd422009-05-10 18:38:11 +00001324
1325 // nullptr type (C++0x 2.14.7)
1326 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001327
1328 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1329 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +00001330
1331 // Builtin type used to help define __builtin_va_list.
Richard Smith9b88a4c2015-07-27 05:40:23 +00001332 VaListTagDecl = nullptr;
Chris Lattner970e54e2006-11-12 00:37:36 +00001333}
1334
David Blaikie9c902b52011-09-25 23:23:43 +00001335DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001336 return SourceMgr.getDiagnostics();
1337}
1338
Douglas Gregor561eceb2010-08-30 16:49:28 +00001339AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1340 AttrVec *&Result = DeclAttrs[D];
1341 if (!Result) {
1342 void *Mem = Allocate(sizeof(AttrVec));
1343 Result = new (Mem) AttrVec;
1344 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001345
Douglas Gregor561eceb2010-08-30 16:49:28 +00001346 return *Result;
1347}
1348
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001349/// Erase the attributes corresponding to the given declaration.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00001350void ASTContext::eraseDeclAttrs(const Decl *D) {
Douglas Gregor561eceb2010-08-30 16:49:28 +00001351 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1352 if (Pos != DeclAttrs.end()) {
1353 Pos->second->~AttrVec();
1354 DeclAttrs.erase(Pos);
1355 }
1356}
1357
Larisse Voufo39a1e502013-08-06 01:03:05 +00001358// FIXME: Remove ?
Douglas Gregor86d142a2009-10-08 07:24:58 +00001359MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +00001360ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001361 assert(Var->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001362 return getTemplateOrSpecializationInfo(Var)
1363 .dyn_cast<MemberSpecializationInfo *>();
1364}
1365
1366ASTContext::TemplateOrSpecializationInfo
1367ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1368 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1369 TemplateOrInstantiation.find(Var);
1370 if (Pos == TemplateOrInstantiation.end())
Eugene Zelenko7855e772018-04-03 00:11:50 +00001371 return {};
Mike Stump11289f42009-09-09 15:08:12 +00001372
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001373 return Pos->second;
1374}
1375
Mike Stump11289f42009-09-09 15:08:12 +00001376void
Douglas Gregor86d142a2009-10-08 07:24:58 +00001377ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +00001378 TemplateSpecializationKind TSK,
1379 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001380 assert(Inst->isStaticDataMember() && "Not a static data member");
1381 assert(Tmpl->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001382 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1383 Tmpl, TSK, PointOfInstantiation));
1384}
1385
1386void
1387ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1388 TemplateOrSpecializationInfo TSI) {
1389 assert(!TemplateOrInstantiation[Inst] &&
1390 "Already noted what the variable was instantiated from");
1391 TemplateOrInstantiation[Inst] = TSI;
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001392}
1393
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001394FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1395 const FunctionDecl *FD){
1396 assert(FD && "Specialization is 0");
1397 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +00001398 = ClassScopeSpecializationPattern.find(FD);
1399 if (Pos == ClassScopeSpecializationPattern.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001400 return nullptr;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001401
1402 return Pos->second;
1403}
1404
1405void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1406 FunctionDecl *Pattern) {
1407 assert(FD && "Specialization is 0");
1408 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +00001409 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001410}
1411
John McCalle61f2ba2009-11-18 02:36:19 +00001412NamedDecl *
Richard Smithd8a9e372016-12-18 21:39:37 +00001413ASTContext::getInstantiatedFromUsingDecl(NamedDecl *UUD) {
1414 auto Pos = InstantiatedFromUsingDecl.find(UUD);
John McCallb96ec562009-12-04 22:46:56 +00001415 if (Pos == InstantiatedFromUsingDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001416 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001417
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001418 return Pos->second;
1419}
1420
1421void
Richard Smithd8a9e372016-12-18 21:39:37 +00001422ASTContext::setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern) {
John McCallb96ec562009-12-04 22:46:56 +00001423 assert((isa<UsingDecl>(Pattern) ||
1424 isa<UnresolvedUsingValueDecl>(Pattern) ||
Fangrui Song6907ce22018-07-30 19:24:48 +00001425 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
John McCallb96ec562009-12-04 22:46:56 +00001426 "pattern decl is not a using decl");
Richard Smithd8a9e372016-12-18 21:39:37 +00001427 assert((isa<UsingDecl>(Inst) ||
1428 isa<UnresolvedUsingValueDecl>(Inst) ||
Fangrui Song6907ce22018-07-30 19:24:48 +00001429 isa<UnresolvedUsingTypenameDecl>(Inst)) &&
Richard Smithd8a9e372016-12-18 21:39:37 +00001430 "instantiation did not produce a using decl");
John McCallb96ec562009-12-04 22:46:56 +00001431 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1432 InstantiatedFromUsingDecl[Inst] = Pattern;
1433}
1434
1435UsingShadowDecl *
1436ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1437 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1438 = InstantiatedFromUsingShadowDecl.find(Inst);
1439 if (Pos == InstantiatedFromUsingShadowDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001440 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00001441
1442 return Pos->second;
1443}
1444
1445void
1446ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1447 UsingShadowDecl *Pattern) {
1448 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1449 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001450}
1451
Anders Carlsson5da84842009-09-01 04:26:58 +00001452FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1453 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1454 = InstantiatedFromUnnamedFieldDecl.find(Field);
1455 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001456 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001457
Anders Carlsson5da84842009-09-01 04:26:58 +00001458 return Pos->second;
1459}
1460
1461void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1462 FieldDecl *Tmpl) {
1463 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1464 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1465 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1466 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +00001467
Anders Carlsson5da84842009-09-01 04:26:58 +00001468 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1469}
1470
Douglas Gregor832940b2010-03-02 23:58:15 +00001471ASTContext::overridden_cxx_method_iterator
1472ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
Benjamin Krameracfa3392017-12-17 23:52:45 +00001473 return overridden_methods(Method).begin();
Douglas Gregor832940b2010-03-02 23:58:15 +00001474}
1475
1476ASTContext::overridden_cxx_method_iterator
1477ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
Benjamin Krameracfa3392017-12-17 23:52:45 +00001478 return overridden_methods(Method).end();
Douglas Gregor832940b2010-03-02 23:58:15 +00001479}
1480
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001481unsigned
1482ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
Benjamin Krameracfa3392017-12-17 23:52:45 +00001483 auto Range = overridden_methods(Method);
1484 return Range.end() - Range.begin();
Clement Courbet8251ebf2016-06-10 11:54:43 +00001485}
1486
Clement Courbet6ecaec82016-07-05 07:49:31 +00001487ASTContext::overridden_method_range
1488ASTContext::overridden_methods(const CXXMethodDecl *Method) const {
Benjamin Krameracfa3392017-12-17 23:52:45 +00001489 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1490 OverriddenMethods.find(Method->getCanonicalDecl());
1491 if (Pos == OverriddenMethods.end())
1492 return overridden_method_range(nullptr, nullptr);
1493 return overridden_method_range(Pos->second.begin(), Pos->second.end());
Clement Courbet6ecaec82016-07-05 07:49:31 +00001494}
1495
Fangrui Song6907ce22018-07-30 19:24:48 +00001496void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
Douglas Gregor832940b2010-03-02 23:58:15 +00001497 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001498 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001499 OverriddenMethods[Method].push_back(Overridden);
1500}
1501
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +00001502void ASTContext::getOverriddenMethods(
1503 const NamedDecl *D,
1504 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001505 assert(D);
1506
Eugene Zelenko7855e772018-04-03 00:11:50 +00001507 if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisc8e70082013-04-17 00:09:03 +00001508 Overridden.append(overridden_methods_begin(CXXMethod),
1509 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001510 return;
1511 }
1512
Eugene Zelenko7855e772018-04-03 00:11:50 +00001513 const auto *Method = dyn_cast<ObjCMethodDecl>(D);
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001514 if (!Method)
1515 return;
1516
Argyrios Kyrtzidis353f6a42012-10-09 18:19:01 +00001517 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1518 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001519 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001520}
1521
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001522void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1523 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1524 assert(!Import->isFromASTFile() && "Non-local import declaration");
1525 if (!FirstLocalImport) {
1526 FirstLocalImport = Import;
1527 LastLocalImport = Import;
1528 return;
1529 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001530
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001531 LastLocalImport->NextLocalImport = Import;
1532 LastLocalImport = Import;
1533}
1534
Chris Lattner53cfe802007-07-18 17:52:12 +00001535//===----------------------------------------------------------------------===//
1536// Type Sizing and Analysis
1537//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001538
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001539/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1540/// scalar floating point type.
1541const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001542 const auto *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001543 assert(BT && "Not a floating point type!");
1544 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001545 default: llvm_unreachable("Not a floating point type!");
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00001546 case BuiltinType::Float16:
1547 case BuiltinType::Half:
1548 return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001549 case BuiltinType::Float: return Target->getFloatFormat();
1550 case BuiltinType::Double: return Target->getDoubleFormat();
1551 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001552 case BuiltinType::Float128: return Target->getFloat128Format();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001553 }
1554}
1555
Rafael Espindola71eccb32013-08-08 19:53:46 +00001556CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001557 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001558
John McCall94268702010-10-08 18:24:19 +00001559 bool UseAlignAttrOnly = false;
1560 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1561 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001562
John McCall94268702010-10-08 18:24:19 +00001563 // __attribute__((aligned)) can increase or decrease alignment
1564 // *except* on a struct or struct member, where it only increases
1565 // alignment unless 'packed' is also specified.
1566 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001567 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001568 // ignore that possibility; Sema should diagnose it.
1569 if (isa<FieldDecl>(D)) {
1570 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1571 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1572 } else {
1573 UseAlignAttrOnly = true;
1574 }
1575 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001576 else if (isa<FieldDecl>(D))
Fangrui Song6907ce22018-07-30 19:24:48 +00001577 UseAlignAttrOnly =
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001578 D->hasAttr<PackedAttr>() ||
1579 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001580
John McCall4e819612011-01-20 07:57:12 +00001581 // If we're using the align attribute only, just ignore everything
1582 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001583 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001584 // do nothing
Eugene Zelenko7855e772018-04-03 00:11:50 +00001585 } else if (const auto *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001586 QualType T = VD->getType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00001587 if (const auto *RT = T->getAs<ReferenceType>()) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001588 if (ForAlignof)
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001589 T = RT->getPointeeType();
1590 else
1591 T = getPointerType(RT->getPointeeType());
1592 }
Richard Smithf6d70302014-06-10 23:34:28 +00001593 QualType BaseT = getBaseElementType(T);
Akira Hatanakad62f2c82017-01-06 17:56:15 +00001594 if (T->isFunctionType())
1595 Align = getTypeInfoImpl(T.getTypePtr()).Align;
1596 else if (!BaseT->isIncompleteType()) {
John McCall33ddac02011-01-19 10:06:00 +00001597 // Adjust alignments of declarations with array type by the
1598 // large-array alignment on the target.
Rafael Espindola88572752013-08-07 18:08:19 +00001599 if (const ArrayType *arrayType = getAsArrayType(T)) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001600 unsigned MinWidth = Target->getLargeArrayMinWidth();
1601 if (!ForAlignof && MinWidth) {
Rafael Espindola88572752013-08-07 18:08:19 +00001602 if (isa<VariableArrayType>(arrayType))
1603 Align = std::max(Align, Target->getLargeArrayAlign());
1604 else if (isa<ConstantArrayType>(arrayType) &&
1605 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1606 Align = std::max(Align, Target->getLargeArrayAlign());
1607 }
John McCall33ddac02011-01-19 10:06:00 +00001608 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001609 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Roger Ferrer Ibanez3fa38a12017-03-08 14:00:44 +00001610 if (BaseT.getQualifiers().hasUnaligned())
1611 Align = Target->getCharWidth();
Eugene Zelenko7855e772018-04-03 00:11:50 +00001612 if (const auto *VD = dyn_cast<VarDecl>(D)) {
Ulrich Weigandb63f7792015-04-21 17:26:18 +00001613 if (VD->hasGlobalStorage() && !ForAlignof)
Ulrich Weigandfa806422013-05-06 16:23:57 +00001614 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1615 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001616 }
John McCall4e819612011-01-20 07:57:12 +00001617
1618 // Fields can be subject to extra alignment constraints, like if
1619 // the field is packed, the struct is packed, or the struct has a
1620 // a max-field-alignment constraint (#pragma pack). So calculate
1621 // the actual alignment of the field within the struct, and then
1622 // (as we're expected to) constrain that by the alignment of the type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00001623 if (const auto *Field = dyn_cast<FieldDecl>(VD)) {
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001624 const RecordDecl *Parent = Field->getParent();
1625 // We can only produce a sensible answer if the record is valid.
1626 if (!Parent->isInvalidDecl()) {
1627 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
John McCall4e819612011-01-20 07:57:12 +00001628
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001629 // Start with the record's overall alignment.
1630 unsigned FieldAlign = toBits(Layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001631
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001632 // Use the GCD of that and the offset within the record.
1633 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1634 if (Offset > 0) {
1635 // Alignment is always a power of 2, so the GCD will be a power of 2,
1636 // which means we get to do this crazy thing instead of Euclid's.
1637 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1638 if (LowBitOfOffset < FieldAlign)
1639 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1640 }
1641
1642 Align = std::min(Align, FieldAlign);
John McCall4e819612011-01-20 07:57:12 +00001643 }
Charles Davis3fc51072010-02-23 04:52:00 +00001644 }
Chris Lattner68061312009-01-24 21:53:27 +00001645 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001646
Ken Dyckcc56c542011-01-15 18:38:59 +00001647 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001648}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001649
John McCallf1249922012-08-21 04:10:00 +00001650// getTypeInfoDataSizeInChars - Return the size of a type, in
1651// chars. If the type is a record, its data size is returned. This is
1652// the size of the memcpy that's performed when assigning this type
1653// using a trivial copy/move assignment operator.
1654std::pair<CharUnits, CharUnits>
1655ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1656 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1657
1658 // In C++, objects can sometimes be allocated into the tail padding
1659 // of a base-class subobject. We decide whether that's possible
1660 // during class layout, so here we can just trust the layout results.
1661 if (getLangOpts().CPlusPlus) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001662 if (const auto *RT = T->getAs<RecordType>()) {
John McCallf1249922012-08-21 04:10:00 +00001663 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1664 sizeAndAlign.first = layout.getDataSize();
1665 }
1666 }
1667
1668 return sizeAndAlign;
1669}
1670
Richard Trieu04d2d942013-05-14 21:59:17 +00001671/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1672/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1673std::pair<CharUnits, CharUnits>
1674static getConstantArrayInfoInChars(const ASTContext &Context,
1675 const ConstantArrayType *CAT) {
1676 std::pair<CharUnits, CharUnits> EltInfo =
1677 Context.getTypeInfoInChars(CAT->getElementType());
1678 uint64_t Size = CAT->getSize().getZExtValue();
Richard Trieuc7509072013-05-14 23:41:50 +00001679 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1680 (uint64_t)(-1)/Size) &&
Richard Trieu04d2d942013-05-14 21:59:17 +00001681 "Overflow in array type char size evaluation");
1682 uint64_t Width = EltInfo.first.getQuantity() * Size;
1683 unsigned Align = EltInfo.second.getQuantity();
Warren Hunt5ae586a2013-11-01 23:59:41 +00001684 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1685 Context.getTargetInfo().getPointerWidth(0) == 64)
Rui Ueyama83aa9792016-01-14 21:00:27 +00001686 Width = llvm::alignTo(Width, Align);
Richard Trieu04d2d942013-05-14 21:59:17 +00001687 return std::make_pair(CharUnits::fromQuantity(Width),
1688 CharUnits::fromQuantity(Align));
1689}
1690
John McCall87fe5d52010-05-20 01:18:31 +00001691std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001692ASTContext::getTypeInfoInChars(const Type *T) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001693 if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
Richard Trieu04d2d942013-05-14 21:59:17 +00001694 return getConstantArrayInfoInChars(*this, CAT);
David Majnemer34b57492014-07-30 01:30:47 +00001695 TypeInfo Info = getTypeInfo(T);
1696 return std::make_pair(toCharUnitsFromBits(Info.Width),
1697 toCharUnitsFromBits(Info.Align));
John McCall87fe5d52010-05-20 01:18:31 +00001698}
1699
1700std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001701ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001702 return getTypeInfoInChars(T.getTypePtr());
1703}
1704
David Majnemer34b57492014-07-30 01:30:47 +00001705bool ASTContext::isAlignmentRequired(const Type *T) const {
1706 return getTypeInfo(T).AlignIsRequired;
1707}
Daniel Dunbarc6475872012-03-09 04:12:54 +00001708
David Majnemer34b57492014-07-30 01:30:47 +00001709bool ASTContext::isAlignmentRequired(QualType T) const {
1710 return isAlignmentRequired(T.getTypePtr());
1711}
1712
Richard Smithb2f0f052016-10-10 18:54:32 +00001713unsigned ASTContext::getTypeAlignIfKnown(QualType T) const {
1714 // An alignment on a typedef overrides anything else.
Eugene Zelenko7855e772018-04-03 00:11:50 +00001715 if (const auto *TT = T->getAs<TypedefType>())
Richard Smithb2f0f052016-10-10 18:54:32 +00001716 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1717 return Align;
1718
1719 // If we have an (array of) complete type, we're done.
1720 T = getBaseElementType(T);
1721 if (!T->isIncompleteType())
1722 return getTypeAlign(T);
1723
1724 // If we had an array type, its element type might be a typedef
1725 // type with an alignment attribute.
Eugene Zelenko7855e772018-04-03 00:11:50 +00001726 if (const auto *TT = T->getAs<TypedefType>())
Richard Smithb2f0f052016-10-10 18:54:32 +00001727 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1728 return Align;
1729
1730 // Otherwise, see if the declaration of the type had an attribute.
Eugene Zelenko7855e772018-04-03 00:11:50 +00001731 if (const auto *TT = T->getAs<TagType>())
Richard Smithb2f0f052016-10-10 18:54:32 +00001732 return TT->getDecl()->getMaxAlignment();
1733
1734 return 0;
1735}
1736
David Majnemer34b57492014-07-30 01:30:47 +00001737TypeInfo ASTContext::getTypeInfo(const Type *T) const {
David Majnemerf8d38642014-07-30 08:42:33 +00001738 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1739 if (I != MemoizedTypeInfo.end())
1740 return I->second;
1741
1742 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1743 TypeInfo TI = getTypeInfoImpl(T);
1744 MemoizedTypeInfo[T] = TI;
Rafael Espindolaeaa88c12014-07-30 04:40:23 +00001745 return TI;
Daniel Dunbarc6475872012-03-09 04:12:54 +00001746}
1747
1748/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1749/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001750///
1751/// FIXME: Pointers into different addr spaces could have different sizes and
1752/// alignment requirements: getPointerInfo should take an AddrSpace, this
1753/// should take a QualType, &c.
David Majnemer34b57492014-07-30 01:30:47 +00001754TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1755 uint64_t Width = 0;
1756 unsigned Align = 8;
1757 bool AlignIsRequired = false;
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001758 unsigned AS = 0;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001759 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001760#define TYPE(Class, Base)
1761#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001762#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001763#define DEPENDENT_TYPE(Class, Base) case Type::Class:
David Blaikieab277d62013-07-13 21:08:03 +00001764#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1765 case Type::Class: \
1766 assert(!T->isDependentType() && "should not see dependent types here"); \
1767 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001768#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001769 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001770
Chris Lattner355332d2007-07-13 22:27:08 +00001771 case Type::FunctionNoProto:
1772 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001773 // GCC extension: alignof(function) = 32 bits
1774 Width = 0;
1775 Align = 32;
1776 break;
1777
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001778 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001779 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001780 Width = 0;
1781 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1782 break;
1783
Steve Naroff5c131802007-08-30 01:06:46 +00001784 case Type::ConstantArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001785 const auto *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001786
David Majnemer34b57492014-07-30 01:30:47 +00001787 TypeInfo EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001788 uint64_t Size = CAT->getSize().getZExtValue();
David Majnemer34b57492014-07-30 01:30:47 +00001789 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
Daniel Dunbarc6475872012-03-09 04:12:54 +00001790 "Overflow in array type bit size evaluation");
David Majnemer34b57492014-07-30 01:30:47 +00001791 Width = EltInfo.Width * Size;
1792 Align = EltInfo.Align;
Warren Hunt5ae586a2013-11-01 23:59:41 +00001793 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1794 getTargetInfo().getPointerWidth(0) == 64)
Rui Ueyama83aa9792016-01-14 21:00:27 +00001795 Width = llvm::alignTo(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001796 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001797 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001798 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001799 case Type::Vector: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001800 const auto *VT = cast<VectorType>(T);
David Majnemer34b57492014-07-30 01:30:47 +00001801 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1802 Width = EltInfo.Width * VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001803 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001804 // If the alignment is not a power of 2, round up to the next power of 2.
1805 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001806 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001807 Align = llvm::NextPowerOf2(Align);
Rui Ueyama83aa9792016-01-14 21:00:27 +00001808 Width = llvm::alignTo(Width, Align);
Chris Lattner63d2b362009-10-22 05:17:15 +00001809 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001810 // Adjust the alignment based on the target max.
1811 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1812 if (TargetVectorAlign && TargetVectorAlign < Align)
1813 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001814 break;
1815 }
Chris Lattner647fb222007-07-18 18:26:58 +00001816
Chris Lattner7570e9c2008-03-08 08:52:55 +00001817 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001818 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001819 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001820 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001821 // GCC extension: alignof(void) = 8 bits.
1822 Width = 0;
1823 Align = 8;
1824 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001825 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001826 Width = Target->getBoolWidth();
1827 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001828 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001829 case BuiltinType::Char_S:
1830 case BuiltinType::Char_U:
1831 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001832 case BuiltinType::SChar:
Richard Smith3a8244d2018-05-01 05:02:45 +00001833 case BuiltinType::Char8:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001834 Width = Target->getCharWidth();
1835 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001836 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001837 case BuiltinType::WChar_S:
1838 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001839 Width = Target->getWCharWidth();
1840 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001841 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001842 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001843 Width = Target->getChar16Width();
1844 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001845 break;
1846 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001847 Width = Target->getChar32Width();
1848 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001849 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001850 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001851 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001852 Width = Target->getShortWidth();
1853 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001854 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001855 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001856 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001857 Width = Target->getIntWidth();
1858 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001859 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001860 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001861 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001862 Width = Target->getLongWidth();
1863 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001864 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001865 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001866 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001867 Width = Target->getLongLongWidth();
1868 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001869 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001870 case BuiltinType::Int128:
1871 case BuiltinType::UInt128:
1872 Width = 128;
1873 Align = 128; // int128_t is 128-bit aligned on all targets.
1874 break;
Leonard Chanf921d852018-06-04 16:07:52 +00001875 case BuiltinType::ShortAccum:
1876 case BuiltinType::UShortAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00001877 case BuiltinType::SatShortAccum:
1878 case BuiltinType::SatUShortAccum:
Leonard Chanf921d852018-06-04 16:07:52 +00001879 Width = Target->getShortAccumWidth();
1880 Align = Target->getShortAccumAlign();
1881 break;
1882 case BuiltinType::Accum:
1883 case BuiltinType::UAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00001884 case BuiltinType::SatAccum:
1885 case BuiltinType::SatUAccum:
Leonard Chanf921d852018-06-04 16:07:52 +00001886 Width = Target->getAccumWidth();
1887 Align = Target->getAccumAlign();
1888 break;
1889 case BuiltinType::LongAccum:
1890 case BuiltinType::ULongAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00001891 case BuiltinType::SatLongAccum:
1892 case BuiltinType::SatULongAccum:
Leonard Chanf921d852018-06-04 16:07:52 +00001893 Width = Target->getLongAccumWidth();
1894 Align = Target->getLongAccumAlign();
1895 break;
Leonard Chanab80f3c2018-06-14 14:53:51 +00001896 case BuiltinType::ShortFract:
1897 case BuiltinType::UShortFract:
1898 case BuiltinType::SatShortFract:
1899 case BuiltinType::SatUShortFract:
1900 Width = Target->getShortFractWidth();
1901 Align = Target->getShortFractAlign();
1902 break;
1903 case BuiltinType::Fract:
1904 case BuiltinType::UFract:
1905 case BuiltinType::SatFract:
1906 case BuiltinType::SatUFract:
1907 Width = Target->getFractWidth();
1908 Align = Target->getFractAlign();
1909 break;
1910 case BuiltinType::LongFract:
1911 case BuiltinType::ULongFract:
1912 case BuiltinType::SatLongFract:
1913 case BuiltinType::SatULongFract:
1914 Width = Target->getLongFractWidth();
1915 Align = Target->getLongFractAlign();
1916 break;
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00001917 case BuiltinType::Float16:
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001918 case BuiltinType::Half:
1919 Width = Target->getHalfWidth();
1920 Align = Target->getHalfAlign();
1921 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001922 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001923 Width = Target->getFloatWidth();
1924 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001925 break;
1926 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001927 Width = Target->getDoubleWidth();
1928 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001929 break;
1930 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001931 Width = Target->getLongDoubleWidth();
1932 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001933 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001934 case BuiltinType::Float128:
1935 Width = Target->getFloat128Width();
1936 Align = Target->getFloat128Align();
1937 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001938 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001939 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1940 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001941 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001942 case BuiltinType::ObjCId:
1943 case BuiltinType::ObjCClass:
1944 case BuiltinType::ObjCSel:
Fangrui Song6907ce22018-07-30 19:24:48 +00001945 Width = Target->getPointerWidth(0);
Douglas Gregore8bbc122011-09-02 00:18:52 +00001946 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001947 break;
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001948 case BuiltinType::OCLSampler:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001949 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001950 case BuiltinType::OCLClkEvent:
1951 case BuiltinType::OCLQueue:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001952 case BuiltinType::OCLReserveID:
Yaxun Liu99444cb2016-08-03 20:38:06 +00001953#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1954 case BuiltinType::Id:
1955#include "clang/Basic/OpenCLImageTypes.def"
Andrew Savonichev3fee3512018-11-08 11:25:41 +00001956#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1957 case BuiltinType::Id:
1958#include "clang/Basic/OpenCLExtensionTypes.def"
Sven van Haastregt3bb7eaf2017-12-06 10:11:28 +00001959 AS = getTargetAddressSpace(
1960 Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T)));
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001961 Width = Target->getPointerWidth(AS);
1962 Align = Target->getPointerAlign(AS);
1963 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001964 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001965 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001966 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001967 Width = Target->getPointerWidth(0);
1968 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001969 break;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00001970 case Type::BlockPointer:
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001971 AS = getTargetAddressSpace(cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001972 Width = Target->getPointerWidth(AS);
1973 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001974 break;
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001975 case Type::LValueReference:
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00001976 case Type::RValueReference:
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001977 // alignof and sizeof should never enter this code path here, so we go
1978 // the pointer route.
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001979 AS = getTargetAddressSpace(cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001980 Width = Target->getPointerWidth(AS);
1981 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001982 break;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00001983 case Type::Pointer:
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001984 AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001985 Width = Target->getPointerWidth(AS);
1986 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001987 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001988 case Type::MemberPointer: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001989 const auto *MPT = cast<MemberPointerType>(T);
Erich Keane8a6b7402017-11-30 16:37:02 +00001990 CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT);
1991 Width = MPI.Width;
1992 Align = MPI.Align;
Anders Carlsson32440a02009-05-17 02:06:04 +00001993 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001994 }
Chris Lattner647fb222007-07-18 18:26:58 +00001995 case Type::Complex: {
1996 // Complex types have the same alignment as their elements, but twice the
1997 // size.
David Majnemer34b57492014-07-30 01:30:47 +00001998 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
1999 Width = EltInfo.Width * 2;
2000 Align = EltInfo.Align;
Chris Lattner647fb222007-07-18 18:26:58 +00002001 break;
2002 }
John McCall8b07ec22010-05-15 11:32:37 +00002003 case Type::ObjCObject:
2004 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Reid Kleckner0503a872013-12-05 01:23:43 +00002005 case Type::Adjusted:
Reid Kleckner8a365022013-06-24 17:51:48 +00002006 case Type::Decayed:
Reid Kleckner0503a872013-12-05 01:23:43 +00002007 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00002008 case Type::ObjCInterface: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002009 const auto *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00002010 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00002011 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00002012 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00002013 break;
2014 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002015 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002016 case Type::Enum: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002017 const auto *TT = cast<TagType>(T);
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00002018
2019 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00002020 Width = 8;
2021 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00002022 break;
2023 }
Mike Stump11289f42009-09-09 15:08:12 +00002024
Eugene Zelenko7855e772018-04-03 00:11:50 +00002025 if (const auto *ET = dyn_cast<EnumType>(TT)) {
David Majnemer475b25e2015-01-21 10:54:38 +00002026 const EnumDecl *ED = ET->getDecl();
2027 TypeInfo Info =
2028 getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType());
2029 if (unsigned AttrAlign = ED->getMaxAlignment()) {
2030 Info.Align = AttrAlign;
2031 Info.AlignIsRequired = true;
2032 }
2033 return Info;
2034 }
Chris Lattner8b23c252008-04-06 22:05:18 +00002035
Eugene Zelenko7855e772018-04-03 00:11:50 +00002036 const auto *RT = cast<RecordType>(TT);
David Majnemer5821ff72015-02-03 08:49:29 +00002037 const RecordDecl *RD = RT->getDecl();
2038 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
Ken Dyckb0fcc592011-02-11 01:54:29 +00002039 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00002040 Align = toBits(Layout.getAlignment());
David Majnemer5821ff72015-02-03 08:49:29 +00002041 AlignIsRequired = RD->hasAttr<AlignedAttr>();
Chris Lattner49a953a2007-07-23 22:46:22 +00002042 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00002043 }
Douglas Gregordc572a32009-03-30 22:58:21 +00002044
Chris Lattner63d2b362009-10-22 05:17:15 +00002045 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00002046 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
2047 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00002048
Richard Smith600b5262017-01-26 20:40:47 +00002049 case Type::Auto:
2050 case Type::DeducedTemplateSpecialization: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002051 const auto *A = cast<DeducedType>(T);
Richard Smith27d807c2013-04-30 13:56:41 +00002052 assert(!A->getDeducedType().isNull() &&
2053 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00002054 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00002055 }
2056
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002057 case Type::Paren:
2058 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
2059
Manman Rene6be26c2016-09-13 17:25:08 +00002060 case Type::ObjCTypeParam:
2061 return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr());
2062
Douglas Gregoref462e62009-04-30 17:32:17 +00002063 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00002064 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
David Majnemer34b57492014-07-30 01:30:47 +00002065 TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00002066 // If the typedef has an aligned attribute on it, it overrides any computed
2067 // alignment we have. This violates the GCC documentation (which says that
2068 // attribute(aligned) can only round up) but matches its implementation.
David Majnemer34b57492014-07-30 01:30:47 +00002069 if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
Chris Lattner29eb47b2011-02-19 22:55:41 +00002070 Align = AttrAlign;
David Majnemer34b57492014-07-30 01:30:47 +00002071 AlignIsRequired = true;
David Majnemer37bffb62014-08-04 05:11:01 +00002072 } else {
David Majnemer34b57492014-07-30 01:30:47 +00002073 Align = Info.Align;
David Majnemer37bffb62014-08-04 05:11:01 +00002074 AlignIsRequired = Info.AlignIsRequired;
2075 }
David Majnemer34b57492014-07-30 01:30:47 +00002076 Width = Info.Width;
Douglas Gregordc572a32009-03-30 22:58:21 +00002077 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00002078 }
Douglas Gregoref462e62009-04-30 17:32:17 +00002079
Abramo Bagnara6150c882010-05-11 21:36:43 +00002080 case Type::Elaborated:
2081 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00002082
John McCall81904512011-01-06 01:58:22 +00002083 case Type::Attributed:
2084 return getTypeInfo(
2085 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
2086
Eli Friedman0dfb8892011-10-06 23:00:33 +00002087 case Type::Atomic: {
John McCalla8ec7eb2013-03-07 21:37:17 +00002088 // Start with the base type information.
David Majnemer34b57492014-07-30 01:30:47 +00002089 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
2090 Width = Info.Width;
2091 Align = Info.Align;
John McCalla8ec7eb2013-03-07 21:37:17 +00002092
JF Bastien801fca22018-05-09 03:51:12 +00002093 if (!Width) {
2094 // An otherwise zero-sized type should still generate an
2095 // atomic operation.
2096 Width = Target->getCharWidth();
2097 assert(Align);
2098 } else if (Width <= Target->getMaxAtomicPromoteWidth()) {
2099 // If the size of the type doesn't exceed the platform's max
2100 // atomic promotion width, make the size and alignment more
2101 // favorable to atomic operations:
2102
John McCalla8ec7eb2013-03-07 21:37:17 +00002103 // Round the size up to a power of 2.
2104 if (!llvm::isPowerOf2_64(Width))
2105 Width = llvm::NextPowerOf2(Width);
2106
2107 // Set the alignment equal to the size.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00002108 Align = static_cast<unsigned>(Width);
2109 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00002110 }
Xiuli Pan9c14e282016-01-09 12:53:17 +00002111 break;
2112
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002113 case Type::Pipe:
Anastasia Stulovab3398932017-06-05 11:27:03 +00002114 Width = Target->getPointerWidth(getTargetAddressSpace(LangAS::opencl_global));
2115 Align = Target->getPointerAlign(getTargetAddressSpace(LangAS::opencl_global));
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002116 break;
Douglas Gregoref462e62009-04-30 17:32:17 +00002117 }
Mike Stump11289f42009-09-09 15:08:12 +00002118
Eli Friedman4b72fdd2011-10-14 20:59:01 +00002119 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
David Majnemer34b57492014-07-30 01:30:47 +00002120 return TypeInfo(Width, Align, AlignIsRequired);
Chris Lattner983a8bb2007-07-13 22:13:22 +00002121}
2122
Momchil Velikov20208cc2018-07-30 17:48:23 +00002123unsigned ASTContext::getTypeUnadjustedAlign(const Type *T) const {
2124 UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(T);
2125 if (I != MemoizedUnadjustedAlign.end())
2126 return I->second;
2127
2128 unsigned UnadjustedAlign;
2129 if (const auto *RT = T->getAs<RecordType>()) {
2130 const RecordDecl *RD = RT->getDecl();
2131 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2132 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2133 } else if (const auto *ObjCI = T->getAs<ObjCInterfaceType>()) {
2134 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2135 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2136 } else {
2137 UnadjustedAlign = getTypeAlign(T);
2138 }
2139
2140 MemoizedUnadjustedAlign[T] = UnadjustedAlign;
2141 return UnadjustedAlign;
2142}
2143
Alexey Bataev00396512015-07-02 03:40:19 +00002144unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
2145 unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign();
2146 // Target ppc64 with QPX: simd default alignment for pointer to double is 32.
2147 if ((getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64 ||
2148 getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64le) &&
2149 getTargetInfo().getABI() == "elfv1-qpx" &&
2150 T->isSpecificBuiltinType(BuiltinType::Double))
2151 SimdAlign = 256;
2152 return SimdAlign;
2153}
2154
Ken Dyckcc56c542011-01-15 18:38:59 +00002155/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
2156CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
2157 return CharUnits::fromQuantity(BitSize / getCharWidth());
2158}
2159
Ken Dyckb0fcc592011-02-11 01:54:29 +00002160/// toBits - Convert a size in characters to a size in characters.
2161int64_t ASTContext::toBits(CharUnits CharSize) const {
2162 return CharSize.getQuantity() * getCharWidth();
2163}
2164
Ken Dyck8c89d592009-12-22 14:23:30 +00002165/// getTypeSizeInChars - Return the size of the specified type, in characters.
2166/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00002167CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00002168 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00002169}
Jay Foad39c79802011-01-12 09:06:06 +00002170CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00002171 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00002172}
2173
Fangrui Song6907ce22018-07-30 19:24:48 +00002174/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00002175/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00002176CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00002177 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00002178}
Jay Foad39c79802011-01-12 09:06:06 +00002179CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00002180 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00002181}
2182
Momchil Velikov20208cc2018-07-30 17:48:23 +00002183/// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a
2184/// type, in characters, before alignment adustments. This method does
2185/// not work on incomplete types.
2186CharUnits ASTContext::getTypeUnadjustedAlignInChars(QualType T) const {
2187 return toCharUnitsFromBits(getTypeUnadjustedAlign(T));
2188}
2189CharUnits ASTContext::getTypeUnadjustedAlignInChars(const Type *T) const {
2190 return toCharUnitsFromBits(getTypeUnadjustedAlign(T));
2191}
2192
Chris Lattnera3402cd2009-01-27 18:08:34 +00002193/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
2194/// type for the current target in bits. This can be different than the ABI
2195/// alignment in cases where it is beneficial for performance to overalign
2196/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00002197unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
David Majnemer34b57492014-07-30 01:30:47 +00002198 TypeInfo TI = getTypeInfo(T);
2199 unsigned ABIAlign = TI.Align;
Eli Friedman7ab09572009-05-25 21:27:19 +00002200
David Majnemere1544562015-04-24 01:25:05 +00002201 T = T->getBaseElementTypeUnsafe();
2202
2203 // The preferred alignment of member pointers is that of a pointer.
2204 if (T->isMemberPointerType())
2205 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
2206
Andrey Turetskiydb6655f2016-02-10 11:58:46 +00002207 if (!Target->allowsLargerPreferedTypeAlignment())
2208 return ABIAlign;
Robert Lyttoneaf6f362013-11-12 10:09:34 +00002209
Eli Friedman7ab09572009-05-25 21:27:19 +00002210 // Double and long long should be naturally aligned if possible.
Eugene Zelenko7855e772018-04-03 00:11:50 +00002211 if (const auto *CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00002212 T = CT->getElementType().getTypePtr();
Eugene Zelenko7855e772018-04-03 00:11:50 +00002213 if (const auto *ET = T->getAs<EnumType>())
David Majnemer475b25e2015-01-21 10:54:38 +00002214 T = ET->getDecl()->getIntegerType().getTypePtr();
Eli Friedman7ab09572009-05-25 21:27:19 +00002215 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00002216 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
2217 T->isSpecificBuiltinType(BuiltinType::ULongLong))
David Majnemer8b6bd572014-02-24 23:34:17 +00002218 // Don't increase the alignment if an alignment attribute was specified on a
2219 // typedef declaration.
David Majnemer34b57492014-07-30 01:30:47 +00002220 if (!TI.AlignIsRequired)
David Majnemer8b6bd572014-02-24 23:34:17 +00002221 return std::max(ABIAlign, (unsigned)getTypeSize(T));
Eli Friedman7ab09572009-05-25 21:27:19 +00002222
Chris Lattnera3402cd2009-01-27 18:08:34 +00002223 return ABIAlign;
2224}
2225
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00002226/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2227/// for __attribute__((aligned)) on this target, to be used if no alignment
2228/// value is specified.
Eugene Zelenkod4304d22015-11-04 21:37:17 +00002229unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const {
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00002230 return getTargetInfo().getDefaultAlignForAttributeAligned();
2231}
2232
Ulrich Weigandfa806422013-05-06 16:23:57 +00002233/// getAlignOfGlobalVar - Return the alignment in bits that should be given
2234/// to a global variable of the specified type.
2235unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
2236 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
2237}
2238
2239/// getAlignOfGlobalVarInChars - Return the alignment in characters that
2240/// should be given to a global variable of the specified type.
2241CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
2242 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
2243}
2244
David Majnemer08ef2ba2015-06-23 20:34:18 +00002245CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
2246 CharUnits Offset = CharUnits::Zero();
2247 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
2248 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2249 Offset += Layout->getBaseClassOffset(Base);
2250 Layout = &getASTRecordLayout(Base);
2251 }
2252 return Offset;
2253}
2254
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002255/// DeepCollectObjCIvars -
2256/// This routine first collects all declared, but not synthesized, ivars in
2257/// super class and then collects all ivars, including those synthesized for
2258/// current class. This routine is used for implementation of current class
2259/// when all ivars, declared and synthesized are known.
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002260void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
2261 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00002262 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002263 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2264 DeepCollectObjCIvars(SuperClass, false, Ivars);
2265 if (!leafClass) {
Aaron Ballman59abbd42014-03-13 21:09:43 +00002266 for (const auto *I : OI->ivars())
2267 Ivars.push_back(I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00002268 } else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002269 auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Fangrui Song6907ce22018-07-30 19:24:48 +00002270 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00002271 Iv= Iv->getNextIvar())
2272 Ivars.push_back(Iv);
2273 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00002274}
2275
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002276/// CollectInheritedProtocols - Collect all protocols in current class and
2277/// those inherited by it.
2278void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00002279 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002280 if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00002281 // We can use protocol_iterator here instead of
Fangrui Song6907ce22018-07-30 19:24:48 +00002282 // all_referenced_protocol_iterator since we are walking all categories.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002283 for (auto *Proto : OI->all_referenced_protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002284 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00002285 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002286
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002287 // Categories of this Interface.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00002288 for (const auto *Cat : OI->visible_categories())
2289 CollectInheritedProtocols(Cat, Protocols);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002290
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002291 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2292 while (SD) {
2293 CollectInheritedProtocols(SD, Protocols);
2294 SD = SD->getSuperClass();
2295 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00002296 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00002297 for (auto *Proto : OC->protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002298 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002299 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00002300 } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002301 // Insert the protocol.
2302 if (!Protocols.insert(
2303 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2304 return;
2305
2306 for (auto *Proto : OP->protocols())
2307 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002308 }
2309}
2310
Erich Keane8a6b7402017-11-30 16:37:02 +00002311static bool unionHasUniqueObjectRepresentations(const ASTContext &Context,
2312 const RecordDecl *RD) {
2313 assert(RD->isUnion() && "Must be union type");
2314 CharUnits UnionSize = Context.getTypeSizeInChars(RD->getTypeForDecl());
2315
2316 for (const auto *Field : RD->fields()) {
2317 if (!Context.hasUniqueObjectRepresentations(Field->getType()))
2318 return false;
2319 CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType());
2320 if (FieldSize != UnionSize)
2321 return false;
2322 }
Eric Fiselier12a9f342018-02-02 20:30:39 +00002323 return !RD->field_empty();
Erich Keane8a6b7402017-11-30 16:37:02 +00002324}
2325
Benjamin Kramer802e6252017-12-24 12:46:22 +00002326static bool isStructEmpty(QualType Ty) {
Erich Keane8a6b7402017-11-30 16:37:02 +00002327 const RecordDecl *RD = Ty->castAs<RecordType>()->getDecl();
2328
2329 if (!RD->field_empty())
2330 return false;
2331
2332 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD))
2333 return ClassDecl->isEmpty();
2334
2335 return true;
2336}
2337
2338static llvm::Optional<int64_t>
2339structHasUniqueObjectRepresentations(const ASTContext &Context,
2340 const RecordDecl *RD) {
2341 assert(!RD->isUnion() && "Must be struct/class type");
2342 const auto &Layout = Context.getASTRecordLayout(RD);
2343
2344 int64_t CurOffsetInBits = 0;
2345 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) {
2346 if (ClassDecl->isDynamicClass())
2347 return llvm::None;
2348
2349 SmallVector<std::pair<QualType, int64_t>, 4> Bases;
2350 for (const auto Base : ClassDecl->bases()) {
2351 // Empty types can be inherited from, and non-empty types can potentially
2352 // have tail padding, so just make sure there isn't an error.
2353 if (!isStructEmpty(Base.getType())) {
2354 llvm::Optional<int64_t> Size = structHasUniqueObjectRepresentations(
2355 Context, Base.getType()->getAs<RecordType>()->getDecl());
2356 if (!Size)
2357 return llvm::None;
2358 Bases.emplace_back(Base.getType(), Size.getValue());
2359 }
2360 }
2361
Fangrui Song1d38c132018-09-30 21:41:11 +00002362 llvm::sort(Bases, [&](const std::pair<QualType, int64_t> &L,
2363 const std::pair<QualType, int64_t> &R) {
2364 return Layout.getBaseClassOffset(L.first->getAsCXXRecordDecl()) <
2365 Layout.getBaseClassOffset(R.first->getAsCXXRecordDecl());
2366 });
Erich Keane8a6b7402017-11-30 16:37:02 +00002367
2368 for (const auto Base : Bases) {
2369 int64_t BaseOffset = Context.toBits(
2370 Layout.getBaseClassOffset(Base.first->getAsCXXRecordDecl()));
2371 int64_t BaseSize = Base.second;
2372 if (BaseOffset != CurOffsetInBits)
2373 return llvm::None;
2374 CurOffsetInBits = BaseOffset + BaseSize;
2375 }
2376 }
2377
2378 for (const auto *Field : RD->fields()) {
2379 if (!Field->getType()->isReferenceType() &&
2380 !Context.hasUniqueObjectRepresentations(Field->getType()))
2381 return llvm::None;
2382
2383 int64_t FieldSizeInBits =
2384 Context.toBits(Context.getTypeSizeInChars(Field->getType()));
2385 if (Field->isBitField()) {
2386 int64_t BitfieldSize = Field->getBitWidthValue(Context);
2387
2388 if (BitfieldSize > FieldSizeInBits)
2389 return llvm::None;
2390 FieldSizeInBits = BitfieldSize;
2391 }
2392
2393 int64_t FieldOffsetInBits = Context.getFieldOffset(Field);
2394
2395 if (FieldOffsetInBits != CurOffsetInBits)
2396 return llvm::None;
2397
2398 CurOffsetInBits = FieldSizeInBits + FieldOffsetInBits;
2399 }
2400
2401 return CurOffsetInBits;
2402}
2403
2404bool ASTContext::hasUniqueObjectRepresentations(QualType Ty) const {
2405 // C++17 [meta.unary.prop]:
2406 // The predicate condition for a template specialization
2407 // has_unique_object_representations<T> shall be
2408 // satisfied if and only if:
2409 // (9.1) - T is trivially copyable, and
2410 // (9.2) - any two objects of type T with the same value have the same
2411 // object representation, where two objects
2412 // of array or non-union class type are considered to have the same value
2413 // if their respective sequences of
2414 // direct subobjects have the same values, and two objects of union type
2415 // are considered to have the same
2416 // value if they have the same active member and the corresponding members
2417 // have the same value.
2418 // The set of scalar types for which this condition holds is
2419 // implementation-defined. [ Note: If a type has padding
2420 // bits, the condition does not hold; otherwise, the condition holds true
2421 // for unsigned integral types. -- end note ]
2422 assert(!Ty.isNull() && "Null QualType sent to unique object rep check");
2423
2424 // Arrays are unique only if their element type is unique.
2425 if (Ty->isArrayType())
2426 return hasUniqueObjectRepresentations(getBaseElementType(Ty));
2427
2428 // (9.1) - T is trivially copyable...
2429 if (!Ty.isTriviallyCopyableType(*this))
2430 return false;
2431
2432 // All integrals and enums are unique.
2433 if (Ty->isIntegralOrEnumerationType())
2434 return true;
2435
2436 // All other pointers are unique.
2437 if (Ty->isPointerType())
2438 return true;
2439
2440 if (Ty->isMemberPointerType()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002441 const auto *MPT = Ty->getAs<MemberPointerType>();
Erich Keane8a6b7402017-11-30 16:37:02 +00002442 return !ABI->getMemberPointerInfo(MPT).HasPadding;
2443 }
2444
2445 if (Ty->isRecordType()) {
2446 const RecordDecl *Record = Ty->getAs<RecordType>()->getDecl();
2447
Erich Keanebd2197c2017-12-12 16:02:06 +00002448 if (Record->isInvalidDecl())
2449 return false;
2450
Erich Keane8a6b7402017-11-30 16:37:02 +00002451 if (Record->isUnion())
2452 return unionHasUniqueObjectRepresentations(*this, Record);
2453
2454 Optional<int64_t> StructSize =
2455 structHasUniqueObjectRepresentations(*this, Record);
2456
2457 return StructSize &&
2458 StructSize.getValue() == static_cast<int64_t>(getTypeSize(Ty));
2459 }
2460
2461 // FIXME: More cases to handle here (list by rsmith):
2462 // vectors (careful about, eg, vector of 3 foo)
2463 // _Complex int and friends
2464 // _Atomic T
2465 // Obj-C block pointers
2466 // Obj-C object pointers
2467 // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t,
2468 // clk_event_t, queue_t, reserve_id_t)
2469 // There're also Obj-C class types and the Obj-C selector type, but I think it
2470 // makes sense for those to return false here.
2471
2472 return false;
2473}
2474
Jay Foad39c79802011-01-12 09:06:06 +00002475unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00002476 unsigned count = 0;
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00002477 // Count ivars declared in class extension.
Aaron Ballmanb4a53452014-03-13 21:57:01 +00002478 for (const auto *Ext : OI->known_extensions())
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002479 count += Ext->ivar_size();
Fangrui Song6907ce22018-07-30 19:24:48 +00002480
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00002481 // Count ivar defined in this class's implementation. This
2482 // includes synthesized ivars.
2483 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00002484 count += ImplDecl->ivar_size();
2485
Fariborz Jahanian7c809592009-06-04 01:19:09 +00002486 return count;
2487}
2488
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00002489bool ASTContext::isSentinelNullExpr(const Expr *E) {
2490 if (!E)
2491 return false;
2492
2493 // nullptr_t is always treated as null.
2494 if (E->getType()->isNullPtrType()) return true;
2495
2496 if (E->getType()->isAnyPointerType() &&
2497 E->IgnoreParenCasts()->isNullPointerConstant(*this,
2498 Expr::NPC_ValueDependentIsNull))
2499 return true;
2500
2501 // Unfortunately, __null has type 'int'.
2502 if (isa<GNUNullExpr>(E)) return true;
2503
2504 return false;
2505}
2506
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002507/// Get the implementation of ObjCInterfaceDecl, or nullptr if none
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002508/// exists.
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002509ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
2510 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2511 I = ObjCImpls.find(D);
2512 if (I != ObjCImpls.end())
2513 return cast<ObjCImplementationDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002514 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002515}
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002516
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002517/// Get the implementation of ObjCCategoryDecl, or nullptr if none
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002518/// exists.
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002519ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
2520 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2521 I = ObjCImpls.find(D);
2522 if (I != ObjCImpls.end())
2523 return cast<ObjCCategoryImplDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002524 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002525}
2526
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002527/// Set the implementation of ObjCInterfaceDecl.
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002528void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2529 ObjCImplementationDecl *ImplD) {
2530 assert(IFaceD && ImplD && "Passed null params");
2531 ObjCImpls[IFaceD] = ImplD;
2532}
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002533
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002534/// Set the implementation of ObjCCategoryDecl.
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002535void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
2536 ObjCCategoryImplDecl *ImplD) {
2537 assert(CatD && ImplD && "Passed null params");
2538 ObjCImpls[CatD] = ImplD;
2539}
2540
Chandler Carruth21c90602015-12-30 03:24:14 +00002541const ObjCMethodDecl *
2542ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const {
2543 return ObjCMethodRedecls.lookup(MD);
2544}
2545
2546void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
2547 const ObjCMethodDecl *Redecl) {
2548 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
2549 ObjCMethodRedecls[MD] = Redecl;
2550}
2551
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002552const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
2553 const NamedDecl *ND) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002554 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002555 return ID;
Eugene Zelenko7855e772018-04-03 00:11:50 +00002556 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002557 return CD->getClassInterface();
Eugene Zelenko7855e772018-04-03 00:11:50 +00002558 if (const auto *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002559 return IMD->getClassInterface();
2560
Craig Topper36250ad2014-05-12 05:36:57 +00002561 return nullptr;
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002562}
2563
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002564/// Get the copy initialization expression of VarDecl, or nullptr if
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002565/// none exists.
Akira Hatanaka9978da32018-08-10 15:09:24 +00002566ASTContext::BlockVarCopyInit
2567ASTContext::getBlockVarCopyInit(const VarDecl*VD) const {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002568 assert(VD && "Passed null params");
Fangrui Song6907ce22018-07-30 19:24:48 +00002569 assert(VD->hasAttr<BlocksAttr>() &&
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002570 "getBlockVarCopyInits - not __block var");
Akira Hatanaka9978da32018-08-10 15:09:24 +00002571 auto I = BlockVarCopyInits.find(VD);
2572 if (I != BlockVarCopyInits.end())
2573 return I->second;
2574 return {nullptr, false};
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002575}
2576
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002577/// Set the copy inialization expression of a block var decl.
Akira Hatanaka9978da32018-08-10 15:09:24 +00002578void ASTContext::setBlockVarCopyInit(const VarDecl*VD, Expr *CopyExpr,
2579 bool CanThrow) {
2580 assert(VD && CopyExpr && "Passed null params");
Fangrui Song6907ce22018-07-30 19:24:48 +00002581 assert(VD->hasAttr<BlocksAttr>() &&
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002582 "setBlockVarCopyInits - not __block var");
Akira Hatanaka9978da32018-08-10 15:09:24 +00002583 BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002584}
2585
John McCallbcd03502009-12-07 02:54:59 +00002586TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002587 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00002588 if (!DataSize)
2589 DataSize = TypeLoc::getFullDataSizeForType(T);
2590 else
2591 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00002592 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00002593
Eugene Zelenko7855e772018-04-03 00:11:50 +00002594 auto *TInfo =
John McCallbcd03502009-12-07 02:54:59 +00002595 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
2596 new (TInfo) TypeSourceInfo(T);
2597 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00002598}
2599
John McCallbcd03502009-12-07 02:54:59 +00002600TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002601 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00002602 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00002603 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00002604 return DI;
2605}
2606
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002607const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002608ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Craig Topper36250ad2014-05-12 05:36:57 +00002609 return getObjCLayout(D, nullptr);
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002610}
2611
2612const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002613ASTContext::getASTObjCImplementationLayout(
2614 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002615 return getObjCLayout(D->getClassInterface(), D);
2616}
2617
Chris Lattner983a8bb2007-07-13 22:13:22 +00002618//===----------------------------------------------------------------------===//
2619// Type creation/memoization methods
2620//===----------------------------------------------------------------------===//
2621
Jay Foad39c79802011-01-12 09:06:06 +00002622QualType
John McCall33ddac02011-01-19 10:06:00 +00002623ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2624 unsigned fastQuals = quals.getFastQualifiers();
2625 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00002626
2627 // Check if we've already instantiated this type.
2628 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002629 ExtQuals::Profile(ID, baseType, quals);
Craig Topper36250ad2014-05-12 05:36:57 +00002630 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002631 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2632 assert(eq->getQualifiers() == quals);
2633 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002634 }
2635
John McCall33ddac02011-01-19 10:06:00 +00002636 // If the base type is not canonical, make the appropriate canonical type.
2637 QualType canon;
2638 if (!baseType->isCanonicalUnqualified()) {
2639 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00002640 canonSplit.Quals.addConsistentQualifiers(quals);
2641 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002642
2643 // Re-find the insert position.
2644 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2645 }
2646
Eugene Zelenko7855e772018-04-03 00:11:50 +00002647 auto *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
John McCall33ddac02011-01-19 10:06:00 +00002648 ExtQualNodes.InsertNode(eq, insertPos);
2649 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002650}
2651
Alexander Richardson6d989432017-10-15 18:48:14 +00002652QualType ASTContext::getAddrSpaceQualType(QualType T,
2653 LangAS AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002654 QualType CanT = getCanonicalType(T);
2655 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00002656 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00002657
John McCall8ccfcb52009-09-24 19:53:00 +00002658 // If we are composing extended qualifiers together, merge together
2659 // into one ExtQuals node.
2660 QualifierCollector Quals;
2661 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002662
John McCall8ccfcb52009-09-24 19:53:00 +00002663 // If this type already has an address space specified, it cannot get
2664 // another one.
2665 assert(!Quals.hasAddressSpace() &&
2666 "Type cannot be in multiple addr spaces!");
2667 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00002668
John McCall8ccfcb52009-09-24 19:53:00 +00002669 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00002670}
2671
Andrew Gozillon572bbb02017-10-02 06:25:51 +00002672QualType ASTContext::removeAddrSpaceQualType(QualType T) const {
2673 // If we are composing extended qualifiers together, merge together
2674 // into one ExtQuals node.
2675 QualifierCollector Quals;
2676 const Type *TypeNode = Quals.strip(T);
2677
2678 // If the qualifier doesn't have an address space just return it.
2679 if (!Quals.hasAddressSpace())
2680 return T;
2681
2682 Quals.removeAddressSpace();
2683
2684 // Removal of the address space can mean there are no longer any
2685 // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts)
2686 // or required.
2687 if (Quals.hasNonFastQualifiers())
2688 return getExtQualType(TypeNode, Quals);
2689 else
2690 return QualType(TypeNode, Quals.getFastQualifiers());
2691}
2692
Chris Lattnerd60183d2009-02-18 22:53:11 +00002693QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002694 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002695 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00002696 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002697 return T;
Mike Stump11289f42009-09-09 15:08:12 +00002698
Eugene Zelenko7855e772018-04-03 00:11:50 +00002699 if (const auto *ptr = T->getAs<PointerType>()) {
John McCall53fa7142010-12-24 02:08:15 +00002700 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00002701 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00002702 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2703 return getPointerType(ResultType);
2704 }
2705 }
Mike Stump11289f42009-09-09 15:08:12 +00002706
John McCall8ccfcb52009-09-24 19:53:00 +00002707 // If we are composing extended qualifiers together, merge together
2708 // into one ExtQuals node.
2709 QualifierCollector Quals;
2710 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002711
John McCall8ccfcb52009-09-24 19:53:00 +00002712 // If this type already has an ObjCGC specified, it cannot get
2713 // another one.
2714 assert(!Quals.hasObjCGCAttr() &&
2715 "Type cannot have multiple ObjCGCs!");
2716 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00002717
John McCall8ccfcb52009-09-24 19:53:00 +00002718 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002719}
Chris Lattner983a8bb2007-07-13 22:13:22 +00002720
John McCall4f5019e2010-12-19 02:44:49 +00002721const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2722 FunctionType::ExtInfo Info) {
2723 if (T->getExtInfo() == Info)
2724 return T;
2725
2726 QualType Result;
Eugene Zelenko7855e772018-04-03 00:11:50 +00002727 if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
Alp Toker314cc812014-01-25 16:55:45 +00002728 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
John McCall4f5019e2010-12-19 02:44:49 +00002729 } else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002730 const auto *FPT = cast<FunctionProtoType>(T);
John McCall4f5019e2010-12-19 02:44:49 +00002731 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2732 EPI.ExtInfo = Info;
Alp Toker314cc812014-01-25 16:55:45 +00002733 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
John McCall4f5019e2010-12-19 02:44:49 +00002734 }
2735
2736 return cast<FunctionType>(Result.getTypePtr());
2737}
2738
Richard Smith2a7d4812013-05-04 07:00:32 +00002739void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2740 QualType ResultType) {
Richard Smith1fa5d642013-05-11 05:45:24 +00002741 FD = FD->getMostRecentDecl();
2742 while (true) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002743 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
Richard Smith2a7d4812013-05-04 07:00:32 +00002744 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Alp Toker9cacbab2014-01-20 20:26:09 +00002745 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
Richard Smith1fa5d642013-05-11 05:45:24 +00002746 if (FunctionDecl *Next = FD->getPreviousDecl())
2747 FD = Next;
2748 else
2749 break;
Richard Smith2a7d4812013-05-04 07:00:32 +00002750 }
Richard Smith1fa5d642013-05-11 05:45:24 +00002751 if (ASTMutationListener *L = getASTMutationListener())
2752 L->DeducedReturnType(FD, ResultType);
Richard Smith2a7d4812013-05-04 07:00:32 +00002753}
2754
Richard Smith0b3a4622014-11-13 20:01:57 +00002755/// Get a function type and produce the equivalent function type with the
2756/// specified exception specification. Type sugar that can be present on a
2757/// declaration of a function with an exception specification is permitted
2758/// and preserved. Other type sugar (for instance, typedefs) is not.
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002759QualType ASTContext::getFunctionTypeWithExceptionSpec(
2760 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) {
Richard Smith0b3a4622014-11-13 20:01:57 +00002761 // Might have some parens.
Eugene Zelenko7855e772018-04-03 00:11:50 +00002762 if (const auto *PT = dyn_cast<ParenType>(Orig))
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002763 return getParenType(
2764 getFunctionTypeWithExceptionSpec(PT->getInnerType(), ESI));
Richard Smith0b3a4622014-11-13 20:01:57 +00002765
2766 // Might have a calling-convention attribute.
Eugene Zelenko7855e772018-04-03 00:11:50 +00002767 if (const auto *AT = dyn_cast<AttributedType>(Orig))
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002768 return getAttributedType(
Richard Smith0b3a4622014-11-13 20:01:57 +00002769 AT->getAttrKind(),
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002770 getFunctionTypeWithExceptionSpec(AT->getModifiedType(), ESI),
2771 getFunctionTypeWithExceptionSpec(AT->getEquivalentType(), ESI));
Richard Smith0b3a4622014-11-13 20:01:57 +00002772
2773 // Anything else must be a function type. Rebuild it with the new exception
2774 // specification.
Eugene Zelenko7855e772018-04-03 00:11:50 +00002775 const auto *Proto = cast<FunctionProtoType>(Orig);
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002776 return getFunctionType(
Richard Smith0b3a4622014-11-13 20:01:57 +00002777 Proto->getReturnType(), Proto->getParamTypes(),
2778 Proto->getExtProtoInfo().withExceptionSpec(ESI));
2779}
2780
Richard Smithdfe85e22016-12-15 02:35:39 +00002781bool ASTContext::hasSameFunctionTypeIgnoringExceptionSpec(QualType T,
2782 QualType U) {
2783 return hasSameType(T, U) ||
Aaron Ballmanc351fba2017-12-04 20:27:34 +00002784 (getLangOpts().CPlusPlus17 &&
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002785 hasSameType(getFunctionTypeWithExceptionSpec(T, EST_None),
2786 getFunctionTypeWithExceptionSpec(U, EST_None)));
Richard Smithdfe85e22016-12-15 02:35:39 +00002787}
2788
Richard Smith0b3a4622014-11-13 20:01:57 +00002789void ASTContext::adjustExceptionSpec(
2790 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
2791 bool AsWritten) {
2792 // Update the type.
2793 QualType Updated =
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002794 getFunctionTypeWithExceptionSpec(FD->getType(), ESI);
Richard Smith0b3a4622014-11-13 20:01:57 +00002795 FD->setType(Updated);
2796
2797 if (!AsWritten)
2798 return;
2799
2800 // Update the type in the type source information too.
2801 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
2802 // If the type and the type-as-written differ, we may need to update
2803 // the type-as-written too.
2804 if (TSInfo->getType() != FD->getType())
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002805 Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI);
Richard Smith0b3a4622014-11-13 20:01:57 +00002806
2807 // FIXME: When we get proper type location information for exceptions,
2808 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
2809 // up the TypeSourceInfo;
2810 assert(TypeLoc::getFullDataSizeForType(Updated) ==
2811 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
2812 "TypeLoc size mismatch from updating exception specification");
2813 TSInfo->overrideType(Updated);
2814 }
2815}
2816
Chris Lattnerc6395932007-06-22 20:56:16 +00002817/// getComplexType - Return the uniqued reference to the type for a complex
2818/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00002819QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00002820 // Unique pointers, to guarantee there is only one pointer of a particular
2821 // structure.
2822 llvm::FoldingSetNodeID ID;
2823 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002824
Craig Topper36250ad2014-05-12 05:36:57 +00002825 void *InsertPos = nullptr;
Chris Lattnerc6395932007-06-22 20:56:16 +00002826 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2827 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002828
Chris Lattnerc6395932007-06-22 20:56:16 +00002829 // If the pointee type isn't canonical, this won't be a canonical type either,
2830 // so fill in the canonical type field.
2831 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002832 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002833 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002834
Chris Lattnerc6395932007-06-22 20:56:16 +00002835 // Get the new insert position for the node we care about.
2836 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002837 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00002838 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00002839 auto *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00002840 Types.push_back(New);
2841 ComplexTypes.InsertNode(New, InsertPos);
2842 return QualType(New, 0);
2843}
2844
Chris Lattner970e54e2006-11-12 00:37:36 +00002845/// getPointerType - Return the uniqued reference to the type for a pointer to
2846/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002847QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00002848 // Unique pointers, to guarantee there is only one pointer of a particular
2849 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002850 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00002851 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002852
Craig Topper36250ad2014-05-12 05:36:57 +00002853 void *InsertPos = nullptr;
Chris Lattner67521df2007-01-27 01:29:36 +00002854 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002855 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002856
Chris Lattner7ccecb92006-11-12 08:50:50 +00002857 // If the pointee type isn't canonical, this won't be a canonical type either,
2858 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002859 QualType Canonical;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002860 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002861 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002862
Bob Wilsonc8541f22013-03-15 17:12:43 +00002863 // Get the new insert position for the node we care about.
2864 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002865 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002866 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00002867 auto *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00002868 Types.push_back(New);
2869 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002870 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00002871}
2872
Reid Kleckner0503a872013-12-05 01:23:43 +00002873QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
2874 llvm::FoldingSetNodeID ID;
2875 AdjustedType::Profile(ID, Orig, New);
Craig Topper36250ad2014-05-12 05:36:57 +00002876 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002877 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2878 if (AT)
2879 return QualType(AT, 0);
2880
2881 QualType Canonical = getCanonicalType(New);
2882
2883 // Get the new insert position for the node we care about.
2884 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002885 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner0503a872013-12-05 01:23:43 +00002886
2887 AT = new (*this, TypeAlignment)
2888 AdjustedType(Type::Adjusted, Orig, New, Canonical);
2889 Types.push_back(AT);
2890 AdjustedTypes.InsertNode(AT, InsertPos);
2891 return QualType(AT, 0);
2892}
2893
Reid Kleckner8a365022013-06-24 17:51:48 +00002894QualType ASTContext::getDecayedType(QualType T) const {
2895 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2896
Reid Kleckner8a365022013-06-24 17:51:48 +00002897 QualType Decayed;
2898
2899 // C99 6.7.5.3p7:
2900 // A declaration of a parameter as "array of type" shall be
2901 // adjusted to "qualified pointer to type", where the type
2902 // qualifiers (if any) are those specified within the [ and ] of
2903 // the array type derivation.
2904 if (T->isArrayType())
2905 Decayed = getArrayDecayedType(T);
2906
2907 // C99 6.7.5.3p8:
2908 // A declaration of a parameter as "function returning type"
2909 // shall be adjusted to "pointer to function returning type", as
2910 // in 6.3.2.1.
2911 if (T->isFunctionType())
2912 Decayed = getPointerType(T);
2913
Reid Kleckner0503a872013-12-05 01:23:43 +00002914 llvm::FoldingSetNodeID ID;
2915 AdjustedType::Profile(ID, T, Decayed);
Craig Topper36250ad2014-05-12 05:36:57 +00002916 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002917 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2918 if (AT)
2919 return QualType(AT, 0);
2920
Reid Kleckner8a365022013-06-24 17:51:48 +00002921 QualType Canonical = getCanonicalType(Decayed);
2922
2923 // Get the new insert position for the node we care about.
Reid Kleckner0503a872013-12-05 01:23:43 +00002924 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002925 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner8a365022013-06-24 17:51:48 +00002926
Reid Kleckner0503a872013-12-05 01:23:43 +00002927 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2928 Types.push_back(AT);
2929 AdjustedTypes.InsertNode(AT, InsertPos);
2930 return QualType(AT, 0);
Reid Kleckner8a365022013-06-24 17:51:48 +00002931}
2932
Mike Stump11289f42009-09-09 15:08:12 +00002933/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00002934/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00002935QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00002936 assert(T->isFunctionType() && "block of function types only");
2937 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00002938 // structure.
2939 llvm::FoldingSetNodeID ID;
2940 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002941
Craig Topper36250ad2014-05-12 05:36:57 +00002942 void *InsertPos = nullptr;
Steve Naroffec33ed92008-08-27 16:04:49 +00002943 if (BlockPointerType *PT =
2944 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2945 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002946
2947 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00002948 // type either so fill in the canonical type field.
2949 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002950 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00002951 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002952
Steve Naroffec33ed92008-08-27 16:04:49 +00002953 // Get the new insert position for the node we care about.
2954 BlockPointerType *NewIP =
2955 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002956 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00002957 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00002958 auto *New = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00002959 Types.push_back(New);
2960 BlockPointerTypes.InsertNode(New, InsertPos);
2961 return QualType(New, 0);
2962}
2963
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002964/// getLValueReferenceType - Return the uniqued reference to the type for an
2965/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002966QualType
2967ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00002968 assert(getCanonicalType(T) != OverloadTy &&
Douglas Gregor291e8ee2011-05-21 22:16:50 +00002969 "Unresolved overloaded function type");
Fangrui Song6907ce22018-07-30 19:24:48 +00002970
Bill Wendling3708c182007-05-27 10:15:43 +00002971 // Unique pointers, to guarantee there is only one pointer of a particular
2972 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002973 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002974 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002975
Craig Topper36250ad2014-05-12 05:36:57 +00002976 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002977 if (LValueReferenceType *RT =
2978 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00002979 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002980
Eugene Zelenko7855e772018-04-03 00:11:50 +00002981 const auto *InnerRef = T->getAs<ReferenceType>();
John McCallfc93cf92009-10-22 22:37:11 +00002982
Bill Wendling3708c182007-05-27 10:15:43 +00002983 // If the referencee type isn't canonical, this won't be a canonical type
2984 // either, so fill in the canonical type field.
2985 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002986 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2987 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2988 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002989
Bill Wendling3708c182007-05-27 10:15:43 +00002990 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002991 LValueReferenceType *NewIP =
2992 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002993 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00002994 }
2995
Eugene Zelenko7855e772018-04-03 00:11:50 +00002996 auto *New = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2997 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002998 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002999 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00003000
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003001 return QualType(New, 0);
3002}
3003
3004/// getRValueReferenceType - Return the uniqued reference to the type for an
3005/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00003006QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003007 // Unique pointers, to guarantee there is only one pointer of a particular
3008 // structure.
3009 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00003010 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003011
Craig Topper36250ad2014-05-12 05:36:57 +00003012 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003013 if (RValueReferenceType *RT =
3014 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
3015 return QualType(RT, 0);
3016
Eugene Zelenko7855e772018-04-03 00:11:50 +00003017 const auto *InnerRef = T->getAs<ReferenceType>();
John McCallfc93cf92009-10-22 22:37:11 +00003018
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003019 // If the referencee type isn't canonical, this won't be a canonical type
3020 // either, so fill in the canonical type field.
3021 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00003022 if (InnerRef || !T.isCanonical()) {
3023 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
3024 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003025
3026 // Get the new insert position for the node we care about.
3027 RValueReferenceType *NewIP =
3028 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003029 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003030 }
3031
Eugene Zelenko7855e772018-04-03 00:11:50 +00003032 auto *New = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003033 Types.push_back(New);
3034 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00003035 return QualType(New, 0);
3036}
3037
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00003038/// getMemberPointerType - Return the uniqued reference to the type for a
3039/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00003040QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00003041 // Unique pointers, to guarantee there is only one pointer of a particular
3042 // structure.
3043 llvm::FoldingSetNodeID ID;
3044 MemberPointerType::Profile(ID, T, Cls);
3045
Craig Topper36250ad2014-05-12 05:36:57 +00003046 void *InsertPos = nullptr;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00003047 if (MemberPointerType *PT =
3048 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3049 return QualType(PT, 0);
3050
3051 // If the pointee or class type isn't canonical, this won't be a canonical
3052 // type either, so fill in the canonical type field.
3053 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00003054 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00003055 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
3056
3057 // Get the new insert position for the node we care about.
3058 MemberPointerType *NewIP =
3059 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003060 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00003061 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00003062 auto *New = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00003063 Types.push_back(New);
3064 MemberPointerTypes.InsertNode(New, InsertPos);
3065 return QualType(New, 0);
3066}
3067
Mike Stump11289f42009-09-09 15:08:12 +00003068/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00003069/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00003070QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00003071 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00003072 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00003073 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00003074 assert((EltTy->isDependentType() ||
3075 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00003076 "Constant array of VLAs is illegal!");
3077
Chris Lattnere2df3f92009-05-13 04:12:56 +00003078 // Convert the array size into a canonical width matching the pointer size for
3079 // the target.
3080 llvm::APInt ArySize(ArySizeIn);
Konstantin Zhuravlyov9c1e3102017-03-21 18:55:39 +00003081 ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth());
Mike Stump11289f42009-09-09 15:08:12 +00003082
Chris Lattner23b7eb62007-06-15 23:05:46 +00003083 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00003084 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00003085
Craig Topper36250ad2014-05-12 05:36:57 +00003086 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003087 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00003088 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003089 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003090
John McCall33ddac02011-01-19 10:06:00 +00003091 // If the element type isn't canonical or has qualifiers, this won't
3092 // be a canonical type either, so fill in the canonical type field.
3093 QualType Canon;
3094 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
3095 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00003096 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00003097 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00003098 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00003099
Chris Lattner36f8e652007-01-27 08:31:04 +00003100 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00003101 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00003102 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003103 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00003104 }
Mike Stump11289f42009-09-09 15:08:12 +00003105
Eugene Zelenko7855e772018-04-03 00:11:50 +00003106 auto *New = new (*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00003107 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00003108 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00003109 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003110 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00003111}
3112
John McCall06549462011-01-18 08:40:38 +00003113/// getVariableArrayDecayedType - Turns the given type, which may be
3114/// variably-modified, into the corresponding type with all the known
3115/// sizes replaced with [*].
3116QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
3117 // Vastly most common case.
3118 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003119
John McCall06549462011-01-18 08:40:38 +00003120 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003121
John McCall06549462011-01-18 08:40:38 +00003122 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00003123 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00003124 switch (ty->getTypeClass()) {
3125#define TYPE(Class, Base)
3126#define ABSTRACT_TYPE(Class, Base)
3127#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3128#include "clang/AST/TypeNodes.def"
3129 llvm_unreachable("didn't desugar past all non-canonical types?");
3130
3131 // These types should never be variably-modified.
3132 case Type::Builtin:
3133 case Type::Complex:
3134 case Type::Vector:
Erich Keanef702b022018-07-13 19:46:04 +00003135 case Type::DependentVector:
John McCall06549462011-01-18 08:40:38 +00003136 case Type::ExtVector:
3137 case Type::DependentSizedExtVector:
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003138 case Type::DependentAddressSpace:
John McCall06549462011-01-18 08:40:38 +00003139 case Type::ObjCObject:
3140 case Type::ObjCInterface:
3141 case Type::ObjCObjectPointer:
3142 case Type::Record:
3143 case Type::Enum:
3144 case Type::UnresolvedUsing:
3145 case Type::TypeOfExpr:
3146 case Type::TypeOf:
3147 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00003148 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00003149 case Type::DependentName:
3150 case Type::InjectedClassName:
3151 case Type::TemplateSpecialization:
3152 case Type::DependentTemplateSpecialization:
3153 case Type::TemplateTypeParm:
3154 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00003155 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00003156 case Type::DeducedTemplateSpecialization:
John McCall06549462011-01-18 08:40:38 +00003157 case Type::PackExpansion:
3158 llvm_unreachable("type should never be variably-modified");
3159
3160 // These types can be variably-modified but should never need to
3161 // further decay.
3162 case Type::FunctionNoProto:
3163 case Type::FunctionProto:
3164 case Type::BlockPointer:
3165 case Type::MemberPointer:
Xiuli Pan9c14e282016-01-09 12:53:17 +00003166 case Type::Pipe:
John McCall06549462011-01-18 08:40:38 +00003167 return type;
3168
3169 // These types can be variably-modified. All these modifications
3170 // preserve structure except as noted by comments.
3171 // TODO: if we ever care about optimizing VLAs, there are no-op
3172 // optimizations available here.
3173 case Type::Pointer:
3174 result = getPointerType(getVariableArrayDecayedType(
3175 cast<PointerType>(ty)->getPointeeType()));
3176 break;
3177
3178 case Type::LValueReference: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003179 const auto *lv = cast<LValueReferenceType>(ty);
John McCall06549462011-01-18 08:40:38 +00003180 result = getLValueReferenceType(
3181 getVariableArrayDecayedType(lv->getPointeeType()),
3182 lv->isSpelledAsLValue());
3183 break;
3184 }
3185
3186 case Type::RValueReference: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003187 const auto *lv = cast<RValueReferenceType>(ty);
John McCall06549462011-01-18 08:40:38 +00003188 result = getRValueReferenceType(
3189 getVariableArrayDecayedType(lv->getPointeeType()));
3190 break;
3191 }
3192
Eli Friedman0dfb8892011-10-06 23:00:33 +00003193 case Type::Atomic: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003194 const auto *at = cast<AtomicType>(ty);
Eli Friedman0dfb8892011-10-06 23:00:33 +00003195 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
3196 break;
3197 }
3198
John McCall06549462011-01-18 08:40:38 +00003199 case Type::ConstantArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003200 const auto *cat = cast<ConstantArrayType>(ty);
John McCall06549462011-01-18 08:40:38 +00003201 result = getConstantArrayType(
3202 getVariableArrayDecayedType(cat->getElementType()),
3203 cat->getSize(),
3204 cat->getSizeModifier(),
3205 cat->getIndexTypeCVRQualifiers());
3206 break;
3207 }
3208
3209 case Type::DependentSizedArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003210 const auto *dat = cast<DependentSizedArrayType>(ty);
John McCall06549462011-01-18 08:40:38 +00003211 result = getDependentSizedArrayType(
3212 getVariableArrayDecayedType(dat->getElementType()),
3213 dat->getSizeExpr(),
3214 dat->getSizeModifier(),
3215 dat->getIndexTypeCVRQualifiers(),
3216 dat->getBracketsRange());
3217 break;
3218 }
3219
3220 // Turn incomplete types into [*] types.
3221 case Type::IncompleteArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003222 const auto *iat = cast<IncompleteArrayType>(ty);
John McCall06549462011-01-18 08:40:38 +00003223 result = getVariableArrayType(
3224 getVariableArrayDecayedType(iat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00003225 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00003226 ArrayType::Normal,
3227 iat->getIndexTypeCVRQualifiers(),
3228 SourceRange());
3229 break;
3230 }
3231
3232 // Turn VLA types into [*] types.
3233 case Type::VariableArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003234 const auto *vat = cast<VariableArrayType>(ty);
John McCall06549462011-01-18 08:40:38 +00003235 result = getVariableArrayType(
3236 getVariableArrayDecayedType(vat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00003237 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00003238 ArrayType::Star,
3239 vat->getIndexTypeCVRQualifiers(),
3240 vat->getBracketsRange());
3241 break;
3242 }
3243 }
3244
3245 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00003246 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00003247}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003248
Steve Naroffcadebd02007-08-30 18:14:25 +00003249/// getVariableArrayType - Returns a non-unique reference to the type for a
3250/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00003251QualType ASTContext::getVariableArrayType(QualType EltTy,
3252 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00003253 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00003254 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00003255 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00003256 // Since we don't unique expressions, it isn't possible to unique VLA's
3257 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00003258 QualType Canon;
Fangrui Song6907ce22018-07-30 19:24:48 +00003259
John McCall33ddac02011-01-19 10:06:00 +00003260 // Be sure to pull qualifiers off the element type.
3261 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
3262 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00003263 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00003264 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00003265 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00003266 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003267
Eugene Zelenko7855e772018-04-03 00:11:50 +00003268 auto *New = new (*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00003269 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00003270
3271 VariableArrayTypes.push_back(New);
3272 Types.push_back(New);
3273 return QualType(New, 0);
3274}
3275
Douglas Gregor4619e432008-12-05 23:32:09 +00003276/// getDependentSizedArrayType - Returns a non-unique reference to
3277/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00003278/// type.
John McCall33ddac02011-01-19 10:06:00 +00003279QualType ASTContext::getDependentSizedArrayType(QualType elementType,
3280 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00003281 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00003282 unsigned elementTypeQuals,
3283 SourceRange brackets) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00003284 assert((!numElements || numElements->isTypeDependent() ||
John McCall33ddac02011-01-19 10:06:00 +00003285 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00003286 "Size must be type- or value-dependent!");
3287
John McCall33ddac02011-01-19 10:06:00 +00003288 // Dependently-sized array types that do not have a specified number
3289 // of elements will have their sizes deduced from a dependent
3290 // initializer. We do no canonicalization here at all, which is okay
3291 // because they can't be used in most locations.
3292 if (!numElements) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003293 auto *newType
John McCall33ddac02011-01-19 10:06:00 +00003294 = new (*this, TypeAlignment)
3295 DependentSizedArrayType(*this, elementType, QualType(),
3296 numElements, ASM, elementTypeQuals,
3297 brackets);
3298 Types.push_back(newType);
3299 return QualType(newType, 0);
3300 }
3301
3302 // Otherwise, we actually build a new type every time, but we
3303 // also build a canonical type.
3304
3305 SplitQualType canonElementType = getCanonicalType(elementType).split();
3306
Craig Topper36250ad2014-05-12 05:36:57 +00003307 void *insertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00003308 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00003309 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00003310 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00003311 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00003312
John McCall33ddac02011-01-19 10:06:00 +00003313 // Look for an existing type with these properties.
3314 DependentSizedArrayType *canonTy =
3315 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00003316
John McCall33ddac02011-01-19 10:06:00 +00003317 // If we don't have one, build one.
3318 if (!canonTy) {
3319 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00003320 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00003321 QualType(), numElements, ASM, elementTypeQuals,
3322 brackets);
3323 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
3324 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00003325 }
3326
John McCall33ddac02011-01-19 10:06:00 +00003327 // Apply qualifiers from the element type to the array.
3328 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00003329 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00003330
David Majnemer16a74702015-07-24 05:54:19 +00003331 // If we didn't need extra canonicalization for the element type or the size
3332 // expression, then just use that as our result.
3333 if (QualType(canonElementType.Ty, 0) == elementType &&
3334 canonTy->getSizeExpr() == numElements)
John McCall33ddac02011-01-19 10:06:00 +00003335 return canon;
3336
3337 // Otherwise, we need to build a type which follows the spelling
3338 // of the element type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00003339 auto *sugaredType
John McCall33ddac02011-01-19 10:06:00 +00003340 = new (*this, TypeAlignment)
3341 DependentSizedArrayType(*this, elementType, canon, numElements,
3342 ASM, elementTypeQuals, brackets);
3343 Types.push_back(sugaredType);
3344 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00003345}
3346
John McCall33ddac02011-01-19 10:06:00 +00003347QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00003348 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00003349 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00003350 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00003351 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00003352
Craig Topper36250ad2014-05-12 05:36:57 +00003353 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00003354 if (IncompleteArrayType *iat =
3355 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
3356 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00003357
3358 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00003359 // either, so fill in the canonical type field. We also have to pull
3360 // qualifiers off the element type.
3361 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00003362
John McCall33ddac02011-01-19 10:06:00 +00003363 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
3364 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00003365 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00003366 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00003367 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00003368
3369 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00003370 IncompleteArrayType *existing =
3371 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
3372 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00003373 }
Eli Friedmanbd258282008-02-15 18:16:39 +00003374
Eugene Zelenko7855e772018-04-03 00:11:50 +00003375 auto *newType = new (*this, TypeAlignment)
John McCall33ddac02011-01-19 10:06:00 +00003376 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00003377
John McCall33ddac02011-01-19 10:06:00 +00003378 IncompleteArrayTypes.InsertNode(newType, insertPos);
3379 Types.push_back(newType);
3380 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00003381}
3382
Steve Naroff91fcddb2007-07-18 18:00:27 +00003383/// getVectorType - Return the unique reference to a vector type of
3384/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00003385QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00003386 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00003387 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00003388
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003389 // Check if we've already instantiated a vector of this type.
3390 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00003391 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00003392
Craig Topper36250ad2014-05-12 05:36:57 +00003393 void *InsertPos = nullptr;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003394 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3395 return QualType(VTP, 0);
3396
3397 // If the element type isn't canonical, this won't be a canonical type either,
3398 // so fill in the canonical type field.
3399 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00003400 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00003401 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00003402
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003403 // Get the new insert position for the node we care about.
3404 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003405 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003406 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00003407 auto *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00003408 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003409 VectorTypes.InsertNode(New, InsertPos);
3410 Types.push_back(New);
3411 return QualType(New, 0);
3412}
3413
Erich Keanef702b022018-07-13 19:46:04 +00003414QualType
3415ASTContext::getDependentVectorType(QualType VecType, Expr *SizeExpr,
3416 SourceLocation AttrLoc,
3417 VectorType::VectorKind VecKind) const {
3418 llvm::FoldingSetNodeID ID;
3419 DependentVectorType::Profile(ID, *this, getCanonicalType(VecType), SizeExpr,
3420 VecKind);
3421 void *InsertPos = nullptr;
3422 DependentVectorType *Canon =
3423 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3424 DependentVectorType *New;
3425
3426 if (Canon) {
3427 New = new (*this, TypeAlignment) DependentVectorType(
3428 *this, VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind);
3429 } else {
3430 QualType CanonVecTy = getCanonicalType(VecType);
3431 if (CanonVecTy == VecType) {
3432 New = new (*this, TypeAlignment) DependentVectorType(
3433 *this, VecType, QualType(), SizeExpr, AttrLoc, VecKind);
3434
3435 DependentVectorType *CanonCheck =
3436 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3437 assert(!CanonCheck &&
3438 "Dependent-sized vector_size canonical type broken");
3439 (void)CanonCheck;
3440 DependentVectorTypes.InsertNode(New, InsertPos);
3441 } else {
3442 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
3443 SourceLocation());
3444 New = new (*this, TypeAlignment) DependentVectorType(
3445 *this, VecType, Canon, SizeExpr, AttrLoc, VecKind);
3446 }
3447 }
3448
3449 Types.push_back(New);
3450 return QualType(New, 0);
3451}
3452
Nate Begemance4d7fc2008-04-18 23:10:10 +00003453/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00003454/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00003455QualType
3456ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00003457 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00003458
Steve Naroff91fcddb2007-07-18 18:00:27 +00003459 // Check if we've already instantiated a vector of this type.
3460 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00003461 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00003462 VectorType::GenericVector);
Craig Topper36250ad2014-05-12 05:36:57 +00003463 void *InsertPos = nullptr;
Steve Naroff91fcddb2007-07-18 18:00:27 +00003464 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3465 return QualType(VTP, 0);
3466
3467 // If the element type isn't canonical, this won't be a canonical type either,
3468 // so fill in the canonical type field.
3469 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00003470 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00003471 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00003472
Steve Naroff91fcddb2007-07-18 18:00:27 +00003473 // Get the new insert position for the node we care about.
3474 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003475 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00003476 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00003477 auto *New = new (*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00003478 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00003479 VectorTypes.InsertNode(New, InsertPos);
3480 Types.push_back(New);
3481 return QualType(New, 0);
3482}
3483
Jay Foad39c79802011-01-12 09:06:06 +00003484QualType
3485ASTContext::getDependentSizedExtVectorType(QualType vecType,
3486 Expr *SizeExpr,
3487 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00003488 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00003489 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00003490 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003491
Craig Topper36250ad2014-05-12 05:36:57 +00003492 void *InsertPos = nullptr;
Douglas Gregor352169a2009-07-31 03:54:25 +00003493 DependentSizedExtVectorType *Canon
3494 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3495 DependentSizedExtVectorType *New;
3496 if (Canon) {
3497 // We already have a canonical version of this array type; use it as
3498 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00003499 New = new (*this, TypeAlignment)
3500 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
3501 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00003502 } else {
3503 QualType CanonVecTy = getCanonicalType(vecType);
3504 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00003505 New = new (*this, TypeAlignment)
3506 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
3507 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003508
3509 DependentSizedExtVectorType *CanonCheck
3510 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3511 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
3512 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00003513 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
3514 } else {
3515 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
3516 SourceLocation());
Fangrui Song6907ce22018-07-30 19:24:48 +00003517 New = new (*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00003518 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00003519 }
3520 }
Mike Stump11289f42009-09-09 15:08:12 +00003521
Douglas Gregor758a8692009-06-17 21:51:59 +00003522 Types.push_back(New);
3523 return QualType(New, 0);
3524}
3525
Fangrui Song6907ce22018-07-30 19:24:48 +00003526QualType ASTContext::getDependentAddressSpaceType(QualType PointeeType,
3527 Expr *AddrSpaceExpr,
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003528 SourceLocation AttrLoc) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00003529 assert(AddrSpaceExpr->isInstantiationDependent());
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003530
3531 QualType canonPointeeType = getCanonicalType(PointeeType);
3532
3533 void *insertPos = nullptr;
3534 llvm::FoldingSetNodeID ID;
3535 DependentAddressSpaceType::Profile(ID, *this, canonPointeeType,
3536 AddrSpaceExpr);
3537
3538 DependentAddressSpaceType *canonTy =
3539 DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos);
3540
3541 if (!canonTy) {
3542 canonTy = new (*this, TypeAlignment)
Fangrui Song6907ce22018-07-30 19:24:48 +00003543 DependentAddressSpaceType(*this, canonPointeeType,
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003544 QualType(), AddrSpaceExpr, AttrLoc);
3545 DependentAddressSpaceTypes.InsertNode(canonTy, insertPos);
3546 Types.push_back(canonTy);
3547 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003548
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003549 if (canonPointeeType == PointeeType &&
3550 canonTy->getAddrSpaceExpr() == AddrSpaceExpr)
Fangrui Song6907ce22018-07-30 19:24:48 +00003551 return QualType(canonTy, 0);
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003552
Eugene Zelenko7855e772018-04-03 00:11:50 +00003553 auto *sugaredType
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003554 = new (*this, TypeAlignment)
Fangrui Song6907ce22018-07-30 19:24:48 +00003555 DependentAddressSpaceType(*this, PointeeType, QualType(canonTy, 0),
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003556 AddrSpaceExpr, AttrLoc);
3557 Types.push_back(sugaredType);
Fangrui Song6907ce22018-07-30 19:24:48 +00003558 return QualType(sugaredType, 0);
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003559}
3560
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003561/// Determine whether \p T is canonical as the result type of a function.
John McCall18afab72016-03-01 00:49:02 +00003562static bool isCanonicalResultType(QualType T) {
3563 return T.isCanonical() &&
3564 (T.getObjCLifetime() == Qualifiers::OCL_None ||
3565 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
3566}
3567
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003568/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Jay Foad39c79802011-01-12 09:06:06 +00003569QualType
3570ASTContext::getFunctionNoProtoType(QualType ResultTy,
3571 const FunctionType::ExtInfo &Info) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003572 // Unique functions, to guarantee there is only one function of a particular
3573 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00003574 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00003575 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00003576
Craig Topper36250ad2014-05-12 05:36:57 +00003577 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003578 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003579 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003580 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003581
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003582 QualType Canonical;
John McCall18afab72016-03-01 00:49:02 +00003583 if (!isCanonicalResultType(ResultTy)) {
3584 Canonical =
3585 getFunctionNoProtoType(getCanonicalFunctionResultType(ResultTy), Info);
Mike Stump11289f42009-09-09 15:08:12 +00003586
Chris Lattner47955de2007-01-27 08:37:20 +00003587 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003588 FunctionNoProtoType *NewIP =
3589 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003590 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00003591 }
Mike Stump11289f42009-09-09 15:08:12 +00003592
Eugene Zelenko7855e772018-04-03 00:11:50 +00003593 auto *New = new (*this, TypeAlignment)
John McCall18afab72016-03-01 00:49:02 +00003594 FunctionNoProtoType(ResultTy, Canonical, Info);
Chris Lattner47955de2007-01-27 08:37:20 +00003595 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003596 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003597 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003598}
3599
Douglas Gregora602a152015-10-01 20:20:47 +00003600CanQualType
3601ASTContext::getCanonicalFunctionResultType(QualType ResultType) const {
3602 CanQualType CanResultType = getCanonicalType(ResultType);
3603
3604 // Canonical result types do not have ARC lifetime qualifiers.
3605 if (CanResultType.getQualifiers().hasObjCLifetime()) {
3606 Qualifiers Qs = CanResultType.getQualifiers();
3607 Qs.removeObjCLifetime();
3608 return CanQualType::CreateUnsafe(
3609 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
3610 }
3611
3612 return CanResultType;
3613}
3614
Richard Smith3c4f8d22016-10-16 17:54:23 +00003615static bool isCanonicalExceptionSpecification(
3616 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
3617 if (ESI.Type == EST_None)
3618 return true;
3619 if (!NoexceptInType)
3620 return false;
3621
3622 // C++17 onwards: exception specification is part of the type, as a simple
3623 // boolean "can this function type throw".
3624 if (ESI.Type == EST_BasicNoexcept)
3625 return true;
3626
Richard Smitheaf11ad2018-05-03 03:58:32 +00003627 // A noexcept(expr) specification is (possibly) canonical if expr is
3628 // value-dependent.
3629 if (ESI.Type == EST_DependentNoexcept)
3630 return true;
3631
Richard Smith3c4f8d22016-10-16 17:54:23 +00003632 // A dynamic exception specification is canonical if it only contains pack
Richard Smith2a2cda52016-10-18 19:29:18 +00003633 // expansions (so we can't tell whether it's non-throwing) and all its
3634 // contained types are canonical.
Richard Smith3c4f8d22016-10-16 17:54:23 +00003635 if (ESI.Type == EST_Dynamic) {
Richard Smithfda59e52016-10-26 01:05:54 +00003636 bool AnyPackExpansions = false;
3637 for (QualType ET : ESI.Exceptions) {
3638 if (!ET.isCanonical())
Richard Smith3c4f8d22016-10-16 17:54:23 +00003639 return false;
Richard Smithfda59e52016-10-26 01:05:54 +00003640 if (ET->getAs<PackExpansionType>())
3641 AnyPackExpansions = true;
3642 }
3643 return AnyPackExpansions;
Richard Smith3c4f8d22016-10-16 17:54:23 +00003644 }
3645
Richard Smith3c4f8d22016-10-16 17:54:23 +00003646 return false;
3647}
3648
Richard Smith304b1242016-10-18 20:13:25 +00003649QualType ASTContext::getFunctionTypeInternal(
3650 QualType ResultTy, ArrayRef<QualType> ArgArray,
3651 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
Jordan Rose5c382722013-03-08 21:51:21 +00003652 size_t NumArgs = ArgArray.size();
3653
Richard Smith2a2cda52016-10-18 19:29:18 +00003654 // Unique functions, to guarantee there is only one function of a particular
3655 // structure.
3656 llvm::FoldingSetNodeID ID;
3657 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
3658 *this, true);
Richard Smith3c4f8d22016-10-16 17:54:23 +00003659
Richard Smith2a2cda52016-10-18 19:29:18 +00003660 QualType Canonical;
3661 bool Unique = false;
3662
3663 void *InsertPos = nullptr;
3664 if (FunctionProtoType *FPT =
3665 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
3666 QualType Existing = QualType(FPT, 0);
3667
3668 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
3669 // it so long as our exception specification doesn't contain a dependent
Richard Smith304b1242016-10-18 20:13:25 +00003670 // noexcept expression, or we're just looking for a canonical type.
3671 // Otherwise, we're going to need to create a type
Richard Smith2a2cda52016-10-18 19:29:18 +00003672 // sugar node to hold the concrete expression.
Richard Smitheaf11ad2018-05-03 03:58:32 +00003673 if (OnlyWantCanonical || !isComputedNoexcept(EPI.ExceptionSpec.Type) ||
Richard Smith2a2cda52016-10-18 19:29:18 +00003674 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
3675 return Existing;
3676
3677 // We need a new type sugar node for this one, to hold the new noexcept
3678 // expression. We do no canonicalization here, but that's OK since we don't
3679 // expect to see the same noexcept expression much more than once.
3680 Canonical = getCanonicalType(Existing);
3681 Unique = true;
3682 }
3683
Aaron Ballmanc351fba2017-12-04 20:27:34 +00003684 bool NoexceptInType = getLangOpts().CPlusPlus17;
Richard Smith3c4f8d22016-10-16 17:54:23 +00003685 bool IsCanonicalExceptionSpec =
3686 isCanonicalExceptionSpecification(EPI.ExceptionSpec, NoexceptInType);
3687
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003688 // Determine whether the type being created is already canonical or not.
Richard Smith2a2cda52016-10-18 19:29:18 +00003689 bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
Richard Smith3c4f8d22016-10-16 17:54:23 +00003690 isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003691 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003692 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003693 isCanonical = false;
3694
Richard Smith304b1242016-10-18 20:13:25 +00003695 if (OnlyWantCanonical)
3696 assert(isCanonical &&
3697 "given non-canonical parameters constructing canonical type");
3698
Richard Smith2a2cda52016-10-18 19:29:18 +00003699 // If this type isn't canonical, get the canonical version of it if we don't
3700 // already have it. The exception spec is only partially part of the
3701 // canonical type, and only in C++17 onwards.
3702 if (!isCanonical && Canonical.isNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003703 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003704 CanonicalArgs.reserve(NumArgs);
3705 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003706 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003707
Benjamin Kramer3f515cd2016-10-26 12:51:45 +00003708 llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
John McCalldb40c7f2010-12-14 08:05:40 +00003709 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00003710 CanonicalEPI.HasTrailingReturn = false;
Richard Smith3c4f8d22016-10-16 17:54:23 +00003711
3712 if (IsCanonicalExceptionSpec) {
3713 // Exception spec is already OK.
3714 } else if (NoexceptInType) {
3715 switch (EPI.ExceptionSpec.Type) {
3716 case EST_Unparsed: case EST_Unevaluated: case EST_Uninstantiated:
3717 // We don't know yet. It shouldn't matter what we pick here; no-one
3718 // should ever look at this.
3719 LLVM_FALLTHROUGH;
Richard Smitheaf11ad2018-05-03 03:58:32 +00003720 case EST_None: case EST_MSAny: case EST_NoexceptFalse:
Richard Smith3c4f8d22016-10-16 17:54:23 +00003721 CanonicalEPI.ExceptionSpec.Type = EST_None;
3722 break;
3723
Richard Smith2a2cda52016-10-18 19:29:18 +00003724 // A dynamic exception specification is almost always "not noexcept",
3725 // with the exception that a pack expansion might expand to no types.
3726 case EST_Dynamic: {
3727 bool AnyPacks = false;
3728 for (QualType ET : EPI.ExceptionSpec.Exceptions) {
3729 if (ET->getAs<PackExpansionType>())
3730 AnyPacks = true;
3731 ExceptionTypeStorage.push_back(getCanonicalType(ET));
3732 }
3733 if (!AnyPacks)
3734 CanonicalEPI.ExceptionSpec.Type = EST_None;
3735 else {
3736 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
3737 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
3738 }
3739 break;
3740 }
3741
Richard Smitheaf11ad2018-05-03 03:58:32 +00003742 case EST_DynamicNone: case EST_BasicNoexcept: case EST_NoexceptTrue:
Richard Smith3c4f8d22016-10-16 17:54:23 +00003743 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
3744 break;
3745
Richard Smitheaf11ad2018-05-03 03:58:32 +00003746 case EST_DependentNoexcept:
3747 llvm_unreachable("dependent noexcept is already canonical");
Richard Smith3c4f8d22016-10-16 17:54:23 +00003748 }
Richard Smith3c4f8d22016-10-16 17:54:23 +00003749 } else {
3750 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
3751 }
John McCalldb40c7f2010-12-14 08:05:40 +00003752
Douglas Gregora602a152015-10-01 20:20:47 +00003753 // Adjust the canonical function result type.
3754 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
Richard Smith304b1242016-10-18 20:13:25 +00003755 Canonical =
3756 getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003757
Chris Lattnerfd4de792007-01-27 01:15:32 +00003758 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003759 FunctionProtoType *NewIP =
3760 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003761 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003762 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003763
Bruno Ricci26a25362018-10-02 11:46:38 +00003764 // Compute the needed size to hold this FunctionProtoType and the
3765 // various trailing objects.
3766 auto ESH = FunctionProtoType::getExceptionSpecSize(
3767 EPI.ExceptionSpec.Type, EPI.ExceptionSpec.Exceptions.size());
3768 size_t Size = FunctionProtoType::totalSizeToAlloc<
3769 QualType, FunctionType::FunctionTypeExtraBitfields,
3770 FunctionType::ExceptionType, Expr *, FunctionDecl *,
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00003771 FunctionProtoType::ExtParameterInfo, Qualifiers>(
Bruno Ricci26a25362018-10-02 11:46:38 +00003772 NumArgs, FunctionProtoType::hasExtraBitfields(EPI.ExceptionSpec.Type),
3773 ESH.NumExceptionType, ESH.NumExprPtr, ESH.NumFunctionDeclPtr,
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00003774 EPI.ExtParameterInfos ? NumArgs : 0,
3775 EPI.TypeQuals.hasNonFastQualifiers() ? 1 : 0);
John McCall18afab72016-03-01 00:49:02 +00003776
Bruno Ricci26a25362018-10-02 11:46:38 +00003777 auto *FTP = (FunctionProtoType *)Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00003778 FunctionProtoType::ExtProtoInfo newEPI = EPI;
Jordan Rose5c382722013-03-08 21:51:21 +00003779 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003780 Types.push_back(FTP);
Richard Smith2a2cda52016-10-18 19:29:18 +00003781 if (!Unique)
3782 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003783 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003784}
Chris Lattneref51c202006-11-10 07:17:23 +00003785
Joey Goulye3c85de2016-12-01 11:30:49 +00003786QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
Xiuli Pan9c14e282016-01-09 12:53:17 +00003787 llvm::FoldingSetNodeID ID;
Joey Goulye3c85de2016-12-01 11:30:49 +00003788 PipeType::Profile(ID, T, ReadOnly);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003789
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00003790 void *InsertPos = nullptr;
Joey Goulye3c85de2016-12-01 11:30:49 +00003791 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
Xiuli Pan9c14e282016-01-09 12:53:17 +00003792 return QualType(PT, 0);
3793
3794 // If the pipe element type isn't canonical, this won't be a canonical type
3795 // either, so fill in the canonical type field.
3796 QualType Canonical;
3797 if (!T.isCanonical()) {
Joey Goulye3c85de2016-12-01 11:30:49 +00003798 Canonical = getPipeType(getCanonicalType(T), ReadOnly);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003799
3800 // Get the new insert position for the node we care about.
Joey Goulye3c85de2016-12-01 11:30:49 +00003801 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003802 assert(!NewIP && "Shouldn't be in the map!");
3803 (void)NewIP;
3804 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00003805 auto *New = new (*this, TypeAlignment) PipeType(T, Canonical, ReadOnly);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003806 Types.push_back(New);
Joey Goulye3c85de2016-12-01 11:30:49 +00003807 PipeTypes.InsertNode(New, InsertPos);
Joey Gouly5788b782016-11-18 14:10:54 +00003808 return QualType(New, 0);
3809}
3810
Anastasia Stulova59055b92018-05-09 13:23:26 +00003811QualType ASTContext::adjustStringLiteralBaseType(QualType Ty) const {
3812 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
3813 return LangOpts.OpenCL ? getAddrSpaceQualType(Ty, LangAS::opencl_constant)
3814 : Ty;
3815}
3816
Joey Goulye3c85de2016-12-01 11:30:49 +00003817QualType ASTContext::getReadPipeType(QualType T) const {
3818 return getPipeType(T, true);
3819}
3820
Joey Gouly5788b782016-11-18 14:10:54 +00003821QualType ASTContext::getWritePipeType(QualType T) const {
Joey Goulye3c85de2016-12-01 11:30:49 +00003822 return getPipeType(T, false);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003823}
3824
John McCalle78aac42010-03-10 03:28:59 +00003825#ifndef NDEBUG
3826static bool NeedsInjectedClassNameType(const RecordDecl *D) {
3827 if (!isa<CXXRecordDecl>(D)) return false;
Eugene Zelenko7855e772018-04-03 00:11:50 +00003828 const auto *RD = cast<CXXRecordDecl>(D);
John McCalle78aac42010-03-10 03:28:59 +00003829 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
3830 return true;
3831 if (RD->getDescribedClassTemplate() &&
3832 !isa<ClassTemplateSpecializationDecl>(RD))
3833 return true;
3834 return false;
3835}
3836#endif
3837
3838/// getInjectedClassNameType - Return the unique reference to the
3839/// injected class name type for the specified templated declaration.
3840QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00003841 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00003842 assert(NeedsInjectedClassNameType(Decl));
3843 if (Decl->TypeForDecl) {
3844 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00003845 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00003846 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
3847 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3848 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
3849 } else {
John McCall424cec92011-01-19 06:33:43 +00003850 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00003851 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00003852 Decl->TypeForDecl = newType;
3853 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00003854 }
3855 return QualType(Decl->TypeForDecl, 0);
3856}
3857
Douglas Gregor83a586e2008-04-13 21:07:44 +00003858/// getTypeDeclType - Return the unique reference to the type for the
3859/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00003860QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00003861 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00003862 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00003863
Eugene Zelenko7855e772018-04-03 00:11:50 +00003864 if (const auto *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00003865 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00003866
John McCall96f0b5f2010-03-10 06:48:02 +00003867 assert(!isa<TemplateTypeParmDecl>(Decl) &&
3868 "Template type parameter types are always available.");
3869
Eugene Zelenko7855e772018-04-03 00:11:50 +00003870 if (const auto *Record = dyn_cast<RecordDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003871 assert(Record->isFirstDecl() && "struct/union has previous declaration");
John McCall96f0b5f2010-03-10 06:48:02 +00003872 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003873 return getRecordType(Record);
Eugene Zelenko7855e772018-04-03 00:11:50 +00003874 } else if (const auto *Enum = dyn_cast<EnumDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003875 assert(Enum->isFirstDecl() && "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003876 return getEnumType(Enum);
Eugene Zelenko7855e772018-04-03 00:11:50 +00003877 } else if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00003878 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
3879 Decl->TypeForDecl = newType;
3880 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00003881 } else
John McCall96f0b5f2010-03-10 06:48:02 +00003882 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003883
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003884 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00003885}
3886
Chris Lattner32d920b2007-01-26 02:01:53 +00003887/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00003888/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003889QualType
Richard Smithdda56e42011-04-15 14:24:37 +00003890ASTContext::getTypedefType(const TypedefNameDecl *Decl,
3891 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003892 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003893
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003894 if (Canonical.isNull())
3895 Canonical = getCanonicalType(Decl->getUnderlyingType());
Eugene Zelenko7855e772018-04-03 00:11:50 +00003896 auto *newType = new (*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00003897 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00003898 Decl->TypeForDecl = newType;
3899 Types.push_back(newType);
3900 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00003901}
3902
Jay Foad39c79802011-01-12 09:06:06 +00003903QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003904 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3905
Douglas Gregorec9fd132012-01-14 16:38:05 +00003906 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003907 if (PrevDecl->TypeForDecl)
Fangrui Song6907ce22018-07-30 19:24:48 +00003908 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003909
Eugene Zelenko7855e772018-04-03 00:11:50 +00003910 auto *newType = new (*this, TypeAlignment) RecordType(Decl);
John McCall424cec92011-01-19 06:33:43 +00003911 Decl->TypeForDecl = newType;
3912 Types.push_back(newType);
3913 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003914}
3915
Jay Foad39c79802011-01-12 09:06:06 +00003916QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003917 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3918
Douglas Gregorec9fd132012-01-14 16:38:05 +00003919 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003920 if (PrevDecl->TypeForDecl)
Fangrui Song6907ce22018-07-30 19:24:48 +00003921 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003922
Eugene Zelenko7855e772018-04-03 00:11:50 +00003923 auto *newType = new (*this, TypeAlignment) EnumType(Decl);
John McCall424cec92011-01-19 06:33:43 +00003924 Decl->TypeForDecl = newType;
3925 Types.push_back(newType);
3926 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003927}
3928
Richard Smithe43e2b32018-08-20 21:47:29 +00003929QualType ASTContext::getAttributedType(attr::Kind attrKind,
John McCall81904512011-01-06 01:58:22 +00003930 QualType modifiedType,
3931 QualType equivalentType) {
3932 llvm::FoldingSetNodeID id;
3933 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
3934
Craig Topper36250ad2014-05-12 05:36:57 +00003935 void *insertPos = nullptr;
John McCall81904512011-01-06 01:58:22 +00003936 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3937 if (type) return QualType(type, 0);
3938
3939 QualType canon = getCanonicalType(equivalentType);
3940 type = new (*this, TypeAlignment)
3941 AttributedType(canon, attrKind, modifiedType, equivalentType);
3942
3943 Types.push_back(type);
3944 AttributedTypes.InsertNode(type, insertPos);
3945
3946 return QualType(type, 0);
3947}
3948
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003949/// Retrieve a substitution-result type.
John McCallcebee162009-10-18 09:09:24 +00003950QualType
3951ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00003952 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00003953 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00003954 && "replacement types must always be canonical");
3955
3956 llvm::FoldingSetNodeID ID;
3957 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00003958 void *InsertPos = nullptr;
John McCallcebee162009-10-18 09:09:24 +00003959 SubstTemplateTypeParmType *SubstParm
3960 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3961
3962 if (!SubstParm) {
3963 SubstParm = new (*this, TypeAlignment)
3964 SubstTemplateTypeParmType(Parm, Replacement);
3965 Types.push_back(SubstParm);
3966 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3967 }
3968
3969 return QualType(SubstParm, 0);
3970}
3971
Fangrui Song6907ce22018-07-30 19:24:48 +00003972/// Retrieve a
Douglas Gregorada4b792011-01-14 02:55:32 +00003973QualType ASTContext::getSubstTemplateTypeParmPackType(
3974 const TemplateTypeParmType *Parm,
3975 const TemplateArgument &ArgPack) {
3976#ifndef NDEBUG
Aaron Ballman2a89e852014-07-15 21:32:31 +00003977 for (const auto &P : ArgPack.pack_elements()) {
3978 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3979 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
Douglas Gregorada4b792011-01-14 02:55:32 +00003980 }
3981#endif
Fangrui Song6907ce22018-07-30 19:24:48 +00003982
Douglas Gregorada4b792011-01-14 02:55:32 +00003983 llvm::FoldingSetNodeID ID;
3984 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00003985 void *InsertPos = nullptr;
Douglas Gregorada4b792011-01-14 02:55:32 +00003986 if (SubstTemplateTypeParmPackType *SubstParm
3987 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3988 return QualType(SubstParm, 0);
Fangrui Song6907ce22018-07-30 19:24:48 +00003989
Douglas Gregorada4b792011-01-14 02:55:32 +00003990 QualType Canon;
3991 if (!Parm->isCanonicalUnqualified()) {
3992 Canon = getCanonicalType(QualType(Parm, 0));
3993 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3994 ArgPack);
3995 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3996 }
3997
Eugene Zelenko7855e772018-04-03 00:11:50 +00003998 auto *SubstParm
Douglas Gregorada4b792011-01-14 02:55:32 +00003999 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
4000 ArgPack);
4001 Types.push_back(SubstParm);
George Burgess IVb5fe8552017-06-12 17:44:30 +00004002 SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos);
Fangrui Song6907ce22018-07-30 19:24:48 +00004003 return QualType(SubstParm, 0);
Douglas Gregorada4b792011-01-14 02:55:32 +00004004}
4005
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004006/// Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00004007/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00004008/// name.
Mike Stump11289f42009-09-09 15:08:12 +00004009QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00004010 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00004011 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00004012 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00004013 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Craig Topper36250ad2014-05-12 05:36:57 +00004014 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004015 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00004016 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4017
4018 if (TypeParm)
4019 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004020
Chandler Carruth08836322011-05-01 00:51:33 +00004021 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00004022 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00004023 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004024
Fangrui Song6907ce22018-07-30 19:24:48 +00004025 TemplateTypeParmType *TypeCheck
Douglas Gregorc42075a2010-02-04 18:10:26 +00004026 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4027 assert(!TypeCheck && "Template type parameter canonical type broken");
4028 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00004029 } else
John McCall90d1c2d2009-09-24 23:30:46 +00004030 TypeParm = new (*this, TypeAlignment)
4031 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00004032
4033 Types.push_back(TypeParm);
4034 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
4035
4036 return QualType(TypeParm, 0);
4037}
4038
John McCalle78aac42010-03-10 03:28:59 +00004039TypeSourceInfo *
4040ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
4041 SourceLocation NameLoc,
4042 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00004043 QualType Underlying) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00004044 assert(!Name.getAsDependentTemplateName() &&
Douglas Gregore16af532011-02-28 18:50:33 +00004045 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00004046 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00004047
4048 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie6adc78e2013-02-18 22:06:02 +00004049 TemplateSpecializationTypeLoc TL =
4050 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara48c05be2012-02-06 14:41:24 +00004051 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00004052 TL.setTemplateNameLoc(NameLoc);
4053 TL.setLAngleLoc(Args.getLAngleLoc());
4054 TL.setRAngleLoc(Args.getRAngleLoc());
4055 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
4056 TL.setArgLocInfo(i, Args[i].getLocInfo());
4057 return DI;
4058}
4059
Mike Stump11289f42009-09-09 15:08:12 +00004060QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00004061ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00004062 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00004063 QualType Underlying) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00004064 assert(!Template.getAsDependentTemplateName() &&
Douglas Gregore16af532011-02-28 18:50:33 +00004065 "No dependent template names here!");
John McCall6b51f282009-11-23 01:53:49 +00004066
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004067 SmallVector<TemplateArgument, 4> ArgVec;
David Majnemer6fbeee32016-07-07 04:43:07 +00004068 ArgVec.reserve(Args.size());
4069 for (const TemplateArgumentLoc &Arg : Args.arguments())
4070 ArgVec.push_back(Arg.getArgument());
John McCall0ad16662009-10-29 08:12:44 +00004071
David Majnemer6fbeee32016-07-07 04:43:07 +00004072 return getTemplateSpecializationType(Template, ArgVec, Underlying);
John McCall0ad16662009-10-29 08:12:44 +00004073}
4074
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004075#ifndef NDEBUG
David Majnemer6fbeee32016-07-07 04:43:07 +00004076static bool hasAnyPackExpansions(ArrayRef<TemplateArgument> Args) {
4077 for (const TemplateArgument &Arg : Args)
4078 if (Arg.isPackExpansion())
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004079 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00004080
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004081 return true;
4082}
4083#endif
4084
John McCall0ad16662009-10-29 08:12:44 +00004085QualType
4086ASTContext::getTemplateSpecializationType(TemplateName Template,
David Majnemer6fbeee32016-07-07 04:43:07 +00004087 ArrayRef<TemplateArgument> Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00004088 QualType Underlying) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00004089 assert(!Template.getAsDependentTemplateName() &&
Douglas Gregore16af532011-02-28 18:50:33 +00004090 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00004091 // Look through qualified template names.
4092 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
4093 Template = TemplateName(QTN->getTemplateDecl());
Fangrui Song6907ce22018-07-30 19:24:48 +00004094
4095 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00004096 Template.getAsTemplateDecl() &&
4097 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00004098 QualType CanonType;
4099 if (!Underlying.isNull())
4100 CanonType = getCanonicalType(Underlying);
4101 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004102 // We can get here with an alias template when the specialization contains
4103 // a pack expansion that does not match up with a parameter pack.
David Majnemer6fbeee32016-07-07 04:43:07 +00004104 assert((!IsTypeAlias || hasAnyPackExpansions(Args)) &&
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004105 "Caller must compute aliased type");
4106 IsTypeAlias = false;
David Majnemer6fbeee32016-07-07 04:43:07 +00004107 CanonType = getCanonicalTemplateSpecializationType(Template, Args);
Richard Smith3f1b5d02011-05-05 21:57:07 +00004108 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00004109
Douglas Gregora8e02e72009-07-28 23:00:59 +00004110 // Allocate the (non-canonical) template specialization type, but don't
4111 // try to unique it: these types typically have location information that
4112 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00004113 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
David Majnemer6fbeee32016-07-07 04:43:07 +00004114 sizeof(TemplateArgument) * Args.size() +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004115 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00004116 TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004117 auto *Spec
David Majnemer6fbeee32016-07-07 04:43:07 +00004118 = new (Mem) TemplateSpecializationType(Template, Args, CanonType,
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004119 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00004120
Douglas Gregor8bf42052009-02-09 18:46:07 +00004121 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00004122 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00004123}
4124
David Majnemer6fbeee32016-07-07 04:43:07 +00004125QualType ASTContext::getCanonicalTemplateSpecializationType(
4126 TemplateName Template, ArrayRef<TemplateArgument> Args) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00004127 assert(!Template.getAsDependentTemplateName() &&
Douglas Gregore16af532011-02-28 18:50:33 +00004128 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00004129
Douglas Gregore29139c2011-03-03 17:04:51 +00004130 // Look through qualified template names.
4131 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
4132 Template = TemplateName(QTN->getTemplateDecl());
Fangrui Song6907ce22018-07-30 19:24:48 +00004133
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004134 // Build the canonical template specialization type.
4135 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004136 SmallVector<TemplateArgument, 4> CanonArgs;
David Majnemer6fbeee32016-07-07 04:43:07 +00004137 unsigned NumArgs = Args.size();
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004138 CanonArgs.reserve(NumArgs);
David Majnemer6fbeee32016-07-07 04:43:07 +00004139 for (const TemplateArgument &Arg : Args)
4140 CanonArgs.push_back(getCanonicalTemplateArgument(Arg));
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004141
4142 // Determine whether this canonical template specialization type already
4143 // exists.
4144 llvm::FoldingSetNodeID ID;
4145 TemplateSpecializationType::Profile(ID, CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00004146 CanonArgs, *this);
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004147
Craig Topper36250ad2014-05-12 05:36:57 +00004148 void *InsertPos = nullptr;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004149 TemplateSpecializationType *Spec
4150 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
4151
4152 if (!Spec) {
4153 // Allocate a new canonical template specialization type.
4154 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
4155 sizeof(TemplateArgument) * NumArgs),
4156 TypeAlignment);
4157 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00004158 CanonArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00004159 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004160 Types.push_back(Spec);
4161 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
4162 }
4163
4164 assert(Spec->isDependentType() &&
4165 "Non-dependent template-id type must have a canonical type");
4166 return QualType(Spec, 0);
4167}
4168
Joel E. Denny7509a2f2018-05-14 19:36:45 +00004169QualType ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
4170 NestedNameSpecifier *NNS,
4171 QualType NamedType,
4172 TagDecl *OwnedTagDecl) const {
Douglas Gregor52537682009-03-19 00:18:19 +00004173 llvm::FoldingSetNodeID ID;
Joel E. Denny7509a2f2018-05-14 19:36:45 +00004174 ElaboratedType::Profile(ID, Keyword, NNS, NamedType, OwnedTagDecl);
Douglas Gregor52537682009-03-19 00:18:19 +00004175
Craig Topper36250ad2014-05-12 05:36:57 +00004176 void *InsertPos = nullptr;
Abramo Bagnara6150c882010-05-11 21:36:43 +00004177 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00004178 if (T)
4179 return QualType(T, 0);
4180
Douglas Gregorc42075a2010-02-04 18:10:26 +00004181 QualType Canon = NamedType;
4182 if (!Canon.isCanonical()) {
4183 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00004184 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
4185 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00004186 (void)CheckT;
4187 }
4188
Bruno Riccid6bd5982018-08-16 10:48:16 +00004189 void *Mem = Allocate(ElaboratedType::totalSizeToAlloc<TagDecl *>(!!OwnedTagDecl),
4190 TypeAlignment);
4191 T = new (Mem) ElaboratedType(Keyword, NNS, NamedType, Canon, OwnedTagDecl);
4192
Douglas Gregor52537682009-03-19 00:18:19 +00004193 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00004194 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00004195 return QualType(T, 0);
4196}
4197
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004198QualType
Jay Foad39c79802011-01-12 09:06:06 +00004199ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004200 llvm::FoldingSetNodeID ID;
4201 ParenType::Profile(ID, InnerType);
4202
Craig Topper36250ad2014-05-12 05:36:57 +00004203 void *InsertPos = nullptr;
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004204 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
4205 if (T)
4206 return QualType(T, 0);
4207
4208 QualType Canon = InnerType;
4209 if (!Canon.isCanonical()) {
4210 Canon = getCanonicalType(InnerType);
4211 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
4212 assert(!CheckT && "Paren canonical type broken");
4213 (void)CheckT;
4214 }
4215
Benjamin Kramer8adeef92015-04-02 16:19:54 +00004216 T = new (*this, TypeAlignment) ParenType(InnerType, Canon);
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004217 Types.push_back(T);
4218 ParenTypes.InsertNode(T, InsertPos);
4219 return QualType(T, 0);
4220}
4221
Douglas Gregor02085352010-03-31 20:19:30 +00004222QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
4223 NestedNameSpecifier *NNS,
4224 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00004225 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00004226 if (Canon.isNull()) {
4227 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Richard Smith74f02342017-01-19 21:00:13 +00004228 if (CanonNNS != NNS)
4229 Canon = getDependentNameType(Keyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00004230 }
4231
4232 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00004233 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00004234
Craig Topper36250ad2014-05-12 05:36:57 +00004235 void *InsertPos = nullptr;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00004236 DependentNameType *T
4237 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00004238 if (T)
4239 return QualType(T, 0);
4240
Benjamin Kramer8adeef92015-04-02 16:19:54 +00004241 T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00004242 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00004243 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00004244 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00004245}
4246
Mike Stump11289f42009-09-09 15:08:12 +00004247QualType
John McCallc392f372010-06-11 00:33:02 +00004248ASTContext::getDependentTemplateSpecializationType(
4249 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00004250 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00004251 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00004252 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00004253 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004254 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00004255 for (unsigned I = 0, E = Args.size(); I != E; ++I)
4256 ArgCopy.push_back(Args[I].getArgument());
David Majnemer6fbeee32016-07-07 04:43:07 +00004257 return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy);
John McCallc392f372010-06-11 00:33:02 +00004258}
4259
4260QualType
4261ASTContext::getDependentTemplateSpecializationType(
4262 ElaboratedTypeKeyword Keyword,
4263 NestedNameSpecifier *NNS,
4264 const IdentifierInfo *Name,
David Majnemer6fbeee32016-07-07 04:43:07 +00004265 ArrayRef<TemplateArgument> Args) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00004266 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor6e068012011-02-28 00:04:36 +00004267 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00004268
Douglas Gregorc42075a2010-02-04 18:10:26 +00004269 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00004270 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00004271 Name, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004272
Craig Topper36250ad2014-05-12 05:36:57 +00004273 void *InsertPos = nullptr;
John McCallc392f372010-06-11 00:33:02 +00004274 DependentTemplateSpecializationType *T
4275 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004276 if (T)
4277 return QualType(T, 0);
4278
John McCallc392f372010-06-11 00:33:02 +00004279 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004280
John McCallc392f372010-06-11 00:33:02 +00004281 ElaboratedTypeKeyword CanonKeyword = Keyword;
4282 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
4283
4284 bool AnyNonCanonArgs = false;
David Majnemer6fbeee32016-07-07 04:43:07 +00004285 unsigned NumArgs = Args.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004286 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00004287 for (unsigned I = 0; I != NumArgs; ++I) {
4288 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
4289 if (!CanonArgs[I].structurallyEquals(Args[I]))
4290 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00004291 }
4292
John McCallc392f372010-06-11 00:33:02 +00004293 QualType Canon;
4294 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
4295 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00004296 Name,
4297 CanonArgs);
John McCallc392f372010-06-11 00:33:02 +00004298
4299 // Find the insert position again.
4300 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
4301 }
4302
4303 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
4304 sizeof(TemplateArgument) * NumArgs),
4305 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00004306 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00004307 Name, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00004308 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00004309 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00004310 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00004311}
4312
Richard Smith32918772017-02-14 00:25:28 +00004313TemplateArgument ASTContext::getInjectedTemplateArg(NamedDecl *Param) {
4314 TemplateArgument Arg;
Eugene Zelenko7855e772018-04-03 00:11:50 +00004315 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
Richard Smith32918772017-02-14 00:25:28 +00004316 QualType ArgType = getTypeDeclType(TTP);
4317 if (TTP->isParameterPack())
4318 ArgType = getPackExpansionType(ArgType, None);
4319
4320 Arg = TemplateArgument(ArgType);
4321 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4322 Expr *E = new (*this) DeclRefExpr(
Bruno Ricci5fc4db72018-12-21 14:10:18 +00004323 *this, NTTP, /*enclosing*/ false,
Richard Smith32918772017-02-14 00:25:28 +00004324 NTTP->getType().getNonLValueExprType(*this),
4325 Expr::getValueKindForType(NTTP->getType()), NTTP->getLocation());
4326
4327 if (NTTP->isParameterPack())
4328 E = new (*this) PackExpansionExpr(DependentTy, E, NTTP->getLocation(),
4329 None);
4330 Arg = TemplateArgument(E);
4331 } else {
4332 auto *TTP = cast<TemplateTemplateParmDecl>(Param);
4333 if (TTP->isParameterPack())
4334 Arg = TemplateArgument(TemplateName(TTP), Optional<unsigned>());
4335 else
4336 Arg = TemplateArgument(TemplateName(TTP));
4337 }
4338
4339 if (Param->isTemplateParameterPack())
4340 Arg = TemplateArgument::CreatePackCopy(*this, Arg);
4341
4342 return Arg;
4343}
4344
Richard Smith43e14d22016-12-23 02:10:11 +00004345void
4346ASTContext::getInjectedTemplateArgs(const TemplateParameterList *Params,
4347 SmallVectorImpl<TemplateArgument> &Args) {
4348 Args.reserve(Args.size() + Params->size());
4349
Richard Smith32918772017-02-14 00:25:28 +00004350 for (NamedDecl *Param : *Params)
4351 Args.push_back(getInjectedTemplateArg(Param));
Richard Smith43e14d22016-12-23 02:10:11 +00004352}
4353
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00004354QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikie05785d12013-02-20 22:23:23 +00004355 Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00004356 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00004357 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00004358
4359 assert(Pattern->containsUnexpandedParameterPack() &&
4360 "Pack expansions must expand one or more parameter packs");
Craig Topper36250ad2014-05-12 05:36:57 +00004361 void *InsertPos = nullptr;
Douglas Gregord2fa7662010-12-20 02:24:11 +00004362 PackExpansionType *T
4363 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
4364 if (T)
4365 return QualType(T, 0);
4366
4367 QualType Canon;
4368 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00004369 Canon = getCanonicalType(Pattern);
4370 // The canonical type might not contain an unexpanded parameter pack, if it
4371 // contains an alias template specialization which ignores one of its
4372 // parameters.
4373 if (Canon->containsUnexpandedParameterPack()) {
Richard Smith8b4e1e22014-07-10 01:20:17 +00004374 Canon = getPackExpansionType(Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00004375
Richard Smith68eea502012-07-16 00:20:35 +00004376 // Find the insert position again, in case we inserted an element into
4377 // PackExpansionTypes and invalidated our insert position.
4378 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
4379 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00004380 }
4381
Benjamin Kramer8adeef92015-04-02 16:19:54 +00004382 T = new (*this, TypeAlignment)
4383 PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00004384 Types.push_back(T);
4385 PackExpansionTypes.InsertNode(T, InsertPos);
Richard Smith8b4e1e22014-07-10 01:20:17 +00004386 return QualType(T, 0);
Douglas Gregord2fa7662010-12-20 02:24:11 +00004387}
4388
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004389/// CmpProtocolNames - Comparison predicate for sorting protocols
4390/// alphabetically.
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00004391static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
4392 ObjCProtocolDecl *const *RHS) {
4393 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004394}
4395
Craig Topper1f26d5b2016-01-03 19:43:23 +00004396static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) {
4397 if (Protocols.empty()) return true;
John McCallfc93cf92009-10-22 22:37:11 +00004398
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00004399 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
4400 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00004401
Craig Topper1f26d5b2016-01-03 19:43:23 +00004402 for (unsigned i = 1; i != Protocols.size(); ++i)
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00004403 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00004404 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00004405 return false;
4406 return true;
4407}
4408
Craig Topper6a8c1512015-10-22 01:56:18 +00004409static void
4410SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) {
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004411 // Sort protocols, keyed by name.
Craig Topper6a8c1512015-10-22 01:56:18 +00004412 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004413
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00004414 // Canonicalize.
Craig Topper6a8c1512015-10-22 01:56:18 +00004415 for (ObjCProtocolDecl *&P : Protocols)
4416 P = P->getCanonicalDecl();
4417
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004418 // Remove duplicates.
Craig Topper6a8c1512015-10-22 01:56:18 +00004419 auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end());
4420 Protocols.erase(ProtocolsEnd, Protocols.end());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004421}
4422
John McCall8b07ec22010-05-15 11:32:37 +00004423QualType ASTContext::getObjCObjectType(QualType BaseType,
4424 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00004425 unsigned NumProtocols) const {
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004426 return getObjCObjectType(BaseType, {},
Douglas Gregorab209d82015-07-07 03:58:42 +00004427 llvm::makeArrayRef(Protocols, NumProtocols),
4428 /*isKindOf=*/false);
Douglas Gregore9d95f12015-07-07 03:57:35 +00004429}
4430
4431QualType ASTContext::getObjCObjectType(
4432 QualType baseType,
4433 ArrayRef<QualType> typeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00004434 ArrayRef<ObjCProtocolDecl *> protocols,
4435 bool isKindOf) const {
Douglas Gregore9d95f12015-07-07 03:57:35 +00004436 // If the base type is an interface and there aren't any protocols or
4437 // type arguments to add, then the interface type will do just fine.
Douglas Gregorab209d82015-07-07 03:58:42 +00004438 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
4439 isa<ObjCInterfaceType>(baseType))
Douglas Gregore9d95f12015-07-07 03:57:35 +00004440 return baseType;
John McCall8b07ec22010-05-15 11:32:37 +00004441
4442 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00004443 llvm::FoldingSetNodeID ID;
Douglas Gregorab209d82015-07-07 03:58:42 +00004444 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
Craig Topper36250ad2014-05-12 05:36:57 +00004445 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00004446 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
4447 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00004448
Douglas Gregore9d95f12015-07-07 03:57:35 +00004449 // Determine the type arguments to be used for canonicalization,
4450 // which may be explicitly specified here or written on the base
4451 // type.
4452 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
4453 if (effectiveTypeArgs.empty()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00004454 if (const auto *baseObject = baseType->getAs<ObjCObjectType>())
Douglas Gregore9d95f12015-07-07 03:57:35 +00004455 effectiveTypeArgs = baseObject->getTypeArgs();
4456 }
John McCallfc93cf92009-10-22 22:37:11 +00004457
Douglas Gregore9d95f12015-07-07 03:57:35 +00004458 // Build the canonical type, which has the canonical base type and a
4459 // sorted-and-uniqued list of protocols and the type arguments
4460 // canonicalized.
4461 QualType canonical;
4462 bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(),
4463 effectiveTypeArgs.end(),
4464 [&](QualType type) {
4465 return type.isCanonical();
4466 });
Craig Topper1f26d5b2016-01-03 19:43:23 +00004467 bool protocolsSorted = areSortedAndUniqued(protocols);
Douglas Gregore9d95f12015-07-07 03:57:35 +00004468 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
4469 // Determine the canonical type arguments.
4470 ArrayRef<QualType> canonTypeArgs;
4471 SmallVector<QualType, 4> canonTypeArgsVec;
4472 if (!typeArgsAreCanonical) {
4473 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
4474 for (auto typeArg : effectiveTypeArgs)
4475 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
4476 canonTypeArgs = canonTypeArgsVec;
John McCallfc93cf92009-10-22 22:37:11 +00004477 } else {
Douglas Gregore9d95f12015-07-07 03:57:35 +00004478 canonTypeArgs = effectiveTypeArgs;
John McCallfc93cf92009-10-22 22:37:11 +00004479 }
4480
Douglas Gregore9d95f12015-07-07 03:57:35 +00004481 ArrayRef<ObjCProtocolDecl *> canonProtocols;
4482 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
4483 if (!protocolsSorted) {
Craig Topper6a8c1512015-10-22 01:56:18 +00004484 canonProtocolsVec.append(protocols.begin(), protocols.end());
4485 SortAndUniqueProtocols(canonProtocolsVec);
4486 canonProtocols = canonProtocolsVec;
Douglas Gregore9d95f12015-07-07 03:57:35 +00004487 } else {
4488 canonProtocols = protocols;
4489 }
4490
4491 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00004492 canonProtocols, isKindOf);
Douglas Gregore9d95f12015-07-07 03:57:35 +00004493
John McCallfc93cf92009-10-22 22:37:11 +00004494 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00004495 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
4496 }
4497
Douglas Gregore9d95f12015-07-07 03:57:35 +00004498 unsigned size = sizeof(ObjCObjectTypeImpl);
4499 size += typeArgs.size() * sizeof(QualType);
4500 size += protocols.size() * sizeof(ObjCProtocolDecl *);
4501 void *mem = Allocate(size, TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004502 auto *T =
Douglas Gregorab209d82015-07-07 03:58:42 +00004503 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
4504 isKindOf);
John McCall8b07ec22010-05-15 11:32:37 +00004505
4506 Types.push_back(T);
4507 ObjCObjectTypes.InsertNode(T, InsertPos);
4508 return QualType(T, 0);
4509}
4510
Manman Ren3569eb52016-09-13 17:03:12 +00004511/// Apply Objective-C protocol qualifiers to the given type.
4512/// If this is for the canonical type of a type parameter, we can apply
4513/// protocol qualifiers on the ObjCObjectPointerType.
4514QualType
4515ASTContext::applyObjCProtocolQualifiers(QualType type,
4516 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
4517 bool allowOnPointerType) const {
4518 hasError = false;
4519
Eugene Zelenko7855e772018-04-03 00:11:50 +00004520 if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
Manman Renc5705ba2016-09-13 17:41:05 +00004521 return getObjCTypeParamType(objT->getDecl(), protocols);
4522 }
4523
Manman Ren3569eb52016-09-13 17:03:12 +00004524 // Apply protocol qualifiers to ObjCObjectPointerType.
4525 if (allowOnPointerType) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00004526 if (const auto *objPtr =
4527 dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
Manman Ren3569eb52016-09-13 17:03:12 +00004528 const ObjCObjectType *objT = objPtr->getObjectType();
4529 // Merge protocol lists and construct ObjCObjectType.
4530 SmallVector<ObjCProtocolDecl*, 8> protocolsVec;
4531 protocolsVec.append(objT->qual_begin(),
4532 objT->qual_end());
4533 protocolsVec.append(protocols.begin(), protocols.end());
4534 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
4535 type = getObjCObjectType(
4536 objT->getBaseType(),
4537 objT->getTypeArgsAsWritten(),
4538 protocols,
4539 objT->isKindOfTypeAsWritten());
4540 return getObjCObjectPointerType(type);
4541 }
4542 }
4543
4544 // Apply protocol qualifiers to ObjCObjectType.
Eugene Zelenko7855e772018-04-03 00:11:50 +00004545 if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
Manman Ren3569eb52016-09-13 17:03:12 +00004546 // FIXME: Check for protocols to which the class type is already
4547 // known to conform.
4548
4549 return getObjCObjectType(objT->getBaseType(),
4550 objT->getTypeArgsAsWritten(),
4551 protocols,
4552 objT->isKindOfTypeAsWritten());
4553 }
4554
4555 // If the canonical type is ObjCObjectType, ...
4556 if (type->isObjCObjectType()) {
4557 // Silently overwrite any existing protocol qualifiers.
4558 // TODO: determine whether that's the right thing to do.
4559
4560 // FIXME: Check for protocols to which the class type is already
4561 // known to conform.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004562 return getObjCObjectType(type, {}, protocols, false);
Manman Ren3569eb52016-09-13 17:03:12 +00004563 }
4564
4565 // id<protocol-list>
4566 if (type->isObjCIdType()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00004567 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004568 type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols,
Manman Ren3569eb52016-09-13 17:03:12 +00004569 objPtr->isKindOfType());
4570 return getObjCObjectPointerType(type);
4571 }
4572
4573 // Class<protocol-list>
4574 if (type->isObjCClassType()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00004575 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004576 type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols,
Manman Ren3569eb52016-09-13 17:03:12 +00004577 objPtr->isKindOfType());
4578 return getObjCObjectPointerType(type);
4579 }
4580
4581 hasError = true;
4582 return type;
4583}
4584
Manman Rene6be26c2016-09-13 17:25:08 +00004585QualType
4586ASTContext::getObjCTypeParamType(const ObjCTypeParamDecl *Decl,
4587 ArrayRef<ObjCProtocolDecl *> protocols,
4588 QualType Canonical) const {
4589 // Look in the folding set for an existing type.
4590 llvm::FoldingSetNodeID ID;
4591 ObjCTypeParamType::Profile(ID, Decl, protocols);
4592 void *InsertPos = nullptr;
4593 if (ObjCTypeParamType *TypeParam =
4594 ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
4595 return QualType(TypeParam, 0);
4596
4597 if (Canonical.isNull()) {
4598 // We canonicalize to the underlying type.
4599 Canonical = getCanonicalType(Decl->getUnderlyingType());
4600 if (!protocols.empty()) {
4601 // Apply the protocol qualifers.
4602 bool hasError;
Richard Trieua986a312018-08-30 01:57:52 +00004603 Canonical = getCanonicalType(applyObjCProtocolQualifiers(
4604 Canonical, protocols, hasError, true /*allowOnPointerType*/));
Manman Rene6be26c2016-09-13 17:25:08 +00004605 assert(!hasError && "Error when apply protocol qualifier to bound type");
4606 }
4607 }
4608
4609 unsigned size = sizeof(ObjCTypeParamType);
4610 size += protocols.size() * sizeof(ObjCProtocolDecl *);
4611 void *mem = Allocate(size, TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004612 auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols);
Manman Rene6be26c2016-09-13 17:25:08 +00004613
4614 Types.push_back(newType);
4615 ObjCTypeParamTypes.InsertNode(newType, InsertPos);
4616 return QualType(newType, 0);
4617}
4618
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004619/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
4620/// protocol list adopt all protocols in QT's qualified-id protocol
4621/// list.
4622bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
4623 ObjCInterfaceDecl *IC) {
4624 if (!QT->isObjCQualifiedIdType())
4625 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00004626
Eugene Zelenko7855e772018-04-03 00:11:50 +00004627 if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004628 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00004629 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004630 if (!IC->ClassImplementsProtocol(Proto, false))
4631 return false;
4632 }
4633 return true;
4634 }
4635 return false;
4636}
4637
4638/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
4639/// QT's qualified-id protocol list adopt all protocols in IDecl's list
4640/// of protocols.
4641bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
4642 ObjCInterfaceDecl *IDecl) {
4643 if (!QT->isObjCQualifiedIdType())
4644 return false;
Eugene Zelenko7855e772018-04-03 00:11:50 +00004645 const auto *OPT = QT->getAs<ObjCObjectPointerType>();
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004646 if (!OPT)
4647 return false;
4648 if (!IDecl->hasDefinition())
4649 return false;
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00004650 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
4651 CollectInheritedProtocols(IDecl, InheritedProtocols);
4652 if (InheritedProtocols.empty())
4653 return false;
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00004654 // Check that if every protocol in list of id<plist> conforms to a protocol
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00004655 // of IDecl's, then bridge casting is ok.
4656 bool Conforms = false;
4657 for (auto *Proto : OPT->quals()) {
4658 Conforms = false;
4659 for (auto *PI : InheritedProtocols) {
4660 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
4661 Conforms = true;
4662 break;
4663 }
4664 }
4665 if (!Conforms)
4666 break;
4667 }
4668 if (Conforms)
4669 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00004670
Aaron Ballman83731462014-03-17 16:14:00 +00004671 for (auto *PI : InheritedProtocols) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004672 // If both the right and left sides have qualifiers.
4673 bool Adopts = false;
Aaron Ballman83731462014-03-17 16:14:00 +00004674 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00004675 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
Aaron Ballman83731462014-03-17 16:14:00 +00004676 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004677 break;
4678 }
4679 if (!Adopts)
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00004680 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004681 }
4682 return true;
4683}
4684
John McCall8b07ec22010-05-15 11:32:37 +00004685/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
4686/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00004687QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00004688 llvm::FoldingSetNodeID ID;
4689 ObjCObjectPointerType::Profile(ID, ObjectT);
4690
Craig Topper36250ad2014-05-12 05:36:57 +00004691 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00004692 if (ObjCObjectPointerType *QT =
4693 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
4694 return QualType(QT, 0);
4695
4696 // Find the canonical object type.
4697 QualType Canonical;
4698 if (!ObjectT.isCanonical()) {
4699 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
4700
4701 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00004702 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
4703 }
4704
Douglas Gregorf85bee62010-02-08 22:59:26 +00004705 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00004706 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004707 auto *QType =
John McCall8b07ec22010-05-15 11:32:37 +00004708 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00004709
Steve Narofffb4330f2009-06-17 22:40:22 +00004710 Types.push_back(QType);
4711 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00004712 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00004713}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004714
Douglas Gregor1c283312010-08-11 12:19:30 +00004715/// getObjCInterfaceType - Return the unique reference to the type for the
4716/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00004717QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
4718 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00004719 if (Decl->TypeForDecl)
4720 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004721
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00004722 if (PrevDecl) {
4723 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
4724 Decl->TypeForDecl = PrevDecl->TypeForDecl;
4725 return QualType(PrevDecl->TypeForDecl, 0);
4726 }
4727
Douglas Gregor7671e532011-12-16 16:34:57 +00004728 // Prefer the definition, if there is one.
4729 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
4730 Decl = Def;
Fangrui Song6907ce22018-07-30 19:24:48 +00004731
Douglas Gregor1c283312010-08-11 12:19:30 +00004732 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004733 auto *T = new (Mem) ObjCInterfaceType(Decl);
Douglas Gregor1c283312010-08-11 12:19:30 +00004734 Decl->TypeForDecl = T;
4735 Types.push_back(T);
4736 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00004737}
4738
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004739/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
4740/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00004741/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00004742/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00004743/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00004744QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00004745 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004746 if (tofExpr->isTypeDependent()) {
4747 llvm::FoldingSetNodeID ID;
4748 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00004749
Craig Topper36250ad2014-05-12 05:36:57 +00004750 void *InsertPos = nullptr;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004751 DependentTypeOfExprType *Canon
4752 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
4753 if (Canon) {
4754 // We already have a "canonical" version of an identical, dependent
4755 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00004756 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004757 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00004758 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004759 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00004760 Canon
4761 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004762 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
4763 toe = Canon;
4764 }
4765 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00004766 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00004767 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00004768 }
Steve Naroffa773cd52007-08-01 18:02:17 +00004769 Types.push_back(toe);
4770 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00004771}
4772
Steve Naroffa773cd52007-08-01 18:02:17 +00004773/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
Richard Smith8eb1d322014-06-05 20:13:13 +00004774/// TypeOfType nodes. The only motivation to unique these nodes would be
Steve Naroffa773cd52007-08-01 18:02:17 +00004775/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Richard Smith8eb1d322014-06-05 20:13:13 +00004776/// an issue. This doesn't affect the type checker, since it operates
4777/// on canonical types (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00004778QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00004779 QualType Canonical = getCanonicalType(tofType);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004780 auto *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00004781 Types.push_back(tot);
4782 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00004783}
4784
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004785/// Unlike many "get<Type>" functions, we don't unique DecltypeType
Richard Smith8eb1d322014-06-05 20:13:13 +00004786/// nodes. This would never be helpful, since each such type has its own
4787/// expression, and would not give a significant memory saving, since there
4788/// is an Expr tree under each such type.
Douglas Gregor81495f32012-02-12 18:42:33 +00004789QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00004790 DecltypeType *dt;
Richard Smith8eb1d322014-06-05 20:13:13 +00004791
4792 // C++11 [temp.type]p2:
Douglas Gregor678d76c2011-07-01 01:22:09 +00004793 // If an expression e involves a template parameter, decltype(e) denotes a
Richard Smith8eb1d322014-06-05 20:13:13 +00004794 // unique dependent type. Two such decltype-specifiers refer to the same
4795 // type only if their expressions are equivalent (14.5.6.1).
Douglas Gregor678d76c2011-07-01 01:22:09 +00004796 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00004797 llvm::FoldingSetNodeID ID;
4798 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00004799
Craig Topper36250ad2014-05-12 05:36:57 +00004800 void *InsertPos = nullptr;
Douglas Gregora21f6c32009-07-30 23:36:40 +00004801 DependentDecltypeType *Canon
4802 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
Richard Smith8eb1d322014-06-05 20:13:13 +00004803 if (!Canon) {
Yaron Keren633e14a2016-11-29 10:08:20 +00004804 // Build a new, canonical decltype(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00004805 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00004806 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
Douglas Gregora21f6c32009-07-30 23:36:40 +00004807 }
Richard Smith8eb1d322014-06-05 20:13:13 +00004808 dt = new (*this, TypeAlignment)
4809 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
Douglas Gregora21f6c32009-07-30 23:36:40 +00004810 } else {
Richard Smith8eb1d322014-06-05 20:13:13 +00004811 dt = new (*this, TypeAlignment)
4812 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00004813 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00004814 Types.push_back(dt);
4815 return QualType(dt, 0);
4816}
4817
Alexis Hunte852b102011-05-24 22:41:36 +00004818/// getUnaryTransformationType - We don't unique these, since the memory
4819/// savings are minimal and these are rare.
4820QualType ASTContext::getUnaryTransformType(QualType BaseType,
4821 QualType UnderlyingType,
4822 UnaryTransformType::UTTKind Kind)
4823 const {
Vassil Vassilevbab6f962016-03-30 22:18:29 +00004824 UnaryTransformType *ut = nullptr;
4825
4826 if (BaseType->isDependentType()) {
4827 // Look in the folding set for an existing type.
4828 llvm::FoldingSetNodeID ID;
4829 DependentUnaryTransformType::Profile(ID, getCanonicalType(BaseType), Kind);
4830
4831 void *InsertPos = nullptr;
4832 DependentUnaryTransformType *Canon
4833 = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
4834
4835 if (!Canon) {
4836 // Build a new, canonical __underlying_type(type) type.
4837 Canon = new (*this, TypeAlignment)
4838 DependentUnaryTransformType(*this, getCanonicalType(BaseType),
4839 Kind);
4840 DependentUnaryTransformTypes.InsertNode(Canon, InsertPos);
4841 }
4842 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4843 QualType(), Kind,
4844 QualType(Canon, 0));
4845 } else {
4846 QualType CanonType = getCanonicalType(UnderlyingType);
4847 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4848 UnderlyingType, Kind,
4849 CanonType);
4850 }
4851 Types.push_back(ut);
4852 return QualType(ut, 0);
Alexis Hunte852b102011-05-24 22:41:36 +00004853}
4854
Richard Smith2a7d4812013-05-04 07:00:32 +00004855/// getAutoType - Return the uniqued reference to the 'auto' type which has been
4856/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
4857/// canonical deduced-but-dependent 'auto' type.
Richard Smithe301ba22015-11-11 02:02:15 +00004858QualType ASTContext::getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004859 bool IsDependent) const {
Richard Smithe301ba22015-11-11 02:02:15 +00004860 if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto && !IsDependent)
Richard Smith2a7d4812013-05-04 07:00:32 +00004861 return getAutoDeductType();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004862
Richard Smith2a7d4812013-05-04 07:00:32 +00004863 // Look in the folding set for an existing type.
Craig Topper36250ad2014-05-12 05:36:57 +00004864 void *InsertPos = nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +00004865 llvm::FoldingSetNodeID ID;
Richard Smithe301ba22015-11-11 02:02:15 +00004866 AutoType::Profile(ID, DeducedType, Keyword, IsDependent);
Richard Smith2a7d4812013-05-04 07:00:32 +00004867 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
4868 return QualType(AT, 0);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004869
Eugene Zelenko7855e772018-04-03 00:11:50 +00004870 auto *AT = new (*this, TypeAlignment)
4871 AutoType(DeducedType, Keyword, IsDependent);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004872 Types.push_back(AT);
4873 if (InsertPos)
4874 AutoTypes.InsertNode(AT, InsertPos);
4875 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00004876}
4877
Richard Smith600b5262017-01-26 20:40:47 +00004878/// Return the uniqued reference to the deduced template specialization type
4879/// which has been deduced to the given type, or to the canonical undeduced
4880/// such type, or the canonical deduced-but-dependent such type.
4881QualType ASTContext::getDeducedTemplateSpecializationType(
4882 TemplateName Template, QualType DeducedType, bool IsDependent) const {
4883 // Look in the folding set for an existing type.
4884 void *InsertPos = nullptr;
4885 llvm::FoldingSetNodeID ID;
4886 DeducedTemplateSpecializationType::Profile(ID, Template, DeducedType,
4887 IsDependent);
4888 if (DeducedTemplateSpecializationType *DTST =
4889 DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
4890 return QualType(DTST, 0);
4891
Eugene Zelenko7855e772018-04-03 00:11:50 +00004892 auto *DTST = new (*this, TypeAlignment)
Richard Smith600b5262017-01-26 20:40:47 +00004893 DeducedTemplateSpecializationType(Template, DeducedType, IsDependent);
4894 Types.push_back(DTST);
4895 if (InsertPos)
4896 DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos);
4897 return QualType(DTST, 0);
4898}
4899
Eli Friedman0dfb8892011-10-06 23:00:33 +00004900/// getAtomicType - Return the uniqued reference to the atomic type for
4901/// the given value type.
4902QualType ASTContext::getAtomicType(QualType T) const {
4903 // Unique pointers, to guarantee there is only one pointer of a particular
4904 // structure.
4905 llvm::FoldingSetNodeID ID;
4906 AtomicType::Profile(ID, T);
4907
Craig Topper36250ad2014-05-12 05:36:57 +00004908 void *InsertPos = nullptr;
Eli Friedman0dfb8892011-10-06 23:00:33 +00004909 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
4910 return QualType(AT, 0);
4911
4912 // If the atomic value type isn't canonical, this won't be a canonical type
4913 // either, so fill in the canonical type field.
4914 QualType Canonical;
4915 if (!T.isCanonical()) {
4916 Canonical = getAtomicType(getCanonicalType(T));
4917
4918 // Get the new insert position for the node we care about.
4919 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00004920 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Eli Friedman0dfb8892011-10-06 23:00:33 +00004921 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00004922 auto *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
Eli Friedman0dfb8892011-10-06 23:00:33 +00004923 Types.push_back(New);
4924 AtomicTypes.InsertNode(New, InsertPos);
4925 return QualType(New, 0);
4926}
4927
Richard Smith02e85f32011-04-14 22:09:26 +00004928/// getAutoDeductType - Get type pattern for deducing against 'auto'.
4929QualType ASTContext::getAutoDeductType() const {
4930 if (AutoDeductTy.isNull())
Richard Smith2a7d4812013-05-04 07:00:32 +00004931 AutoDeductTy = QualType(
Richard Smithe301ba22015-11-11 02:02:15 +00004932 new (*this, TypeAlignment) AutoType(QualType(), AutoTypeKeyword::Auto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004933 /*dependent*/false),
Richard Smith2a7d4812013-05-04 07:00:32 +00004934 0);
Richard Smith02e85f32011-04-14 22:09:26 +00004935 return AutoDeductTy;
4936}
4937
4938/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
4939QualType ASTContext::getAutoRRefDeductType() const {
4940 if (AutoRRefDeductTy.isNull())
4941 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
4942 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
4943 return AutoRRefDeductTy;
4944}
4945
Chris Lattnerfb072462007-01-23 05:45:31 +00004946/// getTagDeclType - Return the unique reference to the type for the
4947/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00004948QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004949 assert(Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00004950 // FIXME: What is the design on getTagDeclType when it requires casting
4951 // away const? mutable?
4952 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00004953}
4954
Mike Stump11289f42009-09-09 15:08:12 +00004955/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
4956/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
4957/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00004958CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00004959 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00004960}
Chris Lattnerfb072462007-01-23 05:45:31 +00004961
Fangrui Song6907ce22018-07-30 19:24:48 +00004962/// Return the unique signed counterpart of the integer type
Alexander Shaposhnikov1e898d92017-07-14 17:30:14 +00004963/// corresponding to size_t.
4964CanQualType ASTContext::getSignedSizeType() const {
4965 return getFromTargetType(Target->getSignedSizeType());
4966}
4967
Hans Wennborg27541db2011-10-27 08:29:09 +00004968/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
4969CanQualType ASTContext::getIntMaxType() const {
4970 return getFromTargetType(Target->getIntMaxType());
4971}
4972
4973/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
4974CanQualType ASTContext::getUIntMaxType() const {
4975 return getFromTargetType(Target->getUIntMaxType());
4976}
4977
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00004978/// getSignedWCharType - Return the type of "signed wchar_t".
4979/// Used when in C++, as a GCC extension.
4980QualType ASTContext::getSignedWCharType() const {
4981 // FIXME: derive from "Target" ?
4982 return WCharTy;
4983}
4984
4985/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
4986/// Used when in C++, as a GCC extension.
4987QualType ASTContext::getUnsignedWCharType() const {
4988 // FIXME: derive from "Target" ?
4989 return UnsignedIntTy;
4990}
4991
Enea Zaffanellaf11ceb62013-01-26 17:08:37 +00004992QualType ASTContext::getIntPtrType() const {
4993 return getFromTargetType(Target->getIntPtrType());
4994}
4995
4996QualType ASTContext::getUIntPtrType() const {
4997 return getCorrespondingUnsignedType(getIntPtrType());
4998}
4999
Hans Wennborg27541db2011-10-27 08:29:09 +00005000/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00005001/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
5002QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00005003 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00005004}
5005
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005006/// Return the unique unsigned counterpart of "ptrdiff_t"
Alexander Shaposhnikov195b25c2017-09-28 23:11:31 +00005007/// integer type. The standard (C11 7.21.6.1p7) refers to this type
5008/// in the definition of %tu format specifier.
5009QualType ASTContext::getUnsignedPointerDiffType() const {
5010 return getFromTargetType(Target->getUnsignedPtrDiffType(0));
5011}
5012
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005013/// Return the unique type for "pid_t" defined in
Eli Friedman4e91899e2012-11-27 02:58:24 +00005014/// <sys/types.h>. We need this to compute the correct type for vfork().
5015QualType ASTContext::getProcessIDType() const {
5016 return getFromTargetType(Target->getProcessIDType());
5017}
5018
Chris Lattnera21ad802008-04-02 05:18:44 +00005019//===----------------------------------------------------------------------===//
5020// Type Operators
5021//===----------------------------------------------------------------------===//
5022
Jay Foad39c79802011-01-12 09:06:06 +00005023CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00005024 // Push qualifiers into arrays, and then discard any remaining
5025 // qualifiers.
5026 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00005027 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00005028 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00005029 QualType Result;
5030 if (isa<ArrayType>(Ty)) {
5031 Result = getArrayDecayedType(QualType(Ty,0));
5032 } else if (isa<FunctionType>(Ty)) {
5033 Result = getPointerType(QualType(Ty, 0));
5034 } else {
5035 Result = QualType(Ty, 0);
5036 }
5037
5038 return CanQualType::CreateUnsafe(Result);
5039}
5040
John McCall6c9dd522011-01-18 07:41:22 +00005041QualType ASTContext::getUnqualifiedArrayType(QualType type,
5042 Qualifiers &quals) {
5043 SplitQualType splitType = type.getSplitUnqualifiedType();
5044
5045 // FIXME: getSplitUnqualifiedType() actually walks all the way to
5046 // the unqualified desugared type and then drops it on the floor.
5047 // We then have to strip that sugar back off with
5048 // getUnqualifiedDesugaredType(), which is silly.
Eugene Zelenko7855e772018-04-03 00:11:50 +00005049 const auto *AT =
5050 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00005051
5052 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00005053 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00005054 quals = splitType.Quals;
5055 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00005056 }
5057
John McCall6c9dd522011-01-18 07:41:22 +00005058 // Otherwise, recurse on the array's element type.
5059 QualType elementType = AT->getElementType();
5060 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
5061
5062 // If that didn't change the element type, AT has no qualifiers, so we
5063 // can just use the results in splitType.
5064 if (elementType == unqualElementType) {
5065 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00005066 quals = splitType.Quals;
5067 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00005068 }
5069
5070 // Otherwise, add in the qualifiers from the outermost type, then
5071 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00005072 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00005073
Eugene Zelenko7855e772018-04-03 00:11:50 +00005074 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00005075 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00005076 CAT->getSizeModifier(), 0);
5077 }
5078
Eugene Zelenko7855e772018-04-03 00:11:50 +00005079 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00005080 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00005081 }
5082
Eugene Zelenko7855e772018-04-03 00:11:50 +00005083 if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00005084 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00005085 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00005086 VAT->getSizeModifier(),
5087 VAT->getIndexTypeCVRQualifiers(),
5088 VAT->getBracketsRange());
5089 }
5090
Eugene Zelenko7855e772018-04-03 00:11:50 +00005091 const auto *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00005092 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00005093 DSAT->getSizeModifier(), 0,
5094 SourceRange());
5095}
5096
Richard Smitha3405ff2018-07-11 00:19:19 +00005097/// Attempt to unwrap two types that may both be array types with the same bound
5098/// (or both be array types of unknown bound) for the purpose of comparing the
5099/// cv-decomposition of two types per C++ [conv.qual].
Richard Smith5407d4f2018-07-18 20:13:36 +00005100bool ASTContext::UnwrapSimilarArrayTypes(QualType &T1, QualType &T2) {
5101 bool UnwrappedAny = false;
Richard Smitha3405ff2018-07-11 00:19:19 +00005102 while (true) {
Richard Smith5407d4f2018-07-18 20:13:36 +00005103 auto *AT1 = getAsArrayType(T1);
5104 if (!AT1) return UnwrappedAny;
Richard Smitha3405ff2018-07-11 00:19:19 +00005105
Richard Smith5407d4f2018-07-18 20:13:36 +00005106 auto *AT2 = getAsArrayType(T2);
5107 if (!AT2) return UnwrappedAny;
Richard Smitha3405ff2018-07-11 00:19:19 +00005108
5109 // If we don't have two array types with the same constant bound nor two
5110 // incomplete array types, we've unwrapped everything we can.
5111 if (auto *CAT1 = dyn_cast<ConstantArrayType>(AT1)) {
5112 auto *CAT2 = dyn_cast<ConstantArrayType>(AT2);
5113 if (!CAT2 || CAT1->getSize() != CAT2->getSize())
Richard Smith5407d4f2018-07-18 20:13:36 +00005114 return UnwrappedAny;
Richard Smitha3405ff2018-07-11 00:19:19 +00005115 } else if (!isa<IncompleteArrayType>(AT1) ||
5116 !isa<IncompleteArrayType>(AT2)) {
Richard Smith5407d4f2018-07-18 20:13:36 +00005117 return UnwrappedAny;
Richard Smitha3405ff2018-07-11 00:19:19 +00005118 }
5119
5120 T1 = AT1->getElementType();
5121 T2 = AT2->getElementType();
Richard Smith5407d4f2018-07-18 20:13:36 +00005122 UnwrappedAny = true;
Richard Smitha3405ff2018-07-11 00:19:19 +00005123 }
5124}
5125
5126/// Attempt to unwrap two types that may be similar (C++ [conv.qual]).
5127///
5128/// If T1 and T2 are both pointer types of the same kind, or both array types
5129/// with the same bound, unwraps layers from T1 and T2 until a pointer type is
5130/// unwrapped. Top-level qualifiers on T1 and T2 are ignored.
5131///
5132/// This function will typically be called in a loop that successively
5133/// "unwraps" pointer and pointer-to-member types to compare them at each
5134/// level.
5135///
5136/// \return \c true if a pointer type was unwrapped, \c false if we reached a
5137/// pair of types that can't be unwrapped further.
5138bool ASTContext::UnwrapSimilarTypes(QualType &T1, QualType &T2) {
Richard Smith5407d4f2018-07-18 20:13:36 +00005139 UnwrapSimilarArrayTypes(T1, T2);
Richard Smitha3405ff2018-07-11 00:19:19 +00005140
Eugene Zelenko7855e772018-04-03 00:11:50 +00005141 const auto *T1PtrType = T1->getAs<PointerType>();
5142 const auto *T2PtrType = T2->getAs<PointerType>();
Douglas Gregor1fc3d662010-06-09 03:53:18 +00005143 if (T1PtrType && T2PtrType) {
5144 T1 = T1PtrType->getPointeeType();
5145 T2 = T2PtrType->getPointeeType();
5146 return true;
5147 }
Richard Smith5407d4f2018-07-18 20:13:36 +00005148
Eugene Zelenko7855e772018-04-03 00:11:50 +00005149 const auto *T1MPType = T1->getAs<MemberPointerType>();
5150 const auto *T2MPType = T2->getAs<MemberPointerType>();
Fangrui Song6907ce22018-07-30 19:24:48 +00005151 if (T1MPType && T2MPType &&
5152 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
Douglas Gregor1fc3d662010-06-09 03:53:18 +00005153 QualType(T2MPType->getClass(), 0))) {
5154 T1 = T1MPType->getPointeeType();
5155 T2 = T2MPType->getPointeeType();
5156 return true;
5157 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005158
Erik Pilkingtonfa983902018-10-30 20:31:30 +00005159 if (getLangOpts().ObjC) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00005160 const auto *T1OPType = T1->getAs<ObjCObjectPointerType>();
5161 const auto *T2OPType = T2->getAs<ObjCObjectPointerType>();
Douglas Gregor1fc3d662010-06-09 03:53:18 +00005162 if (T1OPType && T2OPType) {
5163 T1 = T1OPType->getPointeeType();
5164 T2 = T2OPType->getPointeeType();
5165 return true;
5166 }
5167 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005168
Douglas Gregor1fc3d662010-06-09 03:53:18 +00005169 // FIXME: Block pointers, too?
Fangrui Song6907ce22018-07-30 19:24:48 +00005170
Douglas Gregor1fc3d662010-06-09 03:53:18 +00005171 return false;
5172}
5173
Richard Smitha3405ff2018-07-11 00:19:19 +00005174bool ASTContext::hasSimilarType(QualType T1, QualType T2) {
5175 while (true) {
5176 Qualifiers Quals;
5177 T1 = getUnqualifiedArrayType(T1, Quals);
5178 T2 = getUnqualifiedArrayType(T2, Quals);
5179 if (hasSameType(T1, T2))
5180 return true;
5181 if (!UnwrapSimilarTypes(T1, T2))
5182 return false;
5183 }
5184}
5185
5186bool ASTContext::hasCvrSimilarType(QualType T1, QualType T2) {
5187 while (true) {
5188 Qualifiers Quals1, Quals2;
5189 T1 = getUnqualifiedArrayType(T1, Quals1);
5190 T2 = getUnqualifiedArrayType(T2, Quals2);
5191
5192 Quals1.removeCVRQualifiers();
5193 Quals2.removeCVRQualifiers();
5194 if (Quals1 != Quals2)
5195 return false;
5196
5197 if (hasSameType(T1, T2))
5198 return true;
5199
5200 if (!UnwrapSimilarTypes(T1, T2))
5201 return false;
5202 }
5203}
5204
Jay Foad39c79802011-01-12 09:06:06 +00005205DeclarationNameInfo
5206ASTContext::getNameForTemplate(TemplateName Name,
5207 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00005208 switch (Name.getKind()) {
5209 case TemplateName::QualifiedTemplate:
5210 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005211 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00005212 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
5213 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005214
John McCalld9dfe3a2011-06-30 08:33:18 +00005215 case TemplateName::OverloadedTemplate: {
5216 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
5217 // DNInfo work in progress: CHECKME: what about DNLoc?
5218 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
5219 }
5220
5221 case TemplateName::DependentTemplate: {
5222 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005223 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00005224 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005225 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
5226 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00005227 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005228 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
5229 // DNInfo work in progress: FIXME: source locations?
5230 DeclarationNameLoc DNLoc;
5231 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
5232 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
5233 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00005234 }
5235 }
5236
John McCalld9dfe3a2011-06-30 08:33:18 +00005237 case TemplateName::SubstTemplateTemplateParm: {
5238 SubstTemplateTemplateParmStorage *subst
5239 = Name.getAsSubstTemplateTemplateParm();
5240 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
5241 NameLoc);
5242 }
5243
5244 case TemplateName::SubstTemplateTemplateParmPack: {
5245 SubstTemplateTemplateParmPackStorage *subst
5246 = Name.getAsSubstTemplateTemplateParmPack();
5247 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
5248 NameLoc);
5249 }
5250 }
5251
5252 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00005253}
5254
Jay Foad39c79802011-01-12 09:06:06 +00005255TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00005256 switch (Name.getKind()) {
5257 case TemplateName::QualifiedTemplate:
5258 case TemplateName::Template: {
5259 TemplateDecl *Template = Name.getAsTemplateDecl();
Eugene Zelenko7855e772018-04-03 00:11:50 +00005260 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00005261 Template = getCanonicalTemplateTemplateParmDecl(TTP);
Fangrui Song6907ce22018-07-30 19:24:48 +00005262
Douglas Gregor7dbfb462010-06-16 21:09:37 +00005263 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00005264 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00005265 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00005266
John McCalld9dfe3a2011-06-30 08:33:18 +00005267 case TemplateName::OverloadedTemplate:
5268 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00005269
John McCalld9dfe3a2011-06-30 08:33:18 +00005270 case TemplateName::DependentTemplate: {
5271 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
5272 assert(DTN && "Non-dependent template names must refer to template decls.");
5273 return DTN->CanonicalTemplateName;
5274 }
5275
5276 case TemplateName::SubstTemplateTemplateParm: {
5277 SubstTemplateTemplateParmStorage *subst
5278 = Name.getAsSubstTemplateTemplateParm();
5279 return getCanonicalTemplateName(subst->getReplacement());
5280 }
5281
5282 case TemplateName::SubstTemplateTemplateParmPack: {
5283 SubstTemplateTemplateParmPackStorage *subst
5284 = Name.getAsSubstTemplateTemplateParmPack();
5285 TemplateTemplateParmDecl *canonParameter
5286 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
5287 TemplateArgument canonArgPack
5288 = getCanonicalTemplateArgument(subst->getArgumentPack());
5289 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
5290 }
5291 }
5292
5293 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00005294}
5295
Douglas Gregoradee3e32009-11-11 23:06:43 +00005296bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
5297 X = getCanonicalTemplateName(X);
5298 Y = getCanonicalTemplateName(Y);
5299 return X.getAsVoidPointer() == Y.getAsVoidPointer();
5300}
5301
Mike Stump11289f42009-09-09 15:08:12 +00005302TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00005303ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00005304 switch (Arg.getKind()) {
5305 case TemplateArgument::Null:
5306 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00005307
Douglas Gregora8e02e72009-07-28 23:00:59 +00005308 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00005309 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00005310
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005311 case TemplateArgument::Declaration: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00005312 auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
David Blaikie952a9b12014-10-17 18:00:12 +00005313 return TemplateArgument(D, Arg.getParamTypeForDecl());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005314 }
Mike Stump11289f42009-09-09 15:08:12 +00005315
Eli Friedmanb826a002012-09-26 02:36:12 +00005316 case TemplateArgument::NullPtr:
5317 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
5318 /*isNullPtr*/true);
5319
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005320 case TemplateArgument::Template:
5321 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005322
5323 case TemplateArgument::TemplateExpansion:
5324 return TemplateArgument(getCanonicalTemplateName(
5325 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00005326 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005327
Douglas Gregora8e02e72009-07-28 23:00:59 +00005328 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00005329 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00005330
Douglas Gregora8e02e72009-07-28 23:00:59 +00005331 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00005332 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00005333
Douglas Gregora8e02e72009-07-28 23:00:59 +00005334 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00005335 if (Arg.pack_size() == 0)
5336 return Arg;
Fangrui Song6907ce22018-07-30 19:24:48 +00005337
Eugene Zelenko7855e772018-04-03 00:11:50 +00005338 auto *CanonArgs = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00005339 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00005340 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00005341 AEnd = Arg.pack_end();
5342 A != AEnd; (void)++A, ++Idx)
5343 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00005344
Benjamin Kramercce63472015-08-05 09:40:22 +00005345 return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size()));
Douglas Gregora8e02e72009-07-28 23:00:59 +00005346 }
5347 }
5348
5349 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00005350 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00005351}
5352
Douglas Gregor333489b2009-03-27 23:10:48 +00005353NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00005354ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00005355 if (!NNS)
Craig Topper36250ad2014-05-12 05:36:57 +00005356 return nullptr;
Douglas Gregor333489b2009-03-27 23:10:48 +00005357
5358 switch (NNS->getKind()) {
5359 case NestedNameSpecifier::Identifier:
5360 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00005361 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00005362 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
5363 NNS->getAsIdentifier());
5364
5365 case NestedNameSpecifier::Namespace:
5366 // A namespace is canonical; build a nested-name-specifier with
5367 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00005368 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00005369 NNS->getAsNamespace()->getOriginalNamespace());
5370
5371 case NestedNameSpecifier::NamespaceAlias:
5372 // A namespace is canonical; build a nested-name-specifier with
5373 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00005374 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00005375 NNS->getAsNamespaceAlias()->getNamespace()
5376 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00005377
5378 case NestedNameSpecifier::TypeSpec:
5379 case NestedNameSpecifier::TypeSpecWithTemplate: {
5380 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Fangrui Song6907ce22018-07-30 19:24:48 +00005381
Douglas Gregor3ade5702010-11-04 00:09:33 +00005382 // If we have some kind of dependent-named type (e.g., "typename T::type"),
5383 // break it apart into its prefix and identifier, then reconsititute those
5384 // as the canonical nested-name-specifier. This is required to canonicalize
5385 // a dependent nested-name-specifier involving typedefs of dependent-name
5386 // types, e.g.,
5387 // typedef typename T::type T1;
5388 // typedef typename T1::type T2;
Eugene Zelenko7855e772018-04-03 00:11:50 +00005389 if (const auto *DNT = T->getAs<DependentNameType>())
Fangrui Song6907ce22018-07-30 19:24:48 +00005390 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00005391 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00005392
Eli Friedman5358a0a2012-03-03 04:09:56 +00005393 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
5394 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
5395 // first place?
Craig Topper36250ad2014-05-12 05:36:57 +00005396 return NestedNameSpecifier::Create(*this, nullptr, false,
5397 const_cast<Type *>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00005398 }
5399
5400 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00005401 case NestedNameSpecifier::Super:
5402 // The global specifier and __super specifer are canonical and unique.
Douglas Gregor333489b2009-03-27 23:10:48 +00005403 return NNS;
5404 }
5405
David Blaikie8a40f702012-01-17 06:56:22 +00005406 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00005407}
5408
Jay Foad39c79802011-01-12 09:06:06 +00005409const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00005410 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005411 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00005412 // Handle the common positive case fast.
Eugene Zelenko7855e772018-04-03 00:11:50 +00005413 if (const auto *AT = dyn_cast<ArrayType>(T))
Chris Lattner7adf0762008-08-04 07:31:14 +00005414 return AT;
5415 }
Mike Stump11289f42009-09-09 15:08:12 +00005416
John McCall8ccfcb52009-09-24 19:53:00 +00005417 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00005418 if (!isa<ArrayType>(T.getCanonicalType()))
Craig Topper36250ad2014-05-12 05:36:57 +00005419 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00005420
John McCall8ccfcb52009-09-24 19:53:00 +00005421 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00005422 // implements C99 6.7.3p8: "If the specification of an array type includes
5423 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00005424
Chris Lattner7adf0762008-08-04 07:31:14 +00005425 // If we get here, we either have type qualifiers on the type, or we have
5426 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00005427 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00005428
John McCall33ddac02011-01-19 10:06:00 +00005429 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00005430 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00005431
Chris Lattner7adf0762008-08-04 07:31:14 +00005432 // If we have a simple case, just return now.
Eugene Zelenko7855e772018-04-03 00:11:50 +00005433 const auto *ATy = dyn_cast<ArrayType>(split.Ty);
Craig Topper36250ad2014-05-12 05:36:57 +00005434 if (!ATy || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00005435 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00005436
Chris Lattner7adf0762008-08-04 07:31:14 +00005437 // Otherwise, we have an array and we have qualifiers on it. Push the
5438 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00005439 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00005440
Eugene Zelenko7855e772018-04-03 00:11:50 +00005441 if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy))
Chris Lattner7adf0762008-08-04 07:31:14 +00005442 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
5443 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00005444 CAT->getIndexTypeCVRQualifiers()));
Eugene Zelenko7855e772018-04-03 00:11:50 +00005445 if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy))
Chris Lattner7adf0762008-08-04 07:31:14 +00005446 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
5447 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00005448 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00005449
Eugene Zelenko7855e772018-04-03 00:11:50 +00005450 if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy))
Douglas Gregor4619e432008-12-05 23:32:09 +00005451 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00005452 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00005453 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00005454 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00005455 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00005456 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00005457
Eugene Zelenko7855e772018-04-03 00:11:50 +00005458 const auto *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00005459 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00005460 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00005461 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00005462 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00005463 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00005464}
5465
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00005466QualType ASTContext::getAdjustedParameterType(QualType T) const {
Reid Kleckner8a365022013-06-24 17:51:48 +00005467 if (T->isArrayType() || T->isFunctionType())
5468 return getDecayedType(T);
5469 return T;
Douglas Gregor84280642011-07-12 04:42:08 +00005470}
5471
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00005472QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00005473 T = getVariableArrayDecayedType(T);
5474 T = getAdjustedParameterType(T);
5475 return T.getUnqualifiedType();
5476}
5477
David Majnemerd09a51c2015-03-03 01:50:05 +00005478QualType ASTContext::getExceptionObjectType(QualType T) const {
5479 // C++ [except.throw]p3:
5480 // A throw-expression initializes a temporary object, called the exception
5481 // object, the type of which is determined by removing any top-level
5482 // cv-qualifiers from the static type of the operand of throw and adjusting
5483 // the type from "array of T" or "function returning T" to "pointer to T"
5484 // or "pointer to function returning T", [...]
5485 T = getVariableArrayDecayedType(T);
5486 if (T->isArrayType() || T->isFunctionType())
5487 T = getDecayedType(T);
5488 return T.getUnqualifiedType();
5489}
5490
Chris Lattnera21ad802008-04-02 05:18:44 +00005491/// getArrayDecayedType - Return the properly qualified result of decaying the
5492/// specified array type to a pointer. This operation is non-trivial when
5493/// handling typedefs etc. The canonical type of "T" must be an array type,
5494/// this returns a pointer to a properly qualified element of the array.
5495///
5496/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00005497QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00005498 // Get the element type with 'getAsArrayType' so that we don't lose any
5499 // typedefs in the element type of the array. This also handles propagation
5500 // of type qualifiers from the array type into the element type if present
5501 // (C99 6.7.3p8).
5502 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
5503 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00005504
Chris Lattner7adf0762008-08-04 07:31:14 +00005505 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00005506
5507 // int x[restrict 4] -> int *restrict
Jordan Rose303e2f12016-11-10 23:28:17 +00005508 QualType Result = getQualifiedType(PtrTy,
5509 PrettyArrayType->getIndexTypeQualifiers());
5510
5511 // int x[_Nullable] -> int * _Nullable
5512 if (auto Nullability = Ty->getNullability(*this)) {
5513 Result = const_cast<ASTContext *>(this)->getAttributedType(
5514 AttributedType::getNullabilityAttrKind(*Nullability), Result, Result);
5515 }
5516 return Result;
Chris Lattnera21ad802008-04-02 05:18:44 +00005517}
5518
John McCall33ddac02011-01-19 10:06:00 +00005519QualType ASTContext::getBaseElementType(const ArrayType *array) const {
5520 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00005521}
5522
John McCall33ddac02011-01-19 10:06:00 +00005523QualType ASTContext::getBaseElementType(QualType type) const {
5524 Qualifiers qs;
5525 while (true) {
5526 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00005527 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00005528 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00005529
John McCall33ddac02011-01-19 10:06:00 +00005530 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00005531 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00005532 }
Mike Stump11289f42009-09-09 15:08:12 +00005533
John McCall33ddac02011-01-19 10:06:00 +00005534 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00005535}
5536
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00005537/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00005538uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00005539ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
5540 uint64_t ElementCount = 1;
5541 do {
5542 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00005543 CA = dyn_cast_or_null<ConstantArrayType>(
5544 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00005545 } while (CA);
5546 return ElementCount;
5547}
5548
Steve Naroff0af91202007-04-27 21:51:21 +00005549/// getFloatingRank - Return a relative rank for floating point types.
5550/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00005551static FloatingRank getFloatingRank(QualType T) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00005552 if (const auto *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00005553 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00005554
John McCall9dd450b2009-09-21 23:43:11 +00005555 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
5556 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00005557 default: llvm_unreachable("getFloatingRank(): not a floating type");
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00005558 case BuiltinType::Float16: return Float16Rank;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00005559 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00005560 case BuiltinType::Float: return FloatRank;
5561 case BuiltinType::Double: return DoubleRank;
5562 case BuiltinType::LongDouble: return LongDoubleRank;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005563 case BuiltinType::Float128: return Float128Rank;
Steve Naroffe4718892007-04-27 18:30:00 +00005564 }
5565}
5566
Mike Stump11289f42009-09-09 15:08:12 +00005567/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
5568/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00005569/// 'typeDomain' is a real floating point or complex type.
5570/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00005571QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
5572 QualType Domain) const {
5573 FloatingRank EltRank = getFloatingRank(Size);
5574 if (Domain->isComplexType()) {
5575 switch (EltRank) {
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00005576 case Float16Rank:
David Blaikief47fa302012-01-17 02:30:50 +00005577 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00005578 case FloatRank: return FloatComplexTy;
5579 case DoubleRank: return DoubleComplexTy;
5580 case LongDoubleRank: return LongDoubleComplexTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005581 case Float128Rank: return Float128ComplexTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00005582 }
Steve Naroff0af91202007-04-27 21:51:21 +00005583 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00005584
5585 assert(Domain->isRealFloatingType() && "Unknown domain!");
5586 switch (EltRank) {
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00005587 case Float16Rank: return HalfTy;
Joey Goulydd7f4562013-01-23 11:56:20 +00005588 case HalfRank: return HalfTy;
Chris Lattnerb9dfb032008-04-06 23:58:54 +00005589 case FloatRank: return FloatTy;
5590 case DoubleRank: return DoubleTy;
5591 case LongDoubleRank: return LongDoubleTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005592 case Float128Rank: return Float128Ty;
Steve Naroff9091ef72007-08-27 01:27:54 +00005593 }
David Blaikief47fa302012-01-17 02:30:50 +00005594 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00005595}
5596
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005597/// getFloatingTypeOrder - Compare the rank of the two specified floating
5598/// point types, ignoring the domain of the type (i.e. 'double' ==
5599/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00005600/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00005601int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00005602 FloatingRank LHSR = getFloatingRank(LHS);
5603 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00005604
Chris Lattnerb90739d2008-04-06 23:38:49 +00005605 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00005606 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00005607 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00005608 return 1;
5609 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00005610}
5611
Chris Lattner76a00cf2008-04-06 22:59:24 +00005612/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
5613/// routine will assert if passed a built-in type that isn't an integer or enum,
5614/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00005615unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00005616 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00005617
Chris Lattner76a00cf2008-04-06 22:59:24 +00005618 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00005619 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005620 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005621 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005622 case BuiltinType::Char_S:
5623 case BuiltinType::Char_U:
5624 case BuiltinType::SChar:
5625 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005626 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005627 case BuiltinType::Short:
5628 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005629 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005630 case BuiltinType::Int:
5631 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005632 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005633 case BuiltinType::Long:
5634 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005635 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005636 case BuiltinType::LongLong:
5637 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005638 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00005639 case BuiltinType::Int128:
5640 case BuiltinType::UInt128:
5641 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00005642 }
5643}
5644
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005645/// Whether this is a promotable bitfield reference according
Eli Friedman629ffb92009-08-20 04:21:42 +00005646/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
5647///
5648/// \returns the type this bit-field will promote to, or NULL if no
5649/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00005650QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00005651 if (E->isTypeDependent() || E->isValueDependent())
Eugene Zelenko7855e772018-04-03 00:11:50 +00005652 return {};
Richard Smith5b571672014-09-24 23:55:00 +00005653
Richard Smithaadb2542018-06-28 21:17:55 +00005654 // C++ [conv.prom]p5:
5655 // If the bit-field has an enumerated type, it is treated as any other
5656 // value of that type for promotion purposes.
5657 if (getLangOpts().CPlusPlus && E->getType()->isEnumeralType())
5658 return {};
5659
Richard Smith5b571672014-09-24 23:55:00 +00005660 // FIXME: We should not do this unless E->refersToBitField() is true. This
5661 // matters in C where getSourceBitField() will find bit-fields for various
5662 // cases where the source expression is not a bit-field designator.
5663
John McCalld25db7e2013-05-06 21:39:12 +00005664 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman629ffb92009-08-20 04:21:42 +00005665 if (!Field)
Eugene Zelenko7855e772018-04-03 00:11:50 +00005666 return {};
Eli Friedman629ffb92009-08-20 04:21:42 +00005667
5668 QualType FT = Field->getType();
5669
Richard Smithcaf33902011-10-10 18:28:20 +00005670 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00005671 uint64_t IntSize = getTypeSize(IntTy);
Richard Smith5b571672014-09-24 23:55:00 +00005672 // C++ [conv.prom]p5:
5673 // A prvalue for an integral bit-field can be converted to a prvalue of type
5674 // int if int can represent all the values of the bit-field; otherwise, it
5675 // can be converted to unsigned int if unsigned int can represent all the
5676 // values of the bit-field. If the bit-field is larger yet, no integral
5677 // promotion applies to it.
5678 // C11 6.3.1.1/2:
5679 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
5680 // If an int can represent all values of the original type (as restricted by
5681 // the width, for a bit-field), the value is converted to an int; otherwise,
5682 // it is converted to an unsigned int.
5683 //
5684 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
5685 // We perform that promotion here to match GCC and C++.
Richard Smithaadb2542018-06-28 21:17:55 +00005686 // FIXME: C does not permit promotion of an enum bit-field whose rank is
5687 // greater than that of 'int'. We perform that promotion to match GCC.
Eli Friedman629ffb92009-08-20 04:21:42 +00005688 if (BitWidth < IntSize)
5689 return IntTy;
5690
5691 if (BitWidth == IntSize)
5692 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
5693
Richard Smithaadb2542018-06-28 21:17:55 +00005694 // Bit-fields wider than int are not subject to promotions, and therefore act
Richard Smith5b571672014-09-24 23:55:00 +00005695 // like the base type. GCC has some weird bugs in this area that we
5696 // deliberately do not follow (GCC follows a pre-standard resolution to
5697 // C's DR315 which treats bit-width as being part of the type, and this leaks
5698 // into their semantics in some cases).
Eugene Zelenko7855e772018-04-03 00:11:50 +00005699 return {};
Eli Friedman629ffb92009-08-20 04:21:42 +00005700}
5701
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005702/// getPromotedIntegerType - Returns the type that Promotable will
5703/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
5704/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00005705QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005706 assert(!Promotable.isNull());
5707 assert(Promotable->isPromotableIntegerType());
Eugene Zelenko7855e772018-04-03 00:11:50 +00005708 if (const auto *ET = Promotable->getAs<EnumType>())
John McCall56774992009-12-09 09:09:27 +00005709 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00005710
Eugene Zelenko7855e772018-04-03 00:11:50 +00005711 if (const auto *BT = Promotable->getAs<BuiltinType>()) {
Eli Friedman3f37c1c2011-10-26 07:22:48 +00005712 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
5713 // (3.9.1) can be converted to a prvalue of the first of the following
5714 // types that can represent all the values of its underlying type:
5715 // int, unsigned int, long int, unsigned long int, long long int, or
5716 // unsigned long long int [...]
5717 // FIXME: Is there some better way to compute this?
5718 if (BT->getKind() == BuiltinType::WChar_S ||
5719 BT->getKind() == BuiltinType::WChar_U ||
Richard Smith3a8244d2018-05-01 05:02:45 +00005720 BT->getKind() == BuiltinType::Char8 ||
Eli Friedman3f37c1c2011-10-26 07:22:48 +00005721 BT->getKind() == BuiltinType::Char16 ||
5722 BT->getKind() == BuiltinType::Char32) {
5723 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
5724 uint64_t FromSize = getTypeSize(BT);
5725 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
5726 LongLongTy, UnsignedLongLongTy };
5727 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
5728 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
5729 if (FromSize < ToSize ||
5730 (FromSize == ToSize &&
5731 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
5732 return PromoteTypes[Idx];
5733 }
5734 llvm_unreachable("char type should fit into long long");
5735 }
5736 }
5737
5738 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005739 if (Promotable->isSignedIntegerType())
5740 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00005741 uint64_t PromotableSize = getIntWidth(Promotable);
5742 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005743 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
5744 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
5745}
5746
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005747/// Recurses in pointer/array types until it finds an objc retainable
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00005748/// type and returns its ownership.
5749Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
5750 while (!T.isNull()) {
5751 if (T.getObjCLifetime() != Qualifiers::OCL_None)
5752 return T.getObjCLifetime();
5753 if (T->isArrayType())
5754 T = getBaseElementType(T);
Eugene Zelenko7855e772018-04-03 00:11:50 +00005755 else if (const auto *PT = T->getAs<PointerType>())
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00005756 T = PT->getPointeeType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00005757 else if (const auto *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00005758 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00005759 else
5760 break;
5761 }
5762
5763 return Qualifiers::OCL_None;
5764}
5765
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005766static const Type *getIntegerTypeForEnum(const EnumType *ET) {
5767 // Incomplete enum types are not treated as integer types.
5768 // FIXME: In C++, enum types are never integer types.
5769 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
5770 return ET->getDecl()->getIntegerType().getTypePtr();
Craig Topper36250ad2014-05-12 05:36:57 +00005771 return nullptr;
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005772}
5773
Mike Stump11289f42009-09-09 15:08:12 +00005774/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005775/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00005776/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00005777int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00005778 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
5779 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005780
5781 // Unwrap enums to their underlying type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00005782 if (const auto *ET = dyn_cast<EnumType>(LHSC))
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005783 LHSC = getIntegerTypeForEnum(ET);
Eugene Zelenko7855e772018-04-03 00:11:50 +00005784 if (const auto *ET = dyn_cast<EnumType>(RHSC))
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005785 RHSC = getIntegerTypeForEnum(ET);
5786
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005787 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00005788
Chris Lattner76a00cf2008-04-06 22:59:24 +00005789 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
5790 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00005791
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005792 unsigned LHSRank = getIntegerRank(LHSC);
5793 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00005794
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005795 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
5796 if (LHSRank == RHSRank) return 0;
5797 return LHSRank > RHSRank ? 1 : -1;
5798 }
Mike Stump11289f42009-09-09 15:08:12 +00005799
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005800 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
5801 if (LHSUnsigned) {
5802 // If the unsigned [LHS] type is larger, return it.
5803 if (LHSRank >= RHSRank)
5804 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00005805
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005806 // If the signed type can represent all values of the unsigned type, it
5807 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00005808 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005809 return -1;
5810 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00005811
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005812 // If the unsigned [RHS] type is larger, return it.
5813 if (RHSRank >= LHSRank)
5814 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00005815
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005816 // If the signed type can represent all values of the unsigned type, it
5817 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00005818 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005819 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00005820}
Anders Carlsson98f07902007-08-17 05:31:46 +00005821
Ben Langmuirf5416742016-02-04 00:55:24 +00005822TypedefDecl *ASTContext::getCFConstantStringDecl() const {
Saleem Abdulrasoolef9b88a2018-10-24 16:38:16 +00005823 if (CFConstantStringTypeDecl)
5824 return CFConstantStringTypeDecl;
Anders Carlsson6d417272009-11-14 21:45:58 +00005825
Saleem Abdulrasoolef9b88a2018-10-24 16:38:16 +00005826 assert(!CFConstantStringTagDecl &&
5827 "tag and typedef should be initialized together");
5828 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
5829 CFConstantStringTagDecl->startDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00005830
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00005831 struct {
5832 QualType Type;
5833 const char *Name;
5834 } Fields[5];
5835 unsigned Count = 0;
Mike Stump11289f42009-09-09 15:08:12 +00005836
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00005837 /// Objective-C ABI
5838 ///
5839 /// typedef struct __NSConstantString_tag {
Saleem Abdulrasool1f6c41f2018-10-27 06:12:52 +00005840 /// const int *isa;
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00005841 /// int flags;
5842 /// const char *str;
5843 /// long length;
5844 /// } __NSConstantString;
5845 ///
5846 /// Swift ABI (4.1, 4.2)
5847 ///
5848 /// typedef struct __NSConstantString_tag {
5849 /// uintptr_t _cfisa;
5850 /// uintptr_t _swift_rc;
5851 /// _Atomic(uint64_t) _cfinfoa;
5852 /// const char *_ptr;
5853 /// uint32_t _length;
5854 /// } __NSConstantString;
5855 ///
5856 /// Swift ABI (5.0)
5857 ///
5858 /// typedef struct __NSConstantString_tag {
5859 /// uintptr_t _cfisa;
5860 /// uintptr_t _swift_rc;
5861 /// _Atomic(uint64_t) _cfinfoa;
5862 /// const char *_ptr;
5863 /// uintptr_t _length;
5864 /// } __NSConstantString;
5865
5866 const auto CFRuntime = getLangOpts().CFRuntime;
5867 if (static_cast<unsigned>(CFRuntime) <
5868 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) {
5869 Fields[Count++] = { getPointerType(IntTy.withConst()), "isa" };
5870 Fields[Count++] = { IntTy, "flags" };
5871 Fields[Count++] = { getPointerType(CharTy.withConst()), "str" };
5872 Fields[Count++] = { LongTy, "length" };
5873 } else {
5874 Fields[Count++] = { getUIntPtrType(), "_cfisa" };
5875 Fields[Count++] = { getUIntPtrType(), "_swift_rc" };
5876 Fields[Count++] = { getFromTargetType(Target->getUInt64Type()), "_swift_rc" };
5877 Fields[Count++] = { getPointerType(CharTy.withConst()), "_ptr" };
5878 if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 ||
5879 CFRuntime == LangOptions::CoreFoundationABI::Swift4_2)
5880 Fields[Count++] = { IntTy, "_ptr" };
5881 else
5882 Fields[Count++] = { getUIntPtrType(), "_ptr" };
5883 }
Douglas Gregor91f84212008-12-11 16:49:14 +00005884
Saleem Abdulrasoolef9b88a2018-10-24 16:38:16 +00005885 // Create fields
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00005886 for (unsigned i = 0; i < Count; ++i) {
Saleem Abdulrasoolef9b88a2018-10-24 16:38:16 +00005887 FieldDecl *Field =
5888 FieldDecl::Create(*this, CFConstantStringTagDecl, SourceLocation(),
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00005889 SourceLocation(), &Idents.get(Fields[i].Name),
5890 Fields[i].Type, /*TInfo=*/nullptr,
Saleem Abdulrasoolef9b88a2018-10-24 16:38:16 +00005891 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
5892 Field->setAccess(AS_public);
5893 CFConstantStringTagDecl->addDecl(Field);
Anders Carlsson98f07902007-08-17 05:31:46 +00005894 }
Mike Stump11289f42009-09-09 15:08:12 +00005895
Saleem Abdulrasoolef9b88a2018-10-24 16:38:16 +00005896 CFConstantStringTagDecl->completeDefinition();
5897 // This type is designed to be compatible with NSConstantString, but cannot
5898 // use the same name, since NSConstantString is an interface.
5899 auto tagType = getTagDeclType(CFConstantStringTagDecl);
5900 CFConstantStringTypeDecl =
5901 buildImplicitTypedef(tagType, "__NSConstantString");
5902
Quentin Colombet043406b2016-02-03 22:41:00 +00005903 return CFConstantStringTypeDecl;
5904}
5905
Ben Langmuirf5416742016-02-04 00:55:24 +00005906RecordDecl *ASTContext::getCFConstantStringTagDecl() const {
5907 if (!CFConstantStringTagDecl)
5908 getCFConstantStringDecl(); // Build the tag and the typedef.
5909 return CFConstantStringTagDecl;
5910}
5911
Quentin Colombet043406b2016-02-03 22:41:00 +00005912// getCFConstantStringType - Return the type used for constant CFStrings.
5913QualType ASTContext::getCFConstantStringType() const {
Ben Langmuirf5416742016-02-04 00:55:24 +00005914 return getTypedefType(getCFConstantStringDecl());
Gabor Greif412af032007-09-11 15:32:40 +00005915}
Anders Carlsson87c149b2007-10-11 01:00:40 +00005916
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00005917QualType ASTContext::getObjCSuperType() const {
5918 if (ObjCSuperType.isNull()) {
Alp Toker2dea15b2013-12-17 01:22:38 +00005919 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00005920 TUDecl->addDecl(ObjCSuperTypeDecl);
5921 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
5922 }
5923 return ObjCSuperType;
5924}
5925
Douglas Gregor512b0772009-04-23 22:29:11 +00005926void ASTContext::setCFConstantStringType(QualType T) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00005927 const auto *TD = T->getAs<TypedefType>();
Ben Langmuirf5416742016-02-04 00:55:24 +00005928 assert(TD && "Invalid CFConstantStringType");
5929 CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl());
Eugene Zelenko7855e772018-04-03 00:11:50 +00005930 const auto *TagType =
Ben Langmuirf5416742016-02-04 00:55:24 +00005931 CFConstantStringTypeDecl->getUnderlyingType()->getAs<RecordType>();
5932 assert(TagType && "Invalid CFConstantStringType");
5933 CFConstantStringTagDecl = TagType->getDecl();
Douglas Gregor512b0772009-04-23 22:29:11 +00005934}
5935
Jay Foad39c79802011-01-12 09:06:06 +00005936QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00005937 if (BlockDescriptorType)
5938 return getTagDeclType(BlockDescriptorType);
5939
Alp Toker2dea15b2013-12-17 01:22:38 +00005940 RecordDecl *RD;
Mike Stumpd0153282009-10-20 02:12:22 +00005941 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00005942 RD = buildImplicitRecord("__block_descriptor");
5943 RD->startDefinition();
5944
Mike Stumpd0153282009-10-20 02:12:22 +00005945 QualType FieldTypes[] = {
5946 UnsignedLongTy,
5947 UnsignedLongTy,
5948 };
5949
Craig Topperd6d31ac2013-07-15 08:24:27 +00005950 static const char *const FieldNames[] = {
Mike Stumpd0153282009-10-20 02:12:22 +00005951 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005952 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00005953 };
5954
5955 for (size_t i = 0; i < 2; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00005956 FieldDecl *Field = FieldDecl::Create(
5957 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00005958 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
5959 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00005960 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00005961 RD->addDecl(Field);
Mike Stumpd0153282009-10-20 02:12:22 +00005962 }
5963
Alp Toker2dea15b2013-12-17 01:22:38 +00005964 RD->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00005965
Alp Toker2dea15b2013-12-17 01:22:38 +00005966 BlockDescriptorType = RD;
Mike Stumpd0153282009-10-20 02:12:22 +00005967
5968 return getTagDeclType(BlockDescriptorType);
5969}
5970
Jay Foad39c79802011-01-12 09:06:06 +00005971QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005972 if (BlockDescriptorExtendedType)
5973 return getTagDeclType(BlockDescriptorExtendedType);
5974
Alp Toker2dea15b2013-12-17 01:22:38 +00005975 RecordDecl *RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005976 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00005977 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
5978 RD->startDefinition();
5979
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005980 QualType FieldTypes[] = {
5981 UnsignedLongTy,
5982 UnsignedLongTy,
5983 getPointerType(VoidPtrTy),
5984 getPointerType(VoidPtrTy)
5985 };
5986
Craig Topperd6d31ac2013-07-15 08:24:27 +00005987 static const char *const FieldNames[] = {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005988 "reserved",
5989 "Size",
5990 "CopyFuncPtr",
5991 "DestroyFuncPtr"
5992 };
5993
5994 for (size_t i = 0; i < 4; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00005995 FieldDecl *Field = FieldDecl::Create(
5996 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00005997 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
5998 /*BitWidth=*/nullptr,
Alp Toker2dea15b2013-12-17 01:22:38 +00005999 /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00006000 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00006001 RD->addDecl(Field);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00006002 }
6003
Alp Toker2dea15b2013-12-17 01:22:38 +00006004 RD->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00006005
Alp Toker2dea15b2013-12-17 01:22:38 +00006006 BlockDescriptorExtendedType = RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00006007 return getTagDeclType(BlockDescriptorExtendedType);
6008}
6009
Sven van Haastregt3bb7eaf2017-12-06 10:11:28 +00006010TargetInfo::OpenCLTypeKind ASTContext::getOpenCLTypeKind(const Type *T) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006011 const auto *BT = dyn_cast<BuiltinType>(T);
Sven van Haastregt3bb7eaf2017-12-06 10:11:28 +00006012
6013 if (!BT) {
6014 if (isa<PipeType>(T))
6015 return TargetInfo::OCLTK_Pipe;
6016
6017 return TargetInfo::OCLTK_Default;
6018 }
6019
6020 switch (BT->getKind()) {
6021#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6022 case BuiltinType::Id: \
6023 return TargetInfo::OCLTK_Image;
6024#include "clang/Basic/OpenCLImageTypes.def"
6025
6026 case BuiltinType::OCLClkEvent:
6027 return TargetInfo::OCLTK_ClkEvent;
6028
6029 case BuiltinType::OCLEvent:
6030 return TargetInfo::OCLTK_Event;
6031
6032 case BuiltinType::OCLQueue:
6033 return TargetInfo::OCLTK_Queue;
6034
6035 case BuiltinType::OCLReserveID:
6036 return TargetInfo::OCLTK_ReserveID;
6037
6038 case BuiltinType::OCLSampler:
6039 return TargetInfo::OCLTK_Sampler;
6040
6041 default:
6042 return TargetInfo::OCLTK_Default;
6043 }
6044}
6045
6046LangAS ASTContext::getOpenCLTypeAddrSpace(const Type *T) const {
6047 return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
6048}
6049
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006050/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
6051/// requires copy/dispose. Note that this must match the logic
6052/// in buildByrefHelpers.
6053bool ASTContext::BlockRequiresCopying(QualType Ty,
6054 const VarDecl *D) {
6055 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
Akira Hatanaka9978da32018-08-10 15:09:24 +00006056 const Expr *copyExpr = getBlockVarCopyInit(D).getCopyExpr();
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006057 if (!copyExpr && record->hasTrivialDestructor()) return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00006058
Mike Stump94967902009-10-21 18:16:27 +00006059 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00006060 }
Fangrui Song6907ce22018-07-30 19:24:48 +00006061
Akira Hatanaka7275da02018-02-28 07:15:55 +00006062 // The block needs copy/destroy helpers if Ty is non-trivial to destructively
6063 // move or destroy.
6064 if (Ty.isNonTrivialToPrimitiveDestructiveMove() || Ty.isDestructedType())
6065 return true;
6066
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006067 if (!Ty->isObjCRetainableType()) return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00006068
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006069 Qualifiers qs = Ty.getQualifiers();
Fangrui Song6907ce22018-07-30 19:24:48 +00006070
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006071 // If we have lifetime, that dominates.
6072 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006073 switch (lifetime) {
6074 case Qualifiers::OCL_None: llvm_unreachable("impossible");
Fangrui Song6907ce22018-07-30 19:24:48 +00006075
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006076 // These are just bits as far as the runtime is concerned.
6077 case Qualifiers::OCL_ExplicitNone:
6078 case Qualifiers::OCL_Autoreleasing:
6079 return false;
Akira Hatanaka7275da02018-02-28 07:15:55 +00006080
6081 // These cases should have been taken care of when checking the type's
6082 // non-triviality.
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006083 case Qualifiers::OCL_Weak:
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006084 case Qualifiers::OCL_Strong:
Akira Hatanaka7275da02018-02-28 07:15:55 +00006085 llvm_unreachable("impossible");
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006086 }
6087 llvm_unreachable("fell out of lifetime switch!");
6088 }
6089 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
6090 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00006091}
6092
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006093bool ASTContext::getByrefLifetime(QualType Ty,
6094 Qualifiers::ObjCLifetime &LifeTime,
6095 bool &HasByrefExtendedLayout) const {
Erik Pilkingtonfa983902018-10-30 20:31:30 +00006096 if (!getLangOpts().ObjC ||
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006097 getLangOpts().getGC() != LangOptions::NonGC)
6098 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00006099
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006100 HasByrefExtendedLayout = false;
Fariborz Jahanianf762b722012-12-11 19:58:01 +00006101 if (Ty->isRecordType()) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006102 HasByrefExtendedLayout = true;
6103 LifeTime = Qualifiers::OCL_None;
John McCall460ce582015-10-22 18:38:17 +00006104 } else if ((LifeTime = Ty.getObjCLifetime())) {
6105 // Honor the ARC qualifiers.
6106 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
6107 // The MRR rule.
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006108 LifeTime = Qualifiers::OCL_ExplicitNone;
John McCall460ce582015-10-22 18:38:17 +00006109 } else {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006110 LifeTime = Qualifiers::OCL_None;
John McCall460ce582015-10-22 18:38:17 +00006111 }
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006112 return true;
6113}
6114
Douglas Gregorbab8a962011-09-08 01:46:34 +00006115TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
6116 if (!ObjCInstanceTypeDecl)
Alp Toker56b5cc92013-12-15 10:36:26 +00006117 ObjCInstanceTypeDecl =
6118 buildImplicitTypedef(getObjCIdType(), "instancetype");
Douglas Gregorbab8a962011-09-08 01:46:34 +00006119 return ObjCInstanceTypeDecl;
6120}
6121
Anders Carlsson18acd442007-10-29 06:33:42 +00006122// This returns true if a type has been typedefed to BOOL:
6123// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00006124static bool isTypeTypedefedAsBOOL(QualType T) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006125 if (const auto *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00006126 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
6127 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00006128
Anders Carlssond8499822007-10-29 05:01:08 +00006129 return false;
6130}
6131
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006132/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006133/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00006134CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00006135 if (!type->isIncompleteArrayType() && type->isIncompleteType())
6136 return CharUnits::Zero();
Fangrui Song6907ce22018-07-30 19:24:48 +00006137
Ken Dyck40775002010-01-11 17:06:35 +00006138 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00006139
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006140 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00006141 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00006142 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006143 // Treat arrays as pointers, since that's how they're passed in.
6144 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00006145 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00006146 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00006147}
6148
Hans Wennborg56fc62b2014-07-17 20:25:23 +00006149bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
David Majnemer3f021502015-10-08 04:53:31 +00006150 return getTargetInfo().getCXXABI().isMicrosoft() &&
6151 VD->isStaticDataMember() &&
Hans Wennborgb18da9b2018-02-20 12:43:02 +00006152 VD->getType()->isIntegralOrEnumerationType() &&
David Majnemerfac52432015-10-19 23:22:49 +00006153 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
Hans Wennborg56fc62b2014-07-17 20:25:23 +00006154}
6155
Richard Smithd9b90092016-07-02 01:32:16 +00006156ASTContext::InlineVariableDefinitionKind
6157ASTContext::getInlineVariableDefinitionKind(const VarDecl *VD) const {
6158 if (!VD->isInline())
6159 return InlineVariableDefinitionKind::None;
6160
6161 // In almost all cases, it's a weak definition.
6162 auto *First = VD->getFirstDecl();
Richard Smith8910fe62017-10-23 03:58:34 +00006163 if (First->isInlineSpecified() || !First->isStaticDataMember())
Richard Smithd9b90092016-07-02 01:32:16 +00006164 return InlineVariableDefinitionKind::Weak;
6165
6166 // If there's a file-context declaration in this translation unit, it's a
6167 // non-discardable definition.
6168 for (auto *D : VD->redecls())
Richard Smith8910fe62017-10-23 03:58:34 +00006169 if (D->getLexicalDeclContext()->isFileContext() &&
6170 !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr()))
Richard Smithd9b90092016-07-02 01:32:16 +00006171 return InlineVariableDefinitionKind::Strong;
6172
6173 // If we've not seen one yet, we don't know.
6174 return InlineVariableDefinitionKind::WeakUnknown;
6175}
6176
Eugene Zelenko7855e772018-04-03 00:11:50 +00006177static std::string charUnitsToString(const CharUnits &CU) {
Ken Dyck40775002010-01-11 17:06:35 +00006178 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006179}
6180
John McCall351762c2011-02-07 10:33:21 +00006181/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00006182/// declaration.
John McCall351762c2011-02-07 10:33:21 +00006183std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
6184 std::string S;
6185
David Chisnall950a9512009-11-17 19:33:30 +00006186 const BlockDecl *Decl = Expr->getBlockDecl();
6187 QualType BlockTy =
6188 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
6189 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00006190 if (getLangOpts().EncodeExtendedBlockSig)
Alp Toker314cc812014-01-25 16:55:45 +00006191 getObjCEncodingForMethodParameter(
6192 Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
6193 true /*Extended*/);
Fariborz Jahanian64223e62012-11-14 23:11:38 +00006194 else
Alp Toker314cc812014-01-25 16:55:45 +00006195 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00006196 // Compute size of all parameters.
6197 // Start with computing size of a pointer in number of bytes.
6198 // FIXME: There might(should) be a better way of doing this computation!
Ken Dyck40775002010-01-11 17:06:35 +00006199 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
6200 CharUnits ParmOffset = PtrSize;
David Majnemer59f77922016-06-24 04:05:48 +00006201 for (auto PI : Decl->parameters()) {
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00006202 QualType PType = PI->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00006203 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00006204 if (sz.isZero())
6205 continue;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00006206 assert(sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00006207 ParmOffset += sz;
6208 }
6209 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00006210 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00006211 // Block pointer and offset.
6212 S += "@?0";
Fangrui Song6907ce22018-07-30 19:24:48 +00006213
David Chisnall950a9512009-11-17 19:33:30 +00006214 // Argument types.
6215 ParmOffset = PtrSize;
David Majnemer59f77922016-06-24 04:05:48 +00006216 for (auto PVDecl : Decl->parameters()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00006217 QualType PType = PVDecl->getOriginalType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00006218 if (const auto *AT =
6219 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
David Chisnall950a9512009-11-17 19:33:30 +00006220 // Use array's original type only if it has known number of
6221 // elements.
6222 if (!isa<ConstantArrayType>(AT))
6223 PType = PVDecl->getType();
6224 } else if (PType->isFunctionType())
6225 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00006226 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00006227 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
6228 S, true /*Extended*/);
6229 else
6230 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00006231 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00006232 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00006233 }
John McCall351762c2011-02-07 10:33:21 +00006234
6235 return S;
David Chisnall950a9512009-11-17 19:33:30 +00006236}
6237
John McCall843dfcc2016-11-29 21:57:00 +00006238std::string
6239ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const {
6240 std::string S;
David Chisnall50e4eba2010-12-30 14:05:53 +00006241 // Encode result type.
Alp Toker314cc812014-01-25 16:55:45 +00006242 getObjCEncodingForType(Decl->getReturnType(), S);
David Chisnall50e4eba2010-12-30 14:05:53 +00006243 CharUnits ParmOffset;
6244 // Compute size of all parameters.
David Majnemer59f77922016-06-24 04:05:48 +00006245 for (auto PI : Decl->parameters()) {
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00006246 QualType PType = PI->getType();
David Chisnall50e4eba2010-12-30 14:05:53 +00006247 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00006248 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00006249 continue;
Fangrui Song6907ce22018-07-30 19:24:48 +00006250
6251 assert(sz.isPositive() &&
John McCall843dfcc2016-11-29 21:57:00 +00006252 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00006253 ParmOffset += sz;
6254 }
6255 S += charUnitsToString(ParmOffset);
6256 ParmOffset = CharUnits::Zero();
6257
6258 // Argument types.
David Majnemer59f77922016-06-24 04:05:48 +00006259 for (auto PVDecl : Decl->parameters()) {
David Chisnall50e4eba2010-12-30 14:05:53 +00006260 QualType PType = PVDecl->getOriginalType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00006261 if (const auto *AT =
6262 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
David Chisnall50e4eba2010-12-30 14:05:53 +00006263 // Use array's original type only if it has known number of
6264 // elements.
6265 if (!isa<ConstantArrayType>(AT))
6266 PType = PVDecl->getType();
6267 } else if (PType->isFunctionType())
6268 PType = PVDecl->getType();
6269 getObjCEncodingForType(PType, S);
6270 S += charUnitsToString(ParmOffset);
6271 ParmOffset += getObjCEncodingTypeSize(PType);
6272 }
Fangrui Song6907ce22018-07-30 19:24:48 +00006273
John McCall843dfcc2016-11-29 21:57:00 +00006274 return S;
David Chisnall50e4eba2010-12-30 14:05:53 +00006275}
6276
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006277/// getObjCEncodingForMethodParameter - Return the encoded type for a single
Fangrui Song6907ce22018-07-30 19:24:48 +00006278/// method parameter or return type. If Extended, include class names and
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006279/// block object types.
6280void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
6281 QualType T, std::string& S,
6282 bool Extended) const {
6283 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
6284 getObjCEncodingForTypeQualifier(QT, S);
6285 // Encode parameter type.
Craig Topper36250ad2014-05-12 05:36:57 +00006286 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006287 true /*OutermostType*/,
Fangrui Song6907ce22018-07-30 19:24:48 +00006288 false /*EncodingProperty*/,
6289 false /*StructField*/,
6290 Extended /*EncodeBlockParameters*/,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006291 Extended /*EncodeClassNames*/);
6292}
6293
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006294/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006295/// declaration.
John McCall843dfcc2016-11-29 21:57:00 +00006296std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
6297 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00006298 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006299 // Encode return type.
John McCall843dfcc2016-11-29 21:57:00 +00006300 std::string S;
Alp Toker314cc812014-01-25 16:55:45 +00006301 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
6302 Decl->getReturnType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006303 // Compute size of all parameters.
6304 // Start with computing size of a pointer in number of bytes.
6305 // FIXME: There might(should) be a better way of doing this computation!
Ken Dyck40775002010-01-11 17:06:35 +00006306 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006307 // The first two arguments (self and _cmd) are pointers; account for
6308 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00006309 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00006310 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00006311 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00006312 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00006313 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00006314 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00006315 continue;
Fangrui Song6907ce22018-07-30 19:24:48 +00006316
6317 assert(sz.isPositive() &&
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00006318 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006319 ParmOffset += sz;
6320 }
Ken Dyck40775002010-01-11 17:06:35 +00006321 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006322 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00006323 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00006324
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006325 // Argument types.
6326 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00006327 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00006328 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00006329 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00006330 QualType PType = PVDecl->getOriginalType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00006331 if (const auto *AT =
6332 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
Steve Naroffe4e55d22009-04-14 00:03:58 +00006333 // Use array's original type only if it has known number of
6334 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00006335 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00006336 PType = PVDecl->getType();
6337 } else if (PType->isFunctionType())
6338 PType = PVDecl->getType();
Fangrui Song6907ce22018-07-30 19:24:48 +00006339 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006340 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00006341 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00006342 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006343 }
Fangrui Song6907ce22018-07-30 19:24:48 +00006344
John McCall843dfcc2016-11-29 21:57:00 +00006345 return S;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006346}
6347
Fariborz Jahaniandad96302014-01-22 19:02:20 +00006348ObjCPropertyImplDecl *
6349ASTContext::getObjCPropertyImplDeclForPropertyDecl(
6350 const ObjCPropertyDecl *PD,
6351 const Decl *Container) const {
6352 if (!Container)
Craig Topper36250ad2014-05-12 05:36:57 +00006353 return nullptr;
Eugene Zelenko7855e772018-04-03 00:11:50 +00006354 if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) {
Aaron Ballmand85eff42014-03-14 15:02:45 +00006355 for (auto *PID : CID->property_impls())
6356 if (PID->getPropertyDecl() == PD)
6357 return PID;
Craig Topper36250ad2014-05-12 05:36:57 +00006358 } else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006359 const auto *OID = cast<ObjCImplementationDecl>(Container);
Craig Topper36250ad2014-05-12 05:36:57 +00006360 for (auto *PID : OID->property_impls())
6361 if (PID->getPropertyDecl() == PD)
6362 return PID;
6363 }
6364 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00006365}
6366
Daniel Dunbar4932b362008-08-28 04:38:10 +00006367/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00006368/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00006369/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
6370/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00006371/// Property attributes are stored as a comma-delimited C string. The simple
6372/// attributes readonly and bycopy are encoded as single characters. The
6373/// parametrized attributes, getter=name, setter=name, and ivar=name, are
6374/// encoded as single characters, followed by an identifier. Property types
6375/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00006376/// these attributes are defined by the following enumeration:
6377/// @code
6378/// enum PropertyAttributes {
6379/// kPropertyReadOnly = 'R', // property is read-only.
6380/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
6381/// kPropertyByref = '&', // property is a reference to the value last assigned
6382/// kPropertyDynamic = 'D', // property is dynamic
6383/// kPropertyGetter = 'G', // followed by getter selector name
6384/// kPropertySetter = 'S', // followed by setter selector name
6385/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00006386/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00006387/// kPropertyWeak = 'W' // 'weak' property
6388/// kPropertyStrong = 'P' // property GC'able
6389/// kPropertyNonAtomic = 'N' // property non-atomic
6390/// };
6391/// @endcode
John McCall843dfcc2016-11-29 21:57:00 +00006392std::string
6393ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
6394 const Decl *Container) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00006395 // Collect information from the property implementation decl(s).
6396 bool Dynamic = false;
Craig Topper36250ad2014-05-12 05:36:57 +00006397 ObjCPropertyImplDecl *SynthesizePID = nullptr;
Daniel Dunbar4932b362008-08-28 04:38:10 +00006398
Fariborz Jahaniandad96302014-01-22 19:02:20 +00006399 if (ObjCPropertyImplDecl *PropertyImpDecl =
6400 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
6401 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
6402 Dynamic = true;
6403 else
6404 SynthesizePID = PropertyImpDecl;
Daniel Dunbar4932b362008-08-28 04:38:10 +00006405 }
6406
6407 // FIXME: This is not very efficient.
John McCall843dfcc2016-11-29 21:57:00 +00006408 std::string S = "T";
Daniel Dunbar4932b362008-08-28 04:38:10 +00006409
6410 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00006411 // GCC has some special rules regarding encoding of properties which
6412 // closely resembles encoding of ivars.
Joe Groff98ac7d22014-07-07 22:25:15 +00006413 getObjCEncodingForPropertyType(PD->getType(), S);
Daniel Dunbar4932b362008-08-28 04:38:10 +00006414
6415 if (PD->isReadOnly()) {
6416 S += ",R";
Nico Weber4e8626f2013-05-08 23:47:40 +00006417 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
6418 S += ",C";
6419 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
6420 S += ",&";
Fariborz Jahanian33079ee2014-04-02 22:49:42 +00006421 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
6422 S += ",W";
Daniel Dunbar4932b362008-08-28 04:38:10 +00006423 } else {
6424 switch (PD->getSetterKind()) {
6425 case ObjCPropertyDecl::Assign: break;
6426 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00006427 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00006428 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00006429 }
6430 }
6431
6432 // It really isn't clear at all what this means, since properties
6433 // are "dynamic by default".
6434 if (Dynamic)
6435 S += ",D";
6436
Fariborz Jahanian218c6302009-01-20 19:14:18 +00006437 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
6438 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00006439
Daniel Dunbar4932b362008-08-28 04:38:10 +00006440 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
6441 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00006442 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00006443 }
6444
6445 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
6446 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00006447 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00006448 }
6449
6450 if (SynthesizePID) {
6451 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
6452 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00006453 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00006454 }
6455
6456 // FIXME: OBJCGC: weak & strong
John McCall843dfcc2016-11-29 21:57:00 +00006457 return S;
Daniel Dunbar4932b362008-08-28 04:38:10 +00006458}
6459
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006460/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00006461/// Another legacy compatibility encoding: 32-bit longs are encoded as
6462/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006463/// 'i' or 'I' instead if encoding a struct field, or a pointer!
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006464void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00006465 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006466 if (const auto *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00006467 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006468 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00006469 else
Jay Foad39c79802011-01-12 09:06:06 +00006470 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006471 PointeeTy = IntTy;
6472 }
6473 }
6474}
6475
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00006476void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006477 const FieldDecl *Field,
6478 QualType *NotEncodedT) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00006479 // We follow the behavior of gcc, expanding structures which are
6480 // directly pointed to, and expanding embedded structures. Note that
6481 // these rules are sufficient to prevent recursive encoding of the
6482 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00006483 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006484 true /* outermost type */, false, false,
6485 false, false, false, NotEncodedT);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00006486}
6487
Joe Groff98ac7d22014-07-07 22:25:15 +00006488void ASTContext::getObjCEncodingForPropertyType(QualType T,
6489 std::string& S) const {
6490 // Encode result type.
6491 // GCC has some special rules regarding encoding of properties which
6492 // closely resembles encoding of ivars.
6493 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
6494 true /* outermost type */,
6495 true /* encoding property */);
6496}
6497
John McCall393a78d2012-12-20 02:45:14 +00006498static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
6499 BuiltinType::Kind kind) {
6500 switch (kind) {
David Chisnallb190a2c2010-06-04 01:10:52 +00006501 case BuiltinType::Void: return 'v';
6502 case BuiltinType::Bool: return 'B';
Richard Smith3a8244d2018-05-01 05:02:45 +00006503 case BuiltinType::Char8:
David Chisnallb190a2c2010-06-04 01:10:52 +00006504 case BuiltinType::Char_U:
6505 case BuiltinType::UChar: return 'C';
John McCall393a78d2012-12-20 02:45:14 +00006506 case BuiltinType::Char16:
David Chisnallb190a2c2010-06-04 01:10:52 +00006507 case BuiltinType::UShort: return 'S';
John McCall393a78d2012-12-20 02:45:14 +00006508 case BuiltinType::Char32:
David Chisnallb190a2c2010-06-04 01:10:52 +00006509 case BuiltinType::UInt: return 'I';
6510 case BuiltinType::ULong:
John McCall393a78d2012-12-20 02:45:14 +00006511 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00006512 case BuiltinType::UInt128: return 'T';
6513 case BuiltinType::ULongLong: return 'Q';
6514 case BuiltinType::Char_S:
6515 case BuiltinType::SChar: return 'c';
6516 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00006517 case BuiltinType::WChar_S:
6518 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00006519 case BuiltinType::Int: return 'i';
6520 case BuiltinType::Long:
John McCall393a78d2012-12-20 02:45:14 +00006521 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00006522 case BuiltinType::LongLong: return 'q';
6523 case BuiltinType::Int128: return 't';
6524 case BuiltinType::Float: return 'f';
6525 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00006526 case BuiltinType::LongDouble: return 'D';
John McCall393a78d2012-12-20 02:45:14 +00006527 case BuiltinType::NullPtr: return '*'; // like char*
6528
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00006529 case BuiltinType::Float16:
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00006530 case BuiltinType::Float128:
John McCall393a78d2012-12-20 02:45:14 +00006531 case BuiltinType::Half:
Leonard Chanf921d852018-06-04 16:07:52 +00006532 case BuiltinType::ShortAccum:
6533 case BuiltinType::Accum:
6534 case BuiltinType::LongAccum:
6535 case BuiltinType::UShortAccum:
6536 case BuiltinType::UAccum:
6537 case BuiltinType::ULongAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00006538 case BuiltinType::ShortFract:
6539 case BuiltinType::Fract:
6540 case BuiltinType::LongFract:
6541 case BuiltinType::UShortFract:
6542 case BuiltinType::UFract:
6543 case BuiltinType::ULongFract:
6544 case BuiltinType::SatShortAccum:
6545 case BuiltinType::SatAccum:
6546 case BuiltinType::SatLongAccum:
6547 case BuiltinType::SatUShortAccum:
6548 case BuiltinType::SatUAccum:
6549 case BuiltinType::SatULongAccum:
6550 case BuiltinType::SatShortFract:
6551 case BuiltinType::SatFract:
6552 case BuiltinType::SatLongFract:
6553 case BuiltinType::SatUShortFract:
6554 case BuiltinType::SatUFract:
6555 case BuiltinType::SatULongFract:
John McCall393a78d2012-12-20 02:45:14 +00006556 // FIXME: potentially need @encodes for these!
6557 return ' ';
6558
6559 case BuiltinType::ObjCId:
6560 case BuiltinType::ObjCClass:
6561 case BuiltinType::ObjCSel:
6562 llvm_unreachable("@encoding ObjC primitive type");
6563
6564 // OpenCL and placeholder types don't need @encodings.
Alexey Bader954ba212016-04-08 13:40:33 +00006565#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6566 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00006567#include "clang/Basic/OpenCLImageTypes.def"
Andrew Savonichev3fee3512018-11-08 11:25:41 +00006568#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6569 case BuiltinType::Id:
6570#include "clang/Basic/OpenCLExtensionTypes.def"
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006571 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00006572 case BuiltinType::OCLClkEvent:
6573 case BuiltinType::OCLQueue:
Alexey Bader9c8453f2015-09-15 11:18:52 +00006574 case BuiltinType::OCLReserveID:
Guy Benyei61054192013-02-07 10:55:47 +00006575 case BuiltinType::OCLSampler:
John McCall393a78d2012-12-20 02:45:14 +00006576 case BuiltinType::Dependent:
6577#define BUILTIN_TYPE(KIND, ID)
6578#define PLACEHOLDER_TYPE(KIND, ID) \
6579 case BuiltinType::KIND:
6580#include "clang/AST/BuiltinTypes.def"
6581 llvm_unreachable("invalid builtin type for @encode");
David Chisnallb190a2c2010-06-04 01:10:52 +00006582 }
David Blaikie5a6a0202013-01-09 17:48:41 +00006583 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnallb190a2c2010-06-04 01:10:52 +00006584}
6585
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006586static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
6587 EnumDecl *Enum = ET->getDecl();
Fangrui Song6907ce22018-07-30 19:24:48 +00006588
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006589 // The encoding of an non-fixed enum type is always 'i', regardless of size.
6590 if (!Enum->isFixed())
6591 return 'i';
Fangrui Song6907ce22018-07-30 19:24:48 +00006592
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006593 // The encoding of a fixed enum type matches its fixed underlying type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00006594 const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>();
John McCall393a78d2012-12-20 02:45:14 +00006595 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006596}
6597
Jay Foad39c79802011-01-12 09:06:06 +00006598static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00006599 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00006600 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00006601 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00006602 // The NeXT runtime encodes bit fields as b followed by the number of bits.
6603 // The GNU runtime requires more information; bitfields are encoded as b,
6604 // then the offset (in bits) of the first element, then the type of the
6605 // bitfield, then the size in bits. For example, in this structure:
6606 //
6607 // struct
6608 // {
6609 // int integer;
6610 // int flags:2;
6611 // };
6612 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
6613 // runtime, but b32i2 for the GNU runtime. The reason for this extra
6614 // information is not especially sensible, but we're stuck with it for
6615 // compatibility with GCC, although providing it breaks anything that
6616 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00006617 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
Akira Hatanaka4b1c4842017-06-27 04:34:04 +00006618 uint64_t Offset;
6619
6620 if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) {
6621 Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), nullptr,
6622 IVD);
6623 } else {
6624 const RecordDecl *RD = FD->getParent();
6625 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
6626 Offset = RL.getFieldOffset(FD->getFieldIndex());
6627 }
6628
6629 S += llvm::utostr(Offset);
6630
Eugene Zelenko7855e772018-04-03 00:11:50 +00006631 if (const auto *ET = T->getAs<EnumType>())
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006632 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall393a78d2012-12-20 02:45:14 +00006633 else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006634 const auto *BT = T->castAs<BuiltinType>();
John McCall393a78d2012-12-20 02:45:14 +00006635 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
6636 }
David Chisnallb190a2c2010-06-04 01:10:52 +00006637 }
Richard Smithcaf33902011-10-10 18:28:20 +00006638 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00006639}
6640
Daniel Dunbar07d07852009-10-18 21:17:35 +00006641// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00006642void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
6643 bool ExpandPointedToStructures,
6644 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00006645 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00006646 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006647 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006648 bool StructField,
6649 bool EncodeBlockParameters,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00006650 bool EncodeClassNames,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006651 bool EncodePointerToObjCTypedef,
6652 QualType *NotEncodedT) const {
John McCall393a78d2012-12-20 02:45:14 +00006653 CanQualType CT = getCanonicalType(T);
6654 switch (CT->getTypeClass()) {
6655 case Type::Builtin:
6656 case Type::Enum:
Chris Lattnere7cabb92009-07-13 00:10:46 +00006657 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00006658 return EncodeBitField(this, S, T, FD);
Eugene Zelenko7855e772018-04-03 00:11:50 +00006659 if (const auto *BT = dyn_cast<BuiltinType>(CT))
John McCall393a78d2012-12-20 02:45:14 +00006660 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
6661 else
6662 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnere7cabb92009-07-13 00:10:46 +00006663 return;
Mike Stump11289f42009-09-09 15:08:12 +00006664
John McCall393a78d2012-12-20 02:45:14 +00006665 case Type::Complex: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006666 const auto *CT = T->castAs<ComplexType>();
Anders Carlsson39b2e132009-04-09 21:55:45 +00006667 S += 'j';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006668 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, nullptr);
Chris Lattnere7cabb92009-07-13 00:10:46 +00006669 return;
6670 }
John McCall393a78d2012-12-20 02:45:14 +00006671
6672 case Type::Atomic: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006673 const auto *AT = T->castAs<AtomicType>();
John McCall393a78d2012-12-20 02:45:14 +00006674 S += 'A';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006675 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, nullptr);
John McCall393a78d2012-12-20 02:45:14 +00006676 return;
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00006677 }
John McCall393a78d2012-12-20 02:45:14 +00006678
6679 // encoding for pointer or reference types.
6680 case Type::Pointer:
6681 case Type::LValueReference:
6682 case Type::RValueReference: {
6683 QualType PointeeTy;
6684 if (isa<PointerType>(CT)) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006685 const auto *PT = T->castAs<PointerType>();
John McCall393a78d2012-12-20 02:45:14 +00006686 if (PT->isObjCSelType()) {
6687 S += ':';
6688 return;
6689 }
6690 PointeeTy = PT->getPointeeType();
6691 } else {
6692 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
6693 }
6694
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006695 bool isReadOnly = false;
6696 // For historical/compatibility reasons, the read-only qualifier of the
6697 // pointee gets emitted _before_ the '^'. The read-only qualifier of
6698 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00006699 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00006700 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006701 if (OutermostType && T.isConstQualified()) {
6702 isReadOnly = true;
6703 S += 'r';
6704 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00006705 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006706 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006707 while (P->getAs<PointerType>())
6708 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006709 if (P.isConstQualified()) {
6710 isReadOnly = true;
6711 S += 'r';
6712 }
6713 }
6714 if (isReadOnly) {
6715 // Another legacy compatibility encoding. Some ObjC qualifier and type
6716 // combinations need to be rearranged.
6717 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006718 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00006719 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006720 }
Mike Stump11289f42009-09-09 15:08:12 +00006721
Anders Carlssond8499822007-10-29 05:01:08 +00006722 if (PointeeTy->isCharType()) {
6723 // char pointer types should be encoded as '*' unless it is a
6724 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00006725 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00006726 S += '*';
6727 return;
6728 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00006729 } else if (const auto *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00006730 // GCC binary compat: Need to convert "struct objc_class *" to "#".
6731 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
6732 S += '#';
6733 return;
6734 }
6735 // GCC binary compat: Need to convert "struct objc_object *" to "@".
6736 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
6737 S += '@';
6738 return;
6739 }
6740 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00006741 }
Anders Carlssond8499822007-10-29 05:01:08 +00006742 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006743 getLegacyIntegralTypeEncoding(PointeeTy);
6744
Mike Stump11289f42009-09-09 15:08:12 +00006745 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006746 nullptr, false, false, false, false, false, false,
6747 NotEncodedT);
Chris Lattnere7cabb92009-07-13 00:10:46 +00006748 return;
6749 }
John McCall393a78d2012-12-20 02:45:14 +00006750
6751 case Type::ConstantArray:
6752 case Type::IncompleteArray:
6753 case Type::VariableArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006754 const auto *AT = cast<ArrayType>(CT);
John McCall393a78d2012-12-20 02:45:14 +00006755
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006756 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00006757 // Incomplete arrays are encoded as a pointer to the array element.
6758 S += '^';
6759
Mike Stump11289f42009-09-09 15:08:12 +00006760 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00006761 false, ExpandStructures, FD);
6762 } else {
6763 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00006764
Eugene Zelenko7855e772018-04-03 00:11:50 +00006765 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
Fariborz Jahanianf0dc11a2013-06-04 16:04:37 +00006766 S += llvm::utostr(CAT->getSize().getZExtValue());
6767 else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00006768 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006769 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
6770 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00006771 S += '0';
6772 }
Mike Stump11289f42009-09-09 15:08:12 +00006773
6774 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006775 false, ExpandStructures, FD,
6776 false, false, false, false, false, false,
6777 NotEncodedT);
Anders Carlssond05f44b2009-02-22 01:38:57 +00006778 S += ']';
6779 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006780 return;
6781 }
Mike Stump11289f42009-09-09 15:08:12 +00006782
John McCall393a78d2012-12-20 02:45:14 +00006783 case Type::FunctionNoProto:
6784 case Type::FunctionProto:
Anders Carlssondf4cc612007-10-30 00:06:20 +00006785 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00006786 return;
Mike Stump11289f42009-09-09 15:08:12 +00006787
John McCall393a78d2012-12-20 02:45:14 +00006788 case Type::Record: {
6789 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00006790 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00006791 // Anonymous structures print as '?'
6792 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
6793 S += II->getName();
Eugene Zelenko7855e772018-04-03 00:11:50 +00006794 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
Fariborz Jahanianc5158202010-05-07 00:28:49 +00006795 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00006796 llvm::raw_string_ostream OS(S);
Serge Pavlov03e672c2017-11-28 16:14:14 +00006797 printTemplateArgumentList(OS, TemplateArgs.asArray(),
6798 getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00006799 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00006800 } else {
6801 S += '?';
6802 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00006803 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00006804 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006805 if (!RDecl->isUnion()) {
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006806 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006807 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006808 for (const auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006809 if (FD) {
6810 S += '"';
6811 S += Field->getNameAsString();
6812 S += '"';
6813 }
Mike Stump11289f42009-09-09 15:08:12 +00006814
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006815 // Special case bit-fields.
6816 if (Field->isBitField()) {
6817 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006818 Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006819 } else {
6820 QualType qt = Field->getType();
6821 getLegacyIntegralTypeEncoding(qt);
6822 getObjCEncodingForTypeImpl(qt, S, false, true,
6823 FD, /*OutermostType*/false,
6824 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006825 /*StructField*/true,
6826 false, false, false, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006827 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00006828 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00006829 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00006830 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00006831 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00006832 return;
6833 }
Mike Stump11289f42009-09-09 15:08:12 +00006834
John McCall393a78d2012-12-20 02:45:14 +00006835 case Type::BlockPointer: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006836 const auto *BT = T->castAs<BlockPointerType>();
Steve Naroff49140cb2009-02-02 18:24:29 +00006837 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006838 if (EncodeBlockParameters) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006839 const auto *FT = BT->getPointeeType()->castAs<FunctionType>();
Fangrui Song6907ce22018-07-30 19:24:48 +00006840
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006841 S += '<';
6842 // Block return type
Alp Toker314cc812014-01-25 16:55:45 +00006843 getObjCEncodingForTypeImpl(
6844 FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures,
6845 FD, false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006846 false /* StructField */, EncodeBlockParameters, EncodeClassNames, false,
6847 NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006848 // Block self
6849 S += "@?";
6850 // Block parameters
Eugene Zelenko7855e772018-04-03 00:11:50 +00006851 if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00006852 for (const auto &I : FPT->param_types())
6853 getObjCEncodingForTypeImpl(
6854 I, S, ExpandPointedToStructures, ExpandStructures, FD,
6855 false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006856 false /* StructField */, EncodeBlockParameters, EncodeClassNames,
6857 false, NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006858 }
6859 S += '>';
6860 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006861 return;
6862 }
Mike Stump11289f42009-09-09 15:08:12 +00006863
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00006864 case Type::ObjCObject: {
6865 // hack to match legacy encoding of *id and *Class
6866 QualType Ty = getObjCObjectPointerType(CT);
6867 if (Ty->isObjCIdType()) {
6868 S += "{objc_object=}";
6869 return;
6870 }
6871 else if (Ty->isObjCClassType()) {
6872 S += "{objc_class=}";
6873 return;
6874 }
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00006875 // TODO: Double check to make sure this intentionally falls through.
Galina Kistanovaf87496d2017-06-03 06:31:42 +00006876 LLVM_FALLTHROUGH;
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00006877 }
Fangrui Song6907ce22018-07-30 19:24:48 +00006878
John McCall393a78d2012-12-20 02:45:14 +00006879 case Type::ObjCInterface: {
6880 // Ignore protocol qualifiers when mangling at this level.
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006881 // @encode(class_name)
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006882 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006883 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006884 S += OI->getObjCRuntimeNameAsString();
Akira Hatanakafd0fb202016-08-17 19:42:22 +00006885 if (ExpandStructures) {
6886 S += '=';
6887 SmallVector<const ObjCIvarDecl*, 32> Ivars;
6888 DeepCollectObjCIvars(OI, true, Ivars);
6889 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
George Burgess IV00f70bd2018-03-01 05:43:23 +00006890 const FieldDecl *Field = Ivars[i];
Akira Hatanakafd0fb202016-08-17 19:42:22 +00006891 if (Field->isBitField())
6892 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
6893 else
6894 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
6895 false, false, false, false, false,
6896 EncodePointerToObjCTypedef,
6897 NotEncodedT);
6898 }
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006899 }
6900 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00006901 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006902 }
Mike Stump11289f42009-09-09 15:08:12 +00006903
John McCall393a78d2012-12-20 02:45:14 +00006904 case Type::ObjCObjectPointer: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006905 const auto *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00006906 if (OPT->isObjCIdType()) {
6907 S += '@';
6908 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00006909 }
Mike Stump11289f42009-09-09 15:08:12 +00006910
Steve Narofff0c86112009-10-28 22:03:49 +00006911 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
6912 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
6913 // Since this is a binary compatibility issue, need to consult with runtime
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00006914 // folks. Fortunately, this is a *very* obscure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00006915 S += '#';
6916 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00006917 }
Mike Stump11289f42009-09-09 15:08:12 +00006918
Chris Lattnere7cabb92009-07-13 00:10:46 +00006919 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00006920 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00006921 ExpandPointedToStructures,
6922 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006923 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00006924 // Note that we do extended encoding of protocol qualifer list
6925 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00006926 S += '"';
Aaron Ballman83731462014-03-17 16:14:00 +00006927 for (const auto *I : OPT->quals()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00006928 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006929 S += I->getObjCRuntimeNameAsString();
Steve Naroff7cae42b2009-07-10 23:34:53 +00006930 S += '>';
6931 }
6932 S += '"';
6933 }
6934 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00006935 }
Mike Stump11289f42009-09-09 15:08:12 +00006936
Chris Lattnere7cabb92009-07-13 00:10:46 +00006937 QualType PointeeTy = OPT->getPointeeType();
6938 if (!EncodingProperty &&
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00006939 isa<TypedefType>(PointeeTy.getTypePtr()) &&
6940 !EncodePointerToObjCTypedef) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00006941 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00006942 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00006943 // {...};
6944 S += '^';
Fariborz Jahanian88890e72013-07-12 16:19:11 +00006945 if (FD && OPT->getInterfaceDecl()) {
Fariborz Jahanianc682ef52013-07-12 16:41:56 +00006946 // Prevent recursive encoding of fields in some rare cases.
Fariborz Jahanian88890e72013-07-12 16:19:11 +00006947 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
6948 SmallVector<const ObjCIvarDecl*, 32> Ivars;
6949 DeepCollectObjCIvars(OI, true, Ivars);
6950 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
George Burgess IV00f70bd2018-03-01 05:43:23 +00006951 if (Ivars[i] == FD) {
Fariborz Jahanian88890e72013-07-12 16:19:11 +00006952 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006953 S += OI->getObjCRuntimeNameAsString();
Fariborz Jahanian88890e72013-07-12 16:19:11 +00006954 S += '}';
6955 return;
6956 }
6957 }
6958 }
Mike Stump11289f42009-09-09 15:08:12 +00006959 getObjCEncodingForTypeImpl(PointeeTy, S,
6960 false, ExpandPointedToStructures,
Craig Topper36250ad2014-05-12 05:36:57 +00006961 nullptr,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00006962 false, false, false, false, false,
6963 /*EncodePointerToObjCTypedef*/true);
Steve Naroff7cae42b2009-07-10 23:34:53 +00006964 return;
6965 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006966
6967 S += '@';
Fangrui Song6907ce22018-07-30 19:24:48 +00006968 if (OPT->getInterfaceDecl() &&
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006969 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00006970 S += '"';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006971 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
Aaron Ballman83731462014-03-17 16:14:00 +00006972 for (const auto *I : OPT->quals()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00006973 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006974 S += I->getObjCRuntimeNameAsString();
Chris Lattnere7cabb92009-07-13 00:10:46 +00006975 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00006976 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006977 S += '"';
6978 }
6979 return;
6980 }
Mike Stump11289f42009-09-09 15:08:12 +00006981
John McCalla9e6e8d2010-05-17 23:56:34 +00006982 // gcc just blithely ignores member pointers.
John McCall393a78d2012-12-20 02:45:14 +00006983 // FIXME: we shoul do better than that. 'M' is available.
6984 case Type::MemberPointer:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006985 // This matches gcc's encoding, even though technically it is insufficient.
6986 //FIXME. We should do a better job than gcc.
John McCall393a78d2012-12-20 02:45:14 +00006987 case Type::Vector:
6988 case Type::ExtVector:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006989 // Until we have a coherent encoding of these three types, issue warning.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00006990 if (NotEncodedT)
6991 *NotEncodedT = T;
6992 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00006993
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006994 // We could see an undeduced auto type here during error recovery.
6995 // Just ignore it.
Richard Smith27d807c2013-04-30 13:56:41 +00006996 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00006997 case Type::DeducedTemplateSpecialization:
Richard Smith27d807c2013-04-30 13:56:41 +00006998 return;
6999
Xiuli Pan9c14e282016-01-09 12:53:17 +00007000 case Type::Pipe:
John McCall393a78d2012-12-20 02:45:14 +00007001#define ABSTRACT_TYPE(KIND, BASE)
7002#define TYPE(KIND, BASE)
7003#define DEPENDENT_TYPE(KIND, BASE) \
7004 case Type::KIND:
7005#define NON_CANONICAL_TYPE(KIND, BASE) \
7006 case Type::KIND:
7007#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
7008 case Type::KIND:
7009#include "clang/AST/TypeNodes.def"
7010 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00007011 }
John McCall393a78d2012-12-20 02:45:14 +00007012 llvm_unreachable("bad type kind!");
Anders Carlssond8499822007-10-29 05:01:08 +00007013}
7014
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007015void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
7016 std::string &S,
7017 const FieldDecl *FD,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00007018 bool includeVBases,
7019 QualType *NotEncodedT) const {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007020 assert(RDecl && "Expected non-null RecordDecl");
7021 assert(!RDecl->isUnion() && "Should not be called for unions");
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00007022 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007023 return;
7024
Eugene Zelenko7855e772018-04-03 00:11:50 +00007025 const auto *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007026 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
7027 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
7028
7029 if (CXXRec) {
Aaron Ballman574705e2014-03-13 15:41:46 +00007030 for (const auto &BI : CXXRec->bases()) {
7031 if (!BI.isVirtual()) {
7032 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00007033 if (base->isEmpty())
7034 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00007035 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007036 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
7037 std::make_pair(offs, base));
7038 }
7039 }
7040 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007041
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007042 unsigned i = 0;
Hans Wennborga302cd92014-08-21 16:06:57 +00007043 for (auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007044 uint64_t offs = layout.getFieldOffset(i);
7045 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Hans Wennborga302cd92014-08-21 16:06:57 +00007046 std::make_pair(offs, Field));
7047 ++i;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007048 }
7049
7050 if (CXXRec && includeVBases) {
Aaron Ballman445a9392014-03-13 16:15:17 +00007051 for (const auto &BI : CXXRec->vbases()) {
7052 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00007053 if (base->isEmpty())
7054 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00007055 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Eli Friedman1d24af82013-09-18 01:59:16 +00007056 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
7057 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00007058 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
7059 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007060 }
7061 }
7062
7063 CharUnits size;
7064 if (CXXRec) {
7065 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
7066 } else {
7067 size = layout.getSize();
7068 }
7069
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007070#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007071 uint64_t CurOffs = 0;
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007072#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007073 std::multimap<uint64_t, NamedDecl *>::iterator
7074 CurLayObj = FieldOrBaseOffsets.begin();
7075
Douglas Gregorf5d6c742012-04-27 22:30:01 +00007076 if (CXXRec && CXXRec->isDynamicClass() &&
7077 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007078 if (FD) {
7079 S += "\"_vptr$";
7080 std::string recname = CXXRec->getNameAsString();
7081 if (recname.empty()) recname = "?";
7082 S += recname;
7083 S += '"';
7084 }
7085 S += "^^?";
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007086#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007087 CurOffs += getTypeSize(VoidPtrTy);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007088#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007089 }
7090
7091 if (!RDecl->hasFlexibleArrayMember()) {
7092 // Mark the end of the structure.
7093 uint64_t offs = toBits(size);
7094 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Craig Topper36250ad2014-05-12 05:36:57 +00007095 std::make_pair(offs, nullptr));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007096 }
7097
7098 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007099#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007100 assert(CurOffs <= CurLayObj->first);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007101 if (CurOffs < CurLayObj->first) {
Fangrui Song6907ce22018-07-30 19:24:48 +00007102 uint64_t padding = CurLayObj->first - CurOffs;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007103 // FIXME: There doesn't seem to be a way to indicate in the encoding that
7104 // packing/alignment of members is different that normal, in which case
7105 // the encoding will be out-of-sync with the real layout.
7106 // If the runtime switches to just consider the size of types without
7107 // taking into account alignment, we could make padding explicit in the
7108 // encoding (e.g. using arrays of chars). The encoding strings would be
7109 // longer then though.
7110 CurOffs += padding;
7111 }
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007112#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007113
7114 NamedDecl *dcl = CurLayObj->second;
Craig Topper36250ad2014-05-12 05:36:57 +00007115 if (!dcl)
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007116 break; // reached end of structure.
7117
Eugene Zelenko7855e772018-04-03 00:11:50 +00007118 if (auto *base = dyn_cast<CXXRecordDecl>(dcl)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007119 // We expand the bases without their virtual bases since those are going
7120 // in the initial structure. Note that this differs from gcc which
7121 // expands virtual bases each time one is encountered in the hierarchy,
7122 // making the encoding type bigger than it really is.
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00007123 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
7124 NotEncodedT);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00007125 assert(!base->isEmpty());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007126#ifndef NDEBUG
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00007127 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007128#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007129 } else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00007130 const auto *field = cast<FieldDecl>(dcl);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007131 if (FD) {
7132 S += '"';
7133 S += field->getNameAsString();
7134 S += '"';
7135 }
7136
7137 if (field->isBitField()) {
7138 EncodeBitField(this, S, field->getType(), field);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007139#ifndef NDEBUG
Richard Smithcaf33902011-10-10 18:28:20 +00007140 CurOffs += field->getBitWidthValue(*this);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007141#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007142 } else {
7143 QualType qt = field->getType();
7144 getLegacyIntegralTypeEncoding(qt);
7145 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
7146 /*OutermostType*/false,
7147 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00007148 /*StructField*/true,
7149 false, false, false, NotEncodedT);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007150#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007151 CurOffs += getTypeSize(field->getType());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007152#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007153 }
7154 }
7155 }
7156}
7157
Mike Stump11289f42009-09-09 15:08:12 +00007158void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00007159 std::string& S) const {
7160 if (QT & Decl::OBJC_TQ_In)
7161 S += 'n';
7162 if (QT & Decl::OBJC_TQ_Inout)
7163 S += 'N';
7164 if (QT & Decl::OBJC_TQ_Out)
7165 S += 'o';
7166 if (QT & Decl::OBJC_TQ_Bycopy)
7167 S += 'O';
7168 if (QT & Decl::OBJC_TQ_Byref)
7169 S += 'R';
7170 if (QT & Decl::OBJC_TQ_Oneway)
7171 S += 'V';
7172}
7173
Douglas Gregor3ea72692011-08-12 05:46:01 +00007174TypedefDecl *ASTContext::getObjCIdDecl() const {
7175 if (!ObjCIdDecl) {
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00007176 QualType T = getObjCObjectType(ObjCBuiltinIdTy, {}, {});
Douglas Gregor3ea72692011-08-12 05:46:01 +00007177 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00007178 ObjCIdDecl = buildImplicitTypedef(T, "id");
Douglas Gregor3ea72692011-08-12 05:46:01 +00007179 }
Douglas Gregor3ea72692011-08-12 05:46:01 +00007180 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00007181}
7182
Douglas Gregor52e02802011-08-12 06:17:30 +00007183TypedefDecl *ASTContext::getObjCSelDecl() const {
7184 if (!ObjCSelDecl) {
Alp Toker56b5cc92013-12-15 10:36:26 +00007185 QualType T = getPointerType(ObjCBuiltinSelTy);
7186 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
Douglas Gregor52e02802011-08-12 06:17:30 +00007187 }
7188 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00007189}
7190
Douglas Gregor0a586182011-08-12 05:59:41 +00007191TypedefDecl *ASTContext::getObjCClassDecl() const {
7192 if (!ObjCClassDecl) {
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00007193 QualType T = getObjCObjectType(ObjCBuiltinClassTy, {}, {});
Douglas Gregor0a586182011-08-12 05:59:41 +00007194 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00007195 ObjCClassDecl = buildImplicitTypedef(T, "Class");
Douglas Gregor0a586182011-08-12 05:59:41 +00007196 }
Douglas Gregor0a586182011-08-12 05:59:41 +00007197 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00007198}
7199
Douglas Gregord53ae832012-01-17 18:09:05 +00007200ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
7201 if (!ObjCProtocolClassDecl) {
Fangrui Song6907ce22018-07-30 19:24:48 +00007202 ObjCProtocolClassDecl
7203 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
Douglas Gregord53ae832012-01-17 18:09:05 +00007204 SourceLocation(),
7205 &Idents.get("Protocol"),
Douglas Gregor85f3f952015-07-07 03:57:15 +00007206 /*typeParamList=*/nullptr,
Craig Topper36250ad2014-05-12 05:36:57 +00007207 /*PrevDecl=*/nullptr,
Fangrui Song6907ce22018-07-30 19:24:48 +00007208 SourceLocation(), true);
Douglas Gregord53ae832012-01-17 18:09:05 +00007209 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007210
Douglas Gregord53ae832012-01-17 18:09:05 +00007211 return ObjCProtocolClassDecl;
7212}
7213
Meador Inge5d3fb222012-06-16 03:34:49 +00007214//===----------------------------------------------------------------------===//
7215// __builtin_va_list Construction Functions
7216//===----------------------------------------------------------------------===//
7217
Charles Davisc7d5c942015-09-17 20:55:33 +00007218static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context,
7219 StringRef Name) {
7220 // typedef char* __builtin[_ms]_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00007221 QualType T = Context->getPointerType(Context->CharTy);
Charles Davisc7d5c942015-09-17 20:55:33 +00007222 return Context->buildImplicitTypedef(T, Name);
7223}
7224
7225static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
7226 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
7227}
7228
7229static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
7230 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007231}
7232
7233static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
7234 // typedef void* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00007235 QualType T = Context->getPointerType(Context->VoidTy);
7236 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007237}
7238
Tim Northover9bb857a2013-01-31 12:13:10 +00007239static TypedefDecl *
7240CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00007241 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00007242 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00007243 if (Context->getLangOpts().CPlusPlus) {
7244 // namespace std { struct __va_list {
7245 NamespaceDecl *NS;
7246 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
7247 Context->getTranslationUnitDecl(),
Craig Topper36250ad2014-05-12 05:36:57 +00007248 /*Inline*/ false, SourceLocation(),
Tim Northover9bb857a2013-01-31 12:13:10 +00007249 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00007250 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00007251 NS->setImplicit();
Tim Northover9bb857a2013-01-31 12:13:10 +00007252 VaListTagDecl->setDeclContext(NS);
Tim Northover9bb857a2013-01-31 12:13:10 +00007253 }
7254
7255 VaListTagDecl->startDefinition();
7256
7257 const size_t NumFields = 5;
7258 QualType FieldTypes[NumFields];
7259 const char *FieldNames[NumFields];
7260
7261 // void *__stack;
7262 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
7263 FieldNames[0] = "__stack";
7264
7265 // void *__gr_top;
7266 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
7267 FieldNames[1] = "__gr_top";
7268
7269 // void *__vr_top;
7270 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
7271 FieldNames[2] = "__vr_top";
7272
7273 // int __gr_offs;
7274 FieldTypes[3] = Context->IntTy;
7275 FieldNames[3] = "__gr_offs";
7276
7277 // int __vr_offs;
7278 FieldTypes[4] = Context->IntTy;
7279 FieldNames[4] = "__vr_offs";
7280
7281 // Create fields
7282 for (unsigned i = 0; i < NumFields; ++i) {
7283 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7284 VaListTagDecl,
7285 SourceLocation(),
7286 SourceLocation(),
7287 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00007288 FieldTypes[i], /*TInfo=*/nullptr,
7289 /*BitWidth=*/nullptr,
Tim Northover9bb857a2013-01-31 12:13:10 +00007290 /*Mutable=*/false,
7291 ICIS_NoInit);
7292 Field->setAccess(AS_public);
7293 VaListTagDecl->addDecl(Field);
7294 }
7295 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00007296 Context->VaListTagDecl = VaListTagDecl;
Tim Northover9bb857a2013-01-31 12:13:10 +00007297 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Tim Northover9bb857a2013-01-31 12:13:10 +00007298
7299 // } __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00007300 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00007301}
7302
Meador Inge5d3fb222012-06-16 03:34:49 +00007303static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
7304 // typedef struct __va_list_tag {
7305 RecordDecl *VaListTagDecl;
7306
Alp Toker2dea15b2013-12-17 01:22:38 +00007307 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00007308 VaListTagDecl->startDefinition();
7309
7310 const size_t NumFields = 5;
7311 QualType FieldTypes[NumFields];
7312 const char *FieldNames[NumFields];
7313
7314 // unsigned char gpr;
7315 FieldTypes[0] = Context->UnsignedCharTy;
7316 FieldNames[0] = "gpr";
7317
7318 // unsigned char fpr;
7319 FieldTypes[1] = Context->UnsignedCharTy;
7320 FieldNames[1] = "fpr";
7321
7322 // unsigned short reserved;
7323 FieldTypes[2] = Context->UnsignedShortTy;
7324 FieldNames[2] = "reserved";
7325
7326 // void* overflow_arg_area;
7327 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
7328 FieldNames[3] = "overflow_arg_area";
7329
7330 // void* reg_save_area;
7331 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
7332 FieldNames[4] = "reg_save_area";
7333
7334 // Create fields
7335 for (unsigned i = 0; i < NumFields; ++i) {
7336 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
7337 SourceLocation(),
7338 SourceLocation(),
7339 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00007340 FieldTypes[i], /*TInfo=*/nullptr,
7341 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00007342 /*Mutable=*/false,
7343 ICIS_NoInit);
7344 Field->setAccess(AS_public);
7345 VaListTagDecl->addDecl(Field);
7346 }
7347 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00007348 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00007349 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
7350
7351 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00007352 TypedefDecl *VaListTagTypedefDecl =
7353 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
7354
Meador Inge5d3fb222012-06-16 03:34:49 +00007355 QualType VaListTagTypedefType =
7356 Context->getTypedefType(VaListTagTypedefDecl);
7357
7358 // typedef __va_list_tag __builtin_va_list[1];
7359 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
7360 QualType VaListTagArrayType
7361 = Context->getConstantArrayType(VaListTagTypedefType,
7362 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00007363 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007364}
7365
7366static TypedefDecl *
7367CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00007368 // struct __va_list_tag {
Meador Inge5d3fb222012-06-16 03:34:49 +00007369 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00007370 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00007371 VaListTagDecl->startDefinition();
7372
7373 const size_t NumFields = 4;
7374 QualType FieldTypes[NumFields];
7375 const char *FieldNames[NumFields];
7376
7377 // unsigned gp_offset;
7378 FieldTypes[0] = Context->UnsignedIntTy;
7379 FieldNames[0] = "gp_offset";
7380
7381 // unsigned fp_offset;
7382 FieldTypes[1] = Context->UnsignedIntTy;
7383 FieldNames[1] = "fp_offset";
7384
7385 // void* overflow_arg_area;
7386 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
7387 FieldNames[2] = "overflow_arg_area";
7388
7389 // void* reg_save_area;
7390 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
7391 FieldNames[3] = "reg_save_area";
7392
7393 // Create fields
7394 for (unsigned i = 0; i < NumFields; ++i) {
7395 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7396 VaListTagDecl,
7397 SourceLocation(),
7398 SourceLocation(),
7399 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00007400 FieldTypes[i], /*TInfo=*/nullptr,
7401 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00007402 /*Mutable=*/false,
7403 ICIS_NoInit);
7404 Field->setAccess(AS_public);
7405 VaListTagDecl->addDecl(Field);
7406 }
7407 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00007408 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00007409 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
7410
Richard Smith9b88a4c2015-07-27 05:40:23 +00007411 // };
Alp Toker56b5cc92013-12-15 10:36:26 +00007412
Richard Smith9b88a4c2015-07-27 05:40:23 +00007413 // typedef struct __va_list_tag __builtin_va_list[1];
Meador Inge5d3fb222012-06-16 03:34:49 +00007414 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00007415 QualType VaListTagArrayType =
7416 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00007417 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007418}
7419
7420static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
7421 // typedef int __builtin_va_list[4];
7422 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
Yaron Kerene0bcdd42016-10-08 06:45:10 +00007423 QualType IntArrayType =
7424 Context->getConstantArrayType(Context->IntTy, Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00007425 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007426}
7427
Logan Chien57086ce2012-10-10 06:56:20 +00007428static TypedefDecl *
7429CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00007430 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00007431 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00007432 if (Context->getLangOpts().CPlusPlus) {
7433 // namespace std { struct __va_list {
7434 NamespaceDecl *NS;
7435 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
7436 Context->getTranslationUnitDecl(),
7437 /*Inline*/false, SourceLocation(),
7438 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00007439 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00007440 NS->setImplicit();
Logan Chien57086ce2012-10-10 06:56:20 +00007441 VaListDecl->setDeclContext(NS);
Logan Chien57086ce2012-10-10 06:56:20 +00007442 }
7443
7444 VaListDecl->startDefinition();
7445
7446 // void * __ap;
7447 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7448 VaListDecl,
7449 SourceLocation(),
7450 SourceLocation(),
7451 &Context->Idents.get("__ap"),
7452 Context->getPointerType(Context->VoidTy),
Craig Topper36250ad2014-05-12 05:36:57 +00007453 /*TInfo=*/nullptr,
7454 /*BitWidth=*/nullptr,
Logan Chien57086ce2012-10-10 06:56:20 +00007455 /*Mutable=*/false,
7456 ICIS_NoInit);
7457 Field->setAccess(AS_public);
7458 VaListDecl->addDecl(Field);
7459
7460 // };
7461 VaListDecl->completeDefinition();
Oleg Ranevskyyb88d2472016-03-30 21:30:30 +00007462 Context->VaListTagDecl = VaListDecl;
Logan Chien57086ce2012-10-10 06:56:20 +00007463
7464 // typedef struct __va_list __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00007465 QualType T = Context->getRecordType(VaListDecl);
7466 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00007467}
7468
Ulrich Weigand47445072013-05-06 16:26:41 +00007469static TypedefDecl *
7470CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00007471 // struct __va_list_tag {
Ulrich Weigand47445072013-05-06 16:26:41 +00007472 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00007473 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00007474 VaListTagDecl->startDefinition();
7475
7476 const size_t NumFields = 4;
7477 QualType FieldTypes[NumFields];
7478 const char *FieldNames[NumFields];
7479
7480 // long __gpr;
7481 FieldTypes[0] = Context->LongTy;
7482 FieldNames[0] = "__gpr";
7483
7484 // long __fpr;
7485 FieldTypes[1] = Context->LongTy;
7486 FieldNames[1] = "__fpr";
7487
7488 // void *__overflow_arg_area;
7489 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
7490 FieldNames[2] = "__overflow_arg_area";
7491
7492 // void *__reg_save_area;
7493 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
7494 FieldNames[3] = "__reg_save_area";
7495
7496 // Create fields
7497 for (unsigned i = 0; i < NumFields; ++i) {
7498 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7499 VaListTagDecl,
7500 SourceLocation(),
7501 SourceLocation(),
7502 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00007503 FieldTypes[i], /*TInfo=*/nullptr,
7504 /*BitWidth=*/nullptr,
Ulrich Weigand47445072013-05-06 16:26:41 +00007505 /*Mutable=*/false,
7506 ICIS_NoInit);
7507 Field->setAccess(AS_public);
7508 VaListTagDecl->addDecl(Field);
7509 }
7510 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00007511 Context->VaListTagDecl = VaListTagDecl;
Ulrich Weigand47445072013-05-06 16:26:41 +00007512 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Ulrich Weigand47445072013-05-06 16:26:41 +00007513
Richard Smith9b88a4c2015-07-27 05:40:23 +00007514 // };
Ulrich Weigand47445072013-05-06 16:26:41 +00007515
7516 // typedef __va_list_tag __builtin_va_list[1];
7517 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00007518 QualType VaListTagArrayType =
7519 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Ulrich Weigand47445072013-05-06 16:26:41 +00007520
Alp Toker56b5cc92013-12-15 10:36:26 +00007521 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Ulrich Weigand47445072013-05-06 16:26:41 +00007522}
7523
Meador Inge5d3fb222012-06-16 03:34:49 +00007524static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
7525 TargetInfo::BuiltinVaListKind Kind) {
7526 switch (Kind) {
7527 case TargetInfo::CharPtrBuiltinVaList:
7528 return CreateCharPtrBuiltinVaListDecl(Context);
7529 case TargetInfo::VoidPtrBuiltinVaList:
7530 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northover9bb857a2013-01-31 12:13:10 +00007531 case TargetInfo::AArch64ABIBuiltinVaList:
7532 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00007533 case TargetInfo::PowerABIBuiltinVaList:
7534 return CreatePowerABIBuiltinVaListDecl(Context);
7535 case TargetInfo::X86_64ABIBuiltinVaList:
7536 return CreateX86_64ABIBuiltinVaListDecl(Context);
7537 case TargetInfo::PNaClABIBuiltinVaList:
7538 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00007539 case TargetInfo::AAPCSABIBuiltinVaList:
7540 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigand47445072013-05-06 16:26:41 +00007541 case TargetInfo::SystemZBuiltinVaList:
7542 return CreateSystemZBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00007543 }
7544
7545 llvm_unreachable("Unhandled __builtin_va_list type kind");
7546}
7547
7548TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00007549 if (!BuiltinVaListDecl) {
Meador Inge5d3fb222012-06-16 03:34:49 +00007550 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
Alp Toker56b5cc92013-12-15 10:36:26 +00007551 assert(BuiltinVaListDecl->isImplicit());
7552 }
Meador Inge5d3fb222012-06-16 03:34:49 +00007553
7554 return BuiltinVaListDecl;
7555}
7556
Richard Smith9b88a4c2015-07-27 05:40:23 +00007557Decl *ASTContext::getVaListTagDecl() const {
7558 // Force the creation of VaListTagDecl by building the __builtin_va_list
Meador Ingecfb60902012-07-01 15:57:25 +00007559 // declaration.
Richard Smith9b88a4c2015-07-27 05:40:23 +00007560 if (!VaListTagDecl)
7561 (void)getBuiltinVaListDecl();
Meador Ingecfb60902012-07-01 15:57:25 +00007562
Richard Smith9b88a4c2015-07-27 05:40:23 +00007563 return VaListTagDecl;
Meador Ingecfb60902012-07-01 15:57:25 +00007564}
7565
Charles Davisc7d5c942015-09-17 20:55:33 +00007566TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const {
7567 if (!BuiltinMSVaListDecl)
7568 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
7569
7570 return BuiltinMSVaListDecl;
7571}
7572
Erich Keane41af9712018-04-16 21:30:08 +00007573bool ASTContext::canBuiltinBeRedeclared(const FunctionDecl *FD) const {
7574 return BuiltinInfo.canBeRedeclared(FD->getBuiltinID());
7575}
7576
Ted Kremenek1b0ea822008-01-07 19:49:32 +00007577void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00007578 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00007579 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00007580
Ted Kremenek1b0ea822008-01-07 19:49:32 +00007581 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00007582}
7583
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007584/// Retrieve the template name that corresponds to a non-empty
John McCalld28ae272009-12-02 08:04:21 +00007585/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00007586TemplateName
7587ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
7588 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00007589 unsigned size = End - Begin;
7590 assert(size > 1 && "set is not overloaded!");
7591
7592 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
7593 size * sizeof(FunctionTemplateDecl*));
Eugene Zelenko7855e772018-04-03 00:11:50 +00007594 auto *OT = new (memory) OverloadedTemplateStorage(size);
John McCalld28ae272009-12-02 08:04:21 +00007595
7596 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00007597 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00007598 NamedDecl *D = *I;
7599 assert(isa<FunctionTemplateDecl>(D) ||
Richard Smithef53a3e2018-06-06 16:36:56 +00007600 isa<UnresolvedUsingValueDecl>(D) ||
John McCalld28ae272009-12-02 08:04:21 +00007601 (isa<UsingShadowDecl>(D) &&
7602 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
7603 *Storage++ = D;
7604 }
7605
7606 return TemplateName(OT);
7607}
7608
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007609/// Retrieve the template name that represents a qualified
Douglas Gregordc572a32009-03-30 22:58:21 +00007610/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00007611TemplateName
7612ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
7613 bool TemplateKeyword,
7614 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00007615 assert(NNS && "Missing nested-name-specifier in qualified template name");
Fangrui Song6907ce22018-07-30 19:24:48 +00007616
Douglas Gregorc42075a2010-02-04 18:10:26 +00007617 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00007618 llvm::FoldingSetNodeID ID;
7619 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
7620
Craig Topper36250ad2014-05-12 05:36:57 +00007621 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00007622 QualifiedTemplateName *QTN =
7623 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7624 if (!QTN) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007625 QTN = new (*this, alignof(QualifiedTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007626 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00007627 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
7628 }
7629
7630 return TemplateName(QTN);
7631}
7632
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007633/// Retrieve the template name that represents a dependent
Douglas Gregordc572a32009-03-30 22:58:21 +00007634/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00007635TemplateName
7636ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
7637 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00007638 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00007639 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00007640
7641 llvm::FoldingSetNodeID ID;
7642 DependentTemplateName::Profile(ID, NNS, Name);
7643
Craig Topper36250ad2014-05-12 05:36:57 +00007644 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00007645 DependentTemplateName *QTN =
7646 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7647
7648 if (QTN)
7649 return TemplateName(QTN);
7650
7651 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
7652 if (CanonNNS == NNS) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007653 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007654 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00007655 } else {
7656 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007657 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007658 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00007659 DependentTemplateName *CheckQTN =
7660 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7661 assert(!CheckQTN && "Dependent type name canonicalization broken");
7662 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00007663 }
7664
7665 DependentTemplateNames.InsertNode(QTN, InsertPos);
7666 return TemplateName(QTN);
7667}
7668
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007669/// Retrieve the template name that represents a dependent
Douglas Gregor71395fa2009-11-04 00:56:37 +00007670/// template name such as \c MetaFun::template operator+.
Fangrui Song6907ce22018-07-30 19:24:48 +00007671TemplateName
Douglas Gregor71395fa2009-11-04 00:56:37 +00007672ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00007673 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00007674 assert((!NNS || NNS->isDependent()) &&
7675 "Nested name specifier must be dependent");
Fangrui Song6907ce22018-07-30 19:24:48 +00007676
Douglas Gregor71395fa2009-11-04 00:56:37 +00007677 llvm::FoldingSetNodeID ID;
7678 DependentTemplateName::Profile(ID, NNS, Operator);
Craig Topper36250ad2014-05-12 05:36:57 +00007679
7680 void *InsertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00007681 DependentTemplateName *QTN
7682 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Fangrui Song6907ce22018-07-30 19:24:48 +00007683
Douglas Gregor71395fa2009-11-04 00:56:37 +00007684 if (QTN)
7685 return TemplateName(QTN);
Fangrui Song6907ce22018-07-30 19:24:48 +00007686
Douglas Gregor71395fa2009-11-04 00:56:37 +00007687 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
7688 if (CanonNNS == NNS) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007689 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007690 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00007691 } else {
7692 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007693 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007694 DependentTemplateName(NNS, Operator, Canon);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007695
Douglas Gregorc42075a2010-02-04 18:10:26 +00007696 DependentTemplateName *CheckQTN
7697 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7698 assert(!CheckQTN && "Dependent template name canonicalization broken");
7699 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00007700 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007701
Douglas Gregor71395fa2009-11-04 00:56:37 +00007702 DependentTemplateNames.InsertNode(QTN, InsertPos);
7703 return TemplateName(QTN);
7704}
7705
Fangrui Song6907ce22018-07-30 19:24:48 +00007706TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00007707ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
7708 TemplateName replacement) const {
7709 llvm::FoldingSetNodeID ID;
7710 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00007711
7712 void *insertPos = nullptr;
John McCalld9dfe3a2011-06-30 08:33:18 +00007713 SubstTemplateTemplateParmStorage *subst
7714 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
Fangrui Song6907ce22018-07-30 19:24:48 +00007715
John McCalld9dfe3a2011-06-30 08:33:18 +00007716 if (!subst) {
7717 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
7718 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
7719 }
7720
7721 return TemplateName(subst);
7722}
7723
Fangrui Song6907ce22018-07-30 19:24:48 +00007724TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00007725ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
7726 const TemplateArgument &ArgPack) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00007727 auto &Self = const_cast<ASTContext &>(*this);
Douglas Gregor5590be02011-01-15 06:45:20 +00007728 llvm::FoldingSetNodeID ID;
7729 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00007730
7731 void *InsertPos = nullptr;
Douglas Gregor5590be02011-01-15 06:45:20 +00007732 SubstTemplateTemplateParmPackStorage *Subst
7733 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
Fangrui Song6907ce22018-07-30 19:24:48 +00007734
Douglas Gregor5590be02011-01-15 06:45:20 +00007735 if (!Subst) {
Fangrui Song6907ce22018-07-30 19:24:48 +00007736 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00007737 ArgPack.pack_size(),
7738 ArgPack.pack_begin());
7739 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
7740 }
7741
7742 return TemplateName(Subst);
7743}
7744
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007745/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00007746/// TargetInfo, produce the corresponding type. The unsigned @p Type
7747/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00007748CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007749 switch (Type) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00007750 case TargetInfo::NoInt: return {};
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00007751 case TargetInfo::SignedChar: return SignedCharTy;
7752 case TargetInfo::UnsignedChar: return UnsignedCharTy;
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007753 case TargetInfo::SignedShort: return ShortTy;
7754 case TargetInfo::UnsignedShort: return UnsignedShortTy;
7755 case TargetInfo::SignedInt: return IntTy;
7756 case TargetInfo::UnsignedInt: return UnsignedIntTy;
7757 case TargetInfo::SignedLong: return LongTy;
7758 case TargetInfo::UnsignedLong: return UnsignedLongTy;
7759 case TargetInfo::SignedLongLong: return LongLongTy;
7760 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
7761 }
7762
David Blaikie83d382b2011-09-23 05:06:16 +00007763 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007764}
Ted Kremenek77c51b22008-07-24 23:58:27 +00007765
7766//===----------------------------------------------------------------------===//
7767// Type Predicates.
7768//===----------------------------------------------------------------------===//
7769
Fariborz Jahanian96207692009-02-18 21:49:28 +00007770/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
7771/// garbage collection attribute.
7772///
John McCall553d45a2011-01-12 00:34:59 +00007773Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007774 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00007775 return Qualifiers::GCNone;
7776
Erik Pilkingtonfa983902018-10-30 20:31:30 +00007777 assert(getLangOpts().ObjC);
John McCall553d45a2011-01-12 00:34:59 +00007778 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
7779
7780 // Default behaviour under objective-C's gc is for ObjC pointers
7781 // (or pointers to them) be treated as though they were declared
7782 // as __strong.
7783 if (GCAttrs == Qualifiers::GCNone) {
7784 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
7785 return Qualifiers::Strong;
7786 else if (Ty->isPointerType())
7787 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
7788 } else {
7789 // It's not valid to set GC attributes on anything that isn't a
7790 // pointer.
7791#ifndef NDEBUG
7792 QualType CT = Ty->getCanonicalTypeInternal();
Eugene Zelenko7855e772018-04-03 00:11:50 +00007793 while (const auto *AT = dyn_cast<ArrayType>(CT))
John McCall553d45a2011-01-12 00:34:59 +00007794 CT = AT->getElementType();
7795 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
7796#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00007797 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00007798 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00007799}
7800
Chris Lattner49af6a42008-04-07 06:51:04 +00007801//===----------------------------------------------------------------------===//
7802// Type Compatibility Testing
7803//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00007804
Mike Stump11289f42009-09-09 15:08:12 +00007805/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00007806/// compatible.
7807static bool areCompatVectorTypes(const VectorType *LHS,
7808 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00007809 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00007810 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00007811 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00007812}
7813
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007814bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
7815 QualType SecondVec) {
7816 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
7817 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
7818
7819 if (hasSameUnqualifiedType(FirstVec, SecondVec))
7820 return true;
7821
Bob Wilsone6aeebb2010-11-12 17:24:54 +00007822 // Treat Neon vector types and most AltiVec vector types as if they are the
7823 // equivalent GCC vector types.
Eugene Zelenko7855e772018-04-03 00:11:50 +00007824 const auto *First = FirstVec->getAs<VectorType>();
7825 const auto *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00007826 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007827 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00007828 First->getVectorKind() != VectorType::AltiVecPixel &&
7829 First->getVectorKind() != VectorType::AltiVecBool &&
7830 Second->getVectorKind() != VectorType::AltiVecPixel &&
7831 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007832 return true;
7833
7834 return false;
7835}
7836
Steve Naroff8e6aee52009-07-23 01:01:38 +00007837//===----------------------------------------------------------------------===//
7838// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
7839//===----------------------------------------------------------------------===//
7840
7841/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
7842/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00007843bool
7844ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
7845 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00007846 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00007847 return true;
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00007848 for (auto *PI : rProto->protocols())
7849 if (ProtocolCompatibleWithProtocol(lProto, PI))
Steve Naroff8e6aee52009-07-23 01:01:38 +00007850 return true;
7851 return false;
7852}
7853
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00007854/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
7855/// Class<pr1, ...>.
Fangrui Song6907ce22018-07-30 19:24:48 +00007856bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007857 QualType rhs) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00007858 const auto *lhsQID = lhs->getAs<ObjCObjectPointerType>();
7859 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00007860 assert((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
Fangrui Song6907ce22018-07-30 19:24:48 +00007861
Aaron Ballman83731462014-03-17 16:14:00 +00007862 for (auto *lhsProto : lhsQID->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007863 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00007864 for (auto *rhsProto : rhsOPT->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007865 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
7866 match = true;
7867 break;
7868 }
7869 }
7870 if (!match)
7871 return false;
7872 }
7873 return true;
7874}
7875
Steve Naroff8e6aee52009-07-23 01:01:38 +00007876/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
7877/// ObjCQualifiedIDType.
7878bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
7879 bool compare) {
7880 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00007881 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00007882 lhs->isObjCIdType() || lhs->isObjCClassType())
7883 return true;
Mike Stump11289f42009-09-09 15:08:12 +00007884 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00007885 rhs->isObjCIdType() || rhs->isObjCClassType())
7886 return true;
7887
7888 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00007889 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00007890
Steve Naroff8e6aee52009-07-23 01:01:38 +00007891 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00007892
Steve Naroff8e6aee52009-07-23 01:01:38 +00007893 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00007894 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00007895 // make sure we check the class hierarchy.
7896 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00007897 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007898 // when comparing an id<P> on lhs with a static type on rhs,
7899 // see if static class implements all of id's protocols, directly or
7900 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00007901 if (!rhsID->ClassImplementsProtocol(I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00007902 return false;
7903 }
7904 }
7905 // If there are no qualifiers and no interface, we have an 'id'.
7906 return true;
7907 }
Mike Stump11289f42009-09-09 15:08:12 +00007908 // Both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00007909 for (auto *lhsProto : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007910 bool match = false;
7911
7912 // when comparing an id<P> on lhs with a static type on rhs,
7913 // see if static class implements all of id's protocols, directly or
7914 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00007915 for (auto *rhsProto : rhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007916 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7917 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7918 match = true;
7919 break;
7920 }
7921 }
Mike Stump11289f42009-09-09 15:08:12 +00007922 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00007923 // make sure we check the class hierarchy.
7924 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00007925 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007926 // when comparing an id<P> on lhs with a static type on rhs,
7927 // see if static class implements all of id's protocols, directly or
7928 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00007929 if (rhsID->ClassImplementsProtocol(I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007930 match = true;
7931 break;
7932 }
7933 }
7934 }
7935 if (!match)
7936 return false;
7937 }
Mike Stump11289f42009-09-09 15:08:12 +00007938
Steve Naroff8e6aee52009-07-23 01:01:38 +00007939 return true;
7940 }
Mike Stump11289f42009-09-09 15:08:12 +00007941
Steve Naroff8e6aee52009-07-23 01:01:38 +00007942 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
7943 assert(rhsQID && "One of the LHS/RHS should be id<x>");
7944
Mike Stump11289f42009-09-09 15:08:12 +00007945 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00007946 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007947 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00007948 for (auto *lhsProto : lhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007949 bool match = false;
7950
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007951 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00007952 // see if static class implements all of id's protocols, directly or
7953 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007954 // First, lhs protocols in the qualifier list must be found, direct
7955 // or indirect in rhs's qualifier list or it is a mismatch.
Aaron Ballman83731462014-03-17 16:14:00 +00007956 for (auto *rhsProto : rhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007957 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7958 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7959 match = true;
7960 break;
7961 }
7962 }
7963 if (!match)
7964 return false;
7965 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007966
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007967 // Static class's protocols, or its super class or category protocols
7968 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
7969 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
7970 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
7971 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
7972 // This is rather dubious but matches gcc's behavior. If lhs has
7973 // no type qualifier and its class has no static protocol(s)
7974 // assume that it is mismatch.
7975 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
7976 return false;
Aaron Ballman83731462014-03-17 16:14:00 +00007977 for (auto *lhsProto : LHSInheritedProtocols) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007978 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00007979 for (auto *rhsProto : rhsQID->quals()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007980 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7981 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7982 match = true;
7983 break;
7984 }
7985 }
7986 if (!match)
7987 return false;
7988 }
7989 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00007990 return true;
7991 }
7992 return false;
7993}
7994
Eli Friedman47f77112008-08-22 00:56:42 +00007995/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00007996/// compatible for assignment from RHS to LHS. This handles validation of any
7997/// protocol qualifiers on the LHS or RHS.
Steve Naroff7cae42b2009-07-10 23:34:53 +00007998bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
7999 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00008000 const ObjCObjectType* LHS = LHSOPT->getObjectType();
8001 const ObjCObjectType* RHS = RHSOPT->getObjectType();
8002
Steve Naroff1329fa02009-07-15 18:40:39 +00008003 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00008004 if (LHS->isObjCUnqualifiedIdOrClass() ||
8005 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00008006 return true;
8007
Douglas Gregorab209d82015-07-07 03:58:42 +00008008 // Function object that propagates a successful result or handles
8009 // __kindof types.
8010 auto finish = [&](bool succeeded) -> bool {
8011 if (succeeded)
8012 return true;
8013
8014 if (!RHS->isKindOfType())
8015 return false;
8016
8017 // Strip off __kindof and protocol qualifiers, then check whether
8018 // we can assign the other way.
8019 return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this),
8020 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
8021 };
8022
8023 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
8024 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
8025 QualType(RHSOPT,0),
8026 false));
8027 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008028
Douglas Gregorab209d82015-07-07 03:58:42 +00008029 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
8030 return finish(ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
8031 QualType(RHSOPT,0)));
8032 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008033
John McCall8b07ec22010-05-15 11:32:37 +00008034 // If we have 2 user-defined types, fall into that path.
Douglas Gregorab209d82015-07-07 03:58:42 +00008035 if (LHS->getInterface() && RHS->getInterface()) {
8036 return finish(canAssignObjCInterfaces(LHS, RHS));
8037 }
Mike Stump11289f42009-09-09 15:08:12 +00008038
Steve Naroff8e6aee52009-07-23 01:01:38 +00008039 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00008040}
8041
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008042/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Fangrui Song6907ce22018-07-30 19:24:48 +00008043/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008044/// arguments in block literals. When passed as arguments, passing 'A*' where
8045/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
8046/// not OK. For the return type, the opposite is not OK.
8047bool ASTContext::canAssignObjCInterfacesInBlockPointer(
8048 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00008049 const ObjCObjectPointerType *RHSOPT,
8050 bool BlockReturnType) {
Douglas Gregorab209d82015-07-07 03:58:42 +00008051
8052 // Function object that propagates a successful result or handles
8053 // __kindof types.
8054 auto finish = [&](bool succeeded) -> bool {
8055 if (succeeded)
8056 return true;
8057
8058 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
8059 if (!Expected->isKindOfType())
8060 return false;
8061
8062 // Strip off __kindof and protocol qualifiers, then check whether
8063 // we can assign the other way.
8064 return canAssignObjCInterfacesInBlockPointer(
8065 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
8066 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
8067 BlockReturnType);
8068 };
8069
Fariborz Jahanian440a6832010-04-06 17:23:39 +00008070 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008071 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00008072
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008073 if (LHSOPT->isObjCBuiltinType()) {
Douglas Gregorab209d82015-07-07 03:58:42 +00008074 return finish(RHSOPT->isObjCBuiltinType() ||
8075 RHSOPT->isObjCQualifiedIdType());
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008076 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008077
Fariborz Jahanian440a6832010-04-06 17:23:39 +00008078 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Douglas Gregorab209d82015-07-07 03:58:42 +00008079 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
8080 QualType(RHSOPT,0),
8081 false));
Fangrui Song6907ce22018-07-30 19:24:48 +00008082
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008083 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
8084 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
8085 if (LHS && RHS) { // We have 2 user-defined types.
8086 if (LHS != RHS) {
8087 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00008088 return finish(BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008089 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00008090 return finish(!BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008091 }
8092 else
8093 return true;
8094 }
8095 return false;
8096}
8097
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008098/// Comparison routine for Objective-C protocols to be used with
8099/// llvm::array_pod_sort.
8100static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
8101 ObjCProtocolDecl * const *rhs) {
8102 return (*lhs)->getName().compare((*rhs)->getName());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008103}
8104
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008105/// getIntersectionOfProtocols - This routine finds the intersection of set
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008106/// of protocols inherited from two distinct objective-c pointer objects with
8107/// the given common base.
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008108/// It is used to build composite qualifier list of the composite type of
8109/// the conditional expression involving two objective-c pointer objects.
Fangrui Song6907ce22018-07-30 19:24:48 +00008110static
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008111void getIntersectionOfProtocols(ASTContext &Context,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008112 const ObjCInterfaceDecl *CommonBase,
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008113 const ObjCObjectPointerType *LHSOPT,
8114 const ObjCObjectPointerType *RHSOPT,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008115 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
Fangrui Song6907ce22018-07-30 19:24:48 +00008116
John McCall8b07ec22010-05-15 11:32:37 +00008117 const ObjCObjectType* LHS = LHSOPT->getObjectType();
8118 const ObjCObjectType* RHS = RHSOPT->getObjectType();
8119 assert(LHS->getInterface() && "LHS must have an interface base");
8120 assert(RHS->getInterface() && "RHS must have an interface base");
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008121
8122 // Add all of the protocols for the LHS.
8123 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
8124
8125 // Start with the protocol qualifiers.
8126 for (auto proto : LHS->quals()) {
8127 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008128 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008129
8130 // Also add the protocols associated with the LHS interface.
8131 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
8132
Raphael Isemannb23ccec2018-12-10 12:37:46 +00008133 // Add all of the protocols for the RHS.
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008134 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
8135
8136 // Start with the protocol qualifiers.
8137 for (auto proto : RHS->quals()) {
8138 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008139 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008140
8141 // Also add the protocols associated with the RHS interface.
8142 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
8143
8144 // Compute the intersection of the collected protocol sets.
8145 for (auto proto : LHSProtocolSet) {
8146 if (RHSProtocolSet.count(proto))
8147 IntersectionSet.push_back(proto);
8148 }
8149
8150 // Compute the set of protocols that is implied by either the common type or
8151 // the protocols within the intersection.
8152 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
8153 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
8154
8155 // Remove any implied protocols from the list of inherited protocols.
8156 if (!ImpliedProtocols.empty()) {
8157 IntersectionSet.erase(
8158 std::remove_if(IntersectionSet.begin(),
8159 IntersectionSet.end(),
8160 [&](ObjCProtocolDecl *proto) -> bool {
8161 return ImpliedProtocols.count(proto) > 0;
8162 }),
8163 IntersectionSet.end());
8164 }
8165
8166 // Sort the remaining protocols by name.
8167 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
8168 compareObjCProtocolsByName);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008169}
8170
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008171/// Determine whether the first type is a subtype of the second.
8172static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
8173 QualType rhs) {
8174 // Common case: two object pointers.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008175 const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
8176 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008177 if (lhsOPT && rhsOPT)
8178 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
8179
8180 // Two block pointers.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008181 const auto *lhsBlock = lhs->getAs<BlockPointerType>();
8182 const auto *rhsBlock = rhs->getAs<BlockPointerType>();
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008183 if (lhsBlock && rhsBlock)
8184 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
8185
8186 // If either is an unqualified 'id' and the other is a block, it's
8187 // acceptable.
8188 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
8189 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
8190 return true;
8191
8192 return false;
8193}
8194
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008195// Check that the given Objective-C type argument lists are equivalent.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008196static bool sameObjCTypeArgs(ASTContext &ctx,
8197 const ObjCInterfaceDecl *iface,
8198 ArrayRef<QualType> lhsArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00008199 ArrayRef<QualType> rhsArgs,
8200 bool stripKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008201 if (lhsArgs.size() != rhsArgs.size())
8202 return false;
8203
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008204 ObjCTypeParamList *typeParams = iface->getTypeParamList();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008205 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008206 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
8207 continue;
8208
8209 switch (typeParams->begin()[i]->getVariance()) {
8210 case ObjCTypeParamVariance::Invariant:
Douglas Gregorab209d82015-07-07 03:58:42 +00008211 if (!stripKindOf ||
8212 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
8213 rhsArgs[i].stripObjCKindOfType(ctx))) {
8214 return false;
8215 }
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008216 break;
8217
8218 case ObjCTypeParamVariance::Covariant:
8219 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
8220 return false;
8221 break;
8222
8223 case ObjCTypeParamVariance::Contravariant:
8224 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
8225 return false;
8226 break;
Douglas Gregorab209d82015-07-07 03:58:42 +00008227 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008228 }
8229
8230 return true;
8231}
8232
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00008233QualType ASTContext::areCommonBaseCompatible(
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008234 const ObjCObjectPointerType *Lptr,
8235 const ObjCObjectPointerType *Rptr) {
John McCall8b07ec22010-05-15 11:32:37 +00008236 const ObjCObjectType *LHS = Lptr->getObjectType();
8237 const ObjCObjectType *RHS = Rptr->getObjectType();
8238 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
8239 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008240
8241 if (!LDecl || !RDecl)
Eugene Zelenko7855e772018-04-03 00:11:50 +00008242 return {};
Douglas Gregore83b9562015-07-07 03:57:53 +00008243
Manman Renc46f7d12016-05-06 19:35:02 +00008244 // When either LHS or RHS is a kindof type, we should return a kindof type.
8245 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
8246 // kindof(A).
8247 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
8248
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008249 // Follow the left-hand side up the class hierarchy until we either hit a
8250 // root or find the RHS. Record the ancestors in case we don't find it.
8251 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
8252 LHSAncestors;
8253 while (true) {
8254 // Record this ancestor. We'll need this if the common type isn't in the
8255 // path from the LHS to the root.
8256 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
Douglas Gregore83b9562015-07-07 03:57:53 +00008257
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008258 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
8259 // Get the type arguments.
8260 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
8261 bool anyChanges = false;
8262 if (LHS->isSpecialized() && RHS->isSpecialized()) {
8263 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008264 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
8265 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00008266 /*stripKindOf=*/true))
Eugene Zelenko7855e772018-04-03 00:11:50 +00008267 return {};
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008268 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
8269 // If only one has type arguments, the result will not have type
8270 // arguments.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00008271 LHSTypeArgs = {};
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008272 anyChanges = true;
8273 }
8274
8275 // Compute the intersection of protocols.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008276 SmallVector<ObjCProtocolDecl *, 8> Protocols;
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008277 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
8278 Protocols);
John McCall8b07ec22010-05-15 11:32:37 +00008279 if (!Protocols.empty())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008280 anyChanges = true;
8281
8282 // If anything in the LHS will have changed, build a new result type.
Manman Renc46f7d12016-05-06 19:35:02 +00008283 // If we need to return a kindof type but LHS is not a kindof type, we
8284 // build a new result type.
8285 if (anyChanges || LHS->isKindOfType() != anyKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008286 QualType Result = getObjCInterfaceType(LHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00008287 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
Manman Renc46f7d12016-05-06 19:35:02 +00008288 anyKindOf || LHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008289 return getObjCObjectPointerType(Result);
8290 }
8291
8292 return getObjCObjectPointerType(QualType(LHS, 0));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008293 }
Douglas Gregore83b9562015-07-07 03:57:53 +00008294
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008295 // Find the superclass.
Douglas Gregore83b9562015-07-07 03:57:53 +00008296 QualType LHSSuperType = LHS->getSuperClassType();
8297 if (LHSSuperType.isNull())
8298 break;
8299
8300 LHS = LHSSuperType->castAs<ObjCObjectType>();
8301 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008302
8303 // We didn't find anything by following the LHS to its root; now check
8304 // the RHS against the cached set of ancestors.
8305 while (true) {
8306 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
8307 if (KnownLHS != LHSAncestors.end()) {
8308 LHS = KnownLHS->second;
8309
8310 // Get the type arguments.
8311 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
8312 bool anyChanges = false;
8313 if (LHS->isSpecialized() && RHS->isSpecialized()) {
8314 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008315 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
8316 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00008317 /*stripKindOf=*/true))
Eugene Zelenko7855e772018-04-03 00:11:50 +00008318 return {};
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008319 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
8320 // If only one has type arguments, the result will not have type
8321 // arguments.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00008322 RHSTypeArgs = {};
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008323 anyChanges = true;
8324 }
8325
8326 // Compute the intersection of protocols.
8327 SmallVector<ObjCProtocolDecl *, 8> Protocols;
8328 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
8329 Protocols);
8330 if (!Protocols.empty())
8331 anyChanges = true;
8332
Manman Renc46f7d12016-05-06 19:35:02 +00008333 // If we need to return a kindof type but RHS is not a kindof type, we
8334 // build a new result type.
8335 if (anyChanges || RHS->isKindOfType() != anyKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008336 QualType Result = getObjCInterfaceType(RHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00008337 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
Manman Renc46f7d12016-05-06 19:35:02 +00008338 anyKindOf || RHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008339 return getObjCObjectPointerType(Result);
8340 }
8341
8342 return getObjCObjectPointerType(QualType(RHS, 0));
8343 }
8344
8345 // Find the superclass of the RHS.
8346 QualType RHSSuperType = RHS->getSuperClassType();
8347 if (RHSSuperType.isNull())
8348 break;
8349
8350 RHS = RHSSuperType->castAs<ObjCObjectType>();
8351 }
8352
Eugene Zelenko7855e772018-04-03 00:11:50 +00008353 return {};
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00008354}
8355
John McCall8b07ec22010-05-15 11:32:37 +00008356bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
8357 const ObjCObjectType *RHS) {
8358 assert(LHS->getInterface() && "LHS is not an interface type");
8359 assert(RHS->getInterface() && "RHS is not an interface type");
8360
Chris Lattner49af6a42008-04-07 06:51:04 +00008361 // Verify that the base decls are compatible: the RHS must be a subclass of
8362 // the LHS.
Douglas Gregore83b9562015-07-07 03:57:53 +00008363 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
8364 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
8365 if (!IsSuperClass)
Chris Lattner49af6a42008-04-07 06:51:04 +00008366 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008367
Douglas Gregore83b9562015-07-07 03:57:53 +00008368 // If the LHS has protocol qualifiers, determine whether all of them are
8369 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
8370 // LHS).
8371 if (LHS->getNumProtocols() > 0) {
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00008372 // OK if conversion of LHS to SuperClass results in narrowing of types
8373 // ; i.e., SuperClass may implement at least one of the protocols
8374 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
8375 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
8376 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
8377 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
8378 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
8379 // qualifiers.
8380 for (auto *RHSPI : RHS->quals())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008381 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00008382 // If there is no protocols associated with RHS, it is not a match.
8383 if (SuperClassInheritedProtocols.empty())
Steve Naroff114aecb2009-03-01 16:12:44 +00008384 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00008385
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00008386 for (const auto *LHSProto : LHS->quals()) {
8387 bool SuperImplementsProtocol = false;
8388 for (auto *SuperClassProto : SuperClassInheritedProtocols)
8389 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
8390 SuperImplementsProtocol = true;
8391 break;
8392 }
8393 if (!SuperImplementsProtocol)
8394 return false;
8395 }
Chris Lattner49af6a42008-04-07 06:51:04 +00008396 }
Douglas Gregore83b9562015-07-07 03:57:53 +00008397
8398 // If the LHS is specialized, we may need to check type arguments.
8399 if (LHS->isSpecialized()) {
8400 // Follow the superclass chain until we've matched the LHS class in the
8401 // hierarchy. This substitutes type arguments through.
8402 const ObjCObjectType *RHSSuper = RHS;
8403 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
8404 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
8405
8406 // If the RHS is specializd, compare type arguments.
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008407 if (RHSSuper->isSpecialized() &&
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008408 !sameObjCTypeArgs(*this, LHS->getInterface(),
8409 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00008410 /*stripKindOf=*/true)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008411 return false;
Douglas Gregore83b9562015-07-07 03:57:53 +00008412 }
8413 }
8414
8415 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00008416}
8417
Steve Naroffb7605152009-02-12 17:52:19 +00008418bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
8419 // get the "pointed to" types
Eugene Zelenko7855e772018-04-03 00:11:50 +00008420 const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
8421 const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00008422
Steve Naroff7cae42b2009-07-10 23:34:53 +00008423 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00008424 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00008425
8426 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
8427 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00008428}
8429
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00008430bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
8431 return canAssignObjCInterfaces(
8432 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
8433 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
8434}
8435
Mike Stump11289f42009-09-09 15:08:12 +00008436/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00008437/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00008438/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00008439/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008440bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
8441 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00008442 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00008443 return hasSameType(LHS, RHS);
Joey Gouly5788b782016-11-18 14:10:54 +00008444
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008445 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00008446}
8447
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00008448bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00008449 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00008450}
8451
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008452bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
8453 return !mergeTypes(LHS, RHS, true).isNull();
8454}
8455
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00008456/// mergeTransparentUnionType - if T is a transparent union type and a member
8457/// of T is compatible with SubType, return the merged type, else return
8458/// QualType()
8459QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
8460 bool OfBlockPointer,
8461 bool Unqualified) {
8462 if (const RecordType *UT = T->getAsUnionType()) {
8463 RecordDecl *UD = UT->getDecl();
8464 if (UD->hasAttr<TransparentUnionAttr>()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008465 for (const auto *I : UD->fields()) {
8466 QualType ET = I->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00008467 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
8468 if (!MT.isNull())
8469 return MT;
8470 }
8471 }
8472 }
8473
Eugene Zelenko7855e772018-04-03 00:11:50 +00008474 return {};
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00008475}
8476
Alp Toker9cacbab2014-01-20 20:26:09 +00008477/// mergeFunctionParameterTypes - merge two types which appear as function
8478/// parameter types
8479QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
8480 bool OfBlockPointer,
8481 bool Unqualified) {
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00008482 // GNU extension: two types are compatible if they appear as a function
8483 // argument, one of the types is a transparent union type and the other
8484 // type is compatible with a union member
8485 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
8486 Unqualified);
8487 if (!lmerge.isNull())
8488 return lmerge;
8489
8490 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
8491 Unqualified);
8492 if (!rmerge.isNull())
8493 return rmerge;
8494
8495 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
8496}
8497
Fangrui Song6907ce22018-07-30 19:24:48 +00008498QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008499 bool OfBlockPointer,
8500 bool Unqualified) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00008501 const auto *lbase = lhs->getAs<FunctionType>();
8502 const auto *rbase = rhs->getAs<FunctionType>();
8503 const auto *lproto = dyn_cast<FunctionProtoType>(lbase);
8504 const auto *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00008505 bool allLTypes = true;
8506 bool allRTypes = true;
8507
8508 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008509 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00008510 if (OfBlockPointer) {
Alp Toker314cc812014-01-25 16:55:45 +00008511 QualType RHS = rbase->getReturnType();
8512 QualType LHS = lbase->getReturnType();
Fariborz Jahanian17825972011-02-11 18:46:17 +00008513 bool UnqualifiedResult = Unqualified;
8514 if (!UnqualifiedResult)
8515 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00008516 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00008517 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008518 else
Alp Toker314cc812014-01-25 16:55:45 +00008519 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
John McCall8c6b56f2010-12-15 01:06:38 +00008520 Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00008521 if (retType.isNull())
8522 return {};
Fangrui Song6907ce22018-07-30 19:24:48 +00008523
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008524 if (Unqualified)
8525 retType = retType.getUnqualifiedType();
8526
Alp Toker314cc812014-01-25 16:55:45 +00008527 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
8528 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008529 if (Unqualified) {
8530 LRetType = LRetType.getUnqualifiedType();
8531 RRetType = RRetType.getUnqualifiedType();
8532 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008533
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008534 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00008535 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008536 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00008537 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00008538
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00008539 // FIXME: double check this
8540 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
8541 // rbase->getRegParmAttr() != 0 &&
8542 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00008543 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
8544 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00008545
Douglas Gregor8c940862010-01-18 17:14:39 +00008546 // Compatible functions must have compatible calling conventions
Reid Kleckner78af0702013-08-27 23:08:25 +00008547 if (lbaseInfo.getCC() != rbaseInfo.getCC())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008548 return {};
Mike Stump11289f42009-09-09 15:08:12 +00008549
John McCall8c6b56f2010-12-15 01:06:38 +00008550 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00008551 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008552 return {};
John McCall8c6b56f2010-12-15 01:06:38 +00008553 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008554 return {};
John McCall8c6b56f2010-12-15 01:06:38 +00008555
John McCall31168b02011-06-15 23:02:42 +00008556 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008557 return {};
Oren Ben Simhon318a6ea2017-04-27 12:01:00 +00008558 if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008559 return {};
Oren Ben Simhon220671a2018-03-17 13:31:35 +00008560 if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008561 return {};
John McCall31168b02011-06-15 23:02:42 +00008562
John McCall8c6b56f2010-12-15 01:06:38 +00008563 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
8564 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00008565
Rafael Espindola8778c282012-11-29 16:09:03 +00008566 if (lbaseInfo.getNoReturn() != NoReturn)
8567 allLTypes = false;
8568 if (rbaseInfo.getNoReturn() != NoReturn)
8569 allRTypes = false;
8570
John McCall31168b02011-06-15 23:02:42 +00008571 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00008572
Eli Friedman47f77112008-08-22 00:56:42 +00008573 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00008574 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
8575 "C++ shouldn't be here");
Alp Toker601b22c2014-01-21 23:35:24 +00008576 // Compatible functions must have the same number of parameters
8577 if (lproto->getNumParams() != rproto->getNumParams())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008578 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00008579
8580 // Variadic and non-variadic functions aren't compatible
8581 if (lproto->isVariadic() != rproto->isVariadic())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008582 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00008583
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00008584 if (lproto->getTypeQuals() != rproto->getTypeQuals())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008585 return {};
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00008586
Akira Hatanaka98a49332017-09-22 00:41:05 +00008587 SmallVector<FunctionProtoType::ExtParameterInfo, 4> newParamInfos;
8588 bool canUseLeft, canUseRight;
8589 if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight,
8590 newParamInfos))
Eugene Zelenko7855e772018-04-03 00:11:50 +00008591 return {};
Alp Toker601b22c2014-01-21 23:35:24 +00008592
Akira Hatanaka98a49332017-09-22 00:41:05 +00008593 if (!canUseLeft)
8594 allLTypes = false;
8595 if (!canUseRight)
8596 allRTypes = false;
8597
Alp Toker601b22c2014-01-21 23:35:24 +00008598 // Check parameter type compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008599 SmallVector<QualType, 10> types;
Alp Toker601b22c2014-01-21 23:35:24 +00008600 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
8601 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
8602 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
8603 QualType paramType = mergeFunctionParameterTypes(
8604 lParamType, rParamType, OfBlockPointer, Unqualified);
8605 if (paramType.isNull())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008606 return {};
Alp Toker601b22c2014-01-21 23:35:24 +00008607
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008608 if (Unqualified)
Alp Toker601b22c2014-01-21 23:35:24 +00008609 paramType = paramType.getUnqualifiedType();
8610
8611 types.push_back(paramType);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008612 if (Unqualified) {
Alp Toker601b22c2014-01-21 23:35:24 +00008613 lParamType = lParamType.getUnqualifiedType();
8614 rParamType = rParamType.getUnqualifiedType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008615 }
Alp Toker601b22c2014-01-21 23:35:24 +00008616
8617 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00008618 allLTypes = false;
Alp Toker601b22c2014-01-21 23:35:24 +00008619 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00008620 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00008621 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008622
Eli Friedman47f77112008-08-22 00:56:42 +00008623 if (allLTypes) return lhs;
8624 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00008625
8626 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
8627 EPI.ExtInfo = einfo;
Akira Hatanaka98a49332017-09-22 00:41:05 +00008628 EPI.ExtParameterInfos =
8629 newParamInfos.empty() ? nullptr : newParamInfos.data();
Jordan Rose5c382722013-03-08 21:51:21 +00008630 return getFunctionType(retType, types, EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00008631 }
8632
8633 if (lproto) allRTypes = false;
8634 if (rproto) allLTypes = false;
8635
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008636 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00008637 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00008638 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eugene Zelenko7855e772018-04-03 00:11:50 +00008639 if (proto->isVariadic())
8640 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00008641 // Check that the types are compatible with the types that
8642 // would result from default argument promotions (C99 6.7.5.3p15).
8643 // The only types actually affected are promotable integer
8644 // types and floats, which would be passed as a different
8645 // type depending on whether the prototype is visible.
Alp Toker601b22c2014-01-21 23:35:24 +00008646 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
8647 QualType paramTy = proto->getParamType(i);
Alp Toker9cacbab2014-01-20 20:26:09 +00008648
Eli Friedman448ce402012-08-30 00:44:15 +00008649 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00008650 // to pass enum values.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008651 if (const auto *Enum = paramTy->getAs<EnumType>()) {
Alp Toker601b22c2014-01-21 23:35:24 +00008652 paramTy = Enum->getDecl()->getIntegerType();
8653 if (paramTy.isNull())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008654 return {};
Eli Friedman448ce402012-08-30 00:44:15 +00008655 }
Alp Toker601b22c2014-01-21 23:35:24 +00008656
8657 if (paramTy->isPromotableIntegerType() ||
8658 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
Eugene Zelenko7855e772018-04-03 00:11:50 +00008659 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00008660 }
8661
8662 if (allLTypes) return lhs;
8663 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00008664
8665 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
8666 EPI.ExtInfo = einfo;
Alp Toker9cacbab2014-01-20 20:26:09 +00008667 return getFunctionType(retType, proto->getParamTypes(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00008668 }
8669
8670 if (allLTypes) return lhs;
8671 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00008672 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00008673}
8674
John McCall433c2e62013-03-21 00:10:07 +00008675/// Given that we have an enum type and a non-enum type, try to merge them.
8676static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
8677 QualType other, bool isBlockReturnType) {
8678 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
8679 // a signed integer type, or an unsigned integer type.
8680 // Compatibility is based on the underlying type, not the promotion
8681 // type.
8682 QualType underlyingType = ET->getDecl()->getIntegerType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00008683 if (underlyingType.isNull())
8684 return {};
John McCall433c2e62013-03-21 00:10:07 +00008685 if (Context.hasSameType(underlyingType, other))
8686 return other;
8687
8688 // In block return types, we're more permissive and accept any
8689 // integral type of the same size.
8690 if (isBlockReturnType && other->isIntegerType() &&
8691 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
8692 return other;
8693
Eugene Zelenko7855e772018-04-03 00:11:50 +00008694 return {};
John McCall433c2e62013-03-21 00:10:07 +00008695}
8696
Fangrui Song6907ce22018-07-30 19:24:48 +00008697QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008698 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00008699 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00008700 // C++ [expr]: If an expression initially has the type "reference to T", the
8701 // type is adjusted to "T" prior to any further analysis, the expression
8702 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00008703 // expression is an lvalue unless the reference is an rvalue reference and
8704 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00008705 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
8706 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008707
8708 if (Unqualified) {
8709 LHS = LHS.getUnqualifiedType();
8710 RHS = RHS.getUnqualifiedType();
8711 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008712
Eli Friedman47f77112008-08-22 00:56:42 +00008713 QualType LHSCan = getCanonicalType(LHS),
8714 RHSCan = getCanonicalType(RHS);
8715
8716 // If two types are identical, they are compatible.
8717 if (LHSCan == RHSCan)
8718 return LHS;
8719
John McCall8ccfcb52009-09-24 19:53:00 +00008720 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00008721 Qualifiers LQuals = LHSCan.getLocalQualifiers();
8722 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00008723 if (LQuals != RQuals) {
8724 // If any of these qualifiers are different, we have a type
8725 // mismatch.
8726 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00008727 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
Roger Ferrer Ibanezd93add32017-02-24 08:41:09 +00008728 LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
8729 LQuals.hasUnaligned() != RQuals.hasUnaligned())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008730 return {};
John McCall8ccfcb52009-09-24 19:53:00 +00008731
8732 // Exactly one GC qualifier difference is allowed: __strong is
8733 // okay if the other type has no GC qualifier but is an Objective
8734 // C object pointer (i.e. implicitly strong by default). We fix
8735 // this by pretending that the unqualified type was actually
8736 // qualified __strong.
8737 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
8738 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
8739 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
8740
8741 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
Eugene Zelenko7855e772018-04-03 00:11:50 +00008742 return {};
John McCall8ccfcb52009-09-24 19:53:00 +00008743
8744 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
8745 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
8746 }
8747 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
8748 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
8749 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00008750 return {};
John McCall8ccfcb52009-09-24 19:53:00 +00008751 }
8752
8753 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00008754
Eli Friedmandcca6332009-06-01 01:22:52 +00008755 Type::TypeClass LHSClass = LHSCan->getTypeClass();
8756 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00008757
Chris Lattnerfd652912008-01-14 05:45:46 +00008758 // We want to consider the two function types to be the same for these
8759 // comparisons, just force one to the other.
8760 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
8761 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00008762
8763 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00008764 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
8765 LHSClass = Type::ConstantArray;
8766 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
8767 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00008768
John McCall8b07ec22010-05-15 11:32:37 +00008769 // ObjCInterfaces are just specialized ObjCObjects.
8770 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
8771 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
8772
Nate Begemance4d7fc2008-04-18 23:10:10 +00008773 // Canonicalize ExtVector -> Vector.
8774 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
8775 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00008776
Chris Lattner95554662008-04-07 05:43:21 +00008777 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00008778 if (LHSClass != RHSClass) {
John McCall433c2e62013-03-21 00:10:07 +00008779 // Note that we only have special rules for turning block enum
8780 // returns into block int returns, not vice-versa.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008781 if (const auto *ETy = LHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00008782 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00008783 }
John McCall9dd450b2009-09-21 23:43:11 +00008784 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00008785 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00008786 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00008787 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00008788 if (OfBlockPointer && !BlockReturnType) {
8789 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
8790 return LHS;
8791 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
8792 return RHS;
8793 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008794
Eugene Zelenko7855e772018-04-03 00:11:50 +00008795 return {};
Steve Naroff32e44c02007-10-15 20:41:53 +00008796 }
Eli Friedman47f77112008-08-22 00:56:42 +00008797
Steve Naroffc6edcbd2008-01-09 22:43:08 +00008798 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00008799 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008800#define TYPE(Class, Base)
8801#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00008802#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008803#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
8804#define DEPENDENT_TYPE(Class, Base) case Type::Class:
8805#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00008806 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008807
Richard Smith27d807c2013-04-30 13:56:41 +00008808 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00008809 case Type::DeducedTemplateSpecialization:
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00008810 case Type::LValueReference:
8811 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008812 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00008813 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008814
John McCall8b07ec22010-05-15 11:32:37 +00008815 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008816 case Type::IncompleteArray:
8817 case Type::VariableArray:
8818 case Type::FunctionProto:
8819 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00008820 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008821
Chris Lattnerfd652912008-01-14 05:45:46 +00008822 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00008823 {
8824 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008825 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
8826 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008827 if (Unqualified) {
8828 LHSPointee = LHSPointee.getUnqualifiedType();
8829 RHSPointee = RHSPointee.getUnqualifiedType();
8830 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008831 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008832 Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00008833 if (ResultType.isNull())
8834 return {};
Eli Friedman091a9ac2009-06-02 05:28:56 +00008835 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00008836 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00008837 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00008838 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00008839 return getPointerType(ResultType);
8840 }
Steve Naroff68e167d2008-12-10 17:49:55 +00008841 case Type::BlockPointer:
8842 {
8843 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008844 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
8845 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008846 if (Unqualified) {
8847 LHSPointee = LHSPointee.getUnqualifiedType();
8848 RHSPointee = RHSPointee.getUnqualifiedType();
8849 }
Anastasia Stulova81a25e352017-03-10 15:23:07 +00008850 if (getLangOpts().OpenCL) {
8851 Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
8852 Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
8853 // Blocks can't be an expression in a ternary operator (OpenCL v2.0
8854 // 6.12.5) thus the following check is asymmetric.
8855 if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual))
Eugene Zelenko7855e772018-04-03 00:11:50 +00008856 return {};
Anastasia Stulova81a25e352017-03-10 15:23:07 +00008857 LHSPteeQual.removeAddressSpace();
8858 RHSPteeQual.removeAddressSpace();
8859 LHSPointee =
8860 QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
8861 RHSPointee =
8862 QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
8863 }
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008864 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
8865 Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00008866 if (ResultType.isNull())
8867 return {};
Steve Naroff68e167d2008-12-10 17:49:55 +00008868 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
8869 return LHS;
8870 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
8871 return RHS;
8872 return getBlockPointerType(ResultType);
8873 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00008874 case Type::Atomic:
8875 {
8876 // Merge two pointer types, while trying to preserve typedef info
8877 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
8878 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
8879 if (Unqualified) {
8880 LHSValue = LHSValue.getUnqualifiedType();
8881 RHSValue = RHSValue.getUnqualifiedType();
8882 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008883 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
Eli Friedman0dfb8892011-10-06 23:00:33 +00008884 Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00008885 if (ResultType.isNull())
8886 return {};
Eli Friedman0dfb8892011-10-06 23:00:33 +00008887 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
8888 return LHS;
8889 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
8890 return RHS;
8891 return getAtomicType(ResultType);
8892 }
Chris Lattnerfd652912008-01-14 05:45:46 +00008893 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00008894 {
8895 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
8896 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
8897 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008898 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00008899
8900 QualType LHSElem = getAsArrayType(LHS)->getElementType();
8901 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008902 if (Unqualified) {
8903 LHSElem = LHSElem.getUnqualifiedType();
8904 RHSElem = RHSElem.getUnqualifiedType();
8905 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008906
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008907 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00008908 if (ResultType.isNull())
8909 return {};
Jeremy Morse8129c5c2018-06-05 09:18:26 +00008910
8911 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
8912 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
8913
8914 // If either side is a variable array, and both are complete, check whether
8915 // the current dimension is definite.
8916 if (LVAT || RVAT) {
8917 auto SizeFetch = [this](const VariableArrayType* VAT,
8918 const ConstantArrayType* CAT)
8919 -> std::pair<bool,llvm::APInt> {
8920 if (VAT) {
8921 llvm::APSInt TheInt;
8922 Expr *E = VAT->getSizeExpr();
8923 if (E && E->isIntegerConstantExpr(TheInt, *this))
8924 return std::make_pair(true, TheInt);
8925 else
8926 return std::make_pair(false, TheInt);
8927 } else if (CAT) {
8928 return std::make_pair(true, CAT->getSize());
8929 } else {
8930 return std::make_pair(false, llvm::APInt());
8931 }
8932 };
8933
8934 bool HaveLSize, HaveRSize;
8935 llvm::APInt LSize, RSize;
8936 std::tie(HaveLSize, LSize) = SizeFetch(LVAT, LCAT);
8937 std::tie(HaveRSize, RSize) = SizeFetch(RVAT, RCAT);
8938 if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(LSize, RSize))
8939 return {}; // Definite, but unequal, array dimension
8940 }
8941
Chris Lattner465fa322008-10-05 17:34:18 +00008942 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
8943 return LHS;
8944 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
8945 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00008946 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
8947 ArrayType::ArraySizeModifier(), 0);
8948 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
8949 ArrayType::ArraySizeModifier(), 0);
Chris Lattner465fa322008-10-05 17:34:18 +00008950 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
8951 return LHS;
8952 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
8953 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00008954 if (LVAT) {
8955 // FIXME: This isn't correct! But tricky to implement because
8956 // the array's size has to be the size of LHS, but the type
8957 // has to be different.
8958 return LHS;
8959 }
8960 if (RVAT) {
8961 // FIXME: This isn't correct! But tricky to implement because
8962 // the array's size has to be the size of RHS, but the type
8963 // has to be different.
8964 return RHS;
8965 }
Eli Friedman3e62c212008-08-22 01:48:21 +00008966 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
8967 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00008968 return getIncompleteArrayType(ResultType,
8969 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00008970 }
Chris Lattnerfd652912008-01-14 05:45:46 +00008971 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008972 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008973 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008974 case Type::Enum:
Eugene Zelenko7855e772018-04-03 00:11:50 +00008975 return {};
Chris Lattnerfd652912008-01-14 05:45:46 +00008976 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00008977 // Only exactly equal builtin types are compatible, which is tested above.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008978 return {};
Daniel Dunbar804c0442009-01-28 21:22:12 +00008979 case Type::Complex:
8980 // Distinct complex types are incompatible.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008981 return {};
Chris Lattner7bbd3d72008-04-07 05:55:38 +00008982 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00008983 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00008984 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
8985 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00008986 return LHS;
Eugene Zelenko7855e772018-04-03 00:11:50 +00008987 return {};
John McCall8b07ec22010-05-15 11:32:37 +00008988 case Type::ObjCObject: {
8989 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00008990 // FIXME: This should be type compatibility, e.g. whether
8991 // "LHS x; RHS x;" at global scope is legal.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008992 const auto *LHSIface = LHS->getAs<ObjCObjectType>();
8993 const auto *RHSIface = RHS->getAs<ObjCObjectType>();
John McCall8b07ec22010-05-15 11:32:37 +00008994 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00008995 return LHS;
8996
Eugene Zelenko7855e772018-04-03 00:11:50 +00008997 return {};
Cedric Venet4fc88b72009-02-21 17:14:49 +00008998 }
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00008999 case Type::ObjCObjectPointer:
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00009000 if (OfBlockPointer) {
9001 if (canAssignObjCInterfacesInBlockPointer(
9002 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00009003 RHS->getAs<ObjCObjectPointerType>(),
9004 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00009005 return LHS;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009006 return {};
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00009007 }
John McCall9dd450b2009-09-21 23:43:11 +00009008 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
9009 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00009010 return LHS;
9011
Eugene Zelenko7855e772018-04-03 00:11:50 +00009012 return {};
Xiuli Pan9c14e282016-01-09 12:53:17 +00009013 case Type::Pipe:
Joey Goulye3c85de2016-12-01 11:30:49 +00009014 assert(LHS != RHS &&
9015 "Equivalent pipe types should have already been handled!");
Eugene Zelenko7855e772018-04-03 00:11:50 +00009016 return {};
Xiuli Pan9c14e282016-01-09 12:53:17 +00009017 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00009018
David Blaikie8a40f702012-01-17 06:56:22 +00009019 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00009020}
Ted Kremenekfc581a92007-10-31 17:10:13 +00009021
Akira Hatanaka98a49332017-09-22 00:41:05 +00009022bool ASTContext::mergeExtParameterInfo(
9023 const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType,
9024 bool &CanUseFirst, bool &CanUseSecond,
9025 SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &NewParamInfos) {
9026 assert(NewParamInfos.empty() && "param info list not empty");
9027 CanUseFirst = CanUseSecond = true;
9028 bool FirstHasInfo = FirstFnType->hasExtParameterInfos();
9029 bool SecondHasInfo = SecondFnType->hasExtParameterInfos();
9030
John McCall18afab72016-03-01 00:49:02 +00009031 // Fast path: if the first type doesn't have ext parameter infos,
Akira Hatanaka98a49332017-09-22 00:41:05 +00009032 // we match if and only if the second type also doesn't have them.
9033 if (!FirstHasInfo && !SecondHasInfo)
9034 return true;
John McCall18afab72016-03-01 00:49:02 +00009035
Akira Hatanaka98a49332017-09-22 00:41:05 +00009036 bool NeedParamInfo = false;
9037 size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size()
9038 : SecondFnType->getExtParameterInfos().size();
John McCall18afab72016-03-01 00:49:02 +00009039
Akira Hatanaka98a49332017-09-22 00:41:05 +00009040 for (size_t I = 0; I < E; ++I) {
9041 FunctionProtoType::ExtParameterInfo FirstParam, SecondParam;
9042 if (FirstHasInfo)
9043 FirstParam = FirstFnType->getExtParameterInfo(I);
9044 if (SecondHasInfo)
9045 SecondParam = SecondFnType->getExtParameterInfo(I);
John McCall18afab72016-03-01 00:49:02 +00009046
Akira Hatanaka98a49332017-09-22 00:41:05 +00009047 // Cannot merge unless everything except the noescape flag matches.
9048 if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false))
John McCall18afab72016-03-01 00:49:02 +00009049 return false;
Akira Hatanaka98a49332017-09-22 00:41:05 +00009050
9051 bool FirstNoEscape = FirstParam.isNoEscape();
9052 bool SecondNoEscape = SecondParam.isNoEscape();
9053 bool IsNoEscape = FirstNoEscape && SecondNoEscape;
9054 NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape));
9055 if (NewParamInfos.back().getOpaqueValue())
9056 NeedParamInfo = true;
9057 if (FirstNoEscape != IsNoEscape)
9058 CanUseFirst = false;
9059 if (SecondNoEscape != IsNoEscape)
9060 CanUseSecond = false;
John McCall18afab72016-03-01 00:49:02 +00009061 }
Akira Hatanaka98a49332017-09-22 00:41:05 +00009062
9063 if (!NeedParamInfo)
9064 NewParamInfos.clear();
9065
Fariborz Jahanian97676972011-09-28 21:52:05 +00009066 return true;
9067}
9068
Chandler Carruth21c90602015-12-30 03:24:14 +00009069void ASTContext::ResetObjCLayout(const ObjCContainerDecl *CD) {
9070 ObjCLayouts[CD] = nullptr;
9071}
9072
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009073/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
9074/// 'RHS' attributes and returns the merged version; including for function
9075/// return types.
9076QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
9077 QualType LHSCan = getCanonicalType(LHS),
9078 RHSCan = getCanonicalType(RHS);
9079 // If two types are identical, they are compatible.
9080 if (LHSCan == RHSCan)
9081 return LHS;
9082 if (RHSCan->isFunctionType()) {
9083 if (!LHSCan->isFunctionType())
Eugene Zelenko7855e772018-04-03 00:11:50 +00009084 return {};
Alp Toker314cc812014-01-25 16:55:45 +00009085 QualType OldReturnType =
9086 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009087 QualType NewReturnType =
Alp Toker314cc812014-01-25 16:55:45 +00009088 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
Fangrui Song6907ce22018-07-30 19:24:48 +00009089 QualType ResReturnType =
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009090 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
9091 if (ResReturnType.isNull())
Eugene Zelenko7855e772018-04-03 00:11:50 +00009092 return {};
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009093 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
9094 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
9095 // In either case, use OldReturnType to build the new function type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00009096 const auto *F = LHS->getAs<FunctionType>();
9097 if (const auto *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00009098 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9099 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner896b32f2013-06-10 20:51:09 +00009100 QualType ResultType =
Alp Toker9cacbab2014-01-20 20:26:09 +00009101 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009102 return ResultType;
9103 }
9104 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00009105 return {};
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009106 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009107
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009108 // If the qualifiers are different, the types can still be merged.
9109 Qualifiers LQuals = LHSCan.getLocalQualifiers();
9110 Qualifiers RQuals = RHSCan.getLocalQualifiers();
9111 if (LQuals != RQuals) {
9112 // If any of these qualifiers are different, we have a type mismatch.
9113 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
9114 LQuals.getAddressSpace() != RQuals.getAddressSpace())
Eugene Zelenko7855e772018-04-03 00:11:50 +00009115 return {};
Fangrui Song6907ce22018-07-30 19:24:48 +00009116
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009117 // Exactly one GC qualifier difference is allowed: __strong is
9118 // okay if the other type has no GC qualifier but is an Objective
9119 // C object pointer (i.e. implicitly strong by default). We fix
9120 // this by pretending that the unqualified type was actually
9121 // qualified __strong.
9122 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
9123 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
9124 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
Fangrui Song6907ce22018-07-30 19:24:48 +00009125
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009126 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
Eugene Zelenko7855e772018-04-03 00:11:50 +00009127 return {};
Fangrui Song6907ce22018-07-30 19:24:48 +00009128
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009129 if (GC_L == Qualifiers::Strong)
9130 return LHS;
9131 if (GC_R == Qualifiers::Strong)
9132 return RHS;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009133 return {};
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009134 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009135
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009136 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
9137 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
9138 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
9139 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
9140 if (ResQT == LHSBaseQT)
9141 return LHS;
9142 if (ResQT == RHSBaseQT)
9143 return RHS;
9144 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00009145 return {};
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009146}
9147
Chris Lattner4ba0cef2008-04-07 07:01:58 +00009148//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009149// Integer Predicates
9150//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00009151
Jay Foad39c79802011-01-12 09:06:06 +00009152unsigned ASTContext::getIntWidth(QualType T) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00009153 if (const auto *ET = T->getAs<EnumType>())
Eli Friedmanee275c82009-12-10 22:29:29 +00009154 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00009155 if (T->isBooleanType())
9156 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00009157 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009158 return (unsigned)getTypeSize(T);
9159}
9160
Abramo Bagnara13640492012-09-09 10:21:24 +00009161QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Leonard Chanab80f3c2018-06-14 14:53:51 +00009162 assert((T->hasSignedIntegerRepresentation() || T->isSignedFixedPointType()) &&
9163 "Unexpected type");
Fangrui Song6907ce22018-07-30 19:24:48 +00009164
Chris Lattnerec3a1562009-10-17 20:33:28 +00009165 // Turn <4 x signed int> -> <4 x unsigned int>
Eugene Zelenko7855e772018-04-03 00:11:50 +00009166 if (const auto *VTy = T->getAs<VectorType>())
Chris Lattnerec3a1562009-10-17 20:33:28 +00009167 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00009168 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00009169
9170 // For enums, we return the unsigned version of the base type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00009171 if (const auto *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009172 T = ETy->getDecl()->getIntegerType();
Fangrui Song6907ce22018-07-30 19:24:48 +00009173
Eugene Zelenko7855e772018-04-03 00:11:50 +00009174 const auto *BTy = T->getAs<BuiltinType>();
Leonard Chanab80f3c2018-06-14 14:53:51 +00009175 assert(BTy && "Unexpected signed integer or fixed point type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009176 switch (BTy->getKind()) {
9177 case BuiltinType::Char_S:
9178 case BuiltinType::SChar:
9179 return UnsignedCharTy;
9180 case BuiltinType::Short:
9181 return UnsignedShortTy;
9182 case BuiltinType::Int:
9183 return UnsignedIntTy;
9184 case BuiltinType::Long:
9185 return UnsignedLongTy;
9186 case BuiltinType::LongLong:
9187 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00009188 case BuiltinType::Int128:
9189 return UnsignedInt128Ty;
Leonard Chanab80f3c2018-06-14 14:53:51 +00009190
9191 case BuiltinType::ShortAccum:
9192 return UnsignedShortAccumTy;
9193 case BuiltinType::Accum:
9194 return UnsignedAccumTy;
9195 case BuiltinType::LongAccum:
9196 return UnsignedLongAccumTy;
9197 case BuiltinType::SatShortAccum:
9198 return SatUnsignedShortAccumTy;
9199 case BuiltinType::SatAccum:
9200 return SatUnsignedAccumTy;
9201 case BuiltinType::SatLongAccum:
9202 return SatUnsignedLongAccumTy;
9203 case BuiltinType::ShortFract:
9204 return UnsignedShortFractTy;
9205 case BuiltinType::Fract:
9206 return UnsignedFractTy;
9207 case BuiltinType::LongFract:
9208 return UnsignedLongFractTy;
9209 case BuiltinType::SatShortFract:
9210 return SatUnsignedShortFractTy;
9211 case BuiltinType::SatFract:
9212 return SatUnsignedFractTy;
9213 case BuiltinType::SatLongFract:
9214 return SatUnsignedLongFractTy;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009215 default:
Leonard Chanab80f3c2018-06-14 14:53:51 +00009216 llvm_unreachable("Unexpected signed integer or fixed point type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009217 }
9218}
9219
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009220ASTMutationListener::~ASTMutationListener() = default;
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00009221
Richard Smith1fa5d642013-05-11 05:45:24 +00009222void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
9223 QualType ReturnType) {}
Chris Lattnerecd79c62009-06-14 00:45:47 +00009224
9225//===----------------------------------------------------------------------===//
9226// Builtin Type Computation
9227//===----------------------------------------------------------------------===//
9228
9229/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00009230/// pointer over the consumed characters. This returns the resultant type. If
9231/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
9232/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
9233/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009234///
9235/// RequiresICE is filled in on return to indicate whether the value is required
9236/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00009237static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00009238 ASTContext::GetBuiltinTypeError &Error,
Chandler Carruth45bbe012017-03-24 09:11:57 +00009239 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00009240 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00009241 // Modifiers.
9242 int HowLong = 0;
9243 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009244 RequiresICE = false;
Fangrui Song6907ce22018-07-30 19:24:48 +00009245
Chris Lattnerdc226c22010-10-01 22:42:38 +00009246 // Read the prefixed modifiers first.
Eric Christopher50daf5f2017-07-10 21:28:54 +00009247 bool Done = false;
9248 #ifndef NDEBUG
9249 bool IsSpecialLong = false;
9250 #endif
Chris Lattnerecd79c62009-06-14 00:45:47 +00009251 while (!Done) {
9252 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00009253 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00009254 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009255 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00009256 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009257 case 'S':
9258 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
9259 assert(!Signed && "Can't use 'S' modifier multiple times!");
9260 Signed = true;
9261 break;
9262 case 'U':
9263 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
Sean Silva2a995142015-01-16 21:44:26 +00009264 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00009265 Unsigned = true;
9266 break;
9267 case 'L':
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00009268 assert(!IsSpecialLong && "Can't use 'L' with 'W' or 'N' modifiers");
Chris Lattnerecd79c62009-06-14 00:45:47 +00009269 assert(HowLong <= 2 && "Can't have LLLL modifier");
9270 ++HowLong;
9271 break;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009272 case 'N':
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00009273 // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
9274 assert(!IsSpecialLong && "Can't use two 'N' or 'W' modifiers!");
9275 assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
Eric Christopher50daf5f2017-07-10 21:28:54 +00009276 #ifndef NDEBUG
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00009277 IsSpecialLong = true;
Eric Christopher50daf5f2017-07-10 21:28:54 +00009278 #endif
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00009279 if (Context.getTargetInfo().getLongWidth() == 32)
9280 ++HowLong;
9281 break;
Kevin Qinad64f6d2014-02-24 02:45:03 +00009282 case 'W':
9283 // This modifier represents int64 type.
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00009284 assert(!IsSpecialLong && "Can't use two 'N' or 'W' modifiers!");
Kevin Qinad64f6d2014-02-24 02:45:03 +00009285 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
Eric Christopher50daf5f2017-07-10 21:28:54 +00009286 #ifndef NDEBUG
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00009287 IsSpecialLong = true;
Eric Christopher50daf5f2017-07-10 21:28:54 +00009288 #endif
Kevin Qinad64f6d2014-02-24 02:45:03 +00009289 switch (Context.getTargetInfo().getInt64Type()) {
9290 default:
9291 llvm_unreachable("Unexpected integer type");
9292 case TargetInfo::SignedLong:
9293 HowLong = 1;
9294 break;
9295 case TargetInfo::SignedLongLong:
9296 HowLong = 2;
9297 break;
9298 }
Duncan P. N. Exon Smitheae8caa2017-06-14 21:26:31 +00009299 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009300 }
9301 }
9302
9303 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00009304
Chris Lattnerecd79c62009-06-14 00:45:47 +00009305 // Read the base type.
9306 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00009307 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00009308 case 'v':
9309 assert(HowLong == 0 && !Signed && !Unsigned &&
9310 "Bad modifiers used with 'v'!");
9311 Type = Context.VoidTy;
9312 break;
Jack Carter24bef982013-08-15 15:16:57 +00009313 case 'h':
9314 assert(HowLong == 0 && !Signed && !Unsigned &&
Sean Silva2a995142015-01-16 21:44:26 +00009315 "Bad modifiers used with 'h'!");
Jack Carter24bef982013-08-15 15:16:57 +00009316 Type = Context.HalfTy;
9317 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009318 case 'f':
9319 assert(HowLong == 0 && !Signed && !Unsigned &&
9320 "Bad modifiers used with 'f'!");
9321 Type = Context.FloatTy;
9322 break;
9323 case 'd':
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009324 assert(HowLong < 3 && !Signed && !Unsigned &&
Chris Lattnerecd79c62009-06-14 00:45:47 +00009325 "Bad modifiers used with 'd'!");
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009326 if (HowLong == 1)
Chris Lattnerecd79c62009-06-14 00:45:47 +00009327 Type = Context.LongDoubleTy;
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009328 else if (HowLong == 2)
9329 Type = Context.Float128Ty;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009330 else
9331 Type = Context.DoubleTy;
9332 break;
9333 case 's':
9334 assert(HowLong == 0 && "Bad modifiers used with 's'!");
9335 if (Unsigned)
9336 Type = Context.UnsignedShortTy;
9337 else
9338 Type = Context.ShortTy;
9339 break;
9340 case 'i':
9341 if (HowLong == 3)
9342 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
9343 else if (HowLong == 2)
9344 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
9345 else if (HowLong == 1)
9346 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
9347 else
9348 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
9349 break;
9350 case 'c':
9351 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
9352 if (Signed)
9353 Type = Context.SignedCharTy;
9354 else if (Unsigned)
9355 Type = Context.UnsignedCharTy;
9356 else
9357 Type = Context.CharTy;
9358 break;
9359 case 'b': // boolean
9360 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
9361 Type = Context.BoolTy;
9362 break;
9363 case 'z': // size_t.
9364 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
9365 Type = Context.getSizeType();
9366 break;
Richard Smith8110c9d2016-11-29 19:45:17 +00009367 case 'w': // wchar_t.
9368 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
9369 Type = Context.getWideCharType();
9370 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009371 case 'F':
9372 Type = Context.getCFConstantStringType();
9373 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00009374 case 'G':
9375 Type = Context.getObjCIdType();
9376 break;
9377 case 'H':
9378 Type = Context.getObjCSelType();
9379 break;
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00009380 case 'M':
9381 Type = Context.getObjCSuperType();
9382 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009383 case 'a':
9384 Type = Context.getBuiltinVaListType();
9385 assert(!Type.isNull() && "builtin va list type not initialized!");
9386 break;
9387 case 'A':
9388 // This is a "reference" to a va_list; however, what exactly
9389 // this means depends on how va_list is defined. There are two
9390 // different kinds of va_list: ones passed by value, and ones
9391 // passed by reference. An example of a by-value va_list is
9392 // x86, where va_list is a char*. An example of by-ref va_list
9393 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
9394 // we want this argument to be a char*&; for x86-64, we want
9395 // it to be a __va_list_tag*.
9396 Type = Context.getBuiltinVaListType();
9397 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009398 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00009399 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009400 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00009401 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009402 break;
9403 case 'V': {
9404 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009405 unsigned NumElements = strtoul(Str, &End, 10);
9406 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00009407 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00009408
Fangrui Song6907ce22018-07-30 19:24:48 +00009409 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
Chandler Carruth45bbe012017-03-24 09:11:57 +00009410 RequiresICE, false);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009411 assert(!RequiresICE && "Can't require vector ICE");
Fangrui Song6907ce22018-07-30 19:24:48 +00009412
Chris Lattnerdc226c22010-10-01 22:42:38 +00009413 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00009414 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00009415 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009416 break;
9417 }
Douglas Gregorfed66992012-06-07 18:08:25 +00009418 case 'E': {
9419 char *End;
Fangrui Song6907ce22018-07-30 19:24:48 +00009420
Douglas Gregorfed66992012-06-07 18:08:25 +00009421 unsigned NumElements = strtoul(Str, &End, 10);
9422 assert(End != Str && "Missing vector size");
Fangrui Song6907ce22018-07-30 19:24:48 +00009423
Douglas Gregorfed66992012-06-07 18:08:25 +00009424 Str = End;
Fangrui Song6907ce22018-07-30 19:24:48 +00009425
Douglas Gregorfed66992012-06-07 18:08:25 +00009426 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
Chandler Carruth45bbe012017-03-24 09:11:57 +00009427 false);
Douglas Gregorfed66992012-06-07 18:08:25 +00009428 Type = Context.getExtVectorType(ElementType, NumElements);
Fangrui Song6907ce22018-07-30 19:24:48 +00009429 break;
Douglas Gregorfed66992012-06-07 18:08:25 +00009430 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00009431 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009432 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
Chandler Carruth45bbe012017-03-24 09:11:57 +00009433 false);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009434 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00009435 Type = Context.getComplexType(ElementType);
9436 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00009437 }
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009438 case 'Y':
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00009439 Type = Context.getPointerDiffType();
9440 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00009441 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00009442 Type = Context.getFILEType();
9443 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00009444 Error = ASTContext::GE_Missing_stdio;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009445 return {};
Chris Lattnerecd79c62009-06-14 00:45:47 +00009446 }
Mike Stump2adb4da2009-07-28 23:47:15 +00009447 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00009448 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00009449 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00009450 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00009451 else
9452 Type = Context.getjmp_bufType();
9453
Mike Stump2adb4da2009-07-28 23:47:15 +00009454 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00009455 Error = ASTContext::GE_Missing_setjmp;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009456 return {};
Mike Stump2adb4da2009-07-28 23:47:15 +00009457 }
9458 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00009459 case 'K':
9460 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
9461 Type = Context.getucontext_tType();
9462
9463 if (Type.isNull()) {
9464 Error = ASTContext::GE_Missing_ucontext;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009465 return {};
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00009466 }
9467 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00009468 case 'p':
9469 Type = Context.getProcessIDType();
9470 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00009471 }
Mike Stump11289f42009-09-09 15:08:12 +00009472
Chris Lattnerdc226c22010-10-01 22:42:38 +00009473 // If there are modifiers and if we're allowed to parse them, go for it.
9474 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009475 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00009476 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00009477 default: Done = true; --Str; break;
9478 case '*':
9479 case '&': {
9480 // Both pointers and references can have their pointee types
9481 // qualified with an address space.
9482 char *End;
9483 unsigned AddrSpace = strtoul(Str, &End, 10);
Matt Arsenaultc65f9662018-08-02 12:14:28 +00009484 if (End != Str) {
9485 // Note AddrSpace == 0 is not the same as an unspecified address space.
9486 Type = Context.getAddrSpaceQualType(
9487 Type,
9488 Context.getLangASForBuiltinAddressSpace(AddrSpace));
Chris Lattnerdc226c22010-10-01 22:42:38 +00009489 Str = End;
9490 }
9491 if (c == '*')
9492 Type = Context.getPointerType(Type);
9493 else
9494 Type = Context.getLValueReferenceType(Type);
9495 break;
9496 }
9497 // FIXME: There's no way to have a built-in with an rvalue ref arg.
9498 case 'C':
9499 Type = Type.withConst();
9500 break;
9501 case 'D':
9502 Type = Context.getVolatileType(Type);
9503 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00009504 case 'R':
9505 Type = Type.withRestrict();
9506 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009507 }
9508 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009509
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009510 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Fangrui Song6907ce22018-07-30 19:24:48 +00009511 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00009512
Chris Lattnerecd79c62009-06-14 00:45:47 +00009513 return Type;
9514}
9515
9516/// GetBuiltinType - Return the type for the specified builtin.
Chandler Carruth45bbe012017-03-24 09:11:57 +00009517QualType ASTContext::GetBuiltinType(unsigned Id,
9518 GetBuiltinTypeError &Error,
9519 unsigned *IntegerConstantArgs) const {
Eric Christopher02d5d862015-08-06 01:01:12 +00009520 const char *TypeStr = BuiltinInfo.getTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00009521
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009522 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00009523
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009524 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009525 Error = GE_None;
Chandler Carruth45bbe012017-03-24 09:11:57 +00009526 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
9527 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009528 if (Error != GE_None)
Eugene Zelenko7855e772018-04-03 00:11:50 +00009529 return {};
Fangrui Song6907ce22018-07-30 19:24:48 +00009530
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009531 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
Fangrui Song6907ce22018-07-30 19:24:48 +00009532
Chris Lattnerecd79c62009-06-14 00:45:47 +00009533 while (TypeStr[0] && TypeStr[0] != '.') {
Chandler Carruth45bbe012017-03-24 09:11:57 +00009534 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009535 if (Error != GE_None)
Eugene Zelenko7855e772018-04-03 00:11:50 +00009536 return {};
Chris Lattnerecd79c62009-06-14 00:45:47 +00009537
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009538 // If this argument is required to be an IntegerConstantExpression and the
9539 // caller cares, fill in the bitmask we return.
9540 if (RequiresICE && IntegerConstantArgs)
9541 *IntegerConstantArgs |= 1 << ArgTypes.size();
Fangrui Song6907ce22018-07-30 19:24:48 +00009542
Chris Lattnerecd79c62009-06-14 00:45:47 +00009543 // Do array -> pointer decay. The builtin should use the decayed type.
9544 if (Ty->isArrayType())
9545 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00009546
Chris Lattnerecd79c62009-06-14 00:45:47 +00009547 ArgTypes.push_back(Ty);
9548 }
9549
David Majnemerba3e5ec2015-03-13 18:26:17 +00009550 if (Id == Builtin::BI__GetExceptionInfo)
Eugene Zelenko7855e772018-04-03 00:11:50 +00009551 return {};
David Majnemerba3e5ec2015-03-13 18:26:17 +00009552
Chris Lattnerecd79c62009-06-14 00:45:47 +00009553 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
9554 "'.' should only occur at end of builtin type list!");
9555
Reid Kleckner78af0702013-08-27 23:08:25 +00009556 FunctionType::ExtInfo EI(CC_C);
John McCall991eb4b2010-12-21 00:44:39 +00009557 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
9558
9559 bool Variadic = (TypeStr[0] == '.');
9560
Richard Smith836de6b2016-12-19 23:59:34 +00009561 // We really shouldn't be making a no-proto type here.
9562 if (ArgTypes.empty() && Variadic && !getLangOpts().CPlusPlus)
John McCall991eb4b2010-12-21 00:44:39 +00009563 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00009564
John McCalldb40c7f2010-12-14 08:05:40 +00009565 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00009566 EPI.ExtInfo = EI;
9567 EPI.Variadic = Variadic;
Richard Smith391fb862016-10-18 07:13:55 +00009568 if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id))
9569 EPI.ExceptionSpec.Type =
9570 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
John McCalldb40c7f2010-12-14 08:05:40 +00009571
Jordan Rose5c382722013-03-08 21:51:21 +00009572 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009573}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00009574
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009575static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
9576 const FunctionDecl *FD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00009577 if (!FD->isExternallyVisible())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009578 return GVA_Internal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009579
Richard Smithe2467b72017-11-16 23:54:56 +00009580 // Non-user-provided functions get emitted as weak definitions with every
9581 // use, no matter whether they've been explicitly instantiated etc.
Eugene Zelenko7855e772018-04-03 00:11:50 +00009582 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
Richard Smithe2467b72017-11-16 23:54:56 +00009583 if (!MD->isUserProvided())
9584 return GVA_DiscardableODR;
9585
Yaron Keren4cd211b2017-02-22 14:32:39 +00009586 GVALinkage External;
Rafael Espindola3ae00052013-05-13 00:12:11 +00009587 switch (FD->getTemplateSpecializationKind()) {
9588 case TSK_Undeclared:
9589 case TSK_ExplicitSpecialization:
9590 External = GVA_StrongExternal;
9591 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009592
Rafael Espindola3ae00052013-05-13 00:12:11 +00009593 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00009594 return GVA_StrongODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00009595
David Majnemerc3d07332014-05-15 06:25:57 +00009596 // C++11 [temp.explicit]p10:
9597 // [ Note: The intent is that an inline function that is the subject of
9598 // an explicit instantiation declaration will still be implicitly
9599 // instantiated when used so that the body can be considered for
9600 // inlining, but that no out-of-line copy of the inline function would be
9601 // generated in the translation unit. -- end note ]
Rafael Espindola3ae00052013-05-13 00:12:11 +00009602 case TSK_ExplicitInstantiationDeclaration:
David Majnemer27d69db2014-04-28 22:17:59 +00009603 return GVA_AvailableExternally;
9604
Rafael Espindola3ae00052013-05-13 00:12:11 +00009605 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00009606 External = GVA_DiscardableODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00009607 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009608 }
9609
9610 if (!FD->isInlined())
9611 return External;
David Majnemer62f0ffd2013-08-01 17:26:42 +00009612
David Majnemer3f021502015-10-08 04:53:31 +00009613 if ((!Context.getLangOpts().CPlusPlus &&
9614 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009615 !FD->hasAttr<DLLExportAttr>()) ||
David Majnemer62f0ffd2013-08-01 17:26:42 +00009616 FD->hasAttr<GNUInlineAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009617 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
9618
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009619 // GNU or C99 inline semantics. Determine whether this symbol should be
9620 // externally visible.
9621 if (FD->isInlineDefinitionExternallyVisible())
9622 return External;
9623
9624 // C99 inline semantics, where the symbol is not externally visible.
David Majnemer27d69db2014-04-28 22:17:59 +00009625 return GVA_AvailableExternally;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009626 }
9627
David Majnemer54e3ba52014-04-02 23:17:29 +00009628 // Functions specified with extern and inline in -fms-compatibility mode
9629 // forcibly get emitted. While the body of the function cannot be later
9630 // replaced, the function definition cannot be discarded.
David Majnemer73768702015-03-20 00:02:27 +00009631 if (FD->isMSExternInline())
David Majnemer54e3ba52014-04-02 23:17:29 +00009632 return GVA_StrongODR;
9633
David Majnemer27d69db2014-04-28 22:17:59 +00009634 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009635}
9636
Artem Belevichca2b9512016-05-02 20:30:03 +00009637static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context,
Richard Smitha4653622017-09-06 20:01:14 +00009638 const Decl *D, GVALinkage L) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009639 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
9640 // dllexport/dllimport on inline functions.
9641 if (D->hasAttr<DLLImportAttr>()) {
9642 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
9643 return GVA_AvailableExternally;
Artem Belevichca2b9512016-05-02 20:30:03 +00009644 } else if (D->hasAttr<DLLExportAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009645 if (L == GVA_DiscardableODR)
9646 return GVA_StrongODR;
Artem Belevichca2b9512016-05-02 20:30:03 +00009647 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice &&
9648 D->hasAttr<CUDAGlobalAttr>()) {
9649 // Device-side functions with __global__ attribute must always be
9650 // visible externally so they can be launched from host.
9651 if (L == GVA_DiscardableODR || L == GVA_Internal)
9652 return GVA_StrongODR;
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009653 }
9654 return L;
9655}
9656
Richard Smitha4653622017-09-06 20:01:14 +00009657/// Adjust the GVALinkage for a declaration based on what an external AST source
9658/// knows about whether there can be other definitions of this declaration.
9659static GVALinkage
9660adjustGVALinkageForExternalDefinitionKind(const ASTContext &Ctx, const Decl *D,
9661 GVALinkage L) {
9662 ExternalASTSource *Source = Ctx.getExternalSource();
9663 if (!Source)
9664 return L;
9665
9666 switch (Source->hasExternalDefinitions(D)) {
David Blaikie9ffe5a32017-01-30 05:00:26 +00009667 case ExternalASTSource::EK_Never:
Richard Smitha4653622017-09-06 20:01:14 +00009668 // Other translation units rely on us to provide the definition.
David Blaikie9ffe5a32017-01-30 05:00:26 +00009669 if (L == GVA_DiscardableODR)
9670 return GVA_StrongODR;
9671 break;
Richard Smitha4653622017-09-06 20:01:14 +00009672
David Blaikie9ffe5a32017-01-30 05:00:26 +00009673 case ExternalASTSource::EK_Always:
9674 return GVA_AvailableExternally;
Richard Smitha4653622017-09-06 20:01:14 +00009675
David Blaikie9ffe5a32017-01-30 05:00:26 +00009676 case ExternalASTSource::EK_ReplyHazy:
9677 break;
9678 }
9679 return L;
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009680}
9681
Richard Smitha4653622017-09-06 20:01:14 +00009682GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
9683 return adjustGVALinkageForExternalDefinitionKind(*this, FD,
9684 adjustGVALinkageForAttributes(*this, FD,
9685 basicGVALinkageForFunction(*this, FD)));
9686}
9687
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009688static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
9689 const VarDecl *VD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00009690 if (!VD->isExternallyVisible())
9691 return GVA_Internal;
9692
David Majnemer27d69db2014-04-28 22:17:59 +00009693 if (VD->isStaticLocal()) {
David Majnemer27d69db2014-04-28 22:17:59 +00009694 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
9695 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
9696 LexicalContext = LexicalContext->getLexicalParent();
9697
David Blaikieeb210012017-01-27 23:11:10 +00009698 // ObjC Blocks can create local variables that don't have a FunctionDecl
9699 // LexicalContext.
9700 if (!LexicalContext)
9701 return GVA_DiscardableODR;
David Majnemer27d69db2014-04-28 22:17:59 +00009702
David Blaikieeb210012017-01-27 23:11:10 +00009703 // Otherwise, let the static local variable inherit its linkage from the
9704 // nearest enclosing function.
9705 auto StaticLocalLinkage =
9706 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
9707
9708 // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
9709 // be emitted in any object with references to the symbol for the object it
9710 // contains, whether inline or out-of-line."
9711 // Similar behavior is observed with MSVC. An alternative ABI could use
9712 // StrongODR/AvailableExternally to match the function, but none are
9713 // known/supported currently.
9714 if (StaticLocalLinkage == GVA_StrongODR ||
9715 StaticLocalLinkage == GVA_AvailableExternally)
9716 return GVA_DiscardableODR;
9717 return StaticLocalLinkage;
David Majnemer27d69db2014-04-28 22:17:59 +00009718 }
9719
Hans Wennborg56fc62b2014-07-17 20:25:23 +00009720 // MSVC treats in-class initialized static data members as definitions.
9721 // By giving them non-strong linkage, out-of-line definitions won't
9722 // cause link errors.
9723 if (Context.isMSStaticDataMemberInlineDefinition(VD))
9724 return GVA_DiscardableODR;
9725
Richard Smithd9b90092016-07-02 01:32:16 +00009726 // Most non-template variables have strong linkage; inline variables are
9727 // linkonce_odr or (occasionally, for compatibility) weak_odr.
9728 GVALinkage StrongLinkage;
9729 switch (Context.getInlineVariableDefinitionKind(VD)) {
9730 case ASTContext::InlineVariableDefinitionKind::None:
9731 StrongLinkage = GVA_StrongExternal;
9732 break;
9733 case ASTContext::InlineVariableDefinitionKind::Weak:
9734 case ASTContext::InlineVariableDefinitionKind::WeakUnknown:
Richard Smith62f19e72016-06-25 00:15:56 +00009735 StrongLinkage = GVA_DiscardableODR;
Richard Smithd9b90092016-07-02 01:32:16 +00009736 break;
9737 case ASTContext::InlineVariableDefinitionKind::Strong:
9738 StrongLinkage = GVA_StrongODR;
9739 break;
9740 }
Richard Smith62f19e72016-06-25 00:15:56 +00009741
Richard Smith8809a0c2013-09-27 20:14:12 +00009742 switch (VD->getTemplateSpecializationKind()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00009743 case TSK_Undeclared:
Richard Smith62f19e72016-06-25 00:15:56 +00009744 return StrongLinkage;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009745
David Majnemer6d1780c2015-07-17 23:36:49 +00009746 case TSK_ExplicitSpecialization:
David Majnemer3f021502015-10-08 04:53:31 +00009747 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
9748 VD->isStaticDataMember()
David Majnemer6d1780c2015-07-17 23:36:49 +00009749 ? GVA_StrongODR
Richard Smith62f19e72016-06-25 00:15:56 +00009750 : StrongLinkage;
David Majnemer6d1780c2015-07-17 23:36:49 +00009751
Rafael Espindola3ae00052013-05-13 00:12:11 +00009752 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00009753 return GVA_StrongODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009754
David Majnemer27d69db2014-04-28 22:17:59 +00009755 case TSK_ExplicitInstantiationDeclaration:
9756 return GVA_AvailableExternally;
9757
Rafael Espindola3ae00052013-05-13 00:12:11 +00009758 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00009759 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009760 }
Rafael Espindola27699c82013-05-13 14:05:53 +00009761
9762 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009763}
9764
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009765GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
Richard Smitha4653622017-09-06 20:01:14 +00009766 return adjustGVALinkageForExternalDefinitionKind(*this, VD,
9767 adjustGVALinkageForAttributes(*this, VD,
9768 basicGVALinkageForVariable(*this, VD)));
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009769}
9770
David Blaikiee6b7c282017-04-11 20:46:34 +00009771bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00009772 if (const auto *VD = dyn_cast<VarDecl>(D)) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009773 if (!VD->isFileVarDecl())
9774 return false;
Renato Golin9258aa52014-05-21 10:40:27 +00009775 // Global named register variables (GNU extension) are never emitted.
9776 if (VD->getStorageClass() == SC_Register)
9777 return false;
Richard Smith7747ce22015-08-19 20:49:38 +00009778 if (VD->getDescribedVarTemplate() ||
9779 isa<VarTemplatePartialSpecializationDecl>(VD))
9780 return false;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009781 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
Richard Smith5205a8c2013-04-01 20:22:16 +00009782 // We never need to emit an uninstantiated function template.
9783 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
9784 return false;
Nico Weber66220292016-03-02 17:28:48 +00009785 } else if (isa<PragmaCommentDecl>(D))
9786 return true;
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00009787 else if (isa<OMPThreadPrivateDecl>(D))
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00009788 return true;
Nico Webercbbaeb12016-03-02 19:28:54 +00009789 else if (isa<PragmaDetectMismatchDecl>(D))
9790 return true;
Nico Weber66220292016-03-02 17:28:48 +00009791 else if (isa<OMPThreadPrivateDecl>(D))
Alexey Bataevc5b1d322016-03-04 09:22:22 +00009792 return !D->getDeclContext()->isDependentContext();
9793 else if (isa<OMPDeclareReductionDecl>(D))
9794 return !D->getDeclContext()->isDependentContext();
Richard Smithdc1f0422016-07-20 19:10:16 +00009795 else if (isa<ImportDecl>(D))
9796 return true;
Alexey Bataev97720002014-11-11 04:05:39 +00009797 else
Richard Smith5205a8c2013-04-01 20:22:16 +00009798 return false;
9799
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00009800 if (D->isFromASTFile() && !LangOpts.BuildingPCHWithObjectFile) {
9801 assert(getExternalSource() && "It's from an AST file; must have a source.");
9802 // On Windows, PCH files are built together with an object file. If this
9803 // declaration comes from such a PCH and DeclMustBeEmitted would return
9804 // true, it would have returned true and the decl would have been emitted
9805 // into that object file, so it doesn't need to be emitted here.
9806 // Note that decls are still emitted if they're referenced, as usual;
9807 // DeclMustBeEmitted is used to decide whether a decl must be emitted even
9808 // if it's not referenced.
9809 //
9810 // Explicit template instantiation definitions are tricky. If there was an
9811 // explicit template instantiation decl in the PCH before, it will look like
9812 // the definition comes from there, even if that was just the declaration.
9813 // (Explicit instantiation defs of variable templates always get emitted.)
9814 bool IsExpInstDef =
9815 isa<FunctionDecl>(D) &&
9816 cast<FunctionDecl>(D)->getTemplateSpecializationKind() ==
9817 TSK_ExplicitInstantiationDefinition;
9818
Hans Wennborgb51a7032018-09-14 15:18:30 +00009819 // Implicit member function definitions, such as operator= might not be
9820 // marked as template specializations, since they're not coming from a
9821 // template but synthesized directly on the class.
9822 IsExpInstDef |=
9823 isa<CXXMethodDecl>(D) &&
9824 cast<CXXMethodDecl>(D)->getParent()->getTemplateSpecializationKind() ==
9825 TSK_ExplicitInstantiationDefinition;
9826
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00009827 if (getExternalSource()->DeclIsFromPCHWithObjectFile(D) && !IsExpInstDef)
9828 return false;
9829 }
9830
Richard Smith5205a8c2013-04-01 20:22:16 +00009831 // If this is a member of a class template, we do not need to emit it.
9832 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009833 return false;
9834
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00009835 // Weak references don't produce any output by themselves.
9836 if (D->hasAttr<WeakRefAttr>())
9837 return false;
9838
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009839 // Aliases and used decls are required.
9840 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
9841 return true;
9842
Eugene Zelenko7855e772018-04-03 00:11:50 +00009843 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009844 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00009845 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00009846 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009847
9848 // Constructors and destructors are required.
9849 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
9850 return true;
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00009851
John McCall6bd2a892013-01-25 22:31:03 +00009852 // The key function for a class is required. This rule only comes
9853 // into play when inline functions can be key functions, though.
9854 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00009855 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
John McCall6bd2a892013-01-25 22:31:03 +00009856 const CXXRecordDecl *RD = MD->getParent();
9857 if (MD->isOutOfLine() && RD->isDynamicClass()) {
9858 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
9859 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
9860 return true;
9861 }
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009862 }
9863 }
9864
David Blaikie9ffe5a32017-01-30 05:00:26 +00009865 GVALinkage Linkage = GetGVALinkageForFunction(FD);
9866
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009867 // static, static inline, always_inline, and extern inline functions can
9868 // always be deferred. Normal inline functions can be deferred in C99/C++.
9869 // Implicit template instantiations can also be deferred in C++.
David Blaikie9ffe5a32017-01-30 05:00:26 +00009870 return !isDiscardableGVALinkage(Linkage);
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009871 }
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00009872
Eugene Zelenko7855e772018-04-03 00:11:50 +00009873 const auto *VD = cast<VarDecl>(D);
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009874 assert(VD->isFileVarDecl() && "Expected file scoped var");
9875
Alexey Bataevd01b7492018-08-15 19:45:12 +00009876 // If the decl is marked as `declare target to`, it should be emitted for the
9877 // host and for the device.
9878 if (LangOpts.OpenMP &&
9879 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
9880 return true;
9881
Hans Wennborg56fc62b2014-07-17 20:25:23 +00009882 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
9883 !isMSStaticDataMemberInlineDefinition(VD))
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00009884 return false;
9885
Richard Smitha0e5e542012-11-12 21:38:00 +00009886 // Variables that can be needed in other TUs are required.
Richard Smitha4653622017-09-06 20:01:14 +00009887 auto Linkage = GetGVALinkageForVariable(VD);
9888 if (!isDiscardableGVALinkage(Linkage))
Richard Smitha0e5e542012-11-12 21:38:00 +00009889 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009890
Richard Smitha4653622017-09-06 20:01:14 +00009891 // We never need to emit a variable that is available in another TU.
9892 if (Linkage == GVA_AvailableExternally)
9893 return false;
9894
Richard Smitha0e5e542012-11-12 21:38:00 +00009895 // Variables that have destruction with side-effects are required.
9896 if (VD->getType().isDestructedType())
9897 return true;
9898
9899 // Variables that have initialization with side-effects are required.
Richard Smith7747ce22015-08-19 20:49:38 +00009900 if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
Richard Smith187ffb42017-01-20 01:19:46 +00009901 // We can get a value-dependent initializer during error recovery.
9902 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
Richard Smitha0e5e542012-11-12 21:38:00 +00009903 return true;
9904
Richard Smithda383632016-08-15 01:33:41 +00009905 // Likewise, variables with tuple-like bindings are required if their
9906 // bindings have side-effects.
Eugene Zelenko7855e772018-04-03 00:11:50 +00009907 if (const auto *DD = dyn_cast<DecompositionDecl>(VD))
9908 for (const auto *BD : DD->bindings())
9909 if (const auto *BindingVD = BD->getHoldingVar())
Richard Smithda383632016-08-15 01:33:41 +00009910 if (DeclMustBeEmitted(BindingVD))
9911 return true;
9912
Richard Smitha0e5e542012-11-12 21:38:00 +00009913 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009914}
Charles Davis53c59df2010-08-16 03:33:14 +00009915
Erich Keane281d20b2018-01-08 21:34:17 +00009916void ASTContext::forEachMultiversionedFunctionVersion(
9917 const FunctionDecl *FD,
Erich Keane0fb16482018-08-13 18:33:20 +00009918 llvm::function_ref<void(FunctionDecl *)> Pred) const {
Erich Keane281d20b2018-01-08 21:34:17 +00009919 assert(FD->isMultiVersion() && "Only valid for multiversioned functions");
9920 llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls;
Erich Keane7304f0a2018-11-28 20:58:43 +00009921 FD = FD->getMostRecentDecl();
Erich Keane281d20b2018-01-08 21:34:17 +00009922 for (auto *CurDecl :
9923 FD->getDeclContext()->getRedeclContext()->lookup(FD->getDeclName())) {
Erich Keane7304f0a2018-11-28 20:58:43 +00009924 FunctionDecl *CurFD = CurDecl->getAsFunction()->getMostRecentDecl();
Erich Keane281d20b2018-01-08 21:34:17 +00009925 if (CurFD && hasSameType(CurFD->getType(), FD->getType()) &&
9926 std::end(SeenDecls) == llvm::find(SeenDecls, CurFD)) {
9927 SeenDecls.insert(CurFD);
9928 Pred(CurFD);
9929 }
9930 }
9931}
9932
Reid Kleckner78af0702013-08-27 23:08:25 +00009933CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
9934 bool IsCXXMethod) const {
Charles Davis99202b32010-11-09 18:04:24 +00009935 // Pass through to the C++ ABI object
Reid Kleckner78af0702013-08-27 23:08:25 +00009936 if (IsCXXMethod)
9937 return ABI->getDefaultMethodCallConv(IsVariadic);
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00009938
Alexey Bataeva7547182016-05-18 09:06:38 +00009939 switch (LangOpts.getDefaultCallingConv()) {
9940 case LangOptions::DCC_None:
9941 break;
9942 case LangOptions::DCC_CDecl:
9943 return CC_C;
9944 case LangOptions::DCC_FastCall:
Erich Keane5759fa72017-10-24 23:12:01 +00009945 if (getTargetInfo().hasFeature("sse2") && !IsVariadic)
Alexey Bataeva7547182016-05-18 09:06:38 +00009946 return CC_X86FastCall;
9947 break;
9948 case LangOptions::DCC_StdCall:
9949 if (!IsVariadic)
9950 return CC_X86StdCall;
9951 break;
9952 case LangOptions::DCC_VectorCall:
9953 // __vectorcall cannot be applied to variadic functions.
9954 if (!IsVariadic)
9955 return CC_X86VectorCall;
9956 break;
Erich Keanea957ffb2017-11-02 21:08:00 +00009957 case LangOptions::DCC_RegCall:
9958 // __regcall cannot be applied to variadic functions.
9959 if (!IsVariadic)
9960 return CC_X86RegCall;
9961 break;
Alexey Bataeva7547182016-05-18 09:06:38 +00009962 }
Alexander Kornienko21de0ae2015-01-20 11:20:41 +00009963 return Target->getDefaultCallingConv(TargetInfo::CCMT_Unknown);
Charles Davis99202b32010-11-09 18:04:24 +00009964}
9965
Jay Foad39c79802011-01-12 09:06:06 +00009966bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00009967 // Pass through to the C++ ABI object
9968 return ABI->isNearlyEmpty(RD);
9969}
9970
Reid Kleckner96f8f932014-02-05 17:27:08 +00009971VTableContextBase *ASTContext::getVTableContext() {
9972 if (!VTContext.get()) {
9973 if (Target->getCXXABI().isMicrosoft())
9974 VTContext.reset(new MicrosoftVTableContext(*this));
9975 else
9976 VTContext.reset(new ItaniumVTableContext(*this));
9977 }
9978 return VTContext.get();
9979}
9980
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00009981MangleContext *ASTContext::createMangleContext() {
John McCall359b8852013-01-25 22:30:49 +00009982 switch (Target->getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +00009983 case TargetCXXABI::GenericAArch64:
John McCall359b8852013-01-25 22:30:49 +00009984 case TargetCXXABI::GenericItanium:
9985 case TargetCXXABI::GenericARM:
Zoran Jovanovic26a12162015-02-18 15:21:35 +00009986 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +00009987 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +00009988 case TargetCXXABI::iOS64:
Dan Gohmanc2853072015-09-03 22:51:53 +00009989 case TargetCXXABI::WebAssembly:
Tim Northover756447a2015-10-30 16:30:36 +00009990 case TargetCXXABI::WatchOS:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00009991 return ItaniumMangleContext::create(*this, getDiagnostics());
John McCall359b8852013-01-25 22:30:49 +00009992 case TargetCXXABI::Microsoft:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00009993 return MicrosoftMangleContext::create(*this, getDiagnostics());
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00009994 }
David Blaikie83d382b2011-09-23 05:06:16 +00009995 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00009996}
9997
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009998CXXABI::~CXXABI() = default;
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00009999
10000size_t ASTContext::getSideTableAllocatedMemory() const {
Larisse Voufo39a1e502013-08-06 01:03:05 +000010001 return ASTRecordLayouts.getMemorySize() +
10002 llvm::capacity_in_bytes(ObjCLayouts) +
10003 llvm::capacity_in_bytes(KeyFunctions) +
10004 llvm::capacity_in_bytes(ObjCImpls) +
10005 llvm::capacity_in_bytes(BlockVarCopyInits) +
10006 llvm::capacity_in_bytes(DeclAttrs) +
10007 llvm::capacity_in_bytes(TemplateOrInstantiation) +
10008 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
10009 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
10010 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
10011 llvm::capacity_in_bytes(OverriddenMethods) +
10012 llvm::capacity_in_bytes(Types) +
10013 llvm::capacity_in_bytes(VariableArrayTypes) +
10014 llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +000010015}
Ted Kremenek540017e2011-10-06 05:00:56 +000010016
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +000010017/// getIntTypeForBitwidth -
10018/// sets integer QualTy according to specified details:
10019/// bitwidth, signed/unsigned.
10020/// Returns empty type if there is no appropriate target types.
10021QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
10022 unsigned Signed) const {
10023 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
10024 CanQualType QualTy = getFromTargetType(Ty);
10025 if (!QualTy && DestWidth == 128)
10026 return Signed ? Int128Ty : UnsignedInt128Ty;
10027 return QualTy;
10028}
10029
10030/// getRealTypeForBitwidth -
10031/// sets floating point QualTy according to specified bitwidth.
10032/// Returns empty type if there is no appropriate target types.
10033QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
10034 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
10035 switch (Ty) {
10036 case TargetInfo::Float:
10037 return FloatTy;
10038 case TargetInfo::Double:
10039 return DoubleTy;
10040 case TargetInfo::LongDouble:
10041 return LongDoubleTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +000010042 case TargetInfo::Float128:
10043 return Float128Ty;
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +000010044 case TargetInfo::NoFloat:
Eugene Zelenko7855e772018-04-03 00:11:50 +000010045 return {};
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +000010046 }
10047
10048 llvm_unreachable("Unhandled TargetInfo::RealType value");
10049}
10050
Eli Friedman3b7d46c2013-07-10 00:30:46 +000010051void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
10052 if (Number > 1)
10053 MangleNumbers[ND] = Number;
David Blaikie095deba2012-11-14 01:52:05 +000010054}
10055
Eli Friedman3b7d46c2013-07-10 00:30:46 +000010056unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
Richard Smithe9b02d62016-03-21 22:33:02 +000010057 auto I = MangleNumbers.find(ND);
Eli Friedman3b7d46c2013-07-10 00:30:46 +000010058 return I != MangleNumbers.end() ? I->second : 1;
David Blaikie095deba2012-11-14 01:52:05 +000010059}
10060
David Majnemer2206bf52014-03-05 08:57:59 +000010061void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
10062 if (Number > 1)
10063 StaticLocalNumbers[VD] = Number;
10064}
10065
10066unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
Richard Smithe9b02d62016-03-21 22:33:02 +000010067 auto I = StaticLocalNumbers.find(VD);
David Majnemer2206bf52014-03-05 08:57:59 +000010068 return I != StaticLocalNumbers.end() ? I->second : 1;
10069}
10070
Eli Friedman3b7d46c2013-07-10 00:30:46 +000010071MangleNumberingContext &
10072ASTContext::getManglingNumberContext(const DeclContext *DC) {
Reid Klecknerd8110b62013-09-10 20:14:30 +000010073 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
Justin Lebar20ebffc2016-10-10 16:26:19 +000010074 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
Reid Klecknerd8110b62013-09-10 20:14:30 +000010075 if (!MCtx)
10076 MCtx = createMangleNumberingContext();
10077 return *MCtx;
10078}
10079
Justin Lebar20ebffc2016-10-10 16:26:19 +000010080std::unique_ptr<MangleNumberingContext>
10081ASTContext::createMangleNumberingContext() const {
Reid Klecknerd8110b62013-09-10 20:14:30 +000010082 return ABI->createMangleNumberingContext();
Douglas Gregor63798542012-02-20 19:44:39 +000010083}
10084
David Majnemere7a818f2015-03-06 18:53:55 +000010085const CXXConstructorDecl *
10086ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
10087 return ABI->getCopyConstructorForExceptionObject(
10088 cast<CXXRecordDecl>(RD->getFirstDecl()));
10089}
10090
10091void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
10092 CXXConstructorDecl *CD) {
10093 return ABI->addCopyConstructorForExceptionObject(
10094 cast<CXXRecordDecl>(RD->getFirstDecl()),
10095 cast<CXXConstructorDecl>(CD->getFirstDecl()));
10096}
10097
David Majnemer00350522015-08-31 18:48:39 +000010098void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD,
10099 TypedefNameDecl *DD) {
10100 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
10101}
10102
10103TypedefNameDecl *
10104ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) {
10105 return ABI->getTypedefNameForUnnamedTagDecl(TD);
10106}
10107
10108void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD,
10109 DeclaratorDecl *DD) {
10110 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
10111}
10112
10113DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) {
10114 return ABI->getDeclaratorForUnnamedTagDecl(TD);
10115}
10116
Ted Kremenek540017e2011-10-06 05:00:56 +000010117void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
10118 ParamIndices[D] = index;
10119}
10120
10121unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
10122 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
Fangrui Song6907ce22018-07-30 19:24:48 +000010123 assert(I != ParamIndices.end() &&
Ted Kremenek540017e2011-10-06 05:00:56 +000010124 "ParmIndices lacks entry set by ParmVarDecl");
10125 return I->second;
10126}
Fariborz Jahanian615de762013-05-28 17:37:39 +000010127
Richard Smithe6c01442013-06-05 00:46:14 +000010128APValue *
10129ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
10130 bool MayCreate) {
10131 assert(E && E->getStorageDuration() == SD_Static &&
10132 "don't need to cache the computed value for this temporary");
David Majnemer2dcef9e2015-08-13 23:50:15 +000010133 if (MayCreate) {
10134 APValue *&MTVI = MaterializedTemporaryValues[E];
10135 if (!MTVI)
10136 MTVI = new (*this) APValue;
10137 return MTVI;
10138 }
Richard Smithe6c01442013-06-05 00:46:14 +000010139
David Majnemer2dcef9e2015-08-13 23:50:15 +000010140 return MaterializedTemporaryValues.lookup(E);
Richard Smithe6c01442013-06-05 00:46:14 +000010141}
10142
Fariborz Jahanian615de762013-05-28 17:37:39 +000010143bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
10144 const llvm::Triple &T = getTargetInfo().getTriple();
10145 if (!T.isOSDarwin())
10146 return false;
10147
Bob Wilson2c82c3d2013-11-02 23:27:49 +000010148 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
10149 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
10150 return false;
10151
Fariborz Jahanian615de762013-05-28 17:37:39 +000010152 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
10153 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
10154 uint64_t Size = sizeChars.getQuantity();
10155 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
10156 unsigned Align = alignChars.getQuantity();
10157 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
10158 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
10159}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010160
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010161/// Template specializations to abstract away from pointers and TypeLocs.
10162/// @{
10163template <typename T>
Sam McCall814e7972018-11-14 10:33:30 +000010164static ast_type_traits::DynTypedNode createDynTypedNode(const T &Node) {
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010165 return ast_type_traits::DynTypedNode::create(*Node);
10166}
10167template <>
10168ast_type_traits::DynTypedNode createDynTypedNode(const TypeLoc &Node) {
10169 return ast_type_traits::DynTypedNode::create(Node);
10170}
10171template <>
10172ast_type_traits::DynTypedNode
10173createDynTypedNode(const NestedNameSpecifierLoc &Node) {
10174 return ast_type_traits::DynTypedNode::create(Node);
10175}
10176/// @}
10177
Sam McCall814e7972018-11-14 10:33:30 +000010178/// A \c RecursiveASTVisitor that builds a map from nodes to their
10179/// parents as defined by the \c RecursiveASTVisitor.
10180///
10181/// Note that the relationship described here is purely in terms of AST
10182/// traversal - there are other relationships (for example declaration context)
10183/// in the AST that are better modeled by special matchers.
10184///
10185/// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
10186class ASTContext::ParentMap::ASTVisitor
10187 : public RecursiveASTVisitor<ASTVisitor> {
10188public:
10189 ASTVisitor(ParentMap &Map) : Map(Map) {}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010190
Sam McCall814e7972018-11-14 10:33:30 +000010191private:
10192 friend class RecursiveASTVisitor<ASTVisitor>;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000010193
Sam McCall814e7972018-11-14 10:33:30 +000010194 using VisitorBase = RecursiveASTVisitor<ASTVisitor>;
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010195
Sam McCall814e7972018-11-14 10:33:30 +000010196 bool shouldVisitTemplateInstantiations() const { return true; }
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010197
Sam McCall814e7972018-11-14 10:33:30 +000010198 bool shouldVisitImplicitCode() const { return true; }
10199
10200 template <typename T, typename MapNodeTy, typename BaseTraverseFn,
10201 typename MapTy>
10202 bool TraverseNode(T Node, MapNodeTy MapNode, BaseTraverseFn BaseTraverse,
10203 MapTy *Parents) {
10204 if (!Node)
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010205 return true;
Sam McCall814e7972018-11-14 10:33:30 +000010206 if (ParentStack.size() > 0) {
10207 // FIXME: Currently we add the same parent multiple times, but only
10208 // when no memoization data is available for the type.
10209 // For example when we visit all subexpressions of template
10210 // instantiations; this is suboptimal, but benign: the only way to
10211 // visit those is with hasAncestor / hasParent, and those do not create
10212 // new matches.
10213 // The plan is to enable DynTypedNode to be storable in a map or hash
10214 // map. The main problem there is to implement hash functions /
10215 // comparison operators for all types that DynTypedNode supports that
10216 // do not have pointer identity.
10217 auto &NodeOrVector = (*Parents)[MapNode];
10218 if (NodeOrVector.isNull()) {
10219 if (const auto *D = ParentStack.back().get<Decl>())
10220 NodeOrVector = D;
10221 else if (const auto *S = ParentStack.back().get<Stmt>())
10222 NodeOrVector = S;
10223 else
10224 NodeOrVector = new ast_type_traits::DynTypedNode(ParentStack.back());
10225 } else {
10226 if (!NodeOrVector.template is<ParentVector *>()) {
10227 auto *Vector = new ParentVector(
10228 1, getSingleDynTypedNodeFromParentMap(NodeOrVector));
10229 delete NodeOrVector
10230 .template dyn_cast<ast_type_traits::DynTypedNode *>();
10231 NodeOrVector = Vector;
Manuel Klimek95403e62014-05-21 13:28:59 +000010232 }
Sam McCall814e7972018-11-14 10:33:30 +000010233
10234 auto *Vector = NodeOrVector.template get<ParentVector *>();
10235 // Skip duplicates for types that have memoization data.
10236 // We must check that the type has memoization data before calling
10237 // std::find() because DynTypedNode::operator== can't compare all
10238 // types.
10239 bool Found = ParentStack.back().getMemoizationData() &&
10240 std::find(Vector->begin(), Vector->end(),
10241 ParentStack.back()) != Vector->end();
10242 if (!Found)
10243 Vector->push_back(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +000010244 }
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010245 }
Sam McCall814e7972018-11-14 10:33:30 +000010246 ParentStack.push_back(createDynTypedNode(Node));
10247 bool Result = BaseTraverse();
10248 ParentStack.pop_back();
10249 return Result;
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010250 }
Sam McCall814e7972018-11-14 10:33:30 +000010251
10252 bool TraverseDecl(Decl *DeclNode) {
10253 return TraverseNode(
10254 DeclNode, DeclNode, [&] { return VisitorBase::TraverseDecl(DeclNode); },
10255 &Map.PointerParents);
Manuel Klimek95403e62014-05-21 13:28:59 +000010256 }
Sam McCall814e7972018-11-14 10:33:30 +000010257
10258 bool TraverseStmt(Stmt *StmtNode) {
10259 return TraverseNode(
10260 StmtNode, StmtNode, [&] { return VisitorBase::TraverseStmt(StmtNode); },
10261 &Map.PointerParents);
10262 }
10263
10264 bool TraverseTypeLoc(TypeLoc TypeLocNode) {
10265 return TraverseNode(
10266 TypeLocNode, ast_type_traits::DynTypedNode::create(TypeLocNode),
10267 [&] { return VisitorBase::TraverseTypeLoc(TypeLocNode); },
10268 &Map.OtherParents);
10269 }
10270
10271 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNSLocNode) {
10272 return TraverseNode(
10273 NNSLocNode, ast_type_traits::DynTypedNode::create(NNSLocNode),
10274 [&] { return VisitorBase::TraverseNestedNameSpecifierLoc(NNSLocNode); },
10275 &Map.OtherParents);
10276 }
10277
10278 ParentMap &Map;
10279 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
10280};
10281
10282ASTContext::ParentMap::ParentMap(ASTContext &Ctx) {
10283 ASTVisitor(*this).TraverseAST(Ctx);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010284}
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010285
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010286ASTContext::DynTypedNodeList
10287ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
Sam McCall814e7972018-11-14 10:33:30 +000010288 if (!Parents)
10289 // We build the parent map for the traversal scope (usually whole TU), as
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010290 // hasAncestor can escape any subtree.
Sam McCall814e7972018-11-14 10:33:30 +000010291 Parents = llvm::make_unique<ParentMap>(*this);
10292 return Parents->getParents(Node);
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010293}
10294
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010295bool
10296ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
10297 const ObjCMethodDecl *MethodImpl) {
10298 // No point trying to match an unavailable/deprecated mothod.
10299 if (MethodDecl->hasAttr<UnavailableAttr>()
10300 || MethodDecl->hasAttr<DeprecatedAttr>())
10301 return false;
10302 if (MethodDecl->getObjCDeclQualifier() !=
10303 MethodImpl->getObjCDeclQualifier())
10304 return false;
Alp Toker314cc812014-01-25 16:55:45 +000010305 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010306 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +000010307
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010308 if (MethodDecl->param_size() != MethodImpl->param_size())
10309 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +000010310
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010311 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
10312 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
10313 EF = MethodDecl->param_end();
10314 IM != EM && IF != EF; ++IM, ++IF) {
10315 const ParmVarDecl *DeclVar = (*IF);
10316 const ParmVarDecl *ImplVar = (*IM);
10317 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
10318 return false;
10319 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
10320 return false;
10321 }
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000010322
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010323 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010324}
Richard Smith053f6c62014-05-16 23:01:30 +000010325
Yaxun Liu402804b2016-12-15 08:09:08 +000010326uint64_t ASTContext::getTargetNullPointerValue(QualType QT) const {
Alexander Richardson6d989432017-10-15 18:48:14 +000010327 LangAS AS;
Yaxun Liu402804b2016-12-15 08:09:08 +000010328 if (QT->getUnqualifiedDesugaredType()->isNullPtrType())
Alexander Richardson6d989432017-10-15 18:48:14 +000010329 AS = LangAS::Default;
Yaxun Liu402804b2016-12-15 08:09:08 +000010330 else
10331 AS = QT->getPointeeType().getAddressSpace();
10332
10333 return getTargetInfo().getNullPointerValue(AS);
10334}
10335
Alexander Richardson6d989432017-10-15 18:48:14 +000010336unsigned ASTContext::getTargetAddressSpace(LangAS AS) const {
10337 if (isTargetAddressSpace(AS))
10338 return toTargetAddressSpace(AS);
Yaxun Liub34ec822017-04-11 17:24:23 +000010339 else
Alexander Richardson6d989432017-10-15 18:48:14 +000010340 return (*AddrSpaceMap)[(unsigned)AS];
Yaxun Liub34ec822017-04-11 17:24:23 +000010341}
10342
Leonard Chanab80f3c2018-06-14 14:53:51 +000010343QualType ASTContext::getCorrespondingSaturatedType(QualType Ty) const {
10344 assert(Ty->isFixedPointType());
10345
10346 if (Ty->isSaturatedFixedPointType()) return Ty;
10347
10348 const auto &BT = Ty->getAs<BuiltinType>();
10349 switch (BT->getKind()) {
10350 default:
10351 llvm_unreachable("Not a fixed point type!");
10352 case BuiltinType::ShortAccum:
10353 return SatShortAccumTy;
10354 case BuiltinType::Accum:
10355 return SatAccumTy;
10356 case BuiltinType::LongAccum:
10357 return SatLongAccumTy;
10358 case BuiltinType::UShortAccum:
10359 return SatUnsignedShortAccumTy;
10360 case BuiltinType::UAccum:
10361 return SatUnsignedAccumTy;
10362 case BuiltinType::ULongAccum:
10363 return SatUnsignedLongAccumTy;
10364 case BuiltinType::ShortFract:
10365 return SatShortFractTy;
10366 case BuiltinType::Fract:
10367 return SatFractTy;
10368 case BuiltinType::LongFract:
10369 return SatLongFractTy;
10370 case BuiltinType::UShortFract:
10371 return SatUnsignedShortFractTy;
10372 case BuiltinType::UFract:
10373 return SatUnsignedFractTy;
10374 case BuiltinType::ULongFract:
10375 return SatUnsignedLongFractTy;
10376 }
10377}
10378
Matt Arsenaultc65f9662018-08-02 12:14:28 +000010379LangAS ASTContext::getLangASForBuiltinAddressSpace(unsigned AS) const {
10380 if (LangOpts.OpenCL)
10381 return getTargetInfo().getOpenCLBuiltinAddressSpace(AS);
10382
10383 if (LangOpts.CUDA)
10384 return getTargetInfo().getCUDABuiltinAddressSpace(AS);
10385
10386 return getLangASFromTargetAS(AS);
10387}
10388
Richard Smith053f6c62014-05-16 23:01:30 +000010389// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
10390// doesn't include ASTContext.h
10391template
10392clang::LazyGenerationalUpdatePtr<
10393 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
10394clang::LazyGenerationalUpdatePtr<
10395 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
10396 const clang::ASTContext &Ctx, Decl *Value);
Leonard Chandb01c3a2018-06-20 17:19:40 +000010397
10398unsigned char ASTContext::getFixedPointScale(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.getShortAccumScale();
10409 case BuiltinType::Accum:
10410 case BuiltinType::SatAccum:
10411 return Target.getAccumScale();
10412 case BuiltinType::LongAccum:
10413 case BuiltinType::SatLongAccum:
10414 return Target.getLongAccumScale();
10415 case BuiltinType::UShortAccum:
10416 case BuiltinType::SatUShortAccum:
10417 return Target.getUnsignedShortAccumScale();
10418 case BuiltinType::UAccum:
10419 case BuiltinType::SatUAccum:
10420 return Target.getUnsignedAccumScale();
10421 case BuiltinType::ULongAccum:
10422 case BuiltinType::SatULongAccum:
10423 return Target.getUnsignedLongAccumScale();
10424 case BuiltinType::ShortFract:
10425 case BuiltinType::SatShortFract:
10426 return Target.getShortFractScale();
10427 case BuiltinType::Fract:
10428 case BuiltinType::SatFract:
10429 return Target.getFractScale();
10430 case BuiltinType::LongFract:
10431 case BuiltinType::SatLongFract:
10432 return Target.getLongFractScale();
10433 case BuiltinType::UShortFract:
10434 case BuiltinType::SatUShortFract:
10435 return Target.getUnsignedShortFractScale();
10436 case BuiltinType::UFract:
10437 case BuiltinType::SatUFract:
10438 return Target.getUnsignedFractScale();
10439 case BuiltinType::ULongFract:
10440 case BuiltinType::SatULongFract:
10441 return Target.getUnsignedLongFractScale();
10442 }
10443}
10444
10445unsigned char ASTContext::getFixedPointIBits(QualType Ty) const {
10446 assert(Ty->isFixedPointType());
10447
10448 const auto *BT = Ty->getAs<BuiltinType>();
10449 const TargetInfo &Target = getTargetInfo();
10450 switch (BT->getKind()) {
10451 default:
10452 llvm_unreachable("Not a fixed point type!");
10453 case BuiltinType::ShortAccum:
10454 case BuiltinType::SatShortAccum:
10455 return Target.getShortAccumIBits();
10456 case BuiltinType::Accum:
10457 case BuiltinType::SatAccum:
10458 return Target.getAccumIBits();
10459 case BuiltinType::LongAccum:
10460 case BuiltinType::SatLongAccum:
10461 return Target.getLongAccumIBits();
10462 case BuiltinType::UShortAccum:
10463 case BuiltinType::SatUShortAccum:
10464 return Target.getUnsignedShortAccumIBits();
10465 case BuiltinType::UAccum:
10466 case BuiltinType::SatUAccum:
10467 return Target.getUnsignedAccumIBits();
10468 case BuiltinType::ULongAccum:
10469 case BuiltinType::SatULongAccum:
10470 return Target.getUnsignedLongAccumIBits();
10471 case BuiltinType::ShortFract:
10472 case BuiltinType::SatShortFract:
10473 case BuiltinType::Fract:
10474 case BuiltinType::SatFract:
10475 case BuiltinType::LongFract:
10476 case BuiltinType::SatLongFract:
10477 case BuiltinType::UShortFract:
10478 case BuiltinType::SatUShortFract:
10479 case BuiltinType::UFract:
10480 case BuiltinType::SatUFract:
10481 case BuiltinType::ULongFract:
10482 case BuiltinType::SatULongFract:
10483 return 0;
10484 }
10485}
Leonard Chana6779422018-08-06 16:42:37 +000010486
10487FixedPointSemantics ASTContext::getFixedPointSemantics(QualType Ty) const {
10488 assert(Ty->isFixedPointType());
10489 bool isSigned = Ty->isSignedFixedPointType();
10490 return FixedPointSemantics(
10491 static_cast<unsigned>(getTypeSize(Ty)), getFixedPointScale(Ty), isSigned,
10492 Ty->isSaturatedFixedPointType(),
10493 !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding());
10494}
10495
10496APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const {
10497 assert(Ty->isFixedPointType());
10498 return APFixedPoint::getMax(getFixedPointSemantics(Ty));
10499}
10500
10501APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const {
10502 assert(Ty->isFixedPointType());
10503 return APFixedPoint::getMin(getFixedPointSemantics(Ty));
10504}