blob: d0a790cad4db70577b0f5fe26f26e4b321b15cc1 [file] [log] [blame]
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00001//===- ASTContext.cpp - Context to hold long-lived AST nodes --------------===//
Chris Lattnerddc135e2006-11-10 06:34:16 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chris Lattnerddc135e2006-11-10 06:34:16 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the ASTContext interface.
10//
11//===----------------------------------------------------------------------===//
12
13#include "clang/AST/ASTContext.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000014#include "CXXABI.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000015#include "clang/AST/APValue.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000016#include "clang/AST/ASTMutationListener.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000017#include "clang/AST/ASTTypeTraits.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000018#include "clang/AST/Attr.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000019#include "clang/AST/AttrIterator.h"
Ken Dyck8c89d592009-12-22 14:23:30 +000020#include "clang/AST/CharUnits.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000021#include "clang/AST/Comment.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000022#include "clang/AST/Decl.h"
23#include "clang/AST/DeclBase.h"
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +000024#include "clang/AST/DeclCXX.h"
Chandler Carruthaa36b892015-12-30 03:40:23 +000025#include "clang/AST/DeclContextInternals.h"
Steve Naroff67391b82007-10-01 19:00:59 +000026#include "clang/AST/DeclObjC.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000027#include "clang/AST/DeclOpenMP.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000028#include "clang/AST/DeclTemplate.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000029#include "clang/AST/DeclarationName.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000030#include "clang/AST/Expr.h"
John McCall87fe5d52010-05-20 01:18:31 +000031#include "clang/AST/ExprCXX.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000032#include "clang/AST/ExternalASTSource.h"
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000033#include "clang/AST/Mangle.h"
Reid Klecknerd8110b62013-09-10 20:14:30 +000034#include "clang/AST/MangleNumberingContext.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000035#include "clang/AST/NestedNameSpecifier.h"
36#include "clang/AST/RawCommentList.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000037#include "clang/AST/RecordLayout.h"
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000038#include "clang/AST/RecursiveASTVisitor.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000039#include "clang/AST/Stmt.h"
40#include "clang/AST/TemplateBase.h"
41#include "clang/AST/TemplateName.h"
42#include "clang/AST/Type.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000043#include "clang/AST/TypeLoc.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000044#include "clang/AST/UnresolvedSet.h"
Reid Kleckner96f8f932014-02-05 17:27:08 +000045#include "clang/AST/VTableBuilder.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000046#include "clang/Basic/AddressSpaces.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000047#include "clang/Basic/Builtins.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000048#include "clang/Basic/CommentOptions.h"
Eugene Zelenko7855e772018-04-03 00:11:50 +000049#include "clang/Basic/ExceptionSpecificationType.h"
Leonard Chana6779422018-08-06 16:42:37 +000050#include "clang/Basic/FixedPoint.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000051#include "clang/Basic/IdentifierTable.h"
52#include "clang/Basic/LLVM.h"
53#include "clang/Basic/LangOptions.h"
54#include "clang/Basic/Linkage.h"
55#include "clang/Basic/ObjCRuntime.h"
56#include "clang/Basic/SanitizerBlacklist.h"
57#include "clang/Basic/SourceLocation.h"
Chris Lattnerd2868512009-03-28 03:45:20 +000058#include "clang/Basic/SourceManager.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000059#include "clang/Basic/Specifiers.h"
60#include "clang/Basic/TargetCXXABI.h"
Chris Lattner4dc8a6f2007-05-20 23:50:58 +000061#include "clang/Basic/TargetInfo.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000062#include "clang/Basic/XRayLists.h"
63#include "llvm/ADT/APInt.h"
64#include "llvm/ADT/APSInt.h"
65#include "llvm/ADT/ArrayRef.h"
66#include "llvm/ADT/DenseMap.h"
67#include "llvm/ADT/DenseSet.h"
68#include "llvm/ADT/FoldingSet.h"
69#include "llvm/ADT/None.h"
70#include "llvm/ADT/Optional.h"
71#include "llvm/ADT/PointerUnion.h"
72#include "llvm/ADT/STLExtras.h"
73#include "llvm/ADT/SmallPtrSet.h"
74#include "llvm/ADT/SmallVector.h"
Anders Carlssond8499822007-10-29 05:01:08 +000075#include "llvm/ADT/StringExtras.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000076#include "llvm/ADT/StringRef.h"
Robert Lyttoneaf6f362013-11-12 10:09:34 +000077#include "llvm/ADT/Triple.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000078#include "llvm/Support/Capacity.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000079#include "llvm/Support/Casting.h"
80#include "llvm/Support/Compiler.h"
81#include "llvm/Support/ErrorHandling.h"
Nate Begemanb699c9b2009-01-18 06:42:49 +000082#include "llvm/Support/MathExtras.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000083#include "llvm/Support/raw_ostream.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000084#include <algorithm>
85#include <cassert>
86#include <cstddef>
87#include <cstdint>
88#include <cstdlib>
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +000089#include <map>
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000090#include <memory>
91#include <string>
92#include <tuple>
93#include <utility>
Anders Carlssona4267a62009-07-18 21:19:52 +000094
Chris Lattnerddc135e2006-11-10 06:34:16 +000095using namespace clang;
96
Steve Naroff0af91202007-04-27 21:51:21 +000097enum FloatingRank {
Sjoerd Meijercc623ad2017-09-08 15:15:00 +000098 Float16Rank, HalfRank, FloatRank, DoubleRank, LongDoubleRank, Float128Rank
Steve Naroff0af91202007-04-27 21:51:21 +000099};
100
Dmitri Gribenkof26054f2012-07-11 21:38:39 +0000101RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000102 assert(D);
103
Jan Korous6644d012019-04-10 20:23:33 +0000104 // If we already tried to load comments but there are none,
105 // we won't find anything.
106 if (CommentsLoaded && Comments.getComments().empty())
107 return nullptr;
108
Dmitri Gribenkodf17d642012-06-28 16:19:39 +0000109 // User can not attach documentation to implicit declarations.
110 if (D->isImplicit())
Craig Topper36250ad2014-05-12 05:36:57 +0000111 return nullptr;
Dmitri Gribenkodf17d642012-06-28 16:19:39 +0000112
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000113 // User can not attach documentation to implicit instantiations.
Eugene Zelenko7855e772018-04-03 00:11:50 +0000114 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000115 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +0000116 return nullptr;
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000117 }
118
Eugene Zelenko7855e772018-04-03 00:11:50 +0000119 if (const auto *VD = dyn_cast<VarDecl>(D)) {
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000120 if (VD->isStaticDataMember() &&
121 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +0000122 return nullptr;
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000123 }
124
Eugene Zelenko7855e772018-04-03 00:11:50 +0000125 if (const auto *CRD = dyn_cast<CXXRecordDecl>(D)) {
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000126 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +0000127 return nullptr;
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000128 }
129
Eugene Zelenko7855e772018-04-03 00:11:50 +0000130 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000131 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
132 if (TSK == TSK_ImplicitInstantiation ||
133 TSK == TSK_Undeclared)
Craig Topper36250ad2014-05-12 05:36:57 +0000134 return nullptr;
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000135 }
136
Eugene Zelenko7855e772018-04-03 00:11:50 +0000137 if (const auto *ED = dyn_cast<EnumDecl>(D)) {
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000138 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +0000139 return nullptr;
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000140 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000141 if (const auto *TD = dyn_cast<TagDecl>(D)) {
Fariborz Jahanian799a4032013-04-17 21:05:20 +0000142 // When tag declaration (but not definition!) is part of the
143 // decl-specifier-seq of some other declaration, it doesn't get comment
144 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
Craig Topper36250ad2014-05-12 05:36:57 +0000145 return nullptr;
Fariborz Jahanian799a4032013-04-17 21:05:20 +0000146 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000147 // TODO: handle comments for function parameters properly.
148 if (isa<ParmVarDecl>(D))
Craig Topper36250ad2014-05-12 05:36:57 +0000149 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000150
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000151 // TODO: we could look up template parameter documentation in the template
152 // documentation.
153 if (isa<TemplateTypeParmDecl>(D) ||
154 isa<NonTypeTemplateParmDecl>(D) ||
155 isa<TemplateTemplateParmDecl>(D))
Craig Topper36250ad2014-05-12 05:36:57 +0000156 return nullptr;
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000157
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000158 // Find declaration location.
159 // For Objective-C declarations we generally don't expect to have multiple
160 // declarators, thus use declaration starting location as the "declaration
161 // location".
162 // For all other declarations multiple declarators are used quite frequently,
163 // so we use the location of the identifier as the "declaration location".
164 SourceLocation DeclLoc;
165 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000166 isa<ObjCPropertyDecl>(D) ||
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +0000167 isa<RedeclarableTemplateDecl>(D) ||
168 isa<ClassTemplateSpecializationDecl>(D))
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000169 DeclLoc = D->getBeginLoc();
Fariborz Jahanianb64e95f2013-07-24 22:58:51 +0000170 else {
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000171 DeclLoc = D->getLocation();
Dmitri Gribenkoef099dc2014-03-27 16:40:51 +0000172 if (DeclLoc.isMacroID()) {
173 if (isa<TypedefDecl>(D)) {
174 // If location of the typedef name is in a macro, it is because being
175 // declared via a macro. Try using declaration's starting location as
176 // the "declaration location".
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000177 DeclLoc = D->getBeginLoc();
Eugene Zelenko7855e772018-04-03 00:11:50 +0000178 } else if (const auto *TD = dyn_cast<TagDecl>(D)) {
Dmitri Gribenkoef099dc2014-03-27 16:40:51 +0000179 // If location of the tag decl is inside a macro, but the spelling of
180 // the tag name comes from a macro argument, it looks like a special
181 // macro like NS_ENUM is being used to define the tag decl. In that
182 // case, adjust the source location to the expansion loc so that we can
183 // attach the comment to the tag decl.
184 if (SourceMgr.isMacroArgExpansion(DeclLoc) &&
185 TD->isCompleteDefinition())
186 DeclLoc = SourceMgr.getExpansionLoc(DeclLoc);
187 }
188 }
Fariborz Jahanianb64e95f2013-07-24 22:58:51 +0000189 }
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000190
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000191 // If the declaration doesn't map directly to a location in a file, we
192 // can't find the comment.
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000193 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
Craig Topper36250ad2014-05-12 05:36:57 +0000194 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000195
Jan Korous6644d012019-04-10 20:23:33 +0000196 if (!CommentsLoaded && ExternalSource) {
197 ExternalSource->ReadComments();
198
199#ifndef NDEBUG
200 ArrayRef<RawComment *> RawComments = Comments.getComments();
201 assert(std::is_sorted(RawComments.begin(), RawComments.end(),
202 BeforeThanCompare<RawComment>(SourceMgr)));
203#endif
204
205 CommentsLoaded = true;
206 }
207
208 ArrayRef<RawComment *> RawComments = Comments.getComments();
209 // If there are no comments anywhere, we won't find anything.
210 if (RawComments.empty())
211 return nullptr;
212
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000213 // Find the comment that occurs just after this declaration.
Dmitri Gribenko82ea9472012-07-17 22:01:09 +0000214 ArrayRef<RawComment *>::iterator Comment;
215 {
216 // When searching for comments during parsing, the comment we are looking
217 // for is usually among the last two comments we parsed -- check them
218 // first.
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +0000219 RawComment CommentAtDeclLoc(
David L. Jones13d5a872018-03-02 00:07:45 +0000220 SourceMgr, SourceRange(DeclLoc), LangOpts.CommentOpts, false);
Dmitri Gribenko82ea9472012-07-17 22:01:09 +0000221 BeforeThanCompare<RawComment> Compare(SourceMgr);
222 ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1;
223 bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
224 if (!Found && RawComments.size() >= 2) {
225 MaybeBeforeDecl--;
226 Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
227 }
228
229 if (Found) {
230 Comment = MaybeBeforeDecl + 1;
231 assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(),
232 &CommentAtDeclLoc, Compare));
233 } else {
234 // Slow path.
235 Comment = std::lower_bound(RawComments.begin(), RawComments.end(),
236 &CommentAtDeclLoc, Compare);
237 }
238 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000239
240 // Decompose the location for the declaration and find the beginning of the
241 // file buffer.
242 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
243
244 // First check whether we have a trailing comment.
245 if (Comment != RawComments.end() &&
David L. Jones13d5a872018-03-02 00:07:45 +0000246 ((*Comment)->isDocumentation() || LangOpts.CommentOpts.ParseAllComments)
247 && (*Comment)->isTrailingComment() &&
Fariborz Jahanianfad28542013-08-06 23:29:00 +0000248 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
Fariborz Jahanian3ab62222013-08-07 16:40:29 +0000249 isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000250 std::pair<FileID, unsigned> CommentBeginDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000251 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000252 // Check that Doxygen trailing comment comes after the declaration, starts
253 // on the same line and in the same file as the declaration.
254 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
255 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
256 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
257 CommentBeginDecomp.second)) {
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000258 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000259 }
260 }
261
262 // The comment just after the declaration was not a trailing comment.
263 // Let's look at the previous comment.
264 if (Comment == RawComments.begin())
Craig Topper36250ad2014-05-12 05:36:57 +0000265 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000266 --Comment;
267
268 // Check that we actually have a non-member Doxygen comment.
David L. Jones13d5a872018-03-02 00:07:45 +0000269 if (!((*Comment)->isDocumentation() ||
270 LangOpts.CommentOpts.ParseAllComments) ||
271 (*Comment)->isTrailingComment())
Craig Topper36250ad2014-05-12 05:36:57 +0000272 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000273
274 // Decompose the end of the comment.
275 std::pair<FileID, unsigned> CommentEndDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000276 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000277
278 // If the comment and the declaration aren't in the same file, then they
279 // aren't related.
280 if (DeclLocDecomp.first != CommentEndDecomp.first)
Craig Topper36250ad2014-05-12 05:36:57 +0000281 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000282
283 // Get the corresponding buffer.
284 bool Invalid = false;
285 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
286 &Invalid).data();
287 if (Invalid)
Craig Topper36250ad2014-05-12 05:36:57 +0000288 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000289
290 // Extract text between the comment and declaration.
291 StringRef Text(Buffer + CommentEndDecomp.second,
292 DeclLocDecomp.second - CommentEndDecomp.second);
293
Dmitri Gribenko7e8729b2012-06-27 23:43:37 +0000294 // There should be no other declarations or preprocessor directives between
295 // comment and declaration.
Argyrios Kyrtzidisb534d3a2013-07-26 18:38:12 +0000296 if (Text.find_first_of(";{}#@") != StringRef::npos)
Craig Topper36250ad2014-05-12 05:36:57 +0000297 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000298
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000299 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000300}
301
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000302/// If we have a 'templated' declaration for a template, adjust 'D' to
303/// refer to the actual template.
Dmitri Gribenko90631802012-08-22 17:44:32 +0000304/// If we have an implicit instantiation, adjust 'D' to refer to template.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +0000305static const Decl *adjustDeclToTemplate(const Decl *D) {
Eugene Zelenko7855e772018-04-03 00:11:50 +0000306 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000307 // Is this function declaration part of a function template?
Douglas Gregor35ceb272012-08-13 16:37:30 +0000308 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
Dmitri Gribenko90631802012-08-22 17:44:32 +0000309 return FTD;
310
311 // Nothing to do if function is not an implicit instantiation.
312 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
313 return D;
314
315 // Function is an implicit instantiation of a function template?
316 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
317 return FTD;
318
319 // Function is instantiated from a member definition of a class template?
320 if (const FunctionDecl *MemberDecl =
321 FD->getInstantiatedFromMemberFunction())
322 return MemberDecl;
323
324 return D;
Douglas Gregor35ceb272012-08-13 16:37:30 +0000325 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000326 if (const auto *VD = dyn_cast<VarDecl>(D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000327 // Static data member is instantiated from a member definition of a class
328 // template?
329 if (VD->isStaticDataMember())
330 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
331 return MemberDecl;
332
333 return D;
334 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000335 if (const auto *CRD = dyn_cast<CXXRecordDecl>(D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000336 // Is this class declaration part of a class template?
337 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
338 return CTD;
339
340 // Class is an implicit instantiation of a class template or partial
341 // specialization?
Eugene Zelenko7855e772018-04-03 00:11:50 +0000342 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000343 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
344 return D;
345 llvm::PointerUnion<ClassTemplateDecl *,
346 ClassTemplatePartialSpecializationDecl *>
347 PU = CTSD->getSpecializedTemplateOrPartial();
348 return PU.is<ClassTemplateDecl*>() ?
349 static_cast<const Decl*>(PU.get<ClassTemplateDecl *>()) :
350 static_cast<const Decl*>(
351 PU.get<ClassTemplatePartialSpecializationDecl *>());
352 }
353
354 // Class is instantiated from a member definition of a class template?
355 if (const MemberSpecializationInfo *Info =
356 CRD->getMemberSpecializationInfo())
357 return Info->getInstantiatedFrom();
358
359 return D;
360 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000361 if (const auto *ED = dyn_cast<EnumDecl>(D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000362 // Enum is instantiated from a member definition of a class template?
363 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
364 return MemberDecl;
365
366 return D;
367 }
368 // FIXME: Adjust alias templates?
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000369 return D;
370}
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000371
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000372const RawComment *ASTContext::getRawCommentForAnyRedecl(
373 const Decl *D,
374 const Decl **OriginalDecl) const {
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000375 D = adjustDeclToTemplate(D);
Douglas Gregor35ceb272012-08-13 16:37:30 +0000376
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000377 // Check whether we have cached a comment for this declaration already.
378 {
379 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
380 RedeclComments.find(D);
381 if (Pos != RedeclComments.end()) {
382 const RawCommentAndCacheFlags &Raw = Pos->second;
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000383 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
384 if (OriginalDecl)
385 *OriginalDecl = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000386 return Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000387 }
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000388 }
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000389 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000390
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000391 // Search for comments attached to declarations in the redeclaration chain.
Craig Topper36250ad2014-05-12 05:36:57 +0000392 const RawComment *RC = nullptr;
393 const Decl *OriginalDeclForRC = nullptr;
Aaron Ballman86c93902014-03-06 23:45:36 +0000394 for (auto I : D->redecls()) {
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000395 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
Aaron Ballman86c93902014-03-06 23:45:36 +0000396 RedeclComments.find(I);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000397 if (Pos != RedeclComments.end()) {
398 const RawCommentAndCacheFlags &Raw = Pos->second;
399 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
400 RC = Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000401 OriginalDeclForRC = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000402 break;
403 }
404 } else {
Aaron Ballman86c93902014-03-06 23:45:36 +0000405 RC = getRawCommentForDeclNoCache(I);
406 OriginalDeclForRC = I;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000407 RawCommentAndCacheFlags Raw;
408 if (RC) {
Will Wilsonf9de5362015-10-27 17:01:10 +0000409 // Call order swapped to work around ICE in VS2015 RTM (Release Win32)
410 // https://connect.microsoft.com/VisualStudio/feedback/details/1741530
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000411 Raw.setKind(RawCommentAndCacheFlags::FromDecl);
Will Wilsonf9de5362015-10-27 17:01:10 +0000412 Raw.setRaw(RC);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000413 } else
414 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
Aaron Ballman86c93902014-03-06 23:45:36 +0000415 Raw.setOriginalDecl(I);
416 RedeclComments[I] = Raw;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000417 if (RC)
418 break;
419 }
420 }
421
Dmitri Gribenko5c8897d2012-06-28 16:25:36 +0000422 // If we found a comment, it should be a documentation comment.
David L. Jones13d5a872018-03-02 00:07:45 +0000423 assert(!RC || RC->isDocumentation() || LangOpts.CommentOpts.ParseAllComments);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000424
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000425 if (OriginalDecl)
426 *OriginalDecl = OriginalDeclForRC;
427
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000428 // Update cache for every declaration in the redeclaration chain.
429 RawCommentAndCacheFlags Raw;
430 Raw.setRaw(RC);
431 Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000432 Raw.setOriginalDecl(OriginalDeclForRC);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000433
Aaron Ballman86c93902014-03-06 23:45:36 +0000434 for (auto I : D->redecls()) {
435 RawCommentAndCacheFlags &R = RedeclComments[I];
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000436 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
437 R = Raw;
438 }
439
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000440 return RC;
441}
442
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000443static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
444 SmallVectorImpl<const NamedDecl *> &Redeclared) {
445 const DeclContext *DC = ObjCMethod->getDeclContext();
Eugene Zelenko7855e772018-04-03 00:11:50 +0000446 if (const auto *IMD = dyn_cast<ObjCImplDecl>(DC)) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000447 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
448 if (!ID)
449 return;
450 // Add redeclared method here.
Aaron Ballmanb4a53452014-03-13 21:57:01 +0000451 for (const auto *Ext : ID->known_extensions()) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000452 if (ObjCMethodDecl *RedeclaredMethod =
Douglas Gregor048fbfa2013-01-16 23:00:23 +0000453 Ext->getMethod(ObjCMethod->getSelector(),
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000454 ObjCMethod->isInstanceMethod()))
455 Redeclared.push_back(RedeclaredMethod);
456 }
457 }
458}
459
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000460comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
461 const Decl *D) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +0000462 auto *ThisDeclInfo = new (*this) comments::DeclInfo;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000463 ThisDeclInfo->CommentDecl = D;
464 ThisDeclInfo->IsFilled = false;
465 ThisDeclInfo->fill();
466 ThisDeclInfo->CommentDecl = FC->getDecl();
Argyrios Kyrtzidis7daabbd2014-04-27 22:53:03 +0000467 if (!ThisDeclInfo->TemplateParameters)
468 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000469 comments::FullComment *CFC =
470 new (*this) comments::FullComment(FC->getBlocks(),
471 ThisDeclInfo);
472 return CFC;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000473}
474
Richard Smithb39b9d52013-05-21 05:24:00 +0000475comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
476 const RawComment *RC = getRawCommentForDeclNoCache(D);
Craig Topper36250ad2014-05-12 05:36:57 +0000477 return RC ? RC->parse(*this, nullptr, D) : nullptr;
Richard Smithb39b9d52013-05-21 05:24:00 +0000478}
479
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000480comments::FullComment *ASTContext::getCommentForDecl(
481 const Decl *D,
482 const Preprocessor *PP) const {
Fariborz Jahanian096f7c12013-05-13 17:27:00 +0000483 if (D->isInvalidDecl())
Craig Topper36250ad2014-05-12 05:36:57 +0000484 return nullptr;
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000485 D = adjustDeclToTemplate(D);
Fangrui Song6907ce22018-07-30 19:24:48 +0000486
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000487 const Decl *Canonical = D->getCanonicalDecl();
488 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
489 ParsedComments.find(Canonical);
Fangrui Song6907ce22018-07-30 19:24:48 +0000490
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000491 if (Pos != ParsedComments.end()) {
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000492 if (Canonical != D) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000493 comments::FullComment *FC = Pos->second;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000494 comments::FullComment *CFC = cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000495 return CFC;
496 }
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000497 return Pos->second;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000498 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000499
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000500 const Decl *OriginalDecl;
Fangrui Song6907ce22018-07-30 19:24:48 +0000501
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000502 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000503 if (!RC) {
504 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000505 SmallVector<const NamedDecl*, 8> Overridden;
Eugene Zelenko7855e772018-04-03 00:11:50 +0000506 const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000507 if (OMD && OMD->isPropertyAccessor())
508 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
509 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
510 return cloneFullComment(FC, D);
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000511 if (OMD)
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000512 addRedeclaredMethods(OMD, Overridden);
513 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000514 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
515 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
516 return cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000517 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000518 else if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000519 // Attach any tag type's documentation to its typedef if latter
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000520 // does not have one of its own.
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000521 QualType QT = TD->getUnderlyingType();
Eugene Zelenko7855e772018-04-03 00:11:50 +0000522 if (const auto *TT = QT->getAs<TagType>())
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000523 if (const Decl *TD = TT->getDecl())
524 if (comments::FullComment *FC = getCommentForDecl(TD, PP))
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000525 return cloneFullComment(FC, D);
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000526 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000527 else if (const auto *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000528 while (IC->getSuperClass()) {
529 IC = IC->getSuperClass();
530 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
531 return cloneFullComment(FC, D);
532 }
533 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000534 else if (const auto *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000535 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
536 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
537 return cloneFullComment(FC, D);
538 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000539 else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000540 if (!(RD = RD->getDefinition()))
Craig Topper36250ad2014-05-12 05:36:57 +0000541 return nullptr;
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000542 // Check non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +0000543 for (const auto &I : RD->bases()) {
544 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000545 continue;
Aaron Ballman574705e2014-03-13 15:41:46 +0000546 QualType Ty = I.getType();
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000547 if (Ty.isNull())
548 continue;
549 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
550 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
551 continue;
Fangrui Song6907ce22018-07-30 19:24:48 +0000552
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000553 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
554 return cloneFullComment(FC, D);
555 }
556 }
557 // Check virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +0000558 for (const auto &I : RD->vbases()) {
559 if (I.getAccessSpecifier() != AS_public)
Fariborz Jahanian5a2e4a22013-04-26 23:34:36 +0000560 continue;
Aaron Ballman445a9392014-03-13 16:15:17 +0000561 QualType Ty = I.getType();
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000562 if (Ty.isNull())
563 continue;
564 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
565 if (!(VirtualBase= VirtualBase->getDefinition()))
566 continue;
567 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
568 return cloneFullComment(FC, D);
569 }
570 }
571 }
Craig Topper36250ad2014-05-12 05:36:57 +0000572 return nullptr;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000573 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000574
Dmitri Gribenkobfda9f72012-08-22 18:12:19 +0000575 // If the RawComment was attached to other redeclaration of this Decl, we
576 // should parse the comment in context of that other Decl. This is important
577 // because comments can contain references to parameter names which can be
578 // different across redeclarations.
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000579 if (D != OriginalDecl)
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000580 return getCommentForDecl(OriginalDecl, PP);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000581
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000582 comments::FullComment *FC = RC->parse(*this, PP, D);
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000583 ParsedComments[Canonical] = FC;
584 return FC;
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000585}
586
Fangrui Song6907ce22018-07-30 19:24:48 +0000587void
588ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000589 TemplateTemplateParmDecl *Parm) {
590 ID.AddInteger(Parm->getDepth());
591 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +0000592 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000593
594 TemplateParameterList *Params = Parm->getTemplateParameters();
595 ID.AddInteger(Params->size());
Fangrui Song6907ce22018-07-30 19:24:48 +0000596 for (TemplateParameterList::const_iterator P = Params->begin(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000597 PEnd = Params->end();
598 P != PEnd; ++P) {
Eugene Zelenko7855e772018-04-03 00:11:50 +0000599 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000600 ID.AddInteger(0);
601 ID.AddBoolean(TTP->isParameterPack());
602 continue;
603 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000604
Eugene Zelenko7855e772018-04-03 00:11:50 +0000605 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000606 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +0000607 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman205a4292012-03-07 01:09:33 +0000608 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000609 if (NTTP->isExpandedParameterPack()) {
610 ID.AddBoolean(true);
611 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman205a4292012-03-07 01:09:33 +0000612 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
613 QualType T = NTTP->getExpansionType(I);
614 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
615 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000616 } else
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000617 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000618 continue;
619 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000620
Eugene Zelenko7855e772018-04-03 00:11:50 +0000621 auto *TTP = cast<TemplateTemplateParmDecl>(*P);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000622 ID.AddInteger(2);
623 Profile(ID, TTP);
624 }
625}
626
627TemplateTemplateParmDecl *
628ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +0000629 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000630 // Check if we already have a canonical template template parameter.
631 llvm::FoldingSetNodeID ID;
632 CanonicalTemplateTemplateParm::Profile(ID, TTP);
Craig Topper36250ad2014-05-12 05:36:57 +0000633 void *InsertPos = nullptr;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000634 CanonicalTemplateTemplateParm *Canonical
635 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
636 if (Canonical)
637 return Canonical->getParam();
Fangrui Song6907ce22018-07-30 19:24:48 +0000638
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000639 // Build a canonical template parameter list.
640 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000641 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000642 CanonParams.reserve(Params->size());
Fangrui Song6907ce22018-07-30 19:24:48 +0000643 for (TemplateParameterList::const_iterator P = Params->begin(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000644 PEnd = Params->end();
645 P != PEnd; ++P) {
Eugene Zelenko7855e772018-04-03 00:11:50 +0000646 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000647 CanonParams.push_back(
Fangrui Song6907ce22018-07-30 19:24:48 +0000648 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000649 SourceLocation(),
650 SourceLocation(),
651 TTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000652 TTP->getIndex(), nullptr, false,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000653 TTP->isParameterPack()));
Eugene Zelenko7855e772018-04-03 00:11:50 +0000654 else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000655 QualType T = getCanonicalType(NTTP->getType());
656 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
657 NonTypeTemplateParmDecl *Param;
658 if (NTTP->isExpandedParameterPack()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000659 SmallVector<QualType, 2> ExpandedTypes;
660 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000661 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
662 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
663 ExpandedTInfos.push_back(
664 getTrivialTypeSourceInfo(ExpandedTypes.back()));
665 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000666
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000667 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000668 SourceLocation(),
669 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000670 NTTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000671 NTTP->getPosition(), nullptr,
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000672 T,
673 TInfo,
David Majnemerdfecf1a2016-07-06 04:19:16 +0000674 ExpandedTypes,
675 ExpandedTInfos);
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000676 } else {
677 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000678 SourceLocation(),
679 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000680 NTTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000681 NTTP->getPosition(), nullptr,
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000682 T,
683 NTTP->isParameterPack(),
684 TInfo);
685 }
686 CanonParams.push_back(Param);
687
688 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000689 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
690 cast<TemplateTemplateParmDecl>(*P)));
691 }
692
Hubert Tonge4a0c0e2016-07-30 22:33:34 +0000693 assert(!TTP->getRequiresClause() &&
694 "Unexpected requires-clause on template template-parameter");
George Burgess IVb7e4e482016-08-25 01:54:37 +0000695 Expr *const CanonRequiresClause = nullptr;
Hubert Tonge4a0c0e2016-07-30 22:33:34 +0000696
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000697 TemplateTemplateParmDecl *CanonTTP
Fangrui Song6907ce22018-07-30 19:24:48 +0000698 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000699 SourceLocation(), TTP->getDepth(),
Fangrui Song6907ce22018-07-30 19:24:48 +0000700 TTP->getPosition(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000701 TTP->isParameterPack(),
Craig Topper36250ad2014-05-12 05:36:57 +0000702 nullptr,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000703 TemplateParameterList::Create(*this, SourceLocation(),
704 SourceLocation(),
David Majnemer902f8c62015-12-27 07:16:27 +0000705 CanonParams,
Hubert Tonge4a0c0e2016-07-30 22:33:34 +0000706 SourceLocation(),
707 CanonRequiresClause));
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000708
709 // Get the new insert position for the node we care about.
710 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +0000711 assert(!Canonical && "Shouldn't be in the map!");
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000712 (void)Canonical;
713
714 // Create the canonical template template parameter entry.
715 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
716 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
717 return CanonTTP;
718}
719
Charles Davis53c59df2010-08-16 03:33:14 +0000720CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
Craig Topper36250ad2014-05-12 05:36:57 +0000721 if (!LangOpts.CPlusPlus) return nullptr;
John McCall86353412010-08-21 22:46:04 +0000722
John McCall359b8852013-01-25 22:30:49 +0000723 switch (T.getCXXABI().getKind()) {
Joerg Sonnenbergerdaa13aa2014-05-13 11:20:16 +0000724 case TargetCXXABI::GenericARM: // Same as Itanium at this level
John McCall359b8852013-01-25 22:30:49 +0000725 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +0000726 case TargetCXXABI::iOS64:
Tim Northover756447a2015-10-30 16:30:36 +0000727 case TargetCXXABI::WatchOS:
Joerg Sonnenbergerdaa13aa2014-05-13 11:20:16 +0000728 case TargetCXXABI::GenericAArch64:
Zoran Jovanovic26a12162015-02-18 15:21:35 +0000729 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +0000730 case TargetCXXABI::GenericItanium:
Dan Gohmanc2853072015-09-03 22:51:53 +0000731 case TargetCXXABI::WebAssembly:
Charles Davis53c59df2010-08-16 03:33:14 +0000732 return CreateItaniumCXXABI(*this);
John McCall359b8852013-01-25 22:30:49 +0000733 case TargetCXXABI::Microsoft:
Charles Davis6bcb07a2010-08-19 02:18:14 +0000734 return CreateMicrosoftCXXABI(*this);
735 }
David Blaikie8a40f702012-01-17 06:56:22 +0000736 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000737}
738
Alexander Richardson6d989432017-10-15 18:48:14 +0000739static const LangASMap *getAddressSpaceMap(const TargetInfo &T,
740 const LangOptions &LOpts) {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000741 if (LOpts.FakeAddressSpaceMap) {
742 // The fake address space map must have a distinct entry for each
743 // language-specific address space.
744 static const unsigned FakeAddrSpaceMap[] = {
Yaxun Liub34ec822017-04-11 17:24:23 +0000745 0, // Default
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000746 1, // opencl_global
Egor Churaev28f00aa2016-12-23 16:11:25 +0000747 3, // opencl_local
748 2, // opencl_constant
Yaxun Liub7318e02017-10-13 03:37:48 +0000749 0, // opencl_private
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +0000750 4, // opencl_generic
751 5, // cuda_device
752 6, // cuda_constant
753 7 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000754 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000755 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000756 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000757 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000758 }
759}
760
David Tweed31d09b02013-09-13 12:04:22 +0000761static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
762 const LangOptions &LangOpts) {
763 switch (LangOpts.getAddressSpaceMapMangling()) {
David Tweed31d09b02013-09-13 12:04:22 +0000764 case LangOptions::ASMM_Target:
765 return TI.useAddressSpaceMapMangling();
766 case LangOptions::ASMM_On:
767 return true;
768 case LangOptions::ASMM_Off:
769 return false;
770 }
NAKAMURA Takumi5c81ca42013-09-13 17:12:09 +0000771 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
David Tweed31d09b02013-09-13 12:04:22 +0000772}
773
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000774ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000775 IdentifierTable &idents, SelectorTable &sels,
Alp Toker08043432014-05-03 03:46:04 +0000776 Builtin::Context &builtins)
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000777 : FunctionProtoTypes(this_()), TemplateSpecializationTypes(this_()),
778 DependentTemplateSpecializationTypes(this_()),
Eugene Zelenko5e5e5642017-11-23 01:20:07 +0000779 SubstTemplateTemplateParmPacks(this_()), SourceMgr(SM), LangOpts(LOpts),
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000780 SanitizerBL(new SanitizerBlacklist(LangOpts.SanitizerBlacklistFiles, SM)),
Dean Michael Berris835832d2017-03-30 00:29:36 +0000781 XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles,
Dean Michael Berris20dc6ef2018-04-09 04:02:09 +0000782 LangOpts.XRayNeverInstrumentFiles,
783 LangOpts.XRayAttrListFiles, SM)),
Artem Belevichb5bc9232015-09-22 17:23:22 +0000784 PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
Eugene Zelenko5e5e5642017-11-23 01:20:07 +0000785 BuiltinInfo(builtins), DeclarationNames(*this), Comments(SM),
Eric Fiselier0683c0e2018-05-07 21:07:10 +0000786 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
787 CompCategories(this_()), LastSDM(nullptr, 0) {
Daniel Dunbar221fa942008-08-11 04:54:23 +0000788 TUDecl = TranslationUnitDecl::Create(*this);
Sam McCall814e7972018-11-14 10:33:30 +0000789 TraversalScope = {TUDecl};
Daniel Dunbar221fa942008-08-11 04:54:23 +0000790}
791
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000792ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000793 // Release the DenseMaps associated with DeclContext objects.
794 // FIXME: Is this the ideal solution?
795 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000796
Manuel Klimeka7328992013-06-03 13:51:33 +0000797 // Call all of the deallocation functions on all of their targets.
Chandler Carruthff5a01a2015-12-30 03:00:23 +0000798 for (auto &Pair : Deallocations)
799 (Pair.first)(Pair.second);
Manuel Klimeka7328992013-06-03 13:51:33 +0000800
Ted Kremenek076baeb2010-06-08 23:00:58 +0000801 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000802 // because they can contain DenseMaps.
803 for (llvm::DenseMap<const ObjCContainerDecl*,
804 const ASTRecordLayout*>::iterator
805 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
806 // Increment in loop to prevent using deallocated memory.
Eugene Zelenko7855e772018-04-03 00:11:50 +0000807 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
Douglas Gregor5b11d492010-07-25 17:53:33 +0000808 R->Destroy(*this);
809
Ted Kremenek076baeb2010-06-08 23:00:58 +0000810 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
811 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
812 // Increment in loop to prevent using deallocated memory.
Eugene Zelenko7855e772018-04-03 00:11:50 +0000813 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
Ted Kremenek076baeb2010-06-08 23:00:58 +0000814 R->Destroy(*this);
815 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000816
Douglas Gregor561eceb2010-08-30 16:49:28 +0000817 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
818 AEnd = DeclAttrs.end();
819 A != AEnd; ++A)
820 A->second->~AttrVec();
Reid Klecknerd8110b62013-09-10 20:14:30 +0000821
David Majnemere694f3e2015-08-14 14:43:50 +0000822 for (std::pair<const MaterializeTemporaryExpr *, APValue *> &MTVPair :
823 MaterializedTemporaryValues)
824 MTVPair.second->~APValue();
825
Richard Smith423f46f2016-07-20 21:38:26 +0000826 for (const auto &Value : ModuleInitializers)
827 Value.second->~PerModuleInitializers();
Douglas Gregor561eceb2010-08-30 16:49:28 +0000828}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000829
Sam McCall814e7972018-11-14 10:33:30 +0000830class ASTContext::ParentMap {
831 /// Contains parents of a node.
832 using ParentVector = llvm::SmallVector<ast_type_traits::DynTypedNode, 2>;
833
834 /// Maps from a node to its parents. This is used for nodes that have
835 /// pointer identity only, which are more common and we can save space by
836 /// only storing a unique pointer to them.
837 using ParentMapPointers = llvm::DenseMap<
838 const void *,
839 llvm::PointerUnion4<const Decl *, const Stmt *,
840 ast_type_traits::DynTypedNode *, ParentVector *>>;
841
842 /// Parent map for nodes without pointer identity. We store a full
843 /// DynTypedNode for all keys.
844 using ParentMapOtherNodes = llvm::DenseMap<
845 ast_type_traits::DynTypedNode,
846 llvm::PointerUnion4<const Decl *, const Stmt *,
847 ast_type_traits::DynTypedNode *, ParentVector *>>;
848
849 ParentMapPointers PointerParents;
850 ParentMapOtherNodes OtherParents;
851 class ASTVisitor;
852
853 static ast_type_traits::DynTypedNode
854 getSingleDynTypedNodeFromParentMap(ParentMapPointers::mapped_type U) {
855 if (const auto *D = U.dyn_cast<const Decl *>())
856 return ast_type_traits::DynTypedNode::create(*D);
857 if (const auto *S = U.dyn_cast<const Stmt *>())
858 return ast_type_traits::DynTypedNode::create(*S);
859 return *U.get<ast_type_traits::DynTypedNode *>();
860 }
861
862 template <typename NodeTy, typename MapTy>
863 static ASTContext::DynTypedNodeList getDynNodeFromMap(const NodeTy &Node,
864 const MapTy &Map) {
865 auto I = Map.find(Node);
866 if (I == Map.end()) {
867 return llvm::ArrayRef<ast_type_traits::DynTypedNode>();
868 }
869 if (const auto *V = I->second.template dyn_cast<ParentVector *>()) {
870 return llvm::makeArrayRef(*V);
871 }
872 return getSingleDynTypedNodeFromParentMap(I->second);
873 }
874
875public:
876 ParentMap(ASTContext &Ctx);
877 ~ParentMap() {
878 for (const auto &Entry : PointerParents) {
879 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
880 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
881 } else if (Entry.second.is<ParentVector *>()) {
882 delete Entry.second.get<ParentVector *>();
883 }
884 }
885 for (const auto &Entry : OtherParents) {
886 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
887 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
888 } else if (Entry.second.is<ParentVector *>()) {
889 delete Entry.second.get<ParentVector *>();
890 }
Benjamin Kramer94355ae2015-10-23 09:04:55 +0000891 }
892 }
Sam McCall814e7972018-11-14 10:33:30 +0000893
894 DynTypedNodeList getParents(const ast_type_traits::DynTypedNode &Node) {
895 if (Node.getNodeKind().hasPointerIdentity())
896 return getDynNodeFromMap(Node.getMemoizationData(), PointerParents);
897 return getDynNodeFromMap(Node, OtherParents);
Manuel Klimek95403e62014-05-21 13:28:59 +0000898 }
Sam McCall814e7972018-11-14 10:33:30 +0000899};
900
901void ASTContext::setTraversalScope(const std::vector<Decl *> &TopLevelDecls) {
902 TraversalScope = TopLevelDecls;
903 Parents.reset();
Manuel Klimek95403e62014-05-21 13:28:59 +0000904}
905
Douglas Gregor1a809332010-05-23 18:26:36 +0000906void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
Chandler Carruthff5a01a2015-12-30 03:00:23 +0000907 Deallocations.push_back({Callback, Data});
Douglas Gregor1a809332010-05-23 18:26:36 +0000908}
909
Mike Stump11289f42009-09-09 15:08:12 +0000910void
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000911ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
Benjamin Kramerd6da1a02016-06-12 20:05:23 +0000912 ExternalSource = std::move(Source);
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000913}
914
Chris Lattner4eb445d2007-01-26 01:27:23 +0000915void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000916 llvm::errs() << "\n*** AST Context Stats:\n";
917 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000918
Douglas Gregora30d0462009-05-26 14:40:08 +0000919 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000920#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000921#define ABSTRACT_TYPE(Name, Parent)
922#include "clang/AST/TypeNodes.def"
923 0 // Extra
924 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000925
Chris Lattner4eb445d2007-01-26 01:27:23 +0000926 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
927 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000928 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000929 }
930
Douglas Gregora30d0462009-05-26 14:40:08 +0000931 unsigned Idx = 0;
932 unsigned TotalBytes = 0;
933#define TYPE(Name, Parent) \
934 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000935 llvm::errs() << " " << counts[Idx] << " " << #Name \
Bruno Ricci58e03222018-08-06 15:17:32 +0000936 << " types, " << sizeof(Name##Type) << " each " \
937 << "(" << counts[Idx] * sizeof(Name##Type) \
938 << " bytes)\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000939 TotalBytes += counts[Idx] * sizeof(Name##Type); \
940 ++Idx;
941#define ABSTRACT_TYPE(Name, Parent)
942#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000943
Chandler Carruth3c147a72011-07-04 05:32:14 +0000944 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
945
Douglas Gregor7454c562010-07-02 20:37:36 +0000946 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000947 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
948 << NumImplicitDefaultConstructors
949 << " implicit default constructors created\n";
950 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
951 << NumImplicitCopyConstructors
952 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000953 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000954 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
955 << NumImplicitMoveConstructors
956 << " implicit move constructors created\n";
957 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
958 << NumImplicitCopyAssignmentOperators
959 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000960 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000961 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
962 << NumImplicitMoveAssignmentOperators
963 << " implicit move assignment operators created\n";
964 llvm::errs() << NumImplicitDestructorsDeclared << "/"
965 << NumImplicitDestructors
966 << " implicit destructors created\n";
967
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000968 if (ExternalSource) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000969 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000970 ExternalSource->PrintStats();
971 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000972
Douglas Gregor5b11d492010-07-25 17:53:33 +0000973 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000974}
975
Richard Smith42413142015-05-15 20:05:43 +0000976void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
977 bool NotifyListeners) {
978 if (NotifyListeners)
979 if (auto *Listener = getASTMutationListener())
980 Listener->RedefinedHiddenDefinition(ND, M);
981
Richard Smith13897eb2018-09-12 23:37:00 +0000982 MergedDefModules[cast<NamedDecl>(ND->getCanonicalDecl())].push_back(M);
Richard Smith42413142015-05-15 20:05:43 +0000983}
984
985void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) {
Richard Smith20fbdb32018-09-12 02:13:46 +0000986 auto It = MergedDefModules.find(cast<NamedDecl>(ND->getCanonicalDecl()));
Richard Smith42413142015-05-15 20:05:43 +0000987 if (It == MergedDefModules.end())
988 return;
989
Benjamin Kramera72a70a2016-10-17 13:00:44 +0000990 auto &Merged = It->second;
Richard Smith42413142015-05-15 20:05:43 +0000991 llvm::DenseSet<Module*> Found;
992 for (Module *&M : Merged)
993 if (!Found.insert(M).second)
994 M = nullptr;
995 Merged.erase(std::remove(Merged.begin(), Merged.end(), nullptr), Merged.end());
996}
997
Richard Smithdc1f0422016-07-20 19:10:16 +0000998void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
999 if (LazyInitializers.empty())
1000 return;
1001
1002 auto *Source = Ctx.getExternalSource();
1003 assert(Source && "lazy initializers but no external source");
1004
1005 auto LazyInits = std::move(LazyInitializers);
1006 LazyInitializers.clear();
1007
1008 for (auto ID : LazyInits)
1009 Initializers.push_back(Source->GetExternalDecl(ID));
1010
1011 assert(LazyInitializers.empty() &&
1012 "GetExternalDecl for lazy module initializer added more inits");
1013}
1014
1015void ASTContext::addModuleInitializer(Module *M, Decl *D) {
1016 // One special case: if we add a module initializer that imports another
1017 // module, and that module's only initializer is an ImportDecl, simplify.
Eugene Zelenko7855e772018-04-03 00:11:50 +00001018 if (const auto *ID = dyn_cast<ImportDecl>(D)) {
Richard Smithdc1f0422016-07-20 19:10:16 +00001019 auto It = ModuleInitializers.find(ID->getImportedModule());
1020
1021 // Maybe the ImportDecl does nothing at all. (Common case.)
1022 if (It == ModuleInitializers.end())
1023 return;
1024
1025 // Maybe the ImportDecl only imports another ImportDecl.
1026 auto &Imported = *It->second;
1027 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
1028 Imported.resolve(*this);
1029 auto *OnlyDecl = Imported.Initializers.front();
1030 if (isa<ImportDecl>(OnlyDecl))
1031 D = OnlyDecl;
1032 }
1033 }
1034
1035 auto *&Inits = ModuleInitializers[M];
1036 if (!Inits)
1037 Inits = new (*this) PerModuleInitializers;
1038 Inits->Initializers.push_back(D);
1039}
1040
1041void ASTContext::addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs) {
1042 auto *&Inits = ModuleInitializers[M];
1043 if (!Inits)
1044 Inits = new (*this) PerModuleInitializers;
1045 Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
1046 IDs.begin(), IDs.end());
1047}
1048
Eugene Zelenko7855e772018-04-03 00:11:50 +00001049ArrayRef<Decl *> ASTContext::getModuleInitializers(Module *M) {
Richard Smithdc1f0422016-07-20 19:10:16 +00001050 auto It = ModuleInitializers.find(M);
Fangrui Song6907ce22018-07-30 19:24:48 +00001051 if (It == ModuleInitializers.end())
Richard Smithdc1f0422016-07-20 19:10:16 +00001052 return None;
1053
1054 auto *Inits = It->second;
1055 Inits->resolve(*this);
1056 return Inits->Initializers;
1057}
1058
Richard Smithf19e1272015-03-07 00:04:49 +00001059ExternCContextDecl *ASTContext::getExternCContextDecl() const {
1060 if (!ExternCContext)
1061 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
1062
1063 return ExternCContext;
1064}
1065
David Majnemerd9b1a4f2015-11-04 03:40:30 +00001066BuiltinTemplateDecl *
1067ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
1068 const IdentifierInfo *II) const {
1069 auto *BuiltinTemplate = BuiltinTemplateDecl::Create(*this, TUDecl, II, BTK);
1070 BuiltinTemplate->setImplicit();
1071 TUDecl->addDecl(BuiltinTemplate);
1072
1073 return BuiltinTemplate;
1074}
1075
1076BuiltinTemplateDecl *
1077ASTContext::getMakeIntegerSeqDecl() const {
1078 if (!MakeIntegerSeqDecl)
1079 MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq,
1080 getMakeIntegerSeqName());
1081 return MakeIntegerSeqDecl;
1082}
1083
Eric Fiselier6ad68552016-07-01 01:24:09 +00001084BuiltinTemplateDecl *
1085ASTContext::getTypePackElementDecl() const {
1086 if (!TypePackElementDecl)
1087 TypePackElementDecl = buildBuiltinTemplateDecl(BTK__type_pack_element,
1088 getTypePackElementName());
1089 return TypePackElementDecl;
1090}
1091
Alp Toker2dea15b2013-12-17 01:22:38 +00001092RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
1093 RecordDecl::TagKind TK) const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001094 SourceLocation Loc;
1095 RecordDecl *NewDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00001096 if (getLangOpts().CPlusPlus)
1097 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
1098 Loc, &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +00001099 else
Alp Toker2dea15b2013-12-17 01:22:38 +00001100 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
1101 &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +00001102 NewDecl->setImplicit();
David Majnemerf8637362015-01-15 08:41:25 +00001103 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
1104 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
Alp Toker56b5cc92013-12-15 10:36:26 +00001105 return NewDecl;
1106}
1107
1108TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
1109 StringRef Name) const {
1110 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
1111 TypedefDecl *NewDecl = TypedefDecl::Create(
1112 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
1113 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
1114 NewDecl->setImplicit();
1115 return NewDecl;
1116}
1117
Douglas Gregor801c99d2011-08-12 06:49:56 +00001118TypedefDecl *ASTContext::getInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001119 if (!Int128Decl)
1120 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +00001121 return Int128Decl;
1122}
1123
1124TypedefDecl *ASTContext::getUInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001125 if (!UInt128Decl)
1126 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +00001127 return UInt128Decl;
1128}
Chris Lattner4eb445d2007-01-26 01:27:23 +00001129
John McCall48f2d582009-10-23 23:03:21 +00001130void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001131 auto *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +00001132 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +00001133 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001134}
1135
Artem Belevichb5bc9232015-09-22 17:23:22 +00001136void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
1137 const TargetInfo *AuxTarget) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001138 assert((!this->Target || this->Target == &Target) &&
1139 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +00001140 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +00001141
Douglas Gregore8bbc122011-09-02 00:18:52 +00001142 this->Target = &Target;
Artem Belevichb5bc9232015-09-22 17:23:22 +00001143 this->AuxTarget = AuxTarget;
1144
Douglas Gregore8bbc122011-09-02 00:18:52 +00001145 ABI.reset(createCXXABI(Target));
1146 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
David Tweed31d09b02013-09-13 12:04:22 +00001147 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
Fangrui Song6907ce22018-07-30 19:24:48 +00001148
Chris Lattner970e54e2006-11-12 00:37:36 +00001149 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +00001150 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +00001151
Chris Lattner970e54e2006-11-12 00:37:36 +00001152 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +00001153 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +00001154 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +00001155 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +00001156 InitBuiltinType(CharTy, BuiltinType::Char_S);
1157 else
1158 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +00001159 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +00001160 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
1161 InitBuiltinType(ShortTy, BuiltinType::Short);
1162 InitBuiltinType(IntTy, BuiltinType::Int);
1163 InitBuiltinType(LongTy, BuiltinType::Long);
1164 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +00001165
Chris Lattner970e54e2006-11-12 00:37:36 +00001166 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +00001167 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
1168 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
1169 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
1170 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
1171 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +00001172
Chris Lattner970e54e2006-11-12 00:37:36 +00001173 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +00001174 InitBuiltinType(FloatTy, BuiltinType::Float);
1175 InitBuiltinType(DoubleTy, BuiltinType::Double);
1176 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001177
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001178 // GNU extension, __float128 for IEEE quadruple precision
1179 InitBuiltinType(Float128Ty, BuiltinType::Float128);
1180
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00001181 // C11 extension ISO/IEC TS 18661-3
1182 InitBuiltinType(Float16Ty, BuiltinType::Float16);
1183
Leonard Chanf921d852018-06-04 16:07:52 +00001184 // ISO/IEC JTC1 SC22 WG14 N1169 Extension
Leonard Chanab80f3c2018-06-14 14:53:51 +00001185 InitBuiltinType(ShortAccumTy, BuiltinType::ShortAccum);
1186 InitBuiltinType(AccumTy, BuiltinType::Accum);
1187 InitBuiltinType(LongAccumTy, BuiltinType::LongAccum);
1188 InitBuiltinType(UnsignedShortAccumTy, BuiltinType::UShortAccum);
1189 InitBuiltinType(UnsignedAccumTy, BuiltinType::UAccum);
1190 InitBuiltinType(UnsignedLongAccumTy, BuiltinType::ULongAccum);
1191 InitBuiltinType(ShortFractTy, BuiltinType::ShortFract);
1192 InitBuiltinType(FractTy, BuiltinType::Fract);
1193 InitBuiltinType(LongFractTy, BuiltinType::LongFract);
1194 InitBuiltinType(UnsignedShortFractTy, BuiltinType::UShortFract);
1195 InitBuiltinType(UnsignedFractTy, BuiltinType::UFract);
1196 InitBuiltinType(UnsignedLongFractTy, BuiltinType::ULongFract);
1197 InitBuiltinType(SatShortAccumTy, BuiltinType::SatShortAccum);
1198 InitBuiltinType(SatAccumTy, BuiltinType::SatAccum);
1199 InitBuiltinType(SatLongAccumTy, BuiltinType::SatLongAccum);
1200 InitBuiltinType(SatUnsignedShortAccumTy, BuiltinType::SatUShortAccum);
1201 InitBuiltinType(SatUnsignedAccumTy, BuiltinType::SatUAccum);
1202 InitBuiltinType(SatUnsignedLongAccumTy, BuiltinType::SatULongAccum);
1203 InitBuiltinType(SatShortFractTy, BuiltinType::SatShortFract);
1204 InitBuiltinType(SatFractTy, BuiltinType::SatFract);
1205 InitBuiltinType(SatLongFractTy, BuiltinType::SatLongFract);
1206 InitBuiltinType(SatUnsignedShortFractTy, BuiltinType::SatUShortFract);
1207 InitBuiltinType(SatUnsignedFractTy, BuiltinType::SatUFract);
1208 InitBuiltinType(SatUnsignedLongFractTy, BuiltinType::SatULongFract);
Leonard Chanf921d852018-06-04 16:07:52 +00001209
Chris Lattnerf122cef2009-04-30 02:43:43 +00001210 // GNU extension, 128-bit integers.
1211 InitBuiltinType(Int128Ty, BuiltinType::Int128);
1212 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
1213
Hans Wennborg0d81e012013-05-10 10:08:40 +00001214 // C++ 3.9.1p5
1215 if (TargetInfo::isTypeSigned(Target.getWCharType()))
1216 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1217 else // -fshort-wchar makes wchar_t be unsigned.
1218 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1219 if (LangOpts.CPlusPlus && LangOpts.WChar)
1220 WideCharTy = WCharTy;
1221 else {
1222 // C99 (or C++ using -fno-wchar).
1223 WideCharTy = getFromTargetType(Target.getWCharType());
1224 }
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001225
James Molloy36365542012-05-04 10:55:22 +00001226 WIntTy = getFromTargetType(Target.getWIntType());
1227
Richard Smith3a8244d2018-05-01 05:02:45 +00001228 // C++20 (proposed)
1229 InitBuiltinType(Char8Ty, BuiltinType::Char8);
1230
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001231 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1232 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1233 else // C99
1234 Char16Ty = getFromTargetType(Target.getChar16Type());
1235
1236 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1237 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1238 else // C99
1239 Char32Ty = getFromTargetType(Target.getChar32Type());
1240
Douglas Gregor4619e432008-12-05 23:32:09 +00001241 // Placeholder type for type-dependent expressions whose type is
1242 // completely unknown. No code should ever check a type against
1243 // DependentTy and users should never see it; however, it is here to
1244 // help diagnose failures to properly check for type-dependent
1245 // expressions.
1246 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001247
John McCall36e7fe32010-10-12 00:20:44 +00001248 // Placeholder type for functions.
1249 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1250
John McCall0009fcc2011-04-26 20:42:42 +00001251 // Placeholder type for bound members.
1252 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1253
John McCall526ab472011-10-25 17:37:35 +00001254 // Placeholder type for pseudo-objects.
1255 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1256
John McCall31996342011-04-07 08:22:57 +00001257 // "any" type; useful for debugger-like clients.
1258 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1259
John McCall8a6b59a2011-10-17 18:09:15 +00001260 // Placeholder type for unbridged ARC casts.
1261 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1262
Eli Friedman34866c72012-08-31 00:14:07 +00001263 // Placeholder type for builtin functions.
1264 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1265
Alexey Bataev1a3320e2015-08-25 14:24:04 +00001266 // Placeholder type for OMP array sections.
1267 if (LangOpts.OpenMP)
1268 InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection);
1269
Chris Lattner970e54e2006-11-12 00:37:36 +00001270 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +00001271 FloatComplexTy = getComplexType(FloatTy);
1272 DoubleComplexTy = getComplexType(DoubleTy);
1273 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001274 Float128ComplexTy = getComplexType(Float128Ty);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001275
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001276 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +00001277 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1278 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001279 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001280
Alexey Bader954ba212016-04-08 13:40:33 +00001281 if (LangOpts.OpenCL) {
1282#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1283 InitBuiltinType(SingletonId, BuiltinType::Id);
Alexey Baderb62f1442016-04-13 08:33:41 +00001284#include "clang/Basic/OpenCLImageTypes.def"
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001285
Guy Benyei61054192013-02-07 10:55:47 +00001286 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001287 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Alexey Bader9c8453f2015-09-15 11:18:52 +00001288 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1289 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
Alexey Bader9c8453f2015-09-15 11:18:52 +00001290 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
Andrew Savonichev3fee3512018-11-08 11:25:41 +00001291
1292#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1293 InitBuiltinType(Id##Ty, BuiltinType::Id);
1294#include "clang/Basic/OpenCLExtensionTypes.def"
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001295 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001296
Ted Kremeneke65b0862012-03-06 20:05:56 +00001297 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +00001298 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1299 SignedCharTy : BoolTy);
Fangrui Song6907ce22018-07-30 19:24:48 +00001300
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001301 ObjCConstantStringType = QualType();
Fangrui Song6907ce22018-07-30 19:24:48 +00001302
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001303 ObjCSuperType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +00001304
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00001305 // void * type
Yaxun Liu39195062017-08-04 18:16:31 +00001306 if (LangOpts.OpenCLVersion >= 200) {
1307 auto Q = VoidTy.getQualifiers();
1308 Q.setAddressSpace(LangAS::opencl_generic);
1309 VoidPtrTy = getPointerType(getCanonicalType(
1310 getQualifiedType(VoidTy.getUnqualifiedType(), Q)));
1311 } else {
1312 VoidPtrTy = getPointerType(VoidTy);
1313 }
Sebastian Redl576fd422009-05-10 18:38:11 +00001314
1315 // nullptr type (C++0x 2.14.7)
1316 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001317
1318 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1319 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +00001320
1321 // Builtin type used to help define __builtin_va_list.
Richard Smith9b88a4c2015-07-27 05:40:23 +00001322 VaListTagDecl = nullptr;
Chris Lattner970e54e2006-11-12 00:37:36 +00001323}
1324
David Blaikie9c902b52011-09-25 23:23:43 +00001325DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001326 return SourceMgr.getDiagnostics();
1327}
1328
Douglas Gregor561eceb2010-08-30 16:49:28 +00001329AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1330 AttrVec *&Result = DeclAttrs[D];
1331 if (!Result) {
1332 void *Mem = Allocate(sizeof(AttrVec));
1333 Result = new (Mem) AttrVec;
1334 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001335
Douglas Gregor561eceb2010-08-30 16:49:28 +00001336 return *Result;
1337}
1338
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001339/// Erase the attributes corresponding to the given declaration.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00001340void ASTContext::eraseDeclAttrs(const Decl *D) {
Douglas Gregor561eceb2010-08-30 16:49:28 +00001341 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1342 if (Pos != DeclAttrs.end()) {
1343 Pos->second->~AttrVec();
1344 DeclAttrs.erase(Pos);
1345 }
1346}
1347
Larisse Voufo39a1e502013-08-06 01:03:05 +00001348// FIXME: Remove ?
Douglas Gregor86d142a2009-10-08 07:24:58 +00001349MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +00001350ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001351 assert(Var->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001352 return getTemplateOrSpecializationInfo(Var)
1353 .dyn_cast<MemberSpecializationInfo *>();
1354}
1355
1356ASTContext::TemplateOrSpecializationInfo
1357ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1358 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1359 TemplateOrInstantiation.find(Var);
1360 if (Pos == TemplateOrInstantiation.end())
Eugene Zelenko7855e772018-04-03 00:11:50 +00001361 return {};
Mike Stump11289f42009-09-09 15:08:12 +00001362
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001363 return Pos->second;
1364}
1365
Mike Stump11289f42009-09-09 15:08:12 +00001366void
Douglas Gregor86d142a2009-10-08 07:24:58 +00001367ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +00001368 TemplateSpecializationKind TSK,
1369 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001370 assert(Inst->isStaticDataMember() && "Not a static data member");
1371 assert(Tmpl->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001372 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1373 Tmpl, TSK, PointOfInstantiation));
1374}
1375
1376void
1377ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1378 TemplateOrSpecializationInfo TSI) {
1379 assert(!TemplateOrInstantiation[Inst] &&
1380 "Already noted what the variable was instantiated from");
1381 TemplateOrInstantiation[Inst] = TSI;
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001382}
1383
John McCalle61f2ba2009-11-18 02:36:19 +00001384NamedDecl *
Richard Smithd8a9e372016-12-18 21:39:37 +00001385ASTContext::getInstantiatedFromUsingDecl(NamedDecl *UUD) {
1386 auto Pos = InstantiatedFromUsingDecl.find(UUD);
John McCallb96ec562009-12-04 22:46:56 +00001387 if (Pos == InstantiatedFromUsingDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001388 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001389
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001390 return Pos->second;
1391}
1392
1393void
Richard Smithd8a9e372016-12-18 21:39:37 +00001394ASTContext::setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern) {
John McCallb96ec562009-12-04 22:46:56 +00001395 assert((isa<UsingDecl>(Pattern) ||
1396 isa<UnresolvedUsingValueDecl>(Pattern) ||
Fangrui Song6907ce22018-07-30 19:24:48 +00001397 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
John McCallb96ec562009-12-04 22:46:56 +00001398 "pattern decl is not a using decl");
Richard Smithd8a9e372016-12-18 21:39:37 +00001399 assert((isa<UsingDecl>(Inst) ||
1400 isa<UnresolvedUsingValueDecl>(Inst) ||
Fangrui Song6907ce22018-07-30 19:24:48 +00001401 isa<UnresolvedUsingTypenameDecl>(Inst)) &&
Richard Smithd8a9e372016-12-18 21:39:37 +00001402 "instantiation did not produce a using decl");
John McCallb96ec562009-12-04 22:46:56 +00001403 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1404 InstantiatedFromUsingDecl[Inst] = Pattern;
1405}
1406
1407UsingShadowDecl *
1408ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1409 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1410 = InstantiatedFromUsingShadowDecl.find(Inst);
1411 if (Pos == InstantiatedFromUsingShadowDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001412 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00001413
1414 return Pos->second;
1415}
1416
1417void
1418ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1419 UsingShadowDecl *Pattern) {
1420 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1421 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001422}
1423
Anders Carlsson5da84842009-09-01 04:26:58 +00001424FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1425 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1426 = InstantiatedFromUnnamedFieldDecl.find(Field);
1427 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001428 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001429
Anders Carlsson5da84842009-09-01 04:26:58 +00001430 return Pos->second;
1431}
1432
1433void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1434 FieldDecl *Tmpl) {
1435 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1436 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1437 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1438 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +00001439
Anders Carlsson5da84842009-09-01 04:26:58 +00001440 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1441}
1442
Douglas Gregor832940b2010-03-02 23:58:15 +00001443ASTContext::overridden_cxx_method_iterator
1444ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
Benjamin Krameracfa3392017-12-17 23:52:45 +00001445 return overridden_methods(Method).begin();
Douglas Gregor832940b2010-03-02 23:58:15 +00001446}
1447
1448ASTContext::overridden_cxx_method_iterator
1449ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
Benjamin Krameracfa3392017-12-17 23:52:45 +00001450 return overridden_methods(Method).end();
Douglas Gregor832940b2010-03-02 23:58:15 +00001451}
1452
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001453unsigned
1454ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
Benjamin Krameracfa3392017-12-17 23:52:45 +00001455 auto Range = overridden_methods(Method);
1456 return Range.end() - Range.begin();
Clement Courbet8251ebf2016-06-10 11:54:43 +00001457}
1458
Clement Courbet6ecaec82016-07-05 07:49:31 +00001459ASTContext::overridden_method_range
1460ASTContext::overridden_methods(const CXXMethodDecl *Method) const {
Benjamin Krameracfa3392017-12-17 23:52:45 +00001461 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1462 OverriddenMethods.find(Method->getCanonicalDecl());
1463 if (Pos == OverriddenMethods.end())
1464 return overridden_method_range(nullptr, nullptr);
1465 return overridden_method_range(Pos->second.begin(), Pos->second.end());
Clement Courbet6ecaec82016-07-05 07:49:31 +00001466}
1467
Fangrui Song6907ce22018-07-30 19:24:48 +00001468void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
Douglas Gregor832940b2010-03-02 23:58:15 +00001469 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001470 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001471 OverriddenMethods[Method].push_back(Overridden);
1472}
1473
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +00001474void ASTContext::getOverriddenMethods(
1475 const NamedDecl *D,
1476 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001477 assert(D);
1478
Eugene Zelenko7855e772018-04-03 00:11:50 +00001479 if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisc8e70082013-04-17 00:09:03 +00001480 Overridden.append(overridden_methods_begin(CXXMethod),
1481 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001482 return;
1483 }
1484
Eugene Zelenko7855e772018-04-03 00:11:50 +00001485 const auto *Method = dyn_cast<ObjCMethodDecl>(D);
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001486 if (!Method)
1487 return;
1488
Argyrios Kyrtzidis353f6a42012-10-09 18:19:01 +00001489 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1490 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001491 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001492}
1493
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001494void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1495 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1496 assert(!Import->isFromASTFile() && "Non-local import declaration");
1497 if (!FirstLocalImport) {
1498 FirstLocalImport = Import;
1499 LastLocalImport = Import;
1500 return;
1501 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001502
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001503 LastLocalImport->NextLocalImport = Import;
1504 LastLocalImport = Import;
1505}
1506
Chris Lattner53cfe802007-07-18 17:52:12 +00001507//===----------------------------------------------------------------------===//
1508// Type Sizing and Analysis
1509//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001510
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001511/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1512/// scalar floating point type.
1513const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001514 const auto *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001515 assert(BT && "Not a floating point type!");
1516 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001517 default: llvm_unreachable("Not a floating point type!");
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00001518 case BuiltinType::Float16:
1519 case BuiltinType::Half:
1520 return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001521 case BuiltinType::Float: return Target->getFloatFormat();
1522 case BuiltinType::Double: return Target->getDoubleFormat();
1523 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001524 case BuiltinType::Float128: return Target->getFloat128Format();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001525 }
1526}
1527
Rafael Espindola71eccb32013-08-08 19:53:46 +00001528CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001529 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001530
John McCall94268702010-10-08 18:24:19 +00001531 bool UseAlignAttrOnly = false;
1532 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1533 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001534
John McCall94268702010-10-08 18:24:19 +00001535 // __attribute__((aligned)) can increase or decrease alignment
1536 // *except* on a struct or struct member, where it only increases
1537 // alignment unless 'packed' is also specified.
1538 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001539 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001540 // ignore that possibility; Sema should diagnose it.
1541 if (isa<FieldDecl>(D)) {
1542 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1543 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1544 } else {
1545 UseAlignAttrOnly = true;
1546 }
1547 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001548 else if (isa<FieldDecl>(D))
Fangrui Song6907ce22018-07-30 19:24:48 +00001549 UseAlignAttrOnly =
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001550 D->hasAttr<PackedAttr>() ||
1551 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001552
John McCall4e819612011-01-20 07:57:12 +00001553 // If we're using the align attribute only, just ignore everything
1554 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001555 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001556 // do nothing
Eugene Zelenko7855e772018-04-03 00:11:50 +00001557 } else if (const auto *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001558 QualType T = VD->getType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00001559 if (const auto *RT = T->getAs<ReferenceType>()) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001560 if (ForAlignof)
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001561 T = RT->getPointeeType();
1562 else
1563 T = getPointerType(RT->getPointeeType());
1564 }
Richard Smithf6d70302014-06-10 23:34:28 +00001565 QualType BaseT = getBaseElementType(T);
Akira Hatanakad62f2c82017-01-06 17:56:15 +00001566 if (T->isFunctionType())
1567 Align = getTypeInfoImpl(T.getTypePtr()).Align;
1568 else if (!BaseT->isIncompleteType()) {
John McCall33ddac02011-01-19 10:06:00 +00001569 // Adjust alignments of declarations with array type by the
1570 // large-array alignment on the target.
Rafael Espindola88572752013-08-07 18:08:19 +00001571 if (const ArrayType *arrayType = getAsArrayType(T)) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001572 unsigned MinWidth = Target->getLargeArrayMinWidth();
1573 if (!ForAlignof && MinWidth) {
Rafael Espindola88572752013-08-07 18:08:19 +00001574 if (isa<VariableArrayType>(arrayType))
1575 Align = std::max(Align, Target->getLargeArrayAlign());
1576 else if (isa<ConstantArrayType>(arrayType) &&
1577 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1578 Align = std::max(Align, Target->getLargeArrayAlign());
1579 }
John McCall33ddac02011-01-19 10:06:00 +00001580 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001581 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Roger Ferrer Ibanez3fa38a12017-03-08 14:00:44 +00001582 if (BaseT.getQualifiers().hasUnaligned())
1583 Align = Target->getCharWidth();
Eugene Zelenko7855e772018-04-03 00:11:50 +00001584 if (const auto *VD = dyn_cast<VarDecl>(D)) {
Tom Tanb7c6d952019-05-02 00:38:14 +00001585 if (VD->hasGlobalStorage() && !ForAlignof) {
1586 uint64_t TypeSize = getTypeSize(T.getTypePtr());
1587 Align = std::max(Align, getTargetInfo().getMinGlobalAlign(TypeSize));
1588 }
Ulrich Weigandfa806422013-05-06 16:23:57 +00001589 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001590 }
John McCall4e819612011-01-20 07:57:12 +00001591
1592 // Fields can be subject to extra alignment constraints, like if
1593 // the field is packed, the struct is packed, or the struct has a
1594 // a max-field-alignment constraint (#pragma pack). So calculate
1595 // the actual alignment of the field within the struct, and then
1596 // (as we're expected to) constrain that by the alignment of the type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00001597 if (const auto *Field = dyn_cast<FieldDecl>(VD)) {
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001598 const RecordDecl *Parent = Field->getParent();
1599 // We can only produce a sensible answer if the record is valid.
1600 if (!Parent->isInvalidDecl()) {
1601 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
John McCall4e819612011-01-20 07:57:12 +00001602
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001603 // Start with the record's overall alignment.
1604 unsigned FieldAlign = toBits(Layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001605
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001606 // Use the GCD of that and the offset within the record.
1607 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1608 if (Offset > 0) {
1609 // Alignment is always a power of 2, so the GCD will be a power of 2,
1610 // which means we get to do this crazy thing instead of Euclid's.
1611 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1612 if (LowBitOfOffset < FieldAlign)
1613 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1614 }
1615
1616 Align = std::min(Align, FieldAlign);
John McCall4e819612011-01-20 07:57:12 +00001617 }
Charles Davis3fc51072010-02-23 04:52:00 +00001618 }
Chris Lattner68061312009-01-24 21:53:27 +00001619 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001620
Ken Dyckcc56c542011-01-15 18:38:59 +00001621 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001622}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001623
John McCallf1249922012-08-21 04:10:00 +00001624// getTypeInfoDataSizeInChars - Return the size of a type, in
1625// chars. If the type is a record, its data size is returned. This is
1626// the size of the memcpy that's performed when assigning this type
1627// using a trivial copy/move assignment operator.
1628std::pair<CharUnits, CharUnits>
1629ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1630 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1631
1632 // In C++, objects can sometimes be allocated into the tail padding
1633 // of a base-class subobject. We decide whether that's possible
1634 // during class layout, so here we can just trust the layout results.
1635 if (getLangOpts().CPlusPlus) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001636 if (const auto *RT = T->getAs<RecordType>()) {
John McCallf1249922012-08-21 04:10:00 +00001637 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1638 sizeAndAlign.first = layout.getDataSize();
1639 }
1640 }
1641
1642 return sizeAndAlign;
1643}
1644
Richard Trieu04d2d942013-05-14 21:59:17 +00001645/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1646/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1647std::pair<CharUnits, CharUnits>
1648static getConstantArrayInfoInChars(const ASTContext &Context,
1649 const ConstantArrayType *CAT) {
1650 std::pair<CharUnits, CharUnits> EltInfo =
1651 Context.getTypeInfoInChars(CAT->getElementType());
1652 uint64_t Size = CAT->getSize().getZExtValue();
Richard Trieuc7509072013-05-14 23:41:50 +00001653 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1654 (uint64_t)(-1)/Size) &&
Richard Trieu04d2d942013-05-14 21:59:17 +00001655 "Overflow in array type char size evaluation");
1656 uint64_t Width = EltInfo.first.getQuantity() * Size;
1657 unsigned Align = EltInfo.second.getQuantity();
Warren Hunt5ae586a2013-11-01 23:59:41 +00001658 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1659 Context.getTargetInfo().getPointerWidth(0) == 64)
Rui Ueyama83aa9792016-01-14 21:00:27 +00001660 Width = llvm::alignTo(Width, Align);
Richard Trieu04d2d942013-05-14 21:59:17 +00001661 return std::make_pair(CharUnits::fromQuantity(Width),
1662 CharUnits::fromQuantity(Align));
1663}
1664
John McCall87fe5d52010-05-20 01:18:31 +00001665std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001666ASTContext::getTypeInfoInChars(const Type *T) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001667 if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
Richard Trieu04d2d942013-05-14 21:59:17 +00001668 return getConstantArrayInfoInChars(*this, CAT);
David Majnemer34b57492014-07-30 01:30:47 +00001669 TypeInfo Info = getTypeInfo(T);
1670 return std::make_pair(toCharUnitsFromBits(Info.Width),
1671 toCharUnitsFromBits(Info.Align));
John McCall87fe5d52010-05-20 01:18:31 +00001672}
1673
1674std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001675ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001676 return getTypeInfoInChars(T.getTypePtr());
1677}
1678
David Majnemer34b57492014-07-30 01:30:47 +00001679bool ASTContext::isAlignmentRequired(const Type *T) const {
1680 return getTypeInfo(T).AlignIsRequired;
1681}
Daniel Dunbarc6475872012-03-09 04:12:54 +00001682
David Majnemer34b57492014-07-30 01:30:47 +00001683bool ASTContext::isAlignmentRequired(QualType T) const {
1684 return isAlignmentRequired(T.getTypePtr());
1685}
1686
Richard Smithb2f0f052016-10-10 18:54:32 +00001687unsigned ASTContext::getTypeAlignIfKnown(QualType T) const {
1688 // An alignment on a typedef overrides anything else.
Eugene Zelenko7855e772018-04-03 00:11:50 +00001689 if (const auto *TT = T->getAs<TypedefType>())
Richard Smithb2f0f052016-10-10 18:54:32 +00001690 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1691 return Align;
1692
1693 // If we have an (array of) complete type, we're done.
1694 T = getBaseElementType(T);
1695 if (!T->isIncompleteType())
1696 return getTypeAlign(T);
1697
1698 // If we had an array type, its element type might be a typedef
1699 // type with an alignment attribute.
Eugene Zelenko7855e772018-04-03 00:11:50 +00001700 if (const auto *TT = T->getAs<TypedefType>())
Richard Smithb2f0f052016-10-10 18:54:32 +00001701 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1702 return Align;
1703
1704 // Otherwise, see if the declaration of the type had an attribute.
Eugene Zelenko7855e772018-04-03 00:11:50 +00001705 if (const auto *TT = T->getAs<TagType>())
Richard Smithb2f0f052016-10-10 18:54:32 +00001706 return TT->getDecl()->getMaxAlignment();
1707
1708 return 0;
1709}
1710
David Majnemer34b57492014-07-30 01:30:47 +00001711TypeInfo ASTContext::getTypeInfo(const Type *T) const {
David Majnemerf8d38642014-07-30 08:42:33 +00001712 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1713 if (I != MemoizedTypeInfo.end())
1714 return I->second;
1715
1716 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1717 TypeInfo TI = getTypeInfoImpl(T);
1718 MemoizedTypeInfo[T] = TI;
Rafael Espindolaeaa88c12014-07-30 04:40:23 +00001719 return TI;
Daniel Dunbarc6475872012-03-09 04:12:54 +00001720}
1721
1722/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1723/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001724///
1725/// FIXME: Pointers into different addr spaces could have different sizes and
1726/// alignment requirements: getPointerInfo should take an AddrSpace, this
1727/// should take a QualType, &c.
David Majnemer34b57492014-07-30 01:30:47 +00001728TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1729 uint64_t Width = 0;
1730 unsigned Align = 8;
1731 bool AlignIsRequired = false;
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001732 unsigned AS = 0;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001733 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001734#define TYPE(Class, Base)
1735#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001736#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001737#define DEPENDENT_TYPE(Class, Base) case Type::Class:
David Blaikieab277d62013-07-13 21:08:03 +00001738#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1739 case Type::Class: \
1740 assert(!T->isDependentType() && "should not see dependent types here"); \
1741 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001742#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001743 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001744
Chris Lattner355332d2007-07-13 22:27:08 +00001745 case Type::FunctionNoProto:
1746 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001747 // GCC extension: alignof(function) = 32 bits
1748 Width = 0;
1749 Align = 32;
1750 break;
1751
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001752 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001753 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001754 Width = 0;
1755 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1756 break;
1757
Steve Naroff5c131802007-08-30 01:06:46 +00001758 case Type::ConstantArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001759 const auto *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001760
David Majnemer34b57492014-07-30 01:30:47 +00001761 TypeInfo EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001762 uint64_t Size = CAT->getSize().getZExtValue();
David Majnemer34b57492014-07-30 01:30:47 +00001763 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
Daniel Dunbarc6475872012-03-09 04:12:54 +00001764 "Overflow in array type bit size evaluation");
David Majnemer34b57492014-07-30 01:30:47 +00001765 Width = EltInfo.Width * Size;
1766 Align = EltInfo.Align;
Warren Hunt5ae586a2013-11-01 23:59:41 +00001767 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1768 getTargetInfo().getPointerWidth(0) == 64)
Rui Ueyama83aa9792016-01-14 21:00:27 +00001769 Width = llvm::alignTo(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001770 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001771 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001772 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001773 case Type::Vector: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001774 const auto *VT = cast<VectorType>(T);
David Majnemer34b57492014-07-30 01:30:47 +00001775 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1776 Width = EltInfo.Width * VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001777 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001778 // If the alignment is not a power of 2, round up to the next power of 2.
1779 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001780 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001781 Align = llvm::NextPowerOf2(Align);
Rui Ueyama83aa9792016-01-14 21:00:27 +00001782 Width = llvm::alignTo(Width, Align);
Chris Lattner63d2b362009-10-22 05:17:15 +00001783 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001784 // Adjust the alignment based on the target max.
1785 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1786 if (TargetVectorAlign && TargetVectorAlign < Align)
1787 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001788 break;
1789 }
Chris Lattner647fb222007-07-18 18:26:58 +00001790
Chris Lattner7570e9c2008-03-08 08:52:55 +00001791 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001792 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001793 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001794 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001795 // GCC extension: alignof(void) = 8 bits.
1796 Width = 0;
1797 Align = 8;
1798 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001799 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001800 Width = Target->getBoolWidth();
1801 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001802 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001803 case BuiltinType::Char_S:
1804 case BuiltinType::Char_U:
1805 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001806 case BuiltinType::SChar:
Richard Smith3a8244d2018-05-01 05:02:45 +00001807 case BuiltinType::Char8:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001808 Width = Target->getCharWidth();
1809 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001810 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001811 case BuiltinType::WChar_S:
1812 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001813 Width = Target->getWCharWidth();
1814 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001815 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001816 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001817 Width = Target->getChar16Width();
1818 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001819 break;
1820 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001821 Width = Target->getChar32Width();
1822 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001823 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001824 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001825 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001826 Width = Target->getShortWidth();
1827 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001828 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001829 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001830 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001831 Width = Target->getIntWidth();
1832 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001833 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001834 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001835 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001836 Width = Target->getLongWidth();
1837 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001838 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001839 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001840 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001841 Width = Target->getLongLongWidth();
1842 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001843 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001844 case BuiltinType::Int128:
1845 case BuiltinType::UInt128:
1846 Width = 128;
1847 Align = 128; // int128_t is 128-bit aligned on all targets.
1848 break;
Leonard Chanf921d852018-06-04 16:07:52 +00001849 case BuiltinType::ShortAccum:
1850 case BuiltinType::UShortAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00001851 case BuiltinType::SatShortAccum:
1852 case BuiltinType::SatUShortAccum:
Leonard Chanf921d852018-06-04 16:07:52 +00001853 Width = Target->getShortAccumWidth();
1854 Align = Target->getShortAccumAlign();
1855 break;
1856 case BuiltinType::Accum:
1857 case BuiltinType::UAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00001858 case BuiltinType::SatAccum:
1859 case BuiltinType::SatUAccum:
Leonard Chanf921d852018-06-04 16:07:52 +00001860 Width = Target->getAccumWidth();
1861 Align = Target->getAccumAlign();
1862 break;
1863 case BuiltinType::LongAccum:
1864 case BuiltinType::ULongAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00001865 case BuiltinType::SatLongAccum:
1866 case BuiltinType::SatULongAccum:
Leonard Chanf921d852018-06-04 16:07:52 +00001867 Width = Target->getLongAccumWidth();
1868 Align = Target->getLongAccumAlign();
1869 break;
Leonard Chanab80f3c2018-06-14 14:53:51 +00001870 case BuiltinType::ShortFract:
1871 case BuiltinType::UShortFract:
1872 case BuiltinType::SatShortFract:
1873 case BuiltinType::SatUShortFract:
1874 Width = Target->getShortFractWidth();
1875 Align = Target->getShortFractAlign();
1876 break;
1877 case BuiltinType::Fract:
1878 case BuiltinType::UFract:
1879 case BuiltinType::SatFract:
1880 case BuiltinType::SatUFract:
1881 Width = Target->getFractWidth();
1882 Align = Target->getFractAlign();
1883 break;
1884 case BuiltinType::LongFract:
1885 case BuiltinType::ULongFract:
1886 case BuiltinType::SatLongFract:
1887 case BuiltinType::SatULongFract:
1888 Width = Target->getLongFractWidth();
1889 Align = Target->getLongFractAlign();
1890 break;
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00001891 case BuiltinType::Float16:
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001892 case BuiltinType::Half:
Alexey Bataev123ad192019-02-27 20:29:45 +00001893 if (Target->hasFloat16Type() || !getLangOpts().OpenMP ||
1894 !getLangOpts().OpenMPIsDevice) {
1895 Width = Target->getHalfWidth();
1896 Align = Target->getHalfAlign();
1897 } else {
1898 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
1899 "Expected OpenMP device compilation.");
1900 Width = AuxTarget->getHalfWidth();
1901 Align = AuxTarget->getHalfAlign();
1902 }
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001903 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001904 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001905 Width = Target->getFloatWidth();
1906 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001907 break;
1908 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001909 Width = Target->getDoubleWidth();
1910 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001911 break;
1912 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001913 Width = Target->getLongDoubleWidth();
1914 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001915 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001916 case BuiltinType::Float128:
Alexey Bataev123ad192019-02-27 20:29:45 +00001917 if (Target->hasFloat128Type() || !getLangOpts().OpenMP ||
1918 !getLangOpts().OpenMPIsDevice) {
1919 Width = Target->getFloat128Width();
1920 Align = Target->getFloat128Align();
1921 } else {
1922 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
1923 "Expected OpenMP device compilation.");
1924 Width = AuxTarget->getFloat128Width();
1925 Align = AuxTarget->getFloat128Align();
1926 }
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001927 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001928 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001929 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1930 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001931 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001932 case BuiltinType::ObjCId:
1933 case BuiltinType::ObjCClass:
1934 case BuiltinType::ObjCSel:
Fangrui Song6907ce22018-07-30 19:24:48 +00001935 Width = Target->getPointerWidth(0);
Douglas Gregore8bbc122011-09-02 00:18:52 +00001936 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001937 break;
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001938 case BuiltinType::OCLSampler:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001939 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001940 case BuiltinType::OCLClkEvent:
1941 case BuiltinType::OCLQueue:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001942 case BuiltinType::OCLReserveID:
Yaxun Liu99444cb2016-08-03 20:38:06 +00001943#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1944 case BuiltinType::Id:
1945#include "clang/Basic/OpenCLImageTypes.def"
Andrew Savonichev3fee3512018-11-08 11:25:41 +00001946#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1947 case BuiltinType::Id:
1948#include "clang/Basic/OpenCLExtensionTypes.def"
Sven van Haastregt3bb7eaf2017-12-06 10:11:28 +00001949 AS = getTargetAddressSpace(
1950 Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T)));
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001951 Width = Target->getPointerWidth(AS);
1952 Align = Target->getPointerAlign(AS);
1953 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001954 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001955 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001956 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001957 Width = Target->getPointerWidth(0);
1958 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001959 break;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00001960 case Type::BlockPointer:
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001961 AS = getTargetAddressSpace(cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001962 Width = Target->getPointerWidth(AS);
1963 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001964 break;
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001965 case Type::LValueReference:
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00001966 case Type::RValueReference:
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001967 // alignof and sizeof should never enter this code path here, so we go
1968 // the pointer route.
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001969 AS = getTargetAddressSpace(cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001970 Width = Target->getPointerWidth(AS);
1971 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001972 break;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00001973 case Type::Pointer:
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001974 AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001975 Width = Target->getPointerWidth(AS);
1976 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001977 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001978 case Type::MemberPointer: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001979 const auto *MPT = cast<MemberPointerType>(T);
Erich Keane8a6b7402017-11-30 16:37:02 +00001980 CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT);
1981 Width = MPI.Width;
1982 Align = MPI.Align;
Anders Carlsson32440a02009-05-17 02:06:04 +00001983 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001984 }
Chris Lattner647fb222007-07-18 18:26:58 +00001985 case Type::Complex: {
1986 // Complex types have the same alignment as their elements, but twice the
1987 // size.
David Majnemer34b57492014-07-30 01:30:47 +00001988 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
1989 Width = EltInfo.Width * 2;
1990 Align = EltInfo.Align;
Chris Lattner647fb222007-07-18 18:26:58 +00001991 break;
1992 }
John McCall8b07ec22010-05-15 11:32:37 +00001993 case Type::ObjCObject:
1994 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Reid Kleckner0503a872013-12-05 01:23:43 +00001995 case Type::Adjusted:
Reid Kleckner8a365022013-06-24 17:51:48 +00001996 case Type::Decayed:
Reid Kleckner0503a872013-12-05 01:23:43 +00001997 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001998 case Type::ObjCInterface: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001999 const auto *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00002000 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00002001 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00002002 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00002003 break;
2004 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002005 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002006 case Type::Enum: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002007 const auto *TT = cast<TagType>(T);
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00002008
2009 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00002010 Width = 8;
2011 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00002012 break;
2013 }
Mike Stump11289f42009-09-09 15:08:12 +00002014
Eugene Zelenko7855e772018-04-03 00:11:50 +00002015 if (const auto *ET = dyn_cast<EnumType>(TT)) {
David Majnemer475b25e2015-01-21 10:54:38 +00002016 const EnumDecl *ED = ET->getDecl();
2017 TypeInfo Info =
2018 getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType());
2019 if (unsigned AttrAlign = ED->getMaxAlignment()) {
2020 Info.Align = AttrAlign;
2021 Info.AlignIsRequired = true;
2022 }
2023 return Info;
2024 }
Chris Lattner8b23c252008-04-06 22:05:18 +00002025
Eugene Zelenko7855e772018-04-03 00:11:50 +00002026 const auto *RT = cast<RecordType>(TT);
David Majnemer5821ff72015-02-03 08:49:29 +00002027 const RecordDecl *RD = RT->getDecl();
2028 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
Ken Dyckb0fcc592011-02-11 01:54:29 +00002029 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00002030 Align = toBits(Layout.getAlignment());
David Majnemer5821ff72015-02-03 08:49:29 +00002031 AlignIsRequired = RD->hasAttr<AlignedAttr>();
Chris Lattner49a953a2007-07-23 22:46:22 +00002032 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00002033 }
Douglas Gregordc572a32009-03-30 22:58:21 +00002034
Chris Lattner63d2b362009-10-22 05:17:15 +00002035 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00002036 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
2037 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00002038
Richard Smith600b5262017-01-26 20:40:47 +00002039 case Type::Auto:
2040 case Type::DeducedTemplateSpecialization: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002041 const auto *A = cast<DeducedType>(T);
Richard Smith27d807c2013-04-30 13:56:41 +00002042 assert(!A->getDeducedType().isNull() &&
2043 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00002044 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00002045 }
2046
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002047 case Type::Paren:
2048 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
2049
Manman Rene6be26c2016-09-13 17:25:08 +00002050 case Type::ObjCTypeParam:
2051 return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr());
2052
Douglas Gregoref462e62009-04-30 17:32:17 +00002053 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00002054 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
David Majnemer34b57492014-07-30 01:30:47 +00002055 TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00002056 // If the typedef has an aligned attribute on it, it overrides any computed
2057 // alignment we have. This violates the GCC documentation (which says that
2058 // attribute(aligned) can only round up) but matches its implementation.
David Majnemer34b57492014-07-30 01:30:47 +00002059 if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
Chris Lattner29eb47b2011-02-19 22:55:41 +00002060 Align = AttrAlign;
David Majnemer34b57492014-07-30 01:30:47 +00002061 AlignIsRequired = true;
David Majnemer37bffb62014-08-04 05:11:01 +00002062 } else {
David Majnemer34b57492014-07-30 01:30:47 +00002063 Align = Info.Align;
David Majnemer37bffb62014-08-04 05:11:01 +00002064 AlignIsRequired = Info.AlignIsRequired;
2065 }
David Majnemer34b57492014-07-30 01:30:47 +00002066 Width = Info.Width;
Douglas Gregordc572a32009-03-30 22:58:21 +00002067 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00002068 }
Douglas Gregoref462e62009-04-30 17:32:17 +00002069
Abramo Bagnara6150c882010-05-11 21:36:43 +00002070 case Type::Elaborated:
2071 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00002072
John McCall81904512011-01-06 01:58:22 +00002073 case Type::Attributed:
2074 return getTypeInfo(
2075 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
2076
Eli Friedman0dfb8892011-10-06 23:00:33 +00002077 case Type::Atomic: {
John McCalla8ec7eb2013-03-07 21:37:17 +00002078 // Start with the base type information.
David Majnemer34b57492014-07-30 01:30:47 +00002079 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
2080 Width = Info.Width;
2081 Align = Info.Align;
John McCalla8ec7eb2013-03-07 21:37:17 +00002082
JF Bastien801fca22018-05-09 03:51:12 +00002083 if (!Width) {
2084 // An otherwise zero-sized type should still generate an
2085 // atomic operation.
2086 Width = Target->getCharWidth();
2087 assert(Align);
2088 } else if (Width <= Target->getMaxAtomicPromoteWidth()) {
2089 // If the size of the type doesn't exceed the platform's max
2090 // atomic promotion width, make the size and alignment more
2091 // favorable to atomic operations:
2092
John McCalla8ec7eb2013-03-07 21:37:17 +00002093 // Round the size up to a power of 2.
2094 if (!llvm::isPowerOf2_64(Width))
2095 Width = llvm::NextPowerOf2(Width);
2096
2097 // Set the alignment equal to the size.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00002098 Align = static_cast<unsigned>(Width);
2099 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00002100 }
Xiuli Pan9c14e282016-01-09 12:53:17 +00002101 break;
2102
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002103 case Type::Pipe:
Anastasia Stulovab3398932017-06-05 11:27:03 +00002104 Width = Target->getPointerWidth(getTargetAddressSpace(LangAS::opencl_global));
2105 Align = Target->getPointerAlign(getTargetAddressSpace(LangAS::opencl_global));
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002106 break;
Douglas Gregoref462e62009-04-30 17:32:17 +00002107 }
Mike Stump11289f42009-09-09 15:08:12 +00002108
Eli Friedman4b72fdd2011-10-14 20:59:01 +00002109 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
David Majnemer34b57492014-07-30 01:30:47 +00002110 return TypeInfo(Width, Align, AlignIsRequired);
Chris Lattner983a8bb2007-07-13 22:13:22 +00002111}
2112
Momchil Velikov20208cc2018-07-30 17:48:23 +00002113unsigned ASTContext::getTypeUnadjustedAlign(const Type *T) const {
2114 UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(T);
2115 if (I != MemoizedUnadjustedAlign.end())
2116 return I->second;
2117
2118 unsigned UnadjustedAlign;
2119 if (const auto *RT = T->getAs<RecordType>()) {
2120 const RecordDecl *RD = RT->getDecl();
2121 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2122 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2123 } else if (const auto *ObjCI = T->getAs<ObjCInterfaceType>()) {
2124 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2125 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2126 } else {
2127 UnadjustedAlign = getTypeAlign(T);
2128 }
2129
2130 MemoizedUnadjustedAlign[T] = UnadjustedAlign;
2131 return UnadjustedAlign;
2132}
2133
Alexey Bataev00396512015-07-02 03:40:19 +00002134unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
2135 unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign();
2136 // Target ppc64 with QPX: simd default alignment for pointer to double is 32.
2137 if ((getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64 ||
2138 getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64le) &&
2139 getTargetInfo().getABI() == "elfv1-qpx" &&
2140 T->isSpecificBuiltinType(BuiltinType::Double))
2141 SimdAlign = 256;
2142 return SimdAlign;
2143}
2144
Ken Dyckcc56c542011-01-15 18:38:59 +00002145/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
2146CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
2147 return CharUnits::fromQuantity(BitSize / getCharWidth());
2148}
2149
Ken Dyckb0fcc592011-02-11 01:54:29 +00002150/// toBits - Convert a size in characters to a size in characters.
2151int64_t ASTContext::toBits(CharUnits CharSize) const {
2152 return CharSize.getQuantity() * getCharWidth();
2153}
2154
Ken Dyck8c89d592009-12-22 14:23:30 +00002155/// getTypeSizeInChars - Return the size of the specified type, in characters.
2156/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00002157CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00002158 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00002159}
Jay Foad39c79802011-01-12 09:06:06 +00002160CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00002161 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00002162}
2163
Fangrui Song6907ce22018-07-30 19:24:48 +00002164/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00002165/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00002166CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00002167 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00002168}
Jay Foad39c79802011-01-12 09:06:06 +00002169CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00002170 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00002171}
2172
Momchil Velikov20208cc2018-07-30 17:48:23 +00002173/// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a
2174/// type, in characters, before alignment adustments. This method does
2175/// not work on incomplete types.
2176CharUnits ASTContext::getTypeUnadjustedAlignInChars(QualType T) const {
2177 return toCharUnitsFromBits(getTypeUnadjustedAlign(T));
2178}
2179CharUnits ASTContext::getTypeUnadjustedAlignInChars(const Type *T) const {
2180 return toCharUnitsFromBits(getTypeUnadjustedAlign(T));
2181}
2182
Chris Lattnera3402cd2009-01-27 18:08:34 +00002183/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
2184/// type for the current target in bits. This can be different than the ABI
2185/// alignment in cases where it is beneficial for performance to overalign
2186/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00002187unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
David Majnemer34b57492014-07-30 01:30:47 +00002188 TypeInfo TI = getTypeInfo(T);
2189 unsigned ABIAlign = TI.Align;
Eli Friedman7ab09572009-05-25 21:27:19 +00002190
David Majnemere1544562015-04-24 01:25:05 +00002191 T = T->getBaseElementTypeUnsafe();
2192
2193 // The preferred alignment of member pointers is that of a pointer.
2194 if (T->isMemberPointerType())
2195 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
2196
Andrey Turetskiydb6655f2016-02-10 11:58:46 +00002197 if (!Target->allowsLargerPreferedTypeAlignment())
2198 return ABIAlign;
Robert Lyttoneaf6f362013-11-12 10:09:34 +00002199
Eli Friedman7ab09572009-05-25 21:27:19 +00002200 // Double and long long should be naturally aligned if possible.
Eugene Zelenko7855e772018-04-03 00:11:50 +00002201 if (const auto *CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00002202 T = CT->getElementType().getTypePtr();
Eugene Zelenko7855e772018-04-03 00:11:50 +00002203 if (const auto *ET = T->getAs<EnumType>())
David Majnemer475b25e2015-01-21 10:54:38 +00002204 T = ET->getDecl()->getIntegerType().getTypePtr();
Eli Friedman7ab09572009-05-25 21:27:19 +00002205 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00002206 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
2207 T->isSpecificBuiltinType(BuiltinType::ULongLong))
David Majnemer8b6bd572014-02-24 23:34:17 +00002208 // Don't increase the alignment if an alignment attribute was specified on a
2209 // typedef declaration.
David Majnemer34b57492014-07-30 01:30:47 +00002210 if (!TI.AlignIsRequired)
David Majnemer8b6bd572014-02-24 23:34:17 +00002211 return std::max(ABIAlign, (unsigned)getTypeSize(T));
Eli Friedman7ab09572009-05-25 21:27:19 +00002212
Chris Lattnera3402cd2009-01-27 18:08:34 +00002213 return ABIAlign;
2214}
2215
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00002216/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2217/// for __attribute__((aligned)) on this target, to be used if no alignment
2218/// value is specified.
Eugene Zelenkod4304d22015-11-04 21:37:17 +00002219unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const {
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00002220 return getTargetInfo().getDefaultAlignForAttributeAligned();
2221}
2222
Ulrich Weigandfa806422013-05-06 16:23:57 +00002223/// getAlignOfGlobalVar - Return the alignment in bits that should be given
2224/// to a global variable of the specified type.
2225unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
Tom Tanb7c6d952019-05-02 00:38:14 +00002226 uint64_t TypeSize = getTypeSize(T.getTypePtr());
2227 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign(TypeSize));
Ulrich Weigandfa806422013-05-06 16:23:57 +00002228}
2229
2230/// getAlignOfGlobalVarInChars - Return the alignment in characters that
2231/// should be given to a global variable of the specified type.
2232CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
2233 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
2234}
2235
David Majnemer08ef2ba2015-06-23 20:34:18 +00002236CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
2237 CharUnits Offset = CharUnits::Zero();
2238 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
2239 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2240 Offset += Layout->getBaseClassOffset(Base);
2241 Layout = &getASTRecordLayout(Base);
2242 }
2243 return Offset;
2244}
2245
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002246/// DeepCollectObjCIvars -
2247/// This routine first collects all declared, but not synthesized, ivars in
2248/// super class and then collects all ivars, including those synthesized for
2249/// current class. This routine is used for implementation of current class
2250/// when all ivars, declared and synthesized are known.
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002251void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
2252 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00002253 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002254 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2255 DeepCollectObjCIvars(SuperClass, false, Ivars);
2256 if (!leafClass) {
Aaron Ballman59abbd42014-03-13 21:09:43 +00002257 for (const auto *I : OI->ivars())
2258 Ivars.push_back(I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00002259 } else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002260 auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Fangrui Song6907ce22018-07-30 19:24:48 +00002261 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00002262 Iv= Iv->getNextIvar())
2263 Ivars.push_back(Iv);
2264 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00002265}
2266
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002267/// CollectInheritedProtocols - Collect all protocols in current class and
2268/// those inherited by it.
2269void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00002270 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002271 if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00002272 // We can use protocol_iterator here instead of
Fangrui Song6907ce22018-07-30 19:24:48 +00002273 // all_referenced_protocol_iterator since we are walking all categories.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002274 for (auto *Proto : OI->all_referenced_protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002275 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00002276 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002277
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002278 // Categories of this Interface.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00002279 for (const auto *Cat : OI->visible_categories())
2280 CollectInheritedProtocols(Cat, Protocols);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002281
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002282 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2283 while (SD) {
2284 CollectInheritedProtocols(SD, Protocols);
2285 SD = SD->getSuperClass();
2286 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00002287 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00002288 for (auto *Proto : OC->protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002289 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002290 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00002291 } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002292 // Insert the protocol.
2293 if (!Protocols.insert(
2294 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2295 return;
2296
2297 for (auto *Proto : OP->protocols())
2298 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002299 }
2300}
2301
Erich Keane8a6b7402017-11-30 16:37:02 +00002302static bool unionHasUniqueObjectRepresentations(const ASTContext &Context,
2303 const RecordDecl *RD) {
2304 assert(RD->isUnion() && "Must be union type");
2305 CharUnits UnionSize = Context.getTypeSizeInChars(RD->getTypeForDecl());
2306
2307 for (const auto *Field : RD->fields()) {
2308 if (!Context.hasUniqueObjectRepresentations(Field->getType()))
2309 return false;
2310 CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType());
2311 if (FieldSize != UnionSize)
2312 return false;
2313 }
Eric Fiselier12a9f342018-02-02 20:30:39 +00002314 return !RD->field_empty();
Erich Keane8a6b7402017-11-30 16:37:02 +00002315}
2316
Benjamin Kramer802e6252017-12-24 12:46:22 +00002317static bool isStructEmpty(QualType Ty) {
Erich Keane8a6b7402017-11-30 16:37:02 +00002318 const RecordDecl *RD = Ty->castAs<RecordType>()->getDecl();
2319
2320 if (!RD->field_empty())
2321 return false;
2322
2323 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD))
2324 return ClassDecl->isEmpty();
2325
2326 return true;
2327}
2328
2329static llvm::Optional<int64_t>
2330structHasUniqueObjectRepresentations(const ASTContext &Context,
2331 const RecordDecl *RD) {
2332 assert(!RD->isUnion() && "Must be struct/class type");
2333 const auto &Layout = Context.getASTRecordLayout(RD);
2334
2335 int64_t CurOffsetInBits = 0;
2336 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) {
2337 if (ClassDecl->isDynamicClass())
2338 return llvm::None;
2339
2340 SmallVector<std::pair<QualType, int64_t>, 4> Bases;
2341 for (const auto Base : ClassDecl->bases()) {
2342 // Empty types can be inherited from, and non-empty types can potentially
2343 // have tail padding, so just make sure there isn't an error.
2344 if (!isStructEmpty(Base.getType())) {
2345 llvm::Optional<int64_t> Size = structHasUniqueObjectRepresentations(
2346 Context, Base.getType()->getAs<RecordType>()->getDecl());
2347 if (!Size)
2348 return llvm::None;
2349 Bases.emplace_back(Base.getType(), Size.getValue());
2350 }
2351 }
2352
Fangrui Song1d38c132018-09-30 21:41:11 +00002353 llvm::sort(Bases, [&](const std::pair<QualType, int64_t> &L,
2354 const std::pair<QualType, int64_t> &R) {
2355 return Layout.getBaseClassOffset(L.first->getAsCXXRecordDecl()) <
2356 Layout.getBaseClassOffset(R.first->getAsCXXRecordDecl());
2357 });
Erich Keane8a6b7402017-11-30 16:37:02 +00002358
2359 for (const auto Base : Bases) {
2360 int64_t BaseOffset = Context.toBits(
2361 Layout.getBaseClassOffset(Base.first->getAsCXXRecordDecl()));
2362 int64_t BaseSize = Base.second;
2363 if (BaseOffset != CurOffsetInBits)
2364 return llvm::None;
2365 CurOffsetInBits = BaseOffset + BaseSize;
2366 }
2367 }
2368
2369 for (const auto *Field : RD->fields()) {
2370 if (!Field->getType()->isReferenceType() &&
2371 !Context.hasUniqueObjectRepresentations(Field->getType()))
2372 return llvm::None;
2373
2374 int64_t FieldSizeInBits =
2375 Context.toBits(Context.getTypeSizeInChars(Field->getType()));
2376 if (Field->isBitField()) {
2377 int64_t BitfieldSize = Field->getBitWidthValue(Context);
2378
2379 if (BitfieldSize > FieldSizeInBits)
2380 return llvm::None;
2381 FieldSizeInBits = BitfieldSize;
2382 }
2383
2384 int64_t FieldOffsetInBits = Context.getFieldOffset(Field);
2385
2386 if (FieldOffsetInBits != CurOffsetInBits)
2387 return llvm::None;
2388
2389 CurOffsetInBits = FieldSizeInBits + FieldOffsetInBits;
2390 }
2391
2392 return CurOffsetInBits;
2393}
2394
2395bool ASTContext::hasUniqueObjectRepresentations(QualType Ty) const {
2396 // C++17 [meta.unary.prop]:
2397 // The predicate condition for a template specialization
2398 // has_unique_object_representations<T> shall be
2399 // satisfied if and only if:
2400 // (9.1) - T is trivially copyable, and
2401 // (9.2) - any two objects of type T with the same value have the same
2402 // object representation, where two objects
2403 // of array or non-union class type are considered to have the same value
2404 // if their respective sequences of
2405 // direct subobjects have the same values, and two objects of union type
2406 // are considered to have the same
2407 // value if they have the same active member and the corresponding members
2408 // have the same value.
2409 // The set of scalar types for which this condition holds is
2410 // implementation-defined. [ Note: If a type has padding
2411 // bits, the condition does not hold; otherwise, the condition holds true
2412 // for unsigned integral types. -- end note ]
2413 assert(!Ty.isNull() && "Null QualType sent to unique object rep check");
2414
2415 // Arrays are unique only if their element type is unique.
2416 if (Ty->isArrayType())
2417 return hasUniqueObjectRepresentations(getBaseElementType(Ty));
2418
2419 // (9.1) - T is trivially copyable...
2420 if (!Ty.isTriviallyCopyableType(*this))
2421 return false;
2422
2423 // All integrals and enums are unique.
2424 if (Ty->isIntegralOrEnumerationType())
2425 return true;
2426
2427 // All other pointers are unique.
2428 if (Ty->isPointerType())
2429 return true;
2430
2431 if (Ty->isMemberPointerType()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002432 const auto *MPT = Ty->getAs<MemberPointerType>();
Erich Keane8a6b7402017-11-30 16:37:02 +00002433 return !ABI->getMemberPointerInfo(MPT).HasPadding;
2434 }
2435
2436 if (Ty->isRecordType()) {
2437 const RecordDecl *Record = Ty->getAs<RecordType>()->getDecl();
2438
Erich Keanebd2197c2017-12-12 16:02:06 +00002439 if (Record->isInvalidDecl())
2440 return false;
2441
Erich Keane8a6b7402017-11-30 16:37:02 +00002442 if (Record->isUnion())
2443 return unionHasUniqueObjectRepresentations(*this, Record);
2444
2445 Optional<int64_t> StructSize =
2446 structHasUniqueObjectRepresentations(*this, Record);
2447
2448 return StructSize &&
2449 StructSize.getValue() == static_cast<int64_t>(getTypeSize(Ty));
2450 }
2451
2452 // FIXME: More cases to handle here (list by rsmith):
2453 // vectors (careful about, eg, vector of 3 foo)
2454 // _Complex int and friends
2455 // _Atomic T
2456 // Obj-C block pointers
2457 // Obj-C object pointers
2458 // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t,
2459 // clk_event_t, queue_t, reserve_id_t)
2460 // There're also Obj-C class types and the Obj-C selector type, but I think it
2461 // makes sense for those to return false here.
2462
2463 return false;
2464}
2465
Jay Foad39c79802011-01-12 09:06:06 +00002466unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00002467 unsigned count = 0;
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00002468 // Count ivars declared in class extension.
Aaron Ballmanb4a53452014-03-13 21:57:01 +00002469 for (const auto *Ext : OI->known_extensions())
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002470 count += Ext->ivar_size();
Fangrui Song6907ce22018-07-30 19:24:48 +00002471
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00002472 // Count ivar defined in this class's implementation. This
2473 // includes synthesized ivars.
2474 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00002475 count += ImplDecl->ivar_size();
2476
Fariborz Jahanian7c809592009-06-04 01:19:09 +00002477 return count;
2478}
2479
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00002480bool ASTContext::isSentinelNullExpr(const Expr *E) {
2481 if (!E)
2482 return false;
2483
2484 // nullptr_t is always treated as null.
2485 if (E->getType()->isNullPtrType()) return true;
2486
2487 if (E->getType()->isAnyPointerType() &&
2488 E->IgnoreParenCasts()->isNullPointerConstant(*this,
2489 Expr::NPC_ValueDependentIsNull))
2490 return true;
2491
2492 // Unfortunately, __null has type 'int'.
2493 if (isa<GNUNullExpr>(E)) return true;
2494
2495 return false;
2496}
2497
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002498/// Get the implementation of ObjCInterfaceDecl, or nullptr if none
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002499/// exists.
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002500ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
2501 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2502 I = ObjCImpls.find(D);
2503 if (I != ObjCImpls.end())
2504 return cast<ObjCImplementationDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002505 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002506}
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002507
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002508/// Get the implementation of ObjCCategoryDecl, or nullptr if none
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002509/// exists.
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002510ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
2511 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2512 I = ObjCImpls.find(D);
2513 if (I != ObjCImpls.end())
2514 return cast<ObjCCategoryImplDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002515 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002516}
2517
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002518/// Set the implementation of ObjCInterfaceDecl.
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002519void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2520 ObjCImplementationDecl *ImplD) {
2521 assert(IFaceD && ImplD && "Passed null params");
2522 ObjCImpls[IFaceD] = ImplD;
2523}
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002524
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002525/// Set the implementation of ObjCCategoryDecl.
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002526void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
2527 ObjCCategoryImplDecl *ImplD) {
2528 assert(CatD && ImplD && "Passed null params");
2529 ObjCImpls[CatD] = ImplD;
2530}
2531
Chandler Carruth21c90602015-12-30 03:24:14 +00002532const ObjCMethodDecl *
2533ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const {
2534 return ObjCMethodRedecls.lookup(MD);
2535}
2536
2537void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
2538 const ObjCMethodDecl *Redecl) {
2539 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
2540 ObjCMethodRedecls[MD] = Redecl;
2541}
2542
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002543const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
2544 const NamedDecl *ND) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002545 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002546 return ID;
Eugene Zelenko7855e772018-04-03 00:11:50 +00002547 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002548 return CD->getClassInterface();
Eugene Zelenko7855e772018-04-03 00:11:50 +00002549 if (const auto *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002550 return IMD->getClassInterface();
2551
Craig Topper36250ad2014-05-12 05:36:57 +00002552 return nullptr;
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002553}
2554
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002555/// Get the copy initialization expression of VarDecl, or nullptr if
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002556/// none exists.
Akira Hatanaka9978da32018-08-10 15:09:24 +00002557ASTContext::BlockVarCopyInit
2558ASTContext::getBlockVarCopyInit(const VarDecl*VD) const {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002559 assert(VD && "Passed null params");
Fangrui Song6907ce22018-07-30 19:24:48 +00002560 assert(VD->hasAttr<BlocksAttr>() &&
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002561 "getBlockVarCopyInits - not __block var");
Akira Hatanaka9978da32018-08-10 15:09:24 +00002562 auto I = BlockVarCopyInits.find(VD);
2563 if (I != BlockVarCopyInits.end())
2564 return I->second;
2565 return {nullptr, false};
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002566}
2567
JF Bastien0d702a72019-04-30 00:11:53 +00002568/// Set the copy initialization expression of a block var decl.
Akira Hatanaka9978da32018-08-10 15:09:24 +00002569void ASTContext::setBlockVarCopyInit(const VarDecl*VD, Expr *CopyExpr,
2570 bool CanThrow) {
2571 assert(VD && CopyExpr && "Passed null params");
Fangrui Song6907ce22018-07-30 19:24:48 +00002572 assert(VD->hasAttr<BlocksAttr>() &&
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002573 "setBlockVarCopyInits - not __block var");
Akira Hatanaka9978da32018-08-10 15:09:24 +00002574 BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002575}
2576
John McCallbcd03502009-12-07 02:54:59 +00002577TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002578 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00002579 if (!DataSize)
2580 DataSize = TypeLoc::getFullDataSizeForType(T);
2581 else
2582 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00002583 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00002584
Eugene Zelenko7855e772018-04-03 00:11:50 +00002585 auto *TInfo =
John McCallbcd03502009-12-07 02:54:59 +00002586 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
2587 new (TInfo) TypeSourceInfo(T);
2588 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00002589}
2590
John McCallbcd03502009-12-07 02:54:59 +00002591TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002592 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00002593 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00002594 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00002595 return DI;
2596}
2597
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002598const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002599ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Craig Topper36250ad2014-05-12 05:36:57 +00002600 return getObjCLayout(D, nullptr);
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002601}
2602
2603const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002604ASTContext::getASTObjCImplementationLayout(
2605 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002606 return getObjCLayout(D->getClassInterface(), D);
2607}
2608
Chris Lattner983a8bb2007-07-13 22:13:22 +00002609//===----------------------------------------------------------------------===//
2610// Type creation/memoization methods
2611//===----------------------------------------------------------------------===//
2612
Jay Foad39c79802011-01-12 09:06:06 +00002613QualType
John McCall33ddac02011-01-19 10:06:00 +00002614ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2615 unsigned fastQuals = quals.getFastQualifiers();
2616 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00002617
2618 // Check if we've already instantiated this type.
2619 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002620 ExtQuals::Profile(ID, baseType, quals);
Craig Topper36250ad2014-05-12 05:36:57 +00002621 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002622 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2623 assert(eq->getQualifiers() == quals);
2624 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002625 }
2626
John McCall33ddac02011-01-19 10:06:00 +00002627 // If the base type is not canonical, make the appropriate canonical type.
2628 QualType canon;
2629 if (!baseType->isCanonicalUnqualified()) {
2630 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00002631 canonSplit.Quals.addConsistentQualifiers(quals);
2632 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002633
2634 // Re-find the insert position.
2635 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2636 }
2637
Eugene Zelenko7855e772018-04-03 00:11:50 +00002638 auto *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
John McCall33ddac02011-01-19 10:06:00 +00002639 ExtQualNodes.InsertNode(eq, insertPos);
2640 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002641}
2642
Alexander Richardson6d989432017-10-15 18:48:14 +00002643QualType ASTContext::getAddrSpaceQualType(QualType T,
2644 LangAS AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002645 QualType CanT = getCanonicalType(T);
2646 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00002647 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00002648
John McCall8ccfcb52009-09-24 19:53:00 +00002649 // If we are composing extended qualifiers together, merge together
2650 // into one ExtQuals node.
2651 QualifierCollector Quals;
2652 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002653
John McCall8ccfcb52009-09-24 19:53:00 +00002654 // If this type already has an address space specified, it cannot get
2655 // another one.
2656 assert(!Quals.hasAddressSpace() &&
2657 "Type cannot be in multiple addr spaces!");
2658 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00002659
John McCall8ccfcb52009-09-24 19:53:00 +00002660 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00002661}
2662
Andrew Gozillon572bbb02017-10-02 06:25:51 +00002663QualType ASTContext::removeAddrSpaceQualType(QualType T) const {
2664 // If we are composing extended qualifiers together, merge together
2665 // into one ExtQuals node.
2666 QualifierCollector Quals;
2667 const Type *TypeNode = Quals.strip(T);
2668
2669 // If the qualifier doesn't have an address space just return it.
2670 if (!Quals.hasAddressSpace())
2671 return T;
2672
2673 Quals.removeAddressSpace();
2674
2675 // Removal of the address space can mean there are no longer any
2676 // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts)
2677 // or required.
2678 if (Quals.hasNonFastQualifiers())
2679 return getExtQualType(TypeNode, Quals);
2680 else
2681 return QualType(TypeNode, Quals.getFastQualifiers());
2682}
2683
Chris Lattnerd60183d2009-02-18 22:53:11 +00002684QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002685 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002686 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00002687 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002688 return T;
Mike Stump11289f42009-09-09 15:08:12 +00002689
Eugene Zelenko7855e772018-04-03 00:11:50 +00002690 if (const auto *ptr = T->getAs<PointerType>()) {
John McCall53fa7142010-12-24 02:08:15 +00002691 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00002692 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00002693 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2694 return getPointerType(ResultType);
2695 }
2696 }
Mike Stump11289f42009-09-09 15:08:12 +00002697
John McCall8ccfcb52009-09-24 19:53:00 +00002698 // If we are composing extended qualifiers together, merge together
2699 // into one ExtQuals node.
2700 QualifierCollector Quals;
2701 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002702
John McCall8ccfcb52009-09-24 19:53:00 +00002703 // If this type already has an ObjCGC specified, it cannot get
2704 // another one.
2705 assert(!Quals.hasObjCGCAttr() &&
2706 "Type cannot have multiple ObjCGCs!");
2707 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00002708
John McCall8ccfcb52009-09-24 19:53:00 +00002709 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002710}
Chris Lattner983a8bb2007-07-13 22:13:22 +00002711
John McCall4f5019e2010-12-19 02:44:49 +00002712const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2713 FunctionType::ExtInfo Info) {
2714 if (T->getExtInfo() == Info)
2715 return T;
2716
2717 QualType Result;
Eugene Zelenko7855e772018-04-03 00:11:50 +00002718 if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
Alp Toker314cc812014-01-25 16:55:45 +00002719 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
John McCall4f5019e2010-12-19 02:44:49 +00002720 } else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002721 const auto *FPT = cast<FunctionProtoType>(T);
John McCall4f5019e2010-12-19 02:44:49 +00002722 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2723 EPI.ExtInfo = Info;
Alp Toker314cc812014-01-25 16:55:45 +00002724 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
John McCall4f5019e2010-12-19 02:44:49 +00002725 }
2726
2727 return cast<FunctionType>(Result.getTypePtr());
2728}
2729
Richard Smith2a7d4812013-05-04 07:00:32 +00002730void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2731 QualType ResultType) {
Richard Smith1fa5d642013-05-11 05:45:24 +00002732 FD = FD->getMostRecentDecl();
2733 while (true) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002734 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
Richard Smith2a7d4812013-05-04 07:00:32 +00002735 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Alp Toker9cacbab2014-01-20 20:26:09 +00002736 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
Richard Smith1fa5d642013-05-11 05:45:24 +00002737 if (FunctionDecl *Next = FD->getPreviousDecl())
2738 FD = Next;
2739 else
2740 break;
Richard Smith2a7d4812013-05-04 07:00:32 +00002741 }
Richard Smith1fa5d642013-05-11 05:45:24 +00002742 if (ASTMutationListener *L = getASTMutationListener())
2743 L->DeducedReturnType(FD, ResultType);
Richard Smith2a7d4812013-05-04 07:00:32 +00002744}
2745
Richard Smith0b3a4622014-11-13 20:01:57 +00002746/// Get a function type and produce the equivalent function type with the
2747/// specified exception specification. Type sugar that can be present on a
2748/// declaration of a function with an exception specification is permitted
2749/// and preserved. Other type sugar (for instance, typedefs) is not.
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002750QualType ASTContext::getFunctionTypeWithExceptionSpec(
2751 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) {
Richard Smith0b3a4622014-11-13 20:01:57 +00002752 // Might have some parens.
Eugene Zelenko7855e772018-04-03 00:11:50 +00002753 if (const auto *PT = dyn_cast<ParenType>(Orig))
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002754 return getParenType(
2755 getFunctionTypeWithExceptionSpec(PT->getInnerType(), ESI));
Richard Smith0b3a4622014-11-13 20:01:57 +00002756
2757 // Might have a calling-convention attribute.
Eugene Zelenko7855e772018-04-03 00:11:50 +00002758 if (const auto *AT = dyn_cast<AttributedType>(Orig))
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002759 return getAttributedType(
Richard Smith0b3a4622014-11-13 20:01:57 +00002760 AT->getAttrKind(),
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002761 getFunctionTypeWithExceptionSpec(AT->getModifiedType(), ESI),
2762 getFunctionTypeWithExceptionSpec(AT->getEquivalentType(), ESI));
Richard Smith0b3a4622014-11-13 20:01:57 +00002763
2764 // Anything else must be a function type. Rebuild it with the new exception
2765 // specification.
Stephan Bergmann84dcc8f2019-02-13 09:39:17 +00002766 const auto *Proto = Orig->getAs<FunctionProtoType>();
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002767 return getFunctionType(
Richard Smith0b3a4622014-11-13 20:01:57 +00002768 Proto->getReturnType(), Proto->getParamTypes(),
2769 Proto->getExtProtoInfo().withExceptionSpec(ESI));
2770}
2771
Richard Smithdfe85e22016-12-15 02:35:39 +00002772bool ASTContext::hasSameFunctionTypeIgnoringExceptionSpec(QualType T,
2773 QualType U) {
2774 return hasSameType(T, U) ||
Aaron Ballmanc351fba2017-12-04 20:27:34 +00002775 (getLangOpts().CPlusPlus17 &&
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002776 hasSameType(getFunctionTypeWithExceptionSpec(T, EST_None),
2777 getFunctionTypeWithExceptionSpec(U, EST_None)));
Richard Smithdfe85e22016-12-15 02:35:39 +00002778}
2779
Richard Smith0b3a4622014-11-13 20:01:57 +00002780void ASTContext::adjustExceptionSpec(
2781 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
2782 bool AsWritten) {
2783 // Update the type.
2784 QualType Updated =
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002785 getFunctionTypeWithExceptionSpec(FD->getType(), ESI);
Richard Smith0b3a4622014-11-13 20:01:57 +00002786 FD->setType(Updated);
2787
2788 if (!AsWritten)
2789 return;
2790
2791 // Update the type in the type source information too.
2792 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
2793 // If the type and the type-as-written differ, we may need to update
2794 // the type-as-written too.
2795 if (TSInfo->getType() != FD->getType())
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002796 Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI);
Richard Smith0b3a4622014-11-13 20:01:57 +00002797
2798 // FIXME: When we get proper type location information for exceptions,
2799 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
2800 // up the TypeSourceInfo;
2801 assert(TypeLoc::getFullDataSizeForType(Updated) ==
2802 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
2803 "TypeLoc size mismatch from updating exception specification");
2804 TSInfo->overrideType(Updated);
2805 }
2806}
2807
Chris Lattnerc6395932007-06-22 20:56:16 +00002808/// getComplexType - Return the uniqued reference to the type for a complex
2809/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00002810QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00002811 // Unique pointers, to guarantee there is only one pointer of a particular
2812 // structure.
2813 llvm::FoldingSetNodeID ID;
2814 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002815
Craig Topper36250ad2014-05-12 05:36:57 +00002816 void *InsertPos = nullptr;
Chris Lattnerc6395932007-06-22 20:56:16 +00002817 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2818 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002819
Chris Lattnerc6395932007-06-22 20:56:16 +00002820 // If the pointee type isn't canonical, this won't be a canonical type either,
2821 // so fill in the canonical type field.
2822 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002823 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002824 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002825
Chris Lattnerc6395932007-06-22 20:56:16 +00002826 // Get the new insert position for the node we care about.
2827 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002828 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00002829 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00002830 auto *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00002831 Types.push_back(New);
2832 ComplexTypes.InsertNode(New, InsertPos);
2833 return QualType(New, 0);
2834}
2835
Chris Lattner970e54e2006-11-12 00:37:36 +00002836/// getPointerType - Return the uniqued reference to the type for a pointer to
2837/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002838QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00002839 // Unique pointers, to guarantee there is only one pointer of a particular
2840 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002841 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00002842 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002843
Craig Topper36250ad2014-05-12 05:36:57 +00002844 void *InsertPos = nullptr;
Chris Lattner67521df2007-01-27 01:29:36 +00002845 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002846 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002847
Chris Lattner7ccecb92006-11-12 08:50:50 +00002848 // If the pointee type isn't canonical, this won't be a canonical type either,
2849 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002850 QualType Canonical;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002851 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002852 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002853
Bob Wilsonc8541f22013-03-15 17:12:43 +00002854 // Get the new insert position for the node we care about.
2855 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002856 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002857 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00002858 auto *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00002859 Types.push_back(New);
2860 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002861 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00002862}
2863
Reid Kleckner0503a872013-12-05 01:23:43 +00002864QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
2865 llvm::FoldingSetNodeID ID;
2866 AdjustedType::Profile(ID, Orig, New);
Craig Topper36250ad2014-05-12 05:36:57 +00002867 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002868 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2869 if (AT)
2870 return QualType(AT, 0);
2871
2872 QualType Canonical = getCanonicalType(New);
2873
2874 // Get the new insert position for the node we care about.
2875 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002876 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner0503a872013-12-05 01:23:43 +00002877
2878 AT = new (*this, TypeAlignment)
2879 AdjustedType(Type::Adjusted, Orig, New, Canonical);
2880 Types.push_back(AT);
2881 AdjustedTypes.InsertNode(AT, InsertPos);
2882 return QualType(AT, 0);
2883}
2884
Reid Kleckner8a365022013-06-24 17:51:48 +00002885QualType ASTContext::getDecayedType(QualType T) const {
2886 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2887
Reid Kleckner8a365022013-06-24 17:51:48 +00002888 QualType Decayed;
2889
2890 // C99 6.7.5.3p7:
2891 // A declaration of a parameter as "array of type" shall be
2892 // adjusted to "qualified pointer to type", where the type
2893 // qualifiers (if any) are those specified within the [ and ] of
2894 // the array type derivation.
2895 if (T->isArrayType())
2896 Decayed = getArrayDecayedType(T);
2897
2898 // C99 6.7.5.3p8:
2899 // A declaration of a parameter as "function returning type"
2900 // shall be adjusted to "pointer to function returning type", as
2901 // in 6.3.2.1.
2902 if (T->isFunctionType())
2903 Decayed = getPointerType(T);
2904
Reid Kleckner0503a872013-12-05 01:23:43 +00002905 llvm::FoldingSetNodeID ID;
2906 AdjustedType::Profile(ID, T, Decayed);
Craig Topper36250ad2014-05-12 05:36:57 +00002907 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002908 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2909 if (AT)
2910 return QualType(AT, 0);
2911
Reid Kleckner8a365022013-06-24 17:51:48 +00002912 QualType Canonical = getCanonicalType(Decayed);
2913
2914 // Get the new insert position for the node we care about.
Reid Kleckner0503a872013-12-05 01:23:43 +00002915 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002916 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner8a365022013-06-24 17:51:48 +00002917
Reid Kleckner0503a872013-12-05 01:23:43 +00002918 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2919 Types.push_back(AT);
2920 AdjustedTypes.InsertNode(AT, InsertPos);
2921 return QualType(AT, 0);
Reid Kleckner8a365022013-06-24 17:51:48 +00002922}
2923
Mike Stump11289f42009-09-09 15:08:12 +00002924/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00002925/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00002926QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00002927 assert(T->isFunctionType() && "block of function types only");
2928 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00002929 // structure.
2930 llvm::FoldingSetNodeID ID;
2931 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002932
Craig Topper36250ad2014-05-12 05:36:57 +00002933 void *InsertPos = nullptr;
Steve Naroffec33ed92008-08-27 16:04:49 +00002934 if (BlockPointerType *PT =
2935 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2936 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002937
2938 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00002939 // type either so fill in the canonical type field.
2940 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002941 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00002942 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002943
Steve Naroffec33ed92008-08-27 16:04:49 +00002944 // Get the new insert position for the node we care about.
2945 BlockPointerType *NewIP =
2946 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002947 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00002948 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00002949 auto *New = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00002950 Types.push_back(New);
2951 BlockPointerTypes.InsertNode(New, InsertPos);
2952 return QualType(New, 0);
2953}
2954
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002955/// getLValueReferenceType - Return the uniqued reference to the type for an
2956/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002957QualType
2958ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00002959 assert(getCanonicalType(T) != OverloadTy &&
Douglas Gregor291e8ee2011-05-21 22:16:50 +00002960 "Unresolved overloaded function type");
Fangrui Song6907ce22018-07-30 19:24:48 +00002961
Bill Wendling3708c182007-05-27 10:15:43 +00002962 // Unique pointers, to guarantee there is only one pointer of a particular
2963 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002964 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002965 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002966
Craig Topper36250ad2014-05-12 05:36:57 +00002967 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002968 if (LValueReferenceType *RT =
2969 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00002970 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002971
Eugene Zelenko7855e772018-04-03 00:11:50 +00002972 const auto *InnerRef = T->getAs<ReferenceType>();
John McCallfc93cf92009-10-22 22:37:11 +00002973
Bill Wendling3708c182007-05-27 10:15:43 +00002974 // If the referencee type isn't canonical, this won't be a canonical type
2975 // either, so fill in the canonical type field.
2976 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002977 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2978 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2979 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002980
Bill Wendling3708c182007-05-27 10:15:43 +00002981 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002982 LValueReferenceType *NewIP =
2983 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002984 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00002985 }
2986
Eugene Zelenko7855e772018-04-03 00:11:50 +00002987 auto *New = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2988 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002989 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002990 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00002991
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002992 return QualType(New, 0);
2993}
2994
2995/// getRValueReferenceType - Return the uniqued reference to the type for an
2996/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002997QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002998 // Unique pointers, to guarantee there is only one pointer of a particular
2999 // structure.
3000 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00003001 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003002
Craig Topper36250ad2014-05-12 05:36:57 +00003003 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003004 if (RValueReferenceType *RT =
3005 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
3006 return QualType(RT, 0);
3007
Eugene Zelenko7855e772018-04-03 00:11:50 +00003008 const auto *InnerRef = T->getAs<ReferenceType>();
John McCallfc93cf92009-10-22 22:37:11 +00003009
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003010 // If the referencee type isn't canonical, this won't be a canonical type
3011 // either, so fill in the canonical type field.
3012 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00003013 if (InnerRef || !T.isCanonical()) {
3014 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
3015 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003016
3017 // Get the new insert position for the node we care about.
3018 RValueReferenceType *NewIP =
3019 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003020 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003021 }
3022
Eugene Zelenko7855e772018-04-03 00:11:50 +00003023 auto *New = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003024 Types.push_back(New);
3025 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00003026 return QualType(New, 0);
3027}
3028
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00003029/// getMemberPointerType - Return the uniqued reference to the type for a
3030/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00003031QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00003032 // Unique pointers, to guarantee there is only one pointer of a particular
3033 // structure.
3034 llvm::FoldingSetNodeID ID;
3035 MemberPointerType::Profile(ID, T, Cls);
3036
Craig Topper36250ad2014-05-12 05:36:57 +00003037 void *InsertPos = nullptr;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00003038 if (MemberPointerType *PT =
3039 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3040 return QualType(PT, 0);
3041
3042 // If the pointee or class type isn't canonical, this won't be a canonical
3043 // type either, so fill in the canonical type field.
3044 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00003045 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00003046 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
3047
3048 // Get the new insert position for the node we care about.
3049 MemberPointerType *NewIP =
3050 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003051 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00003052 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00003053 auto *New = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00003054 Types.push_back(New);
3055 MemberPointerTypes.InsertNode(New, InsertPos);
3056 return QualType(New, 0);
3057}
3058
Mike Stump11289f42009-09-09 15:08:12 +00003059/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00003060/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00003061QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00003062 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00003063 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00003064 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00003065 assert((EltTy->isDependentType() ||
3066 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00003067 "Constant array of VLAs is illegal!");
3068
Chris Lattnere2df3f92009-05-13 04:12:56 +00003069 // Convert the array size into a canonical width matching the pointer size for
3070 // the target.
3071 llvm::APInt ArySize(ArySizeIn);
Konstantin Zhuravlyov9c1e3102017-03-21 18:55:39 +00003072 ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth());
Mike Stump11289f42009-09-09 15:08:12 +00003073
Chris Lattner23b7eb62007-06-15 23:05:46 +00003074 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00003075 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00003076
Craig Topper36250ad2014-05-12 05:36:57 +00003077 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003078 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00003079 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003080 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003081
John McCall33ddac02011-01-19 10:06:00 +00003082 // If the element type isn't canonical or has qualifiers, this won't
3083 // be a canonical type either, so fill in the canonical type field.
3084 QualType Canon;
3085 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
3086 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00003087 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00003088 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00003089 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00003090
Chris Lattner36f8e652007-01-27 08:31:04 +00003091 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00003092 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00003093 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003094 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00003095 }
Mike Stump11289f42009-09-09 15:08:12 +00003096
Eugene Zelenko7855e772018-04-03 00:11:50 +00003097 auto *New = new (*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00003098 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00003099 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00003100 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003101 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00003102}
3103
John McCall06549462011-01-18 08:40:38 +00003104/// getVariableArrayDecayedType - Turns the given type, which may be
3105/// variably-modified, into the corresponding type with all the known
3106/// sizes replaced with [*].
3107QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
3108 // Vastly most common case.
3109 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003110
John McCall06549462011-01-18 08:40:38 +00003111 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003112
John McCall06549462011-01-18 08:40:38 +00003113 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00003114 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00003115 switch (ty->getTypeClass()) {
3116#define TYPE(Class, Base)
3117#define ABSTRACT_TYPE(Class, Base)
3118#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3119#include "clang/AST/TypeNodes.def"
3120 llvm_unreachable("didn't desugar past all non-canonical types?");
3121
3122 // These types should never be variably-modified.
3123 case Type::Builtin:
3124 case Type::Complex:
3125 case Type::Vector:
Erich Keanef702b022018-07-13 19:46:04 +00003126 case Type::DependentVector:
John McCall06549462011-01-18 08:40:38 +00003127 case Type::ExtVector:
3128 case Type::DependentSizedExtVector:
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003129 case Type::DependentAddressSpace:
John McCall06549462011-01-18 08:40:38 +00003130 case Type::ObjCObject:
3131 case Type::ObjCInterface:
3132 case Type::ObjCObjectPointer:
3133 case Type::Record:
3134 case Type::Enum:
3135 case Type::UnresolvedUsing:
3136 case Type::TypeOfExpr:
3137 case Type::TypeOf:
3138 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00003139 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00003140 case Type::DependentName:
3141 case Type::InjectedClassName:
3142 case Type::TemplateSpecialization:
3143 case Type::DependentTemplateSpecialization:
3144 case Type::TemplateTypeParm:
3145 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00003146 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00003147 case Type::DeducedTemplateSpecialization:
John McCall06549462011-01-18 08:40:38 +00003148 case Type::PackExpansion:
3149 llvm_unreachable("type should never be variably-modified");
3150
3151 // These types can be variably-modified but should never need to
3152 // further decay.
3153 case Type::FunctionNoProto:
3154 case Type::FunctionProto:
3155 case Type::BlockPointer:
3156 case Type::MemberPointer:
Xiuli Pan9c14e282016-01-09 12:53:17 +00003157 case Type::Pipe:
John McCall06549462011-01-18 08:40:38 +00003158 return type;
3159
3160 // These types can be variably-modified. All these modifications
3161 // preserve structure except as noted by comments.
3162 // TODO: if we ever care about optimizing VLAs, there are no-op
3163 // optimizations available here.
3164 case Type::Pointer:
3165 result = getPointerType(getVariableArrayDecayedType(
3166 cast<PointerType>(ty)->getPointeeType()));
3167 break;
3168
3169 case Type::LValueReference: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003170 const auto *lv = cast<LValueReferenceType>(ty);
John McCall06549462011-01-18 08:40:38 +00003171 result = getLValueReferenceType(
3172 getVariableArrayDecayedType(lv->getPointeeType()),
3173 lv->isSpelledAsLValue());
3174 break;
3175 }
3176
3177 case Type::RValueReference: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003178 const auto *lv = cast<RValueReferenceType>(ty);
John McCall06549462011-01-18 08:40:38 +00003179 result = getRValueReferenceType(
3180 getVariableArrayDecayedType(lv->getPointeeType()));
3181 break;
3182 }
3183
Eli Friedman0dfb8892011-10-06 23:00:33 +00003184 case Type::Atomic: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003185 const auto *at = cast<AtomicType>(ty);
Eli Friedman0dfb8892011-10-06 23:00:33 +00003186 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
3187 break;
3188 }
3189
John McCall06549462011-01-18 08:40:38 +00003190 case Type::ConstantArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003191 const auto *cat = cast<ConstantArrayType>(ty);
John McCall06549462011-01-18 08:40:38 +00003192 result = getConstantArrayType(
3193 getVariableArrayDecayedType(cat->getElementType()),
3194 cat->getSize(),
3195 cat->getSizeModifier(),
3196 cat->getIndexTypeCVRQualifiers());
3197 break;
3198 }
3199
3200 case Type::DependentSizedArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003201 const auto *dat = cast<DependentSizedArrayType>(ty);
John McCall06549462011-01-18 08:40:38 +00003202 result = getDependentSizedArrayType(
3203 getVariableArrayDecayedType(dat->getElementType()),
3204 dat->getSizeExpr(),
3205 dat->getSizeModifier(),
3206 dat->getIndexTypeCVRQualifiers(),
3207 dat->getBracketsRange());
3208 break;
3209 }
3210
3211 // Turn incomplete types into [*] types.
3212 case Type::IncompleteArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003213 const auto *iat = cast<IncompleteArrayType>(ty);
John McCall06549462011-01-18 08:40:38 +00003214 result = getVariableArrayType(
3215 getVariableArrayDecayedType(iat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00003216 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00003217 ArrayType::Normal,
3218 iat->getIndexTypeCVRQualifiers(),
3219 SourceRange());
3220 break;
3221 }
3222
3223 // Turn VLA types into [*] types.
3224 case Type::VariableArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003225 const auto *vat = cast<VariableArrayType>(ty);
John McCall06549462011-01-18 08:40:38 +00003226 result = getVariableArrayType(
3227 getVariableArrayDecayedType(vat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00003228 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00003229 ArrayType::Star,
3230 vat->getIndexTypeCVRQualifiers(),
3231 vat->getBracketsRange());
3232 break;
3233 }
3234 }
3235
3236 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00003237 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00003238}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003239
Steve Naroffcadebd02007-08-30 18:14:25 +00003240/// getVariableArrayType - Returns a non-unique reference to the type for a
3241/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00003242QualType ASTContext::getVariableArrayType(QualType EltTy,
3243 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00003244 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00003245 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00003246 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00003247 // Since we don't unique expressions, it isn't possible to unique VLA's
3248 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00003249 QualType Canon;
Fangrui Song6907ce22018-07-30 19:24:48 +00003250
John McCall33ddac02011-01-19 10:06:00 +00003251 // Be sure to pull qualifiers off the element type.
3252 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
3253 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00003254 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00003255 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00003256 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00003257 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003258
Eugene Zelenko7855e772018-04-03 00:11:50 +00003259 auto *New = new (*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00003260 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00003261
3262 VariableArrayTypes.push_back(New);
3263 Types.push_back(New);
3264 return QualType(New, 0);
3265}
3266
Douglas Gregor4619e432008-12-05 23:32:09 +00003267/// getDependentSizedArrayType - Returns a non-unique reference to
3268/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00003269/// type.
John McCall33ddac02011-01-19 10:06:00 +00003270QualType ASTContext::getDependentSizedArrayType(QualType elementType,
3271 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00003272 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00003273 unsigned elementTypeQuals,
3274 SourceRange brackets) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00003275 assert((!numElements || numElements->isTypeDependent() ||
John McCall33ddac02011-01-19 10:06:00 +00003276 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00003277 "Size must be type- or value-dependent!");
3278
John McCall33ddac02011-01-19 10:06:00 +00003279 // Dependently-sized array types that do not have a specified number
3280 // of elements will have their sizes deduced from a dependent
3281 // initializer. We do no canonicalization here at all, which is okay
3282 // because they can't be used in most locations.
3283 if (!numElements) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003284 auto *newType
John McCall33ddac02011-01-19 10:06:00 +00003285 = new (*this, TypeAlignment)
3286 DependentSizedArrayType(*this, elementType, QualType(),
3287 numElements, ASM, elementTypeQuals,
3288 brackets);
3289 Types.push_back(newType);
3290 return QualType(newType, 0);
3291 }
3292
3293 // Otherwise, we actually build a new type every time, but we
3294 // also build a canonical type.
3295
3296 SplitQualType canonElementType = getCanonicalType(elementType).split();
3297
Craig Topper36250ad2014-05-12 05:36:57 +00003298 void *insertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00003299 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00003300 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00003301 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00003302 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00003303
John McCall33ddac02011-01-19 10:06:00 +00003304 // Look for an existing type with these properties.
3305 DependentSizedArrayType *canonTy =
3306 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00003307
John McCall33ddac02011-01-19 10:06:00 +00003308 // If we don't have one, build one.
3309 if (!canonTy) {
3310 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00003311 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00003312 QualType(), numElements, ASM, elementTypeQuals,
3313 brackets);
3314 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
3315 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00003316 }
3317
John McCall33ddac02011-01-19 10:06:00 +00003318 // Apply qualifiers from the element type to the array.
3319 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00003320 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00003321
David Majnemer16a74702015-07-24 05:54:19 +00003322 // If we didn't need extra canonicalization for the element type or the size
3323 // expression, then just use that as our result.
3324 if (QualType(canonElementType.Ty, 0) == elementType &&
3325 canonTy->getSizeExpr() == numElements)
John McCall33ddac02011-01-19 10:06:00 +00003326 return canon;
3327
3328 // Otherwise, we need to build a type which follows the spelling
3329 // of the element type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00003330 auto *sugaredType
John McCall33ddac02011-01-19 10:06:00 +00003331 = new (*this, TypeAlignment)
3332 DependentSizedArrayType(*this, elementType, canon, numElements,
3333 ASM, elementTypeQuals, brackets);
3334 Types.push_back(sugaredType);
3335 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00003336}
3337
John McCall33ddac02011-01-19 10:06:00 +00003338QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00003339 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00003340 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00003341 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00003342 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00003343
Craig Topper36250ad2014-05-12 05:36:57 +00003344 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00003345 if (IncompleteArrayType *iat =
3346 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
3347 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00003348
3349 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00003350 // either, so fill in the canonical type field. We also have to pull
3351 // qualifiers off the element type.
3352 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00003353
John McCall33ddac02011-01-19 10:06:00 +00003354 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
3355 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00003356 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00003357 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00003358 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00003359
3360 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00003361 IncompleteArrayType *existing =
3362 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
3363 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00003364 }
Eli Friedmanbd258282008-02-15 18:16:39 +00003365
Eugene Zelenko7855e772018-04-03 00:11:50 +00003366 auto *newType = new (*this, TypeAlignment)
John McCall33ddac02011-01-19 10:06:00 +00003367 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00003368
John McCall33ddac02011-01-19 10:06:00 +00003369 IncompleteArrayTypes.InsertNode(newType, insertPos);
3370 Types.push_back(newType);
3371 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00003372}
3373
Steve Naroff91fcddb2007-07-18 18:00:27 +00003374/// getVectorType - Return the unique reference to a vector type of
3375/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00003376QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00003377 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00003378 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00003379
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003380 // Check if we've already instantiated a vector of this type.
3381 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00003382 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00003383
Craig Topper36250ad2014-05-12 05:36:57 +00003384 void *InsertPos = nullptr;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003385 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3386 return QualType(VTP, 0);
3387
3388 // If the element type isn't canonical, this won't be a canonical type either,
3389 // so fill in the canonical type field.
3390 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00003391 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00003392 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00003393
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003394 // Get the new insert position for the node we care about.
3395 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003396 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003397 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00003398 auto *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00003399 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003400 VectorTypes.InsertNode(New, InsertPos);
3401 Types.push_back(New);
3402 return QualType(New, 0);
3403}
3404
Erich Keanef702b022018-07-13 19:46:04 +00003405QualType
3406ASTContext::getDependentVectorType(QualType VecType, Expr *SizeExpr,
3407 SourceLocation AttrLoc,
3408 VectorType::VectorKind VecKind) const {
3409 llvm::FoldingSetNodeID ID;
3410 DependentVectorType::Profile(ID, *this, getCanonicalType(VecType), SizeExpr,
3411 VecKind);
3412 void *InsertPos = nullptr;
3413 DependentVectorType *Canon =
3414 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3415 DependentVectorType *New;
3416
3417 if (Canon) {
3418 New = new (*this, TypeAlignment) DependentVectorType(
3419 *this, VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind);
3420 } else {
3421 QualType CanonVecTy = getCanonicalType(VecType);
3422 if (CanonVecTy == VecType) {
3423 New = new (*this, TypeAlignment) DependentVectorType(
3424 *this, VecType, QualType(), SizeExpr, AttrLoc, VecKind);
3425
3426 DependentVectorType *CanonCheck =
3427 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3428 assert(!CanonCheck &&
3429 "Dependent-sized vector_size canonical type broken");
3430 (void)CanonCheck;
3431 DependentVectorTypes.InsertNode(New, InsertPos);
3432 } else {
3433 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
3434 SourceLocation());
3435 New = new (*this, TypeAlignment) DependentVectorType(
3436 *this, VecType, Canon, SizeExpr, AttrLoc, VecKind);
3437 }
3438 }
3439
3440 Types.push_back(New);
3441 return QualType(New, 0);
3442}
3443
Nate Begemance4d7fc2008-04-18 23:10:10 +00003444/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00003445/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00003446QualType
3447ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00003448 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00003449
Steve Naroff91fcddb2007-07-18 18:00:27 +00003450 // Check if we've already instantiated a vector of this type.
3451 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00003452 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00003453 VectorType::GenericVector);
Craig Topper36250ad2014-05-12 05:36:57 +00003454 void *InsertPos = nullptr;
Steve Naroff91fcddb2007-07-18 18:00:27 +00003455 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3456 return QualType(VTP, 0);
3457
3458 // If the element type isn't canonical, this won't be a canonical type either,
3459 // so fill in the canonical type field.
3460 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00003461 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00003462 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00003463
Steve Naroff91fcddb2007-07-18 18:00:27 +00003464 // Get the new insert position for the node we care about.
3465 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003466 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00003467 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00003468 auto *New = new (*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00003469 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00003470 VectorTypes.InsertNode(New, InsertPos);
3471 Types.push_back(New);
3472 return QualType(New, 0);
3473}
3474
Jay Foad39c79802011-01-12 09:06:06 +00003475QualType
3476ASTContext::getDependentSizedExtVectorType(QualType vecType,
3477 Expr *SizeExpr,
3478 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00003479 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00003480 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00003481 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003482
Craig Topper36250ad2014-05-12 05:36:57 +00003483 void *InsertPos = nullptr;
Douglas Gregor352169a2009-07-31 03:54:25 +00003484 DependentSizedExtVectorType *Canon
3485 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3486 DependentSizedExtVectorType *New;
3487 if (Canon) {
3488 // We already have a canonical version of this array type; use it as
3489 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00003490 New = new (*this, TypeAlignment)
3491 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
3492 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00003493 } else {
3494 QualType CanonVecTy = getCanonicalType(vecType);
3495 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00003496 New = new (*this, TypeAlignment)
3497 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
3498 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003499
3500 DependentSizedExtVectorType *CanonCheck
3501 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3502 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
3503 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00003504 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
3505 } else {
3506 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
3507 SourceLocation());
Fangrui Song6907ce22018-07-30 19:24:48 +00003508 New = new (*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00003509 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00003510 }
3511 }
Mike Stump11289f42009-09-09 15:08:12 +00003512
Douglas Gregor758a8692009-06-17 21:51:59 +00003513 Types.push_back(New);
3514 return QualType(New, 0);
3515}
3516
Fangrui Song6907ce22018-07-30 19:24:48 +00003517QualType ASTContext::getDependentAddressSpaceType(QualType PointeeType,
3518 Expr *AddrSpaceExpr,
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003519 SourceLocation AttrLoc) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00003520 assert(AddrSpaceExpr->isInstantiationDependent());
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003521
3522 QualType canonPointeeType = getCanonicalType(PointeeType);
3523
3524 void *insertPos = nullptr;
3525 llvm::FoldingSetNodeID ID;
3526 DependentAddressSpaceType::Profile(ID, *this, canonPointeeType,
3527 AddrSpaceExpr);
3528
3529 DependentAddressSpaceType *canonTy =
3530 DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos);
3531
3532 if (!canonTy) {
3533 canonTy = new (*this, TypeAlignment)
Fangrui Song6907ce22018-07-30 19:24:48 +00003534 DependentAddressSpaceType(*this, canonPointeeType,
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003535 QualType(), AddrSpaceExpr, AttrLoc);
3536 DependentAddressSpaceTypes.InsertNode(canonTy, insertPos);
3537 Types.push_back(canonTy);
3538 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003539
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003540 if (canonPointeeType == PointeeType &&
3541 canonTy->getAddrSpaceExpr() == AddrSpaceExpr)
Fangrui Song6907ce22018-07-30 19:24:48 +00003542 return QualType(canonTy, 0);
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003543
Eugene Zelenko7855e772018-04-03 00:11:50 +00003544 auto *sugaredType
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003545 = new (*this, TypeAlignment)
Fangrui Song6907ce22018-07-30 19:24:48 +00003546 DependentAddressSpaceType(*this, PointeeType, QualType(canonTy, 0),
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003547 AddrSpaceExpr, AttrLoc);
3548 Types.push_back(sugaredType);
Fangrui Song6907ce22018-07-30 19:24:48 +00003549 return QualType(sugaredType, 0);
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003550}
3551
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003552/// Determine whether \p T is canonical as the result type of a function.
John McCall18afab72016-03-01 00:49:02 +00003553static bool isCanonicalResultType(QualType T) {
3554 return T.isCanonical() &&
3555 (T.getObjCLifetime() == Qualifiers::OCL_None ||
3556 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
3557}
3558
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003559/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Jay Foad39c79802011-01-12 09:06:06 +00003560QualType
3561ASTContext::getFunctionNoProtoType(QualType ResultTy,
3562 const FunctionType::ExtInfo &Info) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003563 // Unique functions, to guarantee there is only one function of a particular
3564 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00003565 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00003566 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00003567
Craig Topper36250ad2014-05-12 05:36:57 +00003568 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003569 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003570 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003571 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003572
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003573 QualType Canonical;
John McCall18afab72016-03-01 00:49:02 +00003574 if (!isCanonicalResultType(ResultTy)) {
3575 Canonical =
3576 getFunctionNoProtoType(getCanonicalFunctionResultType(ResultTy), Info);
Mike Stump11289f42009-09-09 15:08:12 +00003577
Chris Lattner47955de2007-01-27 08:37:20 +00003578 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003579 FunctionNoProtoType *NewIP =
3580 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003581 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00003582 }
Mike Stump11289f42009-09-09 15:08:12 +00003583
Eugene Zelenko7855e772018-04-03 00:11:50 +00003584 auto *New = new (*this, TypeAlignment)
John McCall18afab72016-03-01 00:49:02 +00003585 FunctionNoProtoType(ResultTy, Canonical, Info);
Chris Lattner47955de2007-01-27 08:37:20 +00003586 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003587 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003588 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003589}
3590
Douglas Gregora602a152015-10-01 20:20:47 +00003591CanQualType
3592ASTContext::getCanonicalFunctionResultType(QualType ResultType) const {
3593 CanQualType CanResultType = getCanonicalType(ResultType);
3594
3595 // Canonical result types do not have ARC lifetime qualifiers.
3596 if (CanResultType.getQualifiers().hasObjCLifetime()) {
3597 Qualifiers Qs = CanResultType.getQualifiers();
3598 Qs.removeObjCLifetime();
3599 return CanQualType::CreateUnsafe(
3600 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
3601 }
3602
3603 return CanResultType;
3604}
3605
Richard Smith3c4f8d22016-10-16 17:54:23 +00003606static bool isCanonicalExceptionSpecification(
3607 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
3608 if (ESI.Type == EST_None)
3609 return true;
3610 if (!NoexceptInType)
3611 return false;
3612
3613 // C++17 onwards: exception specification is part of the type, as a simple
3614 // boolean "can this function type throw".
3615 if (ESI.Type == EST_BasicNoexcept)
3616 return true;
3617
Richard Smitheaf11ad2018-05-03 03:58:32 +00003618 // A noexcept(expr) specification is (possibly) canonical if expr is
3619 // value-dependent.
3620 if (ESI.Type == EST_DependentNoexcept)
3621 return true;
3622
Richard Smith3c4f8d22016-10-16 17:54:23 +00003623 // A dynamic exception specification is canonical if it only contains pack
Richard Smith2a2cda52016-10-18 19:29:18 +00003624 // expansions (so we can't tell whether it's non-throwing) and all its
3625 // contained types are canonical.
Richard Smith3c4f8d22016-10-16 17:54:23 +00003626 if (ESI.Type == EST_Dynamic) {
Richard Smithfda59e52016-10-26 01:05:54 +00003627 bool AnyPackExpansions = false;
3628 for (QualType ET : ESI.Exceptions) {
3629 if (!ET.isCanonical())
Richard Smith3c4f8d22016-10-16 17:54:23 +00003630 return false;
Richard Smithfda59e52016-10-26 01:05:54 +00003631 if (ET->getAs<PackExpansionType>())
3632 AnyPackExpansions = true;
3633 }
3634 return AnyPackExpansions;
Richard Smith3c4f8d22016-10-16 17:54:23 +00003635 }
3636
Richard Smith3c4f8d22016-10-16 17:54:23 +00003637 return false;
3638}
3639
Richard Smith304b1242016-10-18 20:13:25 +00003640QualType ASTContext::getFunctionTypeInternal(
3641 QualType ResultTy, ArrayRef<QualType> ArgArray,
3642 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
Jordan Rose5c382722013-03-08 21:51:21 +00003643 size_t NumArgs = ArgArray.size();
3644
Richard Smith2a2cda52016-10-18 19:29:18 +00003645 // Unique functions, to guarantee there is only one function of a particular
3646 // structure.
3647 llvm::FoldingSetNodeID ID;
3648 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
3649 *this, true);
Richard Smith3c4f8d22016-10-16 17:54:23 +00003650
Richard Smith2a2cda52016-10-18 19:29:18 +00003651 QualType Canonical;
3652 bool Unique = false;
3653
3654 void *InsertPos = nullptr;
3655 if (FunctionProtoType *FPT =
3656 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
3657 QualType Existing = QualType(FPT, 0);
3658
3659 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
3660 // it so long as our exception specification doesn't contain a dependent
Richard Smith304b1242016-10-18 20:13:25 +00003661 // noexcept expression, or we're just looking for a canonical type.
3662 // Otherwise, we're going to need to create a type
Richard Smith2a2cda52016-10-18 19:29:18 +00003663 // sugar node to hold the concrete expression.
Richard Smitheaf11ad2018-05-03 03:58:32 +00003664 if (OnlyWantCanonical || !isComputedNoexcept(EPI.ExceptionSpec.Type) ||
Richard Smith2a2cda52016-10-18 19:29:18 +00003665 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
3666 return Existing;
3667
3668 // We need a new type sugar node for this one, to hold the new noexcept
3669 // expression. We do no canonicalization here, but that's OK since we don't
3670 // expect to see the same noexcept expression much more than once.
3671 Canonical = getCanonicalType(Existing);
3672 Unique = true;
3673 }
3674
Aaron Ballmanc351fba2017-12-04 20:27:34 +00003675 bool NoexceptInType = getLangOpts().CPlusPlus17;
Richard Smith3c4f8d22016-10-16 17:54:23 +00003676 bool IsCanonicalExceptionSpec =
3677 isCanonicalExceptionSpecification(EPI.ExceptionSpec, NoexceptInType);
3678
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003679 // Determine whether the type being created is already canonical or not.
Richard Smith2a2cda52016-10-18 19:29:18 +00003680 bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
Richard Smith3c4f8d22016-10-16 17:54:23 +00003681 isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003682 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003683 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003684 isCanonical = false;
3685
Richard Smith304b1242016-10-18 20:13:25 +00003686 if (OnlyWantCanonical)
3687 assert(isCanonical &&
3688 "given non-canonical parameters constructing canonical type");
3689
Richard Smith2a2cda52016-10-18 19:29:18 +00003690 // If this type isn't canonical, get the canonical version of it if we don't
3691 // already have it. The exception spec is only partially part of the
3692 // canonical type, and only in C++17 onwards.
3693 if (!isCanonical && Canonical.isNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003694 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003695 CanonicalArgs.reserve(NumArgs);
3696 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003697 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003698
Benjamin Kramer3f515cd2016-10-26 12:51:45 +00003699 llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
John McCalldb40c7f2010-12-14 08:05:40 +00003700 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00003701 CanonicalEPI.HasTrailingReturn = false;
Richard Smith3c4f8d22016-10-16 17:54:23 +00003702
3703 if (IsCanonicalExceptionSpec) {
3704 // Exception spec is already OK.
3705 } else if (NoexceptInType) {
3706 switch (EPI.ExceptionSpec.Type) {
3707 case EST_Unparsed: case EST_Unevaluated: case EST_Uninstantiated:
3708 // We don't know yet. It shouldn't matter what we pick here; no-one
3709 // should ever look at this.
3710 LLVM_FALLTHROUGH;
Richard Smitheaf11ad2018-05-03 03:58:32 +00003711 case EST_None: case EST_MSAny: case EST_NoexceptFalse:
Richard Smith3c4f8d22016-10-16 17:54:23 +00003712 CanonicalEPI.ExceptionSpec.Type = EST_None;
3713 break;
3714
Richard Smith2a2cda52016-10-18 19:29:18 +00003715 // A dynamic exception specification is almost always "not noexcept",
3716 // with the exception that a pack expansion might expand to no types.
3717 case EST_Dynamic: {
3718 bool AnyPacks = false;
3719 for (QualType ET : EPI.ExceptionSpec.Exceptions) {
3720 if (ET->getAs<PackExpansionType>())
3721 AnyPacks = true;
3722 ExceptionTypeStorage.push_back(getCanonicalType(ET));
3723 }
3724 if (!AnyPacks)
3725 CanonicalEPI.ExceptionSpec.Type = EST_None;
3726 else {
3727 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
3728 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
3729 }
3730 break;
3731 }
3732
Richard Smitheaf11ad2018-05-03 03:58:32 +00003733 case EST_DynamicNone: case EST_BasicNoexcept: case EST_NoexceptTrue:
Richard Smith3c4f8d22016-10-16 17:54:23 +00003734 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
3735 break;
3736
Richard Smitheaf11ad2018-05-03 03:58:32 +00003737 case EST_DependentNoexcept:
3738 llvm_unreachable("dependent noexcept is already canonical");
Richard Smith3c4f8d22016-10-16 17:54:23 +00003739 }
Richard Smith3c4f8d22016-10-16 17:54:23 +00003740 } else {
3741 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
3742 }
John McCalldb40c7f2010-12-14 08:05:40 +00003743
Douglas Gregora602a152015-10-01 20:20:47 +00003744 // Adjust the canonical function result type.
3745 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
Richard Smith304b1242016-10-18 20:13:25 +00003746 Canonical =
3747 getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003748
Chris Lattnerfd4de792007-01-27 01:15:32 +00003749 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003750 FunctionProtoType *NewIP =
3751 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003752 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003753 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003754
Bruno Ricci26a25362018-10-02 11:46:38 +00003755 // Compute the needed size to hold this FunctionProtoType and the
3756 // various trailing objects.
3757 auto ESH = FunctionProtoType::getExceptionSpecSize(
3758 EPI.ExceptionSpec.Type, EPI.ExceptionSpec.Exceptions.size());
3759 size_t Size = FunctionProtoType::totalSizeToAlloc<
3760 QualType, FunctionType::FunctionTypeExtraBitfields,
3761 FunctionType::ExceptionType, Expr *, FunctionDecl *,
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00003762 FunctionProtoType::ExtParameterInfo, Qualifiers>(
Bruno Ricci26a25362018-10-02 11:46:38 +00003763 NumArgs, FunctionProtoType::hasExtraBitfields(EPI.ExceptionSpec.Type),
3764 ESH.NumExceptionType, ESH.NumExprPtr, ESH.NumFunctionDeclPtr,
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00003765 EPI.ExtParameterInfos ? NumArgs : 0,
3766 EPI.TypeQuals.hasNonFastQualifiers() ? 1 : 0);
John McCall18afab72016-03-01 00:49:02 +00003767
Bruno Ricci26a25362018-10-02 11:46:38 +00003768 auto *FTP = (FunctionProtoType *)Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00003769 FunctionProtoType::ExtProtoInfo newEPI = EPI;
Jordan Rose5c382722013-03-08 21:51:21 +00003770 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003771 Types.push_back(FTP);
Richard Smith2a2cda52016-10-18 19:29:18 +00003772 if (!Unique)
3773 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003774 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003775}
Chris Lattneref51c202006-11-10 07:17:23 +00003776
Joey Goulye3c85de2016-12-01 11:30:49 +00003777QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
Xiuli Pan9c14e282016-01-09 12:53:17 +00003778 llvm::FoldingSetNodeID ID;
Joey Goulye3c85de2016-12-01 11:30:49 +00003779 PipeType::Profile(ID, T, ReadOnly);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003780
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00003781 void *InsertPos = nullptr;
Joey Goulye3c85de2016-12-01 11:30:49 +00003782 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
Xiuli Pan9c14e282016-01-09 12:53:17 +00003783 return QualType(PT, 0);
3784
3785 // If the pipe element type isn't canonical, this won't be a canonical type
3786 // either, so fill in the canonical type field.
3787 QualType Canonical;
3788 if (!T.isCanonical()) {
Joey Goulye3c85de2016-12-01 11:30:49 +00003789 Canonical = getPipeType(getCanonicalType(T), ReadOnly);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003790
3791 // Get the new insert position for the node we care about.
Joey Goulye3c85de2016-12-01 11:30:49 +00003792 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003793 assert(!NewIP && "Shouldn't be in the map!");
3794 (void)NewIP;
3795 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00003796 auto *New = new (*this, TypeAlignment) PipeType(T, Canonical, ReadOnly);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003797 Types.push_back(New);
Joey Goulye3c85de2016-12-01 11:30:49 +00003798 PipeTypes.InsertNode(New, InsertPos);
Joey Gouly5788b782016-11-18 14:10:54 +00003799 return QualType(New, 0);
3800}
3801
Anastasia Stulova59055b92018-05-09 13:23:26 +00003802QualType ASTContext::adjustStringLiteralBaseType(QualType Ty) const {
3803 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
3804 return LangOpts.OpenCL ? getAddrSpaceQualType(Ty, LangAS::opencl_constant)
3805 : Ty;
3806}
3807
Joey Goulye3c85de2016-12-01 11:30:49 +00003808QualType ASTContext::getReadPipeType(QualType T) const {
3809 return getPipeType(T, true);
3810}
3811
Joey Gouly5788b782016-11-18 14:10:54 +00003812QualType ASTContext::getWritePipeType(QualType T) const {
Joey Goulye3c85de2016-12-01 11:30:49 +00003813 return getPipeType(T, false);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003814}
3815
John McCalle78aac42010-03-10 03:28:59 +00003816#ifndef NDEBUG
3817static bool NeedsInjectedClassNameType(const RecordDecl *D) {
3818 if (!isa<CXXRecordDecl>(D)) return false;
Eugene Zelenko7855e772018-04-03 00:11:50 +00003819 const auto *RD = cast<CXXRecordDecl>(D);
John McCalle78aac42010-03-10 03:28:59 +00003820 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
3821 return true;
3822 if (RD->getDescribedClassTemplate() &&
3823 !isa<ClassTemplateSpecializationDecl>(RD))
3824 return true;
3825 return false;
3826}
3827#endif
3828
3829/// getInjectedClassNameType - Return the unique reference to the
3830/// injected class name type for the specified templated declaration.
3831QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00003832 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00003833 assert(NeedsInjectedClassNameType(Decl));
3834 if (Decl->TypeForDecl) {
3835 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00003836 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00003837 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
3838 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3839 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
3840 } else {
John McCall424cec92011-01-19 06:33:43 +00003841 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00003842 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00003843 Decl->TypeForDecl = newType;
3844 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00003845 }
3846 return QualType(Decl->TypeForDecl, 0);
3847}
3848
Douglas Gregor83a586e2008-04-13 21:07:44 +00003849/// getTypeDeclType - Return the unique reference to the type for the
3850/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00003851QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00003852 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00003853 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00003854
Eugene Zelenko7855e772018-04-03 00:11:50 +00003855 if (const auto *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00003856 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00003857
John McCall96f0b5f2010-03-10 06:48:02 +00003858 assert(!isa<TemplateTypeParmDecl>(Decl) &&
3859 "Template type parameter types are always available.");
3860
Eugene Zelenko7855e772018-04-03 00:11:50 +00003861 if (const auto *Record = dyn_cast<RecordDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003862 assert(Record->isFirstDecl() && "struct/union has previous declaration");
John McCall96f0b5f2010-03-10 06:48:02 +00003863 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003864 return getRecordType(Record);
Eugene Zelenko7855e772018-04-03 00:11:50 +00003865 } else if (const auto *Enum = dyn_cast<EnumDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003866 assert(Enum->isFirstDecl() && "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003867 return getEnumType(Enum);
Eugene Zelenko7855e772018-04-03 00:11:50 +00003868 } else if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00003869 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
3870 Decl->TypeForDecl = newType;
3871 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00003872 } else
John McCall96f0b5f2010-03-10 06:48:02 +00003873 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003874
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003875 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00003876}
3877
Chris Lattner32d920b2007-01-26 02:01:53 +00003878/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00003879/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003880QualType
Richard Smithdda56e42011-04-15 14:24:37 +00003881ASTContext::getTypedefType(const TypedefNameDecl *Decl,
3882 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003883 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003884
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003885 if (Canonical.isNull())
3886 Canonical = getCanonicalType(Decl->getUnderlyingType());
Eugene Zelenko7855e772018-04-03 00:11:50 +00003887 auto *newType = new (*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00003888 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00003889 Decl->TypeForDecl = newType;
3890 Types.push_back(newType);
3891 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00003892}
3893
Jay Foad39c79802011-01-12 09:06:06 +00003894QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003895 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3896
Douglas Gregorec9fd132012-01-14 16:38:05 +00003897 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003898 if (PrevDecl->TypeForDecl)
Fangrui Song6907ce22018-07-30 19:24:48 +00003899 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003900
Eugene Zelenko7855e772018-04-03 00:11:50 +00003901 auto *newType = new (*this, TypeAlignment) RecordType(Decl);
John McCall424cec92011-01-19 06:33:43 +00003902 Decl->TypeForDecl = newType;
3903 Types.push_back(newType);
3904 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003905}
3906
Jay Foad39c79802011-01-12 09:06:06 +00003907QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003908 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3909
Douglas Gregorec9fd132012-01-14 16:38:05 +00003910 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003911 if (PrevDecl->TypeForDecl)
Fangrui Song6907ce22018-07-30 19:24:48 +00003912 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003913
Eugene Zelenko7855e772018-04-03 00:11:50 +00003914 auto *newType = new (*this, TypeAlignment) EnumType(Decl);
John McCall424cec92011-01-19 06:33:43 +00003915 Decl->TypeForDecl = newType;
3916 Types.push_back(newType);
3917 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003918}
3919
Richard Smithe43e2b32018-08-20 21:47:29 +00003920QualType ASTContext::getAttributedType(attr::Kind attrKind,
John McCall81904512011-01-06 01:58:22 +00003921 QualType modifiedType,
3922 QualType equivalentType) {
3923 llvm::FoldingSetNodeID id;
3924 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
3925
Craig Topper36250ad2014-05-12 05:36:57 +00003926 void *insertPos = nullptr;
John McCall81904512011-01-06 01:58:22 +00003927 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3928 if (type) return QualType(type, 0);
3929
3930 QualType canon = getCanonicalType(equivalentType);
3931 type = new (*this, TypeAlignment)
Leonard Chanef2dc252019-05-03 03:28:06 +00003932 AttributedType(canon, attrKind, modifiedType, equivalentType);
John McCall81904512011-01-06 01:58:22 +00003933
3934 Types.push_back(type);
3935 AttributedTypes.InsertNode(type, insertPos);
3936
3937 return QualType(type, 0);
3938}
3939
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003940/// Retrieve a substitution-result type.
John McCallcebee162009-10-18 09:09:24 +00003941QualType
3942ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00003943 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00003944 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00003945 && "replacement types must always be canonical");
3946
3947 llvm::FoldingSetNodeID ID;
3948 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00003949 void *InsertPos = nullptr;
John McCallcebee162009-10-18 09:09:24 +00003950 SubstTemplateTypeParmType *SubstParm
3951 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3952
3953 if (!SubstParm) {
3954 SubstParm = new (*this, TypeAlignment)
3955 SubstTemplateTypeParmType(Parm, Replacement);
3956 Types.push_back(SubstParm);
3957 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3958 }
3959
3960 return QualType(SubstParm, 0);
3961}
3962
Fangrui Song6907ce22018-07-30 19:24:48 +00003963/// Retrieve a
Douglas Gregorada4b792011-01-14 02:55:32 +00003964QualType ASTContext::getSubstTemplateTypeParmPackType(
3965 const TemplateTypeParmType *Parm,
3966 const TemplateArgument &ArgPack) {
3967#ifndef NDEBUG
Aaron Ballman2a89e852014-07-15 21:32:31 +00003968 for (const auto &P : ArgPack.pack_elements()) {
3969 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3970 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
Douglas Gregorada4b792011-01-14 02:55:32 +00003971 }
3972#endif
Fangrui Song6907ce22018-07-30 19:24:48 +00003973
Douglas Gregorada4b792011-01-14 02:55:32 +00003974 llvm::FoldingSetNodeID ID;
3975 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00003976 void *InsertPos = nullptr;
Douglas Gregorada4b792011-01-14 02:55:32 +00003977 if (SubstTemplateTypeParmPackType *SubstParm
3978 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3979 return QualType(SubstParm, 0);
Fangrui Song6907ce22018-07-30 19:24:48 +00003980
Douglas Gregorada4b792011-01-14 02:55:32 +00003981 QualType Canon;
3982 if (!Parm->isCanonicalUnqualified()) {
3983 Canon = getCanonicalType(QualType(Parm, 0));
3984 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3985 ArgPack);
3986 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3987 }
3988
Eugene Zelenko7855e772018-04-03 00:11:50 +00003989 auto *SubstParm
Douglas Gregorada4b792011-01-14 02:55:32 +00003990 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3991 ArgPack);
3992 Types.push_back(SubstParm);
George Burgess IVb5fe8552017-06-12 17:44:30 +00003993 SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos);
Fangrui Song6907ce22018-07-30 19:24:48 +00003994 return QualType(SubstParm, 0);
Douglas Gregorada4b792011-01-14 02:55:32 +00003995}
3996
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003997/// Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00003998/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00003999/// name.
Mike Stump11289f42009-09-09 15:08:12 +00004000QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00004001 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00004002 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00004003 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00004004 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Craig Topper36250ad2014-05-12 05:36:57 +00004005 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004006 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00004007 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4008
4009 if (TypeParm)
4010 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004011
Chandler Carruth08836322011-05-01 00:51:33 +00004012 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00004013 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00004014 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004015
Fangrui Song6907ce22018-07-30 19:24:48 +00004016 TemplateTypeParmType *TypeCheck
Douglas Gregorc42075a2010-02-04 18:10:26 +00004017 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4018 assert(!TypeCheck && "Template type parameter canonical type broken");
4019 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00004020 } else
John McCall90d1c2d2009-09-24 23:30:46 +00004021 TypeParm = new (*this, TypeAlignment)
4022 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00004023
4024 Types.push_back(TypeParm);
4025 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
4026
4027 return QualType(TypeParm, 0);
4028}
4029
John McCalle78aac42010-03-10 03:28:59 +00004030TypeSourceInfo *
4031ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
4032 SourceLocation NameLoc,
4033 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00004034 QualType Underlying) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00004035 assert(!Name.getAsDependentTemplateName() &&
Douglas Gregore16af532011-02-28 18:50:33 +00004036 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00004037 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00004038
4039 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie6adc78e2013-02-18 22:06:02 +00004040 TemplateSpecializationTypeLoc TL =
4041 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara48c05be2012-02-06 14:41:24 +00004042 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00004043 TL.setTemplateNameLoc(NameLoc);
4044 TL.setLAngleLoc(Args.getLAngleLoc());
4045 TL.setRAngleLoc(Args.getRAngleLoc());
4046 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
4047 TL.setArgLocInfo(i, Args[i].getLocInfo());
4048 return DI;
4049}
4050
Mike Stump11289f42009-09-09 15:08:12 +00004051QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00004052ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00004053 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00004054 QualType Underlying) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00004055 assert(!Template.getAsDependentTemplateName() &&
Douglas Gregore16af532011-02-28 18:50:33 +00004056 "No dependent template names here!");
John McCall6b51f282009-11-23 01:53:49 +00004057
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004058 SmallVector<TemplateArgument, 4> ArgVec;
David Majnemer6fbeee32016-07-07 04:43:07 +00004059 ArgVec.reserve(Args.size());
4060 for (const TemplateArgumentLoc &Arg : Args.arguments())
4061 ArgVec.push_back(Arg.getArgument());
John McCall0ad16662009-10-29 08:12:44 +00004062
David Majnemer6fbeee32016-07-07 04:43:07 +00004063 return getTemplateSpecializationType(Template, ArgVec, Underlying);
John McCall0ad16662009-10-29 08:12:44 +00004064}
4065
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004066#ifndef NDEBUG
David Majnemer6fbeee32016-07-07 04:43:07 +00004067static bool hasAnyPackExpansions(ArrayRef<TemplateArgument> Args) {
4068 for (const TemplateArgument &Arg : Args)
4069 if (Arg.isPackExpansion())
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004070 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00004071
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004072 return true;
4073}
4074#endif
4075
John McCall0ad16662009-10-29 08:12:44 +00004076QualType
4077ASTContext::getTemplateSpecializationType(TemplateName Template,
David Majnemer6fbeee32016-07-07 04:43:07 +00004078 ArrayRef<TemplateArgument> Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00004079 QualType Underlying) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00004080 assert(!Template.getAsDependentTemplateName() &&
Douglas Gregore16af532011-02-28 18:50:33 +00004081 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00004082 // Look through qualified template names.
4083 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
4084 Template = TemplateName(QTN->getTemplateDecl());
Fangrui Song6907ce22018-07-30 19:24:48 +00004085
4086 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00004087 Template.getAsTemplateDecl() &&
4088 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00004089 QualType CanonType;
4090 if (!Underlying.isNull())
4091 CanonType = getCanonicalType(Underlying);
4092 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004093 // We can get here with an alias template when the specialization contains
4094 // a pack expansion that does not match up with a parameter pack.
David Majnemer6fbeee32016-07-07 04:43:07 +00004095 assert((!IsTypeAlias || hasAnyPackExpansions(Args)) &&
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004096 "Caller must compute aliased type");
4097 IsTypeAlias = false;
David Majnemer6fbeee32016-07-07 04:43:07 +00004098 CanonType = getCanonicalTemplateSpecializationType(Template, Args);
Richard Smith3f1b5d02011-05-05 21:57:07 +00004099 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00004100
Douglas Gregora8e02e72009-07-28 23:00:59 +00004101 // Allocate the (non-canonical) template specialization type, but don't
4102 // try to unique it: these types typically have location information that
4103 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00004104 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
David Majnemer6fbeee32016-07-07 04:43:07 +00004105 sizeof(TemplateArgument) * Args.size() +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004106 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00004107 TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004108 auto *Spec
David Majnemer6fbeee32016-07-07 04:43:07 +00004109 = new (Mem) TemplateSpecializationType(Template, Args, CanonType,
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004110 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00004111
Douglas Gregor8bf42052009-02-09 18:46:07 +00004112 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00004113 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00004114}
4115
David Majnemer6fbeee32016-07-07 04:43:07 +00004116QualType ASTContext::getCanonicalTemplateSpecializationType(
4117 TemplateName Template, ArrayRef<TemplateArgument> Args) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00004118 assert(!Template.getAsDependentTemplateName() &&
Douglas Gregore16af532011-02-28 18:50:33 +00004119 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00004120
Douglas Gregore29139c2011-03-03 17:04:51 +00004121 // Look through qualified template names.
4122 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
4123 Template = TemplateName(QTN->getTemplateDecl());
Fangrui Song6907ce22018-07-30 19:24:48 +00004124
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004125 // Build the canonical template specialization type.
4126 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004127 SmallVector<TemplateArgument, 4> CanonArgs;
David Majnemer6fbeee32016-07-07 04:43:07 +00004128 unsigned NumArgs = Args.size();
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004129 CanonArgs.reserve(NumArgs);
David Majnemer6fbeee32016-07-07 04:43:07 +00004130 for (const TemplateArgument &Arg : Args)
4131 CanonArgs.push_back(getCanonicalTemplateArgument(Arg));
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004132
4133 // Determine whether this canonical template specialization type already
4134 // exists.
4135 llvm::FoldingSetNodeID ID;
4136 TemplateSpecializationType::Profile(ID, CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00004137 CanonArgs, *this);
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004138
Craig Topper36250ad2014-05-12 05:36:57 +00004139 void *InsertPos = nullptr;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004140 TemplateSpecializationType *Spec
4141 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
4142
4143 if (!Spec) {
4144 // Allocate a new canonical template specialization type.
4145 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
4146 sizeof(TemplateArgument) * NumArgs),
4147 TypeAlignment);
4148 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00004149 CanonArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00004150 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004151 Types.push_back(Spec);
4152 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
4153 }
4154
4155 assert(Spec->isDependentType() &&
4156 "Non-dependent template-id type must have a canonical type");
4157 return QualType(Spec, 0);
4158}
4159
Joel E. Denny7509a2f2018-05-14 19:36:45 +00004160QualType ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
4161 NestedNameSpecifier *NNS,
4162 QualType NamedType,
4163 TagDecl *OwnedTagDecl) const {
Douglas Gregor52537682009-03-19 00:18:19 +00004164 llvm::FoldingSetNodeID ID;
Joel E. Denny7509a2f2018-05-14 19:36:45 +00004165 ElaboratedType::Profile(ID, Keyword, NNS, NamedType, OwnedTagDecl);
Douglas Gregor52537682009-03-19 00:18:19 +00004166
Craig Topper36250ad2014-05-12 05:36:57 +00004167 void *InsertPos = nullptr;
Abramo Bagnara6150c882010-05-11 21:36:43 +00004168 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00004169 if (T)
4170 return QualType(T, 0);
4171
Douglas Gregorc42075a2010-02-04 18:10:26 +00004172 QualType Canon = NamedType;
4173 if (!Canon.isCanonical()) {
4174 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00004175 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
4176 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00004177 (void)CheckT;
4178 }
4179
Bruno Riccid6bd5982018-08-16 10:48:16 +00004180 void *Mem = Allocate(ElaboratedType::totalSizeToAlloc<TagDecl *>(!!OwnedTagDecl),
4181 TypeAlignment);
4182 T = new (Mem) ElaboratedType(Keyword, NNS, NamedType, Canon, OwnedTagDecl);
4183
Douglas Gregor52537682009-03-19 00:18:19 +00004184 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00004185 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00004186 return QualType(T, 0);
4187}
4188
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004189QualType
Jay Foad39c79802011-01-12 09:06:06 +00004190ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004191 llvm::FoldingSetNodeID ID;
4192 ParenType::Profile(ID, InnerType);
4193
Craig Topper36250ad2014-05-12 05:36:57 +00004194 void *InsertPos = nullptr;
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004195 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
4196 if (T)
4197 return QualType(T, 0);
4198
4199 QualType Canon = InnerType;
4200 if (!Canon.isCanonical()) {
4201 Canon = getCanonicalType(InnerType);
4202 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
4203 assert(!CheckT && "Paren canonical type broken");
4204 (void)CheckT;
4205 }
4206
Benjamin Kramer8adeef92015-04-02 16:19:54 +00004207 T = new (*this, TypeAlignment) ParenType(InnerType, Canon);
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004208 Types.push_back(T);
4209 ParenTypes.InsertNode(T, InsertPos);
4210 return QualType(T, 0);
4211}
4212
Douglas Gregor02085352010-03-31 20:19:30 +00004213QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
4214 NestedNameSpecifier *NNS,
4215 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00004216 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00004217 if (Canon.isNull()) {
4218 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Richard Smith74f02342017-01-19 21:00:13 +00004219 if (CanonNNS != NNS)
4220 Canon = getDependentNameType(Keyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00004221 }
4222
4223 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00004224 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00004225
Craig Topper36250ad2014-05-12 05:36:57 +00004226 void *InsertPos = nullptr;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00004227 DependentNameType *T
4228 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00004229 if (T)
4230 return QualType(T, 0);
4231
Benjamin Kramer8adeef92015-04-02 16:19:54 +00004232 T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00004233 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00004234 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00004235 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00004236}
4237
Mike Stump11289f42009-09-09 15:08:12 +00004238QualType
John McCallc392f372010-06-11 00:33:02 +00004239ASTContext::getDependentTemplateSpecializationType(
4240 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00004241 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00004242 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00004243 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00004244 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004245 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00004246 for (unsigned I = 0, E = Args.size(); I != E; ++I)
4247 ArgCopy.push_back(Args[I].getArgument());
David Majnemer6fbeee32016-07-07 04:43:07 +00004248 return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy);
John McCallc392f372010-06-11 00:33:02 +00004249}
4250
4251QualType
4252ASTContext::getDependentTemplateSpecializationType(
4253 ElaboratedTypeKeyword Keyword,
4254 NestedNameSpecifier *NNS,
4255 const IdentifierInfo *Name,
David Majnemer6fbeee32016-07-07 04:43:07 +00004256 ArrayRef<TemplateArgument> Args) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00004257 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor6e068012011-02-28 00:04:36 +00004258 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00004259
Douglas Gregorc42075a2010-02-04 18:10:26 +00004260 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00004261 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00004262 Name, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004263
Craig Topper36250ad2014-05-12 05:36:57 +00004264 void *InsertPos = nullptr;
John McCallc392f372010-06-11 00:33:02 +00004265 DependentTemplateSpecializationType *T
4266 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004267 if (T)
4268 return QualType(T, 0);
4269
John McCallc392f372010-06-11 00:33:02 +00004270 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004271
John McCallc392f372010-06-11 00:33:02 +00004272 ElaboratedTypeKeyword CanonKeyword = Keyword;
4273 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
4274
4275 bool AnyNonCanonArgs = false;
David Majnemer6fbeee32016-07-07 04:43:07 +00004276 unsigned NumArgs = Args.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004277 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00004278 for (unsigned I = 0; I != NumArgs; ++I) {
4279 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
4280 if (!CanonArgs[I].structurallyEquals(Args[I]))
4281 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00004282 }
4283
John McCallc392f372010-06-11 00:33:02 +00004284 QualType Canon;
4285 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
4286 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00004287 Name,
4288 CanonArgs);
John McCallc392f372010-06-11 00:33:02 +00004289
4290 // Find the insert position again.
4291 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
4292 }
4293
4294 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
4295 sizeof(TemplateArgument) * NumArgs),
4296 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00004297 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00004298 Name, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00004299 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00004300 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00004301 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00004302}
4303
Richard Smith32918772017-02-14 00:25:28 +00004304TemplateArgument ASTContext::getInjectedTemplateArg(NamedDecl *Param) {
4305 TemplateArgument Arg;
Eugene Zelenko7855e772018-04-03 00:11:50 +00004306 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
Richard Smith32918772017-02-14 00:25:28 +00004307 QualType ArgType = getTypeDeclType(TTP);
4308 if (TTP->isParameterPack())
4309 ArgType = getPackExpansionType(ArgType, None);
4310
4311 Arg = TemplateArgument(ArgType);
4312 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4313 Expr *E = new (*this) DeclRefExpr(
Bruno Ricci5fc4db72018-12-21 14:10:18 +00004314 *this, NTTP, /*enclosing*/ false,
Richard Smith32918772017-02-14 00:25:28 +00004315 NTTP->getType().getNonLValueExprType(*this),
4316 Expr::getValueKindForType(NTTP->getType()), NTTP->getLocation());
4317
4318 if (NTTP->isParameterPack())
4319 E = new (*this) PackExpansionExpr(DependentTy, E, NTTP->getLocation(),
4320 None);
4321 Arg = TemplateArgument(E);
4322 } else {
4323 auto *TTP = cast<TemplateTemplateParmDecl>(Param);
4324 if (TTP->isParameterPack())
4325 Arg = TemplateArgument(TemplateName(TTP), Optional<unsigned>());
4326 else
4327 Arg = TemplateArgument(TemplateName(TTP));
4328 }
4329
4330 if (Param->isTemplateParameterPack())
4331 Arg = TemplateArgument::CreatePackCopy(*this, Arg);
4332
4333 return Arg;
4334}
4335
Richard Smith43e14d22016-12-23 02:10:11 +00004336void
4337ASTContext::getInjectedTemplateArgs(const TemplateParameterList *Params,
4338 SmallVectorImpl<TemplateArgument> &Args) {
4339 Args.reserve(Args.size() + Params->size());
4340
Richard Smith32918772017-02-14 00:25:28 +00004341 for (NamedDecl *Param : *Params)
4342 Args.push_back(getInjectedTemplateArg(Param));
Richard Smith43e14d22016-12-23 02:10:11 +00004343}
4344
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00004345QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikie05785d12013-02-20 22:23:23 +00004346 Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00004347 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00004348 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00004349
4350 assert(Pattern->containsUnexpandedParameterPack() &&
4351 "Pack expansions must expand one or more parameter packs");
Craig Topper36250ad2014-05-12 05:36:57 +00004352 void *InsertPos = nullptr;
Douglas Gregord2fa7662010-12-20 02:24:11 +00004353 PackExpansionType *T
4354 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
4355 if (T)
4356 return QualType(T, 0);
4357
4358 QualType Canon;
4359 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00004360 Canon = getCanonicalType(Pattern);
4361 // The canonical type might not contain an unexpanded parameter pack, if it
4362 // contains an alias template specialization which ignores one of its
4363 // parameters.
4364 if (Canon->containsUnexpandedParameterPack()) {
Richard Smith8b4e1e22014-07-10 01:20:17 +00004365 Canon = getPackExpansionType(Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00004366
Richard Smith68eea502012-07-16 00:20:35 +00004367 // Find the insert position again, in case we inserted an element into
4368 // PackExpansionTypes and invalidated our insert position.
4369 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
4370 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00004371 }
4372
Benjamin Kramer8adeef92015-04-02 16:19:54 +00004373 T = new (*this, TypeAlignment)
4374 PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00004375 Types.push_back(T);
4376 PackExpansionTypes.InsertNode(T, InsertPos);
Richard Smith8b4e1e22014-07-10 01:20:17 +00004377 return QualType(T, 0);
Douglas Gregord2fa7662010-12-20 02:24:11 +00004378}
4379
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004380/// CmpProtocolNames - Comparison predicate for sorting protocols
4381/// alphabetically.
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00004382static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
4383 ObjCProtocolDecl *const *RHS) {
4384 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004385}
4386
Craig Topper1f26d5b2016-01-03 19:43:23 +00004387static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) {
4388 if (Protocols.empty()) return true;
John McCallfc93cf92009-10-22 22:37:11 +00004389
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00004390 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
4391 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00004392
Craig Topper1f26d5b2016-01-03 19:43:23 +00004393 for (unsigned i = 1; i != Protocols.size(); ++i)
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00004394 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00004395 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00004396 return false;
4397 return true;
4398}
4399
Craig Topper6a8c1512015-10-22 01:56:18 +00004400static void
4401SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) {
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004402 // Sort protocols, keyed by name.
Craig Topper6a8c1512015-10-22 01:56:18 +00004403 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004404
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00004405 // Canonicalize.
Craig Topper6a8c1512015-10-22 01:56:18 +00004406 for (ObjCProtocolDecl *&P : Protocols)
4407 P = P->getCanonicalDecl();
4408
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004409 // Remove duplicates.
Craig Topper6a8c1512015-10-22 01:56:18 +00004410 auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end());
4411 Protocols.erase(ProtocolsEnd, Protocols.end());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004412}
4413
John McCall8b07ec22010-05-15 11:32:37 +00004414QualType ASTContext::getObjCObjectType(QualType BaseType,
4415 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00004416 unsigned NumProtocols) const {
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004417 return getObjCObjectType(BaseType, {},
Douglas Gregorab209d82015-07-07 03:58:42 +00004418 llvm::makeArrayRef(Protocols, NumProtocols),
4419 /*isKindOf=*/false);
Douglas Gregore9d95f12015-07-07 03:57:35 +00004420}
4421
4422QualType ASTContext::getObjCObjectType(
4423 QualType baseType,
4424 ArrayRef<QualType> typeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00004425 ArrayRef<ObjCProtocolDecl *> protocols,
4426 bool isKindOf) const {
Douglas Gregore9d95f12015-07-07 03:57:35 +00004427 // If the base type is an interface and there aren't any protocols or
4428 // type arguments to add, then the interface type will do just fine.
Douglas Gregorab209d82015-07-07 03:58:42 +00004429 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
4430 isa<ObjCInterfaceType>(baseType))
Douglas Gregore9d95f12015-07-07 03:57:35 +00004431 return baseType;
John McCall8b07ec22010-05-15 11:32:37 +00004432
4433 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00004434 llvm::FoldingSetNodeID ID;
Douglas Gregorab209d82015-07-07 03:58:42 +00004435 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
Craig Topper36250ad2014-05-12 05:36:57 +00004436 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00004437 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
4438 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00004439
Douglas Gregore9d95f12015-07-07 03:57:35 +00004440 // Determine the type arguments to be used for canonicalization,
4441 // which may be explicitly specified here or written on the base
4442 // type.
4443 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
4444 if (effectiveTypeArgs.empty()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00004445 if (const auto *baseObject = baseType->getAs<ObjCObjectType>())
Douglas Gregore9d95f12015-07-07 03:57:35 +00004446 effectiveTypeArgs = baseObject->getTypeArgs();
4447 }
John McCallfc93cf92009-10-22 22:37:11 +00004448
Douglas Gregore9d95f12015-07-07 03:57:35 +00004449 // Build the canonical type, which has the canonical base type and a
4450 // sorted-and-uniqued list of protocols and the type arguments
4451 // canonicalized.
4452 QualType canonical;
4453 bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(),
4454 effectiveTypeArgs.end(),
4455 [&](QualType type) {
4456 return type.isCanonical();
4457 });
Craig Topper1f26d5b2016-01-03 19:43:23 +00004458 bool protocolsSorted = areSortedAndUniqued(protocols);
Douglas Gregore9d95f12015-07-07 03:57:35 +00004459 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
4460 // Determine the canonical type arguments.
4461 ArrayRef<QualType> canonTypeArgs;
4462 SmallVector<QualType, 4> canonTypeArgsVec;
4463 if (!typeArgsAreCanonical) {
4464 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
4465 for (auto typeArg : effectiveTypeArgs)
4466 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
4467 canonTypeArgs = canonTypeArgsVec;
John McCallfc93cf92009-10-22 22:37:11 +00004468 } else {
Douglas Gregore9d95f12015-07-07 03:57:35 +00004469 canonTypeArgs = effectiveTypeArgs;
John McCallfc93cf92009-10-22 22:37:11 +00004470 }
4471
Douglas Gregore9d95f12015-07-07 03:57:35 +00004472 ArrayRef<ObjCProtocolDecl *> canonProtocols;
4473 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
4474 if (!protocolsSorted) {
Craig Topper6a8c1512015-10-22 01:56:18 +00004475 canonProtocolsVec.append(protocols.begin(), protocols.end());
4476 SortAndUniqueProtocols(canonProtocolsVec);
4477 canonProtocols = canonProtocolsVec;
Douglas Gregore9d95f12015-07-07 03:57:35 +00004478 } else {
4479 canonProtocols = protocols;
4480 }
4481
4482 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00004483 canonProtocols, isKindOf);
Douglas Gregore9d95f12015-07-07 03:57:35 +00004484
John McCallfc93cf92009-10-22 22:37:11 +00004485 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00004486 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
4487 }
4488
Douglas Gregore9d95f12015-07-07 03:57:35 +00004489 unsigned size = sizeof(ObjCObjectTypeImpl);
4490 size += typeArgs.size() * sizeof(QualType);
4491 size += protocols.size() * sizeof(ObjCProtocolDecl *);
4492 void *mem = Allocate(size, TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004493 auto *T =
Douglas Gregorab209d82015-07-07 03:58:42 +00004494 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
4495 isKindOf);
John McCall8b07ec22010-05-15 11:32:37 +00004496
4497 Types.push_back(T);
4498 ObjCObjectTypes.InsertNode(T, InsertPos);
4499 return QualType(T, 0);
4500}
4501
Manman Ren3569eb52016-09-13 17:03:12 +00004502/// Apply Objective-C protocol qualifiers to the given type.
4503/// If this is for the canonical type of a type parameter, we can apply
4504/// protocol qualifiers on the ObjCObjectPointerType.
4505QualType
4506ASTContext::applyObjCProtocolQualifiers(QualType type,
4507 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
4508 bool allowOnPointerType) const {
4509 hasError = false;
4510
Eugene Zelenko7855e772018-04-03 00:11:50 +00004511 if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
Manman Renc5705ba2016-09-13 17:41:05 +00004512 return getObjCTypeParamType(objT->getDecl(), protocols);
4513 }
4514
Manman Ren3569eb52016-09-13 17:03:12 +00004515 // Apply protocol qualifiers to ObjCObjectPointerType.
4516 if (allowOnPointerType) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00004517 if (const auto *objPtr =
4518 dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
Manman Ren3569eb52016-09-13 17:03:12 +00004519 const ObjCObjectType *objT = objPtr->getObjectType();
4520 // Merge protocol lists and construct ObjCObjectType.
4521 SmallVector<ObjCProtocolDecl*, 8> protocolsVec;
4522 protocolsVec.append(objT->qual_begin(),
4523 objT->qual_end());
4524 protocolsVec.append(protocols.begin(), protocols.end());
4525 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
4526 type = getObjCObjectType(
4527 objT->getBaseType(),
4528 objT->getTypeArgsAsWritten(),
4529 protocols,
4530 objT->isKindOfTypeAsWritten());
4531 return getObjCObjectPointerType(type);
4532 }
4533 }
4534
4535 // Apply protocol qualifiers to ObjCObjectType.
Eugene Zelenko7855e772018-04-03 00:11:50 +00004536 if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
Manman Ren3569eb52016-09-13 17:03:12 +00004537 // FIXME: Check for protocols to which the class type is already
4538 // known to conform.
4539
4540 return getObjCObjectType(objT->getBaseType(),
4541 objT->getTypeArgsAsWritten(),
4542 protocols,
4543 objT->isKindOfTypeAsWritten());
4544 }
4545
4546 // If the canonical type is ObjCObjectType, ...
4547 if (type->isObjCObjectType()) {
4548 // Silently overwrite any existing protocol qualifiers.
4549 // TODO: determine whether that's the right thing to do.
4550
4551 // FIXME: Check for protocols to which the class type is already
4552 // known to conform.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004553 return getObjCObjectType(type, {}, protocols, false);
Manman Ren3569eb52016-09-13 17:03:12 +00004554 }
4555
4556 // id<protocol-list>
4557 if (type->isObjCIdType()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00004558 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004559 type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols,
Manman Ren3569eb52016-09-13 17:03:12 +00004560 objPtr->isKindOfType());
4561 return getObjCObjectPointerType(type);
4562 }
4563
4564 // Class<protocol-list>
4565 if (type->isObjCClassType()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00004566 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004567 type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols,
Manman Ren3569eb52016-09-13 17:03:12 +00004568 objPtr->isKindOfType());
4569 return getObjCObjectPointerType(type);
4570 }
4571
4572 hasError = true;
4573 return type;
4574}
4575
Manman Rene6be26c2016-09-13 17:25:08 +00004576QualType
4577ASTContext::getObjCTypeParamType(const ObjCTypeParamDecl *Decl,
4578 ArrayRef<ObjCProtocolDecl *> protocols,
4579 QualType Canonical) const {
4580 // Look in the folding set for an existing type.
4581 llvm::FoldingSetNodeID ID;
4582 ObjCTypeParamType::Profile(ID, Decl, protocols);
4583 void *InsertPos = nullptr;
4584 if (ObjCTypeParamType *TypeParam =
4585 ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
4586 return QualType(TypeParam, 0);
4587
4588 if (Canonical.isNull()) {
4589 // We canonicalize to the underlying type.
4590 Canonical = getCanonicalType(Decl->getUnderlyingType());
4591 if (!protocols.empty()) {
4592 // Apply the protocol qualifers.
4593 bool hasError;
Richard Trieua986a312018-08-30 01:57:52 +00004594 Canonical = getCanonicalType(applyObjCProtocolQualifiers(
4595 Canonical, protocols, hasError, true /*allowOnPointerType*/));
Manman Rene6be26c2016-09-13 17:25:08 +00004596 assert(!hasError && "Error when apply protocol qualifier to bound type");
4597 }
4598 }
4599
4600 unsigned size = sizeof(ObjCTypeParamType);
4601 size += protocols.size() * sizeof(ObjCProtocolDecl *);
4602 void *mem = Allocate(size, TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004603 auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols);
Manman Rene6be26c2016-09-13 17:25:08 +00004604
4605 Types.push_back(newType);
4606 ObjCTypeParamTypes.InsertNode(newType, InsertPos);
4607 return QualType(newType, 0);
4608}
4609
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004610/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
4611/// protocol list adopt all protocols in QT's qualified-id protocol
4612/// list.
4613bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
4614 ObjCInterfaceDecl *IC) {
4615 if (!QT->isObjCQualifiedIdType())
4616 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00004617
Eugene Zelenko7855e772018-04-03 00:11:50 +00004618 if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004619 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00004620 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004621 if (!IC->ClassImplementsProtocol(Proto, false))
4622 return false;
4623 }
4624 return true;
4625 }
4626 return false;
4627}
4628
4629/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
4630/// QT's qualified-id protocol list adopt all protocols in IDecl's list
4631/// of protocols.
4632bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
4633 ObjCInterfaceDecl *IDecl) {
4634 if (!QT->isObjCQualifiedIdType())
4635 return false;
Eugene Zelenko7855e772018-04-03 00:11:50 +00004636 const auto *OPT = QT->getAs<ObjCObjectPointerType>();
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004637 if (!OPT)
4638 return false;
4639 if (!IDecl->hasDefinition())
4640 return false;
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00004641 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
4642 CollectInheritedProtocols(IDecl, InheritedProtocols);
4643 if (InheritedProtocols.empty())
4644 return false;
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00004645 // Check that if every protocol in list of id<plist> conforms to a protocol
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00004646 // of IDecl's, then bridge casting is ok.
4647 bool Conforms = false;
4648 for (auto *Proto : OPT->quals()) {
4649 Conforms = false;
4650 for (auto *PI : InheritedProtocols) {
4651 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
4652 Conforms = true;
4653 break;
4654 }
4655 }
4656 if (!Conforms)
4657 break;
4658 }
4659 if (Conforms)
4660 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00004661
Aaron Ballman83731462014-03-17 16:14:00 +00004662 for (auto *PI : InheritedProtocols) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004663 // If both the right and left sides have qualifiers.
4664 bool Adopts = false;
Aaron Ballman83731462014-03-17 16:14:00 +00004665 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00004666 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
Aaron Ballman83731462014-03-17 16:14:00 +00004667 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004668 break;
4669 }
4670 if (!Adopts)
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00004671 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004672 }
4673 return true;
4674}
4675
John McCall8b07ec22010-05-15 11:32:37 +00004676/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
4677/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00004678QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00004679 llvm::FoldingSetNodeID ID;
4680 ObjCObjectPointerType::Profile(ID, ObjectT);
4681
Craig Topper36250ad2014-05-12 05:36:57 +00004682 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00004683 if (ObjCObjectPointerType *QT =
4684 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
4685 return QualType(QT, 0);
4686
4687 // Find the canonical object type.
4688 QualType Canonical;
4689 if (!ObjectT.isCanonical()) {
4690 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
4691
4692 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00004693 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
4694 }
4695
Douglas Gregorf85bee62010-02-08 22:59:26 +00004696 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00004697 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004698 auto *QType =
John McCall8b07ec22010-05-15 11:32:37 +00004699 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00004700
Steve Narofffb4330f2009-06-17 22:40:22 +00004701 Types.push_back(QType);
4702 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00004703 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00004704}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004705
Douglas Gregor1c283312010-08-11 12:19:30 +00004706/// getObjCInterfaceType - Return the unique reference to the type for the
4707/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00004708QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
4709 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00004710 if (Decl->TypeForDecl)
4711 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004712
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00004713 if (PrevDecl) {
4714 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
4715 Decl->TypeForDecl = PrevDecl->TypeForDecl;
4716 return QualType(PrevDecl->TypeForDecl, 0);
4717 }
4718
Douglas Gregor7671e532011-12-16 16:34:57 +00004719 // Prefer the definition, if there is one.
4720 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
4721 Decl = Def;
Fangrui Song6907ce22018-07-30 19:24:48 +00004722
Douglas Gregor1c283312010-08-11 12:19:30 +00004723 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004724 auto *T = new (Mem) ObjCInterfaceType(Decl);
Douglas Gregor1c283312010-08-11 12:19:30 +00004725 Decl->TypeForDecl = T;
4726 Types.push_back(T);
4727 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00004728}
4729
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004730/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
4731/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00004732/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00004733/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00004734/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00004735QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00004736 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004737 if (tofExpr->isTypeDependent()) {
4738 llvm::FoldingSetNodeID ID;
4739 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00004740
Craig Topper36250ad2014-05-12 05:36:57 +00004741 void *InsertPos = nullptr;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004742 DependentTypeOfExprType *Canon
4743 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
4744 if (Canon) {
4745 // We already have a "canonical" version of an identical, dependent
4746 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00004747 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004748 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00004749 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004750 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00004751 Canon
4752 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004753 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
4754 toe = Canon;
4755 }
4756 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00004757 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00004758 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00004759 }
Steve Naroffa773cd52007-08-01 18:02:17 +00004760 Types.push_back(toe);
4761 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00004762}
4763
Steve Naroffa773cd52007-08-01 18:02:17 +00004764/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
Richard Smith8eb1d322014-06-05 20:13:13 +00004765/// TypeOfType nodes. The only motivation to unique these nodes would be
Steve Naroffa773cd52007-08-01 18:02:17 +00004766/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Richard Smith8eb1d322014-06-05 20:13:13 +00004767/// an issue. This doesn't affect the type checker, since it operates
4768/// on canonical types (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00004769QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00004770 QualType Canonical = getCanonicalType(tofType);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004771 auto *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00004772 Types.push_back(tot);
4773 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00004774}
4775
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004776/// Unlike many "get<Type>" functions, we don't unique DecltypeType
Richard Smith8eb1d322014-06-05 20:13:13 +00004777/// nodes. This would never be helpful, since each such type has its own
4778/// expression, and would not give a significant memory saving, since there
4779/// is an Expr tree under each such type.
Douglas Gregor81495f32012-02-12 18:42:33 +00004780QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00004781 DecltypeType *dt;
Richard Smith8eb1d322014-06-05 20:13:13 +00004782
4783 // C++11 [temp.type]p2:
Douglas Gregor678d76c2011-07-01 01:22:09 +00004784 // If an expression e involves a template parameter, decltype(e) denotes a
Richard Smith8eb1d322014-06-05 20:13:13 +00004785 // unique dependent type. Two such decltype-specifiers refer to the same
4786 // type only if their expressions are equivalent (14.5.6.1).
Douglas Gregor678d76c2011-07-01 01:22:09 +00004787 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00004788 llvm::FoldingSetNodeID ID;
4789 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00004790
Craig Topper36250ad2014-05-12 05:36:57 +00004791 void *InsertPos = nullptr;
Douglas Gregora21f6c32009-07-30 23:36:40 +00004792 DependentDecltypeType *Canon
4793 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
Richard Smith8eb1d322014-06-05 20:13:13 +00004794 if (!Canon) {
Yaron Keren633e14a2016-11-29 10:08:20 +00004795 // Build a new, canonical decltype(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00004796 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00004797 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
Douglas Gregora21f6c32009-07-30 23:36:40 +00004798 }
Richard Smith8eb1d322014-06-05 20:13:13 +00004799 dt = new (*this, TypeAlignment)
4800 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
Douglas Gregora21f6c32009-07-30 23:36:40 +00004801 } else {
Richard Smith8eb1d322014-06-05 20:13:13 +00004802 dt = new (*this, TypeAlignment)
4803 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00004804 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00004805 Types.push_back(dt);
4806 return QualType(dt, 0);
4807}
4808
Alexis Hunte852b102011-05-24 22:41:36 +00004809/// getUnaryTransformationType - We don't unique these, since the memory
4810/// savings are minimal and these are rare.
4811QualType ASTContext::getUnaryTransformType(QualType BaseType,
4812 QualType UnderlyingType,
4813 UnaryTransformType::UTTKind Kind)
4814 const {
Vassil Vassilevbab6f962016-03-30 22:18:29 +00004815 UnaryTransformType *ut = nullptr;
4816
4817 if (BaseType->isDependentType()) {
4818 // Look in the folding set for an existing type.
4819 llvm::FoldingSetNodeID ID;
4820 DependentUnaryTransformType::Profile(ID, getCanonicalType(BaseType), Kind);
4821
4822 void *InsertPos = nullptr;
4823 DependentUnaryTransformType *Canon
4824 = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
4825
4826 if (!Canon) {
4827 // Build a new, canonical __underlying_type(type) type.
4828 Canon = new (*this, TypeAlignment)
4829 DependentUnaryTransformType(*this, getCanonicalType(BaseType),
4830 Kind);
4831 DependentUnaryTransformTypes.InsertNode(Canon, InsertPos);
4832 }
4833 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4834 QualType(), Kind,
4835 QualType(Canon, 0));
4836 } else {
4837 QualType CanonType = getCanonicalType(UnderlyingType);
4838 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4839 UnderlyingType, Kind,
4840 CanonType);
4841 }
4842 Types.push_back(ut);
4843 return QualType(ut, 0);
Alexis Hunte852b102011-05-24 22:41:36 +00004844}
4845
Richard Smith2a7d4812013-05-04 07:00:32 +00004846/// getAutoType - Return the uniqued reference to the 'auto' type which has been
4847/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
4848/// canonical deduced-but-dependent 'auto' type.
Richard Smithe301ba22015-11-11 02:02:15 +00004849QualType ASTContext::getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004850 bool IsDependent) const {
Richard Smithe301ba22015-11-11 02:02:15 +00004851 if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto && !IsDependent)
Richard Smith2a7d4812013-05-04 07:00:32 +00004852 return getAutoDeductType();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004853
Richard Smith2a7d4812013-05-04 07:00:32 +00004854 // Look in the folding set for an existing type.
Craig Topper36250ad2014-05-12 05:36:57 +00004855 void *InsertPos = nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +00004856 llvm::FoldingSetNodeID ID;
Richard Smithe301ba22015-11-11 02:02:15 +00004857 AutoType::Profile(ID, DeducedType, Keyword, IsDependent);
Richard Smith2a7d4812013-05-04 07:00:32 +00004858 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
4859 return QualType(AT, 0);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004860
Eugene Zelenko7855e772018-04-03 00:11:50 +00004861 auto *AT = new (*this, TypeAlignment)
4862 AutoType(DeducedType, Keyword, IsDependent);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004863 Types.push_back(AT);
4864 if (InsertPos)
4865 AutoTypes.InsertNode(AT, InsertPos);
4866 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00004867}
4868
Richard Smith600b5262017-01-26 20:40:47 +00004869/// Return the uniqued reference to the deduced template specialization type
4870/// which has been deduced to the given type, or to the canonical undeduced
4871/// such type, or the canonical deduced-but-dependent such type.
4872QualType ASTContext::getDeducedTemplateSpecializationType(
4873 TemplateName Template, QualType DeducedType, bool IsDependent) const {
4874 // Look in the folding set for an existing type.
4875 void *InsertPos = nullptr;
4876 llvm::FoldingSetNodeID ID;
4877 DeducedTemplateSpecializationType::Profile(ID, Template, DeducedType,
4878 IsDependent);
4879 if (DeducedTemplateSpecializationType *DTST =
4880 DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
4881 return QualType(DTST, 0);
4882
Eugene Zelenko7855e772018-04-03 00:11:50 +00004883 auto *DTST = new (*this, TypeAlignment)
Richard Smith600b5262017-01-26 20:40:47 +00004884 DeducedTemplateSpecializationType(Template, DeducedType, IsDependent);
4885 Types.push_back(DTST);
4886 if (InsertPos)
4887 DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos);
4888 return QualType(DTST, 0);
4889}
4890
Eli Friedman0dfb8892011-10-06 23:00:33 +00004891/// getAtomicType - Return the uniqued reference to the atomic type for
4892/// the given value type.
4893QualType ASTContext::getAtomicType(QualType T) const {
4894 // Unique pointers, to guarantee there is only one pointer of a particular
4895 // structure.
4896 llvm::FoldingSetNodeID ID;
4897 AtomicType::Profile(ID, T);
4898
Craig Topper36250ad2014-05-12 05:36:57 +00004899 void *InsertPos = nullptr;
Eli Friedman0dfb8892011-10-06 23:00:33 +00004900 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
4901 return QualType(AT, 0);
4902
4903 // If the atomic value type isn't canonical, this won't be a canonical type
4904 // either, so fill in the canonical type field.
4905 QualType Canonical;
4906 if (!T.isCanonical()) {
4907 Canonical = getAtomicType(getCanonicalType(T));
4908
4909 // Get the new insert position for the node we care about.
4910 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00004911 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Eli Friedman0dfb8892011-10-06 23:00:33 +00004912 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00004913 auto *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
Eli Friedman0dfb8892011-10-06 23:00:33 +00004914 Types.push_back(New);
4915 AtomicTypes.InsertNode(New, InsertPos);
4916 return QualType(New, 0);
4917}
4918
Richard Smith02e85f32011-04-14 22:09:26 +00004919/// getAutoDeductType - Get type pattern for deducing against 'auto'.
4920QualType ASTContext::getAutoDeductType() const {
4921 if (AutoDeductTy.isNull())
Richard Smith2a7d4812013-05-04 07:00:32 +00004922 AutoDeductTy = QualType(
Richard Smithe301ba22015-11-11 02:02:15 +00004923 new (*this, TypeAlignment) AutoType(QualType(), AutoTypeKeyword::Auto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004924 /*dependent*/false),
Richard Smith2a7d4812013-05-04 07:00:32 +00004925 0);
Richard Smith02e85f32011-04-14 22:09:26 +00004926 return AutoDeductTy;
4927}
4928
4929/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
4930QualType ASTContext::getAutoRRefDeductType() const {
4931 if (AutoRRefDeductTy.isNull())
4932 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
4933 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
4934 return AutoRRefDeductTy;
4935}
4936
Chris Lattnerfb072462007-01-23 05:45:31 +00004937/// getTagDeclType - Return the unique reference to the type for the
4938/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00004939QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004940 assert(Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00004941 // FIXME: What is the design on getTagDeclType when it requires casting
4942 // away const? mutable?
4943 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00004944}
4945
Mike Stump11289f42009-09-09 15:08:12 +00004946/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
4947/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
4948/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00004949CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00004950 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00004951}
Chris Lattnerfb072462007-01-23 05:45:31 +00004952
Fangrui Song6907ce22018-07-30 19:24:48 +00004953/// Return the unique signed counterpart of the integer type
Alexander Shaposhnikov1e898d92017-07-14 17:30:14 +00004954/// corresponding to size_t.
4955CanQualType ASTContext::getSignedSizeType() const {
4956 return getFromTargetType(Target->getSignedSizeType());
4957}
4958
Hans Wennborg27541db2011-10-27 08:29:09 +00004959/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
4960CanQualType ASTContext::getIntMaxType() const {
4961 return getFromTargetType(Target->getIntMaxType());
4962}
4963
4964/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
4965CanQualType ASTContext::getUIntMaxType() const {
4966 return getFromTargetType(Target->getUIntMaxType());
4967}
4968
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00004969/// getSignedWCharType - Return the type of "signed wchar_t".
4970/// Used when in C++, as a GCC extension.
4971QualType ASTContext::getSignedWCharType() const {
4972 // FIXME: derive from "Target" ?
4973 return WCharTy;
4974}
4975
4976/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
4977/// Used when in C++, as a GCC extension.
4978QualType ASTContext::getUnsignedWCharType() const {
4979 // FIXME: derive from "Target" ?
4980 return UnsignedIntTy;
4981}
4982
Enea Zaffanellaf11ceb62013-01-26 17:08:37 +00004983QualType ASTContext::getIntPtrType() const {
4984 return getFromTargetType(Target->getIntPtrType());
4985}
4986
4987QualType ASTContext::getUIntPtrType() const {
4988 return getCorrespondingUnsignedType(getIntPtrType());
4989}
4990
Hans Wennborg27541db2011-10-27 08:29:09 +00004991/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00004992/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
4993QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00004994 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00004995}
4996
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004997/// Return the unique unsigned counterpart of "ptrdiff_t"
Alexander Shaposhnikov195b25c2017-09-28 23:11:31 +00004998/// integer type. The standard (C11 7.21.6.1p7) refers to this type
4999/// in the definition of %tu format specifier.
5000QualType ASTContext::getUnsignedPointerDiffType() const {
5001 return getFromTargetType(Target->getUnsignedPtrDiffType(0));
5002}
5003
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005004/// Return the unique type for "pid_t" defined in
Eli Friedman4e91899e2012-11-27 02:58:24 +00005005/// <sys/types.h>. We need this to compute the correct type for vfork().
5006QualType ASTContext::getProcessIDType() const {
5007 return getFromTargetType(Target->getProcessIDType());
5008}
5009
Chris Lattnera21ad802008-04-02 05:18:44 +00005010//===----------------------------------------------------------------------===//
5011// Type Operators
5012//===----------------------------------------------------------------------===//
5013
Jay Foad39c79802011-01-12 09:06:06 +00005014CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00005015 // Push qualifiers into arrays, and then discard any remaining
5016 // qualifiers.
5017 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00005018 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00005019 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00005020 QualType Result;
5021 if (isa<ArrayType>(Ty)) {
5022 Result = getArrayDecayedType(QualType(Ty,0));
5023 } else if (isa<FunctionType>(Ty)) {
5024 Result = getPointerType(QualType(Ty, 0));
5025 } else {
5026 Result = QualType(Ty, 0);
5027 }
5028
5029 return CanQualType::CreateUnsafe(Result);
5030}
5031
John McCall6c9dd522011-01-18 07:41:22 +00005032QualType ASTContext::getUnqualifiedArrayType(QualType type,
5033 Qualifiers &quals) {
5034 SplitQualType splitType = type.getSplitUnqualifiedType();
5035
5036 // FIXME: getSplitUnqualifiedType() actually walks all the way to
5037 // the unqualified desugared type and then drops it on the floor.
5038 // We then have to strip that sugar back off with
5039 // getUnqualifiedDesugaredType(), which is silly.
Eugene Zelenko7855e772018-04-03 00:11:50 +00005040 const auto *AT =
5041 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00005042
5043 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00005044 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00005045 quals = splitType.Quals;
5046 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00005047 }
5048
John McCall6c9dd522011-01-18 07:41:22 +00005049 // Otherwise, recurse on the array's element type.
5050 QualType elementType = AT->getElementType();
5051 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
5052
5053 // If that didn't change the element type, AT has no qualifiers, so we
5054 // can just use the results in splitType.
5055 if (elementType == unqualElementType) {
5056 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00005057 quals = splitType.Quals;
5058 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00005059 }
5060
5061 // Otherwise, add in the qualifiers from the outermost type, then
5062 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00005063 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00005064
Eugene Zelenko7855e772018-04-03 00:11:50 +00005065 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00005066 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00005067 CAT->getSizeModifier(), 0);
5068 }
5069
Eugene Zelenko7855e772018-04-03 00:11:50 +00005070 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00005071 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00005072 }
5073
Eugene Zelenko7855e772018-04-03 00:11:50 +00005074 if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00005075 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00005076 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00005077 VAT->getSizeModifier(),
5078 VAT->getIndexTypeCVRQualifiers(),
5079 VAT->getBracketsRange());
5080 }
5081
Eugene Zelenko7855e772018-04-03 00:11:50 +00005082 const auto *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00005083 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00005084 DSAT->getSizeModifier(), 0,
5085 SourceRange());
5086}
5087
Richard Smitha3405ff2018-07-11 00:19:19 +00005088/// Attempt to unwrap two types that may both be array types with the same bound
5089/// (or both be array types of unknown bound) for the purpose of comparing the
5090/// cv-decomposition of two types per C++ [conv.qual].
Richard Smith5407d4f2018-07-18 20:13:36 +00005091bool ASTContext::UnwrapSimilarArrayTypes(QualType &T1, QualType &T2) {
5092 bool UnwrappedAny = false;
Richard Smitha3405ff2018-07-11 00:19:19 +00005093 while (true) {
Richard Smith5407d4f2018-07-18 20:13:36 +00005094 auto *AT1 = getAsArrayType(T1);
5095 if (!AT1) return UnwrappedAny;
Richard Smitha3405ff2018-07-11 00:19:19 +00005096
Richard Smith5407d4f2018-07-18 20:13:36 +00005097 auto *AT2 = getAsArrayType(T2);
5098 if (!AT2) return UnwrappedAny;
Richard Smitha3405ff2018-07-11 00:19:19 +00005099
5100 // If we don't have two array types with the same constant bound nor two
5101 // incomplete array types, we've unwrapped everything we can.
5102 if (auto *CAT1 = dyn_cast<ConstantArrayType>(AT1)) {
5103 auto *CAT2 = dyn_cast<ConstantArrayType>(AT2);
5104 if (!CAT2 || CAT1->getSize() != CAT2->getSize())
Richard Smith5407d4f2018-07-18 20:13:36 +00005105 return UnwrappedAny;
Richard Smitha3405ff2018-07-11 00:19:19 +00005106 } else if (!isa<IncompleteArrayType>(AT1) ||
5107 !isa<IncompleteArrayType>(AT2)) {
Richard Smith5407d4f2018-07-18 20:13:36 +00005108 return UnwrappedAny;
Richard Smitha3405ff2018-07-11 00:19:19 +00005109 }
5110
5111 T1 = AT1->getElementType();
5112 T2 = AT2->getElementType();
Richard Smith5407d4f2018-07-18 20:13:36 +00005113 UnwrappedAny = true;
Richard Smitha3405ff2018-07-11 00:19:19 +00005114 }
5115}
5116
5117/// Attempt to unwrap two types that may be similar (C++ [conv.qual]).
5118///
5119/// If T1 and T2 are both pointer types of the same kind, or both array types
5120/// with the same bound, unwraps layers from T1 and T2 until a pointer type is
5121/// unwrapped. Top-level qualifiers on T1 and T2 are ignored.
5122///
5123/// This function will typically be called in a loop that successively
5124/// "unwraps" pointer and pointer-to-member types to compare them at each
5125/// level.
5126///
5127/// \return \c true if a pointer type was unwrapped, \c false if we reached a
5128/// pair of types that can't be unwrapped further.
5129bool ASTContext::UnwrapSimilarTypes(QualType &T1, QualType &T2) {
Richard Smith5407d4f2018-07-18 20:13:36 +00005130 UnwrapSimilarArrayTypes(T1, T2);
Richard Smitha3405ff2018-07-11 00:19:19 +00005131
Eugene Zelenko7855e772018-04-03 00:11:50 +00005132 const auto *T1PtrType = T1->getAs<PointerType>();
5133 const auto *T2PtrType = T2->getAs<PointerType>();
Douglas Gregor1fc3d662010-06-09 03:53:18 +00005134 if (T1PtrType && T2PtrType) {
5135 T1 = T1PtrType->getPointeeType();
5136 T2 = T2PtrType->getPointeeType();
5137 return true;
5138 }
Richard Smith5407d4f2018-07-18 20:13:36 +00005139
Eugene Zelenko7855e772018-04-03 00:11:50 +00005140 const auto *T1MPType = T1->getAs<MemberPointerType>();
5141 const auto *T2MPType = T2->getAs<MemberPointerType>();
Fangrui Song6907ce22018-07-30 19:24:48 +00005142 if (T1MPType && T2MPType &&
5143 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
Douglas Gregor1fc3d662010-06-09 03:53:18 +00005144 QualType(T2MPType->getClass(), 0))) {
5145 T1 = T1MPType->getPointeeType();
5146 T2 = T2MPType->getPointeeType();
5147 return true;
5148 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005149
Erik Pilkingtonfa983902018-10-30 20:31:30 +00005150 if (getLangOpts().ObjC) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00005151 const auto *T1OPType = T1->getAs<ObjCObjectPointerType>();
5152 const auto *T2OPType = T2->getAs<ObjCObjectPointerType>();
Douglas Gregor1fc3d662010-06-09 03:53:18 +00005153 if (T1OPType && T2OPType) {
5154 T1 = T1OPType->getPointeeType();
5155 T2 = T2OPType->getPointeeType();
5156 return true;
5157 }
5158 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005159
Douglas Gregor1fc3d662010-06-09 03:53:18 +00005160 // FIXME: Block pointers, too?
Fangrui Song6907ce22018-07-30 19:24:48 +00005161
Douglas Gregor1fc3d662010-06-09 03:53:18 +00005162 return false;
5163}
5164
Richard Smitha3405ff2018-07-11 00:19:19 +00005165bool ASTContext::hasSimilarType(QualType T1, QualType T2) {
5166 while (true) {
5167 Qualifiers Quals;
5168 T1 = getUnqualifiedArrayType(T1, Quals);
5169 T2 = getUnqualifiedArrayType(T2, Quals);
5170 if (hasSameType(T1, T2))
5171 return true;
5172 if (!UnwrapSimilarTypes(T1, T2))
5173 return false;
5174 }
5175}
5176
5177bool ASTContext::hasCvrSimilarType(QualType T1, QualType T2) {
5178 while (true) {
5179 Qualifiers Quals1, Quals2;
5180 T1 = getUnqualifiedArrayType(T1, Quals1);
5181 T2 = getUnqualifiedArrayType(T2, Quals2);
5182
5183 Quals1.removeCVRQualifiers();
5184 Quals2.removeCVRQualifiers();
5185 if (Quals1 != Quals2)
5186 return false;
5187
5188 if (hasSameType(T1, T2))
5189 return true;
5190
5191 if (!UnwrapSimilarTypes(T1, T2))
5192 return false;
5193 }
5194}
5195
Jay Foad39c79802011-01-12 09:06:06 +00005196DeclarationNameInfo
5197ASTContext::getNameForTemplate(TemplateName Name,
5198 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00005199 switch (Name.getKind()) {
5200 case TemplateName::QualifiedTemplate:
5201 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005202 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00005203 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
5204 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005205
John McCalld9dfe3a2011-06-30 08:33:18 +00005206 case TemplateName::OverloadedTemplate: {
5207 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
5208 // DNInfo work in progress: CHECKME: what about DNLoc?
5209 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
5210 }
5211
5212 case TemplateName::DependentTemplate: {
5213 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005214 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00005215 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005216 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
5217 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00005218 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005219 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
5220 // DNInfo work in progress: FIXME: source locations?
5221 DeclarationNameLoc DNLoc;
5222 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
5223 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
5224 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00005225 }
5226 }
5227
John McCalld9dfe3a2011-06-30 08:33:18 +00005228 case TemplateName::SubstTemplateTemplateParm: {
5229 SubstTemplateTemplateParmStorage *subst
5230 = Name.getAsSubstTemplateTemplateParm();
5231 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
5232 NameLoc);
5233 }
5234
5235 case TemplateName::SubstTemplateTemplateParmPack: {
5236 SubstTemplateTemplateParmPackStorage *subst
5237 = Name.getAsSubstTemplateTemplateParmPack();
5238 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
5239 NameLoc);
5240 }
5241 }
5242
5243 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00005244}
5245
Jay Foad39c79802011-01-12 09:06:06 +00005246TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00005247 switch (Name.getKind()) {
5248 case TemplateName::QualifiedTemplate:
5249 case TemplateName::Template: {
5250 TemplateDecl *Template = Name.getAsTemplateDecl();
Eugene Zelenko7855e772018-04-03 00:11:50 +00005251 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00005252 Template = getCanonicalTemplateTemplateParmDecl(TTP);
Fangrui Song6907ce22018-07-30 19:24:48 +00005253
Douglas Gregor7dbfb462010-06-16 21:09:37 +00005254 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00005255 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00005256 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00005257
John McCalld9dfe3a2011-06-30 08:33:18 +00005258 case TemplateName::OverloadedTemplate:
5259 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00005260
John McCalld9dfe3a2011-06-30 08:33:18 +00005261 case TemplateName::DependentTemplate: {
5262 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
5263 assert(DTN && "Non-dependent template names must refer to template decls.");
5264 return DTN->CanonicalTemplateName;
5265 }
5266
5267 case TemplateName::SubstTemplateTemplateParm: {
5268 SubstTemplateTemplateParmStorage *subst
5269 = Name.getAsSubstTemplateTemplateParm();
5270 return getCanonicalTemplateName(subst->getReplacement());
5271 }
5272
5273 case TemplateName::SubstTemplateTemplateParmPack: {
5274 SubstTemplateTemplateParmPackStorage *subst
5275 = Name.getAsSubstTemplateTemplateParmPack();
5276 TemplateTemplateParmDecl *canonParameter
5277 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
5278 TemplateArgument canonArgPack
5279 = getCanonicalTemplateArgument(subst->getArgumentPack());
5280 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
5281 }
5282 }
5283
5284 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00005285}
5286
Douglas Gregoradee3e32009-11-11 23:06:43 +00005287bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
5288 X = getCanonicalTemplateName(X);
5289 Y = getCanonicalTemplateName(Y);
5290 return X.getAsVoidPointer() == Y.getAsVoidPointer();
5291}
5292
Mike Stump11289f42009-09-09 15:08:12 +00005293TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00005294ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00005295 switch (Arg.getKind()) {
5296 case TemplateArgument::Null:
5297 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00005298
Douglas Gregora8e02e72009-07-28 23:00:59 +00005299 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00005300 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00005301
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005302 case TemplateArgument::Declaration: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00005303 auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
David Blaikie952a9b12014-10-17 18:00:12 +00005304 return TemplateArgument(D, Arg.getParamTypeForDecl());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005305 }
Mike Stump11289f42009-09-09 15:08:12 +00005306
Eli Friedmanb826a002012-09-26 02:36:12 +00005307 case TemplateArgument::NullPtr:
5308 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
5309 /*isNullPtr*/true);
5310
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005311 case TemplateArgument::Template:
5312 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005313
5314 case TemplateArgument::TemplateExpansion:
5315 return TemplateArgument(getCanonicalTemplateName(
5316 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00005317 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005318
Douglas Gregora8e02e72009-07-28 23:00:59 +00005319 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00005320 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00005321
Douglas Gregora8e02e72009-07-28 23:00:59 +00005322 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00005323 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00005324
Douglas Gregora8e02e72009-07-28 23:00:59 +00005325 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00005326 if (Arg.pack_size() == 0)
5327 return Arg;
Fangrui Song6907ce22018-07-30 19:24:48 +00005328
Eugene Zelenko7855e772018-04-03 00:11:50 +00005329 auto *CanonArgs = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00005330 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00005331 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00005332 AEnd = Arg.pack_end();
5333 A != AEnd; (void)++A, ++Idx)
5334 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00005335
Benjamin Kramercce63472015-08-05 09:40:22 +00005336 return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size()));
Douglas Gregora8e02e72009-07-28 23:00:59 +00005337 }
5338 }
5339
5340 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00005341 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00005342}
5343
Douglas Gregor333489b2009-03-27 23:10:48 +00005344NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00005345ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00005346 if (!NNS)
Craig Topper36250ad2014-05-12 05:36:57 +00005347 return nullptr;
Douglas Gregor333489b2009-03-27 23:10:48 +00005348
5349 switch (NNS->getKind()) {
5350 case NestedNameSpecifier::Identifier:
5351 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00005352 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00005353 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
5354 NNS->getAsIdentifier());
5355
5356 case NestedNameSpecifier::Namespace:
5357 // A namespace is canonical; build a nested-name-specifier with
5358 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00005359 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00005360 NNS->getAsNamespace()->getOriginalNamespace());
5361
5362 case NestedNameSpecifier::NamespaceAlias:
5363 // A namespace is canonical; build a nested-name-specifier with
5364 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00005365 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00005366 NNS->getAsNamespaceAlias()->getNamespace()
5367 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00005368
5369 case NestedNameSpecifier::TypeSpec:
5370 case NestedNameSpecifier::TypeSpecWithTemplate: {
5371 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Fangrui Song6907ce22018-07-30 19:24:48 +00005372
Douglas Gregor3ade5702010-11-04 00:09:33 +00005373 // If we have some kind of dependent-named type (e.g., "typename T::type"),
5374 // break it apart into its prefix and identifier, then reconsititute those
5375 // as the canonical nested-name-specifier. This is required to canonicalize
5376 // a dependent nested-name-specifier involving typedefs of dependent-name
5377 // types, e.g.,
5378 // typedef typename T::type T1;
5379 // typedef typename T1::type T2;
Eugene Zelenko7855e772018-04-03 00:11:50 +00005380 if (const auto *DNT = T->getAs<DependentNameType>())
Fangrui Song6907ce22018-07-30 19:24:48 +00005381 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00005382 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00005383
Eli Friedman5358a0a2012-03-03 04:09:56 +00005384 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
5385 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
5386 // first place?
Craig Topper36250ad2014-05-12 05:36:57 +00005387 return NestedNameSpecifier::Create(*this, nullptr, false,
5388 const_cast<Type *>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00005389 }
5390
5391 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00005392 case NestedNameSpecifier::Super:
5393 // The global specifier and __super specifer are canonical and unique.
Douglas Gregor333489b2009-03-27 23:10:48 +00005394 return NNS;
5395 }
5396
David Blaikie8a40f702012-01-17 06:56:22 +00005397 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00005398}
5399
Jay Foad39c79802011-01-12 09:06:06 +00005400const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00005401 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005402 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00005403 // Handle the common positive case fast.
Eugene Zelenko7855e772018-04-03 00:11:50 +00005404 if (const auto *AT = dyn_cast<ArrayType>(T))
Chris Lattner7adf0762008-08-04 07:31:14 +00005405 return AT;
5406 }
Mike Stump11289f42009-09-09 15:08:12 +00005407
John McCall8ccfcb52009-09-24 19:53:00 +00005408 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00005409 if (!isa<ArrayType>(T.getCanonicalType()))
Craig Topper36250ad2014-05-12 05:36:57 +00005410 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00005411
John McCall8ccfcb52009-09-24 19:53:00 +00005412 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00005413 // implements C99 6.7.3p8: "If the specification of an array type includes
5414 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00005415
Chris Lattner7adf0762008-08-04 07:31:14 +00005416 // If we get here, we either have type qualifiers on the type, or we have
5417 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00005418 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00005419
John McCall33ddac02011-01-19 10:06:00 +00005420 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00005421 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00005422
Chris Lattner7adf0762008-08-04 07:31:14 +00005423 // If we have a simple case, just return now.
Eugene Zelenko7855e772018-04-03 00:11:50 +00005424 const auto *ATy = dyn_cast<ArrayType>(split.Ty);
Craig Topper36250ad2014-05-12 05:36:57 +00005425 if (!ATy || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00005426 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00005427
Chris Lattner7adf0762008-08-04 07:31:14 +00005428 // Otherwise, we have an array and we have qualifiers on it. Push the
5429 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00005430 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00005431
Eugene Zelenko7855e772018-04-03 00:11:50 +00005432 if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy))
Chris Lattner7adf0762008-08-04 07:31:14 +00005433 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
5434 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00005435 CAT->getIndexTypeCVRQualifiers()));
Eugene Zelenko7855e772018-04-03 00:11:50 +00005436 if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy))
Chris Lattner7adf0762008-08-04 07:31:14 +00005437 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
5438 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00005439 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00005440
Eugene Zelenko7855e772018-04-03 00:11:50 +00005441 if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy))
Douglas Gregor4619e432008-12-05 23:32:09 +00005442 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00005443 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00005444 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00005445 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00005446 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00005447 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00005448
Eugene Zelenko7855e772018-04-03 00:11:50 +00005449 const auto *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00005450 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00005451 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00005452 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00005453 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00005454 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00005455}
5456
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00005457QualType ASTContext::getAdjustedParameterType(QualType T) const {
Reid Kleckner8a365022013-06-24 17:51:48 +00005458 if (T->isArrayType() || T->isFunctionType())
5459 return getDecayedType(T);
5460 return T;
Douglas Gregor84280642011-07-12 04:42:08 +00005461}
5462
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00005463QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00005464 T = getVariableArrayDecayedType(T);
5465 T = getAdjustedParameterType(T);
5466 return T.getUnqualifiedType();
5467}
5468
David Majnemerd09a51c2015-03-03 01:50:05 +00005469QualType ASTContext::getExceptionObjectType(QualType T) const {
5470 // C++ [except.throw]p3:
5471 // A throw-expression initializes a temporary object, called the exception
5472 // object, the type of which is determined by removing any top-level
5473 // cv-qualifiers from the static type of the operand of throw and adjusting
5474 // the type from "array of T" or "function returning T" to "pointer to T"
5475 // or "pointer to function returning T", [...]
5476 T = getVariableArrayDecayedType(T);
5477 if (T->isArrayType() || T->isFunctionType())
5478 T = getDecayedType(T);
5479 return T.getUnqualifiedType();
5480}
5481
Chris Lattnera21ad802008-04-02 05:18:44 +00005482/// getArrayDecayedType - Return the properly qualified result of decaying the
5483/// specified array type to a pointer. This operation is non-trivial when
5484/// handling typedefs etc. The canonical type of "T" must be an array type,
5485/// this returns a pointer to a properly qualified element of the array.
5486///
5487/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00005488QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00005489 // Get the element type with 'getAsArrayType' so that we don't lose any
5490 // typedefs in the element type of the array. This also handles propagation
5491 // of type qualifiers from the array type into the element type if present
5492 // (C99 6.7.3p8).
5493 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
5494 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00005495
Chris Lattner7adf0762008-08-04 07:31:14 +00005496 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00005497
5498 // int x[restrict 4] -> int *restrict
Jordan Rose303e2f12016-11-10 23:28:17 +00005499 QualType Result = getQualifiedType(PtrTy,
5500 PrettyArrayType->getIndexTypeQualifiers());
5501
5502 // int x[_Nullable] -> int * _Nullable
5503 if (auto Nullability = Ty->getNullability(*this)) {
5504 Result = const_cast<ASTContext *>(this)->getAttributedType(
5505 AttributedType::getNullabilityAttrKind(*Nullability), Result, Result);
5506 }
5507 return Result;
Chris Lattnera21ad802008-04-02 05:18:44 +00005508}
5509
John McCall33ddac02011-01-19 10:06:00 +00005510QualType ASTContext::getBaseElementType(const ArrayType *array) const {
5511 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00005512}
5513
John McCall33ddac02011-01-19 10:06:00 +00005514QualType ASTContext::getBaseElementType(QualType type) const {
5515 Qualifiers qs;
5516 while (true) {
5517 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00005518 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00005519 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00005520
John McCall33ddac02011-01-19 10:06:00 +00005521 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00005522 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00005523 }
Mike Stump11289f42009-09-09 15:08:12 +00005524
John McCall33ddac02011-01-19 10:06:00 +00005525 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00005526}
5527
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00005528/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00005529uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00005530ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
5531 uint64_t ElementCount = 1;
5532 do {
5533 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00005534 CA = dyn_cast_or_null<ConstantArrayType>(
5535 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00005536 } while (CA);
5537 return ElementCount;
5538}
5539
Steve Naroff0af91202007-04-27 21:51:21 +00005540/// getFloatingRank - Return a relative rank for floating point types.
5541/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00005542static FloatingRank getFloatingRank(QualType T) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00005543 if (const auto *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00005544 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00005545
John McCall9dd450b2009-09-21 23:43:11 +00005546 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
5547 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00005548 default: llvm_unreachable("getFloatingRank(): not a floating type");
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00005549 case BuiltinType::Float16: return Float16Rank;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00005550 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00005551 case BuiltinType::Float: return FloatRank;
5552 case BuiltinType::Double: return DoubleRank;
5553 case BuiltinType::LongDouble: return LongDoubleRank;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005554 case BuiltinType::Float128: return Float128Rank;
Steve Naroffe4718892007-04-27 18:30:00 +00005555 }
5556}
5557
Mike Stump11289f42009-09-09 15:08:12 +00005558/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
5559/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00005560/// 'typeDomain' is a real floating point or complex type.
5561/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00005562QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
5563 QualType Domain) const {
5564 FloatingRank EltRank = getFloatingRank(Size);
5565 if (Domain->isComplexType()) {
5566 switch (EltRank) {
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00005567 case Float16Rank:
David Blaikief47fa302012-01-17 02:30:50 +00005568 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00005569 case FloatRank: return FloatComplexTy;
5570 case DoubleRank: return DoubleComplexTy;
5571 case LongDoubleRank: return LongDoubleComplexTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005572 case Float128Rank: return Float128ComplexTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00005573 }
Steve Naroff0af91202007-04-27 21:51:21 +00005574 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00005575
5576 assert(Domain->isRealFloatingType() && "Unknown domain!");
5577 switch (EltRank) {
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00005578 case Float16Rank: return HalfTy;
Joey Goulydd7f4562013-01-23 11:56:20 +00005579 case HalfRank: return HalfTy;
Chris Lattnerb9dfb032008-04-06 23:58:54 +00005580 case FloatRank: return FloatTy;
5581 case DoubleRank: return DoubleTy;
5582 case LongDoubleRank: return LongDoubleTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005583 case Float128Rank: return Float128Ty;
Steve Naroff9091ef72007-08-27 01:27:54 +00005584 }
David Blaikief47fa302012-01-17 02:30:50 +00005585 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00005586}
5587
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005588/// getFloatingTypeOrder - Compare the rank of the two specified floating
5589/// point types, ignoring the domain of the type (i.e. 'double' ==
5590/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00005591/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00005592int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00005593 FloatingRank LHSR = getFloatingRank(LHS);
5594 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00005595
Chris Lattnerb90739d2008-04-06 23:38:49 +00005596 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00005597 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00005598 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00005599 return 1;
5600 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00005601}
5602
Erik Pilkingtoneac7c3f2019-02-16 01:11:47 +00005603int ASTContext::getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const {
5604 if (&getFloatTypeSemantics(LHS) == &getFloatTypeSemantics(RHS))
5605 return 0;
5606 return getFloatingTypeOrder(LHS, RHS);
5607}
5608
Chris Lattner76a00cf2008-04-06 22:59:24 +00005609/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
5610/// routine will assert if passed a built-in type that isn't an integer or enum,
5611/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00005612unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00005613 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00005614
Chris Lattner76a00cf2008-04-06 22:59:24 +00005615 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00005616 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005617 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005618 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005619 case BuiltinType::Char_S:
5620 case BuiltinType::Char_U:
5621 case BuiltinType::SChar:
5622 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005623 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005624 case BuiltinType::Short:
5625 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005626 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005627 case BuiltinType::Int:
5628 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005629 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005630 case BuiltinType::Long:
5631 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005632 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005633 case BuiltinType::LongLong:
5634 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005635 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00005636 case BuiltinType::Int128:
5637 case BuiltinType::UInt128:
5638 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00005639 }
5640}
5641
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005642/// Whether this is a promotable bitfield reference according
Eli Friedman629ffb92009-08-20 04:21:42 +00005643/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
5644///
5645/// \returns the type this bit-field will promote to, or NULL if no
5646/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00005647QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00005648 if (E->isTypeDependent() || E->isValueDependent())
Eugene Zelenko7855e772018-04-03 00:11:50 +00005649 return {};
Richard Smith5b571672014-09-24 23:55:00 +00005650
Richard Smithaadb2542018-06-28 21:17:55 +00005651 // C++ [conv.prom]p5:
5652 // If the bit-field has an enumerated type, it is treated as any other
5653 // value of that type for promotion purposes.
5654 if (getLangOpts().CPlusPlus && E->getType()->isEnumeralType())
5655 return {};
5656
Richard Smith5b571672014-09-24 23:55:00 +00005657 // FIXME: We should not do this unless E->refersToBitField() is true. This
5658 // matters in C where getSourceBitField() will find bit-fields for various
5659 // cases where the source expression is not a bit-field designator.
5660
John McCalld25db7e2013-05-06 21:39:12 +00005661 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman629ffb92009-08-20 04:21:42 +00005662 if (!Field)
Eugene Zelenko7855e772018-04-03 00:11:50 +00005663 return {};
Eli Friedman629ffb92009-08-20 04:21:42 +00005664
5665 QualType FT = Field->getType();
5666
Richard Smithcaf33902011-10-10 18:28:20 +00005667 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00005668 uint64_t IntSize = getTypeSize(IntTy);
Richard Smith5b571672014-09-24 23:55:00 +00005669 // C++ [conv.prom]p5:
5670 // A prvalue for an integral bit-field can be converted to a prvalue of type
5671 // int if int can represent all the values of the bit-field; otherwise, it
5672 // can be converted to unsigned int if unsigned int can represent all the
5673 // values of the bit-field. If the bit-field is larger yet, no integral
5674 // promotion applies to it.
5675 // C11 6.3.1.1/2:
5676 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
5677 // If an int can represent all values of the original type (as restricted by
5678 // the width, for a bit-field), the value is converted to an int; otherwise,
5679 // it is converted to an unsigned int.
5680 //
5681 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
5682 // We perform that promotion here to match GCC and C++.
Richard Smithaadb2542018-06-28 21:17:55 +00005683 // FIXME: C does not permit promotion of an enum bit-field whose rank is
5684 // greater than that of 'int'. We perform that promotion to match GCC.
Eli Friedman629ffb92009-08-20 04:21:42 +00005685 if (BitWidth < IntSize)
5686 return IntTy;
5687
5688 if (BitWidth == IntSize)
5689 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
5690
Richard Smithaadb2542018-06-28 21:17:55 +00005691 // Bit-fields wider than int are not subject to promotions, and therefore act
Richard Smith5b571672014-09-24 23:55:00 +00005692 // like the base type. GCC has some weird bugs in this area that we
5693 // deliberately do not follow (GCC follows a pre-standard resolution to
5694 // C's DR315 which treats bit-width as being part of the type, and this leaks
5695 // into their semantics in some cases).
Eugene Zelenko7855e772018-04-03 00:11:50 +00005696 return {};
Eli Friedman629ffb92009-08-20 04:21:42 +00005697}
5698
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005699/// getPromotedIntegerType - Returns the type that Promotable will
5700/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
5701/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00005702QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005703 assert(!Promotable.isNull());
5704 assert(Promotable->isPromotableIntegerType());
Eugene Zelenko7855e772018-04-03 00:11:50 +00005705 if (const auto *ET = Promotable->getAs<EnumType>())
John McCall56774992009-12-09 09:09:27 +00005706 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00005707
Eugene Zelenko7855e772018-04-03 00:11:50 +00005708 if (const auto *BT = Promotable->getAs<BuiltinType>()) {
Eli Friedman3f37c1c2011-10-26 07:22:48 +00005709 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
5710 // (3.9.1) can be converted to a prvalue of the first of the following
5711 // types that can represent all the values of its underlying type:
5712 // int, unsigned int, long int, unsigned long int, long long int, or
5713 // unsigned long long int [...]
5714 // FIXME: Is there some better way to compute this?
5715 if (BT->getKind() == BuiltinType::WChar_S ||
5716 BT->getKind() == BuiltinType::WChar_U ||
Richard Smith3a8244d2018-05-01 05:02:45 +00005717 BT->getKind() == BuiltinType::Char8 ||
Eli Friedman3f37c1c2011-10-26 07:22:48 +00005718 BT->getKind() == BuiltinType::Char16 ||
5719 BT->getKind() == BuiltinType::Char32) {
5720 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
5721 uint64_t FromSize = getTypeSize(BT);
5722 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
5723 LongLongTy, UnsignedLongLongTy };
5724 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
5725 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
5726 if (FromSize < ToSize ||
5727 (FromSize == ToSize &&
5728 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
5729 return PromoteTypes[Idx];
5730 }
5731 llvm_unreachable("char type should fit into long long");
5732 }
5733 }
5734
5735 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005736 if (Promotable->isSignedIntegerType())
5737 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00005738 uint64_t PromotableSize = getIntWidth(Promotable);
5739 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005740 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
5741 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
5742}
5743
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005744/// Recurses in pointer/array types until it finds an objc retainable
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00005745/// type and returns its ownership.
5746Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
5747 while (!T.isNull()) {
5748 if (T.getObjCLifetime() != Qualifiers::OCL_None)
5749 return T.getObjCLifetime();
5750 if (T->isArrayType())
5751 T = getBaseElementType(T);
Eugene Zelenko7855e772018-04-03 00:11:50 +00005752 else if (const auto *PT = T->getAs<PointerType>())
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00005753 T = PT->getPointeeType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00005754 else if (const auto *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00005755 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00005756 else
5757 break;
5758 }
5759
5760 return Qualifiers::OCL_None;
5761}
5762
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005763static const Type *getIntegerTypeForEnum(const EnumType *ET) {
5764 // Incomplete enum types are not treated as integer types.
5765 // FIXME: In C++, enum types are never integer types.
5766 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
5767 return ET->getDecl()->getIntegerType().getTypePtr();
Craig Topper36250ad2014-05-12 05:36:57 +00005768 return nullptr;
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005769}
5770
Mike Stump11289f42009-09-09 15:08:12 +00005771/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005772/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00005773/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00005774int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00005775 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
5776 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005777
5778 // Unwrap enums to their underlying type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00005779 if (const auto *ET = dyn_cast<EnumType>(LHSC))
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005780 LHSC = getIntegerTypeForEnum(ET);
Eugene Zelenko7855e772018-04-03 00:11:50 +00005781 if (const auto *ET = dyn_cast<EnumType>(RHSC))
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005782 RHSC = getIntegerTypeForEnum(ET);
5783
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005784 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00005785
Chris Lattner76a00cf2008-04-06 22:59:24 +00005786 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
5787 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00005788
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005789 unsigned LHSRank = getIntegerRank(LHSC);
5790 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00005791
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005792 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
5793 if (LHSRank == RHSRank) return 0;
5794 return LHSRank > RHSRank ? 1 : -1;
5795 }
Mike Stump11289f42009-09-09 15:08:12 +00005796
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005797 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
5798 if (LHSUnsigned) {
5799 // If the unsigned [LHS] type is larger, return it.
5800 if (LHSRank >= RHSRank)
5801 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00005802
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005803 // If the signed type can represent all values of the unsigned type, it
5804 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00005805 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005806 return -1;
5807 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00005808
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005809 // If the unsigned [RHS] type is larger, return it.
5810 if (RHSRank >= LHSRank)
5811 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00005812
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005813 // If the signed type can represent all values of the unsigned type, it
5814 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00005815 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005816 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00005817}
Anders Carlsson98f07902007-08-17 05:31:46 +00005818
Ben Langmuirf5416742016-02-04 00:55:24 +00005819TypedefDecl *ASTContext::getCFConstantStringDecl() const {
Saleem Abdulrasoolef9b88a2018-10-24 16:38:16 +00005820 if (CFConstantStringTypeDecl)
5821 return CFConstantStringTypeDecl;
Anders Carlsson6d417272009-11-14 21:45:58 +00005822
Saleem Abdulrasoolef9b88a2018-10-24 16:38:16 +00005823 assert(!CFConstantStringTagDecl &&
5824 "tag and typedef should be initialized together");
5825 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
5826 CFConstantStringTagDecl->startDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00005827
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00005828 struct {
5829 QualType Type;
5830 const char *Name;
5831 } Fields[5];
5832 unsigned Count = 0;
Mike Stump11289f42009-09-09 15:08:12 +00005833
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00005834 /// Objective-C ABI
5835 ///
5836 /// typedef struct __NSConstantString_tag {
Saleem Abdulrasool1f6c41f2018-10-27 06:12:52 +00005837 /// const int *isa;
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00005838 /// int flags;
5839 /// const char *str;
5840 /// long length;
5841 /// } __NSConstantString;
5842 ///
5843 /// Swift ABI (4.1, 4.2)
5844 ///
5845 /// typedef struct __NSConstantString_tag {
5846 /// uintptr_t _cfisa;
5847 /// uintptr_t _swift_rc;
5848 /// _Atomic(uint64_t) _cfinfoa;
5849 /// const char *_ptr;
5850 /// uint32_t _length;
5851 /// } __NSConstantString;
5852 ///
5853 /// Swift ABI (5.0)
5854 ///
5855 /// typedef struct __NSConstantString_tag {
5856 /// uintptr_t _cfisa;
5857 /// uintptr_t _swift_rc;
5858 /// _Atomic(uint64_t) _cfinfoa;
5859 /// const char *_ptr;
5860 /// uintptr_t _length;
5861 /// } __NSConstantString;
5862
5863 const auto CFRuntime = getLangOpts().CFRuntime;
5864 if (static_cast<unsigned>(CFRuntime) <
5865 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) {
5866 Fields[Count++] = { getPointerType(IntTy.withConst()), "isa" };
5867 Fields[Count++] = { IntTy, "flags" };
5868 Fields[Count++] = { getPointerType(CharTy.withConst()), "str" };
5869 Fields[Count++] = { LongTy, "length" };
5870 } else {
5871 Fields[Count++] = { getUIntPtrType(), "_cfisa" };
5872 Fields[Count++] = { getUIntPtrType(), "_swift_rc" };
5873 Fields[Count++] = { getFromTargetType(Target->getUInt64Type()), "_swift_rc" };
5874 Fields[Count++] = { getPointerType(CharTy.withConst()), "_ptr" };
5875 if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 ||
5876 CFRuntime == LangOptions::CoreFoundationABI::Swift4_2)
5877 Fields[Count++] = { IntTy, "_ptr" };
5878 else
5879 Fields[Count++] = { getUIntPtrType(), "_ptr" };
5880 }
Douglas Gregor91f84212008-12-11 16:49:14 +00005881
Saleem Abdulrasoolef9b88a2018-10-24 16:38:16 +00005882 // Create fields
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00005883 for (unsigned i = 0; i < Count; ++i) {
Saleem Abdulrasoolef9b88a2018-10-24 16:38:16 +00005884 FieldDecl *Field =
5885 FieldDecl::Create(*this, CFConstantStringTagDecl, SourceLocation(),
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00005886 SourceLocation(), &Idents.get(Fields[i].Name),
5887 Fields[i].Type, /*TInfo=*/nullptr,
Saleem Abdulrasoolef9b88a2018-10-24 16:38:16 +00005888 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
5889 Field->setAccess(AS_public);
5890 CFConstantStringTagDecl->addDecl(Field);
Anders Carlsson98f07902007-08-17 05:31:46 +00005891 }
Mike Stump11289f42009-09-09 15:08:12 +00005892
Saleem Abdulrasoolef9b88a2018-10-24 16:38:16 +00005893 CFConstantStringTagDecl->completeDefinition();
5894 // This type is designed to be compatible with NSConstantString, but cannot
5895 // use the same name, since NSConstantString is an interface.
5896 auto tagType = getTagDeclType(CFConstantStringTagDecl);
5897 CFConstantStringTypeDecl =
5898 buildImplicitTypedef(tagType, "__NSConstantString");
5899
Quentin Colombet043406b2016-02-03 22:41:00 +00005900 return CFConstantStringTypeDecl;
5901}
5902
Ben Langmuirf5416742016-02-04 00:55:24 +00005903RecordDecl *ASTContext::getCFConstantStringTagDecl() const {
5904 if (!CFConstantStringTagDecl)
5905 getCFConstantStringDecl(); // Build the tag and the typedef.
5906 return CFConstantStringTagDecl;
5907}
5908
Quentin Colombet043406b2016-02-03 22:41:00 +00005909// getCFConstantStringType - Return the type used for constant CFStrings.
5910QualType ASTContext::getCFConstantStringType() const {
Ben Langmuirf5416742016-02-04 00:55:24 +00005911 return getTypedefType(getCFConstantStringDecl());
Gabor Greif412af032007-09-11 15:32:40 +00005912}
Anders Carlsson87c149b2007-10-11 01:00:40 +00005913
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00005914QualType ASTContext::getObjCSuperType() const {
5915 if (ObjCSuperType.isNull()) {
Alp Toker2dea15b2013-12-17 01:22:38 +00005916 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00005917 TUDecl->addDecl(ObjCSuperTypeDecl);
5918 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
5919 }
5920 return ObjCSuperType;
5921}
5922
Douglas Gregor512b0772009-04-23 22:29:11 +00005923void ASTContext::setCFConstantStringType(QualType T) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00005924 const auto *TD = T->getAs<TypedefType>();
Ben Langmuirf5416742016-02-04 00:55:24 +00005925 assert(TD && "Invalid CFConstantStringType");
5926 CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl());
Eugene Zelenko7855e772018-04-03 00:11:50 +00005927 const auto *TagType =
Ben Langmuirf5416742016-02-04 00:55:24 +00005928 CFConstantStringTypeDecl->getUnderlyingType()->getAs<RecordType>();
5929 assert(TagType && "Invalid CFConstantStringType");
5930 CFConstantStringTagDecl = TagType->getDecl();
Douglas Gregor512b0772009-04-23 22:29:11 +00005931}
5932
Jay Foad39c79802011-01-12 09:06:06 +00005933QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00005934 if (BlockDescriptorType)
5935 return getTagDeclType(BlockDescriptorType);
5936
Alp Toker2dea15b2013-12-17 01:22:38 +00005937 RecordDecl *RD;
Mike Stumpd0153282009-10-20 02:12:22 +00005938 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00005939 RD = buildImplicitRecord("__block_descriptor");
5940 RD->startDefinition();
5941
Mike Stumpd0153282009-10-20 02:12:22 +00005942 QualType FieldTypes[] = {
5943 UnsignedLongTy,
5944 UnsignedLongTy,
5945 };
5946
Craig Topperd6d31ac2013-07-15 08:24:27 +00005947 static const char *const FieldNames[] = {
Mike Stumpd0153282009-10-20 02:12:22 +00005948 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005949 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00005950 };
5951
5952 for (size_t i = 0; i < 2; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00005953 FieldDecl *Field = FieldDecl::Create(
5954 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00005955 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
5956 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00005957 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00005958 RD->addDecl(Field);
Mike Stumpd0153282009-10-20 02:12:22 +00005959 }
5960
Alp Toker2dea15b2013-12-17 01:22:38 +00005961 RD->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00005962
Alp Toker2dea15b2013-12-17 01:22:38 +00005963 BlockDescriptorType = RD;
Mike Stumpd0153282009-10-20 02:12:22 +00005964
5965 return getTagDeclType(BlockDescriptorType);
5966}
5967
Jay Foad39c79802011-01-12 09:06:06 +00005968QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005969 if (BlockDescriptorExtendedType)
5970 return getTagDeclType(BlockDescriptorExtendedType);
5971
Alp Toker2dea15b2013-12-17 01:22:38 +00005972 RecordDecl *RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005973 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00005974 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
5975 RD->startDefinition();
5976
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005977 QualType FieldTypes[] = {
5978 UnsignedLongTy,
5979 UnsignedLongTy,
5980 getPointerType(VoidPtrTy),
5981 getPointerType(VoidPtrTy)
5982 };
5983
Craig Topperd6d31ac2013-07-15 08:24:27 +00005984 static const char *const FieldNames[] = {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005985 "reserved",
5986 "Size",
5987 "CopyFuncPtr",
5988 "DestroyFuncPtr"
5989 };
5990
5991 for (size_t i = 0; i < 4; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00005992 FieldDecl *Field = FieldDecl::Create(
5993 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00005994 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
5995 /*BitWidth=*/nullptr,
Alp Toker2dea15b2013-12-17 01:22:38 +00005996 /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00005997 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00005998 RD->addDecl(Field);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005999 }
6000
Alp Toker2dea15b2013-12-17 01:22:38 +00006001 RD->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00006002
Alp Toker2dea15b2013-12-17 01:22:38 +00006003 BlockDescriptorExtendedType = RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00006004 return getTagDeclType(BlockDescriptorExtendedType);
6005}
6006
Sven van Haastregt3bb7eaf2017-12-06 10:11:28 +00006007TargetInfo::OpenCLTypeKind ASTContext::getOpenCLTypeKind(const Type *T) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006008 const auto *BT = dyn_cast<BuiltinType>(T);
Sven van Haastregt3bb7eaf2017-12-06 10:11:28 +00006009
6010 if (!BT) {
6011 if (isa<PipeType>(T))
6012 return TargetInfo::OCLTK_Pipe;
6013
6014 return TargetInfo::OCLTK_Default;
6015 }
6016
6017 switch (BT->getKind()) {
6018#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6019 case BuiltinType::Id: \
6020 return TargetInfo::OCLTK_Image;
6021#include "clang/Basic/OpenCLImageTypes.def"
6022
6023 case BuiltinType::OCLClkEvent:
6024 return TargetInfo::OCLTK_ClkEvent;
6025
6026 case BuiltinType::OCLEvent:
6027 return TargetInfo::OCLTK_Event;
6028
6029 case BuiltinType::OCLQueue:
6030 return TargetInfo::OCLTK_Queue;
6031
6032 case BuiltinType::OCLReserveID:
6033 return TargetInfo::OCLTK_ReserveID;
6034
6035 case BuiltinType::OCLSampler:
6036 return TargetInfo::OCLTK_Sampler;
6037
6038 default:
6039 return TargetInfo::OCLTK_Default;
6040 }
6041}
6042
6043LangAS ASTContext::getOpenCLTypeAddrSpace(const Type *T) const {
6044 return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
6045}
6046
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006047/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
6048/// requires copy/dispose. Note that this must match the logic
6049/// in buildByrefHelpers.
6050bool ASTContext::BlockRequiresCopying(QualType Ty,
6051 const VarDecl *D) {
6052 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
Akira Hatanaka9978da32018-08-10 15:09:24 +00006053 const Expr *copyExpr = getBlockVarCopyInit(D).getCopyExpr();
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006054 if (!copyExpr && record->hasTrivialDestructor()) return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00006055
Mike Stump94967902009-10-21 18:16:27 +00006056 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00006057 }
Fangrui Song6907ce22018-07-30 19:24:48 +00006058
Akira Hatanaka7275da02018-02-28 07:15:55 +00006059 // The block needs copy/destroy helpers if Ty is non-trivial to destructively
6060 // move or destroy.
6061 if (Ty.isNonTrivialToPrimitiveDestructiveMove() || Ty.isDestructedType())
6062 return true;
6063
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006064 if (!Ty->isObjCRetainableType()) return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00006065
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006066 Qualifiers qs = Ty.getQualifiers();
Fangrui Song6907ce22018-07-30 19:24:48 +00006067
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006068 // If we have lifetime, that dominates.
6069 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006070 switch (lifetime) {
6071 case Qualifiers::OCL_None: llvm_unreachable("impossible");
Fangrui Song6907ce22018-07-30 19:24:48 +00006072
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006073 // These are just bits as far as the runtime is concerned.
6074 case Qualifiers::OCL_ExplicitNone:
6075 case Qualifiers::OCL_Autoreleasing:
6076 return false;
Akira Hatanaka7275da02018-02-28 07:15:55 +00006077
6078 // These cases should have been taken care of when checking the type's
6079 // non-triviality.
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006080 case Qualifiers::OCL_Weak:
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006081 case Qualifiers::OCL_Strong:
Akira Hatanaka7275da02018-02-28 07:15:55 +00006082 llvm_unreachable("impossible");
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006083 }
6084 llvm_unreachable("fell out of lifetime switch!");
6085 }
6086 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
6087 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00006088}
6089
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006090bool ASTContext::getByrefLifetime(QualType Ty,
6091 Qualifiers::ObjCLifetime &LifeTime,
6092 bool &HasByrefExtendedLayout) const {
Erik Pilkingtonfa983902018-10-30 20:31:30 +00006093 if (!getLangOpts().ObjC ||
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006094 getLangOpts().getGC() != LangOptions::NonGC)
6095 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00006096
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006097 HasByrefExtendedLayout = false;
Fariborz Jahanianf762b722012-12-11 19:58:01 +00006098 if (Ty->isRecordType()) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006099 HasByrefExtendedLayout = true;
6100 LifeTime = Qualifiers::OCL_None;
John McCall460ce582015-10-22 18:38:17 +00006101 } else if ((LifeTime = Ty.getObjCLifetime())) {
6102 // Honor the ARC qualifiers.
6103 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
6104 // The MRR rule.
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006105 LifeTime = Qualifiers::OCL_ExplicitNone;
John McCall460ce582015-10-22 18:38:17 +00006106 } else {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006107 LifeTime = Qualifiers::OCL_None;
John McCall460ce582015-10-22 18:38:17 +00006108 }
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006109 return true;
6110}
6111
Douglas Gregorbab8a962011-09-08 01:46:34 +00006112TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
6113 if (!ObjCInstanceTypeDecl)
Alp Toker56b5cc92013-12-15 10:36:26 +00006114 ObjCInstanceTypeDecl =
6115 buildImplicitTypedef(getObjCIdType(), "instancetype");
Douglas Gregorbab8a962011-09-08 01:46:34 +00006116 return ObjCInstanceTypeDecl;
6117}
6118
Anders Carlsson18acd442007-10-29 06:33:42 +00006119// This returns true if a type has been typedefed to BOOL:
6120// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00006121static bool isTypeTypedefedAsBOOL(QualType T) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006122 if (const auto *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00006123 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
6124 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00006125
Anders Carlssond8499822007-10-29 05:01:08 +00006126 return false;
6127}
6128
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006129/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006130/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00006131CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00006132 if (!type->isIncompleteArrayType() && type->isIncompleteType())
6133 return CharUnits::Zero();
Fangrui Song6907ce22018-07-30 19:24:48 +00006134
Ken Dyck40775002010-01-11 17:06:35 +00006135 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00006136
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006137 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00006138 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00006139 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006140 // Treat arrays as pointers, since that's how they're passed in.
6141 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00006142 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00006143 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00006144}
6145
Hans Wennborg56fc62b2014-07-17 20:25:23 +00006146bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
David Majnemer3f021502015-10-08 04:53:31 +00006147 return getTargetInfo().getCXXABI().isMicrosoft() &&
6148 VD->isStaticDataMember() &&
Hans Wennborgb18da9b2018-02-20 12:43:02 +00006149 VD->getType()->isIntegralOrEnumerationType() &&
David Majnemerfac52432015-10-19 23:22:49 +00006150 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
Hans Wennborg56fc62b2014-07-17 20:25:23 +00006151}
6152
Richard Smithd9b90092016-07-02 01:32:16 +00006153ASTContext::InlineVariableDefinitionKind
6154ASTContext::getInlineVariableDefinitionKind(const VarDecl *VD) const {
6155 if (!VD->isInline())
6156 return InlineVariableDefinitionKind::None;
6157
6158 // In almost all cases, it's a weak definition.
6159 auto *First = VD->getFirstDecl();
Richard Smith8910fe62017-10-23 03:58:34 +00006160 if (First->isInlineSpecified() || !First->isStaticDataMember())
Richard Smithd9b90092016-07-02 01:32:16 +00006161 return InlineVariableDefinitionKind::Weak;
6162
6163 // If there's a file-context declaration in this translation unit, it's a
6164 // non-discardable definition.
6165 for (auto *D : VD->redecls())
Richard Smith8910fe62017-10-23 03:58:34 +00006166 if (D->getLexicalDeclContext()->isFileContext() &&
6167 !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr()))
Richard Smithd9b90092016-07-02 01:32:16 +00006168 return InlineVariableDefinitionKind::Strong;
6169
6170 // If we've not seen one yet, we don't know.
6171 return InlineVariableDefinitionKind::WeakUnknown;
6172}
6173
Eugene Zelenko7855e772018-04-03 00:11:50 +00006174static std::string charUnitsToString(const CharUnits &CU) {
Ken Dyck40775002010-01-11 17:06:35 +00006175 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006176}
6177
John McCall351762c2011-02-07 10:33:21 +00006178/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00006179/// declaration.
John McCall351762c2011-02-07 10:33:21 +00006180std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
6181 std::string S;
6182
David Chisnall950a9512009-11-17 19:33:30 +00006183 const BlockDecl *Decl = Expr->getBlockDecl();
6184 QualType BlockTy =
6185 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
6186 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00006187 if (getLangOpts().EncodeExtendedBlockSig)
Alp Toker314cc812014-01-25 16:55:45 +00006188 getObjCEncodingForMethodParameter(
6189 Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
6190 true /*Extended*/);
Fariborz Jahanian64223e62012-11-14 23:11:38 +00006191 else
Alp Toker314cc812014-01-25 16:55:45 +00006192 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00006193 // Compute size of all parameters.
6194 // Start with computing size of a pointer in number of bytes.
6195 // FIXME: There might(should) be a better way of doing this computation!
Ken Dyck40775002010-01-11 17:06:35 +00006196 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
6197 CharUnits ParmOffset = PtrSize;
David Majnemer59f77922016-06-24 04:05:48 +00006198 for (auto PI : Decl->parameters()) {
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00006199 QualType PType = PI->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00006200 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00006201 if (sz.isZero())
6202 continue;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00006203 assert(sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00006204 ParmOffset += sz;
6205 }
6206 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00006207 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00006208 // Block pointer and offset.
6209 S += "@?0";
Fangrui Song6907ce22018-07-30 19:24:48 +00006210
David Chisnall950a9512009-11-17 19:33:30 +00006211 // Argument types.
6212 ParmOffset = PtrSize;
David Majnemer59f77922016-06-24 04:05:48 +00006213 for (auto PVDecl : Decl->parameters()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00006214 QualType PType = PVDecl->getOriginalType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00006215 if (const auto *AT =
6216 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
David Chisnall950a9512009-11-17 19:33:30 +00006217 // Use array's original type only if it has known number of
6218 // elements.
6219 if (!isa<ConstantArrayType>(AT))
6220 PType = PVDecl->getType();
6221 } else if (PType->isFunctionType())
6222 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00006223 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00006224 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
6225 S, true /*Extended*/);
6226 else
6227 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00006228 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00006229 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00006230 }
John McCall351762c2011-02-07 10:33:21 +00006231
6232 return S;
David Chisnall950a9512009-11-17 19:33:30 +00006233}
6234
John McCall843dfcc2016-11-29 21:57:00 +00006235std::string
6236ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const {
6237 std::string S;
David Chisnall50e4eba2010-12-30 14:05:53 +00006238 // Encode result type.
Alp Toker314cc812014-01-25 16:55:45 +00006239 getObjCEncodingForType(Decl->getReturnType(), S);
David Chisnall50e4eba2010-12-30 14:05:53 +00006240 CharUnits ParmOffset;
6241 // Compute size of all parameters.
David Majnemer59f77922016-06-24 04:05:48 +00006242 for (auto PI : Decl->parameters()) {
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00006243 QualType PType = PI->getType();
David Chisnall50e4eba2010-12-30 14:05:53 +00006244 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00006245 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00006246 continue;
Fangrui Song6907ce22018-07-30 19:24:48 +00006247
6248 assert(sz.isPositive() &&
John McCall843dfcc2016-11-29 21:57:00 +00006249 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00006250 ParmOffset += sz;
6251 }
6252 S += charUnitsToString(ParmOffset);
6253 ParmOffset = CharUnits::Zero();
6254
6255 // Argument types.
David Majnemer59f77922016-06-24 04:05:48 +00006256 for (auto PVDecl : Decl->parameters()) {
David Chisnall50e4eba2010-12-30 14:05:53 +00006257 QualType PType = PVDecl->getOriginalType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00006258 if (const auto *AT =
6259 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
David Chisnall50e4eba2010-12-30 14:05:53 +00006260 // Use array's original type only if it has known number of
6261 // elements.
6262 if (!isa<ConstantArrayType>(AT))
6263 PType = PVDecl->getType();
6264 } else if (PType->isFunctionType())
6265 PType = PVDecl->getType();
6266 getObjCEncodingForType(PType, S);
6267 S += charUnitsToString(ParmOffset);
6268 ParmOffset += getObjCEncodingTypeSize(PType);
6269 }
Fangrui Song6907ce22018-07-30 19:24:48 +00006270
John McCall843dfcc2016-11-29 21:57:00 +00006271 return S;
David Chisnall50e4eba2010-12-30 14:05:53 +00006272}
6273
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006274/// getObjCEncodingForMethodParameter - Return the encoded type for a single
Fangrui Song6907ce22018-07-30 19:24:48 +00006275/// method parameter or return type. If Extended, include class names and
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006276/// block object types.
6277void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
6278 QualType T, std::string& S,
6279 bool Extended) const {
6280 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
6281 getObjCEncodingForTypeQualifier(QT, S);
6282 // Encode parameter type.
Craig Topper36250ad2014-05-12 05:36:57 +00006283 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006284 true /*OutermostType*/,
Fangrui Song6907ce22018-07-30 19:24:48 +00006285 false /*EncodingProperty*/,
6286 false /*StructField*/,
6287 Extended /*EncodeBlockParameters*/,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006288 Extended /*EncodeClassNames*/);
6289}
6290
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006291/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006292/// declaration.
John McCall843dfcc2016-11-29 21:57:00 +00006293std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
6294 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00006295 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006296 // Encode return type.
John McCall843dfcc2016-11-29 21:57:00 +00006297 std::string S;
Alp Toker314cc812014-01-25 16:55:45 +00006298 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
6299 Decl->getReturnType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006300 // Compute size of all parameters.
6301 // Start with computing size of a pointer in number of bytes.
6302 // FIXME: There might(should) be a better way of doing this computation!
Ken Dyck40775002010-01-11 17:06:35 +00006303 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006304 // The first two arguments (self and _cmd) are pointers; account for
6305 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00006306 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00006307 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00006308 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00006309 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00006310 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00006311 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00006312 continue;
Fangrui Song6907ce22018-07-30 19:24:48 +00006313
6314 assert(sz.isPositive() &&
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00006315 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006316 ParmOffset += sz;
6317 }
Ken Dyck40775002010-01-11 17:06:35 +00006318 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006319 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00006320 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00006321
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006322 // Argument types.
6323 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00006324 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00006325 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00006326 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00006327 QualType PType = PVDecl->getOriginalType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00006328 if (const auto *AT =
6329 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
Steve Naroffe4e55d22009-04-14 00:03:58 +00006330 // Use array's original type only if it has known number of
6331 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00006332 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00006333 PType = PVDecl->getType();
6334 } else if (PType->isFunctionType())
6335 PType = PVDecl->getType();
Fangrui Song6907ce22018-07-30 19:24:48 +00006336 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006337 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00006338 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00006339 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006340 }
Fangrui Song6907ce22018-07-30 19:24:48 +00006341
John McCall843dfcc2016-11-29 21:57:00 +00006342 return S;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006343}
6344
Fariborz Jahaniandad96302014-01-22 19:02:20 +00006345ObjCPropertyImplDecl *
6346ASTContext::getObjCPropertyImplDeclForPropertyDecl(
6347 const ObjCPropertyDecl *PD,
6348 const Decl *Container) const {
6349 if (!Container)
Craig Topper36250ad2014-05-12 05:36:57 +00006350 return nullptr;
Eugene Zelenko7855e772018-04-03 00:11:50 +00006351 if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) {
Aaron Ballmand85eff42014-03-14 15:02:45 +00006352 for (auto *PID : CID->property_impls())
6353 if (PID->getPropertyDecl() == PD)
6354 return PID;
Craig Topper36250ad2014-05-12 05:36:57 +00006355 } else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006356 const auto *OID = cast<ObjCImplementationDecl>(Container);
Craig Topper36250ad2014-05-12 05:36:57 +00006357 for (auto *PID : OID->property_impls())
6358 if (PID->getPropertyDecl() == PD)
6359 return PID;
6360 }
6361 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00006362}
6363
Daniel Dunbar4932b362008-08-28 04:38:10 +00006364/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00006365/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00006366/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
6367/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00006368/// Property attributes are stored as a comma-delimited C string. The simple
6369/// attributes readonly and bycopy are encoded as single characters. The
6370/// parametrized attributes, getter=name, setter=name, and ivar=name, are
6371/// encoded as single characters, followed by an identifier. Property types
6372/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00006373/// these attributes are defined by the following enumeration:
6374/// @code
6375/// enum PropertyAttributes {
6376/// kPropertyReadOnly = 'R', // property is read-only.
6377/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
6378/// kPropertyByref = '&', // property is a reference to the value last assigned
6379/// kPropertyDynamic = 'D', // property is dynamic
6380/// kPropertyGetter = 'G', // followed by getter selector name
6381/// kPropertySetter = 'S', // followed by setter selector name
6382/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00006383/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00006384/// kPropertyWeak = 'W' // 'weak' property
6385/// kPropertyStrong = 'P' // property GC'able
6386/// kPropertyNonAtomic = 'N' // property non-atomic
6387/// };
6388/// @endcode
John McCall843dfcc2016-11-29 21:57:00 +00006389std::string
6390ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
6391 const Decl *Container) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00006392 // Collect information from the property implementation decl(s).
6393 bool Dynamic = false;
Craig Topper36250ad2014-05-12 05:36:57 +00006394 ObjCPropertyImplDecl *SynthesizePID = nullptr;
Daniel Dunbar4932b362008-08-28 04:38:10 +00006395
Fariborz Jahaniandad96302014-01-22 19:02:20 +00006396 if (ObjCPropertyImplDecl *PropertyImpDecl =
6397 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
6398 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
6399 Dynamic = true;
6400 else
6401 SynthesizePID = PropertyImpDecl;
Daniel Dunbar4932b362008-08-28 04:38:10 +00006402 }
6403
6404 // FIXME: This is not very efficient.
John McCall843dfcc2016-11-29 21:57:00 +00006405 std::string S = "T";
Daniel Dunbar4932b362008-08-28 04:38:10 +00006406
6407 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00006408 // GCC has some special rules regarding encoding of properties which
6409 // closely resembles encoding of ivars.
Joe Groff98ac7d22014-07-07 22:25:15 +00006410 getObjCEncodingForPropertyType(PD->getType(), S);
Daniel Dunbar4932b362008-08-28 04:38:10 +00006411
6412 if (PD->isReadOnly()) {
6413 S += ",R";
Nico Weber4e8626f2013-05-08 23:47:40 +00006414 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
6415 S += ",C";
6416 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
6417 S += ",&";
Fariborz Jahanian33079ee2014-04-02 22:49:42 +00006418 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
6419 S += ",W";
Daniel Dunbar4932b362008-08-28 04:38:10 +00006420 } else {
6421 switch (PD->getSetterKind()) {
6422 case ObjCPropertyDecl::Assign: break;
6423 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00006424 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00006425 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00006426 }
6427 }
6428
6429 // It really isn't clear at all what this means, since properties
6430 // are "dynamic by default".
6431 if (Dynamic)
6432 S += ",D";
6433
Fariborz Jahanian218c6302009-01-20 19:14:18 +00006434 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
6435 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00006436
Daniel Dunbar4932b362008-08-28 04:38:10 +00006437 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
6438 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00006439 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00006440 }
6441
6442 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
6443 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00006444 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00006445 }
6446
6447 if (SynthesizePID) {
6448 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
6449 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00006450 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00006451 }
6452
6453 // FIXME: OBJCGC: weak & strong
John McCall843dfcc2016-11-29 21:57:00 +00006454 return S;
Daniel Dunbar4932b362008-08-28 04:38:10 +00006455}
6456
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006457/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00006458/// Another legacy compatibility encoding: 32-bit longs are encoded as
6459/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006460/// 'i' or 'I' instead if encoding a struct field, or a pointer!
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006461void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00006462 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006463 if (const auto *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00006464 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006465 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00006466 else
Jay Foad39c79802011-01-12 09:06:06 +00006467 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006468 PointeeTy = IntTy;
6469 }
6470 }
6471}
6472
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00006473void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006474 const FieldDecl *Field,
6475 QualType *NotEncodedT) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00006476 // We follow the behavior of gcc, expanding structures which are
6477 // directly pointed to, and expanding embedded structures. Note that
6478 // these rules are sufficient to prevent recursive encoding of the
6479 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00006480 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006481 true /* outermost type */, false, false,
6482 false, false, false, NotEncodedT);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00006483}
6484
Joe Groff98ac7d22014-07-07 22:25:15 +00006485void ASTContext::getObjCEncodingForPropertyType(QualType T,
6486 std::string& S) const {
6487 // Encode result type.
6488 // GCC has some special rules regarding encoding of properties which
6489 // closely resembles encoding of ivars.
6490 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
6491 true /* outermost type */,
6492 true /* encoding property */);
6493}
6494
John McCall393a78d2012-12-20 02:45:14 +00006495static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
6496 BuiltinType::Kind kind) {
6497 switch (kind) {
David Chisnallb190a2c2010-06-04 01:10:52 +00006498 case BuiltinType::Void: return 'v';
6499 case BuiltinType::Bool: return 'B';
Richard Smith3a8244d2018-05-01 05:02:45 +00006500 case BuiltinType::Char8:
David Chisnallb190a2c2010-06-04 01:10:52 +00006501 case BuiltinType::Char_U:
6502 case BuiltinType::UChar: return 'C';
John McCall393a78d2012-12-20 02:45:14 +00006503 case BuiltinType::Char16:
David Chisnallb190a2c2010-06-04 01:10:52 +00006504 case BuiltinType::UShort: return 'S';
John McCall393a78d2012-12-20 02:45:14 +00006505 case BuiltinType::Char32:
David Chisnallb190a2c2010-06-04 01:10:52 +00006506 case BuiltinType::UInt: return 'I';
6507 case BuiltinType::ULong:
John McCall393a78d2012-12-20 02:45:14 +00006508 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00006509 case BuiltinType::UInt128: return 'T';
6510 case BuiltinType::ULongLong: return 'Q';
6511 case BuiltinType::Char_S:
6512 case BuiltinType::SChar: return 'c';
6513 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00006514 case BuiltinType::WChar_S:
6515 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00006516 case BuiltinType::Int: return 'i';
6517 case BuiltinType::Long:
John McCall393a78d2012-12-20 02:45:14 +00006518 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00006519 case BuiltinType::LongLong: return 'q';
6520 case BuiltinType::Int128: return 't';
6521 case BuiltinType::Float: return 'f';
6522 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00006523 case BuiltinType::LongDouble: return 'D';
John McCall393a78d2012-12-20 02:45:14 +00006524 case BuiltinType::NullPtr: return '*'; // like char*
6525
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00006526 case BuiltinType::Float16:
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00006527 case BuiltinType::Float128:
John McCall393a78d2012-12-20 02:45:14 +00006528 case BuiltinType::Half:
Leonard Chanf921d852018-06-04 16:07:52 +00006529 case BuiltinType::ShortAccum:
6530 case BuiltinType::Accum:
6531 case BuiltinType::LongAccum:
6532 case BuiltinType::UShortAccum:
6533 case BuiltinType::UAccum:
6534 case BuiltinType::ULongAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00006535 case BuiltinType::ShortFract:
6536 case BuiltinType::Fract:
6537 case BuiltinType::LongFract:
6538 case BuiltinType::UShortFract:
6539 case BuiltinType::UFract:
6540 case BuiltinType::ULongFract:
6541 case BuiltinType::SatShortAccum:
6542 case BuiltinType::SatAccum:
6543 case BuiltinType::SatLongAccum:
6544 case BuiltinType::SatUShortAccum:
6545 case BuiltinType::SatUAccum:
6546 case BuiltinType::SatULongAccum:
6547 case BuiltinType::SatShortFract:
6548 case BuiltinType::SatFract:
6549 case BuiltinType::SatLongFract:
6550 case BuiltinType::SatUShortFract:
6551 case BuiltinType::SatUFract:
6552 case BuiltinType::SatULongFract:
John McCall393a78d2012-12-20 02:45:14 +00006553 // FIXME: potentially need @encodes for these!
6554 return ' ';
6555
6556 case BuiltinType::ObjCId:
6557 case BuiltinType::ObjCClass:
6558 case BuiltinType::ObjCSel:
6559 llvm_unreachable("@encoding ObjC primitive type");
6560
6561 // OpenCL and placeholder types don't need @encodings.
Alexey Bader954ba212016-04-08 13:40:33 +00006562#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6563 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00006564#include "clang/Basic/OpenCLImageTypes.def"
Andrew Savonichev3fee3512018-11-08 11:25:41 +00006565#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6566 case BuiltinType::Id:
6567#include "clang/Basic/OpenCLExtensionTypes.def"
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006568 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00006569 case BuiltinType::OCLClkEvent:
6570 case BuiltinType::OCLQueue:
Alexey Bader9c8453f2015-09-15 11:18:52 +00006571 case BuiltinType::OCLReserveID:
Guy Benyei61054192013-02-07 10:55:47 +00006572 case BuiltinType::OCLSampler:
John McCall393a78d2012-12-20 02:45:14 +00006573 case BuiltinType::Dependent:
6574#define BUILTIN_TYPE(KIND, ID)
6575#define PLACEHOLDER_TYPE(KIND, ID) \
6576 case BuiltinType::KIND:
6577#include "clang/AST/BuiltinTypes.def"
6578 llvm_unreachable("invalid builtin type for @encode");
David Chisnallb190a2c2010-06-04 01:10:52 +00006579 }
David Blaikie5a6a0202013-01-09 17:48:41 +00006580 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnallb190a2c2010-06-04 01:10:52 +00006581}
6582
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006583static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
6584 EnumDecl *Enum = ET->getDecl();
Fangrui Song6907ce22018-07-30 19:24:48 +00006585
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006586 // The encoding of an non-fixed enum type is always 'i', regardless of size.
6587 if (!Enum->isFixed())
6588 return 'i';
Fangrui Song6907ce22018-07-30 19:24:48 +00006589
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006590 // The encoding of a fixed enum type matches its fixed underlying type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00006591 const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>();
John McCall393a78d2012-12-20 02:45:14 +00006592 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006593}
6594
Jay Foad39c79802011-01-12 09:06:06 +00006595static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00006596 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00006597 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00006598 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00006599 // The NeXT runtime encodes bit fields as b followed by the number of bits.
6600 // The GNU runtime requires more information; bitfields are encoded as b,
6601 // then the offset (in bits) of the first element, then the type of the
6602 // bitfield, then the size in bits. For example, in this structure:
6603 //
6604 // struct
6605 // {
6606 // int integer;
6607 // int flags:2;
6608 // };
6609 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
6610 // runtime, but b32i2 for the GNU runtime. The reason for this extra
6611 // information is not especially sensible, but we're stuck with it for
6612 // compatibility with GCC, although providing it breaks anything that
6613 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00006614 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
Akira Hatanaka4b1c4842017-06-27 04:34:04 +00006615 uint64_t Offset;
6616
6617 if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) {
6618 Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), nullptr,
6619 IVD);
6620 } else {
6621 const RecordDecl *RD = FD->getParent();
6622 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
6623 Offset = RL.getFieldOffset(FD->getFieldIndex());
6624 }
6625
6626 S += llvm::utostr(Offset);
6627
Eugene Zelenko7855e772018-04-03 00:11:50 +00006628 if (const auto *ET = T->getAs<EnumType>())
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006629 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall393a78d2012-12-20 02:45:14 +00006630 else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006631 const auto *BT = T->castAs<BuiltinType>();
John McCall393a78d2012-12-20 02:45:14 +00006632 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
6633 }
David Chisnallb190a2c2010-06-04 01:10:52 +00006634 }
Richard Smithcaf33902011-10-10 18:28:20 +00006635 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00006636}
6637
Daniel Dunbar07d07852009-10-18 21:17:35 +00006638// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00006639void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
6640 bool ExpandPointedToStructures,
6641 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00006642 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00006643 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006644 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006645 bool StructField,
6646 bool EncodeBlockParameters,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00006647 bool EncodeClassNames,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006648 bool EncodePointerToObjCTypedef,
6649 QualType *NotEncodedT) const {
John McCall393a78d2012-12-20 02:45:14 +00006650 CanQualType CT = getCanonicalType(T);
6651 switch (CT->getTypeClass()) {
6652 case Type::Builtin:
6653 case Type::Enum:
Chris Lattnere7cabb92009-07-13 00:10:46 +00006654 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00006655 return EncodeBitField(this, S, T, FD);
Eugene Zelenko7855e772018-04-03 00:11:50 +00006656 if (const auto *BT = dyn_cast<BuiltinType>(CT))
John McCall393a78d2012-12-20 02:45:14 +00006657 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
6658 else
6659 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnere7cabb92009-07-13 00:10:46 +00006660 return;
Mike Stump11289f42009-09-09 15:08:12 +00006661
John McCall393a78d2012-12-20 02:45:14 +00006662 case Type::Complex: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006663 const auto *CT = T->castAs<ComplexType>();
Anders Carlsson39b2e132009-04-09 21:55:45 +00006664 S += 'j';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006665 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, nullptr);
Chris Lattnere7cabb92009-07-13 00:10:46 +00006666 return;
6667 }
John McCall393a78d2012-12-20 02:45:14 +00006668
6669 case Type::Atomic: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006670 const auto *AT = T->castAs<AtomicType>();
John McCall393a78d2012-12-20 02:45:14 +00006671 S += 'A';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006672 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, nullptr);
John McCall393a78d2012-12-20 02:45:14 +00006673 return;
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00006674 }
John McCall393a78d2012-12-20 02:45:14 +00006675
6676 // encoding for pointer or reference types.
6677 case Type::Pointer:
6678 case Type::LValueReference:
6679 case Type::RValueReference: {
6680 QualType PointeeTy;
6681 if (isa<PointerType>(CT)) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006682 const auto *PT = T->castAs<PointerType>();
John McCall393a78d2012-12-20 02:45:14 +00006683 if (PT->isObjCSelType()) {
6684 S += ':';
6685 return;
6686 }
6687 PointeeTy = PT->getPointeeType();
6688 } else {
6689 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
6690 }
6691
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006692 bool isReadOnly = false;
6693 // For historical/compatibility reasons, the read-only qualifier of the
6694 // pointee gets emitted _before_ the '^'. The read-only qualifier of
6695 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00006696 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00006697 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006698 if (OutermostType && T.isConstQualified()) {
6699 isReadOnly = true;
6700 S += 'r';
6701 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00006702 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006703 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006704 while (P->getAs<PointerType>())
6705 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006706 if (P.isConstQualified()) {
6707 isReadOnly = true;
6708 S += 'r';
6709 }
6710 }
6711 if (isReadOnly) {
6712 // Another legacy compatibility encoding. Some ObjC qualifier and type
6713 // combinations need to be rearranged.
6714 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006715 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00006716 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006717 }
Mike Stump11289f42009-09-09 15:08:12 +00006718
Anders Carlssond8499822007-10-29 05:01:08 +00006719 if (PointeeTy->isCharType()) {
6720 // char pointer types should be encoded as '*' unless it is a
6721 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00006722 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00006723 S += '*';
6724 return;
6725 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00006726 } else if (const auto *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00006727 // GCC binary compat: Need to convert "struct objc_class *" to "#".
6728 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
6729 S += '#';
6730 return;
6731 }
6732 // GCC binary compat: Need to convert "struct objc_object *" to "@".
6733 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
6734 S += '@';
6735 return;
6736 }
6737 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00006738 }
Anders Carlssond8499822007-10-29 05:01:08 +00006739 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006740 getLegacyIntegralTypeEncoding(PointeeTy);
6741
Mike Stump11289f42009-09-09 15:08:12 +00006742 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006743 nullptr, false, false, false, false, false, false,
6744 NotEncodedT);
Chris Lattnere7cabb92009-07-13 00:10:46 +00006745 return;
6746 }
John McCall393a78d2012-12-20 02:45:14 +00006747
6748 case Type::ConstantArray:
6749 case Type::IncompleteArray:
6750 case Type::VariableArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006751 const auto *AT = cast<ArrayType>(CT);
John McCall393a78d2012-12-20 02:45:14 +00006752
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006753 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00006754 // Incomplete arrays are encoded as a pointer to the array element.
6755 S += '^';
6756
Mike Stump11289f42009-09-09 15:08:12 +00006757 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00006758 false, ExpandStructures, FD);
6759 } else {
6760 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00006761
Eugene Zelenko7855e772018-04-03 00:11:50 +00006762 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
Fariborz Jahanianf0dc11a2013-06-04 16:04:37 +00006763 S += llvm::utostr(CAT->getSize().getZExtValue());
6764 else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00006765 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006766 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
6767 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00006768 S += '0';
6769 }
Mike Stump11289f42009-09-09 15:08:12 +00006770
6771 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006772 false, ExpandStructures, FD,
6773 false, false, false, false, false, false,
6774 NotEncodedT);
Anders Carlssond05f44b2009-02-22 01:38:57 +00006775 S += ']';
6776 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006777 return;
6778 }
Mike Stump11289f42009-09-09 15:08:12 +00006779
John McCall393a78d2012-12-20 02:45:14 +00006780 case Type::FunctionNoProto:
6781 case Type::FunctionProto:
Anders Carlssondf4cc612007-10-30 00:06:20 +00006782 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00006783 return;
Mike Stump11289f42009-09-09 15:08:12 +00006784
John McCall393a78d2012-12-20 02:45:14 +00006785 case Type::Record: {
6786 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00006787 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00006788 // Anonymous structures print as '?'
6789 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
6790 S += II->getName();
Eugene Zelenko7855e772018-04-03 00:11:50 +00006791 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
Fariborz Jahanianc5158202010-05-07 00:28:49 +00006792 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00006793 llvm::raw_string_ostream OS(S);
Serge Pavlov03e672c2017-11-28 16:14:14 +00006794 printTemplateArgumentList(OS, TemplateArgs.asArray(),
6795 getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00006796 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00006797 } else {
6798 S += '?';
6799 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00006800 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00006801 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006802 if (!RDecl->isUnion()) {
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006803 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006804 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006805 for (const auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006806 if (FD) {
6807 S += '"';
6808 S += Field->getNameAsString();
6809 S += '"';
6810 }
Mike Stump11289f42009-09-09 15:08:12 +00006811
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006812 // Special case bit-fields.
6813 if (Field->isBitField()) {
6814 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006815 Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006816 } else {
6817 QualType qt = Field->getType();
6818 getLegacyIntegralTypeEncoding(qt);
6819 getObjCEncodingForTypeImpl(qt, S, false, true,
6820 FD, /*OutermostType*/false,
6821 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006822 /*StructField*/true,
6823 false, false, false, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006824 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00006825 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00006826 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00006827 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00006828 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00006829 return;
6830 }
Mike Stump11289f42009-09-09 15:08:12 +00006831
John McCall393a78d2012-12-20 02:45:14 +00006832 case Type::BlockPointer: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006833 const auto *BT = T->castAs<BlockPointerType>();
Steve Naroff49140cb2009-02-02 18:24:29 +00006834 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006835 if (EncodeBlockParameters) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006836 const auto *FT = BT->getPointeeType()->castAs<FunctionType>();
Fangrui Song6907ce22018-07-30 19:24:48 +00006837
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006838 S += '<';
6839 // Block return type
Alp Toker314cc812014-01-25 16:55:45 +00006840 getObjCEncodingForTypeImpl(
6841 FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures,
6842 FD, false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006843 false /* StructField */, EncodeBlockParameters, EncodeClassNames, false,
6844 NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006845 // Block self
6846 S += "@?";
6847 // Block parameters
Eugene Zelenko7855e772018-04-03 00:11:50 +00006848 if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00006849 for (const auto &I : FPT->param_types())
6850 getObjCEncodingForTypeImpl(
6851 I, S, ExpandPointedToStructures, ExpandStructures, FD,
6852 false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006853 false /* StructField */, EncodeBlockParameters, EncodeClassNames,
6854 false, NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006855 }
6856 S += '>';
6857 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006858 return;
6859 }
Mike Stump11289f42009-09-09 15:08:12 +00006860
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00006861 case Type::ObjCObject: {
6862 // hack to match legacy encoding of *id and *Class
6863 QualType Ty = getObjCObjectPointerType(CT);
6864 if (Ty->isObjCIdType()) {
6865 S += "{objc_object=}";
6866 return;
6867 }
6868 else if (Ty->isObjCClassType()) {
6869 S += "{objc_class=}";
6870 return;
6871 }
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00006872 // TODO: Double check to make sure this intentionally falls through.
Galina Kistanovaf87496d2017-06-03 06:31:42 +00006873 LLVM_FALLTHROUGH;
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00006874 }
Fangrui Song6907ce22018-07-30 19:24:48 +00006875
John McCall393a78d2012-12-20 02:45:14 +00006876 case Type::ObjCInterface: {
6877 // Ignore protocol qualifiers when mangling at this level.
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006878 // @encode(class_name)
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006879 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006880 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006881 S += OI->getObjCRuntimeNameAsString();
Akira Hatanakafd0fb202016-08-17 19:42:22 +00006882 if (ExpandStructures) {
6883 S += '=';
6884 SmallVector<const ObjCIvarDecl*, 32> Ivars;
6885 DeepCollectObjCIvars(OI, true, Ivars);
6886 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
George Burgess IV00f70bd2018-03-01 05:43:23 +00006887 const FieldDecl *Field = Ivars[i];
Akira Hatanakafd0fb202016-08-17 19:42:22 +00006888 if (Field->isBitField())
6889 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
6890 else
6891 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
6892 false, false, false, false, false,
6893 EncodePointerToObjCTypedef,
6894 NotEncodedT);
6895 }
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006896 }
6897 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00006898 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006899 }
Mike Stump11289f42009-09-09 15:08:12 +00006900
John McCall393a78d2012-12-20 02:45:14 +00006901 case Type::ObjCObjectPointer: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006902 const auto *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00006903 if (OPT->isObjCIdType()) {
6904 S += '@';
6905 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00006906 }
Mike Stump11289f42009-09-09 15:08:12 +00006907
Steve Narofff0c86112009-10-28 22:03:49 +00006908 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
6909 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
6910 // Since this is a binary compatibility issue, need to consult with runtime
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00006911 // folks. Fortunately, this is a *very* obscure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00006912 S += '#';
6913 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00006914 }
Mike Stump11289f42009-09-09 15:08:12 +00006915
Chris Lattnere7cabb92009-07-13 00:10:46 +00006916 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00006917 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00006918 ExpandPointedToStructures,
6919 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006920 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00006921 // Note that we do extended encoding of protocol qualifer list
6922 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00006923 S += '"';
Aaron Ballman83731462014-03-17 16:14:00 +00006924 for (const auto *I : OPT->quals()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00006925 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006926 S += I->getObjCRuntimeNameAsString();
Steve Naroff7cae42b2009-07-10 23:34:53 +00006927 S += '>';
6928 }
6929 S += '"';
6930 }
6931 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00006932 }
Mike Stump11289f42009-09-09 15:08:12 +00006933
Chris Lattnere7cabb92009-07-13 00:10:46 +00006934 QualType PointeeTy = OPT->getPointeeType();
6935 if (!EncodingProperty &&
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00006936 isa<TypedefType>(PointeeTy.getTypePtr()) &&
6937 !EncodePointerToObjCTypedef) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00006938 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00006939 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00006940 // {...};
6941 S += '^';
Fariborz Jahanian88890e72013-07-12 16:19:11 +00006942 if (FD && OPT->getInterfaceDecl()) {
Fariborz Jahanianc682ef52013-07-12 16:41:56 +00006943 // Prevent recursive encoding of fields in some rare cases.
Fariborz Jahanian88890e72013-07-12 16:19:11 +00006944 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
6945 SmallVector<const ObjCIvarDecl*, 32> Ivars;
6946 DeepCollectObjCIvars(OI, true, Ivars);
6947 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
George Burgess IV00f70bd2018-03-01 05:43:23 +00006948 if (Ivars[i] == FD) {
Fariborz Jahanian88890e72013-07-12 16:19:11 +00006949 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006950 S += OI->getObjCRuntimeNameAsString();
Fariborz Jahanian88890e72013-07-12 16:19:11 +00006951 S += '}';
6952 return;
6953 }
6954 }
6955 }
Mike Stump11289f42009-09-09 15:08:12 +00006956 getObjCEncodingForTypeImpl(PointeeTy, S,
6957 false, ExpandPointedToStructures,
Craig Topper36250ad2014-05-12 05:36:57 +00006958 nullptr,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00006959 false, false, false, false, false,
6960 /*EncodePointerToObjCTypedef*/true);
Steve Naroff7cae42b2009-07-10 23:34:53 +00006961 return;
6962 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006963
6964 S += '@';
Fangrui Song6907ce22018-07-30 19:24:48 +00006965 if (OPT->getInterfaceDecl() &&
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006966 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00006967 S += '"';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006968 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
Aaron Ballman83731462014-03-17 16:14:00 +00006969 for (const auto *I : OPT->quals()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00006970 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006971 S += I->getObjCRuntimeNameAsString();
Chris Lattnere7cabb92009-07-13 00:10:46 +00006972 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00006973 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006974 S += '"';
6975 }
6976 return;
6977 }
Mike Stump11289f42009-09-09 15:08:12 +00006978
John McCalla9e6e8d2010-05-17 23:56:34 +00006979 // gcc just blithely ignores member pointers.
John McCall393a78d2012-12-20 02:45:14 +00006980 // FIXME: we shoul do better than that. 'M' is available.
6981 case Type::MemberPointer:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006982 // This matches gcc's encoding, even though technically it is insufficient.
6983 //FIXME. We should do a better job than gcc.
John McCall393a78d2012-12-20 02:45:14 +00006984 case Type::Vector:
6985 case Type::ExtVector:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006986 // Until we have a coherent encoding of these three types, issue warning.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00006987 if (NotEncodedT)
6988 *NotEncodedT = T;
6989 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00006990
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006991 // We could see an undeduced auto type here during error recovery.
6992 // Just ignore it.
Richard Smith27d807c2013-04-30 13:56:41 +00006993 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00006994 case Type::DeducedTemplateSpecialization:
Richard Smith27d807c2013-04-30 13:56:41 +00006995 return;
6996
Xiuli Pan9c14e282016-01-09 12:53:17 +00006997 case Type::Pipe:
John McCall393a78d2012-12-20 02:45:14 +00006998#define ABSTRACT_TYPE(KIND, BASE)
6999#define TYPE(KIND, BASE)
7000#define DEPENDENT_TYPE(KIND, BASE) \
7001 case Type::KIND:
7002#define NON_CANONICAL_TYPE(KIND, BASE) \
7003 case Type::KIND:
7004#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
7005 case Type::KIND:
7006#include "clang/AST/TypeNodes.def"
7007 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00007008 }
John McCall393a78d2012-12-20 02:45:14 +00007009 llvm_unreachable("bad type kind!");
Anders Carlssond8499822007-10-29 05:01:08 +00007010}
7011
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007012void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
7013 std::string &S,
7014 const FieldDecl *FD,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00007015 bool includeVBases,
7016 QualType *NotEncodedT) const {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007017 assert(RDecl && "Expected non-null RecordDecl");
7018 assert(!RDecl->isUnion() && "Should not be called for unions");
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00007019 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007020 return;
7021
Eugene Zelenko7855e772018-04-03 00:11:50 +00007022 const auto *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007023 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
7024 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
7025
7026 if (CXXRec) {
Aaron Ballman574705e2014-03-13 15:41:46 +00007027 for (const auto &BI : CXXRec->bases()) {
7028 if (!BI.isVirtual()) {
7029 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00007030 if (base->isEmpty())
7031 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00007032 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007033 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
7034 std::make_pair(offs, base));
7035 }
7036 }
7037 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007038
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007039 unsigned i = 0;
Hans Wennborga302cd92014-08-21 16:06:57 +00007040 for (auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007041 uint64_t offs = layout.getFieldOffset(i);
7042 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Hans Wennborga302cd92014-08-21 16:06:57 +00007043 std::make_pair(offs, Field));
7044 ++i;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007045 }
7046
7047 if (CXXRec && includeVBases) {
Aaron Ballman445a9392014-03-13 16:15:17 +00007048 for (const auto &BI : CXXRec->vbases()) {
7049 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00007050 if (base->isEmpty())
7051 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00007052 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Eli Friedman1d24af82013-09-18 01:59:16 +00007053 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
7054 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00007055 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
7056 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007057 }
7058 }
7059
7060 CharUnits size;
7061 if (CXXRec) {
7062 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
7063 } else {
7064 size = layout.getSize();
7065 }
7066
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007067#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007068 uint64_t CurOffs = 0;
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007069#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007070 std::multimap<uint64_t, NamedDecl *>::iterator
7071 CurLayObj = FieldOrBaseOffsets.begin();
7072
Douglas Gregorf5d6c742012-04-27 22:30:01 +00007073 if (CXXRec && CXXRec->isDynamicClass() &&
7074 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007075 if (FD) {
7076 S += "\"_vptr$";
7077 std::string recname = CXXRec->getNameAsString();
7078 if (recname.empty()) recname = "?";
7079 S += recname;
7080 S += '"';
7081 }
7082 S += "^^?";
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007083#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007084 CurOffs += getTypeSize(VoidPtrTy);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007085#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007086 }
7087
7088 if (!RDecl->hasFlexibleArrayMember()) {
7089 // Mark the end of the structure.
7090 uint64_t offs = toBits(size);
7091 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Craig Topper36250ad2014-05-12 05:36:57 +00007092 std::make_pair(offs, nullptr));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007093 }
7094
7095 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007096#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007097 assert(CurOffs <= CurLayObj->first);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007098 if (CurOffs < CurLayObj->first) {
Fangrui Song6907ce22018-07-30 19:24:48 +00007099 uint64_t padding = CurLayObj->first - CurOffs;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007100 // FIXME: There doesn't seem to be a way to indicate in the encoding that
7101 // packing/alignment of members is different that normal, in which case
7102 // the encoding will be out-of-sync with the real layout.
7103 // If the runtime switches to just consider the size of types without
7104 // taking into account alignment, we could make padding explicit in the
7105 // encoding (e.g. using arrays of chars). The encoding strings would be
7106 // longer then though.
7107 CurOffs += padding;
7108 }
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007109#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007110
7111 NamedDecl *dcl = CurLayObj->second;
Craig Topper36250ad2014-05-12 05:36:57 +00007112 if (!dcl)
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007113 break; // reached end of structure.
7114
Eugene Zelenko7855e772018-04-03 00:11:50 +00007115 if (auto *base = dyn_cast<CXXRecordDecl>(dcl)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007116 // We expand the bases without their virtual bases since those are going
7117 // in the initial structure. Note that this differs from gcc which
7118 // expands virtual bases each time one is encountered in the hierarchy,
7119 // making the encoding type bigger than it really is.
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00007120 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
7121 NotEncodedT);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00007122 assert(!base->isEmpty());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007123#ifndef NDEBUG
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00007124 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007125#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007126 } else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00007127 const auto *field = cast<FieldDecl>(dcl);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007128 if (FD) {
7129 S += '"';
7130 S += field->getNameAsString();
7131 S += '"';
7132 }
7133
7134 if (field->isBitField()) {
7135 EncodeBitField(this, S, field->getType(), field);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007136#ifndef NDEBUG
Richard Smithcaf33902011-10-10 18:28:20 +00007137 CurOffs += field->getBitWidthValue(*this);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007138#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007139 } else {
7140 QualType qt = field->getType();
7141 getLegacyIntegralTypeEncoding(qt);
7142 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
7143 /*OutermostType*/false,
7144 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00007145 /*StructField*/true,
7146 false, false, false, NotEncodedT);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007147#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007148 CurOffs += getTypeSize(field->getType());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007149#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007150 }
7151 }
7152 }
7153}
7154
Mike Stump11289f42009-09-09 15:08:12 +00007155void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00007156 std::string& S) const {
7157 if (QT & Decl::OBJC_TQ_In)
7158 S += 'n';
7159 if (QT & Decl::OBJC_TQ_Inout)
7160 S += 'N';
7161 if (QT & Decl::OBJC_TQ_Out)
7162 S += 'o';
7163 if (QT & Decl::OBJC_TQ_Bycopy)
7164 S += 'O';
7165 if (QT & Decl::OBJC_TQ_Byref)
7166 S += 'R';
7167 if (QT & Decl::OBJC_TQ_Oneway)
7168 S += 'V';
7169}
7170
Douglas Gregor3ea72692011-08-12 05:46:01 +00007171TypedefDecl *ASTContext::getObjCIdDecl() const {
7172 if (!ObjCIdDecl) {
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00007173 QualType T = getObjCObjectType(ObjCBuiltinIdTy, {}, {});
Douglas Gregor3ea72692011-08-12 05:46:01 +00007174 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00007175 ObjCIdDecl = buildImplicitTypedef(T, "id");
Douglas Gregor3ea72692011-08-12 05:46:01 +00007176 }
Douglas Gregor3ea72692011-08-12 05:46:01 +00007177 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00007178}
7179
Douglas Gregor52e02802011-08-12 06:17:30 +00007180TypedefDecl *ASTContext::getObjCSelDecl() const {
7181 if (!ObjCSelDecl) {
Alp Toker56b5cc92013-12-15 10:36:26 +00007182 QualType T = getPointerType(ObjCBuiltinSelTy);
7183 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
Douglas Gregor52e02802011-08-12 06:17:30 +00007184 }
7185 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00007186}
7187
Douglas Gregor0a586182011-08-12 05:59:41 +00007188TypedefDecl *ASTContext::getObjCClassDecl() const {
7189 if (!ObjCClassDecl) {
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00007190 QualType T = getObjCObjectType(ObjCBuiltinClassTy, {}, {});
Douglas Gregor0a586182011-08-12 05:59:41 +00007191 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00007192 ObjCClassDecl = buildImplicitTypedef(T, "Class");
Douglas Gregor0a586182011-08-12 05:59:41 +00007193 }
Douglas Gregor0a586182011-08-12 05:59:41 +00007194 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00007195}
7196
Douglas Gregord53ae832012-01-17 18:09:05 +00007197ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
7198 if (!ObjCProtocolClassDecl) {
Fangrui Song6907ce22018-07-30 19:24:48 +00007199 ObjCProtocolClassDecl
7200 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
Douglas Gregord53ae832012-01-17 18:09:05 +00007201 SourceLocation(),
7202 &Idents.get("Protocol"),
Douglas Gregor85f3f952015-07-07 03:57:15 +00007203 /*typeParamList=*/nullptr,
Craig Topper36250ad2014-05-12 05:36:57 +00007204 /*PrevDecl=*/nullptr,
Fangrui Song6907ce22018-07-30 19:24:48 +00007205 SourceLocation(), true);
Douglas Gregord53ae832012-01-17 18:09:05 +00007206 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007207
Douglas Gregord53ae832012-01-17 18:09:05 +00007208 return ObjCProtocolClassDecl;
7209}
7210
Meador Inge5d3fb222012-06-16 03:34:49 +00007211//===----------------------------------------------------------------------===//
7212// __builtin_va_list Construction Functions
7213//===----------------------------------------------------------------------===//
7214
Charles Davisc7d5c942015-09-17 20:55:33 +00007215static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context,
7216 StringRef Name) {
7217 // typedef char* __builtin[_ms]_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00007218 QualType T = Context->getPointerType(Context->CharTy);
Charles Davisc7d5c942015-09-17 20:55:33 +00007219 return Context->buildImplicitTypedef(T, Name);
7220}
7221
7222static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
7223 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
7224}
7225
7226static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
7227 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007228}
7229
7230static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
7231 // typedef void* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00007232 QualType T = Context->getPointerType(Context->VoidTy);
7233 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007234}
7235
Tim Northover9bb857a2013-01-31 12:13:10 +00007236static TypedefDecl *
7237CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00007238 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00007239 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00007240 if (Context->getLangOpts().CPlusPlus) {
7241 // namespace std { struct __va_list {
7242 NamespaceDecl *NS;
7243 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
7244 Context->getTranslationUnitDecl(),
Craig Topper36250ad2014-05-12 05:36:57 +00007245 /*Inline*/ false, SourceLocation(),
Tim Northover9bb857a2013-01-31 12:13:10 +00007246 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00007247 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00007248 NS->setImplicit();
Tim Northover9bb857a2013-01-31 12:13:10 +00007249 VaListTagDecl->setDeclContext(NS);
Tim Northover9bb857a2013-01-31 12:13:10 +00007250 }
7251
7252 VaListTagDecl->startDefinition();
7253
7254 const size_t NumFields = 5;
7255 QualType FieldTypes[NumFields];
7256 const char *FieldNames[NumFields];
7257
7258 // void *__stack;
7259 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
7260 FieldNames[0] = "__stack";
7261
7262 // void *__gr_top;
7263 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
7264 FieldNames[1] = "__gr_top";
7265
7266 // void *__vr_top;
7267 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
7268 FieldNames[2] = "__vr_top";
7269
7270 // int __gr_offs;
7271 FieldTypes[3] = Context->IntTy;
7272 FieldNames[3] = "__gr_offs";
7273
7274 // int __vr_offs;
7275 FieldTypes[4] = Context->IntTy;
7276 FieldNames[4] = "__vr_offs";
7277
7278 // Create fields
7279 for (unsigned i = 0; i < NumFields; ++i) {
7280 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7281 VaListTagDecl,
7282 SourceLocation(),
7283 SourceLocation(),
7284 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00007285 FieldTypes[i], /*TInfo=*/nullptr,
7286 /*BitWidth=*/nullptr,
Tim Northover9bb857a2013-01-31 12:13:10 +00007287 /*Mutable=*/false,
7288 ICIS_NoInit);
7289 Field->setAccess(AS_public);
7290 VaListTagDecl->addDecl(Field);
7291 }
7292 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00007293 Context->VaListTagDecl = VaListTagDecl;
Tim Northover9bb857a2013-01-31 12:13:10 +00007294 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Tim Northover9bb857a2013-01-31 12:13:10 +00007295
7296 // } __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00007297 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00007298}
7299
Meador Inge5d3fb222012-06-16 03:34:49 +00007300static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
7301 // typedef struct __va_list_tag {
7302 RecordDecl *VaListTagDecl;
7303
Alp Toker2dea15b2013-12-17 01:22:38 +00007304 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00007305 VaListTagDecl->startDefinition();
7306
7307 const size_t NumFields = 5;
7308 QualType FieldTypes[NumFields];
7309 const char *FieldNames[NumFields];
7310
7311 // unsigned char gpr;
7312 FieldTypes[0] = Context->UnsignedCharTy;
7313 FieldNames[0] = "gpr";
7314
7315 // unsigned char fpr;
7316 FieldTypes[1] = Context->UnsignedCharTy;
7317 FieldNames[1] = "fpr";
7318
7319 // unsigned short reserved;
7320 FieldTypes[2] = Context->UnsignedShortTy;
7321 FieldNames[2] = "reserved";
7322
7323 // void* overflow_arg_area;
7324 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
7325 FieldNames[3] = "overflow_arg_area";
7326
7327 // void* reg_save_area;
7328 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
7329 FieldNames[4] = "reg_save_area";
7330
7331 // Create fields
7332 for (unsigned i = 0; i < NumFields; ++i) {
7333 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
7334 SourceLocation(),
7335 SourceLocation(),
7336 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00007337 FieldTypes[i], /*TInfo=*/nullptr,
7338 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00007339 /*Mutable=*/false,
7340 ICIS_NoInit);
7341 Field->setAccess(AS_public);
7342 VaListTagDecl->addDecl(Field);
7343 }
7344 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00007345 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00007346 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
7347
7348 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00007349 TypedefDecl *VaListTagTypedefDecl =
7350 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
7351
Meador Inge5d3fb222012-06-16 03:34:49 +00007352 QualType VaListTagTypedefType =
7353 Context->getTypedefType(VaListTagTypedefDecl);
7354
7355 // typedef __va_list_tag __builtin_va_list[1];
7356 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
7357 QualType VaListTagArrayType
7358 = Context->getConstantArrayType(VaListTagTypedefType,
7359 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00007360 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007361}
7362
7363static TypedefDecl *
7364CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00007365 // struct __va_list_tag {
Meador Inge5d3fb222012-06-16 03:34:49 +00007366 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00007367 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00007368 VaListTagDecl->startDefinition();
7369
7370 const size_t NumFields = 4;
7371 QualType FieldTypes[NumFields];
7372 const char *FieldNames[NumFields];
7373
7374 // unsigned gp_offset;
7375 FieldTypes[0] = Context->UnsignedIntTy;
7376 FieldNames[0] = "gp_offset";
7377
7378 // unsigned fp_offset;
7379 FieldTypes[1] = Context->UnsignedIntTy;
7380 FieldNames[1] = "fp_offset";
7381
7382 // void* overflow_arg_area;
7383 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
7384 FieldNames[2] = "overflow_arg_area";
7385
7386 // void* reg_save_area;
7387 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
7388 FieldNames[3] = "reg_save_area";
7389
7390 // Create fields
7391 for (unsigned i = 0; i < NumFields; ++i) {
7392 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7393 VaListTagDecl,
7394 SourceLocation(),
7395 SourceLocation(),
7396 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00007397 FieldTypes[i], /*TInfo=*/nullptr,
7398 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00007399 /*Mutable=*/false,
7400 ICIS_NoInit);
7401 Field->setAccess(AS_public);
7402 VaListTagDecl->addDecl(Field);
7403 }
7404 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00007405 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00007406 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
7407
Richard Smith9b88a4c2015-07-27 05:40:23 +00007408 // };
Alp Toker56b5cc92013-12-15 10:36:26 +00007409
Richard Smith9b88a4c2015-07-27 05:40:23 +00007410 // typedef struct __va_list_tag __builtin_va_list[1];
Meador Inge5d3fb222012-06-16 03:34:49 +00007411 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00007412 QualType VaListTagArrayType =
7413 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00007414 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007415}
7416
7417static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
7418 // typedef int __builtin_va_list[4];
7419 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
Yaron Kerene0bcdd42016-10-08 06:45:10 +00007420 QualType IntArrayType =
7421 Context->getConstantArrayType(Context->IntTy, Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00007422 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007423}
7424
Logan Chien57086ce2012-10-10 06:56:20 +00007425static TypedefDecl *
7426CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00007427 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00007428 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00007429 if (Context->getLangOpts().CPlusPlus) {
7430 // namespace std { struct __va_list {
7431 NamespaceDecl *NS;
7432 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
7433 Context->getTranslationUnitDecl(),
7434 /*Inline*/false, SourceLocation(),
7435 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00007436 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00007437 NS->setImplicit();
Logan Chien57086ce2012-10-10 06:56:20 +00007438 VaListDecl->setDeclContext(NS);
Logan Chien57086ce2012-10-10 06:56:20 +00007439 }
7440
7441 VaListDecl->startDefinition();
7442
7443 // void * __ap;
7444 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7445 VaListDecl,
7446 SourceLocation(),
7447 SourceLocation(),
7448 &Context->Idents.get("__ap"),
7449 Context->getPointerType(Context->VoidTy),
Craig Topper36250ad2014-05-12 05:36:57 +00007450 /*TInfo=*/nullptr,
7451 /*BitWidth=*/nullptr,
Logan Chien57086ce2012-10-10 06:56:20 +00007452 /*Mutable=*/false,
7453 ICIS_NoInit);
7454 Field->setAccess(AS_public);
7455 VaListDecl->addDecl(Field);
7456
7457 // };
7458 VaListDecl->completeDefinition();
Oleg Ranevskyyb88d2472016-03-30 21:30:30 +00007459 Context->VaListTagDecl = VaListDecl;
Logan Chien57086ce2012-10-10 06:56:20 +00007460
7461 // typedef struct __va_list __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00007462 QualType T = Context->getRecordType(VaListDecl);
7463 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00007464}
7465
Ulrich Weigand47445072013-05-06 16:26:41 +00007466static TypedefDecl *
7467CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00007468 // struct __va_list_tag {
Ulrich Weigand47445072013-05-06 16:26:41 +00007469 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00007470 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00007471 VaListTagDecl->startDefinition();
7472
7473 const size_t NumFields = 4;
7474 QualType FieldTypes[NumFields];
7475 const char *FieldNames[NumFields];
7476
7477 // long __gpr;
7478 FieldTypes[0] = Context->LongTy;
7479 FieldNames[0] = "__gpr";
7480
7481 // long __fpr;
7482 FieldTypes[1] = Context->LongTy;
7483 FieldNames[1] = "__fpr";
7484
7485 // void *__overflow_arg_area;
7486 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
7487 FieldNames[2] = "__overflow_arg_area";
7488
7489 // void *__reg_save_area;
7490 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
7491 FieldNames[3] = "__reg_save_area";
7492
7493 // Create fields
7494 for (unsigned i = 0; i < NumFields; ++i) {
7495 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7496 VaListTagDecl,
7497 SourceLocation(),
7498 SourceLocation(),
7499 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00007500 FieldTypes[i], /*TInfo=*/nullptr,
7501 /*BitWidth=*/nullptr,
Ulrich Weigand47445072013-05-06 16:26:41 +00007502 /*Mutable=*/false,
7503 ICIS_NoInit);
7504 Field->setAccess(AS_public);
7505 VaListTagDecl->addDecl(Field);
7506 }
7507 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00007508 Context->VaListTagDecl = VaListTagDecl;
Ulrich Weigand47445072013-05-06 16:26:41 +00007509 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Ulrich Weigand47445072013-05-06 16:26:41 +00007510
Richard Smith9b88a4c2015-07-27 05:40:23 +00007511 // };
Ulrich Weigand47445072013-05-06 16:26:41 +00007512
7513 // typedef __va_list_tag __builtin_va_list[1];
7514 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00007515 QualType VaListTagArrayType =
7516 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Ulrich Weigand47445072013-05-06 16:26:41 +00007517
Alp Toker56b5cc92013-12-15 10:36:26 +00007518 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Ulrich Weigand47445072013-05-06 16:26:41 +00007519}
7520
Meador Inge5d3fb222012-06-16 03:34:49 +00007521static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
7522 TargetInfo::BuiltinVaListKind Kind) {
7523 switch (Kind) {
7524 case TargetInfo::CharPtrBuiltinVaList:
7525 return CreateCharPtrBuiltinVaListDecl(Context);
7526 case TargetInfo::VoidPtrBuiltinVaList:
7527 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northover9bb857a2013-01-31 12:13:10 +00007528 case TargetInfo::AArch64ABIBuiltinVaList:
7529 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00007530 case TargetInfo::PowerABIBuiltinVaList:
7531 return CreatePowerABIBuiltinVaListDecl(Context);
7532 case TargetInfo::X86_64ABIBuiltinVaList:
7533 return CreateX86_64ABIBuiltinVaListDecl(Context);
7534 case TargetInfo::PNaClABIBuiltinVaList:
7535 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00007536 case TargetInfo::AAPCSABIBuiltinVaList:
7537 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigand47445072013-05-06 16:26:41 +00007538 case TargetInfo::SystemZBuiltinVaList:
7539 return CreateSystemZBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00007540 }
7541
7542 llvm_unreachable("Unhandled __builtin_va_list type kind");
7543}
7544
7545TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00007546 if (!BuiltinVaListDecl) {
Meador Inge5d3fb222012-06-16 03:34:49 +00007547 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
Alp Toker56b5cc92013-12-15 10:36:26 +00007548 assert(BuiltinVaListDecl->isImplicit());
7549 }
Meador Inge5d3fb222012-06-16 03:34:49 +00007550
7551 return BuiltinVaListDecl;
7552}
7553
Richard Smith9b88a4c2015-07-27 05:40:23 +00007554Decl *ASTContext::getVaListTagDecl() const {
7555 // Force the creation of VaListTagDecl by building the __builtin_va_list
Meador Ingecfb60902012-07-01 15:57:25 +00007556 // declaration.
Richard Smith9b88a4c2015-07-27 05:40:23 +00007557 if (!VaListTagDecl)
7558 (void)getBuiltinVaListDecl();
Meador Ingecfb60902012-07-01 15:57:25 +00007559
Richard Smith9b88a4c2015-07-27 05:40:23 +00007560 return VaListTagDecl;
Meador Ingecfb60902012-07-01 15:57:25 +00007561}
7562
Charles Davisc7d5c942015-09-17 20:55:33 +00007563TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const {
7564 if (!BuiltinMSVaListDecl)
7565 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
7566
7567 return BuiltinMSVaListDecl;
7568}
7569
Erich Keane41af9712018-04-16 21:30:08 +00007570bool ASTContext::canBuiltinBeRedeclared(const FunctionDecl *FD) const {
7571 return BuiltinInfo.canBeRedeclared(FD->getBuiltinID());
7572}
7573
Ted Kremenek1b0ea822008-01-07 19:49:32 +00007574void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00007575 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00007576 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00007577
Ted Kremenek1b0ea822008-01-07 19:49:32 +00007578 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00007579}
7580
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007581/// Retrieve the template name that corresponds to a non-empty
John McCalld28ae272009-12-02 08:04:21 +00007582/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00007583TemplateName
7584ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
7585 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00007586 unsigned size = End - Begin;
7587 assert(size > 1 && "set is not overloaded!");
7588
7589 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
7590 size * sizeof(FunctionTemplateDecl*));
Eugene Zelenko7855e772018-04-03 00:11:50 +00007591 auto *OT = new (memory) OverloadedTemplateStorage(size);
John McCalld28ae272009-12-02 08:04:21 +00007592
7593 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00007594 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00007595 NamedDecl *D = *I;
7596 assert(isa<FunctionTemplateDecl>(D) ||
Richard Smithef53a3e2018-06-06 16:36:56 +00007597 isa<UnresolvedUsingValueDecl>(D) ||
John McCalld28ae272009-12-02 08:04:21 +00007598 (isa<UsingShadowDecl>(D) &&
7599 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
7600 *Storage++ = D;
7601 }
7602
7603 return TemplateName(OT);
7604}
7605
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007606/// Retrieve the template name that represents a qualified
Douglas Gregordc572a32009-03-30 22:58:21 +00007607/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00007608TemplateName
7609ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
7610 bool TemplateKeyword,
7611 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00007612 assert(NNS && "Missing nested-name-specifier in qualified template name");
Fangrui Song6907ce22018-07-30 19:24:48 +00007613
Douglas Gregorc42075a2010-02-04 18:10:26 +00007614 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00007615 llvm::FoldingSetNodeID ID;
7616 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
7617
Craig Topper36250ad2014-05-12 05:36:57 +00007618 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00007619 QualifiedTemplateName *QTN =
7620 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7621 if (!QTN) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007622 QTN = new (*this, alignof(QualifiedTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007623 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00007624 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
7625 }
7626
7627 return TemplateName(QTN);
7628}
7629
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007630/// Retrieve the template name that represents a dependent
Douglas Gregordc572a32009-03-30 22:58:21 +00007631/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00007632TemplateName
7633ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
7634 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00007635 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00007636 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00007637
7638 llvm::FoldingSetNodeID ID;
7639 DependentTemplateName::Profile(ID, NNS, Name);
7640
Craig Topper36250ad2014-05-12 05:36:57 +00007641 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00007642 DependentTemplateName *QTN =
7643 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7644
7645 if (QTN)
7646 return TemplateName(QTN);
7647
7648 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
7649 if (CanonNNS == NNS) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007650 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007651 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00007652 } else {
7653 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007654 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007655 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00007656 DependentTemplateName *CheckQTN =
7657 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7658 assert(!CheckQTN && "Dependent type name canonicalization broken");
7659 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00007660 }
7661
7662 DependentTemplateNames.InsertNode(QTN, InsertPos);
7663 return TemplateName(QTN);
7664}
7665
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007666/// Retrieve the template name that represents a dependent
Douglas Gregor71395fa2009-11-04 00:56:37 +00007667/// template name such as \c MetaFun::template operator+.
Fangrui Song6907ce22018-07-30 19:24:48 +00007668TemplateName
Douglas Gregor71395fa2009-11-04 00:56:37 +00007669ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00007670 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00007671 assert((!NNS || NNS->isDependent()) &&
7672 "Nested name specifier must be dependent");
Fangrui Song6907ce22018-07-30 19:24:48 +00007673
Douglas Gregor71395fa2009-11-04 00:56:37 +00007674 llvm::FoldingSetNodeID ID;
7675 DependentTemplateName::Profile(ID, NNS, Operator);
Craig Topper36250ad2014-05-12 05:36:57 +00007676
7677 void *InsertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00007678 DependentTemplateName *QTN
7679 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Fangrui Song6907ce22018-07-30 19:24:48 +00007680
Douglas Gregor71395fa2009-11-04 00:56:37 +00007681 if (QTN)
7682 return TemplateName(QTN);
Fangrui Song6907ce22018-07-30 19:24:48 +00007683
Douglas Gregor71395fa2009-11-04 00:56:37 +00007684 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
7685 if (CanonNNS == NNS) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007686 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007687 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00007688 } else {
7689 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007690 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007691 DependentTemplateName(NNS, Operator, Canon);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007692
Douglas Gregorc42075a2010-02-04 18:10:26 +00007693 DependentTemplateName *CheckQTN
7694 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7695 assert(!CheckQTN && "Dependent template name canonicalization broken");
7696 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00007697 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007698
Douglas Gregor71395fa2009-11-04 00:56:37 +00007699 DependentTemplateNames.InsertNode(QTN, InsertPos);
7700 return TemplateName(QTN);
7701}
7702
Fangrui Song6907ce22018-07-30 19:24:48 +00007703TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00007704ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
7705 TemplateName replacement) const {
7706 llvm::FoldingSetNodeID ID;
7707 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00007708
7709 void *insertPos = nullptr;
John McCalld9dfe3a2011-06-30 08:33:18 +00007710 SubstTemplateTemplateParmStorage *subst
7711 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
Fangrui Song6907ce22018-07-30 19:24:48 +00007712
John McCalld9dfe3a2011-06-30 08:33:18 +00007713 if (!subst) {
7714 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
7715 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
7716 }
7717
7718 return TemplateName(subst);
7719}
7720
Fangrui Song6907ce22018-07-30 19:24:48 +00007721TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00007722ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
7723 const TemplateArgument &ArgPack) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00007724 auto &Self = const_cast<ASTContext &>(*this);
Douglas Gregor5590be02011-01-15 06:45:20 +00007725 llvm::FoldingSetNodeID ID;
7726 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00007727
7728 void *InsertPos = nullptr;
Douglas Gregor5590be02011-01-15 06:45:20 +00007729 SubstTemplateTemplateParmPackStorage *Subst
7730 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
Fangrui Song6907ce22018-07-30 19:24:48 +00007731
Douglas Gregor5590be02011-01-15 06:45:20 +00007732 if (!Subst) {
Fangrui Song6907ce22018-07-30 19:24:48 +00007733 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00007734 ArgPack.pack_size(),
7735 ArgPack.pack_begin());
7736 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
7737 }
7738
7739 return TemplateName(Subst);
7740}
7741
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007742/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00007743/// TargetInfo, produce the corresponding type. The unsigned @p Type
7744/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00007745CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007746 switch (Type) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00007747 case TargetInfo::NoInt: return {};
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00007748 case TargetInfo::SignedChar: return SignedCharTy;
7749 case TargetInfo::UnsignedChar: return UnsignedCharTy;
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007750 case TargetInfo::SignedShort: return ShortTy;
7751 case TargetInfo::UnsignedShort: return UnsignedShortTy;
7752 case TargetInfo::SignedInt: return IntTy;
7753 case TargetInfo::UnsignedInt: return UnsignedIntTy;
7754 case TargetInfo::SignedLong: return LongTy;
7755 case TargetInfo::UnsignedLong: return UnsignedLongTy;
7756 case TargetInfo::SignedLongLong: return LongLongTy;
7757 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
7758 }
7759
David Blaikie83d382b2011-09-23 05:06:16 +00007760 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007761}
Ted Kremenek77c51b22008-07-24 23:58:27 +00007762
7763//===----------------------------------------------------------------------===//
7764// Type Predicates.
7765//===----------------------------------------------------------------------===//
7766
Fariborz Jahanian96207692009-02-18 21:49:28 +00007767/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
7768/// garbage collection attribute.
7769///
John McCall553d45a2011-01-12 00:34:59 +00007770Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007771 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00007772 return Qualifiers::GCNone;
7773
Erik Pilkingtonfa983902018-10-30 20:31:30 +00007774 assert(getLangOpts().ObjC);
John McCall553d45a2011-01-12 00:34:59 +00007775 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
7776
7777 // Default behaviour under objective-C's gc is for ObjC pointers
7778 // (or pointers to them) be treated as though they were declared
7779 // as __strong.
7780 if (GCAttrs == Qualifiers::GCNone) {
7781 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
7782 return Qualifiers::Strong;
7783 else if (Ty->isPointerType())
7784 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
7785 } else {
7786 // It's not valid to set GC attributes on anything that isn't a
7787 // pointer.
7788#ifndef NDEBUG
7789 QualType CT = Ty->getCanonicalTypeInternal();
Eugene Zelenko7855e772018-04-03 00:11:50 +00007790 while (const auto *AT = dyn_cast<ArrayType>(CT))
John McCall553d45a2011-01-12 00:34:59 +00007791 CT = AT->getElementType();
7792 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
7793#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00007794 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00007795 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00007796}
7797
Chris Lattner49af6a42008-04-07 06:51:04 +00007798//===----------------------------------------------------------------------===//
7799// Type Compatibility Testing
7800//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00007801
Mike Stump11289f42009-09-09 15:08:12 +00007802/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00007803/// compatible.
7804static bool areCompatVectorTypes(const VectorType *LHS,
7805 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00007806 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00007807 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00007808 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00007809}
7810
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007811bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
7812 QualType SecondVec) {
7813 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
7814 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
7815
7816 if (hasSameUnqualifiedType(FirstVec, SecondVec))
7817 return true;
7818
Bob Wilsone6aeebb2010-11-12 17:24:54 +00007819 // Treat Neon vector types and most AltiVec vector types as if they are the
7820 // equivalent GCC vector types.
Eugene Zelenko7855e772018-04-03 00:11:50 +00007821 const auto *First = FirstVec->getAs<VectorType>();
7822 const auto *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00007823 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007824 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00007825 First->getVectorKind() != VectorType::AltiVecPixel &&
7826 First->getVectorKind() != VectorType::AltiVecBool &&
7827 Second->getVectorKind() != VectorType::AltiVecPixel &&
7828 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007829 return true;
7830
7831 return false;
7832}
7833
Steve Naroff8e6aee52009-07-23 01:01:38 +00007834//===----------------------------------------------------------------------===//
7835// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
7836//===----------------------------------------------------------------------===//
7837
7838/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
7839/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00007840bool
7841ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
7842 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00007843 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00007844 return true;
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00007845 for (auto *PI : rProto->protocols())
7846 if (ProtocolCompatibleWithProtocol(lProto, PI))
Steve Naroff8e6aee52009-07-23 01:01:38 +00007847 return true;
7848 return false;
7849}
7850
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00007851/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
7852/// Class<pr1, ...>.
Fangrui Song6907ce22018-07-30 19:24:48 +00007853bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007854 QualType rhs) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00007855 const auto *lhsQID = lhs->getAs<ObjCObjectPointerType>();
7856 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00007857 assert((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
Fangrui Song6907ce22018-07-30 19:24:48 +00007858
Aaron Ballman83731462014-03-17 16:14:00 +00007859 for (auto *lhsProto : lhsQID->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007860 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00007861 for (auto *rhsProto : rhsOPT->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007862 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
7863 match = true;
7864 break;
7865 }
7866 }
7867 if (!match)
7868 return false;
7869 }
7870 return true;
7871}
7872
Steve Naroff8e6aee52009-07-23 01:01:38 +00007873/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
7874/// ObjCQualifiedIDType.
7875bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
7876 bool compare) {
7877 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00007878 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00007879 lhs->isObjCIdType() || lhs->isObjCClassType())
7880 return true;
Mike Stump11289f42009-09-09 15:08:12 +00007881 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00007882 rhs->isObjCIdType() || rhs->isObjCClassType())
7883 return true;
7884
7885 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00007886 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00007887
Steve Naroff8e6aee52009-07-23 01:01:38 +00007888 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00007889
Steve Naroff8e6aee52009-07-23 01:01:38 +00007890 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00007891 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00007892 // make sure we check the class hierarchy.
7893 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00007894 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007895 // when comparing an id<P> on lhs with a static type on rhs,
7896 // see if static class implements all of id's protocols, directly or
7897 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00007898 if (!rhsID->ClassImplementsProtocol(I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00007899 return false;
7900 }
7901 }
7902 // If there are no qualifiers and no interface, we have an 'id'.
7903 return true;
7904 }
Mike Stump11289f42009-09-09 15:08:12 +00007905 // Both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00007906 for (auto *lhsProto : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007907 bool match = false;
7908
7909 // when comparing an id<P> on lhs with a static type on rhs,
7910 // see if static class implements all of id's protocols, directly or
7911 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00007912 for (auto *rhsProto : rhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007913 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7914 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7915 match = true;
7916 break;
7917 }
7918 }
Mike Stump11289f42009-09-09 15:08:12 +00007919 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00007920 // make sure we check the class hierarchy.
7921 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00007922 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007923 // when comparing an id<P> on lhs with a static type on rhs,
7924 // see if static class implements all of id's protocols, directly or
7925 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00007926 if (rhsID->ClassImplementsProtocol(I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007927 match = true;
7928 break;
7929 }
7930 }
7931 }
7932 if (!match)
7933 return false;
7934 }
Mike Stump11289f42009-09-09 15:08:12 +00007935
Steve Naroff8e6aee52009-07-23 01:01:38 +00007936 return true;
7937 }
Mike Stump11289f42009-09-09 15:08:12 +00007938
Steve Naroff8e6aee52009-07-23 01:01:38 +00007939 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
7940 assert(rhsQID && "One of the LHS/RHS should be id<x>");
7941
Mike Stump11289f42009-09-09 15:08:12 +00007942 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00007943 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007944 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00007945 for (auto *lhsProto : lhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007946 bool match = false;
7947
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007948 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00007949 // see if static class implements all of id's protocols, directly or
7950 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007951 // First, lhs protocols in the qualifier list must be found, direct
7952 // or indirect in rhs's qualifier list or it is a mismatch.
Aaron Ballman83731462014-03-17 16:14:00 +00007953 for (auto *rhsProto : rhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007954 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7955 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7956 match = true;
7957 break;
7958 }
7959 }
7960 if (!match)
7961 return false;
7962 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007963
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007964 // Static class's protocols, or its super class or category protocols
7965 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
7966 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
7967 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
7968 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
7969 // This is rather dubious but matches gcc's behavior. If lhs has
7970 // no type qualifier and its class has no static protocol(s)
7971 // assume that it is mismatch.
7972 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
7973 return false;
Aaron Ballman83731462014-03-17 16:14:00 +00007974 for (auto *lhsProto : LHSInheritedProtocols) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007975 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00007976 for (auto *rhsProto : rhsQID->quals()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007977 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7978 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7979 match = true;
7980 break;
7981 }
7982 }
7983 if (!match)
7984 return false;
7985 }
7986 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00007987 return true;
7988 }
7989 return false;
7990}
7991
Eli Friedman47f77112008-08-22 00:56:42 +00007992/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00007993/// compatible for assignment from RHS to LHS. This handles validation of any
7994/// protocol qualifiers on the LHS or RHS.
Steve Naroff7cae42b2009-07-10 23:34:53 +00007995bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
7996 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00007997 const ObjCObjectType* LHS = LHSOPT->getObjectType();
7998 const ObjCObjectType* RHS = RHSOPT->getObjectType();
7999
Steve Naroff1329fa02009-07-15 18:40:39 +00008000 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00008001 if (LHS->isObjCUnqualifiedIdOrClass() ||
8002 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00008003 return true;
8004
Douglas Gregorab209d82015-07-07 03:58:42 +00008005 // Function object that propagates a successful result or handles
8006 // __kindof types.
8007 auto finish = [&](bool succeeded) -> bool {
8008 if (succeeded)
8009 return true;
8010
8011 if (!RHS->isKindOfType())
8012 return false;
8013
8014 // Strip off __kindof and protocol qualifiers, then check whether
8015 // we can assign the other way.
8016 return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this),
8017 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
8018 };
8019
8020 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
8021 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
8022 QualType(RHSOPT,0),
8023 false));
8024 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008025
Douglas Gregorab209d82015-07-07 03:58:42 +00008026 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
8027 return finish(ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
8028 QualType(RHSOPT,0)));
8029 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008030
John McCall8b07ec22010-05-15 11:32:37 +00008031 // If we have 2 user-defined types, fall into that path.
Douglas Gregorab209d82015-07-07 03:58:42 +00008032 if (LHS->getInterface() && RHS->getInterface()) {
8033 return finish(canAssignObjCInterfaces(LHS, RHS));
8034 }
Mike Stump11289f42009-09-09 15:08:12 +00008035
Steve Naroff8e6aee52009-07-23 01:01:38 +00008036 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00008037}
8038
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008039/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Fangrui Song6907ce22018-07-30 19:24:48 +00008040/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008041/// arguments in block literals. When passed as arguments, passing 'A*' where
8042/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
8043/// not OK. For the return type, the opposite is not OK.
8044bool ASTContext::canAssignObjCInterfacesInBlockPointer(
8045 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00008046 const ObjCObjectPointerType *RHSOPT,
8047 bool BlockReturnType) {
Douglas Gregorab209d82015-07-07 03:58:42 +00008048
8049 // Function object that propagates a successful result or handles
8050 // __kindof types.
8051 auto finish = [&](bool succeeded) -> bool {
8052 if (succeeded)
8053 return true;
8054
8055 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
8056 if (!Expected->isKindOfType())
8057 return false;
8058
8059 // Strip off __kindof and protocol qualifiers, then check whether
8060 // we can assign the other way.
8061 return canAssignObjCInterfacesInBlockPointer(
8062 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
8063 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
8064 BlockReturnType);
8065 };
8066
Fariborz Jahanian440a6832010-04-06 17:23:39 +00008067 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008068 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00008069
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008070 if (LHSOPT->isObjCBuiltinType()) {
Douglas Gregorab209d82015-07-07 03:58:42 +00008071 return finish(RHSOPT->isObjCBuiltinType() ||
8072 RHSOPT->isObjCQualifiedIdType());
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008073 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008074
Fariborz Jahanian440a6832010-04-06 17:23:39 +00008075 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Douglas Gregorab209d82015-07-07 03:58:42 +00008076 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
8077 QualType(RHSOPT,0),
8078 false));
Fangrui Song6907ce22018-07-30 19:24:48 +00008079
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008080 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
8081 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
8082 if (LHS && RHS) { // We have 2 user-defined types.
8083 if (LHS != RHS) {
8084 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00008085 return finish(BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008086 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00008087 return finish(!BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008088 }
8089 else
8090 return true;
8091 }
8092 return false;
8093}
8094
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008095/// Comparison routine for Objective-C protocols to be used with
8096/// llvm::array_pod_sort.
8097static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
8098 ObjCProtocolDecl * const *rhs) {
8099 return (*lhs)->getName().compare((*rhs)->getName());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008100}
8101
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008102/// getIntersectionOfProtocols - This routine finds the intersection of set
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008103/// of protocols inherited from two distinct objective-c pointer objects with
8104/// the given common base.
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008105/// It is used to build composite qualifier list of the composite type of
8106/// the conditional expression involving two objective-c pointer objects.
Fangrui Song6907ce22018-07-30 19:24:48 +00008107static
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008108void getIntersectionOfProtocols(ASTContext &Context,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008109 const ObjCInterfaceDecl *CommonBase,
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008110 const ObjCObjectPointerType *LHSOPT,
8111 const ObjCObjectPointerType *RHSOPT,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008112 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
Fangrui Song6907ce22018-07-30 19:24:48 +00008113
John McCall8b07ec22010-05-15 11:32:37 +00008114 const ObjCObjectType* LHS = LHSOPT->getObjectType();
8115 const ObjCObjectType* RHS = RHSOPT->getObjectType();
8116 assert(LHS->getInterface() && "LHS must have an interface base");
8117 assert(RHS->getInterface() && "RHS must have an interface base");
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008118
8119 // Add all of the protocols for the LHS.
8120 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
8121
8122 // Start with the protocol qualifiers.
8123 for (auto proto : LHS->quals()) {
8124 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008125 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008126
8127 // Also add the protocols associated with the LHS interface.
8128 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
8129
Raphael Isemannb23ccec2018-12-10 12:37:46 +00008130 // Add all of the protocols for the RHS.
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008131 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
8132
8133 // Start with the protocol qualifiers.
8134 for (auto proto : RHS->quals()) {
8135 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008136 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008137
8138 // Also add the protocols associated with the RHS interface.
8139 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
8140
8141 // Compute the intersection of the collected protocol sets.
8142 for (auto proto : LHSProtocolSet) {
8143 if (RHSProtocolSet.count(proto))
8144 IntersectionSet.push_back(proto);
8145 }
8146
8147 // Compute the set of protocols that is implied by either the common type or
8148 // the protocols within the intersection.
8149 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
8150 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
8151
8152 // Remove any implied protocols from the list of inherited protocols.
8153 if (!ImpliedProtocols.empty()) {
8154 IntersectionSet.erase(
8155 std::remove_if(IntersectionSet.begin(),
8156 IntersectionSet.end(),
8157 [&](ObjCProtocolDecl *proto) -> bool {
8158 return ImpliedProtocols.count(proto) > 0;
8159 }),
8160 IntersectionSet.end());
8161 }
8162
8163 // Sort the remaining protocols by name.
8164 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
8165 compareObjCProtocolsByName);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008166}
8167
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008168/// Determine whether the first type is a subtype of the second.
8169static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
8170 QualType rhs) {
8171 // Common case: two object pointers.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008172 const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
8173 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008174 if (lhsOPT && rhsOPT)
8175 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
8176
8177 // Two block pointers.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008178 const auto *lhsBlock = lhs->getAs<BlockPointerType>();
8179 const auto *rhsBlock = rhs->getAs<BlockPointerType>();
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008180 if (lhsBlock && rhsBlock)
8181 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
8182
8183 // If either is an unqualified 'id' and the other is a block, it's
8184 // acceptable.
8185 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
8186 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
8187 return true;
8188
8189 return false;
8190}
8191
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008192// Check that the given Objective-C type argument lists are equivalent.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008193static bool sameObjCTypeArgs(ASTContext &ctx,
8194 const ObjCInterfaceDecl *iface,
8195 ArrayRef<QualType> lhsArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00008196 ArrayRef<QualType> rhsArgs,
8197 bool stripKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008198 if (lhsArgs.size() != rhsArgs.size())
8199 return false;
8200
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008201 ObjCTypeParamList *typeParams = iface->getTypeParamList();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008202 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008203 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
8204 continue;
8205
8206 switch (typeParams->begin()[i]->getVariance()) {
8207 case ObjCTypeParamVariance::Invariant:
Douglas Gregorab209d82015-07-07 03:58:42 +00008208 if (!stripKindOf ||
8209 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
8210 rhsArgs[i].stripObjCKindOfType(ctx))) {
8211 return false;
8212 }
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008213 break;
8214
8215 case ObjCTypeParamVariance::Covariant:
8216 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
8217 return false;
8218 break;
8219
8220 case ObjCTypeParamVariance::Contravariant:
8221 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
8222 return false;
8223 break;
Douglas Gregorab209d82015-07-07 03:58:42 +00008224 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008225 }
8226
8227 return true;
8228}
8229
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00008230QualType ASTContext::areCommonBaseCompatible(
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008231 const ObjCObjectPointerType *Lptr,
8232 const ObjCObjectPointerType *Rptr) {
John McCall8b07ec22010-05-15 11:32:37 +00008233 const ObjCObjectType *LHS = Lptr->getObjectType();
8234 const ObjCObjectType *RHS = Rptr->getObjectType();
8235 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
8236 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008237
8238 if (!LDecl || !RDecl)
Eugene Zelenko7855e772018-04-03 00:11:50 +00008239 return {};
Douglas Gregore83b9562015-07-07 03:57:53 +00008240
Manman Renc46f7d12016-05-06 19:35:02 +00008241 // When either LHS or RHS is a kindof type, we should return a kindof type.
8242 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
8243 // kindof(A).
8244 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
8245
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008246 // Follow the left-hand side up the class hierarchy until we either hit a
8247 // root or find the RHS. Record the ancestors in case we don't find it.
8248 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
8249 LHSAncestors;
8250 while (true) {
8251 // Record this ancestor. We'll need this if the common type isn't in the
8252 // path from the LHS to the root.
8253 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
Douglas Gregore83b9562015-07-07 03:57:53 +00008254
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008255 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
8256 // Get the type arguments.
8257 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
8258 bool anyChanges = false;
8259 if (LHS->isSpecialized() && RHS->isSpecialized()) {
8260 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008261 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
8262 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00008263 /*stripKindOf=*/true))
Eugene Zelenko7855e772018-04-03 00:11:50 +00008264 return {};
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008265 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
8266 // If only one has type arguments, the result will not have type
8267 // arguments.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00008268 LHSTypeArgs = {};
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008269 anyChanges = true;
8270 }
8271
8272 // Compute the intersection of protocols.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008273 SmallVector<ObjCProtocolDecl *, 8> Protocols;
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008274 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
8275 Protocols);
John McCall8b07ec22010-05-15 11:32:37 +00008276 if (!Protocols.empty())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008277 anyChanges = true;
8278
8279 // If anything in the LHS will have changed, build a new result type.
Manman Renc46f7d12016-05-06 19:35:02 +00008280 // If we need to return a kindof type but LHS is not a kindof type, we
8281 // build a new result type.
8282 if (anyChanges || LHS->isKindOfType() != anyKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008283 QualType Result = getObjCInterfaceType(LHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00008284 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
Manman Renc46f7d12016-05-06 19:35:02 +00008285 anyKindOf || LHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008286 return getObjCObjectPointerType(Result);
8287 }
8288
8289 return getObjCObjectPointerType(QualType(LHS, 0));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008290 }
Douglas Gregore83b9562015-07-07 03:57:53 +00008291
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008292 // Find the superclass.
Douglas Gregore83b9562015-07-07 03:57:53 +00008293 QualType LHSSuperType = LHS->getSuperClassType();
8294 if (LHSSuperType.isNull())
8295 break;
8296
8297 LHS = LHSSuperType->castAs<ObjCObjectType>();
8298 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008299
8300 // We didn't find anything by following the LHS to its root; now check
8301 // the RHS against the cached set of ancestors.
8302 while (true) {
8303 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
8304 if (KnownLHS != LHSAncestors.end()) {
8305 LHS = KnownLHS->second;
8306
8307 // Get the type arguments.
8308 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
8309 bool anyChanges = false;
8310 if (LHS->isSpecialized() && RHS->isSpecialized()) {
8311 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008312 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
8313 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00008314 /*stripKindOf=*/true))
Eugene Zelenko7855e772018-04-03 00:11:50 +00008315 return {};
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008316 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
8317 // If only one has type arguments, the result will not have type
8318 // arguments.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00008319 RHSTypeArgs = {};
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008320 anyChanges = true;
8321 }
8322
8323 // Compute the intersection of protocols.
8324 SmallVector<ObjCProtocolDecl *, 8> Protocols;
8325 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
8326 Protocols);
8327 if (!Protocols.empty())
8328 anyChanges = true;
8329
Manman Renc46f7d12016-05-06 19:35:02 +00008330 // If we need to return a kindof type but RHS is not a kindof type, we
8331 // build a new result type.
8332 if (anyChanges || RHS->isKindOfType() != anyKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008333 QualType Result = getObjCInterfaceType(RHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00008334 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
Manman Renc46f7d12016-05-06 19:35:02 +00008335 anyKindOf || RHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008336 return getObjCObjectPointerType(Result);
8337 }
8338
8339 return getObjCObjectPointerType(QualType(RHS, 0));
8340 }
8341
8342 // Find the superclass of the RHS.
8343 QualType RHSSuperType = RHS->getSuperClassType();
8344 if (RHSSuperType.isNull())
8345 break;
8346
8347 RHS = RHSSuperType->castAs<ObjCObjectType>();
8348 }
8349
Eugene Zelenko7855e772018-04-03 00:11:50 +00008350 return {};
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00008351}
8352
John McCall8b07ec22010-05-15 11:32:37 +00008353bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
8354 const ObjCObjectType *RHS) {
8355 assert(LHS->getInterface() && "LHS is not an interface type");
8356 assert(RHS->getInterface() && "RHS is not an interface type");
8357
Chris Lattner49af6a42008-04-07 06:51:04 +00008358 // Verify that the base decls are compatible: the RHS must be a subclass of
8359 // the LHS.
Douglas Gregore83b9562015-07-07 03:57:53 +00008360 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
8361 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
8362 if (!IsSuperClass)
Chris Lattner49af6a42008-04-07 06:51:04 +00008363 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008364
Douglas Gregore83b9562015-07-07 03:57:53 +00008365 // If the LHS has protocol qualifiers, determine whether all of them are
8366 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
8367 // LHS).
8368 if (LHS->getNumProtocols() > 0) {
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00008369 // OK if conversion of LHS to SuperClass results in narrowing of types
8370 // ; i.e., SuperClass may implement at least one of the protocols
8371 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
8372 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
8373 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
8374 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
8375 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
8376 // qualifiers.
8377 for (auto *RHSPI : RHS->quals())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008378 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00008379 // If there is no protocols associated with RHS, it is not a match.
8380 if (SuperClassInheritedProtocols.empty())
Steve Naroff114aecb2009-03-01 16:12:44 +00008381 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00008382
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00008383 for (const auto *LHSProto : LHS->quals()) {
8384 bool SuperImplementsProtocol = false;
8385 for (auto *SuperClassProto : SuperClassInheritedProtocols)
8386 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
8387 SuperImplementsProtocol = true;
8388 break;
8389 }
8390 if (!SuperImplementsProtocol)
8391 return false;
8392 }
Chris Lattner49af6a42008-04-07 06:51:04 +00008393 }
Douglas Gregore83b9562015-07-07 03:57:53 +00008394
8395 // If the LHS is specialized, we may need to check type arguments.
8396 if (LHS->isSpecialized()) {
8397 // Follow the superclass chain until we've matched the LHS class in the
8398 // hierarchy. This substitutes type arguments through.
8399 const ObjCObjectType *RHSSuper = RHS;
8400 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
8401 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
8402
8403 // If the RHS is specializd, compare type arguments.
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008404 if (RHSSuper->isSpecialized() &&
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008405 !sameObjCTypeArgs(*this, LHS->getInterface(),
8406 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00008407 /*stripKindOf=*/true)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008408 return false;
Douglas Gregore83b9562015-07-07 03:57:53 +00008409 }
8410 }
8411
8412 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00008413}
8414
Steve Naroffb7605152009-02-12 17:52:19 +00008415bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
8416 // get the "pointed to" types
Eugene Zelenko7855e772018-04-03 00:11:50 +00008417 const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
8418 const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00008419
Steve Naroff7cae42b2009-07-10 23:34:53 +00008420 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00008421 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00008422
8423 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
8424 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00008425}
8426
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00008427bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
8428 return canAssignObjCInterfaces(
8429 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
8430 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
8431}
8432
Mike Stump11289f42009-09-09 15:08:12 +00008433/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00008434/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00008435/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00008436/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008437bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
8438 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00008439 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00008440 return hasSameType(LHS, RHS);
Joey Gouly5788b782016-11-18 14:10:54 +00008441
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008442 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00008443}
8444
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00008445bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00008446 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00008447}
8448
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008449bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
8450 return !mergeTypes(LHS, RHS, true).isNull();
8451}
8452
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00008453/// mergeTransparentUnionType - if T is a transparent union type and a member
8454/// of T is compatible with SubType, return the merged type, else return
8455/// QualType()
8456QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
8457 bool OfBlockPointer,
8458 bool Unqualified) {
8459 if (const RecordType *UT = T->getAsUnionType()) {
8460 RecordDecl *UD = UT->getDecl();
8461 if (UD->hasAttr<TransparentUnionAttr>()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008462 for (const auto *I : UD->fields()) {
8463 QualType ET = I->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00008464 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
8465 if (!MT.isNull())
8466 return MT;
8467 }
8468 }
8469 }
8470
Eugene Zelenko7855e772018-04-03 00:11:50 +00008471 return {};
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00008472}
8473
Alp Toker9cacbab2014-01-20 20:26:09 +00008474/// mergeFunctionParameterTypes - merge two types which appear as function
8475/// parameter types
8476QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
8477 bool OfBlockPointer,
8478 bool Unqualified) {
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00008479 // GNU extension: two types are compatible if they appear as a function
8480 // argument, one of the types is a transparent union type and the other
8481 // type is compatible with a union member
8482 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
8483 Unqualified);
8484 if (!lmerge.isNull())
8485 return lmerge;
8486
8487 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
8488 Unqualified);
8489 if (!rmerge.isNull())
8490 return rmerge;
8491
8492 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
8493}
8494
Fangrui Song6907ce22018-07-30 19:24:48 +00008495QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008496 bool OfBlockPointer,
8497 bool Unqualified) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00008498 const auto *lbase = lhs->getAs<FunctionType>();
8499 const auto *rbase = rhs->getAs<FunctionType>();
8500 const auto *lproto = dyn_cast<FunctionProtoType>(lbase);
8501 const auto *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00008502 bool allLTypes = true;
8503 bool allRTypes = true;
8504
8505 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008506 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00008507 if (OfBlockPointer) {
Alp Toker314cc812014-01-25 16:55:45 +00008508 QualType RHS = rbase->getReturnType();
8509 QualType LHS = lbase->getReturnType();
Fariborz Jahanian17825972011-02-11 18:46:17 +00008510 bool UnqualifiedResult = Unqualified;
8511 if (!UnqualifiedResult)
8512 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00008513 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00008514 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008515 else
Alp Toker314cc812014-01-25 16:55:45 +00008516 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
John McCall8c6b56f2010-12-15 01:06:38 +00008517 Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00008518 if (retType.isNull())
8519 return {};
Fangrui Song6907ce22018-07-30 19:24:48 +00008520
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008521 if (Unqualified)
8522 retType = retType.getUnqualifiedType();
8523
Alp Toker314cc812014-01-25 16:55:45 +00008524 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
8525 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008526 if (Unqualified) {
8527 LRetType = LRetType.getUnqualifiedType();
8528 RRetType = RRetType.getUnqualifiedType();
8529 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008530
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008531 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00008532 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008533 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00008534 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00008535
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00008536 // FIXME: double check this
8537 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
8538 // rbase->getRegParmAttr() != 0 &&
8539 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00008540 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
8541 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00008542
Douglas Gregor8c940862010-01-18 17:14:39 +00008543 // Compatible functions must have compatible calling conventions
Reid Kleckner78af0702013-08-27 23:08:25 +00008544 if (lbaseInfo.getCC() != rbaseInfo.getCC())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008545 return {};
Mike Stump11289f42009-09-09 15:08:12 +00008546
John McCall8c6b56f2010-12-15 01:06:38 +00008547 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00008548 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008549 return {};
John McCall8c6b56f2010-12-15 01:06:38 +00008550 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008551 return {};
John McCall8c6b56f2010-12-15 01:06:38 +00008552
John McCall31168b02011-06-15 23:02:42 +00008553 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008554 return {};
Oren Ben Simhon318a6ea2017-04-27 12:01:00 +00008555 if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008556 return {};
Oren Ben Simhon220671a2018-03-17 13:31:35 +00008557 if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008558 return {};
John McCall31168b02011-06-15 23:02:42 +00008559
John McCall8c6b56f2010-12-15 01:06:38 +00008560 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
8561 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00008562
Rafael Espindola8778c282012-11-29 16:09:03 +00008563 if (lbaseInfo.getNoReturn() != NoReturn)
8564 allLTypes = false;
8565 if (rbaseInfo.getNoReturn() != NoReturn)
8566 allRTypes = false;
8567
John McCall31168b02011-06-15 23:02:42 +00008568 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00008569
Eli Friedman47f77112008-08-22 00:56:42 +00008570 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00008571 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
8572 "C++ shouldn't be here");
Alp Toker601b22c2014-01-21 23:35:24 +00008573 // Compatible functions must have the same number of parameters
8574 if (lproto->getNumParams() != rproto->getNumParams())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008575 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00008576
8577 // Variadic and non-variadic functions aren't compatible
8578 if (lproto->isVariadic() != rproto->isVariadic())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008579 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00008580
Anastasia Stulovac61eaa52019-01-28 11:37:49 +00008581 if (lproto->getMethodQuals() != rproto->getMethodQuals())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008582 return {};
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00008583
Akira Hatanaka98a49332017-09-22 00:41:05 +00008584 SmallVector<FunctionProtoType::ExtParameterInfo, 4> newParamInfos;
8585 bool canUseLeft, canUseRight;
8586 if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight,
8587 newParamInfos))
Eugene Zelenko7855e772018-04-03 00:11:50 +00008588 return {};
Alp Toker601b22c2014-01-21 23:35:24 +00008589
Akira Hatanaka98a49332017-09-22 00:41:05 +00008590 if (!canUseLeft)
8591 allLTypes = false;
8592 if (!canUseRight)
8593 allRTypes = false;
8594
Alp Toker601b22c2014-01-21 23:35:24 +00008595 // Check parameter type compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008596 SmallVector<QualType, 10> types;
Alp Toker601b22c2014-01-21 23:35:24 +00008597 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
8598 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
8599 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
8600 QualType paramType = mergeFunctionParameterTypes(
8601 lParamType, rParamType, OfBlockPointer, Unqualified);
8602 if (paramType.isNull())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008603 return {};
Alp Toker601b22c2014-01-21 23:35:24 +00008604
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008605 if (Unqualified)
Alp Toker601b22c2014-01-21 23:35:24 +00008606 paramType = paramType.getUnqualifiedType();
8607
8608 types.push_back(paramType);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008609 if (Unqualified) {
Alp Toker601b22c2014-01-21 23:35:24 +00008610 lParamType = lParamType.getUnqualifiedType();
8611 rParamType = rParamType.getUnqualifiedType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008612 }
Alp Toker601b22c2014-01-21 23:35:24 +00008613
8614 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00008615 allLTypes = false;
Alp Toker601b22c2014-01-21 23:35:24 +00008616 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00008617 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00008618 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008619
Eli Friedman47f77112008-08-22 00:56:42 +00008620 if (allLTypes) return lhs;
8621 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00008622
8623 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
8624 EPI.ExtInfo = einfo;
Akira Hatanaka98a49332017-09-22 00:41:05 +00008625 EPI.ExtParameterInfos =
8626 newParamInfos.empty() ? nullptr : newParamInfos.data();
Jordan Rose5c382722013-03-08 21:51:21 +00008627 return getFunctionType(retType, types, EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00008628 }
8629
8630 if (lproto) allRTypes = false;
8631 if (rproto) allLTypes = false;
8632
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008633 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00008634 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00008635 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eugene Zelenko7855e772018-04-03 00:11:50 +00008636 if (proto->isVariadic())
8637 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00008638 // Check that the types are compatible with the types that
8639 // would result from default argument promotions (C99 6.7.5.3p15).
8640 // The only types actually affected are promotable integer
8641 // types and floats, which would be passed as a different
8642 // type depending on whether the prototype is visible.
Alp Toker601b22c2014-01-21 23:35:24 +00008643 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
8644 QualType paramTy = proto->getParamType(i);
Alp Toker9cacbab2014-01-20 20:26:09 +00008645
Eli Friedman448ce402012-08-30 00:44:15 +00008646 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00008647 // to pass enum values.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008648 if (const auto *Enum = paramTy->getAs<EnumType>()) {
Alp Toker601b22c2014-01-21 23:35:24 +00008649 paramTy = Enum->getDecl()->getIntegerType();
8650 if (paramTy.isNull())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008651 return {};
Eli Friedman448ce402012-08-30 00:44:15 +00008652 }
Alp Toker601b22c2014-01-21 23:35:24 +00008653
8654 if (paramTy->isPromotableIntegerType() ||
8655 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
Eugene Zelenko7855e772018-04-03 00:11:50 +00008656 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00008657 }
8658
8659 if (allLTypes) return lhs;
8660 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00008661
8662 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
8663 EPI.ExtInfo = einfo;
Alp Toker9cacbab2014-01-20 20:26:09 +00008664 return getFunctionType(retType, proto->getParamTypes(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00008665 }
8666
8667 if (allLTypes) return lhs;
8668 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00008669 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00008670}
8671
John McCall433c2e62013-03-21 00:10:07 +00008672/// Given that we have an enum type and a non-enum type, try to merge them.
8673static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
8674 QualType other, bool isBlockReturnType) {
8675 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
8676 // a signed integer type, or an unsigned integer type.
8677 // Compatibility is based on the underlying type, not the promotion
8678 // type.
8679 QualType underlyingType = ET->getDecl()->getIntegerType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00008680 if (underlyingType.isNull())
8681 return {};
John McCall433c2e62013-03-21 00:10:07 +00008682 if (Context.hasSameType(underlyingType, other))
8683 return other;
8684
8685 // In block return types, we're more permissive and accept any
8686 // integral type of the same size.
8687 if (isBlockReturnType && other->isIntegerType() &&
8688 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
8689 return other;
8690
Eugene Zelenko7855e772018-04-03 00:11:50 +00008691 return {};
John McCall433c2e62013-03-21 00:10:07 +00008692}
8693
Fangrui Song6907ce22018-07-30 19:24:48 +00008694QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008695 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00008696 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00008697 // C++ [expr]: If an expression initially has the type "reference to T", the
8698 // type is adjusted to "T" prior to any further analysis, the expression
8699 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00008700 // expression is an lvalue unless the reference is an rvalue reference and
8701 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00008702 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
8703 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008704
8705 if (Unqualified) {
8706 LHS = LHS.getUnqualifiedType();
8707 RHS = RHS.getUnqualifiedType();
8708 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008709
Eli Friedman47f77112008-08-22 00:56:42 +00008710 QualType LHSCan = getCanonicalType(LHS),
8711 RHSCan = getCanonicalType(RHS);
8712
8713 // If two types are identical, they are compatible.
8714 if (LHSCan == RHSCan)
8715 return LHS;
8716
John McCall8ccfcb52009-09-24 19:53:00 +00008717 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00008718 Qualifiers LQuals = LHSCan.getLocalQualifiers();
8719 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00008720 if (LQuals != RQuals) {
8721 // If any of these qualifiers are different, we have a type
8722 // mismatch.
8723 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00008724 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
Roger Ferrer Ibanezd93add32017-02-24 08:41:09 +00008725 LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
8726 LQuals.hasUnaligned() != RQuals.hasUnaligned())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008727 return {};
John McCall8ccfcb52009-09-24 19:53:00 +00008728
8729 // Exactly one GC qualifier difference is allowed: __strong is
8730 // okay if the other type has no GC qualifier but is an Objective
8731 // C object pointer (i.e. implicitly strong by default). We fix
8732 // this by pretending that the unqualified type was actually
8733 // qualified __strong.
8734 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
8735 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
8736 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
8737
8738 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
Eugene Zelenko7855e772018-04-03 00:11:50 +00008739 return {};
John McCall8ccfcb52009-09-24 19:53:00 +00008740
8741 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
8742 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
8743 }
8744 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
8745 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
8746 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00008747 return {};
John McCall8ccfcb52009-09-24 19:53:00 +00008748 }
8749
8750 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00008751
Eli Friedmandcca6332009-06-01 01:22:52 +00008752 Type::TypeClass LHSClass = LHSCan->getTypeClass();
8753 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00008754
Chris Lattnerfd652912008-01-14 05:45:46 +00008755 // We want to consider the two function types to be the same for these
8756 // comparisons, just force one to the other.
8757 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
8758 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00008759
8760 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00008761 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
8762 LHSClass = Type::ConstantArray;
8763 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
8764 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00008765
John McCall8b07ec22010-05-15 11:32:37 +00008766 // ObjCInterfaces are just specialized ObjCObjects.
8767 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
8768 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
8769
Nate Begemance4d7fc2008-04-18 23:10:10 +00008770 // Canonicalize ExtVector -> Vector.
8771 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
8772 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00008773
Chris Lattner95554662008-04-07 05:43:21 +00008774 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00008775 if (LHSClass != RHSClass) {
John McCall433c2e62013-03-21 00:10:07 +00008776 // Note that we only have special rules for turning block enum
8777 // returns into block int returns, not vice-versa.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008778 if (const auto *ETy = LHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00008779 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00008780 }
John McCall9dd450b2009-09-21 23:43:11 +00008781 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00008782 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00008783 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00008784 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00008785 if (OfBlockPointer && !BlockReturnType) {
8786 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
8787 return LHS;
8788 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
8789 return RHS;
8790 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008791
Eugene Zelenko7855e772018-04-03 00:11:50 +00008792 return {};
Steve Naroff32e44c02007-10-15 20:41:53 +00008793 }
Eli Friedman47f77112008-08-22 00:56:42 +00008794
Steve Naroffc6edcbd2008-01-09 22:43:08 +00008795 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00008796 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008797#define TYPE(Class, Base)
8798#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00008799#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008800#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
8801#define DEPENDENT_TYPE(Class, Base) case Type::Class:
8802#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00008803 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008804
Richard Smith27d807c2013-04-30 13:56:41 +00008805 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00008806 case Type::DeducedTemplateSpecialization:
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00008807 case Type::LValueReference:
8808 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008809 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00008810 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008811
John McCall8b07ec22010-05-15 11:32:37 +00008812 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008813 case Type::IncompleteArray:
8814 case Type::VariableArray:
8815 case Type::FunctionProto:
8816 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00008817 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008818
Chris Lattnerfd652912008-01-14 05:45:46 +00008819 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00008820 {
8821 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008822 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
8823 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008824 if (Unqualified) {
8825 LHSPointee = LHSPointee.getUnqualifiedType();
8826 RHSPointee = RHSPointee.getUnqualifiedType();
8827 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008828 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008829 Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00008830 if (ResultType.isNull())
8831 return {};
Eli Friedman091a9ac2009-06-02 05:28:56 +00008832 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00008833 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00008834 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00008835 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00008836 return getPointerType(ResultType);
8837 }
Steve Naroff68e167d2008-12-10 17:49:55 +00008838 case Type::BlockPointer:
8839 {
8840 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008841 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
8842 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008843 if (Unqualified) {
8844 LHSPointee = LHSPointee.getUnqualifiedType();
8845 RHSPointee = RHSPointee.getUnqualifiedType();
8846 }
Anastasia Stulova81a25e352017-03-10 15:23:07 +00008847 if (getLangOpts().OpenCL) {
8848 Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
8849 Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
8850 // Blocks can't be an expression in a ternary operator (OpenCL v2.0
8851 // 6.12.5) thus the following check is asymmetric.
8852 if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual))
Eugene Zelenko7855e772018-04-03 00:11:50 +00008853 return {};
Anastasia Stulova81a25e352017-03-10 15:23:07 +00008854 LHSPteeQual.removeAddressSpace();
8855 RHSPteeQual.removeAddressSpace();
8856 LHSPointee =
8857 QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
8858 RHSPointee =
8859 QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
8860 }
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008861 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
8862 Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00008863 if (ResultType.isNull())
8864 return {};
Steve Naroff68e167d2008-12-10 17:49:55 +00008865 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
8866 return LHS;
8867 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
8868 return RHS;
8869 return getBlockPointerType(ResultType);
8870 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00008871 case Type::Atomic:
8872 {
8873 // Merge two pointer types, while trying to preserve typedef info
8874 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
8875 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
8876 if (Unqualified) {
8877 LHSValue = LHSValue.getUnqualifiedType();
8878 RHSValue = RHSValue.getUnqualifiedType();
8879 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008880 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
Eli Friedman0dfb8892011-10-06 23:00:33 +00008881 Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00008882 if (ResultType.isNull())
8883 return {};
Eli Friedman0dfb8892011-10-06 23:00:33 +00008884 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
8885 return LHS;
8886 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
8887 return RHS;
8888 return getAtomicType(ResultType);
8889 }
Chris Lattnerfd652912008-01-14 05:45:46 +00008890 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00008891 {
8892 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
8893 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
8894 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008895 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00008896
8897 QualType LHSElem = getAsArrayType(LHS)->getElementType();
8898 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008899 if (Unqualified) {
8900 LHSElem = LHSElem.getUnqualifiedType();
8901 RHSElem = RHSElem.getUnqualifiedType();
8902 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008903
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008904 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00008905 if (ResultType.isNull())
8906 return {};
Jeremy Morse8129c5c2018-06-05 09:18:26 +00008907
8908 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
8909 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
8910
8911 // If either side is a variable array, and both are complete, check whether
8912 // the current dimension is definite.
8913 if (LVAT || RVAT) {
8914 auto SizeFetch = [this](const VariableArrayType* VAT,
8915 const ConstantArrayType* CAT)
8916 -> std::pair<bool,llvm::APInt> {
8917 if (VAT) {
8918 llvm::APSInt TheInt;
8919 Expr *E = VAT->getSizeExpr();
8920 if (E && E->isIntegerConstantExpr(TheInt, *this))
8921 return std::make_pair(true, TheInt);
8922 else
8923 return std::make_pair(false, TheInt);
8924 } else if (CAT) {
8925 return std::make_pair(true, CAT->getSize());
8926 } else {
8927 return std::make_pair(false, llvm::APInt());
8928 }
8929 };
8930
8931 bool HaveLSize, HaveRSize;
8932 llvm::APInt LSize, RSize;
8933 std::tie(HaveLSize, LSize) = SizeFetch(LVAT, LCAT);
8934 std::tie(HaveRSize, RSize) = SizeFetch(RVAT, RCAT);
8935 if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(LSize, RSize))
8936 return {}; // Definite, but unequal, array dimension
8937 }
8938
Chris Lattner465fa322008-10-05 17:34:18 +00008939 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
8940 return LHS;
8941 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
8942 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00008943 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
8944 ArrayType::ArraySizeModifier(), 0);
8945 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
8946 ArrayType::ArraySizeModifier(), 0);
Chris Lattner465fa322008-10-05 17:34:18 +00008947 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
8948 return LHS;
8949 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
8950 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00008951 if (LVAT) {
8952 // FIXME: This isn't correct! But tricky to implement because
8953 // the array's size has to be the size of LHS, but the type
8954 // has to be different.
8955 return LHS;
8956 }
8957 if (RVAT) {
8958 // FIXME: This isn't correct! But tricky to implement because
8959 // the array's size has to be the size of RHS, but the type
8960 // has to be different.
8961 return RHS;
8962 }
Eli Friedman3e62c212008-08-22 01:48:21 +00008963 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
8964 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00008965 return getIncompleteArrayType(ResultType,
8966 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00008967 }
Chris Lattnerfd652912008-01-14 05:45:46 +00008968 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008969 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008970 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008971 case Type::Enum:
Eugene Zelenko7855e772018-04-03 00:11:50 +00008972 return {};
Chris Lattnerfd652912008-01-14 05:45:46 +00008973 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00008974 // Only exactly equal builtin types are compatible, which is tested above.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008975 return {};
Daniel Dunbar804c0442009-01-28 21:22:12 +00008976 case Type::Complex:
8977 // Distinct complex types are incompatible.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008978 return {};
Chris Lattner7bbd3d72008-04-07 05:55:38 +00008979 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00008980 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00008981 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
8982 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00008983 return LHS;
Eugene Zelenko7855e772018-04-03 00:11:50 +00008984 return {};
John McCall8b07ec22010-05-15 11:32:37 +00008985 case Type::ObjCObject: {
8986 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00008987 // FIXME: This should be type compatibility, e.g. whether
8988 // "LHS x; RHS x;" at global scope is legal.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008989 const auto *LHSIface = LHS->getAs<ObjCObjectType>();
8990 const auto *RHSIface = RHS->getAs<ObjCObjectType>();
John McCall8b07ec22010-05-15 11:32:37 +00008991 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00008992 return LHS;
8993
Eugene Zelenko7855e772018-04-03 00:11:50 +00008994 return {};
Cedric Venet4fc88b72009-02-21 17:14:49 +00008995 }
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00008996 case Type::ObjCObjectPointer:
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008997 if (OfBlockPointer) {
8998 if (canAssignObjCInterfacesInBlockPointer(
8999 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00009000 RHS->getAs<ObjCObjectPointerType>(),
9001 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00009002 return LHS;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009003 return {};
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00009004 }
John McCall9dd450b2009-09-21 23:43:11 +00009005 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
9006 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00009007 return LHS;
9008
Eugene Zelenko7855e772018-04-03 00:11:50 +00009009 return {};
Xiuli Pan9c14e282016-01-09 12:53:17 +00009010 case Type::Pipe:
Joey Goulye3c85de2016-12-01 11:30:49 +00009011 assert(LHS != RHS &&
9012 "Equivalent pipe types should have already been handled!");
Eugene Zelenko7855e772018-04-03 00:11:50 +00009013 return {};
Xiuli Pan9c14e282016-01-09 12:53:17 +00009014 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00009015
David Blaikie8a40f702012-01-17 06:56:22 +00009016 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00009017}
Ted Kremenekfc581a92007-10-31 17:10:13 +00009018
Akira Hatanaka98a49332017-09-22 00:41:05 +00009019bool ASTContext::mergeExtParameterInfo(
9020 const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType,
9021 bool &CanUseFirst, bool &CanUseSecond,
9022 SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &NewParamInfos) {
9023 assert(NewParamInfos.empty() && "param info list not empty");
9024 CanUseFirst = CanUseSecond = true;
9025 bool FirstHasInfo = FirstFnType->hasExtParameterInfos();
9026 bool SecondHasInfo = SecondFnType->hasExtParameterInfos();
9027
John McCall18afab72016-03-01 00:49:02 +00009028 // Fast path: if the first type doesn't have ext parameter infos,
Akira Hatanaka98a49332017-09-22 00:41:05 +00009029 // we match if and only if the second type also doesn't have them.
9030 if (!FirstHasInfo && !SecondHasInfo)
9031 return true;
John McCall18afab72016-03-01 00:49:02 +00009032
Akira Hatanaka98a49332017-09-22 00:41:05 +00009033 bool NeedParamInfo = false;
9034 size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size()
9035 : SecondFnType->getExtParameterInfos().size();
John McCall18afab72016-03-01 00:49:02 +00009036
Akira Hatanaka98a49332017-09-22 00:41:05 +00009037 for (size_t I = 0; I < E; ++I) {
9038 FunctionProtoType::ExtParameterInfo FirstParam, SecondParam;
9039 if (FirstHasInfo)
9040 FirstParam = FirstFnType->getExtParameterInfo(I);
9041 if (SecondHasInfo)
9042 SecondParam = SecondFnType->getExtParameterInfo(I);
John McCall18afab72016-03-01 00:49:02 +00009043
Akira Hatanaka98a49332017-09-22 00:41:05 +00009044 // Cannot merge unless everything except the noescape flag matches.
9045 if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false))
John McCall18afab72016-03-01 00:49:02 +00009046 return false;
Akira Hatanaka98a49332017-09-22 00:41:05 +00009047
9048 bool FirstNoEscape = FirstParam.isNoEscape();
9049 bool SecondNoEscape = SecondParam.isNoEscape();
9050 bool IsNoEscape = FirstNoEscape && SecondNoEscape;
9051 NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape));
9052 if (NewParamInfos.back().getOpaqueValue())
9053 NeedParamInfo = true;
9054 if (FirstNoEscape != IsNoEscape)
9055 CanUseFirst = false;
9056 if (SecondNoEscape != IsNoEscape)
9057 CanUseSecond = false;
John McCall18afab72016-03-01 00:49:02 +00009058 }
Akira Hatanaka98a49332017-09-22 00:41:05 +00009059
9060 if (!NeedParamInfo)
9061 NewParamInfos.clear();
9062
Fariborz Jahanian97676972011-09-28 21:52:05 +00009063 return true;
9064}
9065
Chandler Carruth21c90602015-12-30 03:24:14 +00009066void ASTContext::ResetObjCLayout(const ObjCContainerDecl *CD) {
9067 ObjCLayouts[CD] = nullptr;
9068}
9069
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009070/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
9071/// 'RHS' attributes and returns the merged version; including for function
9072/// return types.
9073QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
9074 QualType LHSCan = getCanonicalType(LHS),
9075 RHSCan = getCanonicalType(RHS);
9076 // If two types are identical, they are compatible.
9077 if (LHSCan == RHSCan)
9078 return LHS;
9079 if (RHSCan->isFunctionType()) {
9080 if (!LHSCan->isFunctionType())
Eugene Zelenko7855e772018-04-03 00:11:50 +00009081 return {};
Alp Toker314cc812014-01-25 16:55:45 +00009082 QualType OldReturnType =
9083 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009084 QualType NewReturnType =
Alp Toker314cc812014-01-25 16:55:45 +00009085 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
Fangrui Song6907ce22018-07-30 19:24:48 +00009086 QualType ResReturnType =
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009087 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
9088 if (ResReturnType.isNull())
Eugene Zelenko7855e772018-04-03 00:11:50 +00009089 return {};
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009090 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
9091 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
9092 // In either case, use OldReturnType to build the new function type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00009093 const auto *F = LHS->getAs<FunctionType>();
9094 if (const auto *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00009095 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9096 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner896b32f2013-06-10 20:51:09 +00009097 QualType ResultType =
Alp Toker9cacbab2014-01-20 20:26:09 +00009098 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009099 return ResultType;
9100 }
9101 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00009102 return {};
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009103 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009104
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009105 // If the qualifiers are different, the types can still be merged.
9106 Qualifiers LQuals = LHSCan.getLocalQualifiers();
9107 Qualifiers RQuals = RHSCan.getLocalQualifiers();
9108 if (LQuals != RQuals) {
9109 // If any of these qualifiers are different, we have a type mismatch.
9110 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
9111 LQuals.getAddressSpace() != RQuals.getAddressSpace())
Eugene Zelenko7855e772018-04-03 00:11:50 +00009112 return {};
Fangrui Song6907ce22018-07-30 19:24:48 +00009113
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009114 // Exactly one GC qualifier difference is allowed: __strong is
9115 // okay if the other type has no GC qualifier but is an Objective
9116 // C object pointer (i.e. implicitly strong by default). We fix
9117 // this by pretending that the unqualified type was actually
9118 // qualified __strong.
9119 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
9120 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
9121 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
Fangrui Song6907ce22018-07-30 19:24:48 +00009122
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009123 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
Eugene Zelenko7855e772018-04-03 00:11:50 +00009124 return {};
Fangrui Song6907ce22018-07-30 19:24:48 +00009125
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009126 if (GC_L == Qualifiers::Strong)
9127 return LHS;
9128 if (GC_R == Qualifiers::Strong)
9129 return RHS;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009130 return {};
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009131 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009132
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009133 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
9134 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
9135 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
9136 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
9137 if (ResQT == LHSBaseQT)
9138 return LHS;
9139 if (ResQT == RHSBaseQT)
9140 return RHS;
9141 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00009142 return {};
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009143}
9144
Chris Lattner4ba0cef2008-04-07 07:01:58 +00009145//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009146// Integer Predicates
9147//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00009148
Jay Foad39c79802011-01-12 09:06:06 +00009149unsigned ASTContext::getIntWidth(QualType T) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00009150 if (const auto *ET = T->getAs<EnumType>())
Eli Friedmanee275c82009-12-10 22:29:29 +00009151 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00009152 if (T->isBooleanType())
9153 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00009154 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009155 return (unsigned)getTypeSize(T);
9156}
9157
Abramo Bagnara13640492012-09-09 10:21:24 +00009158QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Leonard Chanab80f3c2018-06-14 14:53:51 +00009159 assert((T->hasSignedIntegerRepresentation() || T->isSignedFixedPointType()) &&
9160 "Unexpected type");
Fangrui Song6907ce22018-07-30 19:24:48 +00009161
Chris Lattnerec3a1562009-10-17 20:33:28 +00009162 // Turn <4 x signed int> -> <4 x unsigned int>
Eugene Zelenko7855e772018-04-03 00:11:50 +00009163 if (const auto *VTy = T->getAs<VectorType>())
Chris Lattnerec3a1562009-10-17 20:33:28 +00009164 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00009165 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00009166
9167 // For enums, we return the unsigned version of the base type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00009168 if (const auto *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009169 T = ETy->getDecl()->getIntegerType();
Fangrui Song6907ce22018-07-30 19:24:48 +00009170
Eugene Zelenko7855e772018-04-03 00:11:50 +00009171 const auto *BTy = T->getAs<BuiltinType>();
Leonard Chanab80f3c2018-06-14 14:53:51 +00009172 assert(BTy && "Unexpected signed integer or fixed point type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009173 switch (BTy->getKind()) {
9174 case BuiltinType::Char_S:
9175 case BuiltinType::SChar:
9176 return UnsignedCharTy;
9177 case BuiltinType::Short:
9178 return UnsignedShortTy;
9179 case BuiltinType::Int:
9180 return UnsignedIntTy;
9181 case BuiltinType::Long:
9182 return UnsignedLongTy;
9183 case BuiltinType::LongLong:
9184 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00009185 case BuiltinType::Int128:
9186 return UnsignedInt128Ty;
Leonard Chanab80f3c2018-06-14 14:53:51 +00009187
9188 case BuiltinType::ShortAccum:
9189 return UnsignedShortAccumTy;
9190 case BuiltinType::Accum:
9191 return UnsignedAccumTy;
9192 case BuiltinType::LongAccum:
9193 return UnsignedLongAccumTy;
9194 case BuiltinType::SatShortAccum:
9195 return SatUnsignedShortAccumTy;
9196 case BuiltinType::SatAccum:
9197 return SatUnsignedAccumTy;
9198 case BuiltinType::SatLongAccum:
9199 return SatUnsignedLongAccumTy;
9200 case BuiltinType::ShortFract:
9201 return UnsignedShortFractTy;
9202 case BuiltinType::Fract:
9203 return UnsignedFractTy;
9204 case BuiltinType::LongFract:
9205 return UnsignedLongFractTy;
9206 case BuiltinType::SatShortFract:
9207 return SatUnsignedShortFractTy;
9208 case BuiltinType::SatFract:
9209 return SatUnsignedFractTy;
9210 case BuiltinType::SatLongFract:
9211 return SatUnsignedLongFractTy;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009212 default:
Leonard Chanab80f3c2018-06-14 14:53:51 +00009213 llvm_unreachable("Unexpected signed integer or fixed point type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009214 }
9215}
9216
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009217ASTMutationListener::~ASTMutationListener() = default;
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00009218
Richard Smith1fa5d642013-05-11 05:45:24 +00009219void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
9220 QualType ReturnType) {}
Chris Lattnerecd79c62009-06-14 00:45:47 +00009221
9222//===----------------------------------------------------------------------===//
9223// Builtin Type Computation
9224//===----------------------------------------------------------------------===//
9225
9226/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00009227/// pointer over the consumed characters. This returns the resultant type. If
9228/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
9229/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
9230/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009231///
9232/// RequiresICE is filled in on return to indicate whether the value is required
9233/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00009234static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00009235 ASTContext::GetBuiltinTypeError &Error,
Chandler Carruth45bbe012017-03-24 09:11:57 +00009236 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00009237 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00009238 // Modifiers.
9239 int HowLong = 0;
9240 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009241 RequiresICE = false;
Fangrui Song6907ce22018-07-30 19:24:48 +00009242
Chris Lattnerdc226c22010-10-01 22:42:38 +00009243 // Read the prefixed modifiers first.
Eric Christopher50daf5f2017-07-10 21:28:54 +00009244 bool Done = false;
9245 #ifndef NDEBUG
9246 bool IsSpecialLong = false;
9247 #endif
Chris Lattnerecd79c62009-06-14 00:45:47 +00009248 while (!Done) {
9249 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00009250 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00009251 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009252 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00009253 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009254 case 'S':
9255 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
9256 assert(!Signed && "Can't use 'S' modifier multiple times!");
9257 Signed = true;
9258 break;
9259 case 'U':
9260 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
Sean Silva2a995142015-01-16 21:44:26 +00009261 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00009262 Unsigned = true;
9263 break;
9264 case 'L':
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00009265 assert(!IsSpecialLong && "Can't use 'L' with 'W' or 'N' modifiers");
Chris Lattnerecd79c62009-06-14 00:45:47 +00009266 assert(HowLong <= 2 && "Can't have LLLL modifier");
9267 ++HowLong;
9268 break;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009269 case 'N':
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00009270 // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
9271 assert(!IsSpecialLong && "Can't use two 'N' or 'W' modifiers!");
9272 assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
Eric Christopher50daf5f2017-07-10 21:28:54 +00009273 #ifndef NDEBUG
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00009274 IsSpecialLong = true;
Eric Christopher50daf5f2017-07-10 21:28:54 +00009275 #endif
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00009276 if (Context.getTargetInfo().getLongWidth() == 32)
9277 ++HowLong;
9278 break;
Kevin Qinad64f6d2014-02-24 02:45:03 +00009279 case 'W':
9280 // This modifier represents int64 type.
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00009281 assert(!IsSpecialLong && "Can't use two 'N' or 'W' modifiers!");
Kevin Qinad64f6d2014-02-24 02:45:03 +00009282 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
Eric Christopher50daf5f2017-07-10 21:28:54 +00009283 #ifndef NDEBUG
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00009284 IsSpecialLong = true;
Eric Christopher50daf5f2017-07-10 21:28:54 +00009285 #endif
Kevin Qinad64f6d2014-02-24 02:45:03 +00009286 switch (Context.getTargetInfo().getInt64Type()) {
9287 default:
9288 llvm_unreachable("Unexpected integer type");
9289 case TargetInfo::SignedLong:
9290 HowLong = 1;
9291 break;
9292 case TargetInfo::SignedLongLong:
9293 HowLong = 2;
9294 break;
9295 }
Duncan P. N. Exon Smitheae8caa2017-06-14 21:26:31 +00009296 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009297 }
9298 }
9299
9300 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00009301
Chris Lattnerecd79c62009-06-14 00:45:47 +00009302 // Read the base type.
9303 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00009304 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00009305 case 'v':
9306 assert(HowLong == 0 && !Signed && !Unsigned &&
9307 "Bad modifiers used with 'v'!");
9308 Type = Context.VoidTy;
9309 break;
Jack Carter24bef982013-08-15 15:16:57 +00009310 case 'h':
9311 assert(HowLong == 0 && !Signed && !Unsigned &&
Sean Silva2a995142015-01-16 21:44:26 +00009312 "Bad modifiers used with 'h'!");
Jack Carter24bef982013-08-15 15:16:57 +00009313 Type = Context.HalfTy;
9314 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009315 case 'f':
9316 assert(HowLong == 0 && !Signed && !Unsigned &&
9317 "Bad modifiers used with 'f'!");
9318 Type = Context.FloatTy;
9319 break;
9320 case 'd':
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009321 assert(HowLong < 3 && !Signed && !Unsigned &&
Chris Lattnerecd79c62009-06-14 00:45:47 +00009322 "Bad modifiers used with 'd'!");
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009323 if (HowLong == 1)
Chris Lattnerecd79c62009-06-14 00:45:47 +00009324 Type = Context.LongDoubleTy;
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009325 else if (HowLong == 2)
9326 Type = Context.Float128Ty;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009327 else
9328 Type = Context.DoubleTy;
9329 break;
9330 case 's':
9331 assert(HowLong == 0 && "Bad modifiers used with 's'!");
9332 if (Unsigned)
9333 Type = Context.UnsignedShortTy;
9334 else
9335 Type = Context.ShortTy;
9336 break;
9337 case 'i':
9338 if (HowLong == 3)
9339 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
9340 else if (HowLong == 2)
9341 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
9342 else if (HowLong == 1)
9343 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
9344 else
9345 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
9346 break;
9347 case 'c':
9348 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
9349 if (Signed)
9350 Type = Context.SignedCharTy;
9351 else if (Unsigned)
9352 Type = Context.UnsignedCharTy;
9353 else
9354 Type = Context.CharTy;
9355 break;
9356 case 'b': // boolean
9357 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
9358 Type = Context.BoolTy;
9359 break;
9360 case 'z': // size_t.
9361 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
9362 Type = Context.getSizeType();
9363 break;
Richard Smith8110c9d2016-11-29 19:45:17 +00009364 case 'w': // wchar_t.
9365 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
9366 Type = Context.getWideCharType();
9367 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009368 case 'F':
9369 Type = Context.getCFConstantStringType();
9370 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00009371 case 'G':
9372 Type = Context.getObjCIdType();
9373 break;
9374 case 'H':
9375 Type = Context.getObjCSelType();
9376 break;
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00009377 case 'M':
9378 Type = Context.getObjCSuperType();
9379 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009380 case 'a':
9381 Type = Context.getBuiltinVaListType();
9382 assert(!Type.isNull() && "builtin va list type not initialized!");
9383 break;
9384 case 'A':
9385 // This is a "reference" to a va_list; however, what exactly
9386 // this means depends on how va_list is defined. There are two
9387 // different kinds of va_list: ones passed by value, and ones
9388 // passed by reference. An example of a by-value va_list is
9389 // x86, where va_list is a char*. An example of by-ref va_list
9390 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
9391 // we want this argument to be a char*&; for x86-64, we want
9392 // it to be a __va_list_tag*.
9393 Type = Context.getBuiltinVaListType();
9394 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009395 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00009396 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009397 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00009398 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009399 break;
9400 case 'V': {
9401 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009402 unsigned NumElements = strtoul(Str, &End, 10);
9403 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00009404 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00009405
Fangrui Song6907ce22018-07-30 19:24:48 +00009406 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
Chandler Carruth45bbe012017-03-24 09:11:57 +00009407 RequiresICE, false);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009408 assert(!RequiresICE && "Can't require vector ICE");
Fangrui Song6907ce22018-07-30 19:24:48 +00009409
Chris Lattnerdc226c22010-10-01 22:42:38 +00009410 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00009411 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00009412 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009413 break;
9414 }
Douglas Gregorfed66992012-06-07 18:08:25 +00009415 case 'E': {
9416 char *End;
Fangrui Song6907ce22018-07-30 19:24:48 +00009417
Douglas Gregorfed66992012-06-07 18:08:25 +00009418 unsigned NumElements = strtoul(Str, &End, 10);
9419 assert(End != Str && "Missing vector size");
Fangrui Song6907ce22018-07-30 19:24:48 +00009420
Douglas Gregorfed66992012-06-07 18:08:25 +00009421 Str = End;
Fangrui Song6907ce22018-07-30 19:24:48 +00009422
Douglas Gregorfed66992012-06-07 18:08:25 +00009423 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
Chandler Carruth45bbe012017-03-24 09:11:57 +00009424 false);
Douglas Gregorfed66992012-06-07 18:08:25 +00009425 Type = Context.getExtVectorType(ElementType, NumElements);
Fangrui Song6907ce22018-07-30 19:24:48 +00009426 break;
Douglas Gregorfed66992012-06-07 18:08:25 +00009427 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00009428 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009429 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
Chandler Carruth45bbe012017-03-24 09:11:57 +00009430 false);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009431 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00009432 Type = Context.getComplexType(ElementType);
9433 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00009434 }
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009435 case 'Y':
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00009436 Type = Context.getPointerDiffType();
9437 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00009438 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00009439 Type = Context.getFILEType();
9440 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00009441 Error = ASTContext::GE_Missing_stdio;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009442 return {};
Chris Lattnerecd79c62009-06-14 00:45:47 +00009443 }
Mike Stump2adb4da2009-07-28 23:47:15 +00009444 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00009445 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00009446 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00009447 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00009448 else
9449 Type = Context.getjmp_bufType();
9450
Mike Stump2adb4da2009-07-28 23:47:15 +00009451 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00009452 Error = ASTContext::GE_Missing_setjmp;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009453 return {};
Mike Stump2adb4da2009-07-28 23:47:15 +00009454 }
9455 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00009456 case 'K':
9457 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
9458 Type = Context.getucontext_tType();
9459
9460 if (Type.isNull()) {
9461 Error = ASTContext::GE_Missing_ucontext;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009462 return {};
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00009463 }
9464 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00009465 case 'p':
9466 Type = Context.getProcessIDType();
9467 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00009468 }
Mike Stump11289f42009-09-09 15:08:12 +00009469
Chris Lattnerdc226c22010-10-01 22:42:38 +00009470 // If there are modifiers and if we're allowed to parse them, go for it.
9471 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009472 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00009473 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00009474 default: Done = true; --Str; break;
9475 case '*':
9476 case '&': {
9477 // Both pointers and references can have their pointee types
9478 // qualified with an address space.
9479 char *End;
9480 unsigned AddrSpace = strtoul(Str, &End, 10);
Matt Arsenaultc65f9662018-08-02 12:14:28 +00009481 if (End != Str) {
9482 // Note AddrSpace == 0 is not the same as an unspecified address space.
9483 Type = Context.getAddrSpaceQualType(
9484 Type,
9485 Context.getLangASForBuiltinAddressSpace(AddrSpace));
Chris Lattnerdc226c22010-10-01 22:42:38 +00009486 Str = End;
9487 }
9488 if (c == '*')
9489 Type = Context.getPointerType(Type);
9490 else
9491 Type = Context.getLValueReferenceType(Type);
9492 break;
9493 }
9494 // FIXME: There's no way to have a built-in with an rvalue ref arg.
9495 case 'C':
9496 Type = Type.withConst();
9497 break;
9498 case 'D':
9499 Type = Context.getVolatileType(Type);
9500 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00009501 case 'R':
9502 Type = Type.withRestrict();
9503 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009504 }
9505 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009506
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009507 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Fangrui Song6907ce22018-07-30 19:24:48 +00009508 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00009509
Chris Lattnerecd79c62009-06-14 00:45:47 +00009510 return Type;
9511}
9512
9513/// GetBuiltinType - Return the type for the specified builtin.
Chandler Carruth45bbe012017-03-24 09:11:57 +00009514QualType ASTContext::GetBuiltinType(unsigned Id,
9515 GetBuiltinTypeError &Error,
9516 unsigned *IntegerConstantArgs) const {
Eric Christopher02d5d862015-08-06 01:01:12 +00009517 const char *TypeStr = BuiltinInfo.getTypeString(Id);
Johannes Doerfertac991bb2019-01-19 05:36:54 +00009518 if (TypeStr[0] == '\0') {
9519 Error = GE_Missing_type;
9520 return {};
9521 }
Mike Stump11289f42009-09-09 15:08:12 +00009522
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009523 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00009524
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009525 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009526 Error = GE_None;
Chandler Carruth45bbe012017-03-24 09:11:57 +00009527 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
9528 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009529 if (Error != GE_None)
Eugene Zelenko7855e772018-04-03 00:11:50 +00009530 return {};
Fangrui Song6907ce22018-07-30 19:24:48 +00009531
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009532 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
Fangrui Song6907ce22018-07-30 19:24:48 +00009533
Chris Lattnerecd79c62009-06-14 00:45:47 +00009534 while (TypeStr[0] && TypeStr[0] != '.') {
Chandler Carruth45bbe012017-03-24 09:11:57 +00009535 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009536 if (Error != GE_None)
Eugene Zelenko7855e772018-04-03 00:11:50 +00009537 return {};
Chris Lattnerecd79c62009-06-14 00:45:47 +00009538
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009539 // If this argument is required to be an IntegerConstantExpression and the
9540 // caller cares, fill in the bitmask we return.
9541 if (RequiresICE && IntegerConstantArgs)
9542 *IntegerConstantArgs |= 1 << ArgTypes.size();
Fangrui Song6907ce22018-07-30 19:24:48 +00009543
Chris Lattnerecd79c62009-06-14 00:45:47 +00009544 // Do array -> pointer decay. The builtin should use the decayed type.
9545 if (Ty->isArrayType())
9546 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00009547
Chris Lattnerecd79c62009-06-14 00:45:47 +00009548 ArgTypes.push_back(Ty);
9549 }
9550
David Majnemerba3e5ec2015-03-13 18:26:17 +00009551 if (Id == Builtin::BI__GetExceptionInfo)
Eugene Zelenko7855e772018-04-03 00:11:50 +00009552 return {};
David Majnemerba3e5ec2015-03-13 18:26:17 +00009553
Chris Lattnerecd79c62009-06-14 00:45:47 +00009554 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
9555 "'.' should only occur at end of builtin type list!");
9556
Erich Keane881e83d2019-03-04 14:54:52 +00009557 bool Variadic = (TypeStr[0] == '.');
9558
9559 FunctionType::ExtInfo EI(
9560 getDefaultCallingConvention(Variadic, /*IsCXXMethod=*/false));
John McCall991eb4b2010-12-21 00:44:39 +00009561 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
9562
John McCall991eb4b2010-12-21 00:44:39 +00009563
Richard Smith836de6b2016-12-19 23:59:34 +00009564 // We really shouldn't be making a no-proto type here.
9565 if (ArgTypes.empty() && Variadic && !getLangOpts().CPlusPlus)
John McCall991eb4b2010-12-21 00:44:39 +00009566 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00009567
John McCalldb40c7f2010-12-14 08:05:40 +00009568 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00009569 EPI.ExtInfo = EI;
9570 EPI.Variadic = Variadic;
Richard Smith391fb862016-10-18 07:13:55 +00009571 if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id))
9572 EPI.ExceptionSpec.Type =
9573 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
John McCalldb40c7f2010-12-14 08:05:40 +00009574
Jordan Rose5c382722013-03-08 21:51:21 +00009575 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009576}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00009577
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009578static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
9579 const FunctionDecl *FD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00009580 if (!FD->isExternallyVisible())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009581 return GVA_Internal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009582
Richard Smithe2467b72017-11-16 23:54:56 +00009583 // Non-user-provided functions get emitted as weak definitions with every
9584 // use, no matter whether they've been explicitly instantiated etc.
Eugene Zelenko7855e772018-04-03 00:11:50 +00009585 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
Richard Smithe2467b72017-11-16 23:54:56 +00009586 if (!MD->isUserProvided())
9587 return GVA_DiscardableODR;
9588
Yaron Keren4cd211b2017-02-22 14:32:39 +00009589 GVALinkage External;
Rafael Espindola3ae00052013-05-13 00:12:11 +00009590 switch (FD->getTemplateSpecializationKind()) {
9591 case TSK_Undeclared:
9592 case TSK_ExplicitSpecialization:
9593 External = GVA_StrongExternal;
9594 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009595
Rafael Espindola3ae00052013-05-13 00:12:11 +00009596 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00009597 return GVA_StrongODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00009598
David Majnemerc3d07332014-05-15 06:25:57 +00009599 // C++11 [temp.explicit]p10:
9600 // [ Note: The intent is that an inline function that is the subject of
9601 // an explicit instantiation declaration will still be implicitly
9602 // instantiated when used so that the body can be considered for
9603 // inlining, but that no out-of-line copy of the inline function would be
9604 // generated in the translation unit. -- end note ]
Rafael Espindola3ae00052013-05-13 00:12:11 +00009605 case TSK_ExplicitInstantiationDeclaration:
David Majnemer27d69db2014-04-28 22:17:59 +00009606 return GVA_AvailableExternally;
9607
Rafael Espindola3ae00052013-05-13 00:12:11 +00009608 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00009609 External = GVA_DiscardableODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00009610 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009611 }
9612
9613 if (!FD->isInlined())
9614 return External;
David Majnemer62f0ffd2013-08-01 17:26:42 +00009615
David Majnemer3f021502015-10-08 04:53:31 +00009616 if ((!Context.getLangOpts().CPlusPlus &&
9617 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009618 !FD->hasAttr<DLLExportAttr>()) ||
David Majnemer62f0ffd2013-08-01 17:26:42 +00009619 FD->hasAttr<GNUInlineAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009620 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
9621
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009622 // GNU or C99 inline semantics. Determine whether this symbol should be
9623 // externally visible.
9624 if (FD->isInlineDefinitionExternallyVisible())
9625 return External;
9626
9627 // C99 inline semantics, where the symbol is not externally visible.
David Majnemer27d69db2014-04-28 22:17:59 +00009628 return GVA_AvailableExternally;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009629 }
9630
David Majnemer54e3ba52014-04-02 23:17:29 +00009631 // Functions specified with extern and inline in -fms-compatibility mode
9632 // forcibly get emitted. While the body of the function cannot be later
9633 // replaced, the function definition cannot be discarded.
David Majnemer73768702015-03-20 00:02:27 +00009634 if (FD->isMSExternInline())
David Majnemer54e3ba52014-04-02 23:17:29 +00009635 return GVA_StrongODR;
9636
David Majnemer27d69db2014-04-28 22:17:59 +00009637 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009638}
9639
Artem Belevichca2b9512016-05-02 20:30:03 +00009640static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context,
Richard Smitha4653622017-09-06 20:01:14 +00009641 const Decl *D, GVALinkage L) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009642 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
9643 // dllexport/dllimport on inline functions.
9644 if (D->hasAttr<DLLImportAttr>()) {
9645 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
9646 return GVA_AvailableExternally;
Artem Belevichca2b9512016-05-02 20:30:03 +00009647 } else if (D->hasAttr<DLLExportAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009648 if (L == GVA_DiscardableODR)
9649 return GVA_StrongODR;
Artem Belevichca2b9512016-05-02 20:30:03 +00009650 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice &&
9651 D->hasAttr<CUDAGlobalAttr>()) {
9652 // Device-side functions with __global__ attribute must always be
9653 // visible externally so they can be launched from host.
9654 if (L == GVA_DiscardableODR || L == GVA_Internal)
9655 return GVA_StrongODR;
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009656 }
9657 return L;
9658}
9659
Richard Smitha4653622017-09-06 20:01:14 +00009660/// Adjust the GVALinkage for a declaration based on what an external AST source
9661/// knows about whether there can be other definitions of this declaration.
9662static GVALinkage
9663adjustGVALinkageForExternalDefinitionKind(const ASTContext &Ctx, const Decl *D,
9664 GVALinkage L) {
9665 ExternalASTSource *Source = Ctx.getExternalSource();
9666 if (!Source)
9667 return L;
9668
9669 switch (Source->hasExternalDefinitions(D)) {
David Blaikie9ffe5a32017-01-30 05:00:26 +00009670 case ExternalASTSource::EK_Never:
Richard Smitha4653622017-09-06 20:01:14 +00009671 // Other translation units rely on us to provide the definition.
David Blaikie9ffe5a32017-01-30 05:00:26 +00009672 if (L == GVA_DiscardableODR)
9673 return GVA_StrongODR;
9674 break;
Richard Smitha4653622017-09-06 20:01:14 +00009675
David Blaikie9ffe5a32017-01-30 05:00:26 +00009676 case ExternalASTSource::EK_Always:
9677 return GVA_AvailableExternally;
Richard Smitha4653622017-09-06 20:01:14 +00009678
David Blaikie9ffe5a32017-01-30 05:00:26 +00009679 case ExternalASTSource::EK_ReplyHazy:
9680 break;
9681 }
9682 return L;
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009683}
9684
Richard Smitha4653622017-09-06 20:01:14 +00009685GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
9686 return adjustGVALinkageForExternalDefinitionKind(*this, FD,
9687 adjustGVALinkageForAttributes(*this, FD,
9688 basicGVALinkageForFunction(*this, FD)));
9689}
9690
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009691static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
9692 const VarDecl *VD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00009693 if (!VD->isExternallyVisible())
9694 return GVA_Internal;
9695
David Majnemer27d69db2014-04-28 22:17:59 +00009696 if (VD->isStaticLocal()) {
David Majnemer27d69db2014-04-28 22:17:59 +00009697 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
9698 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
9699 LexicalContext = LexicalContext->getLexicalParent();
9700
David Blaikieeb210012017-01-27 23:11:10 +00009701 // ObjC Blocks can create local variables that don't have a FunctionDecl
9702 // LexicalContext.
9703 if (!LexicalContext)
9704 return GVA_DiscardableODR;
David Majnemer27d69db2014-04-28 22:17:59 +00009705
David Blaikieeb210012017-01-27 23:11:10 +00009706 // Otherwise, let the static local variable inherit its linkage from the
9707 // nearest enclosing function.
9708 auto StaticLocalLinkage =
9709 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
9710
9711 // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
9712 // be emitted in any object with references to the symbol for the object it
9713 // contains, whether inline or out-of-line."
9714 // Similar behavior is observed with MSVC. An alternative ABI could use
9715 // StrongODR/AvailableExternally to match the function, but none are
9716 // known/supported currently.
9717 if (StaticLocalLinkage == GVA_StrongODR ||
9718 StaticLocalLinkage == GVA_AvailableExternally)
9719 return GVA_DiscardableODR;
9720 return StaticLocalLinkage;
David Majnemer27d69db2014-04-28 22:17:59 +00009721 }
9722
Hans Wennborg56fc62b2014-07-17 20:25:23 +00009723 // MSVC treats in-class initialized static data members as definitions.
9724 // By giving them non-strong linkage, out-of-line definitions won't
9725 // cause link errors.
9726 if (Context.isMSStaticDataMemberInlineDefinition(VD))
9727 return GVA_DiscardableODR;
9728
Richard Smithd9b90092016-07-02 01:32:16 +00009729 // Most non-template variables have strong linkage; inline variables are
9730 // linkonce_odr or (occasionally, for compatibility) weak_odr.
9731 GVALinkage StrongLinkage;
9732 switch (Context.getInlineVariableDefinitionKind(VD)) {
9733 case ASTContext::InlineVariableDefinitionKind::None:
9734 StrongLinkage = GVA_StrongExternal;
9735 break;
9736 case ASTContext::InlineVariableDefinitionKind::Weak:
9737 case ASTContext::InlineVariableDefinitionKind::WeakUnknown:
Richard Smith62f19e72016-06-25 00:15:56 +00009738 StrongLinkage = GVA_DiscardableODR;
Richard Smithd9b90092016-07-02 01:32:16 +00009739 break;
9740 case ASTContext::InlineVariableDefinitionKind::Strong:
9741 StrongLinkage = GVA_StrongODR;
9742 break;
9743 }
Richard Smith62f19e72016-06-25 00:15:56 +00009744
Richard Smith8809a0c2013-09-27 20:14:12 +00009745 switch (VD->getTemplateSpecializationKind()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00009746 case TSK_Undeclared:
Richard Smith62f19e72016-06-25 00:15:56 +00009747 return StrongLinkage;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009748
David Majnemer6d1780c2015-07-17 23:36:49 +00009749 case TSK_ExplicitSpecialization:
David Majnemer3f021502015-10-08 04:53:31 +00009750 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
9751 VD->isStaticDataMember()
David Majnemer6d1780c2015-07-17 23:36:49 +00009752 ? GVA_StrongODR
Richard Smith62f19e72016-06-25 00:15:56 +00009753 : StrongLinkage;
David Majnemer6d1780c2015-07-17 23:36:49 +00009754
Rafael Espindola3ae00052013-05-13 00:12:11 +00009755 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00009756 return GVA_StrongODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009757
David Majnemer27d69db2014-04-28 22:17:59 +00009758 case TSK_ExplicitInstantiationDeclaration:
9759 return GVA_AvailableExternally;
9760
Rafael Espindola3ae00052013-05-13 00:12:11 +00009761 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00009762 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009763 }
Rafael Espindola27699c82013-05-13 14:05:53 +00009764
9765 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009766}
9767
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009768GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
Richard Smitha4653622017-09-06 20:01:14 +00009769 return adjustGVALinkageForExternalDefinitionKind(*this, VD,
9770 adjustGVALinkageForAttributes(*this, VD,
9771 basicGVALinkageForVariable(*this, VD)));
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009772}
9773
David Blaikiee6b7c282017-04-11 20:46:34 +00009774bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00009775 if (const auto *VD = dyn_cast<VarDecl>(D)) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009776 if (!VD->isFileVarDecl())
9777 return false;
Renato Golin9258aa52014-05-21 10:40:27 +00009778 // Global named register variables (GNU extension) are never emitted.
9779 if (VD->getStorageClass() == SC_Register)
9780 return false;
Richard Smith7747ce22015-08-19 20:49:38 +00009781 if (VD->getDescribedVarTemplate() ||
9782 isa<VarTemplatePartialSpecializationDecl>(VD))
9783 return false;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009784 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
Richard Smith5205a8c2013-04-01 20:22:16 +00009785 // We never need to emit an uninstantiated function template.
9786 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
9787 return false;
Nico Weber66220292016-03-02 17:28:48 +00009788 } else if (isa<PragmaCommentDecl>(D))
9789 return true;
Nico Webercbbaeb12016-03-02 19:28:54 +00009790 else if (isa<PragmaDetectMismatchDecl>(D))
9791 return true;
Nico Weber66220292016-03-02 17:28:48 +00009792 else if (isa<OMPThreadPrivateDecl>(D))
Alexey Bataevc5b1d322016-03-04 09:22:22 +00009793 return !D->getDeclContext()->isDependentContext();
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009794 else if (isa<OMPAllocateDecl>(D))
9795 return !D->getDeclContext()->isDependentContext();
Alexey Bataevc5b1d322016-03-04 09:22:22 +00009796 else if (isa<OMPDeclareReductionDecl>(D))
9797 return !D->getDeclContext()->isDependentContext();
Richard Smithdc1f0422016-07-20 19:10:16 +00009798 else if (isa<ImportDecl>(D))
9799 return true;
Alexey Bataev97720002014-11-11 04:05:39 +00009800 else
Richard Smith5205a8c2013-04-01 20:22:16 +00009801 return false;
9802
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00009803 if (D->isFromASTFile() && !LangOpts.BuildingPCHWithObjectFile) {
9804 assert(getExternalSource() && "It's from an AST file; must have a source.");
9805 // On Windows, PCH files are built together with an object file. If this
9806 // declaration comes from such a PCH and DeclMustBeEmitted would return
9807 // true, it would have returned true and the decl would have been emitted
9808 // into that object file, so it doesn't need to be emitted here.
9809 // Note that decls are still emitted if they're referenced, as usual;
9810 // DeclMustBeEmitted is used to decide whether a decl must be emitted even
9811 // if it's not referenced.
9812 //
9813 // Explicit template instantiation definitions are tricky. If there was an
9814 // explicit template instantiation decl in the PCH before, it will look like
9815 // the definition comes from there, even if that was just the declaration.
9816 // (Explicit instantiation defs of variable templates always get emitted.)
9817 bool IsExpInstDef =
9818 isa<FunctionDecl>(D) &&
9819 cast<FunctionDecl>(D)->getTemplateSpecializationKind() ==
9820 TSK_ExplicitInstantiationDefinition;
9821
Hans Wennborgb51a7032018-09-14 15:18:30 +00009822 // Implicit member function definitions, such as operator= might not be
9823 // marked as template specializations, since they're not coming from a
9824 // template but synthesized directly on the class.
9825 IsExpInstDef |=
9826 isa<CXXMethodDecl>(D) &&
9827 cast<CXXMethodDecl>(D)->getParent()->getTemplateSpecializationKind() ==
9828 TSK_ExplicitInstantiationDefinition;
9829
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00009830 if (getExternalSource()->DeclIsFromPCHWithObjectFile(D) && !IsExpInstDef)
9831 return false;
9832 }
9833
Richard Smith5205a8c2013-04-01 20:22:16 +00009834 // If this is a member of a class template, we do not need to emit it.
9835 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009836 return false;
9837
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00009838 // Weak references don't produce any output by themselves.
9839 if (D->hasAttr<WeakRefAttr>())
9840 return false;
9841
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009842 // Aliases and used decls are required.
9843 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
9844 return true;
9845
Eugene Zelenko7855e772018-04-03 00:11:50 +00009846 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009847 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00009848 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00009849 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009850
9851 // Constructors and destructors are required.
9852 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
9853 return true;
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00009854
John McCall6bd2a892013-01-25 22:31:03 +00009855 // The key function for a class is required. This rule only comes
9856 // into play when inline functions can be key functions, though.
9857 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00009858 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
John McCall6bd2a892013-01-25 22:31:03 +00009859 const CXXRecordDecl *RD = MD->getParent();
9860 if (MD->isOutOfLine() && RD->isDynamicClass()) {
9861 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
9862 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
9863 return true;
9864 }
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009865 }
9866 }
9867
David Blaikie9ffe5a32017-01-30 05:00:26 +00009868 GVALinkage Linkage = GetGVALinkageForFunction(FD);
9869
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009870 // static, static inline, always_inline, and extern inline functions can
9871 // always be deferred. Normal inline functions can be deferred in C99/C++.
9872 // Implicit template instantiations can also be deferred in C++.
David Blaikie9ffe5a32017-01-30 05:00:26 +00009873 return !isDiscardableGVALinkage(Linkage);
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009874 }
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00009875
Eugene Zelenko7855e772018-04-03 00:11:50 +00009876 const auto *VD = cast<VarDecl>(D);
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009877 assert(VD->isFileVarDecl() && "Expected file scoped var");
9878
Alexey Bataevd01b7492018-08-15 19:45:12 +00009879 // If the decl is marked as `declare target to`, it should be emitted for the
9880 // host and for the device.
9881 if (LangOpts.OpenMP &&
9882 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
9883 return true;
9884
Hans Wennborg56fc62b2014-07-17 20:25:23 +00009885 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
9886 !isMSStaticDataMemberInlineDefinition(VD))
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00009887 return false;
9888
Richard Smitha0e5e542012-11-12 21:38:00 +00009889 // Variables that can be needed in other TUs are required.
Richard Smitha4653622017-09-06 20:01:14 +00009890 auto Linkage = GetGVALinkageForVariable(VD);
9891 if (!isDiscardableGVALinkage(Linkage))
Richard Smitha0e5e542012-11-12 21:38:00 +00009892 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009893
Richard Smitha4653622017-09-06 20:01:14 +00009894 // We never need to emit a variable that is available in another TU.
9895 if (Linkage == GVA_AvailableExternally)
9896 return false;
9897
Richard Smitha0e5e542012-11-12 21:38:00 +00009898 // Variables that have destruction with side-effects are required.
9899 if (VD->getType().isDestructedType())
9900 return true;
9901
9902 // Variables that have initialization with side-effects are required.
Richard Smith7747ce22015-08-19 20:49:38 +00009903 if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
Richard Smith187ffb42017-01-20 01:19:46 +00009904 // We can get a value-dependent initializer during error recovery.
9905 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
Richard Smitha0e5e542012-11-12 21:38:00 +00009906 return true;
9907
Richard Smithda383632016-08-15 01:33:41 +00009908 // Likewise, variables with tuple-like bindings are required if their
9909 // bindings have side-effects.
Eugene Zelenko7855e772018-04-03 00:11:50 +00009910 if (const auto *DD = dyn_cast<DecompositionDecl>(VD))
9911 for (const auto *BD : DD->bindings())
9912 if (const auto *BindingVD = BD->getHoldingVar())
Richard Smithda383632016-08-15 01:33:41 +00009913 if (DeclMustBeEmitted(BindingVD))
9914 return true;
9915
Richard Smitha0e5e542012-11-12 21:38:00 +00009916 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009917}
Charles Davis53c59df2010-08-16 03:33:14 +00009918
Erich Keane281d20b2018-01-08 21:34:17 +00009919void ASTContext::forEachMultiversionedFunctionVersion(
9920 const FunctionDecl *FD,
Erich Keane0fb16482018-08-13 18:33:20 +00009921 llvm::function_ref<void(FunctionDecl *)> Pred) const {
Erich Keane281d20b2018-01-08 21:34:17 +00009922 assert(FD->isMultiVersion() && "Only valid for multiversioned functions");
9923 llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls;
Erich Keane7304f0a2018-11-28 20:58:43 +00009924 FD = FD->getMostRecentDecl();
Erich Keane281d20b2018-01-08 21:34:17 +00009925 for (auto *CurDecl :
9926 FD->getDeclContext()->getRedeclContext()->lookup(FD->getDeclName())) {
Erich Keane7304f0a2018-11-28 20:58:43 +00009927 FunctionDecl *CurFD = CurDecl->getAsFunction()->getMostRecentDecl();
Erich Keane281d20b2018-01-08 21:34:17 +00009928 if (CurFD && hasSameType(CurFD->getType(), FD->getType()) &&
9929 std::end(SeenDecls) == llvm::find(SeenDecls, CurFD)) {
9930 SeenDecls.insert(CurFD);
9931 Pred(CurFD);
9932 }
9933 }
9934}
9935
Reid Kleckner78af0702013-08-27 23:08:25 +00009936CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
9937 bool IsCXXMethod) const {
Charles Davis99202b32010-11-09 18:04:24 +00009938 // Pass through to the C++ ABI object
Reid Kleckner78af0702013-08-27 23:08:25 +00009939 if (IsCXXMethod)
9940 return ABI->getDefaultMethodCallConv(IsVariadic);
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00009941
Alexey Bataeva7547182016-05-18 09:06:38 +00009942 switch (LangOpts.getDefaultCallingConv()) {
9943 case LangOptions::DCC_None:
9944 break;
9945 case LangOptions::DCC_CDecl:
9946 return CC_C;
9947 case LangOptions::DCC_FastCall:
Erich Keane5759fa72017-10-24 23:12:01 +00009948 if (getTargetInfo().hasFeature("sse2") && !IsVariadic)
Alexey Bataeva7547182016-05-18 09:06:38 +00009949 return CC_X86FastCall;
9950 break;
9951 case LangOptions::DCC_StdCall:
9952 if (!IsVariadic)
9953 return CC_X86StdCall;
9954 break;
9955 case LangOptions::DCC_VectorCall:
9956 // __vectorcall cannot be applied to variadic functions.
9957 if (!IsVariadic)
9958 return CC_X86VectorCall;
9959 break;
Erich Keanea957ffb2017-11-02 21:08:00 +00009960 case LangOptions::DCC_RegCall:
9961 // __regcall cannot be applied to variadic functions.
9962 if (!IsVariadic)
9963 return CC_X86RegCall;
9964 break;
Alexey Bataeva7547182016-05-18 09:06:38 +00009965 }
Alexander Kornienko21de0ae2015-01-20 11:20:41 +00009966 return Target->getDefaultCallingConv(TargetInfo::CCMT_Unknown);
Charles Davis99202b32010-11-09 18:04:24 +00009967}
9968
Jay Foad39c79802011-01-12 09:06:06 +00009969bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00009970 // Pass through to the C++ ABI object
9971 return ABI->isNearlyEmpty(RD);
9972}
9973
Reid Kleckner96f8f932014-02-05 17:27:08 +00009974VTableContextBase *ASTContext::getVTableContext() {
9975 if (!VTContext.get()) {
9976 if (Target->getCXXABI().isMicrosoft())
9977 VTContext.reset(new MicrosoftVTableContext(*this));
9978 else
9979 VTContext.reset(new ItaniumVTableContext(*this));
9980 }
9981 return VTContext.get();
9982}
9983
Yaxun Liuc18e9ec2019-02-14 02:00:09 +00009984MangleContext *ASTContext::createMangleContext(const TargetInfo *T) {
9985 if (!T)
9986 T = Target;
9987 switch (T->getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +00009988 case TargetCXXABI::GenericAArch64:
John McCall359b8852013-01-25 22:30:49 +00009989 case TargetCXXABI::GenericItanium:
9990 case TargetCXXABI::GenericARM:
Zoran Jovanovic26a12162015-02-18 15:21:35 +00009991 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +00009992 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +00009993 case TargetCXXABI::iOS64:
Dan Gohmanc2853072015-09-03 22:51:53 +00009994 case TargetCXXABI::WebAssembly:
Tim Northover756447a2015-10-30 16:30:36 +00009995 case TargetCXXABI::WatchOS:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00009996 return ItaniumMangleContext::create(*this, getDiagnostics());
John McCall359b8852013-01-25 22:30:49 +00009997 case TargetCXXABI::Microsoft:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00009998 return MicrosoftMangleContext::create(*this, getDiagnostics());
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00009999 }
David Blaikie83d382b2011-09-23 05:06:16 +000010000 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000010001}
10002
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000010003CXXABI::~CXXABI() = default;
Ted Kremenekf5df0ce2011-04-28 04:53:38 +000010004
10005size_t ASTContext::getSideTableAllocatedMemory() const {
Larisse Voufo39a1e502013-08-06 01:03:05 +000010006 return ASTRecordLayouts.getMemorySize() +
10007 llvm::capacity_in_bytes(ObjCLayouts) +
10008 llvm::capacity_in_bytes(KeyFunctions) +
10009 llvm::capacity_in_bytes(ObjCImpls) +
10010 llvm::capacity_in_bytes(BlockVarCopyInits) +
10011 llvm::capacity_in_bytes(DeclAttrs) +
10012 llvm::capacity_in_bytes(TemplateOrInstantiation) +
10013 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
10014 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
10015 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
10016 llvm::capacity_in_bytes(OverriddenMethods) +
10017 llvm::capacity_in_bytes(Types) +
Richard Smithf19a8b02019-05-02 00:49:14 +000010018 llvm::capacity_in_bytes(VariableArrayTypes);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +000010019}
Ted Kremenek540017e2011-10-06 05:00:56 +000010020
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +000010021/// getIntTypeForBitwidth -
10022/// sets integer QualTy according to specified details:
10023/// bitwidth, signed/unsigned.
10024/// Returns empty type if there is no appropriate target types.
10025QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
10026 unsigned Signed) const {
10027 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
10028 CanQualType QualTy = getFromTargetType(Ty);
10029 if (!QualTy && DestWidth == 128)
10030 return Signed ? Int128Ty : UnsignedInt128Ty;
10031 return QualTy;
10032}
10033
10034/// getRealTypeForBitwidth -
10035/// sets floating point QualTy according to specified bitwidth.
10036/// Returns empty type if there is no appropriate target types.
10037QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
10038 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
10039 switch (Ty) {
10040 case TargetInfo::Float:
10041 return FloatTy;
10042 case TargetInfo::Double:
10043 return DoubleTy;
10044 case TargetInfo::LongDouble:
10045 return LongDoubleTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +000010046 case TargetInfo::Float128:
10047 return Float128Ty;
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +000010048 case TargetInfo::NoFloat:
Eugene Zelenko7855e772018-04-03 00:11:50 +000010049 return {};
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +000010050 }
10051
10052 llvm_unreachable("Unhandled TargetInfo::RealType value");
10053}
10054
Eli Friedman3b7d46c2013-07-10 00:30:46 +000010055void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
10056 if (Number > 1)
10057 MangleNumbers[ND] = Number;
David Blaikie095deba2012-11-14 01:52:05 +000010058}
10059
Eli Friedman3b7d46c2013-07-10 00:30:46 +000010060unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
Richard Smithe9b02d62016-03-21 22:33:02 +000010061 auto I = MangleNumbers.find(ND);
Eli Friedman3b7d46c2013-07-10 00:30:46 +000010062 return I != MangleNumbers.end() ? I->second : 1;
David Blaikie095deba2012-11-14 01:52:05 +000010063}
10064
David Majnemer2206bf52014-03-05 08:57:59 +000010065void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
10066 if (Number > 1)
10067 StaticLocalNumbers[VD] = Number;
10068}
10069
10070unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
Richard Smithe9b02d62016-03-21 22:33:02 +000010071 auto I = StaticLocalNumbers.find(VD);
David Majnemer2206bf52014-03-05 08:57:59 +000010072 return I != StaticLocalNumbers.end() ? I->second : 1;
10073}
10074
Eli Friedman3b7d46c2013-07-10 00:30:46 +000010075MangleNumberingContext &
10076ASTContext::getManglingNumberContext(const DeclContext *DC) {
Reid Klecknerd8110b62013-09-10 20:14:30 +000010077 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
Justin Lebar20ebffc2016-10-10 16:26:19 +000010078 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
Reid Klecknerd8110b62013-09-10 20:14:30 +000010079 if (!MCtx)
10080 MCtx = createMangleNumberingContext();
10081 return *MCtx;
10082}
10083
Justin Lebar20ebffc2016-10-10 16:26:19 +000010084std::unique_ptr<MangleNumberingContext>
10085ASTContext::createMangleNumberingContext() const {
Reid Klecknerd8110b62013-09-10 20:14:30 +000010086 return ABI->createMangleNumberingContext();
Douglas Gregor63798542012-02-20 19:44:39 +000010087}
10088
David Majnemere7a818f2015-03-06 18:53:55 +000010089const CXXConstructorDecl *
10090ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
10091 return ABI->getCopyConstructorForExceptionObject(
10092 cast<CXXRecordDecl>(RD->getFirstDecl()));
10093}
10094
10095void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
10096 CXXConstructorDecl *CD) {
10097 return ABI->addCopyConstructorForExceptionObject(
10098 cast<CXXRecordDecl>(RD->getFirstDecl()),
10099 cast<CXXConstructorDecl>(CD->getFirstDecl()));
10100}
10101
David Majnemer00350522015-08-31 18:48:39 +000010102void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD,
10103 TypedefNameDecl *DD) {
10104 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
10105}
10106
10107TypedefNameDecl *
10108ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) {
10109 return ABI->getTypedefNameForUnnamedTagDecl(TD);
10110}
10111
10112void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD,
10113 DeclaratorDecl *DD) {
10114 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
10115}
10116
10117DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) {
10118 return ABI->getDeclaratorForUnnamedTagDecl(TD);
10119}
10120
Ted Kremenek540017e2011-10-06 05:00:56 +000010121void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
10122 ParamIndices[D] = index;
10123}
10124
10125unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
10126 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
Fangrui Song6907ce22018-07-30 19:24:48 +000010127 assert(I != ParamIndices.end() &&
Ted Kremenek540017e2011-10-06 05:00:56 +000010128 "ParmIndices lacks entry set by ParmVarDecl");
10129 return I->second;
10130}
Fariborz Jahanian615de762013-05-28 17:37:39 +000010131
Richard Smithe6c01442013-06-05 00:46:14 +000010132APValue *
10133ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
10134 bool MayCreate) {
10135 assert(E && E->getStorageDuration() == SD_Static &&
10136 "don't need to cache the computed value for this temporary");
David Majnemer2dcef9e2015-08-13 23:50:15 +000010137 if (MayCreate) {
10138 APValue *&MTVI = MaterializedTemporaryValues[E];
10139 if (!MTVI)
10140 MTVI = new (*this) APValue;
10141 return MTVI;
10142 }
Richard Smithe6c01442013-06-05 00:46:14 +000010143
David Majnemer2dcef9e2015-08-13 23:50:15 +000010144 return MaterializedTemporaryValues.lookup(E);
Richard Smithe6c01442013-06-05 00:46:14 +000010145}
10146
Fariborz Jahanian615de762013-05-28 17:37:39 +000010147bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
10148 const llvm::Triple &T = getTargetInfo().getTriple();
10149 if (!T.isOSDarwin())
10150 return false;
10151
Bob Wilson2c82c3d2013-11-02 23:27:49 +000010152 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
10153 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
10154 return false;
10155
Fariborz Jahanian615de762013-05-28 17:37:39 +000010156 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
10157 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
10158 uint64_t Size = sizeChars.getQuantity();
10159 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
10160 unsigned Align = alignChars.getQuantity();
10161 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
10162 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
10163}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010164
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010165/// Template specializations to abstract away from pointers and TypeLocs.
10166/// @{
10167template <typename T>
Sam McCall814e7972018-11-14 10:33:30 +000010168static ast_type_traits::DynTypedNode createDynTypedNode(const T &Node) {
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010169 return ast_type_traits::DynTypedNode::create(*Node);
10170}
10171template <>
10172ast_type_traits::DynTypedNode createDynTypedNode(const TypeLoc &Node) {
10173 return ast_type_traits::DynTypedNode::create(Node);
10174}
10175template <>
10176ast_type_traits::DynTypedNode
10177createDynTypedNode(const NestedNameSpecifierLoc &Node) {
10178 return ast_type_traits::DynTypedNode::create(Node);
10179}
10180/// @}
10181
Sam McCall814e7972018-11-14 10:33:30 +000010182/// A \c RecursiveASTVisitor that builds a map from nodes to their
10183/// parents as defined by the \c RecursiveASTVisitor.
10184///
10185/// Note that the relationship described here is purely in terms of AST
10186/// traversal - there are other relationships (for example declaration context)
10187/// in the AST that are better modeled by special matchers.
10188///
10189/// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
10190class ASTContext::ParentMap::ASTVisitor
10191 : public RecursiveASTVisitor<ASTVisitor> {
10192public:
10193 ASTVisitor(ParentMap &Map) : Map(Map) {}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010194
Sam McCall814e7972018-11-14 10:33:30 +000010195private:
10196 friend class RecursiveASTVisitor<ASTVisitor>;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000010197
Sam McCall814e7972018-11-14 10:33:30 +000010198 using VisitorBase = RecursiveASTVisitor<ASTVisitor>;
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010199
Sam McCall814e7972018-11-14 10:33:30 +000010200 bool shouldVisitTemplateInstantiations() const { return true; }
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010201
Sam McCall814e7972018-11-14 10:33:30 +000010202 bool shouldVisitImplicitCode() const { return true; }
10203
10204 template <typename T, typename MapNodeTy, typename BaseTraverseFn,
10205 typename MapTy>
10206 bool TraverseNode(T Node, MapNodeTy MapNode, BaseTraverseFn BaseTraverse,
10207 MapTy *Parents) {
10208 if (!Node)
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010209 return true;
Sam McCall814e7972018-11-14 10:33:30 +000010210 if (ParentStack.size() > 0) {
10211 // FIXME: Currently we add the same parent multiple times, but only
10212 // when no memoization data is available for the type.
10213 // For example when we visit all subexpressions of template
10214 // instantiations; this is suboptimal, but benign: the only way to
10215 // visit those is with hasAncestor / hasParent, and those do not create
10216 // new matches.
10217 // The plan is to enable DynTypedNode to be storable in a map or hash
10218 // map. The main problem there is to implement hash functions /
10219 // comparison operators for all types that DynTypedNode supports that
10220 // do not have pointer identity.
10221 auto &NodeOrVector = (*Parents)[MapNode];
10222 if (NodeOrVector.isNull()) {
10223 if (const auto *D = ParentStack.back().get<Decl>())
10224 NodeOrVector = D;
10225 else if (const auto *S = ParentStack.back().get<Stmt>())
10226 NodeOrVector = S;
10227 else
10228 NodeOrVector = new ast_type_traits::DynTypedNode(ParentStack.back());
10229 } else {
10230 if (!NodeOrVector.template is<ParentVector *>()) {
10231 auto *Vector = new ParentVector(
10232 1, getSingleDynTypedNodeFromParentMap(NodeOrVector));
10233 delete NodeOrVector
10234 .template dyn_cast<ast_type_traits::DynTypedNode *>();
10235 NodeOrVector = Vector;
Manuel Klimek95403e62014-05-21 13:28:59 +000010236 }
Sam McCall814e7972018-11-14 10:33:30 +000010237
10238 auto *Vector = NodeOrVector.template get<ParentVector *>();
10239 // Skip duplicates for types that have memoization data.
10240 // We must check that the type has memoization data before calling
10241 // std::find() because DynTypedNode::operator== can't compare all
10242 // types.
10243 bool Found = ParentStack.back().getMemoizationData() &&
10244 std::find(Vector->begin(), Vector->end(),
10245 ParentStack.back()) != Vector->end();
10246 if (!Found)
10247 Vector->push_back(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +000010248 }
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010249 }
Sam McCall814e7972018-11-14 10:33:30 +000010250 ParentStack.push_back(createDynTypedNode(Node));
10251 bool Result = BaseTraverse();
10252 ParentStack.pop_back();
10253 return Result;
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010254 }
Sam McCall814e7972018-11-14 10:33:30 +000010255
10256 bool TraverseDecl(Decl *DeclNode) {
10257 return TraverseNode(
10258 DeclNode, DeclNode, [&] { return VisitorBase::TraverseDecl(DeclNode); },
10259 &Map.PointerParents);
Manuel Klimek95403e62014-05-21 13:28:59 +000010260 }
Sam McCall814e7972018-11-14 10:33:30 +000010261
10262 bool TraverseStmt(Stmt *StmtNode) {
10263 return TraverseNode(
10264 StmtNode, StmtNode, [&] { return VisitorBase::TraverseStmt(StmtNode); },
10265 &Map.PointerParents);
10266 }
10267
10268 bool TraverseTypeLoc(TypeLoc TypeLocNode) {
10269 return TraverseNode(
10270 TypeLocNode, ast_type_traits::DynTypedNode::create(TypeLocNode),
10271 [&] { return VisitorBase::TraverseTypeLoc(TypeLocNode); },
10272 &Map.OtherParents);
10273 }
10274
10275 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNSLocNode) {
10276 return TraverseNode(
10277 NNSLocNode, ast_type_traits::DynTypedNode::create(NNSLocNode),
10278 [&] { return VisitorBase::TraverseNestedNameSpecifierLoc(NNSLocNode); },
10279 &Map.OtherParents);
10280 }
10281
10282 ParentMap &Map;
10283 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
10284};
10285
10286ASTContext::ParentMap::ParentMap(ASTContext &Ctx) {
10287 ASTVisitor(*this).TraverseAST(Ctx);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010288}
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010289
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010290ASTContext::DynTypedNodeList
10291ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
Sam McCall814e7972018-11-14 10:33:30 +000010292 if (!Parents)
10293 // We build the parent map for the traversal scope (usually whole TU), as
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010294 // hasAncestor can escape any subtree.
Sam McCall814e7972018-11-14 10:33:30 +000010295 Parents = llvm::make_unique<ParentMap>(*this);
10296 return Parents->getParents(Node);
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010297}
10298
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010299bool
10300ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
10301 const ObjCMethodDecl *MethodImpl) {
10302 // No point trying to match an unavailable/deprecated mothod.
10303 if (MethodDecl->hasAttr<UnavailableAttr>()
10304 || MethodDecl->hasAttr<DeprecatedAttr>())
10305 return false;
10306 if (MethodDecl->getObjCDeclQualifier() !=
10307 MethodImpl->getObjCDeclQualifier())
10308 return false;
Alp Toker314cc812014-01-25 16:55:45 +000010309 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010310 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +000010311
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010312 if (MethodDecl->param_size() != MethodImpl->param_size())
10313 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +000010314
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010315 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
10316 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
10317 EF = MethodDecl->param_end();
10318 IM != EM && IF != EF; ++IM, ++IF) {
10319 const ParmVarDecl *DeclVar = (*IF);
10320 const ParmVarDecl *ImplVar = (*IM);
10321 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
10322 return false;
10323 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
10324 return false;
10325 }
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000010326
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010327 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010328}
Richard Smith053f6c62014-05-16 23:01:30 +000010329
Yaxun Liu402804b2016-12-15 08:09:08 +000010330uint64_t ASTContext::getTargetNullPointerValue(QualType QT) const {
Alexander Richardson6d989432017-10-15 18:48:14 +000010331 LangAS AS;
Yaxun Liu402804b2016-12-15 08:09:08 +000010332 if (QT->getUnqualifiedDesugaredType()->isNullPtrType())
Alexander Richardson6d989432017-10-15 18:48:14 +000010333 AS = LangAS::Default;
Yaxun Liu402804b2016-12-15 08:09:08 +000010334 else
10335 AS = QT->getPointeeType().getAddressSpace();
10336
10337 return getTargetInfo().getNullPointerValue(AS);
10338}
10339
Alexander Richardson6d989432017-10-15 18:48:14 +000010340unsigned ASTContext::getTargetAddressSpace(LangAS AS) const {
10341 if (isTargetAddressSpace(AS))
10342 return toTargetAddressSpace(AS);
Yaxun Liub34ec822017-04-11 17:24:23 +000010343 else
Alexander Richardson6d989432017-10-15 18:48:14 +000010344 return (*AddrSpaceMap)[(unsigned)AS];
Yaxun Liub34ec822017-04-11 17:24:23 +000010345}
10346
Leonard Chanab80f3c2018-06-14 14:53:51 +000010347QualType ASTContext::getCorrespondingSaturatedType(QualType Ty) const {
10348 assert(Ty->isFixedPointType());
10349
10350 if (Ty->isSaturatedFixedPointType()) return Ty;
10351
10352 const auto &BT = Ty->getAs<BuiltinType>();
10353 switch (BT->getKind()) {
10354 default:
10355 llvm_unreachable("Not a fixed point type!");
10356 case BuiltinType::ShortAccum:
10357 return SatShortAccumTy;
10358 case BuiltinType::Accum:
10359 return SatAccumTy;
10360 case BuiltinType::LongAccum:
10361 return SatLongAccumTy;
10362 case BuiltinType::UShortAccum:
10363 return SatUnsignedShortAccumTy;
10364 case BuiltinType::UAccum:
10365 return SatUnsignedAccumTy;
10366 case BuiltinType::ULongAccum:
10367 return SatUnsignedLongAccumTy;
10368 case BuiltinType::ShortFract:
10369 return SatShortFractTy;
10370 case BuiltinType::Fract:
10371 return SatFractTy;
10372 case BuiltinType::LongFract:
10373 return SatLongFractTy;
10374 case BuiltinType::UShortFract:
10375 return SatUnsignedShortFractTy;
10376 case BuiltinType::UFract:
10377 return SatUnsignedFractTy;
10378 case BuiltinType::ULongFract:
10379 return SatUnsignedLongFractTy;
10380 }
10381}
10382
Matt Arsenaultc65f9662018-08-02 12:14:28 +000010383LangAS ASTContext::getLangASForBuiltinAddressSpace(unsigned AS) const {
10384 if (LangOpts.OpenCL)
10385 return getTargetInfo().getOpenCLBuiltinAddressSpace(AS);
10386
10387 if (LangOpts.CUDA)
10388 return getTargetInfo().getCUDABuiltinAddressSpace(AS);
10389
10390 return getLangASFromTargetAS(AS);
10391}
10392
Richard Smith053f6c62014-05-16 23:01:30 +000010393// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
10394// doesn't include ASTContext.h
10395template
10396clang::LazyGenerationalUpdatePtr<
10397 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
10398clang::LazyGenerationalUpdatePtr<
10399 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
10400 const clang::ASTContext &Ctx, Decl *Value);
Leonard Chandb01c3a2018-06-20 17:19:40 +000010401
10402unsigned char ASTContext::getFixedPointScale(QualType Ty) const {
10403 assert(Ty->isFixedPointType());
10404
10405 const auto *BT = Ty->getAs<BuiltinType>();
10406 const TargetInfo &Target = getTargetInfo();
10407 switch (BT->getKind()) {
10408 default:
10409 llvm_unreachable("Not a fixed point type!");
10410 case BuiltinType::ShortAccum:
10411 case BuiltinType::SatShortAccum:
10412 return Target.getShortAccumScale();
10413 case BuiltinType::Accum:
10414 case BuiltinType::SatAccum:
10415 return Target.getAccumScale();
10416 case BuiltinType::LongAccum:
10417 case BuiltinType::SatLongAccum:
10418 return Target.getLongAccumScale();
10419 case BuiltinType::UShortAccum:
10420 case BuiltinType::SatUShortAccum:
10421 return Target.getUnsignedShortAccumScale();
10422 case BuiltinType::UAccum:
10423 case BuiltinType::SatUAccum:
10424 return Target.getUnsignedAccumScale();
10425 case BuiltinType::ULongAccum:
10426 case BuiltinType::SatULongAccum:
10427 return Target.getUnsignedLongAccumScale();
10428 case BuiltinType::ShortFract:
10429 case BuiltinType::SatShortFract:
10430 return Target.getShortFractScale();
10431 case BuiltinType::Fract:
10432 case BuiltinType::SatFract:
10433 return Target.getFractScale();
10434 case BuiltinType::LongFract:
10435 case BuiltinType::SatLongFract:
10436 return Target.getLongFractScale();
10437 case BuiltinType::UShortFract:
10438 case BuiltinType::SatUShortFract:
10439 return Target.getUnsignedShortFractScale();
10440 case BuiltinType::UFract:
10441 case BuiltinType::SatUFract:
10442 return Target.getUnsignedFractScale();
10443 case BuiltinType::ULongFract:
10444 case BuiltinType::SatULongFract:
10445 return Target.getUnsignedLongFractScale();
10446 }
10447}
10448
10449unsigned char ASTContext::getFixedPointIBits(QualType Ty) const {
10450 assert(Ty->isFixedPointType());
10451
10452 const auto *BT = Ty->getAs<BuiltinType>();
10453 const TargetInfo &Target = getTargetInfo();
10454 switch (BT->getKind()) {
10455 default:
10456 llvm_unreachable("Not a fixed point type!");
10457 case BuiltinType::ShortAccum:
10458 case BuiltinType::SatShortAccum:
10459 return Target.getShortAccumIBits();
10460 case BuiltinType::Accum:
10461 case BuiltinType::SatAccum:
10462 return Target.getAccumIBits();
10463 case BuiltinType::LongAccum:
10464 case BuiltinType::SatLongAccum:
10465 return Target.getLongAccumIBits();
10466 case BuiltinType::UShortAccum:
10467 case BuiltinType::SatUShortAccum:
10468 return Target.getUnsignedShortAccumIBits();
10469 case BuiltinType::UAccum:
10470 case BuiltinType::SatUAccum:
10471 return Target.getUnsignedAccumIBits();
10472 case BuiltinType::ULongAccum:
10473 case BuiltinType::SatULongAccum:
10474 return Target.getUnsignedLongAccumIBits();
10475 case BuiltinType::ShortFract:
10476 case BuiltinType::SatShortFract:
10477 case BuiltinType::Fract:
10478 case BuiltinType::SatFract:
10479 case BuiltinType::LongFract:
10480 case BuiltinType::SatLongFract:
10481 case BuiltinType::UShortFract:
10482 case BuiltinType::SatUShortFract:
10483 case BuiltinType::UFract:
10484 case BuiltinType::SatUFract:
10485 case BuiltinType::ULongFract:
10486 case BuiltinType::SatULongFract:
10487 return 0;
10488 }
10489}
Leonard Chana6779422018-08-06 16:42:37 +000010490
10491FixedPointSemantics ASTContext::getFixedPointSemantics(QualType Ty) const {
Erich Keane8e772162019-01-18 19:31:54 +000010492 assert((Ty->isFixedPointType() || Ty->isIntegerType()) &&
10493 "Can only get the fixed point semantics for a "
10494 "fixed point or integer type.");
Leonard Chan2044ac82019-01-16 18:13:59 +000010495 if (Ty->isIntegerType())
10496 return FixedPointSemantics::GetIntegerSemantics(getIntWidth(Ty),
10497 Ty->isSignedIntegerType());
10498
Leonard Chana6779422018-08-06 16:42:37 +000010499 bool isSigned = Ty->isSignedFixedPointType();
10500 return FixedPointSemantics(
10501 static_cast<unsigned>(getTypeSize(Ty)), getFixedPointScale(Ty), isSigned,
10502 Ty->isSaturatedFixedPointType(),
10503 !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding());
10504}
10505
10506APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const {
10507 assert(Ty->isFixedPointType());
10508 return APFixedPoint::getMax(getFixedPointSemantics(Ty));
10509}
10510
10511APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const {
10512 assert(Ty->isFixedPointType());
10513 return APFixedPoint::getMin(getFixedPointSemantics(Ty));
10514}
Leonard Chan2044ac82019-01-16 18:13:59 +000010515
10516QualType ASTContext::getCorrespondingSignedFixedPointType(QualType Ty) const {
10517 assert(Ty->isUnsignedFixedPointType() &&
10518 "Expected unsigned fixed point type");
10519 const auto *BTy = Ty->getAs<BuiltinType>();
10520
10521 switch (BTy->getKind()) {
10522 case BuiltinType::UShortAccum:
10523 return ShortAccumTy;
10524 case BuiltinType::UAccum:
10525 return AccumTy;
10526 case BuiltinType::ULongAccum:
10527 return LongAccumTy;
10528 case BuiltinType::SatUShortAccum:
10529 return SatShortAccumTy;
10530 case BuiltinType::SatUAccum:
10531 return SatAccumTy;
10532 case BuiltinType::SatULongAccum:
10533 return SatLongAccumTy;
10534 case BuiltinType::UShortFract:
10535 return ShortFractTy;
10536 case BuiltinType::UFract:
10537 return FractTy;
10538 case BuiltinType::ULongFract:
10539 return LongFractTy;
10540 case BuiltinType::SatUShortFract:
10541 return SatShortFractTy;
10542 case BuiltinType::SatUFract:
10543 return SatFractTy;
10544 case BuiltinType::SatULongFract:
10545 return SatLongFractTy;
10546 default:
10547 llvm_unreachable("Unexpected unsigned fixed point type");
10548 }
10549}