blob: 9b0d976ebb28fff6e9e688a28aad8fa4cae2f19a [file] [log] [blame]
Chris Lattnera11999d2006-10-15 22:34:45 +00001//===--- Decl.cpp - Declaration AST Node Implementation -------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnera11999d2006-10-15 22:34:45 +00007//
8//===----------------------------------------------------------------------===//
9//
Argyrios Kyrtzidis63018842008-06-04 13:04:04 +000010// This file implements the Decl subclasses.
Chris Lattnera11999d2006-10-15 22:34:45 +000011//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/Decl.h"
George Burgess IV99db3ea2017-08-09 04:02:49 +000015#include "Linkage.h"
Chris Lattnera7b32872008-03-15 06:12:44 +000016#include "clang/AST/ASTContext.h"
Faisal Valib90b2112014-04-03 16:32:21 +000017#include "clang/AST/ASTLambda.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000018#include "clang/AST/ASTMutationListener.h"
19#include "clang/AST/Attr.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/AST/DeclCXX.h"
21#include "clang/AST/DeclObjC.h"
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000022#include "clang/AST/DeclOpenMP.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000023#include "clang/AST/DeclTemplate.h"
Nuno Lopes394ec982008-12-17 23:39:55 +000024#include "clang/AST/Expr.h"
Anders Carlsson714d0962009-12-15 19:16:31 +000025#include "clang/AST/ExprCXX.h"
Douglas Gregor7de59662009-05-29 20:38:28 +000026#include "clang/AST/PrettyPrinter.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000027#include "clang/AST/Stmt.h"
28#include "clang/AST/TypeLoc.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000029#include "clang/Basic/Builtins.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000030#include "clang/Basic/IdentifierTable.h"
Douglas Gregorba345522011-12-02 23:23:56 +000031#include "clang/Basic/Module.h"
Abramo Bagnara6150c882010-05-11 21:36:43 +000032#include "clang/Basic/Specifiers.h"
Douglas Gregor1baf38f2011-03-26 12:10:19 +000033#include "clang/Basic/TargetInfo.h"
Kostya Serebryany293dc9b2014-10-16 20:54:52 +000034#include "clang/Frontend/FrontendDiagnostic.h"
John McCall06f6fe8d2009-09-04 01:14:41 +000035#include "llvm/Support/ErrorHandling.h"
David Blaikie9c70e042011-09-21 18:16:56 +000036#include <algorithm>
37
Chris Lattner6d9a6852006-10-25 05:11:20 +000038using namespace clang;
Chris Lattnera11999d2006-10-15 22:34:45 +000039
Richard Smith0b87e072013-10-07 08:02:11 +000040Decl *clang::getPrimaryMergedDecl(Decl *D) {
41 return D->getASTContext().getPrimaryMergedDecl(D);
42}
43
Richard Smith73b21d82014-09-03 02:33:22 +000044// Defined here so that it can be inlined into its direct callers.
45bool Decl::isOutOfLine() const {
46 return !getLexicalDeclContext()->Equals(getDeclContext());
47}
48
Richard Smith42413142015-05-15 20:05:43 +000049TranslationUnitDecl::TranslationUnitDecl(ASTContext &ctx)
50 : Decl(TranslationUnit, nullptr, SourceLocation()),
Richard Smith26342f92017-05-17 00:24:14 +000051 DeclContext(TranslationUnit), Ctx(ctx), AnonymousNamespace(nullptr) {}
Richard Smith42413142015-05-15 20:05:43 +000052
Chris Lattner88f70d62008-03-15 05:43:15 +000053//===----------------------------------------------------------------------===//
Douglas Gregor6e6ad602009-01-20 01:17:11 +000054// NamedDecl Implementation
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +000055//===----------------------------------------------------------------------===//
56
John McCalldf25c432013-02-16 00:17:33 +000057// Visibility rules aren't rigorously externally specified, but here
58// are the basic principles behind what we implement:
59//
60// 1. An explicit visibility attribute is generally a direct expression
61// of the user's intent and should be honored. Only the innermost
62// visibility attribute applies. If no visibility attribute applies,
63// global visibility settings are considered.
64//
65// 2. There is one caveat to the above: on or in a template pattern,
66// an explicit visibility attribute is just a default rule, and
67// visibility can be decreased by the visibility of template
68// arguments. But this, too, has an exception: an attribute on an
69// explicit specialization or instantiation causes all the visibility
70// restrictions of the template arguments to be ignored.
71//
72// 3. A variable that does not otherwise have explicit visibility can
73// be restricted by the visibility of its type.
74//
75// 4. A visibility restriction is explicit if it comes from an
76// attribute (or something like it), not a global visibility setting.
77// When emitting a reference to an external symbol, visibility
78// restrictions are ignored unless they are explicit.
John McCalld041a9b2013-02-20 01:54:26 +000079//
80// 5. When computing the visibility of a non-type, including a
81// non-type member of a class, only non-type visibility restrictions
82// are considered: the 'visibility' attribute, global value-visibility
83// settings, and a few special cases like __private_extern.
84//
85// 6. When computing the visibility of a type, including a type member
86// of a class, only type visibility restrictions are considered:
87// the 'type_visibility' attribute and global type-visibility settings.
88// However, a 'visibility' attribute counts as a 'type_visibility'
89// attribute on any declaration that only has the former.
90//
91// The visibility of a "secondary" entity, like a template argument,
92// is computed using the kind of that entity, not the kind of the
93// primary entity for which we are computing visibility. For example,
94// the visibility of a specialization of either of these templates:
95// template <class T, bool (&compare)(T, X)> bool has_match(list<T>, X);
96// template <class T, bool (&compare)(T, X)> class matcher;
97// is restricted according to the type visibility of the argument 'T',
98// the type visibility of 'bool(&)(T,X)', and the value visibility of
99// the argument function 'compare'. That 'has_match' is a value
100// and 'matcher' is a type only matters when looking for attributes
101// and settings from the immediate context.
John McCalldf25c432013-02-16 00:17:33 +0000102
John McCalld041a9b2013-02-20 01:54:26 +0000103/// Does this computation kind permit us to consider additional
104/// visibility settings from attributes and the like?
105static bool hasExplicitVisibilityAlready(LVComputationKind computation) {
Richard Smithfbe7b462017-09-22 02:22:32 +0000106 return computation.IgnoreExplicitVisibility;
John McCalld041a9b2013-02-20 01:54:26 +0000107}
108
109/// Given an LVComputationKind, return one of the same type/value sort
110/// that records that it already has explicit visibility.
111static LVComputationKind
Richard Smithfbe7b462017-09-22 02:22:32 +0000112withExplicitVisibilityAlready(LVComputationKind Kind) {
113 Kind.IgnoreExplicitVisibility = true;
114 return Kind;
John McCalld041a9b2013-02-20 01:54:26 +0000115}
116
David Blaikie05785d12013-02-20 22:23:23 +0000117static Optional<Visibility> getExplicitVisibility(const NamedDecl *D,
118 LVComputationKind kind) {
Richard Smithfbe7b462017-09-22 02:22:32 +0000119 assert(!kind.IgnoreExplicitVisibility &&
John McCalld041a9b2013-02-20 01:54:26 +0000120 "asking for explicit visibility when we shouldn't be");
Richard Smithfbe7b462017-09-22 02:22:32 +0000121 return D->getExplicitVisibility(kind.getExplicitVisibilityKind());
John McCalld041a9b2013-02-20 01:54:26 +0000122}
123
John McCalldf25c432013-02-16 00:17:33 +0000124/// Is the given declaration a "type" or a "value" for the purposes of
125/// visibility computation?
126static bool usesTypeVisibility(const NamedDecl *D) {
John McCallb4a99d32013-02-19 01:57:35 +0000127 return isa<TypeDecl>(D) ||
128 isa<ClassTemplateDecl>(D) ||
129 isa<ObjCInterfaceDecl>(D);
John McCalldf25c432013-02-16 00:17:33 +0000130}
131
John McCall5f46c482013-02-21 23:42:58 +0000132/// Does the given declaration have member specialization information,
133/// and if so, is it an explicit specialization?
134template <class T> static typename
Benjamin Kramered2f4762014-03-07 14:30:23 +0000135std::enable_if<!std::is_base_of<RedeclarableTemplateDecl, T>::value, bool>::type
John McCall5f46c482013-02-21 23:42:58 +0000136isExplicitMemberSpecialization(const T *D) {
137 if (const MemberSpecializationInfo *member =
138 D->getMemberSpecializationInfo()) {
139 return member->isExplicitSpecialization();
140 }
141 return false;
142}
143
144/// For templates, this question is easier: a member template can't be
145/// explicitly instantiated, so there's a single bit indicating whether
146/// or not this is an explicit member specialization.
147static bool isExplicitMemberSpecialization(const RedeclarableTemplateDecl *D) {
148 return D->isMemberSpecialization();
149}
150
John McCalld041a9b2013-02-20 01:54:26 +0000151/// Given a visibility attribute, return the explicit visibility
152/// associated with it.
153template <class T>
154static Visibility getVisibilityFromAttr(const T *attr) {
155 switch (attr->getVisibility()) {
156 case T::Default:
157 return DefaultVisibility;
158 case T::Hidden:
159 return HiddenVisibility;
160 case T::Protected:
161 return ProtectedVisibility;
162 }
163 llvm_unreachable("bad visibility kind");
164}
165
John McCalldf25c432013-02-16 00:17:33 +0000166/// Return the explicit visibility of the given declaration.
David Blaikie05785d12013-02-20 22:23:23 +0000167static Optional<Visibility> getVisibilityOf(const NamedDecl *D,
John McCalld041a9b2013-02-20 01:54:26 +0000168 NamedDecl::ExplicitVisibilityKind kind) {
169 // If we're ultimately computing the visibility of a type, look for
170 // a 'type_visibility' attribute before looking for 'visibility'.
171 if (kind == NamedDecl::VisibilityForType) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000172 if (const auto *A = D->getAttr<TypeVisibilityAttr>()) {
John McCalld041a9b2013-02-20 01:54:26 +0000173 return getVisibilityFromAttr(A);
174 }
175 }
176
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000177 // If this declaration has an explicit visibility attribute, use it.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000178 if (const auto *A = D->getAttr<VisibilityAttr>()) {
John McCalld041a9b2013-02-20 01:54:26 +0000179 return getVisibilityFromAttr(A);
John McCall457a04e2010-10-22 21:05:15 +0000180 }
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000181
David Blaikie7a30dc52013-02-21 01:47:18 +0000182 return None;
John McCall457a04e2010-10-22 21:05:15 +0000183}
184
George Burgess IV99db3ea2017-08-09 04:02:49 +0000185LinkageInfo LinkageComputer::getLVForType(const Type &T,
186 LVComputationKind computation) {
Richard Smithfbe7b462017-09-22 02:22:32 +0000187 if (computation.IgnoreAllVisibility)
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000188 return LinkageInfo(T.getLinkage(), DefaultVisibility, true);
George Burgess IV35cb4f82017-08-09 04:12:17 +0000189 return getTypeLinkageAndVisibility(&T);
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000190}
191
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000192/// \brief Get the most restrictive linkage for the types in the given
John McCalldf25c432013-02-16 00:17:33 +0000193/// template parameter list. For visibility purposes, template
194/// parameters are part of the signature of a template.
George Burgess IV99db3ea2017-08-09 04:02:49 +0000195LinkageInfo LinkageComputer::getLVForTemplateParameterList(
196 const TemplateParameterList *Params, LVComputationKind computation) {
John McCalldf25c432013-02-16 00:17:33 +0000197 LinkageInfo LV;
David Majnemerc7b85c42014-04-23 05:16:48 +0000198 for (const NamedDecl *P : *Params) {
John McCalldf25c432013-02-16 00:17:33 +0000199 // Template type parameters are the most common and never
200 // contribute to visibility, pack or not.
David Majnemerc7b85c42014-04-23 05:16:48 +0000201 if (isa<TemplateTypeParmDecl>(P))
John McCalldf25c432013-02-16 00:17:33 +0000202 continue;
203
204 // Non-type template parameters can be restricted by the value type, e.g.
205 // template <enum X> class A { ... };
206 // We have to be careful here, though, because we can be dealing with
207 // dependent types.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000208 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
John McCalldf25c432013-02-16 00:17:33 +0000209 // Handle the non-pack case first.
210 if (!NTTP->isExpandedParameterPack()) {
211 if (!NTTP->getType()->isDependentType()) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000212 LV.merge(getLVForType(*NTTP->getType(), computation));
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000213 }
214 continue;
215 }
Rafael Espindolaeeb9d9f2012-01-02 06:26:22 +0000216
John McCalldf25c432013-02-16 00:17:33 +0000217 // Look at all the types in an expanded pack.
218 for (unsigned i = 0, n = NTTP->getNumExpansionTypes(); i != n; ++i) {
219 QualType type = NTTP->getExpansionType(i);
220 if (!type->isDependentType())
George Burgess IV35cb4f82017-08-09 04:12:17 +0000221 LV.merge(getTypeLinkageAndVisibility(type));
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000222 }
John McCalldf25c432013-02-16 00:17:33 +0000223 continue;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000224 }
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000225
John McCalldf25c432013-02-16 00:17:33 +0000226 // Template template parameters can be restricted by their
227 // template parameters, recursively.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000228 const auto *TTP = cast<TemplateTemplateParmDecl>(P);
John McCalldf25c432013-02-16 00:17:33 +0000229
230 // Handle the non-pack case first.
231 if (!TTP->isExpandedParameterPack()) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000232 LV.merge(getLVForTemplateParameterList(TTP->getTemplateParameters(),
233 computation));
John McCalldf25c432013-02-16 00:17:33 +0000234 continue;
235 }
236
237 // Look at all expansions in an expanded pack.
238 for (unsigned i = 0, n = TTP->getNumExpansionTemplateParameters();
239 i != n; ++i) {
240 LV.merge(getLVForTemplateParameterList(
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000241 TTP->getExpansionTemplateParameters(i), computation));
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000242 }
243 }
244
John McCall457a04e2010-10-22 21:05:15 +0000245 return LV;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000246}
247
Eli Friedman7e346a82013-07-01 20:22:57 +0000248static const Decl *getOutermostFuncOrBlockContext(const Decl *D) {
Craig Topper36250ad2014-05-12 05:36:57 +0000249 const Decl *Ret = nullptr;
Rafael Espindolac1b38a22013-05-16 04:30:21 +0000250 const DeclContext *DC = D->getDeclContext();
251 while (DC->getDeclKind() != Decl::TranslationUnit) {
Eli Friedman7e346a82013-07-01 20:22:57 +0000252 if (isa<FunctionDecl>(DC) || isa<BlockDecl>(DC))
253 Ret = cast<Decl>(DC);
Rafael Espindolac1b38a22013-05-16 04:30:21 +0000254 DC = DC->getParent();
255 }
256 return Ret;
257}
258
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000259/// \brief Get the most restrictive linkage for the types and
260/// declarations in the given template argument list.
John McCalldf25c432013-02-16 00:17:33 +0000261///
262/// Note that we don't take an LVComputationKind because we always
263/// want to honor the visibility of template arguments in the same way.
George Burgess IV99db3ea2017-08-09 04:02:49 +0000264LinkageInfo
265LinkageComputer::getLVForTemplateArgumentList(ArrayRef<TemplateArgument> Args,
266 LVComputationKind computation) {
John McCalldf25c432013-02-16 00:17:33 +0000267 LinkageInfo LV;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000268
David Majnemerc7b85c42014-04-23 05:16:48 +0000269 for (const TemplateArgument &Arg : Args) {
270 switch (Arg.getKind()) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000271 case TemplateArgument::Null:
272 case TemplateArgument::Integral:
273 case TemplateArgument::Expression:
John McCalldf25c432013-02-16 00:17:33 +0000274 continue;
Rafael Espindolaeeb9d9f2012-01-02 06:26:22 +0000275
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000276 case TemplateArgument::Type:
David Majnemerc7b85c42014-04-23 05:16:48 +0000277 LV.merge(getLVForType(*Arg.getAsType(), computation));
John McCalldf25c432013-02-16 00:17:33 +0000278 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000279
280 case TemplateArgument::Declaration:
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000281 if (const auto *ND = dyn_cast<NamedDecl>(Arg.getAsDecl())) {
John McCalldf25c432013-02-16 00:17:33 +0000282 assert(!usesTypeVisibility(ND));
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000283 LV.merge(getLVForDecl(ND, computation));
John McCalldf25c432013-02-16 00:17:33 +0000284 }
285 continue;
Eli Friedmanb826a002012-09-26 02:36:12 +0000286
287 case TemplateArgument::NullPtr:
George Burgess IV35cb4f82017-08-09 04:12:17 +0000288 LV.merge(getTypeLinkageAndVisibility(Arg.getNullPtrType()));
John McCalldf25c432013-02-16 00:17:33 +0000289 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000290
291 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000292 case TemplateArgument::TemplateExpansion:
David Majnemerc7b85c42014-04-23 05:16:48 +0000293 if (TemplateDecl *Template =
294 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl())
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000295 LV.merge(getLVForDecl(Template, computation));
John McCalldf25c432013-02-16 00:17:33 +0000296 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000297
298 case TemplateArgument::Pack:
David Majnemerc7b85c42014-04-23 05:16:48 +0000299 LV.merge(getLVForTemplateArgumentList(Arg.getPackAsArray(), computation));
John McCalldf25c432013-02-16 00:17:33 +0000300 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000301 }
John McCalldf25c432013-02-16 00:17:33 +0000302 llvm_unreachable("bad template argument kind");
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000303 }
304
John McCall457a04e2010-10-22 21:05:15 +0000305 return LV;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000306}
307
George Burgess IV99db3ea2017-08-09 04:02:49 +0000308LinkageInfo
309LinkageComputer::getLVForTemplateArgumentList(const TemplateArgumentList &TArgs,
310 LVComputationKind computation) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000311 return getLVForTemplateArgumentList(TArgs.asArray(), computation);
John McCall8823c652010-08-13 08:35:10 +0000312}
313
John McCall5f46c482013-02-21 23:42:58 +0000314static bool shouldConsiderTemplateVisibility(const FunctionDecl *fn,
315 const FunctionTemplateSpecializationInfo *specInfo) {
316 // Include visibility from the template parameters and arguments
317 // only if this is not an explicit instantiation or specialization
318 // with direct explicit visibility. (Implicit instantiations won't
319 // have a direct attribute.)
320 if (!specInfo->isExplicitInstantiationOrSpecialization())
321 return true;
322
323 return !fn->hasAttr<VisibilityAttr>();
324}
325
John McCalldf25c432013-02-16 00:17:33 +0000326/// Merge in template-related linkage and visibility for the given
327/// function template specialization.
328///
329/// We don't need a computation kind here because we can assume
330/// LVForValue.
John McCall5f46c482013-02-21 23:42:58 +0000331///
NAKAMURA Takumi62eae082013-02-22 04:06:28 +0000332/// \param[out] LV the computation to use for the parent
George Burgess IV99db3ea2017-08-09 04:02:49 +0000333void LinkageComputer::mergeTemplateLV(
334 LinkageInfo &LV, const FunctionDecl *fn,
335 const FunctionTemplateSpecializationInfo *specInfo,
336 LVComputationKind computation) {
John McCall5f46c482013-02-21 23:42:58 +0000337 bool considerVisibility =
338 shouldConsiderTemplateVisibility(fn, specInfo);
John McCalldf25c432013-02-16 00:17:33 +0000339
340 // Merge information from the template parameters.
John McCall5f46c482013-02-21 23:42:58 +0000341 FunctionTemplateDecl *temp = specInfo->getTemplate();
John McCalldf25c432013-02-16 00:17:33 +0000342 LinkageInfo tempLV =
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000343 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
John McCalldf25c432013-02-16 00:17:33 +0000344 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
345
346 // Merge information from the template arguments.
347 const TemplateArgumentList &templateArgs = *specInfo->TemplateArguments;
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000348 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
John McCalldf25c432013-02-16 00:17:33 +0000349 LV.mergeMaybeWithVisibility(argsLV, considerVisibility);
John McCallb8c604a2011-06-27 23:06:04 +0000350}
351
John McCall5f46c482013-02-21 23:42:58 +0000352/// Does the given declaration have a direct visibility attribute
353/// that would match the given rules?
354static bool hasDirectVisibilityAttribute(const NamedDecl *D,
355 LVComputationKind computation) {
Richard Smithfbe7b462017-09-22 02:22:32 +0000356 if (computation.IgnoreAllVisibility)
John McCall5f46c482013-02-21 23:42:58 +0000357 return false;
Richard Smithfbe7b462017-09-22 02:22:32 +0000358
359 return (computation.isTypeVisibility() && D->hasAttr<TypeVisibilityAttr>()) ||
360 D->hasAttr<VisibilityAttr>();
John McCall5f46c482013-02-21 23:42:58 +0000361}
362
John McCalld041a9b2013-02-20 01:54:26 +0000363/// Should we consider visibility associated with the template
364/// arguments and parameters of the given class template specialization?
365static bool shouldConsiderTemplateVisibility(
366 const ClassTemplateSpecializationDecl *spec,
367 LVComputationKind computation) {
John McCalldf25c432013-02-16 00:17:33 +0000368 // Include visibility from the template parameters and arguments
369 // only if this is not an explicit instantiation or specialization
370 // with direct explicit visibility (and note that implicit
371 // instantiations won't have a direct attribute).
372 //
373 // Furthermore, we want to ignore template parameters and arguments
John McCalld041a9b2013-02-20 01:54:26 +0000374 // for an explicit specialization when computing the visibility of a
375 // member thereof with explicit visibility.
John McCalldf25c432013-02-16 00:17:33 +0000376 //
377 // This is a bit complex; let's unpack it.
378 //
379 // An explicit class specialization is an independent, top-level
380 // declaration. As such, if it or any of its members has an
381 // explicit visibility attribute, that must directly express the
382 // user's intent, and we should honor it. The same logic applies to
383 // an explicit instantiation of a member of such a thing.
John McCalld041a9b2013-02-20 01:54:26 +0000384
385 // Fast path: if this is not an explicit instantiation or
386 // specialization, we always want to consider template-related
387 // visibility restrictions.
388 if (!spec->isExplicitInstantiationOrSpecialization())
389 return true;
390
391 // This is the 'member thereof' check.
392 if (spec->isExplicitSpecialization() &&
393 hasExplicitVisibilityAlready(computation))
394 return false;
395
John McCall5f46c482013-02-21 23:42:58 +0000396 return !hasDirectVisibilityAttribute(spec, computation);
John McCalld041a9b2013-02-20 01:54:26 +0000397}
398
399/// Merge in template-related linkage and visibility for the given
400/// class template specialization.
George Burgess IV99db3ea2017-08-09 04:02:49 +0000401void LinkageComputer::mergeTemplateLV(
402 LinkageInfo &LV, const ClassTemplateSpecializationDecl *spec,
403 LVComputationKind computation) {
John McCalld041a9b2013-02-20 01:54:26 +0000404 bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
John McCalldf25c432013-02-16 00:17:33 +0000405
406 // Merge information from the template parameters, but ignore
407 // visibility if we're only considering template arguments.
408
John McCalld041a9b2013-02-20 01:54:26 +0000409 ClassTemplateDecl *temp = spec->getSpecializedTemplate();
John McCalldf25c432013-02-16 00:17:33 +0000410 LinkageInfo tempLV =
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000411 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
John McCalldf25c432013-02-16 00:17:33 +0000412 LV.mergeMaybeWithVisibility(tempLV,
John McCalld041a9b2013-02-20 01:54:26 +0000413 considerVisibility && !hasExplicitVisibilityAlready(computation));
John McCalldf25c432013-02-16 00:17:33 +0000414
415 // Merge information from the template arguments. We ignore
416 // template-argument visibility if we've got an explicit
417 // instantiation with a visibility attribute.
418 const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000419 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
Rafael Espindola503276b2013-05-30 21:23:15 +0000420 if (considerVisibility)
421 LV.mergeVisibility(argsLV);
422 LV.mergeExternalVisibility(argsLV);
John McCallb8c604a2011-06-27 23:06:04 +0000423}
424
Larisse Voufo5899e192014-07-02 23:08:34 +0000425/// Should we consider visibility associated with the template
426/// arguments and parameters of the given variable template
427/// specialization? As usual, follow class template specialization
428/// logic up to initialization.
429static bool shouldConsiderTemplateVisibility(
430 const VarTemplateSpecializationDecl *spec,
431 LVComputationKind computation) {
432 // Include visibility from the template parameters and arguments
433 // only if this is not an explicit instantiation or specialization
434 // with direct explicit visibility (and note that implicit
435 // instantiations won't have a direct attribute).
436 if (!spec->isExplicitInstantiationOrSpecialization())
437 return true;
438
439 // An explicit variable specialization is an independent, top-level
440 // declaration. As such, if it has an explicit visibility attribute,
441 // that must directly express the user's intent, and we should honor
442 // it.
443 if (spec->isExplicitSpecialization() &&
444 hasExplicitVisibilityAlready(computation))
445 return false;
446
447 return !hasDirectVisibilityAttribute(spec, computation);
448}
449
450/// Merge in template-related linkage and visibility for the given
451/// variable template specialization. As usual, follow class template
452/// specialization logic up to initialization.
George Burgess IV99db3ea2017-08-09 04:02:49 +0000453void LinkageComputer::mergeTemplateLV(LinkageInfo &LV,
454 const VarTemplateSpecializationDecl *spec,
455 LVComputationKind computation) {
Larisse Voufo5899e192014-07-02 23:08:34 +0000456 bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
457
458 // Merge information from the template parameters, but ignore
459 // visibility if we're only considering template arguments.
460
461 VarTemplateDecl *temp = spec->getSpecializedTemplate();
462 LinkageInfo tempLV =
463 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
464 LV.mergeMaybeWithVisibility(tempLV,
465 considerVisibility && !hasExplicitVisibilityAlready(computation));
466
467 // Merge information from the template arguments. We ignore
468 // template-argument visibility if we've got an explicit
469 // instantiation with a visibility attribute.
470 const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
471 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
472 if (considerVisibility)
473 LV.mergeVisibility(argsLV);
474 LV.mergeExternalVisibility(argsLV);
475}
476
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000477static bool useInlineVisibilityHidden(const NamedDecl *D) {
478 // FIXME: we should warn if -fvisibility-inlines-hidden is used with c.
Rafael Espindola5cc78902012-07-13 23:26:43 +0000479 const LangOptions &Opts = D->getASTContext().getLangOpts();
480 if (!Opts.CPlusPlus || !Opts.InlineVisibilityHidden)
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000481 return false;
482
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000483 const auto *FD = dyn_cast<FunctionDecl>(D);
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000484 if (!FD)
485 return false;
486
487 TemplateSpecializationKind TSK = TSK_Undeclared;
488 if (FunctionTemplateSpecializationInfo *spec
489 = FD->getTemplateSpecializationInfo()) {
490 TSK = spec->getTemplateSpecializationKind();
491 } else if (MemberSpecializationInfo *MSI =
492 FD->getMemberSpecializationInfo()) {
493 TSK = MSI->getTemplateSpecializationKind();
494 }
495
Craig Topper36250ad2014-05-12 05:36:57 +0000496 const FunctionDecl *Def = nullptr;
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000497 // InlineVisibilityHidden only applies to definitions, and
498 // isInlined() only gives meaningful answers on definitions
499 // anyway.
500 return TSK != TSK_ExplicitInstantiationDeclaration &&
501 TSK != TSK_ExplicitInstantiationDefinition &&
Rafael Espindolafb9d4b42012-10-11 16:32:25 +0000502 FD->hasBody(Def) && Def->isInlined() && !Def->hasAttr<GNUInlineAttr>();
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000503}
504
Rafael Espindola593537a2013-05-05 20:15:21 +0000505template <typename T> static bool isFirstInExternCContext(T *D) {
Rafael Espindola8db352d2013-10-17 15:37:26 +0000506 const T *First = D->getFirstDecl();
Rafael Espindola593537a2013-05-05 20:15:21 +0000507 return First->isInExternCContext();
Rafael Espindolaf4187652013-02-14 01:18:37 +0000508}
509
Richard Smith03c05032014-02-17 23:34:47 +0000510static bool isSingleLineLanguageLinkage(const Decl &D) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000511 if (const auto *SD = dyn_cast<LinkageSpecDecl>(D.getDeclContext()))
Richard Smith03c05032014-02-17 23:34:47 +0000512 if (!SD->hasBraces())
Rafael Espindola327be3c2013-04-26 01:30:23 +0000513 return true;
514 return false;
515}
516
Richard Smith1283e982017-07-07 20:04:28 +0000517static bool isExportedFromModuleIntefaceUnit(const NamedDecl *D) {
Richard Smithbecb92d2017-10-10 22:33:17 +0000518 // FIXME: Handle isModulePrivate.
Richard Smith1283e982017-07-07 20:04:28 +0000519 switch (D->getModuleOwnershipKind()) {
520 case Decl::ModuleOwnershipKind::Unowned:
521 case Decl::ModuleOwnershipKind::ModulePrivate:
522 return false;
523 case Decl::ModuleOwnershipKind::Visible:
524 case Decl::ModuleOwnershipKind::VisibleWhenImported:
525 if (auto *M = D->getOwningModule())
526 return M->Kind == Module::ModuleInterfaceUnit;
527 }
528 llvm_unreachable("unexpected module ownership kind");
529}
530
531static LinkageInfo getInternalLinkageFor(const NamedDecl *D) {
532 // Internal linkage declarations within a module interface unit are modeled
533 // as "module-internal linkage", which means that they have internal linkage
534 // formally but can be indirectly accessed from outside the module via inline
535 // functions and templates defined within the module.
536 if (auto *M = D->getOwningModule())
537 if (M->Kind == Module::ModuleInterfaceUnit)
538 return LinkageInfo(ModuleInternalLinkage, DefaultVisibility, false);
539
540 return LinkageInfo::internal();
541}
542
543static LinkageInfo getExternalLinkageFor(const NamedDecl *D) {
544 // C++ Modules TS [basic.link]/6.8:
545 // - A name declared at namespace scope that does not have internal linkage
546 // by the previous rules and that is introduced by a non-exported
547 // declaration has module linkage.
548 if (auto *M = D->getOwningModule())
549 if (M->Kind == Module::ModuleInterfaceUnit)
Richard Smithbecb92d2017-10-10 22:33:17 +0000550 if (!isExportedFromModuleIntefaceUnit(
551 cast<NamedDecl>(D->getCanonicalDecl())))
Richard Smith1283e982017-07-07 20:04:28 +0000552 return LinkageInfo(ModuleLinkage, DefaultVisibility, false);
553
554 return LinkageInfo::external();
555}
556
George Burgess IV99db3ea2017-08-09 04:02:49 +0000557LinkageInfo
558LinkageComputer::getLVForNamespaceScopeDecl(const NamedDecl *D,
Richard Smithc95d2c52017-09-22 04:25:05 +0000559 LVComputationKind computation,
560 bool IgnoreVarTypeLinkage) {
Sebastian Redl50c68252010-08-31 00:36:30 +0000561 assert(D->getDeclContext()->getRedeclContext()->isFileContext() &&
Douglas Gregorf73b2822009-11-25 22:24:25 +0000562 "Not a name having namespace scope");
563 ASTContext &Context = D->getASTContext();
564
565 // C++ [basic.link]p3:
566 // A name having namespace scope (3.3.6) has internal linkage if it
567 // is the name of
568 // - an object, reference, function or function template that is
569 // explicitly declared static; or,
570 // (This bullet corresponds to C99 6.2.2p3.)
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000571 if (const auto *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregorf73b2822009-11-25 22:24:25 +0000572 // Explicitly declared static.
John McCall8e7d6562010-08-26 03:08:43 +0000573 if (Var->getStorageClass() == SC_Static)
Richard Smith1283e982017-07-07 20:04:28 +0000574 return getInternalLinkageFor(Var);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000575
Richard Smith62f19e72016-06-25 00:15:56 +0000576 // - a non-inline, non-volatile object or reference that is explicitly
577 // declared const or constexpr and neither explicitly declared extern
578 // nor previously declared to have external linkage; or (there is no
579 // equivalent in C99)
Richard Smith1283e982017-07-07 20:04:28 +0000580 // The C++ modules TS adds "non-exported" to this list.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000581 if (Context.getLangOpts().CPlusPlus &&
Richard Smithdc0ef452012-10-19 06:37:48 +0000582 Var->getType().isConstQualified() &&
Richard Smith62f19e72016-06-25 00:15:56 +0000583 !Var->getType().isVolatileQualified() &&
Richard Smith1283e982017-07-07 20:04:28 +0000584 !Var->isInline() &&
585 !isExportedFromModuleIntefaceUnit(Var)) {
Rafael Espindola985a3ab2013-04-03 19:22:20 +0000586 const VarDecl *PrevVar = Var->getPreviousDecl();
Rafael Espindola985a3ab2013-04-03 19:22:20 +0000587 if (PrevVar)
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000588 return getLVForDecl(PrevVar, computation);
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000589
590 if (Var->getStorageClass() != SC_Extern &&
Rafael Espindola327be3c2013-04-26 01:30:23 +0000591 Var->getStorageClass() != SC_PrivateExtern &&
Richard Smith03c05032014-02-17 23:34:47 +0000592 !isSingleLineLanguageLinkage(*Var))
Richard Smith1283e982017-07-07 20:04:28 +0000593 return getInternalLinkageFor(Var);
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000594 }
595
596 for (const VarDecl *PrevVar = Var->getPreviousDecl(); PrevVar;
597 PrevVar = PrevVar->getPreviousDecl()) {
598 if (PrevVar->getStorageClass() == SC_PrivateExtern &&
599 Var->getStorageClass() == SC_None)
George Burgess IV35cb4f82017-08-09 04:12:17 +0000600 return getDeclLinkageAndVisibility(PrevVar);
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000601 // Explicitly declared static.
602 if (PrevVar->getStorageClass() == SC_Static)
Richard Smith1283e982017-07-07 20:04:28 +0000603 return getInternalLinkageFor(Var);
Fariborz Jahanian8feee2d2011-06-16 20:14:50 +0000604 }
Alp Tokera2794f92014-01-22 07:29:52 +0000605 } else if (const FunctionDecl *Function = D->getAsFunction()) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000606 // C++ [temp]p4:
607 // A non-member function template can have internal linkage; any
608 // other template name shall have external linkage.
Douglas Gregorf73b2822009-11-25 22:24:25 +0000609
610 // Explicitly declared static.
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000611 if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
Richard Smith1283e982017-07-07 20:04:28 +0000612 return getInternalLinkageFor(Function);
David Majnemer18fac3b2014-12-10 22:58:14 +0000613 } else if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D)) {
614 // - a data member of an anonymous union.
615 const VarDecl *VD = IFD->getVarDecl();
616 assert(VD && "Expected a VarDecl in this IndirectFieldDecl!");
Richard Smithc95d2c52017-09-22 04:25:05 +0000617 return getLVForNamespaceScopeDecl(VD, computation, IgnoreVarTypeLinkage);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000618 }
David Majnemer0eb8bbd2013-10-23 20:52:43 +0000619 assert(!isa<FieldDecl>(D) && "Didn't expect a FieldDecl!");
Douglas Gregorf73b2822009-11-25 22:24:25 +0000620
Chandler Carruth9682a2fd2011-02-24 19:03:39 +0000621 if (D->isInAnonymousNamespace()) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000622 const auto *Var = dyn_cast<VarDecl>(D);
623 const auto *Func = dyn_cast<FunctionDecl>(D);
Richard Smithdf963a32017-09-22 22:21:44 +0000624 // FIXME: The check for extern "C" here is not justified by the standard
625 // wording, but we retain it from the pre-DR1113 model to avoid breaking
626 // code.
Richard Smith1283e982017-07-07 20:04:28 +0000627 //
628 // C++11 [basic.link]p4:
629 // An unnamed namespace or a namespace declared directly or indirectly
630 // within an unnamed namespace has internal linkage.
Rafael Espindola593537a2013-05-05 20:15:21 +0000631 if ((!Var || !isFirstInExternCContext(Var)) &&
632 (!Func || !isFirstInExternCContext(Func)))
Richard Smithdf963a32017-09-22 22:21:44 +0000633 return getInternalLinkageFor(D);
Chandler Carruth9682a2fd2011-02-24 19:03:39 +0000634 }
John McCallb7139c42010-10-28 04:18:25 +0000635
John McCall457a04e2010-10-22 21:05:15 +0000636 // Set up the defaults.
637
638 // C99 6.2.2p5:
639 // If the declaration of an identifier for an object has file
640 // scope and no storage-class specifier, its linkage is
641 // external.
Richard Smithdd8b5332017-09-04 05:37:53 +0000642 LinkageInfo LV = getExternalLinkageFor(D);
John McCallc273f242010-10-30 11:50:40 +0000643
John McCalld041a9b2013-02-20 01:54:26 +0000644 if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +0000645 if (Optional<Visibility> Vis = getExplicitVisibility(D, computation)) {
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000646 LV.mergeVisibility(*Vis, true);
Rafael Espindola78158af2012-04-16 18:46:26 +0000647 } else {
648 // If we're declared in a namespace with a visibility attribute,
John McCalldf25c432013-02-16 00:17:33 +0000649 // use that namespace's visibility, and it still counts as explicit.
Rafael Espindola78158af2012-04-16 18:46:26 +0000650 for (const DeclContext *DC = D->getDeclContext();
651 !isa<TranslationUnitDecl>(DC);
652 DC = DC->getParent()) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000653 const auto *ND = dyn_cast<NamespaceDecl>(DC);
Rafael Espindola78158af2012-04-16 18:46:26 +0000654 if (!ND) continue;
David Blaikie05785d12013-02-20 22:23:23 +0000655 if (Optional<Visibility> Vis = getExplicitVisibility(ND, computation)) {
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000656 LV.mergeVisibility(*Vis, true);
Rafael Espindola78158af2012-04-16 18:46:26 +0000657 break;
658 }
659 }
660 }
Rafael Espindola78158af2012-04-16 18:46:26 +0000661
John McCalldf25c432013-02-16 00:17:33 +0000662 // Add in global settings if the above didn't give us direct visibility.
Rafael Espindola4a5da442013-02-27 02:56:45 +0000663 if (!LV.isVisibilityExplicit()) {
John McCallb4a99d32013-02-19 01:57:35 +0000664 // Use global type/value visibility as appropriate.
Richard Smithfbe7b462017-09-22 02:22:32 +0000665 Visibility globalVisibility =
666 computation.isValueVisibility()
667 ? Context.getLangOpts().getValueVisibilityMode()
668 : Context.getLangOpts().getTypeVisibilityMode();
John McCallb4a99d32013-02-19 01:57:35 +0000669 LV.mergeVisibility(globalVisibility, /*explicit*/ false);
John McCalldf25c432013-02-16 00:17:33 +0000670
671 // If we're paying attention to global visibility, apply
672 // -finline-visibility-hidden if this is an inline method.
673 if (useInlineVisibilityHidden(D))
674 LV.mergeVisibility(HiddenVisibility, true);
675 }
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000676 }
Rafael Espindolaaf690f52012-04-19 02:55:01 +0000677
Douglas Gregorf73b2822009-11-25 22:24:25 +0000678 // C++ [basic.link]p4:
John McCall457a04e2010-10-22 21:05:15 +0000679
Douglas Gregorf73b2822009-11-25 22:24:25 +0000680 // A name having namespace scope has external linkage if it is the
681 // name of
682 //
683 // - an object or reference, unless it has internal linkage; or
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000684 if (const auto *Var = dyn_cast<VarDecl>(D)) {
John McCall37bb6c92010-10-29 22:22:43 +0000685 // GCC applies the following optimization to variables and static
686 // data members, but not to functions:
687 //
John McCall457a04e2010-10-22 21:05:15 +0000688 // Modify the variable's LV by the LV of its type unless this is
689 // C or extern "C". This follows from [basic.link]p9:
690 // A type without linkage shall not be used as the type of a
691 // variable or function with external linkage unless
692 // - the entity has C language linkage, or
693 // - the entity is declared within an unnamed namespace, or
694 // - the entity is not used or is defined in the same
695 // translation unit.
696 // and [basic.link]p10:
697 // ...the types specified by all declarations referring to a
698 // given variable or function shall be identical...
699 // C does not have an equivalent rule.
700 //
John McCall5fe84122010-10-26 04:59:26 +0000701 // Ignore this if we've got an explicit attribute; the user
702 // probably knows what they're doing.
703 //
John McCall457a04e2010-10-22 21:05:15 +0000704 // Note that we don't want to make the variable non-external
705 // because of this, but unique-external linkage suits us.
Richard Smithc95d2c52017-09-22 04:25:05 +0000706 if (Context.getLangOpts().CPlusPlus && !isFirstInExternCContext(Var) &&
707 !IgnoreVarTypeLinkage) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000708 LinkageInfo TypeLV = getLVForType(*Var->getType(), computation);
Richard Smith405e2db2017-09-20 07:22:00 +0000709 if (!isExternallyVisible(TypeLV.getLinkage()))
John McCallc273f242010-10-30 11:50:40 +0000710 return LinkageInfo::uniqueExternal();
Rafael Espindola4a5da442013-02-27 02:56:45 +0000711 if (!LV.isVisibilityExplicit())
John McCalldf25c432013-02-16 00:17:33 +0000712 LV.mergeVisibility(TypeLV);
John McCall37bb6c92010-10-29 22:22:43 +0000713 }
714
John McCall23032652010-11-02 18:38:13 +0000715 if (Var->getStorageClass() == SC_PrivateExtern)
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000716 LV.mergeVisibility(HiddenVisibility, true);
John McCall23032652010-11-02 18:38:13 +0000717
Rafael Espindolad5ed0332012-11-12 04:10:23 +0000718 // Note that Sema::MergeVarDecl already takes care of implementing
719 // C99 6.2.2p4 and propagating the visibility attribute, so we don't have
720 // to do it here.
Douglas Gregorf73b2822009-11-25 22:24:25 +0000721
Larisse Voufo5899e192014-07-02 23:08:34 +0000722 // As per function and class template specializations (below),
723 // consider LV for the template and template arguments. We're at file
724 // scope, so we do not need to worry about nested specializations.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000725 if (const auto *spec = dyn_cast<VarTemplateSpecializationDecl>(Var)) {
Larisse Voufo5899e192014-07-02 23:08:34 +0000726 mergeTemplateLV(LV, spec, computation);
727 }
728
Douglas Gregorf73b2822009-11-25 22:24:25 +0000729 // - a function, unless it has internal linkage; or
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000730 } else if (const auto *Function = dyn_cast<FunctionDecl>(D)) {
John McCall2efaf112010-10-28 07:07:52 +0000731 // In theory, we can modify the function's LV by the LV of its
732 // type unless it has C linkage (see comment above about variables
733 // for justification). In practice, GCC doesn't do this, so it's
734 // just too painful to make work.
John McCall457a04e2010-10-22 21:05:15 +0000735
John McCall23032652010-11-02 18:38:13 +0000736 if (Function->getStorageClass() == SC_PrivateExtern)
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000737 LV.mergeVisibility(HiddenVisibility, true);
John McCall23032652010-11-02 18:38:13 +0000738
Rafael Espindolaa508c5d2012-11-21 02:47:19 +0000739 // Note that Sema::MergeCompatibleFunctionDecls already takes care of
740 // merging storage classes and visibility attributes, so we don't have to
741 // look at previous decls in here.
Douglas Gregorf73b2822009-11-25 22:24:25 +0000742
John McCallf768aa72011-02-10 06:50:24 +0000743 // In C++, then if the type of the function uses a type with
744 // unique-external linkage, it's not legally usable from outside
745 // this translation unit. However, we should use the C linkage
746 // rules instead for extern "C" declarations.
Richard Smithc95d2c52017-09-22 04:25:05 +0000747 if (Context.getLangOpts().CPlusPlus && !Function->isInExternCContext()) {
748 // Only look at the type-as-written. Otherwise, deducing the return type
749 // of a function could change its linkage.
Richard Smith50f4afc2013-05-12 23:17:59 +0000750 QualType TypeAsWritten = Function->getType();
751 if (TypeSourceInfo *TSI = Function->getTypeSourceInfo())
752 TypeAsWritten = TSI->getType();
Richard Smith405e2db2017-09-20 07:22:00 +0000753 if (!isExternallyVisible(TypeAsWritten->getLinkage()))
Richard Smith50f4afc2013-05-12 23:17:59 +0000754 return LinkageInfo::uniqueExternal();
755 }
John McCallf768aa72011-02-10 06:50:24 +0000756
John McCall5f46c482013-02-21 23:42:58 +0000757 // Consider LV from the template and the template arguments.
758 // We're at file scope, so we do not need to worry about nested
759 // specializations.
John McCallb8c604a2011-06-27 23:06:04 +0000760 if (FunctionTemplateSpecializationInfo *specInfo
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000761 = Function->getTemplateSpecializationInfo()) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000762 mergeTemplateLV(LV, Function, specInfo, computation);
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000763 }
764
Douglas Gregorf73b2822009-11-25 22:24:25 +0000765 // - a named class (Clause 9), or an unnamed class defined in a
766 // typedef declaration in which the class has the typedef name
767 // for linkage purposes (7.1.3); or
768 // - a named enumeration (7.2), or an unnamed enumeration
769 // defined in a typedef declaration in which the enumeration
770 // has the typedef name for linkage purposes (7.1.3); or
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000771 } else if (const auto *Tag = dyn_cast<TagDecl>(D)) {
John McCall457a04e2010-10-22 21:05:15 +0000772 // Unnamed tags have no linkage.
John McCall5ea95772013-03-09 00:54:27 +0000773 if (!Tag->hasNameForLinkage())
John McCallc273f242010-10-30 11:50:40 +0000774 return LinkageInfo::none();
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000775
John McCall457a04e2010-10-22 21:05:15 +0000776 // If this is a class template specialization, consider the
John McCall5f46c482013-02-21 23:42:58 +0000777 // linkage of the template and template arguments. We're at file
778 // scope, so we do not need to worry about nested specializations.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000779 if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) {
John McCalldf25c432013-02-16 00:17:33 +0000780 mergeTemplateLV(LV, spec, computation);
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000781 }
Douglas Gregorf73b2822009-11-25 22:24:25 +0000782
783 // - an enumerator belonging to an enumeration with external linkage;
John McCall457a04e2010-10-22 21:05:15 +0000784 } else if (isa<EnumConstantDecl>(D)) {
Rafael Espindola46cb6f12012-04-21 23:28:21 +0000785 LinkageInfo EnumLV = getLVForDecl(cast<NamedDecl>(D->getDeclContext()),
John McCalldf25c432013-02-16 00:17:33 +0000786 computation);
Rafael Espindolab97e8962013-05-27 14:14:42 +0000787 if (!isExternalFormalLinkage(EnumLV.getLinkage()))
John McCallc273f242010-10-30 11:50:40 +0000788 return LinkageInfo::none();
789 LV.merge(EnumLV);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000790
791 // - a template, unless it is a function template that has
792 // internal linkage (Clause 14);
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000793 } else if (const auto *temp = dyn_cast<TemplateDecl>(D)) {
John McCalld041a9b2013-02-20 01:54:26 +0000794 bool considerVisibility = !hasExplicitVisibilityAlready(computation);
John McCalldf25c432013-02-16 00:17:33 +0000795 LinkageInfo tempLV =
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000796 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
John McCalldf25c432013-02-16 00:17:33 +0000797 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
798
Douglas Gregorf73b2822009-11-25 22:24:25 +0000799 // - a namespace (7.3), unless it is declared within an unnamed
800 // namespace.
Richard Smith1283e982017-07-07 20:04:28 +0000801 //
802 // We handled names in anonymous namespaces above.
803 } else if (isa<NamespaceDecl>(D)) {
John McCall457a04e2010-10-22 21:05:15 +0000804 return LV;
Douglas Gregorf73b2822009-11-25 22:24:25 +0000805
John McCall457a04e2010-10-22 21:05:15 +0000806 // By extension, we assign external linkage to Objective-C
807 // interfaces.
808 } else if (isa<ObjCInterfaceDecl>(D)) {
809 // fallout
810
Richard Smith97135cc2015-11-12 22:19:45 +0000811 } else if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
812 // A typedef declaration has linkage if it gives a type a name for
813 // linkage purposes.
814 if (!TD->getAnonDeclWithTypedefName(/*AnyRedecl*/true))
815 return LinkageInfo::none();
816
John McCall457a04e2010-10-22 21:05:15 +0000817 // Everything not covered here has no linkage.
818 } else {
John McCallc273f242010-10-30 11:50:40 +0000819 return LinkageInfo::none();
John McCall457a04e2010-10-22 21:05:15 +0000820 }
821
Richard Smithc445d5d2017-10-03 01:58:15 +0000822 // If we ended up with non-externally-visible linkage, visibility should
John McCall457a04e2010-10-22 21:05:15 +0000823 // always be default.
Richard Smithc445d5d2017-10-03 01:58:15 +0000824 if (!isExternallyVisible(LV.getLinkage()))
Rafael Espindola4a5da442013-02-27 02:56:45 +0000825 return LinkageInfo(LV.getLinkage(), DefaultVisibility, false);
John McCall457a04e2010-10-22 21:05:15 +0000826
John McCall457a04e2010-10-22 21:05:15 +0000827 return LV;
Douglas Gregorf73b2822009-11-25 22:24:25 +0000828}
829
George Burgess IV99db3ea2017-08-09 04:02:49 +0000830LinkageInfo
831LinkageComputer::getLVForClassMember(const NamedDecl *D,
Richard Smithc95d2c52017-09-22 04:25:05 +0000832 LVComputationKind computation,
833 bool IgnoreVarTypeLinkage) {
John McCall457a04e2010-10-22 21:05:15 +0000834 // Only certain class members have linkage. Note that fields don't
835 // really have linkage, but it's convenient to say they do for the
836 // purposes of calculating linkage of pointer-to-data-member
837 // template arguments.
Richard Smith26d11be2014-01-08 01:51:59 +0000838 //
839 // Templates also don't officially have linkage, but since we ignore
840 // the C++ standard and look at template arguments when determining
841 // linkage and visibility of a template specialization, we might hit
842 // a template template argument that way. If we do, we need to
843 // consider its linkage.
John McCall8823c652010-08-13 08:35:10 +0000844 if (!(isa<CXXMethodDecl>(D) ||
845 isa<VarDecl>(D) ||
John McCall457a04e2010-10-22 21:05:15 +0000846 isa<FieldDecl>(D) ||
David Majnemer0eb8bbd2013-10-23 20:52:43 +0000847 isa<IndirectFieldDecl>(D) ||
Richard Smith26d11be2014-01-08 01:51:59 +0000848 isa<TagDecl>(D) ||
849 isa<TemplateDecl>(D)))
John McCallc273f242010-10-30 11:50:40 +0000850 return LinkageInfo::none();
John McCall8823c652010-08-13 08:35:10 +0000851
John McCall07072662010-11-02 01:45:15 +0000852 LinkageInfo LV;
853
John McCall07072662010-11-02 01:45:15 +0000854 // If we have an explicit visibility attribute, merge that in.
John McCalld041a9b2013-02-20 01:54:26 +0000855 if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +0000856 if (Optional<Visibility> Vis = getExplicitVisibility(D, computation))
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000857 LV.mergeVisibility(*Vis, true);
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000858 // If we're paying attention to global visibility, apply
859 // -finline-visibility-hidden if this is an inline method.
860 //
861 // Note that we do this before merging information about
862 // the class visibility.
Rafael Espindola4a5da442013-02-27 02:56:45 +0000863 if (!LV.isVisibilityExplicit() && useInlineVisibilityHidden(D))
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000864 LV.mergeVisibility(HiddenVisibility, true);
John McCall07072662010-11-02 01:45:15 +0000865 }
Rafael Espindola53cf2192012-04-19 05:50:08 +0000866
867 // If this class member has an explicit visibility attribute, the only
868 // thing that can change its visibility is the template arguments, so
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000869 // only look for them when processing the class.
John McCalld041a9b2013-02-20 01:54:26 +0000870 LVComputationKind classComputation = computation;
Rafael Espindola4a5da442013-02-27 02:56:45 +0000871 if (LV.isVisibilityExplicit())
John McCalld041a9b2013-02-20 01:54:26 +0000872 classComputation = withExplicitVisibilityAlready(computation);
Rafael Espindola505a7c82012-04-16 18:25:01 +0000873
John McCall5f46c482013-02-21 23:42:58 +0000874 LinkageInfo classLV =
875 getLVForDecl(cast<RecordDecl>(D->getDeclContext()), classComputation);
Richard Smithcdb06f22017-09-23 04:02:17 +0000876 // The member has the same linkage as the class. If that's not externally
877 // visible, we don't need to compute anything about the linkage.
878 // FIXME: If we're only computing linkage, can we bail out here?
Rafael Espindolae6190db2013-05-28 02:22:10 +0000879 if (!isExternallyVisible(classLV.getLinkage()))
Richard Smithcdb06f22017-09-23 04:02:17 +0000880 return classLV;
Rafael Espindolae6190db2013-05-28 02:22:10 +0000881
882
John McCall5f46c482013-02-21 23:42:58 +0000883 // Otherwise, don't merge in classLV yet, because in certain cases
884 // we need to completely ignore the visibility from it.
885
886 // Specifically, if this decl exists and has an explicit attribute.
Craig Topper36250ad2014-05-12 05:36:57 +0000887 const NamedDecl *explicitSpecSuppressor = nullptr;
John McCall5f46c482013-02-21 23:42:58 +0000888
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000889 if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
Richard Smithc95d2c52017-09-22 04:25:05 +0000890 // Only look at the type-as-written. Otherwise, deducing the return type
891 // of a function could change its linkage.
892 QualType TypeAsWritten = MD->getType();
893 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
894 TypeAsWritten = TSI->getType();
895 if (!isExternallyVisible(TypeAsWritten->getLinkage()))
896 return LinkageInfo::uniqueExternal();
897
John McCall457a04e2010-10-22 21:05:15 +0000898 // If this is a method template specialization, use the linkage for
899 // the template parameters and arguments.
John McCallb8c604a2011-06-27 23:06:04 +0000900 if (FunctionTemplateSpecializationInfo *spec
John McCall8823c652010-08-13 08:35:10 +0000901 = MD->getTemplateSpecializationInfo()) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000902 mergeTemplateLV(LV, MD, spec, computation);
John McCall5f46c482013-02-21 23:42:58 +0000903 if (spec->isExplicitSpecialization()) {
904 explicitSpecSuppressor = MD;
905 } else if (isExplicitMemberSpecialization(spec->getTemplate())) {
906 explicitSpecSuppressor = spec->getTemplate()->getTemplatedDecl();
907 }
908 } else if (isExplicitMemberSpecialization(MD)) {
909 explicitSpecSuppressor = MD;
John McCalle6e622e2010-11-01 01:29:57 +0000910 }
John McCall457a04e2010-10-22 21:05:15 +0000911
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000912 } else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
913 if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
John McCalldf25c432013-02-16 00:17:33 +0000914 mergeTemplateLV(LV, spec, computation);
John McCall5f46c482013-02-21 23:42:58 +0000915 if (spec->isExplicitSpecialization()) {
916 explicitSpecSuppressor = spec;
917 } else {
918 const ClassTemplateDecl *temp = spec->getSpecializedTemplate();
919 if (isExplicitMemberSpecialization(temp)) {
920 explicitSpecSuppressor = temp->getTemplatedDecl();
921 }
922 }
923 } else if (isExplicitMemberSpecialization(RD)) {
924 explicitSpecSuppressor = RD;
John McCall37bb6c92010-10-29 22:22:43 +0000925 }
926
John McCall37bb6c92010-10-29 22:22:43 +0000927 // Static data members.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000928 } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
929 if (const auto *spec = dyn_cast<VarTemplateSpecializationDecl>(VD))
Larisse Voufo5899e192014-07-02 23:08:34 +0000930 mergeTemplateLV(LV, spec, computation);
931
John McCall36cd5cc2010-10-30 09:18:49 +0000932 // Modify the variable's linkage by its type, but ignore the
933 // type's visibility unless it's a definition.
Richard Smithc95d2c52017-09-22 04:25:05 +0000934 if (!IgnoreVarTypeLinkage) {
935 LinkageInfo typeLV = getLVForType(*VD->getType(), computation);
936 // FIXME: If the type's linkage is not externally visible, we can
937 // give this static data member UniqueExternalLinkage.
938 if (!LV.isVisibilityExplicit() && !classLV.isVisibilityExplicit())
939 LV.mergeVisibility(typeLV);
940 LV.mergeExternalVisibility(typeLV);
941 }
John McCall5f46c482013-02-21 23:42:58 +0000942
943 if (isExplicitMemberSpecialization(VD)) {
944 explicitSpecSuppressor = VD;
945 }
John McCalldf25c432013-02-16 00:17:33 +0000946
947 // Template members.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000948 } else if (const auto *temp = dyn_cast<TemplateDecl>(D)) {
John McCalldf25c432013-02-16 00:17:33 +0000949 bool considerVisibility =
Rafael Espindola4a5da442013-02-27 02:56:45 +0000950 (!LV.isVisibilityExplicit() &&
951 !classLV.isVisibilityExplicit() &&
John McCalld041a9b2013-02-20 01:54:26 +0000952 !hasExplicitVisibilityAlready(computation));
John McCalldf25c432013-02-16 00:17:33 +0000953 LinkageInfo tempLV =
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000954 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
John McCalldf25c432013-02-16 00:17:33 +0000955 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
John McCall5f46c482013-02-21 23:42:58 +0000956
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000957 if (const auto *redeclTemp = dyn_cast<RedeclarableTemplateDecl>(temp)) {
John McCall5f46c482013-02-21 23:42:58 +0000958 if (isExplicitMemberSpecialization(redeclTemp)) {
959 explicitSpecSuppressor = temp->getTemplatedDecl();
960 }
961 }
John McCall37bb6c92010-10-29 22:22:43 +0000962 }
963
John McCall5f46c482013-02-21 23:42:58 +0000964 // We should never be looking for an attribute directly on a template.
965 assert(!explicitSpecSuppressor || !isa<TemplateDecl>(explicitSpecSuppressor));
966
967 // If this member is an explicit member specialization, and it has
968 // an explicit attribute, ignore visibility from the parent.
969 bool considerClassVisibility = true;
970 if (explicitSpecSuppressor &&
Rafael Espindola4a5da442013-02-27 02:56:45 +0000971 // optimization: hasDVA() is true only with explicit visibility.
972 LV.isVisibilityExplicit() &&
973 classLV.getVisibility() != DefaultVisibility &&
John McCall5f46c482013-02-21 23:42:58 +0000974 hasDirectVisibilityAttribute(explicitSpecSuppressor, computation)) {
975 considerClassVisibility = false;
976 }
977
978 // Finally, merge in information from the class.
979 LV.mergeMaybeWithVisibility(classLV, considerClassVisibility);
John McCall457a04e2010-10-22 21:05:15 +0000980 return LV;
John McCall8823c652010-08-13 08:35:10 +0000981}
982
David Blaikie68e081d2011-12-20 02:48:34 +0000983void NamedDecl::anchor() { }
984
Rafael Espindola0e0d0092013-03-14 03:07:35 +0000985bool NamedDecl::isLinkageValid() const {
Rafael Espindola50df3a02013-05-25 17:16:20 +0000986 if (!hasCachedLinkage())
Rafael Espindola0e0d0092013-03-14 03:07:35 +0000987 return true;
John McCalld396b972011-02-08 19:01:05 +0000988
Richard Smithfbe7b462017-09-22 02:22:32 +0000989 Linkage L = LinkageComputer{}
990 .computeLVForDecl(this, LVComputationKind::forLinkageOnly())
991 .getLinkage();
George Burgess IV99db3ea2017-08-09 04:02:49 +0000992 return L == getCachedLinkage();
John McCalld396b972011-02-08 19:01:05 +0000993}
994
Fariborz Jahanian6485fe42014-09-09 23:10:54 +0000995ObjCStringFormatFamily NamedDecl::getObjCFStringFormattingFamily() const {
996 StringRef name = getName();
997 if (name.empty()) return SFF_None;
998
999 if (name.front() == 'C')
1000 if (name == "CFStringCreateWithFormat" ||
1001 name == "CFStringCreateWithFormatAndArguments" ||
1002 name == "CFStringAppendFormat" ||
1003 name == "CFStringAppendFormatAndArguments")
1004 return SFF_CFString;
1005 return SFF_None;
1006}
1007
Rafael Espindola3ae00052013-05-13 00:12:11 +00001008Linkage NamedDecl::getLinkageInternal() const {
John McCalld041a9b2013-02-20 01:54:26 +00001009 // We don't care about visibility here, so ask for the cheapest
1010 // possible visibility analysis.
Richard Smithfbe7b462017-09-22 02:22:32 +00001011 return LinkageComputer{}
1012 .getLVForDecl(this, LVComputationKind::forLinkageOnly())
1013 .getLinkage();
Douglas Gregorbf62d642010-12-06 18:36:25 +00001014}
1015
John McCallc273f242010-10-30 11:50:40 +00001016LinkageInfo NamedDecl::getLinkageAndVisibility() const {
George Burgess IV99db3ea2017-08-09 04:02:49 +00001017 return LinkageComputer{}.getDeclLinkageAndVisibility(this);
John McCall033caa52010-10-29 00:29:13 +00001018}
Ted Kremenek926d8602010-04-20 23:15:35 +00001019
Rafael Espindola9ad61122013-11-26 16:09:08 +00001020static Optional<Visibility>
1021getExplicitVisibilityAux(const NamedDecl *ND,
1022 NamedDecl::ExplicitVisibilityKind kind,
1023 bool IsMostRecent) {
1024 assert(!IsMostRecent || ND == ND->getMostRecentDecl());
1025
Rafael Espindola3a52c442013-02-26 19:33:14 +00001026 // Check the declaration itself first.
Rafael Espindola9ad61122013-11-26 16:09:08 +00001027 if (Optional<Visibility> V = getVisibilityOf(ND, kind))
Rafael Espindola3a52c442013-02-26 19:33:14 +00001028 return V;
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001029
Rafael Espindola3a52c442013-02-26 19:33:14 +00001030 // If this is a member class of a specialization of a class template
1031 // and the corresponding decl has explicit visibility, use that.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001032 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND)) {
Rafael Espindola3a52c442013-02-26 19:33:14 +00001033 CXXRecordDecl *InstantiatedFrom = RD->getInstantiatedFromMemberClass();
1034 if (InstantiatedFrom)
1035 return getVisibilityOf(InstantiatedFrom, kind);
1036 }
1037
1038 // If there wasn't explicit visibility there, and this is a
1039 // specialization of a class template, check for visibility
1040 // on the pattern.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001041 if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(ND))
Rafael Espindola3a52c442013-02-26 19:33:14 +00001042 return getVisibilityOf(spec->getSpecializedTemplate()->getTemplatedDecl(),
1043 kind);
1044
1045 // Use the most recent declaration.
Rafael Espindola7ab1ce02013-12-08 01:13:22 +00001046 if (!IsMostRecent && !isa<NamespaceDecl>(ND)) {
Rafael Espindola9ad61122013-11-26 16:09:08 +00001047 const NamedDecl *MostRecent = ND->getMostRecentDecl();
1048 if (MostRecent != ND)
1049 return getExplicitVisibilityAux(MostRecent, kind, true);
1050 }
Rafael Espindola3a52c442013-02-26 19:33:14 +00001051
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001052 if (const auto *Var = dyn_cast<VarDecl>(ND)) {
Rafael Espindola96e68242012-05-16 02:10:38 +00001053 if (Var->isStaticDataMember()) {
1054 VarDecl *InstantiatedFrom = Var->getInstantiatedFromStaticDataMember();
1055 if (InstantiatedFrom)
John McCalld041a9b2013-02-20 01:54:26 +00001056 return getVisibilityOf(InstantiatedFrom, kind);
Rafael Espindola96e68242012-05-16 02:10:38 +00001057 }
1058
David Majnemer35b02bc2014-04-29 07:32:26 +00001059 if (const auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(Var))
1060 return getVisibilityOf(VTSD->getSpecializedTemplate()->getTemplatedDecl(),
1061 kind);
1062
David Blaikie7a30dc52013-02-21 01:47:18 +00001063 return None;
Rafael Espindola96e68242012-05-16 02:10:38 +00001064 }
Rafael Espindola3a52c442013-02-26 19:33:14 +00001065 // Also handle function template specializations.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001066 if (const auto *fn = dyn_cast<FunctionDecl>(ND)) {
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001067 // If the function is a specialization of a template with an
1068 // explicit visibility attribute, use that.
1069 if (FunctionTemplateSpecializationInfo *templateInfo
1070 = fn->getTemplateSpecializationInfo())
John McCalld041a9b2013-02-20 01:54:26 +00001071 return getVisibilityOf(templateInfo->getTemplate()->getTemplatedDecl(),
1072 kind);
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001073
Rafael Espindola8093fdf2012-02-23 04:17:32 +00001074 // If the function is a member of a specialization of a class template
1075 // and the corresponding decl has explicit visibility, use that.
1076 FunctionDecl *InstantiatedFrom = fn->getInstantiatedFromMemberFunction();
1077 if (InstantiatedFrom)
John McCalld041a9b2013-02-20 01:54:26 +00001078 return getVisibilityOf(InstantiatedFrom, kind);
Rafael Espindola8093fdf2012-02-23 04:17:32 +00001079
David Blaikie7a30dc52013-02-21 01:47:18 +00001080 return None;
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001081 }
1082
Rafael Espindolafb4263f2012-07-31 19:02:02 +00001083 // The visibility of a template is stored in the templated decl.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001084 if (const auto *TD = dyn_cast<TemplateDecl>(ND))
John McCalld041a9b2013-02-20 01:54:26 +00001085 return getVisibilityOf(TD->getTemplatedDecl(), kind);
Rafael Espindolafb4263f2012-07-31 19:02:02 +00001086
David Blaikie7a30dc52013-02-21 01:47:18 +00001087 return None;
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001088}
1089
Rafael Espindola9ad61122013-11-26 16:09:08 +00001090Optional<Visibility>
1091NamedDecl::getExplicitVisibility(ExplicitVisibilityKind kind) const {
1092 return getExplicitVisibilityAux(this, kind, false);
1093}
1094
George Burgess IV99db3ea2017-08-09 04:02:49 +00001095LinkageInfo LinkageComputer::getLVForClosure(const DeclContext *DC,
1096 Decl *ContextDecl,
1097 LVComputationKind computation) {
Eli Friedman7e346a82013-07-01 20:22:57 +00001098 // This lambda has its linkage/visibility determined by its owner.
Richard Smithc95d2c52017-09-22 04:25:05 +00001099 const NamedDecl *Owner;
1100 if (!ContextDecl)
1101 Owner = dyn_cast<NamedDecl>(DC);
1102 else if (isa<ParmVarDecl>(ContextDecl))
1103 Owner =
1104 dyn_cast<NamedDecl>(ContextDecl->getDeclContext()->getRedeclContext());
1105 else
1106 Owner = cast<NamedDecl>(ContextDecl);
1107
Richard Smithc95d2c52017-09-22 04:25:05 +00001108 if (!Owner)
Richard Smith7ff83042017-09-22 04:33:20 +00001109 return LinkageInfo::none();
Richard Smithc95d2c52017-09-22 04:25:05 +00001110
1111 // If the owner has a deduced type, we need to skip querying the linkage and
1112 // visibility of that type, because it might involve this closure type. The
1113 // only effect of this is that we might give a lambda VisibleNoLinkage rather
1114 // than NoLinkage when we don't strictly need to, which is benign.
1115 auto *VD = dyn_cast<VarDecl>(Owner);
Richard Smith7ff83042017-09-22 04:33:20 +00001116 LinkageInfo OwnerLV =
Richard Smithc95d2c52017-09-22 04:25:05 +00001117 VD && VD->getType()->getContainedDeducedType()
1118 ? computeLVForDecl(Owner, computation, /*IgnoreVarTypeLinkage*/true)
1119 : getLVForDecl(Owner, computation);
1120
Richard Smith7ff83042017-09-22 04:33:20 +00001121 // A lambda never formally has linkage. But if the owner is externally
1122 // visible, then the lambda is too. We apply the same rules to blocks.
1123 if (!isExternallyVisible(OwnerLV.getLinkage()))
1124 return LinkageInfo::none();
1125 return LinkageInfo(VisibleNoLinkage, OwnerLV.getVisibility(),
1126 OwnerLV.isVisibilityExplicit());
Eli Friedman7e346a82013-07-01 20:22:57 +00001127}
1128
George Burgess IV99db3ea2017-08-09 04:02:49 +00001129LinkageInfo LinkageComputer::getLVForLocalDecl(const NamedDecl *D,
1130 LVComputationKind computation) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001131 if (const auto *Function = dyn_cast<FunctionDecl>(D)) {
John McCalldf25c432013-02-16 00:17:33 +00001132 if (Function->isInAnonymousNamespace() &&
Rafael Espindola593537a2013-05-05 20:15:21 +00001133 !Function->isInExternCContext())
Richard Smithdf963a32017-09-22 22:21:44 +00001134 return getInternalLinkageFor(Function);
John McCalldf25c432013-02-16 00:17:33 +00001135
1136 // This is a "void f();" which got merged with a file static.
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001137 if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
Richard Smith1283e982017-07-07 20:04:28 +00001138 return getInternalLinkageFor(Function);
John McCalldf25c432013-02-16 00:17:33 +00001139
1140 LinkageInfo LV;
John McCalld041a9b2013-02-20 01:54:26 +00001141 if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +00001142 if (Optional<Visibility> Vis =
1143 getExplicitVisibility(Function, computation))
John McCalldf25c432013-02-16 00:17:33 +00001144 LV.mergeVisibility(*Vis, true);
1145 }
1146
1147 // Note that Sema::MergeCompatibleFunctionDecls already takes care of
1148 // merging storage classes and visibility attributes, so we don't have to
1149 // look at previous decls in here.
1150
1151 return LV;
1152 }
1153
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001154 if (const auto *Var = dyn_cast<VarDecl>(D)) {
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001155 if (Var->hasExternalStorage()) {
Rafael Espindola593537a2013-05-05 20:15:21 +00001156 if (Var->isInAnonymousNamespace() && !Var->isInExternCContext())
Richard Smithdf963a32017-09-22 22:21:44 +00001157 return getInternalLinkageFor(Var);
John McCalldf25c432013-02-16 00:17:33 +00001158
John McCalldf25c432013-02-16 00:17:33 +00001159 LinkageInfo LV;
1160 if (Var->getStorageClass() == SC_PrivateExtern)
1161 LV.mergeVisibility(HiddenVisibility, true);
John McCalld041a9b2013-02-20 01:54:26 +00001162 else if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +00001163 if (Optional<Visibility> Vis = getExplicitVisibility(Var, computation))
John McCalldf25c432013-02-16 00:17:33 +00001164 LV.mergeVisibility(*Vis, true);
1165 }
1166
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001167 if (const VarDecl *Prev = Var->getPreviousDecl()) {
1168 LinkageInfo PrevLV = getLVForDecl(Prev, computation);
1169 if (PrevLV.getLinkage())
1170 LV.setLinkage(PrevLV.getLinkage());
1171 LV.mergeVisibility(PrevLV);
1172 }
1173
John McCalldf25c432013-02-16 00:17:33 +00001174 return LV;
1175 }
Rafael Espindolaa4184182013-06-17 20:04:51 +00001176
1177 if (!Var->isStaticLocal())
1178 return LinkageInfo::none();
John McCalldf25c432013-02-16 00:17:33 +00001179 }
1180
Rafael Espindolaa4184182013-06-17 20:04:51 +00001181 ASTContext &Context = D->getASTContext();
1182 if (!Context.getLangOpts().CPlusPlus)
Rafael Espindola50df3a02013-05-25 17:16:20 +00001183 return LinkageInfo::none();
1184
Eli Friedman7e346a82013-07-01 20:22:57 +00001185 const Decl *OuterD = getOutermostFuncOrBlockContext(D);
Alexey Bataev0a47e652016-01-12 09:01:25 +00001186 if (!OuterD || OuterD->isInvalidDecl())
Rafael Espindola50df3a02013-05-25 17:16:20 +00001187 return LinkageInfo::none();
Rafael Espindola52189362013-06-04 13:43:35 +00001188
Eli Friedman7e346a82013-07-01 20:22:57 +00001189 LinkageInfo LV;
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001190 if (const auto *BD = dyn_cast<BlockDecl>(OuterD)) {
Eli Friedman7e346a82013-07-01 20:22:57 +00001191 if (!BD->getBlockManglingNumber())
1192 return LinkageInfo::none();
Rafael Espindola52189362013-06-04 13:43:35 +00001193
Eli Friedman7e346a82013-07-01 20:22:57 +00001194 LV = getLVForClosure(BD->getDeclContext()->getRedeclContext(),
1195 BD->getBlockManglingContextDecl(), computation);
1196 } else {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001197 const auto *FD = cast<FunctionDecl>(OuterD);
Eli Friedman7e346a82013-07-01 20:22:57 +00001198 if (!FD->isInlined() &&
David Majnemer9963ade2014-12-16 04:52:14 +00001199 !isTemplateInstantiation(FD->getTemplateSpecializationKind()))
Eli Friedman7e346a82013-07-01 20:22:57 +00001200 return LinkageInfo::none();
1201
1202 LV = getLVForDecl(FD, computation);
1203 }
Rafael Espindola111bb2e2013-05-27 14:50:21 +00001204 if (!isExternallyVisible(LV.getLinkage()))
Rafael Espindola50df3a02013-05-25 17:16:20 +00001205 return LinkageInfo::none();
1206 return LinkageInfo(VisibleNoLinkage, LV.getVisibility(),
1207 LV.isVisibilityExplicit());
John McCalldf25c432013-02-16 00:17:33 +00001208}
1209
Faisal Vali49b4c1f2013-10-01 02:51:53 +00001210static inline const CXXRecordDecl*
1211getOutermostEnclosingLambda(const CXXRecordDecl *Record) {
1212 const CXXRecordDecl *Ret = Record;
1213 while (Record && Record->isLambda()) {
1214 Ret = Record;
1215 if (!Record->getParent()) break;
1216 // Get the Containing Class of this Lambda Class
1217 Record = dyn_cast_or_null<CXXRecordDecl>(
1218 Record->getParent()->getParent());
1219 }
1220 return Ret;
1221}
1222
George Burgess IV99db3ea2017-08-09 04:02:49 +00001223LinkageInfo LinkageComputer::computeLVForDecl(const NamedDecl *D,
Richard Smithc95d2c52017-09-22 04:25:05 +00001224 LVComputationKind computation,
1225 bool IgnoreVarTypeLinkage) {
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00001226 // Internal_linkage attribute overrides other considerations.
1227 if (D->hasAttr<InternalLinkageAttr>())
Richard Smith1283e982017-07-07 20:04:28 +00001228 return getInternalLinkageFor(D);
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00001229
Ted Kremenek926d8602010-04-20 23:15:35 +00001230 // Objective-C: treat all Objective-C declarations as having external
1231 // linkage.
John McCall033caa52010-10-29 00:29:13 +00001232 switch (D->getKind()) {
Ted Kremenek926d8602010-04-20 23:15:35 +00001233 default:
1234 break;
Richard Smith97135cc2015-11-12 22:19:45 +00001235
1236 // Per C++ [basic.link]p2, only the names of objects, references,
1237 // functions, types, templates, namespaces, and values ever have linkage.
1238 //
1239 // Note that the name of a typedef, namespace alias, using declaration,
1240 // and so on are not the name of the corresponding type, namespace, or
1241 // declaration, so they do *not* have linkage.
Richard Smith97135cc2015-11-12 22:19:45 +00001242 case Decl::ImplicitParam:
1243 case Decl::Label:
1244 case Decl::NamespaceAlias:
Argyrios Kyrtzidis79d04282011-12-01 01:28:21 +00001245 case Decl::ParmVar:
Richard Smith97135cc2015-11-12 22:19:45 +00001246 case Decl::Using:
1247 case Decl::UsingShadow:
1248 case Decl::UsingDirective:
Argyrios Kyrtzidis79d04282011-12-01 01:28:21 +00001249 return LinkageInfo::none();
Richard Smith97135cc2015-11-12 22:19:45 +00001250
Richard Smith26210db2015-11-13 03:52:13 +00001251 case Decl::EnumConstant:
1252 // C++ [basic.link]p4: an enumerator has the linkage of its enumeration.
Bruno Cardoso Lopes057c82c2017-07-01 00:06:27 +00001253 if (D->getASTContext().getLangOpts().CPlusPlus)
1254 return getLVForDecl(cast<EnumDecl>(D->getDeclContext()), computation);
1255 return LinkageInfo::visible_none();
Richard Smith26210db2015-11-13 03:52:13 +00001256
Richard Smith97135cc2015-11-12 22:19:45 +00001257 case Decl::Typedef:
1258 case Decl::TypeAlias:
1259 // A typedef declaration has linkage if it gives a type a name for
1260 // linkage purposes.
Vassil Vassilevb00ea082017-07-01 20:44:49 +00001261 if (!cast<TypedefNameDecl>(D)
Richard Smith97135cc2015-11-12 22:19:45 +00001262 ->getAnonDeclWithTypedefName(/*AnyRedecl*/true))
1263 return LinkageInfo::none();
1264 break;
1265
John McCall457a04e2010-10-22 21:05:15 +00001266 case Decl::TemplateTemplateParm: // count these as external
1267 case Decl::NonTypeTemplateParm:
Ted Kremenek926d8602010-04-20 23:15:35 +00001268 case Decl::ObjCAtDefsField:
1269 case Decl::ObjCCategory:
1270 case Decl::ObjCCategoryImpl:
Ted Kremenek926d8602010-04-20 23:15:35 +00001271 case Decl::ObjCCompatibleAlias:
Ted Kremenek926d8602010-04-20 23:15:35 +00001272 case Decl::ObjCImplementation:
Ted Kremenek926d8602010-04-20 23:15:35 +00001273 case Decl::ObjCMethod:
1274 case Decl::ObjCProperty:
1275 case Decl::ObjCPropertyImpl:
1276 case Decl::ObjCProtocol:
Richard Smith1283e982017-07-07 20:04:28 +00001277 return getExternalLinkageFor(D);
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001278
1279 case Decl::CXXRecord: {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001280 const auto *Record = cast<CXXRecordDecl>(D);
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001281 if (Record->isLambda()) {
1282 if (!Record->getLambdaManglingNumber()) {
1283 // This lambda has no mangling number, so it's internal.
Richard Smith1283e982017-07-07 20:04:28 +00001284 return getInternalLinkageFor(D);
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001285 }
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001286
Faisal Vali49b4c1f2013-10-01 02:51:53 +00001287 // This lambda has its linkage/visibility determined:
1288 // - either by the outermost lambda if that lambda has no mangling
1289 // number.
1290 // - or by the parent of the outer most lambda
1291 // This prevents infinite recursion in settings such as nested lambdas
1292 // used in NSDMI's, for e.g.
1293 // struct L {
1294 // int t{};
1295 // int t2 = ([](int a) { return [](int b) { return b; };})(t)(t);
1296 // };
1297 const CXXRecordDecl *OuterMostLambda =
1298 getOutermostEnclosingLambda(Record);
1299 if (!OuterMostLambda->getLambdaManglingNumber())
Richard Smith1283e982017-07-07 20:04:28 +00001300 return getInternalLinkageFor(D);
Faisal Vali49b4c1f2013-10-01 02:51:53 +00001301
1302 return getLVForClosure(
1303 OuterMostLambda->getDeclContext()->getRedeclContext(),
1304 OuterMostLambda->getLambdaContextDecl(), computation);
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001305 }
1306
1307 break;
1308 }
Ted Kremenek926d8602010-04-20 23:15:35 +00001309 }
1310
Douglas Gregorf73b2822009-11-25 22:24:25 +00001311 // Handle linkage for namespace-scope names.
John McCall033caa52010-10-29 00:29:13 +00001312 if (D->getDeclContext()->getRedeclContext()->isFileContext())
Richard Smithc95d2c52017-09-22 04:25:05 +00001313 return getLVForNamespaceScopeDecl(D, computation, IgnoreVarTypeLinkage);
Douglas Gregorf73b2822009-11-25 22:24:25 +00001314
1315 // C++ [basic.link]p5:
1316 // In addition, a member function, static data member, a named
1317 // class or enumeration of class scope, or an unnamed class or
1318 // enumeration defined in a class-scope typedef declaration such
1319 // that the class or enumeration has the typedef name for linkage
1320 // purposes (7.1.3), has external linkage if the name of the class
1321 // has external linkage.
John McCall033caa52010-10-29 00:29:13 +00001322 if (D->getDeclContext()->isRecord())
Richard Smithc95d2c52017-09-22 04:25:05 +00001323 return getLVForClassMember(D, computation, IgnoreVarTypeLinkage);
Douglas Gregorf73b2822009-11-25 22:24:25 +00001324
1325 // C++ [basic.link]p6:
1326 // The name of a function declared in block scope and the name of
1327 // an object declared by a block scope extern declaration have
1328 // linkage. If there is a visible declaration of an entity with
1329 // linkage having the same name and type, ignoring entities
1330 // declared outside the innermost enclosing namespace scope, the
1331 // block scope declaration declares that same entity and receives
1332 // the linkage of the previous declaration. If there is more than
1333 // one such matching entity, the program is ill-formed. Otherwise,
1334 // if no matching entity is found, the block scope entity receives
1335 // external linkage.
John McCalldf25c432013-02-16 00:17:33 +00001336 if (D->getDeclContext()->isFunctionOrMethod())
1337 return getLVForLocalDecl(D, computation);
Douglas Gregorf73b2822009-11-25 22:24:25 +00001338
1339 // C++ [basic.link]p6:
1340 // Names not covered by these rules have no linkage.
John McCallc273f242010-10-30 11:50:40 +00001341 return LinkageInfo::none();
John McCall457a04e2010-10-22 21:05:15 +00001342}
Douglas Gregorf73b2822009-11-25 22:24:25 +00001343
George Burgess IV99db3ea2017-08-09 04:02:49 +00001344/// getLVForDecl - Get the linkage and visibility for the given declaration.
1345LinkageInfo LinkageComputer::getLVForDecl(const NamedDecl *D,
1346 LVComputationKind computation) {
1347 // Internal_linkage attribute overrides other considerations.
1348 if (D->hasAttr<InternalLinkageAttr>())
1349 return getInternalLinkageFor(D);
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00001350
Richard Smithfbe7b462017-09-22 02:22:32 +00001351 if (computation.IgnoreAllVisibility && D->hasCachedLinkage())
George Burgess IV99db3ea2017-08-09 04:02:49 +00001352 return LinkageInfo(D->getCachedLinkage(), DefaultVisibility, false);
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001353
George Burgess IV35cb4f82017-08-09 04:12:17 +00001354 if (llvm::Optional<LinkageInfo> LI = lookup(D, computation))
1355 return *LI;
1356
George Burgess IV99db3ea2017-08-09 04:02:49 +00001357 LinkageInfo LV = computeLVForDecl(D, computation);
1358 if (D->hasCachedLinkage())
1359 assert(D->getCachedLinkage() == LV.getLinkage());
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001360
George Burgess IV99db3ea2017-08-09 04:02:49 +00001361 D->setCachedLinkage(LV.getLinkage());
George Burgess IV35cb4f82017-08-09 04:12:17 +00001362 cache(D, computation, LV);
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001363
1364#ifndef NDEBUG
George Burgess IV99db3ea2017-08-09 04:02:49 +00001365 // In C (because of gnu inline) and in c++ with microsoft extensions an
1366 // static can follow an extern, so we can have two decls with different
1367 // linkages.
1368 const LangOptions &Opts = D->getASTContext().getLangOpts();
1369 if (!Opts.CPlusPlus || Opts.MicrosoftExt)
1370 return LV;
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001371
George Burgess IV99db3ea2017-08-09 04:02:49 +00001372 // We have just computed the linkage for this decl. By induction we know
1373 // that all other computed linkages match, check that the one we just
1374 // computed also does.
1375 NamedDecl *Old = nullptr;
1376 for (auto I : D->redecls()) {
1377 auto *T = cast<NamedDecl>(I);
1378 if (T == D)
1379 continue;
1380 if (!T->isInvalidDecl() && T->hasCachedLinkage()) {
1381 Old = T;
1382 break;
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001383 }
George Burgess IV99db3ea2017-08-09 04:02:49 +00001384 }
1385 assert(!Old || Old->getCachedLinkage() == D->getCachedLinkage());
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001386#endif
1387
George Burgess IV99db3ea2017-08-09 04:02:49 +00001388 return LV;
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001389}
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001390
George Burgess IV99db3ea2017-08-09 04:02:49 +00001391LinkageInfo LinkageComputer::getDeclLinkageAndVisibility(const NamedDecl *D) {
Richard Smithfbe7b462017-09-22 02:22:32 +00001392 return getLVForDecl(D,
1393 LVComputationKind(usesTypeVisibility(D)
1394 ? NamedDecl::VisibilityForType
1395 : NamedDecl::VisibilityForValue));
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001396}
1397
Richard Smithbecb92d2017-10-10 22:33:17 +00001398Module *Decl::getOwningModuleForLinkage(bool IgnoreLinkage) const {
Richard Smithdd8b5332017-09-04 05:37:53 +00001399 Module *M = getOwningModule();
1400 if (!M)
1401 return nullptr;
1402
1403 switch (M->Kind) {
1404 case Module::ModuleMapModule:
1405 // Module map modules have no special linkage semantics.
1406 return nullptr;
1407
1408 case Module::ModuleInterfaceUnit:
1409 return M;
1410
1411 case Module::GlobalModuleFragment:
1412 // External linkage declarations in the global module have no owning module
1413 // for linkage purposes. But internal linkage declarations in the global
1414 // module fragment of a particular module are owned by that module for
1415 // linkage purposes.
Richard Smithbecb92d2017-10-10 22:33:17 +00001416 if (IgnoreLinkage)
1417 return nullptr;
1418 bool InternalLinkage;
1419 if (auto *ND = dyn_cast<NamedDecl>(this))
1420 InternalLinkage = !ND->hasExternalFormalLinkage();
1421 else {
1422 auto *NSD = dyn_cast<NamespaceDecl>(this);
1423 InternalLinkage = (NSD && NSD->isAnonymousNamespace()) ||
1424 isInAnonymousNamespace();
1425 }
1426 return InternalLinkage ? M->Parent : nullptr;
Richard Smithdd8b5332017-09-04 05:37:53 +00001427 }
1428
1429 llvm_unreachable("unknown module kind");
1430}
1431
Richard Smith7873de02016-08-11 22:25:46 +00001432void NamedDecl::printName(raw_ostream &os) const {
1433 os << Name;
1434}
1435
Douglas Gregor2ada0482009-02-04 17:27:36 +00001436std::string NamedDecl::getQualifiedNameAsString() const {
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001437 std::string QualName;
1438 llvm::raw_string_ostream OS(QualName);
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00001439 printQualifiedName(OS, getASTContext().getPrintingPolicy());
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001440 return OS.str();
1441}
1442
1443void NamedDecl::printQualifiedName(raw_ostream &OS) const {
1444 printQualifiedName(OS, getASTContext().getPrintingPolicy());
1445}
1446
1447void NamedDecl::printQualifiedName(raw_ostream &OS,
1448 const PrintingPolicy &P) const {
Douglas Gregor2ada0482009-02-04 17:27:36 +00001449 const DeclContext *Ctx = getDeclContext();
1450
Argyrios Kyrtzidisa166a2b2017-03-07 09:26:07 +00001451 // For ObjC methods, look through categories and use the interface as context.
1452 if (auto *MD = dyn_cast<ObjCMethodDecl>(this))
1453 if (auto *ID = MD->getClassInterface())
1454 Ctx = ID;
1455
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001456 if (Ctx->isFunctionOrMethod()) {
1457 printName(OS);
1458 return;
1459 }
Douglas Gregor2ada0482009-02-04 17:27:36 +00001460
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001461 typedef SmallVector<const DeclContext *, 8> ContextsTy;
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001462 ContextsTy Contexts;
1463
1464 // Collect contexts.
1465 while (Ctx && isa<NamedDecl>(Ctx)) {
1466 Contexts.push_back(Ctx);
1467 Ctx = Ctx->getParent();
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001468 }
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001469
David Majnemerf7e36092016-06-23 00:15:04 +00001470 for (const DeclContext *DC : reverse(Contexts)) {
1471 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
Benjamin Kramer9170e912013-02-22 15:46:01 +00001472 OS << Spec->getName();
Douglas Gregor85673582009-05-18 17:01:57 +00001473 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
David Majnemer6fbeee32016-07-07 04:43:07 +00001474 TemplateSpecializationType::PrintTemplateArgumentList(
1475 OS, TemplateArgs.asArray(), P);
David Majnemerf7e36092016-06-23 00:15:04 +00001476 } else if (const auto *ND = dyn_cast<NamespaceDecl>(DC)) {
Richard Smith46dd5bb2014-05-30 22:16:51 +00001477 if (P.SuppressUnwrittenScope &&
1478 (ND->isAnonymousNamespace() || ND->isInline()))
1479 continue;
Reid Kleckner60103382015-12-16 02:04:40 +00001480 if (ND->isAnonymousNamespace()) {
1481 OS << (P.MSVCFormatting ? "`anonymous namespace\'"
1482 : "(anonymous namespace)");
1483 }
Sam Weinig07d211e2009-12-24 23:15:03 +00001484 else
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001485 OS << *ND;
David Majnemerf7e36092016-06-23 00:15:04 +00001486 } else if (const auto *RD = dyn_cast<RecordDecl>(DC)) {
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001487 if (!RD->getIdentifier())
David Blaikieabe1a392014-04-02 05:58:29 +00001488 OS << "(anonymous " << RD->getKindName() << ')';
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001489 else
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001490 OS << *RD;
David Majnemerf7e36092016-06-23 00:15:04 +00001491 } else if (const auto *FD = dyn_cast<FunctionDecl>(DC)) {
Craig Topper36250ad2014-05-12 05:36:57 +00001492 const FunctionProtoType *FT = nullptr;
Sam Weinigb999f682009-12-28 03:19:38 +00001493 if (FD->hasWrittenPrototype())
Eli Friedman5c27c4c2012-08-30 22:22:09 +00001494 FT = dyn_cast<FunctionProtoType>(FD->getType()->castAs<FunctionType>());
Sam Weinigb999f682009-12-28 03:19:38 +00001495
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001496 OS << *FD << '(';
Sam Weinigb999f682009-12-28 03:19:38 +00001497 if (FT) {
Sam Weinigb999f682009-12-28 03:19:38 +00001498 unsigned NumParams = FD->getNumParams();
1499 for (unsigned i = 0; i < NumParams; ++i) {
1500 if (i)
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001501 OS << ", ";
Argyrios Kyrtzidisa18347e2012-05-05 04:20:37 +00001502 OS << FD->getParamDecl(i)->getType().stream(P);
Sam Weinigb999f682009-12-28 03:19:38 +00001503 }
1504
1505 if (FT->isVariadic()) {
1506 if (NumParams > 0)
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001507 OS << ", ";
1508 OS << "...";
Sam Weinigb999f682009-12-28 03:19:38 +00001509 }
1510 }
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001511 OS << ')';
David Majnemerf7e36092016-06-23 00:15:04 +00001512 } else if (const auto *ED = dyn_cast<EnumDecl>(DC)) {
Alexander Kornienko4f355322015-11-09 16:45:17 +00001513 // C++ [dcl.enum]p10: Each enum-name and each unscoped
1514 // enumerator is declared in the scope that immediately contains
1515 // the enum-specifier. Each scoped enumerator is declared in the
1516 // scope of the enumeration.
1517 if (ED->isScoped() || ED->getIdentifier())
1518 OS << *ED;
1519 else
1520 continue;
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001521 } else {
David Majnemerf7e36092016-06-23 00:15:04 +00001522 OS << *cast<NamedDecl>(DC);
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001523 }
1524 OS << "::";
Douglas Gregor2ada0482009-02-04 17:27:36 +00001525 }
1526
Richard Smith7873de02016-08-11 22:25:46 +00001527 if (getDeclName() || isa<DecompositionDecl>(this))
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001528 OS << *this;
John McCalla2a3f7d2010-03-16 21:48:18 +00001529 else
David Blaikieabe1a392014-04-02 05:58:29 +00001530 OS << "(anonymous)";
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001531}
Douglas Gregor2ada0482009-02-04 17:27:36 +00001532
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001533void NamedDecl::getNameForDiagnostic(raw_ostream &OS,
1534 const PrintingPolicy &Policy,
1535 bool Qualified) const {
1536 if (Qualified)
1537 printQualifiedName(OS, Policy);
1538 else
1539 printName(OS);
Douglas Gregor2ada0482009-02-04 17:27:36 +00001540}
1541
Richard Smithe8292b12015-02-10 03:28:10 +00001542template<typename T> static bool isRedeclarableImpl(Redeclarable<T> *) {
1543 return true;
1544}
1545static bool isRedeclarableImpl(...) { return false; }
1546static bool isRedeclarable(Decl::Kind K) {
1547 switch (K) {
1548#define DECL(Type, Base) \
1549 case Decl::Type: \
1550 return isRedeclarableImpl((Type##Decl *)nullptr);
1551#define ABSTRACT_DECL(DECL)
1552#include "clang/AST/DeclNodes.inc"
1553 }
1554 llvm_unreachable("unknown decl kind");
1555}
1556
1557bool NamedDecl::declarationReplaces(NamedDecl *OldD, bool IsKnownNewer) const {
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001558 assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch");
1559
Richard Smithfe620d22015-03-05 23:24:12 +00001560 // Never replace one imported declaration with another; we need both results
1561 // when re-exporting.
1562 if (OldD->isFromASTFile() && isFromASTFile())
1563 return false;
1564
Richard Smith5cd86f82015-11-03 03:13:11 +00001565 // A kind mismatch implies that the declaration is not replaced.
1566 if (OldD->getKind() != getKind())
Richard Smithe8292b12015-02-10 03:28:10 +00001567 return false;
1568
Richard Smith5cd86f82015-11-03 03:13:11 +00001569 // For method declarations, we never replace. (Why?)
1570 if (isa<ObjCMethodDecl>(this))
1571 return false;
1572
1573 // For parameters, pick the newer one. This is either an error or (in
1574 // Objective-C) permitted as an extension.
1575 if (isa<ParmVarDecl>(this))
1576 return true;
1577
Richard Smithe8292b12015-02-10 03:28:10 +00001578 // Inline namespaces can give us two declarations with the same
1579 // name and kind in the same scope but different contexts; we should
1580 // keep both declarations in this case.
1581 if (!this->getDeclContext()->getRedeclContext()->Equals(
1582 OldD->getDeclContext()->getRedeclContext()))
1583 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001584
Richard Smith5cd86f82015-11-03 03:13:11 +00001585 // Using declarations can be replaced if they import the same name from the
1586 // same context.
Richard Smithe8292b12015-02-10 03:28:10 +00001587 if (auto *UD = dyn_cast<UsingDecl>(this)) {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00001588 ASTContext &Context = getASTContext();
Richard Smithe8292b12015-02-10 03:28:10 +00001589 return Context.getCanonicalNestedNameSpecifier(UD->getQualifier()) ==
Douglas Gregora9d87bc2011-02-25 00:36:19 +00001590 Context.getCanonicalNestedNameSpecifier(
Richard Smithe8292b12015-02-10 03:28:10 +00001591 cast<UsingDecl>(OldD)->getQualifier());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00001592 }
Richard Smithe8292b12015-02-10 03:28:10 +00001593 if (auto *UUVD = dyn_cast<UnresolvedUsingValueDecl>(this)) {
Eli Friedman0eaf10b2013-08-20 00:39:40 +00001594 ASTContext &Context = getASTContext();
Richard Smithe8292b12015-02-10 03:28:10 +00001595 return Context.getCanonicalNestedNameSpecifier(UUVD->getQualifier()) ==
Eli Friedman0eaf10b2013-08-20 00:39:40 +00001596 Context.getCanonicalNestedNameSpecifier(
1597 cast<UnresolvedUsingValueDecl>(OldD)->getQualifier());
1598 }
1599
Richard Smithe8292b12015-02-10 03:28:10 +00001600 // UsingDirectiveDecl's are not really NamedDecl's, and all have same name.
Richard Smith5cd86f82015-11-03 03:13:11 +00001601 // They can be replaced if they nominate the same namespace.
1602 // FIXME: Is this true even if they have different module visibility?
Richard Smithe8292b12015-02-10 03:28:10 +00001603 if (auto *UD = dyn_cast<UsingDirectiveDecl>(this))
1604 return UD->getNominatedNamespace()->getOriginalNamespace() ==
1605 cast<UsingDirectiveDecl>(OldD)->getNominatedNamespace()
1606 ->getOriginalNamespace();
Richard Smithbaf3ca52014-03-17 21:46:03 +00001607
Richard Smith5cd86f82015-11-03 03:13:11 +00001608 if (isRedeclarable(getKind())) {
1609 if (getCanonicalDecl() != OldD->getCanonicalDecl())
1610 return false;
1611
1612 if (IsKnownNewer)
1613 return true;
1614
Richard Smithe8292b12015-02-10 03:28:10 +00001615 // Check whether this is actually newer than OldD. We want to keep the
1616 // newer declaration. This loop will usually only iterate once, because
1617 // OldD is usually the previous declaration.
1618 for (auto D : redecls()) {
1619 if (D == OldD)
1620 break;
1621
1622 // If we reach the canonical declaration, then OldD is not actually older
1623 // than this one.
1624 //
1625 // FIXME: In this case, we should not add this decl to the lookup table.
1626 if (D->isCanonicalDecl())
1627 return false;
1628 }
Richard Smith5cd86f82015-11-03 03:13:11 +00001629
1630 // It's a newer declaration of the same kind of declaration in the same
1631 // scope: we want this decl instead of the existing one.
1632 return true;
Richard Smithe8292b12015-02-10 03:28:10 +00001633 }
1634
Richard Smith5cd86f82015-11-03 03:13:11 +00001635 // In all other cases, we need to keep both declarations in case they have
1636 // different visibility. Any attempt to use the name will result in an
1637 // ambiguity if more than one is visible.
1638 return false;
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001639}
1640
Douglas Gregoreddf4332009-02-24 20:03:32 +00001641bool NamedDecl::hasLinkage() const {
Rafael Espindola50df3a02013-05-25 17:16:20 +00001642 return getFormalLinkage() != NoLinkage;
Douglas Gregoreddf4332009-02-24 20:03:32 +00001643}
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001644
Daniel Dunbar166ea9ad2012-03-08 18:20:41 +00001645NamedDecl *NamedDecl::getUnderlyingDeclImpl() {
Anders Carlsson6915bf62009-06-26 06:29:23 +00001646 NamedDecl *ND = this;
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001647 while (auto *UD = dyn_cast<UsingShadowDecl>(ND))
Benjamin Kramerba0495a2012-03-08 21:00:45 +00001648 ND = UD->getTargetDecl();
1649
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001650 if (auto *AD = dyn_cast<ObjCCompatibleAliasDecl>(ND))
Benjamin Kramerba0495a2012-03-08 21:00:45 +00001651 return AD->getClassInterface();
1652
Richard Smithf2005d32015-12-29 23:34:32 +00001653 if (auto *AD = dyn_cast<NamespaceAliasDecl>(ND))
1654 return AD->getNamespace();
1655
Benjamin Kramerba0495a2012-03-08 21:00:45 +00001656 return ND;
Anders Carlsson6915bf62009-06-26 06:29:23 +00001657}
1658
John McCalla8ae2222010-04-06 21:38:20 +00001659bool NamedDecl::isCXXInstanceMember() const {
Douglas Gregor3f28ec22012-03-08 02:08:05 +00001660 if (!isCXXClassMember())
1661 return false;
1662
John McCalla8ae2222010-04-06 21:38:20 +00001663 const NamedDecl *D = this;
1664 if (isa<UsingShadowDecl>(D))
1665 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1666
John McCall5e77d762013-04-16 07:28:30 +00001667 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D) || isa<MSPropertyDecl>(D))
John McCalla8ae2222010-04-06 21:38:20 +00001668 return true;
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001669 if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()))
Alp Tokera2794f92014-01-22 07:29:52 +00001670 return MD->isInstance();
John McCalla8ae2222010-04-06 21:38:20 +00001671 return false;
1672}
1673
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +00001674//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001675// DeclaratorDecl Implementation
1676//===----------------------------------------------------------------------===//
1677
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001678template <typename DeclT>
1679static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) {
1680 if (decl->getNumTemplateParameterLists() > 0)
1681 return decl->getTemplateParameterList(0)->getTemplateLoc();
1682 else
1683 return decl->getInnerLocStart();
1684}
1685
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001686SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const {
John McCallf7bcc812010-05-28 23:32:21 +00001687 TypeSourceInfo *TSI = getTypeSourceInfo();
1688 if (TSI) return TSI->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001689 return SourceLocation();
1690}
1691
Douglas Gregor14454802011-02-25 02:25:35 +00001692void DeclaratorDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
1693 if (QualifierLoc) {
John McCall3e11ebe2010-03-15 10:12:16 +00001694 // Make sure the extended decl info is allocated.
1695 if (!hasExtInfo()) {
1696 // Save (non-extended) type source info pointer.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001697 auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
John McCall3e11ebe2010-03-15 10:12:16 +00001698 // Allocate external info struct.
1699 DeclInfo = new (getASTContext()) ExtInfo;
1700 // Restore savedTInfo into (extended) decl info.
1701 getExtInfo()->TInfo = savedTInfo;
1702 }
1703 // Set qualifier info.
Douglas Gregor14454802011-02-25 02:25:35 +00001704 getExtInfo()->QualifierLoc = QualifierLoc;
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001705 } else {
John McCall3e11ebe2010-03-15 10:12:16 +00001706 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
John McCall3e11ebe2010-03-15 10:12:16 +00001707 if (hasExtInfo()) {
Abramo Bagnara60804e12011-03-18 15:16:37 +00001708 if (getExtInfo()->NumTemplParamLists == 0) {
1709 // Save type source info pointer.
1710 TypeSourceInfo *savedTInfo = getExtInfo()->TInfo;
1711 // Deallocate the extended decl info.
1712 getASTContext().Deallocate(getExtInfo());
1713 // Restore savedTInfo into (non-extended) decl info.
1714 DeclInfo = savedTInfo;
1715 }
1716 else
1717 getExtInfo()->QualifierLoc = QualifierLoc;
John McCall3e11ebe2010-03-15 10:12:16 +00001718 }
1719 }
1720}
1721
Benjamin Kramer9cc210652015-08-05 09:40:49 +00001722void DeclaratorDecl::setTemplateParameterListsInfo(
1723 ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
1724 assert(!TPLists.empty());
Abramo Bagnara60804e12011-03-18 15:16:37 +00001725 // Make sure the extended decl info is allocated.
1726 if (!hasExtInfo()) {
1727 // Save (non-extended) type source info pointer.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001728 auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
Abramo Bagnara60804e12011-03-18 15:16:37 +00001729 // Allocate external info struct.
1730 DeclInfo = new (getASTContext()) ExtInfo;
1731 // Restore savedTInfo into (extended) decl info.
1732 getExtInfo()->TInfo = savedTInfo;
1733 }
1734 // Set the template parameter lists info.
Benjamin Kramer9cc210652015-08-05 09:40:49 +00001735 getExtInfo()->setTemplateParameterListsInfo(Context, TPLists);
Abramo Bagnara60804e12011-03-18 15:16:37 +00001736}
1737
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001738SourceLocation DeclaratorDecl::getOuterLocStart() const {
1739 return getTemplateOrInnerLocStart(this);
1740}
1741
Abramo Bagnaraea947882011-03-08 16:41:52 +00001742namespace {
1743
1744// Helper function: returns true if QT is or contains a type
1745// having a postfix component.
1746bool typeIsPostfix(clang::QualType QT) {
1747 while (true) {
1748 const Type* T = QT.getTypePtr();
1749 switch (T->getTypeClass()) {
1750 default:
1751 return false;
1752 case Type::Pointer:
1753 QT = cast<PointerType>(T)->getPointeeType();
1754 break;
1755 case Type::BlockPointer:
1756 QT = cast<BlockPointerType>(T)->getPointeeType();
1757 break;
1758 case Type::MemberPointer:
1759 QT = cast<MemberPointerType>(T)->getPointeeType();
1760 break;
1761 case Type::LValueReference:
1762 case Type::RValueReference:
1763 QT = cast<ReferenceType>(T)->getPointeeType();
1764 break;
1765 case Type::PackExpansion:
1766 QT = cast<PackExpansionType>(T)->getPattern();
1767 break;
1768 case Type::Paren:
1769 case Type::ConstantArray:
1770 case Type::DependentSizedArray:
1771 case Type::IncompleteArray:
1772 case Type::VariableArray:
1773 case Type::FunctionProto:
1774 case Type::FunctionNoProto:
1775 return true;
1776 }
1777 }
1778}
1779
1780} // namespace
1781
1782SourceRange DeclaratorDecl::getSourceRange() const {
1783 SourceLocation RangeEnd = getLocation();
1784 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
Benjamin Kramer3a7cc812014-02-02 15:28:46 +00001785 // If the declaration has no name or the type extends past the name take the
1786 // end location of the type.
1787 if (!getDeclName() || typeIsPostfix(TInfo->getType()))
Abramo Bagnaraea947882011-03-08 16:41:52 +00001788 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
1789 }
1790 return SourceRange(getOuterLocStart(), RangeEnd);
1791}
1792
Benjamin Kramer9cc210652015-08-05 09:40:49 +00001793void QualifierInfo::setTemplateParameterListsInfo(
1794 ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001795 // Free previous template parameters (if any).
1796 if (NumTemplParamLists > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00001797 Context.Deallocate(TemplParamLists);
Craig Topper36250ad2014-05-12 05:36:57 +00001798 TemplParamLists = nullptr;
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001799 NumTemplParamLists = 0;
1800 }
1801 // Set info on matched template parameter lists (if any).
Benjamin Kramer9cc210652015-08-05 09:40:49 +00001802 if (!TPLists.empty()) {
1803 TemplParamLists = new (Context) TemplateParameterList *[TPLists.size()];
1804 NumTemplParamLists = TPLists.size();
1805 std::copy(TPLists.begin(), TPLists.end(), TemplParamLists);
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001806 }
1807}
1808
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001809//===----------------------------------------------------------------------===//
Nuno Lopes394ec982008-12-17 23:39:55 +00001810// VarDecl Implementation
1811//===----------------------------------------------------------------------===//
1812
Sebastian Redl833ef452010-01-26 22:01:41 +00001813const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) {
1814 switch (SC) {
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00001815 case SC_None: break;
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00001816 case SC_Auto: return "auto";
1817 case SC_Extern: return "extern";
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00001818 case SC_PrivateExtern: return "__private_extern__";
1819 case SC_Register: return "register";
1820 case SC_Static: return "static";
Sebastian Redl833ef452010-01-26 22:01:41 +00001821 }
1822
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00001823 llvm_unreachable("Invalid storage class");
Sebastian Redl833ef452010-01-26 22:01:41 +00001824}
1825
Richard Smith053f6c62014-05-16 23:01:30 +00001826VarDecl::VarDecl(Kind DK, ASTContext &C, DeclContext *DC,
1827 SourceLocation StartLoc, SourceLocation IdLoc,
1828 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
1829 StorageClass SC)
1830 : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc),
1831 redeclarable_base(C), Init() {
Benjamin Kramera939c232014-03-15 18:54:13 +00001832 static_assert(sizeof(VarDeclBitfields) <= sizeof(unsigned),
1833 "VarDeclBitfields too large!");
1834 static_assert(sizeof(ParmVarDeclBitfields) <= sizeof(unsigned),
1835 "ParmVarDeclBitfields too large!");
David Majnemerfa7bc782015-05-19 00:57:16 +00001836 static_assert(sizeof(NonParmVarDeclBitfields) <= sizeof(unsigned),
1837 "NonParmVarDeclBitfields too large!");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001838 AllBits = 0;
1839 VarDeclBits.SClass = SC;
1840 // Everything else is implicitly initialized to false.
1841}
1842
Abramo Bagnaradff19302011-03-08 08:55:46 +00001843VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC,
1844 SourceLocation StartL, SourceLocation IdL,
John McCallbcd03502009-12-07 02:54:59 +00001845 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001846 StorageClass S) {
Richard Smith053f6c62014-05-16 23:01:30 +00001847 return new (C, DC) VarDecl(Var, C, DC, StartL, IdL, Id, T, TInfo, S);
Nuno Lopes394ec982008-12-17 23:39:55 +00001848}
1849
Douglas Gregor72172e92012-01-05 21:55:30 +00001850VarDecl *VarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00001851 return new (C, ID)
1852 VarDecl(Var, C, nullptr, SourceLocation(), SourceLocation(), nullptr,
1853 QualType(), nullptr, SC_None);
Douglas Gregor72172e92012-01-05 21:55:30 +00001854}
1855
Douglas Gregorbf62d642010-12-06 18:36:25 +00001856void VarDecl::setStorageClass(StorageClass SC) {
1857 assert(isLegalForVariable(SC));
John McCallbeaa11c2011-05-01 02:13:58 +00001858 VarDeclBits.SClass = SC;
Douglas Gregorbf62d642010-12-06 18:36:25 +00001859}
1860
Reid Kleckner7d6d2702014-05-01 03:16:47 +00001861VarDecl::TLSKind VarDecl::getTLSKind() const {
1862 switch (VarDeclBits.TSCSpec) {
1863 case TSCS_unspecified:
Samuel Antaof8b50122015-07-13 22:54:53 +00001864 if (!hasAttr<ThreadAttr>() &&
1865 !(getASTContext().getLangOpts().OpenMPUseTLS &&
1866 getASTContext().getTargetInfo().isTLSSupported() &&
1867 hasAttr<OMPThreadPrivateDeclAttr>()))
David Majnemer1b5baff2015-05-14 05:19:23 +00001868 return TLS_None;
Samuel Antaof8b50122015-07-13 22:54:53 +00001869 return ((getASTContext().getLangOpts().isCompatibleWithMSVC(
1870 LangOptions::MSVC2015)) ||
1871 hasAttr<OMPThreadPrivateDeclAttr>())
David Majnemer1b5baff2015-05-14 05:19:23 +00001872 ? TLS_Dynamic
1873 : TLS_Static;
Reid Kleckner7d6d2702014-05-01 03:16:47 +00001874 case TSCS___thread: // Fall through.
1875 case TSCS__Thread_local:
Samuel Antaof8b50122015-07-13 22:54:53 +00001876 return TLS_Static;
Reid Kleckner7d6d2702014-05-01 03:16:47 +00001877 case TSCS_thread_local:
1878 return TLS_Dynamic;
1879 }
1880 llvm_unreachable("Unknown thread storage class specifier!");
1881}
1882
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001883SourceRange VarDecl::getSourceRange() const {
Argyrios Kyrtzidise0d64972012-10-08 23:08:41 +00001884 if (const Expr *Init = getInit()) {
1885 SourceLocation InitEnd = Init->getLocEnd();
Nico Weberbbe13942013-01-22 17:00:09 +00001886 // If Init is implicit, ignore its source range and fallback on
1887 // DeclaratorDecl::getSourceRange() to handle postfix elements.
1888 if (InitEnd.isValid() && InitEnd != getLocation())
Argyrios Kyrtzidise0d64972012-10-08 23:08:41 +00001889 return SourceRange(getOuterLocStart(), InitEnd);
1890 }
Abramo Bagnaraea947882011-03-08 16:41:52 +00001891 return DeclaratorDecl::getSourceRange();
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00001892}
1893
Rafael Espindola88510672013-01-04 21:18:45 +00001894template<typename T>
Alp Toker84212df2014-05-31 06:11:02 +00001895static LanguageLinkage getDeclLanguageLinkage(const T &D) {
Rafael Espindola5bda63f2013-02-14 01:47:04 +00001896 // C++ [dcl.link]p1: All function types, function names with external linkage,
1897 // and variable names with external linkage have a language linkage.
Rafael Espindola3ae00052013-05-13 00:12:11 +00001898 if (!D.hasExternalFormalLinkage())
Rafael Espindola5bda63f2013-02-14 01:47:04 +00001899 return NoLanguageLinkage;
1900
1901 // Language linkage is a C++ concept, but saying that everything else in C has
Rafael Espindola66748e92013-01-04 20:41:40 +00001902 // C language linkage fits the implementation nicely.
Rafael Espindola576127d2012-12-28 14:21:58 +00001903 ASTContext &Context = D.getASTContext();
1904 if (!Context.getLangOpts().CPlusPlus)
Rafael Espindolaf4187652013-02-14 01:18:37 +00001905 return CLanguageLinkage;
1906
Rafael Espindola5bda63f2013-02-14 01:47:04 +00001907 // C++ [dcl.link]p4: A C language linkage is ignored in determining the
1908 // language linkage of the names of class members and the function type of
1909 // class member functions.
Rafael Espindola576127d2012-12-28 14:21:58 +00001910 const DeclContext *DC = D.getDeclContext();
1911 if (DC->isRecord())
Rafael Espindolaf4187652013-02-14 01:18:37 +00001912 return CXXLanguageLinkage;
Rafael Espindola576127d2012-12-28 14:21:58 +00001913
1914 // If the first decl is in an extern "C" context, any other redeclaration
1915 // will have C language linkage. If the first one is not in an extern "C"
1916 // context, we would have reported an error for any other decl being in one.
Rafael Espindola593537a2013-05-05 20:15:21 +00001917 if (isFirstInExternCContext(&D))
Rafael Espindolaf4187652013-02-14 01:18:37 +00001918 return CLanguageLinkage;
1919 return CXXLanguageLinkage;
Rafael Espindola576127d2012-12-28 14:21:58 +00001920}
1921
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001922template<typename T>
Alp Toker84212df2014-05-31 06:11:02 +00001923static bool isDeclExternC(const T &D) {
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001924 // Since the context is ignored for class members, they can only have C++
1925 // language linkage or no language linkage.
1926 const DeclContext *DC = D.getDeclContext();
1927 if (DC->isRecord()) {
1928 assert(D.getASTContext().getLangOpts().CPlusPlus);
1929 return false;
1930 }
1931
1932 return D.getLanguageLinkage() == CLanguageLinkage;
1933}
1934
Rafael Espindolaf4187652013-02-14 01:18:37 +00001935LanguageLinkage VarDecl::getLanguageLinkage() const {
Alp Toker84212df2014-05-31 06:11:02 +00001936 return getDeclLanguageLinkage(*this);
Rafael Espindola576127d2012-12-28 14:21:58 +00001937}
1938
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001939bool VarDecl::isExternC() const {
Alp Toker84212df2014-05-31 06:11:02 +00001940 return isDeclExternC(*this);
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001941}
1942
Rafael Espindola593537a2013-05-05 20:15:21 +00001943bool VarDecl::isInExternCContext() const {
Serge Pavlov3cb80222013-11-14 02:13:03 +00001944 return getLexicalDeclContext()->isExternCContext();
Rafael Espindola593537a2013-05-05 20:15:21 +00001945}
1946
1947bool VarDecl::isInExternCXXContext() const {
Serge Pavlov3cb80222013-11-14 02:13:03 +00001948 return getLexicalDeclContext()->isExternCXXContext();
Rafael Espindola593537a2013-05-05 20:15:21 +00001949}
1950
Rafael Espindola8db352d2013-10-17 15:37:26 +00001951VarDecl *VarDecl::getCanonicalDecl() { return getFirstDecl(); }
Sebastian Redl833ef452010-01-26 22:01:41 +00001952
Nico Weber7f5015a2015-04-15 21:53:00 +00001953VarDecl::DefinitionKind
1954VarDecl::isThisDeclarationADefinition(ASTContext &C) const {
Sebastian Redl35351a92010-01-31 22:27:38 +00001955 // C++ [basic.def]p2:
1956 // A declaration is a definition unless [...] it contains the 'extern'
1957 // specifier or a linkage-specification and neither an initializer [...],
Richard Smith62f19e72016-06-25 00:15:56 +00001958 // it declares a non-inline static data member in a class declaration [...],
1959 // it declares a static data member outside a class definition and the variable
1960 // was defined within the class with the constexpr specifier [...],
Richard Smith8809a0c2013-09-27 20:14:12 +00001961 // C++1y [temp.expl.spec]p15:
1962 // An explicit specialization of a static data member or an explicit
1963 // specialization of a static data member template is a definition if the
1964 // declaration includes an initializer; otherwise, it is a declaration.
1965 //
1966 // FIXME: How do you declare (but not define) a partial specialization of
1967 // a static data member template outside the containing class?
Richard Smithedbc6e92016-10-14 21:41:24 +00001968 if (isThisDeclarationADemotedDefinition())
1969 return DeclarationOnly;
1970
Sebastian Redl35351a92010-01-31 22:27:38 +00001971 if (isStaticDataMember()) {
Richard Smith8809a0c2013-09-27 20:14:12 +00001972 if (isOutOfLine() &&
Richard Smith62f19e72016-06-25 00:15:56 +00001973 !(getCanonicalDecl()->isInline() &&
1974 getCanonicalDecl()->isConstexpr()) &&
Richard Smith8809a0c2013-09-27 20:14:12 +00001975 (hasInit() ||
1976 // If the first declaration is out-of-line, this may be an
1977 // instantiation of an out-of-line partial specialization of a variable
1978 // template for which we have not yet instantiated the initializer.
Rafael Espindola8db352d2013-10-17 15:37:26 +00001979 (getFirstDecl()->isOutOfLine()
Richard Smith8809a0c2013-09-27 20:14:12 +00001980 ? getTemplateSpecializationKind() == TSK_Undeclared
1981 : getTemplateSpecializationKind() !=
1982 TSK_ExplicitSpecialization) ||
1983 isa<VarTemplatePartialSpecializationDecl>(this)))
Sebastian Redl35351a92010-01-31 22:27:38 +00001984 return Definition;
Richard Smith62f19e72016-06-25 00:15:56 +00001985 else if (!isOutOfLine() && isInline())
1986 return Definition;
Sebastian Redl35351a92010-01-31 22:27:38 +00001987 else
1988 return DeclarationOnly;
1989 }
1990 // C99 6.7p5:
1991 // A definition of an identifier is a declaration for that identifier that
1992 // [...] causes storage to be reserved for that object.
1993 // Note: that applies for all non-file-scope objects.
1994 // C99 6.9.2p1:
1995 // If the declaration of an identifier for an object has file scope and an
1996 // initializer, the declaration is an external definition for the identifier
1997 if (hasInit())
1998 return Definition;
Rafael Espindolabff59562013-04-25 12:11:36 +00001999
Dmitry Polukhin85eda122016-04-11 07:48:59 +00002000 if (hasDefiningAttr())
Rafael Espindolad53ffa02013-10-22 21:39:03 +00002001 return Definition;
2002
David Majnemerdd0bed12015-05-14 05:19:20 +00002003 if (const auto *SAA = getAttr<SelectAnyAttr>())
2004 if (!SAA->isInherited())
2005 return Definition;
2006
Richard Smith8809a0c2013-09-27 20:14:12 +00002007 // A variable template specialization (other than a static data member
2008 // template or an explicit specialization) is a declaration until we
2009 // instantiate its initializer.
2010 if (isa<VarTemplateSpecializationDecl>(this) &&
2011 getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
2012 return DeclarationOnly;
2013
Nico Weber608e7682015-04-15 23:04:24 +00002014 if (hasExternalStorage())
Sebastian Redl35351a92010-01-31 22:27:38 +00002015 return DeclarationOnly;
Rafael Espindola8f326a52013-03-07 01:42:44 +00002016
Rafael Espindolabff59562013-04-25 12:11:36 +00002017 // [dcl.link] p7:
2018 // A declaration directly contained in a linkage-specification is treated
2019 // as if it contains the extern specifier for the purpose of determining
2020 // the linkage of the declared name and whether it is a definition.
Nico Weber608e7682015-04-15 23:04:24 +00002021 if (isSingleLineLanguageLinkage(*this))
Rafael Espindola327be3c2013-04-26 01:30:23 +00002022 return DeclarationOnly;
Rafael Espindolabff59562013-04-25 12:11:36 +00002023
Sebastian Redl35351a92010-01-31 22:27:38 +00002024 // C99 6.9.2p2:
2025 // A declaration of an object that has file scope without an initializer,
2026 // and without a storage class specifier or the scs 'static', constitutes
2027 // a tentative definition.
2028 // No such thing in C++.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002029 if (!C.getLangOpts().CPlusPlus && isFileVarDecl())
Sebastian Redl35351a92010-01-31 22:27:38 +00002030 return TentativeDefinition;
2031
2032 // What's left is (in C, block-scope) declarations without initializers or
2033 // external storage. These are definitions.
2034 return Definition;
2035}
2036
Sebastian Redl35351a92010-01-31 22:27:38 +00002037VarDecl *VarDecl::getActingDefinition() {
2038 DefinitionKind Kind = isThisDeclarationADefinition();
2039 if (Kind != TentativeDefinition)
Craig Topper36250ad2014-05-12 05:36:57 +00002040 return nullptr;
Sebastian Redl35351a92010-01-31 22:27:38 +00002041
Craig Topper36250ad2014-05-12 05:36:57 +00002042 VarDecl *LastTentative = nullptr;
Rafael Espindola8db352d2013-10-17 15:37:26 +00002043 VarDecl *First = getFirstDecl();
Aaron Ballman86c93902014-03-06 23:45:36 +00002044 for (auto I : First->redecls()) {
2045 Kind = I->isThisDeclarationADefinition();
Sebastian Redl35351a92010-01-31 22:27:38 +00002046 if (Kind == Definition)
Craig Topper36250ad2014-05-12 05:36:57 +00002047 return nullptr;
Sebastian Redl35351a92010-01-31 22:27:38 +00002048 else if (Kind == TentativeDefinition)
Aaron Ballman86c93902014-03-06 23:45:36 +00002049 LastTentative = I;
Sebastian Redl35351a92010-01-31 22:27:38 +00002050 }
2051 return LastTentative;
2052}
2053
Daniel Dunbar9d355812012-03-09 01:51:51 +00002054VarDecl *VarDecl::getDefinition(ASTContext &C) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00002055 VarDecl *First = getFirstDecl();
Aaron Ballman86c93902014-03-06 23:45:36 +00002056 for (auto I : First->redecls()) {
2057 if (I->isThisDeclarationADefinition(C) == Definition)
2058 return I;
Sebastian Redl5ca79842010-02-01 20:16:42 +00002059 }
Craig Topper36250ad2014-05-12 05:36:57 +00002060 return nullptr;
Sebastian Redl5ca79842010-02-01 20:16:42 +00002061}
2062
Daniel Dunbar9d355812012-03-09 01:51:51 +00002063VarDecl::DefinitionKind VarDecl::hasDefinition(ASTContext &C) const {
John McCall37bb6c92010-10-29 22:22:43 +00002064 DefinitionKind Kind = DeclarationOnly;
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002065
Rafael Espindola8db352d2013-10-17 15:37:26 +00002066 const VarDecl *First = getFirstDecl();
Aaron Ballman86c93902014-03-06 23:45:36 +00002067 for (auto I : First->redecls()) {
2068 Kind = std::max(Kind, I->isThisDeclarationADefinition(C));
Daniel Dunbar082c62d2012-03-06 23:52:46 +00002069 if (Kind == Definition)
2070 break;
2071 }
John McCall37bb6c92010-10-29 22:22:43 +00002072
2073 return Kind;
2074}
2075
Sebastian Redl5ca79842010-02-01 20:16:42 +00002076const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const {
Aaron Ballman86c93902014-03-06 23:45:36 +00002077 for (auto I : redecls()) {
2078 if (auto Expr = I->getInit()) {
2079 D = I;
2080 return Expr;
2081 }
Sebastian Redl833ef452010-01-26 22:01:41 +00002082 }
Craig Topper36250ad2014-05-12 05:36:57 +00002083 return nullptr;
Sebastian Redl833ef452010-01-26 22:01:41 +00002084}
2085
Chandler Carruth813faed2015-12-30 02:51:00 +00002086bool VarDecl::hasInit() const {
2087 if (auto *P = dyn_cast<ParmVarDecl>(this))
2088 if (P->hasUnparsedDefaultArg() || P->hasUninstantiatedDefaultArg())
2089 return false;
2090
2091 return !Init.isNull();
2092}
2093
2094Expr *VarDecl::getInit() {
2095 if (!hasInit())
2096 return nullptr;
2097
2098 if (auto *S = Init.dyn_cast<Stmt *>())
2099 return cast<Expr>(S);
2100
2101 return cast_or_null<Expr>(Init.get<EvaluatedStmt *>()->Value);
2102}
2103
2104Stmt **VarDecl::getInitAddress() {
2105 if (auto *ES = Init.dyn_cast<EvaluatedStmt *>())
2106 return &ES->Value;
2107
2108 return Init.getAddrOfPtr1();
2109}
2110
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002111bool VarDecl::isOutOfLine() const {
Douglas Gregorb11aad82011-02-19 18:51:44 +00002112 if (Decl::isOutOfLine())
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002113 return true;
Chandler Carruthf50ef6e2010-02-21 07:08:09 +00002114
2115 if (!isStaticDataMember())
2116 return false;
2117
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002118 // If this static data member was instantiated from a static data member of
2119 // a class template, check whether that static data member was defined
2120 // out-of-line.
2121 if (VarDecl *VD = getInstantiatedFromStaticDataMember())
2122 return VD->isOutOfLine();
2123
2124 return false;
2125}
2126
Douglas Gregord5058122010-02-11 01:19:42 +00002127void VarDecl::setInit(Expr *I) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002128 if (auto *Eval = Init.dyn_cast<EvaluatedStmt *>()) {
Sebastian Redl833ef452010-01-26 22:01:41 +00002129 Eval->~EvaluatedStmt();
Douglas Gregord5058122010-02-11 01:19:42 +00002130 getASTContext().Deallocate(Eval);
Sebastian Redl833ef452010-01-26 22:01:41 +00002131 }
2132
2133 Init = I;
2134}
2135
Daniel Dunbar9d355812012-03-09 01:51:51 +00002136bool VarDecl::isUsableInConstantExpressions(ASTContext &C) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002137 const LangOptions &Lang = C.getLangOpts();
Richard Smith242ad892011-12-21 02:55:12 +00002138
Richard Smith35ecb362012-03-02 04:14:40 +00002139 if (!Lang.CPlusPlus)
2140 return false;
2141
2142 // In C++11, any variable of reference type can be used in a constant
2143 // expression if it is initialized by a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002144 if (Lang.CPlusPlus11 && getType()->isReferenceType())
Richard Smith35ecb362012-03-02 04:14:40 +00002145 return true;
2146
2147 // Only const objects can be used in constant expressions in C++. C++98 does
Richard Smith242ad892011-12-21 02:55:12 +00002148 // not require the variable to be non-volatile, but we consider this to be a
2149 // defect.
Richard Smith35ecb362012-03-02 04:14:40 +00002150 if (!getType().isConstQualified() || getType().isVolatileQualified())
Richard Smith242ad892011-12-21 02:55:12 +00002151 return false;
2152
2153 // In C++, const, non-volatile variables of integral or enumeration types
2154 // can be used in constant expressions.
2155 if (getType()->isIntegralOrEnumerationType())
2156 return true;
2157
Richard Smith35ecb362012-03-02 04:14:40 +00002158 // Additionally, in C++11, non-volatile constexpr variables can be used in
2159 // constant expressions.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002160 return Lang.CPlusPlus11 && isConstexpr();
Richard Smith242ad892011-12-21 02:55:12 +00002161}
2162
Richard Smithd0b4dd62011-12-19 06:19:21 +00002163/// Convert the initializer for this declaration to the elaborated EvaluatedStmt
2164/// form, which contains extra information on the evaluated value of the
2165/// initializer.
2166EvaluatedStmt *VarDecl::ensureEvaluatedStmt() const {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002167 auto *Eval = Init.dyn_cast<EvaluatedStmt *>();
Richard Smithd0b4dd62011-12-19 06:19:21 +00002168 if (!Eval) {
Manuel Klimeka7328992013-06-03 13:51:33 +00002169 // Note: EvaluatedStmt contains an APValue, which usually holds
2170 // resources not allocated from the ASTContext. We need to do some
2171 // work to avoid leaking those, but we do so in VarDecl::evaluateValue
2172 // where we can detect whether there's anything to clean up or not.
Richard Smithd0b4dd62011-12-19 06:19:21 +00002173 Eval = new (getASTContext()) EvaluatedStmt;
Chandler Carruth813faed2015-12-30 02:51:00 +00002174 Eval->Value = Init.get<Stmt *>();
Richard Smithd0b4dd62011-12-19 06:19:21 +00002175 Init = Eval;
2176 }
2177 return Eval;
2178}
2179
Richard Smithdafff942012-01-14 04:30:29 +00002180APValue *VarDecl::evaluateValue() const {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002181 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithdafff942012-01-14 04:30:29 +00002182 return evaluateValue(Notes);
2183}
2184
2185APValue *VarDecl::evaluateValue(
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002186 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithd0b4dd62011-12-19 06:19:21 +00002187 EvaluatedStmt *Eval = ensureEvaluatedStmt();
2188
2189 // We only produce notes indicating why an initializer is non-constant the
2190 // first time it is evaluated. FIXME: The notes won't always be emitted the
2191 // first time we try evaluation, so might not be produced at all.
2192 if (Eval->WasEvaluated)
Craig Topper36250ad2014-05-12 05:36:57 +00002193 return Eval->Evaluated.isUninit() ? nullptr : &Eval->Evaluated;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002194
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002195 const auto *Init = cast<Expr>(Eval->Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002196 assert(!Init->isValueDependent());
2197
2198 if (Eval->IsEvaluating) {
2199 // FIXME: Produce a diagnostic for self-initialization.
2200 Eval->CheckedICE = true;
2201 Eval->IsICE = false;
Craig Topper36250ad2014-05-12 05:36:57 +00002202 return nullptr;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002203 }
2204
2205 Eval->IsEvaluating = true;
2206
2207 bool Result = Init->EvaluateAsInitializer(Eval->Evaluated, getASTContext(),
2208 this, Notes);
2209
Manuel Klimeka7328992013-06-03 13:51:33 +00002210 // Ensure the computed APValue is cleaned up later if evaluation succeeded,
2211 // or that it's empty (so that there's nothing to clean up) if evaluation
2212 // failed.
Richard Smithd0b4dd62011-12-19 06:19:21 +00002213 if (!Result)
2214 Eval->Evaluated = APValue();
Manuel Klimeka7328992013-06-03 13:51:33 +00002215 else if (Eval->Evaluated.needsCleanup())
George Burgess IVb61bfbd2017-02-14 05:37:36 +00002216 getASTContext().addDestruction(&Eval->Evaluated);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002217
2218 Eval->IsEvaluating = false;
2219 Eval->WasEvaluated = true;
2220
2221 // In C++11, we have determined whether the initializer was a constant
2222 // expression as a side-effect.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002223 if (getASTContext().getLangOpts().CPlusPlus11 && !Eval->CheckedICE) {
Richard Smithd0b4dd62011-12-19 06:19:21 +00002224 Eval->CheckedICE = true;
Eli Friedman8f66cdf2012-02-06 21:50:18 +00002225 Eval->IsICE = Result && Notes.empty();
Richard Smithd0b4dd62011-12-19 06:19:21 +00002226 }
2227
Craig Topper36250ad2014-05-12 05:36:57 +00002228 return Result ? &Eval->Evaluated : nullptr;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002229}
2230
Chandler Carruth813faed2015-12-30 02:51:00 +00002231APValue *VarDecl::getEvaluatedValue() const {
2232 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
2233 if (Eval->WasEvaluated)
2234 return &Eval->Evaluated;
2235
2236 return nullptr;
2237}
2238
2239bool VarDecl::isInitKnownICE() const {
2240 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
2241 return Eval->CheckedICE;
2242
2243 return false;
2244}
2245
2246bool VarDecl::isInitICE() const {
2247 assert(isInitKnownICE() &&
2248 "Check whether we already know that the initializer is an ICE");
2249 return Init.get<EvaluatedStmt *>()->IsICE;
2250}
2251
Richard Smithd0b4dd62011-12-19 06:19:21 +00002252bool VarDecl::checkInitIsICE() const {
John McCalla59dc2f2012-01-05 00:13:19 +00002253 // Initializers of weak variables are never ICEs.
2254 if (isWeak())
2255 return false;
2256
Richard Smithd0b4dd62011-12-19 06:19:21 +00002257 EvaluatedStmt *Eval = ensureEvaluatedStmt();
2258 if (Eval->CheckedICE)
2259 // We have already checked whether this subexpression is an
2260 // integral constant expression.
2261 return Eval->IsICE;
2262
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002263 const auto *Init = cast<Expr>(Eval->Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002264 assert(!Init->isValueDependent());
2265
2266 // In C++11, evaluate the initializer to check whether it's a constant
2267 // expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002268 if (getASTContext().getLangOpts().CPlusPlus11) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002269 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002270 evaluateValue(Notes);
2271 return Eval->IsICE;
2272 }
2273
2274 // It's an ICE whether or not the definition we found is
2275 // out-of-line. See DR 721 and the discussion in Clang PR
2276 // 6206 for details.
2277
2278 if (Eval->CheckingICE)
2279 return false;
2280 Eval->CheckingICE = true;
2281
2282 Eval->IsICE = Init->isIntegerConstantExpr(getASTContext());
2283 Eval->CheckingICE = false;
2284 Eval->CheckedICE = true;
2285 return Eval->IsICE;
2286}
2287
Richard Smith2195ec92017-04-21 01:15:13 +00002288template<typename DeclT>
2289static DeclT *getDefinitionOrSelf(DeclT *D) {
2290 assert(D);
2291 if (auto *Def = D->getDefinition())
2292 return Def;
2293 return D;
2294}
2295
Richard Smithedbc6e92016-10-14 21:41:24 +00002296VarDecl *VarDecl::getTemplateInstantiationPattern() const {
2297 // If it's a variable template specialization, find the template or partial
2298 // specialization from which it was instantiated.
2299 if (auto *VDTemplSpec = dyn_cast<VarTemplateSpecializationDecl>(this)) {
2300 auto From = VDTemplSpec->getInstantiatedFrom();
2301 if (auto *VTD = From.dyn_cast<VarTemplateDecl *>()) {
2302 while (auto *NewVTD = VTD->getInstantiatedFromMemberTemplate()) {
2303 if (NewVTD->isMemberSpecialization())
2304 break;
2305 VTD = NewVTD;
2306 }
Richard Smith2195ec92017-04-21 01:15:13 +00002307 return getDefinitionOrSelf(VTD->getTemplatedDecl());
Richard Smithedbc6e92016-10-14 21:41:24 +00002308 }
2309 if (auto *VTPSD =
2310 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
2311 while (auto *NewVTPSD = VTPSD->getInstantiatedFromMember()) {
2312 if (NewVTPSD->isMemberSpecialization())
2313 break;
2314 VTPSD = NewVTPSD;
2315 }
Richard Smith2195ec92017-04-21 01:15:13 +00002316 return getDefinitionOrSelf<VarDecl>(VTPSD);
Richard Smithedbc6e92016-10-14 21:41:24 +00002317 }
2318 }
2319
2320 if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) {
2321 if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) {
2322 VarDecl *VD = getInstantiatedFromStaticDataMember();
2323 while (auto *NewVD = VD->getInstantiatedFromStaticDataMember())
2324 VD = NewVD;
Richard Smith2195ec92017-04-21 01:15:13 +00002325 return getDefinitionOrSelf(VD);
Richard Smithedbc6e92016-10-14 21:41:24 +00002326 }
2327 }
2328
2329 if (VarTemplateDecl *VarTemplate = getDescribedVarTemplate()) {
Richard Smithedbc6e92016-10-14 21:41:24 +00002330 while (VarTemplate->getInstantiatedFromMemberTemplate()) {
2331 if (VarTemplate->isMemberSpecialization())
2332 break;
2333 VarTemplate = VarTemplate->getInstantiatedFromMemberTemplate();
2334 }
2335
Richard Smith2195ec92017-04-21 01:15:13 +00002336 return getDefinitionOrSelf(VarTemplate->getTemplatedDecl());
Richard Smithedbc6e92016-10-14 21:41:24 +00002337 }
2338 return nullptr;
2339}
2340
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002341VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const {
Douglas Gregor06db9f52009-10-12 20:18:28 +00002342 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
Douglas Gregor86d142a2009-10-08 07:24:58 +00002343 return cast<VarDecl>(MSI->getInstantiatedFrom());
Craig Topper36250ad2014-05-12 05:36:57 +00002344
2345 return nullptr;
Douglas Gregor86d142a2009-10-08 07:24:58 +00002346}
2347
Douglas Gregor3c74d412009-10-14 20:14:33 +00002348TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002349 if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
Larisse Voufo39a1e502013-08-06 01:03:05 +00002350 return Spec->getSpecializationKind();
2351
Sebastian Redl35351a92010-01-31 22:27:38 +00002352 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
Douglas Gregor86d142a2009-10-08 07:24:58 +00002353 return MSI->getTemplateSpecializationKind();
Richard Smith8809a0c2013-09-27 20:14:12 +00002354
Douglas Gregor86d142a2009-10-08 07:24:58 +00002355 return TSK_Undeclared;
2356}
2357
Richard Smith8809a0c2013-09-27 20:14:12 +00002358SourceLocation VarDecl::getPointOfInstantiation() const {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002359 if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
Richard Smith8809a0c2013-09-27 20:14:12 +00002360 return Spec->getPointOfInstantiation();
2361
2362 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2363 return MSI->getPointOfInstantiation();
2364
2365 return SourceLocation();
2366}
2367
Larisse Voufo39a1e502013-08-06 01:03:05 +00002368VarTemplateDecl *VarDecl::getDescribedVarTemplate() const {
2369 return getASTContext().getTemplateOrSpecializationInfo(this)
2370 .dyn_cast<VarTemplateDecl *>();
2371}
2372
2373void VarDecl::setDescribedVarTemplate(VarTemplateDecl *Template) {
2374 getASTContext().setTemplateOrSpecializationInfo(this, Template);
2375}
2376
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002377MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const {
Richard Smithb71782b2013-08-01 04:12:04 +00002378 if (isStaticDataMember())
Larisse Voufo39a1e502013-08-06 01:03:05 +00002379 // FIXME: Remove ?
2380 // return getASTContext().getInstantiatedFromStaticDataMember(this);
2381 return getASTContext().getTemplateOrSpecializationInfo(this)
2382 .dyn_cast<MemberSpecializationInfo *>();
Craig Topper36250ad2014-05-12 05:36:57 +00002383 return nullptr;
Douglas Gregor06db9f52009-10-12 20:18:28 +00002384}
2385
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00002386void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2387 SourceLocation PointOfInstantiation) {
Richard Smith8809a0c2013-09-27 20:14:12 +00002388 assert((isa<VarTemplateSpecializationDecl>(this) ||
2389 getMemberSpecializationInfo()) &&
2390 "not a variable or static data member template specialization");
2391
Larisse Voufo39a1e502013-08-06 01:03:05 +00002392 if (VarTemplateSpecializationDecl *Spec =
2393 dyn_cast<VarTemplateSpecializationDecl>(this)) {
2394 Spec->setSpecializationKind(TSK);
2395 if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
2396 Spec->getPointOfInstantiation().isInvalid())
2397 Spec->setPointOfInstantiation(PointOfInstantiation);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002398 }
2399
2400 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) {
2401 MSI->setTemplateSpecializationKind(TSK);
2402 if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
2403 MSI->getPointOfInstantiation().isInvalid())
2404 MSI->setPointOfInstantiation(PointOfInstantiation);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002405 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002406}
2407
2408void
2409VarDecl::setInstantiationOfStaticDataMember(VarDecl *VD,
2410 TemplateSpecializationKind TSK) {
2411 assert(getASTContext().getTemplateOrSpecializationInfo(this).isNull() &&
2412 "Previous template or instantiation?");
2413 getASTContext().setInstantiatedFromStaticDataMember(this, VD, TSK);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00002414}
2415
Sebastian Redl833ef452010-01-26 22:01:41 +00002416//===----------------------------------------------------------------------===//
2417// ParmVarDecl Implementation
2418//===----------------------------------------------------------------------===//
Douglas Gregor0760fa12009-03-10 23:43:53 +00002419
Sebastian Redl833ef452010-01-26 22:01:41 +00002420ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00002421 SourceLocation StartLoc,
2422 SourceLocation IdLoc, IdentifierInfo *Id,
Sebastian Redl833ef452010-01-26 22:01:41 +00002423 QualType T, TypeSourceInfo *TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002424 StorageClass S, Expr *DefArg) {
Richard Smith053f6c62014-05-16 23:01:30 +00002425 return new (C, DC) ParmVarDecl(ParmVar, C, DC, StartLoc, IdLoc, Id, T, TInfo,
Richard Smithf7981722013-11-22 09:01:48 +00002426 S, DefArg);
Douglas Gregor0760fa12009-03-10 23:43:53 +00002427}
2428
Reid Kleckner8a365022013-06-24 17:51:48 +00002429QualType ParmVarDecl::getOriginalType() const {
2430 TypeSourceInfo *TSI = getTypeSourceInfo();
2431 QualType T = TSI ? TSI->getType() : getType();
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002432 if (const auto *DT = dyn_cast<DecayedType>(T))
Reid Kleckner8a365022013-06-24 17:51:48 +00002433 return DT->getOriginalType();
2434 return T;
2435}
2436
Douglas Gregor72172e92012-01-05 21:55:30 +00002437ParmVarDecl *ParmVarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00002438 return new (C, ID)
2439 ParmVarDecl(ParmVar, C, nullptr, SourceLocation(), SourceLocation(),
2440 nullptr, QualType(), nullptr, SC_None, nullptr);
Douglas Gregor72172e92012-01-05 21:55:30 +00002441}
2442
Argyrios Kyrtzidis4c6efa622011-07-30 17:23:26 +00002443SourceRange ParmVarDecl::getSourceRange() const {
2444 if (!hasInheritedDefaultArg()) {
2445 SourceRange ArgRange = getDefaultArgRange();
2446 if (ArgRange.isValid())
2447 return SourceRange(getOuterLocStart(), ArgRange.getEnd());
2448 }
2449
Argyrios Kyrtzidisa0772792013-04-17 01:56:48 +00002450 // DeclaratorDecl considers the range of postfix types as overlapping with the
2451 // declaration name, but this is not the case with parameters in ObjC methods.
2452 if (isa<ObjCMethodDecl>(getDeclContext()))
2453 return SourceRange(DeclaratorDecl::getLocStart(), getLocation());
2454
Argyrios Kyrtzidis4c6efa622011-07-30 17:23:26 +00002455 return DeclaratorDecl::getSourceRange();
2456}
2457
Sebastian Redl833ef452010-01-26 22:01:41 +00002458Expr *ParmVarDecl::getDefaultArg() {
2459 assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!");
2460 assert(!hasUninstantiatedDefaultArg() &&
2461 "Default argument is not yet instantiated!");
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002462
Sebastian Redl833ef452010-01-26 22:01:41 +00002463 Expr *Arg = getInit();
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002464 if (auto *E = dyn_cast_or_null<ExprWithCleanups>(Arg))
Sebastian Redl833ef452010-01-26 22:01:41 +00002465 return E->getSubExpr();
Douglas Gregor0760fa12009-03-10 23:43:53 +00002466
Sebastian Redl833ef452010-01-26 22:01:41 +00002467 return Arg;
2468}
2469
Chandler Carruth813faed2015-12-30 02:51:00 +00002470void ParmVarDecl::setDefaultArg(Expr *defarg) {
2471 ParmVarDeclBits.DefaultArgKind = DAK_Normal;
2472 Init = defarg;
2473}
Sebastian Redl833ef452010-01-26 22:01:41 +00002474
Chandler Carruth813faed2015-12-30 02:51:00 +00002475SourceRange ParmVarDecl::getDefaultArgRange() const {
2476 switch (ParmVarDeclBits.DefaultArgKind) {
2477 case DAK_None:
2478 case DAK_Unparsed:
2479 // Nothing we can do here.
2480 return SourceRange();
2481
2482 case DAK_Uninstantiated:
Sebastian Redl833ef452010-01-26 22:01:41 +00002483 return getUninstantiatedDefaultArg()->getSourceRange();
2484
Chandler Carruth813faed2015-12-30 02:51:00 +00002485 case DAK_Normal:
2486 if (const Expr *E = getInit())
2487 return E->getSourceRange();
2488
2489 // Missing an actual expression, may be invalid.
2490 return SourceRange();
2491 }
2492 llvm_unreachable("Invalid default argument kind.");
2493}
2494
2495void ParmVarDecl::setUninstantiatedDefaultArg(Expr *arg) {
2496 ParmVarDeclBits.DefaultArgKind = DAK_Uninstantiated;
2497 Init = arg;
2498}
2499
2500Expr *ParmVarDecl::getUninstantiatedDefaultArg() {
2501 assert(hasUninstantiatedDefaultArg() &&
2502 "Wrong kind of initialization expression!");
2503 return cast_or_null<Expr>(Init.get<Stmt *>());
2504}
2505
2506bool ParmVarDecl::hasDefaultArg() const {
2507 // FIXME: We should just return false for DAK_None here once callers are
2508 // prepared for the case that we encountered an invalid default argument and
2509 // were unable to even build an invalid expression.
2510 return hasUnparsedDefaultArg() || hasUninstantiatedDefaultArg() ||
2511 !Init.isNull();
Argyrios Kyrtzidis02dd4f92009-07-05 22:21:56 +00002512}
2513
Douglas Gregor3c6bd2a2011-01-05 21:11:38 +00002514bool ParmVarDecl::isParameterPack() const {
2515 return isa<PackExpansionType>(getType());
2516}
2517
Ted Kremenek540017e2011-10-06 05:00:56 +00002518void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) {
2519 getASTContext().setParameterIndex(this, parameterIndex);
2520 ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel;
2521}
2522
2523unsigned ParmVarDecl::getParameterIndexLarge() const {
2524 return getASTContext().getParameterIndex(this);
2525}
2526
Nuno Lopes394ec982008-12-17 23:39:55 +00002527//===----------------------------------------------------------------------===//
Chris Lattner59a25942008-03-31 00:36:02 +00002528// FunctionDecl Implementation
2529//===----------------------------------------------------------------------===//
2530
Benjamin Kramer9170e912013-02-22 15:46:01 +00002531void FunctionDecl::getNameForDiagnostic(
2532 raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const {
2533 NamedDecl::getNameForDiagnostic(OS, Policy, Qualified);
Douglas Gregorb11aad82011-02-19 18:51:44 +00002534 const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs();
2535 if (TemplateArgs)
Benjamin Kramer9170e912013-02-22 15:46:01 +00002536 TemplateSpecializationType::PrintTemplateArgumentList(
David Majnemer6fbeee32016-07-07 04:43:07 +00002537 OS, TemplateArgs->asArray(), Policy);
Douglas Gregorb11aad82011-02-19 18:51:44 +00002538}
2539
Ted Kremenek186a0742010-04-29 16:49:01 +00002540bool FunctionDecl::isVariadic() const {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002541 if (const auto *FT = getType()->getAs<FunctionProtoType>())
Ted Kremenek186a0742010-04-29 16:49:01 +00002542 return FT->isVariadic();
2543 return false;
2544}
2545
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002546bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const {
Aaron Ballman86c93902014-03-06 23:45:36 +00002547 for (auto I : redecls()) {
Serge Pavlov9a618e12017-02-15 12:30:35 +00002548 if (I->doesThisDeclarationHaveABody()) {
Aaron Ballman86c93902014-03-06 23:45:36 +00002549 Definition = I;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002550 return true;
2551 }
2552 }
2553
2554 return false;
2555}
2556
Anders Carlsson9bd7d162011-05-14 23:26:09 +00002557bool FunctionDecl::hasTrivialBody() const
2558{
2559 Stmt *S = getBody();
2560 if (!S) {
2561 // Since we don't have a body for this function, we don't know if it's
2562 // trivial or not.
2563 return false;
2564 }
2565
2566 if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty())
2567 return true;
2568 return false;
2569}
2570
Alexis Hunt4a8ea102011-05-06 20:44:56 +00002571bool FunctionDecl::isDefined(const FunctionDecl *&Definition) const {
Aaron Ballman86c93902014-03-06 23:45:36 +00002572 for (auto I : redecls()) {
Serge Pavlov10673c92017-06-04 12:53:12 +00002573 if (I->isThisDeclarationADefinition()) {
2574 Definition = I;
Alexis Hunt4a8ea102011-05-06 20:44:56 +00002575 return true;
2576 }
2577 }
2578
2579 return false;
2580}
2581
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00002582Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const {
Rafael Espindola44503012013-10-19 01:37:17 +00002583 if (!hasBody(Definition))
Craig Topper36250ad2014-05-12 05:36:57 +00002584 return nullptr;
Rafael Espindola44503012013-10-19 01:37:17 +00002585
2586 if (Definition->Body)
2587 return Definition->Body.get(getASTContext().getExternalSource());
Douglas Gregor89f238c2008-04-21 02:02:58 +00002588
Craig Topper36250ad2014-05-12 05:36:57 +00002589 return nullptr;
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00002590}
2591
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00002592void FunctionDecl::setBody(Stmt *B) {
2593 Body = B;
Douglas Gregor027ba502010-12-06 17:49:01 +00002594 if (B)
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00002595 EndRangeLoc = B->getLocEnd();
2596}
2597
Douglas Gregor7d9120c2010-09-28 21:55:22 +00002598void FunctionDecl::setPure(bool P) {
2599 IsPure = P;
2600 if (P)
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002601 if (auto *Parent = dyn_cast<CXXRecordDecl>(getDeclContext()))
Douglas Gregor7d9120c2010-09-28 21:55:22 +00002602 Parent->markedVirtualFunctionPure();
2603}
2604
Richard Smith8d0dc312013-07-21 23:12:18 +00002605template<std::size_t Len>
2606static bool isNamed(const NamedDecl *ND, const char (&Str)[Len]) {
2607 IdentifierInfo *II = ND->getIdentifier();
2608 return II && II->isStr(Str);
2609}
2610
Douglas Gregor16618f22009-09-12 00:17:51 +00002611bool FunctionDecl::isMain() const {
John McCall53ffd372011-05-15 17:49:20 +00002612 const TranslationUnitDecl *tunit =
2613 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
2614 return tunit &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002615 !tunit->getASTContext().getLangOpts().Freestanding &&
Richard Smith8d0dc312013-07-21 23:12:18 +00002616 isNamed(this, "main");
John McCall53ffd372011-05-15 17:49:20 +00002617}
2618
David Majnemerc729b0b2013-09-16 22:44:20 +00002619bool FunctionDecl::isMSVCRTEntryPoint() const {
2620 const TranslationUnitDecl *TUnit =
2621 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
2622 if (!TUnit)
2623 return false;
2624
2625 // Even though we aren't really targeting MSVCRT if we are freestanding,
2626 // semantic analysis for these functions remains the same.
2627
2628 // MSVCRT entry points only exist on MSVCRT targets.
2629 if (!TUnit->getASTContext().getTargetInfo().getTriple().isOSMSVCRT())
2630 return false;
2631
2632 // Nameless functions like constructors cannot be entry points.
2633 if (!getIdentifier())
2634 return false;
2635
2636 return llvm::StringSwitch<bool>(getName())
2637 .Cases("main", // an ANSI console app
2638 "wmain", // a Unicode console App
2639 "WinMain", // an ANSI GUI app
2640 "wWinMain", // a Unicode GUI app
2641 "DllMain", // a DLL
2642 true)
2643 .Default(false);
2644}
2645
John McCall53ffd372011-05-15 17:49:20 +00002646bool FunctionDecl::isReservedGlobalPlacementOperator() const {
2647 assert(getDeclName().getNameKind() == DeclarationName::CXXOperatorName);
2648 assert(getDeclName().getCXXOverloadedOperator() == OO_New ||
2649 getDeclName().getCXXOverloadedOperator() == OO_Delete ||
2650 getDeclName().getCXXOverloadedOperator() == OO_Array_New ||
2651 getDeclName().getCXXOverloadedOperator() == OO_Array_Delete);
2652
Richard Smithf6004412014-01-19 23:25:37 +00002653 if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
2654 return false;
John McCall53ffd372011-05-15 17:49:20 +00002655
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002656 const auto *proto = getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00002657 if (proto->getNumParams() != 2 || proto->isVariadic())
2658 return false;
John McCall53ffd372011-05-15 17:49:20 +00002659
2660 ASTContext &Context =
2661 cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext())
2662 ->getASTContext();
2663
2664 // The result type and first argument type are constant across all
2665 // these operators. The second argument must be exactly void*.
Alp Toker9cacbab2014-01-20 20:26:09 +00002666 return (proto->getParamType(1).getCanonicalType() == Context.VoidPtrTy);
Douglas Gregore62c0a42009-02-24 01:23:02 +00002667}
2668
Akira Hatanakacae83f72017-06-29 18:48:40 +00002669bool FunctionDecl::isReplaceableGlobalAllocationFunction(bool *IsAligned) const {
Richard Smith8d0dc312013-07-21 23:12:18 +00002670 if (getDeclName().getNameKind() != DeclarationName::CXXOperatorName)
2671 return false;
2672 if (getDeclName().getCXXOverloadedOperator() != OO_New &&
2673 getDeclName().getCXXOverloadedOperator() != OO_Delete &&
2674 getDeclName().getCXXOverloadedOperator() != OO_Array_New &&
2675 getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
2676 return false;
2677
2678 if (isa<CXXRecordDecl>(getDeclContext()))
2679 return false;
Richard Smithf6004412014-01-19 23:25:37 +00002680
2681 // This can only fail for an invalid 'operator new' declaration.
2682 if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
2683 return false;
Richard Smith8d0dc312013-07-21 23:12:18 +00002684
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002685 const auto *FPT = getType()->castAs<FunctionProtoType>();
Richard Smithb2f0f052016-10-10 18:54:32 +00002686 if (FPT->getNumParams() == 0 || FPT->getNumParams() > 3 || FPT->isVariadic())
Richard Smith8d0dc312013-07-21 23:12:18 +00002687 return false;
2688
2689 // If this is a single-parameter function, it must be a replaceable global
2690 // allocation or deallocation function.
Alp Toker9cacbab2014-01-20 20:26:09 +00002691 if (FPT->getNumParams() == 1)
Richard Smith8d0dc312013-07-21 23:12:18 +00002692 return true;
2693
Richard Smithb2f0f052016-10-10 18:54:32 +00002694 unsigned Params = 1;
2695 QualType Ty = FPT->getParamType(Params);
Richard Smith1cdec012013-09-29 04:40:38 +00002696 ASTContext &Ctx = getASTContext();
Richard Smithb2f0f052016-10-10 18:54:32 +00002697
2698 auto Consume = [&] {
2699 ++Params;
2700 Ty = Params < FPT->getNumParams() ? FPT->getParamType(Params) : QualType();
2701 };
2702
2703 // In C++14, the next parameter can be a 'std::size_t' for sized delete.
2704 bool IsSizedDelete = false;
Richard Smithb47c36f2013-11-05 09:12:18 +00002705 if (Ctx.getLangOpts().SizedDeallocation &&
Richard Smithb2f0f052016-10-10 18:54:32 +00002706 (getDeclName().getCXXOverloadedOperator() == OO_Delete ||
2707 getDeclName().getCXXOverloadedOperator() == OO_Array_Delete) &&
2708 Ctx.hasSameType(Ty, Ctx.getSizeType())) {
2709 IsSizedDelete = true;
2710 Consume();
2711 }
2712
2713 // In C++17, the next parameter can be a 'std::align_val_t' for aligned
2714 // new/delete.
Akira Hatanakacae83f72017-06-29 18:48:40 +00002715 if (Ctx.getLangOpts().AlignedAllocation && !Ty.isNull() && Ty->isAlignValT()) {
2716 if (IsAligned)
2717 *IsAligned = true;
Richard Smithb2f0f052016-10-10 18:54:32 +00002718 Consume();
Akira Hatanakacae83f72017-06-29 18:48:40 +00002719 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002720
2721 // Finally, if this is not a sized delete, the final parameter can
2722 // be a 'const std::nothrow_t&'.
2723 if (!IsSizedDelete && !Ty.isNull() && Ty->isReferenceType()) {
2724 Ty = Ty->getPointeeType();
2725 if (Ty.getCVRQualifiers() != Qualifiers::Const)
2726 return false;
2727 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
2728 if (RD && isNamed(RD, "nothrow_t") && RD->isInStdNamespace())
2729 Consume();
2730 }
2731
2732 return Params == FPT->getNumParams();
Richard Smith8d0dc312013-07-21 23:12:18 +00002733}
2734
Richard Smith5b349582017-10-13 01:55:36 +00002735bool FunctionDecl::isDestroyingOperatorDelete() const {
2736 // C++ P0722:
2737 // Within a class C, a single object deallocation function with signature
2738 // (T, std::destroying_delete_t, <more params>)
2739 // is a destroying operator delete.
2740 if (!isa<CXXMethodDecl>(this) || getOverloadedOperator() != OO_Delete ||
2741 getNumParams() < 2)
2742 return false;
2743
2744 auto *RD = getParamDecl(1)->getType()->getAsCXXRecordDecl();
2745 return RD && RD->isInStdNamespace() && RD->getIdentifier() &&
2746 RD->getIdentifier()->isStr("destroying_delete_t");
2747}
2748
Rafael Espindolaf4187652013-02-14 01:18:37 +00002749LanguageLinkage FunctionDecl::getLanguageLinkage() const {
Alp Toker84212df2014-05-31 06:11:02 +00002750 return getDeclLanguageLinkage(*this);
Rafael Espindola576127d2012-12-28 14:21:58 +00002751}
2752
Rafael Espindola0e0d0092013-03-14 03:07:35 +00002753bool FunctionDecl::isExternC() const {
Alp Toker84212df2014-05-31 06:11:02 +00002754 return isDeclExternC(*this);
Rafael Espindola0e0d0092013-03-14 03:07:35 +00002755}
2756
Rafael Espindola593537a2013-05-05 20:15:21 +00002757bool FunctionDecl::isInExternCContext() const {
Serge Pavlov3cb80222013-11-14 02:13:03 +00002758 return getLexicalDeclContext()->isExternCContext();
Rafael Espindola593537a2013-05-05 20:15:21 +00002759}
2760
2761bool FunctionDecl::isInExternCXXContext() const {
Serge Pavlov3cb80222013-11-14 02:13:03 +00002762 return getLexicalDeclContext()->isExternCXXContext();
Rafael Espindola593537a2013-05-05 20:15:21 +00002763}
2764
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002765bool FunctionDecl::isGlobal() const {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002766 if (const auto *Method = dyn_cast<CXXMethodDecl>(this))
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002767 return Method->isStatic();
2768
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002769 if (getCanonicalDecl()->getStorageClass() == SC_Static)
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002770 return false;
2771
Mike Stump11289f42009-09-09 15:08:12 +00002772 for (const DeclContext *DC = getDeclContext();
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002773 DC->isNamespace();
2774 DC = DC->getParent()) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002775 if (const auto *Namespace = cast<NamespaceDecl>(DC)) {
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002776 if (!Namespace->getDeclName())
2777 return false;
2778 break;
2779 }
2780 }
2781
2782 return true;
2783}
2784
Richard Smith10876ef2013-01-17 01:30:42 +00002785bool FunctionDecl::isNoReturn() const {
Adrian Prantl721c7cb2016-08-17 16:42:15 +00002786 if (hasAttr<NoReturnAttr>() || hasAttr<CXX11NoReturnAttr>() ||
2787 hasAttr<C11NoReturnAttr>())
2788 return true;
2789
2790 if (auto *FnTy = getType()->getAs<FunctionType>())
2791 return FnTy->getNoReturnAttr();
2792
2793 return false;
Richard Smith10876ef2013-01-17 01:30:42 +00002794}
2795
Sebastian Redl833ef452010-01-26 22:01:41 +00002796void
2797FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00002798 redeclarable_base::setPreviousDecl(PrevDecl);
Sebastian Redl833ef452010-01-26 22:01:41 +00002799
2800 if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) {
2801 FunctionTemplateDecl *PrevFunTmpl
Craig Topper36250ad2014-05-12 05:36:57 +00002802 = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : nullptr;
Sebastian Redl833ef452010-01-26 22:01:41 +00002803 assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch");
Rafael Espindola8db352d2013-10-17 15:37:26 +00002804 FunTmpl->setPreviousDecl(PrevFunTmpl);
Sebastian Redl833ef452010-01-26 22:01:41 +00002805 }
Douglas Gregorff76cb92010-12-09 16:59:22 +00002806
Axel Naumannfbc7b982011-11-08 18:21:06 +00002807 if (PrevDecl && PrevDecl->IsInline)
Douglas Gregorff76cb92010-12-09 16:59:22 +00002808 IsInline = true;
Sebastian Redl833ef452010-01-26 22:01:41 +00002809}
2810
Rafael Espindola8db352d2013-10-17 15:37:26 +00002811FunctionDecl *FunctionDecl::getCanonicalDecl() { return getFirstDecl(); }
Sebastian Redl833ef452010-01-26 22:01:41 +00002812
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002813/// \brief Returns a value indicating whether this function
2814/// corresponds to a builtin function.
2815///
2816/// The function corresponds to a built-in function if it is
2817/// declared at translation scope or within an extern "C" block and
2818/// its name matches with the name of a builtin. The returned value
2819/// will be 0 for functions that do not correspond to a builtin, a
Mike Stump11289f42009-09-09 15:08:12 +00002820/// value of type \c Builtin::ID if in the target-independent range
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002821/// \c [1,Builtin::First), or a target-specific builtin value.
Douglas Gregor15fc9562009-09-12 00:22:50 +00002822unsigned FunctionDecl::getBuiltinID() const {
Daniel Dunbar304314d2012-03-06 23:52:37 +00002823 if (!getIdentifier())
Douglas Gregore711f702009-02-14 18:57:46 +00002824 return 0;
2825
2826 unsigned BuiltinID = getIdentifier()->getBuiltinID();
Daniel Dunbar304314d2012-03-06 23:52:37 +00002827 if (!BuiltinID)
2828 return 0;
2829
2830 ASTContext &Context = getASTContext();
Warren Hunt445d83e2013-11-01 23:46:51 +00002831 if (Context.getLangOpts().CPlusPlus) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002832 const auto *LinkageDecl =
2833 dyn_cast<LinkageSpecDecl>(getFirstDecl()->getDeclContext());
Warren Hunt445d83e2013-11-01 23:46:51 +00002834 // In C++, the first declaration of a builtin is always inside an implicit
2835 // extern "C".
2836 // FIXME: A recognised library function may not be directly in an extern "C"
2837 // declaration, for instance "extern "C" { namespace std { decl } }".
David Majnemerba3e5ec2015-03-13 18:26:17 +00002838 if (!LinkageDecl) {
2839 if (BuiltinID == Builtin::BI__GetExceptionInfo &&
David Majnemer145abde2016-01-26 01:12:17 +00002840 Context.getTargetInfo().getCXXABI().isMicrosoft())
David Majnemerba3e5ec2015-03-13 18:26:17 +00002841 return Builtin::BI__GetExceptionInfo;
2842 return 0;
2843 }
2844 if (LinkageDecl->getLanguage() != LinkageSpecDecl::lang_c)
Warren Hunt445d83e2013-11-01 23:46:51 +00002845 return 0;
2846 }
2847
2848 // If the function is marked "overloadable", it has a different mangled name
2849 // and is not the C library function.
Aaron Ballman9ead1242013-12-19 02:39:40 +00002850 if (hasAttr<OverloadableAttr>())
Warren Hunt445d83e2013-11-01 23:46:51 +00002851 return 0;
2852
Douglas Gregore711f702009-02-14 18:57:46 +00002853 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
2854 return BuiltinID;
2855
2856 // This function has the name of a known C library
2857 // function. Determine whether it actually refers to the C library
2858 // function or whether it just has the same name.
2859
Douglas Gregora908e7f2009-02-17 03:23:10 +00002860 // If this is a static function, it's not a builtin.
John McCall8e7d6562010-08-26 03:08:43 +00002861 if (getStorageClass() == SC_Static)
Douglas Gregora908e7f2009-02-17 03:23:10 +00002862 return 0;
2863
Anastasia Stulova1202de32016-02-12 12:07:04 +00002864 // OpenCL v1.2 s6.9.f - The library functions defined in
2865 // the C99 standard headers are not available.
2866 if (Context.getLangOpts().OpenCL &&
2867 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
2868 return 0;
2869
Warren Hunt445d83e2013-11-01 23:46:51 +00002870 return BuiltinID;
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002871}
2872
2873
Chris Lattner47c0d002009-04-25 06:03:53 +00002874/// getNumParams - Return the number of parameters this function must have
Bob Wilsonb39017a2011-01-10 18:23:55 +00002875/// based on its FunctionType. This is the length of the ParamInfo array
Chris Lattner47c0d002009-04-25 06:03:53 +00002876/// after it has been created.
2877unsigned FunctionDecl::getNumParams() const {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002878 const auto *FPT = getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00002879 return FPT ? FPT->getNumParams() : 0;
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00002880}
2881
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00002882void FunctionDecl::setParams(ASTContext &C,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002883 ArrayRef<ParmVarDecl *> NewParamInfo) {
Craig Topper36250ad2014-05-12 05:36:57 +00002884 assert(!ParamInfo && "Already has param info!");
David Blaikie9c70e042011-09-21 18:16:56 +00002885 assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!");
Mike Stump11289f42009-09-09 15:08:12 +00002886
Chris Lattner8f5bf2f2007-01-21 19:04:10 +00002887 // Zero params -> null pointer.
David Blaikie9c70e042011-09-21 18:16:56 +00002888 if (!NewParamInfo.empty()) {
2889 ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()];
2890 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
Chris Lattner8f5bf2f2007-01-21 19:04:10 +00002891 }
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00002892}
Chris Lattner41943152007-01-25 04:52:46 +00002893
Chris Lattner58258242008-04-10 02:22:51 +00002894/// getMinRequiredArguments - Returns the minimum number of arguments
2895/// needed to call this function. This may be fewer than the number of
2896/// function parameters, if some of the parameters have default
Richard Smith91151782014-04-01 19:18:16 +00002897/// arguments (in C++) or are parameter packs (C++11).
Chris Lattner58258242008-04-10 02:22:51 +00002898unsigned FunctionDecl::getMinRequiredArguments() const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002899 if (!getASTContext().getLangOpts().CPlusPlus)
Douglas Gregor0dd423e2011-01-11 01:52:23 +00002900 return getNumParams();
Chris Lattner58258242008-04-10 02:22:51 +00002901
Richard Smith91151782014-04-01 19:18:16 +00002902 unsigned NumRequiredArgs = 0;
David Majnemer59f77922016-06-24 04:05:48 +00002903 for (auto *Param : parameters())
Richard Smith91151782014-04-01 19:18:16 +00002904 if (!Param->isParameterPack() && !Param->hasDefaultArg())
2905 ++NumRequiredArgs;
Chris Lattner58258242008-04-10 02:22:51 +00002906 return NumRequiredArgs;
2907}
2908
David Majnemer54e3ba52014-04-02 23:17:29 +00002909/// \brief The combination of the extern and inline keywords under MSVC forces
2910/// the function to be required.
2911///
2912/// Note: This function assumes that we will only get called when isInlined()
2913/// would return true for this FunctionDecl.
2914bool FunctionDecl::isMSExternInline() const {
2915 assert(isInlined() && "expected to get called on an inlined function!");
2916
2917 const ASTContext &Context = getASTContext();
David Majnemer3f021502015-10-08 04:53:31 +00002918 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
2919 !hasAttr<DLLExportAttr>())
David Majnemer54e3ba52014-04-02 23:17:29 +00002920 return false;
2921
David Majnemer73768702015-03-20 00:02:27 +00002922 for (const FunctionDecl *FD = getMostRecentDecl(); FD;
2923 FD = FD->getPreviousDecl())
David Majnemerc0c42f32015-07-10 20:55:38 +00002924 if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern)
David Majnemer54e3ba52014-04-02 23:17:29 +00002925 return true;
2926
2927 return false;
2928}
2929
2930static bool redeclForcesDefMSVC(const FunctionDecl *Redecl) {
2931 if (Redecl->getStorageClass() != SC_Extern)
2932 return false;
2933
2934 for (const FunctionDecl *FD = Redecl->getPreviousDecl(); FD;
2935 FD = FD->getPreviousDecl())
David Majnemerc0c42f32015-07-10 20:55:38 +00002936 if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern)
David Majnemer54e3ba52014-04-02 23:17:29 +00002937 return false;
2938
2939 return true;
2940}
2941
Eli Friedman1b125c32012-02-07 03:50:18 +00002942static bool RedeclForcesDefC99(const FunctionDecl *Redecl) {
2943 // Only consider file-scope declarations in this test.
2944 if (!Redecl->getLexicalDeclContext()->isTranslationUnit())
2945 return false;
2946
2947 // Only consider explicit declarations; the presence of a builtin for a
2948 // libcall shouldn't affect whether a definition is externally visible.
2949 if (Redecl->isImplicit())
2950 return false;
2951
2952 if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern)
2953 return true; // Not an inline definition
2954
2955 return false;
2956}
2957
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002958/// \brief For a function declaration in C or C++, determine whether this
2959/// declaration causes the definition to be externally visible.
2960///
David Majnemer54e3ba52014-04-02 23:17:29 +00002961/// For instance, this determines if adding the current declaration to the set
Eli Friedman1b125c32012-02-07 03:50:18 +00002962/// of redeclarations of the given functions causes
2963/// isInlineDefinitionExternallyVisible to change from false to true.
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002964bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const {
Justin Lebar0241c962016-10-28 16:46:39 +00002965 assert(!doesThisDeclarationHaveABody() &&
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002966 "Must have a declaration without a body.");
2967
2968 ASTContext &Context = getASTContext();
2969
David Majnemer54e3ba52014-04-02 23:17:29 +00002970 if (Context.getLangOpts().MSVCCompat) {
2971 const FunctionDecl *Definition;
2972 if (hasBody(Definition) && Definition->isInlined() &&
2973 redeclForcesDefMSVC(this))
2974 return true;
2975 }
2976
David Blaikiebbafb8a2012-03-11 07:00:24 +00002977 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
Eli Friedman1b125c32012-02-07 03:50:18 +00002978 // With GNU inlining, a declaration with 'inline' but not 'extern', forces
2979 // an externally visible definition.
2980 //
2981 // FIXME: What happens if gnu_inline gets added on after the first
2982 // declaration?
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002983 if (!isInlineSpecified() || getStorageClass() == SC_Extern)
Eli Friedman1b125c32012-02-07 03:50:18 +00002984 return false;
2985
2986 const FunctionDecl *Prev = this;
2987 bool FoundBody = false;
2988 while ((Prev = Prev->getPreviousDecl())) {
David Blaikie7d170102013-05-15 07:37:26 +00002989 FoundBody |= Prev->Body.isValid();
Eli Friedman1b125c32012-02-07 03:50:18 +00002990
2991 if (Prev->Body) {
2992 // If it's not the case that both 'inline' and 'extern' are
2993 // specified on the definition, then it is always externally visible.
2994 if (!Prev->isInlineSpecified() ||
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002995 Prev->getStorageClass() != SC_Extern)
Eli Friedman1b125c32012-02-07 03:50:18 +00002996 return false;
2997 } else if (Prev->isInlineSpecified() &&
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002998 Prev->getStorageClass() != SC_Extern) {
Eli Friedman1b125c32012-02-07 03:50:18 +00002999 return false;
3000 }
3001 }
3002 return FoundBody;
3003 }
3004
David Blaikiebbafb8a2012-03-11 07:00:24 +00003005 if (Context.getLangOpts().CPlusPlus)
Nick Lewycky26da4dd2011-07-18 05:26:13 +00003006 return false;
Eli Friedman1b125c32012-02-07 03:50:18 +00003007
3008 // C99 6.7.4p6:
3009 // [...] If all of the file scope declarations for a function in a
3010 // translation unit include the inline function specifier without extern,
3011 // then the definition in that translation unit is an inline definition.
3012 if (isInlineSpecified() && getStorageClass() != SC_Extern)
Nick Lewycky26da4dd2011-07-18 05:26:13 +00003013 return false;
Eli Friedman1b125c32012-02-07 03:50:18 +00003014 const FunctionDecl *Prev = this;
3015 bool FoundBody = false;
3016 while ((Prev = Prev->getPreviousDecl())) {
David Blaikie7d170102013-05-15 07:37:26 +00003017 FoundBody |= Prev->Body.isValid();
Eli Friedman1b125c32012-02-07 03:50:18 +00003018 if (RedeclForcesDefC99(Prev))
3019 return false;
3020 }
3021 return FoundBody;
Nick Lewycky26da4dd2011-07-18 05:26:13 +00003022}
3023
Alp Tokerd0787eb2014-07-02 01:47:15 +00003024SourceRange FunctionDecl::getReturnTypeSourceRange() const {
3025 const TypeSourceInfo *TSI = getTypeSourceInfo();
3026 if (!TSI)
3027 return SourceRange();
Alp Tokerf5b10792014-07-02 12:55:58 +00003028 FunctionTypeLoc FTL =
3029 TSI->getTypeLoc().IgnoreParens().getAs<FunctionTypeLoc>();
3030 if (!FTL)
Alp Tokerd0787eb2014-07-02 01:47:15 +00003031 return SourceRange();
3032
Alp Tokerf5b10792014-07-02 12:55:58 +00003033 // Skip self-referential return types.
3034 const SourceManager &SM = getASTContext().getSourceManager();
3035 SourceRange RTRange = FTL.getReturnLoc().getSourceRange();
3036 SourceLocation Boundary = getNameInfo().getLocStart();
3037 if (RTRange.isInvalid() || Boundary.isInvalid() ||
3038 !SM.isBeforeInTranslationUnit(RTRange.getEnd(), Boundary))
3039 return SourceRange();
Alp Tokerd0787eb2014-07-02 01:47:15 +00003040
Alp Tokerf5b10792014-07-02 12:55:58 +00003041 return RTRange;
Alp Tokerd0787eb2014-07-02 01:47:15 +00003042}
3043
Malcolm Parsonsa3220ce2017-01-12 16:11:28 +00003044SourceRange FunctionDecl::getExceptionSpecSourceRange() const {
3045 const TypeSourceInfo *TSI = getTypeSourceInfo();
3046 if (!TSI)
3047 return SourceRange();
3048 FunctionTypeLoc FTL =
3049 TSI->getTypeLoc().IgnoreParens().getAs<FunctionTypeLoc>();
3050 if (!FTL)
3051 return SourceRange();
3052
3053 return FTL.getExceptionSpecRange();
3054}
3055
Aaron Ballmane7964782016-03-07 22:44:55 +00003056const Attr *FunctionDecl::getUnusedResultAttr() const {
Kaelyn Takata0a2e84c2015-04-09 19:43:04 +00003057 QualType RetType = getReturnType();
3058 if (RetType->isRecordType()) {
Erich Keane4b87d812017-04-19 21:24:55 +00003059 if (const CXXRecordDecl *Ret = RetType->getAsCXXRecordDecl()) {
Aaron Ballmane7964782016-03-07 22:44:55 +00003060 if (const auto *R = Ret->getAttr<WarnUnusedResultAttr>())
3061 return R;
3062 }
3063 } else if (const auto *ET = RetType->getAs<EnumType>()) {
3064 if (const EnumDecl *ED = ET->getDecl()) {
3065 if (const auto *R = ED->getAttr<WarnUnusedResultAttr>())
3066 return R;
3067 }
Kaelyn Takata0a2e84c2015-04-09 19:43:04 +00003068 }
Aaron Ballmane7964782016-03-07 22:44:55 +00003069 return getAttr<WarnUnusedResultAttr>();
Kaelyn Takata0a2e84c2015-04-09 19:43:04 +00003070}
3071
Richard Smithf3814ad2013-01-25 00:08:28 +00003072/// \brief For an inline function definition in C, or for a gnu_inline function
3073/// in C++, determine whether the definition will be externally visible.
Douglas Gregor299d76e2009-09-13 07:46:26 +00003074///
3075/// Inline function definitions are always available for inlining optimizations.
3076/// However, depending on the language dialect, declaration specifiers, and
3077/// attributes, the definition of an inline function may or may not be
3078/// "externally" visible to other translation units in the program.
3079///
3080/// In C99, inline definitions are not externally visible by default. However,
Mike Stump13c66702010-01-06 02:05:39 +00003081/// if even one of the global-scope declarations is marked "extern inline", the
Douglas Gregor299d76e2009-09-13 07:46:26 +00003082/// inline definition becomes externally visible (C99 6.7.4p6).
3083///
3084/// In GNU89 mode, or if the gnu_inline attribute is attached to the function
3085/// definition, we use the GNU semantics for inline, which are nearly the
3086/// opposite of C99 semantics. In particular, "inline" by itself will create
3087/// an externally visible symbol, but "extern inline" will not create an
3088/// externally visible symbol.
3089bool FunctionDecl::isInlineDefinitionExternallyVisible() const {
Manuel Klimekda7456a2016-11-01 10:30:50 +00003090 assert((doesThisDeclarationHaveABody() || willHaveBody()) &&
3091 "Must be a function definition");
Douglas Gregor583dcaf2009-10-27 21:11:48 +00003092 assert(isInlined() && "Function must be inline");
Douglas Gregorb7e5c842009-10-27 23:26:40 +00003093 ASTContext &Context = getASTContext();
Douglas Gregor299d76e2009-09-13 07:46:26 +00003094
David Blaikiebbafb8a2012-03-11 07:00:24 +00003095 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
Eli Friedman1b125c32012-02-07 03:50:18 +00003096 // Note: If you change the logic here, please change
3097 // doesDeclarationForceExternallyVisibleDefinition as well.
3098 //
Douglas Gregorff76cb92010-12-09 16:59:22 +00003099 // If it's not the case that both 'inline' and 'extern' are
3100 // specified on the definition, then this inline definition is
3101 // externally visible.
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003102 if (!(isInlineSpecified() && getStorageClass() == SC_Extern))
Douglas Gregorff76cb92010-12-09 16:59:22 +00003103 return true;
3104
3105 // If any declaration is 'inline' but not 'extern', then this definition
3106 // is externally visible.
Aaron Ballman86c93902014-03-06 23:45:36 +00003107 for (auto Redecl : redecls()) {
Douglas Gregorff76cb92010-12-09 16:59:22 +00003108 if (Redecl->isInlineSpecified() &&
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003109 Redecl->getStorageClass() != SC_Extern)
Douglas Gregor299d76e2009-09-13 07:46:26 +00003110 return true;
Douglas Gregorff76cb92010-12-09 16:59:22 +00003111 }
Douglas Gregor299d76e2009-09-13 07:46:26 +00003112
Douglas Gregor76fe50c2009-04-28 06:37:30 +00003113 return false;
Douglas Gregor299d76e2009-09-13 07:46:26 +00003114 }
Eli Friedman1b125c32012-02-07 03:50:18 +00003115
Richard Smithf3814ad2013-01-25 00:08:28 +00003116 // The rest of this function is C-only.
3117 assert(!Context.getLangOpts().CPlusPlus &&
3118 "should not use C inline rules in C++");
3119
Douglas Gregor299d76e2009-09-13 07:46:26 +00003120 // C99 6.7.4p6:
3121 // [...] If all of the file scope declarations for a function in a
3122 // translation unit include the inline function specifier without extern,
3123 // then the definition in that translation unit is an inline definition.
Aaron Ballman86c93902014-03-06 23:45:36 +00003124 for (auto Redecl : redecls()) {
3125 if (RedeclForcesDefC99(Redecl))
Eli Friedman1b125c32012-02-07 03:50:18 +00003126 return true;
Douglas Gregor299d76e2009-09-13 07:46:26 +00003127 }
3128
3129 // C99 6.7.4p6:
3130 // An inline definition does not provide an external definition for the
3131 // function, and does not forbid an external definition in another
3132 // translation unit.
Douglas Gregor76fe50c2009-04-28 06:37:30 +00003133 return false;
3134}
3135
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00003136/// getOverloadedOperator - Which C++ overloaded operator this
3137/// function represents, if any.
3138OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const {
Douglas Gregor163c5852008-11-18 14:39:36 +00003139 if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
3140 return getDeclName().getCXXOverloadedOperator();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00003141 else
3142 return OO_None;
3143}
3144
Alexis Huntc88db062010-01-13 09:01:02 +00003145/// getLiteralIdentifier - The literal suffix identifier this function
3146/// represents, if any.
3147const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const {
3148 if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName)
3149 return getDeclName().getCXXLiteralIdentifier();
3150 else
Craig Topper36250ad2014-05-12 05:36:57 +00003151 return nullptr;
Alexis Huntc88db062010-01-13 09:01:02 +00003152}
3153
Argyrios Kyrtzidiscb6f3462010-06-22 09:54:51 +00003154FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const {
3155 if (TemplateOrSpecialization.isNull())
3156 return TK_NonTemplate;
3157 if (TemplateOrSpecialization.is<FunctionTemplateDecl *>())
3158 return TK_FunctionTemplate;
3159 if (TemplateOrSpecialization.is<MemberSpecializationInfo *>())
3160 return TK_MemberSpecialization;
3161 if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>())
3162 return TK_FunctionTemplateSpecialization;
3163 if (TemplateOrSpecialization.is
3164 <DependentFunctionTemplateSpecializationInfo*>())
3165 return TK_DependentFunctionTemplateSpecialization;
3166
David Blaikie83d382b2011-09-23 05:06:16 +00003167 llvm_unreachable("Did we miss a TemplateOrSpecialization type?");
Argyrios Kyrtzidiscb6f3462010-06-22 09:54:51 +00003168}
3169
Douglas Gregord801b062009-10-07 23:56:10 +00003170FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const {
Douglas Gregor06db9f52009-10-12 20:18:28 +00003171 if (MemberSpecializationInfo *Info = getMemberSpecializationInfo())
Douglas Gregord801b062009-10-07 23:56:10 +00003172 return cast<FunctionDecl>(Info->getInstantiatedFrom());
Craig Topper36250ad2014-05-12 05:36:57 +00003173
3174 return nullptr;
Douglas Gregord801b062009-10-07 23:56:10 +00003175}
3176
Chandler Carruth21c90602015-12-30 03:24:14 +00003177MemberSpecializationInfo *FunctionDecl::getMemberSpecializationInfo() const {
3178 return TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>();
3179}
3180
Douglas Gregord801b062009-10-07 23:56:10 +00003181void
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00003182FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C,
3183 FunctionDecl *FD,
Douglas Gregord801b062009-10-07 23:56:10 +00003184 TemplateSpecializationKind TSK) {
3185 assert(TemplateOrSpecialization.isNull() &&
3186 "Member function is already a specialization");
3187 MemberSpecializationInfo *Info
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00003188 = new (C) MemberSpecializationInfo(FD, TSK);
Douglas Gregord801b062009-10-07 23:56:10 +00003189 TemplateOrSpecialization = Info;
3190}
3191
Chandler Carruth21c90602015-12-30 03:24:14 +00003192FunctionTemplateDecl *FunctionDecl::getDescribedFunctionTemplate() const {
3193 return TemplateOrSpecialization.dyn_cast<FunctionTemplateDecl *>();
3194}
3195
3196void FunctionDecl::setDescribedFunctionTemplate(FunctionTemplateDecl *Template) {
3197 TemplateOrSpecialization = Template;
3198}
3199
Douglas Gregorafca3b42009-10-27 20:53:28 +00003200bool FunctionDecl::isImplicitlyInstantiable() const {
Douglas Gregor69f6a362010-05-17 17:34:56 +00003201 // If the function is invalid, it can't be implicitly instantiated.
3202 if (isInvalidDecl())
Douglas Gregorafca3b42009-10-27 20:53:28 +00003203 return false;
3204
3205 switch (getTemplateSpecializationKind()) {
3206 case TSK_Undeclared:
Douglas Gregorafca3b42009-10-27 20:53:28 +00003207 case TSK_ExplicitInstantiationDefinition:
3208 return false;
3209
3210 case TSK_ImplicitInstantiation:
3211 return true;
3212
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003213 // It is possible to instantiate TSK_ExplicitSpecialization kind
3214 // if the FunctionDecl has a class scope specialization pattern.
3215 case TSK_ExplicitSpecialization:
Craig Topper36250ad2014-05-12 05:36:57 +00003216 return getClassScopeSpecializationPattern() != nullptr;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003217
Douglas Gregorafca3b42009-10-27 20:53:28 +00003218 case TSK_ExplicitInstantiationDeclaration:
3219 // Handled below.
3220 break;
3221 }
3222
3223 // Find the actual template from which we will instantiate.
3224 const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003225 bool HasPattern = false;
Douglas Gregorafca3b42009-10-27 20:53:28 +00003226 if (PatternDecl)
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003227 HasPattern = PatternDecl->hasBody(PatternDecl);
Douglas Gregorafca3b42009-10-27 20:53:28 +00003228
3229 // C++0x [temp.explicit]p9:
3230 // Except for inline functions, other explicit instantiation declarations
3231 // have the effect of suppressing the implicit instantiation of the entity
3232 // to which they refer.
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003233 if (!HasPattern || !PatternDecl)
Douglas Gregorafca3b42009-10-27 20:53:28 +00003234 return true;
3235
Douglas Gregor583dcaf2009-10-27 21:11:48 +00003236 return PatternDecl->isInlined();
Ted Kremenek85825ae2011-12-01 00:59:17 +00003237}
3238
3239bool FunctionDecl::isTemplateInstantiation() const {
3240 switch (getTemplateSpecializationKind()) {
3241 case TSK_Undeclared:
3242 case TSK_ExplicitSpecialization:
3243 return false;
3244 case TSK_ImplicitInstantiation:
3245 case TSK_ExplicitInstantiationDeclaration:
3246 case TSK_ExplicitInstantiationDefinition:
3247 return true;
3248 }
3249 llvm_unreachable("All TSK values handled.");
3250}
Douglas Gregorafca3b42009-10-27 20:53:28 +00003251
3252FunctionDecl *FunctionDecl::getTemplateInstantiationPattern() const {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003253 // Handle class scope explicit specialization special case.
Richard Smith2195ec92017-04-21 01:15:13 +00003254 if (getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
3255 if (auto *Spec = getClassScopeSpecializationPattern())
3256 return getDefinitionOrSelf(Spec);
3257 return nullptr;
3258 }
3259
Faisal Valib90b2112014-04-03 16:32:21 +00003260 // If this is a generic lambda call operator specialization, its
3261 // instantiation pattern is always its primary template's pattern
3262 // even if its primary template was instantiated from another
3263 // member template (which happens with nested generic lambdas).
3264 // Since a lambda's call operator's body is transformed eagerly,
3265 // we don't have to go hunting for a prototype definition template
3266 // (i.e. instantiated-from-member-template) to use as an instantiation
3267 // pattern.
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003268
Faisal Valib90b2112014-04-03 16:32:21 +00003269 if (isGenericLambdaCallOperatorSpecialization(
3270 dyn_cast<CXXMethodDecl>(this))) {
Richard Smith2195ec92017-04-21 01:15:13 +00003271 assert(getPrimaryTemplate() && "not a generic lambda call operator?");
3272 return getDefinitionOrSelf(getPrimaryTemplate()->getTemplatedDecl());
Faisal Valib90b2112014-04-03 16:32:21 +00003273 }
Richard Smith2195ec92017-04-21 01:15:13 +00003274
Douglas Gregorafca3b42009-10-27 20:53:28 +00003275 if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) {
3276 while (Primary->getInstantiatedFromMemberTemplate()) {
3277 // If we have hit a point where the user provided a specialization of
3278 // this template, we're done looking.
3279 if (Primary->isMemberSpecialization())
3280 break;
Douglas Gregorafca3b42009-10-27 20:53:28 +00003281 Primary = Primary->getInstantiatedFromMemberTemplate();
3282 }
Richard Smith2195ec92017-04-21 01:15:13 +00003283
3284 return getDefinitionOrSelf(Primary->getTemplatedDecl());
Douglas Gregorafca3b42009-10-27 20:53:28 +00003285 }
Richard Smith2195ec92017-04-21 01:15:13 +00003286
3287 if (auto *MFD = getInstantiatedFromMemberFunction())
3288 return getDefinitionOrSelf(MFD);
3289
3290 return nullptr;
Douglas Gregorafca3b42009-10-27 20:53:28 +00003291}
3292
Douglas Gregor70d83e22009-06-29 17:30:29 +00003293FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const {
Mike Stump11289f42009-09-09 15:08:12 +00003294 if (FunctionTemplateSpecializationInfo *Info
Douglas Gregor70d83e22009-06-29 17:30:29 +00003295 = TemplateOrSpecialization
3296 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
Douglas Gregore8925db2009-06-29 22:39:32 +00003297 return Info->Template.getPointer();
Douglas Gregor70d83e22009-06-29 17:30:29 +00003298 }
Craig Topper36250ad2014-05-12 05:36:57 +00003299 return nullptr;
Douglas Gregor70d83e22009-06-29 17:30:29 +00003300}
3301
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003302FunctionDecl *FunctionDecl::getClassScopeSpecializationPattern() const {
3303 return getASTContext().getClassScopeSpecializationPattern(this);
3304}
3305
Chandler Carruth21c90602015-12-30 03:24:14 +00003306FunctionTemplateSpecializationInfo *
3307FunctionDecl::getTemplateSpecializationInfo() const {
3308 return TemplateOrSpecialization
3309 .dyn_cast<FunctionTemplateSpecializationInfo *>();
3310}
3311
Douglas Gregor70d83e22009-06-29 17:30:29 +00003312const TemplateArgumentList *
3313FunctionDecl::getTemplateSpecializationArgs() const {
Mike Stump11289f42009-09-09 15:08:12 +00003314 if (FunctionTemplateSpecializationInfo *Info
Douglas Gregorcf915552009-10-13 16:30:37 +00003315 = TemplateOrSpecialization
3316 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
Douglas Gregor70d83e22009-06-29 17:30:29 +00003317 return Info->TemplateArguments;
3318 }
Craig Topper36250ad2014-05-12 05:36:57 +00003319 return nullptr;
Douglas Gregor70d83e22009-06-29 17:30:29 +00003320}
3321
Argyrios Kyrtzidise9a24432011-09-22 20:07:09 +00003322const ASTTemplateArgumentListInfo *
Abramo Bagnara02ccd282010-05-20 15:32:11 +00003323FunctionDecl::getTemplateSpecializationArgsAsWritten() const {
3324 if (FunctionTemplateSpecializationInfo *Info
3325 = TemplateOrSpecialization
3326 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
3327 return Info->TemplateArgumentsAsWritten;
3328 }
Craig Topper36250ad2014-05-12 05:36:57 +00003329 return nullptr;
Abramo Bagnara02ccd282010-05-20 15:32:11 +00003330}
3331
Mike Stump11289f42009-09-09 15:08:12 +00003332void
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00003333FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C,
3334 FunctionTemplateDecl *Template,
Douglas Gregor8f5d4422009-06-29 20:59:39 +00003335 const TemplateArgumentList *TemplateArgs,
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003336 void *InsertPos,
Abramo Bagnara02ccd282010-05-20 15:32:11 +00003337 TemplateSpecializationKind TSK,
Argyrios Kyrtzidis927d8e02010-07-05 10:37:55 +00003338 const TemplateArgumentListInfo *TemplateArgsAsWritten,
3339 SourceLocation PointOfInstantiation) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003340 assert(TSK != TSK_Undeclared &&
3341 "Must specify the type of function template specialization");
Mike Stump11289f42009-09-09 15:08:12 +00003342 FunctionTemplateSpecializationInfo *Info
Douglas Gregor70d83e22009-06-29 17:30:29 +00003343 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00003344 if (!Info)
Argyrios Kyrtzidise262a952010-09-09 11:28:23 +00003345 Info = FunctionTemplateSpecializationInfo::Create(C, this, Template, TSK,
3346 TemplateArgs,
3347 TemplateArgsAsWritten,
3348 PointOfInstantiation);
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00003349 TemplateOrSpecialization = Info;
Douglas Gregorce9978f2012-03-28 14:34:23 +00003350 Template->addSpecialization(Info, InsertPos);
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00003351}
3352
John McCallb9c78482010-04-08 09:05:18 +00003353void
3354FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context,
3355 const UnresolvedSetImpl &Templates,
3356 const TemplateArgumentListInfo &TemplateArgs) {
3357 assert(TemplateOrSpecialization.isNull());
John McCallb9c78482010-04-08 09:05:18 +00003358 DependentFunctionTemplateSpecializationInfo *Info =
James Y Knight7a22b242015-08-06 20:26:32 +00003359 DependentFunctionTemplateSpecializationInfo::Create(Context, Templates,
3360 TemplateArgs);
John McCallb9c78482010-04-08 09:05:18 +00003361 TemplateOrSpecialization = Info;
3362}
3363
James Y Knight7a22b242015-08-06 20:26:32 +00003364DependentFunctionTemplateSpecializationInfo *
Chandler Carruth21c90602015-12-30 03:24:14 +00003365FunctionDecl::getDependentSpecializationInfo() const {
3366 return TemplateOrSpecialization
3367 .dyn_cast<DependentFunctionTemplateSpecializationInfo *>();
3368}
3369
3370DependentFunctionTemplateSpecializationInfo *
James Y Knight7a22b242015-08-06 20:26:32 +00003371DependentFunctionTemplateSpecializationInfo::Create(
3372 ASTContext &Context, const UnresolvedSetImpl &Ts,
3373 const TemplateArgumentListInfo &TArgs) {
3374 void *Buffer = Context.Allocate(
3375 totalSizeToAlloc<TemplateArgumentLoc, FunctionTemplateDecl *>(
3376 TArgs.size(), Ts.size()));
3377 return new (Buffer) DependentFunctionTemplateSpecializationInfo(Ts, TArgs);
3378}
3379
John McCallb9c78482010-04-08 09:05:18 +00003380DependentFunctionTemplateSpecializationInfo::
3381DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts,
3382 const TemplateArgumentListInfo &TArgs)
Benjamin Kramer3ebba522015-04-02 12:43:31 +00003383 : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) {
John McCallb9c78482010-04-08 09:05:18 +00003384
James Y Knight53c76162015-07-17 18:21:37 +00003385 NumTemplates = Ts.size();
3386 NumArgs = TArgs.size();
Benjamin Kramer3ebba522015-04-02 12:43:31 +00003387
James Y Knight7a22b242015-08-06 20:26:32 +00003388 FunctionTemplateDecl **TsArray = getTrailingObjects<FunctionTemplateDecl *>();
John McCallb9c78482010-04-08 09:05:18 +00003389 for (unsigned I = 0, E = Ts.size(); I != E; ++I)
3390 TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl());
3391
James Y Knight7a22b242015-08-06 20:26:32 +00003392 TemplateArgumentLoc *ArgsArray = getTrailingObjects<TemplateArgumentLoc>();
John McCallb9c78482010-04-08 09:05:18 +00003393 for (unsigned I = 0, E = TArgs.size(); I != E; ++I)
3394 new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]);
3395}
3396
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003397TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const {
Mike Stump11289f42009-09-09 15:08:12 +00003398 // For a function template specialization, query the specialization
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003399 // information object.
Douglas Gregord801b062009-10-07 23:56:10 +00003400 FunctionTemplateSpecializationInfo *FTSInfo
Douglas Gregore8925db2009-06-29 22:39:32 +00003401 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
Douglas Gregord801b062009-10-07 23:56:10 +00003402 if (FTSInfo)
3403 return FTSInfo->getTemplateSpecializationKind();
Mike Stump11289f42009-09-09 15:08:12 +00003404
Douglas Gregord801b062009-10-07 23:56:10 +00003405 MemberSpecializationInfo *MSInfo
3406 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
3407 if (MSInfo)
3408 return MSInfo->getTemplateSpecializationKind();
3409
3410 return TSK_Undeclared;
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003411}
3412
Mike Stump11289f42009-09-09 15:08:12 +00003413void
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003414FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
3415 SourceLocation PointOfInstantiation) {
3416 if (FunctionTemplateSpecializationInfo *FTSInfo
3417 = TemplateOrSpecialization.dyn_cast<
3418 FunctionTemplateSpecializationInfo*>()) {
3419 FTSInfo->setTemplateSpecializationKind(TSK);
3420 if (TSK != TSK_ExplicitSpecialization &&
3421 PointOfInstantiation.isValid() &&
3422 FTSInfo->getPointOfInstantiation().isInvalid())
3423 FTSInfo->setPointOfInstantiation(PointOfInstantiation);
3424 } else if (MemberSpecializationInfo *MSInfo
3425 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) {
3426 MSInfo->setTemplateSpecializationKind(TSK);
3427 if (TSK != TSK_ExplicitSpecialization &&
3428 PointOfInstantiation.isValid() &&
3429 MSInfo->getPointOfInstantiation().isInvalid())
3430 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3431 } else
David Blaikie83d382b2011-09-23 05:06:16 +00003432 llvm_unreachable("Function cannot have a template specialization kind");
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003433}
3434
3435SourceLocation FunctionDecl::getPointOfInstantiation() const {
Douglas Gregord801b062009-10-07 23:56:10 +00003436 if (FunctionTemplateSpecializationInfo *FTSInfo
3437 = TemplateOrSpecialization.dyn_cast<
3438 FunctionTemplateSpecializationInfo*>())
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003439 return FTSInfo->getPointOfInstantiation();
Douglas Gregord801b062009-10-07 23:56:10 +00003440 else if (MemberSpecializationInfo *MSInfo
3441 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>())
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003442 return MSInfo->getPointOfInstantiation();
3443
3444 return SourceLocation();
Douglas Gregore8925db2009-06-29 22:39:32 +00003445}
3446
Douglas Gregor6411b922009-09-11 20:15:17 +00003447bool FunctionDecl::isOutOfLine() const {
Douglas Gregorb11aad82011-02-19 18:51:44 +00003448 if (Decl::isOutOfLine())
Douglas Gregor6411b922009-09-11 20:15:17 +00003449 return true;
3450
3451 // If this function was instantiated from a member function of a
3452 // class template, check whether that member function was defined out-of-line.
3453 if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) {
3454 const FunctionDecl *Definition;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003455 if (FD->hasBody(Definition))
Douglas Gregor6411b922009-09-11 20:15:17 +00003456 return Definition->isOutOfLine();
3457 }
3458
3459 // If this function was instantiated from a function template,
3460 // check whether that function template was defined out-of-line.
3461 if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) {
3462 const FunctionDecl *Definition;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003463 if (FunTmpl->getTemplatedDecl()->hasBody(Definition))
Douglas Gregor6411b922009-09-11 20:15:17 +00003464 return Definition->isOutOfLine();
3465 }
3466
3467 return false;
3468}
3469
Abramo Bagnaraea947882011-03-08 16:41:52 +00003470SourceRange FunctionDecl::getSourceRange() const {
3471 return SourceRange(getOuterLocStart(), EndRangeLoc);
3472}
3473
Anna Zaks28db7ce2012-01-18 02:45:01 +00003474unsigned FunctionDecl::getMemoryFunctionKind() const {
Anna Zaks201d4892012-01-13 21:52:01 +00003475 IdentifierInfo *FnInfo = getIdentifier();
3476
3477 if (!FnInfo)
Anna Zaks22122702012-01-17 00:37:07 +00003478 return 0;
Anna Zaks201d4892012-01-13 21:52:01 +00003479
3480 // Builtin handling.
3481 switch (getBuiltinID()) {
3482 case Builtin::BI__builtin_memset:
3483 case Builtin::BI__builtin___memset_chk:
3484 case Builtin::BImemset:
Anna Zaks22122702012-01-17 00:37:07 +00003485 return Builtin::BImemset;
Anna Zaks201d4892012-01-13 21:52:01 +00003486
3487 case Builtin::BI__builtin_memcpy:
3488 case Builtin::BI__builtin___memcpy_chk:
3489 case Builtin::BImemcpy:
Anna Zaks22122702012-01-17 00:37:07 +00003490 return Builtin::BImemcpy;
Anna Zaks201d4892012-01-13 21:52:01 +00003491
3492 case Builtin::BI__builtin_memmove:
3493 case Builtin::BI__builtin___memmove_chk:
3494 case Builtin::BImemmove:
Anna Zaks22122702012-01-17 00:37:07 +00003495 return Builtin::BImemmove;
Anna Zaks201d4892012-01-13 21:52:01 +00003496
3497 case Builtin::BIstrlcpy:
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00003498 case Builtin::BI__builtin___strlcpy_chk:
Anna Zaks22122702012-01-17 00:37:07 +00003499 return Builtin::BIstrlcpy;
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00003500
Anna Zaks201d4892012-01-13 21:52:01 +00003501 case Builtin::BIstrlcat:
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00003502 case Builtin::BI__builtin___strlcat_chk:
Anna Zaks22122702012-01-17 00:37:07 +00003503 return Builtin::BIstrlcat;
Anna Zaks201d4892012-01-13 21:52:01 +00003504
3505 case Builtin::BI__builtin_memcmp:
Anna Zaks22122702012-01-17 00:37:07 +00003506 case Builtin::BImemcmp:
3507 return Builtin::BImemcmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003508
3509 case Builtin::BI__builtin_strncpy:
3510 case Builtin::BI__builtin___strncpy_chk:
3511 case Builtin::BIstrncpy:
Anna Zaks22122702012-01-17 00:37:07 +00003512 return Builtin::BIstrncpy;
Anna Zaks201d4892012-01-13 21:52:01 +00003513
3514 case Builtin::BI__builtin_strncmp:
Anna Zaks22122702012-01-17 00:37:07 +00003515 case Builtin::BIstrncmp:
3516 return Builtin::BIstrncmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003517
3518 case Builtin::BI__builtin_strncasecmp:
Anna Zaks22122702012-01-17 00:37:07 +00003519 case Builtin::BIstrncasecmp:
3520 return Builtin::BIstrncasecmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003521
3522 case Builtin::BI__builtin_strncat:
Anna Zaks314cd092012-02-01 19:08:57 +00003523 case Builtin::BI__builtin___strncat_chk:
Anna Zaks201d4892012-01-13 21:52:01 +00003524 case Builtin::BIstrncat:
Anna Zaks22122702012-01-17 00:37:07 +00003525 return Builtin::BIstrncat;
Anna Zaks201d4892012-01-13 21:52:01 +00003526
3527 case Builtin::BI__builtin_strndup:
3528 case Builtin::BIstrndup:
Anna Zaks22122702012-01-17 00:37:07 +00003529 return Builtin::BIstrndup;
Anna Zaks201d4892012-01-13 21:52:01 +00003530
Anna Zaks314cd092012-02-01 19:08:57 +00003531 case Builtin::BI__builtin_strlen:
3532 case Builtin::BIstrlen:
3533 return Builtin::BIstrlen;
3534
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00003535 case Builtin::BI__builtin_bzero:
3536 case Builtin::BIbzero:
3537 return Builtin::BIbzero;
3538
Anna Zaks201d4892012-01-13 21:52:01 +00003539 default:
Rafael Espindola5bda63f2013-02-14 01:47:04 +00003540 if (isExternC()) {
Anna Zaks201d4892012-01-13 21:52:01 +00003541 if (FnInfo->isStr("memset"))
Anna Zaks22122702012-01-17 00:37:07 +00003542 return Builtin::BImemset;
Anna Zaks201d4892012-01-13 21:52:01 +00003543 else if (FnInfo->isStr("memcpy"))
Anna Zaks22122702012-01-17 00:37:07 +00003544 return Builtin::BImemcpy;
Anna Zaks201d4892012-01-13 21:52:01 +00003545 else if (FnInfo->isStr("memmove"))
Anna Zaks22122702012-01-17 00:37:07 +00003546 return Builtin::BImemmove;
Anna Zaks201d4892012-01-13 21:52:01 +00003547 else if (FnInfo->isStr("memcmp"))
Anna Zaks22122702012-01-17 00:37:07 +00003548 return Builtin::BImemcmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003549 else if (FnInfo->isStr("strncpy"))
Anna Zaks22122702012-01-17 00:37:07 +00003550 return Builtin::BIstrncpy;
Anna Zaks201d4892012-01-13 21:52:01 +00003551 else if (FnInfo->isStr("strncmp"))
Anna Zaks22122702012-01-17 00:37:07 +00003552 return Builtin::BIstrncmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003553 else if (FnInfo->isStr("strncasecmp"))
Anna Zaks22122702012-01-17 00:37:07 +00003554 return Builtin::BIstrncasecmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003555 else if (FnInfo->isStr("strncat"))
Anna Zaks22122702012-01-17 00:37:07 +00003556 return Builtin::BIstrncat;
Anna Zaks201d4892012-01-13 21:52:01 +00003557 else if (FnInfo->isStr("strndup"))
Anna Zaks22122702012-01-17 00:37:07 +00003558 return Builtin::BIstrndup;
Anna Zaks314cd092012-02-01 19:08:57 +00003559 else if (FnInfo->isStr("strlen"))
3560 return Builtin::BIstrlen;
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00003561 else if (FnInfo->isStr("bzero"))
3562 return Builtin::BIbzero;
Anna Zaks201d4892012-01-13 21:52:01 +00003563 }
3564 break;
3565 }
Anna Zaks22122702012-01-17 00:37:07 +00003566 return 0;
Anna Zaks201d4892012-01-13 21:52:01 +00003567}
3568
Chris Lattner59a25942008-03-31 00:36:02 +00003569//===----------------------------------------------------------------------===//
Sebastian Redl833ef452010-01-26 22:01:41 +00003570// FieldDecl Implementation
3571//===----------------------------------------------------------------------===//
3572
Jay Foad39c79802011-01-12 09:06:06 +00003573FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003574 SourceLocation StartLoc, SourceLocation IdLoc,
3575 IdentifierInfo *Id, QualType T,
Richard Smith938f40b2011-06-11 17:19:42 +00003576 TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
Richard Smith2b013182012-06-10 03:12:00 +00003577 InClassInitStyle InitStyle) {
Richard Smithf7981722013-11-22 09:01:48 +00003578 return new (C, DC) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo,
3579 BW, Mutable, InitStyle);
Sebastian Redl833ef452010-01-26 22:01:41 +00003580}
3581
Douglas Gregor72172e92012-01-05 21:55:30 +00003582FieldDecl *FieldDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00003583 return new (C, ID) FieldDecl(Field, nullptr, SourceLocation(),
3584 SourceLocation(), nullptr, QualType(), nullptr,
3585 nullptr, false, ICIS_NoInit);
Douglas Gregor72172e92012-01-05 21:55:30 +00003586}
3587
Sebastian Redl833ef452010-01-26 22:01:41 +00003588bool FieldDecl::isAnonymousStructOrUnion() const {
3589 if (!isImplicit() || getDeclName())
3590 return false;
3591
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00003592 if (const auto *Record = getType()->getAs<RecordType>())
Sebastian Redl833ef452010-01-26 22:01:41 +00003593 return Record->getDecl()->isAnonymousStructOrUnion();
3594
3595 return false;
3596}
3597
Richard Smithcaf33902011-10-10 18:28:20 +00003598unsigned FieldDecl::getBitWidthValue(const ASTContext &Ctx) const {
3599 assert(isBitField() && "not a bitfield");
Richard Smith6b8e3c02017-08-28 00:28:14 +00003600 return getBitWidth()->EvaluateKnownConstInt(Ctx).getZExtValue();
Richard Smithcaf33902011-10-10 18:28:20 +00003601}
3602
John McCall4e819612011-01-20 07:57:12 +00003603unsigned FieldDecl::getFieldIndex() const {
Richard Smith0b87e072013-10-07 08:02:11 +00003604 const FieldDecl *Canonical = getCanonicalDecl();
3605 if (Canonical != this)
3606 return Canonical->getFieldIndex();
3607
John McCall4e819612011-01-20 07:57:12 +00003608 if (CachedFieldIndex) return CachedFieldIndex - 1;
3609
Richard Smithd62306a2011-11-10 06:34:14 +00003610 unsigned Index = 0;
Fariborz Jahanian8409bce42011-04-28 22:49:46 +00003611 const RecordDecl *RD = getParent();
Richard Smithd62306a2011-11-10 06:34:14 +00003612
Hans Wennborga302cd92014-08-21 16:06:57 +00003613 for (auto *Field : RD->fields()) {
3614 Field->getCanonicalDecl()->CachedFieldIndex = Index + 1;
3615 ++Index;
3616 }
John McCall4e819612011-01-20 07:57:12 +00003617
Richard Smithd62306a2011-11-10 06:34:14 +00003618 assert(CachedFieldIndex && "failed to find field in parent");
3619 return CachedFieldIndex - 1;
John McCall4e819612011-01-20 07:57:12 +00003620}
3621
Abramo Bagnara20c9e242011-03-08 11:07:11 +00003622SourceRange FieldDecl::getSourceRange() const {
Richard Smith6b8e3c02017-08-28 00:28:14 +00003623 const Expr *FinalExpr = getInClassInitializer();
3624 if (!FinalExpr)
3625 FinalExpr = getBitWidth();
3626 if (FinalExpr)
3627 return SourceRange(getInnerLocStart(), FinalExpr->getLocEnd());
3628 return DeclaratorDecl::getSourceRange();
Alexey Bataev39c81e22014-08-28 04:28:19 +00003629}
3630
3631void FieldDecl::setCapturedVLAType(const VariableArrayType *VLAType) {
David Blaikie11ab0782014-10-31 17:18:09 +00003632 assert((getParent()->isLambda() || getParent()->isCapturedRecord()) &&
Alexey Bataev330de032014-10-29 12:21:55 +00003633 "capturing type in non-lambda or captured record.");
Richard Smith6b8e3c02017-08-28 00:28:14 +00003634 assert(InitStorage.getInt() == ISK_NoInit &&
John McCallc90c1492014-10-10 18:44:34 +00003635 InitStorage.getPointer() == nullptr &&
Alexey Bataev39c81e22014-08-28 04:28:19 +00003636 "bit width, initializer or captured type already set");
John McCallc90c1492014-10-10 18:44:34 +00003637 InitStorage.setPointerAndInt(const_cast<VariableArrayType *>(VLAType),
3638 ISK_CapturedVLAType);
Alexey Bataev39c81e22014-08-28 04:28:19 +00003639}
3640
Sebastian Redl833ef452010-01-26 22:01:41 +00003641//===----------------------------------------------------------------------===//
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003642// TagDecl Implementation
Ted Kremenek21475702008-09-05 17:16:31 +00003643//===----------------------------------------------------------------------===//
3644
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00003645SourceLocation TagDecl::getOuterLocStart() const {
3646 return getTemplateOrInnerLocStart(this);
3647}
3648
Argyrios Kyrtzidis575fa052009-07-14 03:17:17 +00003649SourceRange TagDecl::getSourceRange() const {
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00003650 SourceLocation RBraceLoc = BraceRange.getEnd();
Argyrios Kyrtzidis575fa052009-07-14 03:17:17 +00003651 SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation();
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00003652 return SourceRange(getOuterLocStart(), E);
Argyrios Kyrtzidis575fa052009-07-14 03:17:17 +00003653}
3654
Rafael Espindola8db352d2013-10-17 15:37:26 +00003655TagDecl *TagDecl::getCanonicalDecl() { return getFirstDecl(); }
Argyrios Kyrtzidis5614aef2009-07-18 00:34:07 +00003656
Rafael Espindolabf5c33b2013-03-12 21:06:00 +00003657void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) {
David Majnemer00350522015-08-31 18:48:39 +00003658 TypedefNameDeclOrQualifier = TDD;
Reid Klecknercae82a22014-04-23 22:03:04 +00003659 if (const Type *T = getTypeForDecl()) {
3660 (void)T;
Richard Smith5b21db82014-04-23 18:20:42 +00003661 assert(T->isLinkageValid());
Reid Klecknercae82a22014-04-23 22:03:04 +00003662 }
Rafael Espindola0e0d0092013-03-14 03:07:35 +00003663 assert(isLinkageValid());
Douglas Gregora72a4e32010-05-19 18:39:18 +00003664}
3665
Douglas Gregordee1be82009-01-17 00:42:38 +00003666void TagDecl::startDefinition() {
Sebastian Redl9d8854e2010-08-02 18:27:05 +00003667 IsBeingDefined = true;
John McCall67da35c2010-02-04 22:26:26 +00003668
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00003669 if (auto *D = dyn_cast<CXXRecordDecl>(this)) {
Richard Smith053f6c62014-05-16 23:01:30 +00003670 struct CXXRecordDecl::DefinitionData *Data =
John McCall67da35c2010-02-04 22:26:26 +00003671 new (getASTContext()) struct CXXRecordDecl::DefinitionData(D);
Aaron Ballman86c93902014-03-06 23:45:36 +00003672 for (auto I : redecls())
Richard Smith64c06302014-05-22 23:19:02 +00003673 cast<CXXRecordDecl>(I)->DefinitionData = Data;
John McCall67da35c2010-02-04 22:26:26 +00003674 }
Douglas Gregordee1be82009-01-17 00:42:38 +00003675}
3676
3677void TagDecl::completeDefinition() {
John McCallae580fe2010-02-05 01:33:36 +00003678 assert((!isa<CXXRecordDecl>(this) ||
3679 cast<CXXRecordDecl>(this)->hasDefinition()) &&
3680 "definition completed but not started");
3681
John McCallf937c022011-10-07 06:10:15 +00003682 IsCompleteDefinition = true;
Sebastian Redl9d8854e2010-08-02 18:27:05 +00003683 IsBeingDefined = false;
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00003684
3685 if (ASTMutationListener *L = getASTMutationListener())
3686 L->CompletedTagDefinition(this);
Douglas Gregordee1be82009-01-17 00:42:38 +00003687}
3688
John McCallf937c022011-10-07 06:10:15 +00003689TagDecl *TagDecl::getDefinition() const {
3690 if (isCompleteDefinition())
Douglas Gregorb6b8f9e2009-07-29 23:36:44 +00003691 return const_cast<TagDecl *>(this);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003692
3693 // If it's possible for us to have an out-of-date definition, check now.
3694 if (MayHaveOutOfDateDef) {
3695 if (IdentifierInfo *II = getIdentifier()) {
3696 if (II->isOutOfDate()) {
3697 updateOutOfDate(*II);
3698 }
3699 }
3700 }
3701
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00003702 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(this))
Andrew Trickba266ee2010-10-19 21:54:32 +00003703 return CXXRD->getDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00003704
Aaron Ballman86c93902014-03-06 23:45:36 +00003705 for (auto R : redecls())
John McCallf937c022011-10-07 06:10:15 +00003706 if (R->isCompleteDefinition())
Aaron Ballman86c93902014-03-06 23:45:36 +00003707 return R;
Mike Stump11289f42009-09-09 15:08:12 +00003708
Craig Topper36250ad2014-05-12 05:36:57 +00003709 return nullptr;
Ted Kremenek21475702008-09-05 17:16:31 +00003710}
3711
Douglas Gregor14454802011-02-25 02:25:35 +00003712void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
3713 if (QualifierLoc) {
John McCall3e11ebe2010-03-15 10:12:16 +00003714 // Make sure the extended qualifier info is allocated.
3715 if (!hasExtInfo())
David Majnemer00350522015-08-31 18:48:39 +00003716 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
John McCall3e11ebe2010-03-15 10:12:16 +00003717 // Set qualifier info.
Douglas Gregor14454802011-02-25 02:25:35 +00003718 getExtInfo()->QualifierLoc = QualifierLoc;
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003719 } else {
John McCall3e11ebe2010-03-15 10:12:16 +00003720 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
John McCall3e11ebe2010-03-15 10:12:16 +00003721 if (hasExtInfo()) {
Abramo Bagnara60804e12011-03-18 15:16:37 +00003722 if (getExtInfo()->NumTemplParamLists == 0) {
3723 getASTContext().Deallocate(getExtInfo());
David Majnemer00350522015-08-31 18:48:39 +00003724 TypedefNameDeclOrQualifier = (TypedefNameDecl *)nullptr;
Abramo Bagnara60804e12011-03-18 15:16:37 +00003725 }
3726 else
3727 getExtInfo()->QualifierLoc = QualifierLoc;
John McCall3e11ebe2010-03-15 10:12:16 +00003728 }
3729 }
3730}
3731
Benjamin Kramer9cc210652015-08-05 09:40:49 +00003732void TagDecl::setTemplateParameterListsInfo(
3733 ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
3734 assert(!TPLists.empty());
Abramo Bagnara60804e12011-03-18 15:16:37 +00003735 // Make sure the extended decl info is allocated.
3736 if (!hasExtInfo())
3737 // Allocate external info struct.
David Majnemer00350522015-08-31 18:48:39 +00003738 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
Abramo Bagnara60804e12011-03-18 15:16:37 +00003739 // Set the template parameter lists info.
Benjamin Kramer9cc210652015-08-05 09:40:49 +00003740 getExtInfo()->setTemplateParameterListsInfo(Context, TPLists);
Abramo Bagnara60804e12011-03-18 15:16:37 +00003741}
3742
Ted Kremenek21475702008-09-05 17:16:31 +00003743//===----------------------------------------------------------------------===//
Sebastian Redl833ef452010-01-26 22:01:41 +00003744// EnumDecl Implementation
3745//===----------------------------------------------------------------------===//
3746
David Blaikie68e081d2011-12-20 02:48:34 +00003747void EnumDecl::anchor() { }
3748
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003749EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC,
3750 SourceLocation StartLoc, SourceLocation IdLoc,
3751 IdentifierInfo *Id,
Abramo Bagnara0e05e242010-12-03 18:54:17 +00003752 EnumDecl *PrevDecl, bool IsScoped,
3753 bool IsScopedUsingClassTag, bool IsFixed) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00003754 auto *Enum = new (C, DC) EnumDecl(C, DC, StartLoc, IdLoc, Id, PrevDecl,
3755 IsScoped, IsScopedUsingClassTag, IsFixed);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003756 Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules;
Sebastian Redl833ef452010-01-26 22:01:41 +00003757 C.getTypeDeclType(Enum, PrevDecl);
3758 return Enum;
3759}
3760
Douglas Gregor72172e92012-01-05 21:55:30 +00003761EnumDecl *EnumDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00003762 EnumDecl *Enum =
3763 new (C, ID) EnumDecl(C, nullptr, SourceLocation(), SourceLocation(),
3764 nullptr, nullptr, false, false, false);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003765 Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3766 return Enum;
Argyrios Kyrtzidis39f0e302010-07-02 11:54:55 +00003767}
3768
Alp Tokerb9fa5122014-01-06 11:31:18 +00003769SourceRange EnumDecl::getIntegerTypeRange() const {
3770 if (const TypeSourceInfo *TI = getIntegerTypeSourceInfo())
3771 return TI->getTypeLoc().getSourceRange();
3772 return SourceRange();
3773}
3774
Douglas Gregord5058122010-02-11 01:19:42 +00003775void EnumDecl::completeDefinition(QualType NewType,
John McCall9aa35be2010-05-06 08:49:23 +00003776 QualType NewPromotionType,
3777 unsigned NumPositiveBits,
3778 unsigned NumNegativeBits) {
John McCallf937c022011-10-07 06:10:15 +00003779 assert(!isCompleteDefinition() && "Cannot redefine enums!");
Douglas Gregor0bf31402010-10-08 23:50:27 +00003780 if (!IntegerType)
3781 IntegerType = NewType.getTypePtr();
Sebastian Redl833ef452010-01-26 22:01:41 +00003782 PromotionType = NewPromotionType;
John McCall9aa35be2010-05-06 08:49:23 +00003783 setNumPositiveBits(NumPositiveBits);
3784 setNumNegativeBits(NumNegativeBits);
Sebastian Redl833ef452010-01-26 22:01:41 +00003785 TagDecl::completeDefinition();
3786}
3787
Akira Hatanaka3c268af2017-03-21 02:23:00 +00003788bool EnumDecl::isClosed() const {
3789 if (const auto *A = getAttr<EnumExtensibilityAttr>())
3790 return A->getExtensibility() == EnumExtensibilityAttr::Closed;
3791 return true;
3792}
3793
3794bool EnumDecl::isClosedFlag() const {
3795 return isClosed() && hasAttr<FlagEnumAttr>();
3796}
3797
3798bool EnumDecl::isClosedNonFlag() const {
3799 return isClosed() && !hasAttr<FlagEnumAttr>();
3800}
3801
Richard Smith7d137e32012-03-23 03:33:32 +00003802TemplateSpecializationKind EnumDecl::getTemplateSpecializationKind() const {
3803 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
3804 return MSI->getTemplateSpecializationKind();
3805
3806 return TSK_Undeclared;
3807}
3808
3809void EnumDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
3810 SourceLocation PointOfInstantiation) {
3811 MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
3812 assert(MSI && "Not an instantiated member enumeration?");
3813 MSI->setTemplateSpecializationKind(TSK);
3814 if (TSK != TSK_ExplicitSpecialization &&
3815 PointOfInstantiation.isValid() &&
3816 MSI->getPointOfInstantiation().isInvalid())
3817 MSI->setPointOfInstantiation(PointOfInstantiation);
3818}
3819
Richard Smith6739a102016-05-05 00:56:12 +00003820EnumDecl *EnumDecl::getTemplateInstantiationPattern() const {
3821 if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) {
3822 if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) {
3823 EnumDecl *ED = getInstantiatedFromMemberEnum();
3824 while (auto *NewED = ED->getInstantiatedFromMemberEnum())
3825 ED = NewED;
Richard Smith2195ec92017-04-21 01:15:13 +00003826 return getDefinitionOrSelf(ED);
Richard Smith6739a102016-05-05 00:56:12 +00003827 }
3828 }
3829
3830 assert(!isTemplateInstantiation(getTemplateSpecializationKind()) &&
3831 "couldn't find pattern for enum instantiation");
3832 return nullptr;
3833}
3834
Richard Smith4b38ded2012-03-14 23:13:10 +00003835EnumDecl *EnumDecl::getInstantiatedFromMemberEnum() const {
3836 if (SpecializationInfo)
3837 return cast<EnumDecl>(SpecializationInfo->getInstantiatedFrom());
3838
Craig Topper36250ad2014-05-12 05:36:57 +00003839 return nullptr;
Richard Smith4b38ded2012-03-14 23:13:10 +00003840}
3841
3842void EnumDecl::setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
3843 TemplateSpecializationKind TSK) {
3844 assert(!SpecializationInfo && "Member enum is already a specialization");
3845 SpecializationInfo = new (C) MemberSpecializationInfo(ED, TSK);
3846}
3847
Sebastian Redl833ef452010-01-26 22:01:41 +00003848//===----------------------------------------------------------------------===//
Chris Lattner59a25942008-03-31 00:36:02 +00003849// RecordDecl Implementation
3850//===----------------------------------------------------------------------===//
Chris Lattner41943152007-01-25 04:52:46 +00003851
Richard Smith053f6c62014-05-16 23:01:30 +00003852RecordDecl::RecordDecl(Kind DK, TagKind TK, const ASTContext &C,
3853 DeclContext *DC, SourceLocation StartLoc,
3854 SourceLocation IdLoc, IdentifierInfo *Id,
3855 RecordDecl *PrevDecl)
3856 : TagDecl(DK, TK, C, DC, IdLoc, Id, PrevDecl, StartLoc) {
Ted Kremenek52baf502008-09-02 21:12:32 +00003857 HasFlexibleArrayMember = false;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003858 AnonymousStructOrUnion = false;
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00003859 HasObjectMember = false;
Fariborz Jahanian78652202013-01-25 23:57:05 +00003860 HasVolatileMember = false;
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003861 LoadedFieldsFromExternalStorage = false;
Ted Kremenek52baf502008-09-02 21:12:32 +00003862 assert(classof(static_cast<Decl*>(this)) && "Invalid Kind!");
Ted Kremenek52baf502008-09-02 21:12:32 +00003863}
3864
Jay Foad39c79802011-01-12 09:06:06 +00003865RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003866 SourceLocation StartLoc, SourceLocation IdLoc,
3867 IdentifierInfo *Id, RecordDecl* PrevDecl) {
Richard Smith053f6c62014-05-16 23:01:30 +00003868 RecordDecl *R = new (C, DC) RecordDecl(Record, TK, C, DC,
3869 StartLoc, IdLoc, Id, PrevDecl);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003870 R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3871
Ted Kremenek21475702008-09-05 17:16:31 +00003872 C.getTypeDeclType(R, PrevDecl);
3873 return R;
Ted Kremenek52baf502008-09-02 21:12:32 +00003874}
3875
Douglas Gregor72172e92012-01-05 21:55:30 +00003876RecordDecl *RecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00003877 RecordDecl *R =
3878 new (C, ID) RecordDecl(Record, TTK_Struct, C, nullptr, SourceLocation(),
3879 SourceLocation(), nullptr, nullptr);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003880 R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3881 return R;
Argyrios Kyrtzidis39f0e302010-07-02 11:54:55 +00003882}
3883
Douglas Gregordfcad112009-03-25 15:59:44 +00003884bool RecordDecl::isInjectedClassName() const {
Mike Stump11289f42009-09-09 15:08:12 +00003885 return isImplicit() && getDeclName() && getDeclContext()->isRecord() &&
Douglas Gregordfcad112009-03-25 15:59:44 +00003886 cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName();
3887}
3888
Alexey Bataev39c81e22014-08-28 04:28:19 +00003889bool RecordDecl::isLambda() const {
3890 if (auto RD = dyn_cast<CXXRecordDecl>(this))
3891 return RD->isLambda();
3892 return false;
3893}
3894
Alexey Bataev330de032014-10-29 12:21:55 +00003895bool RecordDecl::isCapturedRecord() const {
3896 return hasAttr<CapturedRecordAttr>();
3897}
3898
3899void RecordDecl::setCapturedRecord() {
3900 addAttr(CapturedRecordAttr::CreateImplicit(getASTContext()));
3901}
3902
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003903RecordDecl::field_iterator RecordDecl::field_begin() const {
3904 if (hasExternalLexicalStorage() && !LoadedFieldsFromExternalStorage)
3905 LoadFieldsFromExternalStorage();
3906
3907 return field_iterator(decl_iterator(FirstDecl));
3908}
3909
Douglas Gregorb11aad82011-02-19 18:51:44 +00003910/// completeDefinition - Notes that the definition of this type is now
3911/// complete.
3912void RecordDecl::completeDefinition() {
John McCallf937c022011-10-07 06:10:15 +00003913 assert(!isCompleteDefinition() && "Cannot redefine record!");
Douglas Gregorb11aad82011-02-19 18:51:44 +00003914 TagDecl::completeDefinition();
3915}
3916
Eli Friedman9ee2d0472012-10-12 23:29:20 +00003917/// isMsStruct - Get whether or not this record uses ms_struct layout.
3918/// This which can be turned on with an attribute, pragma, or the
3919/// -mms-bitfields command-line option.
3920bool RecordDecl::isMsStruct(const ASTContext &C) const {
David Majnemer8ab003a2015-02-02 19:30:52 +00003921 return hasAttr<MSStructAttr>() || C.getLangOpts().MSBitfields == 1;
Eli Friedman9ee2d0472012-10-12 23:29:20 +00003922}
3923
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003924void RecordDecl::LoadFieldsFromExternalStorage() const {
3925 ExternalASTSource *Source = getASTContext().getExternalSource();
3926 assert(hasExternalLexicalStorage() && Source && "No external storage?");
3927
3928 // Notify that we have a RecordDecl doing some initialization.
3929 ExternalASTSource::Deserializing TheFields(Source);
3930
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003931 SmallVector<Decl*, 64> Decls;
Richard Smith3cb15722015-08-05 22:41:45 +00003932 LoadedFieldsFromExternalStorage = true;
3933 Source->FindExternalLexicalDecls(this, [](Decl::Kind K) {
3934 return FieldDecl::classofKind(K) || IndirectFieldDecl::classofKind(K);
3935 }, Decls);
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003936
3937#ifndef NDEBUG
3938 // Check that all decls we got were FieldDecls.
3939 for (unsigned i=0, e=Decls.size(); i != e; ++i)
Argyrios Kyrtzidisf89a9272012-09-10 22:04:22 +00003940 assert(isa<FieldDecl>(Decls[i]) || isa<IndirectFieldDecl>(Decls[i]));
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003941#endif
3942
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003943 if (Decls.empty())
3944 return;
3945
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00003946 std::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls,
Argyrios Kyrtzidis094da732011-10-07 21:55:43 +00003947 /*FieldsAlreadyLoaded=*/false);
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003948}
3949
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00003950bool RecordDecl::mayInsertExtraPadding(bool EmitRemark) const {
3951 ASTContext &Context = getASTContext();
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00003952 const SanitizerMask EnabledAsanMask = Context.getLangOpts().Sanitize.Mask &
3953 (SanitizerKind::Address | SanitizerKind::KernelAddress);
3954 if (!EnabledAsanMask || !Context.getLangOpts().SanitizeAddressFieldPadding)
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00003955 return false;
Alexey Samsonov33e00e22014-10-16 23:50:26 +00003956 const auto &Blacklist = Context.getSanitizerBlacklist();
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00003957 const auto *CXXRD = dyn_cast<CXXRecordDecl>(this);
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00003958 // We may be able to relax some of these requirements.
3959 int ReasonToReject = -1;
3960 if (!CXXRD || CXXRD->isExternCContext())
3961 ReasonToReject = 0; // is not C++.
3962 else if (CXXRD->hasAttr<PackedAttr>())
3963 ReasonToReject = 1; // is packed.
3964 else if (CXXRD->isUnion())
3965 ReasonToReject = 2; // is a union.
3966 else if (CXXRD->isTriviallyCopyable())
3967 ReasonToReject = 3; // is trivially copyable.
3968 else if (CXXRD->hasTrivialDestructor())
3969 ReasonToReject = 4; // has trivial destructor.
3970 else if (CXXRD->isStandardLayout())
3971 ReasonToReject = 5; // is standard layout.
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00003972 else if (Blacklist.isBlacklistedLocation(EnabledAsanMask, getLocation(),
3973 "field-padding"))
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00003974 ReasonToReject = 6; // is in a blacklisted file.
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00003975 else if (Blacklist.isBlacklistedType(EnabledAsanMask,
3976 getQualifiedNameAsString(),
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00003977 "field-padding"))
3978 ReasonToReject = 7; // is blacklisted.
3979
3980 if (EmitRemark) {
3981 if (ReasonToReject >= 0)
3982 Context.getDiagnostics().Report(
3983 getLocation(),
3984 diag::remark_sanitize_address_insert_extra_padding_rejected)
3985 << getQualifiedNameAsString() << ReasonToReject;
3986 else
3987 Context.getDiagnostics().Report(
3988 getLocation(),
3989 diag::remark_sanitize_address_insert_extra_padding_accepted)
3990 << getQualifiedNameAsString();
3991 }
3992 return ReasonToReject < 0;
3993}
3994
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00003995const FieldDecl *RecordDecl::findFirstNamedDataMember() const {
3996 for (const auto *I : fields()) {
3997 if (I->getIdentifier())
3998 return I;
3999
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00004000 if (const auto *RT = I->getType()->getAs<RecordType>())
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00004001 if (const FieldDecl *NamedDataMember =
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00004002 RT->getDecl()->findFirstNamedDataMember())
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00004003 return NamedDataMember;
4004 }
4005
4006 // We didn't find a named data member.
4007 return nullptr;
4008}
4009
4010
Steve Naroff415d3d52008-10-08 17:01:13 +00004011//===----------------------------------------------------------------------===//
4012// BlockDecl Implementation
4013//===----------------------------------------------------------------------===//
4014
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004015void BlockDecl::setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
Craig Topper36250ad2014-05-12 05:36:57 +00004016 assert(!ParamInfo && "Already has param info!");
Mike Stump11289f42009-09-09 15:08:12 +00004017
Steve Naroffc4b30e52009-03-13 16:56:44 +00004018 // Zero params -> null pointer.
David Blaikie9c70e042011-09-21 18:16:56 +00004019 if (!NewParamInfo.empty()) {
4020 NumParams = NewParamInfo.size();
4021 ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()];
4022 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
Steve Naroffc4b30e52009-03-13 16:56:44 +00004023 }
4024}
4025
Benjamin Kramerb40e4af2015-08-05 09:40:35 +00004026void BlockDecl::setCaptures(ASTContext &Context, ArrayRef<Capture> Captures,
4027 bool CapturesCXXThis) {
4028 this->CapturesCXXThis = CapturesCXXThis;
4029 this->NumCaptures = Captures.size();
John McCallc63de662011-02-02 13:00:07 +00004030
Benjamin Kramerb40e4af2015-08-05 09:40:35 +00004031 if (Captures.empty()) {
4032 this->Captures = nullptr;
John McCallc63de662011-02-02 13:00:07 +00004033 return;
4034 }
4035
Benjamin Kramerb40e4af2015-08-05 09:40:35 +00004036 this->Captures = Captures.copy(Context).data();
Steve Naroffc4b30e52009-03-13 16:56:44 +00004037}
Sebastian Redl833ef452010-01-26 22:01:41 +00004038
John McCallce45f882011-06-15 22:51:16 +00004039bool BlockDecl::capturesVariable(const VarDecl *variable) const {
Aaron Ballman9371dd22014-03-14 18:34:04 +00004040 for (const auto &I : captures())
John McCallce45f882011-06-15 22:51:16 +00004041 // Only auto vars can be captured, so no redeclaration worries.
Aaron Ballman9371dd22014-03-14 18:34:04 +00004042 if (I.getVariable() == variable)
John McCallce45f882011-06-15 22:51:16 +00004043 return true;
4044
4045 return false;
4046}
4047
Douglas Gregor70226da2010-12-21 16:27:07 +00004048SourceRange BlockDecl::getSourceRange() const {
4049 return SourceRange(getLocation(), Body? Body->getLocEnd() : getLocation());
4050}
Sebastian Redl833ef452010-01-26 22:01:41 +00004051
4052//===----------------------------------------------------------------------===//
4053// Other Decl Allocation/Deallocation Method Implementations
4054//===----------------------------------------------------------------------===//
4055
David Blaikie68e081d2011-12-20 02:48:34 +00004056void TranslationUnitDecl::anchor() { }
4057
Sebastian Redl833ef452010-01-26 22:01:41 +00004058TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) {
Craig Topper36250ad2014-05-12 05:36:57 +00004059 return new (C, (DeclContext *)nullptr) TranslationUnitDecl(C);
Sebastian Redl833ef452010-01-26 22:01:41 +00004060}
4061
Nico Weber66220292016-03-02 17:28:48 +00004062void PragmaCommentDecl::anchor() { }
4063
4064PragmaCommentDecl *PragmaCommentDecl::Create(const ASTContext &C,
4065 TranslationUnitDecl *DC,
4066 SourceLocation CommentLoc,
4067 PragmaMSCommentKind CommentKind,
4068 StringRef Arg) {
4069 PragmaCommentDecl *PCD =
4070 new (C, DC, additionalSizeToAlloc<char>(Arg.size() + 1))
4071 PragmaCommentDecl(DC, CommentLoc, CommentKind);
4072 memcpy(PCD->getTrailingObjects<char>(), Arg.data(), Arg.size());
4073 PCD->getTrailingObjects<char>()[Arg.size()] = '\0';
4074 return PCD;
4075}
4076
4077PragmaCommentDecl *PragmaCommentDecl::CreateDeserialized(ASTContext &C,
4078 unsigned ID,
4079 unsigned ArgSize) {
4080 return new (C, ID, additionalSizeToAlloc<char>(ArgSize + 1))
4081 PragmaCommentDecl(nullptr, SourceLocation(), PCK_Unknown);
4082}
4083
Nico Webercbbaeb12016-03-02 19:28:54 +00004084void PragmaDetectMismatchDecl::anchor() { }
4085
4086PragmaDetectMismatchDecl *
4087PragmaDetectMismatchDecl::Create(const ASTContext &C, TranslationUnitDecl *DC,
4088 SourceLocation Loc, StringRef Name,
4089 StringRef Value) {
4090 size_t ValueStart = Name.size() + 1;
4091 PragmaDetectMismatchDecl *PDMD =
4092 new (C, DC, additionalSizeToAlloc<char>(ValueStart + Value.size() + 1))
4093 PragmaDetectMismatchDecl(DC, Loc, ValueStart);
4094 memcpy(PDMD->getTrailingObjects<char>(), Name.data(), Name.size());
4095 PDMD->getTrailingObjects<char>()[Name.size()] = '\0';
4096 memcpy(PDMD->getTrailingObjects<char>() + ValueStart, Value.data(),
4097 Value.size());
4098 PDMD->getTrailingObjects<char>()[ValueStart + Value.size()] = '\0';
4099 return PDMD;
4100}
4101
4102PragmaDetectMismatchDecl *
4103PragmaDetectMismatchDecl::CreateDeserialized(ASTContext &C, unsigned ID,
4104 unsigned NameValueSize) {
4105 return new (C, ID, additionalSizeToAlloc<char>(NameValueSize + 1))
4106 PragmaDetectMismatchDecl(nullptr, SourceLocation(), 0);
4107}
Nico Weber66220292016-03-02 17:28:48 +00004108
Richard Smithf19e1272015-03-07 00:04:49 +00004109void ExternCContextDecl::anchor() { }
4110
4111ExternCContextDecl *ExternCContextDecl::Create(const ASTContext &C,
4112 TranslationUnitDecl *DC) {
4113 return new (C, DC) ExternCContextDecl(DC);
4114}
4115
David Blaikie68e081d2011-12-20 02:48:34 +00004116void LabelDecl::anchor() { }
4117
Chris Lattnerc8e630e2011-02-17 07:39:24 +00004118LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnara1c3af962011-03-05 18:21:20 +00004119 SourceLocation IdentL, IdentifierInfo *II) {
Craig Topper36250ad2014-05-12 05:36:57 +00004120 return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, IdentL);
Abramo Bagnara1c3af962011-03-05 18:21:20 +00004121}
4122
4123LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
4124 SourceLocation IdentL, IdentifierInfo *II,
4125 SourceLocation GnuLabelL) {
4126 assert(GnuLabelL != IdentL && "Use this only for GNU local labels");
Craig Topper36250ad2014-05-12 05:36:57 +00004127 return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, GnuLabelL);
Chris Lattnerc8e630e2011-02-17 07:39:24 +00004128}
4129
Douglas Gregor72172e92012-01-05 21:55:30 +00004130LabelDecl *LabelDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00004131 return new (C, ID) LabelDecl(nullptr, SourceLocation(), nullptr, nullptr,
4132 SourceLocation());
Douglas Gregor417e87c2010-10-27 19:49:05 +00004133}
4134
Ehsan Akhgari31097582014-09-22 02:21:54 +00004135void LabelDecl::setMSAsmLabel(StringRef Name) {
4136 char *Buffer = new (getASTContext(), 1) char[Name.size() + 1];
4137 memcpy(Buffer, Name.data(), Name.size());
4138 Buffer[Name.size()] = '\0';
4139 MSAsmName = Buffer;
4140}
4141
David Blaikie68e081d2011-12-20 02:48:34 +00004142void ValueDecl::anchor() { }
4143
Benjamin Kramerea70eb32012-12-01 15:09:41 +00004144bool ValueDecl::isWeak() const {
Aaron Ballmanb97112e2014-03-08 22:19:01 +00004145 for (const auto *I : attrs())
4146 if (isa<WeakAttr>(I) || isa<WeakRefAttr>(I))
Benjamin Kramerea70eb32012-12-01 15:09:41 +00004147 return true;
4148
4149 return isWeakImported();
4150}
4151
David Blaikie68e081d2011-12-20 02:48:34 +00004152void ImplicitParamDecl::anchor() { }
4153
Sebastian Redl833ef452010-01-26 22:01:41 +00004154ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004155 SourceLocation IdLoc,
Alexey Bataev56223232017-06-09 13:40:18 +00004156 IdentifierInfo *Id, QualType Type,
4157 ImplicitParamKind ParamKind) {
4158 return new (C, DC) ImplicitParamDecl(C, DC, IdLoc, Id, Type, ParamKind);
4159}
4160
4161ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, QualType Type,
4162 ImplicitParamKind ParamKind) {
4163 return new (C, nullptr) ImplicitParamDecl(C, Type, ParamKind);
Sebastian Redl833ef452010-01-26 22:01:41 +00004164}
4165
Richard Smithf7981722013-11-22 09:01:48 +00004166ImplicitParamDecl *ImplicitParamDecl::CreateDeserialized(ASTContext &C,
Douglas Gregor72172e92012-01-05 21:55:30 +00004167 unsigned ID) {
Alexey Bataev56223232017-06-09 13:40:18 +00004168 return new (C, ID) ImplicitParamDecl(C, QualType(), ImplicitParamKind::Other);
Douglas Gregor72172e92012-01-05 21:55:30 +00004169}
4170
Sebastian Redl833ef452010-01-26 22:01:41 +00004171FunctionDecl *FunctionDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004172 SourceLocation StartLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004173 const DeclarationNameInfo &NameInfo,
4174 QualType T, TypeSourceInfo *TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00004175 StorageClass SC,
Richard Smithf7981722013-11-22 09:01:48 +00004176 bool isInlineSpecified,
Richard Smitha77a0a62011-08-15 21:04:07 +00004177 bool hasWrittenPrototype,
4178 bool isConstexprSpecified) {
Richard Smithf7981722013-11-22 09:01:48 +00004179 FunctionDecl *New =
Richard Smith053f6c62014-05-16 23:01:30 +00004180 new (C, DC) FunctionDecl(Function, C, DC, StartLoc, NameInfo, T, TInfo,
4181 SC, isInlineSpecified, isConstexprSpecified);
Sebastian Redl833ef452010-01-26 22:01:41 +00004182 New->HasWrittenPrototype = hasWrittenPrototype;
4183 return New;
4184}
4185
Douglas Gregor72172e92012-01-05 21:55:30 +00004186FunctionDecl *FunctionDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00004187 return new (C, ID) FunctionDecl(Function, C, nullptr, SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004188 DeclarationNameInfo(), QualType(), nullptr,
Richard Smithf7981722013-11-22 09:01:48 +00004189 SC_None, false, false);
Douglas Gregor72172e92012-01-05 21:55:30 +00004190}
4191
Sebastian Redl833ef452010-01-26 22:01:41 +00004192BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
Richard Smithf7981722013-11-22 09:01:48 +00004193 return new (C, DC) BlockDecl(DC, L);
Sebastian Redl833ef452010-01-26 22:01:41 +00004194}
4195
Douglas Gregor72172e92012-01-05 21:55:30 +00004196BlockDecl *BlockDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00004197 return new (C, ID) BlockDecl(nullptr, SourceLocation());
John McCall5e77d762013-04-16 07:28:30 +00004198}
4199
Chandler Carruth21c90602015-12-30 03:24:14 +00004200CapturedDecl::CapturedDecl(DeclContext *DC, unsigned NumParams)
4201 : Decl(Captured, DC, SourceLocation()), DeclContext(Captured),
4202 NumParams(NumParams), ContextParam(0), BodyAndNothrow(nullptr, false) {}
4203
Ben Langmuir37943a72013-05-03 19:00:33 +00004204CapturedDecl *CapturedDecl::Create(ASTContext &C, DeclContext *DC,
4205 unsigned NumParams) {
James Y Knight7a22b242015-08-06 20:26:32 +00004206 return new (C, DC, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams))
Richard Smithf7981722013-11-22 09:01:48 +00004207 CapturedDecl(DC, NumParams);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004208}
4209
Ben Langmuirce914fc2013-05-03 19:20:19 +00004210CapturedDecl *CapturedDecl::CreateDeserialized(ASTContext &C, unsigned ID,
Richard Smithf7981722013-11-22 09:01:48 +00004211 unsigned NumParams) {
James Y Knight7a22b242015-08-06 20:26:32 +00004212 return new (C, ID, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams))
Craig Topper36250ad2014-05-12 05:36:57 +00004213 CapturedDecl(nullptr, NumParams);
Ben Langmuirce914fc2013-05-03 19:20:19 +00004214}
4215
Chandler Carruth21c90602015-12-30 03:24:14 +00004216Stmt *CapturedDecl::getBody() const { return BodyAndNothrow.getPointer(); }
4217void CapturedDecl::setBody(Stmt *B) { BodyAndNothrow.setPointer(B); }
4218
4219bool CapturedDecl::isNothrow() const { return BodyAndNothrow.getInt(); }
4220void CapturedDecl::setNothrow(bool Nothrow) { BodyAndNothrow.setInt(Nothrow); }
4221
Sebastian Redl833ef452010-01-26 22:01:41 +00004222EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD,
4223 SourceLocation L,
4224 IdentifierInfo *Id, QualType T,
4225 Expr *E, const llvm::APSInt &V) {
Richard Smithf7981722013-11-22 09:01:48 +00004226 return new (C, CD) EnumConstantDecl(CD, L, Id, T, E, V);
Sebastian Redl833ef452010-01-26 22:01:41 +00004227}
4228
Douglas Gregor72172e92012-01-05 21:55:30 +00004229EnumConstantDecl *
4230EnumConstantDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00004231 return new (C, ID) EnumConstantDecl(nullptr, SourceLocation(), nullptr,
4232 QualType(), nullptr, llvm::APSInt());
Douglas Gregor72172e92012-01-05 21:55:30 +00004233}
4234
David Blaikie68e081d2011-12-20 02:48:34 +00004235void IndirectFieldDecl::anchor() { }
4236
Richard Smith9f951822016-01-06 22:49:11 +00004237IndirectFieldDecl::IndirectFieldDecl(ASTContext &C, DeclContext *DC,
4238 SourceLocation L, DeclarationName N,
David Majnemer59f77922016-06-24 04:05:48 +00004239 QualType T,
4240 MutableArrayRef<NamedDecl *> CH)
4241 : ValueDecl(IndirectField, DC, L, N, T), Chaining(CH.data()),
4242 ChainingSize(CH.size()) {
Richard Smith9f951822016-01-06 22:49:11 +00004243 // In C++, indirect field declarations conflict with tag declarations in the
4244 // same scope, so add them to IDNS_Tag so that tag redeclaration finds them.
4245 if (C.getLangOpts().CPlusPlus)
4246 IdentifierNamespace |= IDNS_Tag;
4247}
4248
Benjamin Kramer39593702010-11-21 14:11:41 +00004249IndirectFieldDecl *
4250IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,
David Majnemer59f77922016-06-24 04:05:48 +00004251 IdentifierInfo *Id, QualType T,
4252 llvm::MutableArrayRef<NamedDecl *> CH) {
4253 return new (C, DC) IndirectFieldDecl(C, DC, L, Id, T, CH);
Francois Pichet783dd6e2010-11-21 06:08:52 +00004254}
4255
Douglas Gregor72172e92012-01-05 21:55:30 +00004256IndirectFieldDecl *IndirectFieldDecl::CreateDeserialized(ASTContext &C,
4257 unsigned ID) {
Richard Smith9f951822016-01-06 22:49:11 +00004258 return new (C, ID) IndirectFieldDecl(C, nullptr, SourceLocation(),
David Majnemer59f77922016-06-24 04:05:48 +00004259 DeclarationName(), QualType(), None);
Douglas Gregor72172e92012-01-05 21:55:30 +00004260}
4261
Douglas Gregorbe996932010-09-01 20:41:53 +00004262SourceRange EnumConstantDecl::getSourceRange() const {
4263 SourceLocation End = getLocation();
4264 if (Init)
4265 End = Init->getLocEnd();
4266 return SourceRange(getLocation(), End);
4267}
4268
David Blaikie68e081d2011-12-20 02:48:34 +00004269void TypeDecl::anchor() { }
4270
Sebastian Redl833ef452010-01-26 22:01:41 +00004271TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnarab3185b02011-03-06 15:48:19 +00004272 SourceLocation StartLoc, SourceLocation IdLoc,
4273 IdentifierInfo *Id, TypeSourceInfo *TInfo) {
Richard Smith053f6c62014-05-16 23:01:30 +00004274 return new (C, DC) TypedefDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
Sebastian Redl833ef452010-01-26 22:01:41 +00004275}
4276
David Blaikie68e081d2011-12-20 02:48:34 +00004277void TypedefNameDecl::anchor() { }
4278
Richard Smith42413142015-05-15 20:05:43 +00004279TagDecl *TypedefNameDecl::getAnonDeclWithTypedefName(bool AnyRedecl) const {
4280 if (auto *TT = getTypeSourceInfo()->getType()->getAs<TagType>()) {
4281 auto *OwningTypedef = TT->getDecl()->getTypedefNameForAnonDecl();
4282 auto *ThisTypedef = this;
4283 if (AnyRedecl && OwningTypedef) {
4284 OwningTypedef = OwningTypedef->getCanonicalDecl();
4285 ThisTypedef = ThisTypedef->getCanonicalDecl();
4286 }
4287 if (OwningTypedef == ThisTypedef)
Richard Smitha5230222015-03-27 01:37:43 +00004288 return TT->getDecl();
Richard Smith42413142015-05-15 20:05:43 +00004289 }
Richard Smitha5230222015-03-27 01:37:43 +00004290
4291 return nullptr;
4292}
4293
Argyrios Kyrtzidis3b25c912017-03-21 16:56:02 +00004294bool TypedefNameDecl::isTransparentTagSlow() const {
4295 auto determineIsTransparent = [&]() {
4296 if (auto *TT = getUnderlyingType()->getAs<TagType>()) {
4297 if (auto *TD = TT->getDecl()) {
4298 if (TD->getName() != getName())
4299 return false;
4300 SourceLocation TTLoc = getLocation();
4301 SourceLocation TDLoc = TD->getLocation();
4302 if (!TTLoc.isMacroID() || !TDLoc.isMacroID())
4303 return false;
4304 SourceManager &SM = getASTContext().getSourceManager();
4305 return SM.getSpellingLoc(TTLoc) == SM.getSpellingLoc(TDLoc);
4306 }
4307 }
4308 return false;
4309 };
4310
4311 bool isTransparent = determineIsTransparent();
4312 CacheIsTransparentTag = 1;
4313 if (isTransparent)
4314 CacheIsTransparentTag |= 0x2;
4315 return isTransparent;
4316}
4317
Douglas Gregor72172e92012-01-05 21:55:30 +00004318TypedefDecl *TypedefDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00004319 return new (C, ID) TypedefDecl(C, nullptr, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004320 nullptr, nullptr);
Douglas Gregor72172e92012-01-05 21:55:30 +00004321}
4322
Richard Smithdda56e42011-04-15 14:24:37 +00004323TypeAliasDecl *TypeAliasDecl::Create(ASTContext &C, DeclContext *DC,
4324 SourceLocation StartLoc,
4325 SourceLocation IdLoc, IdentifierInfo *Id,
4326 TypeSourceInfo *TInfo) {
Richard Smith053f6c62014-05-16 23:01:30 +00004327 return new (C, DC) TypeAliasDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
Richard Smithdda56e42011-04-15 14:24:37 +00004328}
4329
Douglas Gregor72172e92012-01-05 21:55:30 +00004330TypeAliasDecl *TypeAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00004331 return new (C, ID) TypeAliasDecl(C, nullptr, SourceLocation(),
4332 SourceLocation(), nullptr, nullptr);
Douglas Gregor72172e92012-01-05 21:55:30 +00004333}
4334
Abramo Bagnaraea947882011-03-08 16:41:52 +00004335SourceRange TypedefDecl::getSourceRange() const {
4336 SourceLocation RangeEnd = getLocation();
4337 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
4338 if (typeIsPostfix(TInfo->getType()))
4339 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
4340 }
4341 return SourceRange(getLocStart(), RangeEnd);
4342}
4343
Richard Smithdda56e42011-04-15 14:24:37 +00004344SourceRange TypeAliasDecl::getSourceRange() const {
4345 SourceLocation RangeEnd = getLocStart();
4346 if (TypeSourceInfo *TInfo = getTypeSourceInfo())
4347 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
4348 return SourceRange(getLocStart(), RangeEnd);
4349}
4350
David Blaikie68e081d2011-12-20 02:48:34 +00004351void FileScopeAsmDecl::anchor() { }
4352
Sebastian Redl833ef452010-01-26 22:01:41 +00004353FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnara348823a2011-03-03 14:20:18 +00004354 StringLiteral *Str,
4355 SourceLocation AsmLoc,
4356 SourceLocation RParenLoc) {
Richard Smithf7981722013-11-22 09:01:48 +00004357 return new (C, DC) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc);
Sebastian Redl833ef452010-01-26 22:01:41 +00004358}
Douglas Gregorba345522011-12-02 23:23:56 +00004359
Richard Smithf7981722013-11-22 09:01:48 +00004360FileScopeAsmDecl *FileScopeAsmDecl::CreateDeserialized(ASTContext &C,
Douglas Gregor72172e92012-01-05 21:55:30 +00004361 unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00004362 return new (C, ID) FileScopeAsmDecl(nullptr, nullptr, SourceLocation(),
4363 SourceLocation());
Douglas Gregor72172e92012-01-05 21:55:30 +00004364}
4365
Michael Han84324352013-02-22 17:15:32 +00004366void EmptyDecl::anchor() {}
4367
4368EmptyDecl *EmptyDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
Richard Smithf7981722013-11-22 09:01:48 +00004369 return new (C, DC) EmptyDecl(DC, L);
Michael Han84324352013-02-22 17:15:32 +00004370}
4371
4372EmptyDecl *EmptyDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00004373 return new (C, ID) EmptyDecl(nullptr, SourceLocation());
Michael Han84324352013-02-22 17:15:32 +00004374}
4375
Douglas Gregorba345522011-12-02 23:23:56 +00004376//===----------------------------------------------------------------------===//
4377// ImportDecl Implementation
4378//===----------------------------------------------------------------------===//
4379
4380/// \brief Retrieve the number of module identifiers needed to name the given
4381/// module.
4382static unsigned getNumModuleIdentifiers(Module *Mod) {
4383 unsigned Result = 1;
4384 while (Mod->Parent) {
4385 Mod = Mod->Parent;
4386 ++Result;
4387 }
4388 return Result;
4389}
4390
Douglas Gregor22d09742012-01-03 18:04:46 +00004391ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
Douglas Gregorba345522011-12-02 23:23:56 +00004392 Module *Imported,
4393 ArrayRef<SourceLocation> IdentifierLocs)
Douglas Gregor22d09742012-01-03 18:04:46 +00004394 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, true),
Douglas Gregor0f2a3602011-12-03 00:30:27 +00004395 NextLocalImport()
Douglas Gregorba345522011-12-02 23:23:56 +00004396{
4397 assert(getNumModuleIdentifiers(Imported) == IdentifierLocs.size());
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00004398 auto *StoredLocs = getTrailingObjects<SourceLocation>();
James Y Knight7a22b242015-08-06 20:26:32 +00004399 std::uninitialized_copy(IdentifierLocs.begin(), IdentifierLocs.end(),
4400 StoredLocs);
Douglas Gregorba345522011-12-02 23:23:56 +00004401}
4402
Douglas Gregor22d09742012-01-03 18:04:46 +00004403ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
Douglas Gregorba345522011-12-02 23:23:56 +00004404 Module *Imported, SourceLocation EndLoc)
Douglas Gregor22d09742012-01-03 18:04:46 +00004405 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, false),
Douglas Gregor0f2a3602011-12-03 00:30:27 +00004406 NextLocalImport()
Douglas Gregorba345522011-12-02 23:23:56 +00004407{
James Y Knight7a22b242015-08-06 20:26:32 +00004408 *getTrailingObjects<SourceLocation>() = EndLoc;
Douglas Gregorba345522011-12-02 23:23:56 +00004409}
4410
Richard Smithf7981722013-11-22 09:01:48 +00004411ImportDecl *ImportDecl::Create(ASTContext &C, DeclContext *DC,
Douglas Gregor22d09742012-01-03 18:04:46 +00004412 SourceLocation StartLoc, Module *Imported,
Douglas Gregorba345522011-12-02 23:23:56 +00004413 ArrayRef<SourceLocation> IdentifierLocs) {
James Y Knight7a22b242015-08-06 20:26:32 +00004414 return new (C, DC,
4415 additionalSizeToAlloc<SourceLocation>(IdentifierLocs.size()))
Richard Smithf7981722013-11-22 09:01:48 +00004416 ImportDecl(DC, StartLoc, Imported, IdentifierLocs);
Douglas Gregorba345522011-12-02 23:23:56 +00004417}
4418
Richard Smithf7981722013-11-22 09:01:48 +00004419ImportDecl *ImportDecl::CreateImplicit(ASTContext &C, DeclContext *DC,
Douglas Gregor22d09742012-01-03 18:04:46 +00004420 SourceLocation StartLoc,
Richard Smithf7981722013-11-22 09:01:48 +00004421 Module *Imported,
Douglas Gregorba345522011-12-02 23:23:56 +00004422 SourceLocation EndLoc) {
James Y Knight7a22b242015-08-06 20:26:32 +00004423 ImportDecl *Import = new (C, DC, additionalSizeToAlloc<SourceLocation>(1))
4424 ImportDecl(DC, StartLoc, Imported, EndLoc);
Douglas Gregorba345522011-12-02 23:23:56 +00004425 Import->setImplicit();
4426 return Import;
4427}
4428
Douglas Gregor72172e92012-01-05 21:55:30 +00004429ImportDecl *ImportDecl::CreateDeserialized(ASTContext &C, unsigned ID,
4430 unsigned NumLocations) {
James Y Knight7a22b242015-08-06 20:26:32 +00004431 return new (C, ID, additionalSizeToAlloc<SourceLocation>(NumLocations))
Richard Smithf7981722013-11-22 09:01:48 +00004432 ImportDecl(EmptyShell());
Douglas Gregorba345522011-12-02 23:23:56 +00004433}
4434
4435ArrayRef<SourceLocation> ImportDecl::getIdentifierLocs() const {
4436 if (!ImportedAndComplete.getInt())
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00004437 return None;
Douglas Gregorba345522011-12-02 23:23:56 +00004438
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00004439 const auto *StoredLocs = getTrailingObjects<SourceLocation>();
Craig Topper5fc8fc22014-08-27 06:28:36 +00004440 return llvm::makeArrayRef(StoredLocs,
4441 getNumModuleIdentifiers(getImportedModule()));
Douglas Gregorba345522011-12-02 23:23:56 +00004442}
4443
4444SourceRange ImportDecl::getSourceRange() const {
4445 if (!ImportedAndComplete.getInt())
James Y Knight7a22b242015-08-06 20:26:32 +00004446 return SourceRange(getLocation(), *getTrailingObjects<SourceLocation>());
4447
Douglas Gregorba345522011-12-02 23:23:56 +00004448 return SourceRange(getLocation(), getIdentifierLocs().back());
4449}
Richard Smith8df390f2016-09-08 23:14:54 +00004450
4451//===----------------------------------------------------------------------===//
4452// ExportDecl Implementation
4453//===----------------------------------------------------------------------===//
4454
4455void ExportDecl::anchor() {}
4456
4457ExportDecl *ExportDecl::Create(ASTContext &C, DeclContext *DC,
4458 SourceLocation ExportLoc) {
4459 return new (C, DC) ExportDecl(DC, ExportLoc);
4460}
4461
4462ExportDecl *ExportDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
4463 return new (C, ID) ExportDecl(nullptr, SourceLocation());
4464}