blob: 22927a46a34c57400a91c26e7b29dcbcde57bb46 [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
Douglas Gregor9672f922010-07-03 00:47:00 +000097unsigned ASTContext::NumImplicitDefaultConstructors;
98unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregora6d69502010-07-02 23:41:54 +000099unsigned ASTContext::NumImplicitCopyConstructors;
100unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +0000101unsigned ASTContext::NumImplicitMoveConstructors;
102unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000103unsigned ASTContext::NumImplicitCopyAssignmentOperators;
104unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +0000105unsigned ASTContext::NumImplicitMoveAssignmentOperators;
106unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
Douglas Gregor7454c562010-07-02 20:37:36 +0000107unsigned ASTContext::NumImplicitDestructors;
108unsigned ASTContext::NumImplicitDestructorsDeclared;
109
Steve Naroff0af91202007-04-27 21:51:21 +0000110enum FloatingRank {
Sjoerd Meijercc623ad2017-09-08 15:15:00 +0000111 Float16Rank, HalfRank, FloatRank, DoubleRank, LongDoubleRank, Float128Rank
Steve Naroff0af91202007-04-27 21:51:21 +0000112};
113
Dmitri Gribenkof26054f2012-07-11 21:38:39 +0000114RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000115 if (!CommentsLoaded && ExternalSource) {
116 ExternalSource->ReadComments();
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +0000117
118#ifndef NDEBUG
119 ArrayRef<RawComment *> RawComments = Comments.getComments();
120 assert(std::is_sorted(RawComments.begin(), RawComments.end(),
121 BeforeThanCompare<RawComment>(SourceMgr)));
122#endif
123
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000124 CommentsLoaded = true;
125 }
126
127 assert(D);
128
Dmitri Gribenkodf17d642012-06-28 16:19:39 +0000129 // User can not attach documentation to implicit declarations.
130 if (D->isImplicit())
Craig Topper36250ad2014-05-12 05:36:57 +0000131 return nullptr;
Dmitri Gribenkodf17d642012-06-28 16:19:39 +0000132
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000133 // User can not attach documentation to implicit instantiations.
Eugene Zelenko7855e772018-04-03 00:11:50 +0000134 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000135 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +0000136 return nullptr;
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000137 }
138
Eugene Zelenko7855e772018-04-03 00:11:50 +0000139 if (const auto *VD = dyn_cast<VarDecl>(D)) {
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000140 if (VD->isStaticDataMember() &&
141 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +0000142 return nullptr;
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000143 }
144
Eugene Zelenko7855e772018-04-03 00:11:50 +0000145 if (const auto *CRD = dyn_cast<CXXRecordDecl>(D)) {
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000146 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +0000147 return nullptr;
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000148 }
149
Eugene Zelenko7855e772018-04-03 00:11:50 +0000150 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000151 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
152 if (TSK == TSK_ImplicitInstantiation ||
153 TSK == TSK_Undeclared)
Craig Topper36250ad2014-05-12 05:36:57 +0000154 return nullptr;
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000155 }
156
Eugene Zelenko7855e772018-04-03 00:11:50 +0000157 if (const auto *ED = dyn_cast<EnumDecl>(D)) {
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000158 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +0000159 return nullptr;
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000160 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000161 if (const auto *TD = dyn_cast<TagDecl>(D)) {
Fariborz Jahanian799a4032013-04-17 21:05:20 +0000162 // When tag declaration (but not definition!) is part of the
163 // decl-specifier-seq of some other declaration, it doesn't get comment
164 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
Craig Topper36250ad2014-05-12 05:36:57 +0000165 return nullptr;
Fariborz Jahanian799a4032013-04-17 21:05:20 +0000166 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000167 // TODO: handle comments for function parameters properly.
168 if (isa<ParmVarDecl>(D))
Craig Topper36250ad2014-05-12 05:36:57 +0000169 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000170
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000171 // TODO: we could look up template parameter documentation in the template
172 // documentation.
173 if (isa<TemplateTypeParmDecl>(D) ||
174 isa<NonTypeTemplateParmDecl>(D) ||
175 isa<TemplateTemplateParmDecl>(D))
Craig Topper36250ad2014-05-12 05:36:57 +0000176 return nullptr;
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000177
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000178 ArrayRef<RawComment *> RawComments = Comments.getComments();
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000179
180 // If there are no comments anywhere, we won't find anything.
181 if (RawComments.empty())
Craig Topper36250ad2014-05-12 05:36:57 +0000182 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000183
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000184 // Find declaration location.
185 // For Objective-C declarations we generally don't expect to have multiple
186 // declarators, thus use declaration starting location as the "declaration
187 // location".
188 // For all other declarations multiple declarators are used quite frequently,
189 // so we use the location of the identifier as the "declaration location".
190 SourceLocation DeclLoc;
191 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000192 isa<ObjCPropertyDecl>(D) ||
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +0000193 isa<RedeclarableTemplateDecl>(D) ||
194 isa<ClassTemplateSpecializationDecl>(D))
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000195 DeclLoc = D->getBeginLoc();
Fariborz Jahanianb64e95f2013-07-24 22:58:51 +0000196 else {
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000197 DeclLoc = D->getLocation();
Dmitri Gribenkoef099dc2014-03-27 16:40:51 +0000198 if (DeclLoc.isMacroID()) {
199 if (isa<TypedefDecl>(D)) {
200 // If location of the typedef name is in a macro, it is because being
201 // declared via a macro. Try using declaration's starting location as
202 // the "declaration location".
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000203 DeclLoc = D->getBeginLoc();
Eugene Zelenko7855e772018-04-03 00:11:50 +0000204 } else if (const auto *TD = dyn_cast<TagDecl>(D)) {
Dmitri Gribenkoef099dc2014-03-27 16:40:51 +0000205 // If location of the tag decl is inside a macro, but the spelling of
206 // the tag name comes from a macro argument, it looks like a special
207 // macro like NS_ENUM is being used to define the tag decl. In that
208 // case, adjust the source location to the expansion loc so that we can
209 // attach the comment to the tag decl.
210 if (SourceMgr.isMacroArgExpansion(DeclLoc) &&
211 TD->isCompleteDefinition())
212 DeclLoc = SourceMgr.getExpansionLoc(DeclLoc);
213 }
214 }
Fariborz Jahanianb64e95f2013-07-24 22:58:51 +0000215 }
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000216
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000217 // If the declaration doesn't map directly to a location in a file, we
218 // can't find the comment.
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000219 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
Craig Topper36250ad2014-05-12 05:36:57 +0000220 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000221
222 // Find the comment that occurs just after this declaration.
Dmitri Gribenko82ea9472012-07-17 22:01:09 +0000223 ArrayRef<RawComment *>::iterator Comment;
224 {
225 // When searching for comments during parsing, the comment we are looking
226 // for is usually among the last two comments we parsed -- check them
227 // first.
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +0000228 RawComment CommentAtDeclLoc(
David L. Jones13d5a872018-03-02 00:07:45 +0000229 SourceMgr, SourceRange(DeclLoc), LangOpts.CommentOpts, false);
Dmitri Gribenko82ea9472012-07-17 22:01:09 +0000230 BeforeThanCompare<RawComment> Compare(SourceMgr);
231 ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1;
232 bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
233 if (!Found && RawComments.size() >= 2) {
234 MaybeBeforeDecl--;
235 Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
236 }
237
238 if (Found) {
239 Comment = MaybeBeforeDecl + 1;
240 assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(),
241 &CommentAtDeclLoc, Compare));
242 } else {
243 // Slow path.
244 Comment = std::lower_bound(RawComments.begin(), RawComments.end(),
245 &CommentAtDeclLoc, Compare);
246 }
247 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000248
249 // Decompose the location for the declaration and find the beginning of the
250 // file buffer.
251 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
252
253 // First check whether we have a trailing comment.
254 if (Comment != RawComments.end() &&
David L. Jones13d5a872018-03-02 00:07:45 +0000255 ((*Comment)->isDocumentation() || LangOpts.CommentOpts.ParseAllComments)
256 && (*Comment)->isTrailingComment() &&
Fariborz Jahanianfad28542013-08-06 23:29:00 +0000257 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
Fariborz Jahanian3ab62222013-08-07 16:40:29 +0000258 isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000259 std::pair<FileID, unsigned> CommentBeginDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000260 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000261 // Check that Doxygen trailing comment comes after the declaration, starts
262 // on the same line and in the same file as the declaration.
263 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
264 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
265 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
266 CommentBeginDecomp.second)) {
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000267 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000268 }
269 }
270
271 // The comment just after the declaration was not a trailing comment.
272 // Let's look at the previous comment.
273 if (Comment == RawComments.begin())
Craig Topper36250ad2014-05-12 05:36:57 +0000274 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000275 --Comment;
276
277 // Check that we actually have a non-member Doxygen comment.
David L. Jones13d5a872018-03-02 00:07:45 +0000278 if (!((*Comment)->isDocumentation() ||
279 LangOpts.CommentOpts.ParseAllComments) ||
280 (*Comment)->isTrailingComment())
Craig Topper36250ad2014-05-12 05:36:57 +0000281 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000282
283 // Decompose the end of the comment.
284 std::pair<FileID, unsigned> CommentEndDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000285 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000286
287 // If the comment and the declaration aren't in the same file, then they
288 // aren't related.
289 if (DeclLocDecomp.first != CommentEndDecomp.first)
Craig Topper36250ad2014-05-12 05:36:57 +0000290 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000291
292 // Get the corresponding buffer.
293 bool Invalid = false;
294 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
295 &Invalid).data();
296 if (Invalid)
Craig Topper36250ad2014-05-12 05:36:57 +0000297 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000298
299 // Extract text between the comment and declaration.
300 StringRef Text(Buffer + CommentEndDecomp.second,
301 DeclLocDecomp.second - CommentEndDecomp.second);
302
Dmitri Gribenko7e8729b2012-06-27 23:43:37 +0000303 // There should be no other declarations or preprocessor directives between
304 // comment and declaration.
Argyrios Kyrtzidisb534d3a2013-07-26 18:38:12 +0000305 if (Text.find_first_of(";{}#@") != StringRef::npos)
Craig Topper36250ad2014-05-12 05:36:57 +0000306 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000307
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000308 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000309}
310
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000311/// If we have a 'templated' declaration for a template, adjust 'D' to
312/// refer to the actual template.
Dmitri Gribenko90631802012-08-22 17:44:32 +0000313/// If we have an implicit instantiation, adjust 'D' to refer to template.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +0000314static const Decl *adjustDeclToTemplate(const Decl *D) {
Eugene Zelenko7855e772018-04-03 00:11:50 +0000315 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000316 // Is this function declaration part of a function template?
Douglas Gregor35ceb272012-08-13 16:37:30 +0000317 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
Dmitri Gribenko90631802012-08-22 17:44:32 +0000318 return FTD;
319
320 // Nothing to do if function is not an implicit instantiation.
321 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
322 return D;
323
324 // Function is an implicit instantiation of a function template?
325 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
326 return FTD;
327
328 // Function is instantiated from a member definition of a class template?
329 if (const FunctionDecl *MemberDecl =
330 FD->getInstantiatedFromMemberFunction())
331 return MemberDecl;
332
333 return D;
Douglas Gregor35ceb272012-08-13 16:37:30 +0000334 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000335 if (const auto *VD = dyn_cast<VarDecl>(D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000336 // Static data member is instantiated from a member definition of a class
337 // template?
338 if (VD->isStaticDataMember())
339 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
340 return MemberDecl;
341
342 return D;
343 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000344 if (const auto *CRD = dyn_cast<CXXRecordDecl>(D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000345 // Is this class declaration part of a class template?
346 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
347 return CTD;
348
349 // Class is an implicit instantiation of a class template or partial
350 // specialization?
Eugene Zelenko7855e772018-04-03 00:11:50 +0000351 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000352 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
353 return D;
354 llvm::PointerUnion<ClassTemplateDecl *,
355 ClassTemplatePartialSpecializationDecl *>
356 PU = CTSD->getSpecializedTemplateOrPartial();
357 return PU.is<ClassTemplateDecl*>() ?
358 static_cast<const Decl*>(PU.get<ClassTemplateDecl *>()) :
359 static_cast<const Decl*>(
360 PU.get<ClassTemplatePartialSpecializationDecl *>());
361 }
362
363 // Class is instantiated from a member definition of a class template?
364 if (const MemberSpecializationInfo *Info =
365 CRD->getMemberSpecializationInfo())
366 return Info->getInstantiatedFrom();
367
368 return D;
369 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000370 if (const auto *ED = dyn_cast<EnumDecl>(D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000371 // Enum is instantiated from a member definition of a class template?
372 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
373 return MemberDecl;
374
375 return D;
376 }
377 // FIXME: Adjust alias templates?
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000378 return D;
379}
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000380
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000381const RawComment *ASTContext::getRawCommentForAnyRedecl(
382 const Decl *D,
383 const Decl **OriginalDecl) const {
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000384 D = adjustDeclToTemplate(D);
Douglas Gregor35ceb272012-08-13 16:37:30 +0000385
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000386 // Check whether we have cached a comment for this declaration already.
387 {
388 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
389 RedeclComments.find(D);
390 if (Pos != RedeclComments.end()) {
391 const RawCommentAndCacheFlags &Raw = Pos->second;
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000392 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
393 if (OriginalDecl)
394 *OriginalDecl = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000395 return Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000396 }
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000397 }
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000398 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000399
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000400 // Search for comments attached to declarations in the redeclaration chain.
Craig Topper36250ad2014-05-12 05:36:57 +0000401 const RawComment *RC = nullptr;
402 const Decl *OriginalDeclForRC = nullptr;
Aaron Ballman86c93902014-03-06 23:45:36 +0000403 for (auto I : D->redecls()) {
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000404 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
Aaron Ballman86c93902014-03-06 23:45:36 +0000405 RedeclComments.find(I);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000406 if (Pos != RedeclComments.end()) {
407 const RawCommentAndCacheFlags &Raw = Pos->second;
408 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
409 RC = Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000410 OriginalDeclForRC = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000411 break;
412 }
413 } else {
Aaron Ballman86c93902014-03-06 23:45:36 +0000414 RC = getRawCommentForDeclNoCache(I);
415 OriginalDeclForRC = I;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000416 RawCommentAndCacheFlags Raw;
417 if (RC) {
Will Wilsonf9de5362015-10-27 17:01:10 +0000418 // Call order swapped to work around ICE in VS2015 RTM (Release Win32)
419 // https://connect.microsoft.com/VisualStudio/feedback/details/1741530
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000420 Raw.setKind(RawCommentAndCacheFlags::FromDecl);
Will Wilsonf9de5362015-10-27 17:01:10 +0000421 Raw.setRaw(RC);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000422 } else
423 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
Aaron Ballman86c93902014-03-06 23:45:36 +0000424 Raw.setOriginalDecl(I);
425 RedeclComments[I] = Raw;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000426 if (RC)
427 break;
428 }
429 }
430
Dmitri Gribenko5c8897d2012-06-28 16:25:36 +0000431 // If we found a comment, it should be a documentation comment.
David L. Jones13d5a872018-03-02 00:07:45 +0000432 assert(!RC || RC->isDocumentation() || LangOpts.CommentOpts.ParseAllComments);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000433
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000434 if (OriginalDecl)
435 *OriginalDecl = OriginalDeclForRC;
436
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000437 // Update cache for every declaration in the redeclaration chain.
438 RawCommentAndCacheFlags Raw;
439 Raw.setRaw(RC);
440 Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000441 Raw.setOriginalDecl(OriginalDeclForRC);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000442
Aaron Ballman86c93902014-03-06 23:45:36 +0000443 for (auto I : D->redecls()) {
444 RawCommentAndCacheFlags &R = RedeclComments[I];
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000445 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
446 R = Raw;
447 }
448
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000449 return RC;
450}
451
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000452static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
453 SmallVectorImpl<const NamedDecl *> &Redeclared) {
454 const DeclContext *DC = ObjCMethod->getDeclContext();
Eugene Zelenko7855e772018-04-03 00:11:50 +0000455 if (const auto *IMD = dyn_cast<ObjCImplDecl>(DC)) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000456 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
457 if (!ID)
458 return;
459 // Add redeclared method here.
Aaron Ballmanb4a53452014-03-13 21:57:01 +0000460 for (const auto *Ext : ID->known_extensions()) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000461 if (ObjCMethodDecl *RedeclaredMethod =
Douglas Gregor048fbfa2013-01-16 23:00:23 +0000462 Ext->getMethod(ObjCMethod->getSelector(),
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000463 ObjCMethod->isInstanceMethod()))
464 Redeclared.push_back(RedeclaredMethod);
465 }
466 }
467}
468
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000469comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
470 const Decl *D) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +0000471 auto *ThisDeclInfo = new (*this) comments::DeclInfo;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000472 ThisDeclInfo->CommentDecl = D;
473 ThisDeclInfo->IsFilled = false;
474 ThisDeclInfo->fill();
475 ThisDeclInfo->CommentDecl = FC->getDecl();
Argyrios Kyrtzidis7daabbd2014-04-27 22:53:03 +0000476 if (!ThisDeclInfo->TemplateParameters)
477 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000478 comments::FullComment *CFC =
479 new (*this) comments::FullComment(FC->getBlocks(),
480 ThisDeclInfo);
481 return CFC;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000482}
483
Richard Smithb39b9d52013-05-21 05:24:00 +0000484comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
485 const RawComment *RC = getRawCommentForDeclNoCache(D);
Craig Topper36250ad2014-05-12 05:36:57 +0000486 return RC ? RC->parse(*this, nullptr, D) : nullptr;
Richard Smithb39b9d52013-05-21 05:24:00 +0000487}
488
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000489comments::FullComment *ASTContext::getCommentForDecl(
490 const Decl *D,
491 const Preprocessor *PP) const {
Fariborz Jahanian096f7c12013-05-13 17:27:00 +0000492 if (D->isInvalidDecl())
Craig Topper36250ad2014-05-12 05:36:57 +0000493 return nullptr;
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000494 D = adjustDeclToTemplate(D);
Fangrui Song6907ce22018-07-30 19:24:48 +0000495
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000496 const Decl *Canonical = D->getCanonicalDecl();
497 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
498 ParsedComments.find(Canonical);
Fangrui Song6907ce22018-07-30 19:24:48 +0000499
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000500 if (Pos != ParsedComments.end()) {
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000501 if (Canonical != D) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000502 comments::FullComment *FC = Pos->second;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000503 comments::FullComment *CFC = cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000504 return CFC;
505 }
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000506 return Pos->second;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000507 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000508
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000509 const Decl *OriginalDecl;
Fangrui Song6907ce22018-07-30 19:24:48 +0000510
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000511 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000512 if (!RC) {
513 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000514 SmallVector<const NamedDecl*, 8> Overridden;
Eugene Zelenko7855e772018-04-03 00:11:50 +0000515 const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000516 if (OMD && OMD->isPropertyAccessor())
517 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
518 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
519 return cloneFullComment(FC, D);
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000520 if (OMD)
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000521 addRedeclaredMethods(OMD, Overridden);
522 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000523 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
524 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
525 return cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000526 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000527 else if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000528 // Attach any tag type's documentation to its typedef if latter
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000529 // does not have one of its own.
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000530 QualType QT = TD->getUnderlyingType();
Eugene Zelenko7855e772018-04-03 00:11:50 +0000531 if (const auto *TT = QT->getAs<TagType>())
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000532 if (const Decl *TD = TT->getDecl())
533 if (comments::FullComment *FC = getCommentForDecl(TD, PP))
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000534 return cloneFullComment(FC, D);
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000535 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000536 else if (const auto *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000537 while (IC->getSuperClass()) {
538 IC = IC->getSuperClass();
539 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
540 return cloneFullComment(FC, D);
541 }
542 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000543 else if (const auto *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000544 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
545 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
546 return cloneFullComment(FC, D);
547 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000548 else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000549 if (!(RD = RD->getDefinition()))
Craig Topper36250ad2014-05-12 05:36:57 +0000550 return nullptr;
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000551 // Check non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +0000552 for (const auto &I : RD->bases()) {
553 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000554 continue;
Aaron Ballman574705e2014-03-13 15:41:46 +0000555 QualType Ty = I.getType();
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000556 if (Ty.isNull())
557 continue;
558 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
559 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
560 continue;
Fangrui Song6907ce22018-07-30 19:24:48 +0000561
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000562 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
563 return cloneFullComment(FC, D);
564 }
565 }
566 // Check virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +0000567 for (const auto &I : RD->vbases()) {
568 if (I.getAccessSpecifier() != AS_public)
Fariborz Jahanian5a2e4a22013-04-26 23:34:36 +0000569 continue;
Aaron Ballman445a9392014-03-13 16:15:17 +0000570 QualType Ty = I.getType();
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000571 if (Ty.isNull())
572 continue;
573 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
574 if (!(VirtualBase= VirtualBase->getDefinition()))
575 continue;
576 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
577 return cloneFullComment(FC, D);
578 }
579 }
580 }
Craig Topper36250ad2014-05-12 05:36:57 +0000581 return nullptr;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000582 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000583
Dmitri Gribenkobfda9f72012-08-22 18:12:19 +0000584 // If the RawComment was attached to other redeclaration of this Decl, we
585 // should parse the comment in context of that other Decl. This is important
586 // because comments can contain references to parameter names which can be
587 // different across redeclarations.
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000588 if (D != OriginalDecl)
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000589 return getCommentForDecl(OriginalDecl, PP);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000590
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000591 comments::FullComment *FC = RC->parse(*this, PP, D);
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000592 ParsedComments[Canonical] = FC;
593 return FC;
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000594}
595
Fangrui Song6907ce22018-07-30 19:24:48 +0000596void
597ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000598 TemplateTemplateParmDecl *Parm) {
599 ID.AddInteger(Parm->getDepth());
600 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +0000601 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000602
603 TemplateParameterList *Params = Parm->getTemplateParameters();
604 ID.AddInteger(Params->size());
Fangrui Song6907ce22018-07-30 19:24:48 +0000605 for (TemplateParameterList::const_iterator P = Params->begin(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000606 PEnd = Params->end();
607 P != PEnd; ++P) {
Eugene Zelenko7855e772018-04-03 00:11:50 +0000608 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000609 ID.AddInteger(0);
610 ID.AddBoolean(TTP->isParameterPack());
611 continue;
612 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000613
Eugene Zelenko7855e772018-04-03 00:11:50 +0000614 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000615 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +0000616 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman205a4292012-03-07 01:09:33 +0000617 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000618 if (NTTP->isExpandedParameterPack()) {
619 ID.AddBoolean(true);
620 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman205a4292012-03-07 01:09:33 +0000621 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
622 QualType T = NTTP->getExpansionType(I);
623 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
624 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000625 } else
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000626 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000627 continue;
628 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000629
Eugene Zelenko7855e772018-04-03 00:11:50 +0000630 auto *TTP = cast<TemplateTemplateParmDecl>(*P);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000631 ID.AddInteger(2);
632 Profile(ID, TTP);
633 }
634}
635
636TemplateTemplateParmDecl *
637ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +0000638 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000639 // Check if we already have a canonical template template parameter.
640 llvm::FoldingSetNodeID ID;
641 CanonicalTemplateTemplateParm::Profile(ID, TTP);
Craig Topper36250ad2014-05-12 05:36:57 +0000642 void *InsertPos = nullptr;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000643 CanonicalTemplateTemplateParm *Canonical
644 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
645 if (Canonical)
646 return Canonical->getParam();
Fangrui Song6907ce22018-07-30 19:24:48 +0000647
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000648 // Build a canonical template parameter list.
649 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000650 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000651 CanonParams.reserve(Params->size());
Fangrui Song6907ce22018-07-30 19:24:48 +0000652 for (TemplateParameterList::const_iterator P = Params->begin(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000653 PEnd = Params->end();
654 P != PEnd; ++P) {
Eugene Zelenko7855e772018-04-03 00:11:50 +0000655 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000656 CanonParams.push_back(
Fangrui Song6907ce22018-07-30 19:24:48 +0000657 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000658 SourceLocation(),
659 SourceLocation(),
660 TTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000661 TTP->getIndex(), nullptr, false,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000662 TTP->isParameterPack()));
Eugene Zelenko7855e772018-04-03 00:11:50 +0000663 else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000664 QualType T = getCanonicalType(NTTP->getType());
665 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
666 NonTypeTemplateParmDecl *Param;
667 if (NTTP->isExpandedParameterPack()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000668 SmallVector<QualType, 2> ExpandedTypes;
669 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000670 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
671 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
672 ExpandedTInfos.push_back(
673 getTrivialTypeSourceInfo(ExpandedTypes.back()));
674 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000675
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000676 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000677 SourceLocation(),
678 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000679 NTTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000680 NTTP->getPosition(), nullptr,
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000681 T,
682 TInfo,
David Majnemerdfecf1a2016-07-06 04:19:16 +0000683 ExpandedTypes,
684 ExpandedTInfos);
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000685 } else {
686 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000687 SourceLocation(),
688 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000689 NTTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000690 NTTP->getPosition(), nullptr,
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000691 T,
692 NTTP->isParameterPack(),
693 TInfo);
694 }
695 CanonParams.push_back(Param);
696
697 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000698 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
699 cast<TemplateTemplateParmDecl>(*P)));
700 }
701
Hubert Tonge4a0c0e2016-07-30 22:33:34 +0000702 assert(!TTP->getRequiresClause() &&
703 "Unexpected requires-clause on template template-parameter");
George Burgess IVb7e4e482016-08-25 01:54:37 +0000704 Expr *const CanonRequiresClause = nullptr;
Hubert Tonge4a0c0e2016-07-30 22:33:34 +0000705
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000706 TemplateTemplateParmDecl *CanonTTP
Fangrui Song6907ce22018-07-30 19:24:48 +0000707 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000708 SourceLocation(), TTP->getDepth(),
Fangrui Song6907ce22018-07-30 19:24:48 +0000709 TTP->getPosition(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000710 TTP->isParameterPack(),
Craig Topper36250ad2014-05-12 05:36:57 +0000711 nullptr,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000712 TemplateParameterList::Create(*this, SourceLocation(),
713 SourceLocation(),
David Majnemer902f8c62015-12-27 07:16:27 +0000714 CanonParams,
Hubert Tonge4a0c0e2016-07-30 22:33:34 +0000715 SourceLocation(),
716 CanonRequiresClause));
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000717
718 // Get the new insert position for the node we care about.
719 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +0000720 assert(!Canonical && "Shouldn't be in the map!");
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000721 (void)Canonical;
722
723 // Create the canonical template template parameter entry.
724 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
725 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
726 return CanonTTP;
727}
728
Charles Davis53c59df2010-08-16 03:33:14 +0000729CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
Craig Topper36250ad2014-05-12 05:36:57 +0000730 if (!LangOpts.CPlusPlus) return nullptr;
John McCall86353412010-08-21 22:46:04 +0000731
John McCall359b8852013-01-25 22:30:49 +0000732 switch (T.getCXXABI().getKind()) {
Joerg Sonnenbergerdaa13aa2014-05-13 11:20:16 +0000733 case TargetCXXABI::GenericARM: // Same as Itanium at this level
John McCall359b8852013-01-25 22:30:49 +0000734 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +0000735 case TargetCXXABI::iOS64:
Tim Northover756447a2015-10-30 16:30:36 +0000736 case TargetCXXABI::WatchOS:
Joerg Sonnenbergerdaa13aa2014-05-13 11:20:16 +0000737 case TargetCXXABI::GenericAArch64:
Zoran Jovanovic26a12162015-02-18 15:21:35 +0000738 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +0000739 case TargetCXXABI::GenericItanium:
Dan Gohmanc2853072015-09-03 22:51:53 +0000740 case TargetCXXABI::WebAssembly:
Charles Davis53c59df2010-08-16 03:33:14 +0000741 return CreateItaniumCXXABI(*this);
John McCall359b8852013-01-25 22:30:49 +0000742 case TargetCXXABI::Microsoft:
Charles Davis6bcb07a2010-08-19 02:18:14 +0000743 return CreateMicrosoftCXXABI(*this);
744 }
David Blaikie8a40f702012-01-17 06:56:22 +0000745 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000746}
747
Alexander Richardson6d989432017-10-15 18:48:14 +0000748static const LangASMap *getAddressSpaceMap(const TargetInfo &T,
749 const LangOptions &LOpts) {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000750 if (LOpts.FakeAddressSpaceMap) {
751 // The fake address space map must have a distinct entry for each
752 // language-specific address space.
753 static const unsigned FakeAddrSpaceMap[] = {
Yaxun Liub34ec822017-04-11 17:24:23 +0000754 0, // Default
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000755 1, // opencl_global
Egor Churaev28f00aa2016-12-23 16:11:25 +0000756 3, // opencl_local
757 2, // opencl_constant
Yaxun Liub7318e02017-10-13 03:37:48 +0000758 0, // opencl_private
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +0000759 4, // opencl_generic
760 5, // cuda_device
761 6, // cuda_constant
762 7 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000763 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000764 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000765 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000766 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000767 }
768}
769
David Tweed31d09b02013-09-13 12:04:22 +0000770static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
771 const LangOptions &LangOpts) {
772 switch (LangOpts.getAddressSpaceMapMangling()) {
David Tweed31d09b02013-09-13 12:04:22 +0000773 case LangOptions::ASMM_Target:
774 return TI.useAddressSpaceMapMangling();
775 case LangOptions::ASMM_On:
776 return true;
777 case LangOptions::ASMM_Off:
778 return false;
779 }
NAKAMURA Takumi5c81ca42013-09-13 17:12:09 +0000780 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
David Tweed31d09b02013-09-13 12:04:22 +0000781}
782
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000783ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000784 IdentifierTable &idents, SelectorTable &sels,
Alp Toker08043432014-05-03 03:46:04 +0000785 Builtin::Context &builtins)
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000786 : FunctionProtoTypes(this_()), TemplateSpecializationTypes(this_()),
787 DependentTemplateSpecializationTypes(this_()),
Eugene Zelenko5e5e5642017-11-23 01:20:07 +0000788 SubstTemplateTemplateParmPacks(this_()), SourceMgr(SM), LangOpts(LOpts),
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000789 SanitizerBL(new SanitizerBlacklist(LangOpts.SanitizerBlacklistFiles, SM)),
Dean Michael Berris835832d2017-03-30 00:29:36 +0000790 XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles,
Dean Michael Berris20dc6ef2018-04-09 04:02:09 +0000791 LangOpts.XRayNeverInstrumentFiles,
792 LangOpts.XRayAttrListFiles, SM)),
Artem Belevichb5bc9232015-09-22 17:23:22 +0000793 PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
Eugene Zelenko5e5e5642017-11-23 01:20:07 +0000794 BuiltinInfo(builtins), DeclarationNames(*this), Comments(SM),
Eric Fiselier0683c0e2018-05-07 21:07:10 +0000795 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
796 CompCategories(this_()), LastSDM(nullptr, 0) {
Daniel Dunbar221fa942008-08-11 04:54:23 +0000797 TUDecl = TranslationUnitDecl::Create(*this);
Sam McCall814e7972018-11-14 10:33:30 +0000798 TraversalScope = {TUDecl};
Daniel Dunbar221fa942008-08-11 04:54:23 +0000799}
800
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000801ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000802 // Release the DenseMaps associated with DeclContext objects.
803 // FIXME: Is this the ideal solution?
804 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000805
Manuel Klimeka7328992013-06-03 13:51:33 +0000806 // Call all of the deallocation functions on all of their targets.
Chandler Carruthff5a01a2015-12-30 03:00:23 +0000807 for (auto &Pair : Deallocations)
808 (Pair.first)(Pair.second);
Manuel Klimeka7328992013-06-03 13:51:33 +0000809
Ted Kremenek076baeb2010-06-08 23:00:58 +0000810 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000811 // because they can contain DenseMaps.
812 for (llvm::DenseMap<const ObjCContainerDecl*,
813 const ASTRecordLayout*>::iterator
814 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
815 // Increment in loop to prevent using deallocated memory.
Eugene Zelenko7855e772018-04-03 00:11:50 +0000816 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
Douglas Gregor5b11d492010-07-25 17:53:33 +0000817 R->Destroy(*this);
818
Ted Kremenek076baeb2010-06-08 23:00:58 +0000819 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
820 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
821 // Increment in loop to prevent using deallocated memory.
Eugene Zelenko7855e772018-04-03 00:11:50 +0000822 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
Ted Kremenek076baeb2010-06-08 23:00:58 +0000823 R->Destroy(*this);
824 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000825
Douglas Gregor561eceb2010-08-30 16:49:28 +0000826 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
827 AEnd = DeclAttrs.end();
828 A != AEnd; ++A)
829 A->second->~AttrVec();
Reid Klecknerd8110b62013-09-10 20:14:30 +0000830
David Majnemere694f3e2015-08-14 14:43:50 +0000831 for (std::pair<const MaterializeTemporaryExpr *, APValue *> &MTVPair :
832 MaterializedTemporaryValues)
833 MTVPair.second->~APValue();
834
Richard Smith423f46f2016-07-20 21:38:26 +0000835 for (const auto &Value : ModuleInitializers)
836 Value.second->~PerModuleInitializers();
Douglas Gregor561eceb2010-08-30 16:49:28 +0000837}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000838
Sam McCall814e7972018-11-14 10:33:30 +0000839class ASTContext::ParentMap {
840 /// Contains parents of a node.
841 using ParentVector = llvm::SmallVector<ast_type_traits::DynTypedNode, 2>;
842
843 /// Maps from a node to its parents. This is used for nodes that have
844 /// pointer identity only, which are more common and we can save space by
845 /// only storing a unique pointer to them.
846 using ParentMapPointers = llvm::DenseMap<
847 const void *,
848 llvm::PointerUnion4<const Decl *, const Stmt *,
849 ast_type_traits::DynTypedNode *, ParentVector *>>;
850
851 /// Parent map for nodes without pointer identity. We store a full
852 /// DynTypedNode for all keys.
853 using ParentMapOtherNodes = llvm::DenseMap<
854 ast_type_traits::DynTypedNode,
855 llvm::PointerUnion4<const Decl *, const Stmt *,
856 ast_type_traits::DynTypedNode *, ParentVector *>>;
857
858 ParentMapPointers PointerParents;
859 ParentMapOtherNodes OtherParents;
860 class ASTVisitor;
861
862 static ast_type_traits::DynTypedNode
863 getSingleDynTypedNodeFromParentMap(ParentMapPointers::mapped_type U) {
864 if (const auto *D = U.dyn_cast<const Decl *>())
865 return ast_type_traits::DynTypedNode::create(*D);
866 if (const auto *S = U.dyn_cast<const Stmt *>())
867 return ast_type_traits::DynTypedNode::create(*S);
868 return *U.get<ast_type_traits::DynTypedNode *>();
869 }
870
871 template <typename NodeTy, typename MapTy>
872 static ASTContext::DynTypedNodeList getDynNodeFromMap(const NodeTy &Node,
873 const MapTy &Map) {
874 auto I = Map.find(Node);
875 if (I == Map.end()) {
876 return llvm::ArrayRef<ast_type_traits::DynTypedNode>();
877 }
878 if (const auto *V = I->second.template dyn_cast<ParentVector *>()) {
879 return llvm::makeArrayRef(*V);
880 }
881 return getSingleDynTypedNodeFromParentMap(I->second);
882 }
883
884public:
885 ParentMap(ASTContext &Ctx);
886 ~ParentMap() {
887 for (const auto &Entry : PointerParents) {
888 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
889 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
890 } else if (Entry.second.is<ParentVector *>()) {
891 delete Entry.second.get<ParentVector *>();
892 }
893 }
894 for (const auto &Entry : OtherParents) {
895 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
896 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
897 } else if (Entry.second.is<ParentVector *>()) {
898 delete Entry.second.get<ParentVector *>();
899 }
Benjamin Kramer94355ae2015-10-23 09:04:55 +0000900 }
901 }
Sam McCall814e7972018-11-14 10:33:30 +0000902
903 DynTypedNodeList getParents(const ast_type_traits::DynTypedNode &Node) {
904 if (Node.getNodeKind().hasPointerIdentity())
905 return getDynNodeFromMap(Node.getMemoizationData(), PointerParents);
906 return getDynNodeFromMap(Node, OtherParents);
Manuel Klimek95403e62014-05-21 13:28:59 +0000907 }
Sam McCall814e7972018-11-14 10:33:30 +0000908};
909
910void ASTContext::setTraversalScope(const std::vector<Decl *> &TopLevelDecls) {
911 TraversalScope = TopLevelDecls;
912 Parents.reset();
Manuel Klimek95403e62014-05-21 13:28:59 +0000913}
914
Douglas Gregor1a809332010-05-23 18:26:36 +0000915void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
Chandler Carruthff5a01a2015-12-30 03:00:23 +0000916 Deallocations.push_back({Callback, Data});
Douglas Gregor1a809332010-05-23 18:26:36 +0000917}
918
Mike Stump11289f42009-09-09 15:08:12 +0000919void
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000920ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
Benjamin Kramerd6da1a02016-06-12 20:05:23 +0000921 ExternalSource = std::move(Source);
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000922}
923
Chris Lattner4eb445d2007-01-26 01:27:23 +0000924void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000925 llvm::errs() << "\n*** AST Context Stats:\n";
926 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000927
Douglas Gregora30d0462009-05-26 14:40:08 +0000928 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000929#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000930#define ABSTRACT_TYPE(Name, Parent)
931#include "clang/AST/TypeNodes.def"
932 0 // Extra
933 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000934
Chris Lattner4eb445d2007-01-26 01:27:23 +0000935 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
936 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000937 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000938 }
939
Douglas Gregora30d0462009-05-26 14:40:08 +0000940 unsigned Idx = 0;
941 unsigned TotalBytes = 0;
942#define TYPE(Name, Parent) \
943 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000944 llvm::errs() << " " << counts[Idx] << " " << #Name \
Bruno Ricci58e03222018-08-06 15:17:32 +0000945 << " types, " << sizeof(Name##Type) << " each " \
946 << "(" << counts[Idx] * sizeof(Name##Type) \
947 << " bytes)\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000948 TotalBytes += counts[Idx] * sizeof(Name##Type); \
949 ++Idx;
950#define ABSTRACT_TYPE(Name, Parent)
951#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000952
Chandler Carruth3c147a72011-07-04 05:32:14 +0000953 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
954
Douglas Gregor7454c562010-07-02 20:37:36 +0000955 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000956 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
957 << NumImplicitDefaultConstructors
958 << " implicit default constructors created\n";
959 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
960 << NumImplicitCopyConstructors
961 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000962 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000963 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
964 << NumImplicitMoveConstructors
965 << " implicit move constructors created\n";
966 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
967 << NumImplicitCopyAssignmentOperators
968 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000969 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000970 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
971 << NumImplicitMoveAssignmentOperators
972 << " implicit move assignment operators created\n";
973 llvm::errs() << NumImplicitDestructorsDeclared << "/"
974 << NumImplicitDestructors
975 << " implicit destructors created\n";
976
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000977 if (ExternalSource) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000978 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000979 ExternalSource->PrintStats();
980 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000981
Douglas Gregor5b11d492010-07-25 17:53:33 +0000982 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000983}
984
Richard Smith42413142015-05-15 20:05:43 +0000985void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
986 bool NotifyListeners) {
987 if (NotifyListeners)
988 if (auto *Listener = getASTMutationListener())
989 Listener->RedefinedHiddenDefinition(ND, M);
990
Richard Smith13897eb2018-09-12 23:37:00 +0000991 MergedDefModules[cast<NamedDecl>(ND->getCanonicalDecl())].push_back(M);
Richard Smith42413142015-05-15 20:05:43 +0000992}
993
994void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) {
Richard Smith20fbdb32018-09-12 02:13:46 +0000995 auto It = MergedDefModules.find(cast<NamedDecl>(ND->getCanonicalDecl()));
Richard Smith42413142015-05-15 20:05:43 +0000996 if (It == MergedDefModules.end())
997 return;
998
Benjamin Kramera72a70a2016-10-17 13:00:44 +0000999 auto &Merged = It->second;
Richard Smith42413142015-05-15 20:05:43 +00001000 llvm::DenseSet<Module*> Found;
1001 for (Module *&M : Merged)
1002 if (!Found.insert(M).second)
1003 M = nullptr;
1004 Merged.erase(std::remove(Merged.begin(), Merged.end(), nullptr), Merged.end());
1005}
1006
Richard Smithdc1f0422016-07-20 19:10:16 +00001007void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
1008 if (LazyInitializers.empty())
1009 return;
1010
1011 auto *Source = Ctx.getExternalSource();
1012 assert(Source && "lazy initializers but no external source");
1013
1014 auto LazyInits = std::move(LazyInitializers);
1015 LazyInitializers.clear();
1016
1017 for (auto ID : LazyInits)
1018 Initializers.push_back(Source->GetExternalDecl(ID));
1019
1020 assert(LazyInitializers.empty() &&
1021 "GetExternalDecl for lazy module initializer added more inits");
1022}
1023
1024void ASTContext::addModuleInitializer(Module *M, Decl *D) {
1025 // One special case: if we add a module initializer that imports another
1026 // module, and that module's only initializer is an ImportDecl, simplify.
Eugene Zelenko7855e772018-04-03 00:11:50 +00001027 if (const auto *ID = dyn_cast<ImportDecl>(D)) {
Richard Smithdc1f0422016-07-20 19:10:16 +00001028 auto It = ModuleInitializers.find(ID->getImportedModule());
1029
1030 // Maybe the ImportDecl does nothing at all. (Common case.)
1031 if (It == ModuleInitializers.end())
1032 return;
1033
1034 // Maybe the ImportDecl only imports another ImportDecl.
1035 auto &Imported = *It->second;
1036 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
1037 Imported.resolve(*this);
1038 auto *OnlyDecl = Imported.Initializers.front();
1039 if (isa<ImportDecl>(OnlyDecl))
1040 D = OnlyDecl;
1041 }
1042 }
1043
1044 auto *&Inits = ModuleInitializers[M];
1045 if (!Inits)
1046 Inits = new (*this) PerModuleInitializers;
1047 Inits->Initializers.push_back(D);
1048}
1049
1050void ASTContext::addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs) {
1051 auto *&Inits = ModuleInitializers[M];
1052 if (!Inits)
1053 Inits = new (*this) PerModuleInitializers;
1054 Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
1055 IDs.begin(), IDs.end());
1056}
1057
Eugene Zelenko7855e772018-04-03 00:11:50 +00001058ArrayRef<Decl *> ASTContext::getModuleInitializers(Module *M) {
Richard Smithdc1f0422016-07-20 19:10:16 +00001059 auto It = ModuleInitializers.find(M);
Fangrui Song6907ce22018-07-30 19:24:48 +00001060 if (It == ModuleInitializers.end())
Richard Smithdc1f0422016-07-20 19:10:16 +00001061 return None;
1062
1063 auto *Inits = It->second;
1064 Inits->resolve(*this);
1065 return Inits->Initializers;
1066}
1067
Richard Smithf19e1272015-03-07 00:04:49 +00001068ExternCContextDecl *ASTContext::getExternCContextDecl() const {
1069 if (!ExternCContext)
1070 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
1071
1072 return ExternCContext;
1073}
1074
David Majnemerd9b1a4f2015-11-04 03:40:30 +00001075BuiltinTemplateDecl *
1076ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
1077 const IdentifierInfo *II) const {
1078 auto *BuiltinTemplate = BuiltinTemplateDecl::Create(*this, TUDecl, II, BTK);
1079 BuiltinTemplate->setImplicit();
1080 TUDecl->addDecl(BuiltinTemplate);
1081
1082 return BuiltinTemplate;
1083}
1084
1085BuiltinTemplateDecl *
1086ASTContext::getMakeIntegerSeqDecl() const {
1087 if (!MakeIntegerSeqDecl)
1088 MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq,
1089 getMakeIntegerSeqName());
1090 return MakeIntegerSeqDecl;
1091}
1092
Eric Fiselier6ad68552016-07-01 01:24:09 +00001093BuiltinTemplateDecl *
1094ASTContext::getTypePackElementDecl() const {
1095 if (!TypePackElementDecl)
1096 TypePackElementDecl = buildBuiltinTemplateDecl(BTK__type_pack_element,
1097 getTypePackElementName());
1098 return TypePackElementDecl;
1099}
1100
Alp Toker2dea15b2013-12-17 01:22:38 +00001101RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
1102 RecordDecl::TagKind TK) const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001103 SourceLocation Loc;
1104 RecordDecl *NewDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00001105 if (getLangOpts().CPlusPlus)
1106 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
1107 Loc, &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +00001108 else
Alp Toker2dea15b2013-12-17 01:22:38 +00001109 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
1110 &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +00001111 NewDecl->setImplicit();
David Majnemerf8637362015-01-15 08:41:25 +00001112 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
1113 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
Alp Toker56b5cc92013-12-15 10:36:26 +00001114 return NewDecl;
1115}
1116
1117TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
1118 StringRef Name) const {
1119 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
1120 TypedefDecl *NewDecl = TypedefDecl::Create(
1121 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
1122 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
1123 NewDecl->setImplicit();
1124 return NewDecl;
1125}
1126
Douglas Gregor801c99d2011-08-12 06:49:56 +00001127TypedefDecl *ASTContext::getInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001128 if (!Int128Decl)
1129 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +00001130 return Int128Decl;
1131}
1132
1133TypedefDecl *ASTContext::getUInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001134 if (!UInt128Decl)
1135 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +00001136 return UInt128Decl;
1137}
Chris Lattner4eb445d2007-01-26 01:27:23 +00001138
John McCall48f2d582009-10-23 23:03:21 +00001139void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001140 auto *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +00001141 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +00001142 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001143}
1144
Artem Belevichb5bc9232015-09-22 17:23:22 +00001145void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
1146 const TargetInfo *AuxTarget) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001147 assert((!this->Target || this->Target == &Target) &&
1148 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +00001149 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +00001150
Douglas Gregore8bbc122011-09-02 00:18:52 +00001151 this->Target = &Target;
Artem Belevichb5bc9232015-09-22 17:23:22 +00001152 this->AuxTarget = AuxTarget;
1153
Douglas Gregore8bbc122011-09-02 00:18:52 +00001154 ABI.reset(createCXXABI(Target));
1155 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
David Tweed31d09b02013-09-13 12:04:22 +00001156 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
Fangrui Song6907ce22018-07-30 19:24:48 +00001157
Chris Lattner970e54e2006-11-12 00:37:36 +00001158 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +00001159 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +00001160
Chris Lattner970e54e2006-11-12 00:37:36 +00001161 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +00001162 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +00001163 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +00001164 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +00001165 InitBuiltinType(CharTy, BuiltinType::Char_S);
1166 else
1167 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +00001168 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +00001169 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
1170 InitBuiltinType(ShortTy, BuiltinType::Short);
1171 InitBuiltinType(IntTy, BuiltinType::Int);
1172 InitBuiltinType(LongTy, BuiltinType::Long);
1173 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +00001174
Chris Lattner970e54e2006-11-12 00:37:36 +00001175 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +00001176 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
1177 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
1178 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
1179 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
1180 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +00001181
Chris Lattner970e54e2006-11-12 00:37:36 +00001182 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +00001183 InitBuiltinType(FloatTy, BuiltinType::Float);
1184 InitBuiltinType(DoubleTy, BuiltinType::Double);
1185 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001186
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001187 // GNU extension, __float128 for IEEE quadruple precision
1188 InitBuiltinType(Float128Ty, BuiltinType::Float128);
1189
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00001190 // C11 extension ISO/IEC TS 18661-3
1191 InitBuiltinType(Float16Ty, BuiltinType::Float16);
1192
Leonard Chanf921d852018-06-04 16:07:52 +00001193 // ISO/IEC JTC1 SC22 WG14 N1169 Extension
Leonard Chanab80f3c2018-06-14 14:53:51 +00001194 InitBuiltinType(ShortAccumTy, BuiltinType::ShortAccum);
1195 InitBuiltinType(AccumTy, BuiltinType::Accum);
1196 InitBuiltinType(LongAccumTy, BuiltinType::LongAccum);
1197 InitBuiltinType(UnsignedShortAccumTy, BuiltinType::UShortAccum);
1198 InitBuiltinType(UnsignedAccumTy, BuiltinType::UAccum);
1199 InitBuiltinType(UnsignedLongAccumTy, BuiltinType::ULongAccum);
1200 InitBuiltinType(ShortFractTy, BuiltinType::ShortFract);
1201 InitBuiltinType(FractTy, BuiltinType::Fract);
1202 InitBuiltinType(LongFractTy, BuiltinType::LongFract);
1203 InitBuiltinType(UnsignedShortFractTy, BuiltinType::UShortFract);
1204 InitBuiltinType(UnsignedFractTy, BuiltinType::UFract);
1205 InitBuiltinType(UnsignedLongFractTy, BuiltinType::ULongFract);
1206 InitBuiltinType(SatShortAccumTy, BuiltinType::SatShortAccum);
1207 InitBuiltinType(SatAccumTy, BuiltinType::SatAccum);
1208 InitBuiltinType(SatLongAccumTy, BuiltinType::SatLongAccum);
1209 InitBuiltinType(SatUnsignedShortAccumTy, BuiltinType::SatUShortAccum);
1210 InitBuiltinType(SatUnsignedAccumTy, BuiltinType::SatUAccum);
1211 InitBuiltinType(SatUnsignedLongAccumTy, BuiltinType::SatULongAccum);
1212 InitBuiltinType(SatShortFractTy, BuiltinType::SatShortFract);
1213 InitBuiltinType(SatFractTy, BuiltinType::SatFract);
1214 InitBuiltinType(SatLongFractTy, BuiltinType::SatLongFract);
1215 InitBuiltinType(SatUnsignedShortFractTy, BuiltinType::SatUShortFract);
1216 InitBuiltinType(SatUnsignedFractTy, BuiltinType::SatUFract);
1217 InitBuiltinType(SatUnsignedLongFractTy, BuiltinType::SatULongFract);
Leonard Chanf921d852018-06-04 16:07:52 +00001218
Chris Lattnerf122cef2009-04-30 02:43:43 +00001219 // GNU extension, 128-bit integers.
1220 InitBuiltinType(Int128Ty, BuiltinType::Int128);
1221 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
1222
Hans Wennborg0d81e012013-05-10 10:08:40 +00001223 // C++ 3.9.1p5
1224 if (TargetInfo::isTypeSigned(Target.getWCharType()))
1225 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1226 else // -fshort-wchar makes wchar_t be unsigned.
1227 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1228 if (LangOpts.CPlusPlus && LangOpts.WChar)
1229 WideCharTy = WCharTy;
1230 else {
1231 // C99 (or C++ using -fno-wchar).
1232 WideCharTy = getFromTargetType(Target.getWCharType());
1233 }
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001234
James Molloy36365542012-05-04 10:55:22 +00001235 WIntTy = getFromTargetType(Target.getWIntType());
1236
Richard Smith3a8244d2018-05-01 05:02:45 +00001237 // C++20 (proposed)
1238 InitBuiltinType(Char8Ty, BuiltinType::Char8);
1239
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001240 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1241 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1242 else // C99
1243 Char16Ty = getFromTargetType(Target.getChar16Type());
1244
1245 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1246 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1247 else // C99
1248 Char32Ty = getFromTargetType(Target.getChar32Type());
1249
Douglas Gregor4619e432008-12-05 23:32:09 +00001250 // Placeholder type for type-dependent expressions whose type is
1251 // completely unknown. No code should ever check a type against
1252 // DependentTy and users should never see it; however, it is here to
1253 // help diagnose failures to properly check for type-dependent
1254 // expressions.
1255 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001256
John McCall36e7fe32010-10-12 00:20:44 +00001257 // Placeholder type for functions.
1258 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1259
John McCall0009fcc2011-04-26 20:42:42 +00001260 // Placeholder type for bound members.
1261 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1262
John McCall526ab472011-10-25 17:37:35 +00001263 // Placeholder type for pseudo-objects.
1264 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1265
John McCall31996342011-04-07 08:22:57 +00001266 // "any" type; useful for debugger-like clients.
1267 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1268
John McCall8a6b59a2011-10-17 18:09:15 +00001269 // Placeholder type for unbridged ARC casts.
1270 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1271
Eli Friedman34866c72012-08-31 00:14:07 +00001272 // Placeholder type for builtin functions.
1273 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1274
Alexey Bataev1a3320e2015-08-25 14:24:04 +00001275 // Placeholder type for OMP array sections.
1276 if (LangOpts.OpenMP)
1277 InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection);
1278
Chris Lattner970e54e2006-11-12 00:37:36 +00001279 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +00001280 FloatComplexTy = getComplexType(FloatTy);
1281 DoubleComplexTy = getComplexType(DoubleTy);
1282 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001283 Float128ComplexTy = getComplexType(Float128Ty);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001284
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001285 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +00001286 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1287 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001288 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001289
Alexey Bader954ba212016-04-08 13:40:33 +00001290 if (LangOpts.OpenCL) {
1291#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1292 InitBuiltinType(SingletonId, BuiltinType::Id);
Alexey Baderb62f1442016-04-13 08:33:41 +00001293#include "clang/Basic/OpenCLImageTypes.def"
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001294
Guy Benyei61054192013-02-07 10:55:47 +00001295 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001296 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Alexey Bader9c8453f2015-09-15 11:18:52 +00001297 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1298 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
Alexey Bader9c8453f2015-09-15 11:18:52 +00001299 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
Andrew Savonichev3fee3512018-11-08 11:25:41 +00001300
1301#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1302 InitBuiltinType(Id##Ty, BuiltinType::Id);
1303#include "clang/Basic/OpenCLExtensionTypes.def"
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001304 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001305
Ted Kremeneke65b0862012-03-06 20:05:56 +00001306 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +00001307 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1308 SignedCharTy : BoolTy);
Fangrui Song6907ce22018-07-30 19:24:48 +00001309
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001310 ObjCConstantStringType = QualType();
Fangrui Song6907ce22018-07-30 19:24:48 +00001311
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001312 ObjCSuperType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +00001313
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00001314 // void * type
Yaxun Liu39195062017-08-04 18:16:31 +00001315 if (LangOpts.OpenCLVersion >= 200) {
1316 auto Q = VoidTy.getQualifiers();
1317 Q.setAddressSpace(LangAS::opencl_generic);
1318 VoidPtrTy = getPointerType(getCanonicalType(
1319 getQualifiedType(VoidTy.getUnqualifiedType(), Q)));
1320 } else {
1321 VoidPtrTy = getPointerType(VoidTy);
1322 }
Sebastian Redl576fd422009-05-10 18:38:11 +00001323
1324 // nullptr type (C++0x 2.14.7)
1325 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001326
1327 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1328 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +00001329
1330 // Builtin type used to help define __builtin_va_list.
Richard Smith9b88a4c2015-07-27 05:40:23 +00001331 VaListTagDecl = nullptr;
Chris Lattner970e54e2006-11-12 00:37:36 +00001332}
1333
David Blaikie9c902b52011-09-25 23:23:43 +00001334DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001335 return SourceMgr.getDiagnostics();
1336}
1337
Douglas Gregor561eceb2010-08-30 16:49:28 +00001338AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1339 AttrVec *&Result = DeclAttrs[D];
1340 if (!Result) {
1341 void *Mem = Allocate(sizeof(AttrVec));
1342 Result = new (Mem) AttrVec;
1343 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001344
Douglas Gregor561eceb2010-08-30 16:49:28 +00001345 return *Result;
1346}
1347
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001348/// Erase the attributes corresponding to the given declaration.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00001349void ASTContext::eraseDeclAttrs(const Decl *D) {
Douglas Gregor561eceb2010-08-30 16:49:28 +00001350 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1351 if (Pos != DeclAttrs.end()) {
1352 Pos->second->~AttrVec();
1353 DeclAttrs.erase(Pos);
1354 }
1355}
1356
Larisse Voufo39a1e502013-08-06 01:03:05 +00001357// FIXME: Remove ?
Douglas Gregor86d142a2009-10-08 07:24:58 +00001358MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +00001359ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001360 assert(Var->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001361 return getTemplateOrSpecializationInfo(Var)
1362 .dyn_cast<MemberSpecializationInfo *>();
1363}
1364
1365ASTContext::TemplateOrSpecializationInfo
1366ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1367 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1368 TemplateOrInstantiation.find(Var);
1369 if (Pos == TemplateOrInstantiation.end())
Eugene Zelenko7855e772018-04-03 00:11:50 +00001370 return {};
Mike Stump11289f42009-09-09 15:08:12 +00001371
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001372 return Pos->second;
1373}
1374
Mike Stump11289f42009-09-09 15:08:12 +00001375void
Douglas Gregor86d142a2009-10-08 07:24:58 +00001376ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +00001377 TemplateSpecializationKind TSK,
1378 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001379 assert(Inst->isStaticDataMember() && "Not a static data member");
1380 assert(Tmpl->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001381 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1382 Tmpl, TSK, PointOfInstantiation));
1383}
1384
1385void
1386ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1387 TemplateOrSpecializationInfo TSI) {
1388 assert(!TemplateOrInstantiation[Inst] &&
1389 "Already noted what the variable was instantiated from");
1390 TemplateOrInstantiation[Inst] = TSI;
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001391}
1392
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001393FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1394 const FunctionDecl *FD){
1395 assert(FD && "Specialization is 0");
1396 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +00001397 = ClassScopeSpecializationPattern.find(FD);
1398 if (Pos == ClassScopeSpecializationPattern.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001399 return nullptr;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001400
1401 return Pos->second;
1402}
1403
1404void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1405 FunctionDecl *Pattern) {
1406 assert(FD && "Specialization is 0");
1407 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +00001408 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001409}
1410
John McCalle61f2ba2009-11-18 02:36:19 +00001411NamedDecl *
Richard Smithd8a9e372016-12-18 21:39:37 +00001412ASTContext::getInstantiatedFromUsingDecl(NamedDecl *UUD) {
1413 auto Pos = InstantiatedFromUsingDecl.find(UUD);
John McCallb96ec562009-12-04 22:46:56 +00001414 if (Pos == InstantiatedFromUsingDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001415 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001416
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001417 return Pos->second;
1418}
1419
1420void
Richard Smithd8a9e372016-12-18 21:39:37 +00001421ASTContext::setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern) {
John McCallb96ec562009-12-04 22:46:56 +00001422 assert((isa<UsingDecl>(Pattern) ||
1423 isa<UnresolvedUsingValueDecl>(Pattern) ||
Fangrui Song6907ce22018-07-30 19:24:48 +00001424 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
John McCallb96ec562009-12-04 22:46:56 +00001425 "pattern decl is not a using decl");
Richard Smithd8a9e372016-12-18 21:39:37 +00001426 assert((isa<UsingDecl>(Inst) ||
1427 isa<UnresolvedUsingValueDecl>(Inst) ||
Fangrui Song6907ce22018-07-30 19:24:48 +00001428 isa<UnresolvedUsingTypenameDecl>(Inst)) &&
Richard Smithd8a9e372016-12-18 21:39:37 +00001429 "instantiation did not produce a using decl");
John McCallb96ec562009-12-04 22:46:56 +00001430 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1431 InstantiatedFromUsingDecl[Inst] = Pattern;
1432}
1433
1434UsingShadowDecl *
1435ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1436 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1437 = InstantiatedFromUsingShadowDecl.find(Inst);
1438 if (Pos == InstantiatedFromUsingShadowDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001439 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00001440
1441 return Pos->second;
1442}
1443
1444void
1445ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1446 UsingShadowDecl *Pattern) {
1447 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1448 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001449}
1450
Anders Carlsson5da84842009-09-01 04:26:58 +00001451FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1452 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1453 = InstantiatedFromUnnamedFieldDecl.find(Field);
1454 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001455 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001456
Anders Carlsson5da84842009-09-01 04:26:58 +00001457 return Pos->second;
1458}
1459
1460void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1461 FieldDecl *Tmpl) {
1462 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1463 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1464 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1465 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +00001466
Anders Carlsson5da84842009-09-01 04:26:58 +00001467 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1468}
1469
Douglas Gregor832940b2010-03-02 23:58:15 +00001470ASTContext::overridden_cxx_method_iterator
1471ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
Benjamin Krameracfa3392017-12-17 23:52:45 +00001472 return overridden_methods(Method).begin();
Douglas Gregor832940b2010-03-02 23:58:15 +00001473}
1474
1475ASTContext::overridden_cxx_method_iterator
1476ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
Benjamin Krameracfa3392017-12-17 23:52:45 +00001477 return overridden_methods(Method).end();
Douglas Gregor832940b2010-03-02 23:58:15 +00001478}
1479
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001480unsigned
1481ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
Benjamin Krameracfa3392017-12-17 23:52:45 +00001482 auto Range = overridden_methods(Method);
1483 return Range.end() - Range.begin();
Clement Courbet8251ebf2016-06-10 11:54:43 +00001484}
1485
Clement Courbet6ecaec82016-07-05 07:49:31 +00001486ASTContext::overridden_method_range
1487ASTContext::overridden_methods(const CXXMethodDecl *Method) const {
Benjamin Krameracfa3392017-12-17 23:52:45 +00001488 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1489 OverriddenMethods.find(Method->getCanonicalDecl());
1490 if (Pos == OverriddenMethods.end())
1491 return overridden_method_range(nullptr, nullptr);
1492 return overridden_method_range(Pos->second.begin(), Pos->second.end());
Clement Courbet6ecaec82016-07-05 07:49:31 +00001493}
1494
Fangrui Song6907ce22018-07-30 19:24:48 +00001495void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
Douglas Gregor832940b2010-03-02 23:58:15 +00001496 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001497 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001498 OverriddenMethods[Method].push_back(Overridden);
1499}
1500
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +00001501void ASTContext::getOverriddenMethods(
1502 const NamedDecl *D,
1503 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001504 assert(D);
1505
Eugene Zelenko7855e772018-04-03 00:11:50 +00001506 if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisc8e70082013-04-17 00:09:03 +00001507 Overridden.append(overridden_methods_begin(CXXMethod),
1508 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001509 return;
1510 }
1511
Eugene Zelenko7855e772018-04-03 00:11:50 +00001512 const auto *Method = dyn_cast<ObjCMethodDecl>(D);
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001513 if (!Method)
1514 return;
1515
Argyrios Kyrtzidis353f6a42012-10-09 18:19:01 +00001516 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1517 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001518 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001519}
1520
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001521void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1522 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1523 assert(!Import->isFromASTFile() && "Non-local import declaration");
1524 if (!FirstLocalImport) {
1525 FirstLocalImport = Import;
1526 LastLocalImport = Import;
1527 return;
1528 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001529
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001530 LastLocalImport->NextLocalImport = Import;
1531 LastLocalImport = Import;
1532}
1533
Chris Lattner53cfe802007-07-18 17:52:12 +00001534//===----------------------------------------------------------------------===//
1535// Type Sizing and Analysis
1536//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001537
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001538/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1539/// scalar floating point type.
1540const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001541 const auto *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001542 assert(BT && "Not a floating point type!");
1543 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001544 default: llvm_unreachable("Not a floating point type!");
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00001545 case BuiltinType::Float16:
1546 case BuiltinType::Half:
1547 return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001548 case BuiltinType::Float: return Target->getFloatFormat();
1549 case BuiltinType::Double: return Target->getDoubleFormat();
1550 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001551 case BuiltinType::Float128: return Target->getFloat128Format();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001552 }
1553}
1554
Rafael Espindola71eccb32013-08-08 19:53:46 +00001555CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001556 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001557
John McCall94268702010-10-08 18:24:19 +00001558 bool UseAlignAttrOnly = false;
1559 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1560 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001561
John McCall94268702010-10-08 18:24:19 +00001562 // __attribute__((aligned)) can increase or decrease alignment
1563 // *except* on a struct or struct member, where it only increases
1564 // alignment unless 'packed' is also specified.
1565 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001566 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001567 // ignore that possibility; Sema should diagnose it.
1568 if (isa<FieldDecl>(D)) {
1569 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1570 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1571 } else {
1572 UseAlignAttrOnly = true;
1573 }
1574 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001575 else if (isa<FieldDecl>(D))
Fangrui Song6907ce22018-07-30 19:24:48 +00001576 UseAlignAttrOnly =
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001577 D->hasAttr<PackedAttr>() ||
1578 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001579
John McCall4e819612011-01-20 07:57:12 +00001580 // If we're using the align attribute only, just ignore everything
1581 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001582 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001583 // do nothing
Eugene Zelenko7855e772018-04-03 00:11:50 +00001584 } else if (const auto *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001585 QualType T = VD->getType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00001586 if (const auto *RT = T->getAs<ReferenceType>()) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001587 if (ForAlignof)
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001588 T = RT->getPointeeType();
1589 else
1590 T = getPointerType(RT->getPointeeType());
1591 }
Richard Smithf6d70302014-06-10 23:34:28 +00001592 QualType BaseT = getBaseElementType(T);
Akira Hatanakad62f2c82017-01-06 17:56:15 +00001593 if (T->isFunctionType())
1594 Align = getTypeInfoImpl(T.getTypePtr()).Align;
1595 else if (!BaseT->isIncompleteType()) {
John McCall33ddac02011-01-19 10:06:00 +00001596 // Adjust alignments of declarations with array type by the
1597 // large-array alignment on the target.
Rafael Espindola88572752013-08-07 18:08:19 +00001598 if (const ArrayType *arrayType = getAsArrayType(T)) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001599 unsigned MinWidth = Target->getLargeArrayMinWidth();
1600 if (!ForAlignof && MinWidth) {
Rafael Espindola88572752013-08-07 18:08:19 +00001601 if (isa<VariableArrayType>(arrayType))
1602 Align = std::max(Align, Target->getLargeArrayAlign());
1603 else if (isa<ConstantArrayType>(arrayType) &&
1604 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1605 Align = std::max(Align, Target->getLargeArrayAlign());
1606 }
John McCall33ddac02011-01-19 10:06:00 +00001607 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001608 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Roger Ferrer Ibanez3fa38a12017-03-08 14:00:44 +00001609 if (BaseT.getQualifiers().hasUnaligned())
1610 Align = Target->getCharWidth();
Eugene Zelenko7855e772018-04-03 00:11:50 +00001611 if (const auto *VD = dyn_cast<VarDecl>(D)) {
Ulrich Weigandb63f7792015-04-21 17:26:18 +00001612 if (VD->hasGlobalStorage() && !ForAlignof)
Ulrich Weigandfa806422013-05-06 16:23:57 +00001613 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1614 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001615 }
John McCall4e819612011-01-20 07:57:12 +00001616
1617 // Fields can be subject to extra alignment constraints, like if
1618 // the field is packed, the struct is packed, or the struct has a
1619 // a max-field-alignment constraint (#pragma pack). So calculate
1620 // the actual alignment of the field within the struct, and then
1621 // (as we're expected to) constrain that by the alignment of the type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00001622 if (const auto *Field = dyn_cast<FieldDecl>(VD)) {
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001623 const RecordDecl *Parent = Field->getParent();
1624 // We can only produce a sensible answer if the record is valid.
1625 if (!Parent->isInvalidDecl()) {
1626 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
John McCall4e819612011-01-20 07:57:12 +00001627
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001628 // Start with the record's overall alignment.
1629 unsigned FieldAlign = toBits(Layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001630
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001631 // Use the GCD of that and the offset within the record.
1632 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1633 if (Offset > 0) {
1634 // Alignment is always a power of 2, so the GCD will be a power of 2,
1635 // which means we get to do this crazy thing instead of Euclid's.
1636 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1637 if (LowBitOfOffset < FieldAlign)
1638 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1639 }
1640
1641 Align = std::min(Align, FieldAlign);
John McCall4e819612011-01-20 07:57:12 +00001642 }
Charles Davis3fc51072010-02-23 04:52:00 +00001643 }
Chris Lattner68061312009-01-24 21:53:27 +00001644 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001645
Ken Dyckcc56c542011-01-15 18:38:59 +00001646 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001647}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001648
John McCallf1249922012-08-21 04:10:00 +00001649// getTypeInfoDataSizeInChars - Return the size of a type, in
1650// chars. If the type is a record, its data size is returned. This is
1651// the size of the memcpy that's performed when assigning this type
1652// using a trivial copy/move assignment operator.
1653std::pair<CharUnits, CharUnits>
1654ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1655 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1656
1657 // In C++, objects can sometimes be allocated into the tail padding
1658 // of a base-class subobject. We decide whether that's possible
1659 // during class layout, so here we can just trust the layout results.
1660 if (getLangOpts().CPlusPlus) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001661 if (const auto *RT = T->getAs<RecordType>()) {
John McCallf1249922012-08-21 04:10:00 +00001662 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1663 sizeAndAlign.first = layout.getDataSize();
1664 }
1665 }
1666
1667 return sizeAndAlign;
1668}
1669
Richard Trieu04d2d942013-05-14 21:59:17 +00001670/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1671/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1672std::pair<CharUnits, CharUnits>
1673static getConstantArrayInfoInChars(const ASTContext &Context,
1674 const ConstantArrayType *CAT) {
1675 std::pair<CharUnits, CharUnits> EltInfo =
1676 Context.getTypeInfoInChars(CAT->getElementType());
1677 uint64_t Size = CAT->getSize().getZExtValue();
Richard Trieuc7509072013-05-14 23:41:50 +00001678 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1679 (uint64_t)(-1)/Size) &&
Richard Trieu04d2d942013-05-14 21:59:17 +00001680 "Overflow in array type char size evaluation");
1681 uint64_t Width = EltInfo.first.getQuantity() * Size;
1682 unsigned Align = EltInfo.second.getQuantity();
Warren Hunt5ae586a2013-11-01 23:59:41 +00001683 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1684 Context.getTargetInfo().getPointerWidth(0) == 64)
Rui Ueyama83aa9792016-01-14 21:00:27 +00001685 Width = llvm::alignTo(Width, Align);
Richard Trieu04d2d942013-05-14 21:59:17 +00001686 return std::make_pair(CharUnits::fromQuantity(Width),
1687 CharUnits::fromQuantity(Align));
1688}
1689
John McCall87fe5d52010-05-20 01:18:31 +00001690std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001691ASTContext::getTypeInfoInChars(const Type *T) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001692 if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
Richard Trieu04d2d942013-05-14 21:59:17 +00001693 return getConstantArrayInfoInChars(*this, CAT);
David Majnemer34b57492014-07-30 01:30:47 +00001694 TypeInfo Info = getTypeInfo(T);
1695 return std::make_pair(toCharUnitsFromBits(Info.Width),
1696 toCharUnitsFromBits(Info.Align));
John McCall87fe5d52010-05-20 01:18:31 +00001697}
1698
1699std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001700ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001701 return getTypeInfoInChars(T.getTypePtr());
1702}
1703
David Majnemer34b57492014-07-30 01:30:47 +00001704bool ASTContext::isAlignmentRequired(const Type *T) const {
1705 return getTypeInfo(T).AlignIsRequired;
1706}
Daniel Dunbarc6475872012-03-09 04:12:54 +00001707
David Majnemer34b57492014-07-30 01:30:47 +00001708bool ASTContext::isAlignmentRequired(QualType T) const {
1709 return isAlignmentRequired(T.getTypePtr());
1710}
1711
Richard Smithb2f0f052016-10-10 18:54:32 +00001712unsigned ASTContext::getTypeAlignIfKnown(QualType T) const {
1713 // An alignment on a typedef overrides anything else.
Eugene Zelenko7855e772018-04-03 00:11:50 +00001714 if (const auto *TT = T->getAs<TypedefType>())
Richard Smithb2f0f052016-10-10 18:54:32 +00001715 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1716 return Align;
1717
1718 // If we have an (array of) complete type, we're done.
1719 T = getBaseElementType(T);
1720 if (!T->isIncompleteType())
1721 return getTypeAlign(T);
1722
1723 // If we had an array type, its element type might be a typedef
1724 // type with an alignment attribute.
Eugene Zelenko7855e772018-04-03 00:11:50 +00001725 if (const auto *TT = T->getAs<TypedefType>())
Richard Smithb2f0f052016-10-10 18:54:32 +00001726 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1727 return Align;
1728
1729 // Otherwise, see if the declaration of the type had an attribute.
Eugene Zelenko7855e772018-04-03 00:11:50 +00001730 if (const auto *TT = T->getAs<TagType>())
Richard Smithb2f0f052016-10-10 18:54:32 +00001731 return TT->getDecl()->getMaxAlignment();
1732
1733 return 0;
1734}
1735
David Majnemer34b57492014-07-30 01:30:47 +00001736TypeInfo ASTContext::getTypeInfo(const Type *T) const {
David Majnemerf8d38642014-07-30 08:42:33 +00001737 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1738 if (I != MemoizedTypeInfo.end())
1739 return I->second;
1740
1741 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1742 TypeInfo TI = getTypeInfoImpl(T);
1743 MemoizedTypeInfo[T] = TI;
Rafael Espindolaeaa88c12014-07-30 04:40:23 +00001744 return TI;
Daniel Dunbarc6475872012-03-09 04:12:54 +00001745}
1746
1747/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1748/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001749///
1750/// FIXME: Pointers into different addr spaces could have different sizes and
1751/// alignment requirements: getPointerInfo should take an AddrSpace, this
1752/// should take a QualType, &c.
David Majnemer34b57492014-07-30 01:30:47 +00001753TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1754 uint64_t Width = 0;
1755 unsigned Align = 8;
1756 bool AlignIsRequired = false;
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001757 unsigned AS = 0;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001758 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001759#define TYPE(Class, Base)
1760#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001761#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001762#define DEPENDENT_TYPE(Class, Base) case Type::Class:
David Blaikieab277d62013-07-13 21:08:03 +00001763#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1764 case Type::Class: \
1765 assert(!T->isDependentType() && "should not see dependent types here"); \
1766 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001767#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001768 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001769
Chris Lattner355332d2007-07-13 22:27:08 +00001770 case Type::FunctionNoProto:
1771 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001772 // GCC extension: alignof(function) = 32 bits
1773 Width = 0;
1774 Align = 32;
1775 break;
1776
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001777 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001778 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001779 Width = 0;
1780 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1781 break;
1782
Steve Naroff5c131802007-08-30 01:06:46 +00001783 case Type::ConstantArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001784 const auto *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001785
David Majnemer34b57492014-07-30 01:30:47 +00001786 TypeInfo EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001787 uint64_t Size = CAT->getSize().getZExtValue();
David Majnemer34b57492014-07-30 01:30:47 +00001788 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
Daniel Dunbarc6475872012-03-09 04:12:54 +00001789 "Overflow in array type bit size evaluation");
David Majnemer34b57492014-07-30 01:30:47 +00001790 Width = EltInfo.Width * Size;
1791 Align = EltInfo.Align;
Warren Hunt5ae586a2013-11-01 23:59:41 +00001792 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1793 getTargetInfo().getPointerWidth(0) == 64)
Rui Ueyama83aa9792016-01-14 21:00:27 +00001794 Width = llvm::alignTo(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001795 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001796 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001797 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001798 case Type::Vector: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001799 const auto *VT = cast<VectorType>(T);
David Majnemer34b57492014-07-30 01:30:47 +00001800 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1801 Width = EltInfo.Width * VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001802 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001803 // If the alignment is not a power of 2, round up to the next power of 2.
1804 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001805 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001806 Align = llvm::NextPowerOf2(Align);
Rui Ueyama83aa9792016-01-14 21:00:27 +00001807 Width = llvm::alignTo(Width, Align);
Chris Lattner63d2b362009-10-22 05:17:15 +00001808 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001809 // Adjust the alignment based on the target max.
1810 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1811 if (TargetVectorAlign && TargetVectorAlign < Align)
1812 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001813 break;
1814 }
Chris Lattner647fb222007-07-18 18:26:58 +00001815
Chris Lattner7570e9c2008-03-08 08:52:55 +00001816 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001817 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001818 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001819 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001820 // GCC extension: alignof(void) = 8 bits.
1821 Width = 0;
1822 Align = 8;
1823 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001824 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001825 Width = Target->getBoolWidth();
1826 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001827 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001828 case BuiltinType::Char_S:
1829 case BuiltinType::Char_U:
1830 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001831 case BuiltinType::SChar:
Richard Smith3a8244d2018-05-01 05:02:45 +00001832 case BuiltinType::Char8:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001833 Width = Target->getCharWidth();
1834 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001835 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001836 case BuiltinType::WChar_S:
1837 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001838 Width = Target->getWCharWidth();
1839 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001840 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001841 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001842 Width = Target->getChar16Width();
1843 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001844 break;
1845 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001846 Width = Target->getChar32Width();
1847 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001848 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001849 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001850 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001851 Width = Target->getShortWidth();
1852 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001853 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001854 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001855 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001856 Width = Target->getIntWidth();
1857 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001858 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001859 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001860 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001861 Width = Target->getLongWidth();
1862 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001863 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001864 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001865 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001866 Width = Target->getLongLongWidth();
1867 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001868 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001869 case BuiltinType::Int128:
1870 case BuiltinType::UInt128:
1871 Width = 128;
1872 Align = 128; // int128_t is 128-bit aligned on all targets.
1873 break;
Leonard Chanf921d852018-06-04 16:07:52 +00001874 case BuiltinType::ShortAccum:
1875 case BuiltinType::UShortAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00001876 case BuiltinType::SatShortAccum:
1877 case BuiltinType::SatUShortAccum:
Leonard Chanf921d852018-06-04 16:07:52 +00001878 Width = Target->getShortAccumWidth();
1879 Align = Target->getShortAccumAlign();
1880 break;
1881 case BuiltinType::Accum:
1882 case BuiltinType::UAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00001883 case BuiltinType::SatAccum:
1884 case BuiltinType::SatUAccum:
Leonard Chanf921d852018-06-04 16:07:52 +00001885 Width = Target->getAccumWidth();
1886 Align = Target->getAccumAlign();
1887 break;
1888 case BuiltinType::LongAccum:
1889 case BuiltinType::ULongAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00001890 case BuiltinType::SatLongAccum:
1891 case BuiltinType::SatULongAccum:
Leonard Chanf921d852018-06-04 16:07:52 +00001892 Width = Target->getLongAccumWidth();
1893 Align = Target->getLongAccumAlign();
1894 break;
Leonard Chanab80f3c2018-06-14 14:53:51 +00001895 case BuiltinType::ShortFract:
1896 case BuiltinType::UShortFract:
1897 case BuiltinType::SatShortFract:
1898 case BuiltinType::SatUShortFract:
1899 Width = Target->getShortFractWidth();
1900 Align = Target->getShortFractAlign();
1901 break;
1902 case BuiltinType::Fract:
1903 case BuiltinType::UFract:
1904 case BuiltinType::SatFract:
1905 case BuiltinType::SatUFract:
1906 Width = Target->getFractWidth();
1907 Align = Target->getFractAlign();
1908 break;
1909 case BuiltinType::LongFract:
1910 case BuiltinType::ULongFract:
1911 case BuiltinType::SatLongFract:
1912 case BuiltinType::SatULongFract:
1913 Width = Target->getLongFractWidth();
1914 Align = Target->getLongFractAlign();
1915 break;
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00001916 case BuiltinType::Float16:
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001917 case BuiltinType::Half:
1918 Width = Target->getHalfWidth();
1919 Align = Target->getHalfAlign();
1920 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001921 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001922 Width = Target->getFloatWidth();
1923 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001924 break;
1925 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001926 Width = Target->getDoubleWidth();
1927 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001928 break;
1929 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001930 Width = Target->getLongDoubleWidth();
1931 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001932 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001933 case BuiltinType::Float128:
1934 Width = Target->getFloat128Width();
1935 Align = Target->getFloat128Align();
1936 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001937 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001938 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1939 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001940 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001941 case BuiltinType::ObjCId:
1942 case BuiltinType::ObjCClass:
1943 case BuiltinType::ObjCSel:
Fangrui Song6907ce22018-07-30 19:24:48 +00001944 Width = Target->getPointerWidth(0);
Douglas Gregore8bbc122011-09-02 00:18:52 +00001945 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001946 break;
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001947 case BuiltinType::OCLSampler:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001948 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001949 case BuiltinType::OCLClkEvent:
1950 case BuiltinType::OCLQueue:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001951 case BuiltinType::OCLReserveID:
Yaxun Liu99444cb2016-08-03 20:38:06 +00001952#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1953 case BuiltinType::Id:
1954#include "clang/Basic/OpenCLImageTypes.def"
Andrew Savonichev3fee3512018-11-08 11:25:41 +00001955#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1956 case BuiltinType::Id:
1957#include "clang/Basic/OpenCLExtensionTypes.def"
Sven van Haastregt3bb7eaf2017-12-06 10:11:28 +00001958 AS = getTargetAddressSpace(
1959 Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T)));
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001960 Width = Target->getPointerWidth(AS);
1961 Align = Target->getPointerAlign(AS);
1962 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001963 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001964 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001965 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001966 Width = Target->getPointerWidth(0);
1967 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001968 break;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00001969 case Type::BlockPointer:
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001970 AS = getTargetAddressSpace(cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001971 Width = Target->getPointerWidth(AS);
1972 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001973 break;
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001974 case Type::LValueReference:
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00001975 case Type::RValueReference:
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001976 // alignof and sizeof should never enter this code path here, so we go
1977 // the pointer route.
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001978 AS = getTargetAddressSpace(cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001979 Width = Target->getPointerWidth(AS);
1980 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001981 break;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00001982 case Type::Pointer:
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001983 AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001984 Width = Target->getPointerWidth(AS);
1985 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001986 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001987 case Type::MemberPointer: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001988 const auto *MPT = cast<MemberPointerType>(T);
Erich Keane8a6b7402017-11-30 16:37:02 +00001989 CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT);
1990 Width = MPI.Width;
1991 Align = MPI.Align;
Anders Carlsson32440a02009-05-17 02:06:04 +00001992 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001993 }
Chris Lattner647fb222007-07-18 18:26:58 +00001994 case Type::Complex: {
1995 // Complex types have the same alignment as their elements, but twice the
1996 // size.
David Majnemer34b57492014-07-30 01:30:47 +00001997 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
1998 Width = EltInfo.Width * 2;
1999 Align = EltInfo.Align;
Chris Lattner647fb222007-07-18 18:26:58 +00002000 break;
2001 }
John McCall8b07ec22010-05-15 11:32:37 +00002002 case Type::ObjCObject:
2003 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Reid Kleckner0503a872013-12-05 01:23:43 +00002004 case Type::Adjusted:
Reid Kleckner8a365022013-06-24 17:51:48 +00002005 case Type::Decayed:
Reid Kleckner0503a872013-12-05 01:23:43 +00002006 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00002007 case Type::ObjCInterface: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002008 const auto *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00002009 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00002010 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00002011 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00002012 break;
2013 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002014 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002015 case Type::Enum: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002016 const auto *TT = cast<TagType>(T);
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00002017
2018 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00002019 Width = 8;
2020 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00002021 break;
2022 }
Mike Stump11289f42009-09-09 15:08:12 +00002023
Eugene Zelenko7855e772018-04-03 00:11:50 +00002024 if (const auto *ET = dyn_cast<EnumType>(TT)) {
David Majnemer475b25e2015-01-21 10:54:38 +00002025 const EnumDecl *ED = ET->getDecl();
2026 TypeInfo Info =
2027 getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType());
2028 if (unsigned AttrAlign = ED->getMaxAlignment()) {
2029 Info.Align = AttrAlign;
2030 Info.AlignIsRequired = true;
2031 }
2032 return Info;
2033 }
Chris Lattner8b23c252008-04-06 22:05:18 +00002034
Eugene Zelenko7855e772018-04-03 00:11:50 +00002035 const auto *RT = cast<RecordType>(TT);
David Majnemer5821ff72015-02-03 08:49:29 +00002036 const RecordDecl *RD = RT->getDecl();
2037 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
Ken Dyckb0fcc592011-02-11 01:54:29 +00002038 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00002039 Align = toBits(Layout.getAlignment());
David Majnemer5821ff72015-02-03 08:49:29 +00002040 AlignIsRequired = RD->hasAttr<AlignedAttr>();
Chris Lattner49a953a2007-07-23 22:46:22 +00002041 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00002042 }
Douglas Gregordc572a32009-03-30 22:58:21 +00002043
Chris Lattner63d2b362009-10-22 05:17:15 +00002044 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00002045 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
2046 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00002047
Richard Smith600b5262017-01-26 20:40:47 +00002048 case Type::Auto:
2049 case Type::DeducedTemplateSpecialization: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002050 const auto *A = cast<DeducedType>(T);
Richard Smith27d807c2013-04-30 13:56:41 +00002051 assert(!A->getDeducedType().isNull() &&
2052 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00002053 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00002054 }
2055
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002056 case Type::Paren:
2057 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
2058
Manman Rene6be26c2016-09-13 17:25:08 +00002059 case Type::ObjCTypeParam:
2060 return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr());
2061
Douglas Gregoref462e62009-04-30 17:32:17 +00002062 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00002063 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
David Majnemer34b57492014-07-30 01:30:47 +00002064 TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00002065 // If the typedef has an aligned attribute on it, it overrides any computed
2066 // alignment we have. This violates the GCC documentation (which says that
2067 // attribute(aligned) can only round up) but matches its implementation.
David Majnemer34b57492014-07-30 01:30:47 +00002068 if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
Chris Lattner29eb47b2011-02-19 22:55:41 +00002069 Align = AttrAlign;
David Majnemer34b57492014-07-30 01:30:47 +00002070 AlignIsRequired = true;
David Majnemer37bffb62014-08-04 05:11:01 +00002071 } else {
David Majnemer34b57492014-07-30 01:30:47 +00002072 Align = Info.Align;
David Majnemer37bffb62014-08-04 05:11:01 +00002073 AlignIsRequired = Info.AlignIsRequired;
2074 }
David Majnemer34b57492014-07-30 01:30:47 +00002075 Width = Info.Width;
Douglas Gregordc572a32009-03-30 22:58:21 +00002076 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00002077 }
Douglas Gregoref462e62009-04-30 17:32:17 +00002078
Abramo Bagnara6150c882010-05-11 21:36:43 +00002079 case Type::Elaborated:
2080 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00002081
John McCall81904512011-01-06 01:58:22 +00002082 case Type::Attributed:
2083 return getTypeInfo(
2084 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
2085
Eli Friedman0dfb8892011-10-06 23:00:33 +00002086 case Type::Atomic: {
John McCalla8ec7eb2013-03-07 21:37:17 +00002087 // Start with the base type information.
David Majnemer34b57492014-07-30 01:30:47 +00002088 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
2089 Width = Info.Width;
2090 Align = Info.Align;
John McCalla8ec7eb2013-03-07 21:37:17 +00002091
JF Bastien801fca22018-05-09 03:51:12 +00002092 if (!Width) {
2093 // An otherwise zero-sized type should still generate an
2094 // atomic operation.
2095 Width = Target->getCharWidth();
2096 assert(Align);
2097 } else if (Width <= Target->getMaxAtomicPromoteWidth()) {
2098 // If the size of the type doesn't exceed the platform's max
2099 // atomic promotion width, make the size and alignment more
2100 // favorable to atomic operations:
2101
John McCalla8ec7eb2013-03-07 21:37:17 +00002102 // Round the size up to a power of 2.
2103 if (!llvm::isPowerOf2_64(Width))
2104 Width = llvm::NextPowerOf2(Width);
2105
2106 // Set the alignment equal to the size.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00002107 Align = static_cast<unsigned>(Width);
2108 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00002109 }
Xiuli Pan9c14e282016-01-09 12:53:17 +00002110 break;
2111
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002112 case Type::Pipe:
Anastasia Stulovab3398932017-06-05 11:27:03 +00002113 Width = Target->getPointerWidth(getTargetAddressSpace(LangAS::opencl_global));
2114 Align = Target->getPointerAlign(getTargetAddressSpace(LangAS::opencl_global));
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002115 break;
Douglas Gregoref462e62009-04-30 17:32:17 +00002116 }
Mike Stump11289f42009-09-09 15:08:12 +00002117
Eli Friedman4b72fdd2011-10-14 20:59:01 +00002118 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
David Majnemer34b57492014-07-30 01:30:47 +00002119 return TypeInfo(Width, Align, AlignIsRequired);
Chris Lattner983a8bb2007-07-13 22:13:22 +00002120}
2121
Momchil Velikov20208cc2018-07-30 17:48:23 +00002122unsigned ASTContext::getTypeUnadjustedAlign(const Type *T) const {
2123 UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(T);
2124 if (I != MemoizedUnadjustedAlign.end())
2125 return I->second;
2126
2127 unsigned UnadjustedAlign;
2128 if (const auto *RT = T->getAs<RecordType>()) {
2129 const RecordDecl *RD = RT->getDecl();
2130 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2131 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2132 } else if (const auto *ObjCI = T->getAs<ObjCInterfaceType>()) {
2133 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2134 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2135 } else {
2136 UnadjustedAlign = getTypeAlign(T);
2137 }
2138
2139 MemoizedUnadjustedAlign[T] = UnadjustedAlign;
2140 return UnadjustedAlign;
2141}
2142
Alexey Bataev00396512015-07-02 03:40:19 +00002143unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
2144 unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign();
2145 // Target ppc64 with QPX: simd default alignment for pointer to double is 32.
2146 if ((getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64 ||
2147 getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64le) &&
2148 getTargetInfo().getABI() == "elfv1-qpx" &&
2149 T->isSpecificBuiltinType(BuiltinType::Double))
2150 SimdAlign = 256;
2151 return SimdAlign;
2152}
2153
Ken Dyckcc56c542011-01-15 18:38:59 +00002154/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
2155CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
2156 return CharUnits::fromQuantity(BitSize / getCharWidth());
2157}
2158
Ken Dyckb0fcc592011-02-11 01:54:29 +00002159/// toBits - Convert a size in characters to a size in characters.
2160int64_t ASTContext::toBits(CharUnits CharSize) const {
2161 return CharSize.getQuantity() * getCharWidth();
2162}
2163
Ken Dyck8c89d592009-12-22 14:23:30 +00002164/// getTypeSizeInChars - Return the size of the specified type, in characters.
2165/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00002166CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00002167 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00002168}
Jay Foad39c79802011-01-12 09:06:06 +00002169CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00002170 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00002171}
2172
Fangrui Song6907ce22018-07-30 19:24:48 +00002173/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00002174/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00002175CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00002176 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00002177}
Jay Foad39c79802011-01-12 09:06:06 +00002178CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00002179 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00002180}
2181
Momchil Velikov20208cc2018-07-30 17:48:23 +00002182/// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a
2183/// type, in characters, before alignment adustments. This method does
2184/// not work on incomplete types.
2185CharUnits ASTContext::getTypeUnadjustedAlignInChars(QualType T) const {
2186 return toCharUnitsFromBits(getTypeUnadjustedAlign(T));
2187}
2188CharUnits ASTContext::getTypeUnadjustedAlignInChars(const Type *T) const {
2189 return toCharUnitsFromBits(getTypeUnadjustedAlign(T));
2190}
2191
Chris Lattnera3402cd2009-01-27 18:08:34 +00002192/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
2193/// type for the current target in bits. This can be different than the ABI
2194/// alignment in cases where it is beneficial for performance to overalign
2195/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00002196unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
David Majnemer34b57492014-07-30 01:30:47 +00002197 TypeInfo TI = getTypeInfo(T);
2198 unsigned ABIAlign = TI.Align;
Eli Friedman7ab09572009-05-25 21:27:19 +00002199
David Majnemere1544562015-04-24 01:25:05 +00002200 T = T->getBaseElementTypeUnsafe();
2201
2202 // The preferred alignment of member pointers is that of a pointer.
2203 if (T->isMemberPointerType())
2204 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
2205
Andrey Turetskiydb6655f2016-02-10 11:58:46 +00002206 if (!Target->allowsLargerPreferedTypeAlignment())
2207 return ABIAlign;
Robert Lyttoneaf6f362013-11-12 10:09:34 +00002208
Eli Friedman7ab09572009-05-25 21:27:19 +00002209 // Double and long long should be naturally aligned if possible.
Eugene Zelenko7855e772018-04-03 00:11:50 +00002210 if (const auto *CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00002211 T = CT->getElementType().getTypePtr();
Eugene Zelenko7855e772018-04-03 00:11:50 +00002212 if (const auto *ET = T->getAs<EnumType>())
David Majnemer475b25e2015-01-21 10:54:38 +00002213 T = ET->getDecl()->getIntegerType().getTypePtr();
Eli Friedman7ab09572009-05-25 21:27:19 +00002214 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00002215 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
2216 T->isSpecificBuiltinType(BuiltinType::ULongLong))
David Majnemer8b6bd572014-02-24 23:34:17 +00002217 // Don't increase the alignment if an alignment attribute was specified on a
2218 // typedef declaration.
David Majnemer34b57492014-07-30 01:30:47 +00002219 if (!TI.AlignIsRequired)
David Majnemer8b6bd572014-02-24 23:34:17 +00002220 return std::max(ABIAlign, (unsigned)getTypeSize(T));
Eli Friedman7ab09572009-05-25 21:27:19 +00002221
Chris Lattnera3402cd2009-01-27 18:08:34 +00002222 return ABIAlign;
2223}
2224
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00002225/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2226/// for __attribute__((aligned)) on this target, to be used if no alignment
2227/// value is specified.
Eugene Zelenkod4304d22015-11-04 21:37:17 +00002228unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const {
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00002229 return getTargetInfo().getDefaultAlignForAttributeAligned();
2230}
2231
Ulrich Weigandfa806422013-05-06 16:23:57 +00002232/// getAlignOfGlobalVar - Return the alignment in bits that should be given
2233/// to a global variable of the specified type.
2234unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
2235 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
2236}
2237
2238/// getAlignOfGlobalVarInChars - Return the alignment in characters that
2239/// should be given to a global variable of the specified type.
2240CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
2241 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
2242}
2243
David Majnemer08ef2ba2015-06-23 20:34:18 +00002244CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
2245 CharUnits Offset = CharUnits::Zero();
2246 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
2247 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2248 Offset += Layout->getBaseClassOffset(Base);
2249 Layout = &getASTRecordLayout(Base);
2250 }
2251 return Offset;
2252}
2253
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002254/// DeepCollectObjCIvars -
2255/// This routine first collects all declared, but not synthesized, ivars in
2256/// super class and then collects all ivars, including those synthesized for
2257/// current class. This routine is used for implementation of current class
2258/// when all ivars, declared and synthesized are known.
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002259void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
2260 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00002261 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002262 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2263 DeepCollectObjCIvars(SuperClass, false, Ivars);
2264 if (!leafClass) {
Aaron Ballman59abbd42014-03-13 21:09:43 +00002265 for (const auto *I : OI->ivars())
2266 Ivars.push_back(I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00002267 } else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002268 auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Fangrui Song6907ce22018-07-30 19:24:48 +00002269 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00002270 Iv= Iv->getNextIvar())
2271 Ivars.push_back(Iv);
2272 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00002273}
2274
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002275/// CollectInheritedProtocols - Collect all protocols in current class and
2276/// those inherited by it.
2277void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00002278 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002279 if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00002280 // We can use protocol_iterator here instead of
Fangrui Song6907ce22018-07-30 19:24:48 +00002281 // all_referenced_protocol_iterator since we are walking all categories.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002282 for (auto *Proto : OI->all_referenced_protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002283 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00002284 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002285
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002286 // Categories of this Interface.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00002287 for (const auto *Cat : OI->visible_categories())
2288 CollectInheritedProtocols(Cat, Protocols);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002289
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002290 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2291 while (SD) {
2292 CollectInheritedProtocols(SD, Protocols);
2293 SD = SD->getSuperClass();
2294 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00002295 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00002296 for (auto *Proto : OC->protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002297 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002298 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00002299 } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002300 // Insert the protocol.
2301 if (!Protocols.insert(
2302 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2303 return;
2304
2305 for (auto *Proto : OP->protocols())
2306 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002307 }
2308}
2309
Erich Keane8a6b7402017-11-30 16:37:02 +00002310static bool unionHasUniqueObjectRepresentations(const ASTContext &Context,
2311 const RecordDecl *RD) {
2312 assert(RD->isUnion() && "Must be union type");
2313 CharUnits UnionSize = Context.getTypeSizeInChars(RD->getTypeForDecl());
2314
2315 for (const auto *Field : RD->fields()) {
2316 if (!Context.hasUniqueObjectRepresentations(Field->getType()))
2317 return false;
2318 CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType());
2319 if (FieldSize != UnionSize)
2320 return false;
2321 }
Eric Fiselier12a9f342018-02-02 20:30:39 +00002322 return !RD->field_empty();
Erich Keane8a6b7402017-11-30 16:37:02 +00002323}
2324
Benjamin Kramer802e6252017-12-24 12:46:22 +00002325static bool isStructEmpty(QualType Ty) {
Erich Keane8a6b7402017-11-30 16:37:02 +00002326 const RecordDecl *RD = Ty->castAs<RecordType>()->getDecl();
2327
2328 if (!RD->field_empty())
2329 return false;
2330
2331 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD))
2332 return ClassDecl->isEmpty();
2333
2334 return true;
2335}
2336
2337static llvm::Optional<int64_t>
2338structHasUniqueObjectRepresentations(const ASTContext &Context,
2339 const RecordDecl *RD) {
2340 assert(!RD->isUnion() && "Must be struct/class type");
2341 const auto &Layout = Context.getASTRecordLayout(RD);
2342
2343 int64_t CurOffsetInBits = 0;
2344 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) {
2345 if (ClassDecl->isDynamicClass())
2346 return llvm::None;
2347
2348 SmallVector<std::pair<QualType, int64_t>, 4> Bases;
2349 for (const auto Base : ClassDecl->bases()) {
2350 // Empty types can be inherited from, and non-empty types can potentially
2351 // have tail padding, so just make sure there isn't an error.
2352 if (!isStructEmpty(Base.getType())) {
2353 llvm::Optional<int64_t> Size = structHasUniqueObjectRepresentations(
2354 Context, Base.getType()->getAs<RecordType>()->getDecl());
2355 if (!Size)
2356 return llvm::None;
2357 Bases.emplace_back(Base.getType(), Size.getValue());
2358 }
2359 }
2360
Fangrui Song1d38c132018-09-30 21:41:11 +00002361 llvm::sort(Bases, [&](const std::pair<QualType, int64_t> &L,
2362 const std::pair<QualType, int64_t> &R) {
2363 return Layout.getBaseClassOffset(L.first->getAsCXXRecordDecl()) <
2364 Layout.getBaseClassOffset(R.first->getAsCXXRecordDecl());
2365 });
Erich Keane8a6b7402017-11-30 16:37:02 +00002366
2367 for (const auto Base : Bases) {
2368 int64_t BaseOffset = Context.toBits(
2369 Layout.getBaseClassOffset(Base.first->getAsCXXRecordDecl()));
2370 int64_t BaseSize = Base.second;
2371 if (BaseOffset != CurOffsetInBits)
2372 return llvm::None;
2373 CurOffsetInBits = BaseOffset + BaseSize;
2374 }
2375 }
2376
2377 for (const auto *Field : RD->fields()) {
2378 if (!Field->getType()->isReferenceType() &&
2379 !Context.hasUniqueObjectRepresentations(Field->getType()))
2380 return llvm::None;
2381
2382 int64_t FieldSizeInBits =
2383 Context.toBits(Context.getTypeSizeInChars(Field->getType()));
2384 if (Field->isBitField()) {
2385 int64_t BitfieldSize = Field->getBitWidthValue(Context);
2386
2387 if (BitfieldSize > FieldSizeInBits)
2388 return llvm::None;
2389 FieldSizeInBits = BitfieldSize;
2390 }
2391
2392 int64_t FieldOffsetInBits = Context.getFieldOffset(Field);
2393
2394 if (FieldOffsetInBits != CurOffsetInBits)
2395 return llvm::None;
2396
2397 CurOffsetInBits = FieldSizeInBits + FieldOffsetInBits;
2398 }
2399
2400 return CurOffsetInBits;
2401}
2402
2403bool ASTContext::hasUniqueObjectRepresentations(QualType Ty) const {
2404 // C++17 [meta.unary.prop]:
2405 // The predicate condition for a template specialization
2406 // has_unique_object_representations<T> shall be
2407 // satisfied if and only if:
2408 // (9.1) - T is trivially copyable, and
2409 // (9.2) - any two objects of type T with the same value have the same
2410 // object representation, where two objects
2411 // of array or non-union class type are considered to have the same value
2412 // if their respective sequences of
2413 // direct subobjects have the same values, and two objects of union type
2414 // are considered to have the same
2415 // value if they have the same active member and the corresponding members
2416 // have the same value.
2417 // The set of scalar types for which this condition holds is
2418 // implementation-defined. [ Note: If a type has padding
2419 // bits, the condition does not hold; otherwise, the condition holds true
2420 // for unsigned integral types. -- end note ]
2421 assert(!Ty.isNull() && "Null QualType sent to unique object rep check");
2422
2423 // Arrays are unique only if their element type is unique.
2424 if (Ty->isArrayType())
2425 return hasUniqueObjectRepresentations(getBaseElementType(Ty));
2426
2427 // (9.1) - T is trivially copyable...
2428 if (!Ty.isTriviallyCopyableType(*this))
2429 return false;
2430
2431 // All integrals and enums are unique.
2432 if (Ty->isIntegralOrEnumerationType())
2433 return true;
2434
2435 // All other pointers are unique.
2436 if (Ty->isPointerType())
2437 return true;
2438
2439 if (Ty->isMemberPointerType()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002440 const auto *MPT = Ty->getAs<MemberPointerType>();
Erich Keane8a6b7402017-11-30 16:37:02 +00002441 return !ABI->getMemberPointerInfo(MPT).HasPadding;
2442 }
2443
2444 if (Ty->isRecordType()) {
2445 const RecordDecl *Record = Ty->getAs<RecordType>()->getDecl();
2446
Erich Keanebd2197c2017-12-12 16:02:06 +00002447 if (Record->isInvalidDecl())
2448 return false;
2449
Erich Keane8a6b7402017-11-30 16:37:02 +00002450 if (Record->isUnion())
2451 return unionHasUniqueObjectRepresentations(*this, Record);
2452
2453 Optional<int64_t> StructSize =
2454 structHasUniqueObjectRepresentations(*this, Record);
2455
2456 return StructSize &&
2457 StructSize.getValue() == static_cast<int64_t>(getTypeSize(Ty));
2458 }
2459
2460 // FIXME: More cases to handle here (list by rsmith):
2461 // vectors (careful about, eg, vector of 3 foo)
2462 // _Complex int and friends
2463 // _Atomic T
2464 // Obj-C block pointers
2465 // Obj-C object pointers
2466 // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t,
2467 // clk_event_t, queue_t, reserve_id_t)
2468 // There're also Obj-C class types and the Obj-C selector type, but I think it
2469 // makes sense for those to return false here.
2470
2471 return false;
2472}
2473
Jay Foad39c79802011-01-12 09:06:06 +00002474unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00002475 unsigned count = 0;
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00002476 // Count ivars declared in class extension.
Aaron Ballmanb4a53452014-03-13 21:57:01 +00002477 for (const auto *Ext : OI->known_extensions())
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002478 count += Ext->ivar_size();
Fangrui Song6907ce22018-07-30 19:24:48 +00002479
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00002480 // Count ivar defined in this class's implementation. This
2481 // includes synthesized ivars.
2482 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00002483 count += ImplDecl->ivar_size();
2484
Fariborz Jahanian7c809592009-06-04 01:19:09 +00002485 return count;
2486}
2487
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00002488bool ASTContext::isSentinelNullExpr(const Expr *E) {
2489 if (!E)
2490 return false;
2491
2492 // nullptr_t is always treated as null.
2493 if (E->getType()->isNullPtrType()) return true;
2494
2495 if (E->getType()->isAnyPointerType() &&
2496 E->IgnoreParenCasts()->isNullPointerConstant(*this,
2497 Expr::NPC_ValueDependentIsNull))
2498 return true;
2499
2500 // Unfortunately, __null has type 'int'.
2501 if (isa<GNUNullExpr>(E)) return true;
2502
2503 return false;
2504}
2505
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002506/// Get the implementation of ObjCInterfaceDecl, or nullptr if none
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002507/// exists.
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002508ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
2509 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2510 I = ObjCImpls.find(D);
2511 if (I != ObjCImpls.end())
2512 return cast<ObjCImplementationDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002513 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002514}
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002515
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002516/// Get the implementation of ObjCCategoryDecl, or nullptr if none
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002517/// exists.
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002518ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
2519 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2520 I = ObjCImpls.find(D);
2521 if (I != ObjCImpls.end())
2522 return cast<ObjCCategoryImplDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002523 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002524}
2525
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002526/// Set the implementation of ObjCInterfaceDecl.
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002527void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2528 ObjCImplementationDecl *ImplD) {
2529 assert(IFaceD && ImplD && "Passed null params");
2530 ObjCImpls[IFaceD] = ImplD;
2531}
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002532
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002533/// Set the implementation of ObjCCategoryDecl.
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002534void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
2535 ObjCCategoryImplDecl *ImplD) {
2536 assert(CatD && ImplD && "Passed null params");
2537 ObjCImpls[CatD] = ImplD;
2538}
2539
Chandler Carruth21c90602015-12-30 03:24:14 +00002540const ObjCMethodDecl *
2541ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const {
2542 return ObjCMethodRedecls.lookup(MD);
2543}
2544
2545void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
2546 const ObjCMethodDecl *Redecl) {
2547 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
2548 ObjCMethodRedecls[MD] = Redecl;
2549}
2550
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002551const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
2552 const NamedDecl *ND) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002553 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002554 return ID;
Eugene Zelenko7855e772018-04-03 00:11:50 +00002555 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002556 return CD->getClassInterface();
Eugene Zelenko7855e772018-04-03 00:11:50 +00002557 if (const auto *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002558 return IMD->getClassInterface();
2559
Craig Topper36250ad2014-05-12 05:36:57 +00002560 return nullptr;
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002561}
2562
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002563/// Get the copy initialization expression of VarDecl, or nullptr if
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002564/// none exists.
Akira Hatanaka9978da32018-08-10 15:09:24 +00002565ASTContext::BlockVarCopyInit
2566ASTContext::getBlockVarCopyInit(const VarDecl*VD) const {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002567 assert(VD && "Passed null params");
Fangrui Song6907ce22018-07-30 19:24:48 +00002568 assert(VD->hasAttr<BlocksAttr>() &&
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002569 "getBlockVarCopyInits - not __block var");
Akira Hatanaka9978da32018-08-10 15:09:24 +00002570 auto I = BlockVarCopyInits.find(VD);
2571 if (I != BlockVarCopyInits.end())
2572 return I->second;
2573 return {nullptr, false};
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002574}
2575
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002576/// Set the copy inialization expression of a block var decl.
Akira Hatanaka9978da32018-08-10 15:09:24 +00002577void ASTContext::setBlockVarCopyInit(const VarDecl*VD, Expr *CopyExpr,
2578 bool CanThrow) {
2579 assert(VD && CopyExpr && "Passed null params");
Fangrui Song6907ce22018-07-30 19:24:48 +00002580 assert(VD->hasAttr<BlocksAttr>() &&
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002581 "setBlockVarCopyInits - not __block var");
Akira Hatanaka9978da32018-08-10 15:09:24 +00002582 BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002583}
2584
John McCallbcd03502009-12-07 02:54:59 +00002585TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002586 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00002587 if (!DataSize)
2588 DataSize = TypeLoc::getFullDataSizeForType(T);
2589 else
2590 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00002591 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00002592
Eugene Zelenko7855e772018-04-03 00:11:50 +00002593 auto *TInfo =
John McCallbcd03502009-12-07 02:54:59 +00002594 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
2595 new (TInfo) TypeSourceInfo(T);
2596 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00002597}
2598
John McCallbcd03502009-12-07 02:54:59 +00002599TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002600 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00002601 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00002602 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00002603 return DI;
2604}
2605
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002606const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002607ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Craig Topper36250ad2014-05-12 05:36:57 +00002608 return getObjCLayout(D, nullptr);
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002609}
2610
2611const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002612ASTContext::getASTObjCImplementationLayout(
2613 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002614 return getObjCLayout(D->getClassInterface(), D);
2615}
2616
Chris Lattner983a8bb2007-07-13 22:13:22 +00002617//===----------------------------------------------------------------------===//
2618// Type creation/memoization methods
2619//===----------------------------------------------------------------------===//
2620
Jay Foad39c79802011-01-12 09:06:06 +00002621QualType
John McCall33ddac02011-01-19 10:06:00 +00002622ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2623 unsigned fastQuals = quals.getFastQualifiers();
2624 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00002625
2626 // Check if we've already instantiated this type.
2627 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002628 ExtQuals::Profile(ID, baseType, quals);
Craig Topper36250ad2014-05-12 05:36:57 +00002629 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002630 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2631 assert(eq->getQualifiers() == quals);
2632 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002633 }
2634
John McCall33ddac02011-01-19 10:06:00 +00002635 // If the base type is not canonical, make the appropriate canonical type.
2636 QualType canon;
2637 if (!baseType->isCanonicalUnqualified()) {
2638 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00002639 canonSplit.Quals.addConsistentQualifiers(quals);
2640 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002641
2642 // Re-find the insert position.
2643 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2644 }
2645
Eugene Zelenko7855e772018-04-03 00:11:50 +00002646 auto *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
John McCall33ddac02011-01-19 10:06:00 +00002647 ExtQualNodes.InsertNode(eq, insertPos);
2648 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002649}
2650
Alexander Richardson6d989432017-10-15 18:48:14 +00002651QualType ASTContext::getAddrSpaceQualType(QualType T,
2652 LangAS AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002653 QualType CanT = getCanonicalType(T);
2654 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00002655 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00002656
John McCall8ccfcb52009-09-24 19:53:00 +00002657 // If we are composing extended qualifiers together, merge together
2658 // into one ExtQuals node.
2659 QualifierCollector Quals;
2660 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002661
John McCall8ccfcb52009-09-24 19:53:00 +00002662 // If this type already has an address space specified, it cannot get
2663 // another one.
2664 assert(!Quals.hasAddressSpace() &&
2665 "Type cannot be in multiple addr spaces!");
2666 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00002667
John McCall8ccfcb52009-09-24 19:53:00 +00002668 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00002669}
2670
Andrew Gozillon572bbb02017-10-02 06:25:51 +00002671QualType ASTContext::removeAddrSpaceQualType(QualType T) const {
2672 // If we are composing extended qualifiers together, merge together
2673 // into one ExtQuals node.
2674 QualifierCollector Quals;
2675 const Type *TypeNode = Quals.strip(T);
2676
2677 // If the qualifier doesn't have an address space just return it.
2678 if (!Quals.hasAddressSpace())
2679 return T;
2680
2681 Quals.removeAddressSpace();
2682
2683 // Removal of the address space can mean there are no longer any
2684 // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts)
2685 // or required.
2686 if (Quals.hasNonFastQualifiers())
2687 return getExtQualType(TypeNode, Quals);
2688 else
2689 return QualType(TypeNode, Quals.getFastQualifiers());
2690}
2691
Chris Lattnerd60183d2009-02-18 22:53:11 +00002692QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002693 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002694 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00002695 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002696 return T;
Mike Stump11289f42009-09-09 15:08:12 +00002697
Eugene Zelenko7855e772018-04-03 00:11:50 +00002698 if (const auto *ptr = T->getAs<PointerType>()) {
John McCall53fa7142010-12-24 02:08:15 +00002699 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00002700 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00002701 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2702 return getPointerType(ResultType);
2703 }
2704 }
Mike Stump11289f42009-09-09 15:08:12 +00002705
John McCall8ccfcb52009-09-24 19:53:00 +00002706 // If we are composing extended qualifiers together, merge together
2707 // into one ExtQuals node.
2708 QualifierCollector Quals;
2709 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002710
John McCall8ccfcb52009-09-24 19:53:00 +00002711 // If this type already has an ObjCGC specified, it cannot get
2712 // another one.
2713 assert(!Quals.hasObjCGCAttr() &&
2714 "Type cannot have multiple ObjCGCs!");
2715 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00002716
John McCall8ccfcb52009-09-24 19:53:00 +00002717 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002718}
Chris Lattner983a8bb2007-07-13 22:13:22 +00002719
John McCall4f5019e2010-12-19 02:44:49 +00002720const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2721 FunctionType::ExtInfo Info) {
2722 if (T->getExtInfo() == Info)
2723 return T;
2724
2725 QualType Result;
Eugene Zelenko7855e772018-04-03 00:11:50 +00002726 if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
Alp Toker314cc812014-01-25 16:55:45 +00002727 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
John McCall4f5019e2010-12-19 02:44:49 +00002728 } else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002729 const auto *FPT = cast<FunctionProtoType>(T);
John McCall4f5019e2010-12-19 02:44:49 +00002730 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2731 EPI.ExtInfo = Info;
Alp Toker314cc812014-01-25 16:55:45 +00002732 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
John McCall4f5019e2010-12-19 02:44:49 +00002733 }
2734
2735 return cast<FunctionType>(Result.getTypePtr());
2736}
2737
Richard Smith2a7d4812013-05-04 07:00:32 +00002738void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2739 QualType ResultType) {
Richard Smith1fa5d642013-05-11 05:45:24 +00002740 FD = FD->getMostRecentDecl();
2741 while (true) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002742 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
Richard Smith2a7d4812013-05-04 07:00:32 +00002743 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Alp Toker9cacbab2014-01-20 20:26:09 +00002744 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
Richard Smith1fa5d642013-05-11 05:45:24 +00002745 if (FunctionDecl *Next = FD->getPreviousDecl())
2746 FD = Next;
2747 else
2748 break;
Richard Smith2a7d4812013-05-04 07:00:32 +00002749 }
Richard Smith1fa5d642013-05-11 05:45:24 +00002750 if (ASTMutationListener *L = getASTMutationListener())
2751 L->DeducedReturnType(FD, ResultType);
Richard Smith2a7d4812013-05-04 07:00:32 +00002752}
2753
Richard Smith0b3a4622014-11-13 20:01:57 +00002754/// Get a function type and produce the equivalent function type with the
2755/// specified exception specification. Type sugar that can be present on a
2756/// declaration of a function with an exception specification is permitted
2757/// and preserved. Other type sugar (for instance, typedefs) is not.
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002758QualType ASTContext::getFunctionTypeWithExceptionSpec(
2759 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) {
Richard Smith0b3a4622014-11-13 20:01:57 +00002760 // Might have some parens.
Eugene Zelenko7855e772018-04-03 00:11:50 +00002761 if (const auto *PT = dyn_cast<ParenType>(Orig))
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002762 return getParenType(
2763 getFunctionTypeWithExceptionSpec(PT->getInnerType(), ESI));
Richard Smith0b3a4622014-11-13 20:01:57 +00002764
2765 // Might have a calling-convention attribute.
Eugene Zelenko7855e772018-04-03 00:11:50 +00002766 if (const auto *AT = dyn_cast<AttributedType>(Orig))
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002767 return getAttributedType(
Richard Smith0b3a4622014-11-13 20:01:57 +00002768 AT->getAttrKind(),
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002769 getFunctionTypeWithExceptionSpec(AT->getModifiedType(), ESI),
2770 getFunctionTypeWithExceptionSpec(AT->getEquivalentType(), ESI));
Richard Smith0b3a4622014-11-13 20:01:57 +00002771
2772 // Anything else must be a function type. Rebuild it with the new exception
2773 // specification.
Eugene Zelenko7855e772018-04-03 00:11:50 +00002774 const auto *Proto = cast<FunctionProtoType>(Orig);
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002775 return getFunctionType(
Richard Smith0b3a4622014-11-13 20:01:57 +00002776 Proto->getReturnType(), Proto->getParamTypes(),
2777 Proto->getExtProtoInfo().withExceptionSpec(ESI));
2778}
2779
Richard Smithdfe85e22016-12-15 02:35:39 +00002780bool ASTContext::hasSameFunctionTypeIgnoringExceptionSpec(QualType T,
2781 QualType U) {
2782 return hasSameType(T, U) ||
Aaron Ballmanc351fba2017-12-04 20:27:34 +00002783 (getLangOpts().CPlusPlus17 &&
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002784 hasSameType(getFunctionTypeWithExceptionSpec(T, EST_None),
2785 getFunctionTypeWithExceptionSpec(U, EST_None)));
Richard Smithdfe85e22016-12-15 02:35:39 +00002786}
2787
Richard Smith0b3a4622014-11-13 20:01:57 +00002788void ASTContext::adjustExceptionSpec(
2789 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
2790 bool AsWritten) {
2791 // Update the type.
2792 QualType Updated =
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002793 getFunctionTypeWithExceptionSpec(FD->getType(), ESI);
Richard Smith0b3a4622014-11-13 20:01:57 +00002794 FD->setType(Updated);
2795
2796 if (!AsWritten)
2797 return;
2798
2799 // Update the type in the type source information too.
2800 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
2801 // If the type and the type-as-written differ, we may need to update
2802 // the type-as-written too.
2803 if (TSInfo->getType() != FD->getType())
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002804 Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI);
Richard Smith0b3a4622014-11-13 20:01:57 +00002805
2806 // FIXME: When we get proper type location information for exceptions,
2807 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
2808 // up the TypeSourceInfo;
2809 assert(TypeLoc::getFullDataSizeForType(Updated) ==
2810 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
2811 "TypeLoc size mismatch from updating exception specification");
2812 TSInfo->overrideType(Updated);
2813 }
2814}
2815
Chris Lattnerc6395932007-06-22 20:56:16 +00002816/// getComplexType - Return the uniqued reference to the type for a complex
2817/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00002818QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00002819 // Unique pointers, to guarantee there is only one pointer of a particular
2820 // structure.
2821 llvm::FoldingSetNodeID ID;
2822 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002823
Craig Topper36250ad2014-05-12 05:36:57 +00002824 void *InsertPos = nullptr;
Chris Lattnerc6395932007-06-22 20:56:16 +00002825 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2826 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002827
Chris Lattnerc6395932007-06-22 20:56:16 +00002828 // If the pointee type isn't canonical, this won't be a canonical type either,
2829 // so fill in the canonical type field.
2830 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002831 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002832 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002833
Chris Lattnerc6395932007-06-22 20:56:16 +00002834 // Get the new insert position for the node we care about.
2835 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002836 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00002837 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00002838 auto *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00002839 Types.push_back(New);
2840 ComplexTypes.InsertNode(New, InsertPos);
2841 return QualType(New, 0);
2842}
2843
Chris Lattner970e54e2006-11-12 00:37:36 +00002844/// getPointerType - Return the uniqued reference to the type for a pointer to
2845/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002846QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00002847 // Unique pointers, to guarantee there is only one pointer of a particular
2848 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002849 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00002850 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002851
Craig Topper36250ad2014-05-12 05:36:57 +00002852 void *InsertPos = nullptr;
Chris Lattner67521df2007-01-27 01:29:36 +00002853 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002854 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002855
Chris Lattner7ccecb92006-11-12 08:50:50 +00002856 // If the pointee type isn't canonical, this won't be a canonical type either,
2857 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002858 QualType Canonical;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002859 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002860 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002861
Bob Wilsonc8541f22013-03-15 17:12:43 +00002862 // Get the new insert position for the node we care about.
2863 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002864 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002865 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00002866 auto *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00002867 Types.push_back(New);
2868 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002869 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00002870}
2871
Reid Kleckner0503a872013-12-05 01:23:43 +00002872QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
2873 llvm::FoldingSetNodeID ID;
2874 AdjustedType::Profile(ID, Orig, New);
Craig Topper36250ad2014-05-12 05:36:57 +00002875 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002876 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2877 if (AT)
2878 return QualType(AT, 0);
2879
2880 QualType Canonical = getCanonicalType(New);
2881
2882 // Get the new insert position for the node we care about.
2883 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002884 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner0503a872013-12-05 01:23:43 +00002885
2886 AT = new (*this, TypeAlignment)
2887 AdjustedType(Type::Adjusted, Orig, New, Canonical);
2888 Types.push_back(AT);
2889 AdjustedTypes.InsertNode(AT, InsertPos);
2890 return QualType(AT, 0);
2891}
2892
Reid Kleckner8a365022013-06-24 17:51:48 +00002893QualType ASTContext::getDecayedType(QualType T) const {
2894 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2895
Reid Kleckner8a365022013-06-24 17:51:48 +00002896 QualType Decayed;
2897
2898 // C99 6.7.5.3p7:
2899 // A declaration of a parameter as "array of type" shall be
2900 // adjusted to "qualified pointer to type", where the type
2901 // qualifiers (if any) are those specified within the [ and ] of
2902 // the array type derivation.
2903 if (T->isArrayType())
2904 Decayed = getArrayDecayedType(T);
2905
2906 // C99 6.7.5.3p8:
2907 // A declaration of a parameter as "function returning type"
2908 // shall be adjusted to "pointer to function returning type", as
2909 // in 6.3.2.1.
2910 if (T->isFunctionType())
2911 Decayed = getPointerType(T);
2912
Reid Kleckner0503a872013-12-05 01:23:43 +00002913 llvm::FoldingSetNodeID ID;
2914 AdjustedType::Profile(ID, T, Decayed);
Craig Topper36250ad2014-05-12 05:36:57 +00002915 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002916 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2917 if (AT)
2918 return QualType(AT, 0);
2919
Reid Kleckner8a365022013-06-24 17:51:48 +00002920 QualType Canonical = getCanonicalType(Decayed);
2921
2922 // Get the new insert position for the node we care about.
Reid Kleckner0503a872013-12-05 01:23:43 +00002923 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002924 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner8a365022013-06-24 17:51:48 +00002925
Reid Kleckner0503a872013-12-05 01:23:43 +00002926 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2927 Types.push_back(AT);
2928 AdjustedTypes.InsertNode(AT, InsertPos);
2929 return QualType(AT, 0);
Reid Kleckner8a365022013-06-24 17:51:48 +00002930}
2931
Mike Stump11289f42009-09-09 15:08:12 +00002932/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00002933/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00002934QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00002935 assert(T->isFunctionType() && "block of function types only");
2936 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00002937 // structure.
2938 llvm::FoldingSetNodeID ID;
2939 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002940
Craig Topper36250ad2014-05-12 05:36:57 +00002941 void *InsertPos = nullptr;
Steve Naroffec33ed92008-08-27 16:04:49 +00002942 if (BlockPointerType *PT =
2943 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2944 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002945
2946 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00002947 // type either so fill in the canonical type field.
2948 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002949 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00002950 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002951
Steve Naroffec33ed92008-08-27 16:04:49 +00002952 // Get the new insert position for the node we care about.
2953 BlockPointerType *NewIP =
2954 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002955 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00002956 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00002957 auto *New = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00002958 Types.push_back(New);
2959 BlockPointerTypes.InsertNode(New, InsertPos);
2960 return QualType(New, 0);
2961}
2962
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002963/// getLValueReferenceType - Return the uniqued reference to the type for an
2964/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002965QualType
2966ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00002967 assert(getCanonicalType(T) != OverloadTy &&
Douglas Gregor291e8ee2011-05-21 22:16:50 +00002968 "Unresolved overloaded function type");
Fangrui Song6907ce22018-07-30 19:24:48 +00002969
Bill Wendling3708c182007-05-27 10:15:43 +00002970 // Unique pointers, to guarantee there is only one pointer of a particular
2971 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002972 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002973 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002974
Craig Topper36250ad2014-05-12 05:36:57 +00002975 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002976 if (LValueReferenceType *RT =
2977 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00002978 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002979
Eugene Zelenko7855e772018-04-03 00:11:50 +00002980 const auto *InnerRef = T->getAs<ReferenceType>();
John McCallfc93cf92009-10-22 22:37:11 +00002981
Bill Wendling3708c182007-05-27 10:15:43 +00002982 // If the referencee type isn't canonical, this won't be a canonical type
2983 // either, so fill in the canonical type field.
2984 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002985 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2986 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2987 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002988
Bill Wendling3708c182007-05-27 10:15:43 +00002989 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002990 LValueReferenceType *NewIP =
2991 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002992 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00002993 }
2994
Eugene Zelenko7855e772018-04-03 00:11:50 +00002995 auto *New = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2996 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002997 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002998 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00002999
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003000 return QualType(New, 0);
3001}
3002
3003/// getRValueReferenceType - Return the uniqued reference to the type for an
3004/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00003005QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003006 // Unique pointers, to guarantee there is only one pointer of a particular
3007 // structure.
3008 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00003009 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003010
Craig Topper36250ad2014-05-12 05:36:57 +00003011 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003012 if (RValueReferenceType *RT =
3013 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
3014 return QualType(RT, 0);
3015
Eugene Zelenko7855e772018-04-03 00:11:50 +00003016 const auto *InnerRef = T->getAs<ReferenceType>();
John McCallfc93cf92009-10-22 22:37:11 +00003017
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003018 // If the referencee type isn't canonical, this won't be a canonical type
3019 // either, so fill in the canonical type field.
3020 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00003021 if (InnerRef || !T.isCanonical()) {
3022 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
3023 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003024
3025 // Get the new insert position for the node we care about.
3026 RValueReferenceType *NewIP =
3027 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003028 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003029 }
3030
Eugene Zelenko7855e772018-04-03 00:11:50 +00003031 auto *New = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003032 Types.push_back(New);
3033 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00003034 return QualType(New, 0);
3035}
3036
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00003037/// getMemberPointerType - Return the uniqued reference to the type for a
3038/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00003039QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00003040 // Unique pointers, to guarantee there is only one pointer of a particular
3041 // structure.
3042 llvm::FoldingSetNodeID ID;
3043 MemberPointerType::Profile(ID, T, Cls);
3044
Craig Topper36250ad2014-05-12 05:36:57 +00003045 void *InsertPos = nullptr;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00003046 if (MemberPointerType *PT =
3047 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3048 return QualType(PT, 0);
3049
3050 // If the pointee or class type isn't canonical, this won't be a canonical
3051 // type either, so fill in the canonical type field.
3052 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00003053 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00003054 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
3055
3056 // Get the new insert position for the node we care about.
3057 MemberPointerType *NewIP =
3058 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003059 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00003060 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00003061 auto *New = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00003062 Types.push_back(New);
3063 MemberPointerTypes.InsertNode(New, InsertPos);
3064 return QualType(New, 0);
3065}
3066
Mike Stump11289f42009-09-09 15:08:12 +00003067/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00003068/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00003069QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00003070 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00003071 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00003072 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00003073 assert((EltTy->isDependentType() ||
3074 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00003075 "Constant array of VLAs is illegal!");
3076
Chris Lattnere2df3f92009-05-13 04:12:56 +00003077 // Convert the array size into a canonical width matching the pointer size for
3078 // the target.
3079 llvm::APInt ArySize(ArySizeIn);
Konstantin Zhuravlyov9c1e3102017-03-21 18:55:39 +00003080 ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth());
Mike Stump11289f42009-09-09 15:08:12 +00003081
Chris Lattner23b7eb62007-06-15 23:05:46 +00003082 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00003083 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00003084
Craig Topper36250ad2014-05-12 05:36:57 +00003085 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003086 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00003087 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003088 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003089
John McCall33ddac02011-01-19 10:06:00 +00003090 // If the element type isn't canonical or has qualifiers, this won't
3091 // be a canonical type either, so fill in the canonical type field.
3092 QualType Canon;
3093 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
3094 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00003095 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00003096 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00003097 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00003098
Chris Lattner36f8e652007-01-27 08:31:04 +00003099 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00003100 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00003101 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003102 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00003103 }
Mike Stump11289f42009-09-09 15:08:12 +00003104
Eugene Zelenko7855e772018-04-03 00:11:50 +00003105 auto *New = new (*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00003106 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00003107 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00003108 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003109 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00003110}
3111
John McCall06549462011-01-18 08:40:38 +00003112/// getVariableArrayDecayedType - Turns the given type, which may be
3113/// variably-modified, into the corresponding type with all the known
3114/// sizes replaced with [*].
3115QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
3116 // Vastly most common case.
3117 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003118
John McCall06549462011-01-18 08:40:38 +00003119 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003120
John McCall06549462011-01-18 08:40:38 +00003121 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00003122 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00003123 switch (ty->getTypeClass()) {
3124#define TYPE(Class, Base)
3125#define ABSTRACT_TYPE(Class, Base)
3126#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3127#include "clang/AST/TypeNodes.def"
3128 llvm_unreachable("didn't desugar past all non-canonical types?");
3129
3130 // These types should never be variably-modified.
3131 case Type::Builtin:
3132 case Type::Complex:
3133 case Type::Vector:
Erich Keanef702b022018-07-13 19:46:04 +00003134 case Type::DependentVector:
John McCall06549462011-01-18 08:40:38 +00003135 case Type::ExtVector:
3136 case Type::DependentSizedExtVector:
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003137 case Type::DependentAddressSpace:
John McCall06549462011-01-18 08:40:38 +00003138 case Type::ObjCObject:
3139 case Type::ObjCInterface:
3140 case Type::ObjCObjectPointer:
3141 case Type::Record:
3142 case Type::Enum:
3143 case Type::UnresolvedUsing:
3144 case Type::TypeOfExpr:
3145 case Type::TypeOf:
3146 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00003147 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00003148 case Type::DependentName:
3149 case Type::InjectedClassName:
3150 case Type::TemplateSpecialization:
3151 case Type::DependentTemplateSpecialization:
3152 case Type::TemplateTypeParm:
3153 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00003154 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00003155 case Type::DeducedTemplateSpecialization:
John McCall06549462011-01-18 08:40:38 +00003156 case Type::PackExpansion:
3157 llvm_unreachable("type should never be variably-modified");
3158
3159 // These types can be variably-modified but should never need to
3160 // further decay.
3161 case Type::FunctionNoProto:
3162 case Type::FunctionProto:
3163 case Type::BlockPointer:
3164 case Type::MemberPointer:
Xiuli Pan9c14e282016-01-09 12:53:17 +00003165 case Type::Pipe:
John McCall06549462011-01-18 08:40:38 +00003166 return type;
3167
3168 // These types can be variably-modified. All these modifications
3169 // preserve structure except as noted by comments.
3170 // TODO: if we ever care about optimizing VLAs, there are no-op
3171 // optimizations available here.
3172 case Type::Pointer:
3173 result = getPointerType(getVariableArrayDecayedType(
3174 cast<PointerType>(ty)->getPointeeType()));
3175 break;
3176
3177 case Type::LValueReference: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003178 const auto *lv = cast<LValueReferenceType>(ty);
John McCall06549462011-01-18 08:40:38 +00003179 result = getLValueReferenceType(
3180 getVariableArrayDecayedType(lv->getPointeeType()),
3181 lv->isSpelledAsLValue());
3182 break;
3183 }
3184
3185 case Type::RValueReference: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003186 const auto *lv = cast<RValueReferenceType>(ty);
John McCall06549462011-01-18 08:40:38 +00003187 result = getRValueReferenceType(
3188 getVariableArrayDecayedType(lv->getPointeeType()));
3189 break;
3190 }
3191
Eli Friedman0dfb8892011-10-06 23:00:33 +00003192 case Type::Atomic: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003193 const auto *at = cast<AtomicType>(ty);
Eli Friedman0dfb8892011-10-06 23:00:33 +00003194 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
3195 break;
3196 }
3197
John McCall06549462011-01-18 08:40:38 +00003198 case Type::ConstantArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003199 const auto *cat = cast<ConstantArrayType>(ty);
John McCall06549462011-01-18 08:40:38 +00003200 result = getConstantArrayType(
3201 getVariableArrayDecayedType(cat->getElementType()),
3202 cat->getSize(),
3203 cat->getSizeModifier(),
3204 cat->getIndexTypeCVRQualifiers());
3205 break;
3206 }
3207
3208 case Type::DependentSizedArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003209 const auto *dat = cast<DependentSizedArrayType>(ty);
John McCall06549462011-01-18 08:40:38 +00003210 result = getDependentSizedArrayType(
3211 getVariableArrayDecayedType(dat->getElementType()),
3212 dat->getSizeExpr(),
3213 dat->getSizeModifier(),
3214 dat->getIndexTypeCVRQualifiers(),
3215 dat->getBracketsRange());
3216 break;
3217 }
3218
3219 // Turn incomplete types into [*] types.
3220 case Type::IncompleteArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003221 const auto *iat = cast<IncompleteArrayType>(ty);
John McCall06549462011-01-18 08:40:38 +00003222 result = getVariableArrayType(
3223 getVariableArrayDecayedType(iat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00003224 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00003225 ArrayType::Normal,
3226 iat->getIndexTypeCVRQualifiers(),
3227 SourceRange());
3228 break;
3229 }
3230
3231 // Turn VLA types into [*] types.
3232 case Type::VariableArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003233 const auto *vat = cast<VariableArrayType>(ty);
John McCall06549462011-01-18 08:40:38 +00003234 result = getVariableArrayType(
3235 getVariableArrayDecayedType(vat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00003236 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00003237 ArrayType::Star,
3238 vat->getIndexTypeCVRQualifiers(),
3239 vat->getBracketsRange());
3240 break;
3241 }
3242 }
3243
3244 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00003245 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00003246}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003247
Steve Naroffcadebd02007-08-30 18:14:25 +00003248/// getVariableArrayType - Returns a non-unique reference to the type for a
3249/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00003250QualType ASTContext::getVariableArrayType(QualType EltTy,
3251 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00003252 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00003253 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00003254 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00003255 // Since we don't unique expressions, it isn't possible to unique VLA's
3256 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00003257 QualType Canon;
Fangrui Song6907ce22018-07-30 19:24:48 +00003258
John McCall33ddac02011-01-19 10:06:00 +00003259 // Be sure to pull qualifiers off the element type.
3260 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
3261 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00003262 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00003263 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00003264 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00003265 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003266
Eugene Zelenko7855e772018-04-03 00:11:50 +00003267 auto *New = new (*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00003268 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00003269
3270 VariableArrayTypes.push_back(New);
3271 Types.push_back(New);
3272 return QualType(New, 0);
3273}
3274
Douglas Gregor4619e432008-12-05 23:32:09 +00003275/// getDependentSizedArrayType - Returns a non-unique reference to
3276/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00003277/// type.
John McCall33ddac02011-01-19 10:06:00 +00003278QualType ASTContext::getDependentSizedArrayType(QualType elementType,
3279 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00003280 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00003281 unsigned elementTypeQuals,
3282 SourceRange brackets) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00003283 assert((!numElements || numElements->isTypeDependent() ||
John McCall33ddac02011-01-19 10:06:00 +00003284 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00003285 "Size must be type- or value-dependent!");
3286
John McCall33ddac02011-01-19 10:06:00 +00003287 // Dependently-sized array types that do not have a specified number
3288 // of elements will have their sizes deduced from a dependent
3289 // initializer. We do no canonicalization here at all, which is okay
3290 // because they can't be used in most locations.
3291 if (!numElements) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003292 auto *newType
John McCall33ddac02011-01-19 10:06:00 +00003293 = new (*this, TypeAlignment)
3294 DependentSizedArrayType(*this, elementType, QualType(),
3295 numElements, ASM, elementTypeQuals,
3296 brackets);
3297 Types.push_back(newType);
3298 return QualType(newType, 0);
3299 }
3300
3301 // Otherwise, we actually build a new type every time, but we
3302 // also build a canonical type.
3303
3304 SplitQualType canonElementType = getCanonicalType(elementType).split();
3305
Craig Topper36250ad2014-05-12 05:36:57 +00003306 void *insertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00003307 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00003308 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00003309 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00003310 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00003311
John McCall33ddac02011-01-19 10:06:00 +00003312 // Look for an existing type with these properties.
3313 DependentSizedArrayType *canonTy =
3314 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00003315
John McCall33ddac02011-01-19 10:06:00 +00003316 // If we don't have one, build one.
3317 if (!canonTy) {
3318 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00003319 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00003320 QualType(), numElements, ASM, elementTypeQuals,
3321 brackets);
3322 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
3323 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00003324 }
3325
John McCall33ddac02011-01-19 10:06:00 +00003326 // Apply qualifiers from the element type to the array.
3327 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00003328 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00003329
David Majnemer16a74702015-07-24 05:54:19 +00003330 // If we didn't need extra canonicalization for the element type or the size
3331 // expression, then just use that as our result.
3332 if (QualType(canonElementType.Ty, 0) == elementType &&
3333 canonTy->getSizeExpr() == numElements)
John McCall33ddac02011-01-19 10:06:00 +00003334 return canon;
3335
3336 // Otherwise, we need to build a type which follows the spelling
3337 // of the element type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00003338 auto *sugaredType
John McCall33ddac02011-01-19 10:06:00 +00003339 = new (*this, TypeAlignment)
3340 DependentSizedArrayType(*this, elementType, canon, numElements,
3341 ASM, elementTypeQuals, brackets);
3342 Types.push_back(sugaredType);
3343 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00003344}
3345
John McCall33ddac02011-01-19 10:06:00 +00003346QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00003347 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00003348 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00003349 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00003350 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00003351
Craig Topper36250ad2014-05-12 05:36:57 +00003352 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00003353 if (IncompleteArrayType *iat =
3354 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
3355 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00003356
3357 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00003358 // either, so fill in the canonical type field. We also have to pull
3359 // qualifiers off the element type.
3360 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00003361
John McCall33ddac02011-01-19 10:06:00 +00003362 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
3363 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00003364 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00003365 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00003366 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00003367
3368 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00003369 IncompleteArrayType *existing =
3370 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
3371 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00003372 }
Eli Friedmanbd258282008-02-15 18:16:39 +00003373
Eugene Zelenko7855e772018-04-03 00:11:50 +00003374 auto *newType = new (*this, TypeAlignment)
John McCall33ddac02011-01-19 10:06:00 +00003375 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00003376
John McCall33ddac02011-01-19 10:06:00 +00003377 IncompleteArrayTypes.InsertNode(newType, insertPos);
3378 Types.push_back(newType);
3379 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00003380}
3381
Steve Naroff91fcddb2007-07-18 18:00:27 +00003382/// getVectorType - Return the unique reference to a vector type of
3383/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00003384QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00003385 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00003386 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00003387
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003388 // Check if we've already instantiated a vector of this type.
3389 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00003390 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00003391
Craig Topper36250ad2014-05-12 05:36:57 +00003392 void *InsertPos = nullptr;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003393 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3394 return QualType(VTP, 0);
3395
3396 // If the element type isn't canonical, this won't be a canonical type either,
3397 // so fill in the canonical type field.
3398 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00003399 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00003400 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00003401
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003402 // Get the new insert position for the node we care about.
3403 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003404 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003405 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00003406 auto *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00003407 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003408 VectorTypes.InsertNode(New, InsertPos);
3409 Types.push_back(New);
3410 return QualType(New, 0);
3411}
3412
Erich Keanef702b022018-07-13 19:46:04 +00003413QualType
3414ASTContext::getDependentVectorType(QualType VecType, Expr *SizeExpr,
3415 SourceLocation AttrLoc,
3416 VectorType::VectorKind VecKind) const {
3417 llvm::FoldingSetNodeID ID;
3418 DependentVectorType::Profile(ID, *this, getCanonicalType(VecType), SizeExpr,
3419 VecKind);
3420 void *InsertPos = nullptr;
3421 DependentVectorType *Canon =
3422 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3423 DependentVectorType *New;
3424
3425 if (Canon) {
3426 New = new (*this, TypeAlignment) DependentVectorType(
3427 *this, VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind);
3428 } else {
3429 QualType CanonVecTy = getCanonicalType(VecType);
3430 if (CanonVecTy == VecType) {
3431 New = new (*this, TypeAlignment) DependentVectorType(
3432 *this, VecType, QualType(), SizeExpr, AttrLoc, VecKind);
3433
3434 DependentVectorType *CanonCheck =
3435 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3436 assert(!CanonCheck &&
3437 "Dependent-sized vector_size canonical type broken");
3438 (void)CanonCheck;
3439 DependentVectorTypes.InsertNode(New, InsertPos);
3440 } else {
3441 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
3442 SourceLocation());
3443 New = new (*this, TypeAlignment) DependentVectorType(
3444 *this, VecType, Canon, SizeExpr, AttrLoc, VecKind);
3445 }
3446 }
3447
3448 Types.push_back(New);
3449 return QualType(New, 0);
3450}
3451
Nate Begemance4d7fc2008-04-18 23:10:10 +00003452/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00003453/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00003454QualType
3455ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00003456 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00003457
Steve Naroff91fcddb2007-07-18 18:00:27 +00003458 // Check if we've already instantiated a vector of this type.
3459 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00003460 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00003461 VectorType::GenericVector);
Craig Topper36250ad2014-05-12 05:36:57 +00003462 void *InsertPos = nullptr;
Steve Naroff91fcddb2007-07-18 18:00:27 +00003463 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3464 return QualType(VTP, 0);
3465
3466 // If the element type isn't canonical, this won't be a canonical type either,
3467 // so fill in the canonical type field.
3468 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00003469 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00003470 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00003471
Steve Naroff91fcddb2007-07-18 18:00:27 +00003472 // Get the new insert position for the node we care about.
3473 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003474 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00003475 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00003476 auto *New = new (*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00003477 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00003478 VectorTypes.InsertNode(New, InsertPos);
3479 Types.push_back(New);
3480 return QualType(New, 0);
3481}
3482
Jay Foad39c79802011-01-12 09:06:06 +00003483QualType
3484ASTContext::getDependentSizedExtVectorType(QualType vecType,
3485 Expr *SizeExpr,
3486 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00003487 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00003488 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00003489 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003490
Craig Topper36250ad2014-05-12 05:36:57 +00003491 void *InsertPos = nullptr;
Douglas Gregor352169a2009-07-31 03:54:25 +00003492 DependentSizedExtVectorType *Canon
3493 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3494 DependentSizedExtVectorType *New;
3495 if (Canon) {
3496 // We already have a canonical version of this array type; use it as
3497 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00003498 New = new (*this, TypeAlignment)
3499 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
3500 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00003501 } else {
3502 QualType CanonVecTy = getCanonicalType(vecType);
3503 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00003504 New = new (*this, TypeAlignment)
3505 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
3506 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003507
3508 DependentSizedExtVectorType *CanonCheck
3509 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3510 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
3511 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00003512 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
3513 } else {
3514 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
3515 SourceLocation());
Fangrui Song6907ce22018-07-30 19:24:48 +00003516 New = new (*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00003517 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00003518 }
3519 }
Mike Stump11289f42009-09-09 15:08:12 +00003520
Douglas Gregor758a8692009-06-17 21:51:59 +00003521 Types.push_back(New);
3522 return QualType(New, 0);
3523}
3524
Fangrui Song6907ce22018-07-30 19:24:48 +00003525QualType ASTContext::getDependentAddressSpaceType(QualType PointeeType,
3526 Expr *AddrSpaceExpr,
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003527 SourceLocation AttrLoc) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00003528 assert(AddrSpaceExpr->isInstantiationDependent());
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003529
3530 QualType canonPointeeType = getCanonicalType(PointeeType);
3531
3532 void *insertPos = nullptr;
3533 llvm::FoldingSetNodeID ID;
3534 DependentAddressSpaceType::Profile(ID, *this, canonPointeeType,
3535 AddrSpaceExpr);
3536
3537 DependentAddressSpaceType *canonTy =
3538 DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos);
3539
3540 if (!canonTy) {
3541 canonTy = new (*this, TypeAlignment)
Fangrui Song6907ce22018-07-30 19:24:48 +00003542 DependentAddressSpaceType(*this, canonPointeeType,
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003543 QualType(), AddrSpaceExpr, AttrLoc);
3544 DependentAddressSpaceTypes.InsertNode(canonTy, insertPos);
3545 Types.push_back(canonTy);
3546 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003547
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003548 if (canonPointeeType == PointeeType &&
3549 canonTy->getAddrSpaceExpr() == AddrSpaceExpr)
Fangrui Song6907ce22018-07-30 19:24:48 +00003550 return QualType(canonTy, 0);
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003551
Eugene Zelenko7855e772018-04-03 00:11:50 +00003552 auto *sugaredType
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003553 = new (*this, TypeAlignment)
Fangrui Song6907ce22018-07-30 19:24:48 +00003554 DependentAddressSpaceType(*this, PointeeType, QualType(canonTy, 0),
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003555 AddrSpaceExpr, AttrLoc);
3556 Types.push_back(sugaredType);
Fangrui Song6907ce22018-07-30 19:24:48 +00003557 return QualType(sugaredType, 0);
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003558}
3559
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003560/// Determine whether \p T is canonical as the result type of a function.
John McCall18afab72016-03-01 00:49:02 +00003561static bool isCanonicalResultType(QualType T) {
3562 return T.isCanonical() &&
3563 (T.getObjCLifetime() == Qualifiers::OCL_None ||
3564 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
3565}
3566
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003567/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Jay Foad39c79802011-01-12 09:06:06 +00003568QualType
3569ASTContext::getFunctionNoProtoType(QualType ResultTy,
3570 const FunctionType::ExtInfo &Info) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003571 // Unique functions, to guarantee there is only one function of a particular
3572 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00003573 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00003574 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00003575
Craig Topper36250ad2014-05-12 05:36:57 +00003576 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003577 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003578 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003579 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003580
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003581 QualType Canonical;
John McCall18afab72016-03-01 00:49:02 +00003582 if (!isCanonicalResultType(ResultTy)) {
3583 Canonical =
3584 getFunctionNoProtoType(getCanonicalFunctionResultType(ResultTy), Info);
Mike Stump11289f42009-09-09 15:08:12 +00003585
Chris Lattner47955de2007-01-27 08:37:20 +00003586 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003587 FunctionNoProtoType *NewIP =
3588 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003589 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00003590 }
Mike Stump11289f42009-09-09 15:08:12 +00003591
Eugene Zelenko7855e772018-04-03 00:11:50 +00003592 auto *New = new (*this, TypeAlignment)
John McCall18afab72016-03-01 00:49:02 +00003593 FunctionNoProtoType(ResultTy, Canonical, Info);
Chris Lattner47955de2007-01-27 08:37:20 +00003594 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003595 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003596 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003597}
3598
Douglas Gregora602a152015-10-01 20:20:47 +00003599CanQualType
3600ASTContext::getCanonicalFunctionResultType(QualType ResultType) const {
3601 CanQualType CanResultType = getCanonicalType(ResultType);
3602
3603 // Canonical result types do not have ARC lifetime qualifiers.
3604 if (CanResultType.getQualifiers().hasObjCLifetime()) {
3605 Qualifiers Qs = CanResultType.getQualifiers();
3606 Qs.removeObjCLifetime();
3607 return CanQualType::CreateUnsafe(
3608 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
3609 }
3610
3611 return CanResultType;
3612}
3613
Richard Smith3c4f8d22016-10-16 17:54:23 +00003614static bool isCanonicalExceptionSpecification(
3615 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
3616 if (ESI.Type == EST_None)
3617 return true;
3618 if (!NoexceptInType)
3619 return false;
3620
3621 // C++17 onwards: exception specification is part of the type, as a simple
3622 // boolean "can this function type throw".
3623 if (ESI.Type == EST_BasicNoexcept)
3624 return true;
3625
Richard Smitheaf11ad2018-05-03 03:58:32 +00003626 // A noexcept(expr) specification is (possibly) canonical if expr is
3627 // value-dependent.
3628 if (ESI.Type == EST_DependentNoexcept)
3629 return true;
3630
Richard Smith3c4f8d22016-10-16 17:54:23 +00003631 // A dynamic exception specification is canonical if it only contains pack
Richard Smith2a2cda52016-10-18 19:29:18 +00003632 // expansions (so we can't tell whether it's non-throwing) and all its
3633 // contained types are canonical.
Richard Smith3c4f8d22016-10-16 17:54:23 +00003634 if (ESI.Type == EST_Dynamic) {
Richard Smithfda59e52016-10-26 01:05:54 +00003635 bool AnyPackExpansions = false;
3636 for (QualType ET : ESI.Exceptions) {
3637 if (!ET.isCanonical())
Richard Smith3c4f8d22016-10-16 17:54:23 +00003638 return false;
Richard Smithfda59e52016-10-26 01:05:54 +00003639 if (ET->getAs<PackExpansionType>())
3640 AnyPackExpansions = true;
3641 }
3642 return AnyPackExpansions;
Richard Smith3c4f8d22016-10-16 17:54:23 +00003643 }
3644
Richard Smith3c4f8d22016-10-16 17:54:23 +00003645 return false;
3646}
3647
Richard Smith304b1242016-10-18 20:13:25 +00003648QualType ASTContext::getFunctionTypeInternal(
3649 QualType ResultTy, ArrayRef<QualType> ArgArray,
3650 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
Jordan Rose5c382722013-03-08 21:51:21 +00003651 size_t NumArgs = ArgArray.size();
3652
Richard Smith2a2cda52016-10-18 19:29:18 +00003653 // Unique functions, to guarantee there is only one function of a particular
3654 // structure.
3655 llvm::FoldingSetNodeID ID;
3656 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
3657 *this, true);
Richard Smith3c4f8d22016-10-16 17:54:23 +00003658
Richard Smith2a2cda52016-10-18 19:29:18 +00003659 QualType Canonical;
3660 bool Unique = false;
3661
3662 void *InsertPos = nullptr;
3663 if (FunctionProtoType *FPT =
3664 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
3665 QualType Existing = QualType(FPT, 0);
3666
3667 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
3668 // it so long as our exception specification doesn't contain a dependent
Richard Smith304b1242016-10-18 20:13:25 +00003669 // noexcept expression, or we're just looking for a canonical type.
3670 // Otherwise, we're going to need to create a type
Richard Smith2a2cda52016-10-18 19:29:18 +00003671 // sugar node to hold the concrete expression.
Richard Smitheaf11ad2018-05-03 03:58:32 +00003672 if (OnlyWantCanonical || !isComputedNoexcept(EPI.ExceptionSpec.Type) ||
Richard Smith2a2cda52016-10-18 19:29:18 +00003673 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
3674 return Existing;
3675
3676 // We need a new type sugar node for this one, to hold the new noexcept
3677 // expression. We do no canonicalization here, but that's OK since we don't
3678 // expect to see the same noexcept expression much more than once.
3679 Canonical = getCanonicalType(Existing);
3680 Unique = true;
3681 }
3682
Aaron Ballmanc351fba2017-12-04 20:27:34 +00003683 bool NoexceptInType = getLangOpts().CPlusPlus17;
Richard Smith3c4f8d22016-10-16 17:54:23 +00003684 bool IsCanonicalExceptionSpec =
3685 isCanonicalExceptionSpecification(EPI.ExceptionSpec, NoexceptInType);
3686
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003687 // Determine whether the type being created is already canonical or not.
Richard Smith2a2cda52016-10-18 19:29:18 +00003688 bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
Richard Smith3c4f8d22016-10-16 17:54:23 +00003689 isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003690 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003691 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003692 isCanonical = false;
3693
Richard Smith304b1242016-10-18 20:13:25 +00003694 if (OnlyWantCanonical)
3695 assert(isCanonical &&
3696 "given non-canonical parameters constructing canonical type");
3697
Richard Smith2a2cda52016-10-18 19:29:18 +00003698 // If this type isn't canonical, get the canonical version of it if we don't
3699 // already have it. The exception spec is only partially part of the
3700 // canonical type, and only in C++17 onwards.
3701 if (!isCanonical && Canonical.isNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003702 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003703 CanonicalArgs.reserve(NumArgs);
3704 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003705 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003706
Benjamin Kramer3f515cd2016-10-26 12:51:45 +00003707 llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
John McCalldb40c7f2010-12-14 08:05:40 +00003708 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00003709 CanonicalEPI.HasTrailingReturn = false;
Richard Smith3c4f8d22016-10-16 17:54:23 +00003710
3711 if (IsCanonicalExceptionSpec) {
3712 // Exception spec is already OK.
3713 } else if (NoexceptInType) {
3714 switch (EPI.ExceptionSpec.Type) {
3715 case EST_Unparsed: case EST_Unevaluated: case EST_Uninstantiated:
3716 // We don't know yet. It shouldn't matter what we pick here; no-one
3717 // should ever look at this.
3718 LLVM_FALLTHROUGH;
Richard Smitheaf11ad2018-05-03 03:58:32 +00003719 case EST_None: case EST_MSAny: case EST_NoexceptFalse:
Richard Smith3c4f8d22016-10-16 17:54:23 +00003720 CanonicalEPI.ExceptionSpec.Type = EST_None;
3721 break;
3722
Richard Smith2a2cda52016-10-18 19:29:18 +00003723 // A dynamic exception specification is almost always "not noexcept",
3724 // with the exception that a pack expansion might expand to no types.
3725 case EST_Dynamic: {
3726 bool AnyPacks = false;
3727 for (QualType ET : EPI.ExceptionSpec.Exceptions) {
3728 if (ET->getAs<PackExpansionType>())
3729 AnyPacks = true;
3730 ExceptionTypeStorage.push_back(getCanonicalType(ET));
3731 }
3732 if (!AnyPacks)
3733 CanonicalEPI.ExceptionSpec.Type = EST_None;
3734 else {
3735 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
3736 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
3737 }
3738 break;
3739 }
3740
Richard Smitheaf11ad2018-05-03 03:58:32 +00003741 case EST_DynamicNone: case EST_BasicNoexcept: case EST_NoexceptTrue:
Richard Smith3c4f8d22016-10-16 17:54:23 +00003742 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
3743 break;
3744
Richard Smitheaf11ad2018-05-03 03:58:32 +00003745 case EST_DependentNoexcept:
3746 llvm_unreachable("dependent noexcept is already canonical");
Richard Smith3c4f8d22016-10-16 17:54:23 +00003747 }
Richard Smith3c4f8d22016-10-16 17:54:23 +00003748 } else {
3749 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
3750 }
John McCalldb40c7f2010-12-14 08:05:40 +00003751
Douglas Gregora602a152015-10-01 20:20:47 +00003752 // Adjust the canonical function result type.
3753 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
Richard Smith304b1242016-10-18 20:13:25 +00003754 Canonical =
3755 getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003756
Chris Lattnerfd4de792007-01-27 01:15:32 +00003757 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003758 FunctionProtoType *NewIP =
3759 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003760 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003761 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003762
Bruno Ricci26a25362018-10-02 11:46:38 +00003763 // Compute the needed size to hold this FunctionProtoType and the
3764 // various trailing objects.
3765 auto ESH = FunctionProtoType::getExceptionSpecSize(
3766 EPI.ExceptionSpec.Type, EPI.ExceptionSpec.Exceptions.size());
3767 size_t Size = FunctionProtoType::totalSizeToAlloc<
3768 QualType, FunctionType::FunctionTypeExtraBitfields,
3769 FunctionType::ExceptionType, Expr *, FunctionDecl *,
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00003770 FunctionProtoType::ExtParameterInfo, Qualifiers>(
Bruno Ricci26a25362018-10-02 11:46:38 +00003771 NumArgs, FunctionProtoType::hasExtraBitfields(EPI.ExceptionSpec.Type),
3772 ESH.NumExceptionType, ESH.NumExprPtr, ESH.NumFunctionDeclPtr,
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00003773 EPI.ExtParameterInfos ? NumArgs : 0,
3774 EPI.TypeQuals.hasNonFastQualifiers() ? 1 : 0);
John McCall18afab72016-03-01 00:49:02 +00003775
Bruno Ricci26a25362018-10-02 11:46:38 +00003776 auto *FTP = (FunctionProtoType *)Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00003777 FunctionProtoType::ExtProtoInfo newEPI = EPI;
Jordan Rose5c382722013-03-08 21:51:21 +00003778 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003779 Types.push_back(FTP);
Richard Smith2a2cda52016-10-18 19:29:18 +00003780 if (!Unique)
3781 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003782 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003783}
Chris Lattneref51c202006-11-10 07:17:23 +00003784
Joey Goulye3c85de2016-12-01 11:30:49 +00003785QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
Xiuli Pan9c14e282016-01-09 12:53:17 +00003786 llvm::FoldingSetNodeID ID;
Joey Goulye3c85de2016-12-01 11:30:49 +00003787 PipeType::Profile(ID, T, ReadOnly);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003788
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00003789 void *InsertPos = nullptr;
Joey Goulye3c85de2016-12-01 11:30:49 +00003790 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
Xiuli Pan9c14e282016-01-09 12:53:17 +00003791 return QualType(PT, 0);
3792
3793 // If the pipe element type isn't canonical, this won't be a canonical type
3794 // either, so fill in the canonical type field.
3795 QualType Canonical;
3796 if (!T.isCanonical()) {
Joey Goulye3c85de2016-12-01 11:30:49 +00003797 Canonical = getPipeType(getCanonicalType(T), ReadOnly);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003798
3799 // Get the new insert position for the node we care about.
Joey Goulye3c85de2016-12-01 11:30:49 +00003800 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003801 assert(!NewIP && "Shouldn't be in the map!");
3802 (void)NewIP;
3803 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00003804 auto *New = new (*this, TypeAlignment) PipeType(T, Canonical, ReadOnly);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003805 Types.push_back(New);
Joey Goulye3c85de2016-12-01 11:30:49 +00003806 PipeTypes.InsertNode(New, InsertPos);
Joey Gouly5788b782016-11-18 14:10:54 +00003807 return QualType(New, 0);
3808}
3809
Anastasia Stulova59055b92018-05-09 13:23:26 +00003810QualType ASTContext::adjustStringLiteralBaseType(QualType Ty) const {
3811 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
3812 return LangOpts.OpenCL ? getAddrSpaceQualType(Ty, LangAS::opencl_constant)
3813 : Ty;
3814}
3815
Joey Goulye3c85de2016-12-01 11:30:49 +00003816QualType ASTContext::getReadPipeType(QualType T) const {
3817 return getPipeType(T, true);
3818}
3819
Joey Gouly5788b782016-11-18 14:10:54 +00003820QualType ASTContext::getWritePipeType(QualType T) const {
Joey Goulye3c85de2016-12-01 11:30:49 +00003821 return getPipeType(T, false);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003822}
3823
John McCalle78aac42010-03-10 03:28:59 +00003824#ifndef NDEBUG
3825static bool NeedsInjectedClassNameType(const RecordDecl *D) {
3826 if (!isa<CXXRecordDecl>(D)) return false;
Eugene Zelenko7855e772018-04-03 00:11:50 +00003827 const auto *RD = cast<CXXRecordDecl>(D);
John McCalle78aac42010-03-10 03:28:59 +00003828 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
3829 return true;
3830 if (RD->getDescribedClassTemplate() &&
3831 !isa<ClassTemplateSpecializationDecl>(RD))
3832 return true;
3833 return false;
3834}
3835#endif
3836
3837/// getInjectedClassNameType - Return the unique reference to the
3838/// injected class name type for the specified templated declaration.
3839QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00003840 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00003841 assert(NeedsInjectedClassNameType(Decl));
3842 if (Decl->TypeForDecl) {
3843 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00003844 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00003845 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
3846 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3847 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
3848 } else {
John McCall424cec92011-01-19 06:33:43 +00003849 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00003850 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00003851 Decl->TypeForDecl = newType;
3852 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00003853 }
3854 return QualType(Decl->TypeForDecl, 0);
3855}
3856
Douglas Gregor83a586e2008-04-13 21:07:44 +00003857/// getTypeDeclType - Return the unique reference to the type for the
3858/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00003859QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00003860 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00003861 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00003862
Eugene Zelenko7855e772018-04-03 00:11:50 +00003863 if (const auto *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00003864 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00003865
John McCall96f0b5f2010-03-10 06:48:02 +00003866 assert(!isa<TemplateTypeParmDecl>(Decl) &&
3867 "Template type parameter types are always available.");
3868
Eugene Zelenko7855e772018-04-03 00:11:50 +00003869 if (const auto *Record = dyn_cast<RecordDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003870 assert(Record->isFirstDecl() && "struct/union has previous declaration");
John McCall96f0b5f2010-03-10 06:48:02 +00003871 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003872 return getRecordType(Record);
Eugene Zelenko7855e772018-04-03 00:11:50 +00003873 } else if (const auto *Enum = dyn_cast<EnumDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003874 assert(Enum->isFirstDecl() && "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003875 return getEnumType(Enum);
Eugene Zelenko7855e772018-04-03 00:11:50 +00003876 } else if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00003877 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
3878 Decl->TypeForDecl = newType;
3879 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00003880 } else
John McCall96f0b5f2010-03-10 06:48:02 +00003881 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003882
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003883 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00003884}
3885
Chris Lattner32d920b2007-01-26 02:01:53 +00003886/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00003887/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003888QualType
Richard Smithdda56e42011-04-15 14:24:37 +00003889ASTContext::getTypedefType(const TypedefNameDecl *Decl,
3890 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003891 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003892
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003893 if (Canonical.isNull())
3894 Canonical = getCanonicalType(Decl->getUnderlyingType());
Eugene Zelenko7855e772018-04-03 00:11:50 +00003895 auto *newType = new (*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00003896 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00003897 Decl->TypeForDecl = newType;
3898 Types.push_back(newType);
3899 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00003900}
3901
Jay Foad39c79802011-01-12 09:06:06 +00003902QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003903 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3904
Douglas Gregorec9fd132012-01-14 16:38:05 +00003905 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003906 if (PrevDecl->TypeForDecl)
Fangrui Song6907ce22018-07-30 19:24:48 +00003907 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003908
Eugene Zelenko7855e772018-04-03 00:11:50 +00003909 auto *newType = new (*this, TypeAlignment) RecordType(Decl);
John McCall424cec92011-01-19 06:33:43 +00003910 Decl->TypeForDecl = newType;
3911 Types.push_back(newType);
3912 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003913}
3914
Jay Foad39c79802011-01-12 09:06:06 +00003915QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003916 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3917
Douglas Gregorec9fd132012-01-14 16:38:05 +00003918 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003919 if (PrevDecl->TypeForDecl)
Fangrui Song6907ce22018-07-30 19:24:48 +00003920 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003921
Eugene Zelenko7855e772018-04-03 00:11:50 +00003922 auto *newType = new (*this, TypeAlignment) EnumType(Decl);
John McCall424cec92011-01-19 06:33:43 +00003923 Decl->TypeForDecl = newType;
3924 Types.push_back(newType);
3925 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003926}
3927
Richard Smithe43e2b32018-08-20 21:47:29 +00003928QualType ASTContext::getAttributedType(attr::Kind attrKind,
John McCall81904512011-01-06 01:58:22 +00003929 QualType modifiedType,
3930 QualType equivalentType) {
3931 llvm::FoldingSetNodeID id;
3932 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
3933
Craig Topper36250ad2014-05-12 05:36:57 +00003934 void *insertPos = nullptr;
John McCall81904512011-01-06 01:58:22 +00003935 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3936 if (type) return QualType(type, 0);
3937
3938 QualType canon = getCanonicalType(equivalentType);
3939 type = new (*this, TypeAlignment)
3940 AttributedType(canon, attrKind, modifiedType, equivalentType);
3941
3942 Types.push_back(type);
3943 AttributedTypes.InsertNode(type, insertPos);
3944
3945 return QualType(type, 0);
3946}
3947
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003948/// Retrieve a substitution-result type.
John McCallcebee162009-10-18 09:09:24 +00003949QualType
3950ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00003951 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00003952 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00003953 && "replacement types must always be canonical");
3954
3955 llvm::FoldingSetNodeID ID;
3956 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00003957 void *InsertPos = nullptr;
John McCallcebee162009-10-18 09:09:24 +00003958 SubstTemplateTypeParmType *SubstParm
3959 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3960
3961 if (!SubstParm) {
3962 SubstParm = new (*this, TypeAlignment)
3963 SubstTemplateTypeParmType(Parm, Replacement);
3964 Types.push_back(SubstParm);
3965 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3966 }
3967
3968 return QualType(SubstParm, 0);
3969}
3970
Fangrui Song6907ce22018-07-30 19:24:48 +00003971/// Retrieve a
Douglas Gregorada4b792011-01-14 02:55:32 +00003972QualType ASTContext::getSubstTemplateTypeParmPackType(
3973 const TemplateTypeParmType *Parm,
3974 const TemplateArgument &ArgPack) {
3975#ifndef NDEBUG
Aaron Ballman2a89e852014-07-15 21:32:31 +00003976 for (const auto &P : ArgPack.pack_elements()) {
3977 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3978 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
Douglas Gregorada4b792011-01-14 02:55:32 +00003979 }
3980#endif
Fangrui Song6907ce22018-07-30 19:24:48 +00003981
Douglas Gregorada4b792011-01-14 02:55:32 +00003982 llvm::FoldingSetNodeID ID;
3983 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00003984 void *InsertPos = nullptr;
Douglas Gregorada4b792011-01-14 02:55:32 +00003985 if (SubstTemplateTypeParmPackType *SubstParm
3986 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3987 return QualType(SubstParm, 0);
Fangrui Song6907ce22018-07-30 19:24:48 +00003988
Douglas Gregorada4b792011-01-14 02:55:32 +00003989 QualType Canon;
3990 if (!Parm->isCanonicalUnqualified()) {
3991 Canon = getCanonicalType(QualType(Parm, 0));
3992 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3993 ArgPack);
3994 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3995 }
3996
Eugene Zelenko7855e772018-04-03 00:11:50 +00003997 auto *SubstParm
Douglas Gregorada4b792011-01-14 02:55:32 +00003998 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3999 ArgPack);
4000 Types.push_back(SubstParm);
George Burgess IVb5fe8552017-06-12 17:44:30 +00004001 SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos);
Fangrui Song6907ce22018-07-30 19:24:48 +00004002 return QualType(SubstParm, 0);
Douglas Gregorada4b792011-01-14 02:55:32 +00004003}
4004
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004005/// Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00004006/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00004007/// name.
Mike Stump11289f42009-09-09 15:08:12 +00004008QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00004009 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00004010 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00004011 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00004012 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Craig Topper36250ad2014-05-12 05:36:57 +00004013 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004014 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00004015 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4016
4017 if (TypeParm)
4018 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004019
Chandler Carruth08836322011-05-01 00:51:33 +00004020 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00004021 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00004022 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004023
Fangrui Song6907ce22018-07-30 19:24:48 +00004024 TemplateTypeParmType *TypeCheck
Douglas Gregorc42075a2010-02-04 18:10:26 +00004025 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4026 assert(!TypeCheck && "Template type parameter canonical type broken");
4027 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00004028 } else
John McCall90d1c2d2009-09-24 23:30:46 +00004029 TypeParm = new (*this, TypeAlignment)
4030 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00004031
4032 Types.push_back(TypeParm);
4033 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
4034
4035 return QualType(TypeParm, 0);
4036}
4037
John McCalle78aac42010-03-10 03:28:59 +00004038TypeSourceInfo *
4039ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
4040 SourceLocation NameLoc,
4041 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00004042 QualType Underlying) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00004043 assert(!Name.getAsDependentTemplateName() &&
Douglas Gregore16af532011-02-28 18:50:33 +00004044 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00004045 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00004046
4047 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie6adc78e2013-02-18 22:06:02 +00004048 TemplateSpecializationTypeLoc TL =
4049 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara48c05be2012-02-06 14:41:24 +00004050 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00004051 TL.setTemplateNameLoc(NameLoc);
4052 TL.setLAngleLoc(Args.getLAngleLoc());
4053 TL.setRAngleLoc(Args.getRAngleLoc());
4054 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
4055 TL.setArgLocInfo(i, Args[i].getLocInfo());
4056 return DI;
4057}
4058
Mike Stump11289f42009-09-09 15:08:12 +00004059QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00004060ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00004061 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00004062 QualType Underlying) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00004063 assert(!Template.getAsDependentTemplateName() &&
Douglas Gregore16af532011-02-28 18:50:33 +00004064 "No dependent template names here!");
John McCall6b51f282009-11-23 01:53:49 +00004065
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004066 SmallVector<TemplateArgument, 4> ArgVec;
David Majnemer6fbeee32016-07-07 04:43:07 +00004067 ArgVec.reserve(Args.size());
4068 for (const TemplateArgumentLoc &Arg : Args.arguments())
4069 ArgVec.push_back(Arg.getArgument());
John McCall0ad16662009-10-29 08:12:44 +00004070
David Majnemer6fbeee32016-07-07 04:43:07 +00004071 return getTemplateSpecializationType(Template, ArgVec, Underlying);
John McCall0ad16662009-10-29 08:12:44 +00004072}
4073
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004074#ifndef NDEBUG
David Majnemer6fbeee32016-07-07 04:43:07 +00004075static bool hasAnyPackExpansions(ArrayRef<TemplateArgument> Args) {
4076 for (const TemplateArgument &Arg : Args)
4077 if (Arg.isPackExpansion())
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004078 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00004079
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004080 return true;
4081}
4082#endif
4083
John McCall0ad16662009-10-29 08:12:44 +00004084QualType
4085ASTContext::getTemplateSpecializationType(TemplateName Template,
David Majnemer6fbeee32016-07-07 04:43:07 +00004086 ArrayRef<TemplateArgument> Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00004087 QualType Underlying) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00004088 assert(!Template.getAsDependentTemplateName() &&
Douglas Gregore16af532011-02-28 18:50:33 +00004089 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00004090 // Look through qualified template names.
4091 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
4092 Template = TemplateName(QTN->getTemplateDecl());
Fangrui Song6907ce22018-07-30 19:24:48 +00004093
4094 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00004095 Template.getAsTemplateDecl() &&
4096 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00004097 QualType CanonType;
4098 if (!Underlying.isNull())
4099 CanonType = getCanonicalType(Underlying);
4100 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004101 // We can get here with an alias template when the specialization contains
4102 // a pack expansion that does not match up with a parameter pack.
David Majnemer6fbeee32016-07-07 04:43:07 +00004103 assert((!IsTypeAlias || hasAnyPackExpansions(Args)) &&
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004104 "Caller must compute aliased type");
4105 IsTypeAlias = false;
David Majnemer6fbeee32016-07-07 04:43:07 +00004106 CanonType = getCanonicalTemplateSpecializationType(Template, Args);
Richard Smith3f1b5d02011-05-05 21:57:07 +00004107 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00004108
Douglas Gregora8e02e72009-07-28 23:00:59 +00004109 // Allocate the (non-canonical) template specialization type, but don't
4110 // try to unique it: these types typically have location information that
4111 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00004112 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
David Majnemer6fbeee32016-07-07 04:43:07 +00004113 sizeof(TemplateArgument) * Args.size() +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004114 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00004115 TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004116 auto *Spec
David Majnemer6fbeee32016-07-07 04:43:07 +00004117 = new (Mem) TemplateSpecializationType(Template, Args, CanonType,
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004118 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00004119
Douglas Gregor8bf42052009-02-09 18:46:07 +00004120 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00004121 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00004122}
4123
David Majnemer6fbeee32016-07-07 04:43:07 +00004124QualType ASTContext::getCanonicalTemplateSpecializationType(
4125 TemplateName Template, ArrayRef<TemplateArgument> Args) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00004126 assert(!Template.getAsDependentTemplateName() &&
Douglas Gregore16af532011-02-28 18:50:33 +00004127 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00004128
Douglas Gregore29139c2011-03-03 17:04:51 +00004129 // Look through qualified template names.
4130 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
4131 Template = TemplateName(QTN->getTemplateDecl());
Fangrui Song6907ce22018-07-30 19:24:48 +00004132
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004133 // Build the canonical template specialization type.
4134 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004135 SmallVector<TemplateArgument, 4> CanonArgs;
David Majnemer6fbeee32016-07-07 04:43:07 +00004136 unsigned NumArgs = Args.size();
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004137 CanonArgs.reserve(NumArgs);
David Majnemer6fbeee32016-07-07 04:43:07 +00004138 for (const TemplateArgument &Arg : Args)
4139 CanonArgs.push_back(getCanonicalTemplateArgument(Arg));
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004140
4141 // Determine whether this canonical template specialization type already
4142 // exists.
4143 llvm::FoldingSetNodeID ID;
4144 TemplateSpecializationType::Profile(ID, CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00004145 CanonArgs, *this);
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004146
Craig Topper36250ad2014-05-12 05:36:57 +00004147 void *InsertPos = nullptr;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004148 TemplateSpecializationType *Spec
4149 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
4150
4151 if (!Spec) {
4152 // Allocate a new canonical template specialization type.
4153 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
4154 sizeof(TemplateArgument) * NumArgs),
4155 TypeAlignment);
4156 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00004157 CanonArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00004158 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004159 Types.push_back(Spec);
4160 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
4161 }
4162
4163 assert(Spec->isDependentType() &&
4164 "Non-dependent template-id type must have a canonical type");
4165 return QualType(Spec, 0);
4166}
4167
Joel E. Denny7509a2f2018-05-14 19:36:45 +00004168QualType ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
4169 NestedNameSpecifier *NNS,
4170 QualType NamedType,
4171 TagDecl *OwnedTagDecl) const {
Douglas Gregor52537682009-03-19 00:18:19 +00004172 llvm::FoldingSetNodeID ID;
Joel E. Denny7509a2f2018-05-14 19:36:45 +00004173 ElaboratedType::Profile(ID, Keyword, NNS, NamedType, OwnedTagDecl);
Douglas Gregor52537682009-03-19 00:18:19 +00004174
Craig Topper36250ad2014-05-12 05:36:57 +00004175 void *InsertPos = nullptr;
Abramo Bagnara6150c882010-05-11 21:36:43 +00004176 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00004177 if (T)
4178 return QualType(T, 0);
4179
Douglas Gregorc42075a2010-02-04 18:10:26 +00004180 QualType Canon = NamedType;
4181 if (!Canon.isCanonical()) {
4182 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00004183 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
4184 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00004185 (void)CheckT;
4186 }
4187
Bruno Riccid6bd5982018-08-16 10:48:16 +00004188 void *Mem = Allocate(ElaboratedType::totalSizeToAlloc<TagDecl *>(!!OwnedTagDecl),
4189 TypeAlignment);
4190 T = new (Mem) ElaboratedType(Keyword, NNS, NamedType, Canon, OwnedTagDecl);
4191
Douglas Gregor52537682009-03-19 00:18:19 +00004192 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00004193 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00004194 return QualType(T, 0);
4195}
4196
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004197QualType
Jay Foad39c79802011-01-12 09:06:06 +00004198ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004199 llvm::FoldingSetNodeID ID;
4200 ParenType::Profile(ID, InnerType);
4201
Craig Topper36250ad2014-05-12 05:36:57 +00004202 void *InsertPos = nullptr;
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004203 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
4204 if (T)
4205 return QualType(T, 0);
4206
4207 QualType Canon = InnerType;
4208 if (!Canon.isCanonical()) {
4209 Canon = getCanonicalType(InnerType);
4210 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
4211 assert(!CheckT && "Paren canonical type broken");
4212 (void)CheckT;
4213 }
4214
Benjamin Kramer8adeef92015-04-02 16:19:54 +00004215 T = new (*this, TypeAlignment) ParenType(InnerType, Canon);
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004216 Types.push_back(T);
4217 ParenTypes.InsertNode(T, InsertPos);
4218 return QualType(T, 0);
4219}
4220
Douglas Gregor02085352010-03-31 20:19:30 +00004221QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
4222 NestedNameSpecifier *NNS,
4223 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00004224 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00004225 if (Canon.isNull()) {
4226 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Richard Smith74f02342017-01-19 21:00:13 +00004227 if (CanonNNS != NNS)
4228 Canon = getDependentNameType(Keyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00004229 }
4230
4231 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00004232 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00004233
Craig Topper36250ad2014-05-12 05:36:57 +00004234 void *InsertPos = nullptr;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00004235 DependentNameType *T
4236 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00004237 if (T)
4238 return QualType(T, 0);
4239
Benjamin Kramer8adeef92015-04-02 16:19:54 +00004240 T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00004241 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00004242 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00004243 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00004244}
4245
Mike Stump11289f42009-09-09 15:08:12 +00004246QualType
John McCallc392f372010-06-11 00:33:02 +00004247ASTContext::getDependentTemplateSpecializationType(
4248 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00004249 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00004250 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00004251 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00004252 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004253 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00004254 for (unsigned I = 0, E = Args.size(); I != E; ++I)
4255 ArgCopy.push_back(Args[I].getArgument());
David Majnemer6fbeee32016-07-07 04:43:07 +00004256 return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy);
John McCallc392f372010-06-11 00:33:02 +00004257}
4258
4259QualType
4260ASTContext::getDependentTemplateSpecializationType(
4261 ElaboratedTypeKeyword Keyword,
4262 NestedNameSpecifier *NNS,
4263 const IdentifierInfo *Name,
David Majnemer6fbeee32016-07-07 04:43:07 +00004264 ArrayRef<TemplateArgument> Args) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00004265 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor6e068012011-02-28 00:04:36 +00004266 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00004267
Douglas Gregorc42075a2010-02-04 18:10:26 +00004268 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00004269 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00004270 Name, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004271
Craig Topper36250ad2014-05-12 05:36:57 +00004272 void *InsertPos = nullptr;
John McCallc392f372010-06-11 00:33:02 +00004273 DependentTemplateSpecializationType *T
4274 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004275 if (T)
4276 return QualType(T, 0);
4277
John McCallc392f372010-06-11 00:33:02 +00004278 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004279
John McCallc392f372010-06-11 00:33:02 +00004280 ElaboratedTypeKeyword CanonKeyword = Keyword;
4281 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
4282
4283 bool AnyNonCanonArgs = false;
David Majnemer6fbeee32016-07-07 04:43:07 +00004284 unsigned NumArgs = Args.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004285 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00004286 for (unsigned I = 0; I != NumArgs; ++I) {
4287 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
4288 if (!CanonArgs[I].structurallyEquals(Args[I]))
4289 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00004290 }
4291
John McCallc392f372010-06-11 00:33:02 +00004292 QualType Canon;
4293 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
4294 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00004295 Name,
4296 CanonArgs);
John McCallc392f372010-06-11 00:33:02 +00004297
4298 // Find the insert position again.
4299 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
4300 }
4301
4302 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
4303 sizeof(TemplateArgument) * NumArgs),
4304 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00004305 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00004306 Name, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00004307 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00004308 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00004309 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00004310}
4311
Richard Smith32918772017-02-14 00:25:28 +00004312TemplateArgument ASTContext::getInjectedTemplateArg(NamedDecl *Param) {
4313 TemplateArgument Arg;
Eugene Zelenko7855e772018-04-03 00:11:50 +00004314 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
Richard Smith32918772017-02-14 00:25:28 +00004315 QualType ArgType = getTypeDeclType(TTP);
4316 if (TTP->isParameterPack())
4317 ArgType = getPackExpansionType(ArgType, None);
4318
4319 Arg = TemplateArgument(ArgType);
4320 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4321 Expr *E = new (*this) DeclRefExpr(
Bruno Ricci5fc4db72018-12-21 14:10:18 +00004322 *this, NTTP, /*enclosing*/ false,
Richard Smith32918772017-02-14 00:25:28 +00004323 NTTP->getType().getNonLValueExprType(*this),
4324 Expr::getValueKindForType(NTTP->getType()), NTTP->getLocation());
4325
4326 if (NTTP->isParameterPack())
4327 E = new (*this) PackExpansionExpr(DependentTy, E, NTTP->getLocation(),
4328 None);
4329 Arg = TemplateArgument(E);
4330 } else {
4331 auto *TTP = cast<TemplateTemplateParmDecl>(Param);
4332 if (TTP->isParameterPack())
4333 Arg = TemplateArgument(TemplateName(TTP), Optional<unsigned>());
4334 else
4335 Arg = TemplateArgument(TemplateName(TTP));
4336 }
4337
4338 if (Param->isTemplateParameterPack())
4339 Arg = TemplateArgument::CreatePackCopy(*this, Arg);
4340
4341 return Arg;
4342}
4343
Richard Smith43e14d22016-12-23 02:10:11 +00004344void
4345ASTContext::getInjectedTemplateArgs(const TemplateParameterList *Params,
4346 SmallVectorImpl<TemplateArgument> &Args) {
4347 Args.reserve(Args.size() + Params->size());
4348
Richard Smith32918772017-02-14 00:25:28 +00004349 for (NamedDecl *Param : *Params)
4350 Args.push_back(getInjectedTemplateArg(Param));
Richard Smith43e14d22016-12-23 02:10:11 +00004351}
4352
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00004353QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikie05785d12013-02-20 22:23:23 +00004354 Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00004355 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00004356 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00004357
4358 assert(Pattern->containsUnexpandedParameterPack() &&
4359 "Pack expansions must expand one or more parameter packs");
Craig Topper36250ad2014-05-12 05:36:57 +00004360 void *InsertPos = nullptr;
Douglas Gregord2fa7662010-12-20 02:24:11 +00004361 PackExpansionType *T
4362 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
4363 if (T)
4364 return QualType(T, 0);
4365
4366 QualType Canon;
4367 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00004368 Canon = getCanonicalType(Pattern);
4369 // The canonical type might not contain an unexpanded parameter pack, if it
4370 // contains an alias template specialization which ignores one of its
4371 // parameters.
4372 if (Canon->containsUnexpandedParameterPack()) {
Richard Smith8b4e1e22014-07-10 01:20:17 +00004373 Canon = getPackExpansionType(Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00004374
Richard Smith68eea502012-07-16 00:20:35 +00004375 // Find the insert position again, in case we inserted an element into
4376 // PackExpansionTypes and invalidated our insert position.
4377 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
4378 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00004379 }
4380
Benjamin Kramer8adeef92015-04-02 16:19:54 +00004381 T = new (*this, TypeAlignment)
4382 PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00004383 Types.push_back(T);
4384 PackExpansionTypes.InsertNode(T, InsertPos);
Richard Smith8b4e1e22014-07-10 01:20:17 +00004385 return QualType(T, 0);
Douglas Gregord2fa7662010-12-20 02:24:11 +00004386}
4387
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004388/// CmpProtocolNames - Comparison predicate for sorting protocols
4389/// alphabetically.
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00004390static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
4391 ObjCProtocolDecl *const *RHS) {
4392 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004393}
4394
Craig Topper1f26d5b2016-01-03 19:43:23 +00004395static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) {
4396 if (Protocols.empty()) return true;
John McCallfc93cf92009-10-22 22:37:11 +00004397
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00004398 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
4399 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00004400
Craig Topper1f26d5b2016-01-03 19:43:23 +00004401 for (unsigned i = 1; i != Protocols.size(); ++i)
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00004402 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00004403 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00004404 return false;
4405 return true;
4406}
4407
Craig Topper6a8c1512015-10-22 01:56:18 +00004408static void
4409SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) {
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004410 // Sort protocols, keyed by name.
Craig Topper6a8c1512015-10-22 01:56:18 +00004411 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004412
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00004413 // Canonicalize.
Craig Topper6a8c1512015-10-22 01:56:18 +00004414 for (ObjCProtocolDecl *&P : Protocols)
4415 P = P->getCanonicalDecl();
4416
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004417 // Remove duplicates.
Craig Topper6a8c1512015-10-22 01:56:18 +00004418 auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end());
4419 Protocols.erase(ProtocolsEnd, Protocols.end());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004420}
4421
John McCall8b07ec22010-05-15 11:32:37 +00004422QualType ASTContext::getObjCObjectType(QualType BaseType,
4423 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00004424 unsigned NumProtocols) const {
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004425 return getObjCObjectType(BaseType, {},
Douglas Gregorab209d82015-07-07 03:58:42 +00004426 llvm::makeArrayRef(Protocols, NumProtocols),
4427 /*isKindOf=*/false);
Douglas Gregore9d95f12015-07-07 03:57:35 +00004428}
4429
4430QualType ASTContext::getObjCObjectType(
4431 QualType baseType,
4432 ArrayRef<QualType> typeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00004433 ArrayRef<ObjCProtocolDecl *> protocols,
4434 bool isKindOf) const {
Douglas Gregore9d95f12015-07-07 03:57:35 +00004435 // If the base type is an interface and there aren't any protocols or
4436 // type arguments to add, then the interface type will do just fine.
Douglas Gregorab209d82015-07-07 03:58:42 +00004437 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
4438 isa<ObjCInterfaceType>(baseType))
Douglas Gregore9d95f12015-07-07 03:57:35 +00004439 return baseType;
John McCall8b07ec22010-05-15 11:32:37 +00004440
4441 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00004442 llvm::FoldingSetNodeID ID;
Douglas Gregorab209d82015-07-07 03:58:42 +00004443 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
Craig Topper36250ad2014-05-12 05:36:57 +00004444 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00004445 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
4446 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00004447
Douglas Gregore9d95f12015-07-07 03:57:35 +00004448 // Determine the type arguments to be used for canonicalization,
4449 // which may be explicitly specified here or written on the base
4450 // type.
4451 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
4452 if (effectiveTypeArgs.empty()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00004453 if (const auto *baseObject = baseType->getAs<ObjCObjectType>())
Douglas Gregore9d95f12015-07-07 03:57:35 +00004454 effectiveTypeArgs = baseObject->getTypeArgs();
4455 }
John McCallfc93cf92009-10-22 22:37:11 +00004456
Douglas Gregore9d95f12015-07-07 03:57:35 +00004457 // Build the canonical type, which has the canonical base type and a
4458 // sorted-and-uniqued list of protocols and the type arguments
4459 // canonicalized.
4460 QualType canonical;
4461 bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(),
4462 effectiveTypeArgs.end(),
4463 [&](QualType type) {
4464 return type.isCanonical();
4465 });
Craig Topper1f26d5b2016-01-03 19:43:23 +00004466 bool protocolsSorted = areSortedAndUniqued(protocols);
Douglas Gregore9d95f12015-07-07 03:57:35 +00004467 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
4468 // Determine the canonical type arguments.
4469 ArrayRef<QualType> canonTypeArgs;
4470 SmallVector<QualType, 4> canonTypeArgsVec;
4471 if (!typeArgsAreCanonical) {
4472 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
4473 for (auto typeArg : effectiveTypeArgs)
4474 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
4475 canonTypeArgs = canonTypeArgsVec;
John McCallfc93cf92009-10-22 22:37:11 +00004476 } else {
Douglas Gregore9d95f12015-07-07 03:57:35 +00004477 canonTypeArgs = effectiveTypeArgs;
John McCallfc93cf92009-10-22 22:37:11 +00004478 }
4479
Douglas Gregore9d95f12015-07-07 03:57:35 +00004480 ArrayRef<ObjCProtocolDecl *> canonProtocols;
4481 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
4482 if (!protocolsSorted) {
Craig Topper6a8c1512015-10-22 01:56:18 +00004483 canonProtocolsVec.append(protocols.begin(), protocols.end());
4484 SortAndUniqueProtocols(canonProtocolsVec);
4485 canonProtocols = canonProtocolsVec;
Douglas Gregore9d95f12015-07-07 03:57:35 +00004486 } else {
4487 canonProtocols = protocols;
4488 }
4489
4490 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00004491 canonProtocols, isKindOf);
Douglas Gregore9d95f12015-07-07 03:57:35 +00004492
John McCallfc93cf92009-10-22 22:37:11 +00004493 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00004494 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
4495 }
4496
Douglas Gregore9d95f12015-07-07 03:57:35 +00004497 unsigned size = sizeof(ObjCObjectTypeImpl);
4498 size += typeArgs.size() * sizeof(QualType);
4499 size += protocols.size() * sizeof(ObjCProtocolDecl *);
4500 void *mem = Allocate(size, TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004501 auto *T =
Douglas Gregorab209d82015-07-07 03:58:42 +00004502 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
4503 isKindOf);
John McCall8b07ec22010-05-15 11:32:37 +00004504
4505 Types.push_back(T);
4506 ObjCObjectTypes.InsertNode(T, InsertPos);
4507 return QualType(T, 0);
4508}
4509
Manman Ren3569eb52016-09-13 17:03:12 +00004510/// Apply Objective-C protocol qualifiers to the given type.
4511/// If this is for the canonical type of a type parameter, we can apply
4512/// protocol qualifiers on the ObjCObjectPointerType.
4513QualType
4514ASTContext::applyObjCProtocolQualifiers(QualType type,
4515 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
4516 bool allowOnPointerType) const {
4517 hasError = false;
4518
Eugene Zelenko7855e772018-04-03 00:11:50 +00004519 if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
Manman Renc5705ba2016-09-13 17:41:05 +00004520 return getObjCTypeParamType(objT->getDecl(), protocols);
4521 }
4522
Manman Ren3569eb52016-09-13 17:03:12 +00004523 // Apply protocol qualifiers to ObjCObjectPointerType.
4524 if (allowOnPointerType) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00004525 if (const auto *objPtr =
4526 dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
Manman Ren3569eb52016-09-13 17:03:12 +00004527 const ObjCObjectType *objT = objPtr->getObjectType();
4528 // Merge protocol lists and construct ObjCObjectType.
4529 SmallVector<ObjCProtocolDecl*, 8> protocolsVec;
4530 protocolsVec.append(objT->qual_begin(),
4531 objT->qual_end());
4532 protocolsVec.append(protocols.begin(), protocols.end());
4533 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
4534 type = getObjCObjectType(
4535 objT->getBaseType(),
4536 objT->getTypeArgsAsWritten(),
4537 protocols,
4538 objT->isKindOfTypeAsWritten());
4539 return getObjCObjectPointerType(type);
4540 }
4541 }
4542
4543 // Apply protocol qualifiers to ObjCObjectType.
Eugene Zelenko7855e772018-04-03 00:11:50 +00004544 if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
Manman Ren3569eb52016-09-13 17:03:12 +00004545 // FIXME: Check for protocols to which the class type is already
4546 // known to conform.
4547
4548 return getObjCObjectType(objT->getBaseType(),
4549 objT->getTypeArgsAsWritten(),
4550 protocols,
4551 objT->isKindOfTypeAsWritten());
4552 }
4553
4554 // If the canonical type is ObjCObjectType, ...
4555 if (type->isObjCObjectType()) {
4556 // Silently overwrite any existing protocol qualifiers.
4557 // TODO: determine whether that's the right thing to do.
4558
4559 // FIXME: Check for protocols to which the class type is already
4560 // known to conform.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004561 return getObjCObjectType(type, {}, protocols, false);
Manman Ren3569eb52016-09-13 17:03:12 +00004562 }
4563
4564 // id<protocol-list>
4565 if (type->isObjCIdType()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00004566 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004567 type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols,
Manman Ren3569eb52016-09-13 17:03:12 +00004568 objPtr->isKindOfType());
4569 return getObjCObjectPointerType(type);
4570 }
4571
4572 // Class<protocol-list>
4573 if (type->isObjCClassType()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00004574 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004575 type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols,
Manman Ren3569eb52016-09-13 17:03:12 +00004576 objPtr->isKindOfType());
4577 return getObjCObjectPointerType(type);
4578 }
4579
4580 hasError = true;
4581 return type;
4582}
4583
Manman Rene6be26c2016-09-13 17:25:08 +00004584QualType
4585ASTContext::getObjCTypeParamType(const ObjCTypeParamDecl *Decl,
4586 ArrayRef<ObjCProtocolDecl *> protocols,
4587 QualType Canonical) const {
4588 // Look in the folding set for an existing type.
4589 llvm::FoldingSetNodeID ID;
4590 ObjCTypeParamType::Profile(ID, Decl, protocols);
4591 void *InsertPos = nullptr;
4592 if (ObjCTypeParamType *TypeParam =
4593 ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
4594 return QualType(TypeParam, 0);
4595
4596 if (Canonical.isNull()) {
4597 // We canonicalize to the underlying type.
4598 Canonical = getCanonicalType(Decl->getUnderlyingType());
4599 if (!protocols.empty()) {
4600 // Apply the protocol qualifers.
4601 bool hasError;
Richard Trieua986a312018-08-30 01:57:52 +00004602 Canonical = getCanonicalType(applyObjCProtocolQualifiers(
4603 Canonical, protocols, hasError, true /*allowOnPointerType*/));
Manman Rene6be26c2016-09-13 17:25:08 +00004604 assert(!hasError && "Error when apply protocol qualifier to bound type");
4605 }
4606 }
4607
4608 unsigned size = sizeof(ObjCTypeParamType);
4609 size += protocols.size() * sizeof(ObjCProtocolDecl *);
4610 void *mem = Allocate(size, TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004611 auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols);
Manman Rene6be26c2016-09-13 17:25:08 +00004612
4613 Types.push_back(newType);
4614 ObjCTypeParamTypes.InsertNode(newType, InsertPos);
4615 return QualType(newType, 0);
4616}
4617
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004618/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
4619/// protocol list adopt all protocols in QT's qualified-id protocol
4620/// list.
4621bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
4622 ObjCInterfaceDecl *IC) {
4623 if (!QT->isObjCQualifiedIdType())
4624 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00004625
Eugene Zelenko7855e772018-04-03 00:11:50 +00004626 if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004627 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00004628 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004629 if (!IC->ClassImplementsProtocol(Proto, false))
4630 return false;
4631 }
4632 return true;
4633 }
4634 return false;
4635}
4636
4637/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
4638/// QT's qualified-id protocol list adopt all protocols in IDecl's list
4639/// of protocols.
4640bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
4641 ObjCInterfaceDecl *IDecl) {
4642 if (!QT->isObjCQualifiedIdType())
4643 return false;
Eugene Zelenko7855e772018-04-03 00:11:50 +00004644 const auto *OPT = QT->getAs<ObjCObjectPointerType>();
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004645 if (!OPT)
4646 return false;
4647 if (!IDecl->hasDefinition())
4648 return false;
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00004649 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
4650 CollectInheritedProtocols(IDecl, InheritedProtocols);
4651 if (InheritedProtocols.empty())
4652 return false;
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00004653 // Check that if every protocol in list of id<plist> conforms to a protocol
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00004654 // of IDecl's, then bridge casting is ok.
4655 bool Conforms = false;
4656 for (auto *Proto : OPT->quals()) {
4657 Conforms = false;
4658 for (auto *PI : InheritedProtocols) {
4659 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
4660 Conforms = true;
4661 break;
4662 }
4663 }
4664 if (!Conforms)
4665 break;
4666 }
4667 if (Conforms)
4668 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00004669
Aaron Ballman83731462014-03-17 16:14:00 +00004670 for (auto *PI : InheritedProtocols) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004671 // If both the right and left sides have qualifiers.
4672 bool Adopts = false;
Aaron Ballman83731462014-03-17 16:14:00 +00004673 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00004674 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
Aaron Ballman83731462014-03-17 16:14:00 +00004675 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004676 break;
4677 }
4678 if (!Adopts)
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00004679 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004680 }
4681 return true;
4682}
4683
John McCall8b07ec22010-05-15 11:32:37 +00004684/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
4685/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00004686QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00004687 llvm::FoldingSetNodeID ID;
4688 ObjCObjectPointerType::Profile(ID, ObjectT);
4689
Craig Topper36250ad2014-05-12 05:36:57 +00004690 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00004691 if (ObjCObjectPointerType *QT =
4692 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
4693 return QualType(QT, 0);
4694
4695 // Find the canonical object type.
4696 QualType Canonical;
4697 if (!ObjectT.isCanonical()) {
4698 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
4699
4700 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00004701 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
4702 }
4703
Douglas Gregorf85bee62010-02-08 22:59:26 +00004704 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00004705 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004706 auto *QType =
John McCall8b07ec22010-05-15 11:32:37 +00004707 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00004708
Steve Narofffb4330f2009-06-17 22:40:22 +00004709 Types.push_back(QType);
4710 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00004711 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00004712}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004713
Douglas Gregor1c283312010-08-11 12:19:30 +00004714/// getObjCInterfaceType - Return the unique reference to the type for the
4715/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00004716QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
4717 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00004718 if (Decl->TypeForDecl)
4719 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004720
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00004721 if (PrevDecl) {
4722 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
4723 Decl->TypeForDecl = PrevDecl->TypeForDecl;
4724 return QualType(PrevDecl->TypeForDecl, 0);
4725 }
4726
Douglas Gregor7671e532011-12-16 16:34:57 +00004727 // Prefer the definition, if there is one.
4728 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
4729 Decl = Def;
Fangrui Song6907ce22018-07-30 19:24:48 +00004730
Douglas Gregor1c283312010-08-11 12:19:30 +00004731 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004732 auto *T = new (Mem) ObjCInterfaceType(Decl);
Douglas Gregor1c283312010-08-11 12:19:30 +00004733 Decl->TypeForDecl = T;
4734 Types.push_back(T);
4735 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00004736}
4737
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004738/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
4739/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00004740/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00004741/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00004742/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00004743QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00004744 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004745 if (tofExpr->isTypeDependent()) {
4746 llvm::FoldingSetNodeID ID;
4747 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00004748
Craig Topper36250ad2014-05-12 05:36:57 +00004749 void *InsertPos = nullptr;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004750 DependentTypeOfExprType *Canon
4751 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
4752 if (Canon) {
4753 // We already have a "canonical" version of an identical, dependent
4754 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00004755 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004756 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00004757 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004758 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00004759 Canon
4760 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004761 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
4762 toe = Canon;
4763 }
4764 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00004765 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00004766 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00004767 }
Steve Naroffa773cd52007-08-01 18:02:17 +00004768 Types.push_back(toe);
4769 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00004770}
4771
Steve Naroffa773cd52007-08-01 18:02:17 +00004772/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
Richard Smith8eb1d322014-06-05 20:13:13 +00004773/// TypeOfType nodes. The only motivation to unique these nodes would be
Steve Naroffa773cd52007-08-01 18:02:17 +00004774/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Richard Smith8eb1d322014-06-05 20:13:13 +00004775/// an issue. This doesn't affect the type checker, since it operates
4776/// on canonical types (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00004777QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00004778 QualType Canonical = getCanonicalType(tofType);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004779 auto *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00004780 Types.push_back(tot);
4781 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00004782}
4783
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004784/// Unlike many "get<Type>" functions, we don't unique DecltypeType
Richard Smith8eb1d322014-06-05 20:13:13 +00004785/// nodes. This would never be helpful, since each such type has its own
4786/// expression, and would not give a significant memory saving, since there
4787/// is an Expr tree under each such type.
Douglas Gregor81495f32012-02-12 18:42:33 +00004788QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00004789 DecltypeType *dt;
Richard Smith8eb1d322014-06-05 20:13:13 +00004790
4791 // C++11 [temp.type]p2:
Douglas Gregor678d76c2011-07-01 01:22:09 +00004792 // If an expression e involves a template parameter, decltype(e) denotes a
Richard Smith8eb1d322014-06-05 20:13:13 +00004793 // unique dependent type. Two such decltype-specifiers refer to the same
4794 // type only if their expressions are equivalent (14.5.6.1).
Douglas Gregor678d76c2011-07-01 01:22:09 +00004795 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00004796 llvm::FoldingSetNodeID ID;
4797 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00004798
Craig Topper36250ad2014-05-12 05:36:57 +00004799 void *InsertPos = nullptr;
Douglas Gregora21f6c32009-07-30 23:36:40 +00004800 DependentDecltypeType *Canon
4801 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
Richard Smith8eb1d322014-06-05 20:13:13 +00004802 if (!Canon) {
Yaron Keren633e14a2016-11-29 10:08:20 +00004803 // Build a new, canonical decltype(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00004804 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00004805 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
Douglas Gregora21f6c32009-07-30 23:36:40 +00004806 }
Richard Smith8eb1d322014-06-05 20:13:13 +00004807 dt = new (*this, TypeAlignment)
4808 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
Douglas Gregora21f6c32009-07-30 23:36:40 +00004809 } else {
Richard Smith8eb1d322014-06-05 20:13:13 +00004810 dt = new (*this, TypeAlignment)
4811 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00004812 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00004813 Types.push_back(dt);
4814 return QualType(dt, 0);
4815}
4816
Alexis Hunte852b102011-05-24 22:41:36 +00004817/// getUnaryTransformationType - We don't unique these, since the memory
4818/// savings are minimal and these are rare.
4819QualType ASTContext::getUnaryTransformType(QualType BaseType,
4820 QualType UnderlyingType,
4821 UnaryTransformType::UTTKind Kind)
4822 const {
Vassil Vassilevbab6f962016-03-30 22:18:29 +00004823 UnaryTransformType *ut = nullptr;
4824
4825 if (BaseType->isDependentType()) {
4826 // Look in the folding set for an existing type.
4827 llvm::FoldingSetNodeID ID;
4828 DependentUnaryTransformType::Profile(ID, getCanonicalType(BaseType), Kind);
4829
4830 void *InsertPos = nullptr;
4831 DependentUnaryTransformType *Canon
4832 = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
4833
4834 if (!Canon) {
4835 // Build a new, canonical __underlying_type(type) type.
4836 Canon = new (*this, TypeAlignment)
4837 DependentUnaryTransformType(*this, getCanonicalType(BaseType),
4838 Kind);
4839 DependentUnaryTransformTypes.InsertNode(Canon, InsertPos);
4840 }
4841 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4842 QualType(), Kind,
4843 QualType(Canon, 0));
4844 } else {
4845 QualType CanonType = getCanonicalType(UnderlyingType);
4846 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4847 UnderlyingType, Kind,
4848 CanonType);
4849 }
4850 Types.push_back(ut);
4851 return QualType(ut, 0);
Alexis Hunte852b102011-05-24 22:41:36 +00004852}
4853
Richard Smith2a7d4812013-05-04 07:00:32 +00004854/// getAutoType - Return the uniqued reference to the 'auto' type which has been
4855/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
4856/// canonical deduced-but-dependent 'auto' type.
Richard Smithe301ba22015-11-11 02:02:15 +00004857QualType ASTContext::getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004858 bool IsDependent) const {
Richard Smithe301ba22015-11-11 02:02:15 +00004859 if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto && !IsDependent)
Richard Smith2a7d4812013-05-04 07:00:32 +00004860 return getAutoDeductType();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004861
Richard Smith2a7d4812013-05-04 07:00:32 +00004862 // Look in the folding set for an existing type.
Craig Topper36250ad2014-05-12 05:36:57 +00004863 void *InsertPos = nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +00004864 llvm::FoldingSetNodeID ID;
Richard Smithe301ba22015-11-11 02:02:15 +00004865 AutoType::Profile(ID, DeducedType, Keyword, IsDependent);
Richard Smith2a7d4812013-05-04 07:00:32 +00004866 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
4867 return QualType(AT, 0);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004868
Eugene Zelenko7855e772018-04-03 00:11:50 +00004869 auto *AT = new (*this, TypeAlignment)
4870 AutoType(DeducedType, Keyword, IsDependent);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004871 Types.push_back(AT);
4872 if (InsertPos)
4873 AutoTypes.InsertNode(AT, InsertPos);
4874 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00004875}
4876
Richard Smith600b5262017-01-26 20:40:47 +00004877/// Return the uniqued reference to the deduced template specialization type
4878/// which has been deduced to the given type, or to the canonical undeduced
4879/// such type, or the canonical deduced-but-dependent such type.
4880QualType ASTContext::getDeducedTemplateSpecializationType(
4881 TemplateName Template, QualType DeducedType, bool IsDependent) const {
4882 // Look in the folding set for an existing type.
4883 void *InsertPos = nullptr;
4884 llvm::FoldingSetNodeID ID;
4885 DeducedTemplateSpecializationType::Profile(ID, Template, DeducedType,
4886 IsDependent);
4887 if (DeducedTemplateSpecializationType *DTST =
4888 DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
4889 return QualType(DTST, 0);
4890
Eugene Zelenko7855e772018-04-03 00:11:50 +00004891 auto *DTST = new (*this, TypeAlignment)
Richard Smith600b5262017-01-26 20:40:47 +00004892 DeducedTemplateSpecializationType(Template, DeducedType, IsDependent);
4893 Types.push_back(DTST);
4894 if (InsertPos)
4895 DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos);
4896 return QualType(DTST, 0);
4897}
4898
Eli Friedman0dfb8892011-10-06 23:00:33 +00004899/// getAtomicType - Return the uniqued reference to the atomic type for
4900/// the given value type.
4901QualType ASTContext::getAtomicType(QualType T) const {
4902 // Unique pointers, to guarantee there is only one pointer of a particular
4903 // structure.
4904 llvm::FoldingSetNodeID ID;
4905 AtomicType::Profile(ID, T);
4906
Craig Topper36250ad2014-05-12 05:36:57 +00004907 void *InsertPos = nullptr;
Eli Friedman0dfb8892011-10-06 23:00:33 +00004908 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
4909 return QualType(AT, 0);
4910
4911 // If the atomic value type isn't canonical, this won't be a canonical type
4912 // either, so fill in the canonical type field.
4913 QualType Canonical;
4914 if (!T.isCanonical()) {
4915 Canonical = getAtomicType(getCanonicalType(T));
4916
4917 // Get the new insert position for the node we care about.
4918 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00004919 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Eli Friedman0dfb8892011-10-06 23:00:33 +00004920 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00004921 auto *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
Eli Friedman0dfb8892011-10-06 23:00:33 +00004922 Types.push_back(New);
4923 AtomicTypes.InsertNode(New, InsertPos);
4924 return QualType(New, 0);
4925}
4926
Richard Smith02e85f32011-04-14 22:09:26 +00004927/// getAutoDeductType - Get type pattern for deducing against 'auto'.
4928QualType ASTContext::getAutoDeductType() const {
4929 if (AutoDeductTy.isNull())
Richard Smith2a7d4812013-05-04 07:00:32 +00004930 AutoDeductTy = QualType(
Richard Smithe301ba22015-11-11 02:02:15 +00004931 new (*this, TypeAlignment) AutoType(QualType(), AutoTypeKeyword::Auto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004932 /*dependent*/false),
Richard Smith2a7d4812013-05-04 07:00:32 +00004933 0);
Richard Smith02e85f32011-04-14 22:09:26 +00004934 return AutoDeductTy;
4935}
4936
4937/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
4938QualType ASTContext::getAutoRRefDeductType() const {
4939 if (AutoRRefDeductTy.isNull())
4940 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
4941 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
4942 return AutoRRefDeductTy;
4943}
4944
Chris Lattnerfb072462007-01-23 05:45:31 +00004945/// getTagDeclType - Return the unique reference to the type for the
4946/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00004947QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004948 assert(Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00004949 // FIXME: What is the design on getTagDeclType when it requires casting
4950 // away const? mutable?
4951 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00004952}
4953
Mike Stump11289f42009-09-09 15:08:12 +00004954/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
4955/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
4956/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00004957CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00004958 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00004959}
Chris Lattnerfb072462007-01-23 05:45:31 +00004960
Fangrui Song6907ce22018-07-30 19:24:48 +00004961/// Return the unique signed counterpart of the integer type
Alexander Shaposhnikov1e898d92017-07-14 17:30:14 +00004962/// corresponding to size_t.
4963CanQualType ASTContext::getSignedSizeType() const {
4964 return getFromTargetType(Target->getSignedSizeType());
4965}
4966
Hans Wennborg27541db2011-10-27 08:29:09 +00004967/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
4968CanQualType ASTContext::getIntMaxType() const {
4969 return getFromTargetType(Target->getIntMaxType());
4970}
4971
4972/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
4973CanQualType ASTContext::getUIntMaxType() const {
4974 return getFromTargetType(Target->getUIntMaxType());
4975}
4976
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00004977/// getSignedWCharType - Return the type of "signed wchar_t".
4978/// Used when in C++, as a GCC extension.
4979QualType ASTContext::getSignedWCharType() const {
4980 // FIXME: derive from "Target" ?
4981 return WCharTy;
4982}
4983
4984/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
4985/// Used when in C++, as a GCC extension.
4986QualType ASTContext::getUnsignedWCharType() const {
4987 // FIXME: derive from "Target" ?
4988 return UnsignedIntTy;
4989}
4990
Enea Zaffanellaf11ceb62013-01-26 17:08:37 +00004991QualType ASTContext::getIntPtrType() const {
4992 return getFromTargetType(Target->getIntPtrType());
4993}
4994
4995QualType ASTContext::getUIntPtrType() const {
4996 return getCorrespondingUnsignedType(getIntPtrType());
4997}
4998
Hans Wennborg27541db2011-10-27 08:29:09 +00004999/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00005000/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
5001QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00005002 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00005003}
5004
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005005/// Return the unique unsigned counterpart of "ptrdiff_t"
Alexander Shaposhnikov195b25c2017-09-28 23:11:31 +00005006/// integer type. The standard (C11 7.21.6.1p7) refers to this type
5007/// in the definition of %tu format specifier.
5008QualType ASTContext::getUnsignedPointerDiffType() const {
5009 return getFromTargetType(Target->getUnsignedPtrDiffType(0));
5010}
5011
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005012/// Return the unique type for "pid_t" defined in
Eli Friedman4e91899e2012-11-27 02:58:24 +00005013/// <sys/types.h>. We need this to compute the correct type for vfork().
5014QualType ASTContext::getProcessIDType() const {
5015 return getFromTargetType(Target->getProcessIDType());
5016}
5017
Chris Lattnera21ad802008-04-02 05:18:44 +00005018//===----------------------------------------------------------------------===//
5019// Type Operators
5020//===----------------------------------------------------------------------===//
5021
Jay Foad39c79802011-01-12 09:06:06 +00005022CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00005023 // Push qualifiers into arrays, and then discard any remaining
5024 // qualifiers.
5025 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00005026 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00005027 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00005028 QualType Result;
5029 if (isa<ArrayType>(Ty)) {
5030 Result = getArrayDecayedType(QualType(Ty,0));
5031 } else if (isa<FunctionType>(Ty)) {
5032 Result = getPointerType(QualType(Ty, 0));
5033 } else {
5034 Result = QualType(Ty, 0);
5035 }
5036
5037 return CanQualType::CreateUnsafe(Result);
5038}
5039
John McCall6c9dd522011-01-18 07:41:22 +00005040QualType ASTContext::getUnqualifiedArrayType(QualType type,
5041 Qualifiers &quals) {
5042 SplitQualType splitType = type.getSplitUnqualifiedType();
5043
5044 // FIXME: getSplitUnqualifiedType() actually walks all the way to
5045 // the unqualified desugared type and then drops it on the floor.
5046 // We then have to strip that sugar back off with
5047 // getUnqualifiedDesugaredType(), which is silly.
Eugene Zelenko7855e772018-04-03 00:11:50 +00005048 const auto *AT =
5049 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00005050
5051 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00005052 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00005053 quals = splitType.Quals;
5054 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00005055 }
5056
John McCall6c9dd522011-01-18 07:41:22 +00005057 // Otherwise, recurse on the array's element type.
5058 QualType elementType = AT->getElementType();
5059 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
5060
5061 // If that didn't change the element type, AT has no qualifiers, so we
5062 // can just use the results in splitType.
5063 if (elementType == unqualElementType) {
5064 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00005065 quals = splitType.Quals;
5066 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00005067 }
5068
5069 // Otherwise, add in the qualifiers from the outermost type, then
5070 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00005071 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00005072
Eugene Zelenko7855e772018-04-03 00:11:50 +00005073 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00005074 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00005075 CAT->getSizeModifier(), 0);
5076 }
5077
Eugene Zelenko7855e772018-04-03 00:11:50 +00005078 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00005079 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00005080 }
5081
Eugene Zelenko7855e772018-04-03 00:11:50 +00005082 if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00005083 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00005084 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00005085 VAT->getSizeModifier(),
5086 VAT->getIndexTypeCVRQualifiers(),
5087 VAT->getBracketsRange());
5088 }
5089
Eugene Zelenko7855e772018-04-03 00:11:50 +00005090 const auto *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00005091 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00005092 DSAT->getSizeModifier(), 0,
5093 SourceRange());
5094}
5095
Richard Smitha3405ff2018-07-11 00:19:19 +00005096/// Attempt to unwrap two types that may both be array types with the same bound
5097/// (or both be array types of unknown bound) for the purpose of comparing the
5098/// cv-decomposition of two types per C++ [conv.qual].
Richard Smith5407d4f2018-07-18 20:13:36 +00005099bool ASTContext::UnwrapSimilarArrayTypes(QualType &T1, QualType &T2) {
5100 bool UnwrappedAny = false;
Richard Smitha3405ff2018-07-11 00:19:19 +00005101 while (true) {
Richard Smith5407d4f2018-07-18 20:13:36 +00005102 auto *AT1 = getAsArrayType(T1);
5103 if (!AT1) return UnwrappedAny;
Richard Smitha3405ff2018-07-11 00:19:19 +00005104
Richard Smith5407d4f2018-07-18 20:13:36 +00005105 auto *AT2 = getAsArrayType(T2);
5106 if (!AT2) return UnwrappedAny;
Richard Smitha3405ff2018-07-11 00:19:19 +00005107
5108 // If we don't have two array types with the same constant bound nor two
5109 // incomplete array types, we've unwrapped everything we can.
5110 if (auto *CAT1 = dyn_cast<ConstantArrayType>(AT1)) {
5111 auto *CAT2 = dyn_cast<ConstantArrayType>(AT2);
5112 if (!CAT2 || CAT1->getSize() != CAT2->getSize())
Richard Smith5407d4f2018-07-18 20:13:36 +00005113 return UnwrappedAny;
Richard Smitha3405ff2018-07-11 00:19:19 +00005114 } else if (!isa<IncompleteArrayType>(AT1) ||
5115 !isa<IncompleteArrayType>(AT2)) {
Richard Smith5407d4f2018-07-18 20:13:36 +00005116 return UnwrappedAny;
Richard Smitha3405ff2018-07-11 00:19:19 +00005117 }
5118
5119 T1 = AT1->getElementType();
5120 T2 = AT2->getElementType();
Richard Smith5407d4f2018-07-18 20:13:36 +00005121 UnwrappedAny = true;
Richard Smitha3405ff2018-07-11 00:19:19 +00005122 }
5123}
5124
5125/// Attempt to unwrap two types that may be similar (C++ [conv.qual]).
5126///
5127/// If T1 and T2 are both pointer types of the same kind, or both array types
5128/// with the same bound, unwraps layers from T1 and T2 until a pointer type is
5129/// unwrapped. Top-level qualifiers on T1 and T2 are ignored.
5130///
5131/// This function will typically be called in a loop that successively
5132/// "unwraps" pointer and pointer-to-member types to compare them at each
5133/// level.
5134///
5135/// \return \c true if a pointer type was unwrapped, \c false if we reached a
5136/// pair of types that can't be unwrapped further.
5137bool ASTContext::UnwrapSimilarTypes(QualType &T1, QualType &T2) {
Richard Smith5407d4f2018-07-18 20:13:36 +00005138 UnwrapSimilarArrayTypes(T1, T2);
Richard Smitha3405ff2018-07-11 00:19:19 +00005139
Eugene Zelenko7855e772018-04-03 00:11:50 +00005140 const auto *T1PtrType = T1->getAs<PointerType>();
5141 const auto *T2PtrType = T2->getAs<PointerType>();
Douglas Gregor1fc3d662010-06-09 03:53:18 +00005142 if (T1PtrType && T2PtrType) {
5143 T1 = T1PtrType->getPointeeType();
5144 T2 = T2PtrType->getPointeeType();
5145 return true;
5146 }
Richard Smith5407d4f2018-07-18 20:13:36 +00005147
Eugene Zelenko7855e772018-04-03 00:11:50 +00005148 const auto *T1MPType = T1->getAs<MemberPointerType>();
5149 const auto *T2MPType = T2->getAs<MemberPointerType>();
Fangrui Song6907ce22018-07-30 19:24:48 +00005150 if (T1MPType && T2MPType &&
5151 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
Douglas Gregor1fc3d662010-06-09 03:53:18 +00005152 QualType(T2MPType->getClass(), 0))) {
5153 T1 = T1MPType->getPointeeType();
5154 T2 = T2MPType->getPointeeType();
5155 return true;
5156 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005157
Erik Pilkingtonfa983902018-10-30 20:31:30 +00005158 if (getLangOpts().ObjC) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00005159 const auto *T1OPType = T1->getAs<ObjCObjectPointerType>();
5160 const auto *T2OPType = T2->getAs<ObjCObjectPointerType>();
Douglas Gregor1fc3d662010-06-09 03:53:18 +00005161 if (T1OPType && T2OPType) {
5162 T1 = T1OPType->getPointeeType();
5163 T2 = T2OPType->getPointeeType();
5164 return true;
5165 }
5166 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005167
Douglas Gregor1fc3d662010-06-09 03:53:18 +00005168 // FIXME: Block pointers, too?
Fangrui Song6907ce22018-07-30 19:24:48 +00005169
Douglas Gregor1fc3d662010-06-09 03:53:18 +00005170 return false;
5171}
5172
Richard Smitha3405ff2018-07-11 00:19:19 +00005173bool ASTContext::hasSimilarType(QualType T1, QualType T2) {
5174 while (true) {
5175 Qualifiers Quals;
5176 T1 = getUnqualifiedArrayType(T1, Quals);
5177 T2 = getUnqualifiedArrayType(T2, Quals);
5178 if (hasSameType(T1, T2))
5179 return true;
5180 if (!UnwrapSimilarTypes(T1, T2))
5181 return false;
5182 }
5183}
5184
5185bool ASTContext::hasCvrSimilarType(QualType T1, QualType T2) {
5186 while (true) {
5187 Qualifiers Quals1, Quals2;
5188 T1 = getUnqualifiedArrayType(T1, Quals1);
5189 T2 = getUnqualifiedArrayType(T2, Quals2);
5190
5191 Quals1.removeCVRQualifiers();
5192 Quals2.removeCVRQualifiers();
5193 if (Quals1 != Quals2)
5194 return false;
5195
5196 if (hasSameType(T1, T2))
5197 return true;
5198
5199 if (!UnwrapSimilarTypes(T1, T2))
5200 return false;
5201 }
5202}
5203
Jay Foad39c79802011-01-12 09:06:06 +00005204DeclarationNameInfo
5205ASTContext::getNameForTemplate(TemplateName Name,
5206 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00005207 switch (Name.getKind()) {
5208 case TemplateName::QualifiedTemplate:
5209 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005210 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00005211 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
5212 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005213
John McCalld9dfe3a2011-06-30 08:33:18 +00005214 case TemplateName::OverloadedTemplate: {
5215 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
5216 // DNInfo work in progress: CHECKME: what about DNLoc?
5217 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
5218 }
5219
5220 case TemplateName::DependentTemplate: {
5221 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005222 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00005223 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005224 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
5225 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00005226 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005227 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
5228 // DNInfo work in progress: FIXME: source locations?
5229 DeclarationNameLoc DNLoc;
5230 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
5231 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
5232 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00005233 }
5234 }
5235
John McCalld9dfe3a2011-06-30 08:33:18 +00005236 case TemplateName::SubstTemplateTemplateParm: {
5237 SubstTemplateTemplateParmStorage *subst
5238 = Name.getAsSubstTemplateTemplateParm();
5239 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
5240 NameLoc);
5241 }
5242
5243 case TemplateName::SubstTemplateTemplateParmPack: {
5244 SubstTemplateTemplateParmPackStorage *subst
5245 = Name.getAsSubstTemplateTemplateParmPack();
5246 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
5247 NameLoc);
5248 }
5249 }
5250
5251 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00005252}
5253
Jay Foad39c79802011-01-12 09:06:06 +00005254TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00005255 switch (Name.getKind()) {
5256 case TemplateName::QualifiedTemplate:
5257 case TemplateName::Template: {
5258 TemplateDecl *Template = Name.getAsTemplateDecl();
Eugene Zelenko7855e772018-04-03 00:11:50 +00005259 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00005260 Template = getCanonicalTemplateTemplateParmDecl(TTP);
Fangrui Song6907ce22018-07-30 19:24:48 +00005261
Douglas Gregor7dbfb462010-06-16 21:09:37 +00005262 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00005263 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00005264 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00005265
John McCalld9dfe3a2011-06-30 08:33:18 +00005266 case TemplateName::OverloadedTemplate:
5267 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00005268
John McCalld9dfe3a2011-06-30 08:33:18 +00005269 case TemplateName::DependentTemplate: {
5270 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
5271 assert(DTN && "Non-dependent template names must refer to template decls.");
5272 return DTN->CanonicalTemplateName;
5273 }
5274
5275 case TemplateName::SubstTemplateTemplateParm: {
5276 SubstTemplateTemplateParmStorage *subst
5277 = Name.getAsSubstTemplateTemplateParm();
5278 return getCanonicalTemplateName(subst->getReplacement());
5279 }
5280
5281 case TemplateName::SubstTemplateTemplateParmPack: {
5282 SubstTemplateTemplateParmPackStorage *subst
5283 = Name.getAsSubstTemplateTemplateParmPack();
5284 TemplateTemplateParmDecl *canonParameter
5285 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
5286 TemplateArgument canonArgPack
5287 = getCanonicalTemplateArgument(subst->getArgumentPack());
5288 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
5289 }
5290 }
5291
5292 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00005293}
5294
Douglas Gregoradee3e32009-11-11 23:06:43 +00005295bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
5296 X = getCanonicalTemplateName(X);
5297 Y = getCanonicalTemplateName(Y);
5298 return X.getAsVoidPointer() == Y.getAsVoidPointer();
5299}
5300
Mike Stump11289f42009-09-09 15:08:12 +00005301TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00005302ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00005303 switch (Arg.getKind()) {
5304 case TemplateArgument::Null:
5305 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00005306
Douglas Gregora8e02e72009-07-28 23:00:59 +00005307 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00005308 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00005309
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005310 case TemplateArgument::Declaration: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00005311 auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
David Blaikie952a9b12014-10-17 18:00:12 +00005312 return TemplateArgument(D, Arg.getParamTypeForDecl());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005313 }
Mike Stump11289f42009-09-09 15:08:12 +00005314
Eli Friedmanb826a002012-09-26 02:36:12 +00005315 case TemplateArgument::NullPtr:
5316 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
5317 /*isNullPtr*/true);
5318
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005319 case TemplateArgument::Template:
5320 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005321
5322 case TemplateArgument::TemplateExpansion:
5323 return TemplateArgument(getCanonicalTemplateName(
5324 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00005325 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005326
Douglas Gregora8e02e72009-07-28 23:00:59 +00005327 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00005328 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00005329
Douglas Gregora8e02e72009-07-28 23:00:59 +00005330 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00005331 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00005332
Douglas Gregora8e02e72009-07-28 23:00:59 +00005333 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00005334 if (Arg.pack_size() == 0)
5335 return Arg;
Fangrui Song6907ce22018-07-30 19:24:48 +00005336
Eugene Zelenko7855e772018-04-03 00:11:50 +00005337 auto *CanonArgs = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00005338 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00005339 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00005340 AEnd = Arg.pack_end();
5341 A != AEnd; (void)++A, ++Idx)
5342 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00005343
Benjamin Kramercce63472015-08-05 09:40:22 +00005344 return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size()));
Douglas Gregora8e02e72009-07-28 23:00:59 +00005345 }
5346 }
5347
5348 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00005349 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00005350}
5351
Douglas Gregor333489b2009-03-27 23:10:48 +00005352NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00005353ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00005354 if (!NNS)
Craig Topper36250ad2014-05-12 05:36:57 +00005355 return nullptr;
Douglas Gregor333489b2009-03-27 23:10:48 +00005356
5357 switch (NNS->getKind()) {
5358 case NestedNameSpecifier::Identifier:
5359 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00005360 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00005361 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
5362 NNS->getAsIdentifier());
5363
5364 case NestedNameSpecifier::Namespace:
5365 // A namespace is canonical; build a nested-name-specifier with
5366 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00005367 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00005368 NNS->getAsNamespace()->getOriginalNamespace());
5369
5370 case NestedNameSpecifier::NamespaceAlias:
5371 // A namespace is canonical; build a nested-name-specifier with
5372 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00005373 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00005374 NNS->getAsNamespaceAlias()->getNamespace()
5375 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00005376
5377 case NestedNameSpecifier::TypeSpec:
5378 case NestedNameSpecifier::TypeSpecWithTemplate: {
5379 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Fangrui Song6907ce22018-07-30 19:24:48 +00005380
Douglas Gregor3ade5702010-11-04 00:09:33 +00005381 // If we have some kind of dependent-named type (e.g., "typename T::type"),
5382 // break it apart into its prefix and identifier, then reconsititute those
5383 // as the canonical nested-name-specifier. This is required to canonicalize
5384 // a dependent nested-name-specifier involving typedefs of dependent-name
5385 // types, e.g.,
5386 // typedef typename T::type T1;
5387 // typedef typename T1::type T2;
Eugene Zelenko7855e772018-04-03 00:11:50 +00005388 if (const auto *DNT = T->getAs<DependentNameType>())
Fangrui Song6907ce22018-07-30 19:24:48 +00005389 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00005390 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00005391
Eli Friedman5358a0a2012-03-03 04:09:56 +00005392 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
5393 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
5394 // first place?
Craig Topper36250ad2014-05-12 05:36:57 +00005395 return NestedNameSpecifier::Create(*this, nullptr, false,
5396 const_cast<Type *>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00005397 }
5398
5399 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00005400 case NestedNameSpecifier::Super:
5401 // The global specifier and __super specifer are canonical and unique.
Douglas Gregor333489b2009-03-27 23:10:48 +00005402 return NNS;
5403 }
5404
David Blaikie8a40f702012-01-17 06:56:22 +00005405 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00005406}
5407
Jay Foad39c79802011-01-12 09:06:06 +00005408const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00005409 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005410 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00005411 // Handle the common positive case fast.
Eugene Zelenko7855e772018-04-03 00:11:50 +00005412 if (const auto *AT = dyn_cast<ArrayType>(T))
Chris Lattner7adf0762008-08-04 07:31:14 +00005413 return AT;
5414 }
Mike Stump11289f42009-09-09 15:08:12 +00005415
John McCall8ccfcb52009-09-24 19:53:00 +00005416 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00005417 if (!isa<ArrayType>(T.getCanonicalType()))
Craig Topper36250ad2014-05-12 05:36:57 +00005418 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00005419
John McCall8ccfcb52009-09-24 19:53:00 +00005420 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00005421 // implements C99 6.7.3p8: "If the specification of an array type includes
5422 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00005423
Chris Lattner7adf0762008-08-04 07:31:14 +00005424 // If we get here, we either have type qualifiers on the type, or we have
5425 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00005426 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00005427
John McCall33ddac02011-01-19 10:06:00 +00005428 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00005429 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00005430
Chris Lattner7adf0762008-08-04 07:31:14 +00005431 // If we have a simple case, just return now.
Eugene Zelenko7855e772018-04-03 00:11:50 +00005432 const auto *ATy = dyn_cast<ArrayType>(split.Ty);
Craig Topper36250ad2014-05-12 05:36:57 +00005433 if (!ATy || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00005434 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00005435
Chris Lattner7adf0762008-08-04 07:31:14 +00005436 // Otherwise, we have an array and we have qualifiers on it. Push the
5437 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00005438 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00005439
Eugene Zelenko7855e772018-04-03 00:11:50 +00005440 if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy))
Chris Lattner7adf0762008-08-04 07:31:14 +00005441 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
5442 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00005443 CAT->getIndexTypeCVRQualifiers()));
Eugene Zelenko7855e772018-04-03 00:11:50 +00005444 if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy))
Chris Lattner7adf0762008-08-04 07:31:14 +00005445 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
5446 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00005447 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00005448
Eugene Zelenko7855e772018-04-03 00:11:50 +00005449 if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy))
Douglas Gregor4619e432008-12-05 23:32:09 +00005450 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00005451 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00005452 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00005453 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00005454 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00005455 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00005456
Eugene Zelenko7855e772018-04-03 00:11:50 +00005457 const auto *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00005458 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00005459 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00005460 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00005461 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00005462 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00005463}
5464
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00005465QualType ASTContext::getAdjustedParameterType(QualType T) const {
Reid Kleckner8a365022013-06-24 17:51:48 +00005466 if (T->isArrayType() || T->isFunctionType())
5467 return getDecayedType(T);
5468 return T;
Douglas Gregor84280642011-07-12 04:42:08 +00005469}
5470
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00005471QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00005472 T = getVariableArrayDecayedType(T);
5473 T = getAdjustedParameterType(T);
5474 return T.getUnqualifiedType();
5475}
5476
David Majnemerd09a51c2015-03-03 01:50:05 +00005477QualType ASTContext::getExceptionObjectType(QualType T) const {
5478 // C++ [except.throw]p3:
5479 // A throw-expression initializes a temporary object, called the exception
5480 // object, the type of which is determined by removing any top-level
5481 // cv-qualifiers from the static type of the operand of throw and adjusting
5482 // the type from "array of T" or "function returning T" to "pointer to T"
5483 // or "pointer to function returning T", [...]
5484 T = getVariableArrayDecayedType(T);
5485 if (T->isArrayType() || T->isFunctionType())
5486 T = getDecayedType(T);
5487 return T.getUnqualifiedType();
5488}
5489
Chris Lattnera21ad802008-04-02 05:18:44 +00005490/// getArrayDecayedType - Return the properly qualified result of decaying the
5491/// specified array type to a pointer. This operation is non-trivial when
5492/// handling typedefs etc. The canonical type of "T" must be an array type,
5493/// this returns a pointer to a properly qualified element of the array.
5494///
5495/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00005496QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00005497 // Get the element type with 'getAsArrayType' so that we don't lose any
5498 // typedefs in the element type of the array. This also handles propagation
5499 // of type qualifiers from the array type into the element type if present
5500 // (C99 6.7.3p8).
5501 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
5502 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00005503
Chris Lattner7adf0762008-08-04 07:31:14 +00005504 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00005505
5506 // int x[restrict 4] -> int *restrict
Jordan Rose303e2f12016-11-10 23:28:17 +00005507 QualType Result = getQualifiedType(PtrTy,
5508 PrettyArrayType->getIndexTypeQualifiers());
5509
5510 // int x[_Nullable] -> int * _Nullable
5511 if (auto Nullability = Ty->getNullability(*this)) {
5512 Result = const_cast<ASTContext *>(this)->getAttributedType(
5513 AttributedType::getNullabilityAttrKind(*Nullability), Result, Result);
5514 }
5515 return Result;
Chris Lattnera21ad802008-04-02 05:18:44 +00005516}
5517
John McCall33ddac02011-01-19 10:06:00 +00005518QualType ASTContext::getBaseElementType(const ArrayType *array) const {
5519 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00005520}
5521
John McCall33ddac02011-01-19 10:06:00 +00005522QualType ASTContext::getBaseElementType(QualType type) const {
5523 Qualifiers qs;
5524 while (true) {
5525 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00005526 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00005527 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00005528
John McCall33ddac02011-01-19 10:06:00 +00005529 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00005530 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00005531 }
Mike Stump11289f42009-09-09 15:08:12 +00005532
John McCall33ddac02011-01-19 10:06:00 +00005533 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00005534}
5535
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00005536/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00005537uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00005538ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
5539 uint64_t ElementCount = 1;
5540 do {
5541 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00005542 CA = dyn_cast_or_null<ConstantArrayType>(
5543 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00005544 } while (CA);
5545 return ElementCount;
5546}
5547
Steve Naroff0af91202007-04-27 21:51:21 +00005548/// getFloatingRank - Return a relative rank for floating point types.
5549/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00005550static FloatingRank getFloatingRank(QualType T) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00005551 if (const auto *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00005552 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00005553
John McCall9dd450b2009-09-21 23:43:11 +00005554 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
5555 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00005556 default: llvm_unreachable("getFloatingRank(): not a floating type");
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00005557 case BuiltinType::Float16: return Float16Rank;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00005558 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00005559 case BuiltinType::Float: return FloatRank;
5560 case BuiltinType::Double: return DoubleRank;
5561 case BuiltinType::LongDouble: return LongDoubleRank;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005562 case BuiltinType::Float128: return Float128Rank;
Steve Naroffe4718892007-04-27 18:30:00 +00005563 }
5564}
5565
Mike Stump11289f42009-09-09 15:08:12 +00005566/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
5567/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00005568/// 'typeDomain' is a real floating point or complex type.
5569/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00005570QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
5571 QualType Domain) const {
5572 FloatingRank EltRank = getFloatingRank(Size);
5573 if (Domain->isComplexType()) {
5574 switch (EltRank) {
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00005575 case Float16Rank:
David Blaikief47fa302012-01-17 02:30:50 +00005576 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00005577 case FloatRank: return FloatComplexTy;
5578 case DoubleRank: return DoubleComplexTy;
5579 case LongDoubleRank: return LongDoubleComplexTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005580 case Float128Rank: return Float128ComplexTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00005581 }
Steve Naroff0af91202007-04-27 21:51:21 +00005582 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00005583
5584 assert(Domain->isRealFloatingType() && "Unknown domain!");
5585 switch (EltRank) {
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00005586 case Float16Rank: return HalfTy;
Joey Goulydd7f4562013-01-23 11:56:20 +00005587 case HalfRank: return HalfTy;
Chris Lattnerb9dfb032008-04-06 23:58:54 +00005588 case FloatRank: return FloatTy;
5589 case DoubleRank: return DoubleTy;
5590 case LongDoubleRank: return LongDoubleTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005591 case Float128Rank: return Float128Ty;
Steve Naroff9091ef72007-08-27 01:27:54 +00005592 }
David Blaikief47fa302012-01-17 02:30:50 +00005593 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00005594}
5595
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005596/// getFloatingTypeOrder - Compare the rank of the two specified floating
5597/// point types, ignoring the domain of the type (i.e. 'double' ==
5598/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00005599/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00005600int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00005601 FloatingRank LHSR = getFloatingRank(LHS);
5602 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00005603
Chris Lattnerb90739d2008-04-06 23:38:49 +00005604 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00005605 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00005606 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00005607 return 1;
5608 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00005609}
5610
Chris Lattner76a00cf2008-04-06 22:59:24 +00005611/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
5612/// routine will assert if passed a built-in type that isn't an integer or enum,
5613/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00005614unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00005615 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00005616
Chris Lattner76a00cf2008-04-06 22:59:24 +00005617 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00005618 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005619 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005620 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005621 case BuiltinType::Char_S:
5622 case BuiltinType::Char_U:
5623 case BuiltinType::SChar:
5624 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005625 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005626 case BuiltinType::Short:
5627 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005628 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005629 case BuiltinType::Int:
5630 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005631 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005632 case BuiltinType::Long:
5633 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005634 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005635 case BuiltinType::LongLong:
5636 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005637 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00005638 case BuiltinType::Int128:
5639 case BuiltinType::UInt128:
5640 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00005641 }
5642}
5643
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005644/// Whether this is a promotable bitfield reference according
Eli Friedman629ffb92009-08-20 04:21:42 +00005645/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
5646///
5647/// \returns the type this bit-field will promote to, or NULL if no
5648/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00005649QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00005650 if (E->isTypeDependent() || E->isValueDependent())
Eugene Zelenko7855e772018-04-03 00:11:50 +00005651 return {};
Richard Smith5b571672014-09-24 23:55:00 +00005652
Richard Smithaadb2542018-06-28 21:17:55 +00005653 // C++ [conv.prom]p5:
5654 // If the bit-field has an enumerated type, it is treated as any other
5655 // value of that type for promotion purposes.
5656 if (getLangOpts().CPlusPlus && E->getType()->isEnumeralType())
5657 return {};
5658
Richard Smith5b571672014-09-24 23:55:00 +00005659 // FIXME: We should not do this unless E->refersToBitField() is true. This
5660 // matters in C where getSourceBitField() will find bit-fields for various
5661 // cases where the source expression is not a bit-field designator.
5662
John McCalld25db7e2013-05-06 21:39:12 +00005663 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman629ffb92009-08-20 04:21:42 +00005664 if (!Field)
Eugene Zelenko7855e772018-04-03 00:11:50 +00005665 return {};
Eli Friedman629ffb92009-08-20 04:21:42 +00005666
5667 QualType FT = Field->getType();
5668
Richard Smithcaf33902011-10-10 18:28:20 +00005669 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00005670 uint64_t IntSize = getTypeSize(IntTy);
Richard Smith5b571672014-09-24 23:55:00 +00005671 // C++ [conv.prom]p5:
5672 // A prvalue for an integral bit-field can be converted to a prvalue of type
5673 // int if int can represent all the values of the bit-field; otherwise, it
5674 // can be converted to unsigned int if unsigned int can represent all the
5675 // values of the bit-field. If the bit-field is larger yet, no integral
5676 // promotion applies to it.
5677 // C11 6.3.1.1/2:
5678 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
5679 // If an int can represent all values of the original type (as restricted by
5680 // the width, for a bit-field), the value is converted to an int; otherwise,
5681 // it is converted to an unsigned int.
5682 //
5683 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
5684 // We perform that promotion here to match GCC and C++.
Richard Smithaadb2542018-06-28 21:17:55 +00005685 // FIXME: C does not permit promotion of an enum bit-field whose rank is
5686 // greater than that of 'int'. We perform that promotion to match GCC.
Eli Friedman629ffb92009-08-20 04:21:42 +00005687 if (BitWidth < IntSize)
5688 return IntTy;
5689
5690 if (BitWidth == IntSize)
5691 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
5692
Richard Smithaadb2542018-06-28 21:17:55 +00005693 // Bit-fields wider than int are not subject to promotions, and therefore act
Richard Smith5b571672014-09-24 23:55:00 +00005694 // like the base type. GCC has some weird bugs in this area that we
5695 // deliberately do not follow (GCC follows a pre-standard resolution to
5696 // C's DR315 which treats bit-width as being part of the type, and this leaks
5697 // into their semantics in some cases).
Eugene Zelenko7855e772018-04-03 00:11:50 +00005698 return {};
Eli Friedman629ffb92009-08-20 04:21:42 +00005699}
5700
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005701/// getPromotedIntegerType - Returns the type that Promotable will
5702/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
5703/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00005704QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005705 assert(!Promotable.isNull());
5706 assert(Promotable->isPromotableIntegerType());
Eugene Zelenko7855e772018-04-03 00:11:50 +00005707 if (const auto *ET = Promotable->getAs<EnumType>())
John McCall56774992009-12-09 09:09:27 +00005708 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00005709
Eugene Zelenko7855e772018-04-03 00:11:50 +00005710 if (const auto *BT = Promotable->getAs<BuiltinType>()) {
Eli Friedman3f37c1c2011-10-26 07:22:48 +00005711 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
5712 // (3.9.1) can be converted to a prvalue of the first of the following
5713 // types that can represent all the values of its underlying type:
5714 // int, unsigned int, long int, unsigned long int, long long int, or
5715 // unsigned long long int [...]
5716 // FIXME: Is there some better way to compute this?
5717 if (BT->getKind() == BuiltinType::WChar_S ||
5718 BT->getKind() == BuiltinType::WChar_U ||
Richard Smith3a8244d2018-05-01 05:02:45 +00005719 BT->getKind() == BuiltinType::Char8 ||
Eli Friedman3f37c1c2011-10-26 07:22:48 +00005720 BT->getKind() == BuiltinType::Char16 ||
5721 BT->getKind() == BuiltinType::Char32) {
5722 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
5723 uint64_t FromSize = getTypeSize(BT);
5724 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
5725 LongLongTy, UnsignedLongLongTy };
5726 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
5727 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
5728 if (FromSize < ToSize ||
5729 (FromSize == ToSize &&
5730 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
5731 return PromoteTypes[Idx];
5732 }
5733 llvm_unreachable("char type should fit into long long");
5734 }
5735 }
5736
5737 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005738 if (Promotable->isSignedIntegerType())
5739 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00005740 uint64_t PromotableSize = getIntWidth(Promotable);
5741 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005742 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
5743 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
5744}
5745
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005746/// Recurses in pointer/array types until it finds an objc retainable
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00005747/// type and returns its ownership.
5748Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
5749 while (!T.isNull()) {
5750 if (T.getObjCLifetime() != Qualifiers::OCL_None)
5751 return T.getObjCLifetime();
5752 if (T->isArrayType())
5753 T = getBaseElementType(T);
Eugene Zelenko7855e772018-04-03 00:11:50 +00005754 else if (const auto *PT = T->getAs<PointerType>())
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00005755 T = PT->getPointeeType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00005756 else if (const auto *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00005757 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00005758 else
5759 break;
5760 }
5761
5762 return Qualifiers::OCL_None;
5763}
5764
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005765static const Type *getIntegerTypeForEnum(const EnumType *ET) {
5766 // Incomplete enum types are not treated as integer types.
5767 // FIXME: In C++, enum types are never integer types.
5768 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
5769 return ET->getDecl()->getIntegerType().getTypePtr();
Craig Topper36250ad2014-05-12 05:36:57 +00005770 return nullptr;
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005771}
5772
Mike Stump11289f42009-09-09 15:08:12 +00005773/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005774/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00005775/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00005776int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00005777 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
5778 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005779
5780 // Unwrap enums to their underlying type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00005781 if (const auto *ET = dyn_cast<EnumType>(LHSC))
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005782 LHSC = getIntegerTypeForEnum(ET);
Eugene Zelenko7855e772018-04-03 00:11:50 +00005783 if (const auto *ET = dyn_cast<EnumType>(RHSC))
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005784 RHSC = getIntegerTypeForEnum(ET);
5785
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005786 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00005787
Chris Lattner76a00cf2008-04-06 22:59:24 +00005788 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
5789 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00005790
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005791 unsigned LHSRank = getIntegerRank(LHSC);
5792 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00005793
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005794 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
5795 if (LHSRank == RHSRank) return 0;
5796 return LHSRank > RHSRank ? 1 : -1;
5797 }
Mike Stump11289f42009-09-09 15:08:12 +00005798
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005799 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
5800 if (LHSUnsigned) {
5801 // If the unsigned [LHS] type is larger, return it.
5802 if (LHSRank >= RHSRank)
5803 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00005804
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005805 // If the signed type can represent all values of the unsigned type, it
5806 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00005807 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005808 return -1;
5809 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00005810
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005811 // If the unsigned [RHS] type is larger, return it.
5812 if (RHSRank >= LHSRank)
5813 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00005814
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005815 // If the signed type can represent all values of the unsigned type, it
5816 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00005817 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005818 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00005819}
Anders Carlsson98f07902007-08-17 05:31:46 +00005820
Ben Langmuirf5416742016-02-04 00:55:24 +00005821TypedefDecl *ASTContext::getCFConstantStringDecl() const {
Saleem Abdulrasoolef9b88a2018-10-24 16:38:16 +00005822 if (CFConstantStringTypeDecl)
5823 return CFConstantStringTypeDecl;
Anders Carlsson6d417272009-11-14 21:45:58 +00005824
Saleem Abdulrasoolef9b88a2018-10-24 16:38:16 +00005825 assert(!CFConstantStringTagDecl &&
5826 "tag and typedef should be initialized together");
5827 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
5828 CFConstantStringTagDecl->startDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00005829
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00005830 struct {
5831 QualType Type;
5832 const char *Name;
5833 } Fields[5];
5834 unsigned Count = 0;
Mike Stump11289f42009-09-09 15:08:12 +00005835
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00005836 /// Objective-C ABI
5837 ///
5838 /// typedef struct __NSConstantString_tag {
Saleem Abdulrasool1f6c41f2018-10-27 06:12:52 +00005839 /// const int *isa;
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00005840 /// int flags;
5841 /// const char *str;
5842 /// long length;
5843 /// } __NSConstantString;
5844 ///
5845 /// Swift ABI (4.1, 4.2)
5846 ///
5847 /// typedef struct __NSConstantString_tag {
5848 /// uintptr_t _cfisa;
5849 /// uintptr_t _swift_rc;
5850 /// _Atomic(uint64_t) _cfinfoa;
5851 /// const char *_ptr;
5852 /// uint32_t _length;
5853 /// } __NSConstantString;
5854 ///
5855 /// Swift ABI (5.0)
5856 ///
5857 /// typedef struct __NSConstantString_tag {
5858 /// uintptr_t _cfisa;
5859 /// uintptr_t _swift_rc;
5860 /// _Atomic(uint64_t) _cfinfoa;
5861 /// const char *_ptr;
5862 /// uintptr_t _length;
5863 /// } __NSConstantString;
5864
5865 const auto CFRuntime = getLangOpts().CFRuntime;
5866 if (static_cast<unsigned>(CFRuntime) <
5867 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) {
5868 Fields[Count++] = { getPointerType(IntTy.withConst()), "isa" };
5869 Fields[Count++] = { IntTy, "flags" };
5870 Fields[Count++] = { getPointerType(CharTy.withConst()), "str" };
5871 Fields[Count++] = { LongTy, "length" };
5872 } else {
5873 Fields[Count++] = { getUIntPtrType(), "_cfisa" };
5874 Fields[Count++] = { getUIntPtrType(), "_swift_rc" };
5875 Fields[Count++] = { getFromTargetType(Target->getUInt64Type()), "_swift_rc" };
5876 Fields[Count++] = { getPointerType(CharTy.withConst()), "_ptr" };
5877 if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 ||
5878 CFRuntime == LangOptions::CoreFoundationABI::Swift4_2)
5879 Fields[Count++] = { IntTy, "_ptr" };
5880 else
5881 Fields[Count++] = { getUIntPtrType(), "_ptr" };
5882 }
Douglas Gregor91f84212008-12-11 16:49:14 +00005883
Saleem Abdulrasoolef9b88a2018-10-24 16:38:16 +00005884 // Create fields
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00005885 for (unsigned i = 0; i < Count; ++i) {
Saleem Abdulrasoolef9b88a2018-10-24 16:38:16 +00005886 FieldDecl *Field =
5887 FieldDecl::Create(*this, CFConstantStringTagDecl, SourceLocation(),
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00005888 SourceLocation(), &Idents.get(Fields[i].Name),
5889 Fields[i].Type, /*TInfo=*/nullptr,
Saleem Abdulrasoolef9b88a2018-10-24 16:38:16 +00005890 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
5891 Field->setAccess(AS_public);
5892 CFConstantStringTagDecl->addDecl(Field);
Anders Carlsson98f07902007-08-17 05:31:46 +00005893 }
Mike Stump11289f42009-09-09 15:08:12 +00005894
Saleem Abdulrasoolef9b88a2018-10-24 16:38:16 +00005895 CFConstantStringTagDecl->completeDefinition();
5896 // This type is designed to be compatible with NSConstantString, but cannot
5897 // use the same name, since NSConstantString is an interface.
5898 auto tagType = getTagDeclType(CFConstantStringTagDecl);
5899 CFConstantStringTypeDecl =
5900 buildImplicitTypedef(tagType, "__NSConstantString");
5901
Quentin Colombet043406b2016-02-03 22:41:00 +00005902 return CFConstantStringTypeDecl;
5903}
5904
Ben Langmuirf5416742016-02-04 00:55:24 +00005905RecordDecl *ASTContext::getCFConstantStringTagDecl() const {
5906 if (!CFConstantStringTagDecl)
5907 getCFConstantStringDecl(); // Build the tag and the typedef.
5908 return CFConstantStringTagDecl;
5909}
5910
Quentin Colombet043406b2016-02-03 22:41:00 +00005911// getCFConstantStringType - Return the type used for constant CFStrings.
5912QualType ASTContext::getCFConstantStringType() const {
Ben Langmuirf5416742016-02-04 00:55:24 +00005913 return getTypedefType(getCFConstantStringDecl());
Gabor Greif412af032007-09-11 15:32:40 +00005914}
Anders Carlsson87c149b2007-10-11 01:00:40 +00005915
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00005916QualType ASTContext::getObjCSuperType() const {
5917 if (ObjCSuperType.isNull()) {
Alp Toker2dea15b2013-12-17 01:22:38 +00005918 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00005919 TUDecl->addDecl(ObjCSuperTypeDecl);
5920 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
5921 }
5922 return ObjCSuperType;
5923}
5924
Douglas Gregor512b0772009-04-23 22:29:11 +00005925void ASTContext::setCFConstantStringType(QualType T) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00005926 const auto *TD = T->getAs<TypedefType>();
Ben Langmuirf5416742016-02-04 00:55:24 +00005927 assert(TD && "Invalid CFConstantStringType");
5928 CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl());
Eugene Zelenko7855e772018-04-03 00:11:50 +00005929 const auto *TagType =
Ben Langmuirf5416742016-02-04 00:55:24 +00005930 CFConstantStringTypeDecl->getUnderlyingType()->getAs<RecordType>();
5931 assert(TagType && "Invalid CFConstantStringType");
5932 CFConstantStringTagDecl = TagType->getDecl();
Douglas Gregor512b0772009-04-23 22:29:11 +00005933}
5934
Jay Foad39c79802011-01-12 09:06:06 +00005935QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00005936 if (BlockDescriptorType)
5937 return getTagDeclType(BlockDescriptorType);
5938
Alp Toker2dea15b2013-12-17 01:22:38 +00005939 RecordDecl *RD;
Mike Stumpd0153282009-10-20 02:12:22 +00005940 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00005941 RD = buildImplicitRecord("__block_descriptor");
5942 RD->startDefinition();
5943
Mike Stumpd0153282009-10-20 02:12:22 +00005944 QualType FieldTypes[] = {
5945 UnsignedLongTy,
5946 UnsignedLongTy,
5947 };
5948
Craig Topperd6d31ac2013-07-15 08:24:27 +00005949 static const char *const FieldNames[] = {
Mike Stumpd0153282009-10-20 02:12:22 +00005950 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005951 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00005952 };
5953
5954 for (size_t i = 0; i < 2; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00005955 FieldDecl *Field = FieldDecl::Create(
5956 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00005957 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
5958 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00005959 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00005960 RD->addDecl(Field);
Mike Stumpd0153282009-10-20 02:12:22 +00005961 }
5962
Alp Toker2dea15b2013-12-17 01:22:38 +00005963 RD->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00005964
Alp Toker2dea15b2013-12-17 01:22:38 +00005965 BlockDescriptorType = RD;
Mike Stumpd0153282009-10-20 02:12:22 +00005966
5967 return getTagDeclType(BlockDescriptorType);
5968}
5969
Jay Foad39c79802011-01-12 09:06:06 +00005970QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005971 if (BlockDescriptorExtendedType)
5972 return getTagDeclType(BlockDescriptorExtendedType);
5973
Alp Toker2dea15b2013-12-17 01:22:38 +00005974 RecordDecl *RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005975 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00005976 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
5977 RD->startDefinition();
5978
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005979 QualType FieldTypes[] = {
5980 UnsignedLongTy,
5981 UnsignedLongTy,
5982 getPointerType(VoidPtrTy),
5983 getPointerType(VoidPtrTy)
5984 };
5985
Craig Topperd6d31ac2013-07-15 08:24:27 +00005986 static const char *const FieldNames[] = {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005987 "reserved",
5988 "Size",
5989 "CopyFuncPtr",
5990 "DestroyFuncPtr"
5991 };
5992
5993 for (size_t i = 0; i < 4; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00005994 FieldDecl *Field = FieldDecl::Create(
5995 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00005996 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
5997 /*BitWidth=*/nullptr,
Alp Toker2dea15b2013-12-17 01:22:38 +00005998 /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00005999 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00006000 RD->addDecl(Field);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00006001 }
6002
Alp Toker2dea15b2013-12-17 01:22:38 +00006003 RD->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00006004
Alp Toker2dea15b2013-12-17 01:22:38 +00006005 BlockDescriptorExtendedType = RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00006006 return getTagDeclType(BlockDescriptorExtendedType);
6007}
6008
Sven van Haastregt3bb7eaf2017-12-06 10:11:28 +00006009TargetInfo::OpenCLTypeKind ASTContext::getOpenCLTypeKind(const Type *T) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006010 const auto *BT = dyn_cast<BuiltinType>(T);
Sven van Haastregt3bb7eaf2017-12-06 10:11:28 +00006011
6012 if (!BT) {
6013 if (isa<PipeType>(T))
6014 return TargetInfo::OCLTK_Pipe;
6015
6016 return TargetInfo::OCLTK_Default;
6017 }
6018
6019 switch (BT->getKind()) {
6020#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6021 case BuiltinType::Id: \
6022 return TargetInfo::OCLTK_Image;
6023#include "clang/Basic/OpenCLImageTypes.def"
6024
6025 case BuiltinType::OCLClkEvent:
6026 return TargetInfo::OCLTK_ClkEvent;
6027
6028 case BuiltinType::OCLEvent:
6029 return TargetInfo::OCLTK_Event;
6030
6031 case BuiltinType::OCLQueue:
6032 return TargetInfo::OCLTK_Queue;
6033
6034 case BuiltinType::OCLReserveID:
6035 return TargetInfo::OCLTK_ReserveID;
6036
6037 case BuiltinType::OCLSampler:
6038 return TargetInfo::OCLTK_Sampler;
6039
6040 default:
6041 return TargetInfo::OCLTK_Default;
6042 }
6043}
6044
6045LangAS ASTContext::getOpenCLTypeAddrSpace(const Type *T) const {
6046 return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
6047}
6048
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006049/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
6050/// requires copy/dispose. Note that this must match the logic
6051/// in buildByrefHelpers.
6052bool ASTContext::BlockRequiresCopying(QualType Ty,
6053 const VarDecl *D) {
6054 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
Akira Hatanaka9978da32018-08-10 15:09:24 +00006055 const Expr *copyExpr = getBlockVarCopyInit(D).getCopyExpr();
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006056 if (!copyExpr && record->hasTrivialDestructor()) return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00006057
Mike Stump94967902009-10-21 18:16:27 +00006058 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00006059 }
Fangrui Song6907ce22018-07-30 19:24:48 +00006060
Akira Hatanaka7275da02018-02-28 07:15:55 +00006061 // The block needs copy/destroy helpers if Ty is non-trivial to destructively
6062 // move or destroy.
6063 if (Ty.isNonTrivialToPrimitiveDestructiveMove() || Ty.isDestructedType())
6064 return true;
6065
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006066 if (!Ty->isObjCRetainableType()) return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00006067
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006068 Qualifiers qs = Ty.getQualifiers();
Fangrui Song6907ce22018-07-30 19:24:48 +00006069
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006070 // If we have lifetime, that dominates.
6071 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006072 switch (lifetime) {
6073 case Qualifiers::OCL_None: llvm_unreachable("impossible");
Fangrui Song6907ce22018-07-30 19:24:48 +00006074
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006075 // These are just bits as far as the runtime is concerned.
6076 case Qualifiers::OCL_ExplicitNone:
6077 case Qualifiers::OCL_Autoreleasing:
6078 return false;
Akira Hatanaka7275da02018-02-28 07:15:55 +00006079
6080 // These cases should have been taken care of when checking the type's
6081 // non-triviality.
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006082 case Qualifiers::OCL_Weak:
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006083 case Qualifiers::OCL_Strong:
Akira Hatanaka7275da02018-02-28 07:15:55 +00006084 llvm_unreachable("impossible");
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00006085 }
6086 llvm_unreachable("fell out of lifetime switch!");
6087 }
6088 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
6089 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00006090}
6091
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006092bool ASTContext::getByrefLifetime(QualType Ty,
6093 Qualifiers::ObjCLifetime &LifeTime,
6094 bool &HasByrefExtendedLayout) const {
Erik Pilkingtonfa983902018-10-30 20:31:30 +00006095 if (!getLangOpts().ObjC ||
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006096 getLangOpts().getGC() != LangOptions::NonGC)
6097 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00006098
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006099 HasByrefExtendedLayout = false;
Fariborz Jahanianf762b722012-12-11 19:58:01 +00006100 if (Ty->isRecordType()) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006101 HasByrefExtendedLayout = true;
6102 LifeTime = Qualifiers::OCL_None;
John McCall460ce582015-10-22 18:38:17 +00006103 } else if ((LifeTime = Ty.getObjCLifetime())) {
6104 // Honor the ARC qualifiers.
6105 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
6106 // The MRR rule.
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006107 LifeTime = Qualifiers::OCL_ExplicitNone;
John McCall460ce582015-10-22 18:38:17 +00006108 } else {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006109 LifeTime = Qualifiers::OCL_None;
John McCall460ce582015-10-22 18:38:17 +00006110 }
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006111 return true;
6112}
6113
Douglas Gregorbab8a962011-09-08 01:46:34 +00006114TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
6115 if (!ObjCInstanceTypeDecl)
Alp Toker56b5cc92013-12-15 10:36:26 +00006116 ObjCInstanceTypeDecl =
6117 buildImplicitTypedef(getObjCIdType(), "instancetype");
Douglas Gregorbab8a962011-09-08 01:46:34 +00006118 return ObjCInstanceTypeDecl;
6119}
6120
Anders Carlsson18acd442007-10-29 06:33:42 +00006121// This returns true if a type has been typedefed to BOOL:
6122// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00006123static bool isTypeTypedefedAsBOOL(QualType T) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006124 if (const auto *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00006125 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
6126 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00006127
Anders Carlssond8499822007-10-29 05:01:08 +00006128 return false;
6129}
6130
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006131/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006132/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00006133CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00006134 if (!type->isIncompleteArrayType() && type->isIncompleteType())
6135 return CharUnits::Zero();
Fangrui Song6907ce22018-07-30 19:24:48 +00006136
Ken Dyck40775002010-01-11 17:06:35 +00006137 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00006138
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006139 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00006140 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00006141 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006142 // Treat arrays as pointers, since that's how they're passed in.
6143 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00006144 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00006145 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00006146}
6147
Hans Wennborg56fc62b2014-07-17 20:25:23 +00006148bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
David Majnemer3f021502015-10-08 04:53:31 +00006149 return getTargetInfo().getCXXABI().isMicrosoft() &&
6150 VD->isStaticDataMember() &&
Hans Wennborgb18da9b2018-02-20 12:43:02 +00006151 VD->getType()->isIntegralOrEnumerationType() &&
David Majnemerfac52432015-10-19 23:22:49 +00006152 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
Hans Wennborg56fc62b2014-07-17 20:25:23 +00006153}
6154
Richard Smithd9b90092016-07-02 01:32:16 +00006155ASTContext::InlineVariableDefinitionKind
6156ASTContext::getInlineVariableDefinitionKind(const VarDecl *VD) const {
6157 if (!VD->isInline())
6158 return InlineVariableDefinitionKind::None;
6159
6160 // In almost all cases, it's a weak definition.
6161 auto *First = VD->getFirstDecl();
Richard Smith8910fe62017-10-23 03:58:34 +00006162 if (First->isInlineSpecified() || !First->isStaticDataMember())
Richard Smithd9b90092016-07-02 01:32:16 +00006163 return InlineVariableDefinitionKind::Weak;
6164
6165 // If there's a file-context declaration in this translation unit, it's a
6166 // non-discardable definition.
6167 for (auto *D : VD->redecls())
Richard Smith8910fe62017-10-23 03:58:34 +00006168 if (D->getLexicalDeclContext()->isFileContext() &&
6169 !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr()))
Richard Smithd9b90092016-07-02 01:32:16 +00006170 return InlineVariableDefinitionKind::Strong;
6171
6172 // If we've not seen one yet, we don't know.
6173 return InlineVariableDefinitionKind::WeakUnknown;
6174}
6175
Eugene Zelenko7855e772018-04-03 00:11:50 +00006176static std::string charUnitsToString(const CharUnits &CU) {
Ken Dyck40775002010-01-11 17:06:35 +00006177 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006178}
6179
John McCall351762c2011-02-07 10:33:21 +00006180/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00006181/// declaration.
John McCall351762c2011-02-07 10:33:21 +00006182std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
6183 std::string S;
6184
David Chisnall950a9512009-11-17 19:33:30 +00006185 const BlockDecl *Decl = Expr->getBlockDecl();
6186 QualType BlockTy =
6187 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
6188 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00006189 if (getLangOpts().EncodeExtendedBlockSig)
Alp Toker314cc812014-01-25 16:55:45 +00006190 getObjCEncodingForMethodParameter(
6191 Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
6192 true /*Extended*/);
Fariborz Jahanian64223e62012-11-14 23:11:38 +00006193 else
Alp Toker314cc812014-01-25 16:55:45 +00006194 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00006195 // Compute size of all parameters.
6196 // Start with computing size of a pointer in number of bytes.
6197 // FIXME: There might(should) be a better way of doing this computation!
Ken Dyck40775002010-01-11 17:06:35 +00006198 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
6199 CharUnits ParmOffset = PtrSize;
David Majnemer59f77922016-06-24 04:05:48 +00006200 for (auto PI : Decl->parameters()) {
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00006201 QualType PType = PI->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00006202 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00006203 if (sz.isZero())
6204 continue;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00006205 assert(sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00006206 ParmOffset += sz;
6207 }
6208 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00006209 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00006210 // Block pointer and offset.
6211 S += "@?0";
Fangrui Song6907ce22018-07-30 19:24:48 +00006212
David Chisnall950a9512009-11-17 19:33:30 +00006213 // Argument types.
6214 ParmOffset = PtrSize;
David Majnemer59f77922016-06-24 04:05:48 +00006215 for (auto PVDecl : Decl->parameters()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00006216 QualType PType = PVDecl->getOriginalType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00006217 if (const auto *AT =
6218 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
David Chisnall950a9512009-11-17 19:33:30 +00006219 // Use array's original type only if it has known number of
6220 // elements.
6221 if (!isa<ConstantArrayType>(AT))
6222 PType = PVDecl->getType();
6223 } else if (PType->isFunctionType())
6224 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00006225 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00006226 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
6227 S, true /*Extended*/);
6228 else
6229 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00006230 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00006231 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00006232 }
John McCall351762c2011-02-07 10:33:21 +00006233
6234 return S;
David Chisnall950a9512009-11-17 19:33:30 +00006235}
6236
John McCall843dfcc2016-11-29 21:57:00 +00006237std::string
6238ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const {
6239 std::string S;
David Chisnall50e4eba2010-12-30 14:05:53 +00006240 // Encode result type.
Alp Toker314cc812014-01-25 16:55:45 +00006241 getObjCEncodingForType(Decl->getReturnType(), S);
David Chisnall50e4eba2010-12-30 14:05:53 +00006242 CharUnits ParmOffset;
6243 // Compute size of all parameters.
David Majnemer59f77922016-06-24 04:05:48 +00006244 for (auto PI : Decl->parameters()) {
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00006245 QualType PType = PI->getType();
David Chisnall50e4eba2010-12-30 14:05:53 +00006246 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00006247 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00006248 continue;
Fangrui Song6907ce22018-07-30 19:24:48 +00006249
6250 assert(sz.isPositive() &&
John McCall843dfcc2016-11-29 21:57:00 +00006251 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00006252 ParmOffset += sz;
6253 }
6254 S += charUnitsToString(ParmOffset);
6255 ParmOffset = CharUnits::Zero();
6256
6257 // Argument types.
David Majnemer59f77922016-06-24 04:05:48 +00006258 for (auto PVDecl : Decl->parameters()) {
David Chisnall50e4eba2010-12-30 14:05:53 +00006259 QualType PType = PVDecl->getOriginalType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00006260 if (const auto *AT =
6261 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
David Chisnall50e4eba2010-12-30 14:05:53 +00006262 // Use array's original type only if it has known number of
6263 // elements.
6264 if (!isa<ConstantArrayType>(AT))
6265 PType = PVDecl->getType();
6266 } else if (PType->isFunctionType())
6267 PType = PVDecl->getType();
6268 getObjCEncodingForType(PType, S);
6269 S += charUnitsToString(ParmOffset);
6270 ParmOffset += getObjCEncodingTypeSize(PType);
6271 }
Fangrui Song6907ce22018-07-30 19:24:48 +00006272
John McCall843dfcc2016-11-29 21:57:00 +00006273 return S;
David Chisnall50e4eba2010-12-30 14:05:53 +00006274}
6275
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006276/// getObjCEncodingForMethodParameter - Return the encoded type for a single
Fangrui Song6907ce22018-07-30 19:24:48 +00006277/// method parameter or return type. If Extended, include class names and
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006278/// block object types.
6279void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
6280 QualType T, std::string& S,
6281 bool Extended) const {
6282 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
6283 getObjCEncodingForTypeQualifier(QT, S);
6284 // Encode parameter type.
Craig Topper36250ad2014-05-12 05:36:57 +00006285 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006286 true /*OutermostType*/,
Fangrui Song6907ce22018-07-30 19:24:48 +00006287 false /*EncodingProperty*/,
6288 false /*StructField*/,
6289 Extended /*EncodeBlockParameters*/,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006290 Extended /*EncodeClassNames*/);
6291}
6292
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006293/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006294/// declaration.
John McCall843dfcc2016-11-29 21:57:00 +00006295std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
6296 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00006297 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006298 // Encode return type.
John McCall843dfcc2016-11-29 21:57:00 +00006299 std::string S;
Alp Toker314cc812014-01-25 16:55:45 +00006300 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
6301 Decl->getReturnType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006302 // Compute size of all parameters.
6303 // Start with computing size of a pointer in number of bytes.
6304 // FIXME: There might(should) be a better way of doing this computation!
Ken Dyck40775002010-01-11 17:06:35 +00006305 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006306 // The first two arguments (self and _cmd) are pointers; account for
6307 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00006308 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00006309 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00006310 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00006311 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00006312 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00006313 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00006314 continue;
Fangrui Song6907ce22018-07-30 19:24:48 +00006315
6316 assert(sz.isPositive() &&
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00006317 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006318 ParmOffset += sz;
6319 }
Ken Dyck40775002010-01-11 17:06:35 +00006320 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006321 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00006322 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00006323
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006324 // Argument types.
6325 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00006326 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00006327 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00006328 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00006329 QualType PType = PVDecl->getOriginalType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00006330 if (const auto *AT =
6331 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
Steve Naroffe4e55d22009-04-14 00:03:58 +00006332 // Use array's original type only if it has known number of
6333 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00006334 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00006335 PType = PVDecl->getType();
6336 } else if (PType->isFunctionType())
6337 PType = PVDecl->getType();
Fangrui Song6907ce22018-07-30 19:24:48 +00006338 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006339 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00006340 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00006341 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006342 }
Fangrui Song6907ce22018-07-30 19:24:48 +00006343
John McCall843dfcc2016-11-29 21:57:00 +00006344 return S;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006345}
6346
Fariborz Jahaniandad96302014-01-22 19:02:20 +00006347ObjCPropertyImplDecl *
6348ASTContext::getObjCPropertyImplDeclForPropertyDecl(
6349 const ObjCPropertyDecl *PD,
6350 const Decl *Container) const {
6351 if (!Container)
Craig Topper36250ad2014-05-12 05:36:57 +00006352 return nullptr;
Eugene Zelenko7855e772018-04-03 00:11:50 +00006353 if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) {
Aaron Ballmand85eff42014-03-14 15:02:45 +00006354 for (auto *PID : CID->property_impls())
6355 if (PID->getPropertyDecl() == PD)
6356 return PID;
Craig Topper36250ad2014-05-12 05:36:57 +00006357 } else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006358 const auto *OID = cast<ObjCImplementationDecl>(Container);
Craig Topper36250ad2014-05-12 05:36:57 +00006359 for (auto *PID : OID->property_impls())
6360 if (PID->getPropertyDecl() == PD)
6361 return PID;
6362 }
6363 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00006364}
6365
Daniel Dunbar4932b362008-08-28 04:38:10 +00006366/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00006367/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00006368/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
6369/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00006370/// Property attributes are stored as a comma-delimited C string. The simple
6371/// attributes readonly and bycopy are encoded as single characters. The
6372/// parametrized attributes, getter=name, setter=name, and ivar=name, are
6373/// encoded as single characters, followed by an identifier. Property types
6374/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00006375/// these attributes are defined by the following enumeration:
6376/// @code
6377/// enum PropertyAttributes {
6378/// kPropertyReadOnly = 'R', // property is read-only.
6379/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
6380/// kPropertyByref = '&', // property is a reference to the value last assigned
6381/// kPropertyDynamic = 'D', // property is dynamic
6382/// kPropertyGetter = 'G', // followed by getter selector name
6383/// kPropertySetter = 'S', // followed by setter selector name
6384/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00006385/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00006386/// kPropertyWeak = 'W' // 'weak' property
6387/// kPropertyStrong = 'P' // property GC'able
6388/// kPropertyNonAtomic = 'N' // property non-atomic
6389/// };
6390/// @endcode
John McCall843dfcc2016-11-29 21:57:00 +00006391std::string
6392ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
6393 const Decl *Container) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00006394 // Collect information from the property implementation decl(s).
6395 bool Dynamic = false;
Craig Topper36250ad2014-05-12 05:36:57 +00006396 ObjCPropertyImplDecl *SynthesizePID = nullptr;
Daniel Dunbar4932b362008-08-28 04:38:10 +00006397
Fariborz Jahaniandad96302014-01-22 19:02:20 +00006398 if (ObjCPropertyImplDecl *PropertyImpDecl =
6399 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
6400 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
6401 Dynamic = true;
6402 else
6403 SynthesizePID = PropertyImpDecl;
Daniel Dunbar4932b362008-08-28 04:38:10 +00006404 }
6405
6406 // FIXME: This is not very efficient.
John McCall843dfcc2016-11-29 21:57:00 +00006407 std::string S = "T";
Daniel Dunbar4932b362008-08-28 04:38:10 +00006408
6409 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00006410 // GCC has some special rules regarding encoding of properties which
6411 // closely resembles encoding of ivars.
Joe Groff98ac7d22014-07-07 22:25:15 +00006412 getObjCEncodingForPropertyType(PD->getType(), S);
Daniel Dunbar4932b362008-08-28 04:38:10 +00006413
6414 if (PD->isReadOnly()) {
6415 S += ",R";
Nico Weber4e8626f2013-05-08 23:47:40 +00006416 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
6417 S += ",C";
6418 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
6419 S += ",&";
Fariborz Jahanian33079ee2014-04-02 22:49:42 +00006420 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
6421 S += ",W";
Daniel Dunbar4932b362008-08-28 04:38:10 +00006422 } else {
6423 switch (PD->getSetterKind()) {
6424 case ObjCPropertyDecl::Assign: break;
6425 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00006426 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00006427 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00006428 }
6429 }
6430
6431 // It really isn't clear at all what this means, since properties
6432 // are "dynamic by default".
6433 if (Dynamic)
6434 S += ",D";
6435
Fariborz Jahanian218c6302009-01-20 19:14:18 +00006436 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
6437 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00006438
Daniel Dunbar4932b362008-08-28 04:38:10 +00006439 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
6440 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00006441 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00006442 }
6443
6444 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
6445 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00006446 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00006447 }
6448
6449 if (SynthesizePID) {
6450 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
6451 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00006452 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00006453 }
6454
6455 // FIXME: OBJCGC: weak & strong
John McCall843dfcc2016-11-29 21:57:00 +00006456 return S;
Daniel Dunbar4932b362008-08-28 04:38:10 +00006457}
6458
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006459/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00006460/// Another legacy compatibility encoding: 32-bit longs are encoded as
6461/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006462/// 'i' or 'I' instead if encoding a struct field, or a pointer!
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006463void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00006464 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006465 if (const auto *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00006466 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006467 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00006468 else
Jay Foad39c79802011-01-12 09:06:06 +00006469 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006470 PointeeTy = IntTy;
6471 }
6472 }
6473}
6474
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00006475void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006476 const FieldDecl *Field,
6477 QualType *NotEncodedT) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00006478 // We follow the behavior of gcc, expanding structures which are
6479 // directly pointed to, and expanding embedded structures. Note that
6480 // these rules are sufficient to prevent recursive encoding of the
6481 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00006482 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006483 true /* outermost type */, false, false,
6484 false, false, false, NotEncodedT);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00006485}
6486
Joe Groff98ac7d22014-07-07 22:25:15 +00006487void ASTContext::getObjCEncodingForPropertyType(QualType T,
6488 std::string& S) const {
6489 // Encode result type.
6490 // GCC has some special rules regarding encoding of properties which
6491 // closely resembles encoding of ivars.
6492 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
6493 true /* outermost type */,
6494 true /* encoding property */);
6495}
6496
John McCall393a78d2012-12-20 02:45:14 +00006497static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
6498 BuiltinType::Kind kind) {
6499 switch (kind) {
David Chisnallb190a2c2010-06-04 01:10:52 +00006500 case BuiltinType::Void: return 'v';
6501 case BuiltinType::Bool: return 'B';
Richard Smith3a8244d2018-05-01 05:02:45 +00006502 case BuiltinType::Char8:
David Chisnallb190a2c2010-06-04 01:10:52 +00006503 case BuiltinType::Char_U:
6504 case BuiltinType::UChar: return 'C';
John McCall393a78d2012-12-20 02:45:14 +00006505 case BuiltinType::Char16:
David Chisnallb190a2c2010-06-04 01:10:52 +00006506 case BuiltinType::UShort: return 'S';
John McCall393a78d2012-12-20 02:45:14 +00006507 case BuiltinType::Char32:
David Chisnallb190a2c2010-06-04 01:10:52 +00006508 case BuiltinType::UInt: return 'I';
6509 case BuiltinType::ULong:
John McCall393a78d2012-12-20 02:45:14 +00006510 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00006511 case BuiltinType::UInt128: return 'T';
6512 case BuiltinType::ULongLong: return 'Q';
6513 case BuiltinType::Char_S:
6514 case BuiltinType::SChar: return 'c';
6515 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00006516 case BuiltinType::WChar_S:
6517 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00006518 case BuiltinType::Int: return 'i';
6519 case BuiltinType::Long:
John McCall393a78d2012-12-20 02:45:14 +00006520 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00006521 case BuiltinType::LongLong: return 'q';
6522 case BuiltinType::Int128: return 't';
6523 case BuiltinType::Float: return 'f';
6524 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00006525 case BuiltinType::LongDouble: return 'D';
John McCall393a78d2012-12-20 02:45:14 +00006526 case BuiltinType::NullPtr: return '*'; // like char*
6527
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00006528 case BuiltinType::Float16:
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00006529 case BuiltinType::Float128:
John McCall393a78d2012-12-20 02:45:14 +00006530 case BuiltinType::Half:
Leonard Chanf921d852018-06-04 16:07:52 +00006531 case BuiltinType::ShortAccum:
6532 case BuiltinType::Accum:
6533 case BuiltinType::LongAccum:
6534 case BuiltinType::UShortAccum:
6535 case BuiltinType::UAccum:
6536 case BuiltinType::ULongAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00006537 case BuiltinType::ShortFract:
6538 case BuiltinType::Fract:
6539 case BuiltinType::LongFract:
6540 case BuiltinType::UShortFract:
6541 case BuiltinType::UFract:
6542 case BuiltinType::ULongFract:
6543 case BuiltinType::SatShortAccum:
6544 case BuiltinType::SatAccum:
6545 case BuiltinType::SatLongAccum:
6546 case BuiltinType::SatUShortAccum:
6547 case BuiltinType::SatUAccum:
6548 case BuiltinType::SatULongAccum:
6549 case BuiltinType::SatShortFract:
6550 case BuiltinType::SatFract:
6551 case BuiltinType::SatLongFract:
6552 case BuiltinType::SatUShortFract:
6553 case BuiltinType::SatUFract:
6554 case BuiltinType::SatULongFract:
John McCall393a78d2012-12-20 02:45:14 +00006555 // FIXME: potentially need @encodes for these!
6556 return ' ';
6557
6558 case BuiltinType::ObjCId:
6559 case BuiltinType::ObjCClass:
6560 case BuiltinType::ObjCSel:
6561 llvm_unreachable("@encoding ObjC primitive type");
6562
6563 // OpenCL and placeholder types don't need @encodings.
Alexey Bader954ba212016-04-08 13:40:33 +00006564#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6565 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00006566#include "clang/Basic/OpenCLImageTypes.def"
Andrew Savonichev3fee3512018-11-08 11:25:41 +00006567#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6568 case BuiltinType::Id:
6569#include "clang/Basic/OpenCLExtensionTypes.def"
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006570 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00006571 case BuiltinType::OCLClkEvent:
6572 case BuiltinType::OCLQueue:
Alexey Bader9c8453f2015-09-15 11:18:52 +00006573 case BuiltinType::OCLReserveID:
Guy Benyei61054192013-02-07 10:55:47 +00006574 case BuiltinType::OCLSampler:
John McCall393a78d2012-12-20 02:45:14 +00006575 case BuiltinType::Dependent:
6576#define BUILTIN_TYPE(KIND, ID)
6577#define PLACEHOLDER_TYPE(KIND, ID) \
6578 case BuiltinType::KIND:
6579#include "clang/AST/BuiltinTypes.def"
6580 llvm_unreachable("invalid builtin type for @encode");
David Chisnallb190a2c2010-06-04 01:10:52 +00006581 }
David Blaikie5a6a0202013-01-09 17:48:41 +00006582 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnallb190a2c2010-06-04 01:10:52 +00006583}
6584
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006585static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
6586 EnumDecl *Enum = ET->getDecl();
Fangrui Song6907ce22018-07-30 19:24:48 +00006587
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006588 // The encoding of an non-fixed enum type is always 'i', regardless of size.
6589 if (!Enum->isFixed())
6590 return 'i';
Fangrui Song6907ce22018-07-30 19:24:48 +00006591
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006592 // The encoding of a fixed enum type matches its fixed underlying type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00006593 const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>();
John McCall393a78d2012-12-20 02:45:14 +00006594 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006595}
6596
Jay Foad39c79802011-01-12 09:06:06 +00006597static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00006598 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00006599 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00006600 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00006601 // The NeXT runtime encodes bit fields as b followed by the number of bits.
6602 // The GNU runtime requires more information; bitfields are encoded as b,
6603 // then the offset (in bits) of the first element, then the type of the
6604 // bitfield, then the size in bits. For example, in this structure:
6605 //
6606 // struct
6607 // {
6608 // int integer;
6609 // int flags:2;
6610 // };
6611 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
6612 // runtime, but b32i2 for the GNU runtime. The reason for this extra
6613 // information is not especially sensible, but we're stuck with it for
6614 // compatibility with GCC, although providing it breaks anything that
6615 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00006616 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
Akira Hatanaka4b1c4842017-06-27 04:34:04 +00006617 uint64_t Offset;
6618
6619 if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) {
6620 Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), nullptr,
6621 IVD);
6622 } else {
6623 const RecordDecl *RD = FD->getParent();
6624 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
6625 Offset = RL.getFieldOffset(FD->getFieldIndex());
6626 }
6627
6628 S += llvm::utostr(Offset);
6629
Eugene Zelenko7855e772018-04-03 00:11:50 +00006630 if (const auto *ET = T->getAs<EnumType>())
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006631 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall393a78d2012-12-20 02:45:14 +00006632 else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006633 const auto *BT = T->castAs<BuiltinType>();
John McCall393a78d2012-12-20 02:45:14 +00006634 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
6635 }
David Chisnallb190a2c2010-06-04 01:10:52 +00006636 }
Richard Smithcaf33902011-10-10 18:28:20 +00006637 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00006638}
6639
Daniel Dunbar07d07852009-10-18 21:17:35 +00006640// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00006641void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
6642 bool ExpandPointedToStructures,
6643 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00006644 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00006645 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006646 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006647 bool StructField,
6648 bool EncodeBlockParameters,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00006649 bool EncodeClassNames,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006650 bool EncodePointerToObjCTypedef,
6651 QualType *NotEncodedT) const {
John McCall393a78d2012-12-20 02:45:14 +00006652 CanQualType CT = getCanonicalType(T);
6653 switch (CT->getTypeClass()) {
6654 case Type::Builtin:
6655 case Type::Enum:
Chris Lattnere7cabb92009-07-13 00:10:46 +00006656 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00006657 return EncodeBitField(this, S, T, FD);
Eugene Zelenko7855e772018-04-03 00:11:50 +00006658 if (const auto *BT = dyn_cast<BuiltinType>(CT))
John McCall393a78d2012-12-20 02:45:14 +00006659 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
6660 else
6661 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnere7cabb92009-07-13 00:10:46 +00006662 return;
Mike Stump11289f42009-09-09 15:08:12 +00006663
John McCall393a78d2012-12-20 02:45:14 +00006664 case Type::Complex: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006665 const auto *CT = T->castAs<ComplexType>();
Anders Carlsson39b2e132009-04-09 21:55:45 +00006666 S += 'j';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006667 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, nullptr);
Chris Lattnere7cabb92009-07-13 00:10:46 +00006668 return;
6669 }
John McCall393a78d2012-12-20 02:45:14 +00006670
6671 case Type::Atomic: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006672 const auto *AT = T->castAs<AtomicType>();
John McCall393a78d2012-12-20 02:45:14 +00006673 S += 'A';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006674 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, nullptr);
John McCall393a78d2012-12-20 02:45:14 +00006675 return;
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00006676 }
John McCall393a78d2012-12-20 02:45:14 +00006677
6678 // encoding for pointer or reference types.
6679 case Type::Pointer:
6680 case Type::LValueReference:
6681 case Type::RValueReference: {
6682 QualType PointeeTy;
6683 if (isa<PointerType>(CT)) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006684 const auto *PT = T->castAs<PointerType>();
John McCall393a78d2012-12-20 02:45:14 +00006685 if (PT->isObjCSelType()) {
6686 S += ':';
6687 return;
6688 }
6689 PointeeTy = PT->getPointeeType();
6690 } else {
6691 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
6692 }
6693
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006694 bool isReadOnly = false;
6695 // For historical/compatibility reasons, the read-only qualifier of the
6696 // pointee gets emitted _before_ the '^'. The read-only qualifier of
6697 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00006698 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00006699 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006700 if (OutermostType && T.isConstQualified()) {
6701 isReadOnly = true;
6702 S += 'r';
6703 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00006704 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006705 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006706 while (P->getAs<PointerType>())
6707 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006708 if (P.isConstQualified()) {
6709 isReadOnly = true;
6710 S += 'r';
6711 }
6712 }
6713 if (isReadOnly) {
6714 // Another legacy compatibility encoding. Some ObjC qualifier and type
6715 // combinations need to be rearranged.
6716 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006717 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00006718 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006719 }
Mike Stump11289f42009-09-09 15:08:12 +00006720
Anders Carlssond8499822007-10-29 05:01:08 +00006721 if (PointeeTy->isCharType()) {
6722 // char pointer types should be encoded as '*' unless it is a
6723 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00006724 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00006725 S += '*';
6726 return;
6727 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00006728 } else if (const auto *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00006729 // GCC binary compat: Need to convert "struct objc_class *" to "#".
6730 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
6731 S += '#';
6732 return;
6733 }
6734 // GCC binary compat: Need to convert "struct objc_object *" to "@".
6735 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
6736 S += '@';
6737 return;
6738 }
6739 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00006740 }
Anders Carlssond8499822007-10-29 05:01:08 +00006741 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006742 getLegacyIntegralTypeEncoding(PointeeTy);
6743
Mike Stump11289f42009-09-09 15:08:12 +00006744 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006745 nullptr, false, false, false, false, false, false,
6746 NotEncodedT);
Chris Lattnere7cabb92009-07-13 00:10:46 +00006747 return;
6748 }
John McCall393a78d2012-12-20 02:45:14 +00006749
6750 case Type::ConstantArray:
6751 case Type::IncompleteArray:
6752 case Type::VariableArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006753 const auto *AT = cast<ArrayType>(CT);
John McCall393a78d2012-12-20 02:45:14 +00006754
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006755 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00006756 // Incomplete arrays are encoded as a pointer to the array element.
6757 S += '^';
6758
Mike Stump11289f42009-09-09 15:08:12 +00006759 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00006760 false, ExpandStructures, FD);
6761 } else {
6762 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00006763
Eugene Zelenko7855e772018-04-03 00:11:50 +00006764 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
Fariborz Jahanianf0dc11a2013-06-04 16:04:37 +00006765 S += llvm::utostr(CAT->getSize().getZExtValue());
6766 else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00006767 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006768 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
6769 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00006770 S += '0';
6771 }
Mike Stump11289f42009-09-09 15:08:12 +00006772
6773 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006774 false, ExpandStructures, FD,
6775 false, false, false, false, false, false,
6776 NotEncodedT);
Anders Carlssond05f44b2009-02-22 01:38:57 +00006777 S += ']';
6778 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006779 return;
6780 }
Mike Stump11289f42009-09-09 15:08:12 +00006781
John McCall393a78d2012-12-20 02:45:14 +00006782 case Type::FunctionNoProto:
6783 case Type::FunctionProto:
Anders Carlssondf4cc612007-10-30 00:06:20 +00006784 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00006785 return;
Mike Stump11289f42009-09-09 15:08:12 +00006786
John McCall393a78d2012-12-20 02:45:14 +00006787 case Type::Record: {
6788 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00006789 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00006790 // Anonymous structures print as '?'
6791 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
6792 S += II->getName();
Eugene Zelenko7855e772018-04-03 00:11:50 +00006793 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
Fariborz Jahanianc5158202010-05-07 00:28:49 +00006794 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00006795 llvm::raw_string_ostream OS(S);
Serge Pavlov03e672c2017-11-28 16:14:14 +00006796 printTemplateArgumentList(OS, TemplateArgs.asArray(),
6797 getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00006798 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00006799 } else {
6800 S += '?';
6801 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00006802 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00006803 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006804 if (!RDecl->isUnion()) {
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006805 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006806 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006807 for (const auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006808 if (FD) {
6809 S += '"';
6810 S += Field->getNameAsString();
6811 S += '"';
6812 }
Mike Stump11289f42009-09-09 15:08:12 +00006813
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006814 // Special case bit-fields.
6815 if (Field->isBitField()) {
6816 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006817 Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006818 } else {
6819 QualType qt = Field->getType();
6820 getLegacyIntegralTypeEncoding(qt);
6821 getObjCEncodingForTypeImpl(qt, S, false, true,
6822 FD, /*OutermostType*/false,
6823 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006824 /*StructField*/true,
6825 false, false, false, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006826 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00006827 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00006828 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00006829 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00006830 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00006831 return;
6832 }
Mike Stump11289f42009-09-09 15:08:12 +00006833
John McCall393a78d2012-12-20 02:45:14 +00006834 case Type::BlockPointer: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006835 const auto *BT = T->castAs<BlockPointerType>();
Steve Naroff49140cb2009-02-02 18:24:29 +00006836 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006837 if (EncodeBlockParameters) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006838 const auto *FT = BT->getPointeeType()->castAs<FunctionType>();
Fangrui Song6907ce22018-07-30 19:24:48 +00006839
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006840 S += '<';
6841 // Block return type
Alp Toker314cc812014-01-25 16:55:45 +00006842 getObjCEncodingForTypeImpl(
6843 FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures,
6844 FD, false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006845 false /* StructField */, EncodeBlockParameters, EncodeClassNames, false,
6846 NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006847 // Block self
6848 S += "@?";
6849 // Block parameters
Eugene Zelenko7855e772018-04-03 00:11:50 +00006850 if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00006851 for (const auto &I : FPT->param_types())
6852 getObjCEncodingForTypeImpl(
6853 I, S, ExpandPointedToStructures, ExpandStructures, FD,
6854 false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006855 false /* StructField */, EncodeBlockParameters, EncodeClassNames,
6856 false, NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006857 }
6858 S += '>';
6859 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006860 return;
6861 }
Mike Stump11289f42009-09-09 15:08:12 +00006862
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00006863 case Type::ObjCObject: {
6864 // hack to match legacy encoding of *id and *Class
6865 QualType Ty = getObjCObjectPointerType(CT);
6866 if (Ty->isObjCIdType()) {
6867 S += "{objc_object=}";
6868 return;
6869 }
6870 else if (Ty->isObjCClassType()) {
6871 S += "{objc_class=}";
6872 return;
6873 }
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00006874 // TODO: Double check to make sure this intentionally falls through.
Galina Kistanovaf87496d2017-06-03 06:31:42 +00006875 LLVM_FALLTHROUGH;
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00006876 }
Fangrui Song6907ce22018-07-30 19:24:48 +00006877
John McCall393a78d2012-12-20 02:45:14 +00006878 case Type::ObjCInterface: {
6879 // Ignore protocol qualifiers when mangling at this level.
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006880 // @encode(class_name)
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006881 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006882 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006883 S += OI->getObjCRuntimeNameAsString();
Akira Hatanakafd0fb202016-08-17 19:42:22 +00006884 if (ExpandStructures) {
6885 S += '=';
6886 SmallVector<const ObjCIvarDecl*, 32> Ivars;
6887 DeepCollectObjCIvars(OI, true, Ivars);
6888 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
George Burgess IV00f70bd2018-03-01 05:43:23 +00006889 const FieldDecl *Field = Ivars[i];
Akira Hatanakafd0fb202016-08-17 19:42:22 +00006890 if (Field->isBitField())
6891 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
6892 else
6893 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
6894 false, false, false, false, false,
6895 EncodePointerToObjCTypedef,
6896 NotEncodedT);
6897 }
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006898 }
6899 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00006900 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006901 }
Mike Stump11289f42009-09-09 15:08:12 +00006902
John McCall393a78d2012-12-20 02:45:14 +00006903 case Type::ObjCObjectPointer: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006904 const auto *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00006905 if (OPT->isObjCIdType()) {
6906 S += '@';
6907 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00006908 }
Mike Stump11289f42009-09-09 15:08:12 +00006909
Steve Narofff0c86112009-10-28 22:03:49 +00006910 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
6911 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
6912 // Since this is a binary compatibility issue, need to consult with runtime
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00006913 // folks. Fortunately, this is a *very* obscure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00006914 S += '#';
6915 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00006916 }
Mike Stump11289f42009-09-09 15:08:12 +00006917
Chris Lattnere7cabb92009-07-13 00:10:46 +00006918 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00006919 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00006920 ExpandPointedToStructures,
6921 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006922 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00006923 // Note that we do extended encoding of protocol qualifer list
6924 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00006925 S += '"';
Aaron Ballman83731462014-03-17 16:14:00 +00006926 for (const auto *I : OPT->quals()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00006927 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006928 S += I->getObjCRuntimeNameAsString();
Steve Naroff7cae42b2009-07-10 23:34:53 +00006929 S += '>';
6930 }
6931 S += '"';
6932 }
6933 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00006934 }
Mike Stump11289f42009-09-09 15:08:12 +00006935
Chris Lattnere7cabb92009-07-13 00:10:46 +00006936 QualType PointeeTy = OPT->getPointeeType();
6937 if (!EncodingProperty &&
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00006938 isa<TypedefType>(PointeeTy.getTypePtr()) &&
6939 !EncodePointerToObjCTypedef) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00006940 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00006941 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00006942 // {...};
6943 S += '^';
Fariborz Jahanian88890e72013-07-12 16:19:11 +00006944 if (FD && OPT->getInterfaceDecl()) {
Fariborz Jahanianc682ef52013-07-12 16:41:56 +00006945 // Prevent recursive encoding of fields in some rare cases.
Fariborz Jahanian88890e72013-07-12 16:19:11 +00006946 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
6947 SmallVector<const ObjCIvarDecl*, 32> Ivars;
6948 DeepCollectObjCIvars(OI, true, Ivars);
6949 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
George Burgess IV00f70bd2018-03-01 05:43:23 +00006950 if (Ivars[i] == FD) {
Fariborz Jahanian88890e72013-07-12 16:19:11 +00006951 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006952 S += OI->getObjCRuntimeNameAsString();
Fariborz Jahanian88890e72013-07-12 16:19:11 +00006953 S += '}';
6954 return;
6955 }
6956 }
6957 }
Mike Stump11289f42009-09-09 15:08:12 +00006958 getObjCEncodingForTypeImpl(PointeeTy, S,
6959 false, ExpandPointedToStructures,
Craig Topper36250ad2014-05-12 05:36:57 +00006960 nullptr,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00006961 false, false, false, false, false,
6962 /*EncodePointerToObjCTypedef*/true);
Steve Naroff7cae42b2009-07-10 23:34:53 +00006963 return;
6964 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006965
6966 S += '@';
Fangrui Song6907ce22018-07-30 19:24:48 +00006967 if (OPT->getInterfaceDecl() &&
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006968 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00006969 S += '"';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006970 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
Aaron Ballman83731462014-03-17 16:14:00 +00006971 for (const auto *I : OPT->quals()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00006972 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006973 S += I->getObjCRuntimeNameAsString();
Chris Lattnere7cabb92009-07-13 00:10:46 +00006974 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00006975 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006976 S += '"';
6977 }
6978 return;
6979 }
Mike Stump11289f42009-09-09 15:08:12 +00006980
John McCalla9e6e8d2010-05-17 23:56:34 +00006981 // gcc just blithely ignores member pointers.
John McCall393a78d2012-12-20 02:45:14 +00006982 // FIXME: we shoul do better than that. 'M' is available.
6983 case Type::MemberPointer:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006984 // This matches gcc's encoding, even though technically it is insufficient.
6985 //FIXME. We should do a better job than gcc.
John McCall393a78d2012-12-20 02:45:14 +00006986 case Type::Vector:
6987 case Type::ExtVector:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006988 // Until we have a coherent encoding of these three types, issue warning.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00006989 if (NotEncodedT)
6990 *NotEncodedT = T;
6991 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00006992
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006993 // We could see an undeduced auto type here during error recovery.
6994 // Just ignore it.
Richard Smith27d807c2013-04-30 13:56:41 +00006995 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00006996 case Type::DeducedTemplateSpecialization:
Richard Smith27d807c2013-04-30 13:56:41 +00006997 return;
6998
Xiuli Pan9c14e282016-01-09 12:53:17 +00006999 case Type::Pipe:
John McCall393a78d2012-12-20 02:45:14 +00007000#define ABSTRACT_TYPE(KIND, BASE)
7001#define TYPE(KIND, BASE)
7002#define DEPENDENT_TYPE(KIND, BASE) \
7003 case Type::KIND:
7004#define NON_CANONICAL_TYPE(KIND, BASE) \
7005 case Type::KIND:
7006#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
7007 case Type::KIND:
7008#include "clang/AST/TypeNodes.def"
7009 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00007010 }
John McCall393a78d2012-12-20 02:45:14 +00007011 llvm_unreachable("bad type kind!");
Anders Carlssond8499822007-10-29 05:01:08 +00007012}
7013
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007014void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
7015 std::string &S,
7016 const FieldDecl *FD,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00007017 bool includeVBases,
7018 QualType *NotEncodedT) const {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007019 assert(RDecl && "Expected non-null RecordDecl");
7020 assert(!RDecl->isUnion() && "Should not be called for unions");
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00007021 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007022 return;
7023
Eugene Zelenko7855e772018-04-03 00:11:50 +00007024 const auto *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007025 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
7026 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
7027
7028 if (CXXRec) {
Aaron Ballman574705e2014-03-13 15:41:46 +00007029 for (const auto &BI : CXXRec->bases()) {
7030 if (!BI.isVirtual()) {
7031 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00007032 if (base->isEmpty())
7033 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00007034 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007035 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
7036 std::make_pair(offs, base));
7037 }
7038 }
7039 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007040
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007041 unsigned i = 0;
Hans Wennborga302cd92014-08-21 16:06:57 +00007042 for (auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007043 uint64_t offs = layout.getFieldOffset(i);
7044 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Hans Wennborga302cd92014-08-21 16:06:57 +00007045 std::make_pair(offs, Field));
7046 ++i;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007047 }
7048
7049 if (CXXRec && includeVBases) {
Aaron Ballman445a9392014-03-13 16:15:17 +00007050 for (const auto &BI : CXXRec->vbases()) {
7051 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00007052 if (base->isEmpty())
7053 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00007054 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Eli Friedman1d24af82013-09-18 01:59:16 +00007055 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
7056 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00007057 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
7058 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007059 }
7060 }
7061
7062 CharUnits size;
7063 if (CXXRec) {
7064 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
7065 } else {
7066 size = layout.getSize();
7067 }
7068
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007069#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007070 uint64_t CurOffs = 0;
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007071#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007072 std::multimap<uint64_t, NamedDecl *>::iterator
7073 CurLayObj = FieldOrBaseOffsets.begin();
7074
Douglas Gregorf5d6c742012-04-27 22:30:01 +00007075 if (CXXRec && CXXRec->isDynamicClass() &&
7076 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007077 if (FD) {
7078 S += "\"_vptr$";
7079 std::string recname = CXXRec->getNameAsString();
7080 if (recname.empty()) recname = "?";
7081 S += recname;
7082 S += '"';
7083 }
7084 S += "^^?";
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007085#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007086 CurOffs += getTypeSize(VoidPtrTy);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007087#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007088 }
7089
7090 if (!RDecl->hasFlexibleArrayMember()) {
7091 // Mark the end of the structure.
7092 uint64_t offs = toBits(size);
7093 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Craig Topper36250ad2014-05-12 05:36:57 +00007094 std::make_pair(offs, nullptr));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007095 }
7096
7097 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007098#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007099 assert(CurOffs <= CurLayObj->first);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007100 if (CurOffs < CurLayObj->first) {
Fangrui Song6907ce22018-07-30 19:24:48 +00007101 uint64_t padding = CurLayObj->first - CurOffs;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007102 // FIXME: There doesn't seem to be a way to indicate in the encoding that
7103 // packing/alignment of members is different that normal, in which case
7104 // the encoding will be out-of-sync with the real layout.
7105 // If the runtime switches to just consider the size of types without
7106 // taking into account alignment, we could make padding explicit in the
7107 // encoding (e.g. using arrays of chars). The encoding strings would be
7108 // longer then though.
7109 CurOffs += padding;
7110 }
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007111#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007112
7113 NamedDecl *dcl = CurLayObj->second;
Craig Topper36250ad2014-05-12 05:36:57 +00007114 if (!dcl)
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007115 break; // reached end of structure.
7116
Eugene Zelenko7855e772018-04-03 00:11:50 +00007117 if (auto *base = dyn_cast<CXXRecordDecl>(dcl)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007118 // We expand the bases without their virtual bases since those are going
7119 // in the initial structure. Note that this differs from gcc which
7120 // expands virtual bases each time one is encountered in the hierarchy,
7121 // making the encoding type bigger than it really is.
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00007122 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
7123 NotEncodedT);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00007124 assert(!base->isEmpty());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007125#ifndef NDEBUG
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00007126 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007127#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007128 } else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00007129 const auto *field = cast<FieldDecl>(dcl);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007130 if (FD) {
7131 S += '"';
7132 S += field->getNameAsString();
7133 S += '"';
7134 }
7135
7136 if (field->isBitField()) {
7137 EncodeBitField(this, S, field->getType(), field);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007138#ifndef NDEBUG
Richard Smithcaf33902011-10-10 18:28:20 +00007139 CurOffs += field->getBitWidthValue(*this);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007140#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007141 } else {
7142 QualType qt = field->getType();
7143 getLegacyIntegralTypeEncoding(qt);
7144 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
7145 /*OutermostType*/false,
7146 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00007147 /*StructField*/true,
7148 false, false, false, NotEncodedT);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007149#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007150 CurOffs += getTypeSize(field->getType());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007151#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007152 }
7153 }
7154 }
7155}
7156
Mike Stump11289f42009-09-09 15:08:12 +00007157void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00007158 std::string& S) const {
7159 if (QT & Decl::OBJC_TQ_In)
7160 S += 'n';
7161 if (QT & Decl::OBJC_TQ_Inout)
7162 S += 'N';
7163 if (QT & Decl::OBJC_TQ_Out)
7164 S += 'o';
7165 if (QT & Decl::OBJC_TQ_Bycopy)
7166 S += 'O';
7167 if (QT & Decl::OBJC_TQ_Byref)
7168 S += 'R';
7169 if (QT & Decl::OBJC_TQ_Oneway)
7170 S += 'V';
7171}
7172
Douglas Gregor3ea72692011-08-12 05:46:01 +00007173TypedefDecl *ASTContext::getObjCIdDecl() const {
7174 if (!ObjCIdDecl) {
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00007175 QualType T = getObjCObjectType(ObjCBuiltinIdTy, {}, {});
Douglas Gregor3ea72692011-08-12 05:46:01 +00007176 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00007177 ObjCIdDecl = buildImplicitTypedef(T, "id");
Douglas Gregor3ea72692011-08-12 05:46:01 +00007178 }
Douglas Gregor3ea72692011-08-12 05:46:01 +00007179 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00007180}
7181
Douglas Gregor52e02802011-08-12 06:17:30 +00007182TypedefDecl *ASTContext::getObjCSelDecl() const {
7183 if (!ObjCSelDecl) {
Alp Toker56b5cc92013-12-15 10:36:26 +00007184 QualType T = getPointerType(ObjCBuiltinSelTy);
7185 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
Douglas Gregor52e02802011-08-12 06:17:30 +00007186 }
7187 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00007188}
7189
Douglas Gregor0a586182011-08-12 05:59:41 +00007190TypedefDecl *ASTContext::getObjCClassDecl() const {
7191 if (!ObjCClassDecl) {
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00007192 QualType T = getObjCObjectType(ObjCBuiltinClassTy, {}, {});
Douglas Gregor0a586182011-08-12 05:59:41 +00007193 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00007194 ObjCClassDecl = buildImplicitTypedef(T, "Class");
Douglas Gregor0a586182011-08-12 05:59:41 +00007195 }
Douglas Gregor0a586182011-08-12 05:59:41 +00007196 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00007197}
7198
Douglas Gregord53ae832012-01-17 18:09:05 +00007199ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
7200 if (!ObjCProtocolClassDecl) {
Fangrui Song6907ce22018-07-30 19:24:48 +00007201 ObjCProtocolClassDecl
7202 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
Douglas Gregord53ae832012-01-17 18:09:05 +00007203 SourceLocation(),
7204 &Idents.get("Protocol"),
Douglas Gregor85f3f952015-07-07 03:57:15 +00007205 /*typeParamList=*/nullptr,
Craig Topper36250ad2014-05-12 05:36:57 +00007206 /*PrevDecl=*/nullptr,
Fangrui Song6907ce22018-07-30 19:24:48 +00007207 SourceLocation(), true);
Douglas Gregord53ae832012-01-17 18:09:05 +00007208 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007209
Douglas Gregord53ae832012-01-17 18:09:05 +00007210 return ObjCProtocolClassDecl;
7211}
7212
Meador Inge5d3fb222012-06-16 03:34:49 +00007213//===----------------------------------------------------------------------===//
7214// __builtin_va_list Construction Functions
7215//===----------------------------------------------------------------------===//
7216
Charles Davisc7d5c942015-09-17 20:55:33 +00007217static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context,
7218 StringRef Name) {
7219 // typedef char* __builtin[_ms]_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00007220 QualType T = Context->getPointerType(Context->CharTy);
Charles Davisc7d5c942015-09-17 20:55:33 +00007221 return Context->buildImplicitTypedef(T, Name);
7222}
7223
7224static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
7225 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
7226}
7227
7228static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
7229 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007230}
7231
7232static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
7233 // typedef void* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00007234 QualType T = Context->getPointerType(Context->VoidTy);
7235 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007236}
7237
Tim Northover9bb857a2013-01-31 12:13:10 +00007238static TypedefDecl *
7239CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00007240 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00007241 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00007242 if (Context->getLangOpts().CPlusPlus) {
7243 // namespace std { struct __va_list {
7244 NamespaceDecl *NS;
7245 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
7246 Context->getTranslationUnitDecl(),
Craig Topper36250ad2014-05-12 05:36:57 +00007247 /*Inline*/ false, SourceLocation(),
Tim Northover9bb857a2013-01-31 12:13:10 +00007248 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00007249 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00007250 NS->setImplicit();
Tim Northover9bb857a2013-01-31 12:13:10 +00007251 VaListTagDecl->setDeclContext(NS);
Tim Northover9bb857a2013-01-31 12:13:10 +00007252 }
7253
7254 VaListTagDecl->startDefinition();
7255
7256 const size_t NumFields = 5;
7257 QualType FieldTypes[NumFields];
7258 const char *FieldNames[NumFields];
7259
7260 // void *__stack;
7261 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
7262 FieldNames[0] = "__stack";
7263
7264 // void *__gr_top;
7265 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
7266 FieldNames[1] = "__gr_top";
7267
7268 // void *__vr_top;
7269 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
7270 FieldNames[2] = "__vr_top";
7271
7272 // int __gr_offs;
7273 FieldTypes[3] = Context->IntTy;
7274 FieldNames[3] = "__gr_offs";
7275
7276 // int __vr_offs;
7277 FieldTypes[4] = Context->IntTy;
7278 FieldNames[4] = "__vr_offs";
7279
7280 // Create fields
7281 for (unsigned i = 0; i < NumFields; ++i) {
7282 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7283 VaListTagDecl,
7284 SourceLocation(),
7285 SourceLocation(),
7286 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00007287 FieldTypes[i], /*TInfo=*/nullptr,
7288 /*BitWidth=*/nullptr,
Tim Northover9bb857a2013-01-31 12:13:10 +00007289 /*Mutable=*/false,
7290 ICIS_NoInit);
7291 Field->setAccess(AS_public);
7292 VaListTagDecl->addDecl(Field);
7293 }
7294 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00007295 Context->VaListTagDecl = VaListTagDecl;
Tim Northover9bb857a2013-01-31 12:13:10 +00007296 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Tim Northover9bb857a2013-01-31 12:13:10 +00007297
7298 // } __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00007299 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00007300}
7301
Meador Inge5d3fb222012-06-16 03:34:49 +00007302static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
7303 // typedef struct __va_list_tag {
7304 RecordDecl *VaListTagDecl;
7305
Alp Toker2dea15b2013-12-17 01:22:38 +00007306 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00007307 VaListTagDecl->startDefinition();
7308
7309 const size_t NumFields = 5;
7310 QualType FieldTypes[NumFields];
7311 const char *FieldNames[NumFields];
7312
7313 // unsigned char gpr;
7314 FieldTypes[0] = Context->UnsignedCharTy;
7315 FieldNames[0] = "gpr";
7316
7317 // unsigned char fpr;
7318 FieldTypes[1] = Context->UnsignedCharTy;
7319 FieldNames[1] = "fpr";
7320
7321 // unsigned short reserved;
7322 FieldTypes[2] = Context->UnsignedShortTy;
7323 FieldNames[2] = "reserved";
7324
7325 // void* overflow_arg_area;
7326 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
7327 FieldNames[3] = "overflow_arg_area";
7328
7329 // void* reg_save_area;
7330 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
7331 FieldNames[4] = "reg_save_area";
7332
7333 // Create fields
7334 for (unsigned i = 0; i < NumFields; ++i) {
7335 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
7336 SourceLocation(),
7337 SourceLocation(),
7338 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00007339 FieldTypes[i], /*TInfo=*/nullptr,
7340 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00007341 /*Mutable=*/false,
7342 ICIS_NoInit);
7343 Field->setAccess(AS_public);
7344 VaListTagDecl->addDecl(Field);
7345 }
7346 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00007347 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00007348 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
7349
7350 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00007351 TypedefDecl *VaListTagTypedefDecl =
7352 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
7353
Meador Inge5d3fb222012-06-16 03:34:49 +00007354 QualType VaListTagTypedefType =
7355 Context->getTypedefType(VaListTagTypedefDecl);
7356
7357 // typedef __va_list_tag __builtin_va_list[1];
7358 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
7359 QualType VaListTagArrayType
7360 = Context->getConstantArrayType(VaListTagTypedefType,
7361 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00007362 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007363}
7364
7365static TypedefDecl *
7366CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00007367 // struct __va_list_tag {
Meador Inge5d3fb222012-06-16 03:34:49 +00007368 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00007369 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00007370 VaListTagDecl->startDefinition();
7371
7372 const size_t NumFields = 4;
7373 QualType FieldTypes[NumFields];
7374 const char *FieldNames[NumFields];
7375
7376 // unsigned gp_offset;
7377 FieldTypes[0] = Context->UnsignedIntTy;
7378 FieldNames[0] = "gp_offset";
7379
7380 // unsigned fp_offset;
7381 FieldTypes[1] = Context->UnsignedIntTy;
7382 FieldNames[1] = "fp_offset";
7383
7384 // void* overflow_arg_area;
7385 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
7386 FieldNames[2] = "overflow_arg_area";
7387
7388 // void* reg_save_area;
7389 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
7390 FieldNames[3] = "reg_save_area";
7391
7392 // Create fields
7393 for (unsigned i = 0; i < NumFields; ++i) {
7394 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7395 VaListTagDecl,
7396 SourceLocation(),
7397 SourceLocation(),
7398 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00007399 FieldTypes[i], /*TInfo=*/nullptr,
7400 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00007401 /*Mutable=*/false,
7402 ICIS_NoInit);
7403 Field->setAccess(AS_public);
7404 VaListTagDecl->addDecl(Field);
7405 }
7406 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00007407 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00007408 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
7409
Richard Smith9b88a4c2015-07-27 05:40:23 +00007410 // };
Alp Toker56b5cc92013-12-15 10:36:26 +00007411
Richard Smith9b88a4c2015-07-27 05:40:23 +00007412 // typedef struct __va_list_tag __builtin_va_list[1];
Meador Inge5d3fb222012-06-16 03:34:49 +00007413 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00007414 QualType VaListTagArrayType =
7415 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00007416 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007417}
7418
7419static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
7420 // typedef int __builtin_va_list[4];
7421 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
Yaron Kerene0bcdd42016-10-08 06:45:10 +00007422 QualType IntArrayType =
7423 Context->getConstantArrayType(Context->IntTy, Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00007424 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007425}
7426
Logan Chien57086ce2012-10-10 06:56:20 +00007427static TypedefDecl *
7428CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00007429 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00007430 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00007431 if (Context->getLangOpts().CPlusPlus) {
7432 // namespace std { struct __va_list {
7433 NamespaceDecl *NS;
7434 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
7435 Context->getTranslationUnitDecl(),
7436 /*Inline*/false, SourceLocation(),
7437 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00007438 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00007439 NS->setImplicit();
Logan Chien57086ce2012-10-10 06:56:20 +00007440 VaListDecl->setDeclContext(NS);
Logan Chien57086ce2012-10-10 06:56:20 +00007441 }
7442
7443 VaListDecl->startDefinition();
7444
7445 // void * __ap;
7446 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7447 VaListDecl,
7448 SourceLocation(),
7449 SourceLocation(),
7450 &Context->Idents.get("__ap"),
7451 Context->getPointerType(Context->VoidTy),
Craig Topper36250ad2014-05-12 05:36:57 +00007452 /*TInfo=*/nullptr,
7453 /*BitWidth=*/nullptr,
Logan Chien57086ce2012-10-10 06:56:20 +00007454 /*Mutable=*/false,
7455 ICIS_NoInit);
7456 Field->setAccess(AS_public);
7457 VaListDecl->addDecl(Field);
7458
7459 // };
7460 VaListDecl->completeDefinition();
Oleg Ranevskyyb88d2472016-03-30 21:30:30 +00007461 Context->VaListTagDecl = VaListDecl;
Logan Chien57086ce2012-10-10 06:56:20 +00007462
7463 // typedef struct __va_list __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00007464 QualType T = Context->getRecordType(VaListDecl);
7465 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00007466}
7467
Ulrich Weigand47445072013-05-06 16:26:41 +00007468static TypedefDecl *
7469CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00007470 // struct __va_list_tag {
Ulrich Weigand47445072013-05-06 16:26:41 +00007471 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00007472 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00007473 VaListTagDecl->startDefinition();
7474
7475 const size_t NumFields = 4;
7476 QualType FieldTypes[NumFields];
7477 const char *FieldNames[NumFields];
7478
7479 // long __gpr;
7480 FieldTypes[0] = Context->LongTy;
7481 FieldNames[0] = "__gpr";
7482
7483 // long __fpr;
7484 FieldTypes[1] = Context->LongTy;
7485 FieldNames[1] = "__fpr";
7486
7487 // void *__overflow_arg_area;
7488 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
7489 FieldNames[2] = "__overflow_arg_area";
7490
7491 // void *__reg_save_area;
7492 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
7493 FieldNames[3] = "__reg_save_area";
7494
7495 // Create fields
7496 for (unsigned i = 0; i < NumFields; ++i) {
7497 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7498 VaListTagDecl,
7499 SourceLocation(),
7500 SourceLocation(),
7501 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00007502 FieldTypes[i], /*TInfo=*/nullptr,
7503 /*BitWidth=*/nullptr,
Ulrich Weigand47445072013-05-06 16:26:41 +00007504 /*Mutable=*/false,
7505 ICIS_NoInit);
7506 Field->setAccess(AS_public);
7507 VaListTagDecl->addDecl(Field);
7508 }
7509 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00007510 Context->VaListTagDecl = VaListTagDecl;
Ulrich Weigand47445072013-05-06 16:26:41 +00007511 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Ulrich Weigand47445072013-05-06 16:26:41 +00007512
Richard Smith9b88a4c2015-07-27 05:40:23 +00007513 // };
Ulrich Weigand47445072013-05-06 16:26:41 +00007514
7515 // typedef __va_list_tag __builtin_va_list[1];
7516 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00007517 QualType VaListTagArrayType =
7518 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Ulrich Weigand47445072013-05-06 16:26:41 +00007519
Alp Toker56b5cc92013-12-15 10:36:26 +00007520 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Ulrich Weigand47445072013-05-06 16:26:41 +00007521}
7522
Meador Inge5d3fb222012-06-16 03:34:49 +00007523static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
7524 TargetInfo::BuiltinVaListKind Kind) {
7525 switch (Kind) {
7526 case TargetInfo::CharPtrBuiltinVaList:
7527 return CreateCharPtrBuiltinVaListDecl(Context);
7528 case TargetInfo::VoidPtrBuiltinVaList:
7529 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northover9bb857a2013-01-31 12:13:10 +00007530 case TargetInfo::AArch64ABIBuiltinVaList:
7531 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00007532 case TargetInfo::PowerABIBuiltinVaList:
7533 return CreatePowerABIBuiltinVaListDecl(Context);
7534 case TargetInfo::X86_64ABIBuiltinVaList:
7535 return CreateX86_64ABIBuiltinVaListDecl(Context);
7536 case TargetInfo::PNaClABIBuiltinVaList:
7537 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00007538 case TargetInfo::AAPCSABIBuiltinVaList:
7539 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigand47445072013-05-06 16:26:41 +00007540 case TargetInfo::SystemZBuiltinVaList:
7541 return CreateSystemZBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00007542 }
7543
7544 llvm_unreachable("Unhandled __builtin_va_list type kind");
7545}
7546
7547TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00007548 if (!BuiltinVaListDecl) {
Meador Inge5d3fb222012-06-16 03:34:49 +00007549 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
Alp Toker56b5cc92013-12-15 10:36:26 +00007550 assert(BuiltinVaListDecl->isImplicit());
7551 }
Meador Inge5d3fb222012-06-16 03:34:49 +00007552
7553 return BuiltinVaListDecl;
7554}
7555
Richard Smith9b88a4c2015-07-27 05:40:23 +00007556Decl *ASTContext::getVaListTagDecl() const {
7557 // Force the creation of VaListTagDecl by building the __builtin_va_list
Meador Ingecfb60902012-07-01 15:57:25 +00007558 // declaration.
Richard Smith9b88a4c2015-07-27 05:40:23 +00007559 if (!VaListTagDecl)
7560 (void)getBuiltinVaListDecl();
Meador Ingecfb60902012-07-01 15:57:25 +00007561
Richard Smith9b88a4c2015-07-27 05:40:23 +00007562 return VaListTagDecl;
Meador Ingecfb60902012-07-01 15:57:25 +00007563}
7564
Charles Davisc7d5c942015-09-17 20:55:33 +00007565TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const {
7566 if (!BuiltinMSVaListDecl)
7567 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
7568
7569 return BuiltinMSVaListDecl;
7570}
7571
Erich Keane41af9712018-04-16 21:30:08 +00007572bool ASTContext::canBuiltinBeRedeclared(const FunctionDecl *FD) const {
7573 return BuiltinInfo.canBeRedeclared(FD->getBuiltinID());
7574}
7575
Ted Kremenek1b0ea822008-01-07 19:49:32 +00007576void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00007577 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00007578 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00007579
Ted Kremenek1b0ea822008-01-07 19:49:32 +00007580 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00007581}
7582
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007583/// Retrieve the template name that corresponds to a non-empty
John McCalld28ae272009-12-02 08:04:21 +00007584/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00007585TemplateName
7586ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
7587 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00007588 unsigned size = End - Begin;
7589 assert(size > 1 && "set is not overloaded!");
7590
7591 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
7592 size * sizeof(FunctionTemplateDecl*));
Eugene Zelenko7855e772018-04-03 00:11:50 +00007593 auto *OT = new (memory) OverloadedTemplateStorage(size);
John McCalld28ae272009-12-02 08:04:21 +00007594
7595 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00007596 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00007597 NamedDecl *D = *I;
7598 assert(isa<FunctionTemplateDecl>(D) ||
Richard Smithef53a3e2018-06-06 16:36:56 +00007599 isa<UnresolvedUsingValueDecl>(D) ||
John McCalld28ae272009-12-02 08:04:21 +00007600 (isa<UsingShadowDecl>(D) &&
7601 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
7602 *Storage++ = D;
7603 }
7604
7605 return TemplateName(OT);
7606}
7607
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007608/// Retrieve the template name that represents a qualified
Douglas Gregordc572a32009-03-30 22:58:21 +00007609/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00007610TemplateName
7611ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
7612 bool TemplateKeyword,
7613 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00007614 assert(NNS && "Missing nested-name-specifier in qualified template name");
Fangrui Song6907ce22018-07-30 19:24:48 +00007615
Douglas Gregorc42075a2010-02-04 18:10:26 +00007616 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00007617 llvm::FoldingSetNodeID ID;
7618 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
7619
Craig Topper36250ad2014-05-12 05:36:57 +00007620 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00007621 QualifiedTemplateName *QTN =
7622 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7623 if (!QTN) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007624 QTN = new (*this, alignof(QualifiedTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007625 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00007626 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
7627 }
7628
7629 return TemplateName(QTN);
7630}
7631
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007632/// Retrieve the template name that represents a dependent
Douglas Gregordc572a32009-03-30 22:58:21 +00007633/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00007634TemplateName
7635ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
7636 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00007637 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00007638 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00007639
7640 llvm::FoldingSetNodeID ID;
7641 DependentTemplateName::Profile(ID, NNS, Name);
7642
Craig Topper36250ad2014-05-12 05:36:57 +00007643 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00007644 DependentTemplateName *QTN =
7645 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7646
7647 if (QTN)
7648 return TemplateName(QTN);
7649
7650 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
7651 if (CanonNNS == NNS) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007652 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007653 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00007654 } else {
7655 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007656 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007657 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00007658 DependentTemplateName *CheckQTN =
7659 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7660 assert(!CheckQTN && "Dependent type name canonicalization broken");
7661 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00007662 }
7663
7664 DependentTemplateNames.InsertNode(QTN, InsertPos);
7665 return TemplateName(QTN);
7666}
7667
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007668/// Retrieve the template name that represents a dependent
Douglas Gregor71395fa2009-11-04 00:56:37 +00007669/// template name such as \c MetaFun::template operator+.
Fangrui Song6907ce22018-07-30 19:24:48 +00007670TemplateName
Douglas Gregor71395fa2009-11-04 00:56:37 +00007671ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00007672 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00007673 assert((!NNS || NNS->isDependent()) &&
7674 "Nested name specifier must be dependent");
Fangrui Song6907ce22018-07-30 19:24:48 +00007675
Douglas Gregor71395fa2009-11-04 00:56:37 +00007676 llvm::FoldingSetNodeID ID;
7677 DependentTemplateName::Profile(ID, NNS, Operator);
Craig Topper36250ad2014-05-12 05:36:57 +00007678
7679 void *InsertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00007680 DependentTemplateName *QTN
7681 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Fangrui Song6907ce22018-07-30 19:24:48 +00007682
Douglas Gregor71395fa2009-11-04 00:56:37 +00007683 if (QTN)
7684 return TemplateName(QTN);
Fangrui Song6907ce22018-07-30 19:24:48 +00007685
Douglas Gregor71395fa2009-11-04 00:56:37 +00007686 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
7687 if (CanonNNS == NNS) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007688 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007689 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00007690 } else {
7691 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007692 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007693 DependentTemplateName(NNS, Operator, Canon);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007694
Douglas Gregorc42075a2010-02-04 18:10:26 +00007695 DependentTemplateName *CheckQTN
7696 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7697 assert(!CheckQTN && "Dependent template name canonicalization broken");
7698 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00007699 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007700
Douglas Gregor71395fa2009-11-04 00:56:37 +00007701 DependentTemplateNames.InsertNode(QTN, InsertPos);
7702 return TemplateName(QTN);
7703}
7704
Fangrui Song6907ce22018-07-30 19:24:48 +00007705TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00007706ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
7707 TemplateName replacement) const {
7708 llvm::FoldingSetNodeID ID;
7709 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00007710
7711 void *insertPos = nullptr;
John McCalld9dfe3a2011-06-30 08:33:18 +00007712 SubstTemplateTemplateParmStorage *subst
7713 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
Fangrui Song6907ce22018-07-30 19:24:48 +00007714
John McCalld9dfe3a2011-06-30 08:33:18 +00007715 if (!subst) {
7716 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
7717 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
7718 }
7719
7720 return TemplateName(subst);
7721}
7722
Fangrui Song6907ce22018-07-30 19:24:48 +00007723TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00007724ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
7725 const TemplateArgument &ArgPack) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00007726 auto &Self = const_cast<ASTContext &>(*this);
Douglas Gregor5590be02011-01-15 06:45:20 +00007727 llvm::FoldingSetNodeID ID;
7728 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00007729
7730 void *InsertPos = nullptr;
Douglas Gregor5590be02011-01-15 06:45:20 +00007731 SubstTemplateTemplateParmPackStorage *Subst
7732 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
Fangrui Song6907ce22018-07-30 19:24:48 +00007733
Douglas Gregor5590be02011-01-15 06:45:20 +00007734 if (!Subst) {
Fangrui Song6907ce22018-07-30 19:24:48 +00007735 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00007736 ArgPack.pack_size(),
7737 ArgPack.pack_begin());
7738 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
7739 }
7740
7741 return TemplateName(Subst);
7742}
7743
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007744/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00007745/// TargetInfo, produce the corresponding type. The unsigned @p Type
7746/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00007747CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007748 switch (Type) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00007749 case TargetInfo::NoInt: return {};
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00007750 case TargetInfo::SignedChar: return SignedCharTy;
7751 case TargetInfo::UnsignedChar: return UnsignedCharTy;
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007752 case TargetInfo::SignedShort: return ShortTy;
7753 case TargetInfo::UnsignedShort: return UnsignedShortTy;
7754 case TargetInfo::SignedInt: return IntTy;
7755 case TargetInfo::UnsignedInt: return UnsignedIntTy;
7756 case TargetInfo::SignedLong: return LongTy;
7757 case TargetInfo::UnsignedLong: return UnsignedLongTy;
7758 case TargetInfo::SignedLongLong: return LongLongTy;
7759 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
7760 }
7761
David Blaikie83d382b2011-09-23 05:06:16 +00007762 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007763}
Ted Kremenek77c51b22008-07-24 23:58:27 +00007764
7765//===----------------------------------------------------------------------===//
7766// Type Predicates.
7767//===----------------------------------------------------------------------===//
7768
Fariborz Jahanian96207692009-02-18 21:49:28 +00007769/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
7770/// garbage collection attribute.
7771///
John McCall553d45a2011-01-12 00:34:59 +00007772Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007773 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00007774 return Qualifiers::GCNone;
7775
Erik Pilkingtonfa983902018-10-30 20:31:30 +00007776 assert(getLangOpts().ObjC);
John McCall553d45a2011-01-12 00:34:59 +00007777 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
7778
7779 // Default behaviour under objective-C's gc is for ObjC pointers
7780 // (or pointers to them) be treated as though they were declared
7781 // as __strong.
7782 if (GCAttrs == Qualifiers::GCNone) {
7783 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
7784 return Qualifiers::Strong;
7785 else if (Ty->isPointerType())
7786 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
7787 } else {
7788 // It's not valid to set GC attributes on anything that isn't a
7789 // pointer.
7790#ifndef NDEBUG
7791 QualType CT = Ty->getCanonicalTypeInternal();
Eugene Zelenko7855e772018-04-03 00:11:50 +00007792 while (const auto *AT = dyn_cast<ArrayType>(CT))
John McCall553d45a2011-01-12 00:34:59 +00007793 CT = AT->getElementType();
7794 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
7795#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00007796 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00007797 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00007798}
7799
Chris Lattner49af6a42008-04-07 06:51:04 +00007800//===----------------------------------------------------------------------===//
7801// Type Compatibility Testing
7802//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00007803
Mike Stump11289f42009-09-09 15:08:12 +00007804/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00007805/// compatible.
7806static bool areCompatVectorTypes(const VectorType *LHS,
7807 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00007808 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00007809 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00007810 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00007811}
7812
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007813bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
7814 QualType SecondVec) {
7815 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
7816 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
7817
7818 if (hasSameUnqualifiedType(FirstVec, SecondVec))
7819 return true;
7820
Bob Wilsone6aeebb2010-11-12 17:24:54 +00007821 // Treat Neon vector types and most AltiVec vector types as if they are the
7822 // equivalent GCC vector types.
Eugene Zelenko7855e772018-04-03 00:11:50 +00007823 const auto *First = FirstVec->getAs<VectorType>();
7824 const auto *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00007825 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007826 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00007827 First->getVectorKind() != VectorType::AltiVecPixel &&
7828 First->getVectorKind() != VectorType::AltiVecBool &&
7829 Second->getVectorKind() != VectorType::AltiVecPixel &&
7830 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007831 return true;
7832
7833 return false;
7834}
7835
Steve Naroff8e6aee52009-07-23 01:01:38 +00007836//===----------------------------------------------------------------------===//
7837// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
7838//===----------------------------------------------------------------------===//
7839
7840/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
7841/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00007842bool
7843ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
7844 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00007845 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00007846 return true;
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00007847 for (auto *PI : rProto->protocols())
7848 if (ProtocolCompatibleWithProtocol(lProto, PI))
Steve Naroff8e6aee52009-07-23 01:01:38 +00007849 return true;
7850 return false;
7851}
7852
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00007853/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
7854/// Class<pr1, ...>.
Fangrui Song6907ce22018-07-30 19:24:48 +00007855bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007856 QualType rhs) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00007857 const auto *lhsQID = lhs->getAs<ObjCObjectPointerType>();
7858 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00007859 assert((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
Fangrui Song6907ce22018-07-30 19:24:48 +00007860
Aaron Ballman83731462014-03-17 16:14:00 +00007861 for (auto *lhsProto : lhsQID->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007862 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00007863 for (auto *rhsProto : rhsOPT->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007864 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
7865 match = true;
7866 break;
7867 }
7868 }
7869 if (!match)
7870 return false;
7871 }
7872 return true;
7873}
7874
Steve Naroff8e6aee52009-07-23 01:01:38 +00007875/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
7876/// ObjCQualifiedIDType.
7877bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
7878 bool compare) {
7879 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00007880 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00007881 lhs->isObjCIdType() || lhs->isObjCClassType())
7882 return true;
Mike Stump11289f42009-09-09 15:08:12 +00007883 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00007884 rhs->isObjCIdType() || rhs->isObjCClassType())
7885 return true;
7886
7887 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00007888 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00007889
Steve Naroff8e6aee52009-07-23 01:01:38 +00007890 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00007891
Steve Naroff8e6aee52009-07-23 01:01:38 +00007892 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00007893 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00007894 // make sure we check the class hierarchy.
7895 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00007896 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007897 // when comparing an id<P> on lhs with a static type on rhs,
7898 // see if static class implements all of id's protocols, directly or
7899 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00007900 if (!rhsID->ClassImplementsProtocol(I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00007901 return false;
7902 }
7903 }
7904 // If there are no qualifiers and no interface, we have an 'id'.
7905 return true;
7906 }
Mike Stump11289f42009-09-09 15:08:12 +00007907 // Both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00007908 for (auto *lhsProto : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007909 bool match = false;
7910
7911 // when comparing an id<P> on lhs with a static type on rhs,
7912 // see if static class implements all of id's protocols, directly or
7913 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00007914 for (auto *rhsProto : rhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007915 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7916 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7917 match = true;
7918 break;
7919 }
7920 }
Mike Stump11289f42009-09-09 15:08:12 +00007921 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00007922 // make sure we check the class hierarchy.
7923 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00007924 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007925 // when comparing an id<P> on lhs with a static type on rhs,
7926 // see if static class implements all of id's protocols, directly or
7927 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00007928 if (rhsID->ClassImplementsProtocol(I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007929 match = true;
7930 break;
7931 }
7932 }
7933 }
7934 if (!match)
7935 return false;
7936 }
Mike Stump11289f42009-09-09 15:08:12 +00007937
Steve Naroff8e6aee52009-07-23 01:01:38 +00007938 return true;
7939 }
Mike Stump11289f42009-09-09 15:08:12 +00007940
Steve Naroff8e6aee52009-07-23 01:01:38 +00007941 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
7942 assert(rhsQID && "One of the LHS/RHS should be id<x>");
7943
Mike Stump11289f42009-09-09 15:08:12 +00007944 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00007945 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007946 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00007947 for (auto *lhsProto : lhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007948 bool match = false;
7949
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007950 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00007951 // see if static class implements all of id's protocols, directly or
7952 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007953 // First, lhs protocols in the qualifier list must be found, direct
7954 // or indirect in rhs's qualifier list or it is a mismatch.
Aaron Ballman83731462014-03-17 16:14:00 +00007955 for (auto *rhsProto : rhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007956 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7957 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7958 match = true;
7959 break;
7960 }
7961 }
7962 if (!match)
7963 return false;
7964 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007965
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007966 // Static class's protocols, or its super class or category protocols
7967 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
7968 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
7969 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
7970 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
7971 // This is rather dubious but matches gcc's behavior. If lhs has
7972 // no type qualifier and its class has no static protocol(s)
7973 // assume that it is mismatch.
7974 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
7975 return false;
Aaron Ballman83731462014-03-17 16:14:00 +00007976 for (auto *lhsProto : LHSInheritedProtocols) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007977 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00007978 for (auto *rhsProto : rhsQID->quals()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007979 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7980 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7981 match = true;
7982 break;
7983 }
7984 }
7985 if (!match)
7986 return false;
7987 }
7988 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00007989 return true;
7990 }
7991 return false;
7992}
7993
Eli Friedman47f77112008-08-22 00:56:42 +00007994/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00007995/// compatible for assignment from RHS to LHS. This handles validation of any
7996/// protocol qualifiers on the LHS or RHS.
Steve Naroff7cae42b2009-07-10 23:34:53 +00007997bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
7998 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00007999 const ObjCObjectType* LHS = LHSOPT->getObjectType();
8000 const ObjCObjectType* RHS = RHSOPT->getObjectType();
8001
Steve Naroff1329fa02009-07-15 18:40:39 +00008002 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00008003 if (LHS->isObjCUnqualifiedIdOrClass() ||
8004 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00008005 return true;
8006
Douglas Gregorab209d82015-07-07 03:58:42 +00008007 // Function object that propagates a successful result or handles
8008 // __kindof types.
8009 auto finish = [&](bool succeeded) -> bool {
8010 if (succeeded)
8011 return true;
8012
8013 if (!RHS->isKindOfType())
8014 return false;
8015
8016 // Strip off __kindof and protocol qualifiers, then check whether
8017 // we can assign the other way.
8018 return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this),
8019 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
8020 };
8021
8022 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
8023 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
8024 QualType(RHSOPT,0),
8025 false));
8026 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008027
Douglas Gregorab209d82015-07-07 03:58:42 +00008028 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
8029 return finish(ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
8030 QualType(RHSOPT,0)));
8031 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008032
John McCall8b07ec22010-05-15 11:32:37 +00008033 // If we have 2 user-defined types, fall into that path.
Douglas Gregorab209d82015-07-07 03:58:42 +00008034 if (LHS->getInterface() && RHS->getInterface()) {
8035 return finish(canAssignObjCInterfaces(LHS, RHS));
8036 }
Mike Stump11289f42009-09-09 15:08:12 +00008037
Steve Naroff8e6aee52009-07-23 01:01:38 +00008038 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00008039}
8040
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008041/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Fangrui Song6907ce22018-07-30 19:24:48 +00008042/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008043/// arguments in block literals. When passed as arguments, passing 'A*' where
8044/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
8045/// not OK. For the return type, the opposite is not OK.
8046bool ASTContext::canAssignObjCInterfacesInBlockPointer(
8047 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00008048 const ObjCObjectPointerType *RHSOPT,
8049 bool BlockReturnType) {
Douglas Gregorab209d82015-07-07 03:58:42 +00008050
8051 // Function object that propagates a successful result or handles
8052 // __kindof types.
8053 auto finish = [&](bool succeeded) -> bool {
8054 if (succeeded)
8055 return true;
8056
8057 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
8058 if (!Expected->isKindOfType())
8059 return false;
8060
8061 // Strip off __kindof and protocol qualifiers, then check whether
8062 // we can assign the other way.
8063 return canAssignObjCInterfacesInBlockPointer(
8064 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
8065 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
8066 BlockReturnType);
8067 };
8068
Fariborz Jahanian440a6832010-04-06 17:23:39 +00008069 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008070 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00008071
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008072 if (LHSOPT->isObjCBuiltinType()) {
Douglas Gregorab209d82015-07-07 03:58:42 +00008073 return finish(RHSOPT->isObjCBuiltinType() ||
8074 RHSOPT->isObjCQualifiedIdType());
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008075 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008076
Fariborz Jahanian440a6832010-04-06 17:23:39 +00008077 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Douglas Gregorab209d82015-07-07 03:58:42 +00008078 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
8079 QualType(RHSOPT,0),
8080 false));
Fangrui Song6907ce22018-07-30 19:24:48 +00008081
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008082 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
8083 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
8084 if (LHS && RHS) { // We have 2 user-defined types.
8085 if (LHS != RHS) {
8086 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00008087 return finish(BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008088 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00008089 return finish(!BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008090 }
8091 else
8092 return true;
8093 }
8094 return false;
8095}
8096
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008097/// Comparison routine for Objective-C protocols to be used with
8098/// llvm::array_pod_sort.
8099static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
8100 ObjCProtocolDecl * const *rhs) {
8101 return (*lhs)->getName().compare((*rhs)->getName());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008102}
8103
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008104/// getIntersectionOfProtocols - This routine finds the intersection of set
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008105/// of protocols inherited from two distinct objective-c pointer objects with
8106/// the given common base.
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008107/// It is used to build composite qualifier list of the composite type of
8108/// the conditional expression involving two objective-c pointer objects.
Fangrui Song6907ce22018-07-30 19:24:48 +00008109static
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008110void getIntersectionOfProtocols(ASTContext &Context,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008111 const ObjCInterfaceDecl *CommonBase,
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008112 const ObjCObjectPointerType *LHSOPT,
8113 const ObjCObjectPointerType *RHSOPT,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008114 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
Fangrui Song6907ce22018-07-30 19:24:48 +00008115
John McCall8b07ec22010-05-15 11:32:37 +00008116 const ObjCObjectType* LHS = LHSOPT->getObjectType();
8117 const ObjCObjectType* RHS = RHSOPT->getObjectType();
8118 assert(LHS->getInterface() && "LHS must have an interface base");
8119 assert(RHS->getInterface() && "RHS must have an interface base");
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008120
8121 // Add all of the protocols for the LHS.
8122 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
8123
8124 // Start with the protocol qualifiers.
8125 for (auto proto : LHS->quals()) {
8126 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008127 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008128
8129 // Also add the protocols associated with the LHS interface.
8130 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
8131
Raphael Isemannb23ccec2018-12-10 12:37:46 +00008132 // Add all of the protocols for the RHS.
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008133 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
8134
8135 // Start with the protocol qualifiers.
8136 for (auto proto : RHS->quals()) {
8137 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008138 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008139
8140 // Also add the protocols associated with the RHS interface.
8141 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
8142
8143 // Compute the intersection of the collected protocol sets.
8144 for (auto proto : LHSProtocolSet) {
8145 if (RHSProtocolSet.count(proto))
8146 IntersectionSet.push_back(proto);
8147 }
8148
8149 // Compute the set of protocols that is implied by either the common type or
8150 // the protocols within the intersection.
8151 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
8152 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
8153
8154 // Remove any implied protocols from the list of inherited protocols.
8155 if (!ImpliedProtocols.empty()) {
8156 IntersectionSet.erase(
8157 std::remove_if(IntersectionSet.begin(),
8158 IntersectionSet.end(),
8159 [&](ObjCProtocolDecl *proto) -> bool {
8160 return ImpliedProtocols.count(proto) > 0;
8161 }),
8162 IntersectionSet.end());
8163 }
8164
8165 // Sort the remaining protocols by name.
8166 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
8167 compareObjCProtocolsByName);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008168}
8169
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008170/// Determine whether the first type is a subtype of the second.
8171static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
8172 QualType rhs) {
8173 // Common case: two object pointers.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008174 const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
8175 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008176 if (lhsOPT && rhsOPT)
8177 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
8178
8179 // Two block pointers.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008180 const auto *lhsBlock = lhs->getAs<BlockPointerType>();
8181 const auto *rhsBlock = rhs->getAs<BlockPointerType>();
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008182 if (lhsBlock && rhsBlock)
8183 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
8184
8185 // If either is an unqualified 'id' and the other is a block, it's
8186 // acceptable.
8187 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
8188 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
8189 return true;
8190
8191 return false;
8192}
8193
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008194// Check that the given Objective-C type argument lists are equivalent.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008195static bool sameObjCTypeArgs(ASTContext &ctx,
8196 const ObjCInterfaceDecl *iface,
8197 ArrayRef<QualType> lhsArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00008198 ArrayRef<QualType> rhsArgs,
8199 bool stripKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008200 if (lhsArgs.size() != rhsArgs.size())
8201 return false;
8202
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008203 ObjCTypeParamList *typeParams = iface->getTypeParamList();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008204 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008205 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
8206 continue;
8207
8208 switch (typeParams->begin()[i]->getVariance()) {
8209 case ObjCTypeParamVariance::Invariant:
Douglas Gregorab209d82015-07-07 03:58:42 +00008210 if (!stripKindOf ||
8211 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
8212 rhsArgs[i].stripObjCKindOfType(ctx))) {
8213 return false;
8214 }
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008215 break;
8216
8217 case ObjCTypeParamVariance::Covariant:
8218 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
8219 return false;
8220 break;
8221
8222 case ObjCTypeParamVariance::Contravariant:
8223 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
8224 return false;
8225 break;
Douglas Gregorab209d82015-07-07 03:58:42 +00008226 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008227 }
8228
8229 return true;
8230}
8231
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00008232QualType ASTContext::areCommonBaseCompatible(
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008233 const ObjCObjectPointerType *Lptr,
8234 const ObjCObjectPointerType *Rptr) {
John McCall8b07ec22010-05-15 11:32:37 +00008235 const ObjCObjectType *LHS = Lptr->getObjectType();
8236 const ObjCObjectType *RHS = Rptr->getObjectType();
8237 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
8238 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008239
8240 if (!LDecl || !RDecl)
Eugene Zelenko7855e772018-04-03 00:11:50 +00008241 return {};
Douglas Gregore83b9562015-07-07 03:57:53 +00008242
Manman Renc46f7d12016-05-06 19:35:02 +00008243 // When either LHS or RHS is a kindof type, we should return a kindof type.
8244 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
8245 // kindof(A).
8246 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
8247
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008248 // Follow the left-hand side up the class hierarchy until we either hit a
8249 // root or find the RHS. Record the ancestors in case we don't find it.
8250 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
8251 LHSAncestors;
8252 while (true) {
8253 // Record this ancestor. We'll need this if the common type isn't in the
8254 // path from the LHS to the root.
8255 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
Douglas Gregore83b9562015-07-07 03:57:53 +00008256
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008257 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
8258 // Get the type arguments.
8259 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
8260 bool anyChanges = false;
8261 if (LHS->isSpecialized() && RHS->isSpecialized()) {
8262 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008263 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
8264 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00008265 /*stripKindOf=*/true))
Eugene Zelenko7855e772018-04-03 00:11:50 +00008266 return {};
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008267 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
8268 // If only one has type arguments, the result will not have type
8269 // arguments.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00008270 LHSTypeArgs = {};
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008271 anyChanges = true;
8272 }
8273
8274 // Compute the intersection of protocols.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008275 SmallVector<ObjCProtocolDecl *, 8> Protocols;
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008276 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
8277 Protocols);
John McCall8b07ec22010-05-15 11:32:37 +00008278 if (!Protocols.empty())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008279 anyChanges = true;
8280
8281 // If anything in the LHS will have changed, build a new result type.
Manman Renc46f7d12016-05-06 19:35:02 +00008282 // If we need to return a kindof type but LHS is not a kindof type, we
8283 // build a new result type.
8284 if (anyChanges || LHS->isKindOfType() != anyKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008285 QualType Result = getObjCInterfaceType(LHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00008286 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
Manman Renc46f7d12016-05-06 19:35:02 +00008287 anyKindOf || LHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008288 return getObjCObjectPointerType(Result);
8289 }
8290
8291 return getObjCObjectPointerType(QualType(LHS, 0));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008292 }
Douglas Gregore83b9562015-07-07 03:57:53 +00008293
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008294 // Find the superclass.
Douglas Gregore83b9562015-07-07 03:57:53 +00008295 QualType LHSSuperType = LHS->getSuperClassType();
8296 if (LHSSuperType.isNull())
8297 break;
8298
8299 LHS = LHSSuperType->castAs<ObjCObjectType>();
8300 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008301
8302 // We didn't find anything by following the LHS to its root; now check
8303 // the RHS against the cached set of ancestors.
8304 while (true) {
8305 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
8306 if (KnownLHS != LHSAncestors.end()) {
8307 LHS = KnownLHS->second;
8308
8309 // Get the type arguments.
8310 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
8311 bool anyChanges = false;
8312 if (LHS->isSpecialized() && RHS->isSpecialized()) {
8313 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008314 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
8315 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00008316 /*stripKindOf=*/true))
Eugene Zelenko7855e772018-04-03 00:11:50 +00008317 return {};
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008318 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
8319 // If only one has type arguments, the result will not have type
8320 // arguments.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00008321 RHSTypeArgs = {};
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008322 anyChanges = true;
8323 }
8324
8325 // Compute the intersection of protocols.
8326 SmallVector<ObjCProtocolDecl *, 8> Protocols;
8327 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
8328 Protocols);
8329 if (!Protocols.empty())
8330 anyChanges = true;
8331
Manman Renc46f7d12016-05-06 19:35:02 +00008332 // If we need to return a kindof type but RHS is not a kindof type, we
8333 // build a new result type.
8334 if (anyChanges || RHS->isKindOfType() != anyKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008335 QualType Result = getObjCInterfaceType(RHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00008336 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
Manman Renc46f7d12016-05-06 19:35:02 +00008337 anyKindOf || RHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008338 return getObjCObjectPointerType(Result);
8339 }
8340
8341 return getObjCObjectPointerType(QualType(RHS, 0));
8342 }
8343
8344 // Find the superclass of the RHS.
8345 QualType RHSSuperType = RHS->getSuperClassType();
8346 if (RHSSuperType.isNull())
8347 break;
8348
8349 RHS = RHSSuperType->castAs<ObjCObjectType>();
8350 }
8351
Eugene Zelenko7855e772018-04-03 00:11:50 +00008352 return {};
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00008353}
8354
John McCall8b07ec22010-05-15 11:32:37 +00008355bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
8356 const ObjCObjectType *RHS) {
8357 assert(LHS->getInterface() && "LHS is not an interface type");
8358 assert(RHS->getInterface() && "RHS is not an interface type");
8359
Chris Lattner49af6a42008-04-07 06:51:04 +00008360 // Verify that the base decls are compatible: the RHS must be a subclass of
8361 // the LHS.
Douglas Gregore83b9562015-07-07 03:57:53 +00008362 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
8363 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
8364 if (!IsSuperClass)
Chris Lattner49af6a42008-04-07 06:51:04 +00008365 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008366
Douglas Gregore83b9562015-07-07 03:57:53 +00008367 // If the LHS has protocol qualifiers, determine whether all of them are
8368 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
8369 // LHS).
8370 if (LHS->getNumProtocols() > 0) {
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00008371 // OK if conversion of LHS to SuperClass results in narrowing of types
8372 // ; i.e., SuperClass may implement at least one of the protocols
8373 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
8374 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
8375 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
8376 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
8377 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
8378 // qualifiers.
8379 for (auto *RHSPI : RHS->quals())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008380 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00008381 // If there is no protocols associated with RHS, it is not a match.
8382 if (SuperClassInheritedProtocols.empty())
Steve Naroff114aecb2009-03-01 16:12:44 +00008383 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00008384
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00008385 for (const auto *LHSProto : LHS->quals()) {
8386 bool SuperImplementsProtocol = false;
8387 for (auto *SuperClassProto : SuperClassInheritedProtocols)
8388 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
8389 SuperImplementsProtocol = true;
8390 break;
8391 }
8392 if (!SuperImplementsProtocol)
8393 return false;
8394 }
Chris Lattner49af6a42008-04-07 06:51:04 +00008395 }
Douglas Gregore83b9562015-07-07 03:57:53 +00008396
8397 // If the LHS is specialized, we may need to check type arguments.
8398 if (LHS->isSpecialized()) {
8399 // Follow the superclass chain until we've matched the LHS class in the
8400 // hierarchy. This substitutes type arguments through.
8401 const ObjCObjectType *RHSSuper = RHS;
8402 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
8403 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
8404
8405 // If the RHS is specializd, compare type arguments.
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008406 if (RHSSuper->isSpecialized() &&
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008407 !sameObjCTypeArgs(*this, LHS->getInterface(),
8408 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00008409 /*stripKindOf=*/true)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008410 return false;
Douglas Gregore83b9562015-07-07 03:57:53 +00008411 }
8412 }
8413
8414 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00008415}
8416
Steve Naroffb7605152009-02-12 17:52:19 +00008417bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
8418 // get the "pointed to" types
Eugene Zelenko7855e772018-04-03 00:11:50 +00008419 const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
8420 const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00008421
Steve Naroff7cae42b2009-07-10 23:34:53 +00008422 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00008423 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00008424
8425 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
8426 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00008427}
8428
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00008429bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
8430 return canAssignObjCInterfaces(
8431 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
8432 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
8433}
8434
Mike Stump11289f42009-09-09 15:08:12 +00008435/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00008436/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00008437/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00008438/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008439bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
8440 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00008441 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00008442 return hasSameType(LHS, RHS);
Joey Gouly5788b782016-11-18 14:10:54 +00008443
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008444 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00008445}
8446
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00008447bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00008448 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00008449}
8450
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008451bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
8452 return !mergeTypes(LHS, RHS, true).isNull();
8453}
8454
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00008455/// mergeTransparentUnionType - if T is a transparent union type and a member
8456/// of T is compatible with SubType, return the merged type, else return
8457/// QualType()
8458QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
8459 bool OfBlockPointer,
8460 bool Unqualified) {
8461 if (const RecordType *UT = T->getAsUnionType()) {
8462 RecordDecl *UD = UT->getDecl();
8463 if (UD->hasAttr<TransparentUnionAttr>()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008464 for (const auto *I : UD->fields()) {
8465 QualType ET = I->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00008466 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
8467 if (!MT.isNull())
8468 return MT;
8469 }
8470 }
8471 }
8472
Eugene Zelenko7855e772018-04-03 00:11:50 +00008473 return {};
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00008474}
8475
Alp Toker9cacbab2014-01-20 20:26:09 +00008476/// mergeFunctionParameterTypes - merge two types which appear as function
8477/// parameter types
8478QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
8479 bool OfBlockPointer,
8480 bool Unqualified) {
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00008481 // GNU extension: two types are compatible if they appear as a function
8482 // argument, one of the types is a transparent union type and the other
8483 // type is compatible with a union member
8484 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
8485 Unqualified);
8486 if (!lmerge.isNull())
8487 return lmerge;
8488
8489 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
8490 Unqualified);
8491 if (!rmerge.isNull())
8492 return rmerge;
8493
8494 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
8495}
8496
Fangrui Song6907ce22018-07-30 19:24:48 +00008497QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008498 bool OfBlockPointer,
8499 bool Unqualified) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00008500 const auto *lbase = lhs->getAs<FunctionType>();
8501 const auto *rbase = rhs->getAs<FunctionType>();
8502 const auto *lproto = dyn_cast<FunctionProtoType>(lbase);
8503 const auto *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00008504 bool allLTypes = true;
8505 bool allRTypes = true;
8506
8507 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008508 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00008509 if (OfBlockPointer) {
Alp Toker314cc812014-01-25 16:55:45 +00008510 QualType RHS = rbase->getReturnType();
8511 QualType LHS = lbase->getReturnType();
Fariborz Jahanian17825972011-02-11 18:46:17 +00008512 bool UnqualifiedResult = Unqualified;
8513 if (!UnqualifiedResult)
8514 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00008515 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00008516 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008517 else
Alp Toker314cc812014-01-25 16:55:45 +00008518 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
John McCall8c6b56f2010-12-15 01:06:38 +00008519 Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00008520 if (retType.isNull())
8521 return {};
Fangrui Song6907ce22018-07-30 19:24:48 +00008522
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008523 if (Unqualified)
8524 retType = retType.getUnqualifiedType();
8525
Alp Toker314cc812014-01-25 16:55:45 +00008526 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
8527 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008528 if (Unqualified) {
8529 LRetType = LRetType.getUnqualifiedType();
8530 RRetType = RRetType.getUnqualifiedType();
8531 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008532
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008533 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00008534 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008535 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00008536 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00008537
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00008538 // FIXME: double check this
8539 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
8540 // rbase->getRegParmAttr() != 0 &&
8541 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00008542 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
8543 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00008544
Douglas Gregor8c940862010-01-18 17:14:39 +00008545 // Compatible functions must have compatible calling conventions
Reid Kleckner78af0702013-08-27 23:08:25 +00008546 if (lbaseInfo.getCC() != rbaseInfo.getCC())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008547 return {};
Mike Stump11289f42009-09-09 15:08:12 +00008548
John McCall8c6b56f2010-12-15 01:06:38 +00008549 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00008550 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008551 return {};
John McCall8c6b56f2010-12-15 01:06:38 +00008552 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008553 return {};
John McCall8c6b56f2010-12-15 01:06:38 +00008554
John McCall31168b02011-06-15 23:02:42 +00008555 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008556 return {};
Oren Ben Simhon318a6ea2017-04-27 12:01:00 +00008557 if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008558 return {};
Oren Ben Simhon220671a2018-03-17 13:31:35 +00008559 if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008560 return {};
John McCall31168b02011-06-15 23:02:42 +00008561
John McCall8c6b56f2010-12-15 01:06:38 +00008562 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
8563 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00008564
Rafael Espindola8778c282012-11-29 16:09:03 +00008565 if (lbaseInfo.getNoReturn() != NoReturn)
8566 allLTypes = false;
8567 if (rbaseInfo.getNoReturn() != NoReturn)
8568 allRTypes = false;
8569
John McCall31168b02011-06-15 23:02:42 +00008570 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00008571
Eli Friedman47f77112008-08-22 00:56:42 +00008572 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00008573 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
8574 "C++ shouldn't be here");
Alp Toker601b22c2014-01-21 23:35:24 +00008575 // Compatible functions must have the same number of parameters
8576 if (lproto->getNumParams() != rproto->getNumParams())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008577 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00008578
8579 // Variadic and non-variadic functions aren't compatible
8580 if (lproto->isVariadic() != rproto->isVariadic())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008581 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00008582
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00008583 if (lproto->getTypeQuals() != rproto->getTypeQuals())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008584 return {};
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00008585
Akira Hatanaka98a49332017-09-22 00:41:05 +00008586 SmallVector<FunctionProtoType::ExtParameterInfo, 4> newParamInfos;
8587 bool canUseLeft, canUseRight;
8588 if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight,
8589 newParamInfos))
Eugene Zelenko7855e772018-04-03 00:11:50 +00008590 return {};
Alp Toker601b22c2014-01-21 23:35:24 +00008591
Akira Hatanaka98a49332017-09-22 00:41:05 +00008592 if (!canUseLeft)
8593 allLTypes = false;
8594 if (!canUseRight)
8595 allRTypes = false;
8596
Alp Toker601b22c2014-01-21 23:35:24 +00008597 // Check parameter type compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008598 SmallVector<QualType, 10> types;
Alp Toker601b22c2014-01-21 23:35:24 +00008599 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
8600 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
8601 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
8602 QualType paramType = mergeFunctionParameterTypes(
8603 lParamType, rParamType, OfBlockPointer, Unqualified);
8604 if (paramType.isNull())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008605 return {};
Alp Toker601b22c2014-01-21 23:35:24 +00008606
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008607 if (Unqualified)
Alp Toker601b22c2014-01-21 23:35:24 +00008608 paramType = paramType.getUnqualifiedType();
8609
8610 types.push_back(paramType);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008611 if (Unqualified) {
Alp Toker601b22c2014-01-21 23:35:24 +00008612 lParamType = lParamType.getUnqualifiedType();
8613 rParamType = rParamType.getUnqualifiedType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008614 }
Alp Toker601b22c2014-01-21 23:35:24 +00008615
8616 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00008617 allLTypes = false;
Alp Toker601b22c2014-01-21 23:35:24 +00008618 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00008619 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00008620 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008621
Eli Friedman47f77112008-08-22 00:56:42 +00008622 if (allLTypes) return lhs;
8623 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00008624
8625 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
8626 EPI.ExtInfo = einfo;
Akira Hatanaka98a49332017-09-22 00:41:05 +00008627 EPI.ExtParameterInfos =
8628 newParamInfos.empty() ? nullptr : newParamInfos.data();
Jordan Rose5c382722013-03-08 21:51:21 +00008629 return getFunctionType(retType, types, EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00008630 }
8631
8632 if (lproto) allRTypes = false;
8633 if (rproto) allLTypes = false;
8634
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008635 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00008636 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00008637 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eugene Zelenko7855e772018-04-03 00:11:50 +00008638 if (proto->isVariadic())
8639 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00008640 // Check that the types are compatible with the types that
8641 // would result from default argument promotions (C99 6.7.5.3p15).
8642 // The only types actually affected are promotable integer
8643 // types and floats, which would be passed as a different
8644 // type depending on whether the prototype is visible.
Alp Toker601b22c2014-01-21 23:35:24 +00008645 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
8646 QualType paramTy = proto->getParamType(i);
Alp Toker9cacbab2014-01-20 20:26:09 +00008647
Eli Friedman448ce402012-08-30 00:44:15 +00008648 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00008649 // to pass enum values.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008650 if (const auto *Enum = paramTy->getAs<EnumType>()) {
Alp Toker601b22c2014-01-21 23:35:24 +00008651 paramTy = Enum->getDecl()->getIntegerType();
8652 if (paramTy.isNull())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008653 return {};
Eli Friedman448ce402012-08-30 00:44:15 +00008654 }
Alp Toker601b22c2014-01-21 23:35:24 +00008655
8656 if (paramTy->isPromotableIntegerType() ||
8657 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
Eugene Zelenko7855e772018-04-03 00:11:50 +00008658 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00008659 }
8660
8661 if (allLTypes) return lhs;
8662 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00008663
8664 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
8665 EPI.ExtInfo = einfo;
Alp Toker9cacbab2014-01-20 20:26:09 +00008666 return getFunctionType(retType, proto->getParamTypes(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00008667 }
8668
8669 if (allLTypes) return lhs;
8670 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00008671 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00008672}
8673
John McCall433c2e62013-03-21 00:10:07 +00008674/// Given that we have an enum type and a non-enum type, try to merge them.
8675static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
8676 QualType other, bool isBlockReturnType) {
8677 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
8678 // a signed integer type, or an unsigned integer type.
8679 // Compatibility is based on the underlying type, not the promotion
8680 // type.
8681 QualType underlyingType = ET->getDecl()->getIntegerType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00008682 if (underlyingType.isNull())
8683 return {};
John McCall433c2e62013-03-21 00:10:07 +00008684 if (Context.hasSameType(underlyingType, other))
8685 return other;
8686
8687 // In block return types, we're more permissive and accept any
8688 // integral type of the same size.
8689 if (isBlockReturnType && other->isIntegerType() &&
8690 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
8691 return other;
8692
Eugene Zelenko7855e772018-04-03 00:11:50 +00008693 return {};
John McCall433c2e62013-03-21 00:10:07 +00008694}
8695
Fangrui Song6907ce22018-07-30 19:24:48 +00008696QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008697 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00008698 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00008699 // C++ [expr]: If an expression initially has the type "reference to T", the
8700 // type is adjusted to "T" prior to any further analysis, the expression
8701 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00008702 // expression is an lvalue unless the reference is an rvalue reference and
8703 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00008704 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
8705 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008706
8707 if (Unqualified) {
8708 LHS = LHS.getUnqualifiedType();
8709 RHS = RHS.getUnqualifiedType();
8710 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008711
Eli Friedman47f77112008-08-22 00:56:42 +00008712 QualType LHSCan = getCanonicalType(LHS),
8713 RHSCan = getCanonicalType(RHS);
8714
8715 // If two types are identical, they are compatible.
8716 if (LHSCan == RHSCan)
8717 return LHS;
8718
John McCall8ccfcb52009-09-24 19:53:00 +00008719 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00008720 Qualifiers LQuals = LHSCan.getLocalQualifiers();
8721 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00008722 if (LQuals != RQuals) {
8723 // If any of these qualifiers are different, we have a type
8724 // mismatch.
8725 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00008726 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
Roger Ferrer Ibanezd93add32017-02-24 08:41:09 +00008727 LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
8728 LQuals.hasUnaligned() != RQuals.hasUnaligned())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008729 return {};
John McCall8ccfcb52009-09-24 19:53:00 +00008730
8731 // Exactly one GC qualifier difference is allowed: __strong is
8732 // okay if the other type has no GC qualifier but is an Objective
8733 // C object pointer (i.e. implicitly strong by default). We fix
8734 // this by pretending that the unqualified type was actually
8735 // qualified __strong.
8736 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
8737 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
8738 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
8739
8740 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
Eugene Zelenko7855e772018-04-03 00:11:50 +00008741 return {};
John McCall8ccfcb52009-09-24 19:53:00 +00008742
8743 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
8744 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
8745 }
8746 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
8747 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
8748 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00008749 return {};
John McCall8ccfcb52009-09-24 19:53:00 +00008750 }
8751
8752 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00008753
Eli Friedmandcca6332009-06-01 01:22:52 +00008754 Type::TypeClass LHSClass = LHSCan->getTypeClass();
8755 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00008756
Chris Lattnerfd652912008-01-14 05:45:46 +00008757 // We want to consider the two function types to be the same for these
8758 // comparisons, just force one to the other.
8759 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
8760 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00008761
8762 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00008763 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
8764 LHSClass = Type::ConstantArray;
8765 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
8766 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00008767
John McCall8b07ec22010-05-15 11:32:37 +00008768 // ObjCInterfaces are just specialized ObjCObjects.
8769 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
8770 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
8771
Nate Begemance4d7fc2008-04-18 23:10:10 +00008772 // Canonicalize ExtVector -> Vector.
8773 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
8774 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00008775
Chris Lattner95554662008-04-07 05:43:21 +00008776 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00008777 if (LHSClass != RHSClass) {
John McCall433c2e62013-03-21 00:10:07 +00008778 // Note that we only have special rules for turning block enum
8779 // returns into block int returns, not vice-versa.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008780 if (const auto *ETy = LHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00008781 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00008782 }
John McCall9dd450b2009-09-21 23:43:11 +00008783 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00008784 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00008785 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00008786 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00008787 if (OfBlockPointer && !BlockReturnType) {
8788 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
8789 return LHS;
8790 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
8791 return RHS;
8792 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008793
Eugene Zelenko7855e772018-04-03 00:11:50 +00008794 return {};
Steve Naroff32e44c02007-10-15 20:41:53 +00008795 }
Eli Friedman47f77112008-08-22 00:56:42 +00008796
Steve Naroffc6edcbd2008-01-09 22:43:08 +00008797 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00008798 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008799#define TYPE(Class, Base)
8800#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00008801#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008802#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
8803#define DEPENDENT_TYPE(Class, Base) case Type::Class:
8804#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00008805 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008806
Richard Smith27d807c2013-04-30 13:56:41 +00008807 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00008808 case Type::DeducedTemplateSpecialization:
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00008809 case Type::LValueReference:
8810 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008811 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00008812 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008813
John McCall8b07ec22010-05-15 11:32:37 +00008814 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008815 case Type::IncompleteArray:
8816 case Type::VariableArray:
8817 case Type::FunctionProto:
8818 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00008819 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008820
Chris Lattnerfd652912008-01-14 05:45:46 +00008821 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00008822 {
8823 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008824 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
8825 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008826 if (Unqualified) {
8827 LHSPointee = LHSPointee.getUnqualifiedType();
8828 RHSPointee = RHSPointee.getUnqualifiedType();
8829 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008830 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008831 Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00008832 if (ResultType.isNull())
8833 return {};
Eli Friedman091a9ac2009-06-02 05:28:56 +00008834 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00008835 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00008836 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00008837 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00008838 return getPointerType(ResultType);
8839 }
Steve Naroff68e167d2008-12-10 17:49:55 +00008840 case Type::BlockPointer:
8841 {
8842 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008843 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
8844 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008845 if (Unqualified) {
8846 LHSPointee = LHSPointee.getUnqualifiedType();
8847 RHSPointee = RHSPointee.getUnqualifiedType();
8848 }
Anastasia Stulova81a25e352017-03-10 15:23:07 +00008849 if (getLangOpts().OpenCL) {
8850 Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
8851 Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
8852 // Blocks can't be an expression in a ternary operator (OpenCL v2.0
8853 // 6.12.5) thus the following check is asymmetric.
8854 if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual))
Eugene Zelenko7855e772018-04-03 00:11:50 +00008855 return {};
Anastasia Stulova81a25e352017-03-10 15:23:07 +00008856 LHSPteeQual.removeAddressSpace();
8857 RHSPteeQual.removeAddressSpace();
8858 LHSPointee =
8859 QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
8860 RHSPointee =
8861 QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
8862 }
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008863 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
8864 Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00008865 if (ResultType.isNull())
8866 return {};
Steve Naroff68e167d2008-12-10 17:49:55 +00008867 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
8868 return LHS;
8869 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
8870 return RHS;
8871 return getBlockPointerType(ResultType);
8872 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00008873 case Type::Atomic:
8874 {
8875 // Merge two pointer types, while trying to preserve typedef info
8876 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
8877 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
8878 if (Unqualified) {
8879 LHSValue = LHSValue.getUnqualifiedType();
8880 RHSValue = RHSValue.getUnqualifiedType();
8881 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008882 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
Eli Friedman0dfb8892011-10-06 23:00:33 +00008883 Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00008884 if (ResultType.isNull())
8885 return {};
Eli Friedman0dfb8892011-10-06 23:00:33 +00008886 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
8887 return LHS;
8888 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
8889 return RHS;
8890 return getAtomicType(ResultType);
8891 }
Chris Lattnerfd652912008-01-14 05:45:46 +00008892 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00008893 {
8894 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
8895 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
8896 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008897 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00008898
8899 QualType LHSElem = getAsArrayType(LHS)->getElementType();
8900 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008901 if (Unqualified) {
8902 LHSElem = LHSElem.getUnqualifiedType();
8903 RHSElem = RHSElem.getUnqualifiedType();
8904 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008905
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008906 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00008907 if (ResultType.isNull())
8908 return {};
Jeremy Morse8129c5c2018-06-05 09:18:26 +00008909
8910 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
8911 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
8912
8913 // If either side is a variable array, and both are complete, check whether
8914 // the current dimension is definite.
8915 if (LVAT || RVAT) {
8916 auto SizeFetch = [this](const VariableArrayType* VAT,
8917 const ConstantArrayType* CAT)
8918 -> std::pair<bool,llvm::APInt> {
8919 if (VAT) {
8920 llvm::APSInt TheInt;
8921 Expr *E = VAT->getSizeExpr();
8922 if (E && E->isIntegerConstantExpr(TheInt, *this))
8923 return std::make_pair(true, TheInt);
8924 else
8925 return std::make_pair(false, TheInt);
8926 } else if (CAT) {
8927 return std::make_pair(true, CAT->getSize());
8928 } else {
8929 return std::make_pair(false, llvm::APInt());
8930 }
8931 };
8932
8933 bool HaveLSize, HaveRSize;
8934 llvm::APInt LSize, RSize;
8935 std::tie(HaveLSize, LSize) = SizeFetch(LVAT, LCAT);
8936 std::tie(HaveRSize, RSize) = SizeFetch(RVAT, RCAT);
8937 if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(LSize, RSize))
8938 return {}; // Definite, but unequal, array dimension
8939 }
8940
Chris Lattner465fa322008-10-05 17:34:18 +00008941 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
8942 return LHS;
8943 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
8944 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00008945 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
8946 ArrayType::ArraySizeModifier(), 0);
8947 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
8948 ArrayType::ArraySizeModifier(), 0);
Chris Lattner465fa322008-10-05 17:34:18 +00008949 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
8950 return LHS;
8951 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
8952 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00008953 if (LVAT) {
8954 // FIXME: This isn't correct! But tricky to implement because
8955 // the array's size has to be the size of LHS, but the type
8956 // has to be different.
8957 return LHS;
8958 }
8959 if (RVAT) {
8960 // FIXME: This isn't correct! But tricky to implement because
8961 // the array's size has to be the size of RHS, but the type
8962 // has to be different.
8963 return RHS;
8964 }
Eli Friedman3e62c212008-08-22 01:48:21 +00008965 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
8966 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00008967 return getIncompleteArrayType(ResultType,
8968 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00008969 }
Chris Lattnerfd652912008-01-14 05:45:46 +00008970 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008971 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008972 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008973 case Type::Enum:
Eugene Zelenko7855e772018-04-03 00:11:50 +00008974 return {};
Chris Lattnerfd652912008-01-14 05:45:46 +00008975 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00008976 // Only exactly equal builtin types are compatible, which is tested above.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008977 return {};
Daniel Dunbar804c0442009-01-28 21:22:12 +00008978 case Type::Complex:
8979 // Distinct complex types are incompatible.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008980 return {};
Chris Lattner7bbd3d72008-04-07 05:55:38 +00008981 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00008982 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00008983 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
8984 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00008985 return LHS;
Eugene Zelenko7855e772018-04-03 00:11:50 +00008986 return {};
John McCall8b07ec22010-05-15 11:32:37 +00008987 case Type::ObjCObject: {
8988 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00008989 // FIXME: This should be type compatibility, e.g. whether
8990 // "LHS x; RHS x;" at global scope is legal.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008991 const auto *LHSIface = LHS->getAs<ObjCObjectType>();
8992 const auto *RHSIface = RHS->getAs<ObjCObjectType>();
John McCall8b07ec22010-05-15 11:32:37 +00008993 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00008994 return LHS;
8995
Eugene Zelenko7855e772018-04-03 00:11:50 +00008996 return {};
Cedric Venet4fc88b72009-02-21 17:14:49 +00008997 }
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00008998 case Type::ObjCObjectPointer:
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008999 if (OfBlockPointer) {
9000 if (canAssignObjCInterfacesInBlockPointer(
9001 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00009002 RHS->getAs<ObjCObjectPointerType>(),
9003 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00009004 return LHS;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009005 return {};
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00009006 }
John McCall9dd450b2009-09-21 23:43:11 +00009007 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
9008 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00009009 return LHS;
9010
Eugene Zelenko7855e772018-04-03 00:11:50 +00009011 return {};
Xiuli Pan9c14e282016-01-09 12:53:17 +00009012 case Type::Pipe:
Joey Goulye3c85de2016-12-01 11:30:49 +00009013 assert(LHS != RHS &&
9014 "Equivalent pipe types should have already been handled!");
Eugene Zelenko7855e772018-04-03 00:11:50 +00009015 return {};
Xiuli Pan9c14e282016-01-09 12:53:17 +00009016 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00009017
David Blaikie8a40f702012-01-17 06:56:22 +00009018 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00009019}
Ted Kremenekfc581a92007-10-31 17:10:13 +00009020
Akira Hatanaka98a49332017-09-22 00:41:05 +00009021bool ASTContext::mergeExtParameterInfo(
9022 const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType,
9023 bool &CanUseFirst, bool &CanUseSecond,
9024 SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &NewParamInfos) {
9025 assert(NewParamInfos.empty() && "param info list not empty");
9026 CanUseFirst = CanUseSecond = true;
9027 bool FirstHasInfo = FirstFnType->hasExtParameterInfos();
9028 bool SecondHasInfo = SecondFnType->hasExtParameterInfos();
9029
John McCall18afab72016-03-01 00:49:02 +00009030 // Fast path: if the first type doesn't have ext parameter infos,
Akira Hatanaka98a49332017-09-22 00:41:05 +00009031 // we match if and only if the second type also doesn't have them.
9032 if (!FirstHasInfo && !SecondHasInfo)
9033 return true;
John McCall18afab72016-03-01 00:49:02 +00009034
Akira Hatanaka98a49332017-09-22 00:41:05 +00009035 bool NeedParamInfo = false;
9036 size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size()
9037 : SecondFnType->getExtParameterInfos().size();
John McCall18afab72016-03-01 00:49:02 +00009038
Akira Hatanaka98a49332017-09-22 00:41:05 +00009039 for (size_t I = 0; I < E; ++I) {
9040 FunctionProtoType::ExtParameterInfo FirstParam, SecondParam;
9041 if (FirstHasInfo)
9042 FirstParam = FirstFnType->getExtParameterInfo(I);
9043 if (SecondHasInfo)
9044 SecondParam = SecondFnType->getExtParameterInfo(I);
John McCall18afab72016-03-01 00:49:02 +00009045
Akira Hatanaka98a49332017-09-22 00:41:05 +00009046 // Cannot merge unless everything except the noescape flag matches.
9047 if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false))
John McCall18afab72016-03-01 00:49:02 +00009048 return false;
Akira Hatanaka98a49332017-09-22 00:41:05 +00009049
9050 bool FirstNoEscape = FirstParam.isNoEscape();
9051 bool SecondNoEscape = SecondParam.isNoEscape();
9052 bool IsNoEscape = FirstNoEscape && SecondNoEscape;
9053 NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape));
9054 if (NewParamInfos.back().getOpaqueValue())
9055 NeedParamInfo = true;
9056 if (FirstNoEscape != IsNoEscape)
9057 CanUseFirst = false;
9058 if (SecondNoEscape != IsNoEscape)
9059 CanUseSecond = false;
John McCall18afab72016-03-01 00:49:02 +00009060 }
Akira Hatanaka98a49332017-09-22 00:41:05 +00009061
9062 if (!NeedParamInfo)
9063 NewParamInfos.clear();
9064
Fariborz Jahanian97676972011-09-28 21:52:05 +00009065 return true;
9066}
9067
Chandler Carruth21c90602015-12-30 03:24:14 +00009068void ASTContext::ResetObjCLayout(const ObjCContainerDecl *CD) {
9069 ObjCLayouts[CD] = nullptr;
9070}
9071
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009072/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
9073/// 'RHS' attributes and returns the merged version; including for function
9074/// return types.
9075QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
9076 QualType LHSCan = getCanonicalType(LHS),
9077 RHSCan = getCanonicalType(RHS);
9078 // If two types are identical, they are compatible.
9079 if (LHSCan == RHSCan)
9080 return LHS;
9081 if (RHSCan->isFunctionType()) {
9082 if (!LHSCan->isFunctionType())
Eugene Zelenko7855e772018-04-03 00:11:50 +00009083 return {};
Alp Toker314cc812014-01-25 16:55:45 +00009084 QualType OldReturnType =
9085 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009086 QualType NewReturnType =
Alp Toker314cc812014-01-25 16:55:45 +00009087 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
Fangrui Song6907ce22018-07-30 19:24:48 +00009088 QualType ResReturnType =
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009089 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
9090 if (ResReturnType.isNull())
Eugene Zelenko7855e772018-04-03 00:11:50 +00009091 return {};
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009092 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
9093 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
9094 // In either case, use OldReturnType to build the new function type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00009095 const auto *F = LHS->getAs<FunctionType>();
9096 if (const auto *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00009097 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9098 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner896b32f2013-06-10 20:51:09 +00009099 QualType ResultType =
Alp Toker9cacbab2014-01-20 20:26:09 +00009100 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009101 return ResultType;
9102 }
9103 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00009104 return {};
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009105 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009106
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009107 // If the qualifiers are different, the types can still be merged.
9108 Qualifiers LQuals = LHSCan.getLocalQualifiers();
9109 Qualifiers RQuals = RHSCan.getLocalQualifiers();
9110 if (LQuals != RQuals) {
9111 // If any of these qualifiers are different, we have a type mismatch.
9112 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
9113 LQuals.getAddressSpace() != RQuals.getAddressSpace())
Eugene Zelenko7855e772018-04-03 00:11:50 +00009114 return {};
Fangrui Song6907ce22018-07-30 19:24:48 +00009115
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009116 // Exactly one GC qualifier difference is allowed: __strong is
9117 // okay if the other type has no GC qualifier but is an Objective
9118 // C object pointer (i.e. implicitly strong by default). We fix
9119 // this by pretending that the unqualified type was actually
9120 // qualified __strong.
9121 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
9122 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
9123 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
Fangrui Song6907ce22018-07-30 19:24:48 +00009124
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009125 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
Eugene Zelenko7855e772018-04-03 00:11:50 +00009126 return {};
Fangrui Song6907ce22018-07-30 19:24:48 +00009127
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009128 if (GC_L == Qualifiers::Strong)
9129 return LHS;
9130 if (GC_R == Qualifiers::Strong)
9131 return RHS;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009132 return {};
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009133 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009134
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009135 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
9136 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
9137 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
9138 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
9139 if (ResQT == LHSBaseQT)
9140 return LHS;
9141 if (ResQT == RHSBaseQT)
9142 return RHS;
9143 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00009144 return {};
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009145}
9146
Chris Lattner4ba0cef2008-04-07 07:01:58 +00009147//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009148// Integer Predicates
9149//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00009150
Jay Foad39c79802011-01-12 09:06:06 +00009151unsigned ASTContext::getIntWidth(QualType T) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00009152 if (const auto *ET = T->getAs<EnumType>())
Eli Friedmanee275c82009-12-10 22:29:29 +00009153 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00009154 if (T->isBooleanType())
9155 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00009156 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009157 return (unsigned)getTypeSize(T);
9158}
9159
Abramo Bagnara13640492012-09-09 10:21:24 +00009160QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Leonard Chanab80f3c2018-06-14 14:53:51 +00009161 assert((T->hasSignedIntegerRepresentation() || T->isSignedFixedPointType()) &&
9162 "Unexpected type");
Fangrui Song6907ce22018-07-30 19:24:48 +00009163
Chris Lattnerec3a1562009-10-17 20:33:28 +00009164 // Turn <4 x signed int> -> <4 x unsigned int>
Eugene Zelenko7855e772018-04-03 00:11:50 +00009165 if (const auto *VTy = T->getAs<VectorType>())
Chris Lattnerec3a1562009-10-17 20:33:28 +00009166 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00009167 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00009168
9169 // For enums, we return the unsigned version of the base type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00009170 if (const auto *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009171 T = ETy->getDecl()->getIntegerType();
Fangrui Song6907ce22018-07-30 19:24:48 +00009172
Eugene Zelenko7855e772018-04-03 00:11:50 +00009173 const auto *BTy = T->getAs<BuiltinType>();
Leonard Chanab80f3c2018-06-14 14:53:51 +00009174 assert(BTy && "Unexpected signed integer or fixed point type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009175 switch (BTy->getKind()) {
9176 case BuiltinType::Char_S:
9177 case BuiltinType::SChar:
9178 return UnsignedCharTy;
9179 case BuiltinType::Short:
9180 return UnsignedShortTy;
9181 case BuiltinType::Int:
9182 return UnsignedIntTy;
9183 case BuiltinType::Long:
9184 return UnsignedLongTy;
9185 case BuiltinType::LongLong:
9186 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00009187 case BuiltinType::Int128:
9188 return UnsignedInt128Ty;
Leonard Chanab80f3c2018-06-14 14:53:51 +00009189
9190 case BuiltinType::ShortAccum:
9191 return UnsignedShortAccumTy;
9192 case BuiltinType::Accum:
9193 return UnsignedAccumTy;
9194 case BuiltinType::LongAccum:
9195 return UnsignedLongAccumTy;
9196 case BuiltinType::SatShortAccum:
9197 return SatUnsignedShortAccumTy;
9198 case BuiltinType::SatAccum:
9199 return SatUnsignedAccumTy;
9200 case BuiltinType::SatLongAccum:
9201 return SatUnsignedLongAccumTy;
9202 case BuiltinType::ShortFract:
9203 return UnsignedShortFractTy;
9204 case BuiltinType::Fract:
9205 return UnsignedFractTy;
9206 case BuiltinType::LongFract:
9207 return UnsignedLongFractTy;
9208 case BuiltinType::SatShortFract:
9209 return SatUnsignedShortFractTy;
9210 case BuiltinType::SatFract:
9211 return SatUnsignedFractTy;
9212 case BuiltinType::SatLongFract:
9213 return SatUnsignedLongFractTy;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009214 default:
Leonard Chanab80f3c2018-06-14 14:53:51 +00009215 llvm_unreachable("Unexpected signed integer or fixed point type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009216 }
9217}
9218
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009219ASTMutationListener::~ASTMutationListener() = default;
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00009220
Richard Smith1fa5d642013-05-11 05:45:24 +00009221void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
9222 QualType ReturnType) {}
Chris Lattnerecd79c62009-06-14 00:45:47 +00009223
9224//===----------------------------------------------------------------------===//
9225// Builtin Type Computation
9226//===----------------------------------------------------------------------===//
9227
9228/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00009229/// pointer over the consumed characters. This returns the resultant type. If
9230/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
9231/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
9232/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009233///
9234/// RequiresICE is filled in on return to indicate whether the value is required
9235/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00009236static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00009237 ASTContext::GetBuiltinTypeError &Error,
Chandler Carruth45bbe012017-03-24 09:11:57 +00009238 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00009239 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00009240 // Modifiers.
9241 int HowLong = 0;
9242 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009243 RequiresICE = false;
Fangrui Song6907ce22018-07-30 19:24:48 +00009244
Chris Lattnerdc226c22010-10-01 22:42:38 +00009245 // Read the prefixed modifiers first.
Eric Christopher50daf5f2017-07-10 21:28:54 +00009246 bool Done = false;
9247 #ifndef NDEBUG
9248 bool IsSpecialLong = false;
9249 #endif
Chris Lattnerecd79c62009-06-14 00:45:47 +00009250 while (!Done) {
9251 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00009252 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00009253 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009254 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00009255 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009256 case 'S':
9257 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
9258 assert(!Signed && "Can't use 'S' modifier multiple times!");
9259 Signed = true;
9260 break;
9261 case 'U':
9262 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
Sean Silva2a995142015-01-16 21:44:26 +00009263 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00009264 Unsigned = true;
9265 break;
9266 case 'L':
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00009267 assert(!IsSpecialLong && "Can't use 'L' with 'W' or 'N' modifiers");
Chris Lattnerecd79c62009-06-14 00:45:47 +00009268 assert(HowLong <= 2 && "Can't have LLLL modifier");
9269 ++HowLong;
9270 break;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009271 case 'N':
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00009272 // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
9273 assert(!IsSpecialLong && "Can't use two 'N' or 'W' modifiers!");
9274 assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
Eric Christopher50daf5f2017-07-10 21:28:54 +00009275 #ifndef NDEBUG
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00009276 IsSpecialLong = true;
Eric Christopher50daf5f2017-07-10 21:28:54 +00009277 #endif
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00009278 if (Context.getTargetInfo().getLongWidth() == 32)
9279 ++HowLong;
9280 break;
Kevin Qinad64f6d2014-02-24 02:45:03 +00009281 case 'W':
9282 // This modifier represents int64 type.
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00009283 assert(!IsSpecialLong && "Can't use two 'N' or 'W' modifiers!");
Kevin Qinad64f6d2014-02-24 02:45:03 +00009284 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
Eric Christopher50daf5f2017-07-10 21:28:54 +00009285 #ifndef NDEBUG
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00009286 IsSpecialLong = true;
Eric Christopher50daf5f2017-07-10 21:28:54 +00009287 #endif
Kevin Qinad64f6d2014-02-24 02:45:03 +00009288 switch (Context.getTargetInfo().getInt64Type()) {
9289 default:
9290 llvm_unreachable("Unexpected integer type");
9291 case TargetInfo::SignedLong:
9292 HowLong = 1;
9293 break;
9294 case TargetInfo::SignedLongLong:
9295 HowLong = 2;
9296 break;
9297 }
Duncan P. N. Exon Smitheae8caa2017-06-14 21:26:31 +00009298 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009299 }
9300 }
9301
9302 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00009303
Chris Lattnerecd79c62009-06-14 00:45:47 +00009304 // Read the base type.
9305 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00009306 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00009307 case 'v':
9308 assert(HowLong == 0 && !Signed && !Unsigned &&
9309 "Bad modifiers used with 'v'!");
9310 Type = Context.VoidTy;
9311 break;
Jack Carter24bef982013-08-15 15:16:57 +00009312 case 'h':
9313 assert(HowLong == 0 && !Signed && !Unsigned &&
Sean Silva2a995142015-01-16 21:44:26 +00009314 "Bad modifiers used with 'h'!");
Jack Carter24bef982013-08-15 15:16:57 +00009315 Type = Context.HalfTy;
9316 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009317 case 'f':
9318 assert(HowLong == 0 && !Signed && !Unsigned &&
9319 "Bad modifiers used with 'f'!");
9320 Type = Context.FloatTy;
9321 break;
9322 case 'd':
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009323 assert(HowLong < 3 && !Signed && !Unsigned &&
Chris Lattnerecd79c62009-06-14 00:45:47 +00009324 "Bad modifiers used with 'd'!");
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009325 if (HowLong == 1)
Chris Lattnerecd79c62009-06-14 00:45:47 +00009326 Type = Context.LongDoubleTy;
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009327 else if (HowLong == 2)
9328 Type = Context.Float128Ty;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009329 else
9330 Type = Context.DoubleTy;
9331 break;
9332 case 's':
9333 assert(HowLong == 0 && "Bad modifiers used with 's'!");
9334 if (Unsigned)
9335 Type = Context.UnsignedShortTy;
9336 else
9337 Type = Context.ShortTy;
9338 break;
9339 case 'i':
9340 if (HowLong == 3)
9341 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
9342 else if (HowLong == 2)
9343 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
9344 else if (HowLong == 1)
9345 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
9346 else
9347 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
9348 break;
9349 case 'c':
9350 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
9351 if (Signed)
9352 Type = Context.SignedCharTy;
9353 else if (Unsigned)
9354 Type = Context.UnsignedCharTy;
9355 else
9356 Type = Context.CharTy;
9357 break;
9358 case 'b': // boolean
9359 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
9360 Type = Context.BoolTy;
9361 break;
9362 case 'z': // size_t.
9363 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
9364 Type = Context.getSizeType();
9365 break;
Richard Smith8110c9d2016-11-29 19:45:17 +00009366 case 'w': // wchar_t.
9367 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
9368 Type = Context.getWideCharType();
9369 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009370 case 'F':
9371 Type = Context.getCFConstantStringType();
9372 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00009373 case 'G':
9374 Type = Context.getObjCIdType();
9375 break;
9376 case 'H':
9377 Type = Context.getObjCSelType();
9378 break;
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00009379 case 'M':
9380 Type = Context.getObjCSuperType();
9381 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009382 case 'a':
9383 Type = Context.getBuiltinVaListType();
9384 assert(!Type.isNull() && "builtin va list type not initialized!");
9385 break;
9386 case 'A':
9387 // This is a "reference" to a va_list; however, what exactly
9388 // this means depends on how va_list is defined. There are two
9389 // different kinds of va_list: ones passed by value, and ones
9390 // passed by reference. An example of a by-value va_list is
9391 // x86, where va_list is a char*. An example of by-ref va_list
9392 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
9393 // we want this argument to be a char*&; for x86-64, we want
9394 // it to be a __va_list_tag*.
9395 Type = Context.getBuiltinVaListType();
9396 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009397 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00009398 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009399 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00009400 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009401 break;
9402 case 'V': {
9403 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009404 unsigned NumElements = strtoul(Str, &End, 10);
9405 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00009406 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00009407
Fangrui Song6907ce22018-07-30 19:24:48 +00009408 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
Chandler Carruth45bbe012017-03-24 09:11:57 +00009409 RequiresICE, false);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009410 assert(!RequiresICE && "Can't require vector ICE");
Fangrui Song6907ce22018-07-30 19:24:48 +00009411
Chris Lattnerdc226c22010-10-01 22:42:38 +00009412 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00009413 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00009414 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009415 break;
9416 }
Douglas Gregorfed66992012-06-07 18:08:25 +00009417 case 'E': {
9418 char *End;
Fangrui Song6907ce22018-07-30 19:24:48 +00009419
Douglas Gregorfed66992012-06-07 18:08:25 +00009420 unsigned NumElements = strtoul(Str, &End, 10);
9421 assert(End != Str && "Missing vector size");
Fangrui Song6907ce22018-07-30 19:24:48 +00009422
Douglas Gregorfed66992012-06-07 18:08:25 +00009423 Str = End;
Fangrui Song6907ce22018-07-30 19:24:48 +00009424
Douglas Gregorfed66992012-06-07 18:08:25 +00009425 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
Chandler Carruth45bbe012017-03-24 09:11:57 +00009426 false);
Douglas Gregorfed66992012-06-07 18:08:25 +00009427 Type = Context.getExtVectorType(ElementType, NumElements);
Fangrui Song6907ce22018-07-30 19:24:48 +00009428 break;
Douglas Gregorfed66992012-06-07 18:08:25 +00009429 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00009430 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009431 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
Chandler Carruth45bbe012017-03-24 09:11:57 +00009432 false);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009433 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00009434 Type = Context.getComplexType(ElementType);
9435 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00009436 }
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009437 case 'Y':
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00009438 Type = Context.getPointerDiffType();
9439 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00009440 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00009441 Type = Context.getFILEType();
9442 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00009443 Error = ASTContext::GE_Missing_stdio;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009444 return {};
Chris Lattnerecd79c62009-06-14 00:45:47 +00009445 }
Mike Stump2adb4da2009-07-28 23:47:15 +00009446 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00009447 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00009448 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00009449 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00009450 else
9451 Type = Context.getjmp_bufType();
9452
Mike Stump2adb4da2009-07-28 23:47:15 +00009453 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00009454 Error = ASTContext::GE_Missing_setjmp;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009455 return {};
Mike Stump2adb4da2009-07-28 23:47:15 +00009456 }
9457 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00009458 case 'K':
9459 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
9460 Type = Context.getucontext_tType();
9461
9462 if (Type.isNull()) {
9463 Error = ASTContext::GE_Missing_ucontext;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009464 return {};
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00009465 }
9466 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00009467 case 'p':
9468 Type = Context.getProcessIDType();
9469 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00009470 }
Mike Stump11289f42009-09-09 15:08:12 +00009471
Chris Lattnerdc226c22010-10-01 22:42:38 +00009472 // If there are modifiers and if we're allowed to parse them, go for it.
9473 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009474 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00009475 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00009476 default: Done = true; --Str; break;
9477 case '*':
9478 case '&': {
9479 // Both pointers and references can have their pointee types
9480 // qualified with an address space.
9481 char *End;
9482 unsigned AddrSpace = strtoul(Str, &End, 10);
Matt Arsenaultc65f9662018-08-02 12:14:28 +00009483 if (End != Str) {
9484 // Note AddrSpace == 0 is not the same as an unspecified address space.
9485 Type = Context.getAddrSpaceQualType(
9486 Type,
9487 Context.getLangASForBuiltinAddressSpace(AddrSpace));
Chris Lattnerdc226c22010-10-01 22:42:38 +00009488 Str = End;
9489 }
9490 if (c == '*')
9491 Type = Context.getPointerType(Type);
9492 else
9493 Type = Context.getLValueReferenceType(Type);
9494 break;
9495 }
9496 // FIXME: There's no way to have a built-in with an rvalue ref arg.
9497 case 'C':
9498 Type = Type.withConst();
9499 break;
9500 case 'D':
9501 Type = Context.getVolatileType(Type);
9502 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00009503 case 'R':
9504 Type = Type.withRestrict();
9505 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009506 }
9507 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009508
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009509 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Fangrui Song6907ce22018-07-30 19:24:48 +00009510 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00009511
Chris Lattnerecd79c62009-06-14 00:45:47 +00009512 return Type;
9513}
9514
9515/// GetBuiltinType - Return the type for the specified builtin.
Chandler Carruth45bbe012017-03-24 09:11:57 +00009516QualType ASTContext::GetBuiltinType(unsigned Id,
9517 GetBuiltinTypeError &Error,
9518 unsigned *IntegerConstantArgs) const {
Eric Christopher02d5d862015-08-06 01:01:12 +00009519 const char *TypeStr = BuiltinInfo.getTypeString(Id);
Johannes Doerfertac991bb2019-01-19 05:36:54 +00009520 if (TypeStr[0] == '\0') {
9521 Error = GE_Missing_type;
9522 return {};
9523 }
Mike Stump11289f42009-09-09 15:08:12 +00009524
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009525 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00009526
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009527 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009528 Error = GE_None;
Chandler Carruth45bbe012017-03-24 09:11:57 +00009529 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
9530 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009531 if (Error != GE_None)
Eugene Zelenko7855e772018-04-03 00:11:50 +00009532 return {};
Fangrui Song6907ce22018-07-30 19:24:48 +00009533
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009534 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
Fangrui Song6907ce22018-07-30 19:24:48 +00009535
Chris Lattnerecd79c62009-06-14 00:45:47 +00009536 while (TypeStr[0] && TypeStr[0] != '.') {
Chandler Carruth45bbe012017-03-24 09:11:57 +00009537 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009538 if (Error != GE_None)
Eugene Zelenko7855e772018-04-03 00:11:50 +00009539 return {};
Chris Lattnerecd79c62009-06-14 00:45:47 +00009540
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009541 // If this argument is required to be an IntegerConstantExpression and the
9542 // caller cares, fill in the bitmask we return.
9543 if (RequiresICE && IntegerConstantArgs)
9544 *IntegerConstantArgs |= 1 << ArgTypes.size();
Fangrui Song6907ce22018-07-30 19:24:48 +00009545
Chris Lattnerecd79c62009-06-14 00:45:47 +00009546 // Do array -> pointer decay. The builtin should use the decayed type.
9547 if (Ty->isArrayType())
9548 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00009549
Chris Lattnerecd79c62009-06-14 00:45:47 +00009550 ArgTypes.push_back(Ty);
9551 }
9552
David Majnemerba3e5ec2015-03-13 18:26:17 +00009553 if (Id == Builtin::BI__GetExceptionInfo)
Eugene Zelenko7855e772018-04-03 00:11:50 +00009554 return {};
David Majnemerba3e5ec2015-03-13 18:26:17 +00009555
Chris Lattnerecd79c62009-06-14 00:45:47 +00009556 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
9557 "'.' should only occur at end of builtin type list!");
9558
Reid Kleckner78af0702013-08-27 23:08:25 +00009559 FunctionType::ExtInfo EI(CC_C);
John McCall991eb4b2010-12-21 00:44:39 +00009560 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
9561
9562 bool Variadic = (TypeStr[0] == '.');
9563
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;
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00009790 else if (isa<OMPThreadPrivateDecl>(D))
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00009791 return true;
Nico Webercbbaeb12016-03-02 19:28:54 +00009792 else if (isa<PragmaDetectMismatchDecl>(D))
9793 return true;
Nico Weber66220292016-03-02 17:28:48 +00009794 else if (isa<OMPThreadPrivateDecl>(D))
Alexey Bataevc5b1d322016-03-04 09:22:22 +00009795 return !D->getDeclContext()->isDependentContext();
9796 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
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00009984MangleContext *ASTContext::createMangleContext() {
John McCall359b8852013-01-25 22:30:49 +00009985 switch (Target->getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +00009986 case TargetCXXABI::GenericAArch64:
John McCall359b8852013-01-25 22:30:49 +00009987 case TargetCXXABI::GenericItanium:
9988 case TargetCXXABI::GenericARM:
Zoran Jovanovic26a12162015-02-18 15:21:35 +00009989 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +00009990 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +00009991 case TargetCXXABI::iOS64:
Dan Gohmanc2853072015-09-03 22:51:53 +00009992 case TargetCXXABI::WebAssembly:
Tim Northover756447a2015-10-30 16:30:36 +00009993 case TargetCXXABI::WatchOS:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00009994 return ItaniumMangleContext::create(*this, getDiagnostics());
John McCall359b8852013-01-25 22:30:49 +00009995 case TargetCXXABI::Microsoft:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00009996 return MicrosoftMangleContext::create(*this, getDiagnostics());
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00009997 }
David Blaikie83d382b2011-09-23 05:06:16 +00009998 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00009999}
10000
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000010001CXXABI::~CXXABI() = default;
Ted Kremenekf5df0ce2011-04-28 04:53:38 +000010002
10003size_t ASTContext::getSideTableAllocatedMemory() const {
Larisse Voufo39a1e502013-08-06 01:03:05 +000010004 return ASTRecordLayouts.getMemorySize() +
10005 llvm::capacity_in_bytes(ObjCLayouts) +
10006 llvm::capacity_in_bytes(KeyFunctions) +
10007 llvm::capacity_in_bytes(ObjCImpls) +
10008 llvm::capacity_in_bytes(BlockVarCopyInits) +
10009 llvm::capacity_in_bytes(DeclAttrs) +
10010 llvm::capacity_in_bytes(TemplateOrInstantiation) +
10011 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
10012 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
10013 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
10014 llvm::capacity_in_bytes(OverriddenMethods) +
10015 llvm::capacity_in_bytes(Types) +
10016 llvm::capacity_in_bytes(VariableArrayTypes) +
10017 llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +000010018}
Ted Kremenek540017e2011-10-06 05:00:56 +000010019
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +000010020/// getIntTypeForBitwidth -
10021/// sets integer QualTy according to specified details:
10022/// bitwidth, signed/unsigned.
10023/// Returns empty type if there is no appropriate target types.
10024QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
10025 unsigned Signed) const {
10026 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
10027 CanQualType QualTy = getFromTargetType(Ty);
10028 if (!QualTy && DestWidth == 128)
10029 return Signed ? Int128Ty : UnsignedInt128Ty;
10030 return QualTy;
10031}
10032
10033/// getRealTypeForBitwidth -
10034/// sets floating point QualTy according to specified bitwidth.
10035/// Returns empty type if there is no appropriate target types.
10036QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
10037 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
10038 switch (Ty) {
10039 case TargetInfo::Float:
10040 return FloatTy;
10041 case TargetInfo::Double:
10042 return DoubleTy;
10043 case TargetInfo::LongDouble:
10044 return LongDoubleTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +000010045 case TargetInfo::Float128:
10046 return Float128Ty;
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +000010047 case TargetInfo::NoFloat:
Eugene Zelenko7855e772018-04-03 00:11:50 +000010048 return {};
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +000010049 }
10050
10051 llvm_unreachable("Unhandled TargetInfo::RealType value");
10052}
10053
Eli Friedman3b7d46c2013-07-10 00:30:46 +000010054void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
10055 if (Number > 1)
10056 MangleNumbers[ND] = Number;
David Blaikie095deba2012-11-14 01:52:05 +000010057}
10058
Eli Friedman3b7d46c2013-07-10 00:30:46 +000010059unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
Richard Smithe9b02d62016-03-21 22:33:02 +000010060 auto I = MangleNumbers.find(ND);
Eli Friedman3b7d46c2013-07-10 00:30:46 +000010061 return I != MangleNumbers.end() ? I->second : 1;
David Blaikie095deba2012-11-14 01:52:05 +000010062}
10063
David Majnemer2206bf52014-03-05 08:57:59 +000010064void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
10065 if (Number > 1)
10066 StaticLocalNumbers[VD] = Number;
10067}
10068
10069unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
Richard Smithe9b02d62016-03-21 22:33:02 +000010070 auto I = StaticLocalNumbers.find(VD);
David Majnemer2206bf52014-03-05 08:57:59 +000010071 return I != StaticLocalNumbers.end() ? I->second : 1;
10072}
10073
Eli Friedman3b7d46c2013-07-10 00:30:46 +000010074MangleNumberingContext &
10075ASTContext::getManglingNumberContext(const DeclContext *DC) {
Reid Klecknerd8110b62013-09-10 20:14:30 +000010076 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
Justin Lebar20ebffc2016-10-10 16:26:19 +000010077 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
Reid Klecknerd8110b62013-09-10 20:14:30 +000010078 if (!MCtx)
10079 MCtx = createMangleNumberingContext();
10080 return *MCtx;
10081}
10082
Justin Lebar20ebffc2016-10-10 16:26:19 +000010083std::unique_ptr<MangleNumberingContext>
10084ASTContext::createMangleNumberingContext() const {
Reid Klecknerd8110b62013-09-10 20:14:30 +000010085 return ABI->createMangleNumberingContext();
Douglas Gregor63798542012-02-20 19:44:39 +000010086}
10087
David Majnemere7a818f2015-03-06 18:53:55 +000010088const CXXConstructorDecl *
10089ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
10090 return ABI->getCopyConstructorForExceptionObject(
10091 cast<CXXRecordDecl>(RD->getFirstDecl()));
10092}
10093
10094void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
10095 CXXConstructorDecl *CD) {
10096 return ABI->addCopyConstructorForExceptionObject(
10097 cast<CXXRecordDecl>(RD->getFirstDecl()),
10098 cast<CXXConstructorDecl>(CD->getFirstDecl()));
10099}
10100
David Majnemer00350522015-08-31 18:48:39 +000010101void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD,
10102 TypedefNameDecl *DD) {
10103 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
10104}
10105
10106TypedefNameDecl *
10107ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) {
10108 return ABI->getTypedefNameForUnnamedTagDecl(TD);
10109}
10110
10111void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD,
10112 DeclaratorDecl *DD) {
10113 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
10114}
10115
10116DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) {
10117 return ABI->getDeclaratorForUnnamedTagDecl(TD);
10118}
10119
Ted Kremenek540017e2011-10-06 05:00:56 +000010120void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
10121 ParamIndices[D] = index;
10122}
10123
10124unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
10125 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
Fangrui Song6907ce22018-07-30 19:24:48 +000010126 assert(I != ParamIndices.end() &&
Ted Kremenek540017e2011-10-06 05:00:56 +000010127 "ParmIndices lacks entry set by ParmVarDecl");
10128 return I->second;
10129}
Fariborz Jahanian615de762013-05-28 17:37:39 +000010130
Richard Smithe6c01442013-06-05 00:46:14 +000010131APValue *
10132ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
10133 bool MayCreate) {
10134 assert(E && E->getStorageDuration() == SD_Static &&
10135 "don't need to cache the computed value for this temporary");
David Majnemer2dcef9e2015-08-13 23:50:15 +000010136 if (MayCreate) {
10137 APValue *&MTVI = MaterializedTemporaryValues[E];
10138 if (!MTVI)
10139 MTVI = new (*this) APValue;
10140 return MTVI;
10141 }
Richard Smithe6c01442013-06-05 00:46:14 +000010142
David Majnemer2dcef9e2015-08-13 23:50:15 +000010143 return MaterializedTemporaryValues.lookup(E);
Richard Smithe6c01442013-06-05 00:46:14 +000010144}
10145
Fariborz Jahanian615de762013-05-28 17:37:39 +000010146bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
10147 const llvm::Triple &T = getTargetInfo().getTriple();
10148 if (!T.isOSDarwin())
10149 return false;
10150
Bob Wilson2c82c3d2013-11-02 23:27:49 +000010151 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
10152 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
10153 return false;
10154
Fariborz Jahanian615de762013-05-28 17:37:39 +000010155 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
10156 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
10157 uint64_t Size = sizeChars.getQuantity();
10158 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
10159 unsigned Align = alignChars.getQuantity();
10160 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
10161 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
10162}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010163
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010164/// Template specializations to abstract away from pointers and TypeLocs.
10165/// @{
10166template <typename T>
Sam McCall814e7972018-11-14 10:33:30 +000010167static ast_type_traits::DynTypedNode createDynTypedNode(const T &Node) {
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010168 return ast_type_traits::DynTypedNode::create(*Node);
10169}
10170template <>
10171ast_type_traits::DynTypedNode createDynTypedNode(const TypeLoc &Node) {
10172 return ast_type_traits::DynTypedNode::create(Node);
10173}
10174template <>
10175ast_type_traits::DynTypedNode
10176createDynTypedNode(const NestedNameSpecifierLoc &Node) {
10177 return ast_type_traits::DynTypedNode::create(Node);
10178}
10179/// @}
10180
Sam McCall814e7972018-11-14 10:33:30 +000010181/// A \c RecursiveASTVisitor that builds a map from nodes to their
10182/// parents as defined by the \c RecursiveASTVisitor.
10183///
10184/// Note that the relationship described here is purely in terms of AST
10185/// traversal - there are other relationships (for example declaration context)
10186/// in the AST that are better modeled by special matchers.
10187///
10188/// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
10189class ASTContext::ParentMap::ASTVisitor
10190 : public RecursiveASTVisitor<ASTVisitor> {
10191public:
10192 ASTVisitor(ParentMap &Map) : Map(Map) {}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010193
Sam McCall814e7972018-11-14 10:33:30 +000010194private:
10195 friend class RecursiveASTVisitor<ASTVisitor>;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000010196
Sam McCall814e7972018-11-14 10:33:30 +000010197 using VisitorBase = RecursiveASTVisitor<ASTVisitor>;
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010198
Sam McCall814e7972018-11-14 10:33:30 +000010199 bool shouldVisitTemplateInstantiations() const { return true; }
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010200
Sam McCall814e7972018-11-14 10:33:30 +000010201 bool shouldVisitImplicitCode() const { return true; }
10202
10203 template <typename T, typename MapNodeTy, typename BaseTraverseFn,
10204 typename MapTy>
10205 bool TraverseNode(T Node, MapNodeTy MapNode, BaseTraverseFn BaseTraverse,
10206 MapTy *Parents) {
10207 if (!Node)
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010208 return true;
Sam McCall814e7972018-11-14 10:33:30 +000010209 if (ParentStack.size() > 0) {
10210 // FIXME: Currently we add the same parent multiple times, but only
10211 // when no memoization data is available for the type.
10212 // For example when we visit all subexpressions of template
10213 // instantiations; this is suboptimal, but benign: the only way to
10214 // visit those is with hasAncestor / hasParent, and those do not create
10215 // new matches.
10216 // The plan is to enable DynTypedNode to be storable in a map or hash
10217 // map. The main problem there is to implement hash functions /
10218 // comparison operators for all types that DynTypedNode supports that
10219 // do not have pointer identity.
10220 auto &NodeOrVector = (*Parents)[MapNode];
10221 if (NodeOrVector.isNull()) {
10222 if (const auto *D = ParentStack.back().get<Decl>())
10223 NodeOrVector = D;
10224 else if (const auto *S = ParentStack.back().get<Stmt>())
10225 NodeOrVector = S;
10226 else
10227 NodeOrVector = new ast_type_traits::DynTypedNode(ParentStack.back());
10228 } else {
10229 if (!NodeOrVector.template is<ParentVector *>()) {
10230 auto *Vector = new ParentVector(
10231 1, getSingleDynTypedNodeFromParentMap(NodeOrVector));
10232 delete NodeOrVector
10233 .template dyn_cast<ast_type_traits::DynTypedNode *>();
10234 NodeOrVector = Vector;
Manuel Klimek95403e62014-05-21 13:28:59 +000010235 }
Sam McCall814e7972018-11-14 10:33:30 +000010236
10237 auto *Vector = NodeOrVector.template get<ParentVector *>();
10238 // Skip duplicates for types that have memoization data.
10239 // We must check that the type has memoization data before calling
10240 // std::find() because DynTypedNode::operator== can't compare all
10241 // types.
10242 bool Found = ParentStack.back().getMemoizationData() &&
10243 std::find(Vector->begin(), Vector->end(),
10244 ParentStack.back()) != Vector->end();
10245 if (!Found)
10246 Vector->push_back(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +000010247 }
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010248 }
Sam McCall814e7972018-11-14 10:33:30 +000010249 ParentStack.push_back(createDynTypedNode(Node));
10250 bool Result = BaseTraverse();
10251 ParentStack.pop_back();
10252 return Result;
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010253 }
Sam McCall814e7972018-11-14 10:33:30 +000010254
10255 bool TraverseDecl(Decl *DeclNode) {
10256 return TraverseNode(
10257 DeclNode, DeclNode, [&] { return VisitorBase::TraverseDecl(DeclNode); },
10258 &Map.PointerParents);
Manuel Klimek95403e62014-05-21 13:28:59 +000010259 }
Sam McCall814e7972018-11-14 10:33:30 +000010260
10261 bool TraverseStmt(Stmt *StmtNode) {
10262 return TraverseNode(
10263 StmtNode, StmtNode, [&] { return VisitorBase::TraverseStmt(StmtNode); },
10264 &Map.PointerParents);
10265 }
10266
10267 bool TraverseTypeLoc(TypeLoc TypeLocNode) {
10268 return TraverseNode(
10269 TypeLocNode, ast_type_traits::DynTypedNode::create(TypeLocNode),
10270 [&] { return VisitorBase::TraverseTypeLoc(TypeLocNode); },
10271 &Map.OtherParents);
10272 }
10273
10274 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNSLocNode) {
10275 return TraverseNode(
10276 NNSLocNode, ast_type_traits::DynTypedNode::create(NNSLocNode),
10277 [&] { return VisitorBase::TraverseNestedNameSpecifierLoc(NNSLocNode); },
10278 &Map.OtherParents);
10279 }
10280
10281 ParentMap &Map;
10282 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
10283};
10284
10285ASTContext::ParentMap::ParentMap(ASTContext &Ctx) {
10286 ASTVisitor(*this).TraverseAST(Ctx);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010287}
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010288
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010289ASTContext::DynTypedNodeList
10290ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
Sam McCall814e7972018-11-14 10:33:30 +000010291 if (!Parents)
10292 // We build the parent map for the traversal scope (usually whole TU), as
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010293 // hasAncestor can escape any subtree.
Sam McCall814e7972018-11-14 10:33:30 +000010294 Parents = llvm::make_unique<ParentMap>(*this);
10295 return Parents->getParents(Node);
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010296}
10297
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010298bool
10299ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
10300 const ObjCMethodDecl *MethodImpl) {
10301 // No point trying to match an unavailable/deprecated mothod.
10302 if (MethodDecl->hasAttr<UnavailableAttr>()
10303 || MethodDecl->hasAttr<DeprecatedAttr>())
10304 return false;
10305 if (MethodDecl->getObjCDeclQualifier() !=
10306 MethodImpl->getObjCDeclQualifier())
10307 return false;
Alp Toker314cc812014-01-25 16:55:45 +000010308 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010309 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +000010310
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010311 if (MethodDecl->param_size() != MethodImpl->param_size())
10312 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +000010313
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010314 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
10315 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
10316 EF = MethodDecl->param_end();
10317 IM != EM && IF != EF; ++IM, ++IF) {
10318 const ParmVarDecl *DeclVar = (*IF);
10319 const ParmVarDecl *ImplVar = (*IM);
10320 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
10321 return false;
10322 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
10323 return false;
10324 }
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000010325
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010326 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010327}
Richard Smith053f6c62014-05-16 23:01:30 +000010328
Yaxun Liu402804b2016-12-15 08:09:08 +000010329uint64_t ASTContext::getTargetNullPointerValue(QualType QT) const {
Alexander Richardson6d989432017-10-15 18:48:14 +000010330 LangAS AS;
Yaxun Liu402804b2016-12-15 08:09:08 +000010331 if (QT->getUnqualifiedDesugaredType()->isNullPtrType())
Alexander Richardson6d989432017-10-15 18:48:14 +000010332 AS = LangAS::Default;
Yaxun Liu402804b2016-12-15 08:09:08 +000010333 else
10334 AS = QT->getPointeeType().getAddressSpace();
10335
10336 return getTargetInfo().getNullPointerValue(AS);
10337}
10338
Alexander Richardson6d989432017-10-15 18:48:14 +000010339unsigned ASTContext::getTargetAddressSpace(LangAS AS) const {
10340 if (isTargetAddressSpace(AS))
10341 return toTargetAddressSpace(AS);
Yaxun Liub34ec822017-04-11 17:24:23 +000010342 else
Alexander Richardson6d989432017-10-15 18:48:14 +000010343 return (*AddrSpaceMap)[(unsigned)AS];
Yaxun Liub34ec822017-04-11 17:24:23 +000010344}
10345
Leonard Chanab80f3c2018-06-14 14:53:51 +000010346QualType ASTContext::getCorrespondingSaturatedType(QualType Ty) const {
10347 assert(Ty->isFixedPointType());
10348
10349 if (Ty->isSaturatedFixedPointType()) return Ty;
10350
10351 const auto &BT = Ty->getAs<BuiltinType>();
10352 switch (BT->getKind()) {
10353 default:
10354 llvm_unreachable("Not a fixed point type!");
10355 case BuiltinType::ShortAccum:
10356 return SatShortAccumTy;
10357 case BuiltinType::Accum:
10358 return SatAccumTy;
10359 case BuiltinType::LongAccum:
10360 return SatLongAccumTy;
10361 case BuiltinType::UShortAccum:
10362 return SatUnsignedShortAccumTy;
10363 case BuiltinType::UAccum:
10364 return SatUnsignedAccumTy;
10365 case BuiltinType::ULongAccum:
10366 return SatUnsignedLongAccumTy;
10367 case BuiltinType::ShortFract:
10368 return SatShortFractTy;
10369 case BuiltinType::Fract:
10370 return SatFractTy;
10371 case BuiltinType::LongFract:
10372 return SatLongFractTy;
10373 case BuiltinType::UShortFract:
10374 return SatUnsignedShortFractTy;
10375 case BuiltinType::UFract:
10376 return SatUnsignedFractTy;
10377 case BuiltinType::ULongFract:
10378 return SatUnsignedLongFractTy;
10379 }
10380}
10381
Matt Arsenaultc65f9662018-08-02 12:14:28 +000010382LangAS ASTContext::getLangASForBuiltinAddressSpace(unsigned AS) const {
10383 if (LangOpts.OpenCL)
10384 return getTargetInfo().getOpenCLBuiltinAddressSpace(AS);
10385
10386 if (LangOpts.CUDA)
10387 return getTargetInfo().getCUDABuiltinAddressSpace(AS);
10388
10389 return getLangASFromTargetAS(AS);
10390}
10391
Richard Smith053f6c62014-05-16 23:01:30 +000010392// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
10393// doesn't include ASTContext.h
10394template
10395clang::LazyGenerationalUpdatePtr<
10396 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
10397clang::LazyGenerationalUpdatePtr<
10398 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
10399 const clang::ASTContext &Ctx, Decl *Value);
Leonard Chandb01c3a2018-06-20 17:19:40 +000010400
10401unsigned char ASTContext::getFixedPointScale(QualType Ty) const {
10402 assert(Ty->isFixedPointType());
10403
10404 const auto *BT = Ty->getAs<BuiltinType>();
10405 const TargetInfo &Target = getTargetInfo();
10406 switch (BT->getKind()) {
10407 default:
10408 llvm_unreachable("Not a fixed point type!");
10409 case BuiltinType::ShortAccum:
10410 case BuiltinType::SatShortAccum:
10411 return Target.getShortAccumScale();
10412 case BuiltinType::Accum:
10413 case BuiltinType::SatAccum:
10414 return Target.getAccumScale();
10415 case BuiltinType::LongAccum:
10416 case BuiltinType::SatLongAccum:
10417 return Target.getLongAccumScale();
10418 case BuiltinType::UShortAccum:
10419 case BuiltinType::SatUShortAccum:
10420 return Target.getUnsignedShortAccumScale();
10421 case BuiltinType::UAccum:
10422 case BuiltinType::SatUAccum:
10423 return Target.getUnsignedAccumScale();
10424 case BuiltinType::ULongAccum:
10425 case BuiltinType::SatULongAccum:
10426 return Target.getUnsignedLongAccumScale();
10427 case BuiltinType::ShortFract:
10428 case BuiltinType::SatShortFract:
10429 return Target.getShortFractScale();
10430 case BuiltinType::Fract:
10431 case BuiltinType::SatFract:
10432 return Target.getFractScale();
10433 case BuiltinType::LongFract:
10434 case BuiltinType::SatLongFract:
10435 return Target.getLongFractScale();
10436 case BuiltinType::UShortFract:
10437 case BuiltinType::SatUShortFract:
10438 return Target.getUnsignedShortFractScale();
10439 case BuiltinType::UFract:
10440 case BuiltinType::SatUFract:
10441 return Target.getUnsignedFractScale();
10442 case BuiltinType::ULongFract:
10443 case BuiltinType::SatULongFract:
10444 return Target.getUnsignedLongFractScale();
10445 }
10446}
10447
10448unsigned char ASTContext::getFixedPointIBits(QualType Ty) const {
10449 assert(Ty->isFixedPointType());
10450
10451 const auto *BT = Ty->getAs<BuiltinType>();
10452 const TargetInfo &Target = getTargetInfo();
10453 switch (BT->getKind()) {
10454 default:
10455 llvm_unreachable("Not a fixed point type!");
10456 case BuiltinType::ShortAccum:
10457 case BuiltinType::SatShortAccum:
10458 return Target.getShortAccumIBits();
10459 case BuiltinType::Accum:
10460 case BuiltinType::SatAccum:
10461 return Target.getAccumIBits();
10462 case BuiltinType::LongAccum:
10463 case BuiltinType::SatLongAccum:
10464 return Target.getLongAccumIBits();
10465 case BuiltinType::UShortAccum:
10466 case BuiltinType::SatUShortAccum:
10467 return Target.getUnsignedShortAccumIBits();
10468 case BuiltinType::UAccum:
10469 case BuiltinType::SatUAccum:
10470 return Target.getUnsignedAccumIBits();
10471 case BuiltinType::ULongAccum:
10472 case BuiltinType::SatULongAccum:
10473 return Target.getUnsignedLongAccumIBits();
10474 case BuiltinType::ShortFract:
10475 case BuiltinType::SatShortFract:
10476 case BuiltinType::Fract:
10477 case BuiltinType::SatFract:
10478 case BuiltinType::LongFract:
10479 case BuiltinType::SatLongFract:
10480 case BuiltinType::UShortFract:
10481 case BuiltinType::SatUShortFract:
10482 case BuiltinType::UFract:
10483 case BuiltinType::SatUFract:
10484 case BuiltinType::ULongFract:
10485 case BuiltinType::SatULongFract:
10486 return 0;
10487 }
10488}
Leonard Chana6779422018-08-06 16:42:37 +000010489
10490FixedPointSemantics ASTContext::getFixedPointSemantics(QualType Ty) const {
Erich Keane8e772162019-01-18 19:31:54 +000010491 assert((Ty->isFixedPointType() || Ty->isIntegerType()) &&
10492 "Can only get the fixed point semantics for a "
10493 "fixed point or integer type.");
Leonard Chan2044ac82019-01-16 18:13:59 +000010494 if (Ty->isIntegerType())
10495 return FixedPointSemantics::GetIntegerSemantics(getIntWidth(Ty),
10496 Ty->isSignedIntegerType());
10497
Leonard Chana6779422018-08-06 16:42:37 +000010498 bool isSigned = Ty->isSignedFixedPointType();
10499 return FixedPointSemantics(
10500 static_cast<unsigned>(getTypeSize(Ty)), getFixedPointScale(Ty), isSigned,
10501 Ty->isSaturatedFixedPointType(),
10502 !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding());
10503}
10504
10505APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const {
10506 assert(Ty->isFixedPointType());
10507 return APFixedPoint::getMax(getFixedPointSemantics(Ty));
10508}
10509
10510APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const {
10511 assert(Ty->isFixedPointType());
10512 return APFixedPoint::getMin(getFixedPointSemantics(Ty));
10513}
Leonard Chan2044ac82019-01-16 18:13:59 +000010514
10515QualType ASTContext::getCorrespondingSignedFixedPointType(QualType Ty) const {
10516 assert(Ty->isUnsignedFixedPointType() &&
10517 "Expected unsigned fixed point type");
10518 const auto *BTy = Ty->getAs<BuiltinType>();
10519
10520 switch (BTy->getKind()) {
10521 case BuiltinType::UShortAccum:
10522 return ShortAccumTy;
10523 case BuiltinType::UAccum:
10524 return AccumTy;
10525 case BuiltinType::ULongAccum:
10526 return LongAccumTy;
10527 case BuiltinType::SatUShortAccum:
10528 return SatShortAccumTy;
10529 case BuiltinType::SatUAccum:
10530 return SatAccumTy;
10531 case BuiltinType::SatULongAccum:
10532 return SatLongAccumTy;
10533 case BuiltinType::UShortFract:
10534 return ShortFractTy;
10535 case BuiltinType::UFract:
10536 return FractTy;
10537 case BuiltinType::ULongFract:
10538 return LongFractTy;
10539 case BuiltinType::SatUShortFract:
10540 return SatShortFractTy;
10541 case BuiltinType::SatUFract:
10542 return SatFractTy;
10543 case BuiltinType::SatULongFract:
10544 return SatLongFractTy;
10545 default:
10546 llvm_unreachable("Unexpected unsigned fixed point type");
10547 }
10548}