blob: 4956710b4f50b17c270c91940734687632b0ba44 [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"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000051#include "clang/Basic/IdentifierTable.h"
52#include "clang/Basic/LLVM.h"
53#include "clang/Basic/LangOptions.h"
54#include "clang/Basic/Linkage.h"
55#include "clang/Basic/ObjCRuntime.h"
56#include "clang/Basic/SanitizerBlacklist.h"
57#include "clang/Basic/SourceLocation.h"
Chris Lattnerd2868512009-03-28 03:45:20 +000058#include "clang/Basic/SourceManager.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000059#include "clang/Basic/Specifiers.h"
60#include "clang/Basic/TargetCXXABI.h"
Chris Lattner4dc8a6f2007-05-20 23:50:58 +000061#include "clang/Basic/TargetInfo.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000062#include "clang/Basic/XRayLists.h"
63#include "llvm/ADT/APInt.h"
64#include "llvm/ADT/APSInt.h"
65#include "llvm/ADT/ArrayRef.h"
66#include "llvm/ADT/DenseMap.h"
67#include "llvm/ADT/DenseSet.h"
68#include "llvm/ADT/FoldingSet.h"
69#include "llvm/ADT/None.h"
70#include "llvm/ADT/Optional.h"
71#include "llvm/ADT/PointerUnion.h"
72#include "llvm/ADT/STLExtras.h"
73#include "llvm/ADT/SmallPtrSet.h"
74#include "llvm/ADT/SmallVector.h"
Anders Carlssond8499822007-10-29 05:01:08 +000075#include "llvm/ADT/StringExtras.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000076#include "llvm/ADT/StringRef.h"
Robert Lyttoneaf6f362013-11-12 10:09:34 +000077#include "llvm/ADT/Triple.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000078#include "llvm/Support/Capacity.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000079#include "llvm/Support/Casting.h"
80#include "llvm/Support/Compiler.h"
81#include "llvm/Support/ErrorHandling.h"
Nate Begemanb699c9b2009-01-18 06:42:49 +000082#include "llvm/Support/MathExtras.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000083#include "llvm/Support/raw_ostream.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000084#include <algorithm>
85#include <cassert>
86#include <cstddef>
87#include <cstdint>
88#include <cstdlib>
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +000089#include <map>
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000090#include <memory>
91#include <string>
92#include <tuple>
93#include <utility>
Anders Carlssona4267a62009-07-18 21:19:52 +000094
Chris Lattnerddc135e2006-11-10 06:34:16 +000095using namespace clang;
96
Douglas Gregor9672f922010-07-03 00:47:00 +000097unsigned ASTContext::NumImplicitDefaultConstructors;
98unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregora6d69502010-07-02 23:41:54 +000099unsigned ASTContext::NumImplicitCopyConstructors;
100unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +0000101unsigned ASTContext::NumImplicitMoveConstructors;
102unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000103unsigned ASTContext::NumImplicitCopyAssignmentOperators;
104unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +0000105unsigned ASTContext::NumImplicitMoveAssignmentOperators;
106unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
Douglas Gregor7454c562010-07-02 20:37:36 +0000107unsigned ASTContext::NumImplicitDestructors;
108unsigned ASTContext::NumImplicitDestructorsDeclared;
109
Steve Naroff0af91202007-04-27 21:51:21 +0000110enum FloatingRank {
Sjoerd Meijercc623ad2017-09-08 15:15:00 +0000111 Float16Rank, HalfRank, FloatRank, DoubleRank, LongDoubleRank, Float128Rank
Steve Naroff0af91202007-04-27 21:51:21 +0000112};
113
Dmitri Gribenkof26054f2012-07-11 21:38:39 +0000114RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000115 if (!CommentsLoaded && ExternalSource) {
116 ExternalSource->ReadComments();
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +0000117
118#ifndef NDEBUG
119 ArrayRef<RawComment *> RawComments = Comments.getComments();
120 assert(std::is_sorted(RawComments.begin(), RawComments.end(),
121 BeforeThanCompare<RawComment>(SourceMgr)));
122#endif
123
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000124 CommentsLoaded = true;
125 }
126
127 assert(D);
128
Dmitri Gribenkodf17d642012-06-28 16:19:39 +0000129 // User can not attach documentation to implicit declarations.
130 if (D->isImplicit())
Craig Topper36250ad2014-05-12 05:36:57 +0000131 return nullptr;
Dmitri Gribenkodf17d642012-06-28 16:19:39 +0000132
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000133 // User can not attach documentation to implicit instantiations.
Eugene Zelenko7855e772018-04-03 00:11:50 +0000134 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000135 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +0000136 return nullptr;
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000137 }
138
Eugene Zelenko7855e772018-04-03 00:11:50 +0000139 if (const auto *VD = dyn_cast<VarDecl>(D)) {
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000140 if (VD->isStaticDataMember() &&
141 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +0000142 return nullptr;
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000143 }
144
Eugene Zelenko7855e772018-04-03 00:11:50 +0000145 if (const auto *CRD = dyn_cast<CXXRecordDecl>(D)) {
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000146 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +0000147 return nullptr;
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000148 }
149
Eugene Zelenko7855e772018-04-03 00:11:50 +0000150 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000151 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
152 if (TSK == TSK_ImplicitInstantiation ||
153 TSK == TSK_Undeclared)
Craig Topper36250ad2014-05-12 05:36:57 +0000154 return nullptr;
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000155 }
156
Eugene Zelenko7855e772018-04-03 00:11:50 +0000157 if (const auto *ED = dyn_cast<EnumDecl>(D)) {
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000158 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +0000159 return nullptr;
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000160 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000161 if (const auto *TD = dyn_cast<TagDecl>(D)) {
Fariborz Jahanian799a4032013-04-17 21:05:20 +0000162 // When tag declaration (but not definition!) is part of the
163 // decl-specifier-seq of some other declaration, it doesn't get comment
164 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
Craig Topper36250ad2014-05-12 05:36:57 +0000165 return nullptr;
Fariborz Jahanian799a4032013-04-17 21:05:20 +0000166 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000167 // TODO: handle comments for function parameters properly.
168 if (isa<ParmVarDecl>(D))
Craig Topper36250ad2014-05-12 05:36:57 +0000169 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000170
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000171 // TODO: we could look up template parameter documentation in the template
172 // documentation.
173 if (isa<TemplateTypeParmDecl>(D) ||
174 isa<NonTypeTemplateParmDecl>(D) ||
175 isa<TemplateTemplateParmDecl>(D))
Craig Topper36250ad2014-05-12 05:36:57 +0000176 return nullptr;
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000177
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000178 ArrayRef<RawComment *> RawComments = Comments.getComments();
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000179
180 // If there are no comments anywhere, we won't find anything.
181 if (RawComments.empty())
Craig Topper36250ad2014-05-12 05:36:57 +0000182 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000183
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000184 // Find declaration location.
185 // For Objective-C declarations we generally don't expect to have multiple
186 // declarators, thus use declaration starting location as the "declaration
187 // location".
188 // For all other declarations multiple declarators are used quite frequently,
189 // so we use the location of the identifier as the "declaration location".
190 SourceLocation DeclLoc;
191 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000192 isa<ObjCPropertyDecl>(D) ||
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +0000193 isa<RedeclarableTemplateDecl>(D) ||
194 isa<ClassTemplateSpecializationDecl>(D))
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000195 DeclLoc = D->getLocStart();
Fariborz Jahanianb64e95f2013-07-24 22:58:51 +0000196 else {
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000197 DeclLoc = D->getLocation();
Dmitri Gribenkoef099dc2014-03-27 16:40:51 +0000198 if (DeclLoc.isMacroID()) {
199 if (isa<TypedefDecl>(D)) {
200 // If location of the typedef name is in a macro, it is because being
201 // declared via a macro. Try using declaration's starting location as
202 // the "declaration location".
203 DeclLoc = D->getLocStart();
Eugene Zelenko7855e772018-04-03 00:11:50 +0000204 } else if (const auto *TD = dyn_cast<TagDecl>(D)) {
Dmitri Gribenkoef099dc2014-03-27 16:40:51 +0000205 // If location of the tag decl is inside a macro, but the spelling of
206 // the tag name comes from a macro argument, it looks like a special
207 // macro like NS_ENUM is being used to define the tag decl. In that
208 // case, adjust the source location to the expansion loc so that we can
209 // attach the comment to the tag decl.
210 if (SourceMgr.isMacroArgExpansion(DeclLoc) &&
211 TD->isCompleteDefinition())
212 DeclLoc = SourceMgr.getExpansionLoc(DeclLoc);
213 }
214 }
Fariborz Jahanianb64e95f2013-07-24 22:58:51 +0000215 }
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000216
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000217 // If the declaration doesn't map directly to a location in a file, we
218 // can't find the comment.
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000219 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
Craig Topper36250ad2014-05-12 05:36:57 +0000220 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000221
222 // Find the comment that occurs just after this declaration.
Dmitri Gribenko82ea9472012-07-17 22:01:09 +0000223 ArrayRef<RawComment *>::iterator Comment;
224 {
225 // When searching for comments during parsing, the comment we are looking
226 // for is usually among the last two comments we parsed -- check them
227 // first.
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +0000228 RawComment CommentAtDeclLoc(
David L. Jones13d5a872018-03-02 00:07:45 +0000229 SourceMgr, SourceRange(DeclLoc), LangOpts.CommentOpts, false);
Dmitri Gribenko82ea9472012-07-17 22:01:09 +0000230 BeforeThanCompare<RawComment> Compare(SourceMgr);
231 ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1;
232 bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
233 if (!Found && RawComments.size() >= 2) {
234 MaybeBeforeDecl--;
235 Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
236 }
237
238 if (Found) {
239 Comment = MaybeBeforeDecl + 1;
240 assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(),
241 &CommentAtDeclLoc, Compare));
242 } else {
243 // Slow path.
244 Comment = std::lower_bound(RawComments.begin(), RawComments.end(),
245 &CommentAtDeclLoc, Compare);
246 }
247 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000248
249 // Decompose the location for the declaration and find the beginning of the
250 // file buffer.
251 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
252
253 // First check whether we have a trailing comment.
254 if (Comment != RawComments.end() &&
David L. Jones13d5a872018-03-02 00:07:45 +0000255 ((*Comment)->isDocumentation() || LangOpts.CommentOpts.ParseAllComments)
256 && (*Comment)->isTrailingComment() &&
Fariborz Jahanianfad28542013-08-06 23:29:00 +0000257 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
Fariborz Jahanian3ab62222013-08-07 16:40:29 +0000258 isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000259 std::pair<FileID, unsigned> CommentBeginDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000260 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000261 // Check that Doxygen trailing comment comes after the declaration, starts
262 // on the same line and in the same file as the declaration.
263 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
264 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
265 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
266 CommentBeginDecomp.second)) {
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000267 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000268 }
269 }
270
271 // The comment just after the declaration was not a trailing comment.
272 // Let's look at the previous comment.
273 if (Comment == RawComments.begin())
Craig Topper36250ad2014-05-12 05:36:57 +0000274 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000275 --Comment;
276
277 // Check that we actually have a non-member Doxygen comment.
David L. Jones13d5a872018-03-02 00:07:45 +0000278 if (!((*Comment)->isDocumentation() ||
279 LangOpts.CommentOpts.ParseAllComments) ||
280 (*Comment)->isTrailingComment())
Craig Topper36250ad2014-05-12 05:36:57 +0000281 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000282
283 // Decompose the end of the comment.
284 std::pair<FileID, unsigned> CommentEndDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000285 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000286
287 // If the comment and the declaration aren't in the same file, then they
288 // aren't related.
289 if (DeclLocDecomp.first != CommentEndDecomp.first)
Craig Topper36250ad2014-05-12 05:36:57 +0000290 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000291
292 // Get the corresponding buffer.
293 bool Invalid = false;
294 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
295 &Invalid).data();
296 if (Invalid)
Craig Topper36250ad2014-05-12 05:36:57 +0000297 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000298
299 // Extract text between the comment and declaration.
300 StringRef Text(Buffer + CommentEndDecomp.second,
301 DeclLocDecomp.second - CommentEndDecomp.second);
302
Dmitri Gribenko7e8729b2012-06-27 23:43:37 +0000303 // There should be no other declarations or preprocessor directives between
304 // comment and declaration.
Argyrios Kyrtzidisb534d3a2013-07-26 18:38:12 +0000305 if (Text.find_first_of(";{}#@") != StringRef::npos)
Craig Topper36250ad2014-05-12 05:36:57 +0000306 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000307
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000308 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000309}
310
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000311/// If we have a 'templated' declaration for a template, adjust 'D' to
312/// refer to the actual template.
Dmitri Gribenko90631802012-08-22 17:44:32 +0000313/// If we have an implicit instantiation, adjust 'D' to refer to template.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +0000314static const Decl *adjustDeclToTemplate(const Decl *D) {
Eugene Zelenko7855e772018-04-03 00:11:50 +0000315 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000316 // Is this function declaration part of a function template?
Douglas Gregor35ceb272012-08-13 16:37:30 +0000317 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
Dmitri Gribenko90631802012-08-22 17:44:32 +0000318 return FTD;
319
320 // Nothing to do if function is not an implicit instantiation.
321 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
322 return D;
323
324 // Function is an implicit instantiation of a function template?
325 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
326 return FTD;
327
328 // Function is instantiated from a member definition of a class template?
329 if (const FunctionDecl *MemberDecl =
330 FD->getInstantiatedFromMemberFunction())
331 return MemberDecl;
332
333 return D;
Douglas Gregor35ceb272012-08-13 16:37:30 +0000334 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000335 if (const auto *VD = dyn_cast<VarDecl>(D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000336 // Static data member is instantiated from a member definition of a class
337 // template?
338 if (VD->isStaticDataMember())
339 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
340 return MemberDecl;
341
342 return D;
343 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000344 if (const auto *CRD = dyn_cast<CXXRecordDecl>(D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000345 // Is this class declaration part of a class template?
346 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
347 return CTD;
348
349 // Class is an implicit instantiation of a class template or partial
350 // specialization?
Eugene Zelenko7855e772018-04-03 00:11:50 +0000351 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000352 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
353 return D;
354 llvm::PointerUnion<ClassTemplateDecl *,
355 ClassTemplatePartialSpecializationDecl *>
356 PU = CTSD->getSpecializedTemplateOrPartial();
357 return PU.is<ClassTemplateDecl*>() ?
358 static_cast<const Decl*>(PU.get<ClassTemplateDecl *>()) :
359 static_cast<const Decl*>(
360 PU.get<ClassTemplatePartialSpecializationDecl *>());
361 }
362
363 // Class is instantiated from a member definition of a class template?
364 if (const MemberSpecializationInfo *Info =
365 CRD->getMemberSpecializationInfo())
366 return Info->getInstantiatedFrom();
367
368 return D;
369 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000370 if (const auto *ED = dyn_cast<EnumDecl>(D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000371 // Enum is instantiated from a member definition of a class template?
372 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
373 return MemberDecl;
374
375 return D;
376 }
377 // FIXME: Adjust alias templates?
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000378 return D;
379}
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000380
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000381const RawComment *ASTContext::getRawCommentForAnyRedecl(
382 const Decl *D,
383 const Decl **OriginalDecl) const {
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000384 D = adjustDeclToTemplate(D);
Douglas Gregor35ceb272012-08-13 16:37:30 +0000385
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000386 // Check whether we have cached a comment for this declaration already.
387 {
388 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
389 RedeclComments.find(D);
390 if (Pos != RedeclComments.end()) {
391 const RawCommentAndCacheFlags &Raw = Pos->second;
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000392 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
393 if (OriginalDecl)
394 *OriginalDecl = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000395 return Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000396 }
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000397 }
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000398 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000399
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000400 // Search for comments attached to declarations in the redeclaration chain.
Craig Topper36250ad2014-05-12 05:36:57 +0000401 const RawComment *RC = nullptr;
402 const Decl *OriginalDeclForRC = nullptr;
Aaron Ballman86c93902014-03-06 23:45:36 +0000403 for (auto I : D->redecls()) {
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000404 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
Aaron Ballman86c93902014-03-06 23:45:36 +0000405 RedeclComments.find(I);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000406 if (Pos != RedeclComments.end()) {
407 const RawCommentAndCacheFlags &Raw = Pos->second;
408 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
409 RC = Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000410 OriginalDeclForRC = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000411 break;
412 }
413 } else {
Aaron Ballman86c93902014-03-06 23:45:36 +0000414 RC = getRawCommentForDeclNoCache(I);
415 OriginalDeclForRC = I;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000416 RawCommentAndCacheFlags Raw;
417 if (RC) {
Will Wilsonf9de5362015-10-27 17:01:10 +0000418 // Call order swapped to work around ICE in VS2015 RTM (Release Win32)
419 // https://connect.microsoft.com/VisualStudio/feedback/details/1741530
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000420 Raw.setKind(RawCommentAndCacheFlags::FromDecl);
Will Wilsonf9de5362015-10-27 17:01:10 +0000421 Raw.setRaw(RC);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000422 } else
423 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
Aaron Ballman86c93902014-03-06 23:45:36 +0000424 Raw.setOriginalDecl(I);
425 RedeclComments[I] = Raw;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000426 if (RC)
427 break;
428 }
429 }
430
Dmitri Gribenko5c8897d2012-06-28 16:25:36 +0000431 // If we found a comment, it should be a documentation comment.
David L. Jones13d5a872018-03-02 00:07:45 +0000432 assert(!RC || RC->isDocumentation() || LangOpts.CommentOpts.ParseAllComments);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000433
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000434 if (OriginalDecl)
435 *OriginalDecl = OriginalDeclForRC;
436
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000437 // Update cache for every declaration in the redeclaration chain.
438 RawCommentAndCacheFlags Raw;
439 Raw.setRaw(RC);
440 Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000441 Raw.setOriginalDecl(OriginalDeclForRC);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000442
Aaron Ballman86c93902014-03-06 23:45:36 +0000443 for (auto I : D->redecls()) {
444 RawCommentAndCacheFlags &R = RedeclComments[I];
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000445 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
446 R = Raw;
447 }
448
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000449 return RC;
450}
451
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000452static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
453 SmallVectorImpl<const NamedDecl *> &Redeclared) {
454 const DeclContext *DC = ObjCMethod->getDeclContext();
Eugene Zelenko7855e772018-04-03 00:11:50 +0000455 if (const auto *IMD = dyn_cast<ObjCImplDecl>(DC)) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000456 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
457 if (!ID)
458 return;
459 // Add redeclared method here.
Aaron Ballmanb4a53452014-03-13 21:57:01 +0000460 for (const auto *Ext : ID->known_extensions()) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000461 if (ObjCMethodDecl *RedeclaredMethod =
Douglas Gregor048fbfa2013-01-16 23:00:23 +0000462 Ext->getMethod(ObjCMethod->getSelector(),
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000463 ObjCMethod->isInstanceMethod()))
464 Redeclared.push_back(RedeclaredMethod);
465 }
466 }
467}
468
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000469comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
470 const Decl *D) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +0000471 auto *ThisDeclInfo = new (*this) comments::DeclInfo;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000472 ThisDeclInfo->CommentDecl = D;
473 ThisDeclInfo->IsFilled = false;
474 ThisDeclInfo->fill();
475 ThisDeclInfo->CommentDecl = FC->getDecl();
Argyrios Kyrtzidis7daabbd2014-04-27 22:53:03 +0000476 if (!ThisDeclInfo->TemplateParameters)
477 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000478 comments::FullComment *CFC =
479 new (*this) comments::FullComment(FC->getBlocks(),
480 ThisDeclInfo);
481 return CFC;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000482}
483
Richard Smithb39b9d52013-05-21 05:24:00 +0000484comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
485 const RawComment *RC = getRawCommentForDeclNoCache(D);
Craig Topper36250ad2014-05-12 05:36:57 +0000486 return RC ? RC->parse(*this, nullptr, D) : nullptr;
Richard Smithb39b9d52013-05-21 05:24:00 +0000487}
488
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000489comments::FullComment *ASTContext::getCommentForDecl(
490 const Decl *D,
491 const Preprocessor *PP) const {
Fariborz Jahanian096f7c12013-05-13 17:27:00 +0000492 if (D->isInvalidDecl())
Craig Topper36250ad2014-05-12 05:36:57 +0000493 return nullptr;
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000494 D = adjustDeclToTemplate(D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000495
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000496 const Decl *Canonical = D->getCanonicalDecl();
497 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
498 ParsedComments.find(Canonical);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000499
500 if (Pos != ParsedComments.end()) {
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000501 if (Canonical != D) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000502 comments::FullComment *FC = Pos->second;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000503 comments::FullComment *CFC = cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000504 return CFC;
505 }
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000506 return Pos->second;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000507 }
508
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000509 const Decl *OriginalDecl;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000510
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000511 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000512 if (!RC) {
513 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000514 SmallVector<const NamedDecl*, 8> Overridden;
Eugene Zelenko7855e772018-04-03 00:11:50 +0000515 const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000516 if (OMD && OMD->isPropertyAccessor())
517 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
518 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
519 return cloneFullComment(FC, D);
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000520 if (OMD)
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000521 addRedeclaredMethods(OMD, Overridden);
522 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000523 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
524 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
525 return cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000526 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000527 else if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000528 // Attach any tag type's documentation to its typedef if latter
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000529 // does not have one of its own.
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000530 QualType QT = TD->getUnderlyingType();
Eugene Zelenko7855e772018-04-03 00:11:50 +0000531 if (const auto *TT = QT->getAs<TagType>())
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000532 if (const Decl *TD = TT->getDecl())
533 if (comments::FullComment *FC = getCommentForDecl(TD, PP))
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000534 return cloneFullComment(FC, D);
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000535 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000536 else if (const auto *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000537 while (IC->getSuperClass()) {
538 IC = IC->getSuperClass();
539 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
540 return cloneFullComment(FC, D);
541 }
542 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000543 else if (const auto *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000544 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
545 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
546 return cloneFullComment(FC, D);
547 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000548 else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000549 if (!(RD = RD->getDefinition()))
Craig Topper36250ad2014-05-12 05:36:57 +0000550 return nullptr;
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000551 // Check non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +0000552 for (const auto &I : RD->bases()) {
553 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000554 continue;
Aaron Ballman574705e2014-03-13 15:41:46 +0000555 QualType Ty = I.getType();
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000556 if (Ty.isNull())
557 continue;
558 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
559 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
560 continue;
561
562 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
563 return cloneFullComment(FC, D);
564 }
565 }
566 // Check virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +0000567 for (const auto &I : RD->vbases()) {
568 if (I.getAccessSpecifier() != AS_public)
Fariborz Jahanian5a2e4a22013-04-26 23:34:36 +0000569 continue;
Aaron Ballman445a9392014-03-13 16:15:17 +0000570 QualType Ty = I.getType();
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000571 if (Ty.isNull())
572 continue;
573 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
574 if (!(VirtualBase= VirtualBase->getDefinition()))
575 continue;
576 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
577 return cloneFullComment(FC, D);
578 }
579 }
580 }
Craig Topper36250ad2014-05-12 05:36:57 +0000581 return nullptr;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000582 }
583
Dmitri Gribenkobfda9f72012-08-22 18:12:19 +0000584 // If the RawComment was attached to other redeclaration of this Decl, we
585 // should parse the comment in context of that other Decl. This is important
586 // because comments can contain references to parameter names which can be
587 // different across redeclarations.
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000588 if (D != OriginalDecl)
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000589 return getCommentForDecl(OriginalDecl, PP);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000590
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000591 comments::FullComment *FC = RC->parse(*this, PP, D);
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000592 ParsedComments[Canonical] = FC;
593 return FC;
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000594}
595
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000596void
597ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
598 TemplateTemplateParmDecl *Parm) {
599 ID.AddInteger(Parm->getDepth());
600 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +0000601 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000602
603 TemplateParameterList *Params = Parm->getTemplateParameters();
604 ID.AddInteger(Params->size());
605 for (TemplateParameterList::const_iterator P = Params->begin(),
606 PEnd = Params->end();
607 P != PEnd; ++P) {
Eugene Zelenko7855e772018-04-03 00:11:50 +0000608 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000609 ID.AddInteger(0);
610 ID.AddBoolean(TTP->isParameterPack());
611 continue;
612 }
613
Eugene Zelenko7855e772018-04-03 00:11:50 +0000614 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000615 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +0000616 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman205a4292012-03-07 01:09:33 +0000617 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000618 if (NTTP->isExpandedParameterPack()) {
619 ID.AddBoolean(true);
620 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman205a4292012-03-07 01:09:33 +0000621 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
622 QualType T = NTTP->getExpansionType(I);
623 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
624 }
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000625 } else
626 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000627 continue;
628 }
629
Eugene Zelenko7855e772018-04-03 00:11:50 +0000630 auto *TTP = cast<TemplateTemplateParmDecl>(*P);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000631 ID.AddInteger(2);
632 Profile(ID, TTP);
633 }
634}
635
636TemplateTemplateParmDecl *
637ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +0000638 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000639 // Check if we already have a canonical template template parameter.
640 llvm::FoldingSetNodeID ID;
641 CanonicalTemplateTemplateParm::Profile(ID, TTP);
Craig Topper36250ad2014-05-12 05:36:57 +0000642 void *InsertPos = nullptr;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000643 CanonicalTemplateTemplateParm *Canonical
644 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
645 if (Canonical)
646 return Canonical->getParam();
647
648 // Build a canonical template parameter list.
649 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000650 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000651 CanonParams.reserve(Params->size());
652 for (TemplateParameterList::const_iterator P = Params->begin(),
653 PEnd = Params->end();
654 P != PEnd; ++P) {
Eugene Zelenko7855e772018-04-03 00:11:50 +0000655 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000656 CanonParams.push_back(
657 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000658 SourceLocation(),
659 SourceLocation(),
660 TTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000661 TTP->getIndex(), nullptr, false,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000662 TTP->isParameterPack()));
Eugene Zelenko7855e772018-04-03 00:11:50 +0000663 else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000664 QualType T = getCanonicalType(NTTP->getType());
665 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
666 NonTypeTemplateParmDecl *Param;
667 if (NTTP->isExpandedParameterPack()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000668 SmallVector<QualType, 2> ExpandedTypes;
669 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000670 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
671 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
672 ExpandedTInfos.push_back(
673 getTrivialTypeSourceInfo(ExpandedTypes.back()));
674 }
675
676 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000677 SourceLocation(),
678 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000679 NTTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000680 NTTP->getPosition(), nullptr,
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000681 T,
682 TInfo,
David Majnemerdfecf1a2016-07-06 04:19:16 +0000683 ExpandedTypes,
684 ExpandedTInfos);
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000685 } else {
686 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000687 SourceLocation(),
688 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000689 NTTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000690 NTTP->getPosition(), nullptr,
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000691 T,
692 NTTP->isParameterPack(),
693 TInfo);
694 }
695 CanonParams.push_back(Param);
696
697 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000698 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
699 cast<TemplateTemplateParmDecl>(*P)));
700 }
701
Hubert Tonge4a0c0e2016-07-30 22:33:34 +0000702 assert(!TTP->getRequiresClause() &&
703 "Unexpected requires-clause on template template-parameter");
George Burgess IVb7e4e482016-08-25 01:54:37 +0000704 Expr *const CanonRequiresClause = nullptr;
Hubert Tonge4a0c0e2016-07-30 22:33:34 +0000705
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000706 TemplateTemplateParmDecl *CanonTTP
707 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
708 SourceLocation(), TTP->getDepth(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000709 TTP->getPosition(),
710 TTP->isParameterPack(),
Craig Topper36250ad2014-05-12 05:36:57 +0000711 nullptr,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000712 TemplateParameterList::Create(*this, SourceLocation(),
713 SourceLocation(),
David Majnemer902f8c62015-12-27 07:16:27 +0000714 CanonParams,
Hubert Tonge4a0c0e2016-07-30 22:33:34 +0000715 SourceLocation(),
716 CanonRequiresClause));
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000717
718 // Get the new insert position for the node we care about.
719 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +0000720 assert(!Canonical && "Shouldn't be in the map!");
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000721 (void)Canonical;
722
723 // Create the canonical template template parameter entry.
724 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
725 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
726 return CanonTTP;
727}
728
Charles Davis53c59df2010-08-16 03:33:14 +0000729CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
Craig Topper36250ad2014-05-12 05:36:57 +0000730 if (!LangOpts.CPlusPlus) return nullptr;
John McCall86353412010-08-21 22:46:04 +0000731
John McCall359b8852013-01-25 22:30:49 +0000732 switch (T.getCXXABI().getKind()) {
Joerg Sonnenbergerdaa13aa2014-05-13 11:20:16 +0000733 case TargetCXXABI::GenericARM: // Same as Itanium at this level
John McCall359b8852013-01-25 22:30:49 +0000734 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +0000735 case TargetCXXABI::iOS64:
Tim Northover756447a2015-10-30 16:30:36 +0000736 case TargetCXXABI::WatchOS:
Joerg Sonnenbergerdaa13aa2014-05-13 11:20:16 +0000737 case TargetCXXABI::GenericAArch64:
Zoran Jovanovic26a12162015-02-18 15:21:35 +0000738 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +0000739 case TargetCXXABI::GenericItanium:
Dan Gohmanc2853072015-09-03 22:51:53 +0000740 case TargetCXXABI::WebAssembly:
Charles Davis53c59df2010-08-16 03:33:14 +0000741 return CreateItaniumCXXABI(*this);
John McCall359b8852013-01-25 22:30:49 +0000742 case TargetCXXABI::Microsoft:
Charles Davis6bcb07a2010-08-19 02:18:14 +0000743 return CreateMicrosoftCXXABI(*this);
744 }
David Blaikie8a40f702012-01-17 06:56:22 +0000745 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000746}
747
Alexander Richardson6d989432017-10-15 18:48:14 +0000748static const LangASMap *getAddressSpaceMap(const TargetInfo &T,
749 const LangOptions &LOpts) {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000750 if (LOpts.FakeAddressSpaceMap) {
751 // The fake address space map must have a distinct entry for each
752 // language-specific address space.
753 static const unsigned FakeAddrSpaceMap[] = {
Yaxun Liub34ec822017-04-11 17:24:23 +0000754 0, // Default
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000755 1, // opencl_global
Egor Churaev28f00aa2016-12-23 16:11:25 +0000756 3, // opencl_local
757 2, // opencl_constant
Yaxun Liub7318e02017-10-13 03:37:48 +0000758 0, // opencl_private
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +0000759 4, // opencl_generic
760 5, // cuda_device
761 6, // cuda_constant
762 7 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000763 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000764 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000765 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000766 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000767 }
768}
769
David Tweed31d09b02013-09-13 12:04:22 +0000770static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
771 const LangOptions &LangOpts) {
772 switch (LangOpts.getAddressSpaceMapMangling()) {
David Tweed31d09b02013-09-13 12:04:22 +0000773 case LangOptions::ASMM_Target:
774 return TI.useAddressSpaceMapMangling();
775 case LangOptions::ASMM_On:
776 return true;
777 case LangOptions::ASMM_Off:
778 return false;
779 }
NAKAMURA Takumi5c81ca42013-09-13 17:12:09 +0000780 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
David Tweed31d09b02013-09-13 12:04:22 +0000781}
782
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000783ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000784 IdentifierTable &idents, SelectorTable &sels,
Alp Toker08043432014-05-03 03:46:04 +0000785 Builtin::Context &builtins)
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000786 : FunctionProtoTypes(this_()), TemplateSpecializationTypes(this_()),
787 DependentTemplateSpecializationTypes(this_()),
Eugene Zelenko5e5e5642017-11-23 01:20:07 +0000788 SubstTemplateTemplateParmPacks(this_()), SourceMgr(SM), LangOpts(LOpts),
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000789 SanitizerBL(new SanitizerBlacklist(LangOpts.SanitizerBlacklistFiles, SM)),
Dean Michael Berris835832d2017-03-30 00:29:36 +0000790 XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles,
Dean Michael Berris20dc6ef2018-04-09 04:02:09 +0000791 LangOpts.XRayNeverInstrumentFiles,
792 LangOpts.XRayAttrListFiles, SM)),
Artem Belevichb5bc9232015-09-22 17:23:22 +0000793 PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
Eugene Zelenko5e5e5642017-11-23 01:20:07 +0000794 BuiltinInfo(builtins), DeclarationNames(*this), Comments(SM),
Eric Fiselier0683c0e2018-05-07 21:07:10 +0000795 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
796 CompCategories(this_()), LastSDM(nullptr, 0) {
Daniel Dunbar221fa942008-08-11 04:54:23 +0000797 TUDecl = TranslationUnitDecl::Create(*this);
798}
799
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000800ASTContext::~ASTContext() {
Manuel Klimek95403e62014-05-21 13:28:59 +0000801 ReleaseParentMapEntries();
802
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 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000826
827 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
Manuel Klimek95403e62014-05-21 13:28:59 +0000840void ASTContext::ReleaseParentMapEntries() {
Benjamin Kramer94355ae2015-10-23 09:04:55 +0000841 if (!PointerParents) return;
842 for (const auto &Entry : *PointerParents) {
843 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
844 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
845 } else if (Entry.second.is<ParentVector *>()) {
846 delete Entry.second.get<ParentVector *>();
847 }
848 }
849 for (const auto &Entry : *OtherParents) {
Manuel Klimek95403e62014-05-21 13:28:59 +0000850 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
851 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
Benjamin Kramer8e4a1762015-10-22 11:21:40 +0000852 } else if (Entry.second.is<ParentVector *>()) {
Manuel Klimek95403e62014-05-21 13:28:59 +0000853 delete Entry.second.get<ParentVector *>();
854 }
855 }
856}
857
Douglas Gregor1a809332010-05-23 18:26:36 +0000858void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
Chandler Carruthff5a01a2015-12-30 03:00:23 +0000859 Deallocations.push_back({Callback, Data});
Douglas Gregor1a809332010-05-23 18:26:36 +0000860}
861
Mike Stump11289f42009-09-09 15:08:12 +0000862void
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000863ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
Benjamin Kramerd6da1a02016-06-12 20:05:23 +0000864 ExternalSource = std::move(Source);
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000865}
866
Chris Lattner4eb445d2007-01-26 01:27:23 +0000867void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000868 llvm::errs() << "\n*** AST Context Stats:\n";
869 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000870
Douglas Gregora30d0462009-05-26 14:40:08 +0000871 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000872#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000873#define ABSTRACT_TYPE(Name, Parent)
874#include "clang/AST/TypeNodes.def"
875 0 // Extra
876 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000877
Chris Lattner4eb445d2007-01-26 01:27:23 +0000878 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
879 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000880 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000881 }
882
Douglas Gregora30d0462009-05-26 14:40:08 +0000883 unsigned Idx = 0;
884 unsigned TotalBytes = 0;
885#define TYPE(Name, Parent) \
886 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000887 llvm::errs() << " " << counts[Idx] << " " << #Name \
888 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000889 TotalBytes += counts[Idx] * sizeof(Name##Type); \
890 ++Idx;
891#define ABSTRACT_TYPE(Name, Parent)
892#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000893
Chandler Carruth3c147a72011-07-04 05:32:14 +0000894 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
895
Douglas Gregor7454c562010-07-02 20:37:36 +0000896 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000897 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
898 << NumImplicitDefaultConstructors
899 << " implicit default constructors created\n";
900 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
901 << NumImplicitCopyConstructors
902 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000903 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000904 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
905 << NumImplicitMoveConstructors
906 << " implicit move constructors created\n";
907 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
908 << NumImplicitCopyAssignmentOperators
909 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000910 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000911 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
912 << NumImplicitMoveAssignmentOperators
913 << " implicit move assignment operators created\n";
914 llvm::errs() << NumImplicitDestructorsDeclared << "/"
915 << NumImplicitDestructors
916 << " implicit destructors created\n";
917
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000918 if (ExternalSource) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000919 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000920 ExternalSource->PrintStats();
921 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000922
Douglas Gregor5b11d492010-07-25 17:53:33 +0000923 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000924}
925
Richard Smith42413142015-05-15 20:05:43 +0000926void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
927 bool NotifyListeners) {
928 if (NotifyListeners)
929 if (auto *Listener = getASTMutationListener())
930 Listener->RedefinedHiddenDefinition(ND, M);
931
Benjamin Kramera72a70a2016-10-17 13:00:44 +0000932 if (getLangOpts().ModulesLocalVisibility)
933 MergedDefModules[ND].push_back(M);
934 else
Richard Smith90dc5252017-06-23 01:04:34 +0000935 ND->setVisibleDespiteOwningModule();
Richard Smith42413142015-05-15 20:05:43 +0000936}
937
938void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) {
939 auto It = MergedDefModules.find(ND);
940 if (It == MergedDefModules.end())
941 return;
942
Benjamin Kramera72a70a2016-10-17 13:00:44 +0000943 auto &Merged = It->second;
Richard Smith42413142015-05-15 20:05:43 +0000944 llvm::DenseSet<Module*> Found;
945 for (Module *&M : Merged)
946 if (!Found.insert(M).second)
947 M = nullptr;
948 Merged.erase(std::remove(Merged.begin(), Merged.end(), nullptr), Merged.end());
949}
950
Richard Smithdc1f0422016-07-20 19:10:16 +0000951void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
952 if (LazyInitializers.empty())
953 return;
954
955 auto *Source = Ctx.getExternalSource();
956 assert(Source && "lazy initializers but no external source");
957
958 auto LazyInits = std::move(LazyInitializers);
959 LazyInitializers.clear();
960
961 for (auto ID : LazyInits)
962 Initializers.push_back(Source->GetExternalDecl(ID));
963
964 assert(LazyInitializers.empty() &&
965 "GetExternalDecl for lazy module initializer added more inits");
966}
967
968void ASTContext::addModuleInitializer(Module *M, Decl *D) {
969 // One special case: if we add a module initializer that imports another
970 // module, and that module's only initializer is an ImportDecl, simplify.
Eugene Zelenko7855e772018-04-03 00:11:50 +0000971 if (const auto *ID = dyn_cast<ImportDecl>(D)) {
Richard Smithdc1f0422016-07-20 19:10:16 +0000972 auto It = ModuleInitializers.find(ID->getImportedModule());
973
974 // Maybe the ImportDecl does nothing at all. (Common case.)
975 if (It == ModuleInitializers.end())
976 return;
977
978 // Maybe the ImportDecl only imports another ImportDecl.
979 auto &Imported = *It->second;
980 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
981 Imported.resolve(*this);
982 auto *OnlyDecl = Imported.Initializers.front();
983 if (isa<ImportDecl>(OnlyDecl))
984 D = OnlyDecl;
985 }
986 }
987
988 auto *&Inits = ModuleInitializers[M];
989 if (!Inits)
990 Inits = new (*this) PerModuleInitializers;
991 Inits->Initializers.push_back(D);
992}
993
994void ASTContext::addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs) {
995 auto *&Inits = ModuleInitializers[M];
996 if (!Inits)
997 Inits = new (*this) PerModuleInitializers;
998 Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
999 IDs.begin(), IDs.end());
1000}
1001
Eugene Zelenko7855e772018-04-03 00:11:50 +00001002ArrayRef<Decl *> ASTContext::getModuleInitializers(Module *M) {
Richard Smithdc1f0422016-07-20 19:10:16 +00001003 auto It = ModuleInitializers.find(M);
1004 if (It == ModuleInitializers.end())
1005 return None;
1006
1007 auto *Inits = It->second;
1008 Inits->resolve(*this);
1009 return Inits->Initializers;
1010}
1011
Richard Smithf19e1272015-03-07 00:04:49 +00001012ExternCContextDecl *ASTContext::getExternCContextDecl() const {
1013 if (!ExternCContext)
1014 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
1015
1016 return ExternCContext;
1017}
1018
David Majnemerd9b1a4f2015-11-04 03:40:30 +00001019BuiltinTemplateDecl *
1020ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
1021 const IdentifierInfo *II) const {
1022 auto *BuiltinTemplate = BuiltinTemplateDecl::Create(*this, TUDecl, II, BTK);
1023 BuiltinTemplate->setImplicit();
1024 TUDecl->addDecl(BuiltinTemplate);
1025
1026 return BuiltinTemplate;
1027}
1028
1029BuiltinTemplateDecl *
1030ASTContext::getMakeIntegerSeqDecl() const {
1031 if (!MakeIntegerSeqDecl)
1032 MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq,
1033 getMakeIntegerSeqName());
1034 return MakeIntegerSeqDecl;
1035}
1036
Eric Fiselier6ad68552016-07-01 01:24:09 +00001037BuiltinTemplateDecl *
1038ASTContext::getTypePackElementDecl() const {
1039 if (!TypePackElementDecl)
1040 TypePackElementDecl = buildBuiltinTemplateDecl(BTK__type_pack_element,
1041 getTypePackElementName());
1042 return TypePackElementDecl;
1043}
1044
Alp Toker2dea15b2013-12-17 01:22:38 +00001045RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
1046 RecordDecl::TagKind TK) const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001047 SourceLocation Loc;
1048 RecordDecl *NewDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00001049 if (getLangOpts().CPlusPlus)
1050 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
1051 Loc, &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +00001052 else
Alp Toker2dea15b2013-12-17 01:22:38 +00001053 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
1054 &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +00001055 NewDecl->setImplicit();
David Majnemerf8637362015-01-15 08:41:25 +00001056 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
1057 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
Alp Toker56b5cc92013-12-15 10:36:26 +00001058 return NewDecl;
1059}
1060
1061TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
1062 StringRef Name) const {
1063 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
1064 TypedefDecl *NewDecl = TypedefDecl::Create(
1065 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
1066 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
1067 NewDecl->setImplicit();
1068 return NewDecl;
1069}
1070
Douglas Gregor801c99d2011-08-12 06:49:56 +00001071TypedefDecl *ASTContext::getInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001072 if (!Int128Decl)
1073 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +00001074 return Int128Decl;
1075}
1076
1077TypedefDecl *ASTContext::getUInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001078 if (!UInt128Decl)
1079 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +00001080 return UInt128Decl;
1081}
Chris Lattner4eb445d2007-01-26 01:27:23 +00001082
John McCall48f2d582009-10-23 23:03:21 +00001083void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001084 auto *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +00001085 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +00001086 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001087}
1088
Artem Belevichb5bc9232015-09-22 17:23:22 +00001089void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
1090 const TargetInfo *AuxTarget) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001091 assert((!this->Target || this->Target == &Target) &&
1092 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +00001093 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +00001094
Douglas Gregore8bbc122011-09-02 00:18:52 +00001095 this->Target = &Target;
Artem Belevichb5bc9232015-09-22 17:23:22 +00001096 this->AuxTarget = AuxTarget;
1097
Douglas Gregore8bbc122011-09-02 00:18:52 +00001098 ABI.reset(createCXXABI(Target));
1099 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
David Tweed31d09b02013-09-13 12:04:22 +00001100 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
Douglas Gregore8bbc122011-09-02 00:18:52 +00001101
Chris Lattner970e54e2006-11-12 00:37:36 +00001102 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +00001103 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +00001104
Chris Lattner970e54e2006-11-12 00:37:36 +00001105 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +00001106 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +00001107 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +00001108 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +00001109 InitBuiltinType(CharTy, BuiltinType::Char_S);
1110 else
1111 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +00001112 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +00001113 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
1114 InitBuiltinType(ShortTy, BuiltinType::Short);
1115 InitBuiltinType(IntTy, BuiltinType::Int);
1116 InitBuiltinType(LongTy, BuiltinType::Long);
1117 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +00001118
Chris Lattner970e54e2006-11-12 00:37:36 +00001119 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +00001120 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
1121 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
1122 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
1123 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
1124 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +00001125
Chris Lattner970e54e2006-11-12 00:37:36 +00001126 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +00001127 InitBuiltinType(FloatTy, BuiltinType::Float);
1128 InitBuiltinType(DoubleTy, BuiltinType::Double);
1129 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001130
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001131 // GNU extension, __float128 for IEEE quadruple precision
1132 InitBuiltinType(Float128Ty, BuiltinType::Float128);
1133
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00001134 // C11 extension ISO/IEC TS 18661-3
1135 InitBuiltinType(Float16Ty, BuiltinType::Float16);
1136
Leonard Chanf921d852018-06-04 16:07:52 +00001137 // ISO/IEC JTC1 SC22 WG14 N1169 Extension
1138 InitBuiltinType(ShortAccumTy, BuiltinType::ShortAccum);
1139 InitBuiltinType(AccumTy, BuiltinType::Accum);
1140 InitBuiltinType(LongAccumTy, BuiltinType::LongAccum);
1141 InitBuiltinType(UnsignedShortAccumTy, BuiltinType::UShortAccum);
1142 InitBuiltinType(UnsignedAccumTy, BuiltinType::UAccum);
1143 InitBuiltinType(UnsignedLongAccumTy, BuiltinType::ULongAccum);
1144
Chris Lattnerf122cef2009-04-30 02:43:43 +00001145 // GNU extension, 128-bit integers.
1146 InitBuiltinType(Int128Ty, BuiltinType::Int128);
1147 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
1148
Hans Wennborg0d81e012013-05-10 10:08:40 +00001149 // C++ 3.9.1p5
1150 if (TargetInfo::isTypeSigned(Target.getWCharType()))
1151 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1152 else // -fshort-wchar makes wchar_t be unsigned.
1153 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1154 if (LangOpts.CPlusPlus && LangOpts.WChar)
1155 WideCharTy = WCharTy;
1156 else {
1157 // C99 (or C++ using -fno-wchar).
1158 WideCharTy = getFromTargetType(Target.getWCharType());
1159 }
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001160
James Molloy36365542012-05-04 10:55:22 +00001161 WIntTy = getFromTargetType(Target.getWIntType());
1162
Richard Smith3a8244d2018-05-01 05:02:45 +00001163 // C++20 (proposed)
1164 InitBuiltinType(Char8Ty, BuiltinType::Char8);
1165
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001166 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1167 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1168 else // C99
1169 Char16Ty = getFromTargetType(Target.getChar16Type());
1170
1171 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1172 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1173 else // C99
1174 Char32Ty = getFromTargetType(Target.getChar32Type());
1175
Douglas Gregor4619e432008-12-05 23:32:09 +00001176 // Placeholder type for type-dependent expressions whose type is
1177 // completely unknown. No code should ever check a type against
1178 // DependentTy and users should never see it; however, it is here to
1179 // help diagnose failures to properly check for type-dependent
1180 // expressions.
1181 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001182
John McCall36e7fe32010-10-12 00:20:44 +00001183 // Placeholder type for functions.
1184 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1185
John McCall0009fcc2011-04-26 20:42:42 +00001186 // Placeholder type for bound members.
1187 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1188
John McCall526ab472011-10-25 17:37:35 +00001189 // Placeholder type for pseudo-objects.
1190 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1191
John McCall31996342011-04-07 08:22:57 +00001192 // "any" type; useful for debugger-like clients.
1193 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1194
John McCall8a6b59a2011-10-17 18:09:15 +00001195 // Placeholder type for unbridged ARC casts.
1196 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1197
Eli Friedman34866c72012-08-31 00:14:07 +00001198 // Placeholder type for builtin functions.
1199 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1200
Alexey Bataev1a3320e2015-08-25 14:24:04 +00001201 // Placeholder type for OMP array sections.
1202 if (LangOpts.OpenMP)
1203 InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection);
1204
Chris Lattner970e54e2006-11-12 00:37:36 +00001205 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +00001206 FloatComplexTy = getComplexType(FloatTy);
1207 DoubleComplexTy = getComplexType(DoubleTy);
1208 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001209 Float128ComplexTy = getComplexType(Float128Ty);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001210
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001211 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +00001212 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1213 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001214 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001215
Alexey Bader954ba212016-04-08 13:40:33 +00001216 if (LangOpts.OpenCL) {
1217#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1218 InitBuiltinType(SingletonId, BuiltinType::Id);
Alexey Baderb62f1442016-04-13 08:33:41 +00001219#include "clang/Basic/OpenCLImageTypes.def"
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001220
Guy Benyei61054192013-02-07 10:55:47 +00001221 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001222 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Alexey Bader9c8453f2015-09-15 11:18:52 +00001223 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1224 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
Alexey Bader9c8453f2015-09-15 11:18:52 +00001225 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001226 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00001227
1228 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +00001229 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1230 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001231
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001232 ObjCConstantStringType = QualType();
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001233
1234 ObjCSuperType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +00001235
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00001236 // void * type
Yaxun Liu39195062017-08-04 18:16:31 +00001237 if (LangOpts.OpenCLVersion >= 200) {
1238 auto Q = VoidTy.getQualifiers();
1239 Q.setAddressSpace(LangAS::opencl_generic);
1240 VoidPtrTy = getPointerType(getCanonicalType(
1241 getQualifiedType(VoidTy.getUnqualifiedType(), Q)));
1242 } else {
1243 VoidPtrTy = getPointerType(VoidTy);
1244 }
Sebastian Redl576fd422009-05-10 18:38:11 +00001245
1246 // nullptr type (C++0x 2.14.7)
1247 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001248
1249 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1250 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +00001251
1252 // Builtin type used to help define __builtin_va_list.
Richard Smith9b88a4c2015-07-27 05:40:23 +00001253 VaListTagDecl = nullptr;
Chris Lattner970e54e2006-11-12 00:37:36 +00001254}
1255
David Blaikie9c902b52011-09-25 23:23:43 +00001256DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001257 return SourceMgr.getDiagnostics();
1258}
1259
Douglas Gregor561eceb2010-08-30 16:49:28 +00001260AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1261 AttrVec *&Result = DeclAttrs[D];
1262 if (!Result) {
1263 void *Mem = Allocate(sizeof(AttrVec));
1264 Result = new (Mem) AttrVec;
1265 }
1266
1267 return *Result;
1268}
1269
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001270/// Erase the attributes corresponding to the given declaration.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00001271void ASTContext::eraseDeclAttrs(const Decl *D) {
Douglas Gregor561eceb2010-08-30 16:49:28 +00001272 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1273 if (Pos != DeclAttrs.end()) {
1274 Pos->second->~AttrVec();
1275 DeclAttrs.erase(Pos);
1276 }
1277}
1278
Larisse Voufo39a1e502013-08-06 01:03:05 +00001279// FIXME: Remove ?
Douglas Gregor86d142a2009-10-08 07:24:58 +00001280MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +00001281ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001282 assert(Var->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001283 return getTemplateOrSpecializationInfo(Var)
1284 .dyn_cast<MemberSpecializationInfo *>();
1285}
1286
1287ASTContext::TemplateOrSpecializationInfo
1288ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1289 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1290 TemplateOrInstantiation.find(Var);
1291 if (Pos == TemplateOrInstantiation.end())
Eugene Zelenko7855e772018-04-03 00:11:50 +00001292 return {};
Mike Stump11289f42009-09-09 15:08:12 +00001293
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001294 return Pos->second;
1295}
1296
Mike Stump11289f42009-09-09 15:08:12 +00001297void
Douglas Gregor86d142a2009-10-08 07:24:58 +00001298ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +00001299 TemplateSpecializationKind TSK,
1300 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001301 assert(Inst->isStaticDataMember() && "Not a static data member");
1302 assert(Tmpl->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001303 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1304 Tmpl, TSK, PointOfInstantiation));
1305}
1306
1307void
1308ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1309 TemplateOrSpecializationInfo TSI) {
1310 assert(!TemplateOrInstantiation[Inst] &&
1311 "Already noted what the variable was instantiated from");
1312 TemplateOrInstantiation[Inst] = TSI;
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001313}
1314
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001315FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1316 const FunctionDecl *FD){
1317 assert(FD && "Specialization is 0");
1318 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +00001319 = ClassScopeSpecializationPattern.find(FD);
1320 if (Pos == ClassScopeSpecializationPattern.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001321 return nullptr;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001322
1323 return Pos->second;
1324}
1325
1326void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1327 FunctionDecl *Pattern) {
1328 assert(FD && "Specialization is 0");
1329 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +00001330 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001331}
1332
John McCalle61f2ba2009-11-18 02:36:19 +00001333NamedDecl *
Richard Smithd8a9e372016-12-18 21:39:37 +00001334ASTContext::getInstantiatedFromUsingDecl(NamedDecl *UUD) {
1335 auto Pos = InstantiatedFromUsingDecl.find(UUD);
John McCallb96ec562009-12-04 22:46:56 +00001336 if (Pos == InstantiatedFromUsingDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001337 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001338
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001339 return Pos->second;
1340}
1341
1342void
Richard Smithd8a9e372016-12-18 21:39:37 +00001343ASTContext::setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern) {
John McCallb96ec562009-12-04 22:46:56 +00001344 assert((isa<UsingDecl>(Pattern) ||
1345 isa<UnresolvedUsingValueDecl>(Pattern) ||
1346 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1347 "pattern decl is not a using decl");
Richard Smithd8a9e372016-12-18 21:39:37 +00001348 assert((isa<UsingDecl>(Inst) ||
1349 isa<UnresolvedUsingValueDecl>(Inst) ||
1350 isa<UnresolvedUsingTypenameDecl>(Inst)) &&
1351 "instantiation did not produce a using decl");
John McCallb96ec562009-12-04 22:46:56 +00001352 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1353 InstantiatedFromUsingDecl[Inst] = Pattern;
1354}
1355
1356UsingShadowDecl *
1357ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1358 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1359 = InstantiatedFromUsingShadowDecl.find(Inst);
1360 if (Pos == InstantiatedFromUsingShadowDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001361 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00001362
1363 return Pos->second;
1364}
1365
1366void
1367ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1368 UsingShadowDecl *Pattern) {
1369 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1370 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001371}
1372
Anders Carlsson5da84842009-09-01 04:26:58 +00001373FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1374 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1375 = InstantiatedFromUnnamedFieldDecl.find(Field);
1376 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001377 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001378
Anders Carlsson5da84842009-09-01 04:26:58 +00001379 return Pos->second;
1380}
1381
1382void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1383 FieldDecl *Tmpl) {
1384 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1385 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1386 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1387 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +00001388
Anders Carlsson5da84842009-09-01 04:26:58 +00001389 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1390}
1391
Douglas Gregor832940b2010-03-02 23:58:15 +00001392ASTContext::overridden_cxx_method_iterator
1393ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
Benjamin Krameracfa3392017-12-17 23:52:45 +00001394 return overridden_methods(Method).begin();
Douglas Gregor832940b2010-03-02 23:58:15 +00001395}
1396
1397ASTContext::overridden_cxx_method_iterator
1398ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
Benjamin Krameracfa3392017-12-17 23:52:45 +00001399 return overridden_methods(Method).end();
Douglas Gregor832940b2010-03-02 23:58:15 +00001400}
1401
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001402unsigned
1403ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
Benjamin Krameracfa3392017-12-17 23:52:45 +00001404 auto Range = overridden_methods(Method);
1405 return Range.end() - Range.begin();
Clement Courbet8251ebf2016-06-10 11:54:43 +00001406}
1407
Clement Courbet6ecaec82016-07-05 07:49:31 +00001408ASTContext::overridden_method_range
1409ASTContext::overridden_methods(const CXXMethodDecl *Method) const {
Benjamin Krameracfa3392017-12-17 23:52:45 +00001410 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1411 OverriddenMethods.find(Method->getCanonicalDecl());
1412 if (Pos == OverriddenMethods.end())
1413 return overridden_method_range(nullptr, nullptr);
1414 return overridden_method_range(Pos->second.begin(), Pos->second.end());
Clement Courbet6ecaec82016-07-05 07:49:31 +00001415}
1416
Douglas Gregor832940b2010-03-02 23:58:15 +00001417void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1418 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001419 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001420 OverriddenMethods[Method].push_back(Overridden);
1421}
1422
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +00001423void ASTContext::getOverriddenMethods(
1424 const NamedDecl *D,
1425 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001426 assert(D);
1427
Eugene Zelenko7855e772018-04-03 00:11:50 +00001428 if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisc8e70082013-04-17 00:09:03 +00001429 Overridden.append(overridden_methods_begin(CXXMethod),
1430 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001431 return;
1432 }
1433
Eugene Zelenko7855e772018-04-03 00:11:50 +00001434 const auto *Method = dyn_cast<ObjCMethodDecl>(D);
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001435 if (!Method)
1436 return;
1437
Argyrios Kyrtzidis353f6a42012-10-09 18:19:01 +00001438 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1439 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001440 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001441}
1442
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001443void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1444 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1445 assert(!Import->isFromASTFile() && "Non-local import declaration");
1446 if (!FirstLocalImport) {
1447 FirstLocalImport = Import;
1448 LastLocalImport = Import;
1449 return;
1450 }
1451
1452 LastLocalImport->NextLocalImport = Import;
1453 LastLocalImport = Import;
1454}
1455
Chris Lattner53cfe802007-07-18 17:52:12 +00001456//===----------------------------------------------------------------------===//
1457// Type Sizing and Analysis
1458//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001459
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001460/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1461/// scalar floating point type.
1462const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001463 const auto *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001464 assert(BT && "Not a floating point type!");
1465 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001466 default: llvm_unreachable("Not a floating point type!");
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00001467 case BuiltinType::Float16:
1468 case BuiltinType::Half:
1469 return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001470 case BuiltinType::Float: return Target->getFloatFormat();
1471 case BuiltinType::Double: return Target->getDoubleFormat();
1472 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001473 case BuiltinType::Float128: return Target->getFloat128Format();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001474 }
1475}
1476
Rafael Espindola71eccb32013-08-08 19:53:46 +00001477CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001478 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001479
John McCall94268702010-10-08 18:24:19 +00001480 bool UseAlignAttrOnly = false;
1481 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1482 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001483
John McCall94268702010-10-08 18:24:19 +00001484 // __attribute__((aligned)) can increase or decrease alignment
1485 // *except* on a struct or struct member, where it only increases
1486 // alignment unless 'packed' is also specified.
1487 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001488 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001489 // ignore that possibility; Sema should diagnose it.
1490 if (isa<FieldDecl>(D)) {
1491 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1492 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1493 } else {
1494 UseAlignAttrOnly = true;
1495 }
1496 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001497 else if (isa<FieldDecl>(D))
1498 UseAlignAttrOnly =
1499 D->hasAttr<PackedAttr>() ||
1500 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001501
John McCall4e819612011-01-20 07:57:12 +00001502 // If we're using the align attribute only, just ignore everything
1503 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001504 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001505 // do nothing
Eugene Zelenko7855e772018-04-03 00:11:50 +00001506 } else if (const auto *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001507 QualType T = VD->getType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00001508 if (const auto *RT = T->getAs<ReferenceType>()) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001509 if (ForAlignof)
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001510 T = RT->getPointeeType();
1511 else
1512 T = getPointerType(RT->getPointeeType());
1513 }
Richard Smithf6d70302014-06-10 23:34:28 +00001514 QualType BaseT = getBaseElementType(T);
Akira Hatanakad62f2c82017-01-06 17:56:15 +00001515 if (T->isFunctionType())
1516 Align = getTypeInfoImpl(T.getTypePtr()).Align;
1517 else if (!BaseT->isIncompleteType()) {
John McCall33ddac02011-01-19 10:06:00 +00001518 // Adjust alignments of declarations with array type by the
1519 // large-array alignment on the target.
Rafael Espindola88572752013-08-07 18:08:19 +00001520 if (const ArrayType *arrayType = getAsArrayType(T)) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001521 unsigned MinWidth = Target->getLargeArrayMinWidth();
1522 if (!ForAlignof && MinWidth) {
Rafael Espindola88572752013-08-07 18:08:19 +00001523 if (isa<VariableArrayType>(arrayType))
1524 Align = std::max(Align, Target->getLargeArrayAlign());
1525 else if (isa<ConstantArrayType>(arrayType) &&
1526 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1527 Align = std::max(Align, Target->getLargeArrayAlign());
1528 }
John McCall33ddac02011-01-19 10:06:00 +00001529 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001530 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Roger Ferrer Ibanez3fa38a12017-03-08 14:00:44 +00001531 if (BaseT.getQualifiers().hasUnaligned())
1532 Align = Target->getCharWidth();
Eugene Zelenko7855e772018-04-03 00:11:50 +00001533 if (const auto *VD = dyn_cast<VarDecl>(D)) {
Ulrich Weigandb63f7792015-04-21 17:26:18 +00001534 if (VD->hasGlobalStorage() && !ForAlignof)
Ulrich Weigandfa806422013-05-06 16:23:57 +00001535 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1536 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001537 }
John McCall4e819612011-01-20 07:57:12 +00001538
1539 // Fields can be subject to extra alignment constraints, like if
1540 // the field is packed, the struct is packed, or the struct has a
1541 // a max-field-alignment constraint (#pragma pack). So calculate
1542 // the actual alignment of the field within the struct, and then
1543 // (as we're expected to) constrain that by the alignment of the type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00001544 if (const auto *Field = dyn_cast<FieldDecl>(VD)) {
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001545 const RecordDecl *Parent = Field->getParent();
1546 // We can only produce a sensible answer if the record is valid.
1547 if (!Parent->isInvalidDecl()) {
1548 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
John McCall4e819612011-01-20 07:57:12 +00001549
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001550 // Start with the record's overall alignment.
1551 unsigned FieldAlign = toBits(Layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001552
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001553 // Use the GCD of that and the offset within the record.
1554 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1555 if (Offset > 0) {
1556 // Alignment is always a power of 2, so the GCD will be a power of 2,
1557 // which means we get to do this crazy thing instead of Euclid's.
1558 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1559 if (LowBitOfOffset < FieldAlign)
1560 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1561 }
1562
1563 Align = std::min(Align, FieldAlign);
John McCall4e819612011-01-20 07:57:12 +00001564 }
Charles Davis3fc51072010-02-23 04:52:00 +00001565 }
Chris Lattner68061312009-01-24 21:53:27 +00001566 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001567
Ken Dyckcc56c542011-01-15 18:38:59 +00001568 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001569}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001570
John McCallf1249922012-08-21 04:10:00 +00001571// getTypeInfoDataSizeInChars - Return the size of a type, in
1572// chars. If the type is a record, its data size is returned. This is
1573// the size of the memcpy that's performed when assigning this type
1574// using a trivial copy/move assignment operator.
1575std::pair<CharUnits, CharUnits>
1576ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1577 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1578
1579 // In C++, objects can sometimes be allocated into the tail padding
1580 // of a base-class subobject. We decide whether that's possible
1581 // during class layout, so here we can just trust the layout results.
1582 if (getLangOpts().CPlusPlus) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001583 if (const auto *RT = T->getAs<RecordType>()) {
John McCallf1249922012-08-21 04:10:00 +00001584 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1585 sizeAndAlign.first = layout.getDataSize();
1586 }
1587 }
1588
1589 return sizeAndAlign;
1590}
1591
Richard Trieu04d2d942013-05-14 21:59:17 +00001592/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1593/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1594std::pair<CharUnits, CharUnits>
1595static getConstantArrayInfoInChars(const ASTContext &Context,
1596 const ConstantArrayType *CAT) {
1597 std::pair<CharUnits, CharUnits> EltInfo =
1598 Context.getTypeInfoInChars(CAT->getElementType());
1599 uint64_t Size = CAT->getSize().getZExtValue();
Richard Trieuc7509072013-05-14 23:41:50 +00001600 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1601 (uint64_t)(-1)/Size) &&
Richard Trieu04d2d942013-05-14 21:59:17 +00001602 "Overflow in array type char size evaluation");
1603 uint64_t Width = EltInfo.first.getQuantity() * Size;
1604 unsigned Align = EltInfo.second.getQuantity();
Warren Hunt5ae586a2013-11-01 23:59:41 +00001605 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1606 Context.getTargetInfo().getPointerWidth(0) == 64)
Rui Ueyama83aa9792016-01-14 21:00:27 +00001607 Width = llvm::alignTo(Width, Align);
Richard Trieu04d2d942013-05-14 21:59:17 +00001608 return std::make_pair(CharUnits::fromQuantity(Width),
1609 CharUnits::fromQuantity(Align));
1610}
1611
John McCall87fe5d52010-05-20 01:18:31 +00001612std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001613ASTContext::getTypeInfoInChars(const Type *T) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001614 if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
Richard Trieu04d2d942013-05-14 21:59:17 +00001615 return getConstantArrayInfoInChars(*this, CAT);
David Majnemer34b57492014-07-30 01:30:47 +00001616 TypeInfo Info = getTypeInfo(T);
1617 return std::make_pair(toCharUnitsFromBits(Info.Width),
1618 toCharUnitsFromBits(Info.Align));
John McCall87fe5d52010-05-20 01:18:31 +00001619}
1620
1621std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001622ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001623 return getTypeInfoInChars(T.getTypePtr());
1624}
1625
David Majnemer34b57492014-07-30 01:30:47 +00001626bool ASTContext::isAlignmentRequired(const Type *T) const {
1627 return getTypeInfo(T).AlignIsRequired;
1628}
Daniel Dunbarc6475872012-03-09 04:12:54 +00001629
David Majnemer34b57492014-07-30 01:30:47 +00001630bool ASTContext::isAlignmentRequired(QualType T) const {
1631 return isAlignmentRequired(T.getTypePtr());
1632}
1633
Richard Smithb2f0f052016-10-10 18:54:32 +00001634unsigned ASTContext::getTypeAlignIfKnown(QualType T) const {
1635 // An alignment on a typedef overrides anything else.
Eugene Zelenko7855e772018-04-03 00:11:50 +00001636 if (const auto *TT = T->getAs<TypedefType>())
Richard Smithb2f0f052016-10-10 18:54:32 +00001637 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1638 return Align;
1639
1640 // If we have an (array of) complete type, we're done.
1641 T = getBaseElementType(T);
1642 if (!T->isIncompleteType())
1643 return getTypeAlign(T);
1644
1645 // If we had an array type, its element type might be a typedef
1646 // type with an alignment attribute.
Eugene Zelenko7855e772018-04-03 00:11:50 +00001647 if (const auto *TT = T->getAs<TypedefType>())
Richard Smithb2f0f052016-10-10 18:54:32 +00001648 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1649 return Align;
1650
1651 // Otherwise, see if the declaration of the type had an attribute.
Eugene Zelenko7855e772018-04-03 00:11:50 +00001652 if (const auto *TT = T->getAs<TagType>())
Richard Smithb2f0f052016-10-10 18:54:32 +00001653 return TT->getDecl()->getMaxAlignment();
1654
1655 return 0;
1656}
1657
David Majnemer34b57492014-07-30 01:30:47 +00001658TypeInfo ASTContext::getTypeInfo(const Type *T) const {
David Majnemerf8d38642014-07-30 08:42:33 +00001659 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1660 if (I != MemoizedTypeInfo.end())
1661 return I->second;
1662
1663 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1664 TypeInfo TI = getTypeInfoImpl(T);
1665 MemoizedTypeInfo[T] = TI;
Rafael Espindolaeaa88c12014-07-30 04:40:23 +00001666 return TI;
Daniel Dunbarc6475872012-03-09 04:12:54 +00001667}
1668
1669/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1670/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001671///
1672/// FIXME: Pointers into different addr spaces could have different sizes and
1673/// alignment requirements: getPointerInfo should take an AddrSpace, this
1674/// should take a QualType, &c.
David Majnemer34b57492014-07-30 01:30:47 +00001675TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1676 uint64_t Width = 0;
1677 unsigned Align = 8;
1678 bool AlignIsRequired = false;
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001679 unsigned AS = 0;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001680 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001681#define TYPE(Class, Base)
1682#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001683#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001684#define DEPENDENT_TYPE(Class, Base) case Type::Class:
David Blaikieab277d62013-07-13 21:08:03 +00001685#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1686 case Type::Class: \
1687 assert(!T->isDependentType() && "should not see dependent types here"); \
1688 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001689#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001690 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001691
Chris Lattner355332d2007-07-13 22:27:08 +00001692 case Type::FunctionNoProto:
1693 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001694 // GCC extension: alignof(function) = 32 bits
1695 Width = 0;
1696 Align = 32;
1697 break;
1698
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001699 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001700 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001701 Width = 0;
1702 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1703 break;
1704
Steve Naroff5c131802007-08-30 01:06:46 +00001705 case Type::ConstantArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001706 const auto *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001707
David Majnemer34b57492014-07-30 01:30:47 +00001708 TypeInfo EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001709 uint64_t Size = CAT->getSize().getZExtValue();
David Majnemer34b57492014-07-30 01:30:47 +00001710 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
Daniel Dunbarc6475872012-03-09 04:12:54 +00001711 "Overflow in array type bit size evaluation");
David Majnemer34b57492014-07-30 01:30:47 +00001712 Width = EltInfo.Width * Size;
1713 Align = EltInfo.Align;
Warren Hunt5ae586a2013-11-01 23:59:41 +00001714 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1715 getTargetInfo().getPointerWidth(0) == 64)
Rui Ueyama83aa9792016-01-14 21:00:27 +00001716 Width = llvm::alignTo(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001717 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001718 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001719 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001720 case Type::Vector: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001721 const auto *VT = cast<VectorType>(T);
David Majnemer34b57492014-07-30 01:30:47 +00001722 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1723 Width = EltInfo.Width * VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001724 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001725 // If the alignment is not a power of 2, round up to the next power of 2.
1726 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001727 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001728 Align = llvm::NextPowerOf2(Align);
Rui Ueyama83aa9792016-01-14 21:00:27 +00001729 Width = llvm::alignTo(Width, Align);
Chris Lattner63d2b362009-10-22 05:17:15 +00001730 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001731 // Adjust the alignment based on the target max.
1732 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1733 if (TargetVectorAlign && TargetVectorAlign < Align)
1734 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001735 break;
1736 }
Chris Lattner647fb222007-07-18 18:26:58 +00001737
Chris Lattner7570e9c2008-03-08 08:52:55 +00001738 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001739 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001740 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001741 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001742 // GCC extension: alignof(void) = 8 bits.
1743 Width = 0;
1744 Align = 8;
1745 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001746 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001747 Width = Target->getBoolWidth();
1748 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001749 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001750 case BuiltinType::Char_S:
1751 case BuiltinType::Char_U:
1752 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001753 case BuiltinType::SChar:
Richard Smith3a8244d2018-05-01 05:02:45 +00001754 case BuiltinType::Char8:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001755 Width = Target->getCharWidth();
1756 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001757 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001758 case BuiltinType::WChar_S:
1759 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001760 Width = Target->getWCharWidth();
1761 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001762 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001763 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001764 Width = Target->getChar16Width();
1765 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001766 break;
1767 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001768 Width = Target->getChar32Width();
1769 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001770 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001771 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001772 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001773 Width = Target->getShortWidth();
1774 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001775 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001776 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001777 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001778 Width = Target->getIntWidth();
1779 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001780 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001781 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001782 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001783 Width = Target->getLongWidth();
1784 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001785 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001786 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001787 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001788 Width = Target->getLongLongWidth();
1789 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001790 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001791 case BuiltinType::Int128:
1792 case BuiltinType::UInt128:
1793 Width = 128;
1794 Align = 128; // int128_t is 128-bit aligned on all targets.
1795 break;
Leonard Chanf921d852018-06-04 16:07:52 +00001796 case BuiltinType::ShortAccum:
1797 case BuiltinType::UShortAccum:
1798 Width = Target->getShortAccumWidth();
1799 Align = Target->getShortAccumAlign();
1800 break;
1801 case BuiltinType::Accum:
1802 case BuiltinType::UAccum:
1803 Width = Target->getAccumWidth();
1804 Align = Target->getAccumAlign();
1805 break;
1806 case BuiltinType::LongAccum:
1807 case BuiltinType::ULongAccum:
1808 Width = Target->getLongAccumWidth();
1809 Align = Target->getLongAccumAlign();
1810 break;
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00001811 case BuiltinType::Float16:
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001812 case BuiltinType::Half:
1813 Width = Target->getHalfWidth();
1814 Align = Target->getHalfAlign();
1815 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001816 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001817 Width = Target->getFloatWidth();
1818 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001819 break;
1820 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001821 Width = Target->getDoubleWidth();
1822 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001823 break;
1824 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001825 Width = Target->getLongDoubleWidth();
1826 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001827 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001828 case BuiltinType::Float128:
1829 Width = Target->getFloat128Width();
1830 Align = Target->getFloat128Align();
1831 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001832 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001833 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1834 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001835 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001836 case BuiltinType::ObjCId:
1837 case BuiltinType::ObjCClass:
1838 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001839 Width = Target->getPointerWidth(0);
1840 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001841 break;
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001842 case BuiltinType::OCLSampler:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001843 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001844 case BuiltinType::OCLClkEvent:
1845 case BuiltinType::OCLQueue:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001846 case BuiltinType::OCLReserveID:
Yaxun Liu99444cb2016-08-03 20:38:06 +00001847#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1848 case BuiltinType::Id:
1849#include "clang/Basic/OpenCLImageTypes.def"
Sven van Haastregt3bb7eaf2017-12-06 10:11:28 +00001850 AS = getTargetAddressSpace(
1851 Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T)));
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001852 Width = Target->getPointerWidth(AS);
1853 Align = Target->getPointerAlign(AS);
1854 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001855 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001856 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001857 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001858 Width = Target->getPointerWidth(0);
1859 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001860 break;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00001861 case Type::BlockPointer:
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001862 AS = getTargetAddressSpace(cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001863 Width = Target->getPointerWidth(AS);
1864 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001865 break;
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001866 case Type::LValueReference:
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00001867 case Type::RValueReference:
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001868 // alignof and sizeof should never enter this code path here, so we go
1869 // the pointer route.
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001870 AS = getTargetAddressSpace(cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001871 Width = Target->getPointerWidth(AS);
1872 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001873 break;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00001874 case Type::Pointer:
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001875 AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001876 Width = Target->getPointerWidth(AS);
1877 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001878 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001879 case Type::MemberPointer: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001880 const auto *MPT = cast<MemberPointerType>(T);
Erich Keane8a6b7402017-11-30 16:37:02 +00001881 CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT);
1882 Width = MPI.Width;
1883 Align = MPI.Align;
Anders Carlsson32440a02009-05-17 02:06:04 +00001884 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001885 }
Chris Lattner647fb222007-07-18 18:26:58 +00001886 case Type::Complex: {
1887 // Complex types have the same alignment as their elements, but twice the
1888 // size.
David Majnemer34b57492014-07-30 01:30:47 +00001889 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
1890 Width = EltInfo.Width * 2;
1891 Align = EltInfo.Align;
Chris Lattner647fb222007-07-18 18:26:58 +00001892 break;
1893 }
John McCall8b07ec22010-05-15 11:32:37 +00001894 case Type::ObjCObject:
1895 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Reid Kleckner0503a872013-12-05 01:23:43 +00001896 case Type::Adjusted:
Reid Kleckner8a365022013-06-24 17:51:48 +00001897 case Type::Decayed:
Reid Kleckner0503a872013-12-05 01:23:43 +00001898 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001899 case Type::ObjCInterface: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001900 const auto *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001901 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001902 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001903 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001904 break;
1905 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001906 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001907 case Type::Enum: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001908 const auto *TT = cast<TagType>(T);
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001909
1910 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001911 Width = 8;
1912 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001913 break;
1914 }
Mike Stump11289f42009-09-09 15:08:12 +00001915
Eugene Zelenko7855e772018-04-03 00:11:50 +00001916 if (const auto *ET = dyn_cast<EnumType>(TT)) {
David Majnemer475b25e2015-01-21 10:54:38 +00001917 const EnumDecl *ED = ET->getDecl();
1918 TypeInfo Info =
1919 getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType());
1920 if (unsigned AttrAlign = ED->getMaxAlignment()) {
1921 Info.Align = AttrAlign;
1922 Info.AlignIsRequired = true;
1923 }
1924 return Info;
1925 }
Chris Lattner8b23c252008-04-06 22:05:18 +00001926
Eugene Zelenko7855e772018-04-03 00:11:50 +00001927 const auto *RT = cast<RecordType>(TT);
David Majnemer5821ff72015-02-03 08:49:29 +00001928 const RecordDecl *RD = RT->getDecl();
1929 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
Ken Dyckb0fcc592011-02-11 01:54:29 +00001930 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001931 Align = toBits(Layout.getAlignment());
David Majnemer5821ff72015-02-03 08:49:29 +00001932 AlignIsRequired = RD->hasAttr<AlignedAttr>();
Chris Lattner49a953a2007-07-23 22:46:22 +00001933 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001934 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001935
Chris Lattner63d2b362009-10-22 05:17:15 +00001936 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001937 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1938 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001939
Richard Smith600b5262017-01-26 20:40:47 +00001940 case Type::Auto:
1941 case Type::DeducedTemplateSpecialization: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001942 const auto *A = cast<DeducedType>(T);
Richard Smith27d807c2013-04-30 13:56:41 +00001943 assert(!A->getDeducedType().isNull() &&
1944 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001945 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001946 }
1947
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001948 case Type::Paren:
1949 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1950
Manman Rene6be26c2016-09-13 17:25:08 +00001951 case Type::ObjCTypeParam:
1952 return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr());
1953
Douglas Gregoref462e62009-04-30 17:32:17 +00001954 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001955 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
David Majnemer34b57492014-07-30 01:30:47 +00001956 TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001957 // If the typedef has an aligned attribute on it, it overrides any computed
1958 // alignment we have. This violates the GCC documentation (which says that
1959 // attribute(aligned) can only round up) but matches its implementation.
David Majnemer34b57492014-07-30 01:30:47 +00001960 if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
Chris Lattner29eb47b2011-02-19 22:55:41 +00001961 Align = AttrAlign;
David Majnemer34b57492014-07-30 01:30:47 +00001962 AlignIsRequired = true;
David Majnemer37bffb62014-08-04 05:11:01 +00001963 } else {
David Majnemer34b57492014-07-30 01:30:47 +00001964 Align = Info.Align;
David Majnemer37bffb62014-08-04 05:11:01 +00001965 AlignIsRequired = Info.AlignIsRequired;
1966 }
David Majnemer34b57492014-07-30 01:30:47 +00001967 Width = Info.Width;
Douglas Gregordc572a32009-03-30 22:58:21 +00001968 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001969 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001970
Abramo Bagnara6150c882010-05-11 21:36:43 +00001971 case Type::Elaborated:
1972 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001973
John McCall81904512011-01-06 01:58:22 +00001974 case Type::Attributed:
1975 return getTypeInfo(
1976 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1977
Eli Friedman0dfb8892011-10-06 23:00:33 +00001978 case Type::Atomic: {
John McCalla8ec7eb2013-03-07 21:37:17 +00001979 // Start with the base type information.
David Majnemer34b57492014-07-30 01:30:47 +00001980 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
1981 Width = Info.Width;
1982 Align = Info.Align;
John McCalla8ec7eb2013-03-07 21:37:17 +00001983
JF Bastien801fca22018-05-09 03:51:12 +00001984 if (!Width) {
1985 // An otherwise zero-sized type should still generate an
1986 // atomic operation.
1987 Width = Target->getCharWidth();
1988 assert(Align);
1989 } else if (Width <= Target->getMaxAtomicPromoteWidth()) {
1990 // If the size of the type doesn't exceed the platform's max
1991 // atomic promotion width, make the size and alignment more
1992 // favorable to atomic operations:
1993
John McCalla8ec7eb2013-03-07 21:37:17 +00001994 // Round the size up to a power of 2.
1995 if (!llvm::isPowerOf2_64(Width))
1996 Width = llvm::NextPowerOf2(Width);
1997
1998 // Set the alignment equal to the size.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001999 Align = static_cast<unsigned>(Width);
2000 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00002001 }
Xiuli Pan9c14e282016-01-09 12:53:17 +00002002 break;
2003
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002004 case Type::Pipe:
Anastasia Stulovab3398932017-06-05 11:27:03 +00002005 Width = Target->getPointerWidth(getTargetAddressSpace(LangAS::opencl_global));
2006 Align = Target->getPointerAlign(getTargetAddressSpace(LangAS::opencl_global));
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002007 break;
Douglas Gregoref462e62009-04-30 17:32:17 +00002008 }
Mike Stump11289f42009-09-09 15:08:12 +00002009
Eli Friedman4b72fdd2011-10-14 20:59:01 +00002010 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
David Majnemer34b57492014-07-30 01:30:47 +00002011 return TypeInfo(Width, Align, AlignIsRequired);
Chris Lattner983a8bb2007-07-13 22:13:22 +00002012}
2013
Alexey Bataev00396512015-07-02 03:40:19 +00002014unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
2015 unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign();
2016 // Target ppc64 with QPX: simd default alignment for pointer to double is 32.
2017 if ((getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64 ||
2018 getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64le) &&
2019 getTargetInfo().getABI() == "elfv1-qpx" &&
2020 T->isSpecificBuiltinType(BuiltinType::Double))
2021 SimdAlign = 256;
2022 return SimdAlign;
2023}
2024
Ken Dyckcc56c542011-01-15 18:38:59 +00002025/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
2026CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
2027 return CharUnits::fromQuantity(BitSize / getCharWidth());
2028}
2029
Ken Dyckb0fcc592011-02-11 01:54:29 +00002030/// toBits - Convert a size in characters to a size in characters.
2031int64_t ASTContext::toBits(CharUnits CharSize) const {
2032 return CharSize.getQuantity() * getCharWidth();
2033}
2034
Ken Dyck8c89d592009-12-22 14:23:30 +00002035/// getTypeSizeInChars - Return the size of the specified type, in characters.
2036/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00002037CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00002038 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00002039}
Jay Foad39c79802011-01-12 09:06:06 +00002040CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00002041 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00002042}
2043
Ken Dycka6046ab2010-01-26 17:25:18 +00002044/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00002045/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00002046CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00002047 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00002048}
Jay Foad39c79802011-01-12 09:06:06 +00002049CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00002050 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00002051}
2052
Chris Lattnera3402cd2009-01-27 18:08:34 +00002053/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
2054/// type for the current target in bits. This can be different than the ABI
2055/// alignment in cases where it is beneficial for performance to overalign
2056/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00002057unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
David Majnemer34b57492014-07-30 01:30:47 +00002058 TypeInfo TI = getTypeInfo(T);
2059 unsigned ABIAlign = TI.Align;
Eli Friedman7ab09572009-05-25 21:27:19 +00002060
David Majnemere1544562015-04-24 01:25:05 +00002061 T = T->getBaseElementTypeUnsafe();
2062
2063 // The preferred alignment of member pointers is that of a pointer.
2064 if (T->isMemberPointerType())
2065 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
2066
Andrey Turetskiydb6655f2016-02-10 11:58:46 +00002067 if (!Target->allowsLargerPreferedTypeAlignment())
2068 return ABIAlign;
Robert Lyttoneaf6f362013-11-12 10:09:34 +00002069
Eli Friedman7ab09572009-05-25 21:27:19 +00002070 // Double and long long should be naturally aligned if possible.
Eugene Zelenko7855e772018-04-03 00:11:50 +00002071 if (const auto *CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00002072 T = CT->getElementType().getTypePtr();
Eugene Zelenko7855e772018-04-03 00:11:50 +00002073 if (const auto *ET = T->getAs<EnumType>())
David Majnemer475b25e2015-01-21 10:54:38 +00002074 T = ET->getDecl()->getIntegerType().getTypePtr();
Eli Friedman7ab09572009-05-25 21:27:19 +00002075 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00002076 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
2077 T->isSpecificBuiltinType(BuiltinType::ULongLong))
David Majnemer8b6bd572014-02-24 23:34:17 +00002078 // Don't increase the alignment if an alignment attribute was specified on a
2079 // typedef declaration.
David Majnemer34b57492014-07-30 01:30:47 +00002080 if (!TI.AlignIsRequired)
David Majnemer8b6bd572014-02-24 23:34:17 +00002081 return std::max(ABIAlign, (unsigned)getTypeSize(T));
Eli Friedman7ab09572009-05-25 21:27:19 +00002082
Chris Lattnera3402cd2009-01-27 18:08:34 +00002083 return ABIAlign;
2084}
2085
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00002086/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2087/// for __attribute__((aligned)) on this target, to be used if no alignment
2088/// value is specified.
Eugene Zelenkod4304d22015-11-04 21:37:17 +00002089unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const {
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00002090 return getTargetInfo().getDefaultAlignForAttributeAligned();
2091}
2092
Ulrich Weigandfa806422013-05-06 16:23:57 +00002093/// getAlignOfGlobalVar - Return the alignment in bits that should be given
2094/// to a global variable of the specified type.
2095unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
2096 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
2097}
2098
2099/// getAlignOfGlobalVarInChars - Return the alignment in characters that
2100/// should be given to a global variable of the specified type.
2101CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
2102 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
2103}
2104
David Majnemer08ef2ba2015-06-23 20:34:18 +00002105CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
2106 CharUnits Offset = CharUnits::Zero();
2107 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
2108 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2109 Offset += Layout->getBaseClassOffset(Base);
2110 Layout = &getASTRecordLayout(Base);
2111 }
2112 return Offset;
2113}
2114
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002115/// DeepCollectObjCIvars -
2116/// This routine first collects all declared, but not synthesized, ivars in
2117/// super class and then collects all ivars, including those synthesized for
2118/// current class. This routine is used for implementation of current class
2119/// when all ivars, declared and synthesized are known.
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002120void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
2121 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00002122 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002123 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2124 DeepCollectObjCIvars(SuperClass, false, Ivars);
2125 if (!leafClass) {
Aaron Ballman59abbd42014-03-13 21:09:43 +00002126 for (const auto *I : OI->ivars())
2127 Ivars.push_back(I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00002128 } else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002129 auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00002130 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00002131 Iv= Iv->getNextIvar())
2132 Ivars.push_back(Iv);
2133 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00002134}
2135
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002136/// CollectInheritedProtocols - Collect all protocols in current class and
2137/// those inherited by it.
2138void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00002139 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002140 if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00002141 // We can use protocol_iterator here instead of
2142 // all_referenced_protocol_iterator since we are walking all categories.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002143 for (auto *Proto : OI->all_referenced_protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002144 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00002145 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002146
2147 // Categories of this Interface.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00002148 for (const auto *Cat : OI->visible_categories())
2149 CollectInheritedProtocols(Cat, Protocols);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002150
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002151 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2152 while (SD) {
2153 CollectInheritedProtocols(SD, Protocols);
2154 SD = SD->getSuperClass();
2155 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00002156 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00002157 for (auto *Proto : OC->protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002158 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002159 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00002160 } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002161 // Insert the protocol.
2162 if (!Protocols.insert(
2163 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2164 return;
2165
2166 for (auto *Proto : OP->protocols())
2167 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002168 }
2169}
2170
Erich Keane8a6b7402017-11-30 16:37:02 +00002171static bool unionHasUniqueObjectRepresentations(const ASTContext &Context,
2172 const RecordDecl *RD) {
2173 assert(RD->isUnion() && "Must be union type");
2174 CharUnits UnionSize = Context.getTypeSizeInChars(RD->getTypeForDecl());
2175
2176 for (const auto *Field : RD->fields()) {
2177 if (!Context.hasUniqueObjectRepresentations(Field->getType()))
2178 return false;
2179 CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType());
2180 if (FieldSize != UnionSize)
2181 return false;
2182 }
Eric Fiselier12a9f342018-02-02 20:30:39 +00002183 return !RD->field_empty();
Erich Keane8a6b7402017-11-30 16:37:02 +00002184}
2185
Benjamin Kramer802e6252017-12-24 12:46:22 +00002186static bool isStructEmpty(QualType Ty) {
Erich Keane8a6b7402017-11-30 16:37:02 +00002187 const RecordDecl *RD = Ty->castAs<RecordType>()->getDecl();
2188
2189 if (!RD->field_empty())
2190 return false;
2191
2192 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD))
2193 return ClassDecl->isEmpty();
2194
2195 return true;
2196}
2197
2198static llvm::Optional<int64_t>
2199structHasUniqueObjectRepresentations(const ASTContext &Context,
2200 const RecordDecl *RD) {
2201 assert(!RD->isUnion() && "Must be struct/class type");
2202 const auto &Layout = Context.getASTRecordLayout(RD);
2203
2204 int64_t CurOffsetInBits = 0;
2205 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) {
2206 if (ClassDecl->isDynamicClass())
2207 return llvm::None;
2208
2209 SmallVector<std::pair<QualType, int64_t>, 4> Bases;
2210 for (const auto Base : ClassDecl->bases()) {
2211 // Empty types can be inherited from, and non-empty types can potentially
2212 // have tail padding, so just make sure there isn't an error.
2213 if (!isStructEmpty(Base.getType())) {
2214 llvm::Optional<int64_t> Size = structHasUniqueObjectRepresentations(
2215 Context, Base.getType()->getAs<RecordType>()->getDecl());
2216 if (!Size)
2217 return llvm::None;
2218 Bases.emplace_back(Base.getType(), Size.getValue());
2219 }
2220 }
2221
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +00002222 llvm::sort(
Erich Keane8a6b7402017-11-30 16:37:02 +00002223 Bases.begin(), Bases.end(), [&](const std::pair<QualType, int64_t> &L,
2224 const std::pair<QualType, int64_t> &R) {
2225 return Layout.getBaseClassOffset(L.first->getAsCXXRecordDecl()) <
2226 Layout.getBaseClassOffset(R.first->getAsCXXRecordDecl());
2227 });
2228
2229 for (const auto Base : Bases) {
2230 int64_t BaseOffset = Context.toBits(
2231 Layout.getBaseClassOffset(Base.first->getAsCXXRecordDecl()));
2232 int64_t BaseSize = Base.second;
2233 if (BaseOffset != CurOffsetInBits)
2234 return llvm::None;
2235 CurOffsetInBits = BaseOffset + BaseSize;
2236 }
2237 }
2238
2239 for (const auto *Field : RD->fields()) {
2240 if (!Field->getType()->isReferenceType() &&
2241 !Context.hasUniqueObjectRepresentations(Field->getType()))
2242 return llvm::None;
2243
2244 int64_t FieldSizeInBits =
2245 Context.toBits(Context.getTypeSizeInChars(Field->getType()));
2246 if (Field->isBitField()) {
2247 int64_t BitfieldSize = Field->getBitWidthValue(Context);
2248
2249 if (BitfieldSize > FieldSizeInBits)
2250 return llvm::None;
2251 FieldSizeInBits = BitfieldSize;
2252 }
2253
2254 int64_t FieldOffsetInBits = Context.getFieldOffset(Field);
2255
2256 if (FieldOffsetInBits != CurOffsetInBits)
2257 return llvm::None;
2258
2259 CurOffsetInBits = FieldSizeInBits + FieldOffsetInBits;
2260 }
2261
2262 return CurOffsetInBits;
2263}
2264
2265bool ASTContext::hasUniqueObjectRepresentations(QualType Ty) const {
2266 // C++17 [meta.unary.prop]:
2267 // The predicate condition for a template specialization
2268 // has_unique_object_representations<T> shall be
2269 // satisfied if and only if:
2270 // (9.1) - T is trivially copyable, and
2271 // (9.2) - any two objects of type T with the same value have the same
2272 // object representation, where two objects
2273 // of array or non-union class type are considered to have the same value
2274 // if their respective sequences of
2275 // direct subobjects have the same values, and two objects of union type
2276 // are considered to have the same
2277 // value if they have the same active member and the corresponding members
2278 // have the same value.
2279 // The set of scalar types for which this condition holds is
2280 // implementation-defined. [ Note: If a type has padding
2281 // bits, the condition does not hold; otherwise, the condition holds true
2282 // for unsigned integral types. -- end note ]
2283 assert(!Ty.isNull() && "Null QualType sent to unique object rep check");
2284
2285 // Arrays are unique only if their element type is unique.
2286 if (Ty->isArrayType())
2287 return hasUniqueObjectRepresentations(getBaseElementType(Ty));
2288
2289 // (9.1) - T is trivially copyable...
2290 if (!Ty.isTriviallyCopyableType(*this))
2291 return false;
2292
2293 // All integrals and enums are unique.
2294 if (Ty->isIntegralOrEnumerationType())
2295 return true;
2296
2297 // All other pointers are unique.
2298 if (Ty->isPointerType())
2299 return true;
2300
2301 if (Ty->isMemberPointerType()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002302 const auto *MPT = Ty->getAs<MemberPointerType>();
Erich Keane8a6b7402017-11-30 16:37:02 +00002303 return !ABI->getMemberPointerInfo(MPT).HasPadding;
2304 }
2305
2306 if (Ty->isRecordType()) {
2307 const RecordDecl *Record = Ty->getAs<RecordType>()->getDecl();
2308
Erich Keanebd2197c2017-12-12 16:02:06 +00002309 if (Record->isInvalidDecl())
2310 return false;
2311
Erich Keane8a6b7402017-11-30 16:37:02 +00002312 if (Record->isUnion())
2313 return unionHasUniqueObjectRepresentations(*this, Record);
2314
2315 Optional<int64_t> StructSize =
2316 structHasUniqueObjectRepresentations(*this, Record);
2317
2318 return StructSize &&
2319 StructSize.getValue() == static_cast<int64_t>(getTypeSize(Ty));
2320 }
2321
2322 // FIXME: More cases to handle here (list by rsmith):
2323 // vectors (careful about, eg, vector of 3 foo)
2324 // _Complex int and friends
2325 // _Atomic T
2326 // Obj-C block pointers
2327 // Obj-C object pointers
2328 // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t,
2329 // clk_event_t, queue_t, reserve_id_t)
2330 // There're also Obj-C class types and the Obj-C selector type, but I think it
2331 // makes sense for those to return false here.
2332
2333 return false;
2334}
2335
Jay Foad39c79802011-01-12 09:06:06 +00002336unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00002337 unsigned count = 0;
2338 // Count ivars declared in class extension.
Aaron Ballmanb4a53452014-03-13 21:57:01 +00002339 for (const auto *Ext : OI->known_extensions())
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002340 count += Ext->ivar_size();
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002341
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00002342 // Count ivar defined in this class's implementation. This
2343 // includes synthesized ivars.
2344 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00002345 count += ImplDecl->ivar_size();
2346
Fariborz Jahanian7c809592009-06-04 01:19:09 +00002347 return count;
2348}
2349
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00002350bool ASTContext::isSentinelNullExpr(const Expr *E) {
2351 if (!E)
2352 return false;
2353
2354 // nullptr_t is always treated as null.
2355 if (E->getType()->isNullPtrType()) return true;
2356
2357 if (E->getType()->isAnyPointerType() &&
2358 E->IgnoreParenCasts()->isNullPointerConstant(*this,
2359 Expr::NPC_ValueDependentIsNull))
2360 return true;
2361
2362 // Unfortunately, __null has type 'int'.
2363 if (isa<GNUNullExpr>(E)) return true;
2364
2365 return false;
2366}
2367
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002368/// Get the implementation of ObjCInterfaceDecl, or nullptr if none
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002369/// exists.
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002370ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
2371 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2372 I = ObjCImpls.find(D);
2373 if (I != ObjCImpls.end())
2374 return cast<ObjCImplementationDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002375 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002376}
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002377
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002378/// Get the implementation of ObjCCategoryDecl, or nullptr if none
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002379/// exists.
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002380ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
2381 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2382 I = ObjCImpls.find(D);
2383 if (I != ObjCImpls.end())
2384 return cast<ObjCCategoryImplDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002385 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002386}
2387
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002388/// Set the implementation of ObjCInterfaceDecl.
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002389void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2390 ObjCImplementationDecl *ImplD) {
2391 assert(IFaceD && ImplD && "Passed null params");
2392 ObjCImpls[IFaceD] = ImplD;
2393}
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002394
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002395/// Set the implementation of ObjCCategoryDecl.
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002396void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
2397 ObjCCategoryImplDecl *ImplD) {
2398 assert(CatD && ImplD && "Passed null params");
2399 ObjCImpls[CatD] = ImplD;
2400}
2401
Chandler Carruth21c90602015-12-30 03:24:14 +00002402const ObjCMethodDecl *
2403ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const {
2404 return ObjCMethodRedecls.lookup(MD);
2405}
2406
2407void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
2408 const ObjCMethodDecl *Redecl) {
2409 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
2410 ObjCMethodRedecls[MD] = Redecl;
2411}
2412
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002413const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
2414 const NamedDecl *ND) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002415 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002416 return ID;
Eugene Zelenko7855e772018-04-03 00:11:50 +00002417 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002418 return CD->getClassInterface();
Eugene Zelenko7855e772018-04-03 00:11:50 +00002419 if (const auto *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002420 return IMD->getClassInterface();
2421
Craig Topper36250ad2014-05-12 05:36:57 +00002422 return nullptr;
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002423}
2424
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002425/// Get the copy initialization expression of VarDecl, or nullptr if
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002426/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00002427Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002428 assert(VD && "Passed null params");
2429 assert(VD->hasAttr<BlocksAttr>() &&
2430 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00002431 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002432 I = BlockVarCopyInits.find(VD);
George Burgess IV00f70bd2018-03-01 05:43:23 +00002433 return (I != BlockVarCopyInits.end()) ? I->second : nullptr;
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002434}
2435
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002436/// Set the copy inialization expression of a block var decl.
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002437void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
2438 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002439 assert(VD->hasAttr<BlocksAttr>() &&
2440 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002441 BlockVarCopyInits[VD] = Init;
2442}
2443
John McCallbcd03502009-12-07 02:54:59 +00002444TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002445 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00002446 if (!DataSize)
2447 DataSize = TypeLoc::getFullDataSizeForType(T);
2448 else
2449 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00002450 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00002451
Eugene Zelenko7855e772018-04-03 00:11:50 +00002452 auto *TInfo =
John McCallbcd03502009-12-07 02:54:59 +00002453 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
2454 new (TInfo) TypeSourceInfo(T);
2455 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00002456}
2457
John McCallbcd03502009-12-07 02:54:59 +00002458TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002459 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00002460 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00002461 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00002462 return DI;
2463}
2464
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002465const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002466ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Craig Topper36250ad2014-05-12 05:36:57 +00002467 return getObjCLayout(D, nullptr);
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002468}
2469
2470const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002471ASTContext::getASTObjCImplementationLayout(
2472 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002473 return getObjCLayout(D->getClassInterface(), D);
2474}
2475
Chris Lattner983a8bb2007-07-13 22:13:22 +00002476//===----------------------------------------------------------------------===//
2477// Type creation/memoization methods
2478//===----------------------------------------------------------------------===//
2479
Jay Foad39c79802011-01-12 09:06:06 +00002480QualType
John McCall33ddac02011-01-19 10:06:00 +00002481ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2482 unsigned fastQuals = quals.getFastQualifiers();
2483 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00002484
2485 // Check if we've already instantiated this type.
2486 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002487 ExtQuals::Profile(ID, baseType, quals);
Craig Topper36250ad2014-05-12 05:36:57 +00002488 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002489 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2490 assert(eq->getQualifiers() == quals);
2491 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002492 }
2493
John McCall33ddac02011-01-19 10:06:00 +00002494 // If the base type is not canonical, make the appropriate canonical type.
2495 QualType canon;
2496 if (!baseType->isCanonicalUnqualified()) {
2497 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00002498 canonSplit.Quals.addConsistentQualifiers(quals);
2499 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002500
2501 // Re-find the insert position.
2502 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2503 }
2504
Eugene Zelenko7855e772018-04-03 00:11:50 +00002505 auto *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
John McCall33ddac02011-01-19 10:06:00 +00002506 ExtQualNodes.InsertNode(eq, insertPos);
2507 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002508}
2509
Alexander Richardson6d989432017-10-15 18:48:14 +00002510QualType ASTContext::getAddrSpaceQualType(QualType T,
2511 LangAS AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002512 QualType CanT = getCanonicalType(T);
2513 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00002514 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00002515
John McCall8ccfcb52009-09-24 19:53:00 +00002516 // If we are composing extended qualifiers together, merge together
2517 // into one ExtQuals node.
2518 QualifierCollector Quals;
2519 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002520
John McCall8ccfcb52009-09-24 19:53:00 +00002521 // If this type already has an address space specified, it cannot get
2522 // another one.
2523 assert(!Quals.hasAddressSpace() &&
2524 "Type cannot be in multiple addr spaces!");
2525 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00002526
John McCall8ccfcb52009-09-24 19:53:00 +00002527 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00002528}
2529
Andrew Gozillon572bbb02017-10-02 06:25:51 +00002530QualType ASTContext::removeAddrSpaceQualType(QualType T) const {
2531 // If we are composing extended qualifiers together, merge together
2532 // into one ExtQuals node.
2533 QualifierCollector Quals;
2534 const Type *TypeNode = Quals.strip(T);
2535
2536 // If the qualifier doesn't have an address space just return it.
2537 if (!Quals.hasAddressSpace())
2538 return T;
2539
2540 Quals.removeAddressSpace();
2541
2542 // Removal of the address space can mean there are no longer any
2543 // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts)
2544 // or required.
2545 if (Quals.hasNonFastQualifiers())
2546 return getExtQualType(TypeNode, Quals);
2547 else
2548 return QualType(TypeNode, Quals.getFastQualifiers());
2549}
2550
Chris Lattnerd60183d2009-02-18 22:53:11 +00002551QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002552 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002553 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00002554 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002555 return T;
Mike Stump11289f42009-09-09 15:08:12 +00002556
Eugene Zelenko7855e772018-04-03 00:11:50 +00002557 if (const auto *ptr = T->getAs<PointerType>()) {
John McCall53fa7142010-12-24 02:08:15 +00002558 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00002559 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00002560 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2561 return getPointerType(ResultType);
2562 }
2563 }
Mike Stump11289f42009-09-09 15:08:12 +00002564
John McCall8ccfcb52009-09-24 19:53:00 +00002565 // If we are composing extended qualifiers together, merge together
2566 // into one ExtQuals node.
2567 QualifierCollector Quals;
2568 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002569
John McCall8ccfcb52009-09-24 19:53:00 +00002570 // If this type already has an ObjCGC specified, it cannot get
2571 // another one.
2572 assert(!Quals.hasObjCGCAttr() &&
2573 "Type cannot have multiple ObjCGCs!");
2574 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00002575
John McCall8ccfcb52009-09-24 19:53:00 +00002576 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002577}
Chris Lattner983a8bb2007-07-13 22:13:22 +00002578
John McCall4f5019e2010-12-19 02:44:49 +00002579const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2580 FunctionType::ExtInfo Info) {
2581 if (T->getExtInfo() == Info)
2582 return T;
2583
2584 QualType Result;
Eugene Zelenko7855e772018-04-03 00:11:50 +00002585 if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
Alp Toker314cc812014-01-25 16:55:45 +00002586 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
John McCall4f5019e2010-12-19 02:44:49 +00002587 } else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002588 const auto *FPT = cast<FunctionProtoType>(T);
John McCall4f5019e2010-12-19 02:44:49 +00002589 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2590 EPI.ExtInfo = Info;
Alp Toker314cc812014-01-25 16:55:45 +00002591 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
John McCall4f5019e2010-12-19 02:44:49 +00002592 }
2593
2594 return cast<FunctionType>(Result.getTypePtr());
2595}
2596
Richard Smith2a7d4812013-05-04 07:00:32 +00002597void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2598 QualType ResultType) {
Richard Smith1fa5d642013-05-11 05:45:24 +00002599 FD = FD->getMostRecentDecl();
2600 while (true) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002601 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
Richard Smith2a7d4812013-05-04 07:00:32 +00002602 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Alp Toker9cacbab2014-01-20 20:26:09 +00002603 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
Richard Smith1fa5d642013-05-11 05:45:24 +00002604 if (FunctionDecl *Next = FD->getPreviousDecl())
2605 FD = Next;
2606 else
2607 break;
Richard Smith2a7d4812013-05-04 07:00:32 +00002608 }
Richard Smith1fa5d642013-05-11 05:45:24 +00002609 if (ASTMutationListener *L = getASTMutationListener())
2610 L->DeducedReturnType(FD, ResultType);
Richard Smith2a7d4812013-05-04 07:00:32 +00002611}
2612
Richard Smith0b3a4622014-11-13 20:01:57 +00002613/// Get a function type and produce the equivalent function type with the
2614/// specified exception specification. Type sugar that can be present on a
2615/// declaration of a function with an exception specification is permitted
2616/// and preserved. Other type sugar (for instance, typedefs) is not.
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002617QualType ASTContext::getFunctionTypeWithExceptionSpec(
2618 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) {
Richard Smith0b3a4622014-11-13 20:01:57 +00002619 // Might have some parens.
Eugene Zelenko7855e772018-04-03 00:11:50 +00002620 if (const auto *PT = dyn_cast<ParenType>(Orig))
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002621 return getParenType(
2622 getFunctionTypeWithExceptionSpec(PT->getInnerType(), ESI));
Richard Smith0b3a4622014-11-13 20:01:57 +00002623
2624 // Might have a calling-convention attribute.
Eugene Zelenko7855e772018-04-03 00:11:50 +00002625 if (const auto *AT = dyn_cast<AttributedType>(Orig))
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002626 return getAttributedType(
Richard Smith0b3a4622014-11-13 20:01:57 +00002627 AT->getAttrKind(),
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002628 getFunctionTypeWithExceptionSpec(AT->getModifiedType(), ESI),
2629 getFunctionTypeWithExceptionSpec(AT->getEquivalentType(), ESI));
Richard Smith0b3a4622014-11-13 20:01:57 +00002630
2631 // Anything else must be a function type. Rebuild it with the new exception
2632 // specification.
Eugene Zelenko7855e772018-04-03 00:11:50 +00002633 const auto *Proto = cast<FunctionProtoType>(Orig);
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002634 return getFunctionType(
Richard Smith0b3a4622014-11-13 20:01:57 +00002635 Proto->getReturnType(), Proto->getParamTypes(),
2636 Proto->getExtProtoInfo().withExceptionSpec(ESI));
2637}
2638
Richard Smithdfe85e22016-12-15 02:35:39 +00002639bool ASTContext::hasSameFunctionTypeIgnoringExceptionSpec(QualType T,
2640 QualType U) {
2641 return hasSameType(T, U) ||
Aaron Ballmanc351fba2017-12-04 20:27:34 +00002642 (getLangOpts().CPlusPlus17 &&
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002643 hasSameType(getFunctionTypeWithExceptionSpec(T, EST_None),
2644 getFunctionTypeWithExceptionSpec(U, EST_None)));
Richard Smithdfe85e22016-12-15 02:35:39 +00002645}
2646
Richard Smith0b3a4622014-11-13 20:01:57 +00002647void ASTContext::adjustExceptionSpec(
2648 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
2649 bool AsWritten) {
2650 // Update the type.
2651 QualType Updated =
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002652 getFunctionTypeWithExceptionSpec(FD->getType(), ESI);
Richard Smith0b3a4622014-11-13 20:01:57 +00002653 FD->setType(Updated);
2654
2655 if (!AsWritten)
2656 return;
2657
2658 // Update the type in the type source information too.
2659 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
2660 // If the type and the type-as-written differ, we may need to update
2661 // the type-as-written too.
2662 if (TSInfo->getType() != FD->getType())
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002663 Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI);
Richard Smith0b3a4622014-11-13 20:01:57 +00002664
2665 // FIXME: When we get proper type location information for exceptions,
2666 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
2667 // up the TypeSourceInfo;
2668 assert(TypeLoc::getFullDataSizeForType(Updated) ==
2669 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
2670 "TypeLoc size mismatch from updating exception specification");
2671 TSInfo->overrideType(Updated);
2672 }
2673}
2674
Chris Lattnerc6395932007-06-22 20:56:16 +00002675/// getComplexType - Return the uniqued reference to the type for a complex
2676/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00002677QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00002678 // Unique pointers, to guarantee there is only one pointer of a particular
2679 // structure.
2680 llvm::FoldingSetNodeID ID;
2681 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002682
Craig Topper36250ad2014-05-12 05:36:57 +00002683 void *InsertPos = nullptr;
Chris Lattnerc6395932007-06-22 20:56:16 +00002684 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2685 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002686
Chris Lattnerc6395932007-06-22 20:56:16 +00002687 // If the pointee type isn't canonical, this won't be a canonical type either,
2688 // so fill in the canonical type field.
2689 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002690 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002691 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002692
Chris Lattnerc6395932007-06-22 20:56:16 +00002693 // Get the new insert position for the node we care about.
2694 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002695 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00002696 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00002697 auto *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00002698 Types.push_back(New);
2699 ComplexTypes.InsertNode(New, InsertPos);
2700 return QualType(New, 0);
2701}
2702
Chris Lattner970e54e2006-11-12 00:37:36 +00002703/// getPointerType - Return the uniqued reference to the type for a pointer to
2704/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002705QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00002706 // Unique pointers, to guarantee there is only one pointer of a particular
2707 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002708 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00002709 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002710
Craig Topper36250ad2014-05-12 05:36:57 +00002711 void *InsertPos = nullptr;
Chris Lattner67521df2007-01-27 01:29:36 +00002712 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002713 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002714
Chris Lattner7ccecb92006-11-12 08:50:50 +00002715 // If the pointee type isn't canonical, this won't be a canonical type either,
2716 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002717 QualType Canonical;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002718 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002719 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002720
Bob Wilsonc8541f22013-03-15 17:12:43 +00002721 // Get the new insert position for the node we care about.
2722 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002723 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002724 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00002725 auto *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00002726 Types.push_back(New);
2727 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002728 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00002729}
2730
Reid Kleckner0503a872013-12-05 01:23:43 +00002731QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
2732 llvm::FoldingSetNodeID ID;
2733 AdjustedType::Profile(ID, Orig, New);
Craig Topper36250ad2014-05-12 05:36:57 +00002734 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002735 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2736 if (AT)
2737 return QualType(AT, 0);
2738
2739 QualType Canonical = getCanonicalType(New);
2740
2741 // Get the new insert position for the node we care about.
2742 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002743 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner0503a872013-12-05 01:23:43 +00002744
2745 AT = new (*this, TypeAlignment)
2746 AdjustedType(Type::Adjusted, Orig, New, Canonical);
2747 Types.push_back(AT);
2748 AdjustedTypes.InsertNode(AT, InsertPos);
2749 return QualType(AT, 0);
2750}
2751
Reid Kleckner8a365022013-06-24 17:51:48 +00002752QualType ASTContext::getDecayedType(QualType T) const {
2753 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2754
Reid Kleckner8a365022013-06-24 17:51:48 +00002755 QualType Decayed;
2756
2757 // C99 6.7.5.3p7:
2758 // A declaration of a parameter as "array of type" shall be
2759 // adjusted to "qualified pointer to type", where the type
2760 // qualifiers (if any) are those specified within the [ and ] of
2761 // the array type derivation.
2762 if (T->isArrayType())
2763 Decayed = getArrayDecayedType(T);
2764
2765 // C99 6.7.5.3p8:
2766 // A declaration of a parameter as "function returning type"
2767 // shall be adjusted to "pointer to function returning type", as
2768 // in 6.3.2.1.
2769 if (T->isFunctionType())
2770 Decayed = getPointerType(T);
2771
Reid Kleckner0503a872013-12-05 01:23:43 +00002772 llvm::FoldingSetNodeID ID;
2773 AdjustedType::Profile(ID, T, Decayed);
Craig Topper36250ad2014-05-12 05:36:57 +00002774 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002775 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2776 if (AT)
2777 return QualType(AT, 0);
2778
Reid Kleckner8a365022013-06-24 17:51:48 +00002779 QualType Canonical = getCanonicalType(Decayed);
2780
2781 // Get the new insert position for the node we care about.
Reid Kleckner0503a872013-12-05 01:23:43 +00002782 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002783 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner8a365022013-06-24 17:51:48 +00002784
Reid Kleckner0503a872013-12-05 01:23:43 +00002785 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2786 Types.push_back(AT);
2787 AdjustedTypes.InsertNode(AT, InsertPos);
2788 return QualType(AT, 0);
Reid Kleckner8a365022013-06-24 17:51:48 +00002789}
2790
Mike Stump11289f42009-09-09 15:08:12 +00002791/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00002792/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00002793QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00002794 assert(T->isFunctionType() && "block of function types only");
2795 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00002796 // structure.
2797 llvm::FoldingSetNodeID ID;
2798 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002799
Craig Topper36250ad2014-05-12 05:36:57 +00002800 void *InsertPos = nullptr;
Steve Naroffec33ed92008-08-27 16:04:49 +00002801 if (BlockPointerType *PT =
2802 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2803 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002804
2805 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00002806 // type either so fill in the canonical type field.
2807 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002808 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00002809 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002810
Steve Naroffec33ed92008-08-27 16:04:49 +00002811 // Get the new insert position for the node we care about.
2812 BlockPointerType *NewIP =
2813 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002814 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00002815 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00002816 auto *New = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00002817 Types.push_back(New);
2818 BlockPointerTypes.InsertNode(New, InsertPos);
2819 return QualType(New, 0);
2820}
2821
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002822/// getLValueReferenceType - Return the uniqued reference to the type for an
2823/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002824QualType
2825ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00002826 assert(getCanonicalType(T) != OverloadTy &&
2827 "Unresolved overloaded function type");
2828
Bill Wendling3708c182007-05-27 10:15:43 +00002829 // Unique pointers, to guarantee there is only one pointer of a particular
2830 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002831 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002832 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002833
Craig Topper36250ad2014-05-12 05:36:57 +00002834 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002835 if (LValueReferenceType *RT =
2836 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00002837 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002838
Eugene Zelenko7855e772018-04-03 00:11:50 +00002839 const auto *InnerRef = T->getAs<ReferenceType>();
John McCallfc93cf92009-10-22 22:37:11 +00002840
Bill Wendling3708c182007-05-27 10:15:43 +00002841 // If the referencee type isn't canonical, this won't be a canonical type
2842 // either, so fill in the canonical type field.
2843 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002844 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2845 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2846 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002847
Bill Wendling3708c182007-05-27 10:15:43 +00002848 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002849 LValueReferenceType *NewIP =
2850 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002851 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00002852 }
2853
Eugene Zelenko7855e772018-04-03 00:11:50 +00002854 auto *New = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2855 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002856 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002857 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00002858
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002859 return QualType(New, 0);
2860}
2861
2862/// getRValueReferenceType - Return the uniqued reference to the type for an
2863/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002864QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002865 // Unique pointers, to guarantee there is only one pointer of a particular
2866 // structure.
2867 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002868 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002869
Craig Topper36250ad2014-05-12 05:36:57 +00002870 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002871 if (RValueReferenceType *RT =
2872 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2873 return QualType(RT, 0);
2874
Eugene Zelenko7855e772018-04-03 00:11:50 +00002875 const auto *InnerRef = T->getAs<ReferenceType>();
John McCallfc93cf92009-10-22 22:37:11 +00002876
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002877 // If the referencee type isn't canonical, this won't be a canonical type
2878 // either, so fill in the canonical type field.
2879 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002880 if (InnerRef || !T.isCanonical()) {
2881 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2882 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002883
2884 // Get the new insert position for the node we care about.
2885 RValueReferenceType *NewIP =
2886 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002887 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002888 }
2889
Eugene Zelenko7855e772018-04-03 00:11:50 +00002890 auto *New = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002891 Types.push_back(New);
2892 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00002893 return QualType(New, 0);
2894}
2895
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002896/// getMemberPointerType - Return the uniqued reference to the type for a
2897/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00002898QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002899 // Unique pointers, to guarantee there is only one pointer of a particular
2900 // structure.
2901 llvm::FoldingSetNodeID ID;
2902 MemberPointerType::Profile(ID, T, Cls);
2903
Craig Topper36250ad2014-05-12 05:36:57 +00002904 void *InsertPos = nullptr;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002905 if (MemberPointerType *PT =
2906 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2907 return QualType(PT, 0);
2908
2909 // If the pointee or class type isn't canonical, this won't be a canonical
2910 // type either, so fill in the canonical type field.
2911 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00002912 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002913 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2914
2915 // Get the new insert position for the node we care about.
2916 MemberPointerType *NewIP =
2917 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002918 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002919 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00002920 auto *New = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002921 Types.push_back(New);
2922 MemberPointerTypes.InsertNode(New, InsertPos);
2923 return QualType(New, 0);
2924}
2925
Mike Stump11289f42009-09-09 15:08:12 +00002926/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00002927/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00002928QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00002929 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002930 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002931 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00002932 assert((EltTy->isDependentType() ||
2933 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00002934 "Constant array of VLAs is illegal!");
2935
Chris Lattnere2df3f92009-05-13 04:12:56 +00002936 // Convert the array size into a canonical width matching the pointer size for
2937 // the target.
2938 llvm::APInt ArySize(ArySizeIn);
Konstantin Zhuravlyov9c1e3102017-03-21 18:55:39 +00002939 ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth());
Mike Stump11289f42009-09-09 15:08:12 +00002940
Chris Lattner23b7eb62007-06-15 23:05:46 +00002941 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00002942 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00002943
Craig Topper36250ad2014-05-12 05:36:57 +00002944 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002945 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002946 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002947 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002948
John McCall33ddac02011-01-19 10:06:00 +00002949 // If the element type isn't canonical or has qualifiers, this won't
2950 // be a canonical type either, so fill in the canonical type field.
2951 QualType Canon;
2952 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2953 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002954 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002955 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002956 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002957
Chris Lattner36f8e652007-01-27 08:31:04 +00002958 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00002959 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002960 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002961 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00002962 }
Mike Stump11289f42009-09-09 15:08:12 +00002963
Eugene Zelenko7855e772018-04-03 00:11:50 +00002964 auto *New = new (*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002965 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00002966 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00002967 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002968 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00002969}
2970
John McCall06549462011-01-18 08:40:38 +00002971/// getVariableArrayDecayedType - Turns the given type, which may be
2972/// variably-modified, into the corresponding type with all the known
2973/// sizes replaced with [*].
2974QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2975 // Vastly most common case.
2976 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002977
John McCall06549462011-01-18 08:40:38 +00002978 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002979
John McCall06549462011-01-18 08:40:38 +00002980 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00002981 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00002982 switch (ty->getTypeClass()) {
2983#define TYPE(Class, Base)
2984#define ABSTRACT_TYPE(Class, Base)
2985#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2986#include "clang/AST/TypeNodes.def"
2987 llvm_unreachable("didn't desugar past all non-canonical types?");
2988
2989 // These types should never be variably-modified.
2990 case Type::Builtin:
2991 case Type::Complex:
2992 case Type::Vector:
2993 case Type::ExtVector:
2994 case Type::DependentSizedExtVector:
Andrew Gozillon572bbb02017-10-02 06:25:51 +00002995 case Type::DependentAddressSpace:
John McCall06549462011-01-18 08:40:38 +00002996 case Type::ObjCObject:
2997 case Type::ObjCInterface:
2998 case Type::ObjCObjectPointer:
2999 case Type::Record:
3000 case Type::Enum:
3001 case Type::UnresolvedUsing:
3002 case Type::TypeOfExpr:
3003 case Type::TypeOf:
3004 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00003005 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00003006 case Type::DependentName:
3007 case Type::InjectedClassName:
3008 case Type::TemplateSpecialization:
3009 case Type::DependentTemplateSpecialization:
3010 case Type::TemplateTypeParm:
3011 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00003012 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00003013 case Type::DeducedTemplateSpecialization:
John McCall06549462011-01-18 08:40:38 +00003014 case Type::PackExpansion:
3015 llvm_unreachable("type should never be variably-modified");
3016
3017 // These types can be variably-modified but should never need to
3018 // further decay.
3019 case Type::FunctionNoProto:
3020 case Type::FunctionProto:
3021 case Type::BlockPointer:
3022 case Type::MemberPointer:
Xiuli Pan9c14e282016-01-09 12:53:17 +00003023 case Type::Pipe:
John McCall06549462011-01-18 08:40:38 +00003024 return type;
3025
3026 // These types can be variably-modified. All these modifications
3027 // preserve structure except as noted by comments.
3028 // TODO: if we ever care about optimizing VLAs, there are no-op
3029 // optimizations available here.
3030 case Type::Pointer:
3031 result = getPointerType(getVariableArrayDecayedType(
3032 cast<PointerType>(ty)->getPointeeType()));
3033 break;
3034
3035 case Type::LValueReference: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003036 const auto *lv = cast<LValueReferenceType>(ty);
John McCall06549462011-01-18 08:40:38 +00003037 result = getLValueReferenceType(
3038 getVariableArrayDecayedType(lv->getPointeeType()),
3039 lv->isSpelledAsLValue());
3040 break;
3041 }
3042
3043 case Type::RValueReference: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003044 const auto *lv = cast<RValueReferenceType>(ty);
John McCall06549462011-01-18 08:40:38 +00003045 result = getRValueReferenceType(
3046 getVariableArrayDecayedType(lv->getPointeeType()));
3047 break;
3048 }
3049
Eli Friedman0dfb8892011-10-06 23:00:33 +00003050 case Type::Atomic: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003051 const auto *at = cast<AtomicType>(ty);
Eli Friedman0dfb8892011-10-06 23:00:33 +00003052 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
3053 break;
3054 }
3055
John McCall06549462011-01-18 08:40:38 +00003056 case Type::ConstantArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003057 const auto *cat = cast<ConstantArrayType>(ty);
John McCall06549462011-01-18 08:40:38 +00003058 result = getConstantArrayType(
3059 getVariableArrayDecayedType(cat->getElementType()),
3060 cat->getSize(),
3061 cat->getSizeModifier(),
3062 cat->getIndexTypeCVRQualifiers());
3063 break;
3064 }
3065
3066 case Type::DependentSizedArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003067 const auto *dat = cast<DependentSizedArrayType>(ty);
John McCall06549462011-01-18 08:40:38 +00003068 result = getDependentSizedArrayType(
3069 getVariableArrayDecayedType(dat->getElementType()),
3070 dat->getSizeExpr(),
3071 dat->getSizeModifier(),
3072 dat->getIndexTypeCVRQualifiers(),
3073 dat->getBracketsRange());
3074 break;
3075 }
3076
3077 // Turn incomplete types into [*] types.
3078 case Type::IncompleteArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003079 const auto *iat = cast<IncompleteArrayType>(ty);
John McCall06549462011-01-18 08:40:38 +00003080 result = getVariableArrayType(
3081 getVariableArrayDecayedType(iat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00003082 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00003083 ArrayType::Normal,
3084 iat->getIndexTypeCVRQualifiers(),
3085 SourceRange());
3086 break;
3087 }
3088
3089 // Turn VLA types into [*] types.
3090 case Type::VariableArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003091 const auto *vat = cast<VariableArrayType>(ty);
John McCall06549462011-01-18 08:40:38 +00003092 result = getVariableArrayType(
3093 getVariableArrayDecayedType(vat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00003094 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00003095 ArrayType::Star,
3096 vat->getIndexTypeCVRQualifiers(),
3097 vat->getBracketsRange());
3098 break;
3099 }
3100 }
3101
3102 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00003103 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00003104}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003105
Steve Naroffcadebd02007-08-30 18:14:25 +00003106/// getVariableArrayType - Returns a non-unique reference to the type for a
3107/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00003108QualType ASTContext::getVariableArrayType(QualType EltTy,
3109 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00003110 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00003111 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00003112 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00003113 // Since we don't unique expressions, it isn't possible to unique VLA's
3114 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00003115 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00003116
John McCall33ddac02011-01-19 10:06:00 +00003117 // Be sure to pull qualifiers off the element type.
3118 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
3119 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00003120 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00003121 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00003122 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00003123 }
3124
Eugene Zelenko7855e772018-04-03 00:11:50 +00003125 auto *New = new (*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00003126 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00003127
3128 VariableArrayTypes.push_back(New);
3129 Types.push_back(New);
3130 return QualType(New, 0);
3131}
3132
Douglas Gregor4619e432008-12-05 23:32:09 +00003133/// getDependentSizedArrayType - Returns a non-unique reference to
3134/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00003135/// type.
John McCall33ddac02011-01-19 10:06:00 +00003136QualType ASTContext::getDependentSizedArrayType(QualType elementType,
3137 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00003138 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00003139 unsigned elementTypeQuals,
3140 SourceRange brackets) const {
3141 assert((!numElements || numElements->isTypeDependent() ||
3142 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00003143 "Size must be type- or value-dependent!");
3144
John McCall33ddac02011-01-19 10:06:00 +00003145 // Dependently-sized array types that do not have a specified number
3146 // of elements will have their sizes deduced from a dependent
3147 // initializer. We do no canonicalization here at all, which is okay
3148 // because they can't be used in most locations.
3149 if (!numElements) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003150 auto *newType
John McCall33ddac02011-01-19 10:06:00 +00003151 = new (*this, TypeAlignment)
3152 DependentSizedArrayType(*this, elementType, QualType(),
3153 numElements, ASM, elementTypeQuals,
3154 brackets);
3155 Types.push_back(newType);
3156 return QualType(newType, 0);
3157 }
3158
3159 // Otherwise, we actually build a new type every time, but we
3160 // also build a canonical type.
3161
3162 SplitQualType canonElementType = getCanonicalType(elementType).split();
3163
Craig Topper36250ad2014-05-12 05:36:57 +00003164 void *insertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00003165 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00003166 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00003167 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00003168 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00003169
John McCall33ddac02011-01-19 10:06:00 +00003170 // Look for an existing type with these properties.
3171 DependentSizedArrayType *canonTy =
3172 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00003173
John McCall33ddac02011-01-19 10:06:00 +00003174 // If we don't have one, build one.
3175 if (!canonTy) {
3176 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00003177 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00003178 QualType(), numElements, ASM, elementTypeQuals,
3179 brackets);
3180 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
3181 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00003182 }
3183
John McCall33ddac02011-01-19 10:06:00 +00003184 // Apply qualifiers from the element type to the array.
3185 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00003186 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00003187
David Majnemer16a74702015-07-24 05:54:19 +00003188 // If we didn't need extra canonicalization for the element type or the size
3189 // expression, then just use that as our result.
3190 if (QualType(canonElementType.Ty, 0) == elementType &&
3191 canonTy->getSizeExpr() == numElements)
John McCall33ddac02011-01-19 10:06:00 +00003192 return canon;
3193
3194 // Otherwise, we need to build a type which follows the spelling
3195 // of the element type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00003196 auto *sugaredType
John McCall33ddac02011-01-19 10:06:00 +00003197 = new (*this, TypeAlignment)
3198 DependentSizedArrayType(*this, elementType, canon, numElements,
3199 ASM, elementTypeQuals, brackets);
3200 Types.push_back(sugaredType);
3201 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00003202}
3203
John McCall33ddac02011-01-19 10:06:00 +00003204QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00003205 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00003206 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00003207 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00003208 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00003209
Craig Topper36250ad2014-05-12 05:36:57 +00003210 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00003211 if (IncompleteArrayType *iat =
3212 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
3213 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00003214
3215 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00003216 // either, so fill in the canonical type field. We also have to pull
3217 // qualifiers off the element type.
3218 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00003219
John McCall33ddac02011-01-19 10:06:00 +00003220 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
3221 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00003222 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00003223 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00003224 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00003225
3226 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00003227 IncompleteArrayType *existing =
3228 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
3229 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00003230 }
Eli Friedmanbd258282008-02-15 18:16:39 +00003231
Eugene Zelenko7855e772018-04-03 00:11:50 +00003232 auto *newType = new (*this, TypeAlignment)
John McCall33ddac02011-01-19 10:06:00 +00003233 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00003234
John McCall33ddac02011-01-19 10:06:00 +00003235 IncompleteArrayTypes.InsertNode(newType, insertPos);
3236 Types.push_back(newType);
3237 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00003238}
3239
Steve Naroff91fcddb2007-07-18 18:00:27 +00003240/// getVectorType - Return the unique reference to a vector type of
3241/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00003242QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00003243 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00003244 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00003245
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003246 // Check if we've already instantiated a vector of this type.
3247 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00003248 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00003249
Craig Topper36250ad2014-05-12 05:36:57 +00003250 void *InsertPos = nullptr;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003251 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3252 return QualType(VTP, 0);
3253
3254 // If the element type isn't canonical, this won't be a canonical type either,
3255 // so fill in the canonical type field.
3256 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00003257 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00003258 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00003259
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003260 // Get the new insert position for the node we care about.
3261 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003262 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003263 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00003264 auto *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00003265 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003266 VectorTypes.InsertNode(New, InsertPos);
3267 Types.push_back(New);
3268 return QualType(New, 0);
3269}
3270
Nate Begemance4d7fc2008-04-18 23:10:10 +00003271/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00003272/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00003273QualType
3274ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00003275 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00003276
Steve Naroff91fcddb2007-07-18 18:00:27 +00003277 // Check if we've already instantiated a vector of this type.
3278 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00003279 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00003280 VectorType::GenericVector);
Craig Topper36250ad2014-05-12 05:36:57 +00003281 void *InsertPos = nullptr;
Steve Naroff91fcddb2007-07-18 18:00:27 +00003282 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3283 return QualType(VTP, 0);
3284
3285 // If the element type isn't canonical, this won't be a canonical type either,
3286 // so fill in the canonical type field.
3287 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00003288 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00003289 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00003290
Steve Naroff91fcddb2007-07-18 18:00:27 +00003291 // Get the new insert position for the node we care about.
3292 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003293 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00003294 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00003295 auto *New = new (*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00003296 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00003297 VectorTypes.InsertNode(New, InsertPos);
3298 Types.push_back(New);
3299 return QualType(New, 0);
3300}
3301
Jay Foad39c79802011-01-12 09:06:06 +00003302QualType
3303ASTContext::getDependentSizedExtVectorType(QualType vecType,
3304 Expr *SizeExpr,
3305 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00003306 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00003307 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00003308 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003309
Craig Topper36250ad2014-05-12 05:36:57 +00003310 void *InsertPos = nullptr;
Douglas Gregor352169a2009-07-31 03:54:25 +00003311 DependentSizedExtVectorType *Canon
3312 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3313 DependentSizedExtVectorType *New;
3314 if (Canon) {
3315 // We already have a canonical version of this array type; use it as
3316 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00003317 New = new (*this, TypeAlignment)
3318 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
3319 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00003320 } else {
3321 QualType CanonVecTy = getCanonicalType(vecType);
3322 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00003323 New = new (*this, TypeAlignment)
3324 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
3325 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003326
3327 DependentSizedExtVectorType *CanonCheck
3328 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3329 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
3330 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00003331 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
3332 } else {
3333 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
3334 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00003335 New = new (*this, TypeAlignment)
3336 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00003337 }
3338 }
Mike Stump11289f42009-09-09 15:08:12 +00003339
Douglas Gregor758a8692009-06-17 21:51:59 +00003340 Types.push_back(New);
3341 return QualType(New, 0);
3342}
3343
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003344QualType ASTContext::getDependentAddressSpaceType(QualType PointeeType,
3345 Expr *AddrSpaceExpr,
3346 SourceLocation AttrLoc) const {
3347 assert(AddrSpaceExpr->isInstantiationDependent());
3348
3349 QualType canonPointeeType = getCanonicalType(PointeeType);
3350
3351 void *insertPos = nullptr;
3352 llvm::FoldingSetNodeID ID;
3353 DependentAddressSpaceType::Profile(ID, *this, canonPointeeType,
3354 AddrSpaceExpr);
3355
3356 DependentAddressSpaceType *canonTy =
3357 DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos);
3358
3359 if (!canonTy) {
3360 canonTy = new (*this, TypeAlignment)
3361 DependentAddressSpaceType(*this, canonPointeeType,
3362 QualType(), AddrSpaceExpr, AttrLoc);
3363 DependentAddressSpaceTypes.InsertNode(canonTy, insertPos);
3364 Types.push_back(canonTy);
3365 }
3366
3367 if (canonPointeeType == PointeeType &&
3368 canonTy->getAddrSpaceExpr() == AddrSpaceExpr)
3369 return QualType(canonTy, 0);
3370
Eugene Zelenko7855e772018-04-03 00:11:50 +00003371 auto *sugaredType
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003372 = new (*this, TypeAlignment)
3373 DependentAddressSpaceType(*this, PointeeType, QualType(canonTy, 0),
3374 AddrSpaceExpr, AttrLoc);
3375 Types.push_back(sugaredType);
3376 return QualType(sugaredType, 0);
3377}
3378
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003379/// Determine whether \p T is canonical as the result type of a function.
John McCall18afab72016-03-01 00:49:02 +00003380static bool isCanonicalResultType(QualType T) {
3381 return T.isCanonical() &&
3382 (T.getObjCLifetime() == Qualifiers::OCL_None ||
3383 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
3384}
3385
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003386/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Jay Foad39c79802011-01-12 09:06:06 +00003387QualType
3388ASTContext::getFunctionNoProtoType(QualType ResultTy,
3389 const FunctionType::ExtInfo &Info) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003390 // Unique functions, to guarantee there is only one function of a particular
3391 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00003392 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00003393 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00003394
Craig Topper36250ad2014-05-12 05:36:57 +00003395 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003396 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003397 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003398 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003399
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003400 QualType Canonical;
John McCall18afab72016-03-01 00:49:02 +00003401 if (!isCanonicalResultType(ResultTy)) {
3402 Canonical =
3403 getFunctionNoProtoType(getCanonicalFunctionResultType(ResultTy), Info);
Mike Stump11289f42009-09-09 15:08:12 +00003404
Chris Lattner47955de2007-01-27 08:37:20 +00003405 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003406 FunctionNoProtoType *NewIP =
3407 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003408 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00003409 }
Mike Stump11289f42009-09-09 15:08:12 +00003410
Eugene Zelenko7855e772018-04-03 00:11:50 +00003411 auto *New = new (*this, TypeAlignment)
John McCall18afab72016-03-01 00:49:02 +00003412 FunctionNoProtoType(ResultTy, Canonical, Info);
Chris Lattner47955de2007-01-27 08:37:20 +00003413 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003414 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003415 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003416}
3417
Douglas Gregora602a152015-10-01 20:20:47 +00003418CanQualType
3419ASTContext::getCanonicalFunctionResultType(QualType ResultType) const {
3420 CanQualType CanResultType = getCanonicalType(ResultType);
3421
3422 // Canonical result types do not have ARC lifetime qualifiers.
3423 if (CanResultType.getQualifiers().hasObjCLifetime()) {
3424 Qualifiers Qs = CanResultType.getQualifiers();
3425 Qs.removeObjCLifetime();
3426 return CanQualType::CreateUnsafe(
3427 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
3428 }
3429
3430 return CanResultType;
3431}
3432
Richard Smith3c4f8d22016-10-16 17:54:23 +00003433static bool isCanonicalExceptionSpecification(
3434 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
3435 if (ESI.Type == EST_None)
3436 return true;
3437 if (!NoexceptInType)
3438 return false;
3439
3440 // C++17 onwards: exception specification is part of the type, as a simple
3441 // boolean "can this function type throw".
3442 if (ESI.Type == EST_BasicNoexcept)
3443 return true;
3444
Richard Smitheaf11ad2018-05-03 03:58:32 +00003445 // A noexcept(expr) specification is (possibly) canonical if expr is
3446 // value-dependent.
3447 if (ESI.Type == EST_DependentNoexcept)
3448 return true;
3449
Richard Smith3c4f8d22016-10-16 17:54:23 +00003450 // A dynamic exception specification is canonical if it only contains pack
Richard Smith2a2cda52016-10-18 19:29:18 +00003451 // expansions (so we can't tell whether it's non-throwing) and all its
3452 // contained types are canonical.
Richard Smith3c4f8d22016-10-16 17:54:23 +00003453 if (ESI.Type == EST_Dynamic) {
Richard Smithfda59e52016-10-26 01:05:54 +00003454 bool AnyPackExpansions = false;
3455 for (QualType ET : ESI.Exceptions) {
3456 if (!ET.isCanonical())
Richard Smith3c4f8d22016-10-16 17:54:23 +00003457 return false;
Richard Smithfda59e52016-10-26 01:05:54 +00003458 if (ET->getAs<PackExpansionType>())
3459 AnyPackExpansions = true;
3460 }
3461 return AnyPackExpansions;
Richard Smith3c4f8d22016-10-16 17:54:23 +00003462 }
3463
Richard Smith3c4f8d22016-10-16 17:54:23 +00003464 return false;
3465}
3466
Richard Smith304b1242016-10-18 20:13:25 +00003467QualType ASTContext::getFunctionTypeInternal(
3468 QualType ResultTy, ArrayRef<QualType> ArgArray,
3469 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
Jordan Rose5c382722013-03-08 21:51:21 +00003470 size_t NumArgs = ArgArray.size();
3471
Richard Smith2a2cda52016-10-18 19:29:18 +00003472 // Unique functions, to guarantee there is only one function of a particular
3473 // structure.
3474 llvm::FoldingSetNodeID ID;
3475 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
3476 *this, true);
Richard Smith3c4f8d22016-10-16 17:54:23 +00003477
Richard Smith2a2cda52016-10-18 19:29:18 +00003478 QualType Canonical;
3479 bool Unique = false;
3480
3481 void *InsertPos = nullptr;
3482 if (FunctionProtoType *FPT =
3483 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
3484 QualType Existing = QualType(FPT, 0);
3485
3486 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
3487 // it so long as our exception specification doesn't contain a dependent
Richard Smith304b1242016-10-18 20:13:25 +00003488 // noexcept expression, or we're just looking for a canonical type.
3489 // Otherwise, we're going to need to create a type
Richard Smith2a2cda52016-10-18 19:29:18 +00003490 // sugar node to hold the concrete expression.
Richard Smitheaf11ad2018-05-03 03:58:32 +00003491 if (OnlyWantCanonical || !isComputedNoexcept(EPI.ExceptionSpec.Type) ||
Richard Smith2a2cda52016-10-18 19:29:18 +00003492 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
3493 return Existing;
3494
3495 // We need a new type sugar node for this one, to hold the new noexcept
3496 // expression. We do no canonicalization here, but that's OK since we don't
3497 // expect to see the same noexcept expression much more than once.
3498 Canonical = getCanonicalType(Existing);
3499 Unique = true;
3500 }
3501
Aaron Ballmanc351fba2017-12-04 20:27:34 +00003502 bool NoexceptInType = getLangOpts().CPlusPlus17;
Richard Smith3c4f8d22016-10-16 17:54:23 +00003503 bool IsCanonicalExceptionSpec =
3504 isCanonicalExceptionSpecification(EPI.ExceptionSpec, NoexceptInType);
3505
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003506 // Determine whether the type being created is already canonical or not.
Richard Smith2a2cda52016-10-18 19:29:18 +00003507 bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
Richard Smith3c4f8d22016-10-16 17:54:23 +00003508 isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003509 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003510 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003511 isCanonical = false;
3512
Richard Smith304b1242016-10-18 20:13:25 +00003513 if (OnlyWantCanonical)
3514 assert(isCanonical &&
3515 "given non-canonical parameters constructing canonical type");
3516
Richard Smith2a2cda52016-10-18 19:29:18 +00003517 // If this type isn't canonical, get the canonical version of it if we don't
3518 // already have it. The exception spec is only partially part of the
3519 // canonical type, and only in C++17 onwards.
3520 if (!isCanonical && Canonical.isNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003521 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003522 CanonicalArgs.reserve(NumArgs);
3523 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003524 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003525
Benjamin Kramer3f515cd2016-10-26 12:51:45 +00003526 llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
John McCalldb40c7f2010-12-14 08:05:40 +00003527 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00003528 CanonicalEPI.HasTrailingReturn = false;
Richard Smith3c4f8d22016-10-16 17:54:23 +00003529
3530 if (IsCanonicalExceptionSpec) {
3531 // Exception spec is already OK.
3532 } else if (NoexceptInType) {
3533 switch (EPI.ExceptionSpec.Type) {
3534 case EST_Unparsed: case EST_Unevaluated: case EST_Uninstantiated:
3535 // We don't know yet. It shouldn't matter what we pick here; no-one
3536 // should ever look at this.
3537 LLVM_FALLTHROUGH;
Richard Smitheaf11ad2018-05-03 03:58:32 +00003538 case EST_None: case EST_MSAny: case EST_NoexceptFalse:
Richard Smith3c4f8d22016-10-16 17:54:23 +00003539 CanonicalEPI.ExceptionSpec.Type = EST_None;
3540 break;
3541
Richard Smith2a2cda52016-10-18 19:29:18 +00003542 // A dynamic exception specification is almost always "not noexcept",
3543 // with the exception that a pack expansion might expand to no types.
3544 case EST_Dynamic: {
3545 bool AnyPacks = false;
3546 for (QualType ET : EPI.ExceptionSpec.Exceptions) {
3547 if (ET->getAs<PackExpansionType>())
3548 AnyPacks = true;
3549 ExceptionTypeStorage.push_back(getCanonicalType(ET));
3550 }
3551 if (!AnyPacks)
3552 CanonicalEPI.ExceptionSpec.Type = EST_None;
3553 else {
3554 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
3555 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
3556 }
3557 break;
3558 }
3559
Richard Smitheaf11ad2018-05-03 03:58:32 +00003560 case EST_DynamicNone: case EST_BasicNoexcept: case EST_NoexceptTrue:
Richard Smith3c4f8d22016-10-16 17:54:23 +00003561 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
3562 break;
3563
Richard Smitheaf11ad2018-05-03 03:58:32 +00003564 case EST_DependentNoexcept:
3565 llvm_unreachable("dependent noexcept is already canonical");
Richard Smith3c4f8d22016-10-16 17:54:23 +00003566 }
Richard Smith3c4f8d22016-10-16 17:54:23 +00003567 } else {
3568 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
3569 }
John McCalldb40c7f2010-12-14 08:05:40 +00003570
Douglas Gregora602a152015-10-01 20:20:47 +00003571 // Adjust the canonical function result type.
3572 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
Richard Smith304b1242016-10-18 20:13:25 +00003573 Canonical =
3574 getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003575
Chris Lattnerfd4de792007-01-27 01:15:32 +00003576 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003577 FunctionProtoType *NewIP =
3578 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003579 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003580 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003581
John McCall31168b02011-06-15 23:02:42 +00003582 // FunctionProtoType objects are allocated with extra bytes after
3583 // them for three variable size arrays at the end:
3584 // - parameter types
3585 // - exception types
John McCall18afab72016-03-01 00:49:02 +00003586 // - extended parameter information
John McCall31168b02011-06-15 23:02:42 +00003587 // Instead of the exception types, there could be a noexcept
Richard Smithd3b5c9082012-07-27 04:22:15 +00003588 // expression, or information used to resolve the exception
3589 // specification.
Richard Smitheaf11ad2018-05-03 03:58:32 +00003590 size_t Size =
3591 sizeof(FunctionProtoType) + NumArgs * sizeof(QualType) +
3592 FunctionProtoType::getExceptionSpecSize(
3593 EPI.ExceptionSpec.Type, EPI.ExceptionSpec.Exceptions.size());
John McCall18afab72016-03-01 00:49:02 +00003594
3595 // Put the ExtParameterInfos last. If all were equal, it would make
3596 // more sense to put these before the exception specification, because
3597 // it's much easier to skip past them compared to the elaborate switch
3598 // required to skip the exception specification. However, all is not
3599 // equal; ExtParameterInfos are used to model very uncommon features,
3600 // and it's better not to burden the more common paths.
3601 if (EPI.ExtParameterInfos) {
3602 Size += NumArgs * sizeof(FunctionProtoType::ExtParameterInfo);
3603 }
John McCall31168b02011-06-15 23:02:42 +00003604
Eugene Zelenko7855e772018-04-03 00:11:50 +00003605 auto *FTP = (FunctionProtoType *) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00003606 FunctionProtoType::ExtProtoInfo newEPI = EPI;
Jordan Rose5c382722013-03-08 21:51:21 +00003607 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003608 Types.push_back(FTP);
Richard Smith2a2cda52016-10-18 19:29:18 +00003609 if (!Unique)
3610 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003611 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003612}
Chris Lattneref51c202006-11-10 07:17:23 +00003613
Joey Goulye3c85de2016-12-01 11:30:49 +00003614QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
Xiuli Pan9c14e282016-01-09 12:53:17 +00003615 llvm::FoldingSetNodeID ID;
Joey Goulye3c85de2016-12-01 11:30:49 +00003616 PipeType::Profile(ID, T, ReadOnly);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003617
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00003618 void *InsertPos = nullptr;
Joey Goulye3c85de2016-12-01 11:30:49 +00003619 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
Xiuli Pan9c14e282016-01-09 12:53:17 +00003620 return QualType(PT, 0);
3621
3622 // If the pipe element type isn't canonical, this won't be a canonical type
3623 // either, so fill in the canonical type field.
3624 QualType Canonical;
3625 if (!T.isCanonical()) {
Joey Goulye3c85de2016-12-01 11:30:49 +00003626 Canonical = getPipeType(getCanonicalType(T), ReadOnly);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003627
3628 // Get the new insert position for the node we care about.
Joey Goulye3c85de2016-12-01 11:30:49 +00003629 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003630 assert(!NewIP && "Shouldn't be in the map!");
3631 (void)NewIP;
3632 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00003633 auto *New = new (*this, TypeAlignment) PipeType(T, Canonical, ReadOnly);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003634 Types.push_back(New);
Joey Goulye3c85de2016-12-01 11:30:49 +00003635 PipeTypes.InsertNode(New, InsertPos);
Joey Gouly5788b782016-11-18 14:10:54 +00003636 return QualType(New, 0);
3637}
3638
Anastasia Stulova59055b92018-05-09 13:23:26 +00003639QualType ASTContext::adjustStringLiteralBaseType(QualType Ty) const {
3640 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
3641 return LangOpts.OpenCL ? getAddrSpaceQualType(Ty, LangAS::opencl_constant)
3642 : Ty;
3643}
3644
Joey Goulye3c85de2016-12-01 11:30:49 +00003645QualType ASTContext::getReadPipeType(QualType T) const {
3646 return getPipeType(T, true);
3647}
3648
Joey Gouly5788b782016-11-18 14:10:54 +00003649QualType ASTContext::getWritePipeType(QualType T) const {
Joey Goulye3c85de2016-12-01 11:30:49 +00003650 return getPipeType(T, false);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003651}
3652
John McCalle78aac42010-03-10 03:28:59 +00003653#ifndef NDEBUG
3654static bool NeedsInjectedClassNameType(const RecordDecl *D) {
3655 if (!isa<CXXRecordDecl>(D)) return false;
Eugene Zelenko7855e772018-04-03 00:11:50 +00003656 const auto *RD = cast<CXXRecordDecl>(D);
John McCalle78aac42010-03-10 03:28:59 +00003657 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
3658 return true;
3659 if (RD->getDescribedClassTemplate() &&
3660 !isa<ClassTemplateSpecializationDecl>(RD))
3661 return true;
3662 return false;
3663}
3664#endif
3665
3666/// getInjectedClassNameType - Return the unique reference to the
3667/// injected class name type for the specified templated declaration.
3668QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00003669 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00003670 assert(NeedsInjectedClassNameType(Decl));
3671 if (Decl->TypeForDecl) {
3672 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00003673 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00003674 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
3675 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3676 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
3677 } else {
John McCall424cec92011-01-19 06:33:43 +00003678 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00003679 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00003680 Decl->TypeForDecl = newType;
3681 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00003682 }
3683 return QualType(Decl->TypeForDecl, 0);
3684}
3685
Douglas Gregor83a586e2008-04-13 21:07:44 +00003686/// getTypeDeclType - Return the unique reference to the type for the
3687/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00003688QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00003689 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00003690 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00003691
Eugene Zelenko7855e772018-04-03 00:11:50 +00003692 if (const auto *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00003693 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00003694
John McCall96f0b5f2010-03-10 06:48:02 +00003695 assert(!isa<TemplateTypeParmDecl>(Decl) &&
3696 "Template type parameter types are always available.");
3697
Eugene Zelenko7855e772018-04-03 00:11:50 +00003698 if (const auto *Record = dyn_cast<RecordDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003699 assert(Record->isFirstDecl() && "struct/union has previous declaration");
John McCall96f0b5f2010-03-10 06:48:02 +00003700 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003701 return getRecordType(Record);
Eugene Zelenko7855e772018-04-03 00:11:50 +00003702 } else if (const auto *Enum = dyn_cast<EnumDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003703 assert(Enum->isFirstDecl() && "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003704 return getEnumType(Enum);
Eugene Zelenko7855e772018-04-03 00:11:50 +00003705 } else if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00003706 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
3707 Decl->TypeForDecl = newType;
3708 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00003709 } else
John McCall96f0b5f2010-03-10 06:48:02 +00003710 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003711
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003712 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00003713}
3714
Chris Lattner32d920b2007-01-26 02:01:53 +00003715/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00003716/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003717QualType
Richard Smithdda56e42011-04-15 14:24:37 +00003718ASTContext::getTypedefType(const TypedefNameDecl *Decl,
3719 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003720 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003721
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003722 if (Canonical.isNull())
3723 Canonical = getCanonicalType(Decl->getUnderlyingType());
Eugene Zelenko7855e772018-04-03 00:11:50 +00003724 auto *newType = new (*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00003725 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00003726 Decl->TypeForDecl = newType;
3727 Types.push_back(newType);
3728 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00003729}
3730
Jay Foad39c79802011-01-12 09:06:06 +00003731QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003732 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3733
Douglas Gregorec9fd132012-01-14 16:38:05 +00003734 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003735 if (PrevDecl->TypeForDecl)
3736 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3737
Eugene Zelenko7855e772018-04-03 00:11:50 +00003738 auto *newType = new (*this, TypeAlignment) RecordType(Decl);
John McCall424cec92011-01-19 06:33:43 +00003739 Decl->TypeForDecl = newType;
3740 Types.push_back(newType);
3741 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003742}
3743
Jay Foad39c79802011-01-12 09:06:06 +00003744QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003745 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3746
Douglas Gregorec9fd132012-01-14 16:38:05 +00003747 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003748 if (PrevDecl->TypeForDecl)
3749 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3750
Eugene Zelenko7855e772018-04-03 00:11:50 +00003751 auto *newType = new (*this, TypeAlignment) EnumType(Decl);
John McCall424cec92011-01-19 06:33:43 +00003752 Decl->TypeForDecl = newType;
3753 Types.push_back(newType);
3754 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003755}
3756
John McCall81904512011-01-06 01:58:22 +00003757QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
3758 QualType modifiedType,
3759 QualType equivalentType) {
3760 llvm::FoldingSetNodeID id;
3761 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
3762
Craig Topper36250ad2014-05-12 05:36:57 +00003763 void *insertPos = nullptr;
John McCall81904512011-01-06 01:58:22 +00003764 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3765 if (type) return QualType(type, 0);
3766
3767 QualType canon = getCanonicalType(equivalentType);
3768 type = new (*this, TypeAlignment)
3769 AttributedType(canon, attrKind, modifiedType, equivalentType);
3770
3771 Types.push_back(type);
3772 AttributedTypes.InsertNode(type, insertPos);
3773
3774 return QualType(type, 0);
3775}
3776
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003777/// Retrieve a substitution-result type.
John McCallcebee162009-10-18 09:09:24 +00003778QualType
3779ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00003780 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00003781 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00003782 && "replacement types must always be canonical");
3783
3784 llvm::FoldingSetNodeID ID;
3785 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00003786 void *InsertPos = nullptr;
John McCallcebee162009-10-18 09:09:24 +00003787 SubstTemplateTypeParmType *SubstParm
3788 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3789
3790 if (!SubstParm) {
3791 SubstParm = new (*this, TypeAlignment)
3792 SubstTemplateTypeParmType(Parm, Replacement);
3793 Types.push_back(SubstParm);
3794 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3795 }
3796
3797 return QualType(SubstParm, 0);
3798}
3799
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003800/// Retrieve a
Douglas Gregorada4b792011-01-14 02:55:32 +00003801QualType ASTContext::getSubstTemplateTypeParmPackType(
3802 const TemplateTypeParmType *Parm,
3803 const TemplateArgument &ArgPack) {
3804#ifndef NDEBUG
Aaron Ballman2a89e852014-07-15 21:32:31 +00003805 for (const auto &P : ArgPack.pack_elements()) {
3806 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3807 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
Douglas Gregorada4b792011-01-14 02:55:32 +00003808 }
3809#endif
3810
3811 llvm::FoldingSetNodeID ID;
3812 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00003813 void *InsertPos = nullptr;
Douglas Gregorada4b792011-01-14 02:55:32 +00003814 if (SubstTemplateTypeParmPackType *SubstParm
3815 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3816 return QualType(SubstParm, 0);
3817
3818 QualType Canon;
3819 if (!Parm->isCanonicalUnqualified()) {
3820 Canon = getCanonicalType(QualType(Parm, 0));
3821 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3822 ArgPack);
3823 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3824 }
3825
Eugene Zelenko7855e772018-04-03 00:11:50 +00003826 auto *SubstParm
Douglas Gregorada4b792011-01-14 02:55:32 +00003827 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3828 ArgPack);
3829 Types.push_back(SubstParm);
George Burgess IVb5fe8552017-06-12 17:44:30 +00003830 SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos);
Douglas Gregorada4b792011-01-14 02:55:32 +00003831 return QualType(SubstParm, 0);
3832}
3833
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003834/// Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00003835/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00003836/// name.
Mike Stump11289f42009-09-09 15:08:12 +00003837QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00003838 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00003839 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00003840 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00003841 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Craig Topper36250ad2014-05-12 05:36:57 +00003842 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003843 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00003844 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3845
3846 if (TypeParm)
3847 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003848
Chandler Carruth08836322011-05-01 00:51:33 +00003849 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00003850 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00003851 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003852
3853 TemplateTypeParmType *TypeCheck
3854 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3855 assert(!TypeCheck && "Template type parameter canonical type broken");
3856 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00003857 } else
John McCall90d1c2d2009-09-24 23:30:46 +00003858 TypeParm = new (*this, TypeAlignment)
3859 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00003860
3861 Types.push_back(TypeParm);
3862 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3863
3864 return QualType(TypeParm, 0);
3865}
3866
John McCalle78aac42010-03-10 03:28:59 +00003867TypeSourceInfo *
3868ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3869 SourceLocation NameLoc,
3870 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003871 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003872 assert(!Name.getAsDependentTemplateName() &&
3873 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003874 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00003875
3876 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie6adc78e2013-02-18 22:06:02 +00003877 TemplateSpecializationTypeLoc TL =
3878 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003879 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00003880 TL.setTemplateNameLoc(NameLoc);
3881 TL.setLAngleLoc(Args.getLAngleLoc());
3882 TL.setRAngleLoc(Args.getRAngleLoc());
3883 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3884 TL.setArgLocInfo(i, Args[i].getLocInfo());
3885 return DI;
3886}
3887
Mike Stump11289f42009-09-09 15:08:12 +00003888QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00003889ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00003890 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003891 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003892 assert(!Template.getAsDependentTemplateName() &&
3893 "No dependent template names here!");
John McCall6b51f282009-11-23 01:53:49 +00003894
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003895 SmallVector<TemplateArgument, 4> ArgVec;
David Majnemer6fbeee32016-07-07 04:43:07 +00003896 ArgVec.reserve(Args.size());
3897 for (const TemplateArgumentLoc &Arg : Args.arguments())
3898 ArgVec.push_back(Arg.getArgument());
John McCall0ad16662009-10-29 08:12:44 +00003899
David Majnemer6fbeee32016-07-07 04:43:07 +00003900 return getTemplateSpecializationType(Template, ArgVec, Underlying);
John McCall0ad16662009-10-29 08:12:44 +00003901}
3902
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003903#ifndef NDEBUG
David Majnemer6fbeee32016-07-07 04:43:07 +00003904static bool hasAnyPackExpansions(ArrayRef<TemplateArgument> Args) {
3905 for (const TemplateArgument &Arg : Args)
3906 if (Arg.isPackExpansion())
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003907 return true;
3908
3909 return true;
3910}
3911#endif
3912
John McCall0ad16662009-10-29 08:12:44 +00003913QualType
3914ASTContext::getTemplateSpecializationType(TemplateName Template,
David Majnemer6fbeee32016-07-07 04:43:07 +00003915 ArrayRef<TemplateArgument> Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003916 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003917 assert(!Template.getAsDependentTemplateName() &&
3918 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00003919 // Look through qualified template names.
3920 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3921 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003922
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003923 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00003924 Template.getAsTemplateDecl() &&
3925 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00003926 QualType CanonType;
3927 if (!Underlying.isNull())
3928 CanonType = getCanonicalType(Underlying);
3929 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003930 // We can get here with an alias template when the specialization contains
3931 // a pack expansion that does not match up with a parameter pack.
David Majnemer6fbeee32016-07-07 04:43:07 +00003932 assert((!IsTypeAlias || hasAnyPackExpansions(Args)) &&
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003933 "Caller must compute aliased type");
3934 IsTypeAlias = false;
David Majnemer6fbeee32016-07-07 04:43:07 +00003935 CanonType = getCanonicalTemplateSpecializationType(Template, Args);
Richard Smith3f1b5d02011-05-05 21:57:07 +00003936 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00003937
Douglas Gregora8e02e72009-07-28 23:00:59 +00003938 // Allocate the (non-canonical) template specialization type, but don't
3939 // try to unique it: these types typically have location information that
3940 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003941 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
David Majnemer6fbeee32016-07-07 04:43:07 +00003942 sizeof(TemplateArgument) * Args.size() +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003943 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00003944 TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00003945 auto *Spec
David Majnemer6fbeee32016-07-07 04:43:07 +00003946 = new (Mem) TemplateSpecializationType(Template, Args, CanonType,
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003947 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00003948
Douglas Gregor8bf42052009-02-09 18:46:07 +00003949 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00003950 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00003951}
3952
David Majnemer6fbeee32016-07-07 04:43:07 +00003953QualType ASTContext::getCanonicalTemplateSpecializationType(
3954 TemplateName Template, ArrayRef<TemplateArgument> Args) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003955 assert(!Template.getAsDependentTemplateName() &&
3956 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003957
Douglas Gregore29139c2011-03-03 17:04:51 +00003958 // Look through qualified template names.
3959 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3960 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003961
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003962 // Build the canonical template specialization type.
3963 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003964 SmallVector<TemplateArgument, 4> CanonArgs;
David Majnemer6fbeee32016-07-07 04:43:07 +00003965 unsigned NumArgs = Args.size();
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003966 CanonArgs.reserve(NumArgs);
David Majnemer6fbeee32016-07-07 04:43:07 +00003967 for (const TemplateArgument &Arg : Args)
3968 CanonArgs.push_back(getCanonicalTemplateArgument(Arg));
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003969
3970 // Determine whether this canonical template specialization type already
3971 // exists.
3972 llvm::FoldingSetNodeID ID;
3973 TemplateSpecializationType::Profile(ID, CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00003974 CanonArgs, *this);
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003975
Craig Topper36250ad2014-05-12 05:36:57 +00003976 void *InsertPos = nullptr;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003977 TemplateSpecializationType *Spec
3978 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3979
3980 if (!Spec) {
3981 // Allocate a new canonical template specialization type.
3982 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3983 sizeof(TemplateArgument) * NumArgs),
3984 TypeAlignment);
3985 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00003986 CanonArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003987 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003988 Types.push_back(Spec);
3989 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3990 }
3991
3992 assert(Spec->isDependentType() &&
3993 "Non-dependent template-id type must have a canonical type");
3994 return QualType(Spec, 0);
3995}
3996
Joel E. Denny7509a2f2018-05-14 19:36:45 +00003997QualType ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3998 NestedNameSpecifier *NNS,
3999 QualType NamedType,
4000 TagDecl *OwnedTagDecl) const {
Douglas Gregor52537682009-03-19 00:18:19 +00004001 llvm::FoldingSetNodeID ID;
Joel E. Denny7509a2f2018-05-14 19:36:45 +00004002 ElaboratedType::Profile(ID, Keyword, NNS, NamedType, OwnedTagDecl);
Douglas Gregor52537682009-03-19 00:18:19 +00004003
Craig Topper36250ad2014-05-12 05:36:57 +00004004 void *InsertPos = nullptr;
Abramo Bagnara6150c882010-05-11 21:36:43 +00004005 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00004006 if (T)
4007 return QualType(T, 0);
4008
Douglas Gregorc42075a2010-02-04 18:10:26 +00004009 QualType Canon = NamedType;
4010 if (!Canon.isCanonical()) {
4011 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00004012 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
4013 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00004014 (void)CheckT;
4015 }
4016
Joel E. Denny7509a2f2018-05-14 19:36:45 +00004017 T = new (*this, TypeAlignment)
4018 ElaboratedType(Keyword, NNS, NamedType, Canon, OwnedTagDecl);
Douglas Gregor52537682009-03-19 00:18:19 +00004019 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00004020 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00004021 return QualType(T, 0);
4022}
4023
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004024QualType
Jay Foad39c79802011-01-12 09:06:06 +00004025ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004026 llvm::FoldingSetNodeID ID;
4027 ParenType::Profile(ID, InnerType);
4028
Craig Topper36250ad2014-05-12 05:36:57 +00004029 void *InsertPos = nullptr;
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004030 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
4031 if (T)
4032 return QualType(T, 0);
4033
4034 QualType Canon = InnerType;
4035 if (!Canon.isCanonical()) {
4036 Canon = getCanonicalType(InnerType);
4037 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
4038 assert(!CheckT && "Paren canonical type broken");
4039 (void)CheckT;
4040 }
4041
Benjamin Kramer8adeef92015-04-02 16:19:54 +00004042 T = new (*this, TypeAlignment) ParenType(InnerType, Canon);
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004043 Types.push_back(T);
4044 ParenTypes.InsertNode(T, InsertPos);
4045 return QualType(T, 0);
4046}
4047
Douglas Gregor02085352010-03-31 20:19:30 +00004048QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
4049 NestedNameSpecifier *NNS,
4050 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00004051 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00004052 if (Canon.isNull()) {
4053 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Richard Smith74f02342017-01-19 21:00:13 +00004054 if (CanonNNS != NNS)
4055 Canon = getDependentNameType(Keyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00004056 }
4057
4058 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00004059 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00004060
Craig Topper36250ad2014-05-12 05:36:57 +00004061 void *InsertPos = nullptr;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00004062 DependentNameType *T
4063 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00004064 if (T)
4065 return QualType(T, 0);
4066
Benjamin Kramer8adeef92015-04-02 16:19:54 +00004067 T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00004068 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00004069 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00004070 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00004071}
4072
Mike Stump11289f42009-09-09 15:08:12 +00004073QualType
John McCallc392f372010-06-11 00:33:02 +00004074ASTContext::getDependentTemplateSpecializationType(
4075 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00004076 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00004077 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00004078 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00004079 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004080 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00004081 for (unsigned I = 0, E = Args.size(); I != E; ++I)
4082 ArgCopy.push_back(Args[I].getArgument());
David Majnemer6fbeee32016-07-07 04:43:07 +00004083 return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy);
John McCallc392f372010-06-11 00:33:02 +00004084}
4085
4086QualType
4087ASTContext::getDependentTemplateSpecializationType(
4088 ElaboratedTypeKeyword Keyword,
4089 NestedNameSpecifier *NNS,
4090 const IdentifierInfo *Name,
David Majnemer6fbeee32016-07-07 04:43:07 +00004091 ArrayRef<TemplateArgument> Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00004092 assert((!NNS || NNS->isDependent()) &&
4093 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00004094
Douglas Gregorc42075a2010-02-04 18:10:26 +00004095 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00004096 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00004097 Name, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004098
Craig Topper36250ad2014-05-12 05:36:57 +00004099 void *InsertPos = nullptr;
John McCallc392f372010-06-11 00:33:02 +00004100 DependentTemplateSpecializationType *T
4101 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004102 if (T)
4103 return QualType(T, 0);
4104
John McCallc392f372010-06-11 00:33:02 +00004105 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004106
John McCallc392f372010-06-11 00:33:02 +00004107 ElaboratedTypeKeyword CanonKeyword = Keyword;
4108 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
4109
4110 bool AnyNonCanonArgs = false;
David Majnemer6fbeee32016-07-07 04:43:07 +00004111 unsigned NumArgs = Args.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004112 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00004113 for (unsigned I = 0; I != NumArgs; ++I) {
4114 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
4115 if (!CanonArgs[I].structurallyEquals(Args[I]))
4116 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00004117 }
4118
John McCallc392f372010-06-11 00:33:02 +00004119 QualType Canon;
4120 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
4121 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00004122 Name,
4123 CanonArgs);
John McCallc392f372010-06-11 00:33:02 +00004124
4125 // Find the insert position again.
4126 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
4127 }
4128
4129 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
4130 sizeof(TemplateArgument) * NumArgs),
4131 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00004132 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00004133 Name, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00004134 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00004135 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00004136 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00004137}
4138
Richard Smith32918772017-02-14 00:25:28 +00004139TemplateArgument ASTContext::getInjectedTemplateArg(NamedDecl *Param) {
4140 TemplateArgument Arg;
Eugene Zelenko7855e772018-04-03 00:11:50 +00004141 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
Richard Smith32918772017-02-14 00:25:28 +00004142 QualType ArgType = getTypeDeclType(TTP);
4143 if (TTP->isParameterPack())
4144 ArgType = getPackExpansionType(ArgType, None);
4145
4146 Arg = TemplateArgument(ArgType);
4147 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4148 Expr *E = new (*this) DeclRefExpr(
4149 NTTP, /*enclosing*/false,
4150 NTTP->getType().getNonLValueExprType(*this),
4151 Expr::getValueKindForType(NTTP->getType()), NTTP->getLocation());
4152
4153 if (NTTP->isParameterPack())
4154 E = new (*this) PackExpansionExpr(DependentTy, E, NTTP->getLocation(),
4155 None);
4156 Arg = TemplateArgument(E);
4157 } else {
4158 auto *TTP = cast<TemplateTemplateParmDecl>(Param);
4159 if (TTP->isParameterPack())
4160 Arg = TemplateArgument(TemplateName(TTP), Optional<unsigned>());
4161 else
4162 Arg = TemplateArgument(TemplateName(TTP));
4163 }
4164
4165 if (Param->isTemplateParameterPack())
4166 Arg = TemplateArgument::CreatePackCopy(*this, Arg);
4167
4168 return Arg;
4169}
4170
Richard Smith43e14d22016-12-23 02:10:11 +00004171void
4172ASTContext::getInjectedTemplateArgs(const TemplateParameterList *Params,
4173 SmallVectorImpl<TemplateArgument> &Args) {
4174 Args.reserve(Args.size() + Params->size());
4175
Richard Smith32918772017-02-14 00:25:28 +00004176 for (NamedDecl *Param : *Params)
4177 Args.push_back(getInjectedTemplateArg(Param));
Richard Smith43e14d22016-12-23 02:10:11 +00004178}
4179
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00004180QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikie05785d12013-02-20 22:23:23 +00004181 Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00004182 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00004183 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00004184
4185 assert(Pattern->containsUnexpandedParameterPack() &&
4186 "Pack expansions must expand one or more parameter packs");
Craig Topper36250ad2014-05-12 05:36:57 +00004187 void *InsertPos = nullptr;
Douglas Gregord2fa7662010-12-20 02:24:11 +00004188 PackExpansionType *T
4189 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
4190 if (T)
4191 return QualType(T, 0);
4192
4193 QualType Canon;
4194 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00004195 Canon = getCanonicalType(Pattern);
4196 // The canonical type might not contain an unexpanded parameter pack, if it
4197 // contains an alias template specialization which ignores one of its
4198 // parameters.
4199 if (Canon->containsUnexpandedParameterPack()) {
Richard Smith8b4e1e22014-07-10 01:20:17 +00004200 Canon = getPackExpansionType(Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00004201
Richard Smith68eea502012-07-16 00:20:35 +00004202 // Find the insert position again, in case we inserted an element into
4203 // PackExpansionTypes and invalidated our insert position.
4204 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
4205 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00004206 }
4207
Benjamin Kramer8adeef92015-04-02 16:19:54 +00004208 T = new (*this, TypeAlignment)
4209 PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00004210 Types.push_back(T);
4211 PackExpansionTypes.InsertNode(T, InsertPos);
Richard Smith8b4e1e22014-07-10 01:20:17 +00004212 return QualType(T, 0);
Douglas Gregord2fa7662010-12-20 02:24:11 +00004213}
4214
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004215/// CmpProtocolNames - Comparison predicate for sorting protocols
4216/// alphabetically.
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00004217static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
4218 ObjCProtocolDecl *const *RHS) {
4219 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004220}
4221
Craig Topper1f26d5b2016-01-03 19:43:23 +00004222static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) {
4223 if (Protocols.empty()) return true;
John McCallfc93cf92009-10-22 22:37:11 +00004224
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00004225 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
4226 return false;
4227
Craig Topper1f26d5b2016-01-03 19:43:23 +00004228 for (unsigned i = 1; i != Protocols.size(); ++i)
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00004229 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00004230 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00004231 return false;
4232 return true;
4233}
4234
Craig Topper6a8c1512015-10-22 01:56:18 +00004235static void
4236SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) {
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004237 // Sort protocols, keyed by name.
Craig Topper6a8c1512015-10-22 01:56:18 +00004238 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004239
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00004240 // Canonicalize.
Craig Topper6a8c1512015-10-22 01:56:18 +00004241 for (ObjCProtocolDecl *&P : Protocols)
4242 P = P->getCanonicalDecl();
4243
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004244 // Remove duplicates.
Craig Topper6a8c1512015-10-22 01:56:18 +00004245 auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end());
4246 Protocols.erase(ProtocolsEnd, Protocols.end());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004247}
4248
John McCall8b07ec22010-05-15 11:32:37 +00004249QualType ASTContext::getObjCObjectType(QualType BaseType,
4250 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00004251 unsigned NumProtocols) const {
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004252 return getObjCObjectType(BaseType, {},
Douglas Gregorab209d82015-07-07 03:58:42 +00004253 llvm::makeArrayRef(Protocols, NumProtocols),
4254 /*isKindOf=*/false);
Douglas Gregore9d95f12015-07-07 03:57:35 +00004255}
4256
4257QualType ASTContext::getObjCObjectType(
4258 QualType baseType,
4259 ArrayRef<QualType> typeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00004260 ArrayRef<ObjCProtocolDecl *> protocols,
4261 bool isKindOf) const {
Douglas Gregore9d95f12015-07-07 03:57:35 +00004262 // If the base type is an interface and there aren't any protocols or
4263 // type arguments to add, then the interface type will do just fine.
Douglas Gregorab209d82015-07-07 03:58:42 +00004264 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
4265 isa<ObjCInterfaceType>(baseType))
Douglas Gregore9d95f12015-07-07 03:57:35 +00004266 return baseType;
John McCall8b07ec22010-05-15 11:32:37 +00004267
4268 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00004269 llvm::FoldingSetNodeID ID;
Douglas Gregorab209d82015-07-07 03:58:42 +00004270 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
Craig Topper36250ad2014-05-12 05:36:57 +00004271 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00004272 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
4273 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00004274
Douglas Gregore9d95f12015-07-07 03:57:35 +00004275 // Determine the type arguments to be used for canonicalization,
4276 // which may be explicitly specified here or written on the base
4277 // type.
4278 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
4279 if (effectiveTypeArgs.empty()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00004280 if (const auto *baseObject = baseType->getAs<ObjCObjectType>())
Douglas Gregore9d95f12015-07-07 03:57:35 +00004281 effectiveTypeArgs = baseObject->getTypeArgs();
4282 }
John McCallfc93cf92009-10-22 22:37:11 +00004283
Douglas Gregore9d95f12015-07-07 03:57:35 +00004284 // Build the canonical type, which has the canonical base type and a
4285 // sorted-and-uniqued list of protocols and the type arguments
4286 // canonicalized.
4287 QualType canonical;
4288 bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(),
4289 effectiveTypeArgs.end(),
4290 [&](QualType type) {
4291 return type.isCanonical();
4292 });
Craig Topper1f26d5b2016-01-03 19:43:23 +00004293 bool protocolsSorted = areSortedAndUniqued(protocols);
Douglas Gregore9d95f12015-07-07 03:57:35 +00004294 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
4295 // Determine the canonical type arguments.
4296 ArrayRef<QualType> canonTypeArgs;
4297 SmallVector<QualType, 4> canonTypeArgsVec;
4298 if (!typeArgsAreCanonical) {
4299 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
4300 for (auto typeArg : effectiveTypeArgs)
4301 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
4302 canonTypeArgs = canonTypeArgsVec;
John McCallfc93cf92009-10-22 22:37:11 +00004303 } else {
Douglas Gregore9d95f12015-07-07 03:57:35 +00004304 canonTypeArgs = effectiveTypeArgs;
John McCallfc93cf92009-10-22 22:37:11 +00004305 }
4306
Douglas Gregore9d95f12015-07-07 03:57:35 +00004307 ArrayRef<ObjCProtocolDecl *> canonProtocols;
4308 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
4309 if (!protocolsSorted) {
Craig Topper6a8c1512015-10-22 01:56:18 +00004310 canonProtocolsVec.append(protocols.begin(), protocols.end());
4311 SortAndUniqueProtocols(canonProtocolsVec);
4312 canonProtocols = canonProtocolsVec;
Douglas Gregore9d95f12015-07-07 03:57:35 +00004313 } else {
4314 canonProtocols = protocols;
4315 }
4316
4317 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00004318 canonProtocols, isKindOf);
Douglas Gregore9d95f12015-07-07 03:57:35 +00004319
John McCallfc93cf92009-10-22 22:37:11 +00004320 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00004321 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
4322 }
4323
Douglas Gregore9d95f12015-07-07 03:57:35 +00004324 unsigned size = sizeof(ObjCObjectTypeImpl);
4325 size += typeArgs.size() * sizeof(QualType);
4326 size += protocols.size() * sizeof(ObjCProtocolDecl *);
4327 void *mem = Allocate(size, TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004328 auto *T =
Douglas Gregorab209d82015-07-07 03:58:42 +00004329 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
4330 isKindOf);
John McCall8b07ec22010-05-15 11:32:37 +00004331
4332 Types.push_back(T);
4333 ObjCObjectTypes.InsertNode(T, InsertPos);
4334 return QualType(T, 0);
4335}
4336
Manman Ren3569eb52016-09-13 17:03:12 +00004337/// Apply Objective-C protocol qualifiers to the given type.
4338/// If this is for the canonical type of a type parameter, we can apply
4339/// protocol qualifiers on the ObjCObjectPointerType.
4340QualType
4341ASTContext::applyObjCProtocolQualifiers(QualType type,
4342 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
4343 bool allowOnPointerType) const {
4344 hasError = false;
4345
Eugene Zelenko7855e772018-04-03 00:11:50 +00004346 if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
Manman Renc5705ba2016-09-13 17:41:05 +00004347 return getObjCTypeParamType(objT->getDecl(), protocols);
4348 }
4349
Manman Ren3569eb52016-09-13 17:03:12 +00004350 // Apply protocol qualifiers to ObjCObjectPointerType.
4351 if (allowOnPointerType) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00004352 if (const auto *objPtr =
4353 dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
Manman Ren3569eb52016-09-13 17:03:12 +00004354 const ObjCObjectType *objT = objPtr->getObjectType();
4355 // Merge protocol lists and construct ObjCObjectType.
4356 SmallVector<ObjCProtocolDecl*, 8> protocolsVec;
4357 protocolsVec.append(objT->qual_begin(),
4358 objT->qual_end());
4359 protocolsVec.append(protocols.begin(), protocols.end());
4360 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
4361 type = getObjCObjectType(
4362 objT->getBaseType(),
4363 objT->getTypeArgsAsWritten(),
4364 protocols,
4365 objT->isKindOfTypeAsWritten());
4366 return getObjCObjectPointerType(type);
4367 }
4368 }
4369
4370 // Apply protocol qualifiers to ObjCObjectType.
Eugene Zelenko7855e772018-04-03 00:11:50 +00004371 if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
Manman Ren3569eb52016-09-13 17:03:12 +00004372 // FIXME: Check for protocols to which the class type is already
4373 // known to conform.
4374
4375 return getObjCObjectType(objT->getBaseType(),
4376 objT->getTypeArgsAsWritten(),
4377 protocols,
4378 objT->isKindOfTypeAsWritten());
4379 }
4380
4381 // If the canonical type is ObjCObjectType, ...
4382 if (type->isObjCObjectType()) {
4383 // Silently overwrite any existing protocol qualifiers.
4384 // TODO: determine whether that's the right thing to do.
4385
4386 // FIXME: Check for protocols to which the class type is already
4387 // known to conform.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004388 return getObjCObjectType(type, {}, protocols, false);
Manman Ren3569eb52016-09-13 17:03:12 +00004389 }
4390
4391 // id<protocol-list>
4392 if (type->isObjCIdType()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00004393 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004394 type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols,
Manman Ren3569eb52016-09-13 17:03:12 +00004395 objPtr->isKindOfType());
4396 return getObjCObjectPointerType(type);
4397 }
4398
4399 // Class<protocol-list>
4400 if (type->isObjCClassType()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00004401 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004402 type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols,
Manman Ren3569eb52016-09-13 17:03:12 +00004403 objPtr->isKindOfType());
4404 return getObjCObjectPointerType(type);
4405 }
4406
4407 hasError = true;
4408 return type;
4409}
4410
Manman Rene6be26c2016-09-13 17:25:08 +00004411QualType
4412ASTContext::getObjCTypeParamType(const ObjCTypeParamDecl *Decl,
4413 ArrayRef<ObjCProtocolDecl *> protocols,
4414 QualType Canonical) const {
4415 // Look in the folding set for an existing type.
4416 llvm::FoldingSetNodeID ID;
4417 ObjCTypeParamType::Profile(ID, Decl, protocols);
4418 void *InsertPos = nullptr;
4419 if (ObjCTypeParamType *TypeParam =
4420 ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
4421 return QualType(TypeParam, 0);
4422
4423 if (Canonical.isNull()) {
4424 // We canonicalize to the underlying type.
4425 Canonical = getCanonicalType(Decl->getUnderlyingType());
4426 if (!protocols.empty()) {
4427 // Apply the protocol qualifers.
4428 bool hasError;
4429 Canonical = applyObjCProtocolQualifiers(Canonical, protocols, hasError,
4430 true/*allowOnPointerType*/);
4431 assert(!hasError && "Error when apply protocol qualifier to bound type");
4432 }
4433 }
4434
4435 unsigned size = sizeof(ObjCTypeParamType);
4436 size += protocols.size() * sizeof(ObjCProtocolDecl *);
4437 void *mem = Allocate(size, TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004438 auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols);
Manman Rene6be26c2016-09-13 17:25:08 +00004439
4440 Types.push_back(newType);
4441 ObjCTypeParamTypes.InsertNode(newType, InsertPos);
4442 return QualType(newType, 0);
4443}
4444
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004445/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
4446/// protocol list adopt all protocols in QT's qualified-id protocol
4447/// list.
4448bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
4449 ObjCInterfaceDecl *IC) {
4450 if (!QT->isObjCQualifiedIdType())
4451 return false;
4452
Eugene Zelenko7855e772018-04-03 00:11:50 +00004453 if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004454 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00004455 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004456 if (!IC->ClassImplementsProtocol(Proto, false))
4457 return false;
4458 }
4459 return true;
4460 }
4461 return false;
4462}
4463
4464/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
4465/// QT's qualified-id protocol list adopt all protocols in IDecl's list
4466/// of protocols.
4467bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
4468 ObjCInterfaceDecl *IDecl) {
4469 if (!QT->isObjCQualifiedIdType())
4470 return false;
Eugene Zelenko7855e772018-04-03 00:11:50 +00004471 const auto *OPT = QT->getAs<ObjCObjectPointerType>();
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004472 if (!OPT)
4473 return false;
4474 if (!IDecl->hasDefinition())
4475 return false;
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00004476 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
4477 CollectInheritedProtocols(IDecl, InheritedProtocols);
4478 if (InheritedProtocols.empty())
4479 return false;
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00004480 // Check that if every protocol in list of id<plist> conforms to a protocol
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00004481 // of IDecl's, then bridge casting is ok.
4482 bool Conforms = false;
4483 for (auto *Proto : OPT->quals()) {
4484 Conforms = false;
4485 for (auto *PI : InheritedProtocols) {
4486 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
4487 Conforms = true;
4488 break;
4489 }
4490 }
4491 if (!Conforms)
4492 break;
4493 }
4494 if (Conforms)
4495 return true;
4496
Aaron Ballman83731462014-03-17 16:14:00 +00004497 for (auto *PI : InheritedProtocols) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004498 // If both the right and left sides have qualifiers.
4499 bool Adopts = false;
Aaron Ballman83731462014-03-17 16:14:00 +00004500 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00004501 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
Aaron Ballman83731462014-03-17 16:14:00 +00004502 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004503 break;
4504 }
4505 if (!Adopts)
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00004506 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004507 }
4508 return true;
4509}
4510
John McCall8b07ec22010-05-15 11:32:37 +00004511/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
4512/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00004513QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00004514 llvm::FoldingSetNodeID ID;
4515 ObjCObjectPointerType::Profile(ID, ObjectT);
4516
Craig Topper36250ad2014-05-12 05:36:57 +00004517 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00004518 if (ObjCObjectPointerType *QT =
4519 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
4520 return QualType(QT, 0);
4521
4522 // Find the canonical object type.
4523 QualType Canonical;
4524 if (!ObjectT.isCanonical()) {
4525 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
4526
4527 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00004528 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
4529 }
4530
Douglas Gregorf85bee62010-02-08 22:59:26 +00004531 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00004532 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004533 auto *QType =
John McCall8b07ec22010-05-15 11:32:37 +00004534 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00004535
Steve Narofffb4330f2009-06-17 22:40:22 +00004536 Types.push_back(QType);
4537 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00004538 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00004539}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004540
Douglas Gregor1c283312010-08-11 12:19:30 +00004541/// getObjCInterfaceType - Return the unique reference to the type for the
4542/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00004543QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
4544 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00004545 if (Decl->TypeForDecl)
4546 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004547
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00004548 if (PrevDecl) {
4549 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
4550 Decl->TypeForDecl = PrevDecl->TypeForDecl;
4551 return QualType(PrevDecl->TypeForDecl, 0);
4552 }
4553
Douglas Gregor7671e532011-12-16 16:34:57 +00004554 // Prefer the definition, if there is one.
4555 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
4556 Decl = Def;
4557
Douglas Gregor1c283312010-08-11 12:19:30 +00004558 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004559 auto *T = new (Mem) ObjCInterfaceType(Decl);
Douglas Gregor1c283312010-08-11 12:19:30 +00004560 Decl->TypeForDecl = T;
4561 Types.push_back(T);
4562 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00004563}
4564
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004565/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
4566/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00004567/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00004568/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00004569/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00004570QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00004571 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004572 if (tofExpr->isTypeDependent()) {
4573 llvm::FoldingSetNodeID ID;
4574 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00004575
Craig Topper36250ad2014-05-12 05:36:57 +00004576 void *InsertPos = nullptr;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004577 DependentTypeOfExprType *Canon
4578 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
4579 if (Canon) {
4580 // We already have a "canonical" version of an identical, dependent
4581 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00004582 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004583 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00004584 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004585 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00004586 Canon
4587 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004588 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
4589 toe = Canon;
4590 }
4591 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00004592 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00004593 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00004594 }
Steve Naroffa773cd52007-08-01 18:02:17 +00004595 Types.push_back(toe);
4596 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00004597}
4598
Steve Naroffa773cd52007-08-01 18:02:17 +00004599/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
Richard Smith8eb1d322014-06-05 20:13:13 +00004600/// TypeOfType nodes. The only motivation to unique these nodes would be
Steve Naroffa773cd52007-08-01 18:02:17 +00004601/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Richard Smith8eb1d322014-06-05 20:13:13 +00004602/// an issue. This doesn't affect the type checker, since it operates
4603/// on canonical types (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00004604QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00004605 QualType Canonical = getCanonicalType(tofType);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004606 auto *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00004607 Types.push_back(tot);
4608 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00004609}
4610
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004611/// Unlike many "get<Type>" functions, we don't unique DecltypeType
Richard Smith8eb1d322014-06-05 20:13:13 +00004612/// nodes. This would never be helpful, since each such type has its own
4613/// expression, and would not give a significant memory saving, since there
4614/// is an Expr tree under each such type.
Douglas Gregor81495f32012-02-12 18:42:33 +00004615QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00004616 DecltypeType *dt;
Richard Smith8eb1d322014-06-05 20:13:13 +00004617
4618 // C++11 [temp.type]p2:
Douglas Gregor678d76c2011-07-01 01:22:09 +00004619 // If an expression e involves a template parameter, decltype(e) denotes a
Richard Smith8eb1d322014-06-05 20:13:13 +00004620 // unique dependent type. Two such decltype-specifiers refer to the same
4621 // type only if their expressions are equivalent (14.5.6.1).
Douglas Gregor678d76c2011-07-01 01:22:09 +00004622 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00004623 llvm::FoldingSetNodeID ID;
4624 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00004625
Craig Topper36250ad2014-05-12 05:36:57 +00004626 void *InsertPos = nullptr;
Douglas Gregora21f6c32009-07-30 23:36:40 +00004627 DependentDecltypeType *Canon
4628 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
Richard Smith8eb1d322014-06-05 20:13:13 +00004629 if (!Canon) {
Yaron Keren633e14a2016-11-29 10:08:20 +00004630 // Build a new, canonical decltype(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00004631 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00004632 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
Douglas Gregora21f6c32009-07-30 23:36:40 +00004633 }
Richard Smith8eb1d322014-06-05 20:13:13 +00004634 dt = new (*this, TypeAlignment)
4635 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
Douglas Gregora21f6c32009-07-30 23:36:40 +00004636 } else {
Richard Smith8eb1d322014-06-05 20:13:13 +00004637 dt = new (*this, TypeAlignment)
4638 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00004639 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00004640 Types.push_back(dt);
4641 return QualType(dt, 0);
4642}
4643
Alexis Hunte852b102011-05-24 22:41:36 +00004644/// getUnaryTransformationType - We don't unique these, since the memory
4645/// savings are minimal and these are rare.
4646QualType ASTContext::getUnaryTransformType(QualType BaseType,
4647 QualType UnderlyingType,
4648 UnaryTransformType::UTTKind Kind)
4649 const {
Vassil Vassilevbab6f962016-03-30 22:18:29 +00004650 UnaryTransformType *ut = nullptr;
4651
4652 if (BaseType->isDependentType()) {
4653 // Look in the folding set for an existing type.
4654 llvm::FoldingSetNodeID ID;
4655 DependentUnaryTransformType::Profile(ID, getCanonicalType(BaseType), Kind);
4656
4657 void *InsertPos = nullptr;
4658 DependentUnaryTransformType *Canon
4659 = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
4660
4661 if (!Canon) {
4662 // Build a new, canonical __underlying_type(type) type.
4663 Canon = new (*this, TypeAlignment)
4664 DependentUnaryTransformType(*this, getCanonicalType(BaseType),
4665 Kind);
4666 DependentUnaryTransformTypes.InsertNode(Canon, InsertPos);
4667 }
4668 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4669 QualType(), Kind,
4670 QualType(Canon, 0));
4671 } else {
4672 QualType CanonType = getCanonicalType(UnderlyingType);
4673 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4674 UnderlyingType, Kind,
4675 CanonType);
4676 }
4677 Types.push_back(ut);
4678 return QualType(ut, 0);
Alexis Hunte852b102011-05-24 22:41:36 +00004679}
4680
Richard Smith2a7d4812013-05-04 07:00:32 +00004681/// getAutoType - Return the uniqued reference to the 'auto' type which has been
4682/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
4683/// canonical deduced-but-dependent 'auto' type.
Richard Smithe301ba22015-11-11 02:02:15 +00004684QualType ASTContext::getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004685 bool IsDependent) const {
Richard Smithe301ba22015-11-11 02:02:15 +00004686 if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto && !IsDependent)
Richard Smith2a7d4812013-05-04 07:00:32 +00004687 return getAutoDeductType();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004688
Richard Smith2a7d4812013-05-04 07:00:32 +00004689 // Look in the folding set for an existing type.
Craig Topper36250ad2014-05-12 05:36:57 +00004690 void *InsertPos = nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +00004691 llvm::FoldingSetNodeID ID;
Richard Smithe301ba22015-11-11 02:02:15 +00004692 AutoType::Profile(ID, DeducedType, Keyword, IsDependent);
Richard Smith2a7d4812013-05-04 07:00:32 +00004693 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
4694 return QualType(AT, 0);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004695
Eugene Zelenko7855e772018-04-03 00:11:50 +00004696 auto *AT = new (*this, TypeAlignment)
4697 AutoType(DeducedType, Keyword, IsDependent);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004698 Types.push_back(AT);
4699 if (InsertPos)
4700 AutoTypes.InsertNode(AT, InsertPos);
4701 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00004702}
4703
Richard Smith600b5262017-01-26 20:40:47 +00004704/// Return the uniqued reference to the deduced template specialization type
4705/// which has been deduced to the given type, or to the canonical undeduced
4706/// such type, or the canonical deduced-but-dependent such type.
4707QualType ASTContext::getDeducedTemplateSpecializationType(
4708 TemplateName Template, QualType DeducedType, bool IsDependent) const {
4709 // Look in the folding set for an existing type.
4710 void *InsertPos = nullptr;
4711 llvm::FoldingSetNodeID ID;
4712 DeducedTemplateSpecializationType::Profile(ID, Template, DeducedType,
4713 IsDependent);
4714 if (DeducedTemplateSpecializationType *DTST =
4715 DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
4716 return QualType(DTST, 0);
4717
Eugene Zelenko7855e772018-04-03 00:11:50 +00004718 auto *DTST = new (*this, TypeAlignment)
Richard Smith600b5262017-01-26 20:40:47 +00004719 DeducedTemplateSpecializationType(Template, DeducedType, IsDependent);
4720 Types.push_back(DTST);
4721 if (InsertPos)
4722 DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos);
4723 return QualType(DTST, 0);
4724}
4725
Eli Friedman0dfb8892011-10-06 23:00:33 +00004726/// getAtomicType - Return the uniqued reference to the atomic type for
4727/// the given value type.
4728QualType ASTContext::getAtomicType(QualType T) const {
4729 // Unique pointers, to guarantee there is only one pointer of a particular
4730 // structure.
4731 llvm::FoldingSetNodeID ID;
4732 AtomicType::Profile(ID, T);
4733
Craig Topper36250ad2014-05-12 05:36:57 +00004734 void *InsertPos = nullptr;
Eli Friedman0dfb8892011-10-06 23:00:33 +00004735 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
4736 return QualType(AT, 0);
4737
4738 // If the atomic value type isn't canonical, this won't be a canonical type
4739 // either, so fill in the canonical type field.
4740 QualType Canonical;
4741 if (!T.isCanonical()) {
4742 Canonical = getAtomicType(getCanonicalType(T));
4743
4744 // Get the new insert position for the node we care about.
4745 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00004746 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Eli Friedman0dfb8892011-10-06 23:00:33 +00004747 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00004748 auto *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
Eli Friedman0dfb8892011-10-06 23:00:33 +00004749 Types.push_back(New);
4750 AtomicTypes.InsertNode(New, InsertPos);
4751 return QualType(New, 0);
4752}
4753
Richard Smith02e85f32011-04-14 22:09:26 +00004754/// getAutoDeductType - Get type pattern for deducing against 'auto'.
4755QualType ASTContext::getAutoDeductType() const {
4756 if (AutoDeductTy.isNull())
Richard Smith2a7d4812013-05-04 07:00:32 +00004757 AutoDeductTy = QualType(
Richard Smithe301ba22015-11-11 02:02:15 +00004758 new (*this, TypeAlignment) AutoType(QualType(), AutoTypeKeyword::Auto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004759 /*dependent*/false),
Richard Smith2a7d4812013-05-04 07:00:32 +00004760 0);
Richard Smith02e85f32011-04-14 22:09:26 +00004761 return AutoDeductTy;
4762}
4763
4764/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
4765QualType ASTContext::getAutoRRefDeductType() const {
4766 if (AutoRRefDeductTy.isNull())
4767 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
4768 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
4769 return AutoRRefDeductTy;
4770}
4771
Chris Lattnerfb072462007-01-23 05:45:31 +00004772/// getTagDeclType - Return the unique reference to the type for the
4773/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00004774QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004775 assert(Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00004776 // FIXME: What is the design on getTagDeclType when it requires casting
4777 // away const? mutable?
4778 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00004779}
4780
Mike Stump11289f42009-09-09 15:08:12 +00004781/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
4782/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
4783/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00004784CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00004785 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00004786}
Chris Lattnerfb072462007-01-23 05:45:31 +00004787
Alexander Shaposhnikov1e898d92017-07-14 17:30:14 +00004788/// Return the unique signed counterpart of the integer type
4789/// corresponding to size_t.
4790CanQualType ASTContext::getSignedSizeType() const {
4791 return getFromTargetType(Target->getSignedSizeType());
4792}
4793
Hans Wennborg27541db2011-10-27 08:29:09 +00004794/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
4795CanQualType ASTContext::getIntMaxType() const {
4796 return getFromTargetType(Target->getIntMaxType());
4797}
4798
4799/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
4800CanQualType ASTContext::getUIntMaxType() const {
4801 return getFromTargetType(Target->getUIntMaxType());
4802}
4803
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00004804/// getSignedWCharType - Return the type of "signed wchar_t".
4805/// Used when in C++, as a GCC extension.
4806QualType ASTContext::getSignedWCharType() const {
4807 // FIXME: derive from "Target" ?
4808 return WCharTy;
4809}
4810
4811/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
4812/// Used when in C++, as a GCC extension.
4813QualType ASTContext::getUnsignedWCharType() const {
4814 // FIXME: derive from "Target" ?
4815 return UnsignedIntTy;
4816}
4817
Enea Zaffanellaf11ceb62013-01-26 17:08:37 +00004818QualType ASTContext::getIntPtrType() const {
4819 return getFromTargetType(Target->getIntPtrType());
4820}
4821
4822QualType ASTContext::getUIntPtrType() const {
4823 return getCorrespondingUnsignedType(getIntPtrType());
4824}
4825
Hans Wennborg27541db2011-10-27 08:29:09 +00004826/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00004827/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
4828QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00004829 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00004830}
4831
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004832/// Return the unique unsigned counterpart of "ptrdiff_t"
Alexander Shaposhnikov195b25c2017-09-28 23:11:31 +00004833/// integer type. The standard (C11 7.21.6.1p7) refers to this type
4834/// in the definition of %tu format specifier.
4835QualType ASTContext::getUnsignedPointerDiffType() const {
4836 return getFromTargetType(Target->getUnsignedPtrDiffType(0));
4837}
4838
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004839/// Return the unique type for "pid_t" defined in
Eli Friedman4e91899e2012-11-27 02:58:24 +00004840/// <sys/types.h>. We need this to compute the correct type for vfork().
4841QualType ASTContext::getProcessIDType() const {
4842 return getFromTargetType(Target->getProcessIDType());
4843}
4844
Chris Lattnera21ad802008-04-02 05:18:44 +00004845//===----------------------------------------------------------------------===//
4846// Type Operators
4847//===----------------------------------------------------------------------===//
4848
Jay Foad39c79802011-01-12 09:06:06 +00004849CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00004850 // Push qualifiers into arrays, and then discard any remaining
4851 // qualifiers.
4852 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00004853 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00004854 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00004855 QualType Result;
4856 if (isa<ArrayType>(Ty)) {
4857 Result = getArrayDecayedType(QualType(Ty,0));
4858 } else if (isa<FunctionType>(Ty)) {
4859 Result = getPointerType(QualType(Ty, 0));
4860 } else {
4861 Result = QualType(Ty, 0);
4862 }
4863
4864 return CanQualType::CreateUnsafe(Result);
4865}
4866
John McCall6c9dd522011-01-18 07:41:22 +00004867QualType ASTContext::getUnqualifiedArrayType(QualType type,
4868 Qualifiers &quals) {
4869 SplitQualType splitType = type.getSplitUnqualifiedType();
4870
4871 // FIXME: getSplitUnqualifiedType() actually walks all the way to
4872 // the unqualified desugared type and then drops it on the floor.
4873 // We then have to strip that sugar back off with
4874 // getUnqualifiedDesugaredType(), which is silly.
Eugene Zelenko7855e772018-04-03 00:11:50 +00004875 const auto *AT =
4876 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00004877
4878 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004879 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00004880 quals = splitType.Quals;
4881 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004882 }
4883
John McCall6c9dd522011-01-18 07:41:22 +00004884 // Otherwise, recurse on the array's element type.
4885 QualType elementType = AT->getElementType();
4886 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
4887
4888 // If that didn't change the element type, AT has no qualifiers, so we
4889 // can just use the results in splitType.
4890 if (elementType == unqualElementType) {
4891 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00004892 quals = splitType.Quals;
4893 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00004894 }
4895
4896 // Otherwise, add in the qualifiers from the outermost type, then
4897 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00004898 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004899
Eugene Zelenko7855e772018-04-03 00:11:50 +00004900 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004901 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00004902 CAT->getSizeModifier(), 0);
4903 }
4904
Eugene Zelenko7855e772018-04-03 00:11:50 +00004905 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004906 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004907 }
4908
Eugene Zelenko7855e772018-04-03 00:11:50 +00004909 if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004910 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00004911 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004912 VAT->getSizeModifier(),
4913 VAT->getIndexTypeCVRQualifiers(),
4914 VAT->getBracketsRange());
4915 }
4916
Eugene Zelenko7855e772018-04-03 00:11:50 +00004917 const auto *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00004918 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00004919 DSAT->getSizeModifier(), 0,
4920 SourceRange());
4921}
4922
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004923/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
4924/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
4925/// they point to and return true. If T1 and T2 aren't pointer types
4926/// or pointer-to-member types, or if they are not similar at this
4927/// level, returns false and leaves T1 and T2 unchanged. Top-level
4928/// qualifiers on T1 and T2 are ignored. This function will typically
4929/// be called in a loop that successively "unwraps" pointer and
4930/// pointer-to-member types to compare them at each level.
4931bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00004932 const auto *T1PtrType = T1->getAs<PointerType>();
4933 const auto *T2PtrType = T2->getAs<PointerType>();
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004934 if (T1PtrType && T2PtrType) {
4935 T1 = T1PtrType->getPointeeType();
4936 T2 = T2PtrType->getPointeeType();
4937 return true;
4938 }
4939
Eugene Zelenko7855e772018-04-03 00:11:50 +00004940 const auto *T1MPType = T1->getAs<MemberPointerType>();
4941 const auto *T2MPType = T2->getAs<MemberPointerType>();
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004942 if (T1MPType && T2MPType &&
4943 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
4944 QualType(T2MPType->getClass(), 0))) {
4945 T1 = T1MPType->getPointeeType();
4946 T2 = T2MPType->getPointeeType();
4947 return true;
4948 }
4949
David Blaikiebbafb8a2012-03-11 07:00:24 +00004950 if (getLangOpts().ObjC1) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00004951 const auto *T1OPType = T1->getAs<ObjCObjectPointerType>();
4952 const auto *T2OPType = T2->getAs<ObjCObjectPointerType>();
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004953 if (T1OPType && T2OPType) {
4954 T1 = T1OPType->getPointeeType();
4955 T2 = T2OPType->getPointeeType();
4956 return true;
4957 }
4958 }
4959
4960 // FIXME: Block pointers, too?
4961
4962 return false;
4963}
4964
Jay Foad39c79802011-01-12 09:06:06 +00004965DeclarationNameInfo
4966ASTContext::getNameForTemplate(TemplateName Name,
4967 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004968 switch (Name.getKind()) {
4969 case TemplateName::QualifiedTemplate:
4970 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004971 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00004972 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
4973 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004974
John McCalld9dfe3a2011-06-30 08:33:18 +00004975 case TemplateName::OverloadedTemplate: {
4976 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
4977 // DNInfo work in progress: CHECKME: what about DNLoc?
4978 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
4979 }
4980
4981 case TemplateName::DependentTemplate: {
4982 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004983 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00004984 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004985 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
4986 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00004987 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004988 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
4989 // DNInfo work in progress: FIXME: source locations?
4990 DeclarationNameLoc DNLoc;
4991 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
4992 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
4993 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00004994 }
4995 }
4996
John McCalld9dfe3a2011-06-30 08:33:18 +00004997 case TemplateName::SubstTemplateTemplateParm: {
4998 SubstTemplateTemplateParmStorage *subst
4999 = Name.getAsSubstTemplateTemplateParm();
5000 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
5001 NameLoc);
5002 }
5003
5004 case TemplateName::SubstTemplateTemplateParmPack: {
5005 SubstTemplateTemplateParmPackStorage *subst
5006 = Name.getAsSubstTemplateTemplateParmPack();
5007 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
5008 NameLoc);
5009 }
5010 }
5011
5012 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00005013}
5014
Jay Foad39c79802011-01-12 09:06:06 +00005015TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00005016 switch (Name.getKind()) {
5017 case TemplateName::QualifiedTemplate:
5018 case TemplateName::Template: {
5019 TemplateDecl *Template = Name.getAsTemplateDecl();
Eugene Zelenko7855e772018-04-03 00:11:50 +00005020 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00005021 Template = getCanonicalTemplateTemplateParmDecl(TTP);
5022
5023 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00005024 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00005025 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00005026
John McCalld9dfe3a2011-06-30 08:33:18 +00005027 case TemplateName::OverloadedTemplate:
5028 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00005029
John McCalld9dfe3a2011-06-30 08:33:18 +00005030 case TemplateName::DependentTemplate: {
5031 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
5032 assert(DTN && "Non-dependent template names must refer to template decls.");
5033 return DTN->CanonicalTemplateName;
5034 }
5035
5036 case TemplateName::SubstTemplateTemplateParm: {
5037 SubstTemplateTemplateParmStorage *subst
5038 = Name.getAsSubstTemplateTemplateParm();
5039 return getCanonicalTemplateName(subst->getReplacement());
5040 }
5041
5042 case TemplateName::SubstTemplateTemplateParmPack: {
5043 SubstTemplateTemplateParmPackStorage *subst
5044 = Name.getAsSubstTemplateTemplateParmPack();
5045 TemplateTemplateParmDecl *canonParameter
5046 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
5047 TemplateArgument canonArgPack
5048 = getCanonicalTemplateArgument(subst->getArgumentPack());
5049 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
5050 }
5051 }
5052
5053 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00005054}
5055
Douglas Gregoradee3e32009-11-11 23:06:43 +00005056bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
5057 X = getCanonicalTemplateName(X);
5058 Y = getCanonicalTemplateName(Y);
5059 return X.getAsVoidPointer() == Y.getAsVoidPointer();
5060}
5061
Mike Stump11289f42009-09-09 15:08:12 +00005062TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00005063ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00005064 switch (Arg.getKind()) {
5065 case TemplateArgument::Null:
5066 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00005067
Douglas Gregora8e02e72009-07-28 23:00:59 +00005068 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00005069 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00005070
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005071 case TemplateArgument::Declaration: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00005072 auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
David Blaikie952a9b12014-10-17 18:00:12 +00005073 return TemplateArgument(D, Arg.getParamTypeForDecl());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005074 }
Mike Stump11289f42009-09-09 15:08:12 +00005075
Eli Friedmanb826a002012-09-26 02:36:12 +00005076 case TemplateArgument::NullPtr:
5077 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
5078 /*isNullPtr*/true);
5079
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005080 case TemplateArgument::Template:
5081 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005082
5083 case TemplateArgument::TemplateExpansion:
5084 return TemplateArgument(getCanonicalTemplateName(
5085 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00005086 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005087
Douglas Gregora8e02e72009-07-28 23:00:59 +00005088 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00005089 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00005090
Douglas Gregora8e02e72009-07-28 23:00:59 +00005091 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00005092 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00005093
Douglas Gregora8e02e72009-07-28 23:00:59 +00005094 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00005095 if (Arg.pack_size() == 0)
5096 return Arg;
5097
Eugene Zelenko7855e772018-04-03 00:11:50 +00005098 auto *CanonArgs = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00005099 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00005100 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00005101 AEnd = Arg.pack_end();
5102 A != AEnd; (void)++A, ++Idx)
5103 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00005104
Benjamin Kramercce63472015-08-05 09:40:22 +00005105 return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size()));
Douglas Gregora8e02e72009-07-28 23:00:59 +00005106 }
5107 }
5108
5109 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00005110 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00005111}
5112
Douglas Gregor333489b2009-03-27 23:10:48 +00005113NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00005114ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00005115 if (!NNS)
Craig Topper36250ad2014-05-12 05:36:57 +00005116 return nullptr;
Douglas Gregor333489b2009-03-27 23:10:48 +00005117
5118 switch (NNS->getKind()) {
5119 case NestedNameSpecifier::Identifier:
5120 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00005121 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00005122 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
5123 NNS->getAsIdentifier());
5124
5125 case NestedNameSpecifier::Namespace:
5126 // A namespace is canonical; build a nested-name-specifier with
5127 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00005128 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00005129 NNS->getAsNamespace()->getOriginalNamespace());
5130
5131 case NestedNameSpecifier::NamespaceAlias:
5132 // A namespace is canonical; build a nested-name-specifier with
5133 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00005134 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00005135 NNS->getAsNamespaceAlias()->getNamespace()
5136 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00005137
5138 case NestedNameSpecifier::TypeSpec:
5139 case NestedNameSpecifier::TypeSpecWithTemplate: {
5140 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00005141
5142 // If we have some kind of dependent-named type (e.g., "typename T::type"),
5143 // break it apart into its prefix and identifier, then reconsititute those
5144 // as the canonical nested-name-specifier. This is required to canonicalize
5145 // a dependent nested-name-specifier involving typedefs of dependent-name
5146 // types, e.g.,
5147 // typedef typename T::type T1;
5148 // typedef typename T1::type T2;
Eugene Zelenko7855e772018-04-03 00:11:50 +00005149 if (const auto *DNT = T->getAs<DependentNameType>())
Eli Friedman5358a0a2012-03-03 04:09:56 +00005150 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00005151 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00005152
Eli Friedman5358a0a2012-03-03 04:09:56 +00005153 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
5154 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
5155 // first place?
Craig Topper36250ad2014-05-12 05:36:57 +00005156 return NestedNameSpecifier::Create(*this, nullptr, false,
5157 const_cast<Type *>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00005158 }
5159
5160 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00005161 case NestedNameSpecifier::Super:
5162 // The global specifier and __super specifer are canonical and unique.
Douglas Gregor333489b2009-03-27 23:10:48 +00005163 return NNS;
5164 }
5165
David Blaikie8a40f702012-01-17 06:56:22 +00005166 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00005167}
5168
Jay Foad39c79802011-01-12 09:06:06 +00005169const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00005170 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005171 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00005172 // Handle the common positive case fast.
Eugene Zelenko7855e772018-04-03 00:11:50 +00005173 if (const auto *AT = dyn_cast<ArrayType>(T))
Chris Lattner7adf0762008-08-04 07:31:14 +00005174 return AT;
5175 }
Mike Stump11289f42009-09-09 15:08:12 +00005176
John McCall8ccfcb52009-09-24 19:53:00 +00005177 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00005178 if (!isa<ArrayType>(T.getCanonicalType()))
Craig Topper36250ad2014-05-12 05:36:57 +00005179 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00005180
John McCall8ccfcb52009-09-24 19:53:00 +00005181 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00005182 // implements C99 6.7.3p8: "If the specification of an array type includes
5183 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00005184
Chris Lattner7adf0762008-08-04 07:31:14 +00005185 // If we get here, we either have type qualifiers on the type, or we have
5186 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00005187 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00005188
John McCall33ddac02011-01-19 10:06:00 +00005189 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00005190 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00005191
Chris Lattner7adf0762008-08-04 07:31:14 +00005192 // If we have a simple case, just return now.
Eugene Zelenko7855e772018-04-03 00:11:50 +00005193 const auto *ATy = dyn_cast<ArrayType>(split.Ty);
Craig Topper36250ad2014-05-12 05:36:57 +00005194 if (!ATy || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00005195 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00005196
Chris Lattner7adf0762008-08-04 07:31:14 +00005197 // Otherwise, we have an array and we have qualifiers on it. Push the
5198 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00005199 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00005200
Eugene Zelenko7855e772018-04-03 00:11:50 +00005201 if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy))
Chris Lattner7adf0762008-08-04 07:31:14 +00005202 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
5203 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00005204 CAT->getIndexTypeCVRQualifiers()));
Eugene Zelenko7855e772018-04-03 00:11:50 +00005205 if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy))
Chris Lattner7adf0762008-08-04 07:31:14 +00005206 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
5207 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00005208 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00005209
Eugene Zelenko7855e772018-04-03 00:11:50 +00005210 if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy))
Douglas Gregor4619e432008-12-05 23:32:09 +00005211 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00005212 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00005213 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00005214 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00005215 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00005216 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00005217
Eugene Zelenko7855e772018-04-03 00:11:50 +00005218 const auto *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00005219 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00005220 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00005221 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00005222 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00005223 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00005224}
5225
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00005226QualType ASTContext::getAdjustedParameterType(QualType T) const {
Reid Kleckner8a365022013-06-24 17:51:48 +00005227 if (T->isArrayType() || T->isFunctionType())
5228 return getDecayedType(T);
5229 return T;
Douglas Gregor84280642011-07-12 04:42:08 +00005230}
5231
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00005232QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00005233 T = getVariableArrayDecayedType(T);
5234 T = getAdjustedParameterType(T);
5235 return T.getUnqualifiedType();
5236}
5237
David Majnemerd09a51c2015-03-03 01:50:05 +00005238QualType ASTContext::getExceptionObjectType(QualType T) const {
5239 // C++ [except.throw]p3:
5240 // A throw-expression initializes a temporary object, called the exception
5241 // object, the type of which is determined by removing any top-level
5242 // cv-qualifiers from the static type of the operand of throw and adjusting
5243 // the type from "array of T" or "function returning T" to "pointer to T"
5244 // or "pointer to function returning T", [...]
5245 T = getVariableArrayDecayedType(T);
5246 if (T->isArrayType() || T->isFunctionType())
5247 T = getDecayedType(T);
5248 return T.getUnqualifiedType();
5249}
5250
Chris Lattnera21ad802008-04-02 05:18:44 +00005251/// getArrayDecayedType - Return the properly qualified result of decaying the
5252/// specified array type to a pointer. This operation is non-trivial when
5253/// handling typedefs etc. The canonical type of "T" must be an array type,
5254/// this returns a pointer to a properly qualified element of the array.
5255///
5256/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00005257QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00005258 // Get the element type with 'getAsArrayType' so that we don't lose any
5259 // typedefs in the element type of the array. This also handles propagation
5260 // of type qualifiers from the array type into the element type if present
5261 // (C99 6.7.3p8).
5262 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
5263 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00005264
Chris Lattner7adf0762008-08-04 07:31:14 +00005265 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00005266
5267 // int x[restrict 4] -> int *restrict
Jordan Rose303e2f12016-11-10 23:28:17 +00005268 QualType Result = getQualifiedType(PtrTy,
5269 PrettyArrayType->getIndexTypeQualifiers());
5270
5271 // int x[_Nullable] -> int * _Nullable
5272 if (auto Nullability = Ty->getNullability(*this)) {
5273 Result = const_cast<ASTContext *>(this)->getAttributedType(
5274 AttributedType::getNullabilityAttrKind(*Nullability), Result, Result);
5275 }
5276 return Result;
Chris Lattnera21ad802008-04-02 05:18:44 +00005277}
5278
John McCall33ddac02011-01-19 10:06:00 +00005279QualType ASTContext::getBaseElementType(const ArrayType *array) const {
5280 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00005281}
5282
John McCall33ddac02011-01-19 10:06:00 +00005283QualType ASTContext::getBaseElementType(QualType type) const {
5284 Qualifiers qs;
5285 while (true) {
5286 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00005287 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00005288 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00005289
John McCall33ddac02011-01-19 10:06:00 +00005290 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00005291 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00005292 }
Mike Stump11289f42009-09-09 15:08:12 +00005293
John McCall33ddac02011-01-19 10:06:00 +00005294 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00005295}
5296
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00005297/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00005298uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00005299ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
5300 uint64_t ElementCount = 1;
5301 do {
5302 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00005303 CA = dyn_cast_or_null<ConstantArrayType>(
5304 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00005305 } while (CA);
5306 return ElementCount;
5307}
5308
Steve Naroff0af91202007-04-27 21:51:21 +00005309/// getFloatingRank - Return a relative rank for floating point types.
5310/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00005311static FloatingRank getFloatingRank(QualType T) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00005312 if (const auto *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00005313 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00005314
John McCall9dd450b2009-09-21 23:43:11 +00005315 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
5316 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00005317 default: llvm_unreachable("getFloatingRank(): not a floating type");
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00005318 case BuiltinType::Float16: return Float16Rank;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00005319 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00005320 case BuiltinType::Float: return FloatRank;
5321 case BuiltinType::Double: return DoubleRank;
5322 case BuiltinType::LongDouble: return LongDoubleRank;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005323 case BuiltinType::Float128: return Float128Rank;
Steve Naroffe4718892007-04-27 18:30:00 +00005324 }
5325}
5326
Mike Stump11289f42009-09-09 15:08:12 +00005327/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
5328/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00005329/// 'typeDomain' is a real floating point or complex type.
5330/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00005331QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
5332 QualType Domain) const {
5333 FloatingRank EltRank = getFloatingRank(Size);
5334 if (Domain->isComplexType()) {
5335 switch (EltRank) {
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00005336 case Float16Rank:
David Blaikief47fa302012-01-17 02:30:50 +00005337 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00005338 case FloatRank: return FloatComplexTy;
5339 case DoubleRank: return DoubleComplexTy;
5340 case LongDoubleRank: return LongDoubleComplexTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005341 case Float128Rank: return Float128ComplexTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00005342 }
Steve Naroff0af91202007-04-27 21:51:21 +00005343 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00005344
5345 assert(Domain->isRealFloatingType() && "Unknown domain!");
5346 switch (EltRank) {
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00005347 case Float16Rank: return HalfTy;
Joey Goulydd7f4562013-01-23 11:56:20 +00005348 case HalfRank: return HalfTy;
Chris Lattnerb9dfb032008-04-06 23:58:54 +00005349 case FloatRank: return FloatTy;
5350 case DoubleRank: return DoubleTy;
5351 case LongDoubleRank: return LongDoubleTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005352 case Float128Rank: return Float128Ty;
Steve Naroff9091ef72007-08-27 01:27:54 +00005353 }
David Blaikief47fa302012-01-17 02:30:50 +00005354 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00005355}
5356
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005357/// getFloatingTypeOrder - Compare the rank of the two specified floating
5358/// point types, ignoring the domain of the type (i.e. 'double' ==
5359/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00005360/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00005361int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00005362 FloatingRank LHSR = getFloatingRank(LHS);
5363 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00005364
Chris Lattnerb90739d2008-04-06 23:38:49 +00005365 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00005366 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00005367 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00005368 return 1;
5369 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00005370}
5371
Chris Lattner76a00cf2008-04-06 22:59:24 +00005372/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
5373/// routine will assert if passed a built-in type that isn't an integer or enum,
5374/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00005375unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00005376 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00005377
Chris Lattner76a00cf2008-04-06 22:59:24 +00005378 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00005379 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005380 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005381 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005382 case BuiltinType::Char_S:
5383 case BuiltinType::Char_U:
5384 case BuiltinType::SChar:
5385 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005386 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005387 case BuiltinType::Short:
5388 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005389 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005390 case BuiltinType::Int:
5391 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005392 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005393 case BuiltinType::Long:
5394 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005395 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005396 case BuiltinType::LongLong:
5397 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005398 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00005399 case BuiltinType::Int128:
5400 case BuiltinType::UInt128:
5401 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00005402 }
5403}
5404
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005405/// Whether this is a promotable bitfield reference according
Eli Friedman629ffb92009-08-20 04:21:42 +00005406/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
5407///
5408/// \returns the type this bit-field will promote to, or NULL if no
5409/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00005410QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00005411 if (E->isTypeDependent() || E->isValueDependent())
Eugene Zelenko7855e772018-04-03 00:11:50 +00005412 return {};
Richard Smith5b571672014-09-24 23:55:00 +00005413
5414 // FIXME: We should not do this unless E->refersToBitField() is true. This
5415 // matters in C where getSourceBitField() will find bit-fields for various
5416 // cases where the source expression is not a bit-field designator.
5417
John McCalld25db7e2013-05-06 21:39:12 +00005418 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman629ffb92009-08-20 04:21:42 +00005419 if (!Field)
Eugene Zelenko7855e772018-04-03 00:11:50 +00005420 return {};
Eli Friedman629ffb92009-08-20 04:21:42 +00005421
5422 QualType FT = Field->getType();
5423
Richard Smithcaf33902011-10-10 18:28:20 +00005424 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00005425 uint64_t IntSize = getTypeSize(IntTy);
Richard Smith5b571672014-09-24 23:55:00 +00005426 // C++ [conv.prom]p5:
5427 // A prvalue for an integral bit-field can be converted to a prvalue of type
5428 // int if int can represent all the values of the bit-field; otherwise, it
5429 // can be converted to unsigned int if unsigned int can represent all the
5430 // values of the bit-field. If the bit-field is larger yet, no integral
5431 // promotion applies to it.
5432 // C11 6.3.1.1/2:
5433 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
5434 // If an int can represent all values of the original type (as restricted by
5435 // the width, for a bit-field), the value is converted to an int; otherwise,
5436 // it is converted to an unsigned int.
5437 //
5438 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
5439 // We perform that promotion here to match GCC and C++.
Eli Friedman629ffb92009-08-20 04:21:42 +00005440 if (BitWidth < IntSize)
5441 return IntTy;
5442
5443 if (BitWidth == IntSize)
5444 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
5445
5446 // Types bigger than int are not subject to promotions, and therefore act
Richard Smith5b571672014-09-24 23:55:00 +00005447 // like the base type. GCC has some weird bugs in this area that we
5448 // deliberately do not follow (GCC follows a pre-standard resolution to
5449 // C's DR315 which treats bit-width as being part of the type, and this leaks
5450 // into their semantics in some cases).
Eugene Zelenko7855e772018-04-03 00:11:50 +00005451 return {};
Eli Friedman629ffb92009-08-20 04:21:42 +00005452}
5453
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005454/// getPromotedIntegerType - Returns the type that Promotable will
5455/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
5456/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00005457QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005458 assert(!Promotable.isNull());
5459 assert(Promotable->isPromotableIntegerType());
Eugene Zelenko7855e772018-04-03 00:11:50 +00005460 if (const auto *ET = Promotable->getAs<EnumType>())
John McCall56774992009-12-09 09:09:27 +00005461 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00005462
Eugene Zelenko7855e772018-04-03 00:11:50 +00005463 if (const auto *BT = Promotable->getAs<BuiltinType>()) {
Eli Friedman3f37c1c2011-10-26 07:22:48 +00005464 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
5465 // (3.9.1) can be converted to a prvalue of the first of the following
5466 // types that can represent all the values of its underlying type:
5467 // int, unsigned int, long int, unsigned long int, long long int, or
5468 // unsigned long long int [...]
5469 // FIXME: Is there some better way to compute this?
5470 if (BT->getKind() == BuiltinType::WChar_S ||
5471 BT->getKind() == BuiltinType::WChar_U ||
Richard Smith3a8244d2018-05-01 05:02:45 +00005472 BT->getKind() == BuiltinType::Char8 ||
Eli Friedman3f37c1c2011-10-26 07:22:48 +00005473 BT->getKind() == BuiltinType::Char16 ||
5474 BT->getKind() == BuiltinType::Char32) {
5475 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
5476 uint64_t FromSize = getTypeSize(BT);
5477 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
5478 LongLongTy, UnsignedLongLongTy };
5479 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
5480 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
5481 if (FromSize < ToSize ||
5482 (FromSize == ToSize &&
5483 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
5484 return PromoteTypes[Idx];
5485 }
5486 llvm_unreachable("char type should fit into long long");
5487 }
5488 }
5489
5490 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005491 if (Promotable->isSignedIntegerType())
5492 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00005493 uint64_t PromotableSize = getIntWidth(Promotable);
5494 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005495 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
5496 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
5497}
5498
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005499/// Recurses in pointer/array types until it finds an objc retainable
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00005500/// type and returns its ownership.
5501Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
5502 while (!T.isNull()) {
5503 if (T.getObjCLifetime() != Qualifiers::OCL_None)
5504 return T.getObjCLifetime();
5505 if (T->isArrayType())
5506 T = getBaseElementType(T);
Eugene Zelenko7855e772018-04-03 00:11:50 +00005507 else if (const auto *PT = T->getAs<PointerType>())
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00005508 T = PT->getPointeeType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00005509 else if (const auto *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00005510 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00005511 else
5512 break;
5513 }
5514
5515 return Qualifiers::OCL_None;
5516}
5517
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005518static const Type *getIntegerTypeForEnum(const EnumType *ET) {
5519 // Incomplete enum types are not treated as integer types.
5520 // FIXME: In C++, enum types are never integer types.
5521 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
5522 return ET->getDecl()->getIntegerType().getTypePtr();
Craig Topper36250ad2014-05-12 05:36:57 +00005523 return nullptr;
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005524}
5525
Mike Stump11289f42009-09-09 15:08:12 +00005526/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005527/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00005528/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00005529int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00005530 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
5531 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005532
5533 // Unwrap enums to their underlying type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00005534 if (const auto *ET = dyn_cast<EnumType>(LHSC))
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005535 LHSC = getIntegerTypeForEnum(ET);
Eugene Zelenko7855e772018-04-03 00:11:50 +00005536 if (const auto *ET = dyn_cast<EnumType>(RHSC))
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005537 RHSC = getIntegerTypeForEnum(ET);
5538
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005539 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00005540
Chris Lattner76a00cf2008-04-06 22:59:24 +00005541 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
5542 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00005543
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005544 unsigned LHSRank = getIntegerRank(LHSC);
5545 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00005546
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005547 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
5548 if (LHSRank == RHSRank) return 0;
5549 return LHSRank > RHSRank ? 1 : -1;
5550 }
Mike Stump11289f42009-09-09 15:08:12 +00005551
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005552 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
5553 if (LHSUnsigned) {
5554 // If the unsigned [LHS] type is larger, return it.
5555 if (LHSRank >= RHSRank)
5556 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00005557
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005558 // If the signed type can represent all values of the unsigned type, it
5559 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00005560 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005561 return -1;
5562 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00005563
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005564 // If the unsigned [RHS] type is larger, return it.
5565 if (RHSRank >= LHSRank)
5566 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00005567
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005568 // If the signed type can represent all values of the unsigned type, it
5569 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00005570 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005571 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00005572}
Anders Carlsson98f07902007-08-17 05:31:46 +00005573
Ben Langmuirf5416742016-02-04 00:55:24 +00005574TypedefDecl *ASTContext::getCFConstantStringDecl() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00005575 if (!CFConstantStringTypeDecl) {
Ben Langmuirf5416742016-02-04 00:55:24 +00005576 assert(!CFConstantStringTagDecl &&
5577 "tag and typedef should be initialized together");
5578 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
5579 CFConstantStringTagDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00005580
Anders Carlsson9c1011c2007-11-19 00:25:30 +00005581 QualType FieldTypes[4];
Ben Langmuir4791a802016-02-25 16:36:26 +00005582 const char *FieldNames[4];
Mike Stump11289f42009-09-09 15:08:12 +00005583
Anders Carlsson98f07902007-08-17 05:31:46 +00005584 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00005585 FieldTypes[0] = getPointerType(IntTy.withConst());
Ben Langmuir4791a802016-02-25 16:36:26 +00005586 FieldNames[0] = "isa";
Anders Carlsson9c1011c2007-11-19 00:25:30 +00005587 // int flags;
5588 FieldTypes[1] = IntTy;
Ben Langmuir4791a802016-02-25 16:36:26 +00005589 FieldNames[1] = "flags";
Anders Carlsson98f07902007-08-17 05:31:46 +00005590 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00005591 FieldTypes[2] = getPointerType(CharTy.withConst());
Ben Langmuir4791a802016-02-25 16:36:26 +00005592 FieldNames[2] = "str";
Anders Carlsson98f07902007-08-17 05:31:46 +00005593 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00005594 FieldTypes[3] = LongTy;
Ben Langmuir4791a802016-02-25 16:36:26 +00005595 FieldNames[3] = "length";
Mike Stump11289f42009-09-09 15:08:12 +00005596
Anders Carlsson98f07902007-08-17 05:31:46 +00005597 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00005598 for (unsigned i = 0; i < 4; ++i) {
Ben Langmuirf5416742016-02-04 00:55:24 +00005599 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTagDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00005600 SourceLocation(),
Ben Langmuir4791a802016-02-25 16:36:26 +00005601 SourceLocation(),
5602 &Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00005603 FieldTypes[i], /*TInfo=*/nullptr,
5604 /*BitWidth=*/nullptr,
Richard Smith938f40b2011-06-11 17:19:42 +00005605 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00005606 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00005607 Field->setAccess(AS_public);
Ben Langmuirf5416742016-02-04 00:55:24 +00005608 CFConstantStringTagDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00005609 }
5610
Ben Langmuirf5416742016-02-04 00:55:24 +00005611 CFConstantStringTagDecl->completeDefinition();
5612 // This type is designed to be compatible with NSConstantString, but cannot
5613 // use the same name, since NSConstantString is an interface.
5614 auto tagType = getTagDeclType(CFConstantStringTagDecl);
5615 CFConstantStringTypeDecl =
5616 buildImplicitTypedef(tagType, "__NSConstantString");
Anders Carlsson98f07902007-08-17 05:31:46 +00005617 }
Mike Stump11289f42009-09-09 15:08:12 +00005618
Quentin Colombet043406b2016-02-03 22:41:00 +00005619 return CFConstantStringTypeDecl;
5620}
5621
Ben Langmuirf5416742016-02-04 00:55:24 +00005622RecordDecl *ASTContext::getCFConstantStringTagDecl() const {
5623 if (!CFConstantStringTagDecl)
5624 getCFConstantStringDecl(); // Build the tag and the typedef.
5625 return CFConstantStringTagDecl;
5626}
5627
Quentin Colombet043406b2016-02-03 22:41:00 +00005628// getCFConstantStringType - Return the type used for constant CFStrings.
5629QualType ASTContext::getCFConstantStringType() const {
Ben Langmuirf5416742016-02-04 00:55:24 +00005630 return getTypedefType(getCFConstantStringDecl());
Gabor Greif412af032007-09-11 15:32:40 +00005631}
Anders Carlsson87c149b2007-10-11 01:00:40 +00005632
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00005633QualType ASTContext::getObjCSuperType() const {
5634 if (ObjCSuperType.isNull()) {
Alp Toker2dea15b2013-12-17 01:22:38 +00005635 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00005636 TUDecl->addDecl(ObjCSuperTypeDecl);
5637 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
5638 }
5639 return ObjCSuperType;
5640}
5641
Douglas Gregor512b0772009-04-23 22:29:11 +00005642void ASTContext::setCFConstantStringType(QualType T) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00005643 const auto *TD = T->getAs<TypedefType>();
Ben Langmuirf5416742016-02-04 00:55:24 +00005644 assert(TD && "Invalid CFConstantStringType");
5645 CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl());
Eugene Zelenko7855e772018-04-03 00:11:50 +00005646 const auto *TagType =
Ben Langmuirf5416742016-02-04 00:55:24 +00005647 CFConstantStringTypeDecl->getUnderlyingType()->getAs<RecordType>();
5648 assert(TagType && "Invalid CFConstantStringType");
5649 CFConstantStringTagDecl = TagType->getDecl();
Douglas Gregor512b0772009-04-23 22:29:11 +00005650}
5651
Jay Foad39c79802011-01-12 09:06:06 +00005652QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00005653 if (BlockDescriptorType)
5654 return getTagDeclType(BlockDescriptorType);
5655
Alp Toker2dea15b2013-12-17 01:22:38 +00005656 RecordDecl *RD;
Mike Stumpd0153282009-10-20 02:12:22 +00005657 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00005658 RD = buildImplicitRecord("__block_descriptor");
5659 RD->startDefinition();
5660
Mike Stumpd0153282009-10-20 02:12:22 +00005661 QualType FieldTypes[] = {
5662 UnsignedLongTy,
5663 UnsignedLongTy,
5664 };
5665
Craig Topperd6d31ac2013-07-15 08:24:27 +00005666 static const char *const FieldNames[] = {
Mike Stumpd0153282009-10-20 02:12:22 +00005667 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005668 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00005669 };
5670
5671 for (size_t i = 0; i < 2; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00005672 FieldDecl *Field = FieldDecl::Create(
5673 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00005674 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
5675 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00005676 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00005677 RD->addDecl(Field);
Mike Stumpd0153282009-10-20 02:12:22 +00005678 }
5679
Alp Toker2dea15b2013-12-17 01:22:38 +00005680 RD->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00005681
Alp Toker2dea15b2013-12-17 01:22:38 +00005682 BlockDescriptorType = RD;
Mike Stumpd0153282009-10-20 02:12:22 +00005683
5684 return getTagDeclType(BlockDescriptorType);
5685}
5686
Jay Foad39c79802011-01-12 09:06:06 +00005687QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005688 if (BlockDescriptorExtendedType)
5689 return getTagDeclType(BlockDescriptorExtendedType);
5690
Alp Toker2dea15b2013-12-17 01:22:38 +00005691 RecordDecl *RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005692 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00005693 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
5694 RD->startDefinition();
5695
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005696 QualType FieldTypes[] = {
5697 UnsignedLongTy,
5698 UnsignedLongTy,
5699 getPointerType(VoidPtrTy),
5700 getPointerType(VoidPtrTy)
5701 };
5702
Craig Topperd6d31ac2013-07-15 08:24:27 +00005703 static const char *const FieldNames[] = {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005704 "reserved",
5705 "Size",
5706 "CopyFuncPtr",
5707 "DestroyFuncPtr"
5708 };
5709
5710 for (size_t i = 0; i < 4; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00005711 FieldDecl *Field = FieldDecl::Create(
5712 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00005713 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
5714 /*BitWidth=*/nullptr,
Alp Toker2dea15b2013-12-17 01:22:38 +00005715 /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00005716 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00005717 RD->addDecl(Field);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005718 }
5719
Alp Toker2dea15b2013-12-17 01:22:38 +00005720 RD->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005721
Alp Toker2dea15b2013-12-17 01:22:38 +00005722 BlockDescriptorExtendedType = RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005723 return getTagDeclType(BlockDescriptorExtendedType);
5724}
5725
Sven van Haastregt3bb7eaf2017-12-06 10:11:28 +00005726TargetInfo::OpenCLTypeKind ASTContext::getOpenCLTypeKind(const Type *T) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00005727 const auto *BT = dyn_cast<BuiltinType>(T);
Sven van Haastregt3bb7eaf2017-12-06 10:11:28 +00005728
5729 if (!BT) {
5730 if (isa<PipeType>(T))
5731 return TargetInfo::OCLTK_Pipe;
5732
5733 return TargetInfo::OCLTK_Default;
5734 }
5735
5736 switch (BT->getKind()) {
5737#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5738 case BuiltinType::Id: \
5739 return TargetInfo::OCLTK_Image;
5740#include "clang/Basic/OpenCLImageTypes.def"
5741
5742 case BuiltinType::OCLClkEvent:
5743 return TargetInfo::OCLTK_ClkEvent;
5744
5745 case BuiltinType::OCLEvent:
5746 return TargetInfo::OCLTK_Event;
5747
5748 case BuiltinType::OCLQueue:
5749 return TargetInfo::OCLTK_Queue;
5750
5751 case BuiltinType::OCLReserveID:
5752 return TargetInfo::OCLTK_ReserveID;
5753
5754 case BuiltinType::OCLSampler:
5755 return TargetInfo::OCLTK_Sampler;
5756
5757 default:
5758 return TargetInfo::OCLTK_Default;
5759 }
5760}
5761
5762LangAS ASTContext::getOpenCLTypeAddrSpace(const Type *T) const {
5763 return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
5764}
5765
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005766/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
5767/// requires copy/dispose. Note that this must match the logic
5768/// in buildByrefHelpers.
5769bool ASTContext::BlockRequiresCopying(QualType Ty,
5770 const VarDecl *D) {
5771 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
5772 const Expr *copyExpr = getBlockVarCopyInits(D);
5773 if (!copyExpr && record->hasTrivialDestructor()) return false;
5774
Mike Stump94967902009-10-21 18:16:27 +00005775 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00005776 }
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005777
Akira Hatanaka7275da02018-02-28 07:15:55 +00005778 // The block needs copy/destroy helpers if Ty is non-trivial to destructively
5779 // move or destroy.
5780 if (Ty.isNonTrivialToPrimitiveDestructiveMove() || Ty.isDestructedType())
5781 return true;
5782
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005783 if (!Ty->isObjCRetainableType()) return false;
5784
5785 Qualifiers qs = Ty.getQualifiers();
5786
5787 // If we have lifetime, that dominates.
5788 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005789 switch (lifetime) {
5790 case Qualifiers::OCL_None: llvm_unreachable("impossible");
5791
5792 // These are just bits as far as the runtime is concerned.
5793 case Qualifiers::OCL_ExplicitNone:
5794 case Qualifiers::OCL_Autoreleasing:
5795 return false;
Akira Hatanaka7275da02018-02-28 07:15:55 +00005796
5797 // These cases should have been taken care of when checking the type's
5798 // non-triviality.
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005799 case Qualifiers::OCL_Weak:
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005800 case Qualifiers::OCL_Strong:
Akira Hatanaka7275da02018-02-28 07:15:55 +00005801 llvm_unreachable("impossible");
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005802 }
5803 llvm_unreachable("fell out of lifetime switch!");
5804 }
5805 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
5806 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00005807}
5808
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005809bool ASTContext::getByrefLifetime(QualType Ty,
5810 Qualifiers::ObjCLifetime &LifeTime,
5811 bool &HasByrefExtendedLayout) const {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005812 if (!getLangOpts().ObjC1 ||
5813 getLangOpts().getGC() != LangOptions::NonGC)
5814 return false;
5815
5816 HasByrefExtendedLayout = false;
Fariborz Jahanianf762b722012-12-11 19:58:01 +00005817 if (Ty->isRecordType()) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005818 HasByrefExtendedLayout = true;
5819 LifeTime = Qualifiers::OCL_None;
John McCall460ce582015-10-22 18:38:17 +00005820 } else if ((LifeTime = Ty.getObjCLifetime())) {
5821 // Honor the ARC qualifiers.
5822 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
5823 // The MRR rule.
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005824 LifeTime = Qualifiers::OCL_ExplicitNone;
John McCall460ce582015-10-22 18:38:17 +00005825 } else {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005826 LifeTime = Qualifiers::OCL_None;
John McCall460ce582015-10-22 18:38:17 +00005827 }
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005828 return true;
5829}
5830
Douglas Gregorbab8a962011-09-08 01:46:34 +00005831TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
5832 if (!ObjCInstanceTypeDecl)
Alp Toker56b5cc92013-12-15 10:36:26 +00005833 ObjCInstanceTypeDecl =
5834 buildImplicitTypedef(getObjCIdType(), "instancetype");
Douglas Gregorbab8a962011-09-08 01:46:34 +00005835 return ObjCInstanceTypeDecl;
5836}
5837
Anders Carlsson18acd442007-10-29 06:33:42 +00005838// This returns true if a type has been typedefed to BOOL:
5839// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00005840static bool isTypeTypedefedAsBOOL(QualType T) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00005841 if (const auto *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00005842 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
5843 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00005844
Anders Carlssond8499822007-10-29 05:01:08 +00005845 return false;
5846}
5847
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005848/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005849/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00005850CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00005851 if (!type->isIncompleteArrayType() && type->isIncompleteType())
5852 return CharUnits::Zero();
5853
Ken Dyck40775002010-01-11 17:06:35 +00005854 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00005855
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005856 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00005857 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00005858 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005859 // Treat arrays as pointers, since that's how they're passed in.
5860 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00005861 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00005862 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00005863}
5864
Hans Wennborg56fc62b2014-07-17 20:25:23 +00005865bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
David Majnemer3f021502015-10-08 04:53:31 +00005866 return getTargetInfo().getCXXABI().isMicrosoft() &&
5867 VD->isStaticDataMember() &&
Hans Wennborgb18da9b2018-02-20 12:43:02 +00005868 VD->getType()->isIntegralOrEnumerationType() &&
David Majnemerfac52432015-10-19 23:22:49 +00005869 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
Hans Wennborg56fc62b2014-07-17 20:25:23 +00005870}
5871
Richard Smithd9b90092016-07-02 01:32:16 +00005872ASTContext::InlineVariableDefinitionKind
5873ASTContext::getInlineVariableDefinitionKind(const VarDecl *VD) const {
5874 if (!VD->isInline())
5875 return InlineVariableDefinitionKind::None;
5876
5877 // In almost all cases, it's a weak definition.
5878 auto *First = VD->getFirstDecl();
Richard Smith8910fe62017-10-23 03:58:34 +00005879 if (First->isInlineSpecified() || !First->isStaticDataMember())
Richard Smithd9b90092016-07-02 01:32:16 +00005880 return InlineVariableDefinitionKind::Weak;
5881
5882 // If there's a file-context declaration in this translation unit, it's a
5883 // non-discardable definition.
5884 for (auto *D : VD->redecls())
Richard Smith8910fe62017-10-23 03:58:34 +00005885 if (D->getLexicalDeclContext()->isFileContext() &&
5886 !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr()))
Richard Smithd9b90092016-07-02 01:32:16 +00005887 return InlineVariableDefinitionKind::Strong;
5888
5889 // If we've not seen one yet, we don't know.
5890 return InlineVariableDefinitionKind::WeakUnknown;
5891}
5892
Eugene Zelenko7855e772018-04-03 00:11:50 +00005893static std::string charUnitsToString(const CharUnits &CU) {
Ken Dyck40775002010-01-11 17:06:35 +00005894 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005895}
5896
John McCall351762c2011-02-07 10:33:21 +00005897/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00005898/// declaration.
John McCall351762c2011-02-07 10:33:21 +00005899std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
5900 std::string S;
5901
David Chisnall950a9512009-11-17 19:33:30 +00005902 const BlockDecl *Decl = Expr->getBlockDecl();
5903 QualType BlockTy =
5904 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
5905 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00005906 if (getLangOpts().EncodeExtendedBlockSig)
Alp Toker314cc812014-01-25 16:55:45 +00005907 getObjCEncodingForMethodParameter(
5908 Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
5909 true /*Extended*/);
Fariborz Jahanian64223e62012-11-14 23:11:38 +00005910 else
Alp Toker314cc812014-01-25 16:55:45 +00005911 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00005912 // Compute size of all parameters.
5913 // Start with computing size of a pointer in number of bytes.
5914 // FIXME: There might(should) be a better way of doing this computation!
Ken Dyck40775002010-01-11 17:06:35 +00005915 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
5916 CharUnits ParmOffset = PtrSize;
David Majnemer59f77922016-06-24 04:05:48 +00005917 for (auto PI : Decl->parameters()) {
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00005918 QualType PType = PI->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00005919 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00005920 if (sz.isZero())
5921 continue;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00005922 assert(sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00005923 ParmOffset += sz;
5924 }
5925 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00005926 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00005927 // Block pointer and offset.
5928 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00005929
5930 // Argument types.
5931 ParmOffset = PtrSize;
David Majnemer59f77922016-06-24 04:05:48 +00005932 for (auto PVDecl : Decl->parameters()) {
David Chisnall950a9512009-11-17 19:33:30 +00005933 QualType PType = PVDecl->getOriginalType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00005934 if (const auto *AT =
5935 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
David Chisnall950a9512009-11-17 19:33:30 +00005936 // Use array's original type only if it has known number of
5937 // elements.
5938 if (!isa<ConstantArrayType>(AT))
5939 PType = PVDecl->getType();
5940 } else if (PType->isFunctionType())
5941 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00005942 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00005943 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
5944 S, true /*Extended*/);
5945 else
5946 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00005947 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00005948 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00005949 }
John McCall351762c2011-02-07 10:33:21 +00005950
5951 return S;
David Chisnall950a9512009-11-17 19:33:30 +00005952}
5953
John McCall843dfcc2016-11-29 21:57:00 +00005954std::string
5955ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const {
5956 std::string S;
David Chisnall50e4eba2010-12-30 14:05:53 +00005957 // Encode result type.
Alp Toker314cc812014-01-25 16:55:45 +00005958 getObjCEncodingForType(Decl->getReturnType(), S);
David Chisnall50e4eba2010-12-30 14:05:53 +00005959 CharUnits ParmOffset;
5960 // Compute size of all parameters.
David Majnemer59f77922016-06-24 04:05:48 +00005961 for (auto PI : Decl->parameters()) {
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00005962 QualType PType = PI->getType();
David Chisnall50e4eba2010-12-30 14:05:53 +00005963 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00005964 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00005965 continue;
5966
John McCall843dfcc2016-11-29 21:57:00 +00005967 assert(sz.isPositive() &&
5968 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00005969 ParmOffset += sz;
5970 }
5971 S += charUnitsToString(ParmOffset);
5972 ParmOffset = CharUnits::Zero();
5973
5974 // Argument types.
David Majnemer59f77922016-06-24 04:05:48 +00005975 for (auto PVDecl : Decl->parameters()) {
David Chisnall50e4eba2010-12-30 14:05:53 +00005976 QualType PType = PVDecl->getOriginalType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00005977 if (const auto *AT =
5978 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
David Chisnall50e4eba2010-12-30 14:05:53 +00005979 // Use array's original type only if it has known number of
5980 // elements.
5981 if (!isa<ConstantArrayType>(AT))
5982 PType = PVDecl->getType();
5983 } else if (PType->isFunctionType())
5984 PType = PVDecl->getType();
5985 getObjCEncodingForType(PType, S);
5986 S += charUnitsToString(ParmOffset);
5987 ParmOffset += getObjCEncodingTypeSize(PType);
5988 }
Douglas Gregora9d84932011-05-27 01:19:52 +00005989
John McCall843dfcc2016-11-29 21:57:00 +00005990 return S;
David Chisnall50e4eba2010-12-30 14:05:53 +00005991}
5992
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005993/// getObjCEncodingForMethodParameter - Return the encoded type for a single
5994/// method parameter or return type. If Extended, include class names and
5995/// block object types.
5996void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
5997 QualType T, std::string& S,
5998 bool Extended) const {
5999 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
6000 getObjCEncodingForTypeQualifier(QT, S);
6001 // Encode parameter type.
Craig Topper36250ad2014-05-12 05:36:57 +00006002 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006003 true /*OutermostType*/,
6004 false /*EncodingProperty*/,
6005 false /*StructField*/,
6006 Extended /*EncodeBlockParameters*/,
6007 Extended /*EncodeClassNames*/);
6008}
6009
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006010/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006011/// declaration.
John McCall843dfcc2016-11-29 21:57:00 +00006012std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
6013 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00006014 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006015 // Encode return type.
John McCall843dfcc2016-11-29 21:57:00 +00006016 std::string S;
Alp Toker314cc812014-01-25 16:55:45 +00006017 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
6018 Decl->getReturnType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006019 // Compute size of all parameters.
6020 // Start with computing size of a pointer in number of bytes.
6021 // FIXME: There might(should) be a better way of doing this computation!
Ken Dyck40775002010-01-11 17:06:35 +00006022 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006023 // The first two arguments (self and _cmd) are pointers; account for
6024 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00006025 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00006026 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00006027 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00006028 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00006029 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00006030 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00006031 continue;
6032
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00006033 assert(sz.isPositive() &&
6034 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006035 ParmOffset += sz;
6036 }
Ken Dyck40775002010-01-11 17:06:35 +00006037 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006038 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00006039 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00006040
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006041 // Argument types.
6042 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00006043 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00006044 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00006045 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00006046 QualType PType = PVDecl->getOriginalType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00006047 if (const auto *AT =
6048 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
Steve Naroffe4e55d22009-04-14 00:03:58 +00006049 // Use array's original type only if it has known number of
6050 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00006051 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00006052 PType = PVDecl->getType();
6053 } else if (PType->isFunctionType())
6054 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006055 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
6056 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00006057 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00006058 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006059 }
Douglas Gregora9d84932011-05-27 01:19:52 +00006060
John McCall843dfcc2016-11-29 21:57:00 +00006061 return S;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006062}
6063
Fariborz Jahaniandad96302014-01-22 19:02:20 +00006064ObjCPropertyImplDecl *
6065ASTContext::getObjCPropertyImplDeclForPropertyDecl(
6066 const ObjCPropertyDecl *PD,
6067 const Decl *Container) const {
6068 if (!Container)
Craig Topper36250ad2014-05-12 05:36:57 +00006069 return nullptr;
Eugene Zelenko7855e772018-04-03 00:11:50 +00006070 if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) {
Aaron Ballmand85eff42014-03-14 15:02:45 +00006071 for (auto *PID : CID->property_impls())
6072 if (PID->getPropertyDecl() == PD)
6073 return PID;
Craig Topper36250ad2014-05-12 05:36:57 +00006074 } else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006075 const auto *OID = cast<ObjCImplementationDecl>(Container);
Craig Topper36250ad2014-05-12 05:36:57 +00006076 for (auto *PID : OID->property_impls())
6077 if (PID->getPropertyDecl() == PD)
6078 return PID;
6079 }
6080 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00006081}
6082
Daniel Dunbar4932b362008-08-28 04:38:10 +00006083/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00006084/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00006085/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
6086/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00006087/// Property attributes are stored as a comma-delimited C string. The simple
6088/// attributes readonly and bycopy are encoded as single characters. The
6089/// parametrized attributes, getter=name, setter=name, and ivar=name, are
6090/// encoded as single characters, followed by an identifier. Property types
6091/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00006092/// these attributes are defined by the following enumeration:
6093/// @code
6094/// enum PropertyAttributes {
6095/// kPropertyReadOnly = 'R', // property is read-only.
6096/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
6097/// kPropertyByref = '&', // property is a reference to the value last assigned
6098/// kPropertyDynamic = 'D', // property is dynamic
6099/// kPropertyGetter = 'G', // followed by getter selector name
6100/// kPropertySetter = 'S', // followed by setter selector name
6101/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00006102/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00006103/// kPropertyWeak = 'W' // 'weak' property
6104/// kPropertyStrong = 'P' // property GC'able
6105/// kPropertyNonAtomic = 'N' // property non-atomic
6106/// };
6107/// @endcode
John McCall843dfcc2016-11-29 21:57:00 +00006108std::string
6109ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
6110 const Decl *Container) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00006111 // Collect information from the property implementation decl(s).
6112 bool Dynamic = false;
Craig Topper36250ad2014-05-12 05:36:57 +00006113 ObjCPropertyImplDecl *SynthesizePID = nullptr;
Daniel Dunbar4932b362008-08-28 04:38:10 +00006114
Fariborz Jahaniandad96302014-01-22 19:02:20 +00006115 if (ObjCPropertyImplDecl *PropertyImpDecl =
6116 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
6117 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
6118 Dynamic = true;
6119 else
6120 SynthesizePID = PropertyImpDecl;
Daniel Dunbar4932b362008-08-28 04:38:10 +00006121 }
6122
6123 // FIXME: This is not very efficient.
John McCall843dfcc2016-11-29 21:57:00 +00006124 std::string S = "T";
Daniel Dunbar4932b362008-08-28 04:38:10 +00006125
6126 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00006127 // GCC has some special rules regarding encoding of properties which
6128 // closely resembles encoding of ivars.
Joe Groff98ac7d22014-07-07 22:25:15 +00006129 getObjCEncodingForPropertyType(PD->getType(), S);
Daniel Dunbar4932b362008-08-28 04:38:10 +00006130
6131 if (PD->isReadOnly()) {
6132 S += ",R";
Nico Weber4e8626f2013-05-08 23:47:40 +00006133 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
6134 S += ",C";
6135 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
6136 S += ",&";
Fariborz Jahanian33079ee2014-04-02 22:49:42 +00006137 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
6138 S += ",W";
Daniel Dunbar4932b362008-08-28 04:38:10 +00006139 } else {
6140 switch (PD->getSetterKind()) {
6141 case ObjCPropertyDecl::Assign: break;
6142 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00006143 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00006144 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00006145 }
6146 }
6147
6148 // It really isn't clear at all what this means, since properties
6149 // are "dynamic by default".
6150 if (Dynamic)
6151 S += ",D";
6152
Fariborz Jahanian218c6302009-01-20 19:14:18 +00006153 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
6154 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00006155
Daniel Dunbar4932b362008-08-28 04:38:10 +00006156 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
6157 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00006158 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00006159 }
6160
6161 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
6162 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00006163 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00006164 }
6165
6166 if (SynthesizePID) {
6167 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
6168 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00006169 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00006170 }
6171
6172 // FIXME: OBJCGC: weak & strong
John McCall843dfcc2016-11-29 21:57:00 +00006173 return S;
Daniel Dunbar4932b362008-08-28 04:38:10 +00006174}
6175
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006176/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00006177/// Another legacy compatibility encoding: 32-bit longs are encoded as
6178/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006179/// 'i' or 'I' instead if encoding a struct field, or a pointer!
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006180void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00006181 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006182 if (const auto *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00006183 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006184 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00006185 else
Jay Foad39c79802011-01-12 09:06:06 +00006186 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006187 PointeeTy = IntTy;
6188 }
6189 }
6190}
6191
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00006192void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006193 const FieldDecl *Field,
6194 QualType *NotEncodedT) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00006195 // We follow the behavior of gcc, expanding structures which are
6196 // directly pointed to, and expanding embedded structures. Note that
6197 // these rules are sufficient to prevent recursive encoding of the
6198 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00006199 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006200 true /* outermost type */, false, false,
6201 false, false, false, NotEncodedT);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00006202}
6203
Joe Groff98ac7d22014-07-07 22:25:15 +00006204void ASTContext::getObjCEncodingForPropertyType(QualType T,
6205 std::string& S) const {
6206 // Encode result type.
6207 // GCC has some special rules regarding encoding of properties which
6208 // closely resembles encoding of ivars.
6209 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
6210 true /* outermost type */,
6211 true /* encoding property */);
6212}
6213
John McCall393a78d2012-12-20 02:45:14 +00006214static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
6215 BuiltinType::Kind kind) {
6216 switch (kind) {
David Chisnallb190a2c2010-06-04 01:10:52 +00006217 case BuiltinType::Void: return 'v';
6218 case BuiltinType::Bool: return 'B';
Richard Smith3a8244d2018-05-01 05:02:45 +00006219 case BuiltinType::Char8:
David Chisnallb190a2c2010-06-04 01:10:52 +00006220 case BuiltinType::Char_U:
6221 case BuiltinType::UChar: return 'C';
John McCall393a78d2012-12-20 02:45:14 +00006222 case BuiltinType::Char16:
David Chisnallb190a2c2010-06-04 01:10:52 +00006223 case BuiltinType::UShort: return 'S';
John McCall393a78d2012-12-20 02:45:14 +00006224 case BuiltinType::Char32:
David Chisnallb190a2c2010-06-04 01:10:52 +00006225 case BuiltinType::UInt: return 'I';
6226 case BuiltinType::ULong:
John McCall393a78d2012-12-20 02:45:14 +00006227 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00006228 case BuiltinType::UInt128: return 'T';
6229 case BuiltinType::ULongLong: return 'Q';
6230 case BuiltinType::Char_S:
6231 case BuiltinType::SChar: return 'c';
6232 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00006233 case BuiltinType::WChar_S:
6234 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00006235 case BuiltinType::Int: return 'i';
6236 case BuiltinType::Long:
John McCall393a78d2012-12-20 02:45:14 +00006237 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00006238 case BuiltinType::LongLong: return 'q';
6239 case BuiltinType::Int128: return 't';
6240 case BuiltinType::Float: return 'f';
6241 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00006242 case BuiltinType::LongDouble: return 'D';
John McCall393a78d2012-12-20 02:45:14 +00006243 case BuiltinType::NullPtr: return '*'; // like char*
6244
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00006245 case BuiltinType::Float16:
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00006246 case BuiltinType::Float128:
John McCall393a78d2012-12-20 02:45:14 +00006247 case BuiltinType::Half:
Leonard Chanf921d852018-06-04 16:07:52 +00006248 case BuiltinType::ShortAccum:
6249 case BuiltinType::Accum:
6250 case BuiltinType::LongAccum:
6251 case BuiltinType::UShortAccum:
6252 case BuiltinType::UAccum:
6253 case BuiltinType::ULongAccum:
John McCall393a78d2012-12-20 02:45:14 +00006254 // FIXME: potentially need @encodes for these!
6255 return ' ';
6256
6257 case BuiltinType::ObjCId:
6258 case BuiltinType::ObjCClass:
6259 case BuiltinType::ObjCSel:
6260 llvm_unreachable("@encoding ObjC primitive type");
6261
6262 // OpenCL and placeholder types don't need @encodings.
Alexey Bader954ba212016-04-08 13:40:33 +00006263#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6264 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00006265#include "clang/Basic/OpenCLImageTypes.def"
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006266 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00006267 case BuiltinType::OCLClkEvent:
6268 case BuiltinType::OCLQueue:
Alexey Bader9c8453f2015-09-15 11:18:52 +00006269 case BuiltinType::OCLReserveID:
Guy Benyei61054192013-02-07 10:55:47 +00006270 case BuiltinType::OCLSampler:
John McCall393a78d2012-12-20 02:45:14 +00006271 case BuiltinType::Dependent:
6272#define BUILTIN_TYPE(KIND, ID)
6273#define PLACEHOLDER_TYPE(KIND, ID) \
6274 case BuiltinType::KIND:
6275#include "clang/AST/BuiltinTypes.def"
6276 llvm_unreachable("invalid builtin type for @encode");
David Chisnallb190a2c2010-06-04 01:10:52 +00006277 }
David Blaikie5a6a0202013-01-09 17:48:41 +00006278 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnallb190a2c2010-06-04 01:10:52 +00006279}
6280
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006281static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
6282 EnumDecl *Enum = ET->getDecl();
6283
6284 // The encoding of an non-fixed enum type is always 'i', regardless of size.
6285 if (!Enum->isFixed())
6286 return 'i';
6287
6288 // The encoding of a fixed enum type matches its fixed underlying type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00006289 const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>();
John McCall393a78d2012-12-20 02:45:14 +00006290 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006291}
6292
Jay Foad39c79802011-01-12 09:06:06 +00006293static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00006294 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00006295 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00006296 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00006297 // The NeXT runtime encodes bit fields as b followed by the number of bits.
6298 // The GNU runtime requires more information; bitfields are encoded as b,
6299 // then the offset (in bits) of the first element, then the type of the
6300 // bitfield, then the size in bits. For example, in this structure:
6301 //
6302 // struct
6303 // {
6304 // int integer;
6305 // int flags:2;
6306 // };
6307 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
6308 // runtime, but b32i2 for the GNU runtime. The reason for this extra
6309 // information is not especially sensible, but we're stuck with it for
6310 // compatibility with GCC, although providing it breaks anything that
6311 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00006312 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
Akira Hatanaka4b1c4842017-06-27 04:34:04 +00006313 uint64_t Offset;
6314
6315 if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) {
6316 Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), nullptr,
6317 IVD);
6318 } else {
6319 const RecordDecl *RD = FD->getParent();
6320 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
6321 Offset = RL.getFieldOffset(FD->getFieldIndex());
6322 }
6323
6324 S += llvm::utostr(Offset);
6325
Eugene Zelenko7855e772018-04-03 00:11:50 +00006326 if (const auto *ET = T->getAs<EnumType>())
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006327 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall393a78d2012-12-20 02:45:14 +00006328 else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006329 const auto *BT = T->castAs<BuiltinType>();
John McCall393a78d2012-12-20 02:45:14 +00006330 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
6331 }
David Chisnallb190a2c2010-06-04 01:10:52 +00006332 }
Richard Smithcaf33902011-10-10 18:28:20 +00006333 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00006334}
6335
Daniel Dunbar07d07852009-10-18 21:17:35 +00006336// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00006337void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
6338 bool ExpandPointedToStructures,
6339 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00006340 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00006341 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006342 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006343 bool StructField,
6344 bool EncodeBlockParameters,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00006345 bool EncodeClassNames,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006346 bool EncodePointerToObjCTypedef,
6347 QualType *NotEncodedT) const {
John McCall393a78d2012-12-20 02:45:14 +00006348 CanQualType CT = getCanonicalType(T);
6349 switch (CT->getTypeClass()) {
6350 case Type::Builtin:
6351 case Type::Enum:
Chris Lattnere7cabb92009-07-13 00:10:46 +00006352 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00006353 return EncodeBitField(this, S, T, FD);
Eugene Zelenko7855e772018-04-03 00:11:50 +00006354 if (const auto *BT = dyn_cast<BuiltinType>(CT))
John McCall393a78d2012-12-20 02:45:14 +00006355 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
6356 else
6357 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnere7cabb92009-07-13 00:10:46 +00006358 return;
Mike Stump11289f42009-09-09 15:08:12 +00006359
John McCall393a78d2012-12-20 02:45:14 +00006360 case Type::Complex: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006361 const auto *CT = T->castAs<ComplexType>();
Anders Carlsson39b2e132009-04-09 21:55:45 +00006362 S += 'j';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006363 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, nullptr);
Chris Lattnere7cabb92009-07-13 00:10:46 +00006364 return;
6365 }
John McCall393a78d2012-12-20 02:45:14 +00006366
6367 case Type::Atomic: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006368 const auto *AT = T->castAs<AtomicType>();
John McCall393a78d2012-12-20 02:45:14 +00006369 S += 'A';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006370 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, nullptr);
John McCall393a78d2012-12-20 02:45:14 +00006371 return;
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00006372 }
John McCall393a78d2012-12-20 02:45:14 +00006373
6374 // encoding for pointer or reference types.
6375 case Type::Pointer:
6376 case Type::LValueReference:
6377 case Type::RValueReference: {
6378 QualType PointeeTy;
6379 if (isa<PointerType>(CT)) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006380 const auto *PT = T->castAs<PointerType>();
John McCall393a78d2012-12-20 02:45:14 +00006381 if (PT->isObjCSelType()) {
6382 S += ':';
6383 return;
6384 }
6385 PointeeTy = PT->getPointeeType();
6386 } else {
6387 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
6388 }
6389
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006390 bool isReadOnly = false;
6391 // For historical/compatibility reasons, the read-only qualifier of the
6392 // pointee gets emitted _before_ the '^'. The read-only qualifier of
6393 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00006394 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00006395 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006396 if (OutermostType && T.isConstQualified()) {
6397 isReadOnly = true;
6398 S += 'r';
6399 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00006400 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006401 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006402 while (P->getAs<PointerType>())
6403 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006404 if (P.isConstQualified()) {
6405 isReadOnly = true;
6406 S += 'r';
6407 }
6408 }
6409 if (isReadOnly) {
6410 // Another legacy compatibility encoding. Some ObjC qualifier and type
6411 // combinations need to be rearranged.
6412 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006413 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00006414 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006415 }
Mike Stump11289f42009-09-09 15:08:12 +00006416
Anders Carlssond8499822007-10-29 05:01:08 +00006417 if (PointeeTy->isCharType()) {
6418 // char pointer types should be encoded as '*' unless it is a
6419 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00006420 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00006421 S += '*';
6422 return;
6423 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00006424 } else if (const auto *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00006425 // GCC binary compat: Need to convert "struct objc_class *" to "#".
6426 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
6427 S += '#';
6428 return;
6429 }
6430 // GCC binary compat: Need to convert "struct objc_object *" to "@".
6431 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
6432 S += '@';
6433 return;
6434 }
6435 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00006436 }
Anders Carlssond8499822007-10-29 05:01:08 +00006437 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006438 getLegacyIntegralTypeEncoding(PointeeTy);
6439
Mike Stump11289f42009-09-09 15:08:12 +00006440 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006441 nullptr, false, false, false, false, false, false,
6442 NotEncodedT);
Chris Lattnere7cabb92009-07-13 00:10:46 +00006443 return;
6444 }
John McCall393a78d2012-12-20 02:45:14 +00006445
6446 case Type::ConstantArray:
6447 case Type::IncompleteArray:
6448 case Type::VariableArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006449 const auto *AT = cast<ArrayType>(CT);
John McCall393a78d2012-12-20 02:45:14 +00006450
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006451 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00006452 // Incomplete arrays are encoded as a pointer to the array element.
6453 S += '^';
6454
Mike Stump11289f42009-09-09 15:08:12 +00006455 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00006456 false, ExpandStructures, FD);
6457 } else {
6458 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00006459
Eugene Zelenko7855e772018-04-03 00:11:50 +00006460 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
Fariborz Jahanianf0dc11a2013-06-04 16:04:37 +00006461 S += llvm::utostr(CAT->getSize().getZExtValue());
6462 else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00006463 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006464 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
6465 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00006466 S += '0';
6467 }
Mike Stump11289f42009-09-09 15:08:12 +00006468
6469 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006470 false, ExpandStructures, FD,
6471 false, false, false, false, false, false,
6472 NotEncodedT);
Anders Carlssond05f44b2009-02-22 01:38:57 +00006473 S += ']';
6474 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006475 return;
6476 }
Mike Stump11289f42009-09-09 15:08:12 +00006477
John McCall393a78d2012-12-20 02:45:14 +00006478 case Type::FunctionNoProto:
6479 case Type::FunctionProto:
Anders Carlssondf4cc612007-10-30 00:06:20 +00006480 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00006481 return;
Mike Stump11289f42009-09-09 15:08:12 +00006482
John McCall393a78d2012-12-20 02:45:14 +00006483 case Type::Record: {
6484 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00006485 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00006486 // Anonymous structures print as '?'
6487 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
6488 S += II->getName();
Eugene Zelenko7855e772018-04-03 00:11:50 +00006489 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
Fariborz Jahanianc5158202010-05-07 00:28:49 +00006490 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00006491 llvm::raw_string_ostream OS(S);
Serge Pavlov03e672c2017-11-28 16:14:14 +00006492 printTemplateArgumentList(OS, TemplateArgs.asArray(),
6493 getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00006494 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00006495 } else {
6496 S += '?';
6497 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00006498 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00006499 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006500 if (!RDecl->isUnion()) {
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006501 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006502 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006503 for (const auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006504 if (FD) {
6505 S += '"';
6506 S += Field->getNameAsString();
6507 S += '"';
6508 }
Mike Stump11289f42009-09-09 15:08:12 +00006509
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006510 // Special case bit-fields.
6511 if (Field->isBitField()) {
6512 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006513 Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006514 } else {
6515 QualType qt = Field->getType();
6516 getLegacyIntegralTypeEncoding(qt);
6517 getObjCEncodingForTypeImpl(qt, S, false, true,
6518 FD, /*OutermostType*/false,
6519 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006520 /*StructField*/true,
6521 false, false, false, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006522 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00006523 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00006524 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00006525 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00006526 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00006527 return;
6528 }
Mike Stump11289f42009-09-09 15:08:12 +00006529
John McCall393a78d2012-12-20 02:45:14 +00006530 case Type::BlockPointer: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006531 const auto *BT = T->castAs<BlockPointerType>();
Steve Naroff49140cb2009-02-02 18:24:29 +00006532 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006533 if (EncodeBlockParameters) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006534 const auto *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006535
6536 S += '<';
6537 // Block return type
Alp Toker314cc812014-01-25 16:55:45 +00006538 getObjCEncodingForTypeImpl(
6539 FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures,
6540 FD, false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006541 false /* StructField */, EncodeBlockParameters, EncodeClassNames, false,
6542 NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006543 // Block self
6544 S += "@?";
6545 // Block parameters
Eugene Zelenko7855e772018-04-03 00:11:50 +00006546 if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00006547 for (const auto &I : FPT->param_types())
6548 getObjCEncodingForTypeImpl(
6549 I, S, ExpandPointedToStructures, ExpandStructures, FD,
6550 false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006551 false /* StructField */, EncodeBlockParameters, EncodeClassNames,
6552 false, NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006553 }
6554 S += '>';
6555 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006556 return;
6557 }
Mike Stump11289f42009-09-09 15:08:12 +00006558
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00006559 case Type::ObjCObject: {
6560 // hack to match legacy encoding of *id and *Class
6561 QualType Ty = getObjCObjectPointerType(CT);
6562 if (Ty->isObjCIdType()) {
6563 S += "{objc_object=}";
6564 return;
6565 }
6566 else if (Ty->isObjCClassType()) {
6567 S += "{objc_class=}";
6568 return;
6569 }
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00006570 // TODO: Double check to make sure this intentionally falls through.
Galina Kistanovaf87496d2017-06-03 06:31:42 +00006571 LLVM_FALLTHROUGH;
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00006572 }
6573
John McCall393a78d2012-12-20 02:45:14 +00006574 case Type::ObjCInterface: {
6575 // Ignore protocol qualifiers when mangling at this level.
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006576 // @encode(class_name)
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006577 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006578 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006579 S += OI->getObjCRuntimeNameAsString();
Akira Hatanakafd0fb202016-08-17 19:42:22 +00006580 if (ExpandStructures) {
6581 S += '=';
6582 SmallVector<const ObjCIvarDecl*, 32> Ivars;
6583 DeepCollectObjCIvars(OI, true, Ivars);
6584 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
George Burgess IV00f70bd2018-03-01 05:43:23 +00006585 const FieldDecl *Field = Ivars[i];
Akira Hatanakafd0fb202016-08-17 19:42:22 +00006586 if (Field->isBitField())
6587 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
6588 else
6589 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
6590 false, false, false, false, false,
6591 EncodePointerToObjCTypedef,
6592 NotEncodedT);
6593 }
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006594 }
6595 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00006596 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006597 }
Mike Stump11289f42009-09-09 15:08:12 +00006598
John McCall393a78d2012-12-20 02:45:14 +00006599 case Type::ObjCObjectPointer: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006600 const auto *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00006601 if (OPT->isObjCIdType()) {
6602 S += '@';
6603 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00006604 }
Mike Stump11289f42009-09-09 15:08:12 +00006605
Steve Narofff0c86112009-10-28 22:03:49 +00006606 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
6607 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
6608 // Since this is a binary compatibility issue, need to consult with runtime
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00006609 // folks. Fortunately, this is a *very* obscure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00006610 S += '#';
6611 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00006612 }
Mike Stump11289f42009-09-09 15:08:12 +00006613
Chris Lattnere7cabb92009-07-13 00:10:46 +00006614 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00006615 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00006616 ExpandPointedToStructures,
6617 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006618 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00006619 // Note that we do extended encoding of protocol qualifer list
6620 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00006621 S += '"';
Aaron Ballman83731462014-03-17 16:14:00 +00006622 for (const auto *I : OPT->quals()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00006623 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006624 S += I->getObjCRuntimeNameAsString();
Steve Naroff7cae42b2009-07-10 23:34:53 +00006625 S += '>';
6626 }
6627 S += '"';
6628 }
6629 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00006630 }
Mike Stump11289f42009-09-09 15:08:12 +00006631
Chris Lattnere7cabb92009-07-13 00:10:46 +00006632 QualType PointeeTy = OPT->getPointeeType();
6633 if (!EncodingProperty &&
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00006634 isa<TypedefType>(PointeeTy.getTypePtr()) &&
6635 !EncodePointerToObjCTypedef) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00006636 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00006637 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00006638 // {...};
6639 S += '^';
Fariborz Jahanian88890e72013-07-12 16:19:11 +00006640 if (FD && OPT->getInterfaceDecl()) {
Fariborz Jahanianc682ef52013-07-12 16:41:56 +00006641 // Prevent recursive encoding of fields in some rare cases.
Fariborz Jahanian88890e72013-07-12 16:19:11 +00006642 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
6643 SmallVector<const ObjCIvarDecl*, 32> Ivars;
6644 DeepCollectObjCIvars(OI, true, Ivars);
6645 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
George Burgess IV00f70bd2018-03-01 05:43:23 +00006646 if (Ivars[i] == FD) {
Fariborz Jahanian88890e72013-07-12 16:19:11 +00006647 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006648 S += OI->getObjCRuntimeNameAsString();
Fariborz Jahanian88890e72013-07-12 16:19:11 +00006649 S += '}';
6650 return;
6651 }
6652 }
6653 }
Mike Stump11289f42009-09-09 15:08:12 +00006654 getObjCEncodingForTypeImpl(PointeeTy, S,
6655 false, ExpandPointedToStructures,
Craig Topper36250ad2014-05-12 05:36:57 +00006656 nullptr,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00006657 false, false, false, false, false,
6658 /*EncodePointerToObjCTypedef*/true);
Steve Naroff7cae42b2009-07-10 23:34:53 +00006659 return;
6660 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006661
6662 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006663 if (OPT->getInterfaceDecl() &&
6664 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00006665 S += '"';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006666 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
Aaron Ballman83731462014-03-17 16:14:00 +00006667 for (const auto *I : OPT->quals()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00006668 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006669 S += I->getObjCRuntimeNameAsString();
Chris Lattnere7cabb92009-07-13 00:10:46 +00006670 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00006671 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006672 S += '"';
6673 }
6674 return;
6675 }
Mike Stump11289f42009-09-09 15:08:12 +00006676
John McCalla9e6e8d2010-05-17 23:56:34 +00006677 // gcc just blithely ignores member pointers.
John McCall393a78d2012-12-20 02:45:14 +00006678 // FIXME: we shoul do better than that. 'M' is available.
6679 case Type::MemberPointer:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006680 // This matches gcc's encoding, even though technically it is insufficient.
6681 //FIXME. We should do a better job than gcc.
John McCall393a78d2012-12-20 02:45:14 +00006682 case Type::Vector:
6683 case Type::ExtVector:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006684 // Until we have a coherent encoding of these three types, issue warning.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00006685 if (NotEncodedT)
6686 *NotEncodedT = T;
6687 return;
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006688
6689 // We could see an undeduced auto type here during error recovery.
6690 // Just ignore it.
Richard Smith27d807c2013-04-30 13:56:41 +00006691 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00006692 case Type::DeducedTemplateSpecialization:
Richard Smith27d807c2013-04-30 13:56:41 +00006693 return;
6694
Xiuli Pan9c14e282016-01-09 12:53:17 +00006695 case Type::Pipe:
John McCall393a78d2012-12-20 02:45:14 +00006696#define ABSTRACT_TYPE(KIND, BASE)
6697#define TYPE(KIND, BASE)
6698#define DEPENDENT_TYPE(KIND, BASE) \
6699 case Type::KIND:
6700#define NON_CANONICAL_TYPE(KIND, BASE) \
6701 case Type::KIND:
6702#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
6703 case Type::KIND:
6704#include "clang/AST/TypeNodes.def"
6705 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00006706 }
John McCall393a78d2012-12-20 02:45:14 +00006707 llvm_unreachable("bad type kind!");
Anders Carlssond8499822007-10-29 05:01:08 +00006708}
6709
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006710void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
6711 std::string &S,
6712 const FieldDecl *FD,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006713 bool includeVBases,
6714 QualType *NotEncodedT) const {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006715 assert(RDecl && "Expected non-null RecordDecl");
6716 assert(!RDecl->isUnion() && "Should not be called for unions");
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00006717 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006718 return;
6719
Eugene Zelenko7855e772018-04-03 00:11:50 +00006720 const auto *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006721 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
6722 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
6723
6724 if (CXXRec) {
Aaron Ballman574705e2014-03-13 15:41:46 +00006725 for (const auto &BI : CXXRec->bases()) {
6726 if (!BI.isVirtual()) {
6727 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006728 if (base->isEmpty())
6729 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00006730 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006731 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
6732 std::make_pair(offs, base));
6733 }
6734 }
6735 }
6736
6737 unsigned i = 0;
Hans Wennborga302cd92014-08-21 16:06:57 +00006738 for (auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006739 uint64_t offs = layout.getFieldOffset(i);
6740 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Hans Wennborga302cd92014-08-21 16:06:57 +00006741 std::make_pair(offs, Field));
6742 ++i;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006743 }
6744
6745 if (CXXRec && includeVBases) {
Aaron Ballman445a9392014-03-13 16:15:17 +00006746 for (const auto &BI : CXXRec->vbases()) {
6747 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006748 if (base->isEmpty())
6749 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00006750 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Eli Friedman1d24af82013-09-18 01:59:16 +00006751 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
6752 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00006753 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
6754 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006755 }
6756 }
6757
6758 CharUnits size;
6759 if (CXXRec) {
6760 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
6761 } else {
6762 size = layout.getSize();
6763 }
6764
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006765#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006766 uint64_t CurOffs = 0;
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006767#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006768 std::multimap<uint64_t, NamedDecl *>::iterator
6769 CurLayObj = FieldOrBaseOffsets.begin();
6770
Douglas Gregorf5d6c742012-04-27 22:30:01 +00006771 if (CXXRec && CXXRec->isDynamicClass() &&
6772 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006773 if (FD) {
6774 S += "\"_vptr$";
6775 std::string recname = CXXRec->getNameAsString();
6776 if (recname.empty()) recname = "?";
6777 S += recname;
6778 S += '"';
6779 }
6780 S += "^^?";
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006781#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006782 CurOffs += getTypeSize(VoidPtrTy);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006783#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006784 }
6785
6786 if (!RDecl->hasFlexibleArrayMember()) {
6787 // Mark the end of the structure.
6788 uint64_t offs = toBits(size);
6789 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Craig Topper36250ad2014-05-12 05:36:57 +00006790 std::make_pair(offs, nullptr));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006791 }
6792
6793 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006794#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006795 assert(CurOffs <= CurLayObj->first);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006796 if (CurOffs < CurLayObj->first) {
6797 uint64_t padding = CurLayObj->first - CurOffs;
6798 // FIXME: There doesn't seem to be a way to indicate in the encoding that
6799 // packing/alignment of members is different that normal, in which case
6800 // the encoding will be out-of-sync with the real layout.
6801 // If the runtime switches to just consider the size of types without
6802 // taking into account alignment, we could make padding explicit in the
6803 // encoding (e.g. using arrays of chars). The encoding strings would be
6804 // longer then though.
6805 CurOffs += padding;
6806 }
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006807#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006808
6809 NamedDecl *dcl = CurLayObj->second;
Craig Topper36250ad2014-05-12 05:36:57 +00006810 if (!dcl)
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006811 break; // reached end of structure.
6812
Eugene Zelenko7855e772018-04-03 00:11:50 +00006813 if (auto *base = dyn_cast<CXXRecordDecl>(dcl)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006814 // We expand the bases without their virtual bases since those are going
6815 // in the initial structure. Note that this differs from gcc which
6816 // expands virtual bases each time one is encountered in the hierarchy,
6817 // making the encoding type bigger than it really is.
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006818 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
6819 NotEncodedT);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006820 assert(!base->isEmpty());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006821#ifndef NDEBUG
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006822 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006823#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006824 } else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006825 const auto *field = cast<FieldDecl>(dcl);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006826 if (FD) {
6827 S += '"';
6828 S += field->getNameAsString();
6829 S += '"';
6830 }
6831
6832 if (field->isBitField()) {
6833 EncodeBitField(this, S, field->getType(), field);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006834#ifndef NDEBUG
Richard Smithcaf33902011-10-10 18:28:20 +00006835 CurOffs += field->getBitWidthValue(*this);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006836#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006837 } else {
6838 QualType qt = field->getType();
6839 getLegacyIntegralTypeEncoding(qt);
6840 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
6841 /*OutermostType*/false,
6842 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006843 /*StructField*/true,
6844 false, false, false, NotEncodedT);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006845#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006846 CurOffs += getTypeSize(field->getType());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006847#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006848 }
6849 }
6850 }
6851}
6852
Mike Stump11289f42009-09-09 15:08:12 +00006853void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00006854 std::string& S) const {
6855 if (QT & Decl::OBJC_TQ_In)
6856 S += 'n';
6857 if (QT & Decl::OBJC_TQ_Inout)
6858 S += 'N';
6859 if (QT & Decl::OBJC_TQ_Out)
6860 S += 'o';
6861 if (QT & Decl::OBJC_TQ_Bycopy)
6862 S += 'O';
6863 if (QT & Decl::OBJC_TQ_Byref)
6864 S += 'R';
6865 if (QT & Decl::OBJC_TQ_Oneway)
6866 S += 'V';
6867}
6868
Douglas Gregor3ea72692011-08-12 05:46:01 +00006869TypedefDecl *ASTContext::getObjCIdDecl() const {
6870 if (!ObjCIdDecl) {
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00006871 QualType T = getObjCObjectType(ObjCBuiltinIdTy, {}, {});
Douglas Gregor3ea72692011-08-12 05:46:01 +00006872 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00006873 ObjCIdDecl = buildImplicitTypedef(T, "id");
Douglas Gregor3ea72692011-08-12 05:46:01 +00006874 }
Douglas Gregor3ea72692011-08-12 05:46:01 +00006875 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00006876}
6877
Douglas Gregor52e02802011-08-12 06:17:30 +00006878TypedefDecl *ASTContext::getObjCSelDecl() const {
6879 if (!ObjCSelDecl) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006880 QualType T = getPointerType(ObjCBuiltinSelTy);
6881 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
Douglas Gregor52e02802011-08-12 06:17:30 +00006882 }
6883 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00006884}
6885
Douglas Gregor0a586182011-08-12 05:59:41 +00006886TypedefDecl *ASTContext::getObjCClassDecl() const {
6887 if (!ObjCClassDecl) {
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00006888 QualType T = getObjCObjectType(ObjCBuiltinClassTy, {}, {});
Douglas Gregor0a586182011-08-12 05:59:41 +00006889 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00006890 ObjCClassDecl = buildImplicitTypedef(T, "Class");
Douglas Gregor0a586182011-08-12 05:59:41 +00006891 }
Douglas Gregor0a586182011-08-12 05:59:41 +00006892 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00006893}
6894
Douglas Gregord53ae832012-01-17 18:09:05 +00006895ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
6896 if (!ObjCProtocolClassDecl) {
6897 ObjCProtocolClassDecl
6898 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
6899 SourceLocation(),
6900 &Idents.get("Protocol"),
Douglas Gregor85f3f952015-07-07 03:57:15 +00006901 /*typeParamList=*/nullptr,
Craig Topper36250ad2014-05-12 05:36:57 +00006902 /*PrevDecl=*/nullptr,
Douglas Gregord53ae832012-01-17 18:09:05 +00006903 SourceLocation(), true);
6904 }
6905
6906 return ObjCProtocolClassDecl;
6907}
6908
Meador Inge5d3fb222012-06-16 03:34:49 +00006909//===----------------------------------------------------------------------===//
6910// __builtin_va_list Construction Functions
6911//===----------------------------------------------------------------------===//
6912
Charles Davisc7d5c942015-09-17 20:55:33 +00006913static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context,
6914 StringRef Name) {
6915 // typedef char* __builtin[_ms]_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006916 QualType T = Context->getPointerType(Context->CharTy);
Charles Davisc7d5c942015-09-17 20:55:33 +00006917 return Context->buildImplicitTypedef(T, Name);
6918}
6919
6920static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
6921 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
6922}
6923
6924static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
6925 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006926}
6927
6928static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
6929 // typedef void* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006930 QualType T = Context->getPointerType(Context->VoidTy);
6931 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006932}
6933
Tim Northover9bb857a2013-01-31 12:13:10 +00006934static TypedefDecl *
6935CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006936 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00006937 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00006938 if (Context->getLangOpts().CPlusPlus) {
6939 // namespace std { struct __va_list {
6940 NamespaceDecl *NS;
6941 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6942 Context->getTranslationUnitDecl(),
Craig Topper36250ad2014-05-12 05:36:57 +00006943 /*Inline*/ false, SourceLocation(),
Tim Northover9bb857a2013-01-31 12:13:10 +00006944 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00006945 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00006946 NS->setImplicit();
Tim Northover9bb857a2013-01-31 12:13:10 +00006947 VaListTagDecl->setDeclContext(NS);
Tim Northover9bb857a2013-01-31 12:13:10 +00006948 }
6949
6950 VaListTagDecl->startDefinition();
6951
6952 const size_t NumFields = 5;
6953 QualType FieldTypes[NumFields];
6954 const char *FieldNames[NumFields];
6955
6956 // void *__stack;
6957 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
6958 FieldNames[0] = "__stack";
6959
6960 // void *__gr_top;
6961 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
6962 FieldNames[1] = "__gr_top";
6963
6964 // void *__vr_top;
6965 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6966 FieldNames[2] = "__vr_top";
6967
6968 // int __gr_offs;
6969 FieldTypes[3] = Context->IntTy;
6970 FieldNames[3] = "__gr_offs";
6971
6972 // int __vr_offs;
6973 FieldTypes[4] = Context->IntTy;
6974 FieldNames[4] = "__vr_offs";
6975
6976 // Create fields
6977 for (unsigned i = 0; i < NumFields; ++i) {
6978 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6979 VaListTagDecl,
6980 SourceLocation(),
6981 SourceLocation(),
6982 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006983 FieldTypes[i], /*TInfo=*/nullptr,
6984 /*BitWidth=*/nullptr,
Tim Northover9bb857a2013-01-31 12:13:10 +00006985 /*Mutable=*/false,
6986 ICIS_NoInit);
6987 Field->setAccess(AS_public);
6988 VaListTagDecl->addDecl(Field);
6989 }
6990 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006991 Context->VaListTagDecl = VaListTagDecl;
Tim Northover9bb857a2013-01-31 12:13:10 +00006992 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Tim Northover9bb857a2013-01-31 12:13:10 +00006993
6994 // } __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006995 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00006996}
6997
Meador Inge5d3fb222012-06-16 03:34:49 +00006998static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
6999 // typedef struct __va_list_tag {
7000 RecordDecl *VaListTagDecl;
7001
Alp Toker2dea15b2013-12-17 01:22:38 +00007002 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00007003 VaListTagDecl->startDefinition();
7004
7005 const size_t NumFields = 5;
7006 QualType FieldTypes[NumFields];
7007 const char *FieldNames[NumFields];
7008
7009 // unsigned char gpr;
7010 FieldTypes[0] = Context->UnsignedCharTy;
7011 FieldNames[0] = "gpr";
7012
7013 // unsigned char fpr;
7014 FieldTypes[1] = Context->UnsignedCharTy;
7015 FieldNames[1] = "fpr";
7016
7017 // unsigned short reserved;
7018 FieldTypes[2] = Context->UnsignedShortTy;
7019 FieldNames[2] = "reserved";
7020
7021 // void* overflow_arg_area;
7022 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
7023 FieldNames[3] = "overflow_arg_area";
7024
7025 // void* reg_save_area;
7026 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
7027 FieldNames[4] = "reg_save_area";
7028
7029 // Create fields
7030 for (unsigned i = 0; i < NumFields; ++i) {
7031 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
7032 SourceLocation(),
7033 SourceLocation(),
7034 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00007035 FieldTypes[i], /*TInfo=*/nullptr,
7036 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00007037 /*Mutable=*/false,
7038 ICIS_NoInit);
7039 Field->setAccess(AS_public);
7040 VaListTagDecl->addDecl(Field);
7041 }
7042 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00007043 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00007044 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
7045
7046 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00007047 TypedefDecl *VaListTagTypedefDecl =
7048 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
7049
Meador Inge5d3fb222012-06-16 03:34:49 +00007050 QualType VaListTagTypedefType =
7051 Context->getTypedefType(VaListTagTypedefDecl);
7052
7053 // typedef __va_list_tag __builtin_va_list[1];
7054 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
7055 QualType VaListTagArrayType
7056 = Context->getConstantArrayType(VaListTagTypedefType,
7057 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00007058 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007059}
7060
7061static TypedefDecl *
7062CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00007063 // struct __va_list_tag {
Meador Inge5d3fb222012-06-16 03:34:49 +00007064 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00007065 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00007066 VaListTagDecl->startDefinition();
7067
7068 const size_t NumFields = 4;
7069 QualType FieldTypes[NumFields];
7070 const char *FieldNames[NumFields];
7071
7072 // unsigned gp_offset;
7073 FieldTypes[0] = Context->UnsignedIntTy;
7074 FieldNames[0] = "gp_offset";
7075
7076 // unsigned fp_offset;
7077 FieldTypes[1] = Context->UnsignedIntTy;
7078 FieldNames[1] = "fp_offset";
7079
7080 // void* overflow_arg_area;
7081 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
7082 FieldNames[2] = "overflow_arg_area";
7083
7084 // void* reg_save_area;
7085 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
7086 FieldNames[3] = "reg_save_area";
7087
7088 // Create fields
7089 for (unsigned i = 0; i < NumFields; ++i) {
7090 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7091 VaListTagDecl,
7092 SourceLocation(),
7093 SourceLocation(),
7094 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00007095 FieldTypes[i], /*TInfo=*/nullptr,
7096 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00007097 /*Mutable=*/false,
7098 ICIS_NoInit);
7099 Field->setAccess(AS_public);
7100 VaListTagDecl->addDecl(Field);
7101 }
7102 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00007103 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00007104 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
7105
Richard Smith9b88a4c2015-07-27 05:40:23 +00007106 // };
Alp Toker56b5cc92013-12-15 10:36:26 +00007107
Richard Smith9b88a4c2015-07-27 05:40:23 +00007108 // typedef struct __va_list_tag __builtin_va_list[1];
Meador Inge5d3fb222012-06-16 03:34:49 +00007109 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00007110 QualType VaListTagArrayType =
7111 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00007112 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007113}
7114
7115static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
7116 // typedef int __builtin_va_list[4];
7117 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
Yaron Kerene0bcdd42016-10-08 06:45:10 +00007118 QualType IntArrayType =
7119 Context->getConstantArrayType(Context->IntTy, Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00007120 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007121}
7122
Logan Chien57086ce2012-10-10 06:56:20 +00007123static TypedefDecl *
7124CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00007125 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00007126 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00007127 if (Context->getLangOpts().CPlusPlus) {
7128 // namespace std { struct __va_list {
7129 NamespaceDecl *NS;
7130 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
7131 Context->getTranslationUnitDecl(),
7132 /*Inline*/false, SourceLocation(),
7133 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00007134 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00007135 NS->setImplicit();
Logan Chien57086ce2012-10-10 06:56:20 +00007136 VaListDecl->setDeclContext(NS);
Logan Chien57086ce2012-10-10 06:56:20 +00007137 }
7138
7139 VaListDecl->startDefinition();
7140
7141 // void * __ap;
7142 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7143 VaListDecl,
7144 SourceLocation(),
7145 SourceLocation(),
7146 &Context->Idents.get("__ap"),
7147 Context->getPointerType(Context->VoidTy),
Craig Topper36250ad2014-05-12 05:36:57 +00007148 /*TInfo=*/nullptr,
7149 /*BitWidth=*/nullptr,
Logan Chien57086ce2012-10-10 06:56:20 +00007150 /*Mutable=*/false,
7151 ICIS_NoInit);
7152 Field->setAccess(AS_public);
7153 VaListDecl->addDecl(Field);
7154
7155 // };
7156 VaListDecl->completeDefinition();
Oleg Ranevskyyb88d2472016-03-30 21:30:30 +00007157 Context->VaListTagDecl = VaListDecl;
Logan Chien57086ce2012-10-10 06:56:20 +00007158
7159 // typedef struct __va_list __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00007160 QualType T = Context->getRecordType(VaListDecl);
7161 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00007162}
7163
Ulrich Weigand47445072013-05-06 16:26:41 +00007164static TypedefDecl *
7165CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00007166 // struct __va_list_tag {
Ulrich Weigand47445072013-05-06 16:26:41 +00007167 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00007168 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00007169 VaListTagDecl->startDefinition();
7170
7171 const size_t NumFields = 4;
7172 QualType FieldTypes[NumFields];
7173 const char *FieldNames[NumFields];
7174
7175 // long __gpr;
7176 FieldTypes[0] = Context->LongTy;
7177 FieldNames[0] = "__gpr";
7178
7179 // long __fpr;
7180 FieldTypes[1] = Context->LongTy;
7181 FieldNames[1] = "__fpr";
7182
7183 // void *__overflow_arg_area;
7184 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
7185 FieldNames[2] = "__overflow_arg_area";
7186
7187 // void *__reg_save_area;
7188 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
7189 FieldNames[3] = "__reg_save_area";
7190
7191 // Create fields
7192 for (unsigned i = 0; i < NumFields; ++i) {
7193 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7194 VaListTagDecl,
7195 SourceLocation(),
7196 SourceLocation(),
7197 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00007198 FieldTypes[i], /*TInfo=*/nullptr,
7199 /*BitWidth=*/nullptr,
Ulrich Weigand47445072013-05-06 16:26:41 +00007200 /*Mutable=*/false,
7201 ICIS_NoInit);
7202 Field->setAccess(AS_public);
7203 VaListTagDecl->addDecl(Field);
7204 }
7205 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00007206 Context->VaListTagDecl = VaListTagDecl;
Ulrich Weigand47445072013-05-06 16:26:41 +00007207 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Ulrich Weigand47445072013-05-06 16:26:41 +00007208
Richard Smith9b88a4c2015-07-27 05:40:23 +00007209 // };
Ulrich Weigand47445072013-05-06 16:26:41 +00007210
7211 // typedef __va_list_tag __builtin_va_list[1];
7212 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00007213 QualType VaListTagArrayType =
7214 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Ulrich Weigand47445072013-05-06 16:26:41 +00007215
Alp Toker56b5cc92013-12-15 10:36:26 +00007216 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Ulrich Weigand47445072013-05-06 16:26:41 +00007217}
7218
Meador Inge5d3fb222012-06-16 03:34:49 +00007219static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
7220 TargetInfo::BuiltinVaListKind Kind) {
7221 switch (Kind) {
7222 case TargetInfo::CharPtrBuiltinVaList:
7223 return CreateCharPtrBuiltinVaListDecl(Context);
7224 case TargetInfo::VoidPtrBuiltinVaList:
7225 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northover9bb857a2013-01-31 12:13:10 +00007226 case TargetInfo::AArch64ABIBuiltinVaList:
7227 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00007228 case TargetInfo::PowerABIBuiltinVaList:
7229 return CreatePowerABIBuiltinVaListDecl(Context);
7230 case TargetInfo::X86_64ABIBuiltinVaList:
7231 return CreateX86_64ABIBuiltinVaListDecl(Context);
7232 case TargetInfo::PNaClABIBuiltinVaList:
7233 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00007234 case TargetInfo::AAPCSABIBuiltinVaList:
7235 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigand47445072013-05-06 16:26:41 +00007236 case TargetInfo::SystemZBuiltinVaList:
7237 return CreateSystemZBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00007238 }
7239
7240 llvm_unreachable("Unhandled __builtin_va_list type kind");
7241}
7242
7243TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00007244 if (!BuiltinVaListDecl) {
Meador Inge5d3fb222012-06-16 03:34:49 +00007245 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
Alp Toker56b5cc92013-12-15 10:36:26 +00007246 assert(BuiltinVaListDecl->isImplicit());
7247 }
Meador Inge5d3fb222012-06-16 03:34:49 +00007248
7249 return BuiltinVaListDecl;
7250}
7251
Richard Smith9b88a4c2015-07-27 05:40:23 +00007252Decl *ASTContext::getVaListTagDecl() const {
7253 // Force the creation of VaListTagDecl by building the __builtin_va_list
Meador Ingecfb60902012-07-01 15:57:25 +00007254 // declaration.
Richard Smith9b88a4c2015-07-27 05:40:23 +00007255 if (!VaListTagDecl)
7256 (void)getBuiltinVaListDecl();
Meador Ingecfb60902012-07-01 15:57:25 +00007257
Richard Smith9b88a4c2015-07-27 05:40:23 +00007258 return VaListTagDecl;
Meador Ingecfb60902012-07-01 15:57:25 +00007259}
7260
Charles Davisc7d5c942015-09-17 20:55:33 +00007261TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const {
7262 if (!BuiltinMSVaListDecl)
7263 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
7264
7265 return BuiltinMSVaListDecl;
7266}
7267
Erich Keane41af9712018-04-16 21:30:08 +00007268bool ASTContext::canBuiltinBeRedeclared(const FunctionDecl *FD) const {
7269 return BuiltinInfo.canBeRedeclared(FD->getBuiltinID());
7270}
7271
Ted Kremenek1b0ea822008-01-07 19:49:32 +00007272void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00007273 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00007274 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00007275
Ted Kremenek1b0ea822008-01-07 19:49:32 +00007276 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00007277}
7278
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007279/// Retrieve the template name that corresponds to a non-empty
John McCalld28ae272009-12-02 08:04:21 +00007280/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00007281TemplateName
7282ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
7283 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00007284 unsigned size = End - Begin;
7285 assert(size > 1 && "set is not overloaded!");
7286
7287 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
7288 size * sizeof(FunctionTemplateDecl*));
Eugene Zelenko7855e772018-04-03 00:11:50 +00007289 auto *OT = new (memory) OverloadedTemplateStorage(size);
John McCalld28ae272009-12-02 08:04:21 +00007290
7291 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00007292 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00007293 NamedDecl *D = *I;
7294 assert(isa<FunctionTemplateDecl>(D) ||
7295 (isa<UsingShadowDecl>(D) &&
7296 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
7297 *Storage++ = D;
7298 }
7299
7300 return TemplateName(OT);
7301}
7302
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007303/// Retrieve the template name that represents a qualified
Douglas Gregordc572a32009-03-30 22:58:21 +00007304/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00007305TemplateName
7306ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
7307 bool TemplateKeyword,
7308 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00007309 assert(NNS && "Missing nested-name-specifier in qualified template name");
7310
Douglas Gregorc42075a2010-02-04 18:10:26 +00007311 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00007312 llvm::FoldingSetNodeID ID;
7313 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
7314
Craig Topper36250ad2014-05-12 05:36:57 +00007315 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00007316 QualifiedTemplateName *QTN =
7317 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7318 if (!QTN) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007319 QTN = new (*this, alignof(QualifiedTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007320 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00007321 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
7322 }
7323
7324 return TemplateName(QTN);
7325}
7326
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007327/// Retrieve the template name that represents a dependent
Douglas Gregordc572a32009-03-30 22:58:21 +00007328/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00007329TemplateName
7330ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
7331 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00007332 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00007333 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00007334
7335 llvm::FoldingSetNodeID ID;
7336 DependentTemplateName::Profile(ID, NNS, Name);
7337
Craig Topper36250ad2014-05-12 05:36:57 +00007338 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00007339 DependentTemplateName *QTN =
7340 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7341
7342 if (QTN)
7343 return TemplateName(QTN);
7344
7345 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
7346 if (CanonNNS == NNS) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007347 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007348 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00007349 } else {
7350 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007351 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007352 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00007353 DependentTemplateName *CheckQTN =
7354 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7355 assert(!CheckQTN && "Dependent type name canonicalization broken");
7356 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00007357 }
7358
7359 DependentTemplateNames.InsertNode(QTN, InsertPos);
7360 return TemplateName(QTN);
7361}
7362
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007363/// Retrieve the template name that represents a dependent
Douglas Gregor71395fa2009-11-04 00:56:37 +00007364/// template name such as \c MetaFun::template operator+.
7365TemplateName
7366ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00007367 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00007368 assert((!NNS || NNS->isDependent()) &&
7369 "Nested name specifier must be dependent");
7370
7371 llvm::FoldingSetNodeID ID;
7372 DependentTemplateName::Profile(ID, NNS, Operator);
Craig Topper36250ad2014-05-12 05:36:57 +00007373
7374 void *InsertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00007375 DependentTemplateName *QTN
7376 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00007377
7378 if (QTN)
7379 return TemplateName(QTN);
7380
7381 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
7382 if (CanonNNS == NNS) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007383 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007384 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00007385 } else {
7386 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007387 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007388 DependentTemplateName(NNS, Operator, Canon);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007389
Douglas Gregorc42075a2010-02-04 18:10:26 +00007390 DependentTemplateName *CheckQTN
7391 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7392 assert(!CheckQTN && "Dependent template name canonicalization broken");
7393 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00007394 }
7395
7396 DependentTemplateNames.InsertNode(QTN, InsertPos);
7397 return TemplateName(QTN);
7398}
7399
Douglas Gregor5590be02011-01-15 06:45:20 +00007400TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00007401ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
7402 TemplateName replacement) const {
7403 llvm::FoldingSetNodeID ID;
7404 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00007405
7406 void *insertPos = nullptr;
John McCalld9dfe3a2011-06-30 08:33:18 +00007407 SubstTemplateTemplateParmStorage *subst
7408 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
7409
7410 if (!subst) {
7411 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
7412 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
7413 }
7414
7415 return TemplateName(subst);
7416}
7417
7418TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00007419ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
7420 const TemplateArgument &ArgPack) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00007421 auto &Self = const_cast<ASTContext &>(*this);
Douglas Gregor5590be02011-01-15 06:45:20 +00007422 llvm::FoldingSetNodeID ID;
7423 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00007424
7425 void *InsertPos = nullptr;
Douglas Gregor5590be02011-01-15 06:45:20 +00007426 SubstTemplateTemplateParmPackStorage *Subst
7427 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
7428
7429 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00007430 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00007431 ArgPack.pack_size(),
7432 ArgPack.pack_begin());
7433 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
7434 }
7435
7436 return TemplateName(Subst);
7437}
7438
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007439/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00007440/// TargetInfo, produce the corresponding type. The unsigned @p Type
7441/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00007442CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007443 switch (Type) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00007444 case TargetInfo::NoInt: return {};
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00007445 case TargetInfo::SignedChar: return SignedCharTy;
7446 case TargetInfo::UnsignedChar: return UnsignedCharTy;
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007447 case TargetInfo::SignedShort: return ShortTy;
7448 case TargetInfo::UnsignedShort: return UnsignedShortTy;
7449 case TargetInfo::SignedInt: return IntTy;
7450 case TargetInfo::UnsignedInt: return UnsignedIntTy;
7451 case TargetInfo::SignedLong: return LongTy;
7452 case TargetInfo::UnsignedLong: return UnsignedLongTy;
7453 case TargetInfo::SignedLongLong: return LongLongTy;
7454 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
7455 }
7456
David Blaikie83d382b2011-09-23 05:06:16 +00007457 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007458}
Ted Kremenek77c51b22008-07-24 23:58:27 +00007459
7460//===----------------------------------------------------------------------===//
7461// Type Predicates.
7462//===----------------------------------------------------------------------===//
7463
Fariborz Jahanian96207692009-02-18 21:49:28 +00007464/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
7465/// garbage collection attribute.
7466///
John McCall553d45a2011-01-12 00:34:59 +00007467Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007468 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00007469 return Qualifiers::GCNone;
7470
David Blaikiebbafb8a2012-03-11 07:00:24 +00007471 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00007472 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
7473
7474 // Default behaviour under objective-C's gc is for ObjC pointers
7475 // (or pointers to them) be treated as though they were declared
7476 // as __strong.
7477 if (GCAttrs == Qualifiers::GCNone) {
7478 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
7479 return Qualifiers::Strong;
7480 else if (Ty->isPointerType())
7481 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
7482 } else {
7483 // It's not valid to set GC attributes on anything that isn't a
7484 // pointer.
7485#ifndef NDEBUG
7486 QualType CT = Ty->getCanonicalTypeInternal();
Eugene Zelenko7855e772018-04-03 00:11:50 +00007487 while (const auto *AT = dyn_cast<ArrayType>(CT))
John McCall553d45a2011-01-12 00:34:59 +00007488 CT = AT->getElementType();
7489 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
7490#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00007491 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00007492 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00007493}
7494
Chris Lattner49af6a42008-04-07 06:51:04 +00007495//===----------------------------------------------------------------------===//
7496// Type Compatibility Testing
7497//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00007498
Mike Stump11289f42009-09-09 15:08:12 +00007499/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00007500/// compatible.
7501static bool areCompatVectorTypes(const VectorType *LHS,
7502 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00007503 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00007504 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00007505 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00007506}
7507
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007508bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
7509 QualType SecondVec) {
7510 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
7511 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
7512
7513 if (hasSameUnqualifiedType(FirstVec, SecondVec))
7514 return true;
7515
Bob Wilsone6aeebb2010-11-12 17:24:54 +00007516 // Treat Neon vector types and most AltiVec vector types as if they are the
7517 // equivalent GCC vector types.
Eugene Zelenko7855e772018-04-03 00:11:50 +00007518 const auto *First = FirstVec->getAs<VectorType>();
7519 const auto *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00007520 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007521 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00007522 First->getVectorKind() != VectorType::AltiVecPixel &&
7523 First->getVectorKind() != VectorType::AltiVecBool &&
7524 Second->getVectorKind() != VectorType::AltiVecPixel &&
7525 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007526 return true;
7527
7528 return false;
7529}
7530
Steve Naroff8e6aee52009-07-23 01:01:38 +00007531//===----------------------------------------------------------------------===//
7532// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
7533//===----------------------------------------------------------------------===//
7534
7535/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
7536/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00007537bool
7538ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
7539 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00007540 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00007541 return true;
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00007542 for (auto *PI : rProto->protocols())
7543 if (ProtocolCompatibleWithProtocol(lProto, PI))
Steve Naroff8e6aee52009-07-23 01:01:38 +00007544 return true;
7545 return false;
7546}
7547
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00007548/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
7549/// Class<pr1, ...>.
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007550bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
7551 QualType rhs) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00007552 const auto *lhsQID = lhs->getAs<ObjCObjectPointerType>();
7553 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00007554 assert((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007555
Aaron Ballman83731462014-03-17 16:14:00 +00007556 for (auto *lhsProto : lhsQID->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007557 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00007558 for (auto *rhsProto : rhsOPT->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007559 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
7560 match = true;
7561 break;
7562 }
7563 }
7564 if (!match)
7565 return false;
7566 }
7567 return true;
7568}
7569
Steve Naroff8e6aee52009-07-23 01:01:38 +00007570/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
7571/// ObjCQualifiedIDType.
7572bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
7573 bool compare) {
7574 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00007575 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00007576 lhs->isObjCIdType() || lhs->isObjCClassType())
7577 return true;
Mike Stump11289f42009-09-09 15:08:12 +00007578 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00007579 rhs->isObjCIdType() || rhs->isObjCClassType())
7580 return true;
7581
7582 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00007583 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00007584
Steve Naroff8e6aee52009-07-23 01:01:38 +00007585 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00007586
Steve Naroff8e6aee52009-07-23 01:01:38 +00007587 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00007588 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00007589 // make sure we check the class hierarchy.
7590 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00007591 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007592 // when comparing an id<P> on lhs with a static type on rhs,
7593 // see if static class implements all of id's protocols, directly or
7594 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00007595 if (!rhsID->ClassImplementsProtocol(I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00007596 return false;
7597 }
7598 }
7599 // If there are no qualifiers and no interface, we have an 'id'.
7600 return true;
7601 }
Mike Stump11289f42009-09-09 15:08:12 +00007602 // Both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00007603 for (auto *lhsProto : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007604 bool match = false;
7605
7606 // when comparing an id<P> on lhs with a static type on rhs,
7607 // see if static class implements all of id's protocols, directly or
7608 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00007609 for (auto *rhsProto : rhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007610 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7611 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7612 match = true;
7613 break;
7614 }
7615 }
Mike Stump11289f42009-09-09 15:08:12 +00007616 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00007617 // make sure we check the class hierarchy.
7618 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00007619 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007620 // when comparing an id<P> on lhs with a static type on rhs,
7621 // see if static class implements all of id's protocols, directly or
7622 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00007623 if (rhsID->ClassImplementsProtocol(I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007624 match = true;
7625 break;
7626 }
7627 }
7628 }
7629 if (!match)
7630 return false;
7631 }
Mike Stump11289f42009-09-09 15:08:12 +00007632
Steve Naroff8e6aee52009-07-23 01:01:38 +00007633 return true;
7634 }
Mike Stump11289f42009-09-09 15:08:12 +00007635
Steve Naroff8e6aee52009-07-23 01:01:38 +00007636 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
7637 assert(rhsQID && "One of the LHS/RHS should be id<x>");
7638
Mike Stump11289f42009-09-09 15:08:12 +00007639 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00007640 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007641 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00007642 for (auto *lhsProto : lhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007643 bool match = false;
7644
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007645 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00007646 // see if static class implements all of id's protocols, directly or
7647 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007648 // First, lhs protocols in the qualifier list must be found, direct
7649 // or indirect in rhs's qualifier list or it is a mismatch.
Aaron Ballman83731462014-03-17 16:14:00 +00007650 for (auto *rhsProto : rhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007651 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7652 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7653 match = true;
7654 break;
7655 }
7656 }
7657 if (!match)
7658 return false;
7659 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007660
7661 // Static class's protocols, or its super class or category protocols
7662 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
7663 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
7664 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
7665 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
7666 // This is rather dubious but matches gcc's behavior. If lhs has
7667 // no type qualifier and its class has no static protocol(s)
7668 // assume that it is mismatch.
7669 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
7670 return false;
Aaron Ballman83731462014-03-17 16:14:00 +00007671 for (auto *lhsProto : LHSInheritedProtocols) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007672 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00007673 for (auto *rhsProto : rhsQID->quals()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007674 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7675 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7676 match = true;
7677 break;
7678 }
7679 }
7680 if (!match)
7681 return false;
7682 }
7683 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00007684 return true;
7685 }
7686 return false;
7687}
7688
Eli Friedman47f77112008-08-22 00:56:42 +00007689/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00007690/// compatible for assignment from RHS to LHS. This handles validation of any
7691/// protocol qualifiers on the LHS or RHS.
Steve Naroff7cae42b2009-07-10 23:34:53 +00007692bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
7693 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00007694 const ObjCObjectType* LHS = LHSOPT->getObjectType();
7695 const ObjCObjectType* RHS = RHSOPT->getObjectType();
7696
Steve Naroff1329fa02009-07-15 18:40:39 +00007697 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00007698 if (LHS->isObjCUnqualifiedIdOrClass() ||
7699 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00007700 return true;
7701
Douglas Gregorab209d82015-07-07 03:58:42 +00007702 // Function object that propagates a successful result or handles
7703 // __kindof types.
7704 auto finish = [&](bool succeeded) -> bool {
7705 if (succeeded)
7706 return true;
7707
7708 if (!RHS->isKindOfType())
7709 return false;
7710
7711 // Strip off __kindof and protocol qualifiers, then check whether
7712 // we can assign the other way.
7713 return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this),
7714 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
7715 };
7716
7717 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
7718 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
7719 QualType(RHSOPT,0),
7720 false));
7721 }
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007722
Douglas Gregorab209d82015-07-07 03:58:42 +00007723 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
7724 return finish(ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
7725 QualType(RHSOPT,0)));
7726 }
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007727
John McCall8b07ec22010-05-15 11:32:37 +00007728 // If we have 2 user-defined types, fall into that path.
Douglas Gregorab209d82015-07-07 03:58:42 +00007729 if (LHS->getInterface() && RHS->getInterface()) {
7730 return finish(canAssignObjCInterfaces(LHS, RHS));
7731 }
Mike Stump11289f42009-09-09 15:08:12 +00007732
Steve Naroff8e6aee52009-07-23 01:01:38 +00007733 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00007734}
7735
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007736/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00007737/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007738/// arguments in block literals. When passed as arguments, passing 'A*' where
7739/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
7740/// not OK. For the return type, the opposite is not OK.
7741bool ASTContext::canAssignObjCInterfacesInBlockPointer(
7742 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007743 const ObjCObjectPointerType *RHSOPT,
7744 bool BlockReturnType) {
Douglas Gregorab209d82015-07-07 03:58:42 +00007745
7746 // Function object that propagates a successful result or handles
7747 // __kindof types.
7748 auto finish = [&](bool succeeded) -> bool {
7749 if (succeeded)
7750 return true;
7751
7752 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
7753 if (!Expected->isKindOfType())
7754 return false;
7755
7756 // Strip off __kindof and protocol qualifiers, then check whether
7757 // we can assign the other way.
7758 return canAssignObjCInterfacesInBlockPointer(
7759 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
7760 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
7761 BlockReturnType);
7762 };
7763
Fariborz Jahanian440a6832010-04-06 17:23:39 +00007764 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007765 return true;
7766
7767 if (LHSOPT->isObjCBuiltinType()) {
Douglas Gregorab209d82015-07-07 03:58:42 +00007768 return finish(RHSOPT->isObjCBuiltinType() ||
7769 RHSOPT->isObjCQualifiedIdType());
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007770 }
7771
Fariborz Jahanian440a6832010-04-06 17:23:39 +00007772 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Douglas Gregorab209d82015-07-07 03:58:42 +00007773 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
7774 QualType(RHSOPT,0),
7775 false));
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007776
7777 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
7778 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
7779 if (LHS && RHS) { // We have 2 user-defined types.
7780 if (LHS != RHS) {
7781 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00007782 return finish(BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007783 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00007784 return finish(!BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007785 }
7786 else
7787 return true;
7788 }
7789 return false;
7790}
7791
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007792/// Comparison routine for Objective-C protocols to be used with
7793/// llvm::array_pod_sort.
7794static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
7795 ObjCProtocolDecl * const *rhs) {
7796 return (*lhs)->getName().compare((*rhs)->getName());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007797}
7798
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007799/// getIntersectionOfProtocols - This routine finds the intersection of set
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007800/// of protocols inherited from two distinct objective-c pointer objects with
7801/// the given common base.
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007802/// It is used to build composite qualifier list of the composite type of
7803/// the conditional expression involving two objective-c pointer objects.
7804static
7805void getIntersectionOfProtocols(ASTContext &Context,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007806 const ObjCInterfaceDecl *CommonBase,
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007807 const ObjCObjectPointerType *LHSOPT,
7808 const ObjCObjectPointerType *RHSOPT,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007809 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007810
John McCall8b07ec22010-05-15 11:32:37 +00007811 const ObjCObjectType* LHS = LHSOPT->getObjectType();
7812 const ObjCObjectType* RHS = RHSOPT->getObjectType();
7813 assert(LHS->getInterface() && "LHS must have an interface base");
7814 assert(RHS->getInterface() && "RHS must have an interface base");
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007815
7816 // Add all of the protocols for the LHS.
7817 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
7818
7819 // Start with the protocol qualifiers.
7820 for (auto proto : LHS->quals()) {
7821 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007822 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007823
7824 // Also add the protocols associated with the LHS interface.
7825 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
7826
7827 // Add all of the protocls for the RHS.
7828 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
7829
7830 // Start with the protocol qualifiers.
7831 for (auto proto : RHS->quals()) {
7832 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007833 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007834
7835 // Also add the protocols associated with the RHS interface.
7836 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
7837
7838 // Compute the intersection of the collected protocol sets.
7839 for (auto proto : LHSProtocolSet) {
7840 if (RHSProtocolSet.count(proto))
7841 IntersectionSet.push_back(proto);
7842 }
7843
7844 // Compute the set of protocols that is implied by either the common type or
7845 // the protocols within the intersection.
7846 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
7847 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
7848
7849 // Remove any implied protocols from the list of inherited protocols.
7850 if (!ImpliedProtocols.empty()) {
7851 IntersectionSet.erase(
7852 std::remove_if(IntersectionSet.begin(),
7853 IntersectionSet.end(),
7854 [&](ObjCProtocolDecl *proto) -> bool {
7855 return ImpliedProtocols.count(proto) > 0;
7856 }),
7857 IntersectionSet.end());
7858 }
7859
7860 // Sort the remaining protocols by name.
7861 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
7862 compareObjCProtocolsByName);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007863}
7864
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007865/// Determine whether the first type is a subtype of the second.
7866static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
7867 QualType rhs) {
7868 // Common case: two object pointers.
Eugene Zelenko7855e772018-04-03 00:11:50 +00007869 const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
7870 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007871 if (lhsOPT && rhsOPT)
7872 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
7873
7874 // Two block pointers.
Eugene Zelenko7855e772018-04-03 00:11:50 +00007875 const auto *lhsBlock = lhs->getAs<BlockPointerType>();
7876 const auto *rhsBlock = rhs->getAs<BlockPointerType>();
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007877 if (lhsBlock && rhsBlock)
7878 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
7879
7880 // If either is an unqualified 'id' and the other is a block, it's
7881 // acceptable.
7882 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
7883 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
7884 return true;
7885
7886 return false;
7887}
7888
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007889// Check that the given Objective-C type argument lists are equivalent.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007890static bool sameObjCTypeArgs(ASTContext &ctx,
7891 const ObjCInterfaceDecl *iface,
7892 ArrayRef<QualType> lhsArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00007893 ArrayRef<QualType> rhsArgs,
7894 bool stripKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007895 if (lhsArgs.size() != rhsArgs.size())
7896 return false;
7897
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007898 ObjCTypeParamList *typeParams = iface->getTypeParamList();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007899 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007900 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
7901 continue;
7902
7903 switch (typeParams->begin()[i]->getVariance()) {
7904 case ObjCTypeParamVariance::Invariant:
Douglas Gregorab209d82015-07-07 03:58:42 +00007905 if (!stripKindOf ||
7906 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
7907 rhsArgs[i].stripObjCKindOfType(ctx))) {
7908 return false;
7909 }
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007910 break;
7911
7912 case ObjCTypeParamVariance::Covariant:
7913 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
7914 return false;
7915 break;
7916
7917 case ObjCTypeParamVariance::Contravariant:
7918 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
7919 return false;
7920 break;
Douglas Gregorab209d82015-07-07 03:58:42 +00007921 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007922 }
7923
7924 return true;
7925}
7926
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007927QualType ASTContext::areCommonBaseCompatible(
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007928 const ObjCObjectPointerType *Lptr,
7929 const ObjCObjectPointerType *Rptr) {
John McCall8b07ec22010-05-15 11:32:37 +00007930 const ObjCObjectType *LHS = Lptr->getObjectType();
7931 const ObjCObjectType *RHS = Rptr->getObjectType();
7932 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
7933 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007934
7935 if (!LDecl || !RDecl)
Eugene Zelenko7855e772018-04-03 00:11:50 +00007936 return {};
Douglas Gregore83b9562015-07-07 03:57:53 +00007937
Manman Renc46f7d12016-05-06 19:35:02 +00007938 // When either LHS or RHS is a kindof type, we should return a kindof type.
7939 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
7940 // kindof(A).
7941 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
7942
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007943 // Follow the left-hand side up the class hierarchy until we either hit a
7944 // root or find the RHS. Record the ancestors in case we don't find it.
7945 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
7946 LHSAncestors;
7947 while (true) {
7948 // Record this ancestor. We'll need this if the common type isn't in the
7949 // path from the LHS to the root.
7950 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
Douglas Gregore83b9562015-07-07 03:57:53 +00007951
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007952 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
7953 // Get the type arguments.
7954 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
7955 bool anyChanges = false;
7956 if (LHS->isSpecialized() && RHS->isSpecialized()) {
7957 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007958 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7959 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007960 /*stripKindOf=*/true))
Eugene Zelenko7855e772018-04-03 00:11:50 +00007961 return {};
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007962 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7963 // If only one has type arguments, the result will not have type
7964 // arguments.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00007965 LHSTypeArgs = {};
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007966 anyChanges = true;
7967 }
7968
7969 // Compute the intersection of protocols.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007970 SmallVector<ObjCProtocolDecl *, 8> Protocols;
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007971 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
7972 Protocols);
John McCall8b07ec22010-05-15 11:32:37 +00007973 if (!Protocols.empty())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007974 anyChanges = true;
7975
7976 // If anything in the LHS will have changed, build a new result type.
Manman Renc46f7d12016-05-06 19:35:02 +00007977 // If we need to return a kindof type but LHS is not a kindof type, we
7978 // build a new result type.
7979 if (anyChanges || LHS->isKindOfType() != anyKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007980 QualType Result = getObjCInterfaceType(LHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00007981 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
Manman Renc46f7d12016-05-06 19:35:02 +00007982 anyKindOf || LHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007983 return getObjCObjectPointerType(Result);
7984 }
7985
7986 return getObjCObjectPointerType(QualType(LHS, 0));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007987 }
Douglas Gregore83b9562015-07-07 03:57:53 +00007988
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007989 // Find the superclass.
Douglas Gregore83b9562015-07-07 03:57:53 +00007990 QualType LHSSuperType = LHS->getSuperClassType();
7991 if (LHSSuperType.isNull())
7992 break;
7993
7994 LHS = LHSSuperType->castAs<ObjCObjectType>();
7995 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007996
7997 // We didn't find anything by following the LHS to its root; now check
7998 // the RHS against the cached set of ancestors.
7999 while (true) {
8000 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
8001 if (KnownLHS != LHSAncestors.end()) {
8002 LHS = KnownLHS->second;
8003
8004 // Get the type arguments.
8005 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
8006 bool anyChanges = false;
8007 if (LHS->isSpecialized() && RHS->isSpecialized()) {
8008 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008009 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
8010 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00008011 /*stripKindOf=*/true))
Eugene Zelenko7855e772018-04-03 00:11:50 +00008012 return {};
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008013 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
8014 // If only one has type arguments, the result will not have type
8015 // arguments.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00008016 RHSTypeArgs = {};
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008017 anyChanges = true;
8018 }
8019
8020 // Compute the intersection of protocols.
8021 SmallVector<ObjCProtocolDecl *, 8> Protocols;
8022 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
8023 Protocols);
8024 if (!Protocols.empty())
8025 anyChanges = true;
8026
Manman Renc46f7d12016-05-06 19:35:02 +00008027 // If we need to return a kindof type but RHS is not a kindof type, we
8028 // build a new result type.
8029 if (anyChanges || RHS->isKindOfType() != anyKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008030 QualType Result = getObjCInterfaceType(RHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00008031 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
Manman Renc46f7d12016-05-06 19:35:02 +00008032 anyKindOf || RHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008033 return getObjCObjectPointerType(Result);
8034 }
8035
8036 return getObjCObjectPointerType(QualType(RHS, 0));
8037 }
8038
8039 // Find the superclass of the RHS.
8040 QualType RHSSuperType = RHS->getSuperClassType();
8041 if (RHSSuperType.isNull())
8042 break;
8043
8044 RHS = RHSSuperType->castAs<ObjCObjectType>();
8045 }
8046
Eugene Zelenko7855e772018-04-03 00:11:50 +00008047 return {};
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00008048}
8049
John McCall8b07ec22010-05-15 11:32:37 +00008050bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
8051 const ObjCObjectType *RHS) {
8052 assert(LHS->getInterface() && "LHS is not an interface type");
8053 assert(RHS->getInterface() && "RHS is not an interface type");
8054
Chris Lattner49af6a42008-04-07 06:51:04 +00008055 // Verify that the base decls are compatible: the RHS must be a subclass of
8056 // the LHS.
Douglas Gregore83b9562015-07-07 03:57:53 +00008057 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
8058 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
8059 if (!IsSuperClass)
Chris Lattner49af6a42008-04-07 06:51:04 +00008060 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008061
Douglas Gregore83b9562015-07-07 03:57:53 +00008062 // If the LHS has protocol qualifiers, determine whether all of them are
8063 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
8064 // LHS).
8065 if (LHS->getNumProtocols() > 0) {
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00008066 // OK if conversion of LHS to SuperClass results in narrowing of types
8067 // ; i.e., SuperClass may implement at least one of the protocols
8068 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
8069 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
8070 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
8071 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
8072 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
8073 // qualifiers.
8074 for (auto *RHSPI : RHS->quals())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008075 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00008076 // If there is no protocols associated with RHS, it is not a match.
8077 if (SuperClassInheritedProtocols.empty())
Steve Naroff114aecb2009-03-01 16:12:44 +00008078 return false;
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00008079
8080 for (const auto *LHSProto : LHS->quals()) {
8081 bool SuperImplementsProtocol = false;
8082 for (auto *SuperClassProto : SuperClassInheritedProtocols)
8083 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
8084 SuperImplementsProtocol = true;
8085 break;
8086 }
8087 if (!SuperImplementsProtocol)
8088 return false;
8089 }
Chris Lattner49af6a42008-04-07 06:51:04 +00008090 }
Douglas Gregore83b9562015-07-07 03:57:53 +00008091
8092 // If the LHS is specialized, we may need to check type arguments.
8093 if (LHS->isSpecialized()) {
8094 // Follow the superclass chain until we've matched the LHS class in the
8095 // hierarchy. This substitutes type arguments through.
8096 const ObjCObjectType *RHSSuper = RHS;
8097 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
8098 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
8099
8100 // If the RHS is specializd, compare type arguments.
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008101 if (RHSSuper->isSpecialized() &&
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008102 !sameObjCTypeArgs(*this, LHS->getInterface(),
8103 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00008104 /*stripKindOf=*/true)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008105 return false;
Douglas Gregore83b9562015-07-07 03:57:53 +00008106 }
8107 }
8108
8109 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00008110}
8111
Steve Naroffb7605152009-02-12 17:52:19 +00008112bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
8113 // get the "pointed to" types
Eugene Zelenko7855e772018-04-03 00:11:50 +00008114 const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
8115 const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00008116
Steve Naroff7cae42b2009-07-10 23:34:53 +00008117 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00008118 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00008119
8120 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
8121 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00008122}
8123
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00008124bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
8125 return canAssignObjCInterfaces(
8126 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
8127 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
8128}
8129
Mike Stump11289f42009-09-09 15:08:12 +00008130/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00008131/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00008132/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00008133/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008134bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
8135 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00008136 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00008137 return hasSameType(LHS, RHS);
Joey Gouly5788b782016-11-18 14:10:54 +00008138
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008139 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00008140}
8141
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00008142bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00008143 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00008144}
8145
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008146bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
8147 return !mergeTypes(LHS, RHS, true).isNull();
8148}
8149
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00008150/// mergeTransparentUnionType - if T is a transparent union type and a member
8151/// of T is compatible with SubType, return the merged type, else return
8152/// QualType()
8153QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
8154 bool OfBlockPointer,
8155 bool Unqualified) {
8156 if (const RecordType *UT = T->getAsUnionType()) {
8157 RecordDecl *UD = UT->getDecl();
8158 if (UD->hasAttr<TransparentUnionAttr>()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008159 for (const auto *I : UD->fields()) {
8160 QualType ET = I->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00008161 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
8162 if (!MT.isNull())
8163 return MT;
8164 }
8165 }
8166 }
8167
Eugene Zelenko7855e772018-04-03 00:11:50 +00008168 return {};
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00008169}
8170
Alp Toker9cacbab2014-01-20 20:26:09 +00008171/// mergeFunctionParameterTypes - merge two types which appear as function
8172/// parameter types
8173QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
8174 bool OfBlockPointer,
8175 bool Unqualified) {
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00008176 // GNU extension: two types are compatible if they appear as a function
8177 // argument, one of the types is a transparent union type and the other
8178 // type is compatible with a union member
8179 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
8180 Unqualified);
8181 if (!lmerge.isNull())
8182 return lmerge;
8183
8184 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
8185 Unqualified);
8186 if (!rmerge.isNull())
8187 return rmerge;
8188
8189 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
8190}
8191
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008192QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008193 bool OfBlockPointer,
8194 bool Unqualified) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00008195 const auto *lbase = lhs->getAs<FunctionType>();
8196 const auto *rbase = rhs->getAs<FunctionType>();
8197 const auto *lproto = dyn_cast<FunctionProtoType>(lbase);
8198 const auto *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00008199 bool allLTypes = true;
8200 bool allRTypes = true;
8201
8202 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008203 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00008204 if (OfBlockPointer) {
Alp Toker314cc812014-01-25 16:55:45 +00008205 QualType RHS = rbase->getReturnType();
8206 QualType LHS = lbase->getReturnType();
Fariborz Jahanian17825972011-02-11 18:46:17 +00008207 bool UnqualifiedResult = Unqualified;
8208 if (!UnqualifiedResult)
8209 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00008210 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00008211 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008212 else
Alp Toker314cc812014-01-25 16:55:45 +00008213 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
John McCall8c6b56f2010-12-15 01:06:38 +00008214 Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00008215 if (retType.isNull())
8216 return {};
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008217
8218 if (Unqualified)
8219 retType = retType.getUnqualifiedType();
8220
Alp Toker314cc812014-01-25 16:55:45 +00008221 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
8222 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008223 if (Unqualified) {
8224 LRetType = LRetType.getUnqualifiedType();
8225 RRetType = RRetType.getUnqualifiedType();
8226 }
8227
8228 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00008229 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008230 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00008231 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00008232
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00008233 // FIXME: double check this
8234 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
8235 // rbase->getRegParmAttr() != 0 &&
8236 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00008237 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
8238 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00008239
Douglas Gregor8c940862010-01-18 17:14:39 +00008240 // Compatible functions must have compatible calling conventions
Reid Kleckner78af0702013-08-27 23:08:25 +00008241 if (lbaseInfo.getCC() != rbaseInfo.getCC())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008242 return {};
Mike Stump11289f42009-09-09 15:08:12 +00008243
John McCall8c6b56f2010-12-15 01:06:38 +00008244 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00008245 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008246 return {};
John McCall8c6b56f2010-12-15 01:06:38 +00008247 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008248 return {};
John McCall8c6b56f2010-12-15 01:06:38 +00008249
John McCall31168b02011-06-15 23:02:42 +00008250 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008251 return {};
Oren Ben Simhon318a6ea2017-04-27 12:01:00 +00008252 if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008253 return {};
Oren Ben Simhon220671a2018-03-17 13:31:35 +00008254 if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008255 return {};
John McCall31168b02011-06-15 23:02:42 +00008256
John McCall8c6b56f2010-12-15 01:06:38 +00008257 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
8258 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00008259
Rafael Espindola8778c282012-11-29 16:09:03 +00008260 if (lbaseInfo.getNoReturn() != NoReturn)
8261 allLTypes = false;
8262 if (rbaseInfo.getNoReturn() != NoReturn)
8263 allRTypes = false;
8264
John McCall31168b02011-06-15 23:02:42 +00008265 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00008266
Eli Friedman47f77112008-08-22 00:56:42 +00008267 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00008268 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
8269 "C++ shouldn't be here");
Alp Toker601b22c2014-01-21 23:35:24 +00008270 // Compatible functions must have the same number of parameters
8271 if (lproto->getNumParams() != rproto->getNumParams())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008272 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00008273
8274 // Variadic and non-variadic functions aren't compatible
8275 if (lproto->isVariadic() != rproto->isVariadic())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008276 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00008277
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00008278 if (lproto->getTypeQuals() != rproto->getTypeQuals())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008279 return {};
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00008280
Akira Hatanaka98a49332017-09-22 00:41:05 +00008281 SmallVector<FunctionProtoType::ExtParameterInfo, 4> newParamInfos;
8282 bool canUseLeft, canUseRight;
8283 if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight,
8284 newParamInfos))
Eugene Zelenko7855e772018-04-03 00:11:50 +00008285 return {};
Alp Toker601b22c2014-01-21 23:35:24 +00008286
Akira Hatanaka98a49332017-09-22 00:41:05 +00008287 if (!canUseLeft)
8288 allLTypes = false;
8289 if (!canUseRight)
8290 allRTypes = false;
8291
Alp Toker601b22c2014-01-21 23:35:24 +00008292 // Check parameter type compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008293 SmallVector<QualType, 10> types;
Alp Toker601b22c2014-01-21 23:35:24 +00008294 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
8295 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
8296 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
8297 QualType paramType = mergeFunctionParameterTypes(
8298 lParamType, rParamType, OfBlockPointer, Unqualified);
8299 if (paramType.isNull())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008300 return {};
Alp Toker601b22c2014-01-21 23:35:24 +00008301
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008302 if (Unqualified)
Alp Toker601b22c2014-01-21 23:35:24 +00008303 paramType = paramType.getUnqualifiedType();
8304
8305 types.push_back(paramType);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008306 if (Unqualified) {
Alp Toker601b22c2014-01-21 23:35:24 +00008307 lParamType = lParamType.getUnqualifiedType();
8308 rParamType = rParamType.getUnqualifiedType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008309 }
Alp Toker601b22c2014-01-21 23:35:24 +00008310
8311 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00008312 allLTypes = false;
Alp Toker601b22c2014-01-21 23:35:24 +00008313 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00008314 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00008315 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00008316
Eli Friedman47f77112008-08-22 00:56:42 +00008317 if (allLTypes) return lhs;
8318 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00008319
8320 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
8321 EPI.ExtInfo = einfo;
Akira Hatanaka98a49332017-09-22 00:41:05 +00008322 EPI.ExtParameterInfos =
8323 newParamInfos.empty() ? nullptr : newParamInfos.data();
Jordan Rose5c382722013-03-08 21:51:21 +00008324 return getFunctionType(retType, types, EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00008325 }
8326
8327 if (lproto) allRTypes = false;
8328 if (rproto) allLTypes = false;
8329
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008330 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00008331 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00008332 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eugene Zelenko7855e772018-04-03 00:11:50 +00008333 if (proto->isVariadic())
8334 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00008335 // Check that the types are compatible with the types that
8336 // would result from default argument promotions (C99 6.7.5.3p15).
8337 // The only types actually affected are promotable integer
8338 // types and floats, which would be passed as a different
8339 // type depending on whether the prototype is visible.
Alp Toker601b22c2014-01-21 23:35:24 +00008340 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
8341 QualType paramTy = proto->getParamType(i);
Alp Toker9cacbab2014-01-20 20:26:09 +00008342
Eli Friedman448ce402012-08-30 00:44:15 +00008343 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00008344 // to pass enum values.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008345 if (const auto *Enum = paramTy->getAs<EnumType>()) {
Alp Toker601b22c2014-01-21 23:35:24 +00008346 paramTy = Enum->getDecl()->getIntegerType();
8347 if (paramTy.isNull())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008348 return {};
Eli Friedman448ce402012-08-30 00:44:15 +00008349 }
Alp Toker601b22c2014-01-21 23:35:24 +00008350
8351 if (paramTy->isPromotableIntegerType() ||
8352 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
Eugene Zelenko7855e772018-04-03 00:11:50 +00008353 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00008354 }
8355
8356 if (allLTypes) return lhs;
8357 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00008358
8359 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
8360 EPI.ExtInfo = einfo;
Alp Toker9cacbab2014-01-20 20:26:09 +00008361 return getFunctionType(retType, proto->getParamTypes(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00008362 }
8363
8364 if (allLTypes) return lhs;
8365 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00008366 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00008367}
8368
John McCall433c2e62013-03-21 00:10:07 +00008369/// Given that we have an enum type and a non-enum type, try to merge them.
8370static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
8371 QualType other, bool isBlockReturnType) {
8372 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
8373 // a signed integer type, or an unsigned integer type.
8374 // Compatibility is based on the underlying type, not the promotion
8375 // type.
8376 QualType underlyingType = ET->getDecl()->getIntegerType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00008377 if (underlyingType.isNull())
8378 return {};
John McCall433c2e62013-03-21 00:10:07 +00008379 if (Context.hasSameType(underlyingType, other))
8380 return other;
8381
8382 // In block return types, we're more permissive and accept any
8383 // integral type of the same size.
8384 if (isBlockReturnType && other->isIntegerType() &&
8385 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
8386 return other;
8387
Eugene Zelenko7855e772018-04-03 00:11:50 +00008388 return {};
John McCall433c2e62013-03-21 00:10:07 +00008389}
8390
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008391QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008392 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00008393 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00008394 // C++ [expr]: If an expression initially has the type "reference to T", the
8395 // type is adjusted to "T" prior to any further analysis, the expression
8396 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00008397 // expression is an lvalue unless the reference is an rvalue reference and
8398 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00008399 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
8400 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008401
8402 if (Unqualified) {
8403 LHS = LHS.getUnqualifiedType();
8404 RHS = RHS.getUnqualifiedType();
8405 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00008406
Eli Friedman47f77112008-08-22 00:56:42 +00008407 QualType LHSCan = getCanonicalType(LHS),
8408 RHSCan = getCanonicalType(RHS);
8409
8410 // If two types are identical, they are compatible.
8411 if (LHSCan == RHSCan)
8412 return LHS;
8413
John McCall8ccfcb52009-09-24 19:53:00 +00008414 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00008415 Qualifiers LQuals = LHSCan.getLocalQualifiers();
8416 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00008417 if (LQuals != RQuals) {
8418 // If any of these qualifiers are different, we have a type
8419 // mismatch.
8420 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00008421 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
Roger Ferrer Ibanezd93add32017-02-24 08:41:09 +00008422 LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
8423 LQuals.hasUnaligned() != RQuals.hasUnaligned())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008424 return {};
John McCall8ccfcb52009-09-24 19:53:00 +00008425
8426 // Exactly one GC qualifier difference is allowed: __strong is
8427 // okay if the other type has no GC qualifier but is an Objective
8428 // C object pointer (i.e. implicitly strong by default). We fix
8429 // this by pretending that the unqualified type was actually
8430 // qualified __strong.
8431 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
8432 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
8433 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
8434
8435 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
Eugene Zelenko7855e772018-04-03 00:11:50 +00008436 return {};
John McCall8ccfcb52009-09-24 19:53:00 +00008437
8438 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
8439 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
8440 }
8441 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
8442 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
8443 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00008444 return {};
John McCall8ccfcb52009-09-24 19:53:00 +00008445 }
8446
8447 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00008448
Eli Friedmandcca6332009-06-01 01:22:52 +00008449 Type::TypeClass LHSClass = LHSCan->getTypeClass();
8450 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00008451
Chris Lattnerfd652912008-01-14 05:45:46 +00008452 // We want to consider the two function types to be the same for these
8453 // comparisons, just force one to the other.
8454 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
8455 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00008456
8457 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00008458 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
8459 LHSClass = Type::ConstantArray;
8460 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
8461 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00008462
John McCall8b07ec22010-05-15 11:32:37 +00008463 // ObjCInterfaces are just specialized ObjCObjects.
8464 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
8465 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
8466
Nate Begemance4d7fc2008-04-18 23:10:10 +00008467 // Canonicalize ExtVector -> Vector.
8468 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
8469 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00008470
Chris Lattner95554662008-04-07 05:43:21 +00008471 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00008472 if (LHSClass != RHSClass) {
John McCall433c2e62013-03-21 00:10:07 +00008473 // Note that we only have special rules for turning block enum
8474 // returns into block int returns, not vice-versa.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008475 if (const auto *ETy = LHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00008476 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00008477 }
John McCall9dd450b2009-09-21 23:43:11 +00008478 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00008479 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00008480 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00008481 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00008482 if (OfBlockPointer && !BlockReturnType) {
8483 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
8484 return LHS;
8485 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
8486 return RHS;
8487 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00008488
Eugene Zelenko7855e772018-04-03 00:11:50 +00008489 return {};
Steve Naroff32e44c02007-10-15 20:41:53 +00008490 }
Eli Friedman47f77112008-08-22 00:56:42 +00008491
Steve Naroffc6edcbd2008-01-09 22:43:08 +00008492 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00008493 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008494#define TYPE(Class, Base)
8495#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00008496#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008497#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
8498#define DEPENDENT_TYPE(Class, Base) case Type::Class:
8499#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00008500 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008501
Richard Smith27d807c2013-04-30 13:56:41 +00008502 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00008503 case Type::DeducedTemplateSpecialization:
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00008504 case Type::LValueReference:
8505 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008506 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00008507 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008508
John McCall8b07ec22010-05-15 11:32:37 +00008509 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008510 case Type::IncompleteArray:
8511 case Type::VariableArray:
8512 case Type::FunctionProto:
8513 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00008514 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008515
Chris Lattnerfd652912008-01-14 05:45:46 +00008516 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00008517 {
8518 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008519 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
8520 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008521 if (Unqualified) {
8522 LHSPointee = LHSPointee.getUnqualifiedType();
8523 RHSPointee = RHSPointee.getUnqualifiedType();
8524 }
8525 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
8526 Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00008527 if (ResultType.isNull())
8528 return {};
Eli Friedman091a9ac2009-06-02 05:28:56 +00008529 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00008530 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00008531 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00008532 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00008533 return getPointerType(ResultType);
8534 }
Steve Naroff68e167d2008-12-10 17:49:55 +00008535 case Type::BlockPointer:
8536 {
8537 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008538 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
8539 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008540 if (Unqualified) {
8541 LHSPointee = LHSPointee.getUnqualifiedType();
8542 RHSPointee = RHSPointee.getUnqualifiedType();
8543 }
Anastasia Stulova81a25e352017-03-10 15:23:07 +00008544 if (getLangOpts().OpenCL) {
8545 Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
8546 Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
8547 // Blocks can't be an expression in a ternary operator (OpenCL v2.0
8548 // 6.12.5) thus the following check is asymmetric.
8549 if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual))
Eugene Zelenko7855e772018-04-03 00:11:50 +00008550 return {};
Anastasia Stulova81a25e352017-03-10 15:23:07 +00008551 LHSPteeQual.removeAddressSpace();
8552 RHSPteeQual.removeAddressSpace();
8553 LHSPointee =
8554 QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
8555 RHSPointee =
8556 QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
8557 }
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008558 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
8559 Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00008560 if (ResultType.isNull())
8561 return {};
Steve Naroff68e167d2008-12-10 17:49:55 +00008562 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
8563 return LHS;
8564 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
8565 return RHS;
8566 return getBlockPointerType(ResultType);
8567 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00008568 case Type::Atomic:
8569 {
8570 // Merge two pointer types, while trying to preserve typedef info
8571 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
8572 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
8573 if (Unqualified) {
8574 LHSValue = LHSValue.getUnqualifiedType();
8575 RHSValue = RHSValue.getUnqualifiedType();
8576 }
8577 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
8578 Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00008579 if (ResultType.isNull())
8580 return {};
Eli Friedman0dfb8892011-10-06 23:00:33 +00008581 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
8582 return LHS;
8583 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
8584 return RHS;
8585 return getAtomicType(ResultType);
8586 }
Chris Lattnerfd652912008-01-14 05:45:46 +00008587 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00008588 {
8589 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
8590 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
8591 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008592 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00008593
8594 QualType LHSElem = getAsArrayType(LHS)->getElementType();
8595 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008596 if (Unqualified) {
8597 LHSElem = LHSElem.getUnqualifiedType();
8598 RHSElem = RHSElem.getUnqualifiedType();
8599 }
8600
8601 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00008602 if (ResultType.isNull())
8603 return {};
Chris Lattner465fa322008-10-05 17:34:18 +00008604 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
8605 return LHS;
8606 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
8607 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00008608 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
8609 ArrayType::ArraySizeModifier(), 0);
8610 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
8611 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00008612 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
8613 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00008614 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
8615 return LHS;
8616 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
8617 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00008618 if (LVAT) {
8619 // FIXME: This isn't correct! But tricky to implement because
8620 // the array's size has to be the size of LHS, but the type
8621 // has to be different.
8622 return LHS;
8623 }
8624 if (RVAT) {
8625 // FIXME: This isn't correct! But tricky to implement because
8626 // the array's size has to be the size of RHS, but the type
8627 // has to be different.
8628 return RHS;
8629 }
Eli Friedman3e62c212008-08-22 01:48:21 +00008630 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
8631 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00008632 return getIncompleteArrayType(ResultType,
8633 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00008634 }
Chris Lattnerfd652912008-01-14 05:45:46 +00008635 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008636 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008637 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008638 case Type::Enum:
Eugene Zelenko7855e772018-04-03 00:11:50 +00008639 return {};
Chris Lattnerfd652912008-01-14 05:45:46 +00008640 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00008641 // Only exactly equal builtin types are compatible, which is tested above.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008642 return {};
Daniel Dunbar804c0442009-01-28 21:22:12 +00008643 case Type::Complex:
8644 // Distinct complex types are incompatible.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008645 return {};
Chris Lattner7bbd3d72008-04-07 05:55:38 +00008646 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00008647 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00008648 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
8649 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00008650 return LHS;
Eugene Zelenko7855e772018-04-03 00:11:50 +00008651 return {};
John McCall8b07ec22010-05-15 11:32:37 +00008652 case Type::ObjCObject: {
8653 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00008654 // FIXME: This should be type compatibility, e.g. whether
8655 // "LHS x; RHS x;" at global scope is legal.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008656 const auto *LHSIface = LHS->getAs<ObjCObjectType>();
8657 const auto *RHSIface = RHS->getAs<ObjCObjectType>();
John McCall8b07ec22010-05-15 11:32:37 +00008658 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00008659 return LHS;
8660
Eugene Zelenko7855e772018-04-03 00:11:50 +00008661 return {};
Cedric Venet4fc88b72009-02-21 17:14:49 +00008662 }
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00008663 case Type::ObjCObjectPointer:
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008664 if (OfBlockPointer) {
8665 if (canAssignObjCInterfacesInBlockPointer(
8666 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00008667 RHS->getAs<ObjCObjectPointerType>(),
8668 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00008669 return LHS;
Eugene Zelenko7855e772018-04-03 00:11:50 +00008670 return {};
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008671 }
John McCall9dd450b2009-09-21 23:43:11 +00008672 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
8673 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00008674 return LHS;
8675
Eugene Zelenko7855e772018-04-03 00:11:50 +00008676 return {};
Xiuli Pan9c14e282016-01-09 12:53:17 +00008677 case Type::Pipe:
Joey Goulye3c85de2016-12-01 11:30:49 +00008678 assert(LHS != RHS &&
8679 "Equivalent pipe types should have already been handled!");
Eugene Zelenko7855e772018-04-03 00:11:50 +00008680 return {};
Xiuli Pan9c14e282016-01-09 12:53:17 +00008681 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008682
David Blaikie8a40f702012-01-17 06:56:22 +00008683 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00008684}
Ted Kremenekfc581a92007-10-31 17:10:13 +00008685
Akira Hatanaka98a49332017-09-22 00:41:05 +00008686bool ASTContext::mergeExtParameterInfo(
8687 const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType,
8688 bool &CanUseFirst, bool &CanUseSecond,
8689 SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &NewParamInfos) {
8690 assert(NewParamInfos.empty() && "param info list not empty");
8691 CanUseFirst = CanUseSecond = true;
8692 bool FirstHasInfo = FirstFnType->hasExtParameterInfos();
8693 bool SecondHasInfo = SecondFnType->hasExtParameterInfos();
8694
John McCall18afab72016-03-01 00:49:02 +00008695 // Fast path: if the first type doesn't have ext parameter infos,
Akira Hatanaka98a49332017-09-22 00:41:05 +00008696 // we match if and only if the second type also doesn't have them.
8697 if (!FirstHasInfo && !SecondHasInfo)
8698 return true;
John McCall18afab72016-03-01 00:49:02 +00008699
Akira Hatanaka98a49332017-09-22 00:41:05 +00008700 bool NeedParamInfo = false;
8701 size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size()
8702 : SecondFnType->getExtParameterInfos().size();
John McCall18afab72016-03-01 00:49:02 +00008703
Akira Hatanaka98a49332017-09-22 00:41:05 +00008704 for (size_t I = 0; I < E; ++I) {
8705 FunctionProtoType::ExtParameterInfo FirstParam, SecondParam;
8706 if (FirstHasInfo)
8707 FirstParam = FirstFnType->getExtParameterInfo(I);
8708 if (SecondHasInfo)
8709 SecondParam = SecondFnType->getExtParameterInfo(I);
John McCall18afab72016-03-01 00:49:02 +00008710
Akira Hatanaka98a49332017-09-22 00:41:05 +00008711 // Cannot merge unless everything except the noescape flag matches.
8712 if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false))
John McCall18afab72016-03-01 00:49:02 +00008713 return false;
Akira Hatanaka98a49332017-09-22 00:41:05 +00008714
8715 bool FirstNoEscape = FirstParam.isNoEscape();
8716 bool SecondNoEscape = SecondParam.isNoEscape();
8717 bool IsNoEscape = FirstNoEscape && SecondNoEscape;
8718 NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape));
8719 if (NewParamInfos.back().getOpaqueValue())
8720 NeedParamInfo = true;
8721 if (FirstNoEscape != IsNoEscape)
8722 CanUseFirst = false;
8723 if (SecondNoEscape != IsNoEscape)
8724 CanUseSecond = false;
John McCall18afab72016-03-01 00:49:02 +00008725 }
Akira Hatanaka98a49332017-09-22 00:41:05 +00008726
8727 if (!NeedParamInfo)
8728 NewParamInfos.clear();
8729
Fariborz Jahanian97676972011-09-28 21:52:05 +00008730 return true;
8731}
8732
Chandler Carruth21c90602015-12-30 03:24:14 +00008733void ASTContext::ResetObjCLayout(const ObjCContainerDecl *CD) {
8734 ObjCLayouts[CD] = nullptr;
8735}
8736
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008737/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
8738/// 'RHS' attributes and returns the merged version; including for function
8739/// return types.
8740QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
8741 QualType LHSCan = getCanonicalType(LHS),
8742 RHSCan = getCanonicalType(RHS);
8743 // If two types are identical, they are compatible.
8744 if (LHSCan == RHSCan)
8745 return LHS;
8746 if (RHSCan->isFunctionType()) {
8747 if (!LHSCan->isFunctionType())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008748 return {};
Alp Toker314cc812014-01-25 16:55:45 +00008749 QualType OldReturnType =
8750 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008751 QualType NewReturnType =
Alp Toker314cc812014-01-25 16:55:45 +00008752 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008753 QualType ResReturnType =
8754 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
8755 if (ResReturnType.isNull())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008756 return {};
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008757 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
8758 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
8759 // In either case, use OldReturnType to build the new function type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008760 const auto *F = LHS->getAs<FunctionType>();
8761 if (const auto *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00008762 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8763 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner896b32f2013-06-10 20:51:09 +00008764 QualType ResultType =
Alp Toker9cacbab2014-01-20 20:26:09 +00008765 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008766 return ResultType;
8767 }
8768 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00008769 return {};
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008770 }
8771
8772 // If the qualifiers are different, the types can still be merged.
8773 Qualifiers LQuals = LHSCan.getLocalQualifiers();
8774 Qualifiers RQuals = RHSCan.getLocalQualifiers();
8775 if (LQuals != RQuals) {
8776 // If any of these qualifiers are different, we have a type mismatch.
8777 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
8778 LQuals.getAddressSpace() != RQuals.getAddressSpace())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008779 return {};
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008780
8781 // Exactly one GC qualifier difference is allowed: __strong is
8782 // okay if the other type has no GC qualifier but is an Objective
8783 // C object pointer (i.e. implicitly strong by default). We fix
8784 // this by pretending that the unqualified type was actually
8785 // qualified __strong.
8786 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
8787 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
8788 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
8789
8790 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
Eugene Zelenko7855e772018-04-03 00:11:50 +00008791 return {};
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008792
8793 if (GC_L == Qualifiers::Strong)
8794 return LHS;
8795 if (GC_R == Qualifiers::Strong)
8796 return RHS;
Eugene Zelenko7855e772018-04-03 00:11:50 +00008797 return {};
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008798 }
8799
8800 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
8801 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
8802 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
8803 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
8804 if (ResQT == LHSBaseQT)
8805 return LHS;
8806 if (ResQT == RHSBaseQT)
8807 return RHS;
8808 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00008809 return {};
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008810}
8811
Chris Lattner4ba0cef2008-04-07 07:01:58 +00008812//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008813// Integer Predicates
8814//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00008815
Jay Foad39c79802011-01-12 09:06:06 +00008816unsigned ASTContext::getIntWidth(QualType T) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00008817 if (const auto *ET = T->getAs<EnumType>())
Eli Friedmanee275c82009-12-10 22:29:29 +00008818 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00008819 if (T->isBooleanType())
8820 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00008821 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008822 return (unsigned)getTypeSize(T);
8823}
8824
Abramo Bagnara13640492012-09-09 10:21:24 +00008825QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00008826 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00008827
8828 // Turn <4 x signed int> -> <4 x unsigned int>
Eugene Zelenko7855e772018-04-03 00:11:50 +00008829 if (const auto *VTy = T->getAs<VectorType>())
Chris Lattnerec3a1562009-10-17 20:33:28 +00008830 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00008831 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00008832
8833 // For enums, we return the unsigned version of the base type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008834 if (const auto *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008835 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00008836
Eugene Zelenko7855e772018-04-03 00:11:50 +00008837 const auto *BTy = T->getAs<BuiltinType>();
Chris Lattnerec3a1562009-10-17 20:33:28 +00008838 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008839 switch (BTy->getKind()) {
8840 case BuiltinType::Char_S:
8841 case BuiltinType::SChar:
8842 return UnsignedCharTy;
8843 case BuiltinType::Short:
8844 return UnsignedShortTy;
8845 case BuiltinType::Int:
8846 return UnsignedIntTy;
8847 case BuiltinType::Long:
8848 return UnsignedLongTy;
8849 case BuiltinType::LongLong:
8850 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00008851 case BuiltinType::Int128:
8852 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008853 default:
David Blaikie83d382b2011-09-23 05:06:16 +00008854 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008855 }
8856}
8857
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00008858ASTMutationListener::~ASTMutationListener() = default;
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00008859
Richard Smith1fa5d642013-05-11 05:45:24 +00008860void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
8861 QualType ReturnType) {}
Chris Lattnerecd79c62009-06-14 00:45:47 +00008862
8863//===----------------------------------------------------------------------===//
8864// Builtin Type Computation
8865//===----------------------------------------------------------------------===//
8866
8867/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00008868/// pointer over the consumed characters. This returns the resultant type. If
8869/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
8870/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
8871/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008872///
8873/// RequiresICE is filled in on return to indicate whether the value is required
8874/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00008875static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00008876 ASTContext::GetBuiltinTypeError &Error,
Chandler Carruth45bbe012017-03-24 09:11:57 +00008877 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00008878 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00008879 // Modifiers.
8880 int HowLong = 0;
8881 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008882 RequiresICE = false;
Chandler Carruth45bbe012017-03-24 09:11:57 +00008883
Chris Lattnerdc226c22010-10-01 22:42:38 +00008884 // Read the prefixed modifiers first.
Eric Christopher50daf5f2017-07-10 21:28:54 +00008885 bool Done = false;
8886 #ifndef NDEBUG
8887 bool IsSpecialLong = false;
8888 #endif
Chris Lattnerecd79c62009-06-14 00:45:47 +00008889 while (!Done) {
8890 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00008891 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00008892 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008893 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00008894 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008895 case 'S':
8896 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
8897 assert(!Signed && "Can't use 'S' modifier multiple times!");
8898 Signed = true;
8899 break;
8900 case 'U':
8901 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
Sean Silva2a995142015-01-16 21:44:26 +00008902 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00008903 Unsigned = true;
8904 break;
8905 case 'L':
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00008906 assert(!IsSpecialLong && "Can't use 'L' with 'W' or 'N' modifiers");
Chris Lattnerecd79c62009-06-14 00:45:47 +00008907 assert(HowLong <= 2 && "Can't have LLLL modifier");
8908 ++HowLong;
8909 break;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00008910 case 'N':
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00008911 // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
8912 assert(!IsSpecialLong && "Can't use two 'N' or 'W' modifiers!");
8913 assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
Eric Christopher50daf5f2017-07-10 21:28:54 +00008914 #ifndef NDEBUG
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00008915 IsSpecialLong = true;
Eric Christopher50daf5f2017-07-10 21:28:54 +00008916 #endif
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00008917 if (Context.getTargetInfo().getLongWidth() == 32)
8918 ++HowLong;
8919 break;
Kevin Qinad64f6d2014-02-24 02:45:03 +00008920 case 'W':
8921 // This modifier represents int64 type.
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00008922 assert(!IsSpecialLong && "Can't use two 'N' or 'W' modifiers!");
Kevin Qinad64f6d2014-02-24 02:45:03 +00008923 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
Eric Christopher50daf5f2017-07-10 21:28:54 +00008924 #ifndef NDEBUG
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00008925 IsSpecialLong = true;
Eric Christopher50daf5f2017-07-10 21:28:54 +00008926 #endif
Kevin Qinad64f6d2014-02-24 02:45:03 +00008927 switch (Context.getTargetInfo().getInt64Type()) {
8928 default:
8929 llvm_unreachable("Unexpected integer type");
8930 case TargetInfo::SignedLong:
8931 HowLong = 1;
8932 break;
8933 case TargetInfo::SignedLongLong:
8934 HowLong = 2;
8935 break;
8936 }
Duncan P. N. Exon Smitheae8caa2017-06-14 21:26:31 +00008937 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008938 }
8939 }
8940
8941 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00008942
Chris Lattnerecd79c62009-06-14 00:45:47 +00008943 // Read the base type.
8944 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00008945 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00008946 case 'v':
8947 assert(HowLong == 0 && !Signed && !Unsigned &&
8948 "Bad modifiers used with 'v'!");
8949 Type = Context.VoidTy;
8950 break;
Jack Carter24bef982013-08-15 15:16:57 +00008951 case 'h':
8952 assert(HowLong == 0 && !Signed && !Unsigned &&
Sean Silva2a995142015-01-16 21:44:26 +00008953 "Bad modifiers used with 'h'!");
Jack Carter24bef982013-08-15 15:16:57 +00008954 Type = Context.HalfTy;
8955 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008956 case 'f':
8957 assert(HowLong == 0 && !Signed && !Unsigned &&
8958 "Bad modifiers used with 'f'!");
8959 Type = Context.FloatTy;
8960 break;
8961 case 'd':
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00008962 assert(HowLong < 3 && !Signed && !Unsigned &&
Chris Lattnerecd79c62009-06-14 00:45:47 +00008963 "Bad modifiers used with 'd'!");
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00008964 if (HowLong == 1)
Chris Lattnerecd79c62009-06-14 00:45:47 +00008965 Type = Context.LongDoubleTy;
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00008966 else if (HowLong == 2)
8967 Type = Context.Float128Ty;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008968 else
8969 Type = Context.DoubleTy;
8970 break;
8971 case 's':
8972 assert(HowLong == 0 && "Bad modifiers used with 's'!");
8973 if (Unsigned)
8974 Type = Context.UnsignedShortTy;
8975 else
8976 Type = Context.ShortTy;
8977 break;
8978 case 'i':
8979 if (HowLong == 3)
8980 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
8981 else if (HowLong == 2)
8982 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
8983 else if (HowLong == 1)
8984 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
8985 else
8986 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
8987 break;
8988 case 'c':
8989 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
8990 if (Signed)
8991 Type = Context.SignedCharTy;
8992 else if (Unsigned)
8993 Type = Context.UnsignedCharTy;
8994 else
8995 Type = Context.CharTy;
8996 break;
8997 case 'b': // boolean
8998 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
8999 Type = Context.BoolTy;
9000 break;
9001 case 'z': // size_t.
9002 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
9003 Type = Context.getSizeType();
9004 break;
Richard Smith8110c9d2016-11-29 19:45:17 +00009005 case 'w': // wchar_t.
9006 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
9007 Type = Context.getWideCharType();
9008 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009009 case 'F':
9010 Type = Context.getCFConstantStringType();
9011 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00009012 case 'G':
9013 Type = Context.getObjCIdType();
9014 break;
9015 case 'H':
9016 Type = Context.getObjCSelType();
9017 break;
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00009018 case 'M':
9019 Type = Context.getObjCSuperType();
9020 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009021 case 'a':
9022 Type = Context.getBuiltinVaListType();
9023 assert(!Type.isNull() && "builtin va list type not initialized!");
9024 break;
9025 case 'A':
9026 // This is a "reference" to a va_list; however, what exactly
9027 // this means depends on how va_list is defined. There are two
9028 // different kinds of va_list: ones passed by value, and ones
9029 // passed by reference. An example of a by-value va_list is
9030 // x86, where va_list is a char*. An example of by-ref va_list
9031 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
9032 // we want this argument to be a char*&; for x86-64, we want
9033 // it to be a __va_list_tag*.
9034 Type = Context.getBuiltinVaListType();
9035 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009036 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00009037 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009038 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00009039 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009040 break;
9041 case 'V': {
9042 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009043 unsigned NumElements = strtoul(Str, &End, 10);
9044 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00009045 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00009046
Chandler Carruth45bbe012017-03-24 09:11:57 +00009047 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
9048 RequiresICE, false);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009049 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00009050
9051 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00009052 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00009053 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009054 break;
9055 }
Douglas Gregorfed66992012-06-07 18:08:25 +00009056 case 'E': {
9057 char *End;
9058
9059 unsigned NumElements = strtoul(Str, &End, 10);
9060 assert(End != Str && "Missing vector size");
9061
9062 Str = End;
Chandler Carruth45bbe012017-03-24 09:11:57 +00009063
Douglas Gregorfed66992012-06-07 18:08:25 +00009064 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
Chandler Carruth45bbe012017-03-24 09:11:57 +00009065 false);
Douglas Gregorfed66992012-06-07 18:08:25 +00009066 Type = Context.getExtVectorType(ElementType, NumElements);
9067 break;
9068 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00009069 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009070 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
Chandler Carruth45bbe012017-03-24 09:11:57 +00009071 false);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009072 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00009073 Type = Context.getComplexType(ElementType);
9074 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00009075 }
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009076 case 'Y':
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00009077 Type = Context.getPointerDiffType();
9078 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00009079 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00009080 Type = Context.getFILEType();
9081 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00009082 Error = ASTContext::GE_Missing_stdio;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009083 return {};
Chris Lattnerecd79c62009-06-14 00:45:47 +00009084 }
Mike Stump2adb4da2009-07-28 23:47:15 +00009085 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00009086 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00009087 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00009088 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00009089 else
9090 Type = Context.getjmp_bufType();
9091
Mike Stump2adb4da2009-07-28 23:47:15 +00009092 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00009093 Error = ASTContext::GE_Missing_setjmp;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009094 return {};
Mike Stump2adb4da2009-07-28 23:47:15 +00009095 }
9096 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00009097 case 'K':
9098 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
9099 Type = Context.getucontext_tType();
9100
9101 if (Type.isNull()) {
9102 Error = ASTContext::GE_Missing_ucontext;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009103 return {};
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00009104 }
9105 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00009106 case 'p':
9107 Type = Context.getProcessIDType();
9108 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00009109 }
Mike Stump11289f42009-09-09 15:08:12 +00009110
Chris Lattnerdc226c22010-10-01 22:42:38 +00009111 // If there are modifiers and if we're allowed to parse them, go for it.
9112 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009113 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00009114 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00009115 default: Done = true; --Str; break;
9116 case '*':
9117 case '&': {
9118 // Both pointers and references can have their pointee types
9119 // qualified with an address space.
9120 char *End;
9121 unsigned AddrSpace = strtoul(Str, &End, 10);
9122 if (End != Str && AddrSpace != 0) {
Alexander Richardson6d989432017-10-15 18:48:14 +00009123 Type = Context.getAddrSpaceQualType(Type,
9124 getLangASFromTargetAS(AddrSpace));
Chris Lattnerdc226c22010-10-01 22:42:38 +00009125 Str = End;
9126 }
9127 if (c == '*')
9128 Type = Context.getPointerType(Type);
9129 else
9130 Type = Context.getLValueReferenceType(Type);
9131 break;
9132 }
9133 // FIXME: There's no way to have a built-in with an rvalue ref arg.
9134 case 'C':
9135 Type = Type.withConst();
9136 break;
9137 case 'D':
9138 Type = Context.getVolatileType(Type);
9139 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00009140 case 'R':
9141 Type = Type.withRestrict();
9142 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009143 }
9144 }
Chris Lattner84733392010-10-01 07:13:18 +00009145
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009146 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00009147 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00009148
Chris Lattnerecd79c62009-06-14 00:45:47 +00009149 return Type;
9150}
9151
9152/// GetBuiltinType - Return the type for the specified builtin.
Chandler Carruth45bbe012017-03-24 09:11:57 +00009153QualType ASTContext::GetBuiltinType(unsigned Id,
9154 GetBuiltinTypeError &Error,
9155 unsigned *IntegerConstantArgs) const {
Eric Christopher02d5d862015-08-06 01:01:12 +00009156 const char *TypeStr = BuiltinInfo.getTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00009157
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009158 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00009159
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009160 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009161 Error = GE_None;
Chandler Carruth45bbe012017-03-24 09:11:57 +00009162 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
9163 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009164 if (Error != GE_None)
Eugene Zelenko7855e772018-04-03 00:11:50 +00009165 return {};
Chandler Carruth45bbe012017-03-24 09:11:57 +00009166
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009167 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
Chandler Carruth45bbe012017-03-24 09:11:57 +00009168
Chris Lattnerecd79c62009-06-14 00:45:47 +00009169 while (TypeStr[0] && TypeStr[0] != '.') {
Chandler Carruth45bbe012017-03-24 09:11:57 +00009170 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009171 if (Error != GE_None)
Eugene Zelenko7855e772018-04-03 00:11:50 +00009172 return {};
Chris Lattnerecd79c62009-06-14 00:45:47 +00009173
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009174 // If this argument is required to be an IntegerConstantExpression and the
9175 // caller cares, fill in the bitmask we return.
9176 if (RequiresICE && IntegerConstantArgs)
9177 *IntegerConstantArgs |= 1 << ArgTypes.size();
9178
Chris Lattnerecd79c62009-06-14 00:45:47 +00009179 // Do array -> pointer decay. The builtin should use the decayed type.
9180 if (Ty->isArrayType())
9181 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00009182
Chris Lattnerecd79c62009-06-14 00:45:47 +00009183 ArgTypes.push_back(Ty);
9184 }
9185
David Majnemerba3e5ec2015-03-13 18:26:17 +00009186 if (Id == Builtin::BI__GetExceptionInfo)
Eugene Zelenko7855e772018-04-03 00:11:50 +00009187 return {};
David Majnemerba3e5ec2015-03-13 18:26:17 +00009188
Chris Lattnerecd79c62009-06-14 00:45:47 +00009189 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
9190 "'.' should only occur at end of builtin type list!");
9191
Reid Kleckner78af0702013-08-27 23:08:25 +00009192 FunctionType::ExtInfo EI(CC_C);
John McCall991eb4b2010-12-21 00:44:39 +00009193 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
9194
9195 bool Variadic = (TypeStr[0] == '.');
9196
Richard Smith836de6b2016-12-19 23:59:34 +00009197 // We really shouldn't be making a no-proto type here.
9198 if (ArgTypes.empty() && Variadic && !getLangOpts().CPlusPlus)
John McCall991eb4b2010-12-21 00:44:39 +00009199 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00009200
John McCalldb40c7f2010-12-14 08:05:40 +00009201 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00009202 EPI.ExtInfo = EI;
9203 EPI.Variadic = Variadic;
Richard Smith391fb862016-10-18 07:13:55 +00009204 if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id))
9205 EPI.ExceptionSpec.Type =
9206 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
John McCalldb40c7f2010-12-14 08:05:40 +00009207
Jordan Rose5c382722013-03-08 21:51:21 +00009208 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009209}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00009210
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009211static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
9212 const FunctionDecl *FD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00009213 if (!FD->isExternallyVisible())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009214 return GVA_Internal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009215
Richard Smithe2467b72017-11-16 23:54:56 +00009216 // Non-user-provided functions get emitted as weak definitions with every
9217 // use, no matter whether they've been explicitly instantiated etc.
Eugene Zelenko7855e772018-04-03 00:11:50 +00009218 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
Richard Smithe2467b72017-11-16 23:54:56 +00009219 if (!MD->isUserProvided())
9220 return GVA_DiscardableODR;
9221
Yaron Keren4cd211b2017-02-22 14:32:39 +00009222 GVALinkage External;
Rafael Espindola3ae00052013-05-13 00:12:11 +00009223 switch (FD->getTemplateSpecializationKind()) {
9224 case TSK_Undeclared:
9225 case TSK_ExplicitSpecialization:
9226 External = GVA_StrongExternal;
9227 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009228
Rafael Espindola3ae00052013-05-13 00:12:11 +00009229 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00009230 return GVA_StrongODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00009231
David Majnemerc3d07332014-05-15 06:25:57 +00009232 // C++11 [temp.explicit]p10:
9233 // [ Note: The intent is that an inline function that is the subject of
9234 // an explicit instantiation declaration will still be implicitly
9235 // instantiated when used so that the body can be considered for
9236 // inlining, but that no out-of-line copy of the inline function would be
9237 // generated in the translation unit. -- end note ]
Rafael Espindola3ae00052013-05-13 00:12:11 +00009238 case TSK_ExplicitInstantiationDeclaration:
David Majnemer27d69db2014-04-28 22:17:59 +00009239 return GVA_AvailableExternally;
9240
Rafael Espindola3ae00052013-05-13 00:12:11 +00009241 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00009242 External = GVA_DiscardableODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00009243 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009244 }
9245
9246 if (!FD->isInlined())
9247 return External;
David Majnemer62f0ffd2013-08-01 17:26:42 +00009248
David Majnemer3f021502015-10-08 04:53:31 +00009249 if ((!Context.getLangOpts().CPlusPlus &&
9250 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009251 !FD->hasAttr<DLLExportAttr>()) ||
David Majnemer62f0ffd2013-08-01 17:26:42 +00009252 FD->hasAttr<GNUInlineAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009253 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
9254
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009255 // GNU or C99 inline semantics. Determine whether this symbol should be
9256 // externally visible.
9257 if (FD->isInlineDefinitionExternallyVisible())
9258 return External;
9259
9260 // C99 inline semantics, where the symbol is not externally visible.
David Majnemer27d69db2014-04-28 22:17:59 +00009261 return GVA_AvailableExternally;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009262 }
9263
David Majnemer54e3ba52014-04-02 23:17:29 +00009264 // Functions specified with extern and inline in -fms-compatibility mode
9265 // forcibly get emitted. While the body of the function cannot be later
9266 // replaced, the function definition cannot be discarded.
David Majnemer73768702015-03-20 00:02:27 +00009267 if (FD->isMSExternInline())
David Majnemer54e3ba52014-04-02 23:17:29 +00009268 return GVA_StrongODR;
9269
David Majnemer27d69db2014-04-28 22:17:59 +00009270 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009271}
9272
Artem Belevichca2b9512016-05-02 20:30:03 +00009273static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context,
Richard Smitha4653622017-09-06 20:01:14 +00009274 const Decl *D, GVALinkage L) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009275 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
9276 // dllexport/dllimport on inline functions.
9277 if (D->hasAttr<DLLImportAttr>()) {
9278 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
9279 return GVA_AvailableExternally;
Artem Belevichca2b9512016-05-02 20:30:03 +00009280 } else if (D->hasAttr<DLLExportAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009281 if (L == GVA_DiscardableODR)
9282 return GVA_StrongODR;
Artem Belevichca2b9512016-05-02 20:30:03 +00009283 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice &&
9284 D->hasAttr<CUDAGlobalAttr>()) {
9285 // Device-side functions with __global__ attribute must always be
9286 // visible externally so they can be launched from host.
9287 if (L == GVA_DiscardableODR || L == GVA_Internal)
9288 return GVA_StrongODR;
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009289 }
9290 return L;
9291}
9292
Richard Smitha4653622017-09-06 20:01:14 +00009293/// Adjust the GVALinkage for a declaration based on what an external AST source
9294/// knows about whether there can be other definitions of this declaration.
9295static GVALinkage
9296adjustGVALinkageForExternalDefinitionKind(const ASTContext &Ctx, const Decl *D,
9297 GVALinkage L) {
9298 ExternalASTSource *Source = Ctx.getExternalSource();
9299 if (!Source)
9300 return L;
9301
9302 switch (Source->hasExternalDefinitions(D)) {
David Blaikie9ffe5a32017-01-30 05:00:26 +00009303 case ExternalASTSource::EK_Never:
Richard Smitha4653622017-09-06 20:01:14 +00009304 // Other translation units rely on us to provide the definition.
David Blaikie9ffe5a32017-01-30 05:00:26 +00009305 if (L == GVA_DiscardableODR)
9306 return GVA_StrongODR;
9307 break;
Richard Smitha4653622017-09-06 20:01:14 +00009308
David Blaikie9ffe5a32017-01-30 05:00:26 +00009309 case ExternalASTSource::EK_Always:
9310 return GVA_AvailableExternally;
Richard Smitha4653622017-09-06 20:01:14 +00009311
David Blaikie9ffe5a32017-01-30 05:00:26 +00009312 case ExternalASTSource::EK_ReplyHazy:
9313 break;
9314 }
9315 return L;
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009316}
9317
Richard Smitha4653622017-09-06 20:01:14 +00009318GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
9319 return adjustGVALinkageForExternalDefinitionKind(*this, FD,
9320 adjustGVALinkageForAttributes(*this, FD,
9321 basicGVALinkageForFunction(*this, FD)));
9322}
9323
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009324static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
9325 const VarDecl *VD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00009326 if (!VD->isExternallyVisible())
9327 return GVA_Internal;
9328
David Majnemer27d69db2014-04-28 22:17:59 +00009329 if (VD->isStaticLocal()) {
David Majnemer27d69db2014-04-28 22:17:59 +00009330 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
9331 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
9332 LexicalContext = LexicalContext->getLexicalParent();
9333
David Blaikieeb210012017-01-27 23:11:10 +00009334 // ObjC Blocks can create local variables that don't have a FunctionDecl
9335 // LexicalContext.
9336 if (!LexicalContext)
9337 return GVA_DiscardableODR;
David Majnemer27d69db2014-04-28 22:17:59 +00009338
David Blaikieeb210012017-01-27 23:11:10 +00009339 // Otherwise, let the static local variable inherit its linkage from the
9340 // nearest enclosing function.
9341 auto StaticLocalLinkage =
9342 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
9343
9344 // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
9345 // be emitted in any object with references to the symbol for the object it
9346 // contains, whether inline or out-of-line."
9347 // Similar behavior is observed with MSVC. An alternative ABI could use
9348 // StrongODR/AvailableExternally to match the function, but none are
9349 // known/supported currently.
9350 if (StaticLocalLinkage == GVA_StrongODR ||
9351 StaticLocalLinkage == GVA_AvailableExternally)
9352 return GVA_DiscardableODR;
9353 return StaticLocalLinkage;
David Majnemer27d69db2014-04-28 22:17:59 +00009354 }
9355
Hans Wennborg56fc62b2014-07-17 20:25:23 +00009356 // MSVC treats in-class initialized static data members as definitions.
9357 // By giving them non-strong linkage, out-of-line definitions won't
9358 // cause link errors.
9359 if (Context.isMSStaticDataMemberInlineDefinition(VD))
9360 return GVA_DiscardableODR;
9361
Richard Smithd9b90092016-07-02 01:32:16 +00009362 // Most non-template variables have strong linkage; inline variables are
9363 // linkonce_odr or (occasionally, for compatibility) weak_odr.
9364 GVALinkage StrongLinkage;
9365 switch (Context.getInlineVariableDefinitionKind(VD)) {
9366 case ASTContext::InlineVariableDefinitionKind::None:
9367 StrongLinkage = GVA_StrongExternal;
9368 break;
9369 case ASTContext::InlineVariableDefinitionKind::Weak:
9370 case ASTContext::InlineVariableDefinitionKind::WeakUnknown:
Richard Smith62f19e72016-06-25 00:15:56 +00009371 StrongLinkage = GVA_DiscardableODR;
Richard Smithd9b90092016-07-02 01:32:16 +00009372 break;
9373 case ASTContext::InlineVariableDefinitionKind::Strong:
9374 StrongLinkage = GVA_StrongODR;
9375 break;
9376 }
Richard Smith62f19e72016-06-25 00:15:56 +00009377
Richard Smith8809a0c2013-09-27 20:14:12 +00009378 switch (VD->getTemplateSpecializationKind()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00009379 case TSK_Undeclared:
Richard Smith62f19e72016-06-25 00:15:56 +00009380 return StrongLinkage;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009381
David Majnemer6d1780c2015-07-17 23:36:49 +00009382 case TSK_ExplicitSpecialization:
David Majnemer3f021502015-10-08 04:53:31 +00009383 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
9384 VD->isStaticDataMember()
David Majnemer6d1780c2015-07-17 23:36:49 +00009385 ? GVA_StrongODR
Richard Smith62f19e72016-06-25 00:15:56 +00009386 : StrongLinkage;
David Majnemer6d1780c2015-07-17 23:36:49 +00009387
Rafael Espindola3ae00052013-05-13 00:12:11 +00009388 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00009389 return GVA_StrongODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009390
David Majnemer27d69db2014-04-28 22:17:59 +00009391 case TSK_ExplicitInstantiationDeclaration:
9392 return GVA_AvailableExternally;
9393
Rafael Espindola3ae00052013-05-13 00:12:11 +00009394 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00009395 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009396 }
Rafael Espindola27699c82013-05-13 14:05:53 +00009397
9398 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009399}
9400
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009401GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
Richard Smitha4653622017-09-06 20:01:14 +00009402 return adjustGVALinkageForExternalDefinitionKind(*this, VD,
9403 adjustGVALinkageForAttributes(*this, VD,
9404 basicGVALinkageForVariable(*this, VD)));
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009405}
9406
David Blaikiee6b7c282017-04-11 20:46:34 +00009407bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00009408 if (const auto *VD = dyn_cast<VarDecl>(D)) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009409 if (!VD->isFileVarDecl())
9410 return false;
Renato Golin9258aa52014-05-21 10:40:27 +00009411 // Global named register variables (GNU extension) are never emitted.
9412 if (VD->getStorageClass() == SC_Register)
9413 return false;
Richard Smith7747ce22015-08-19 20:49:38 +00009414 if (VD->getDescribedVarTemplate() ||
9415 isa<VarTemplatePartialSpecializationDecl>(VD))
9416 return false;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009417 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
Richard Smith5205a8c2013-04-01 20:22:16 +00009418 // We never need to emit an uninstantiated function template.
9419 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
9420 return false;
Nico Weber66220292016-03-02 17:28:48 +00009421 } else if (isa<PragmaCommentDecl>(D))
9422 return true;
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00009423 else if (isa<OMPThreadPrivateDecl>(D))
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00009424 return true;
Nico Webercbbaeb12016-03-02 19:28:54 +00009425 else if (isa<PragmaDetectMismatchDecl>(D))
9426 return true;
Nico Weber66220292016-03-02 17:28:48 +00009427 else if (isa<OMPThreadPrivateDecl>(D))
Alexey Bataevc5b1d322016-03-04 09:22:22 +00009428 return !D->getDeclContext()->isDependentContext();
9429 else if (isa<OMPDeclareReductionDecl>(D))
9430 return !D->getDeclContext()->isDependentContext();
Richard Smithdc1f0422016-07-20 19:10:16 +00009431 else if (isa<ImportDecl>(D))
9432 return true;
Alexey Bataev97720002014-11-11 04:05:39 +00009433 else
Richard Smith5205a8c2013-04-01 20:22:16 +00009434 return false;
9435
9436 // If this is a member of a class template, we do not need to emit it.
9437 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009438 return false;
9439
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00009440 // Weak references don't produce any output by themselves.
9441 if (D->hasAttr<WeakRefAttr>())
9442 return false;
9443
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009444 // Aliases and used decls are required.
9445 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
9446 return true;
9447
Eugene Zelenko7855e772018-04-03 00:11:50 +00009448 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009449 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00009450 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00009451 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009452
9453 // Constructors and destructors are required.
9454 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
9455 return true;
9456
John McCall6bd2a892013-01-25 22:31:03 +00009457 // The key function for a class is required. This rule only comes
9458 // into play when inline functions can be key functions, though.
9459 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00009460 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
John McCall6bd2a892013-01-25 22:31:03 +00009461 const CXXRecordDecl *RD = MD->getParent();
9462 if (MD->isOutOfLine() && RD->isDynamicClass()) {
9463 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
9464 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
9465 return true;
9466 }
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009467 }
9468 }
9469
David Blaikie9ffe5a32017-01-30 05:00:26 +00009470 GVALinkage Linkage = GetGVALinkageForFunction(FD);
9471
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009472 // static, static inline, always_inline, and extern inline functions can
9473 // always be deferred. Normal inline functions can be deferred in C99/C++.
9474 // Implicit template instantiations can also be deferred in C++.
David Blaikie9ffe5a32017-01-30 05:00:26 +00009475 return !isDiscardableGVALinkage(Linkage);
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009476 }
Douglas Gregor87d81242011-09-10 00:22:34 +00009477
Eugene Zelenko7855e772018-04-03 00:11:50 +00009478 const auto *VD = cast<VarDecl>(D);
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009479 assert(VD->isFileVarDecl() && "Expected file scoped var");
9480
Hans Wennborg56fc62b2014-07-17 20:25:23 +00009481 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
9482 !isMSStaticDataMemberInlineDefinition(VD))
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00009483 return false;
9484
Richard Smitha0e5e542012-11-12 21:38:00 +00009485 // Variables that can be needed in other TUs are required.
Richard Smitha4653622017-09-06 20:01:14 +00009486 auto Linkage = GetGVALinkageForVariable(VD);
9487 if (!isDiscardableGVALinkage(Linkage))
Richard Smitha0e5e542012-11-12 21:38:00 +00009488 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009489
Richard Smitha4653622017-09-06 20:01:14 +00009490 // We never need to emit a variable that is available in another TU.
9491 if (Linkage == GVA_AvailableExternally)
9492 return false;
9493
Richard Smitha0e5e542012-11-12 21:38:00 +00009494 // Variables that have destruction with side-effects are required.
9495 if (VD->getType().isDestructedType())
9496 return true;
9497
9498 // Variables that have initialization with side-effects are required.
Richard Smith7747ce22015-08-19 20:49:38 +00009499 if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
Richard Smith187ffb42017-01-20 01:19:46 +00009500 // We can get a value-dependent initializer during error recovery.
9501 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
Richard Smitha0e5e542012-11-12 21:38:00 +00009502 return true;
9503
Richard Smithda383632016-08-15 01:33:41 +00009504 // Likewise, variables with tuple-like bindings are required if their
9505 // bindings have side-effects.
Eugene Zelenko7855e772018-04-03 00:11:50 +00009506 if (const auto *DD = dyn_cast<DecompositionDecl>(VD))
9507 for (const auto *BD : DD->bindings())
9508 if (const auto *BindingVD = BD->getHoldingVar())
Richard Smithda383632016-08-15 01:33:41 +00009509 if (DeclMustBeEmitted(BindingVD))
9510 return true;
9511
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00009512 // If the decl is marked as `declare target`, it should be emitted.
Alexey Bataev92327c52018-03-26 16:40:55 +00009513 for (const auto *Decl : D->redecls()) {
9514 if (!Decl->hasAttrs())
9515 continue;
9516 if (const auto *Attr = Decl->getAttr<OMPDeclareTargetDeclAttr>())
9517 if (Attr->getMapType() != OMPDeclareTargetDeclAttr::MT_Link)
9518 return true;
9519 }
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00009520
Richard Smitha0e5e542012-11-12 21:38:00 +00009521 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009522}
Charles Davis53c59df2010-08-16 03:33:14 +00009523
Erich Keane281d20b2018-01-08 21:34:17 +00009524void ASTContext::forEachMultiversionedFunctionVersion(
9525 const FunctionDecl *FD,
9526 llvm::function_ref<void(const FunctionDecl *)> Pred) const {
9527 assert(FD->isMultiVersion() && "Only valid for multiversioned functions");
9528 llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls;
9529 FD = FD->getCanonicalDecl();
9530 for (auto *CurDecl :
9531 FD->getDeclContext()->getRedeclContext()->lookup(FD->getDeclName())) {
9532 FunctionDecl *CurFD = CurDecl->getAsFunction()->getCanonicalDecl();
9533 if (CurFD && hasSameType(CurFD->getType(), FD->getType()) &&
9534 std::end(SeenDecls) == llvm::find(SeenDecls, CurFD)) {
9535 SeenDecls.insert(CurFD);
9536 Pred(CurFD);
9537 }
9538 }
9539}
9540
Reid Kleckner78af0702013-08-27 23:08:25 +00009541CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
9542 bool IsCXXMethod) const {
Charles Davis99202b32010-11-09 18:04:24 +00009543 // Pass through to the C++ ABI object
Reid Kleckner78af0702013-08-27 23:08:25 +00009544 if (IsCXXMethod)
9545 return ABI->getDefaultMethodCallConv(IsVariadic);
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00009546
Alexey Bataeva7547182016-05-18 09:06:38 +00009547 switch (LangOpts.getDefaultCallingConv()) {
9548 case LangOptions::DCC_None:
9549 break;
9550 case LangOptions::DCC_CDecl:
9551 return CC_C;
9552 case LangOptions::DCC_FastCall:
Erich Keane5759fa72017-10-24 23:12:01 +00009553 if (getTargetInfo().hasFeature("sse2") && !IsVariadic)
Alexey Bataeva7547182016-05-18 09:06:38 +00009554 return CC_X86FastCall;
9555 break;
9556 case LangOptions::DCC_StdCall:
9557 if (!IsVariadic)
9558 return CC_X86StdCall;
9559 break;
9560 case LangOptions::DCC_VectorCall:
9561 // __vectorcall cannot be applied to variadic functions.
9562 if (!IsVariadic)
9563 return CC_X86VectorCall;
9564 break;
Erich Keanea957ffb2017-11-02 21:08:00 +00009565 case LangOptions::DCC_RegCall:
9566 // __regcall cannot be applied to variadic functions.
9567 if (!IsVariadic)
9568 return CC_X86RegCall;
9569 break;
Alexey Bataeva7547182016-05-18 09:06:38 +00009570 }
Alexander Kornienko21de0ae2015-01-20 11:20:41 +00009571 return Target->getDefaultCallingConv(TargetInfo::CCMT_Unknown);
Charles Davis99202b32010-11-09 18:04:24 +00009572}
9573
Jay Foad39c79802011-01-12 09:06:06 +00009574bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00009575 // Pass through to the C++ ABI object
9576 return ABI->isNearlyEmpty(RD);
9577}
9578
Reid Kleckner96f8f932014-02-05 17:27:08 +00009579VTableContextBase *ASTContext::getVTableContext() {
9580 if (!VTContext.get()) {
9581 if (Target->getCXXABI().isMicrosoft())
9582 VTContext.reset(new MicrosoftVTableContext(*this));
9583 else
9584 VTContext.reset(new ItaniumVTableContext(*this));
9585 }
9586 return VTContext.get();
9587}
9588
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00009589MangleContext *ASTContext::createMangleContext() {
John McCall359b8852013-01-25 22:30:49 +00009590 switch (Target->getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +00009591 case TargetCXXABI::GenericAArch64:
John McCall359b8852013-01-25 22:30:49 +00009592 case TargetCXXABI::GenericItanium:
9593 case TargetCXXABI::GenericARM:
Zoran Jovanovic26a12162015-02-18 15:21:35 +00009594 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +00009595 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +00009596 case TargetCXXABI::iOS64:
Dan Gohmanc2853072015-09-03 22:51:53 +00009597 case TargetCXXABI::WebAssembly:
Tim Northover756447a2015-10-30 16:30:36 +00009598 case TargetCXXABI::WatchOS:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00009599 return ItaniumMangleContext::create(*this, getDiagnostics());
John McCall359b8852013-01-25 22:30:49 +00009600 case TargetCXXABI::Microsoft:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00009601 return MicrosoftMangleContext::create(*this, getDiagnostics());
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00009602 }
David Blaikie83d382b2011-09-23 05:06:16 +00009603 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00009604}
9605
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009606CXXABI::~CXXABI() = default;
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00009607
9608size_t ASTContext::getSideTableAllocatedMemory() const {
Larisse Voufo39a1e502013-08-06 01:03:05 +00009609 return ASTRecordLayouts.getMemorySize() +
9610 llvm::capacity_in_bytes(ObjCLayouts) +
9611 llvm::capacity_in_bytes(KeyFunctions) +
9612 llvm::capacity_in_bytes(ObjCImpls) +
9613 llvm::capacity_in_bytes(BlockVarCopyInits) +
9614 llvm::capacity_in_bytes(DeclAttrs) +
9615 llvm::capacity_in_bytes(TemplateOrInstantiation) +
9616 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
9617 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
9618 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
9619 llvm::capacity_in_bytes(OverriddenMethods) +
9620 llvm::capacity_in_bytes(Types) +
9621 llvm::capacity_in_bytes(VariableArrayTypes) +
9622 llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00009623}
Ted Kremenek540017e2011-10-06 05:00:56 +00009624
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00009625/// getIntTypeForBitwidth -
9626/// sets integer QualTy according to specified details:
9627/// bitwidth, signed/unsigned.
9628/// Returns empty type if there is no appropriate target types.
9629QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
9630 unsigned Signed) const {
9631 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
9632 CanQualType QualTy = getFromTargetType(Ty);
9633 if (!QualTy && DestWidth == 128)
9634 return Signed ? Int128Ty : UnsignedInt128Ty;
9635 return QualTy;
9636}
9637
9638/// getRealTypeForBitwidth -
9639/// sets floating point QualTy according to specified bitwidth.
9640/// Returns empty type if there is no appropriate target types.
9641QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
9642 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
9643 switch (Ty) {
9644 case TargetInfo::Float:
9645 return FloatTy;
9646 case TargetInfo::Double:
9647 return DoubleTy;
9648 case TargetInfo::LongDouble:
9649 return LongDoubleTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00009650 case TargetInfo::Float128:
9651 return Float128Ty;
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00009652 case TargetInfo::NoFloat:
Eugene Zelenko7855e772018-04-03 00:11:50 +00009653 return {};
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00009654 }
9655
9656 llvm_unreachable("Unhandled TargetInfo::RealType value");
9657}
9658
Eli Friedman3b7d46c2013-07-10 00:30:46 +00009659void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
9660 if (Number > 1)
9661 MangleNumbers[ND] = Number;
David Blaikie095deba2012-11-14 01:52:05 +00009662}
9663
Eli Friedman3b7d46c2013-07-10 00:30:46 +00009664unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
Richard Smithe9b02d62016-03-21 22:33:02 +00009665 auto I = MangleNumbers.find(ND);
Eli Friedman3b7d46c2013-07-10 00:30:46 +00009666 return I != MangleNumbers.end() ? I->second : 1;
David Blaikie095deba2012-11-14 01:52:05 +00009667}
9668
David Majnemer2206bf52014-03-05 08:57:59 +00009669void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
9670 if (Number > 1)
9671 StaticLocalNumbers[VD] = Number;
9672}
9673
9674unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
Richard Smithe9b02d62016-03-21 22:33:02 +00009675 auto I = StaticLocalNumbers.find(VD);
David Majnemer2206bf52014-03-05 08:57:59 +00009676 return I != StaticLocalNumbers.end() ? I->second : 1;
9677}
9678
Eli Friedman3b7d46c2013-07-10 00:30:46 +00009679MangleNumberingContext &
9680ASTContext::getManglingNumberContext(const DeclContext *DC) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00009681 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
Justin Lebar20ebffc2016-10-10 16:26:19 +00009682 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
Reid Klecknerd8110b62013-09-10 20:14:30 +00009683 if (!MCtx)
9684 MCtx = createMangleNumberingContext();
9685 return *MCtx;
9686}
9687
Justin Lebar20ebffc2016-10-10 16:26:19 +00009688std::unique_ptr<MangleNumberingContext>
9689ASTContext::createMangleNumberingContext() const {
Reid Klecknerd8110b62013-09-10 20:14:30 +00009690 return ABI->createMangleNumberingContext();
Douglas Gregor63798542012-02-20 19:44:39 +00009691}
9692
David Majnemere7a818f2015-03-06 18:53:55 +00009693const CXXConstructorDecl *
9694ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
9695 return ABI->getCopyConstructorForExceptionObject(
9696 cast<CXXRecordDecl>(RD->getFirstDecl()));
9697}
9698
9699void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
9700 CXXConstructorDecl *CD) {
9701 return ABI->addCopyConstructorForExceptionObject(
9702 cast<CXXRecordDecl>(RD->getFirstDecl()),
9703 cast<CXXConstructorDecl>(CD->getFirstDecl()));
9704}
9705
David Majnemer00350522015-08-31 18:48:39 +00009706void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD,
9707 TypedefNameDecl *DD) {
9708 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
9709}
9710
9711TypedefNameDecl *
9712ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) {
9713 return ABI->getTypedefNameForUnnamedTagDecl(TD);
9714}
9715
9716void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD,
9717 DeclaratorDecl *DD) {
9718 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
9719}
9720
9721DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) {
9722 return ABI->getDeclaratorForUnnamedTagDecl(TD);
9723}
9724
Ted Kremenek540017e2011-10-06 05:00:56 +00009725void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
9726 ParamIndices[D] = index;
9727}
9728
9729unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
9730 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
9731 assert(I != ParamIndices.end() &&
9732 "ParmIndices lacks entry set by ParmVarDecl");
9733 return I->second;
9734}
Fariborz Jahanian615de762013-05-28 17:37:39 +00009735
Richard Smithe6c01442013-06-05 00:46:14 +00009736APValue *
9737ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
9738 bool MayCreate) {
9739 assert(E && E->getStorageDuration() == SD_Static &&
9740 "don't need to cache the computed value for this temporary");
David Majnemer2dcef9e2015-08-13 23:50:15 +00009741 if (MayCreate) {
9742 APValue *&MTVI = MaterializedTemporaryValues[E];
9743 if (!MTVI)
9744 MTVI = new (*this) APValue;
9745 return MTVI;
9746 }
Richard Smithe6c01442013-06-05 00:46:14 +00009747
David Majnemer2dcef9e2015-08-13 23:50:15 +00009748 return MaterializedTemporaryValues.lookup(E);
Richard Smithe6c01442013-06-05 00:46:14 +00009749}
9750
Fariborz Jahanian615de762013-05-28 17:37:39 +00009751bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
9752 const llvm::Triple &T = getTargetInfo().getTriple();
9753 if (!T.isOSDarwin())
9754 return false;
9755
Bob Wilson2c82c3d2013-11-02 23:27:49 +00009756 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
9757 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
9758 return false;
9759
Fariborz Jahanian615de762013-05-28 17:37:39 +00009760 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
9761 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
9762 uint64_t Size = sizeChars.getQuantity();
9763 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
9764 unsigned Align = alignChars.getQuantity();
9765 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
9766 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
9767}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009768
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009769static ast_type_traits::DynTypedNode getSingleDynTypedNodeFromParentMap(
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009770 ASTContext::ParentMapPointers::mapped_type U) {
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +00009771 if (const auto *D = U.dyn_cast<const Decl *>())
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009772 return ast_type_traits::DynTypedNode::create(*D);
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +00009773 if (const auto *S = U.dyn_cast<const Stmt *>())
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009774 return ast_type_traits::DynTypedNode::create(*S);
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +00009775 return *U.get<ast_type_traits::DynTypedNode *>();
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009776}
9777
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009778namespace {
9779
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009780/// Template specializations to abstract away from pointers and TypeLocs.
9781/// @{
9782template <typename T>
9783ast_type_traits::DynTypedNode createDynTypedNode(const T &Node) {
9784 return ast_type_traits::DynTypedNode::create(*Node);
9785}
9786template <>
9787ast_type_traits::DynTypedNode createDynTypedNode(const TypeLoc &Node) {
9788 return ast_type_traits::DynTypedNode::create(Node);
9789}
9790template <>
9791ast_type_traits::DynTypedNode
9792createDynTypedNode(const NestedNameSpecifierLoc &Node) {
9793 return ast_type_traits::DynTypedNode::create(Node);
9794}
9795/// @}
9796
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009797 /// A \c RecursiveASTVisitor that builds a map from nodes to their
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009798 /// parents as defined by the \c RecursiveASTVisitor.
9799 ///
9800 /// Note that the relationship described here is purely in terms of AST
9801 /// traversal - there are other relationships (for example declaration context)
9802 /// in the AST that are better modeled by special matchers.
9803 ///
Benjamin Kramere8c51fd2015-10-21 10:07:26 +00009804 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009805 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009806 public:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009807 /// Builds and returns the translation unit's parent map.
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009808 ///
9809 /// The caller takes ownership of the returned \c ParentMap.
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009810 static std::pair<ASTContext::ParentMapPointers *,
9811 ASTContext::ParentMapOtherNodes *>
9812 buildMap(TranslationUnitDecl &TU) {
9813 ParentMapASTVisitor Visitor(new ASTContext::ParentMapPointers,
9814 new ASTContext::ParentMapOtherNodes);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009815 Visitor.TraverseDecl(&TU);
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009816 return std::make_pair(Visitor.Parents, Visitor.OtherParents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009817 }
9818
9819 private:
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009820 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
9821
9822 using VisitorBase = RecursiveASTVisitor<ParentMapASTVisitor>;
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009823
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009824 ParentMapASTVisitor(ASTContext::ParentMapPointers *Parents,
9825 ASTContext::ParentMapOtherNodes *OtherParents)
9826 : Parents(Parents), OtherParents(OtherParents) {}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009827
9828 bool shouldVisitTemplateInstantiations() const {
9829 return true;
9830 }
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009831
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009832 bool shouldVisitImplicitCode() const {
9833 return true;
9834 }
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009835
Richard Smith85838722015-11-24 03:09:01 +00009836 template <typename T, typename MapNodeTy, typename BaseTraverseFn,
9837 typename MapTy>
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009838 bool TraverseNode(T Node, MapNodeTy MapNode,
Richard Smith85838722015-11-24 03:09:01 +00009839 BaseTraverseFn BaseTraverse, MapTy *Parents) {
Craig Topper36250ad2014-05-12 05:36:57 +00009840 if (!Node)
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009841 return true;
Manuel Klimek95403e62014-05-21 13:28:59 +00009842 if (ParentStack.size() > 0) {
Benjamin Kramere8c51fd2015-10-21 10:07:26 +00009843 // FIXME: Currently we add the same parent multiple times, but only
9844 // when no memoization data is available for the type.
9845 // For example when we visit all subexpressions of template
9846 // instantiations; this is suboptimal, but benign: the only way to
9847 // visit those is with hasAncestor / hasParent, and those do not create
9848 // new matches.
9849 // The plan is to enable DynTypedNode to be storable in a map or hash
9850 // map. The main problem there is to implement hash functions /
9851 // comparison operators for all types that DynTypedNode supports that
9852 // do not have pointer identity.
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009853 auto &NodeOrVector = (*Parents)[MapNode];
Manuel Klimek95403e62014-05-21 13:28:59 +00009854 if (NodeOrVector.isNull()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009855 if (const auto *D = ParentStack.back().get<Decl>())
9856 NodeOrVector = D;
9857 else if (const auto *S = ParentStack.back().get<Stmt>())
9858 NodeOrVector = S;
9859 else
9860 NodeOrVector =
9861 new ast_type_traits::DynTypedNode(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00009862 } else {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009863 if (!NodeOrVector.template is<ASTContext::ParentVector *>()) {
9864 auto *Vector = new ASTContext::ParentVector(
9865 1, getSingleDynTypedNodeFromParentMap(NodeOrVector));
Gabor Horvath10a837a2017-04-19 15:11:10 +00009866 delete NodeOrVector
9867 .template dyn_cast<ast_type_traits::DynTypedNode *>();
Benjamin Kramer422b3ff2015-10-23 13:24:18 +00009868 NodeOrVector = Vector;
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00009869 }
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00009870
9871 auto *Vector =
9872 NodeOrVector.template get<ASTContext::ParentVector *>();
9873 // Skip duplicates for types that have memoization data.
9874 // We must check that the type has memoization data before calling
9875 // std::find() because DynTypedNode::operator== can't compare all
9876 // types.
9877 bool Found = ParentStack.back().getMemoizationData() &&
9878 std::find(Vector->begin(), Vector->end(),
9879 ParentStack.back()) != Vector->end();
9880 if (!Found)
9881 Vector->push_back(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00009882 }
9883 }
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009884 ParentStack.push_back(createDynTypedNode(Node));
Richard Smith85838722015-11-24 03:09:01 +00009885 bool Result = BaseTraverse();
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009886 ParentStack.pop_back();
9887 return Result;
9888 }
9889
9890 bool TraverseDecl(Decl *DeclNode) {
Richard Smith85838722015-11-24 03:09:01 +00009891 return TraverseNode(DeclNode, DeclNode,
9892 [&] { return VisitorBase::TraverseDecl(DeclNode); },
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009893 Parents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009894 }
9895
9896 bool TraverseStmt(Stmt *StmtNode) {
Richard Smith85838722015-11-24 03:09:01 +00009897 return TraverseNode(StmtNode, StmtNode,
9898 [&] { return VisitorBase::TraverseStmt(StmtNode); },
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009899 Parents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009900 }
9901
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009902 bool TraverseTypeLoc(TypeLoc TypeLocNode) {
Richard Smith85838722015-11-24 03:09:01 +00009903 return TraverseNode(
9904 TypeLocNode, ast_type_traits::DynTypedNode::create(TypeLocNode),
9905 [&] { return VisitorBase::TraverseTypeLoc(TypeLocNode); },
9906 OtherParents);
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009907 }
9908
9909 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNSLocNode) {
9910 return TraverseNode(
9911 NNSLocNode, ast_type_traits::DynTypedNode::create(NNSLocNode),
Richard Smith85838722015-11-24 03:09:01 +00009912 [&] {
9913 return VisitorBase::TraverseNestedNameSpecifierLoc(NNSLocNode);
9914 },
9915 OtherParents);
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009916 }
9917
9918 ASTContext::ParentMapPointers *Parents;
9919 ASTContext::ParentMapOtherNodes *OtherParents;
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009920 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009921 };
9922
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009923} // namespace
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009924
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009925template <typename NodeTy, typename MapTy>
9926static ASTContext::DynTypedNodeList getDynNodeFromMap(const NodeTy &Node,
9927 const MapTy &Map) {
9928 auto I = Map.find(Node);
9929 if (I == Map.end()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009930 return llvm::ArrayRef<ast_type_traits::DynTypedNode>();
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009931 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00009932 if (const auto *V =
9933 I->second.template dyn_cast<ASTContext::ParentVector *>()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009934 return llvm::makeArrayRef(*V);
Manuel Klimek95403e62014-05-21 13:28:59 +00009935 }
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009936 return getSingleDynTypedNodeFromParentMap(I->second);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009937}
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00009938
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009939ASTContext::DynTypedNodeList
9940ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
9941 if (!PointerParents) {
9942 // We always need to run over the whole translation unit, as
9943 // hasAncestor can escape any subtree.
9944 auto Maps = ParentMapASTVisitor::buildMap(*getTranslationUnitDecl());
9945 PointerParents.reset(Maps.first);
9946 OtherParents.reset(Maps.second);
9947 }
9948 if (Node.getNodeKind().hasPointerIdentity())
9949 return getDynNodeFromMap(Node.getMemoizationData(), *PointerParents);
9950 return getDynNodeFromMap(Node, *OtherParents);
9951}
9952
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00009953bool
9954ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
9955 const ObjCMethodDecl *MethodImpl) {
9956 // No point trying to match an unavailable/deprecated mothod.
9957 if (MethodDecl->hasAttr<UnavailableAttr>()
9958 || MethodDecl->hasAttr<DeprecatedAttr>())
9959 return false;
9960 if (MethodDecl->getObjCDeclQualifier() !=
9961 MethodImpl->getObjCDeclQualifier())
9962 return false;
Alp Toker314cc812014-01-25 16:55:45 +00009963 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00009964 return false;
9965
9966 if (MethodDecl->param_size() != MethodImpl->param_size())
9967 return false;
9968
9969 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
9970 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
9971 EF = MethodDecl->param_end();
9972 IM != EM && IF != EF; ++IM, ++IF) {
9973 const ParmVarDecl *DeclVar = (*IF);
9974 const ParmVarDecl *ImplVar = (*IM);
9975 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
9976 return false;
9977 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
9978 return false;
9979 }
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009980
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00009981 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00009982}
Richard Smith053f6c62014-05-16 23:01:30 +00009983
Yaxun Liu402804b2016-12-15 08:09:08 +00009984uint64_t ASTContext::getTargetNullPointerValue(QualType QT) const {
Alexander Richardson6d989432017-10-15 18:48:14 +00009985 LangAS AS;
Yaxun Liu402804b2016-12-15 08:09:08 +00009986 if (QT->getUnqualifiedDesugaredType()->isNullPtrType())
Alexander Richardson6d989432017-10-15 18:48:14 +00009987 AS = LangAS::Default;
Yaxun Liu402804b2016-12-15 08:09:08 +00009988 else
9989 AS = QT->getPointeeType().getAddressSpace();
9990
9991 return getTargetInfo().getNullPointerValue(AS);
9992}
9993
Alexander Richardson6d989432017-10-15 18:48:14 +00009994unsigned ASTContext::getTargetAddressSpace(LangAS AS) const {
9995 if (isTargetAddressSpace(AS))
9996 return toTargetAddressSpace(AS);
Yaxun Liub34ec822017-04-11 17:24:23 +00009997 else
Alexander Richardson6d989432017-10-15 18:48:14 +00009998 return (*AddrSpaceMap)[(unsigned)AS];
Yaxun Liub34ec822017-04-11 17:24:23 +00009999}
10000
Richard Smith053f6c62014-05-16 23:01:30 +000010001// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
10002// doesn't include ASTContext.h
10003template
10004clang::LazyGenerationalUpdatePtr<
10005 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
10006clang::LazyGenerationalUpdatePtr<
10007 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
10008 const clang::ASTContext &Ctx, Decl *Value);