blob: 3f9eaf28ef94750605cc11a0a090a54ab6f17689 [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) {
518 switch (D->getModuleOwnershipKind()) {
519 case Decl::ModuleOwnershipKind::Unowned:
520 case Decl::ModuleOwnershipKind::ModulePrivate:
521 return false;
522 case Decl::ModuleOwnershipKind::Visible:
523 case Decl::ModuleOwnershipKind::VisibleWhenImported:
524 if (auto *M = D->getOwningModule())
525 return M->Kind == Module::ModuleInterfaceUnit;
526 }
527 llvm_unreachable("unexpected module ownership kind");
528}
529
530static LinkageInfo getInternalLinkageFor(const NamedDecl *D) {
531 // Internal linkage declarations within a module interface unit are modeled
532 // as "module-internal linkage", which means that they have internal linkage
533 // formally but can be indirectly accessed from outside the module via inline
534 // functions and templates defined within the module.
535 if (auto *M = D->getOwningModule())
536 if (M->Kind == Module::ModuleInterfaceUnit)
537 return LinkageInfo(ModuleInternalLinkage, DefaultVisibility, false);
538
539 return LinkageInfo::internal();
540}
541
542static LinkageInfo getExternalLinkageFor(const NamedDecl *D) {
543 // C++ Modules TS [basic.link]/6.8:
544 // - A name declared at namespace scope that does not have internal linkage
545 // by the previous rules and that is introduced by a non-exported
546 // declaration has module linkage.
547 if (auto *M = D->getOwningModule())
548 if (M->Kind == Module::ModuleInterfaceUnit)
549 if (!isExportedFromModuleIntefaceUnit(D))
550 return LinkageInfo(ModuleLinkage, DefaultVisibility, false);
551
552 return LinkageInfo::external();
553}
554
George Burgess IV99db3ea2017-08-09 04:02:49 +0000555LinkageInfo
556LinkageComputer::getLVForNamespaceScopeDecl(const NamedDecl *D,
Richard Smithc95d2c52017-09-22 04:25:05 +0000557 LVComputationKind computation,
558 bool IgnoreVarTypeLinkage) {
Sebastian Redl50c68252010-08-31 00:36:30 +0000559 assert(D->getDeclContext()->getRedeclContext()->isFileContext() &&
Douglas Gregorf73b2822009-11-25 22:24:25 +0000560 "Not a name having namespace scope");
561 ASTContext &Context = D->getASTContext();
562
563 // C++ [basic.link]p3:
564 // A name having namespace scope (3.3.6) has internal linkage if it
565 // is the name of
566 // - an object, reference, function or function template that is
567 // explicitly declared static; or,
568 // (This bullet corresponds to C99 6.2.2p3.)
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000569 if (const auto *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregorf73b2822009-11-25 22:24:25 +0000570 // Explicitly declared static.
John McCall8e7d6562010-08-26 03:08:43 +0000571 if (Var->getStorageClass() == SC_Static)
Richard Smith1283e982017-07-07 20:04:28 +0000572 return getInternalLinkageFor(Var);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000573
Richard Smith62f19e72016-06-25 00:15:56 +0000574 // - a non-inline, non-volatile object or reference that is explicitly
575 // declared const or constexpr and neither explicitly declared extern
576 // nor previously declared to have external linkage; or (there is no
577 // equivalent in C99)
Richard Smith1283e982017-07-07 20:04:28 +0000578 // The C++ modules TS adds "non-exported" to this list.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000579 if (Context.getLangOpts().CPlusPlus &&
Richard Smithdc0ef452012-10-19 06:37:48 +0000580 Var->getType().isConstQualified() &&
Richard Smith62f19e72016-06-25 00:15:56 +0000581 !Var->getType().isVolatileQualified() &&
Richard Smith1283e982017-07-07 20:04:28 +0000582 !Var->isInline() &&
583 !isExportedFromModuleIntefaceUnit(Var)) {
Rafael Espindola985a3ab2013-04-03 19:22:20 +0000584 const VarDecl *PrevVar = Var->getPreviousDecl();
Rafael Espindola985a3ab2013-04-03 19:22:20 +0000585 if (PrevVar)
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000586 return getLVForDecl(PrevVar, computation);
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000587
588 if (Var->getStorageClass() != SC_Extern &&
Rafael Espindola327be3c2013-04-26 01:30:23 +0000589 Var->getStorageClass() != SC_PrivateExtern &&
Richard Smith03c05032014-02-17 23:34:47 +0000590 !isSingleLineLanguageLinkage(*Var))
Richard Smith1283e982017-07-07 20:04:28 +0000591 return getInternalLinkageFor(Var);
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000592 }
593
594 for (const VarDecl *PrevVar = Var->getPreviousDecl(); PrevVar;
595 PrevVar = PrevVar->getPreviousDecl()) {
596 if (PrevVar->getStorageClass() == SC_PrivateExtern &&
597 Var->getStorageClass() == SC_None)
George Burgess IV35cb4f82017-08-09 04:12:17 +0000598 return getDeclLinkageAndVisibility(PrevVar);
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000599 // Explicitly declared static.
600 if (PrevVar->getStorageClass() == SC_Static)
Richard Smith1283e982017-07-07 20:04:28 +0000601 return getInternalLinkageFor(Var);
Fariborz Jahanian8feee2d2011-06-16 20:14:50 +0000602 }
Alp Tokera2794f92014-01-22 07:29:52 +0000603 } else if (const FunctionDecl *Function = D->getAsFunction()) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000604 // C++ [temp]p4:
605 // A non-member function template can have internal linkage; any
606 // other template name shall have external linkage.
Douglas Gregorf73b2822009-11-25 22:24:25 +0000607
608 // Explicitly declared static.
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000609 if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
Richard Smith1283e982017-07-07 20:04:28 +0000610 return getInternalLinkageFor(Function);
David Majnemer18fac3b2014-12-10 22:58:14 +0000611 } else if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D)) {
612 // - a data member of an anonymous union.
613 const VarDecl *VD = IFD->getVarDecl();
614 assert(VD && "Expected a VarDecl in this IndirectFieldDecl!");
Richard Smithc95d2c52017-09-22 04:25:05 +0000615 return getLVForNamespaceScopeDecl(VD, computation, IgnoreVarTypeLinkage);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000616 }
David Majnemer0eb8bbd2013-10-23 20:52:43 +0000617 assert(!isa<FieldDecl>(D) && "Didn't expect a FieldDecl!");
Douglas Gregorf73b2822009-11-25 22:24:25 +0000618
Chandler Carruth9682a2fd2011-02-24 19:03:39 +0000619 if (D->isInAnonymousNamespace()) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000620 const auto *Var = dyn_cast<VarDecl>(D);
621 const auto *Func = dyn_cast<FunctionDecl>(D);
Richard Smithdf963a32017-09-22 22:21:44 +0000622 // FIXME: The check for extern "C" here is not justified by the standard
623 // wording, but we retain it from the pre-DR1113 model to avoid breaking
624 // code.
Richard Smith1283e982017-07-07 20:04:28 +0000625 //
626 // C++11 [basic.link]p4:
627 // An unnamed namespace or a namespace declared directly or indirectly
628 // within an unnamed namespace has internal linkage.
Rafael Espindola593537a2013-05-05 20:15:21 +0000629 if ((!Var || !isFirstInExternCContext(Var)) &&
630 (!Func || !isFirstInExternCContext(Func)))
Richard Smithdf963a32017-09-22 22:21:44 +0000631 return getInternalLinkageFor(D);
Chandler Carruth9682a2fd2011-02-24 19:03:39 +0000632 }
John McCallb7139c42010-10-28 04:18:25 +0000633
John McCall457a04e2010-10-22 21:05:15 +0000634 // Set up the defaults.
635
636 // C99 6.2.2p5:
637 // If the declaration of an identifier for an object has file
638 // scope and no storage-class specifier, its linkage is
639 // external.
Richard Smithdd8b5332017-09-04 05:37:53 +0000640 LinkageInfo LV = getExternalLinkageFor(D);
John McCallc273f242010-10-30 11:50:40 +0000641
John McCalld041a9b2013-02-20 01:54:26 +0000642 if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +0000643 if (Optional<Visibility> Vis = getExplicitVisibility(D, computation)) {
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000644 LV.mergeVisibility(*Vis, true);
Rafael Espindola78158af2012-04-16 18:46:26 +0000645 } else {
646 // If we're declared in a namespace with a visibility attribute,
John McCalldf25c432013-02-16 00:17:33 +0000647 // use that namespace's visibility, and it still counts as explicit.
Rafael Espindola78158af2012-04-16 18:46:26 +0000648 for (const DeclContext *DC = D->getDeclContext();
649 !isa<TranslationUnitDecl>(DC);
650 DC = DC->getParent()) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000651 const auto *ND = dyn_cast<NamespaceDecl>(DC);
Rafael Espindola78158af2012-04-16 18:46:26 +0000652 if (!ND) continue;
David Blaikie05785d12013-02-20 22:23:23 +0000653 if (Optional<Visibility> Vis = getExplicitVisibility(ND, computation)) {
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000654 LV.mergeVisibility(*Vis, true);
Rafael Espindola78158af2012-04-16 18:46:26 +0000655 break;
656 }
657 }
658 }
Rafael Espindola78158af2012-04-16 18:46:26 +0000659
John McCalldf25c432013-02-16 00:17:33 +0000660 // Add in global settings if the above didn't give us direct visibility.
Rafael Espindola4a5da442013-02-27 02:56:45 +0000661 if (!LV.isVisibilityExplicit()) {
John McCallb4a99d32013-02-19 01:57:35 +0000662 // Use global type/value visibility as appropriate.
Richard Smithfbe7b462017-09-22 02:22:32 +0000663 Visibility globalVisibility =
664 computation.isValueVisibility()
665 ? Context.getLangOpts().getValueVisibilityMode()
666 : Context.getLangOpts().getTypeVisibilityMode();
John McCallb4a99d32013-02-19 01:57:35 +0000667 LV.mergeVisibility(globalVisibility, /*explicit*/ false);
John McCalldf25c432013-02-16 00:17:33 +0000668
669 // If we're paying attention to global visibility, apply
670 // -finline-visibility-hidden if this is an inline method.
671 if (useInlineVisibilityHidden(D))
672 LV.mergeVisibility(HiddenVisibility, true);
673 }
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000674 }
Rafael Espindolaaf690f52012-04-19 02:55:01 +0000675
Douglas Gregorf73b2822009-11-25 22:24:25 +0000676 // C++ [basic.link]p4:
John McCall457a04e2010-10-22 21:05:15 +0000677
Douglas Gregorf73b2822009-11-25 22:24:25 +0000678 // A name having namespace scope has external linkage if it is the
679 // name of
680 //
681 // - an object or reference, unless it has internal linkage; or
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000682 if (const auto *Var = dyn_cast<VarDecl>(D)) {
John McCall37bb6c92010-10-29 22:22:43 +0000683 // GCC applies the following optimization to variables and static
684 // data members, but not to functions:
685 //
John McCall457a04e2010-10-22 21:05:15 +0000686 // Modify the variable's LV by the LV of its type unless this is
687 // C or extern "C". This follows from [basic.link]p9:
688 // A type without linkage shall not be used as the type of a
689 // variable or function with external linkage unless
690 // - the entity has C language linkage, or
691 // - the entity is declared within an unnamed namespace, or
692 // - the entity is not used or is defined in the same
693 // translation unit.
694 // and [basic.link]p10:
695 // ...the types specified by all declarations referring to a
696 // given variable or function shall be identical...
697 // C does not have an equivalent rule.
698 //
John McCall5fe84122010-10-26 04:59:26 +0000699 // Ignore this if we've got an explicit attribute; the user
700 // probably knows what they're doing.
701 //
John McCall457a04e2010-10-22 21:05:15 +0000702 // Note that we don't want to make the variable non-external
703 // because of this, but unique-external linkage suits us.
Richard Smithc95d2c52017-09-22 04:25:05 +0000704 if (Context.getLangOpts().CPlusPlus && !isFirstInExternCContext(Var) &&
705 !IgnoreVarTypeLinkage) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000706 LinkageInfo TypeLV = getLVForType(*Var->getType(), computation);
Richard Smith405e2db2017-09-20 07:22:00 +0000707 if (!isExternallyVisible(TypeLV.getLinkage()))
John McCallc273f242010-10-30 11:50:40 +0000708 return LinkageInfo::uniqueExternal();
Rafael Espindola4a5da442013-02-27 02:56:45 +0000709 if (!LV.isVisibilityExplicit())
John McCalldf25c432013-02-16 00:17:33 +0000710 LV.mergeVisibility(TypeLV);
John McCall37bb6c92010-10-29 22:22:43 +0000711 }
712
John McCall23032652010-11-02 18:38:13 +0000713 if (Var->getStorageClass() == SC_PrivateExtern)
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000714 LV.mergeVisibility(HiddenVisibility, true);
John McCall23032652010-11-02 18:38:13 +0000715
Rafael Espindolad5ed0332012-11-12 04:10:23 +0000716 // Note that Sema::MergeVarDecl already takes care of implementing
717 // C99 6.2.2p4 and propagating the visibility attribute, so we don't have
718 // to do it here.
Douglas Gregorf73b2822009-11-25 22:24:25 +0000719
Larisse Voufo5899e192014-07-02 23:08:34 +0000720 // As per function and class template specializations (below),
721 // consider LV for the template and template arguments. We're at file
722 // scope, so we do not need to worry about nested specializations.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000723 if (const auto *spec = dyn_cast<VarTemplateSpecializationDecl>(Var)) {
Larisse Voufo5899e192014-07-02 23:08:34 +0000724 mergeTemplateLV(LV, spec, computation);
725 }
726
Douglas Gregorf73b2822009-11-25 22:24:25 +0000727 // - a function, unless it has internal linkage; or
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000728 } else if (const auto *Function = dyn_cast<FunctionDecl>(D)) {
John McCall2efaf112010-10-28 07:07:52 +0000729 // In theory, we can modify the function's LV by the LV of its
730 // type unless it has C linkage (see comment above about variables
731 // for justification). In practice, GCC doesn't do this, so it's
732 // just too painful to make work.
John McCall457a04e2010-10-22 21:05:15 +0000733
John McCall23032652010-11-02 18:38:13 +0000734 if (Function->getStorageClass() == SC_PrivateExtern)
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000735 LV.mergeVisibility(HiddenVisibility, true);
John McCall23032652010-11-02 18:38:13 +0000736
Rafael Espindolaa508c5d2012-11-21 02:47:19 +0000737 // Note that Sema::MergeCompatibleFunctionDecls already takes care of
738 // merging storage classes and visibility attributes, so we don't have to
739 // look at previous decls in here.
Douglas Gregorf73b2822009-11-25 22:24:25 +0000740
John McCallf768aa72011-02-10 06:50:24 +0000741 // In C++, then if the type of the function uses a type with
742 // unique-external linkage, it's not legally usable from outside
743 // this translation unit. However, we should use the C linkage
744 // rules instead for extern "C" declarations.
Richard Smithc95d2c52017-09-22 04:25:05 +0000745 if (Context.getLangOpts().CPlusPlus && !Function->isInExternCContext()) {
746 // Only look at the type-as-written. Otherwise, deducing the return type
747 // of a function could change its linkage.
Richard Smith50f4afc2013-05-12 23:17:59 +0000748 QualType TypeAsWritten = Function->getType();
749 if (TypeSourceInfo *TSI = Function->getTypeSourceInfo())
750 TypeAsWritten = TSI->getType();
Richard Smith405e2db2017-09-20 07:22:00 +0000751 if (!isExternallyVisible(TypeAsWritten->getLinkage()))
Richard Smith50f4afc2013-05-12 23:17:59 +0000752 return LinkageInfo::uniqueExternal();
753 }
John McCallf768aa72011-02-10 06:50:24 +0000754
John McCall5f46c482013-02-21 23:42:58 +0000755 // Consider LV from the template and the template arguments.
756 // We're at file scope, so we do not need to worry about nested
757 // specializations.
John McCallb8c604a2011-06-27 23:06:04 +0000758 if (FunctionTemplateSpecializationInfo *specInfo
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000759 = Function->getTemplateSpecializationInfo()) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000760 mergeTemplateLV(LV, Function, specInfo, computation);
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000761 }
762
Douglas Gregorf73b2822009-11-25 22:24:25 +0000763 // - a named class (Clause 9), or an unnamed class defined in a
764 // typedef declaration in which the class has the typedef name
765 // for linkage purposes (7.1.3); or
766 // - a named enumeration (7.2), or an unnamed enumeration
767 // defined in a typedef declaration in which the enumeration
768 // has the typedef name for linkage purposes (7.1.3); or
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000769 } else if (const auto *Tag = dyn_cast<TagDecl>(D)) {
John McCall457a04e2010-10-22 21:05:15 +0000770 // Unnamed tags have no linkage.
John McCall5ea95772013-03-09 00:54:27 +0000771 if (!Tag->hasNameForLinkage())
John McCallc273f242010-10-30 11:50:40 +0000772 return LinkageInfo::none();
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000773
John McCall457a04e2010-10-22 21:05:15 +0000774 // If this is a class template specialization, consider the
John McCall5f46c482013-02-21 23:42:58 +0000775 // linkage of the template and template arguments. We're at file
776 // scope, so we do not need to worry about nested specializations.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000777 if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) {
John McCalldf25c432013-02-16 00:17:33 +0000778 mergeTemplateLV(LV, spec, computation);
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000779 }
Douglas Gregorf73b2822009-11-25 22:24:25 +0000780
781 // - an enumerator belonging to an enumeration with external linkage;
John McCall457a04e2010-10-22 21:05:15 +0000782 } else if (isa<EnumConstantDecl>(D)) {
Rafael Espindola46cb6f12012-04-21 23:28:21 +0000783 LinkageInfo EnumLV = getLVForDecl(cast<NamedDecl>(D->getDeclContext()),
John McCalldf25c432013-02-16 00:17:33 +0000784 computation);
Rafael Espindolab97e8962013-05-27 14:14:42 +0000785 if (!isExternalFormalLinkage(EnumLV.getLinkage()))
John McCallc273f242010-10-30 11:50:40 +0000786 return LinkageInfo::none();
787 LV.merge(EnumLV);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000788
789 // - a template, unless it is a function template that has
790 // internal linkage (Clause 14);
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000791 } else if (const auto *temp = dyn_cast<TemplateDecl>(D)) {
John McCalld041a9b2013-02-20 01:54:26 +0000792 bool considerVisibility = !hasExplicitVisibilityAlready(computation);
John McCalldf25c432013-02-16 00:17:33 +0000793 LinkageInfo tempLV =
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000794 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
John McCalldf25c432013-02-16 00:17:33 +0000795 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
796
Douglas Gregorf73b2822009-11-25 22:24:25 +0000797 // - a namespace (7.3), unless it is declared within an unnamed
798 // namespace.
Richard Smith1283e982017-07-07 20:04:28 +0000799 //
800 // We handled names in anonymous namespaces above.
801 } else if (isa<NamespaceDecl>(D)) {
John McCall457a04e2010-10-22 21:05:15 +0000802 return LV;
Douglas Gregorf73b2822009-11-25 22:24:25 +0000803
John McCall457a04e2010-10-22 21:05:15 +0000804 // By extension, we assign external linkage to Objective-C
805 // interfaces.
806 } else if (isa<ObjCInterfaceDecl>(D)) {
807 // fallout
808
Richard Smith97135cc2015-11-12 22:19:45 +0000809 } else if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
810 // A typedef declaration has linkage if it gives a type a name for
811 // linkage purposes.
812 if (!TD->getAnonDeclWithTypedefName(/*AnyRedecl*/true))
813 return LinkageInfo::none();
814
John McCall457a04e2010-10-22 21:05:15 +0000815 // Everything not covered here has no linkage.
816 } else {
John McCallc273f242010-10-30 11:50:40 +0000817 return LinkageInfo::none();
John McCall457a04e2010-10-22 21:05:15 +0000818 }
819
820 // If we ended up with non-external linkage, visibility should
821 // always be default.
Rafael Espindola4a5da442013-02-27 02:56:45 +0000822 if (LV.getLinkage() != ExternalLinkage)
823 return LinkageInfo(LV.getLinkage(), DefaultVisibility, false);
John McCall457a04e2010-10-22 21:05:15 +0000824
John McCall457a04e2010-10-22 21:05:15 +0000825 return LV;
Douglas Gregorf73b2822009-11-25 22:24:25 +0000826}
827
George Burgess IV99db3ea2017-08-09 04:02:49 +0000828LinkageInfo
829LinkageComputer::getLVForClassMember(const NamedDecl *D,
Richard Smithc95d2c52017-09-22 04:25:05 +0000830 LVComputationKind computation,
831 bool IgnoreVarTypeLinkage) {
John McCall457a04e2010-10-22 21:05:15 +0000832 // Only certain class members have linkage. Note that fields don't
833 // really have linkage, but it's convenient to say they do for the
834 // purposes of calculating linkage of pointer-to-data-member
835 // template arguments.
Richard Smith26d11be2014-01-08 01:51:59 +0000836 //
837 // Templates also don't officially have linkage, but since we ignore
838 // the C++ standard and look at template arguments when determining
839 // linkage and visibility of a template specialization, we might hit
840 // a template template argument that way. If we do, we need to
841 // consider its linkage.
John McCall8823c652010-08-13 08:35:10 +0000842 if (!(isa<CXXMethodDecl>(D) ||
843 isa<VarDecl>(D) ||
John McCall457a04e2010-10-22 21:05:15 +0000844 isa<FieldDecl>(D) ||
David Majnemer0eb8bbd2013-10-23 20:52:43 +0000845 isa<IndirectFieldDecl>(D) ||
Richard Smith26d11be2014-01-08 01:51:59 +0000846 isa<TagDecl>(D) ||
847 isa<TemplateDecl>(D)))
John McCallc273f242010-10-30 11:50:40 +0000848 return LinkageInfo::none();
John McCall8823c652010-08-13 08:35:10 +0000849
John McCall07072662010-11-02 01:45:15 +0000850 LinkageInfo LV;
851
John McCall07072662010-11-02 01:45:15 +0000852 // If we have an explicit visibility attribute, merge that in.
John McCalld041a9b2013-02-20 01:54:26 +0000853 if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +0000854 if (Optional<Visibility> Vis = getExplicitVisibility(D, computation))
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000855 LV.mergeVisibility(*Vis, true);
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000856 // If we're paying attention to global visibility, apply
857 // -finline-visibility-hidden if this is an inline method.
858 //
859 // Note that we do this before merging information about
860 // the class visibility.
Rafael Espindola4a5da442013-02-27 02:56:45 +0000861 if (!LV.isVisibilityExplicit() && useInlineVisibilityHidden(D))
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000862 LV.mergeVisibility(HiddenVisibility, true);
John McCall07072662010-11-02 01:45:15 +0000863 }
Rafael Espindola53cf2192012-04-19 05:50:08 +0000864
865 // If this class member has an explicit visibility attribute, the only
866 // thing that can change its visibility is the template arguments, so
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000867 // only look for them when processing the class.
John McCalld041a9b2013-02-20 01:54:26 +0000868 LVComputationKind classComputation = computation;
Rafael Espindola4a5da442013-02-27 02:56:45 +0000869 if (LV.isVisibilityExplicit())
John McCalld041a9b2013-02-20 01:54:26 +0000870 classComputation = withExplicitVisibilityAlready(computation);
Rafael Espindola505a7c82012-04-16 18:25:01 +0000871
John McCall5f46c482013-02-21 23:42:58 +0000872 LinkageInfo classLV =
873 getLVForDecl(cast<RecordDecl>(D->getDeclContext()), classComputation);
John McCall8823c652010-08-13 08:35:10 +0000874 // If the class already has unique-external linkage, we can't improve.
Rafael Espindola4a5da442013-02-27 02:56:45 +0000875 if (classLV.getLinkage() == UniqueExternalLinkage)
John McCallc273f242010-10-30 11:50:40 +0000876 return LinkageInfo::uniqueExternal();
John McCall8823c652010-08-13 08:35:10 +0000877
Rafael Espindolae6190db2013-05-28 02:22:10 +0000878 if (!isExternallyVisible(classLV.getLinkage()))
879 return LinkageInfo::none();
880
881
John McCall5f46c482013-02-21 23:42:58 +0000882 // Otherwise, don't merge in classLV yet, because in certain cases
883 // we need to completely ignore the visibility from it.
884
885 // Specifically, if this decl exists and has an explicit attribute.
Craig Topper36250ad2014-05-12 05:36:57 +0000886 const NamedDecl *explicitSpecSuppressor = nullptr;
John McCall5f46c482013-02-21 23:42:58 +0000887
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000888 if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
Richard Smithc95d2c52017-09-22 04:25:05 +0000889 // Only look at the type-as-written. Otherwise, deducing the return type
890 // of a function could change its linkage.
891 QualType TypeAsWritten = MD->getType();
892 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
893 TypeAsWritten = TSI->getType();
894 if (!isExternallyVisible(TypeAsWritten->getLinkage()))
895 return LinkageInfo::uniqueExternal();
896
John McCall457a04e2010-10-22 21:05:15 +0000897 // If this is a method template specialization, use the linkage for
898 // the template parameters and arguments.
John McCallb8c604a2011-06-27 23:06:04 +0000899 if (FunctionTemplateSpecializationInfo *spec
John McCall8823c652010-08-13 08:35:10 +0000900 = MD->getTemplateSpecializationInfo()) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000901 mergeTemplateLV(LV, MD, spec, computation);
John McCall5f46c482013-02-21 23:42:58 +0000902 if (spec->isExplicitSpecialization()) {
903 explicitSpecSuppressor = MD;
904 } else if (isExplicitMemberSpecialization(spec->getTemplate())) {
905 explicitSpecSuppressor = spec->getTemplate()->getTemplatedDecl();
906 }
907 } else if (isExplicitMemberSpecialization(MD)) {
908 explicitSpecSuppressor = MD;
John McCalle6e622e2010-11-01 01:29:57 +0000909 }
John McCall457a04e2010-10-22 21:05:15 +0000910
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000911 } else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
912 if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
John McCalldf25c432013-02-16 00:17:33 +0000913 mergeTemplateLV(LV, spec, computation);
John McCall5f46c482013-02-21 23:42:58 +0000914 if (spec->isExplicitSpecialization()) {
915 explicitSpecSuppressor = spec;
916 } else {
917 const ClassTemplateDecl *temp = spec->getSpecializedTemplate();
918 if (isExplicitMemberSpecialization(temp)) {
919 explicitSpecSuppressor = temp->getTemplatedDecl();
920 }
921 }
922 } else if (isExplicitMemberSpecialization(RD)) {
923 explicitSpecSuppressor = RD;
John McCall37bb6c92010-10-29 22:22:43 +0000924 }
925
John McCall37bb6c92010-10-29 22:22:43 +0000926 // Static data members.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000927 } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
928 if (const auto *spec = dyn_cast<VarTemplateSpecializationDecl>(VD))
Larisse Voufo5899e192014-07-02 23:08:34 +0000929 mergeTemplateLV(LV, spec, computation);
930
John McCall36cd5cc2010-10-30 09:18:49 +0000931 // Modify the variable's linkage by its type, but ignore the
932 // type's visibility unless it's a definition.
Richard Smithc95d2c52017-09-22 04:25:05 +0000933 if (!IgnoreVarTypeLinkage) {
934 LinkageInfo typeLV = getLVForType(*VD->getType(), computation);
935 // FIXME: If the type's linkage is not externally visible, we can
936 // give this static data member UniqueExternalLinkage.
937 if (!LV.isVisibilityExplicit() && !classLV.isVisibilityExplicit())
938 LV.mergeVisibility(typeLV);
939 LV.mergeExternalVisibility(typeLV);
940 }
John McCall5f46c482013-02-21 23:42:58 +0000941
942 if (isExplicitMemberSpecialization(VD)) {
943 explicitSpecSuppressor = VD;
944 }
John McCalldf25c432013-02-16 00:17:33 +0000945
946 // Template members.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000947 } else if (const auto *temp = dyn_cast<TemplateDecl>(D)) {
John McCalldf25c432013-02-16 00:17:33 +0000948 bool considerVisibility =
Rafael Espindola4a5da442013-02-27 02:56:45 +0000949 (!LV.isVisibilityExplicit() &&
950 !classLV.isVisibilityExplicit() &&
John McCalld041a9b2013-02-20 01:54:26 +0000951 !hasExplicitVisibilityAlready(computation));
John McCalldf25c432013-02-16 00:17:33 +0000952 LinkageInfo tempLV =
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000953 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
John McCalldf25c432013-02-16 00:17:33 +0000954 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
John McCall5f46c482013-02-21 23:42:58 +0000955
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000956 if (const auto *redeclTemp = dyn_cast<RedeclarableTemplateDecl>(temp)) {
John McCall5f46c482013-02-21 23:42:58 +0000957 if (isExplicitMemberSpecialization(redeclTemp)) {
958 explicitSpecSuppressor = temp->getTemplatedDecl();
959 }
960 }
John McCall37bb6c92010-10-29 22:22:43 +0000961 }
962
John McCall5f46c482013-02-21 23:42:58 +0000963 // We should never be looking for an attribute directly on a template.
964 assert(!explicitSpecSuppressor || !isa<TemplateDecl>(explicitSpecSuppressor));
965
966 // If this member is an explicit member specialization, and it has
967 // an explicit attribute, ignore visibility from the parent.
968 bool considerClassVisibility = true;
969 if (explicitSpecSuppressor &&
Rafael Espindola4a5da442013-02-27 02:56:45 +0000970 // optimization: hasDVA() is true only with explicit visibility.
971 LV.isVisibilityExplicit() &&
972 classLV.getVisibility() != DefaultVisibility &&
John McCall5f46c482013-02-21 23:42:58 +0000973 hasDirectVisibilityAttribute(explicitSpecSuppressor, computation)) {
974 considerClassVisibility = false;
975 }
976
977 // Finally, merge in information from the class.
978 LV.mergeMaybeWithVisibility(classLV, considerClassVisibility);
John McCall457a04e2010-10-22 21:05:15 +0000979 return LV;
John McCall8823c652010-08-13 08:35:10 +0000980}
981
David Blaikie68e081d2011-12-20 02:48:34 +0000982void NamedDecl::anchor() { }
983
Rafael Espindola0e0d0092013-03-14 03:07:35 +0000984bool NamedDecl::isLinkageValid() const {
Rafael Espindola50df3a02013-05-25 17:16:20 +0000985 if (!hasCachedLinkage())
Rafael Espindola0e0d0092013-03-14 03:07:35 +0000986 return true;
John McCalld396b972011-02-08 19:01:05 +0000987
Richard Smithfbe7b462017-09-22 02:22:32 +0000988 Linkage L = LinkageComputer{}
989 .computeLVForDecl(this, LVComputationKind::forLinkageOnly())
990 .getLinkage();
George Burgess IV99db3ea2017-08-09 04:02:49 +0000991 return L == getCachedLinkage();
John McCalld396b972011-02-08 19:01:05 +0000992}
993
Fariborz Jahanian6485fe42014-09-09 23:10:54 +0000994ObjCStringFormatFamily NamedDecl::getObjCFStringFormattingFamily() const {
995 StringRef name = getName();
996 if (name.empty()) return SFF_None;
997
998 if (name.front() == 'C')
999 if (name == "CFStringCreateWithFormat" ||
1000 name == "CFStringCreateWithFormatAndArguments" ||
1001 name == "CFStringAppendFormat" ||
1002 name == "CFStringAppendFormatAndArguments")
1003 return SFF_CFString;
1004 return SFF_None;
1005}
1006
Rafael Espindola3ae00052013-05-13 00:12:11 +00001007Linkage NamedDecl::getLinkageInternal() const {
John McCalld041a9b2013-02-20 01:54:26 +00001008 // We don't care about visibility here, so ask for the cheapest
1009 // possible visibility analysis.
Richard Smithfbe7b462017-09-22 02:22:32 +00001010 return LinkageComputer{}
1011 .getLVForDecl(this, LVComputationKind::forLinkageOnly())
1012 .getLinkage();
Douglas Gregorbf62d642010-12-06 18:36:25 +00001013}
1014
John McCallc273f242010-10-30 11:50:40 +00001015LinkageInfo NamedDecl::getLinkageAndVisibility() const {
George Burgess IV99db3ea2017-08-09 04:02:49 +00001016 return LinkageComputer{}.getDeclLinkageAndVisibility(this);
John McCall033caa52010-10-29 00:29:13 +00001017}
Ted Kremenek926d8602010-04-20 23:15:35 +00001018
Rafael Espindola9ad61122013-11-26 16:09:08 +00001019static Optional<Visibility>
1020getExplicitVisibilityAux(const NamedDecl *ND,
1021 NamedDecl::ExplicitVisibilityKind kind,
1022 bool IsMostRecent) {
1023 assert(!IsMostRecent || ND == ND->getMostRecentDecl());
1024
Rafael Espindola3a52c442013-02-26 19:33:14 +00001025 // Check the declaration itself first.
Rafael Espindola9ad61122013-11-26 16:09:08 +00001026 if (Optional<Visibility> V = getVisibilityOf(ND, kind))
Rafael Espindola3a52c442013-02-26 19:33:14 +00001027 return V;
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001028
Rafael Espindola3a52c442013-02-26 19:33:14 +00001029 // If this is a member class of a specialization of a class template
1030 // and the corresponding decl has explicit visibility, use that.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001031 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND)) {
Rafael Espindola3a52c442013-02-26 19:33:14 +00001032 CXXRecordDecl *InstantiatedFrom = RD->getInstantiatedFromMemberClass();
1033 if (InstantiatedFrom)
1034 return getVisibilityOf(InstantiatedFrom, kind);
1035 }
1036
1037 // If there wasn't explicit visibility there, and this is a
1038 // specialization of a class template, check for visibility
1039 // on the pattern.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001040 if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(ND))
Rafael Espindola3a52c442013-02-26 19:33:14 +00001041 return getVisibilityOf(spec->getSpecializedTemplate()->getTemplatedDecl(),
1042 kind);
1043
1044 // Use the most recent declaration.
Rafael Espindola7ab1ce02013-12-08 01:13:22 +00001045 if (!IsMostRecent && !isa<NamespaceDecl>(ND)) {
Rafael Espindola9ad61122013-11-26 16:09:08 +00001046 const NamedDecl *MostRecent = ND->getMostRecentDecl();
1047 if (MostRecent != ND)
1048 return getExplicitVisibilityAux(MostRecent, kind, true);
1049 }
Rafael Espindola3a52c442013-02-26 19:33:14 +00001050
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001051 if (const auto *Var = dyn_cast<VarDecl>(ND)) {
Rafael Espindola96e68242012-05-16 02:10:38 +00001052 if (Var->isStaticDataMember()) {
1053 VarDecl *InstantiatedFrom = Var->getInstantiatedFromStaticDataMember();
1054 if (InstantiatedFrom)
John McCalld041a9b2013-02-20 01:54:26 +00001055 return getVisibilityOf(InstantiatedFrom, kind);
Rafael Espindola96e68242012-05-16 02:10:38 +00001056 }
1057
David Majnemer35b02bc2014-04-29 07:32:26 +00001058 if (const auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(Var))
1059 return getVisibilityOf(VTSD->getSpecializedTemplate()->getTemplatedDecl(),
1060 kind);
1061
David Blaikie7a30dc52013-02-21 01:47:18 +00001062 return None;
Rafael Espindola96e68242012-05-16 02:10:38 +00001063 }
Rafael Espindola3a52c442013-02-26 19:33:14 +00001064 // Also handle function template specializations.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001065 if (const auto *fn = dyn_cast<FunctionDecl>(ND)) {
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001066 // If the function is a specialization of a template with an
1067 // explicit visibility attribute, use that.
1068 if (FunctionTemplateSpecializationInfo *templateInfo
1069 = fn->getTemplateSpecializationInfo())
John McCalld041a9b2013-02-20 01:54:26 +00001070 return getVisibilityOf(templateInfo->getTemplate()->getTemplatedDecl(),
1071 kind);
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001072
Rafael Espindola8093fdf2012-02-23 04:17:32 +00001073 // If the function is a member of a specialization of a class template
1074 // and the corresponding decl has explicit visibility, use that.
1075 FunctionDecl *InstantiatedFrom = fn->getInstantiatedFromMemberFunction();
1076 if (InstantiatedFrom)
John McCalld041a9b2013-02-20 01:54:26 +00001077 return getVisibilityOf(InstantiatedFrom, kind);
Rafael Espindola8093fdf2012-02-23 04:17:32 +00001078
David Blaikie7a30dc52013-02-21 01:47:18 +00001079 return None;
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001080 }
1081
Rafael Espindolafb4263f2012-07-31 19:02:02 +00001082 // The visibility of a template is stored in the templated decl.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001083 if (const auto *TD = dyn_cast<TemplateDecl>(ND))
John McCalld041a9b2013-02-20 01:54:26 +00001084 return getVisibilityOf(TD->getTemplatedDecl(), kind);
Rafael Espindolafb4263f2012-07-31 19:02:02 +00001085
David Blaikie7a30dc52013-02-21 01:47:18 +00001086 return None;
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001087}
1088
Rafael Espindola9ad61122013-11-26 16:09:08 +00001089Optional<Visibility>
1090NamedDecl::getExplicitVisibility(ExplicitVisibilityKind kind) const {
1091 return getExplicitVisibilityAux(this, kind, false);
1092}
1093
George Burgess IV99db3ea2017-08-09 04:02:49 +00001094LinkageInfo LinkageComputer::getLVForClosure(const DeclContext *DC,
1095 Decl *ContextDecl,
1096 LVComputationKind computation) {
Eli Friedman7e346a82013-07-01 20:22:57 +00001097 // This lambda has its linkage/visibility determined by its owner.
Richard Smithc95d2c52017-09-22 04:25:05 +00001098 const NamedDecl *Owner;
1099 if (!ContextDecl)
1100 Owner = dyn_cast<NamedDecl>(DC);
1101 else if (isa<ParmVarDecl>(ContextDecl))
1102 Owner =
1103 dyn_cast<NamedDecl>(ContextDecl->getDeclContext()->getRedeclContext());
1104 else
1105 Owner = cast<NamedDecl>(ContextDecl);
1106
Richard Smithc95d2c52017-09-22 04:25:05 +00001107 if (!Owner)
Richard Smith7ff83042017-09-22 04:33:20 +00001108 return LinkageInfo::none();
Richard Smithc95d2c52017-09-22 04:25:05 +00001109
1110 // If the owner has a deduced type, we need to skip querying the linkage and
1111 // visibility of that type, because it might involve this closure type. The
1112 // only effect of this is that we might give a lambda VisibleNoLinkage rather
1113 // than NoLinkage when we don't strictly need to, which is benign.
1114 auto *VD = dyn_cast<VarDecl>(Owner);
Richard Smith7ff83042017-09-22 04:33:20 +00001115 LinkageInfo OwnerLV =
Richard Smithc95d2c52017-09-22 04:25:05 +00001116 VD && VD->getType()->getContainedDeducedType()
1117 ? computeLVForDecl(Owner, computation, /*IgnoreVarTypeLinkage*/true)
1118 : getLVForDecl(Owner, computation);
1119
Richard Smith7ff83042017-09-22 04:33:20 +00001120 // A lambda never formally has linkage. But if the owner is externally
1121 // visible, then the lambda is too. We apply the same rules to blocks.
1122 if (!isExternallyVisible(OwnerLV.getLinkage()))
1123 return LinkageInfo::none();
1124 return LinkageInfo(VisibleNoLinkage, OwnerLV.getVisibility(),
1125 OwnerLV.isVisibilityExplicit());
Eli Friedman7e346a82013-07-01 20:22:57 +00001126}
1127
George Burgess IV99db3ea2017-08-09 04:02:49 +00001128LinkageInfo LinkageComputer::getLVForLocalDecl(const NamedDecl *D,
1129 LVComputationKind computation) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001130 if (const auto *Function = dyn_cast<FunctionDecl>(D)) {
John McCalldf25c432013-02-16 00:17:33 +00001131 if (Function->isInAnonymousNamespace() &&
Rafael Espindola593537a2013-05-05 20:15:21 +00001132 !Function->isInExternCContext())
Richard Smithdf963a32017-09-22 22:21:44 +00001133 return getInternalLinkageFor(Function);
John McCalldf25c432013-02-16 00:17:33 +00001134
1135 // This is a "void f();" which got merged with a file static.
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001136 if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
Richard Smith1283e982017-07-07 20:04:28 +00001137 return getInternalLinkageFor(Function);
John McCalldf25c432013-02-16 00:17:33 +00001138
1139 LinkageInfo LV;
John McCalld041a9b2013-02-20 01:54:26 +00001140 if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +00001141 if (Optional<Visibility> Vis =
1142 getExplicitVisibility(Function, computation))
John McCalldf25c432013-02-16 00:17:33 +00001143 LV.mergeVisibility(*Vis, true);
1144 }
1145
1146 // Note that Sema::MergeCompatibleFunctionDecls already takes care of
1147 // merging storage classes and visibility attributes, so we don't have to
1148 // look at previous decls in here.
1149
1150 return LV;
1151 }
1152
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001153 if (const auto *Var = dyn_cast<VarDecl>(D)) {
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001154 if (Var->hasExternalStorage()) {
Rafael Espindola593537a2013-05-05 20:15:21 +00001155 if (Var->isInAnonymousNamespace() && !Var->isInExternCContext())
Richard Smithdf963a32017-09-22 22:21:44 +00001156 return getInternalLinkageFor(Var);
John McCalldf25c432013-02-16 00:17:33 +00001157
John McCalldf25c432013-02-16 00:17:33 +00001158 LinkageInfo LV;
1159 if (Var->getStorageClass() == SC_PrivateExtern)
1160 LV.mergeVisibility(HiddenVisibility, true);
John McCalld041a9b2013-02-20 01:54:26 +00001161 else if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +00001162 if (Optional<Visibility> Vis = getExplicitVisibility(Var, computation))
John McCalldf25c432013-02-16 00:17:33 +00001163 LV.mergeVisibility(*Vis, true);
1164 }
1165
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001166 if (const VarDecl *Prev = Var->getPreviousDecl()) {
1167 LinkageInfo PrevLV = getLVForDecl(Prev, computation);
1168 if (PrevLV.getLinkage())
1169 LV.setLinkage(PrevLV.getLinkage());
1170 LV.mergeVisibility(PrevLV);
1171 }
1172
John McCalldf25c432013-02-16 00:17:33 +00001173 return LV;
1174 }
Rafael Espindolaa4184182013-06-17 20:04:51 +00001175
1176 if (!Var->isStaticLocal())
1177 return LinkageInfo::none();
John McCalldf25c432013-02-16 00:17:33 +00001178 }
1179
Rafael Espindolaa4184182013-06-17 20:04:51 +00001180 ASTContext &Context = D->getASTContext();
1181 if (!Context.getLangOpts().CPlusPlus)
Rafael Espindola50df3a02013-05-25 17:16:20 +00001182 return LinkageInfo::none();
1183
Eli Friedman7e346a82013-07-01 20:22:57 +00001184 const Decl *OuterD = getOutermostFuncOrBlockContext(D);
Alexey Bataev0a47e652016-01-12 09:01:25 +00001185 if (!OuterD || OuterD->isInvalidDecl())
Rafael Espindola50df3a02013-05-25 17:16:20 +00001186 return LinkageInfo::none();
Rafael Espindola52189362013-06-04 13:43:35 +00001187
Eli Friedman7e346a82013-07-01 20:22:57 +00001188 LinkageInfo LV;
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001189 if (const auto *BD = dyn_cast<BlockDecl>(OuterD)) {
Eli Friedman7e346a82013-07-01 20:22:57 +00001190 if (!BD->getBlockManglingNumber())
1191 return LinkageInfo::none();
Rafael Espindola52189362013-06-04 13:43:35 +00001192
Eli Friedman7e346a82013-07-01 20:22:57 +00001193 LV = getLVForClosure(BD->getDeclContext()->getRedeclContext(),
1194 BD->getBlockManglingContextDecl(), computation);
1195 } else {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001196 const auto *FD = cast<FunctionDecl>(OuterD);
Eli Friedman7e346a82013-07-01 20:22:57 +00001197 if (!FD->isInlined() &&
David Majnemer9963ade2014-12-16 04:52:14 +00001198 !isTemplateInstantiation(FD->getTemplateSpecializationKind()))
Eli Friedman7e346a82013-07-01 20:22:57 +00001199 return LinkageInfo::none();
1200
1201 LV = getLVForDecl(FD, computation);
1202 }
Rafael Espindola111bb2e2013-05-27 14:50:21 +00001203 if (!isExternallyVisible(LV.getLinkage()))
Rafael Espindola50df3a02013-05-25 17:16:20 +00001204 return LinkageInfo::none();
1205 return LinkageInfo(VisibleNoLinkage, LV.getVisibility(),
1206 LV.isVisibilityExplicit());
John McCalldf25c432013-02-16 00:17:33 +00001207}
1208
Faisal Vali49b4c1f2013-10-01 02:51:53 +00001209static inline const CXXRecordDecl*
1210getOutermostEnclosingLambda(const CXXRecordDecl *Record) {
1211 const CXXRecordDecl *Ret = Record;
1212 while (Record && Record->isLambda()) {
1213 Ret = Record;
1214 if (!Record->getParent()) break;
1215 // Get the Containing Class of this Lambda Class
1216 Record = dyn_cast_or_null<CXXRecordDecl>(
1217 Record->getParent()->getParent());
1218 }
1219 return Ret;
1220}
1221
George Burgess IV99db3ea2017-08-09 04:02:49 +00001222LinkageInfo LinkageComputer::computeLVForDecl(const NamedDecl *D,
Richard Smithc95d2c52017-09-22 04:25:05 +00001223 LVComputationKind computation,
1224 bool IgnoreVarTypeLinkage) {
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00001225 // Internal_linkage attribute overrides other considerations.
1226 if (D->hasAttr<InternalLinkageAttr>())
Richard Smith1283e982017-07-07 20:04:28 +00001227 return getInternalLinkageFor(D);
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00001228
Ted Kremenek926d8602010-04-20 23:15:35 +00001229 // Objective-C: treat all Objective-C declarations as having external
1230 // linkage.
John McCall033caa52010-10-29 00:29:13 +00001231 switch (D->getKind()) {
Ted Kremenek926d8602010-04-20 23:15:35 +00001232 default:
1233 break;
Richard Smith97135cc2015-11-12 22:19:45 +00001234
1235 // Per C++ [basic.link]p2, only the names of objects, references,
1236 // functions, types, templates, namespaces, and values ever have linkage.
1237 //
1238 // Note that the name of a typedef, namespace alias, using declaration,
1239 // and so on are not the name of the corresponding type, namespace, or
1240 // declaration, so they do *not* have linkage.
Richard Smith97135cc2015-11-12 22:19:45 +00001241 case Decl::ImplicitParam:
1242 case Decl::Label:
1243 case Decl::NamespaceAlias:
Argyrios Kyrtzidis79d04282011-12-01 01:28:21 +00001244 case Decl::ParmVar:
Richard Smith97135cc2015-11-12 22:19:45 +00001245 case Decl::Using:
1246 case Decl::UsingShadow:
1247 case Decl::UsingDirective:
Argyrios Kyrtzidis79d04282011-12-01 01:28:21 +00001248 return LinkageInfo::none();
Richard Smith97135cc2015-11-12 22:19:45 +00001249
Richard Smith26210db2015-11-13 03:52:13 +00001250 case Decl::EnumConstant:
1251 // C++ [basic.link]p4: an enumerator has the linkage of its enumeration.
Bruno Cardoso Lopes057c82c2017-07-01 00:06:27 +00001252 if (D->getASTContext().getLangOpts().CPlusPlus)
1253 return getLVForDecl(cast<EnumDecl>(D->getDeclContext()), computation);
1254 return LinkageInfo::visible_none();
Richard Smith26210db2015-11-13 03:52:13 +00001255
Richard Smith97135cc2015-11-12 22:19:45 +00001256 case Decl::Typedef:
1257 case Decl::TypeAlias:
1258 // A typedef declaration has linkage if it gives a type a name for
1259 // linkage purposes.
Vassil Vassilevb00ea082017-07-01 20:44:49 +00001260 if (!cast<TypedefNameDecl>(D)
Richard Smith97135cc2015-11-12 22:19:45 +00001261 ->getAnonDeclWithTypedefName(/*AnyRedecl*/true))
1262 return LinkageInfo::none();
1263 break;
1264
John McCall457a04e2010-10-22 21:05:15 +00001265 case Decl::TemplateTemplateParm: // count these as external
1266 case Decl::NonTypeTemplateParm:
Ted Kremenek926d8602010-04-20 23:15:35 +00001267 case Decl::ObjCAtDefsField:
1268 case Decl::ObjCCategory:
1269 case Decl::ObjCCategoryImpl:
Ted Kremenek926d8602010-04-20 23:15:35 +00001270 case Decl::ObjCCompatibleAlias:
Ted Kremenek926d8602010-04-20 23:15:35 +00001271 case Decl::ObjCImplementation:
Ted Kremenek926d8602010-04-20 23:15:35 +00001272 case Decl::ObjCMethod:
1273 case Decl::ObjCProperty:
1274 case Decl::ObjCPropertyImpl:
1275 case Decl::ObjCProtocol:
Richard Smith1283e982017-07-07 20:04:28 +00001276 return getExternalLinkageFor(D);
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001277
1278 case Decl::CXXRecord: {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001279 const auto *Record = cast<CXXRecordDecl>(D);
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001280 if (Record->isLambda()) {
1281 if (!Record->getLambdaManglingNumber()) {
1282 // This lambda has no mangling number, so it's internal.
Richard Smith1283e982017-07-07 20:04:28 +00001283 return getInternalLinkageFor(D);
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001284 }
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001285
Faisal Vali49b4c1f2013-10-01 02:51:53 +00001286 // This lambda has its linkage/visibility determined:
1287 // - either by the outermost lambda if that lambda has no mangling
1288 // number.
1289 // - or by the parent of the outer most lambda
1290 // This prevents infinite recursion in settings such as nested lambdas
1291 // used in NSDMI's, for e.g.
1292 // struct L {
1293 // int t{};
1294 // int t2 = ([](int a) { return [](int b) { return b; };})(t)(t);
1295 // };
1296 const CXXRecordDecl *OuterMostLambda =
1297 getOutermostEnclosingLambda(Record);
1298 if (!OuterMostLambda->getLambdaManglingNumber())
Richard Smith1283e982017-07-07 20:04:28 +00001299 return getInternalLinkageFor(D);
Faisal Vali49b4c1f2013-10-01 02:51:53 +00001300
1301 return getLVForClosure(
1302 OuterMostLambda->getDeclContext()->getRedeclContext(),
1303 OuterMostLambda->getLambdaContextDecl(), computation);
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001304 }
1305
1306 break;
1307 }
Ted Kremenek926d8602010-04-20 23:15:35 +00001308 }
1309
Douglas Gregorf73b2822009-11-25 22:24:25 +00001310 // Handle linkage for namespace-scope names.
John McCall033caa52010-10-29 00:29:13 +00001311 if (D->getDeclContext()->getRedeclContext()->isFileContext())
Richard Smithc95d2c52017-09-22 04:25:05 +00001312 return getLVForNamespaceScopeDecl(D, computation, IgnoreVarTypeLinkage);
Douglas Gregorf73b2822009-11-25 22:24:25 +00001313
1314 // C++ [basic.link]p5:
1315 // In addition, a member function, static data member, a named
1316 // class or enumeration of class scope, or an unnamed class or
1317 // enumeration defined in a class-scope typedef declaration such
1318 // that the class or enumeration has the typedef name for linkage
1319 // purposes (7.1.3), has external linkage if the name of the class
1320 // has external linkage.
John McCall033caa52010-10-29 00:29:13 +00001321 if (D->getDeclContext()->isRecord())
Richard Smithc95d2c52017-09-22 04:25:05 +00001322 return getLVForClassMember(D, computation, IgnoreVarTypeLinkage);
Douglas Gregorf73b2822009-11-25 22:24:25 +00001323
1324 // C++ [basic.link]p6:
1325 // The name of a function declared in block scope and the name of
1326 // an object declared by a block scope extern declaration have
1327 // linkage. If there is a visible declaration of an entity with
1328 // linkage having the same name and type, ignoring entities
1329 // declared outside the innermost enclosing namespace scope, the
1330 // block scope declaration declares that same entity and receives
1331 // the linkage of the previous declaration. If there is more than
1332 // one such matching entity, the program is ill-formed. Otherwise,
1333 // if no matching entity is found, the block scope entity receives
1334 // external linkage.
John McCalldf25c432013-02-16 00:17:33 +00001335 if (D->getDeclContext()->isFunctionOrMethod())
1336 return getLVForLocalDecl(D, computation);
Douglas Gregorf73b2822009-11-25 22:24:25 +00001337
1338 // C++ [basic.link]p6:
1339 // Names not covered by these rules have no linkage.
John McCallc273f242010-10-30 11:50:40 +00001340 return LinkageInfo::none();
John McCall457a04e2010-10-22 21:05:15 +00001341}
Douglas Gregorf73b2822009-11-25 22:24:25 +00001342
George Burgess IV99db3ea2017-08-09 04:02:49 +00001343/// getLVForDecl - Get the linkage and visibility for the given declaration.
1344LinkageInfo LinkageComputer::getLVForDecl(const NamedDecl *D,
1345 LVComputationKind computation) {
1346 // Internal_linkage attribute overrides other considerations.
1347 if (D->hasAttr<InternalLinkageAttr>())
1348 return getInternalLinkageFor(D);
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00001349
Richard Smithfbe7b462017-09-22 02:22:32 +00001350 if (computation.IgnoreAllVisibility && D->hasCachedLinkage())
George Burgess IV99db3ea2017-08-09 04:02:49 +00001351 return LinkageInfo(D->getCachedLinkage(), DefaultVisibility, false);
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001352
George Burgess IV35cb4f82017-08-09 04:12:17 +00001353 if (llvm::Optional<LinkageInfo> LI = lookup(D, computation))
1354 return *LI;
1355
George Burgess IV99db3ea2017-08-09 04:02:49 +00001356 LinkageInfo LV = computeLVForDecl(D, computation);
1357 if (D->hasCachedLinkage())
1358 assert(D->getCachedLinkage() == LV.getLinkage());
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001359
George Burgess IV99db3ea2017-08-09 04:02:49 +00001360 D->setCachedLinkage(LV.getLinkage());
George Burgess IV35cb4f82017-08-09 04:12:17 +00001361 cache(D, computation, LV);
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001362
1363#ifndef NDEBUG
George Burgess IV99db3ea2017-08-09 04:02:49 +00001364 // In C (because of gnu inline) and in c++ with microsoft extensions an
1365 // static can follow an extern, so we can have two decls with different
1366 // linkages.
1367 const LangOptions &Opts = D->getASTContext().getLangOpts();
1368 if (!Opts.CPlusPlus || Opts.MicrosoftExt)
1369 return LV;
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001370
George Burgess IV99db3ea2017-08-09 04:02:49 +00001371 // We have just computed the linkage for this decl. By induction we know
1372 // that all other computed linkages match, check that the one we just
1373 // computed also does.
1374 NamedDecl *Old = nullptr;
1375 for (auto I : D->redecls()) {
1376 auto *T = cast<NamedDecl>(I);
1377 if (T == D)
1378 continue;
1379 if (!T->isInvalidDecl() && T->hasCachedLinkage()) {
1380 Old = T;
1381 break;
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001382 }
George Burgess IV99db3ea2017-08-09 04:02:49 +00001383 }
1384 assert(!Old || Old->getCachedLinkage() == D->getCachedLinkage());
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001385#endif
1386
George Burgess IV99db3ea2017-08-09 04:02:49 +00001387 return LV;
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001388}
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001389
George Burgess IV99db3ea2017-08-09 04:02:49 +00001390LinkageInfo LinkageComputer::getDeclLinkageAndVisibility(const NamedDecl *D) {
Richard Smithfbe7b462017-09-22 02:22:32 +00001391 return getLVForDecl(D,
1392 LVComputationKind(usesTypeVisibility(D)
1393 ? NamedDecl::VisibilityForType
1394 : NamedDecl::VisibilityForValue));
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001395}
1396
Richard Smithdd8b5332017-09-04 05:37:53 +00001397Module *NamedDecl::getOwningModuleForLinkage() const {
1398 Module *M = getOwningModule();
1399 if (!M)
1400 return nullptr;
1401
1402 switch (M->Kind) {
1403 case Module::ModuleMapModule:
1404 // Module map modules have no special linkage semantics.
1405 return nullptr;
1406
1407 case Module::ModuleInterfaceUnit:
1408 return M;
1409
1410 case Module::GlobalModuleFragment:
1411 // External linkage declarations in the global module have no owning module
1412 // for linkage purposes. But internal linkage declarations in the global
1413 // module fragment of a particular module are owned by that module for
1414 // linkage purposes.
1415 return hasExternalFormalLinkage() ? nullptr : M->Parent;
1416 }
1417
1418 llvm_unreachable("unknown module kind");
1419}
1420
Richard Smith7873de02016-08-11 22:25:46 +00001421void NamedDecl::printName(raw_ostream &os) const {
1422 os << Name;
1423}
1424
Douglas Gregor2ada0482009-02-04 17:27:36 +00001425std::string NamedDecl::getQualifiedNameAsString() const {
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001426 std::string QualName;
1427 llvm::raw_string_ostream OS(QualName);
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00001428 printQualifiedName(OS, getASTContext().getPrintingPolicy());
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001429 return OS.str();
1430}
1431
1432void NamedDecl::printQualifiedName(raw_ostream &OS) const {
1433 printQualifiedName(OS, getASTContext().getPrintingPolicy());
1434}
1435
1436void NamedDecl::printQualifiedName(raw_ostream &OS,
1437 const PrintingPolicy &P) const {
Douglas Gregor2ada0482009-02-04 17:27:36 +00001438 const DeclContext *Ctx = getDeclContext();
1439
Argyrios Kyrtzidisa166a2b2017-03-07 09:26:07 +00001440 // For ObjC methods, look through categories and use the interface as context.
1441 if (auto *MD = dyn_cast<ObjCMethodDecl>(this))
1442 if (auto *ID = MD->getClassInterface())
1443 Ctx = ID;
1444
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001445 if (Ctx->isFunctionOrMethod()) {
1446 printName(OS);
1447 return;
1448 }
Douglas Gregor2ada0482009-02-04 17:27:36 +00001449
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001450 typedef SmallVector<const DeclContext *, 8> ContextsTy;
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001451 ContextsTy Contexts;
1452
1453 // Collect contexts.
1454 while (Ctx && isa<NamedDecl>(Ctx)) {
1455 Contexts.push_back(Ctx);
1456 Ctx = Ctx->getParent();
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001457 }
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001458
David Majnemerf7e36092016-06-23 00:15:04 +00001459 for (const DeclContext *DC : reverse(Contexts)) {
1460 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
Benjamin Kramer9170e912013-02-22 15:46:01 +00001461 OS << Spec->getName();
Douglas Gregor85673582009-05-18 17:01:57 +00001462 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
David Majnemer6fbeee32016-07-07 04:43:07 +00001463 TemplateSpecializationType::PrintTemplateArgumentList(
1464 OS, TemplateArgs.asArray(), P);
David Majnemerf7e36092016-06-23 00:15:04 +00001465 } else if (const auto *ND = dyn_cast<NamespaceDecl>(DC)) {
Richard Smith46dd5bb2014-05-30 22:16:51 +00001466 if (P.SuppressUnwrittenScope &&
1467 (ND->isAnonymousNamespace() || ND->isInline()))
1468 continue;
Reid Kleckner60103382015-12-16 02:04:40 +00001469 if (ND->isAnonymousNamespace()) {
1470 OS << (P.MSVCFormatting ? "`anonymous namespace\'"
1471 : "(anonymous namespace)");
1472 }
Sam Weinig07d211e2009-12-24 23:15:03 +00001473 else
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001474 OS << *ND;
David Majnemerf7e36092016-06-23 00:15:04 +00001475 } else if (const auto *RD = dyn_cast<RecordDecl>(DC)) {
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001476 if (!RD->getIdentifier())
David Blaikieabe1a392014-04-02 05:58:29 +00001477 OS << "(anonymous " << RD->getKindName() << ')';
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001478 else
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001479 OS << *RD;
David Majnemerf7e36092016-06-23 00:15:04 +00001480 } else if (const auto *FD = dyn_cast<FunctionDecl>(DC)) {
Craig Topper36250ad2014-05-12 05:36:57 +00001481 const FunctionProtoType *FT = nullptr;
Sam Weinigb999f682009-12-28 03:19:38 +00001482 if (FD->hasWrittenPrototype())
Eli Friedman5c27c4c2012-08-30 22:22:09 +00001483 FT = dyn_cast<FunctionProtoType>(FD->getType()->castAs<FunctionType>());
Sam Weinigb999f682009-12-28 03:19:38 +00001484
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001485 OS << *FD << '(';
Sam Weinigb999f682009-12-28 03:19:38 +00001486 if (FT) {
Sam Weinigb999f682009-12-28 03:19:38 +00001487 unsigned NumParams = FD->getNumParams();
1488 for (unsigned i = 0; i < NumParams; ++i) {
1489 if (i)
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001490 OS << ", ";
Argyrios Kyrtzidisa18347e2012-05-05 04:20:37 +00001491 OS << FD->getParamDecl(i)->getType().stream(P);
Sam Weinigb999f682009-12-28 03:19:38 +00001492 }
1493
1494 if (FT->isVariadic()) {
1495 if (NumParams > 0)
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001496 OS << ", ";
1497 OS << "...";
Sam Weinigb999f682009-12-28 03:19:38 +00001498 }
1499 }
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001500 OS << ')';
David Majnemerf7e36092016-06-23 00:15:04 +00001501 } else if (const auto *ED = dyn_cast<EnumDecl>(DC)) {
Alexander Kornienko4f355322015-11-09 16:45:17 +00001502 // C++ [dcl.enum]p10: Each enum-name and each unscoped
1503 // enumerator is declared in the scope that immediately contains
1504 // the enum-specifier. Each scoped enumerator is declared in the
1505 // scope of the enumeration.
1506 if (ED->isScoped() || ED->getIdentifier())
1507 OS << *ED;
1508 else
1509 continue;
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001510 } else {
David Majnemerf7e36092016-06-23 00:15:04 +00001511 OS << *cast<NamedDecl>(DC);
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001512 }
1513 OS << "::";
Douglas Gregor2ada0482009-02-04 17:27:36 +00001514 }
1515
Richard Smith7873de02016-08-11 22:25:46 +00001516 if (getDeclName() || isa<DecompositionDecl>(this))
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001517 OS << *this;
John McCalla2a3f7d2010-03-16 21:48:18 +00001518 else
David Blaikieabe1a392014-04-02 05:58:29 +00001519 OS << "(anonymous)";
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001520}
Douglas Gregor2ada0482009-02-04 17:27:36 +00001521
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001522void NamedDecl::getNameForDiagnostic(raw_ostream &OS,
1523 const PrintingPolicy &Policy,
1524 bool Qualified) const {
1525 if (Qualified)
1526 printQualifiedName(OS, Policy);
1527 else
1528 printName(OS);
Douglas Gregor2ada0482009-02-04 17:27:36 +00001529}
1530
Richard Smithe8292b12015-02-10 03:28:10 +00001531template<typename T> static bool isRedeclarableImpl(Redeclarable<T> *) {
1532 return true;
1533}
1534static bool isRedeclarableImpl(...) { return false; }
1535static bool isRedeclarable(Decl::Kind K) {
1536 switch (K) {
1537#define DECL(Type, Base) \
1538 case Decl::Type: \
1539 return isRedeclarableImpl((Type##Decl *)nullptr);
1540#define ABSTRACT_DECL(DECL)
1541#include "clang/AST/DeclNodes.inc"
1542 }
1543 llvm_unreachable("unknown decl kind");
1544}
1545
1546bool NamedDecl::declarationReplaces(NamedDecl *OldD, bool IsKnownNewer) const {
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001547 assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch");
1548
Richard Smithfe620d22015-03-05 23:24:12 +00001549 // Never replace one imported declaration with another; we need both results
1550 // when re-exporting.
1551 if (OldD->isFromASTFile() && isFromASTFile())
1552 return false;
1553
Richard Smith5cd86f82015-11-03 03:13:11 +00001554 // A kind mismatch implies that the declaration is not replaced.
1555 if (OldD->getKind() != getKind())
Richard Smithe8292b12015-02-10 03:28:10 +00001556 return false;
1557
Richard Smith5cd86f82015-11-03 03:13:11 +00001558 // For method declarations, we never replace. (Why?)
1559 if (isa<ObjCMethodDecl>(this))
1560 return false;
1561
1562 // For parameters, pick the newer one. This is either an error or (in
1563 // Objective-C) permitted as an extension.
1564 if (isa<ParmVarDecl>(this))
1565 return true;
1566
Richard Smithe8292b12015-02-10 03:28:10 +00001567 // Inline namespaces can give us two declarations with the same
1568 // name and kind in the same scope but different contexts; we should
1569 // keep both declarations in this case.
1570 if (!this->getDeclContext()->getRedeclContext()->Equals(
1571 OldD->getDeclContext()->getRedeclContext()))
1572 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001573
Richard Smith5cd86f82015-11-03 03:13:11 +00001574 // Using declarations can be replaced if they import the same name from the
1575 // same context.
Richard Smithe8292b12015-02-10 03:28:10 +00001576 if (auto *UD = dyn_cast<UsingDecl>(this)) {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00001577 ASTContext &Context = getASTContext();
Richard Smithe8292b12015-02-10 03:28:10 +00001578 return Context.getCanonicalNestedNameSpecifier(UD->getQualifier()) ==
Douglas Gregora9d87bc2011-02-25 00:36:19 +00001579 Context.getCanonicalNestedNameSpecifier(
Richard Smithe8292b12015-02-10 03:28:10 +00001580 cast<UsingDecl>(OldD)->getQualifier());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00001581 }
Richard Smithe8292b12015-02-10 03:28:10 +00001582 if (auto *UUVD = dyn_cast<UnresolvedUsingValueDecl>(this)) {
Eli Friedman0eaf10b2013-08-20 00:39:40 +00001583 ASTContext &Context = getASTContext();
Richard Smithe8292b12015-02-10 03:28:10 +00001584 return Context.getCanonicalNestedNameSpecifier(UUVD->getQualifier()) ==
Eli Friedman0eaf10b2013-08-20 00:39:40 +00001585 Context.getCanonicalNestedNameSpecifier(
1586 cast<UnresolvedUsingValueDecl>(OldD)->getQualifier());
1587 }
1588
Richard Smithe8292b12015-02-10 03:28:10 +00001589 // UsingDirectiveDecl's are not really NamedDecl's, and all have same name.
Richard Smith5cd86f82015-11-03 03:13:11 +00001590 // They can be replaced if they nominate the same namespace.
1591 // FIXME: Is this true even if they have different module visibility?
Richard Smithe8292b12015-02-10 03:28:10 +00001592 if (auto *UD = dyn_cast<UsingDirectiveDecl>(this))
1593 return UD->getNominatedNamespace()->getOriginalNamespace() ==
1594 cast<UsingDirectiveDecl>(OldD)->getNominatedNamespace()
1595 ->getOriginalNamespace();
Richard Smithbaf3ca52014-03-17 21:46:03 +00001596
Richard Smith5cd86f82015-11-03 03:13:11 +00001597 if (isRedeclarable(getKind())) {
1598 if (getCanonicalDecl() != OldD->getCanonicalDecl())
1599 return false;
1600
1601 if (IsKnownNewer)
1602 return true;
1603
Richard Smithe8292b12015-02-10 03:28:10 +00001604 // Check whether this is actually newer than OldD. We want to keep the
1605 // newer declaration. This loop will usually only iterate once, because
1606 // OldD is usually the previous declaration.
1607 for (auto D : redecls()) {
1608 if (D == OldD)
1609 break;
1610
1611 // If we reach the canonical declaration, then OldD is not actually older
1612 // than this one.
1613 //
1614 // FIXME: In this case, we should not add this decl to the lookup table.
1615 if (D->isCanonicalDecl())
1616 return false;
1617 }
Richard Smith5cd86f82015-11-03 03:13:11 +00001618
1619 // It's a newer declaration of the same kind of declaration in the same
1620 // scope: we want this decl instead of the existing one.
1621 return true;
Richard Smithe8292b12015-02-10 03:28:10 +00001622 }
1623
Richard Smith5cd86f82015-11-03 03:13:11 +00001624 // In all other cases, we need to keep both declarations in case they have
1625 // different visibility. Any attempt to use the name will result in an
1626 // ambiguity if more than one is visible.
1627 return false;
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001628}
1629
Douglas Gregoreddf4332009-02-24 20:03:32 +00001630bool NamedDecl::hasLinkage() const {
Rafael Espindola50df3a02013-05-25 17:16:20 +00001631 return getFormalLinkage() != NoLinkage;
Douglas Gregoreddf4332009-02-24 20:03:32 +00001632}
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001633
Daniel Dunbar166ea9ad2012-03-08 18:20:41 +00001634NamedDecl *NamedDecl::getUnderlyingDeclImpl() {
Anders Carlsson6915bf62009-06-26 06:29:23 +00001635 NamedDecl *ND = this;
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001636 while (auto *UD = dyn_cast<UsingShadowDecl>(ND))
Benjamin Kramerba0495a2012-03-08 21:00:45 +00001637 ND = UD->getTargetDecl();
1638
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001639 if (auto *AD = dyn_cast<ObjCCompatibleAliasDecl>(ND))
Benjamin Kramerba0495a2012-03-08 21:00:45 +00001640 return AD->getClassInterface();
1641
Richard Smithf2005d32015-12-29 23:34:32 +00001642 if (auto *AD = dyn_cast<NamespaceAliasDecl>(ND))
1643 return AD->getNamespace();
1644
Benjamin Kramerba0495a2012-03-08 21:00:45 +00001645 return ND;
Anders Carlsson6915bf62009-06-26 06:29:23 +00001646}
1647
John McCalla8ae2222010-04-06 21:38:20 +00001648bool NamedDecl::isCXXInstanceMember() const {
Douglas Gregor3f28ec22012-03-08 02:08:05 +00001649 if (!isCXXClassMember())
1650 return false;
1651
John McCalla8ae2222010-04-06 21:38:20 +00001652 const NamedDecl *D = this;
1653 if (isa<UsingShadowDecl>(D))
1654 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1655
John McCall5e77d762013-04-16 07:28:30 +00001656 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D) || isa<MSPropertyDecl>(D))
John McCalla8ae2222010-04-06 21:38:20 +00001657 return true;
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001658 if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()))
Alp Tokera2794f92014-01-22 07:29:52 +00001659 return MD->isInstance();
John McCalla8ae2222010-04-06 21:38:20 +00001660 return false;
1661}
1662
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +00001663//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001664// DeclaratorDecl Implementation
1665//===----------------------------------------------------------------------===//
1666
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001667template <typename DeclT>
1668static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) {
1669 if (decl->getNumTemplateParameterLists() > 0)
1670 return decl->getTemplateParameterList(0)->getTemplateLoc();
1671 else
1672 return decl->getInnerLocStart();
1673}
1674
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001675SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const {
John McCallf7bcc812010-05-28 23:32:21 +00001676 TypeSourceInfo *TSI = getTypeSourceInfo();
1677 if (TSI) return TSI->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001678 return SourceLocation();
1679}
1680
Douglas Gregor14454802011-02-25 02:25:35 +00001681void DeclaratorDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
1682 if (QualifierLoc) {
John McCall3e11ebe2010-03-15 10:12:16 +00001683 // Make sure the extended decl info is allocated.
1684 if (!hasExtInfo()) {
1685 // Save (non-extended) type source info pointer.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001686 auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
John McCall3e11ebe2010-03-15 10:12:16 +00001687 // Allocate external info struct.
1688 DeclInfo = new (getASTContext()) ExtInfo;
1689 // Restore savedTInfo into (extended) decl info.
1690 getExtInfo()->TInfo = savedTInfo;
1691 }
1692 // Set qualifier info.
Douglas Gregor14454802011-02-25 02:25:35 +00001693 getExtInfo()->QualifierLoc = QualifierLoc;
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001694 } else {
John McCall3e11ebe2010-03-15 10:12:16 +00001695 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
John McCall3e11ebe2010-03-15 10:12:16 +00001696 if (hasExtInfo()) {
Abramo Bagnara60804e12011-03-18 15:16:37 +00001697 if (getExtInfo()->NumTemplParamLists == 0) {
1698 // Save type source info pointer.
1699 TypeSourceInfo *savedTInfo = getExtInfo()->TInfo;
1700 // Deallocate the extended decl info.
1701 getASTContext().Deallocate(getExtInfo());
1702 // Restore savedTInfo into (non-extended) decl info.
1703 DeclInfo = savedTInfo;
1704 }
1705 else
1706 getExtInfo()->QualifierLoc = QualifierLoc;
John McCall3e11ebe2010-03-15 10:12:16 +00001707 }
1708 }
1709}
1710
Benjamin Kramer9cc210652015-08-05 09:40:49 +00001711void DeclaratorDecl::setTemplateParameterListsInfo(
1712 ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
1713 assert(!TPLists.empty());
Abramo Bagnara60804e12011-03-18 15:16:37 +00001714 // Make sure the extended decl info is allocated.
1715 if (!hasExtInfo()) {
1716 // Save (non-extended) type source info pointer.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001717 auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
Abramo Bagnara60804e12011-03-18 15:16:37 +00001718 // Allocate external info struct.
1719 DeclInfo = new (getASTContext()) ExtInfo;
1720 // Restore savedTInfo into (extended) decl info.
1721 getExtInfo()->TInfo = savedTInfo;
1722 }
1723 // Set the template parameter lists info.
Benjamin Kramer9cc210652015-08-05 09:40:49 +00001724 getExtInfo()->setTemplateParameterListsInfo(Context, TPLists);
Abramo Bagnara60804e12011-03-18 15:16:37 +00001725}
1726
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001727SourceLocation DeclaratorDecl::getOuterLocStart() const {
1728 return getTemplateOrInnerLocStart(this);
1729}
1730
Abramo Bagnaraea947882011-03-08 16:41:52 +00001731namespace {
1732
1733// Helper function: returns true if QT is or contains a type
1734// having a postfix component.
1735bool typeIsPostfix(clang::QualType QT) {
1736 while (true) {
1737 const Type* T = QT.getTypePtr();
1738 switch (T->getTypeClass()) {
1739 default:
1740 return false;
1741 case Type::Pointer:
1742 QT = cast<PointerType>(T)->getPointeeType();
1743 break;
1744 case Type::BlockPointer:
1745 QT = cast<BlockPointerType>(T)->getPointeeType();
1746 break;
1747 case Type::MemberPointer:
1748 QT = cast<MemberPointerType>(T)->getPointeeType();
1749 break;
1750 case Type::LValueReference:
1751 case Type::RValueReference:
1752 QT = cast<ReferenceType>(T)->getPointeeType();
1753 break;
1754 case Type::PackExpansion:
1755 QT = cast<PackExpansionType>(T)->getPattern();
1756 break;
1757 case Type::Paren:
1758 case Type::ConstantArray:
1759 case Type::DependentSizedArray:
1760 case Type::IncompleteArray:
1761 case Type::VariableArray:
1762 case Type::FunctionProto:
1763 case Type::FunctionNoProto:
1764 return true;
1765 }
1766 }
1767}
1768
1769} // namespace
1770
1771SourceRange DeclaratorDecl::getSourceRange() const {
1772 SourceLocation RangeEnd = getLocation();
1773 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
Benjamin Kramer3a7cc812014-02-02 15:28:46 +00001774 // If the declaration has no name or the type extends past the name take the
1775 // end location of the type.
1776 if (!getDeclName() || typeIsPostfix(TInfo->getType()))
Abramo Bagnaraea947882011-03-08 16:41:52 +00001777 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
1778 }
1779 return SourceRange(getOuterLocStart(), RangeEnd);
1780}
1781
Benjamin Kramer9cc210652015-08-05 09:40:49 +00001782void QualifierInfo::setTemplateParameterListsInfo(
1783 ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001784 // Free previous template parameters (if any).
1785 if (NumTemplParamLists > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00001786 Context.Deallocate(TemplParamLists);
Craig Topper36250ad2014-05-12 05:36:57 +00001787 TemplParamLists = nullptr;
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001788 NumTemplParamLists = 0;
1789 }
1790 // Set info on matched template parameter lists (if any).
Benjamin Kramer9cc210652015-08-05 09:40:49 +00001791 if (!TPLists.empty()) {
1792 TemplParamLists = new (Context) TemplateParameterList *[TPLists.size()];
1793 NumTemplParamLists = TPLists.size();
1794 std::copy(TPLists.begin(), TPLists.end(), TemplParamLists);
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001795 }
1796}
1797
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001798//===----------------------------------------------------------------------===//
Nuno Lopes394ec982008-12-17 23:39:55 +00001799// VarDecl Implementation
1800//===----------------------------------------------------------------------===//
1801
Sebastian Redl833ef452010-01-26 22:01:41 +00001802const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) {
1803 switch (SC) {
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00001804 case SC_None: break;
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00001805 case SC_Auto: return "auto";
1806 case SC_Extern: return "extern";
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00001807 case SC_PrivateExtern: return "__private_extern__";
1808 case SC_Register: return "register";
1809 case SC_Static: return "static";
Sebastian Redl833ef452010-01-26 22:01:41 +00001810 }
1811
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00001812 llvm_unreachable("Invalid storage class");
Sebastian Redl833ef452010-01-26 22:01:41 +00001813}
1814
Richard Smith053f6c62014-05-16 23:01:30 +00001815VarDecl::VarDecl(Kind DK, ASTContext &C, DeclContext *DC,
1816 SourceLocation StartLoc, SourceLocation IdLoc,
1817 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
1818 StorageClass SC)
1819 : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc),
1820 redeclarable_base(C), Init() {
Benjamin Kramera939c232014-03-15 18:54:13 +00001821 static_assert(sizeof(VarDeclBitfields) <= sizeof(unsigned),
1822 "VarDeclBitfields too large!");
1823 static_assert(sizeof(ParmVarDeclBitfields) <= sizeof(unsigned),
1824 "ParmVarDeclBitfields too large!");
David Majnemerfa7bc782015-05-19 00:57:16 +00001825 static_assert(sizeof(NonParmVarDeclBitfields) <= sizeof(unsigned),
1826 "NonParmVarDeclBitfields too large!");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001827 AllBits = 0;
1828 VarDeclBits.SClass = SC;
1829 // Everything else is implicitly initialized to false.
1830}
1831
Abramo Bagnaradff19302011-03-08 08:55:46 +00001832VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC,
1833 SourceLocation StartL, SourceLocation IdL,
John McCallbcd03502009-12-07 02:54:59 +00001834 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001835 StorageClass S) {
Richard Smith053f6c62014-05-16 23:01:30 +00001836 return new (C, DC) VarDecl(Var, C, DC, StartL, IdL, Id, T, TInfo, S);
Nuno Lopes394ec982008-12-17 23:39:55 +00001837}
1838
Douglas Gregor72172e92012-01-05 21:55:30 +00001839VarDecl *VarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00001840 return new (C, ID)
1841 VarDecl(Var, C, nullptr, SourceLocation(), SourceLocation(), nullptr,
1842 QualType(), nullptr, SC_None);
Douglas Gregor72172e92012-01-05 21:55:30 +00001843}
1844
Douglas Gregorbf62d642010-12-06 18:36:25 +00001845void VarDecl::setStorageClass(StorageClass SC) {
1846 assert(isLegalForVariable(SC));
John McCallbeaa11c2011-05-01 02:13:58 +00001847 VarDeclBits.SClass = SC;
Douglas Gregorbf62d642010-12-06 18:36:25 +00001848}
1849
Reid Kleckner7d6d2702014-05-01 03:16:47 +00001850VarDecl::TLSKind VarDecl::getTLSKind() const {
1851 switch (VarDeclBits.TSCSpec) {
1852 case TSCS_unspecified:
Samuel Antaof8b50122015-07-13 22:54:53 +00001853 if (!hasAttr<ThreadAttr>() &&
1854 !(getASTContext().getLangOpts().OpenMPUseTLS &&
1855 getASTContext().getTargetInfo().isTLSSupported() &&
1856 hasAttr<OMPThreadPrivateDeclAttr>()))
David Majnemer1b5baff2015-05-14 05:19:23 +00001857 return TLS_None;
Samuel Antaof8b50122015-07-13 22:54:53 +00001858 return ((getASTContext().getLangOpts().isCompatibleWithMSVC(
1859 LangOptions::MSVC2015)) ||
1860 hasAttr<OMPThreadPrivateDeclAttr>())
David Majnemer1b5baff2015-05-14 05:19:23 +00001861 ? TLS_Dynamic
1862 : TLS_Static;
Reid Kleckner7d6d2702014-05-01 03:16:47 +00001863 case TSCS___thread: // Fall through.
1864 case TSCS__Thread_local:
Samuel Antaof8b50122015-07-13 22:54:53 +00001865 return TLS_Static;
Reid Kleckner7d6d2702014-05-01 03:16:47 +00001866 case TSCS_thread_local:
1867 return TLS_Dynamic;
1868 }
1869 llvm_unreachable("Unknown thread storage class specifier!");
1870}
1871
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001872SourceRange VarDecl::getSourceRange() const {
Argyrios Kyrtzidise0d64972012-10-08 23:08:41 +00001873 if (const Expr *Init = getInit()) {
1874 SourceLocation InitEnd = Init->getLocEnd();
Nico Weberbbe13942013-01-22 17:00:09 +00001875 // If Init is implicit, ignore its source range and fallback on
1876 // DeclaratorDecl::getSourceRange() to handle postfix elements.
1877 if (InitEnd.isValid() && InitEnd != getLocation())
Argyrios Kyrtzidise0d64972012-10-08 23:08:41 +00001878 return SourceRange(getOuterLocStart(), InitEnd);
1879 }
Abramo Bagnaraea947882011-03-08 16:41:52 +00001880 return DeclaratorDecl::getSourceRange();
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00001881}
1882
Rafael Espindola88510672013-01-04 21:18:45 +00001883template<typename T>
Alp Toker84212df2014-05-31 06:11:02 +00001884static LanguageLinkage getDeclLanguageLinkage(const T &D) {
Rafael Espindola5bda63f2013-02-14 01:47:04 +00001885 // C++ [dcl.link]p1: All function types, function names with external linkage,
1886 // and variable names with external linkage have a language linkage.
Rafael Espindola3ae00052013-05-13 00:12:11 +00001887 if (!D.hasExternalFormalLinkage())
Rafael Espindola5bda63f2013-02-14 01:47:04 +00001888 return NoLanguageLinkage;
1889
1890 // Language linkage is a C++ concept, but saying that everything else in C has
Rafael Espindola66748e92013-01-04 20:41:40 +00001891 // C language linkage fits the implementation nicely.
Rafael Espindola576127d2012-12-28 14:21:58 +00001892 ASTContext &Context = D.getASTContext();
1893 if (!Context.getLangOpts().CPlusPlus)
Rafael Espindolaf4187652013-02-14 01:18:37 +00001894 return CLanguageLinkage;
1895
Rafael Espindola5bda63f2013-02-14 01:47:04 +00001896 // C++ [dcl.link]p4: A C language linkage is ignored in determining the
1897 // language linkage of the names of class members and the function type of
1898 // class member functions.
Rafael Espindola576127d2012-12-28 14:21:58 +00001899 const DeclContext *DC = D.getDeclContext();
1900 if (DC->isRecord())
Rafael Espindolaf4187652013-02-14 01:18:37 +00001901 return CXXLanguageLinkage;
Rafael Espindola576127d2012-12-28 14:21:58 +00001902
1903 // If the first decl is in an extern "C" context, any other redeclaration
1904 // will have C language linkage. If the first one is not in an extern "C"
1905 // context, we would have reported an error for any other decl being in one.
Rafael Espindola593537a2013-05-05 20:15:21 +00001906 if (isFirstInExternCContext(&D))
Rafael Espindolaf4187652013-02-14 01:18:37 +00001907 return CLanguageLinkage;
1908 return CXXLanguageLinkage;
Rafael Espindola576127d2012-12-28 14:21:58 +00001909}
1910
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001911template<typename T>
Alp Toker84212df2014-05-31 06:11:02 +00001912static bool isDeclExternC(const T &D) {
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001913 // Since the context is ignored for class members, they can only have C++
1914 // language linkage or no language linkage.
1915 const DeclContext *DC = D.getDeclContext();
1916 if (DC->isRecord()) {
1917 assert(D.getASTContext().getLangOpts().CPlusPlus);
1918 return false;
1919 }
1920
1921 return D.getLanguageLinkage() == CLanguageLinkage;
1922}
1923
Rafael Espindolaf4187652013-02-14 01:18:37 +00001924LanguageLinkage VarDecl::getLanguageLinkage() const {
Alp Toker84212df2014-05-31 06:11:02 +00001925 return getDeclLanguageLinkage(*this);
Rafael Espindola576127d2012-12-28 14:21:58 +00001926}
1927
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001928bool VarDecl::isExternC() const {
Alp Toker84212df2014-05-31 06:11:02 +00001929 return isDeclExternC(*this);
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001930}
1931
Rafael Espindola593537a2013-05-05 20:15:21 +00001932bool VarDecl::isInExternCContext() const {
Serge Pavlov3cb80222013-11-14 02:13:03 +00001933 return getLexicalDeclContext()->isExternCContext();
Rafael Espindola593537a2013-05-05 20:15:21 +00001934}
1935
1936bool VarDecl::isInExternCXXContext() const {
Serge Pavlov3cb80222013-11-14 02:13:03 +00001937 return getLexicalDeclContext()->isExternCXXContext();
Rafael Espindola593537a2013-05-05 20:15:21 +00001938}
1939
Rafael Espindola8db352d2013-10-17 15:37:26 +00001940VarDecl *VarDecl::getCanonicalDecl() { return getFirstDecl(); }
Sebastian Redl833ef452010-01-26 22:01:41 +00001941
Nico Weber7f5015a2015-04-15 21:53:00 +00001942VarDecl::DefinitionKind
1943VarDecl::isThisDeclarationADefinition(ASTContext &C) const {
Sebastian Redl35351a92010-01-31 22:27:38 +00001944 // C++ [basic.def]p2:
1945 // A declaration is a definition unless [...] it contains the 'extern'
1946 // specifier or a linkage-specification and neither an initializer [...],
Richard Smith62f19e72016-06-25 00:15:56 +00001947 // it declares a non-inline static data member in a class declaration [...],
1948 // it declares a static data member outside a class definition and the variable
1949 // was defined within the class with the constexpr specifier [...],
Richard Smith8809a0c2013-09-27 20:14:12 +00001950 // C++1y [temp.expl.spec]p15:
1951 // An explicit specialization of a static data member or an explicit
1952 // specialization of a static data member template is a definition if the
1953 // declaration includes an initializer; otherwise, it is a declaration.
1954 //
1955 // FIXME: How do you declare (but not define) a partial specialization of
1956 // a static data member template outside the containing class?
Richard Smithedbc6e92016-10-14 21:41:24 +00001957 if (isThisDeclarationADemotedDefinition())
1958 return DeclarationOnly;
1959
Sebastian Redl35351a92010-01-31 22:27:38 +00001960 if (isStaticDataMember()) {
Richard Smith8809a0c2013-09-27 20:14:12 +00001961 if (isOutOfLine() &&
Richard Smith62f19e72016-06-25 00:15:56 +00001962 !(getCanonicalDecl()->isInline() &&
1963 getCanonicalDecl()->isConstexpr()) &&
Richard Smith8809a0c2013-09-27 20:14:12 +00001964 (hasInit() ||
1965 // If the first declaration is out-of-line, this may be an
1966 // instantiation of an out-of-line partial specialization of a variable
1967 // template for which we have not yet instantiated the initializer.
Rafael Espindola8db352d2013-10-17 15:37:26 +00001968 (getFirstDecl()->isOutOfLine()
Richard Smith8809a0c2013-09-27 20:14:12 +00001969 ? getTemplateSpecializationKind() == TSK_Undeclared
1970 : getTemplateSpecializationKind() !=
1971 TSK_ExplicitSpecialization) ||
1972 isa<VarTemplatePartialSpecializationDecl>(this)))
Sebastian Redl35351a92010-01-31 22:27:38 +00001973 return Definition;
Richard Smith62f19e72016-06-25 00:15:56 +00001974 else if (!isOutOfLine() && isInline())
1975 return Definition;
Sebastian Redl35351a92010-01-31 22:27:38 +00001976 else
1977 return DeclarationOnly;
1978 }
1979 // C99 6.7p5:
1980 // A definition of an identifier is a declaration for that identifier that
1981 // [...] causes storage to be reserved for that object.
1982 // Note: that applies for all non-file-scope objects.
1983 // C99 6.9.2p1:
1984 // If the declaration of an identifier for an object has file scope and an
1985 // initializer, the declaration is an external definition for the identifier
1986 if (hasInit())
1987 return Definition;
Rafael Espindolabff59562013-04-25 12:11:36 +00001988
Dmitry Polukhin85eda122016-04-11 07:48:59 +00001989 if (hasDefiningAttr())
Rafael Espindolad53ffa02013-10-22 21:39:03 +00001990 return Definition;
1991
David Majnemerdd0bed12015-05-14 05:19:20 +00001992 if (const auto *SAA = getAttr<SelectAnyAttr>())
1993 if (!SAA->isInherited())
1994 return Definition;
1995
Richard Smith8809a0c2013-09-27 20:14:12 +00001996 // A variable template specialization (other than a static data member
1997 // template or an explicit specialization) is a declaration until we
1998 // instantiate its initializer.
1999 if (isa<VarTemplateSpecializationDecl>(this) &&
2000 getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
2001 return DeclarationOnly;
2002
Nico Weber608e7682015-04-15 23:04:24 +00002003 if (hasExternalStorage())
Sebastian Redl35351a92010-01-31 22:27:38 +00002004 return DeclarationOnly;
Rafael Espindola8f326a52013-03-07 01:42:44 +00002005
Rafael Espindolabff59562013-04-25 12:11:36 +00002006 // [dcl.link] p7:
2007 // A declaration directly contained in a linkage-specification is treated
2008 // as if it contains the extern specifier for the purpose of determining
2009 // the linkage of the declared name and whether it is a definition.
Nico Weber608e7682015-04-15 23:04:24 +00002010 if (isSingleLineLanguageLinkage(*this))
Rafael Espindola327be3c2013-04-26 01:30:23 +00002011 return DeclarationOnly;
Rafael Espindolabff59562013-04-25 12:11:36 +00002012
Sebastian Redl35351a92010-01-31 22:27:38 +00002013 // C99 6.9.2p2:
2014 // A declaration of an object that has file scope without an initializer,
2015 // and without a storage class specifier or the scs 'static', constitutes
2016 // a tentative definition.
2017 // No such thing in C++.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002018 if (!C.getLangOpts().CPlusPlus && isFileVarDecl())
Sebastian Redl35351a92010-01-31 22:27:38 +00002019 return TentativeDefinition;
2020
2021 // What's left is (in C, block-scope) declarations without initializers or
2022 // external storage. These are definitions.
2023 return Definition;
2024}
2025
Sebastian Redl35351a92010-01-31 22:27:38 +00002026VarDecl *VarDecl::getActingDefinition() {
2027 DefinitionKind Kind = isThisDeclarationADefinition();
2028 if (Kind != TentativeDefinition)
Craig Topper36250ad2014-05-12 05:36:57 +00002029 return nullptr;
Sebastian Redl35351a92010-01-31 22:27:38 +00002030
Craig Topper36250ad2014-05-12 05:36:57 +00002031 VarDecl *LastTentative = nullptr;
Rafael Espindola8db352d2013-10-17 15:37:26 +00002032 VarDecl *First = getFirstDecl();
Aaron Ballman86c93902014-03-06 23:45:36 +00002033 for (auto I : First->redecls()) {
2034 Kind = I->isThisDeclarationADefinition();
Sebastian Redl35351a92010-01-31 22:27:38 +00002035 if (Kind == Definition)
Craig Topper36250ad2014-05-12 05:36:57 +00002036 return nullptr;
Sebastian Redl35351a92010-01-31 22:27:38 +00002037 else if (Kind == TentativeDefinition)
Aaron Ballman86c93902014-03-06 23:45:36 +00002038 LastTentative = I;
Sebastian Redl35351a92010-01-31 22:27:38 +00002039 }
2040 return LastTentative;
2041}
2042
Daniel Dunbar9d355812012-03-09 01:51:51 +00002043VarDecl *VarDecl::getDefinition(ASTContext &C) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00002044 VarDecl *First = getFirstDecl();
Aaron Ballman86c93902014-03-06 23:45:36 +00002045 for (auto I : First->redecls()) {
2046 if (I->isThisDeclarationADefinition(C) == Definition)
2047 return I;
Sebastian Redl5ca79842010-02-01 20:16:42 +00002048 }
Craig Topper36250ad2014-05-12 05:36:57 +00002049 return nullptr;
Sebastian Redl5ca79842010-02-01 20:16:42 +00002050}
2051
Daniel Dunbar9d355812012-03-09 01:51:51 +00002052VarDecl::DefinitionKind VarDecl::hasDefinition(ASTContext &C) const {
John McCall37bb6c92010-10-29 22:22:43 +00002053 DefinitionKind Kind = DeclarationOnly;
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002054
Rafael Espindola8db352d2013-10-17 15:37:26 +00002055 const VarDecl *First = getFirstDecl();
Aaron Ballman86c93902014-03-06 23:45:36 +00002056 for (auto I : First->redecls()) {
2057 Kind = std::max(Kind, I->isThisDeclarationADefinition(C));
Daniel Dunbar082c62d2012-03-06 23:52:46 +00002058 if (Kind == Definition)
2059 break;
2060 }
John McCall37bb6c92010-10-29 22:22:43 +00002061
2062 return Kind;
2063}
2064
Sebastian Redl5ca79842010-02-01 20:16:42 +00002065const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const {
Aaron Ballman86c93902014-03-06 23:45:36 +00002066 for (auto I : redecls()) {
2067 if (auto Expr = I->getInit()) {
2068 D = I;
2069 return Expr;
2070 }
Sebastian Redl833ef452010-01-26 22:01:41 +00002071 }
Craig Topper36250ad2014-05-12 05:36:57 +00002072 return nullptr;
Sebastian Redl833ef452010-01-26 22:01:41 +00002073}
2074
Chandler Carruth813faed2015-12-30 02:51:00 +00002075bool VarDecl::hasInit() const {
2076 if (auto *P = dyn_cast<ParmVarDecl>(this))
2077 if (P->hasUnparsedDefaultArg() || P->hasUninstantiatedDefaultArg())
2078 return false;
2079
2080 return !Init.isNull();
2081}
2082
2083Expr *VarDecl::getInit() {
2084 if (!hasInit())
2085 return nullptr;
2086
2087 if (auto *S = Init.dyn_cast<Stmt *>())
2088 return cast<Expr>(S);
2089
2090 return cast_or_null<Expr>(Init.get<EvaluatedStmt *>()->Value);
2091}
2092
2093Stmt **VarDecl::getInitAddress() {
2094 if (auto *ES = Init.dyn_cast<EvaluatedStmt *>())
2095 return &ES->Value;
2096
2097 return Init.getAddrOfPtr1();
2098}
2099
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002100bool VarDecl::isOutOfLine() const {
Douglas Gregorb11aad82011-02-19 18:51:44 +00002101 if (Decl::isOutOfLine())
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002102 return true;
Chandler Carruthf50ef6e2010-02-21 07:08:09 +00002103
2104 if (!isStaticDataMember())
2105 return false;
2106
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002107 // If this static data member was instantiated from a static data member of
2108 // a class template, check whether that static data member was defined
2109 // out-of-line.
2110 if (VarDecl *VD = getInstantiatedFromStaticDataMember())
2111 return VD->isOutOfLine();
2112
2113 return false;
2114}
2115
Douglas Gregord5058122010-02-11 01:19:42 +00002116void VarDecl::setInit(Expr *I) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002117 if (auto *Eval = Init.dyn_cast<EvaluatedStmt *>()) {
Sebastian Redl833ef452010-01-26 22:01:41 +00002118 Eval->~EvaluatedStmt();
Douglas Gregord5058122010-02-11 01:19:42 +00002119 getASTContext().Deallocate(Eval);
Sebastian Redl833ef452010-01-26 22:01:41 +00002120 }
2121
2122 Init = I;
2123}
2124
Daniel Dunbar9d355812012-03-09 01:51:51 +00002125bool VarDecl::isUsableInConstantExpressions(ASTContext &C) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002126 const LangOptions &Lang = C.getLangOpts();
Richard Smith242ad892011-12-21 02:55:12 +00002127
Richard Smith35ecb362012-03-02 04:14:40 +00002128 if (!Lang.CPlusPlus)
2129 return false;
2130
2131 // In C++11, any variable of reference type can be used in a constant
2132 // expression if it is initialized by a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002133 if (Lang.CPlusPlus11 && getType()->isReferenceType())
Richard Smith35ecb362012-03-02 04:14:40 +00002134 return true;
2135
2136 // Only const objects can be used in constant expressions in C++. C++98 does
Richard Smith242ad892011-12-21 02:55:12 +00002137 // not require the variable to be non-volatile, but we consider this to be a
2138 // defect.
Richard Smith35ecb362012-03-02 04:14:40 +00002139 if (!getType().isConstQualified() || getType().isVolatileQualified())
Richard Smith242ad892011-12-21 02:55:12 +00002140 return false;
2141
2142 // In C++, const, non-volatile variables of integral or enumeration types
2143 // can be used in constant expressions.
2144 if (getType()->isIntegralOrEnumerationType())
2145 return true;
2146
Richard Smith35ecb362012-03-02 04:14:40 +00002147 // Additionally, in C++11, non-volatile constexpr variables can be used in
2148 // constant expressions.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002149 return Lang.CPlusPlus11 && isConstexpr();
Richard Smith242ad892011-12-21 02:55:12 +00002150}
2151
Richard Smithd0b4dd62011-12-19 06:19:21 +00002152/// Convert the initializer for this declaration to the elaborated EvaluatedStmt
2153/// form, which contains extra information on the evaluated value of the
2154/// initializer.
2155EvaluatedStmt *VarDecl::ensureEvaluatedStmt() const {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002156 auto *Eval = Init.dyn_cast<EvaluatedStmt *>();
Richard Smithd0b4dd62011-12-19 06:19:21 +00002157 if (!Eval) {
Manuel Klimeka7328992013-06-03 13:51:33 +00002158 // Note: EvaluatedStmt contains an APValue, which usually holds
2159 // resources not allocated from the ASTContext. We need to do some
2160 // work to avoid leaking those, but we do so in VarDecl::evaluateValue
2161 // where we can detect whether there's anything to clean up or not.
Richard Smithd0b4dd62011-12-19 06:19:21 +00002162 Eval = new (getASTContext()) EvaluatedStmt;
Chandler Carruth813faed2015-12-30 02:51:00 +00002163 Eval->Value = Init.get<Stmt *>();
Richard Smithd0b4dd62011-12-19 06:19:21 +00002164 Init = Eval;
2165 }
2166 return Eval;
2167}
2168
Richard Smithdafff942012-01-14 04:30:29 +00002169APValue *VarDecl::evaluateValue() const {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002170 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithdafff942012-01-14 04:30:29 +00002171 return evaluateValue(Notes);
2172}
2173
2174APValue *VarDecl::evaluateValue(
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002175 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithd0b4dd62011-12-19 06:19:21 +00002176 EvaluatedStmt *Eval = ensureEvaluatedStmt();
2177
2178 // We only produce notes indicating why an initializer is non-constant the
2179 // first time it is evaluated. FIXME: The notes won't always be emitted the
2180 // first time we try evaluation, so might not be produced at all.
2181 if (Eval->WasEvaluated)
Craig Topper36250ad2014-05-12 05:36:57 +00002182 return Eval->Evaluated.isUninit() ? nullptr : &Eval->Evaluated;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002183
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002184 const auto *Init = cast<Expr>(Eval->Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002185 assert(!Init->isValueDependent());
2186
2187 if (Eval->IsEvaluating) {
2188 // FIXME: Produce a diagnostic for self-initialization.
2189 Eval->CheckedICE = true;
2190 Eval->IsICE = false;
Craig Topper36250ad2014-05-12 05:36:57 +00002191 return nullptr;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002192 }
2193
2194 Eval->IsEvaluating = true;
2195
2196 bool Result = Init->EvaluateAsInitializer(Eval->Evaluated, getASTContext(),
2197 this, Notes);
2198
Manuel Klimeka7328992013-06-03 13:51:33 +00002199 // Ensure the computed APValue is cleaned up later if evaluation succeeded,
2200 // or that it's empty (so that there's nothing to clean up) if evaluation
2201 // failed.
Richard Smithd0b4dd62011-12-19 06:19:21 +00002202 if (!Result)
2203 Eval->Evaluated = APValue();
Manuel Klimeka7328992013-06-03 13:51:33 +00002204 else if (Eval->Evaluated.needsCleanup())
George Burgess IVb61bfbd2017-02-14 05:37:36 +00002205 getASTContext().addDestruction(&Eval->Evaluated);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002206
2207 Eval->IsEvaluating = false;
2208 Eval->WasEvaluated = true;
2209
2210 // In C++11, we have determined whether the initializer was a constant
2211 // expression as a side-effect.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002212 if (getASTContext().getLangOpts().CPlusPlus11 && !Eval->CheckedICE) {
Richard Smithd0b4dd62011-12-19 06:19:21 +00002213 Eval->CheckedICE = true;
Eli Friedman8f66cdf2012-02-06 21:50:18 +00002214 Eval->IsICE = Result && Notes.empty();
Richard Smithd0b4dd62011-12-19 06:19:21 +00002215 }
2216
Craig Topper36250ad2014-05-12 05:36:57 +00002217 return Result ? &Eval->Evaluated : nullptr;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002218}
2219
Chandler Carruth813faed2015-12-30 02:51:00 +00002220APValue *VarDecl::getEvaluatedValue() const {
2221 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
2222 if (Eval->WasEvaluated)
2223 return &Eval->Evaluated;
2224
2225 return nullptr;
2226}
2227
2228bool VarDecl::isInitKnownICE() const {
2229 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
2230 return Eval->CheckedICE;
2231
2232 return false;
2233}
2234
2235bool VarDecl::isInitICE() const {
2236 assert(isInitKnownICE() &&
2237 "Check whether we already know that the initializer is an ICE");
2238 return Init.get<EvaluatedStmt *>()->IsICE;
2239}
2240
Richard Smithd0b4dd62011-12-19 06:19:21 +00002241bool VarDecl::checkInitIsICE() const {
John McCalla59dc2f2012-01-05 00:13:19 +00002242 // Initializers of weak variables are never ICEs.
2243 if (isWeak())
2244 return false;
2245
Richard Smithd0b4dd62011-12-19 06:19:21 +00002246 EvaluatedStmt *Eval = ensureEvaluatedStmt();
2247 if (Eval->CheckedICE)
2248 // We have already checked whether this subexpression is an
2249 // integral constant expression.
2250 return Eval->IsICE;
2251
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002252 const auto *Init = cast<Expr>(Eval->Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002253 assert(!Init->isValueDependent());
2254
2255 // In C++11, evaluate the initializer to check whether it's a constant
2256 // expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002257 if (getASTContext().getLangOpts().CPlusPlus11) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002258 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002259 evaluateValue(Notes);
2260 return Eval->IsICE;
2261 }
2262
2263 // It's an ICE whether or not the definition we found is
2264 // out-of-line. See DR 721 and the discussion in Clang PR
2265 // 6206 for details.
2266
2267 if (Eval->CheckingICE)
2268 return false;
2269 Eval->CheckingICE = true;
2270
2271 Eval->IsICE = Init->isIntegerConstantExpr(getASTContext());
2272 Eval->CheckingICE = false;
2273 Eval->CheckedICE = true;
2274 return Eval->IsICE;
2275}
2276
Richard Smith2195ec92017-04-21 01:15:13 +00002277template<typename DeclT>
2278static DeclT *getDefinitionOrSelf(DeclT *D) {
2279 assert(D);
2280 if (auto *Def = D->getDefinition())
2281 return Def;
2282 return D;
2283}
2284
Richard Smithedbc6e92016-10-14 21:41:24 +00002285VarDecl *VarDecl::getTemplateInstantiationPattern() const {
2286 // If it's a variable template specialization, find the template or partial
2287 // specialization from which it was instantiated.
2288 if (auto *VDTemplSpec = dyn_cast<VarTemplateSpecializationDecl>(this)) {
2289 auto From = VDTemplSpec->getInstantiatedFrom();
2290 if (auto *VTD = From.dyn_cast<VarTemplateDecl *>()) {
2291 while (auto *NewVTD = VTD->getInstantiatedFromMemberTemplate()) {
2292 if (NewVTD->isMemberSpecialization())
2293 break;
2294 VTD = NewVTD;
2295 }
Richard Smith2195ec92017-04-21 01:15:13 +00002296 return getDefinitionOrSelf(VTD->getTemplatedDecl());
Richard Smithedbc6e92016-10-14 21:41:24 +00002297 }
2298 if (auto *VTPSD =
2299 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
2300 while (auto *NewVTPSD = VTPSD->getInstantiatedFromMember()) {
2301 if (NewVTPSD->isMemberSpecialization())
2302 break;
2303 VTPSD = NewVTPSD;
2304 }
Richard Smith2195ec92017-04-21 01:15:13 +00002305 return getDefinitionOrSelf<VarDecl>(VTPSD);
Richard Smithedbc6e92016-10-14 21:41:24 +00002306 }
2307 }
2308
2309 if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) {
2310 if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) {
2311 VarDecl *VD = getInstantiatedFromStaticDataMember();
2312 while (auto *NewVD = VD->getInstantiatedFromStaticDataMember())
2313 VD = NewVD;
Richard Smith2195ec92017-04-21 01:15:13 +00002314 return getDefinitionOrSelf(VD);
Richard Smithedbc6e92016-10-14 21:41:24 +00002315 }
2316 }
2317
2318 if (VarTemplateDecl *VarTemplate = getDescribedVarTemplate()) {
Richard Smithedbc6e92016-10-14 21:41:24 +00002319 while (VarTemplate->getInstantiatedFromMemberTemplate()) {
2320 if (VarTemplate->isMemberSpecialization())
2321 break;
2322 VarTemplate = VarTemplate->getInstantiatedFromMemberTemplate();
2323 }
2324
Richard Smith2195ec92017-04-21 01:15:13 +00002325 return getDefinitionOrSelf(VarTemplate->getTemplatedDecl());
Richard Smithedbc6e92016-10-14 21:41:24 +00002326 }
2327 return nullptr;
2328}
2329
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002330VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const {
Douglas Gregor06db9f52009-10-12 20:18:28 +00002331 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
Douglas Gregor86d142a2009-10-08 07:24:58 +00002332 return cast<VarDecl>(MSI->getInstantiatedFrom());
Craig Topper36250ad2014-05-12 05:36:57 +00002333
2334 return nullptr;
Douglas Gregor86d142a2009-10-08 07:24:58 +00002335}
2336
Douglas Gregor3c74d412009-10-14 20:14:33 +00002337TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002338 if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
Larisse Voufo39a1e502013-08-06 01:03:05 +00002339 return Spec->getSpecializationKind();
2340
Sebastian Redl35351a92010-01-31 22:27:38 +00002341 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
Douglas Gregor86d142a2009-10-08 07:24:58 +00002342 return MSI->getTemplateSpecializationKind();
Richard Smith8809a0c2013-09-27 20:14:12 +00002343
Douglas Gregor86d142a2009-10-08 07:24:58 +00002344 return TSK_Undeclared;
2345}
2346
Richard Smith8809a0c2013-09-27 20:14:12 +00002347SourceLocation VarDecl::getPointOfInstantiation() const {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002348 if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
Richard Smith8809a0c2013-09-27 20:14:12 +00002349 return Spec->getPointOfInstantiation();
2350
2351 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2352 return MSI->getPointOfInstantiation();
2353
2354 return SourceLocation();
2355}
2356
Larisse Voufo39a1e502013-08-06 01:03:05 +00002357VarTemplateDecl *VarDecl::getDescribedVarTemplate() const {
2358 return getASTContext().getTemplateOrSpecializationInfo(this)
2359 .dyn_cast<VarTemplateDecl *>();
2360}
2361
2362void VarDecl::setDescribedVarTemplate(VarTemplateDecl *Template) {
2363 getASTContext().setTemplateOrSpecializationInfo(this, Template);
2364}
2365
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002366MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const {
Richard Smithb71782b2013-08-01 04:12:04 +00002367 if (isStaticDataMember())
Larisse Voufo39a1e502013-08-06 01:03:05 +00002368 // FIXME: Remove ?
2369 // return getASTContext().getInstantiatedFromStaticDataMember(this);
2370 return getASTContext().getTemplateOrSpecializationInfo(this)
2371 .dyn_cast<MemberSpecializationInfo *>();
Craig Topper36250ad2014-05-12 05:36:57 +00002372 return nullptr;
Douglas Gregor06db9f52009-10-12 20:18:28 +00002373}
2374
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00002375void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2376 SourceLocation PointOfInstantiation) {
Richard Smith8809a0c2013-09-27 20:14:12 +00002377 assert((isa<VarTemplateSpecializationDecl>(this) ||
2378 getMemberSpecializationInfo()) &&
2379 "not a variable or static data member template specialization");
2380
Larisse Voufo39a1e502013-08-06 01:03:05 +00002381 if (VarTemplateSpecializationDecl *Spec =
2382 dyn_cast<VarTemplateSpecializationDecl>(this)) {
2383 Spec->setSpecializationKind(TSK);
2384 if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
2385 Spec->getPointOfInstantiation().isInvalid())
2386 Spec->setPointOfInstantiation(PointOfInstantiation);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002387 }
2388
2389 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) {
2390 MSI->setTemplateSpecializationKind(TSK);
2391 if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
2392 MSI->getPointOfInstantiation().isInvalid())
2393 MSI->setPointOfInstantiation(PointOfInstantiation);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002394 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002395}
2396
2397void
2398VarDecl::setInstantiationOfStaticDataMember(VarDecl *VD,
2399 TemplateSpecializationKind TSK) {
2400 assert(getASTContext().getTemplateOrSpecializationInfo(this).isNull() &&
2401 "Previous template or instantiation?");
2402 getASTContext().setInstantiatedFromStaticDataMember(this, VD, TSK);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00002403}
2404
Sebastian Redl833ef452010-01-26 22:01:41 +00002405//===----------------------------------------------------------------------===//
2406// ParmVarDecl Implementation
2407//===----------------------------------------------------------------------===//
Douglas Gregor0760fa12009-03-10 23:43:53 +00002408
Sebastian Redl833ef452010-01-26 22:01:41 +00002409ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00002410 SourceLocation StartLoc,
2411 SourceLocation IdLoc, IdentifierInfo *Id,
Sebastian Redl833ef452010-01-26 22:01:41 +00002412 QualType T, TypeSourceInfo *TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002413 StorageClass S, Expr *DefArg) {
Richard Smith053f6c62014-05-16 23:01:30 +00002414 return new (C, DC) ParmVarDecl(ParmVar, C, DC, StartLoc, IdLoc, Id, T, TInfo,
Richard Smithf7981722013-11-22 09:01:48 +00002415 S, DefArg);
Douglas Gregor0760fa12009-03-10 23:43:53 +00002416}
2417
Reid Kleckner8a365022013-06-24 17:51:48 +00002418QualType ParmVarDecl::getOriginalType() const {
2419 TypeSourceInfo *TSI = getTypeSourceInfo();
2420 QualType T = TSI ? TSI->getType() : getType();
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002421 if (const auto *DT = dyn_cast<DecayedType>(T))
Reid Kleckner8a365022013-06-24 17:51:48 +00002422 return DT->getOriginalType();
2423 return T;
2424}
2425
Douglas Gregor72172e92012-01-05 21:55:30 +00002426ParmVarDecl *ParmVarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00002427 return new (C, ID)
2428 ParmVarDecl(ParmVar, C, nullptr, SourceLocation(), SourceLocation(),
2429 nullptr, QualType(), nullptr, SC_None, nullptr);
Douglas Gregor72172e92012-01-05 21:55:30 +00002430}
2431
Argyrios Kyrtzidis4c6efa622011-07-30 17:23:26 +00002432SourceRange ParmVarDecl::getSourceRange() const {
2433 if (!hasInheritedDefaultArg()) {
2434 SourceRange ArgRange = getDefaultArgRange();
2435 if (ArgRange.isValid())
2436 return SourceRange(getOuterLocStart(), ArgRange.getEnd());
2437 }
2438
Argyrios Kyrtzidisa0772792013-04-17 01:56:48 +00002439 // DeclaratorDecl considers the range of postfix types as overlapping with the
2440 // declaration name, but this is not the case with parameters in ObjC methods.
2441 if (isa<ObjCMethodDecl>(getDeclContext()))
2442 return SourceRange(DeclaratorDecl::getLocStart(), getLocation());
2443
Argyrios Kyrtzidis4c6efa622011-07-30 17:23:26 +00002444 return DeclaratorDecl::getSourceRange();
2445}
2446
Sebastian Redl833ef452010-01-26 22:01:41 +00002447Expr *ParmVarDecl::getDefaultArg() {
2448 assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!");
2449 assert(!hasUninstantiatedDefaultArg() &&
2450 "Default argument is not yet instantiated!");
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002451
Sebastian Redl833ef452010-01-26 22:01:41 +00002452 Expr *Arg = getInit();
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002453 if (auto *E = dyn_cast_or_null<ExprWithCleanups>(Arg))
Sebastian Redl833ef452010-01-26 22:01:41 +00002454 return E->getSubExpr();
Douglas Gregor0760fa12009-03-10 23:43:53 +00002455
Sebastian Redl833ef452010-01-26 22:01:41 +00002456 return Arg;
2457}
2458
Chandler Carruth813faed2015-12-30 02:51:00 +00002459void ParmVarDecl::setDefaultArg(Expr *defarg) {
2460 ParmVarDeclBits.DefaultArgKind = DAK_Normal;
2461 Init = defarg;
2462}
Sebastian Redl833ef452010-01-26 22:01:41 +00002463
Chandler Carruth813faed2015-12-30 02:51:00 +00002464SourceRange ParmVarDecl::getDefaultArgRange() const {
2465 switch (ParmVarDeclBits.DefaultArgKind) {
2466 case DAK_None:
2467 case DAK_Unparsed:
2468 // Nothing we can do here.
2469 return SourceRange();
2470
2471 case DAK_Uninstantiated:
Sebastian Redl833ef452010-01-26 22:01:41 +00002472 return getUninstantiatedDefaultArg()->getSourceRange();
2473
Chandler Carruth813faed2015-12-30 02:51:00 +00002474 case DAK_Normal:
2475 if (const Expr *E = getInit())
2476 return E->getSourceRange();
2477
2478 // Missing an actual expression, may be invalid.
2479 return SourceRange();
2480 }
2481 llvm_unreachable("Invalid default argument kind.");
2482}
2483
2484void ParmVarDecl::setUninstantiatedDefaultArg(Expr *arg) {
2485 ParmVarDeclBits.DefaultArgKind = DAK_Uninstantiated;
2486 Init = arg;
2487}
2488
2489Expr *ParmVarDecl::getUninstantiatedDefaultArg() {
2490 assert(hasUninstantiatedDefaultArg() &&
2491 "Wrong kind of initialization expression!");
2492 return cast_or_null<Expr>(Init.get<Stmt *>());
2493}
2494
2495bool ParmVarDecl::hasDefaultArg() const {
2496 // FIXME: We should just return false for DAK_None here once callers are
2497 // prepared for the case that we encountered an invalid default argument and
2498 // were unable to even build an invalid expression.
2499 return hasUnparsedDefaultArg() || hasUninstantiatedDefaultArg() ||
2500 !Init.isNull();
Argyrios Kyrtzidis02dd4f92009-07-05 22:21:56 +00002501}
2502
Douglas Gregor3c6bd2a2011-01-05 21:11:38 +00002503bool ParmVarDecl::isParameterPack() const {
2504 return isa<PackExpansionType>(getType());
2505}
2506
Ted Kremenek540017e2011-10-06 05:00:56 +00002507void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) {
2508 getASTContext().setParameterIndex(this, parameterIndex);
2509 ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel;
2510}
2511
2512unsigned ParmVarDecl::getParameterIndexLarge() const {
2513 return getASTContext().getParameterIndex(this);
2514}
2515
Nuno Lopes394ec982008-12-17 23:39:55 +00002516//===----------------------------------------------------------------------===//
Chris Lattner59a25942008-03-31 00:36:02 +00002517// FunctionDecl Implementation
2518//===----------------------------------------------------------------------===//
2519
Benjamin Kramer9170e912013-02-22 15:46:01 +00002520void FunctionDecl::getNameForDiagnostic(
2521 raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const {
2522 NamedDecl::getNameForDiagnostic(OS, Policy, Qualified);
Douglas Gregorb11aad82011-02-19 18:51:44 +00002523 const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs();
2524 if (TemplateArgs)
Benjamin Kramer9170e912013-02-22 15:46:01 +00002525 TemplateSpecializationType::PrintTemplateArgumentList(
David Majnemer6fbeee32016-07-07 04:43:07 +00002526 OS, TemplateArgs->asArray(), Policy);
Douglas Gregorb11aad82011-02-19 18:51:44 +00002527}
2528
Ted Kremenek186a0742010-04-29 16:49:01 +00002529bool FunctionDecl::isVariadic() const {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002530 if (const auto *FT = getType()->getAs<FunctionProtoType>())
Ted Kremenek186a0742010-04-29 16:49:01 +00002531 return FT->isVariadic();
2532 return false;
2533}
2534
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002535bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const {
Aaron Ballman86c93902014-03-06 23:45:36 +00002536 for (auto I : redecls()) {
Serge Pavlov9a618e12017-02-15 12:30:35 +00002537 if (I->doesThisDeclarationHaveABody()) {
Aaron Ballman86c93902014-03-06 23:45:36 +00002538 Definition = I;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002539 return true;
2540 }
2541 }
2542
2543 return false;
2544}
2545
Anders Carlsson9bd7d162011-05-14 23:26:09 +00002546bool FunctionDecl::hasTrivialBody() const
2547{
2548 Stmt *S = getBody();
2549 if (!S) {
2550 // Since we don't have a body for this function, we don't know if it's
2551 // trivial or not.
2552 return false;
2553 }
2554
2555 if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty())
2556 return true;
2557 return false;
2558}
2559
Alexis Hunt4a8ea102011-05-06 20:44:56 +00002560bool FunctionDecl::isDefined(const FunctionDecl *&Definition) const {
Aaron Ballman86c93902014-03-06 23:45:36 +00002561 for (auto I : redecls()) {
Serge Pavlov10673c92017-06-04 12:53:12 +00002562 if (I->isThisDeclarationADefinition()) {
2563 Definition = I;
Alexis Hunt4a8ea102011-05-06 20:44:56 +00002564 return true;
2565 }
2566 }
2567
2568 return false;
2569}
2570
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00002571Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const {
Rafael Espindola44503012013-10-19 01:37:17 +00002572 if (!hasBody(Definition))
Craig Topper36250ad2014-05-12 05:36:57 +00002573 return nullptr;
Rafael Espindola44503012013-10-19 01:37:17 +00002574
2575 if (Definition->Body)
2576 return Definition->Body.get(getASTContext().getExternalSource());
Douglas Gregor89f238c2008-04-21 02:02:58 +00002577
Craig Topper36250ad2014-05-12 05:36:57 +00002578 return nullptr;
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00002579}
2580
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00002581void FunctionDecl::setBody(Stmt *B) {
2582 Body = B;
Douglas Gregor027ba502010-12-06 17:49:01 +00002583 if (B)
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00002584 EndRangeLoc = B->getLocEnd();
2585}
2586
Douglas Gregor7d9120c2010-09-28 21:55:22 +00002587void FunctionDecl::setPure(bool P) {
2588 IsPure = P;
2589 if (P)
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002590 if (auto *Parent = dyn_cast<CXXRecordDecl>(getDeclContext()))
Douglas Gregor7d9120c2010-09-28 21:55:22 +00002591 Parent->markedVirtualFunctionPure();
2592}
2593
Richard Smith8d0dc312013-07-21 23:12:18 +00002594template<std::size_t Len>
2595static bool isNamed(const NamedDecl *ND, const char (&Str)[Len]) {
2596 IdentifierInfo *II = ND->getIdentifier();
2597 return II && II->isStr(Str);
2598}
2599
Douglas Gregor16618f22009-09-12 00:17:51 +00002600bool FunctionDecl::isMain() const {
John McCall53ffd372011-05-15 17:49:20 +00002601 const TranslationUnitDecl *tunit =
2602 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
2603 return tunit &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002604 !tunit->getASTContext().getLangOpts().Freestanding &&
Richard Smith8d0dc312013-07-21 23:12:18 +00002605 isNamed(this, "main");
John McCall53ffd372011-05-15 17:49:20 +00002606}
2607
David Majnemerc729b0b2013-09-16 22:44:20 +00002608bool FunctionDecl::isMSVCRTEntryPoint() const {
2609 const TranslationUnitDecl *TUnit =
2610 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
2611 if (!TUnit)
2612 return false;
2613
2614 // Even though we aren't really targeting MSVCRT if we are freestanding,
2615 // semantic analysis for these functions remains the same.
2616
2617 // MSVCRT entry points only exist on MSVCRT targets.
2618 if (!TUnit->getASTContext().getTargetInfo().getTriple().isOSMSVCRT())
2619 return false;
2620
2621 // Nameless functions like constructors cannot be entry points.
2622 if (!getIdentifier())
2623 return false;
2624
2625 return llvm::StringSwitch<bool>(getName())
2626 .Cases("main", // an ANSI console app
2627 "wmain", // a Unicode console App
2628 "WinMain", // an ANSI GUI app
2629 "wWinMain", // a Unicode GUI app
2630 "DllMain", // a DLL
2631 true)
2632 .Default(false);
2633}
2634
John McCall53ffd372011-05-15 17:49:20 +00002635bool FunctionDecl::isReservedGlobalPlacementOperator() const {
2636 assert(getDeclName().getNameKind() == DeclarationName::CXXOperatorName);
2637 assert(getDeclName().getCXXOverloadedOperator() == OO_New ||
2638 getDeclName().getCXXOverloadedOperator() == OO_Delete ||
2639 getDeclName().getCXXOverloadedOperator() == OO_Array_New ||
2640 getDeclName().getCXXOverloadedOperator() == OO_Array_Delete);
2641
Richard Smithf6004412014-01-19 23:25:37 +00002642 if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
2643 return false;
John McCall53ffd372011-05-15 17:49:20 +00002644
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002645 const auto *proto = getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00002646 if (proto->getNumParams() != 2 || proto->isVariadic())
2647 return false;
John McCall53ffd372011-05-15 17:49:20 +00002648
2649 ASTContext &Context =
2650 cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext())
2651 ->getASTContext();
2652
2653 // The result type and first argument type are constant across all
2654 // these operators. The second argument must be exactly void*.
Alp Toker9cacbab2014-01-20 20:26:09 +00002655 return (proto->getParamType(1).getCanonicalType() == Context.VoidPtrTy);
Douglas Gregore62c0a42009-02-24 01:23:02 +00002656}
2657
Akira Hatanakacae83f72017-06-29 18:48:40 +00002658bool FunctionDecl::isReplaceableGlobalAllocationFunction(bool *IsAligned) const {
Richard Smith8d0dc312013-07-21 23:12:18 +00002659 if (getDeclName().getNameKind() != DeclarationName::CXXOperatorName)
2660 return false;
2661 if (getDeclName().getCXXOverloadedOperator() != OO_New &&
2662 getDeclName().getCXXOverloadedOperator() != OO_Delete &&
2663 getDeclName().getCXXOverloadedOperator() != OO_Array_New &&
2664 getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
2665 return false;
2666
2667 if (isa<CXXRecordDecl>(getDeclContext()))
2668 return false;
Richard Smithf6004412014-01-19 23:25:37 +00002669
2670 // This can only fail for an invalid 'operator new' declaration.
2671 if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
2672 return false;
Richard Smith8d0dc312013-07-21 23:12:18 +00002673
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002674 const auto *FPT = getType()->castAs<FunctionProtoType>();
Richard Smithb2f0f052016-10-10 18:54:32 +00002675 if (FPT->getNumParams() == 0 || FPT->getNumParams() > 3 || FPT->isVariadic())
Richard Smith8d0dc312013-07-21 23:12:18 +00002676 return false;
2677
2678 // If this is a single-parameter function, it must be a replaceable global
2679 // allocation or deallocation function.
Alp Toker9cacbab2014-01-20 20:26:09 +00002680 if (FPT->getNumParams() == 1)
Richard Smith8d0dc312013-07-21 23:12:18 +00002681 return true;
2682
Richard Smithb2f0f052016-10-10 18:54:32 +00002683 unsigned Params = 1;
2684 QualType Ty = FPT->getParamType(Params);
Richard Smith1cdec012013-09-29 04:40:38 +00002685 ASTContext &Ctx = getASTContext();
Richard Smithb2f0f052016-10-10 18:54:32 +00002686
2687 auto Consume = [&] {
2688 ++Params;
2689 Ty = Params < FPT->getNumParams() ? FPT->getParamType(Params) : QualType();
2690 };
2691
2692 // In C++14, the next parameter can be a 'std::size_t' for sized delete.
2693 bool IsSizedDelete = false;
Richard Smithb47c36f2013-11-05 09:12:18 +00002694 if (Ctx.getLangOpts().SizedDeallocation &&
Richard Smithb2f0f052016-10-10 18:54:32 +00002695 (getDeclName().getCXXOverloadedOperator() == OO_Delete ||
2696 getDeclName().getCXXOverloadedOperator() == OO_Array_Delete) &&
2697 Ctx.hasSameType(Ty, Ctx.getSizeType())) {
2698 IsSizedDelete = true;
2699 Consume();
2700 }
2701
2702 // In C++17, the next parameter can be a 'std::align_val_t' for aligned
2703 // new/delete.
Akira Hatanakacae83f72017-06-29 18:48:40 +00002704 if (Ctx.getLangOpts().AlignedAllocation && !Ty.isNull() && Ty->isAlignValT()) {
2705 if (IsAligned)
2706 *IsAligned = true;
Richard Smithb2f0f052016-10-10 18:54:32 +00002707 Consume();
Akira Hatanakacae83f72017-06-29 18:48:40 +00002708 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002709
2710 // Finally, if this is not a sized delete, the final parameter can
2711 // be a 'const std::nothrow_t&'.
2712 if (!IsSizedDelete && !Ty.isNull() && Ty->isReferenceType()) {
2713 Ty = Ty->getPointeeType();
2714 if (Ty.getCVRQualifiers() != Qualifiers::Const)
2715 return false;
2716 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
2717 if (RD && isNamed(RD, "nothrow_t") && RD->isInStdNamespace())
2718 Consume();
2719 }
2720
2721 return Params == FPT->getNumParams();
Richard Smith8d0dc312013-07-21 23:12:18 +00002722}
2723
Rafael Espindolaf4187652013-02-14 01:18:37 +00002724LanguageLinkage FunctionDecl::getLanguageLinkage() const {
Alp Toker84212df2014-05-31 06:11:02 +00002725 return getDeclLanguageLinkage(*this);
Rafael Espindola576127d2012-12-28 14:21:58 +00002726}
2727
Rafael Espindola0e0d0092013-03-14 03:07:35 +00002728bool FunctionDecl::isExternC() const {
Alp Toker84212df2014-05-31 06:11:02 +00002729 return isDeclExternC(*this);
Rafael Espindola0e0d0092013-03-14 03:07:35 +00002730}
2731
Rafael Espindola593537a2013-05-05 20:15:21 +00002732bool FunctionDecl::isInExternCContext() const {
Serge Pavlov3cb80222013-11-14 02:13:03 +00002733 return getLexicalDeclContext()->isExternCContext();
Rafael Espindola593537a2013-05-05 20:15:21 +00002734}
2735
2736bool FunctionDecl::isInExternCXXContext() const {
Serge Pavlov3cb80222013-11-14 02:13:03 +00002737 return getLexicalDeclContext()->isExternCXXContext();
Rafael Espindola593537a2013-05-05 20:15:21 +00002738}
2739
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002740bool FunctionDecl::isGlobal() const {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002741 if (const auto *Method = dyn_cast<CXXMethodDecl>(this))
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002742 return Method->isStatic();
2743
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002744 if (getCanonicalDecl()->getStorageClass() == SC_Static)
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002745 return false;
2746
Mike Stump11289f42009-09-09 15:08:12 +00002747 for (const DeclContext *DC = getDeclContext();
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002748 DC->isNamespace();
2749 DC = DC->getParent()) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002750 if (const auto *Namespace = cast<NamespaceDecl>(DC)) {
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002751 if (!Namespace->getDeclName())
2752 return false;
2753 break;
2754 }
2755 }
2756
2757 return true;
2758}
2759
Richard Smith10876ef2013-01-17 01:30:42 +00002760bool FunctionDecl::isNoReturn() const {
Adrian Prantl721c7cb2016-08-17 16:42:15 +00002761 if (hasAttr<NoReturnAttr>() || hasAttr<CXX11NoReturnAttr>() ||
2762 hasAttr<C11NoReturnAttr>())
2763 return true;
2764
2765 if (auto *FnTy = getType()->getAs<FunctionType>())
2766 return FnTy->getNoReturnAttr();
2767
2768 return false;
Richard Smith10876ef2013-01-17 01:30:42 +00002769}
2770
Sebastian Redl833ef452010-01-26 22:01:41 +00002771void
2772FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00002773 redeclarable_base::setPreviousDecl(PrevDecl);
Sebastian Redl833ef452010-01-26 22:01:41 +00002774
2775 if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) {
2776 FunctionTemplateDecl *PrevFunTmpl
Craig Topper36250ad2014-05-12 05:36:57 +00002777 = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : nullptr;
Sebastian Redl833ef452010-01-26 22:01:41 +00002778 assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch");
Rafael Espindola8db352d2013-10-17 15:37:26 +00002779 FunTmpl->setPreviousDecl(PrevFunTmpl);
Sebastian Redl833ef452010-01-26 22:01:41 +00002780 }
Douglas Gregorff76cb92010-12-09 16:59:22 +00002781
Axel Naumannfbc7b982011-11-08 18:21:06 +00002782 if (PrevDecl && PrevDecl->IsInline)
Douglas Gregorff76cb92010-12-09 16:59:22 +00002783 IsInline = true;
Sebastian Redl833ef452010-01-26 22:01:41 +00002784}
2785
Rafael Espindola8db352d2013-10-17 15:37:26 +00002786FunctionDecl *FunctionDecl::getCanonicalDecl() { return getFirstDecl(); }
Sebastian Redl833ef452010-01-26 22:01:41 +00002787
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002788/// \brief Returns a value indicating whether this function
2789/// corresponds to a builtin function.
2790///
2791/// The function corresponds to a built-in function if it is
2792/// declared at translation scope or within an extern "C" block and
2793/// its name matches with the name of a builtin. The returned value
2794/// will be 0 for functions that do not correspond to a builtin, a
Mike Stump11289f42009-09-09 15:08:12 +00002795/// value of type \c Builtin::ID if in the target-independent range
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002796/// \c [1,Builtin::First), or a target-specific builtin value.
Douglas Gregor15fc9562009-09-12 00:22:50 +00002797unsigned FunctionDecl::getBuiltinID() const {
Daniel Dunbar304314d2012-03-06 23:52:37 +00002798 if (!getIdentifier())
Douglas Gregore711f702009-02-14 18:57:46 +00002799 return 0;
2800
2801 unsigned BuiltinID = getIdentifier()->getBuiltinID();
Daniel Dunbar304314d2012-03-06 23:52:37 +00002802 if (!BuiltinID)
2803 return 0;
2804
2805 ASTContext &Context = getASTContext();
Warren Hunt445d83e2013-11-01 23:46:51 +00002806 if (Context.getLangOpts().CPlusPlus) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002807 const auto *LinkageDecl =
2808 dyn_cast<LinkageSpecDecl>(getFirstDecl()->getDeclContext());
Warren Hunt445d83e2013-11-01 23:46:51 +00002809 // In C++, the first declaration of a builtin is always inside an implicit
2810 // extern "C".
2811 // FIXME: A recognised library function may not be directly in an extern "C"
2812 // declaration, for instance "extern "C" { namespace std { decl } }".
David Majnemerba3e5ec2015-03-13 18:26:17 +00002813 if (!LinkageDecl) {
2814 if (BuiltinID == Builtin::BI__GetExceptionInfo &&
David Majnemer145abde2016-01-26 01:12:17 +00002815 Context.getTargetInfo().getCXXABI().isMicrosoft())
David Majnemerba3e5ec2015-03-13 18:26:17 +00002816 return Builtin::BI__GetExceptionInfo;
2817 return 0;
2818 }
2819 if (LinkageDecl->getLanguage() != LinkageSpecDecl::lang_c)
Warren Hunt445d83e2013-11-01 23:46:51 +00002820 return 0;
2821 }
2822
2823 // If the function is marked "overloadable", it has a different mangled name
2824 // and is not the C library function.
Aaron Ballman9ead1242013-12-19 02:39:40 +00002825 if (hasAttr<OverloadableAttr>())
Warren Hunt445d83e2013-11-01 23:46:51 +00002826 return 0;
2827
Douglas Gregore711f702009-02-14 18:57:46 +00002828 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
2829 return BuiltinID;
2830
2831 // This function has the name of a known C library
2832 // function. Determine whether it actually refers to the C library
2833 // function or whether it just has the same name.
2834
Douglas Gregora908e7f2009-02-17 03:23:10 +00002835 // If this is a static function, it's not a builtin.
John McCall8e7d6562010-08-26 03:08:43 +00002836 if (getStorageClass() == SC_Static)
Douglas Gregora908e7f2009-02-17 03:23:10 +00002837 return 0;
2838
Anastasia Stulova1202de32016-02-12 12:07:04 +00002839 // OpenCL v1.2 s6.9.f - The library functions defined in
2840 // the C99 standard headers are not available.
2841 if (Context.getLangOpts().OpenCL &&
2842 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
2843 return 0;
2844
Warren Hunt445d83e2013-11-01 23:46:51 +00002845 return BuiltinID;
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002846}
2847
2848
Chris Lattner47c0d002009-04-25 06:03:53 +00002849/// getNumParams - Return the number of parameters this function must have
Bob Wilsonb39017a2011-01-10 18:23:55 +00002850/// based on its FunctionType. This is the length of the ParamInfo array
Chris Lattner47c0d002009-04-25 06:03:53 +00002851/// after it has been created.
2852unsigned FunctionDecl::getNumParams() const {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002853 const auto *FPT = getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00002854 return FPT ? FPT->getNumParams() : 0;
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00002855}
2856
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00002857void FunctionDecl::setParams(ASTContext &C,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002858 ArrayRef<ParmVarDecl *> NewParamInfo) {
Craig Topper36250ad2014-05-12 05:36:57 +00002859 assert(!ParamInfo && "Already has param info!");
David Blaikie9c70e042011-09-21 18:16:56 +00002860 assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!");
Mike Stump11289f42009-09-09 15:08:12 +00002861
Chris Lattner8f5bf2f2007-01-21 19:04:10 +00002862 // Zero params -> null pointer.
David Blaikie9c70e042011-09-21 18:16:56 +00002863 if (!NewParamInfo.empty()) {
2864 ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()];
2865 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
Chris Lattner8f5bf2f2007-01-21 19:04:10 +00002866 }
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00002867}
Chris Lattner41943152007-01-25 04:52:46 +00002868
Chris Lattner58258242008-04-10 02:22:51 +00002869/// getMinRequiredArguments - Returns the minimum number of arguments
2870/// needed to call this function. This may be fewer than the number of
2871/// function parameters, if some of the parameters have default
Richard Smith91151782014-04-01 19:18:16 +00002872/// arguments (in C++) or are parameter packs (C++11).
Chris Lattner58258242008-04-10 02:22:51 +00002873unsigned FunctionDecl::getMinRequiredArguments() const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002874 if (!getASTContext().getLangOpts().CPlusPlus)
Douglas Gregor0dd423e2011-01-11 01:52:23 +00002875 return getNumParams();
Chris Lattner58258242008-04-10 02:22:51 +00002876
Richard Smith91151782014-04-01 19:18:16 +00002877 unsigned NumRequiredArgs = 0;
David Majnemer59f77922016-06-24 04:05:48 +00002878 for (auto *Param : parameters())
Richard Smith91151782014-04-01 19:18:16 +00002879 if (!Param->isParameterPack() && !Param->hasDefaultArg())
2880 ++NumRequiredArgs;
Chris Lattner58258242008-04-10 02:22:51 +00002881 return NumRequiredArgs;
2882}
2883
David Majnemer54e3ba52014-04-02 23:17:29 +00002884/// \brief The combination of the extern and inline keywords under MSVC forces
2885/// the function to be required.
2886///
2887/// Note: This function assumes that we will only get called when isInlined()
2888/// would return true for this FunctionDecl.
2889bool FunctionDecl::isMSExternInline() const {
2890 assert(isInlined() && "expected to get called on an inlined function!");
2891
2892 const ASTContext &Context = getASTContext();
David Majnemer3f021502015-10-08 04:53:31 +00002893 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
2894 !hasAttr<DLLExportAttr>())
David Majnemer54e3ba52014-04-02 23:17:29 +00002895 return false;
2896
David Majnemer73768702015-03-20 00:02:27 +00002897 for (const FunctionDecl *FD = getMostRecentDecl(); FD;
2898 FD = FD->getPreviousDecl())
David Majnemerc0c42f32015-07-10 20:55:38 +00002899 if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern)
David Majnemer54e3ba52014-04-02 23:17:29 +00002900 return true;
2901
2902 return false;
2903}
2904
2905static bool redeclForcesDefMSVC(const FunctionDecl *Redecl) {
2906 if (Redecl->getStorageClass() != SC_Extern)
2907 return false;
2908
2909 for (const FunctionDecl *FD = Redecl->getPreviousDecl(); FD;
2910 FD = FD->getPreviousDecl())
David Majnemerc0c42f32015-07-10 20:55:38 +00002911 if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern)
David Majnemer54e3ba52014-04-02 23:17:29 +00002912 return false;
2913
2914 return true;
2915}
2916
Eli Friedman1b125c32012-02-07 03:50:18 +00002917static bool RedeclForcesDefC99(const FunctionDecl *Redecl) {
2918 // Only consider file-scope declarations in this test.
2919 if (!Redecl->getLexicalDeclContext()->isTranslationUnit())
2920 return false;
2921
2922 // Only consider explicit declarations; the presence of a builtin for a
2923 // libcall shouldn't affect whether a definition is externally visible.
2924 if (Redecl->isImplicit())
2925 return false;
2926
2927 if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern)
2928 return true; // Not an inline definition
2929
2930 return false;
2931}
2932
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002933/// \brief For a function declaration in C or C++, determine whether this
2934/// declaration causes the definition to be externally visible.
2935///
David Majnemer54e3ba52014-04-02 23:17:29 +00002936/// For instance, this determines if adding the current declaration to the set
Eli Friedman1b125c32012-02-07 03:50:18 +00002937/// of redeclarations of the given functions causes
2938/// isInlineDefinitionExternallyVisible to change from false to true.
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002939bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const {
Justin Lebar0241c962016-10-28 16:46:39 +00002940 assert(!doesThisDeclarationHaveABody() &&
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002941 "Must have a declaration without a body.");
2942
2943 ASTContext &Context = getASTContext();
2944
David Majnemer54e3ba52014-04-02 23:17:29 +00002945 if (Context.getLangOpts().MSVCCompat) {
2946 const FunctionDecl *Definition;
2947 if (hasBody(Definition) && Definition->isInlined() &&
2948 redeclForcesDefMSVC(this))
2949 return true;
2950 }
2951
David Blaikiebbafb8a2012-03-11 07:00:24 +00002952 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
Eli Friedman1b125c32012-02-07 03:50:18 +00002953 // With GNU inlining, a declaration with 'inline' but not 'extern', forces
2954 // an externally visible definition.
2955 //
2956 // FIXME: What happens if gnu_inline gets added on after the first
2957 // declaration?
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002958 if (!isInlineSpecified() || getStorageClass() == SC_Extern)
Eli Friedman1b125c32012-02-07 03:50:18 +00002959 return false;
2960
2961 const FunctionDecl *Prev = this;
2962 bool FoundBody = false;
2963 while ((Prev = Prev->getPreviousDecl())) {
David Blaikie7d170102013-05-15 07:37:26 +00002964 FoundBody |= Prev->Body.isValid();
Eli Friedman1b125c32012-02-07 03:50:18 +00002965
2966 if (Prev->Body) {
2967 // If it's not the case that both 'inline' and 'extern' are
2968 // specified on the definition, then it is always externally visible.
2969 if (!Prev->isInlineSpecified() ||
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002970 Prev->getStorageClass() != SC_Extern)
Eli Friedman1b125c32012-02-07 03:50:18 +00002971 return false;
2972 } else if (Prev->isInlineSpecified() &&
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002973 Prev->getStorageClass() != SC_Extern) {
Eli Friedman1b125c32012-02-07 03:50:18 +00002974 return false;
2975 }
2976 }
2977 return FoundBody;
2978 }
2979
David Blaikiebbafb8a2012-03-11 07:00:24 +00002980 if (Context.getLangOpts().CPlusPlus)
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002981 return false;
Eli Friedman1b125c32012-02-07 03:50:18 +00002982
2983 // C99 6.7.4p6:
2984 // [...] If all of the file scope declarations for a function in a
2985 // translation unit include the inline function specifier without extern,
2986 // then the definition in that translation unit is an inline definition.
2987 if (isInlineSpecified() && getStorageClass() != SC_Extern)
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002988 return false;
Eli Friedman1b125c32012-02-07 03:50:18 +00002989 const FunctionDecl *Prev = this;
2990 bool FoundBody = false;
2991 while ((Prev = Prev->getPreviousDecl())) {
David Blaikie7d170102013-05-15 07:37:26 +00002992 FoundBody |= Prev->Body.isValid();
Eli Friedman1b125c32012-02-07 03:50:18 +00002993 if (RedeclForcesDefC99(Prev))
2994 return false;
2995 }
2996 return FoundBody;
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002997}
2998
Alp Tokerd0787eb2014-07-02 01:47:15 +00002999SourceRange FunctionDecl::getReturnTypeSourceRange() const {
3000 const TypeSourceInfo *TSI = getTypeSourceInfo();
3001 if (!TSI)
3002 return SourceRange();
Alp Tokerf5b10792014-07-02 12:55:58 +00003003 FunctionTypeLoc FTL =
3004 TSI->getTypeLoc().IgnoreParens().getAs<FunctionTypeLoc>();
3005 if (!FTL)
Alp Tokerd0787eb2014-07-02 01:47:15 +00003006 return SourceRange();
3007
Alp Tokerf5b10792014-07-02 12:55:58 +00003008 // Skip self-referential return types.
3009 const SourceManager &SM = getASTContext().getSourceManager();
3010 SourceRange RTRange = FTL.getReturnLoc().getSourceRange();
3011 SourceLocation Boundary = getNameInfo().getLocStart();
3012 if (RTRange.isInvalid() || Boundary.isInvalid() ||
3013 !SM.isBeforeInTranslationUnit(RTRange.getEnd(), Boundary))
3014 return SourceRange();
Alp Tokerd0787eb2014-07-02 01:47:15 +00003015
Alp Tokerf5b10792014-07-02 12:55:58 +00003016 return RTRange;
Alp Tokerd0787eb2014-07-02 01:47:15 +00003017}
3018
Malcolm Parsonsa3220ce2017-01-12 16:11:28 +00003019SourceRange FunctionDecl::getExceptionSpecSourceRange() const {
3020 const TypeSourceInfo *TSI = getTypeSourceInfo();
3021 if (!TSI)
3022 return SourceRange();
3023 FunctionTypeLoc FTL =
3024 TSI->getTypeLoc().IgnoreParens().getAs<FunctionTypeLoc>();
3025 if (!FTL)
3026 return SourceRange();
3027
3028 return FTL.getExceptionSpecRange();
3029}
3030
Aaron Ballmane7964782016-03-07 22:44:55 +00003031const Attr *FunctionDecl::getUnusedResultAttr() const {
Kaelyn Takata0a2e84c2015-04-09 19:43:04 +00003032 QualType RetType = getReturnType();
3033 if (RetType->isRecordType()) {
Erich Keane4b87d812017-04-19 21:24:55 +00003034 if (const CXXRecordDecl *Ret = RetType->getAsCXXRecordDecl()) {
Aaron Ballmane7964782016-03-07 22:44:55 +00003035 if (const auto *R = Ret->getAttr<WarnUnusedResultAttr>())
3036 return R;
3037 }
3038 } else if (const auto *ET = RetType->getAs<EnumType>()) {
3039 if (const EnumDecl *ED = ET->getDecl()) {
3040 if (const auto *R = ED->getAttr<WarnUnusedResultAttr>())
3041 return R;
3042 }
Kaelyn Takata0a2e84c2015-04-09 19:43:04 +00003043 }
Aaron Ballmane7964782016-03-07 22:44:55 +00003044 return getAttr<WarnUnusedResultAttr>();
Kaelyn Takata0a2e84c2015-04-09 19:43:04 +00003045}
3046
Richard Smithf3814ad2013-01-25 00:08:28 +00003047/// \brief For an inline function definition in C, or for a gnu_inline function
3048/// in C++, determine whether the definition will be externally visible.
Douglas Gregor299d76e2009-09-13 07:46:26 +00003049///
3050/// Inline function definitions are always available for inlining optimizations.
3051/// However, depending on the language dialect, declaration specifiers, and
3052/// attributes, the definition of an inline function may or may not be
3053/// "externally" visible to other translation units in the program.
3054///
3055/// In C99, inline definitions are not externally visible by default. However,
Mike Stump13c66702010-01-06 02:05:39 +00003056/// if even one of the global-scope declarations is marked "extern inline", the
Douglas Gregor299d76e2009-09-13 07:46:26 +00003057/// inline definition becomes externally visible (C99 6.7.4p6).
3058///
3059/// In GNU89 mode, or if the gnu_inline attribute is attached to the function
3060/// definition, we use the GNU semantics for inline, which are nearly the
3061/// opposite of C99 semantics. In particular, "inline" by itself will create
3062/// an externally visible symbol, but "extern inline" will not create an
3063/// externally visible symbol.
3064bool FunctionDecl::isInlineDefinitionExternallyVisible() const {
Manuel Klimekda7456a2016-11-01 10:30:50 +00003065 assert((doesThisDeclarationHaveABody() || willHaveBody()) &&
3066 "Must be a function definition");
Douglas Gregor583dcaf2009-10-27 21:11:48 +00003067 assert(isInlined() && "Function must be inline");
Douglas Gregorb7e5c842009-10-27 23:26:40 +00003068 ASTContext &Context = getASTContext();
Douglas Gregor299d76e2009-09-13 07:46:26 +00003069
David Blaikiebbafb8a2012-03-11 07:00:24 +00003070 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
Eli Friedman1b125c32012-02-07 03:50:18 +00003071 // Note: If you change the logic here, please change
3072 // doesDeclarationForceExternallyVisibleDefinition as well.
3073 //
Douglas Gregorff76cb92010-12-09 16:59:22 +00003074 // If it's not the case that both 'inline' and 'extern' are
3075 // specified on the definition, then this inline definition is
3076 // externally visible.
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003077 if (!(isInlineSpecified() && getStorageClass() == SC_Extern))
Douglas Gregorff76cb92010-12-09 16:59:22 +00003078 return true;
3079
3080 // If any declaration is 'inline' but not 'extern', then this definition
3081 // is externally visible.
Aaron Ballman86c93902014-03-06 23:45:36 +00003082 for (auto Redecl : redecls()) {
Douglas Gregorff76cb92010-12-09 16:59:22 +00003083 if (Redecl->isInlineSpecified() &&
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003084 Redecl->getStorageClass() != SC_Extern)
Douglas Gregor299d76e2009-09-13 07:46:26 +00003085 return true;
Douglas Gregorff76cb92010-12-09 16:59:22 +00003086 }
Douglas Gregor299d76e2009-09-13 07:46:26 +00003087
Douglas Gregor76fe50c2009-04-28 06:37:30 +00003088 return false;
Douglas Gregor299d76e2009-09-13 07:46:26 +00003089 }
Eli Friedman1b125c32012-02-07 03:50:18 +00003090
Richard Smithf3814ad2013-01-25 00:08:28 +00003091 // The rest of this function is C-only.
3092 assert(!Context.getLangOpts().CPlusPlus &&
3093 "should not use C inline rules in C++");
3094
Douglas Gregor299d76e2009-09-13 07:46:26 +00003095 // C99 6.7.4p6:
3096 // [...] If all of the file scope declarations for a function in a
3097 // translation unit include the inline function specifier without extern,
3098 // then the definition in that translation unit is an inline definition.
Aaron Ballman86c93902014-03-06 23:45:36 +00003099 for (auto Redecl : redecls()) {
3100 if (RedeclForcesDefC99(Redecl))
Eli Friedman1b125c32012-02-07 03:50:18 +00003101 return true;
Douglas Gregor299d76e2009-09-13 07:46:26 +00003102 }
3103
3104 // C99 6.7.4p6:
3105 // An inline definition does not provide an external definition for the
3106 // function, and does not forbid an external definition in another
3107 // translation unit.
Douglas Gregor76fe50c2009-04-28 06:37:30 +00003108 return false;
3109}
3110
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00003111/// getOverloadedOperator - Which C++ overloaded operator this
3112/// function represents, if any.
3113OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const {
Douglas Gregor163c5852008-11-18 14:39:36 +00003114 if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
3115 return getDeclName().getCXXOverloadedOperator();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00003116 else
3117 return OO_None;
3118}
3119
Alexis Huntc88db062010-01-13 09:01:02 +00003120/// getLiteralIdentifier - The literal suffix identifier this function
3121/// represents, if any.
3122const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const {
3123 if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName)
3124 return getDeclName().getCXXLiteralIdentifier();
3125 else
Craig Topper36250ad2014-05-12 05:36:57 +00003126 return nullptr;
Alexis Huntc88db062010-01-13 09:01:02 +00003127}
3128
Argyrios Kyrtzidiscb6f3462010-06-22 09:54:51 +00003129FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const {
3130 if (TemplateOrSpecialization.isNull())
3131 return TK_NonTemplate;
3132 if (TemplateOrSpecialization.is<FunctionTemplateDecl *>())
3133 return TK_FunctionTemplate;
3134 if (TemplateOrSpecialization.is<MemberSpecializationInfo *>())
3135 return TK_MemberSpecialization;
3136 if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>())
3137 return TK_FunctionTemplateSpecialization;
3138 if (TemplateOrSpecialization.is
3139 <DependentFunctionTemplateSpecializationInfo*>())
3140 return TK_DependentFunctionTemplateSpecialization;
3141
David Blaikie83d382b2011-09-23 05:06:16 +00003142 llvm_unreachable("Did we miss a TemplateOrSpecialization type?");
Argyrios Kyrtzidiscb6f3462010-06-22 09:54:51 +00003143}
3144
Douglas Gregord801b062009-10-07 23:56:10 +00003145FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const {
Douglas Gregor06db9f52009-10-12 20:18:28 +00003146 if (MemberSpecializationInfo *Info = getMemberSpecializationInfo())
Douglas Gregord801b062009-10-07 23:56:10 +00003147 return cast<FunctionDecl>(Info->getInstantiatedFrom());
Craig Topper36250ad2014-05-12 05:36:57 +00003148
3149 return nullptr;
Douglas Gregord801b062009-10-07 23:56:10 +00003150}
3151
Chandler Carruth21c90602015-12-30 03:24:14 +00003152MemberSpecializationInfo *FunctionDecl::getMemberSpecializationInfo() const {
3153 return TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>();
3154}
3155
Douglas Gregord801b062009-10-07 23:56:10 +00003156void
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00003157FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C,
3158 FunctionDecl *FD,
Douglas Gregord801b062009-10-07 23:56:10 +00003159 TemplateSpecializationKind TSK) {
3160 assert(TemplateOrSpecialization.isNull() &&
3161 "Member function is already a specialization");
3162 MemberSpecializationInfo *Info
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00003163 = new (C) MemberSpecializationInfo(FD, TSK);
Douglas Gregord801b062009-10-07 23:56:10 +00003164 TemplateOrSpecialization = Info;
3165}
3166
Chandler Carruth21c90602015-12-30 03:24:14 +00003167FunctionTemplateDecl *FunctionDecl::getDescribedFunctionTemplate() const {
3168 return TemplateOrSpecialization.dyn_cast<FunctionTemplateDecl *>();
3169}
3170
3171void FunctionDecl::setDescribedFunctionTemplate(FunctionTemplateDecl *Template) {
3172 TemplateOrSpecialization = Template;
3173}
3174
Douglas Gregorafca3b42009-10-27 20:53:28 +00003175bool FunctionDecl::isImplicitlyInstantiable() const {
Douglas Gregor69f6a362010-05-17 17:34:56 +00003176 // If the function is invalid, it can't be implicitly instantiated.
3177 if (isInvalidDecl())
Douglas Gregorafca3b42009-10-27 20:53:28 +00003178 return false;
3179
3180 switch (getTemplateSpecializationKind()) {
3181 case TSK_Undeclared:
Douglas Gregorafca3b42009-10-27 20:53:28 +00003182 case TSK_ExplicitInstantiationDefinition:
3183 return false;
3184
3185 case TSK_ImplicitInstantiation:
3186 return true;
3187
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003188 // It is possible to instantiate TSK_ExplicitSpecialization kind
3189 // if the FunctionDecl has a class scope specialization pattern.
3190 case TSK_ExplicitSpecialization:
Craig Topper36250ad2014-05-12 05:36:57 +00003191 return getClassScopeSpecializationPattern() != nullptr;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003192
Douglas Gregorafca3b42009-10-27 20:53:28 +00003193 case TSK_ExplicitInstantiationDeclaration:
3194 // Handled below.
3195 break;
3196 }
3197
3198 // Find the actual template from which we will instantiate.
3199 const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003200 bool HasPattern = false;
Douglas Gregorafca3b42009-10-27 20:53:28 +00003201 if (PatternDecl)
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003202 HasPattern = PatternDecl->hasBody(PatternDecl);
Douglas Gregorafca3b42009-10-27 20:53:28 +00003203
3204 // C++0x [temp.explicit]p9:
3205 // Except for inline functions, other explicit instantiation declarations
3206 // have the effect of suppressing the implicit instantiation of the entity
3207 // to which they refer.
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003208 if (!HasPattern || !PatternDecl)
Douglas Gregorafca3b42009-10-27 20:53:28 +00003209 return true;
3210
Douglas Gregor583dcaf2009-10-27 21:11:48 +00003211 return PatternDecl->isInlined();
Ted Kremenek85825ae2011-12-01 00:59:17 +00003212}
3213
3214bool FunctionDecl::isTemplateInstantiation() const {
3215 switch (getTemplateSpecializationKind()) {
3216 case TSK_Undeclared:
3217 case TSK_ExplicitSpecialization:
3218 return false;
3219 case TSK_ImplicitInstantiation:
3220 case TSK_ExplicitInstantiationDeclaration:
3221 case TSK_ExplicitInstantiationDefinition:
3222 return true;
3223 }
3224 llvm_unreachable("All TSK values handled.");
3225}
Douglas Gregorafca3b42009-10-27 20:53:28 +00003226
3227FunctionDecl *FunctionDecl::getTemplateInstantiationPattern() const {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003228 // Handle class scope explicit specialization special case.
Richard Smith2195ec92017-04-21 01:15:13 +00003229 if (getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
3230 if (auto *Spec = getClassScopeSpecializationPattern())
3231 return getDefinitionOrSelf(Spec);
3232 return nullptr;
3233 }
3234
Faisal Valib90b2112014-04-03 16:32:21 +00003235 // If this is a generic lambda call operator specialization, its
3236 // instantiation pattern is always its primary template's pattern
3237 // even if its primary template was instantiated from another
3238 // member template (which happens with nested generic lambdas).
3239 // Since a lambda's call operator's body is transformed eagerly,
3240 // we don't have to go hunting for a prototype definition template
3241 // (i.e. instantiated-from-member-template) to use as an instantiation
3242 // pattern.
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003243
Faisal Valib90b2112014-04-03 16:32:21 +00003244 if (isGenericLambdaCallOperatorSpecialization(
3245 dyn_cast<CXXMethodDecl>(this))) {
Richard Smith2195ec92017-04-21 01:15:13 +00003246 assert(getPrimaryTemplate() && "not a generic lambda call operator?");
3247 return getDefinitionOrSelf(getPrimaryTemplate()->getTemplatedDecl());
Faisal Valib90b2112014-04-03 16:32:21 +00003248 }
Richard Smith2195ec92017-04-21 01:15:13 +00003249
Douglas Gregorafca3b42009-10-27 20:53:28 +00003250 if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) {
3251 while (Primary->getInstantiatedFromMemberTemplate()) {
3252 // If we have hit a point where the user provided a specialization of
3253 // this template, we're done looking.
3254 if (Primary->isMemberSpecialization())
3255 break;
Douglas Gregorafca3b42009-10-27 20:53:28 +00003256 Primary = Primary->getInstantiatedFromMemberTemplate();
3257 }
Richard Smith2195ec92017-04-21 01:15:13 +00003258
3259 return getDefinitionOrSelf(Primary->getTemplatedDecl());
Douglas Gregorafca3b42009-10-27 20:53:28 +00003260 }
Richard Smith2195ec92017-04-21 01:15:13 +00003261
3262 if (auto *MFD = getInstantiatedFromMemberFunction())
3263 return getDefinitionOrSelf(MFD);
3264
3265 return nullptr;
Douglas Gregorafca3b42009-10-27 20:53:28 +00003266}
3267
Douglas Gregor70d83e22009-06-29 17:30:29 +00003268FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const {
Mike Stump11289f42009-09-09 15:08:12 +00003269 if (FunctionTemplateSpecializationInfo *Info
Douglas Gregor70d83e22009-06-29 17:30:29 +00003270 = TemplateOrSpecialization
3271 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
Douglas Gregore8925db2009-06-29 22:39:32 +00003272 return Info->Template.getPointer();
Douglas Gregor70d83e22009-06-29 17:30:29 +00003273 }
Craig Topper36250ad2014-05-12 05:36:57 +00003274 return nullptr;
Douglas Gregor70d83e22009-06-29 17:30:29 +00003275}
3276
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003277FunctionDecl *FunctionDecl::getClassScopeSpecializationPattern() const {
3278 return getASTContext().getClassScopeSpecializationPattern(this);
3279}
3280
Chandler Carruth21c90602015-12-30 03:24:14 +00003281FunctionTemplateSpecializationInfo *
3282FunctionDecl::getTemplateSpecializationInfo() const {
3283 return TemplateOrSpecialization
3284 .dyn_cast<FunctionTemplateSpecializationInfo *>();
3285}
3286
Douglas Gregor70d83e22009-06-29 17:30:29 +00003287const TemplateArgumentList *
3288FunctionDecl::getTemplateSpecializationArgs() const {
Mike Stump11289f42009-09-09 15:08:12 +00003289 if (FunctionTemplateSpecializationInfo *Info
Douglas Gregorcf915552009-10-13 16:30:37 +00003290 = TemplateOrSpecialization
3291 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
Douglas Gregor70d83e22009-06-29 17:30:29 +00003292 return Info->TemplateArguments;
3293 }
Craig Topper36250ad2014-05-12 05:36:57 +00003294 return nullptr;
Douglas Gregor70d83e22009-06-29 17:30:29 +00003295}
3296
Argyrios Kyrtzidise9a24432011-09-22 20:07:09 +00003297const ASTTemplateArgumentListInfo *
Abramo Bagnara02ccd282010-05-20 15:32:11 +00003298FunctionDecl::getTemplateSpecializationArgsAsWritten() const {
3299 if (FunctionTemplateSpecializationInfo *Info
3300 = TemplateOrSpecialization
3301 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
3302 return Info->TemplateArgumentsAsWritten;
3303 }
Craig Topper36250ad2014-05-12 05:36:57 +00003304 return nullptr;
Abramo Bagnara02ccd282010-05-20 15:32:11 +00003305}
3306
Mike Stump11289f42009-09-09 15:08:12 +00003307void
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00003308FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C,
3309 FunctionTemplateDecl *Template,
Douglas Gregor8f5d4422009-06-29 20:59:39 +00003310 const TemplateArgumentList *TemplateArgs,
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003311 void *InsertPos,
Abramo Bagnara02ccd282010-05-20 15:32:11 +00003312 TemplateSpecializationKind TSK,
Argyrios Kyrtzidis927d8e02010-07-05 10:37:55 +00003313 const TemplateArgumentListInfo *TemplateArgsAsWritten,
3314 SourceLocation PointOfInstantiation) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003315 assert(TSK != TSK_Undeclared &&
3316 "Must specify the type of function template specialization");
Mike Stump11289f42009-09-09 15:08:12 +00003317 FunctionTemplateSpecializationInfo *Info
Douglas Gregor70d83e22009-06-29 17:30:29 +00003318 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00003319 if (!Info)
Argyrios Kyrtzidise262a952010-09-09 11:28:23 +00003320 Info = FunctionTemplateSpecializationInfo::Create(C, this, Template, TSK,
3321 TemplateArgs,
3322 TemplateArgsAsWritten,
3323 PointOfInstantiation);
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00003324 TemplateOrSpecialization = Info;
Douglas Gregorce9978f2012-03-28 14:34:23 +00003325 Template->addSpecialization(Info, InsertPos);
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00003326}
3327
John McCallb9c78482010-04-08 09:05:18 +00003328void
3329FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context,
3330 const UnresolvedSetImpl &Templates,
3331 const TemplateArgumentListInfo &TemplateArgs) {
3332 assert(TemplateOrSpecialization.isNull());
John McCallb9c78482010-04-08 09:05:18 +00003333 DependentFunctionTemplateSpecializationInfo *Info =
James Y Knight7a22b242015-08-06 20:26:32 +00003334 DependentFunctionTemplateSpecializationInfo::Create(Context, Templates,
3335 TemplateArgs);
John McCallb9c78482010-04-08 09:05:18 +00003336 TemplateOrSpecialization = Info;
3337}
3338
James Y Knight7a22b242015-08-06 20:26:32 +00003339DependentFunctionTemplateSpecializationInfo *
Chandler Carruth21c90602015-12-30 03:24:14 +00003340FunctionDecl::getDependentSpecializationInfo() const {
3341 return TemplateOrSpecialization
3342 .dyn_cast<DependentFunctionTemplateSpecializationInfo *>();
3343}
3344
3345DependentFunctionTemplateSpecializationInfo *
James Y Knight7a22b242015-08-06 20:26:32 +00003346DependentFunctionTemplateSpecializationInfo::Create(
3347 ASTContext &Context, const UnresolvedSetImpl &Ts,
3348 const TemplateArgumentListInfo &TArgs) {
3349 void *Buffer = Context.Allocate(
3350 totalSizeToAlloc<TemplateArgumentLoc, FunctionTemplateDecl *>(
3351 TArgs.size(), Ts.size()));
3352 return new (Buffer) DependentFunctionTemplateSpecializationInfo(Ts, TArgs);
3353}
3354
John McCallb9c78482010-04-08 09:05:18 +00003355DependentFunctionTemplateSpecializationInfo::
3356DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts,
3357 const TemplateArgumentListInfo &TArgs)
Benjamin Kramer3ebba522015-04-02 12:43:31 +00003358 : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) {
John McCallb9c78482010-04-08 09:05:18 +00003359
James Y Knight53c76162015-07-17 18:21:37 +00003360 NumTemplates = Ts.size();
3361 NumArgs = TArgs.size();
Benjamin Kramer3ebba522015-04-02 12:43:31 +00003362
James Y Knight7a22b242015-08-06 20:26:32 +00003363 FunctionTemplateDecl **TsArray = getTrailingObjects<FunctionTemplateDecl *>();
John McCallb9c78482010-04-08 09:05:18 +00003364 for (unsigned I = 0, E = Ts.size(); I != E; ++I)
3365 TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl());
3366
James Y Knight7a22b242015-08-06 20:26:32 +00003367 TemplateArgumentLoc *ArgsArray = getTrailingObjects<TemplateArgumentLoc>();
John McCallb9c78482010-04-08 09:05:18 +00003368 for (unsigned I = 0, E = TArgs.size(); I != E; ++I)
3369 new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]);
3370}
3371
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003372TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const {
Mike Stump11289f42009-09-09 15:08:12 +00003373 // For a function template specialization, query the specialization
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003374 // information object.
Douglas Gregord801b062009-10-07 23:56:10 +00003375 FunctionTemplateSpecializationInfo *FTSInfo
Douglas Gregore8925db2009-06-29 22:39:32 +00003376 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
Douglas Gregord801b062009-10-07 23:56:10 +00003377 if (FTSInfo)
3378 return FTSInfo->getTemplateSpecializationKind();
Mike Stump11289f42009-09-09 15:08:12 +00003379
Douglas Gregord801b062009-10-07 23:56:10 +00003380 MemberSpecializationInfo *MSInfo
3381 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
3382 if (MSInfo)
3383 return MSInfo->getTemplateSpecializationKind();
3384
3385 return TSK_Undeclared;
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003386}
3387
Mike Stump11289f42009-09-09 15:08:12 +00003388void
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003389FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
3390 SourceLocation PointOfInstantiation) {
3391 if (FunctionTemplateSpecializationInfo *FTSInfo
3392 = TemplateOrSpecialization.dyn_cast<
3393 FunctionTemplateSpecializationInfo*>()) {
3394 FTSInfo->setTemplateSpecializationKind(TSK);
3395 if (TSK != TSK_ExplicitSpecialization &&
3396 PointOfInstantiation.isValid() &&
3397 FTSInfo->getPointOfInstantiation().isInvalid())
3398 FTSInfo->setPointOfInstantiation(PointOfInstantiation);
3399 } else if (MemberSpecializationInfo *MSInfo
3400 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) {
3401 MSInfo->setTemplateSpecializationKind(TSK);
3402 if (TSK != TSK_ExplicitSpecialization &&
3403 PointOfInstantiation.isValid() &&
3404 MSInfo->getPointOfInstantiation().isInvalid())
3405 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3406 } else
David Blaikie83d382b2011-09-23 05:06:16 +00003407 llvm_unreachable("Function cannot have a template specialization kind");
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003408}
3409
3410SourceLocation FunctionDecl::getPointOfInstantiation() const {
Douglas Gregord801b062009-10-07 23:56:10 +00003411 if (FunctionTemplateSpecializationInfo *FTSInfo
3412 = TemplateOrSpecialization.dyn_cast<
3413 FunctionTemplateSpecializationInfo*>())
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003414 return FTSInfo->getPointOfInstantiation();
Douglas Gregord801b062009-10-07 23:56:10 +00003415 else if (MemberSpecializationInfo *MSInfo
3416 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>())
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003417 return MSInfo->getPointOfInstantiation();
3418
3419 return SourceLocation();
Douglas Gregore8925db2009-06-29 22:39:32 +00003420}
3421
Douglas Gregor6411b922009-09-11 20:15:17 +00003422bool FunctionDecl::isOutOfLine() const {
Douglas Gregorb11aad82011-02-19 18:51:44 +00003423 if (Decl::isOutOfLine())
Douglas Gregor6411b922009-09-11 20:15:17 +00003424 return true;
3425
3426 // If this function was instantiated from a member function of a
3427 // class template, check whether that member function was defined out-of-line.
3428 if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) {
3429 const FunctionDecl *Definition;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003430 if (FD->hasBody(Definition))
Douglas Gregor6411b922009-09-11 20:15:17 +00003431 return Definition->isOutOfLine();
3432 }
3433
3434 // If this function was instantiated from a function template,
3435 // check whether that function template was defined out-of-line.
3436 if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) {
3437 const FunctionDecl *Definition;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003438 if (FunTmpl->getTemplatedDecl()->hasBody(Definition))
Douglas Gregor6411b922009-09-11 20:15:17 +00003439 return Definition->isOutOfLine();
3440 }
3441
3442 return false;
3443}
3444
Abramo Bagnaraea947882011-03-08 16:41:52 +00003445SourceRange FunctionDecl::getSourceRange() const {
3446 return SourceRange(getOuterLocStart(), EndRangeLoc);
3447}
3448
Anna Zaks28db7ce2012-01-18 02:45:01 +00003449unsigned FunctionDecl::getMemoryFunctionKind() const {
Anna Zaks201d4892012-01-13 21:52:01 +00003450 IdentifierInfo *FnInfo = getIdentifier();
3451
3452 if (!FnInfo)
Anna Zaks22122702012-01-17 00:37:07 +00003453 return 0;
Anna Zaks201d4892012-01-13 21:52:01 +00003454
3455 // Builtin handling.
3456 switch (getBuiltinID()) {
3457 case Builtin::BI__builtin_memset:
3458 case Builtin::BI__builtin___memset_chk:
3459 case Builtin::BImemset:
Anna Zaks22122702012-01-17 00:37:07 +00003460 return Builtin::BImemset;
Anna Zaks201d4892012-01-13 21:52:01 +00003461
3462 case Builtin::BI__builtin_memcpy:
3463 case Builtin::BI__builtin___memcpy_chk:
3464 case Builtin::BImemcpy:
Anna Zaks22122702012-01-17 00:37:07 +00003465 return Builtin::BImemcpy;
Anna Zaks201d4892012-01-13 21:52:01 +00003466
3467 case Builtin::BI__builtin_memmove:
3468 case Builtin::BI__builtin___memmove_chk:
3469 case Builtin::BImemmove:
Anna Zaks22122702012-01-17 00:37:07 +00003470 return Builtin::BImemmove;
Anna Zaks201d4892012-01-13 21:52:01 +00003471
3472 case Builtin::BIstrlcpy:
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00003473 case Builtin::BI__builtin___strlcpy_chk:
Anna Zaks22122702012-01-17 00:37:07 +00003474 return Builtin::BIstrlcpy;
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00003475
Anna Zaks201d4892012-01-13 21:52:01 +00003476 case Builtin::BIstrlcat:
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00003477 case Builtin::BI__builtin___strlcat_chk:
Anna Zaks22122702012-01-17 00:37:07 +00003478 return Builtin::BIstrlcat;
Anna Zaks201d4892012-01-13 21:52:01 +00003479
3480 case Builtin::BI__builtin_memcmp:
Anna Zaks22122702012-01-17 00:37:07 +00003481 case Builtin::BImemcmp:
3482 return Builtin::BImemcmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003483
3484 case Builtin::BI__builtin_strncpy:
3485 case Builtin::BI__builtin___strncpy_chk:
3486 case Builtin::BIstrncpy:
Anna Zaks22122702012-01-17 00:37:07 +00003487 return Builtin::BIstrncpy;
Anna Zaks201d4892012-01-13 21:52:01 +00003488
3489 case Builtin::BI__builtin_strncmp:
Anna Zaks22122702012-01-17 00:37:07 +00003490 case Builtin::BIstrncmp:
3491 return Builtin::BIstrncmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003492
3493 case Builtin::BI__builtin_strncasecmp:
Anna Zaks22122702012-01-17 00:37:07 +00003494 case Builtin::BIstrncasecmp:
3495 return Builtin::BIstrncasecmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003496
3497 case Builtin::BI__builtin_strncat:
Anna Zaks314cd092012-02-01 19:08:57 +00003498 case Builtin::BI__builtin___strncat_chk:
Anna Zaks201d4892012-01-13 21:52:01 +00003499 case Builtin::BIstrncat:
Anna Zaks22122702012-01-17 00:37:07 +00003500 return Builtin::BIstrncat;
Anna Zaks201d4892012-01-13 21:52:01 +00003501
3502 case Builtin::BI__builtin_strndup:
3503 case Builtin::BIstrndup:
Anna Zaks22122702012-01-17 00:37:07 +00003504 return Builtin::BIstrndup;
Anna Zaks201d4892012-01-13 21:52:01 +00003505
Anna Zaks314cd092012-02-01 19:08:57 +00003506 case Builtin::BI__builtin_strlen:
3507 case Builtin::BIstrlen:
3508 return Builtin::BIstrlen;
3509
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00003510 case Builtin::BI__builtin_bzero:
3511 case Builtin::BIbzero:
3512 return Builtin::BIbzero;
3513
Anna Zaks201d4892012-01-13 21:52:01 +00003514 default:
Rafael Espindola5bda63f2013-02-14 01:47:04 +00003515 if (isExternC()) {
Anna Zaks201d4892012-01-13 21:52:01 +00003516 if (FnInfo->isStr("memset"))
Anna Zaks22122702012-01-17 00:37:07 +00003517 return Builtin::BImemset;
Anna Zaks201d4892012-01-13 21:52:01 +00003518 else if (FnInfo->isStr("memcpy"))
Anna Zaks22122702012-01-17 00:37:07 +00003519 return Builtin::BImemcpy;
Anna Zaks201d4892012-01-13 21:52:01 +00003520 else if (FnInfo->isStr("memmove"))
Anna Zaks22122702012-01-17 00:37:07 +00003521 return Builtin::BImemmove;
Anna Zaks201d4892012-01-13 21:52:01 +00003522 else if (FnInfo->isStr("memcmp"))
Anna Zaks22122702012-01-17 00:37:07 +00003523 return Builtin::BImemcmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003524 else if (FnInfo->isStr("strncpy"))
Anna Zaks22122702012-01-17 00:37:07 +00003525 return Builtin::BIstrncpy;
Anna Zaks201d4892012-01-13 21:52:01 +00003526 else if (FnInfo->isStr("strncmp"))
Anna Zaks22122702012-01-17 00:37:07 +00003527 return Builtin::BIstrncmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003528 else if (FnInfo->isStr("strncasecmp"))
Anna Zaks22122702012-01-17 00:37:07 +00003529 return Builtin::BIstrncasecmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003530 else if (FnInfo->isStr("strncat"))
Anna Zaks22122702012-01-17 00:37:07 +00003531 return Builtin::BIstrncat;
Anna Zaks201d4892012-01-13 21:52:01 +00003532 else if (FnInfo->isStr("strndup"))
Anna Zaks22122702012-01-17 00:37:07 +00003533 return Builtin::BIstrndup;
Anna Zaks314cd092012-02-01 19:08:57 +00003534 else if (FnInfo->isStr("strlen"))
3535 return Builtin::BIstrlen;
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00003536 else if (FnInfo->isStr("bzero"))
3537 return Builtin::BIbzero;
Anna Zaks201d4892012-01-13 21:52:01 +00003538 }
3539 break;
3540 }
Anna Zaks22122702012-01-17 00:37:07 +00003541 return 0;
Anna Zaks201d4892012-01-13 21:52:01 +00003542}
3543
Chris Lattner59a25942008-03-31 00:36:02 +00003544//===----------------------------------------------------------------------===//
Sebastian Redl833ef452010-01-26 22:01:41 +00003545// FieldDecl Implementation
3546//===----------------------------------------------------------------------===//
3547
Jay Foad39c79802011-01-12 09:06:06 +00003548FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003549 SourceLocation StartLoc, SourceLocation IdLoc,
3550 IdentifierInfo *Id, QualType T,
Richard Smith938f40b2011-06-11 17:19:42 +00003551 TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
Richard Smith2b013182012-06-10 03:12:00 +00003552 InClassInitStyle InitStyle) {
Richard Smithf7981722013-11-22 09:01:48 +00003553 return new (C, DC) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo,
3554 BW, Mutable, InitStyle);
Sebastian Redl833ef452010-01-26 22:01:41 +00003555}
3556
Douglas Gregor72172e92012-01-05 21:55:30 +00003557FieldDecl *FieldDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00003558 return new (C, ID) FieldDecl(Field, nullptr, SourceLocation(),
3559 SourceLocation(), nullptr, QualType(), nullptr,
3560 nullptr, false, ICIS_NoInit);
Douglas Gregor72172e92012-01-05 21:55:30 +00003561}
3562
Sebastian Redl833ef452010-01-26 22:01:41 +00003563bool FieldDecl::isAnonymousStructOrUnion() const {
3564 if (!isImplicit() || getDeclName())
3565 return false;
3566
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00003567 if (const auto *Record = getType()->getAs<RecordType>())
Sebastian Redl833ef452010-01-26 22:01:41 +00003568 return Record->getDecl()->isAnonymousStructOrUnion();
3569
3570 return false;
3571}
3572
Richard Smithcaf33902011-10-10 18:28:20 +00003573unsigned FieldDecl::getBitWidthValue(const ASTContext &Ctx) const {
3574 assert(isBitField() && "not a bitfield");
Richard Smith6b8e3c02017-08-28 00:28:14 +00003575 return getBitWidth()->EvaluateKnownConstInt(Ctx).getZExtValue();
Richard Smithcaf33902011-10-10 18:28:20 +00003576}
3577
John McCall4e819612011-01-20 07:57:12 +00003578unsigned FieldDecl::getFieldIndex() const {
Richard Smith0b87e072013-10-07 08:02:11 +00003579 const FieldDecl *Canonical = getCanonicalDecl();
3580 if (Canonical != this)
3581 return Canonical->getFieldIndex();
3582
John McCall4e819612011-01-20 07:57:12 +00003583 if (CachedFieldIndex) return CachedFieldIndex - 1;
3584
Richard Smithd62306a2011-11-10 06:34:14 +00003585 unsigned Index = 0;
Fariborz Jahanian8409bce42011-04-28 22:49:46 +00003586 const RecordDecl *RD = getParent();
Richard Smithd62306a2011-11-10 06:34:14 +00003587
Hans Wennborga302cd92014-08-21 16:06:57 +00003588 for (auto *Field : RD->fields()) {
3589 Field->getCanonicalDecl()->CachedFieldIndex = Index + 1;
3590 ++Index;
3591 }
John McCall4e819612011-01-20 07:57:12 +00003592
Richard Smithd62306a2011-11-10 06:34:14 +00003593 assert(CachedFieldIndex && "failed to find field in parent");
3594 return CachedFieldIndex - 1;
John McCall4e819612011-01-20 07:57:12 +00003595}
3596
Abramo Bagnara20c9e242011-03-08 11:07:11 +00003597SourceRange FieldDecl::getSourceRange() const {
Richard Smith6b8e3c02017-08-28 00:28:14 +00003598 const Expr *FinalExpr = getInClassInitializer();
3599 if (!FinalExpr)
3600 FinalExpr = getBitWidth();
3601 if (FinalExpr)
3602 return SourceRange(getInnerLocStart(), FinalExpr->getLocEnd());
3603 return DeclaratorDecl::getSourceRange();
Alexey Bataev39c81e22014-08-28 04:28:19 +00003604}
3605
3606void FieldDecl::setCapturedVLAType(const VariableArrayType *VLAType) {
David Blaikie11ab0782014-10-31 17:18:09 +00003607 assert((getParent()->isLambda() || getParent()->isCapturedRecord()) &&
Alexey Bataev330de032014-10-29 12:21:55 +00003608 "capturing type in non-lambda or captured record.");
Richard Smith6b8e3c02017-08-28 00:28:14 +00003609 assert(InitStorage.getInt() == ISK_NoInit &&
John McCallc90c1492014-10-10 18:44:34 +00003610 InitStorage.getPointer() == nullptr &&
Alexey Bataev39c81e22014-08-28 04:28:19 +00003611 "bit width, initializer or captured type already set");
John McCallc90c1492014-10-10 18:44:34 +00003612 InitStorage.setPointerAndInt(const_cast<VariableArrayType *>(VLAType),
3613 ISK_CapturedVLAType);
Alexey Bataev39c81e22014-08-28 04:28:19 +00003614}
3615
Sebastian Redl833ef452010-01-26 22:01:41 +00003616//===----------------------------------------------------------------------===//
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003617// TagDecl Implementation
Ted Kremenek21475702008-09-05 17:16:31 +00003618//===----------------------------------------------------------------------===//
3619
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00003620SourceLocation TagDecl::getOuterLocStart() const {
3621 return getTemplateOrInnerLocStart(this);
3622}
3623
Argyrios Kyrtzidis575fa052009-07-14 03:17:17 +00003624SourceRange TagDecl::getSourceRange() const {
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00003625 SourceLocation RBraceLoc = BraceRange.getEnd();
Argyrios Kyrtzidis575fa052009-07-14 03:17:17 +00003626 SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation();
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00003627 return SourceRange(getOuterLocStart(), E);
Argyrios Kyrtzidis575fa052009-07-14 03:17:17 +00003628}
3629
Rafael Espindola8db352d2013-10-17 15:37:26 +00003630TagDecl *TagDecl::getCanonicalDecl() { return getFirstDecl(); }
Argyrios Kyrtzidis5614aef2009-07-18 00:34:07 +00003631
Rafael Espindolabf5c33b2013-03-12 21:06:00 +00003632void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) {
David Majnemer00350522015-08-31 18:48:39 +00003633 TypedefNameDeclOrQualifier = TDD;
Reid Klecknercae82a22014-04-23 22:03:04 +00003634 if (const Type *T = getTypeForDecl()) {
3635 (void)T;
Richard Smith5b21db82014-04-23 18:20:42 +00003636 assert(T->isLinkageValid());
Reid Klecknercae82a22014-04-23 22:03:04 +00003637 }
Rafael Espindola0e0d0092013-03-14 03:07:35 +00003638 assert(isLinkageValid());
Douglas Gregora72a4e32010-05-19 18:39:18 +00003639}
3640
Douglas Gregordee1be82009-01-17 00:42:38 +00003641void TagDecl::startDefinition() {
Sebastian Redl9d8854e2010-08-02 18:27:05 +00003642 IsBeingDefined = true;
John McCall67da35c2010-02-04 22:26:26 +00003643
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00003644 if (auto *D = dyn_cast<CXXRecordDecl>(this)) {
Richard Smith053f6c62014-05-16 23:01:30 +00003645 struct CXXRecordDecl::DefinitionData *Data =
John McCall67da35c2010-02-04 22:26:26 +00003646 new (getASTContext()) struct CXXRecordDecl::DefinitionData(D);
Aaron Ballman86c93902014-03-06 23:45:36 +00003647 for (auto I : redecls())
Richard Smith64c06302014-05-22 23:19:02 +00003648 cast<CXXRecordDecl>(I)->DefinitionData = Data;
John McCall67da35c2010-02-04 22:26:26 +00003649 }
Douglas Gregordee1be82009-01-17 00:42:38 +00003650}
3651
3652void TagDecl::completeDefinition() {
John McCallae580fe2010-02-05 01:33:36 +00003653 assert((!isa<CXXRecordDecl>(this) ||
3654 cast<CXXRecordDecl>(this)->hasDefinition()) &&
3655 "definition completed but not started");
3656
John McCallf937c022011-10-07 06:10:15 +00003657 IsCompleteDefinition = true;
Sebastian Redl9d8854e2010-08-02 18:27:05 +00003658 IsBeingDefined = false;
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00003659
3660 if (ASTMutationListener *L = getASTMutationListener())
3661 L->CompletedTagDefinition(this);
Douglas Gregordee1be82009-01-17 00:42:38 +00003662}
3663
John McCallf937c022011-10-07 06:10:15 +00003664TagDecl *TagDecl::getDefinition() const {
3665 if (isCompleteDefinition())
Douglas Gregorb6b8f9e2009-07-29 23:36:44 +00003666 return const_cast<TagDecl *>(this);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003667
3668 // If it's possible for us to have an out-of-date definition, check now.
3669 if (MayHaveOutOfDateDef) {
3670 if (IdentifierInfo *II = getIdentifier()) {
3671 if (II->isOutOfDate()) {
3672 updateOutOfDate(*II);
3673 }
3674 }
3675 }
3676
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00003677 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(this))
Andrew Trickba266ee2010-10-19 21:54:32 +00003678 return CXXRD->getDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00003679
Aaron Ballman86c93902014-03-06 23:45:36 +00003680 for (auto R : redecls())
John McCallf937c022011-10-07 06:10:15 +00003681 if (R->isCompleteDefinition())
Aaron Ballman86c93902014-03-06 23:45:36 +00003682 return R;
Mike Stump11289f42009-09-09 15:08:12 +00003683
Craig Topper36250ad2014-05-12 05:36:57 +00003684 return nullptr;
Ted Kremenek21475702008-09-05 17:16:31 +00003685}
3686
Douglas Gregor14454802011-02-25 02:25:35 +00003687void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
3688 if (QualifierLoc) {
John McCall3e11ebe2010-03-15 10:12:16 +00003689 // Make sure the extended qualifier info is allocated.
3690 if (!hasExtInfo())
David Majnemer00350522015-08-31 18:48:39 +00003691 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
John McCall3e11ebe2010-03-15 10:12:16 +00003692 // Set qualifier info.
Douglas Gregor14454802011-02-25 02:25:35 +00003693 getExtInfo()->QualifierLoc = QualifierLoc;
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003694 } else {
John McCall3e11ebe2010-03-15 10:12:16 +00003695 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
John McCall3e11ebe2010-03-15 10:12:16 +00003696 if (hasExtInfo()) {
Abramo Bagnara60804e12011-03-18 15:16:37 +00003697 if (getExtInfo()->NumTemplParamLists == 0) {
3698 getASTContext().Deallocate(getExtInfo());
David Majnemer00350522015-08-31 18:48:39 +00003699 TypedefNameDeclOrQualifier = (TypedefNameDecl *)nullptr;
Abramo Bagnara60804e12011-03-18 15:16:37 +00003700 }
3701 else
3702 getExtInfo()->QualifierLoc = QualifierLoc;
John McCall3e11ebe2010-03-15 10:12:16 +00003703 }
3704 }
3705}
3706
Benjamin Kramer9cc210652015-08-05 09:40:49 +00003707void TagDecl::setTemplateParameterListsInfo(
3708 ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
3709 assert(!TPLists.empty());
Abramo Bagnara60804e12011-03-18 15:16:37 +00003710 // Make sure the extended decl info is allocated.
3711 if (!hasExtInfo())
3712 // Allocate external info struct.
David Majnemer00350522015-08-31 18:48:39 +00003713 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
Abramo Bagnara60804e12011-03-18 15:16:37 +00003714 // Set the template parameter lists info.
Benjamin Kramer9cc210652015-08-05 09:40:49 +00003715 getExtInfo()->setTemplateParameterListsInfo(Context, TPLists);
Abramo Bagnara60804e12011-03-18 15:16:37 +00003716}
3717
Ted Kremenek21475702008-09-05 17:16:31 +00003718//===----------------------------------------------------------------------===//
Sebastian Redl833ef452010-01-26 22:01:41 +00003719// EnumDecl Implementation
3720//===----------------------------------------------------------------------===//
3721
David Blaikie68e081d2011-12-20 02:48:34 +00003722void EnumDecl::anchor() { }
3723
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003724EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC,
3725 SourceLocation StartLoc, SourceLocation IdLoc,
3726 IdentifierInfo *Id,
Abramo Bagnara0e05e242010-12-03 18:54:17 +00003727 EnumDecl *PrevDecl, bool IsScoped,
3728 bool IsScopedUsingClassTag, bool IsFixed) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00003729 auto *Enum = new (C, DC) EnumDecl(C, DC, StartLoc, IdLoc, Id, PrevDecl,
3730 IsScoped, IsScopedUsingClassTag, IsFixed);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003731 Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules;
Sebastian Redl833ef452010-01-26 22:01:41 +00003732 C.getTypeDeclType(Enum, PrevDecl);
3733 return Enum;
3734}
3735
Douglas Gregor72172e92012-01-05 21:55:30 +00003736EnumDecl *EnumDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00003737 EnumDecl *Enum =
3738 new (C, ID) EnumDecl(C, nullptr, SourceLocation(), SourceLocation(),
3739 nullptr, nullptr, false, false, false);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003740 Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3741 return Enum;
Argyrios Kyrtzidis39f0e302010-07-02 11:54:55 +00003742}
3743
Alp Tokerb9fa5122014-01-06 11:31:18 +00003744SourceRange EnumDecl::getIntegerTypeRange() const {
3745 if (const TypeSourceInfo *TI = getIntegerTypeSourceInfo())
3746 return TI->getTypeLoc().getSourceRange();
3747 return SourceRange();
3748}
3749
Douglas Gregord5058122010-02-11 01:19:42 +00003750void EnumDecl::completeDefinition(QualType NewType,
John McCall9aa35be2010-05-06 08:49:23 +00003751 QualType NewPromotionType,
3752 unsigned NumPositiveBits,
3753 unsigned NumNegativeBits) {
John McCallf937c022011-10-07 06:10:15 +00003754 assert(!isCompleteDefinition() && "Cannot redefine enums!");
Douglas Gregor0bf31402010-10-08 23:50:27 +00003755 if (!IntegerType)
3756 IntegerType = NewType.getTypePtr();
Sebastian Redl833ef452010-01-26 22:01:41 +00003757 PromotionType = NewPromotionType;
John McCall9aa35be2010-05-06 08:49:23 +00003758 setNumPositiveBits(NumPositiveBits);
3759 setNumNegativeBits(NumNegativeBits);
Sebastian Redl833ef452010-01-26 22:01:41 +00003760 TagDecl::completeDefinition();
3761}
3762
Akira Hatanaka3c268af2017-03-21 02:23:00 +00003763bool EnumDecl::isClosed() const {
3764 if (const auto *A = getAttr<EnumExtensibilityAttr>())
3765 return A->getExtensibility() == EnumExtensibilityAttr::Closed;
3766 return true;
3767}
3768
3769bool EnumDecl::isClosedFlag() const {
3770 return isClosed() && hasAttr<FlagEnumAttr>();
3771}
3772
3773bool EnumDecl::isClosedNonFlag() const {
3774 return isClosed() && !hasAttr<FlagEnumAttr>();
3775}
3776
Richard Smith7d137e32012-03-23 03:33:32 +00003777TemplateSpecializationKind EnumDecl::getTemplateSpecializationKind() const {
3778 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
3779 return MSI->getTemplateSpecializationKind();
3780
3781 return TSK_Undeclared;
3782}
3783
3784void EnumDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
3785 SourceLocation PointOfInstantiation) {
3786 MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
3787 assert(MSI && "Not an instantiated member enumeration?");
3788 MSI->setTemplateSpecializationKind(TSK);
3789 if (TSK != TSK_ExplicitSpecialization &&
3790 PointOfInstantiation.isValid() &&
3791 MSI->getPointOfInstantiation().isInvalid())
3792 MSI->setPointOfInstantiation(PointOfInstantiation);
3793}
3794
Richard Smith6739a102016-05-05 00:56:12 +00003795EnumDecl *EnumDecl::getTemplateInstantiationPattern() const {
3796 if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) {
3797 if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) {
3798 EnumDecl *ED = getInstantiatedFromMemberEnum();
3799 while (auto *NewED = ED->getInstantiatedFromMemberEnum())
3800 ED = NewED;
Richard Smith2195ec92017-04-21 01:15:13 +00003801 return getDefinitionOrSelf(ED);
Richard Smith6739a102016-05-05 00:56:12 +00003802 }
3803 }
3804
3805 assert(!isTemplateInstantiation(getTemplateSpecializationKind()) &&
3806 "couldn't find pattern for enum instantiation");
3807 return nullptr;
3808}
3809
Richard Smith4b38ded2012-03-14 23:13:10 +00003810EnumDecl *EnumDecl::getInstantiatedFromMemberEnum() const {
3811 if (SpecializationInfo)
3812 return cast<EnumDecl>(SpecializationInfo->getInstantiatedFrom());
3813
Craig Topper36250ad2014-05-12 05:36:57 +00003814 return nullptr;
Richard Smith4b38ded2012-03-14 23:13:10 +00003815}
3816
3817void EnumDecl::setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
3818 TemplateSpecializationKind TSK) {
3819 assert(!SpecializationInfo && "Member enum is already a specialization");
3820 SpecializationInfo = new (C) MemberSpecializationInfo(ED, TSK);
3821}
3822
Sebastian Redl833ef452010-01-26 22:01:41 +00003823//===----------------------------------------------------------------------===//
Chris Lattner59a25942008-03-31 00:36:02 +00003824// RecordDecl Implementation
3825//===----------------------------------------------------------------------===//
Chris Lattner41943152007-01-25 04:52:46 +00003826
Richard Smith053f6c62014-05-16 23:01:30 +00003827RecordDecl::RecordDecl(Kind DK, TagKind TK, const ASTContext &C,
3828 DeclContext *DC, SourceLocation StartLoc,
3829 SourceLocation IdLoc, IdentifierInfo *Id,
3830 RecordDecl *PrevDecl)
3831 : TagDecl(DK, TK, C, DC, IdLoc, Id, PrevDecl, StartLoc) {
Ted Kremenek52baf502008-09-02 21:12:32 +00003832 HasFlexibleArrayMember = false;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003833 AnonymousStructOrUnion = false;
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00003834 HasObjectMember = false;
Fariborz Jahanian78652202013-01-25 23:57:05 +00003835 HasVolatileMember = false;
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003836 LoadedFieldsFromExternalStorage = false;
Ted Kremenek52baf502008-09-02 21:12:32 +00003837 assert(classof(static_cast<Decl*>(this)) && "Invalid Kind!");
Ted Kremenek52baf502008-09-02 21:12:32 +00003838}
3839
Jay Foad39c79802011-01-12 09:06:06 +00003840RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003841 SourceLocation StartLoc, SourceLocation IdLoc,
3842 IdentifierInfo *Id, RecordDecl* PrevDecl) {
Richard Smith053f6c62014-05-16 23:01:30 +00003843 RecordDecl *R = new (C, DC) RecordDecl(Record, TK, C, DC,
3844 StartLoc, IdLoc, Id, PrevDecl);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003845 R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3846
Ted Kremenek21475702008-09-05 17:16:31 +00003847 C.getTypeDeclType(R, PrevDecl);
3848 return R;
Ted Kremenek52baf502008-09-02 21:12:32 +00003849}
3850
Douglas Gregor72172e92012-01-05 21:55:30 +00003851RecordDecl *RecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00003852 RecordDecl *R =
3853 new (C, ID) RecordDecl(Record, TTK_Struct, C, nullptr, SourceLocation(),
3854 SourceLocation(), nullptr, nullptr);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003855 R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3856 return R;
Argyrios Kyrtzidis39f0e302010-07-02 11:54:55 +00003857}
3858
Douglas Gregordfcad112009-03-25 15:59:44 +00003859bool RecordDecl::isInjectedClassName() const {
Mike Stump11289f42009-09-09 15:08:12 +00003860 return isImplicit() && getDeclName() && getDeclContext()->isRecord() &&
Douglas Gregordfcad112009-03-25 15:59:44 +00003861 cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName();
3862}
3863
Alexey Bataev39c81e22014-08-28 04:28:19 +00003864bool RecordDecl::isLambda() const {
3865 if (auto RD = dyn_cast<CXXRecordDecl>(this))
3866 return RD->isLambda();
3867 return false;
3868}
3869
Alexey Bataev330de032014-10-29 12:21:55 +00003870bool RecordDecl::isCapturedRecord() const {
3871 return hasAttr<CapturedRecordAttr>();
3872}
3873
3874void RecordDecl::setCapturedRecord() {
3875 addAttr(CapturedRecordAttr::CreateImplicit(getASTContext()));
3876}
3877
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003878RecordDecl::field_iterator RecordDecl::field_begin() const {
3879 if (hasExternalLexicalStorage() && !LoadedFieldsFromExternalStorage)
3880 LoadFieldsFromExternalStorage();
3881
3882 return field_iterator(decl_iterator(FirstDecl));
3883}
3884
Douglas Gregorb11aad82011-02-19 18:51:44 +00003885/// completeDefinition - Notes that the definition of this type is now
3886/// complete.
3887void RecordDecl::completeDefinition() {
John McCallf937c022011-10-07 06:10:15 +00003888 assert(!isCompleteDefinition() && "Cannot redefine record!");
Douglas Gregorb11aad82011-02-19 18:51:44 +00003889 TagDecl::completeDefinition();
3890}
3891
Eli Friedman9ee2d0472012-10-12 23:29:20 +00003892/// isMsStruct - Get whether or not this record uses ms_struct layout.
3893/// This which can be turned on with an attribute, pragma, or the
3894/// -mms-bitfields command-line option.
3895bool RecordDecl::isMsStruct(const ASTContext &C) const {
David Majnemer8ab003a2015-02-02 19:30:52 +00003896 return hasAttr<MSStructAttr>() || C.getLangOpts().MSBitfields == 1;
Eli Friedman9ee2d0472012-10-12 23:29:20 +00003897}
3898
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003899void RecordDecl::LoadFieldsFromExternalStorage() const {
3900 ExternalASTSource *Source = getASTContext().getExternalSource();
3901 assert(hasExternalLexicalStorage() && Source && "No external storage?");
3902
3903 // Notify that we have a RecordDecl doing some initialization.
3904 ExternalASTSource::Deserializing TheFields(Source);
3905
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003906 SmallVector<Decl*, 64> Decls;
Richard Smith3cb15722015-08-05 22:41:45 +00003907 LoadedFieldsFromExternalStorage = true;
3908 Source->FindExternalLexicalDecls(this, [](Decl::Kind K) {
3909 return FieldDecl::classofKind(K) || IndirectFieldDecl::classofKind(K);
3910 }, Decls);
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003911
3912#ifndef NDEBUG
3913 // Check that all decls we got were FieldDecls.
3914 for (unsigned i=0, e=Decls.size(); i != e; ++i)
Argyrios Kyrtzidisf89a9272012-09-10 22:04:22 +00003915 assert(isa<FieldDecl>(Decls[i]) || isa<IndirectFieldDecl>(Decls[i]));
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003916#endif
3917
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003918 if (Decls.empty())
3919 return;
3920
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00003921 std::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls,
Argyrios Kyrtzidis094da732011-10-07 21:55:43 +00003922 /*FieldsAlreadyLoaded=*/false);
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003923}
3924
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00003925bool RecordDecl::mayInsertExtraPadding(bool EmitRemark) const {
3926 ASTContext &Context = getASTContext();
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00003927 if (!Context.getLangOpts().Sanitize.hasOneOf(
3928 SanitizerKind::Address | SanitizerKind::KernelAddress) ||
Alexey Samsonova0416102014-11-11 01:26:14 +00003929 !Context.getLangOpts().SanitizeAddressFieldPadding)
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00003930 return false;
Alexey Samsonov33e00e22014-10-16 23:50:26 +00003931 const auto &Blacklist = Context.getSanitizerBlacklist();
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00003932 const auto *CXXRD = dyn_cast<CXXRecordDecl>(this);
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00003933 // We may be able to relax some of these requirements.
3934 int ReasonToReject = -1;
3935 if (!CXXRD || CXXRD->isExternCContext())
3936 ReasonToReject = 0; // is not C++.
3937 else if (CXXRD->hasAttr<PackedAttr>())
3938 ReasonToReject = 1; // is packed.
3939 else if (CXXRD->isUnion())
3940 ReasonToReject = 2; // is a union.
3941 else if (CXXRD->isTriviallyCopyable())
3942 ReasonToReject = 3; // is trivially copyable.
3943 else if (CXXRD->hasTrivialDestructor())
3944 ReasonToReject = 4; // has trivial destructor.
3945 else if (CXXRD->isStandardLayout())
3946 ReasonToReject = 5; // is standard layout.
Alexey Samsonov33e00e22014-10-16 23:50:26 +00003947 else if (Blacklist.isBlacklistedLocation(getLocation(), "field-padding"))
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00003948 ReasonToReject = 6; // is in a blacklisted file.
3949 else if (Blacklist.isBlacklistedType(getQualifiedNameAsString(),
3950 "field-padding"))
3951 ReasonToReject = 7; // is blacklisted.
3952
3953 if (EmitRemark) {
3954 if (ReasonToReject >= 0)
3955 Context.getDiagnostics().Report(
3956 getLocation(),
3957 diag::remark_sanitize_address_insert_extra_padding_rejected)
3958 << getQualifiedNameAsString() << ReasonToReject;
3959 else
3960 Context.getDiagnostics().Report(
3961 getLocation(),
3962 diag::remark_sanitize_address_insert_extra_padding_accepted)
3963 << getQualifiedNameAsString();
3964 }
3965 return ReasonToReject < 0;
3966}
3967
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00003968const FieldDecl *RecordDecl::findFirstNamedDataMember() const {
3969 for (const auto *I : fields()) {
3970 if (I->getIdentifier())
3971 return I;
3972
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00003973 if (const auto *RT = I->getType()->getAs<RecordType>())
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00003974 if (const FieldDecl *NamedDataMember =
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00003975 RT->getDecl()->findFirstNamedDataMember())
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00003976 return NamedDataMember;
3977 }
3978
3979 // We didn't find a named data member.
3980 return nullptr;
3981}
3982
3983
Steve Naroff415d3d52008-10-08 17:01:13 +00003984//===----------------------------------------------------------------------===//
3985// BlockDecl Implementation
3986//===----------------------------------------------------------------------===//
3987
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003988void BlockDecl::setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
Craig Topper36250ad2014-05-12 05:36:57 +00003989 assert(!ParamInfo && "Already has param info!");
Mike Stump11289f42009-09-09 15:08:12 +00003990
Steve Naroffc4b30e52009-03-13 16:56:44 +00003991 // Zero params -> null pointer.
David Blaikie9c70e042011-09-21 18:16:56 +00003992 if (!NewParamInfo.empty()) {
3993 NumParams = NewParamInfo.size();
3994 ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()];
3995 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
Steve Naroffc4b30e52009-03-13 16:56:44 +00003996 }
3997}
3998
Benjamin Kramerb40e4af2015-08-05 09:40:35 +00003999void BlockDecl::setCaptures(ASTContext &Context, ArrayRef<Capture> Captures,
4000 bool CapturesCXXThis) {
4001 this->CapturesCXXThis = CapturesCXXThis;
4002 this->NumCaptures = Captures.size();
John McCallc63de662011-02-02 13:00:07 +00004003
Benjamin Kramerb40e4af2015-08-05 09:40:35 +00004004 if (Captures.empty()) {
4005 this->Captures = nullptr;
John McCallc63de662011-02-02 13:00:07 +00004006 return;
4007 }
4008
Benjamin Kramerb40e4af2015-08-05 09:40:35 +00004009 this->Captures = Captures.copy(Context).data();
Steve Naroffc4b30e52009-03-13 16:56:44 +00004010}
Sebastian Redl833ef452010-01-26 22:01:41 +00004011
John McCallce45f882011-06-15 22:51:16 +00004012bool BlockDecl::capturesVariable(const VarDecl *variable) const {
Aaron Ballman9371dd22014-03-14 18:34:04 +00004013 for (const auto &I : captures())
John McCallce45f882011-06-15 22:51:16 +00004014 // Only auto vars can be captured, so no redeclaration worries.
Aaron Ballman9371dd22014-03-14 18:34:04 +00004015 if (I.getVariable() == variable)
John McCallce45f882011-06-15 22:51:16 +00004016 return true;
4017
4018 return false;
4019}
4020
Douglas Gregor70226da2010-12-21 16:27:07 +00004021SourceRange BlockDecl::getSourceRange() const {
4022 return SourceRange(getLocation(), Body? Body->getLocEnd() : getLocation());
4023}
Sebastian Redl833ef452010-01-26 22:01:41 +00004024
4025//===----------------------------------------------------------------------===//
4026// Other Decl Allocation/Deallocation Method Implementations
4027//===----------------------------------------------------------------------===//
4028
David Blaikie68e081d2011-12-20 02:48:34 +00004029void TranslationUnitDecl::anchor() { }
4030
Sebastian Redl833ef452010-01-26 22:01:41 +00004031TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) {
Craig Topper36250ad2014-05-12 05:36:57 +00004032 return new (C, (DeclContext *)nullptr) TranslationUnitDecl(C);
Sebastian Redl833ef452010-01-26 22:01:41 +00004033}
4034
Nico Weber66220292016-03-02 17:28:48 +00004035void PragmaCommentDecl::anchor() { }
4036
4037PragmaCommentDecl *PragmaCommentDecl::Create(const ASTContext &C,
4038 TranslationUnitDecl *DC,
4039 SourceLocation CommentLoc,
4040 PragmaMSCommentKind CommentKind,
4041 StringRef Arg) {
4042 PragmaCommentDecl *PCD =
4043 new (C, DC, additionalSizeToAlloc<char>(Arg.size() + 1))
4044 PragmaCommentDecl(DC, CommentLoc, CommentKind);
4045 memcpy(PCD->getTrailingObjects<char>(), Arg.data(), Arg.size());
4046 PCD->getTrailingObjects<char>()[Arg.size()] = '\0';
4047 return PCD;
4048}
4049
4050PragmaCommentDecl *PragmaCommentDecl::CreateDeserialized(ASTContext &C,
4051 unsigned ID,
4052 unsigned ArgSize) {
4053 return new (C, ID, additionalSizeToAlloc<char>(ArgSize + 1))
4054 PragmaCommentDecl(nullptr, SourceLocation(), PCK_Unknown);
4055}
4056
Nico Webercbbaeb12016-03-02 19:28:54 +00004057void PragmaDetectMismatchDecl::anchor() { }
4058
4059PragmaDetectMismatchDecl *
4060PragmaDetectMismatchDecl::Create(const ASTContext &C, TranslationUnitDecl *DC,
4061 SourceLocation Loc, StringRef Name,
4062 StringRef Value) {
4063 size_t ValueStart = Name.size() + 1;
4064 PragmaDetectMismatchDecl *PDMD =
4065 new (C, DC, additionalSizeToAlloc<char>(ValueStart + Value.size() + 1))
4066 PragmaDetectMismatchDecl(DC, Loc, ValueStart);
4067 memcpy(PDMD->getTrailingObjects<char>(), Name.data(), Name.size());
4068 PDMD->getTrailingObjects<char>()[Name.size()] = '\0';
4069 memcpy(PDMD->getTrailingObjects<char>() + ValueStart, Value.data(),
4070 Value.size());
4071 PDMD->getTrailingObjects<char>()[ValueStart + Value.size()] = '\0';
4072 return PDMD;
4073}
4074
4075PragmaDetectMismatchDecl *
4076PragmaDetectMismatchDecl::CreateDeserialized(ASTContext &C, unsigned ID,
4077 unsigned NameValueSize) {
4078 return new (C, ID, additionalSizeToAlloc<char>(NameValueSize + 1))
4079 PragmaDetectMismatchDecl(nullptr, SourceLocation(), 0);
4080}
Nico Weber66220292016-03-02 17:28:48 +00004081
Richard Smithf19e1272015-03-07 00:04:49 +00004082void ExternCContextDecl::anchor() { }
4083
4084ExternCContextDecl *ExternCContextDecl::Create(const ASTContext &C,
4085 TranslationUnitDecl *DC) {
4086 return new (C, DC) ExternCContextDecl(DC);
4087}
4088
David Blaikie68e081d2011-12-20 02:48:34 +00004089void LabelDecl::anchor() { }
4090
Chris Lattnerc8e630e2011-02-17 07:39:24 +00004091LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnara1c3af962011-03-05 18:21:20 +00004092 SourceLocation IdentL, IdentifierInfo *II) {
Craig Topper36250ad2014-05-12 05:36:57 +00004093 return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, IdentL);
Abramo Bagnara1c3af962011-03-05 18:21:20 +00004094}
4095
4096LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
4097 SourceLocation IdentL, IdentifierInfo *II,
4098 SourceLocation GnuLabelL) {
4099 assert(GnuLabelL != IdentL && "Use this only for GNU local labels");
Craig Topper36250ad2014-05-12 05:36:57 +00004100 return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, GnuLabelL);
Chris Lattnerc8e630e2011-02-17 07:39:24 +00004101}
4102
Douglas Gregor72172e92012-01-05 21:55:30 +00004103LabelDecl *LabelDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00004104 return new (C, ID) LabelDecl(nullptr, SourceLocation(), nullptr, nullptr,
4105 SourceLocation());
Douglas Gregor417e87c2010-10-27 19:49:05 +00004106}
4107
Ehsan Akhgari31097582014-09-22 02:21:54 +00004108void LabelDecl::setMSAsmLabel(StringRef Name) {
4109 char *Buffer = new (getASTContext(), 1) char[Name.size() + 1];
4110 memcpy(Buffer, Name.data(), Name.size());
4111 Buffer[Name.size()] = '\0';
4112 MSAsmName = Buffer;
4113}
4114
David Blaikie68e081d2011-12-20 02:48:34 +00004115void ValueDecl::anchor() { }
4116
Benjamin Kramerea70eb32012-12-01 15:09:41 +00004117bool ValueDecl::isWeak() const {
Aaron Ballmanb97112e2014-03-08 22:19:01 +00004118 for (const auto *I : attrs())
4119 if (isa<WeakAttr>(I) || isa<WeakRefAttr>(I))
Benjamin Kramerea70eb32012-12-01 15:09:41 +00004120 return true;
4121
4122 return isWeakImported();
4123}
4124
David Blaikie68e081d2011-12-20 02:48:34 +00004125void ImplicitParamDecl::anchor() { }
4126
Sebastian Redl833ef452010-01-26 22:01:41 +00004127ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004128 SourceLocation IdLoc,
Alexey Bataev56223232017-06-09 13:40:18 +00004129 IdentifierInfo *Id, QualType Type,
4130 ImplicitParamKind ParamKind) {
4131 return new (C, DC) ImplicitParamDecl(C, DC, IdLoc, Id, Type, ParamKind);
4132}
4133
4134ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, QualType Type,
4135 ImplicitParamKind ParamKind) {
4136 return new (C, nullptr) ImplicitParamDecl(C, Type, ParamKind);
Sebastian Redl833ef452010-01-26 22:01:41 +00004137}
4138
Richard Smithf7981722013-11-22 09:01:48 +00004139ImplicitParamDecl *ImplicitParamDecl::CreateDeserialized(ASTContext &C,
Douglas Gregor72172e92012-01-05 21:55:30 +00004140 unsigned ID) {
Alexey Bataev56223232017-06-09 13:40:18 +00004141 return new (C, ID) ImplicitParamDecl(C, QualType(), ImplicitParamKind::Other);
Douglas Gregor72172e92012-01-05 21:55:30 +00004142}
4143
Sebastian Redl833ef452010-01-26 22:01:41 +00004144FunctionDecl *FunctionDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004145 SourceLocation StartLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004146 const DeclarationNameInfo &NameInfo,
4147 QualType T, TypeSourceInfo *TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00004148 StorageClass SC,
Richard Smithf7981722013-11-22 09:01:48 +00004149 bool isInlineSpecified,
Richard Smitha77a0a62011-08-15 21:04:07 +00004150 bool hasWrittenPrototype,
4151 bool isConstexprSpecified) {
Richard Smithf7981722013-11-22 09:01:48 +00004152 FunctionDecl *New =
Richard Smith053f6c62014-05-16 23:01:30 +00004153 new (C, DC) FunctionDecl(Function, C, DC, StartLoc, NameInfo, T, TInfo,
4154 SC, isInlineSpecified, isConstexprSpecified);
Sebastian Redl833ef452010-01-26 22:01:41 +00004155 New->HasWrittenPrototype = hasWrittenPrototype;
4156 return New;
4157}
4158
Douglas Gregor72172e92012-01-05 21:55:30 +00004159FunctionDecl *FunctionDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00004160 return new (C, ID) FunctionDecl(Function, C, nullptr, SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004161 DeclarationNameInfo(), QualType(), nullptr,
Richard Smithf7981722013-11-22 09:01:48 +00004162 SC_None, false, false);
Douglas Gregor72172e92012-01-05 21:55:30 +00004163}
4164
Sebastian Redl833ef452010-01-26 22:01:41 +00004165BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
Richard Smithf7981722013-11-22 09:01:48 +00004166 return new (C, DC) BlockDecl(DC, L);
Sebastian Redl833ef452010-01-26 22:01:41 +00004167}
4168
Douglas Gregor72172e92012-01-05 21:55:30 +00004169BlockDecl *BlockDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00004170 return new (C, ID) BlockDecl(nullptr, SourceLocation());
John McCall5e77d762013-04-16 07:28:30 +00004171}
4172
Chandler Carruth21c90602015-12-30 03:24:14 +00004173CapturedDecl::CapturedDecl(DeclContext *DC, unsigned NumParams)
4174 : Decl(Captured, DC, SourceLocation()), DeclContext(Captured),
4175 NumParams(NumParams), ContextParam(0), BodyAndNothrow(nullptr, false) {}
4176
Ben Langmuir37943a72013-05-03 19:00:33 +00004177CapturedDecl *CapturedDecl::Create(ASTContext &C, DeclContext *DC,
4178 unsigned NumParams) {
James Y Knight7a22b242015-08-06 20:26:32 +00004179 return new (C, DC, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams))
Richard Smithf7981722013-11-22 09:01:48 +00004180 CapturedDecl(DC, NumParams);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004181}
4182
Ben Langmuirce914fc2013-05-03 19:20:19 +00004183CapturedDecl *CapturedDecl::CreateDeserialized(ASTContext &C, unsigned ID,
Richard Smithf7981722013-11-22 09:01:48 +00004184 unsigned NumParams) {
James Y Knight7a22b242015-08-06 20:26:32 +00004185 return new (C, ID, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams))
Craig Topper36250ad2014-05-12 05:36:57 +00004186 CapturedDecl(nullptr, NumParams);
Ben Langmuirce914fc2013-05-03 19:20:19 +00004187}
4188
Chandler Carruth21c90602015-12-30 03:24:14 +00004189Stmt *CapturedDecl::getBody() const { return BodyAndNothrow.getPointer(); }
4190void CapturedDecl::setBody(Stmt *B) { BodyAndNothrow.setPointer(B); }
4191
4192bool CapturedDecl::isNothrow() const { return BodyAndNothrow.getInt(); }
4193void CapturedDecl::setNothrow(bool Nothrow) { BodyAndNothrow.setInt(Nothrow); }
4194
Sebastian Redl833ef452010-01-26 22:01:41 +00004195EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD,
4196 SourceLocation L,
4197 IdentifierInfo *Id, QualType T,
4198 Expr *E, const llvm::APSInt &V) {
Richard Smithf7981722013-11-22 09:01:48 +00004199 return new (C, CD) EnumConstantDecl(CD, L, Id, T, E, V);
Sebastian Redl833ef452010-01-26 22:01:41 +00004200}
4201
Douglas Gregor72172e92012-01-05 21:55:30 +00004202EnumConstantDecl *
4203EnumConstantDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00004204 return new (C, ID) EnumConstantDecl(nullptr, SourceLocation(), nullptr,
4205 QualType(), nullptr, llvm::APSInt());
Douglas Gregor72172e92012-01-05 21:55:30 +00004206}
4207
David Blaikie68e081d2011-12-20 02:48:34 +00004208void IndirectFieldDecl::anchor() { }
4209
Richard Smith9f951822016-01-06 22:49:11 +00004210IndirectFieldDecl::IndirectFieldDecl(ASTContext &C, DeclContext *DC,
4211 SourceLocation L, DeclarationName N,
David Majnemer59f77922016-06-24 04:05:48 +00004212 QualType T,
4213 MutableArrayRef<NamedDecl *> CH)
4214 : ValueDecl(IndirectField, DC, L, N, T), Chaining(CH.data()),
4215 ChainingSize(CH.size()) {
Richard Smith9f951822016-01-06 22:49:11 +00004216 // In C++, indirect field declarations conflict with tag declarations in the
4217 // same scope, so add them to IDNS_Tag so that tag redeclaration finds them.
4218 if (C.getLangOpts().CPlusPlus)
4219 IdentifierNamespace |= IDNS_Tag;
4220}
4221
Benjamin Kramer39593702010-11-21 14:11:41 +00004222IndirectFieldDecl *
4223IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,
David Majnemer59f77922016-06-24 04:05:48 +00004224 IdentifierInfo *Id, QualType T,
4225 llvm::MutableArrayRef<NamedDecl *> CH) {
4226 return new (C, DC) IndirectFieldDecl(C, DC, L, Id, T, CH);
Francois Pichet783dd6e2010-11-21 06:08:52 +00004227}
4228
Douglas Gregor72172e92012-01-05 21:55:30 +00004229IndirectFieldDecl *IndirectFieldDecl::CreateDeserialized(ASTContext &C,
4230 unsigned ID) {
Richard Smith9f951822016-01-06 22:49:11 +00004231 return new (C, ID) IndirectFieldDecl(C, nullptr, SourceLocation(),
David Majnemer59f77922016-06-24 04:05:48 +00004232 DeclarationName(), QualType(), None);
Douglas Gregor72172e92012-01-05 21:55:30 +00004233}
4234
Douglas Gregorbe996932010-09-01 20:41:53 +00004235SourceRange EnumConstantDecl::getSourceRange() const {
4236 SourceLocation End = getLocation();
4237 if (Init)
4238 End = Init->getLocEnd();
4239 return SourceRange(getLocation(), End);
4240}
4241
David Blaikie68e081d2011-12-20 02:48:34 +00004242void TypeDecl::anchor() { }
4243
Sebastian Redl833ef452010-01-26 22:01:41 +00004244TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnarab3185b02011-03-06 15:48:19 +00004245 SourceLocation StartLoc, SourceLocation IdLoc,
4246 IdentifierInfo *Id, TypeSourceInfo *TInfo) {
Richard Smith053f6c62014-05-16 23:01:30 +00004247 return new (C, DC) TypedefDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
Sebastian Redl833ef452010-01-26 22:01:41 +00004248}
4249
David Blaikie68e081d2011-12-20 02:48:34 +00004250void TypedefNameDecl::anchor() { }
4251
Richard Smith42413142015-05-15 20:05:43 +00004252TagDecl *TypedefNameDecl::getAnonDeclWithTypedefName(bool AnyRedecl) const {
4253 if (auto *TT = getTypeSourceInfo()->getType()->getAs<TagType>()) {
4254 auto *OwningTypedef = TT->getDecl()->getTypedefNameForAnonDecl();
4255 auto *ThisTypedef = this;
4256 if (AnyRedecl && OwningTypedef) {
4257 OwningTypedef = OwningTypedef->getCanonicalDecl();
4258 ThisTypedef = ThisTypedef->getCanonicalDecl();
4259 }
4260 if (OwningTypedef == ThisTypedef)
Richard Smitha5230222015-03-27 01:37:43 +00004261 return TT->getDecl();
Richard Smith42413142015-05-15 20:05:43 +00004262 }
Richard Smitha5230222015-03-27 01:37:43 +00004263
4264 return nullptr;
4265}
4266
Argyrios Kyrtzidis3b25c912017-03-21 16:56:02 +00004267bool TypedefNameDecl::isTransparentTagSlow() const {
4268 auto determineIsTransparent = [&]() {
4269 if (auto *TT = getUnderlyingType()->getAs<TagType>()) {
4270 if (auto *TD = TT->getDecl()) {
4271 if (TD->getName() != getName())
4272 return false;
4273 SourceLocation TTLoc = getLocation();
4274 SourceLocation TDLoc = TD->getLocation();
4275 if (!TTLoc.isMacroID() || !TDLoc.isMacroID())
4276 return false;
4277 SourceManager &SM = getASTContext().getSourceManager();
4278 return SM.getSpellingLoc(TTLoc) == SM.getSpellingLoc(TDLoc);
4279 }
4280 }
4281 return false;
4282 };
4283
4284 bool isTransparent = determineIsTransparent();
4285 CacheIsTransparentTag = 1;
4286 if (isTransparent)
4287 CacheIsTransparentTag |= 0x2;
4288 return isTransparent;
4289}
4290
Douglas Gregor72172e92012-01-05 21:55:30 +00004291TypedefDecl *TypedefDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00004292 return new (C, ID) TypedefDecl(C, nullptr, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004293 nullptr, nullptr);
Douglas Gregor72172e92012-01-05 21:55:30 +00004294}
4295
Richard Smithdda56e42011-04-15 14:24:37 +00004296TypeAliasDecl *TypeAliasDecl::Create(ASTContext &C, DeclContext *DC,
4297 SourceLocation StartLoc,
4298 SourceLocation IdLoc, IdentifierInfo *Id,
4299 TypeSourceInfo *TInfo) {
Richard Smith053f6c62014-05-16 23:01:30 +00004300 return new (C, DC) TypeAliasDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
Richard Smithdda56e42011-04-15 14:24:37 +00004301}
4302
Douglas Gregor72172e92012-01-05 21:55:30 +00004303TypeAliasDecl *TypeAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00004304 return new (C, ID) TypeAliasDecl(C, nullptr, SourceLocation(),
4305 SourceLocation(), nullptr, nullptr);
Douglas Gregor72172e92012-01-05 21:55:30 +00004306}
4307
Abramo Bagnaraea947882011-03-08 16:41:52 +00004308SourceRange TypedefDecl::getSourceRange() const {
4309 SourceLocation RangeEnd = getLocation();
4310 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
4311 if (typeIsPostfix(TInfo->getType()))
4312 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
4313 }
4314 return SourceRange(getLocStart(), RangeEnd);
4315}
4316
Richard Smithdda56e42011-04-15 14:24:37 +00004317SourceRange TypeAliasDecl::getSourceRange() const {
4318 SourceLocation RangeEnd = getLocStart();
4319 if (TypeSourceInfo *TInfo = getTypeSourceInfo())
4320 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
4321 return SourceRange(getLocStart(), RangeEnd);
4322}
4323
David Blaikie68e081d2011-12-20 02:48:34 +00004324void FileScopeAsmDecl::anchor() { }
4325
Sebastian Redl833ef452010-01-26 22:01:41 +00004326FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnara348823a2011-03-03 14:20:18 +00004327 StringLiteral *Str,
4328 SourceLocation AsmLoc,
4329 SourceLocation RParenLoc) {
Richard Smithf7981722013-11-22 09:01:48 +00004330 return new (C, DC) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc);
Sebastian Redl833ef452010-01-26 22:01:41 +00004331}
Douglas Gregorba345522011-12-02 23:23:56 +00004332
Richard Smithf7981722013-11-22 09:01:48 +00004333FileScopeAsmDecl *FileScopeAsmDecl::CreateDeserialized(ASTContext &C,
Douglas Gregor72172e92012-01-05 21:55:30 +00004334 unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00004335 return new (C, ID) FileScopeAsmDecl(nullptr, nullptr, SourceLocation(),
4336 SourceLocation());
Douglas Gregor72172e92012-01-05 21:55:30 +00004337}
4338
Michael Han84324352013-02-22 17:15:32 +00004339void EmptyDecl::anchor() {}
4340
4341EmptyDecl *EmptyDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
Richard Smithf7981722013-11-22 09:01:48 +00004342 return new (C, DC) EmptyDecl(DC, L);
Michael Han84324352013-02-22 17:15:32 +00004343}
4344
4345EmptyDecl *EmptyDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00004346 return new (C, ID) EmptyDecl(nullptr, SourceLocation());
Michael Han84324352013-02-22 17:15:32 +00004347}
4348
Douglas Gregorba345522011-12-02 23:23:56 +00004349//===----------------------------------------------------------------------===//
4350// ImportDecl Implementation
4351//===----------------------------------------------------------------------===//
4352
4353/// \brief Retrieve the number of module identifiers needed to name the given
4354/// module.
4355static unsigned getNumModuleIdentifiers(Module *Mod) {
4356 unsigned Result = 1;
4357 while (Mod->Parent) {
4358 Mod = Mod->Parent;
4359 ++Result;
4360 }
4361 return Result;
4362}
4363
Douglas Gregor22d09742012-01-03 18:04:46 +00004364ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
Douglas Gregorba345522011-12-02 23:23:56 +00004365 Module *Imported,
4366 ArrayRef<SourceLocation> IdentifierLocs)
Douglas Gregor22d09742012-01-03 18:04:46 +00004367 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, true),
Douglas Gregor0f2a3602011-12-03 00:30:27 +00004368 NextLocalImport()
Douglas Gregorba345522011-12-02 23:23:56 +00004369{
4370 assert(getNumModuleIdentifiers(Imported) == IdentifierLocs.size());
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00004371 auto *StoredLocs = getTrailingObjects<SourceLocation>();
James Y Knight7a22b242015-08-06 20:26:32 +00004372 std::uninitialized_copy(IdentifierLocs.begin(), IdentifierLocs.end(),
4373 StoredLocs);
Douglas Gregorba345522011-12-02 23:23:56 +00004374}
4375
Douglas Gregor22d09742012-01-03 18:04:46 +00004376ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
Douglas Gregorba345522011-12-02 23:23:56 +00004377 Module *Imported, SourceLocation EndLoc)
Douglas Gregor22d09742012-01-03 18:04:46 +00004378 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, false),
Douglas Gregor0f2a3602011-12-03 00:30:27 +00004379 NextLocalImport()
Douglas Gregorba345522011-12-02 23:23:56 +00004380{
James Y Knight7a22b242015-08-06 20:26:32 +00004381 *getTrailingObjects<SourceLocation>() = EndLoc;
Douglas Gregorba345522011-12-02 23:23:56 +00004382}
4383
Richard Smithf7981722013-11-22 09:01:48 +00004384ImportDecl *ImportDecl::Create(ASTContext &C, DeclContext *DC,
Douglas Gregor22d09742012-01-03 18:04:46 +00004385 SourceLocation StartLoc, Module *Imported,
Douglas Gregorba345522011-12-02 23:23:56 +00004386 ArrayRef<SourceLocation> IdentifierLocs) {
James Y Knight7a22b242015-08-06 20:26:32 +00004387 return new (C, DC,
4388 additionalSizeToAlloc<SourceLocation>(IdentifierLocs.size()))
Richard Smithf7981722013-11-22 09:01:48 +00004389 ImportDecl(DC, StartLoc, Imported, IdentifierLocs);
Douglas Gregorba345522011-12-02 23:23:56 +00004390}
4391
Richard Smithf7981722013-11-22 09:01:48 +00004392ImportDecl *ImportDecl::CreateImplicit(ASTContext &C, DeclContext *DC,
Douglas Gregor22d09742012-01-03 18:04:46 +00004393 SourceLocation StartLoc,
Richard Smithf7981722013-11-22 09:01:48 +00004394 Module *Imported,
Douglas Gregorba345522011-12-02 23:23:56 +00004395 SourceLocation EndLoc) {
James Y Knight7a22b242015-08-06 20:26:32 +00004396 ImportDecl *Import = new (C, DC, additionalSizeToAlloc<SourceLocation>(1))
4397 ImportDecl(DC, StartLoc, Imported, EndLoc);
Douglas Gregorba345522011-12-02 23:23:56 +00004398 Import->setImplicit();
4399 return Import;
4400}
4401
Douglas Gregor72172e92012-01-05 21:55:30 +00004402ImportDecl *ImportDecl::CreateDeserialized(ASTContext &C, unsigned ID,
4403 unsigned NumLocations) {
James Y Knight7a22b242015-08-06 20:26:32 +00004404 return new (C, ID, additionalSizeToAlloc<SourceLocation>(NumLocations))
Richard Smithf7981722013-11-22 09:01:48 +00004405 ImportDecl(EmptyShell());
Douglas Gregorba345522011-12-02 23:23:56 +00004406}
4407
4408ArrayRef<SourceLocation> ImportDecl::getIdentifierLocs() const {
4409 if (!ImportedAndComplete.getInt())
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00004410 return None;
Douglas Gregorba345522011-12-02 23:23:56 +00004411
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00004412 const auto *StoredLocs = getTrailingObjects<SourceLocation>();
Craig Topper5fc8fc22014-08-27 06:28:36 +00004413 return llvm::makeArrayRef(StoredLocs,
4414 getNumModuleIdentifiers(getImportedModule()));
Douglas Gregorba345522011-12-02 23:23:56 +00004415}
4416
4417SourceRange ImportDecl::getSourceRange() const {
4418 if (!ImportedAndComplete.getInt())
James Y Knight7a22b242015-08-06 20:26:32 +00004419 return SourceRange(getLocation(), *getTrailingObjects<SourceLocation>());
4420
Douglas Gregorba345522011-12-02 23:23:56 +00004421 return SourceRange(getLocation(), getIdentifierLocs().back());
4422}
Richard Smith8df390f2016-09-08 23:14:54 +00004423
4424//===----------------------------------------------------------------------===//
4425// ExportDecl Implementation
4426//===----------------------------------------------------------------------===//
4427
4428void ExportDecl::anchor() {}
4429
4430ExportDecl *ExportDecl::Create(ASTContext &C, DeclContext *DC,
4431 SourceLocation ExportLoc) {
4432 return new (C, DC) ExportDecl(DC, ExportLoc);
4433}
4434
4435ExportDecl *ExportDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
4436 return new (C, ID) ExportDecl(nullptr, SourceLocation());
4437}