blob: 30599ea7cfbe025f8b54c9f1b53422c2c8f9f87d [file] [log] [blame]
Eugene Zelenkode0215c2017-11-13 23:01:27 +00001//===- Decl.cpp - Declaration AST Node Implementation ---------------------===//
Chris Lattnera11999d2006-10-15 22:34:45 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris 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"
Eugene Zelenkode0215c2017-11-13 23:01:27 +000019#include "clang/AST/CanonicalType.h"
20#include "clang/AST/DeclBase.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "clang/AST/DeclCXX.h"
22#include "clang/AST/DeclObjC.h"
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000023#include "clang/AST/DeclOpenMP.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000024#include "clang/AST/DeclTemplate.h"
Eugene Zelenkode0215c2017-11-13 23:01:27 +000025#include "clang/AST/DeclarationName.h"
Nuno Lopes394ec982008-12-17 23:39:55 +000026#include "clang/AST/Expr.h"
Anders Carlsson714d0962009-12-15 19:16:31 +000027#include "clang/AST/ExprCXX.h"
Eugene Zelenkode0215c2017-11-13 23:01:27 +000028#include "clang/AST/ExternalASTSource.h"
Richard Trieue6caa262017-12-23 00:41:01 +000029#include "clang/AST/ODRHash.h"
Douglas Gregor7de59662009-05-29 20:38:28 +000030#include "clang/AST/PrettyPrinter.h"
Eugene Zelenkode0215c2017-11-13 23:01:27 +000031#include "clang/AST/Redeclarable.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000032#include "clang/AST/Stmt.h"
Eugene Zelenkode0215c2017-11-13 23:01:27 +000033#include "clang/AST/TemplateBase.h"
34#include "clang/AST/Type.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000035#include "clang/AST/TypeLoc.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000036#include "clang/Basic/Builtins.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000037#include "clang/Basic/IdentifierTable.h"
Eugene Zelenkode0215c2017-11-13 23:01:27 +000038#include "clang/Basic/LLVM.h"
39#include "clang/Basic/LangOptions.h"
40#include "clang/Basic/Linkage.h"
Douglas Gregorba345522011-12-02 23:23:56 +000041#include "clang/Basic/Module.h"
Eugene Zelenkode0215c2017-11-13 23:01:27 +000042#include "clang/Basic/PartialDiagnostic.h"
43#include "clang/Basic/SanitizerBlacklist.h"
44#include "clang/Basic/Sanitizers.h"
45#include "clang/Basic/SourceLocation.h"
46#include "clang/Basic/SourceManager.h"
Abramo Bagnara6150c882010-05-11 21:36:43 +000047#include "clang/Basic/Specifiers.h"
Eugene Zelenkode0215c2017-11-13 23:01:27 +000048#include "clang/Basic/TargetCXXABI.h"
Douglas Gregor1baf38f2011-03-26 12:10:19 +000049#include "clang/Basic/TargetInfo.h"
Eugene Zelenkode0215c2017-11-13 23:01:27 +000050#include "clang/Basic/Visibility.h"
Kostya Serebryany293dc9b2014-10-16 20:54:52 +000051#include "clang/Frontend/FrontendDiagnostic.h"
Eugene Zelenkode0215c2017-11-13 23:01:27 +000052#include "llvm/ADT/APSInt.h"
53#include "llvm/ADT/ArrayRef.h"
54#include "llvm/ADT/None.h"
55#include "llvm/ADT/Optional.h"
56#include "llvm/ADT/STLExtras.h"
57#include "llvm/ADT/SmallVector.h"
58#include "llvm/ADT/StringSwitch.h"
59#include "llvm/ADT/StringRef.h"
60#include "llvm/ADT/Triple.h"
61#include "llvm/Support/Casting.h"
John McCall06f6fe8d2009-09-04 01:14:41 +000062#include "llvm/Support/ErrorHandling.h"
Eugene Zelenkode0215c2017-11-13 23:01:27 +000063#include "llvm/Support/raw_ostream.h"
David Blaikie9c70e042011-09-21 18:16:56 +000064#include <algorithm>
Eugene Zelenkode0215c2017-11-13 23:01:27 +000065#include <cassert>
66#include <cstddef>
67#include <cstring>
68#include <memory>
69#include <string>
70#include <tuple>
71#include <type_traits>
David Blaikie9c70e042011-09-21 18:16:56 +000072
Chris Lattner6d9a6852006-10-25 05:11:20 +000073using namespace clang;
Chris Lattnera11999d2006-10-15 22:34:45 +000074
Richard Smith0b87e072013-10-07 08:02:11 +000075Decl *clang::getPrimaryMergedDecl(Decl *D) {
76 return D->getASTContext().getPrimaryMergedDecl(D);
77}
78
Richard Smith73b21d82014-09-03 02:33:22 +000079// Defined here so that it can be inlined into its direct callers.
80bool Decl::isOutOfLine() const {
81 return !getLexicalDeclContext()->Equals(getDeclContext());
82}
83
Richard Smith42413142015-05-15 20:05:43 +000084TranslationUnitDecl::TranslationUnitDecl(ASTContext &ctx)
85 : Decl(TranslationUnit, nullptr, SourceLocation()),
Eugene Zelenkode0215c2017-11-13 23:01:27 +000086 DeclContext(TranslationUnit), Ctx(ctx) {}
Richard Smith42413142015-05-15 20:05:43 +000087
Chris Lattner88f70d62008-03-15 05:43:15 +000088//===----------------------------------------------------------------------===//
Douglas Gregor6e6ad602009-01-20 01:17:11 +000089// NamedDecl Implementation
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +000090//===----------------------------------------------------------------------===//
91
John McCalldf25c432013-02-16 00:17:33 +000092// Visibility rules aren't rigorously externally specified, but here
93// are the basic principles behind what we implement:
94//
95// 1. An explicit visibility attribute is generally a direct expression
96// of the user's intent and should be honored. Only the innermost
97// visibility attribute applies. If no visibility attribute applies,
98// global visibility settings are considered.
99//
100// 2. There is one caveat to the above: on or in a template pattern,
101// an explicit visibility attribute is just a default rule, and
102// visibility can be decreased by the visibility of template
103// arguments. But this, too, has an exception: an attribute on an
104// explicit specialization or instantiation causes all the visibility
105// restrictions of the template arguments to be ignored.
106//
107// 3. A variable that does not otherwise have explicit visibility can
108// be restricted by the visibility of its type.
109//
110// 4. A visibility restriction is explicit if it comes from an
111// attribute (or something like it), not a global visibility setting.
112// When emitting a reference to an external symbol, visibility
113// restrictions are ignored unless they are explicit.
John McCalld041a9b2013-02-20 01:54:26 +0000114//
115// 5. When computing the visibility of a non-type, including a
116// non-type member of a class, only non-type visibility restrictions
117// are considered: the 'visibility' attribute, global value-visibility
118// settings, and a few special cases like __private_extern.
119//
120// 6. When computing the visibility of a type, including a type member
121// of a class, only type visibility restrictions are considered:
122// the 'type_visibility' attribute and global type-visibility settings.
123// However, a 'visibility' attribute counts as a 'type_visibility'
124// attribute on any declaration that only has the former.
125//
126// The visibility of a "secondary" entity, like a template argument,
127// is computed using the kind of that entity, not the kind of the
128// primary entity for which we are computing visibility. For example,
129// the visibility of a specialization of either of these templates:
130// template <class T, bool (&compare)(T, X)> bool has_match(list<T>, X);
131// template <class T, bool (&compare)(T, X)> class matcher;
132// is restricted according to the type visibility of the argument 'T',
133// the type visibility of 'bool(&)(T,X)', and the value visibility of
134// the argument function 'compare'. That 'has_match' is a value
135// and 'matcher' is a type only matters when looking for attributes
136// and settings from the immediate context.
John McCalldf25c432013-02-16 00:17:33 +0000137
John McCalld041a9b2013-02-20 01:54:26 +0000138/// Does this computation kind permit us to consider additional
139/// visibility settings from attributes and the like?
140static bool hasExplicitVisibilityAlready(LVComputationKind computation) {
Richard Smithfbe7b462017-09-22 02:22:32 +0000141 return computation.IgnoreExplicitVisibility;
John McCalld041a9b2013-02-20 01:54:26 +0000142}
143
144/// Given an LVComputationKind, return one of the same type/value sort
145/// that records that it already has explicit visibility.
146static LVComputationKind
Richard Smithfbe7b462017-09-22 02:22:32 +0000147withExplicitVisibilityAlready(LVComputationKind Kind) {
148 Kind.IgnoreExplicitVisibility = true;
149 return Kind;
John McCalld041a9b2013-02-20 01:54:26 +0000150}
151
David Blaikie05785d12013-02-20 22:23:23 +0000152static Optional<Visibility> getExplicitVisibility(const NamedDecl *D,
153 LVComputationKind kind) {
Richard Smithfbe7b462017-09-22 02:22:32 +0000154 assert(!kind.IgnoreExplicitVisibility &&
John McCalld041a9b2013-02-20 01:54:26 +0000155 "asking for explicit visibility when we shouldn't be");
Richard Smithfbe7b462017-09-22 02:22:32 +0000156 return D->getExplicitVisibility(kind.getExplicitVisibilityKind());
John McCalld041a9b2013-02-20 01:54:26 +0000157}
158
John McCalldf25c432013-02-16 00:17:33 +0000159/// Is the given declaration a "type" or a "value" for the purposes of
160/// visibility computation?
161static bool usesTypeVisibility(const NamedDecl *D) {
John McCallb4a99d32013-02-19 01:57:35 +0000162 return isa<TypeDecl>(D) ||
163 isa<ClassTemplateDecl>(D) ||
164 isa<ObjCInterfaceDecl>(D);
John McCalldf25c432013-02-16 00:17:33 +0000165}
166
John McCall5f46c482013-02-21 23:42:58 +0000167/// Does the given declaration have member specialization information,
168/// and if so, is it an explicit specialization?
169template <class T> static typename
Benjamin Kramered2f4762014-03-07 14:30:23 +0000170std::enable_if<!std::is_base_of<RedeclarableTemplateDecl, T>::value, bool>::type
John McCall5f46c482013-02-21 23:42:58 +0000171isExplicitMemberSpecialization(const T *D) {
172 if (const MemberSpecializationInfo *member =
173 D->getMemberSpecializationInfo()) {
174 return member->isExplicitSpecialization();
175 }
176 return false;
177}
178
179/// For templates, this question is easier: a member template can't be
180/// explicitly instantiated, so there's a single bit indicating whether
181/// or not this is an explicit member specialization.
182static bool isExplicitMemberSpecialization(const RedeclarableTemplateDecl *D) {
183 return D->isMemberSpecialization();
184}
185
John McCalld041a9b2013-02-20 01:54:26 +0000186/// Given a visibility attribute, return the explicit visibility
187/// associated with it.
188template <class T>
189static Visibility getVisibilityFromAttr(const T *attr) {
190 switch (attr->getVisibility()) {
191 case T::Default:
192 return DefaultVisibility;
193 case T::Hidden:
194 return HiddenVisibility;
195 case T::Protected:
196 return ProtectedVisibility;
197 }
198 llvm_unreachable("bad visibility kind");
199}
200
John McCalldf25c432013-02-16 00:17:33 +0000201/// Return the explicit visibility of the given declaration.
David Blaikie05785d12013-02-20 22:23:23 +0000202static Optional<Visibility> getVisibilityOf(const NamedDecl *D,
John McCalld041a9b2013-02-20 01:54:26 +0000203 NamedDecl::ExplicitVisibilityKind kind) {
204 // If we're ultimately computing the visibility of a type, look for
205 // a 'type_visibility' attribute before looking for 'visibility'.
206 if (kind == NamedDecl::VisibilityForType) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000207 if (const auto *A = D->getAttr<TypeVisibilityAttr>()) {
John McCalld041a9b2013-02-20 01:54:26 +0000208 return getVisibilityFromAttr(A);
209 }
210 }
211
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000212 // If this declaration has an explicit visibility attribute, use it.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000213 if (const auto *A = D->getAttr<VisibilityAttr>()) {
John McCalld041a9b2013-02-20 01:54:26 +0000214 return getVisibilityFromAttr(A);
John McCall457a04e2010-10-22 21:05:15 +0000215 }
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000216
David Blaikie7a30dc52013-02-21 01:47:18 +0000217 return None;
John McCall457a04e2010-10-22 21:05:15 +0000218}
219
George Burgess IV99db3ea2017-08-09 04:02:49 +0000220LinkageInfo LinkageComputer::getLVForType(const Type &T,
221 LVComputationKind computation) {
Richard Smithfbe7b462017-09-22 02:22:32 +0000222 if (computation.IgnoreAllVisibility)
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000223 return LinkageInfo(T.getLinkage(), DefaultVisibility, true);
George Burgess IV35cb4f82017-08-09 04:12:17 +0000224 return getTypeLinkageAndVisibility(&T);
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000225}
226
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000227/// \brief Get the most restrictive linkage for the types in the given
John McCalldf25c432013-02-16 00:17:33 +0000228/// template parameter list. For visibility purposes, template
229/// parameters are part of the signature of a template.
George Burgess IV99db3ea2017-08-09 04:02:49 +0000230LinkageInfo LinkageComputer::getLVForTemplateParameterList(
231 const TemplateParameterList *Params, LVComputationKind computation) {
John McCalldf25c432013-02-16 00:17:33 +0000232 LinkageInfo LV;
David Majnemerc7b85c42014-04-23 05:16:48 +0000233 for (const NamedDecl *P : *Params) {
John McCalldf25c432013-02-16 00:17:33 +0000234 // Template type parameters are the most common and never
235 // contribute to visibility, pack or not.
David Majnemerc7b85c42014-04-23 05:16:48 +0000236 if (isa<TemplateTypeParmDecl>(P))
John McCalldf25c432013-02-16 00:17:33 +0000237 continue;
238
239 // Non-type template parameters can be restricted by the value type, e.g.
240 // template <enum X> class A { ... };
241 // We have to be careful here, though, because we can be dealing with
242 // dependent types.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000243 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
John McCalldf25c432013-02-16 00:17:33 +0000244 // Handle the non-pack case first.
245 if (!NTTP->isExpandedParameterPack()) {
246 if (!NTTP->getType()->isDependentType()) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000247 LV.merge(getLVForType(*NTTP->getType(), computation));
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000248 }
249 continue;
250 }
Rafael Espindolaeeb9d9f2012-01-02 06:26:22 +0000251
John McCalldf25c432013-02-16 00:17:33 +0000252 // Look at all the types in an expanded pack.
253 for (unsigned i = 0, n = NTTP->getNumExpansionTypes(); i != n; ++i) {
254 QualType type = NTTP->getExpansionType(i);
255 if (!type->isDependentType())
George Burgess IV35cb4f82017-08-09 04:12:17 +0000256 LV.merge(getTypeLinkageAndVisibility(type));
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000257 }
John McCalldf25c432013-02-16 00:17:33 +0000258 continue;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000259 }
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000260
John McCalldf25c432013-02-16 00:17:33 +0000261 // Template template parameters can be restricted by their
262 // template parameters, recursively.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000263 const auto *TTP = cast<TemplateTemplateParmDecl>(P);
John McCalldf25c432013-02-16 00:17:33 +0000264
265 // Handle the non-pack case first.
266 if (!TTP->isExpandedParameterPack()) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000267 LV.merge(getLVForTemplateParameterList(TTP->getTemplateParameters(),
268 computation));
John McCalldf25c432013-02-16 00:17:33 +0000269 continue;
270 }
271
272 // Look at all expansions in an expanded pack.
273 for (unsigned i = 0, n = TTP->getNumExpansionTemplateParameters();
274 i != n; ++i) {
275 LV.merge(getLVForTemplateParameterList(
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000276 TTP->getExpansionTemplateParameters(i), computation));
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000277 }
278 }
279
John McCall457a04e2010-10-22 21:05:15 +0000280 return LV;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000281}
282
Eli Friedman7e346a82013-07-01 20:22:57 +0000283static const Decl *getOutermostFuncOrBlockContext(const Decl *D) {
Craig Topper36250ad2014-05-12 05:36:57 +0000284 const Decl *Ret = nullptr;
Rafael Espindolac1b38a22013-05-16 04:30:21 +0000285 const DeclContext *DC = D->getDeclContext();
286 while (DC->getDeclKind() != Decl::TranslationUnit) {
Eli Friedman7e346a82013-07-01 20:22:57 +0000287 if (isa<FunctionDecl>(DC) || isa<BlockDecl>(DC))
288 Ret = cast<Decl>(DC);
Rafael Espindolac1b38a22013-05-16 04:30:21 +0000289 DC = DC->getParent();
290 }
291 return Ret;
292}
293
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000294/// \brief Get the most restrictive linkage for the types and
295/// declarations in the given template argument list.
John McCalldf25c432013-02-16 00:17:33 +0000296///
297/// Note that we don't take an LVComputationKind because we always
298/// want to honor the visibility of template arguments in the same way.
George Burgess IV99db3ea2017-08-09 04:02:49 +0000299LinkageInfo
300LinkageComputer::getLVForTemplateArgumentList(ArrayRef<TemplateArgument> Args,
301 LVComputationKind computation) {
John McCalldf25c432013-02-16 00:17:33 +0000302 LinkageInfo LV;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000303
David Majnemerc7b85c42014-04-23 05:16:48 +0000304 for (const TemplateArgument &Arg : Args) {
305 switch (Arg.getKind()) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000306 case TemplateArgument::Null:
307 case TemplateArgument::Integral:
308 case TemplateArgument::Expression:
John McCalldf25c432013-02-16 00:17:33 +0000309 continue;
Rafael Espindolaeeb9d9f2012-01-02 06:26:22 +0000310
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000311 case TemplateArgument::Type:
David Majnemerc7b85c42014-04-23 05:16:48 +0000312 LV.merge(getLVForType(*Arg.getAsType(), computation));
John McCalldf25c432013-02-16 00:17:33 +0000313 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000314
315 case TemplateArgument::Declaration:
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000316 if (const auto *ND = dyn_cast<NamedDecl>(Arg.getAsDecl())) {
John McCalldf25c432013-02-16 00:17:33 +0000317 assert(!usesTypeVisibility(ND));
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000318 LV.merge(getLVForDecl(ND, computation));
John McCalldf25c432013-02-16 00:17:33 +0000319 }
320 continue;
Eli Friedmanb826a002012-09-26 02:36:12 +0000321
322 case TemplateArgument::NullPtr:
George Burgess IV35cb4f82017-08-09 04:12:17 +0000323 LV.merge(getTypeLinkageAndVisibility(Arg.getNullPtrType()));
John McCalldf25c432013-02-16 00:17:33 +0000324 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000325
326 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000327 case TemplateArgument::TemplateExpansion:
David Majnemerc7b85c42014-04-23 05:16:48 +0000328 if (TemplateDecl *Template =
329 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl())
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000330 LV.merge(getLVForDecl(Template, computation));
John McCalldf25c432013-02-16 00:17:33 +0000331 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000332
333 case TemplateArgument::Pack:
David Majnemerc7b85c42014-04-23 05:16:48 +0000334 LV.merge(getLVForTemplateArgumentList(Arg.getPackAsArray(), computation));
John McCalldf25c432013-02-16 00:17:33 +0000335 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000336 }
John McCalldf25c432013-02-16 00:17:33 +0000337 llvm_unreachable("bad template argument kind");
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000338 }
339
John McCall457a04e2010-10-22 21:05:15 +0000340 return LV;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000341}
342
George Burgess IV99db3ea2017-08-09 04:02:49 +0000343LinkageInfo
344LinkageComputer::getLVForTemplateArgumentList(const TemplateArgumentList &TArgs,
345 LVComputationKind computation) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000346 return getLVForTemplateArgumentList(TArgs.asArray(), computation);
John McCall8823c652010-08-13 08:35:10 +0000347}
348
John McCall5f46c482013-02-21 23:42:58 +0000349static bool shouldConsiderTemplateVisibility(const FunctionDecl *fn,
350 const FunctionTemplateSpecializationInfo *specInfo) {
351 // Include visibility from the template parameters and arguments
352 // only if this is not an explicit instantiation or specialization
353 // with direct explicit visibility. (Implicit instantiations won't
354 // have a direct attribute.)
355 if (!specInfo->isExplicitInstantiationOrSpecialization())
356 return true;
357
358 return !fn->hasAttr<VisibilityAttr>();
359}
360
John McCalldf25c432013-02-16 00:17:33 +0000361/// Merge in template-related linkage and visibility for the given
362/// function template specialization.
363///
364/// We don't need a computation kind here because we can assume
365/// LVForValue.
John McCall5f46c482013-02-21 23:42:58 +0000366///
NAKAMURA Takumi62eae082013-02-22 04:06:28 +0000367/// \param[out] LV the computation to use for the parent
George Burgess IV99db3ea2017-08-09 04:02:49 +0000368void LinkageComputer::mergeTemplateLV(
369 LinkageInfo &LV, const FunctionDecl *fn,
370 const FunctionTemplateSpecializationInfo *specInfo,
371 LVComputationKind computation) {
John McCall5f46c482013-02-21 23:42:58 +0000372 bool considerVisibility =
373 shouldConsiderTemplateVisibility(fn, specInfo);
John McCalldf25c432013-02-16 00:17:33 +0000374
375 // Merge information from the template parameters.
John McCall5f46c482013-02-21 23:42:58 +0000376 FunctionTemplateDecl *temp = specInfo->getTemplate();
John McCalldf25c432013-02-16 00:17:33 +0000377 LinkageInfo tempLV =
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000378 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
John McCalldf25c432013-02-16 00:17:33 +0000379 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
380
381 // Merge information from the template arguments.
382 const TemplateArgumentList &templateArgs = *specInfo->TemplateArguments;
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000383 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
John McCalldf25c432013-02-16 00:17:33 +0000384 LV.mergeMaybeWithVisibility(argsLV, considerVisibility);
John McCallb8c604a2011-06-27 23:06:04 +0000385}
386
John McCall5f46c482013-02-21 23:42:58 +0000387/// Does the given declaration have a direct visibility attribute
388/// that would match the given rules?
389static bool hasDirectVisibilityAttribute(const NamedDecl *D,
390 LVComputationKind computation) {
Richard Smithfbe7b462017-09-22 02:22:32 +0000391 if (computation.IgnoreAllVisibility)
John McCall5f46c482013-02-21 23:42:58 +0000392 return false;
Richard Smithfbe7b462017-09-22 02:22:32 +0000393
394 return (computation.isTypeVisibility() && D->hasAttr<TypeVisibilityAttr>()) ||
395 D->hasAttr<VisibilityAttr>();
John McCall5f46c482013-02-21 23:42:58 +0000396}
397
John McCalld041a9b2013-02-20 01:54:26 +0000398/// Should we consider visibility associated with the template
399/// arguments and parameters of the given class template specialization?
400static bool shouldConsiderTemplateVisibility(
401 const ClassTemplateSpecializationDecl *spec,
402 LVComputationKind computation) {
John McCalldf25c432013-02-16 00:17:33 +0000403 // Include visibility from the template parameters and arguments
404 // only if this is not an explicit instantiation or specialization
405 // with direct explicit visibility (and note that implicit
406 // instantiations won't have a direct attribute).
407 //
408 // Furthermore, we want to ignore template parameters and arguments
John McCalld041a9b2013-02-20 01:54:26 +0000409 // for an explicit specialization when computing the visibility of a
410 // member thereof with explicit visibility.
John McCalldf25c432013-02-16 00:17:33 +0000411 //
412 // This is a bit complex; let's unpack it.
413 //
414 // An explicit class specialization is an independent, top-level
415 // declaration. As such, if it or any of its members has an
416 // explicit visibility attribute, that must directly express the
417 // user's intent, and we should honor it. The same logic applies to
418 // an explicit instantiation of a member of such a thing.
John McCalld041a9b2013-02-20 01:54:26 +0000419
420 // Fast path: if this is not an explicit instantiation or
421 // specialization, we always want to consider template-related
422 // visibility restrictions.
423 if (!spec->isExplicitInstantiationOrSpecialization())
424 return true;
425
426 // This is the 'member thereof' check.
427 if (spec->isExplicitSpecialization() &&
428 hasExplicitVisibilityAlready(computation))
429 return false;
430
John McCall5f46c482013-02-21 23:42:58 +0000431 return !hasDirectVisibilityAttribute(spec, computation);
John McCalld041a9b2013-02-20 01:54:26 +0000432}
433
434/// Merge in template-related linkage and visibility for the given
435/// class template specialization.
George Burgess IV99db3ea2017-08-09 04:02:49 +0000436void LinkageComputer::mergeTemplateLV(
437 LinkageInfo &LV, const ClassTemplateSpecializationDecl *spec,
438 LVComputationKind computation) {
John McCalld041a9b2013-02-20 01:54:26 +0000439 bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
John McCalldf25c432013-02-16 00:17:33 +0000440
441 // Merge information from the template parameters, but ignore
442 // visibility if we're only considering template arguments.
443
John McCalld041a9b2013-02-20 01:54:26 +0000444 ClassTemplateDecl *temp = spec->getSpecializedTemplate();
John McCalldf25c432013-02-16 00:17:33 +0000445 LinkageInfo tempLV =
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000446 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
John McCalldf25c432013-02-16 00:17:33 +0000447 LV.mergeMaybeWithVisibility(tempLV,
John McCalld041a9b2013-02-20 01:54:26 +0000448 considerVisibility && !hasExplicitVisibilityAlready(computation));
John McCalldf25c432013-02-16 00:17:33 +0000449
450 // Merge information from the template arguments. We ignore
451 // template-argument visibility if we've got an explicit
452 // instantiation with a visibility attribute.
453 const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000454 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
Rafael Espindola503276b2013-05-30 21:23:15 +0000455 if (considerVisibility)
456 LV.mergeVisibility(argsLV);
457 LV.mergeExternalVisibility(argsLV);
John McCallb8c604a2011-06-27 23:06:04 +0000458}
459
Larisse Voufo5899e192014-07-02 23:08:34 +0000460/// Should we consider visibility associated with the template
461/// arguments and parameters of the given variable template
462/// specialization? As usual, follow class template specialization
463/// logic up to initialization.
464static bool shouldConsiderTemplateVisibility(
465 const VarTemplateSpecializationDecl *spec,
466 LVComputationKind computation) {
467 // Include visibility from the template parameters and arguments
468 // only if this is not an explicit instantiation or specialization
469 // with direct explicit visibility (and note that implicit
470 // instantiations won't have a direct attribute).
471 if (!spec->isExplicitInstantiationOrSpecialization())
472 return true;
473
474 // An explicit variable specialization is an independent, top-level
475 // declaration. As such, if it has an explicit visibility attribute,
476 // that must directly express the user's intent, and we should honor
477 // it.
478 if (spec->isExplicitSpecialization() &&
479 hasExplicitVisibilityAlready(computation))
480 return false;
481
482 return !hasDirectVisibilityAttribute(spec, computation);
483}
484
485/// Merge in template-related linkage and visibility for the given
486/// variable template specialization. As usual, follow class template
487/// specialization logic up to initialization.
George Burgess IV99db3ea2017-08-09 04:02:49 +0000488void LinkageComputer::mergeTemplateLV(LinkageInfo &LV,
489 const VarTemplateSpecializationDecl *spec,
490 LVComputationKind computation) {
Larisse Voufo5899e192014-07-02 23:08:34 +0000491 bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
492
493 // Merge information from the template parameters, but ignore
494 // visibility if we're only considering template arguments.
495
496 VarTemplateDecl *temp = spec->getSpecializedTemplate();
497 LinkageInfo tempLV =
498 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
499 LV.mergeMaybeWithVisibility(tempLV,
500 considerVisibility && !hasExplicitVisibilityAlready(computation));
501
502 // Merge information from the template arguments. We ignore
503 // template-argument visibility if we've got an explicit
504 // instantiation with a visibility attribute.
505 const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
506 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
507 if (considerVisibility)
508 LV.mergeVisibility(argsLV);
509 LV.mergeExternalVisibility(argsLV);
510}
511
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000512static bool useInlineVisibilityHidden(const NamedDecl *D) {
513 // FIXME: we should warn if -fvisibility-inlines-hidden is used with c.
Rafael Espindola5cc78902012-07-13 23:26:43 +0000514 const LangOptions &Opts = D->getASTContext().getLangOpts();
515 if (!Opts.CPlusPlus || !Opts.InlineVisibilityHidden)
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000516 return false;
517
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000518 const auto *FD = dyn_cast<FunctionDecl>(D);
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000519 if (!FD)
520 return false;
521
522 TemplateSpecializationKind TSK = TSK_Undeclared;
523 if (FunctionTemplateSpecializationInfo *spec
524 = FD->getTemplateSpecializationInfo()) {
525 TSK = spec->getTemplateSpecializationKind();
526 } else if (MemberSpecializationInfo *MSI =
527 FD->getMemberSpecializationInfo()) {
528 TSK = MSI->getTemplateSpecializationKind();
529 }
530
Craig Topper36250ad2014-05-12 05:36:57 +0000531 const FunctionDecl *Def = nullptr;
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000532 // InlineVisibilityHidden only applies to definitions, and
533 // isInlined() only gives meaningful answers on definitions
534 // anyway.
535 return TSK != TSK_ExplicitInstantiationDeclaration &&
536 TSK != TSK_ExplicitInstantiationDefinition &&
Rafael Espindolafb9d4b42012-10-11 16:32:25 +0000537 FD->hasBody(Def) && Def->isInlined() && !Def->hasAttr<GNUInlineAttr>();
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000538}
539
Rafael Espindola593537a2013-05-05 20:15:21 +0000540template <typename T> static bool isFirstInExternCContext(T *D) {
Rafael Espindola8db352d2013-10-17 15:37:26 +0000541 const T *First = D->getFirstDecl();
Rafael Espindola593537a2013-05-05 20:15:21 +0000542 return First->isInExternCContext();
Rafael Espindolaf4187652013-02-14 01:18:37 +0000543}
544
Richard Smith03c05032014-02-17 23:34:47 +0000545static bool isSingleLineLanguageLinkage(const Decl &D) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000546 if (const auto *SD = dyn_cast<LinkageSpecDecl>(D.getDeclContext()))
Richard Smith03c05032014-02-17 23:34:47 +0000547 if (!SD->hasBraces())
Rafael Espindola327be3c2013-04-26 01:30:23 +0000548 return true;
549 return false;
550}
551
Richard Smith1283e982017-07-07 20:04:28 +0000552static bool isExportedFromModuleIntefaceUnit(const NamedDecl *D) {
Richard Smithbecb92d2017-10-10 22:33:17 +0000553 // FIXME: Handle isModulePrivate.
Richard Smith1283e982017-07-07 20:04:28 +0000554 switch (D->getModuleOwnershipKind()) {
555 case Decl::ModuleOwnershipKind::Unowned:
556 case Decl::ModuleOwnershipKind::ModulePrivate:
557 return false;
558 case Decl::ModuleOwnershipKind::Visible:
559 case Decl::ModuleOwnershipKind::VisibleWhenImported:
560 if (auto *M = D->getOwningModule())
561 return M->Kind == Module::ModuleInterfaceUnit;
562 }
563 llvm_unreachable("unexpected module ownership kind");
564}
565
566static LinkageInfo getInternalLinkageFor(const NamedDecl *D) {
567 // Internal linkage declarations within a module interface unit are modeled
568 // as "module-internal linkage", which means that they have internal linkage
569 // formally but can be indirectly accessed from outside the module via inline
570 // functions and templates defined within the module.
571 if (auto *M = D->getOwningModule())
572 if (M->Kind == Module::ModuleInterfaceUnit)
573 return LinkageInfo(ModuleInternalLinkage, DefaultVisibility, false);
574
575 return LinkageInfo::internal();
576}
577
578static LinkageInfo getExternalLinkageFor(const NamedDecl *D) {
579 // C++ Modules TS [basic.link]/6.8:
580 // - A name declared at namespace scope that does not have internal linkage
581 // by the previous rules and that is introduced by a non-exported
582 // declaration has module linkage.
583 if (auto *M = D->getOwningModule())
584 if (M->Kind == Module::ModuleInterfaceUnit)
Richard Smithbecb92d2017-10-10 22:33:17 +0000585 if (!isExportedFromModuleIntefaceUnit(
586 cast<NamedDecl>(D->getCanonicalDecl())))
Richard Smith1283e982017-07-07 20:04:28 +0000587 return LinkageInfo(ModuleLinkage, DefaultVisibility, false);
588
589 return LinkageInfo::external();
590}
591
George Burgess IV99db3ea2017-08-09 04:02:49 +0000592LinkageInfo
593LinkageComputer::getLVForNamespaceScopeDecl(const NamedDecl *D,
Richard Smithc95d2c52017-09-22 04:25:05 +0000594 LVComputationKind computation,
595 bool IgnoreVarTypeLinkage) {
Sebastian Redl50c68252010-08-31 00:36:30 +0000596 assert(D->getDeclContext()->getRedeclContext()->isFileContext() &&
Douglas Gregorf73b2822009-11-25 22:24:25 +0000597 "Not a name having namespace scope");
598 ASTContext &Context = D->getASTContext();
599
600 // C++ [basic.link]p3:
601 // A name having namespace scope (3.3.6) has internal linkage if it
602 // is the name of
603 // - an object, reference, function or function template that is
604 // explicitly declared static; or,
605 // (This bullet corresponds to C99 6.2.2p3.)
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000606 if (const auto *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregorf73b2822009-11-25 22:24:25 +0000607 // Explicitly declared static.
John McCall8e7d6562010-08-26 03:08:43 +0000608 if (Var->getStorageClass() == SC_Static)
Richard Smith1283e982017-07-07 20:04:28 +0000609 return getInternalLinkageFor(Var);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000610
Richard Smith62f19e72016-06-25 00:15:56 +0000611 // - a non-inline, non-volatile object or reference that is explicitly
612 // declared const or constexpr and neither explicitly declared extern
613 // nor previously declared to have external linkage; or (there is no
614 // equivalent in C99)
Richard Smith1283e982017-07-07 20:04:28 +0000615 // The C++ modules TS adds "non-exported" to this list.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000616 if (Context.getLangOpts().CPlusPlus &&
Richard Smithdc0ef452012-10-19 06:37:48 +0000617 Var->getType().isConstQualified() &&
Richard Smith62f19e72016-06-25 00:15:56 +0000618 !Var->getType().isVolatileQualified() &&
Richard Smith1283e982017-07-07 20:04:28 +0000619 !Var->isInline() &&
620 !isExportedFromModuleIntefaceUnit(Var)) {
Rafael Espindola985a3ab2013-04-03 19:22:20 +0000621 const VarDecl *PrevVar = Var->getPreviousDecl();
Rafael Espindola985a3ab2013-04-03 19:22:20 +0000622 if (PrevVar)
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000623 return getLVForDecl(PrevVar, computation);
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000624
625 if (Var->getStorageClass() != SC_Extern &&
Rafael Espindola327be3c2013-04-26 01:30:23 +0000626 Var->getStorageClass() != SC_PrivateExtern &&
Richard Smith03c05032014-02-17 23:34:47 +0000627 !isSingleLineLanguageLinkage(*Var))
Richard Smith1283e982017-07-07 20:04:28 +0000628 return getInternalLinkageFor(Var);
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000629 }
630
631 for (const VarDecl *PrevVar = Var->getPreviousDecl(); PrevVar;
632 PrevVar = PrevVar->getPreviousDecl()) {
633 if (PrevVar->getStorageClass() == SC_PrivateExtern &&
634 Var->getStorageClass() == SC_None)
George Burgess IV35cb4f82017-08-09 04:12:17 +0000635 return getDeclLinkageAndVisibility(PrevVar);
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000636 // Explicitly declared static.
637 if (PrevVar->getStorageClass() == SC_Static)
Richard Smith1283e982017-07-07 20:04:28 +0000638 return getInternalLinkageFor(Var);
Fariborz Jahanian8feee2d2011-06-16 20:14:50 +0000639 }
Alp Tokera2794f92014-01-22 07:29:52 +0000640 } else if (const FunctionDecl *Function = D->getAsFunction()) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000641 // C++ [temp]p4:
642 // A non-member function template can have internal linkage; any
643 // other template name shall have external linkage.
Douglas Gregorf73b2822009-11-25 22:24:25 +0000644
645 // Explicitly declared static.
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000646 if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
Richard Smith1283e982017-07-07 20:04:28 +0000647 return getInternalLinkageFor(Function);
David Majnemer18fac3b2014-12-10 22:58:14 +0000648 } else if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D)) {
649 // - a data member of an anonymous union.
650 const VarDecl *VD = IFD->getVarDecl();
651 assert(VD && "Expected a VarDecl in this IndirectFieldDecl!");
Richard Smithc95d2c52017-09-22 04:25:05 +0000652 return getLVForNamespaceScopeDecl(VD, computation, IgnoreVarTypeLinkage);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000653 }
David Majnemer0eb8bbd2013-10-23 20:52:43 +0000654 assert(!isa<FieldDecl>(D) && "Didn't expect a FieldDecl!");
Douglas Gregorf73b2822009-11-25 22:24:25 +0000655
Chandler Carruth9682a2fd2011-02-24 19:03:39 +0000656 if (D->isInAnonymousNamespace()) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000657 const auto *Var = dyn_cast<VarDecl>(D);
658 const auto *Func = dyn_cast<FunctionDecl>(D);
Richard Smithdf963a32017-09-22 22:21:44 +0000659 // FIXME: The check for extern "C" here is not justified by the standard
660 // wording, but we retain it from the pre-DR1113 model to avoid breaking
661 // code.
Richard Smith1283e982017-07-07 20:04:28 +0000662 //
663 // C++11 [basic.link]p4:
664 // An unnamed namespace or a namespace declared directly or indirectly
665 // within an unnamed namespace has internal linkage.
Rafael Espindola593537a2013-05-05 20:15:21 +0000666 if ((!Var || !isFirstInExternCContext(Var)) &&
667 (!Func || !isFirstInExternCContext(Func)))
Richard Smithdf963a32017-09-22 22:21:44 +0000668 return getInternalLinkageFor(D);
Chandler Carruth9682a2fd2011-02-24 19:03:39 +0000669 }
John McCallb7139c42010-10-28 04:18:25 +0000670
John McCall457a04e2010-10-22 21:05:15 +0000671 // Set up the defaults.
672
673 // C99 6.2.2p5:
674 // If the declaration of an identifier for an object has file
675 // scope and no storage-class specifier, its linkage is
676 // external.
Richard Smithdd8b5332017-09-04 05:37:53 +0000677 LinkageInfo LV = getExternalLinkageFor(D);
John McCallc273f242010-10-30 11:50:40 +0000678
John McCalld041a9b2013-02-20 01:54:26 +0000679 if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +0000680 if (Optional<Visibility> Vis = getExplicitVisibility(D, computation)) {
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000681 LV.mergeVisibility(*Vis, true);
Rafael Espindola78158af2012-04-16 18:46:26 +0000682 } else {
683 // If we're declared in a namespace with a visibility attribute,
John McCalldf25c432013-02-16 00:17:33 +0000684 // use that namespace's visibility, and it still counts as explicit.
Rafael Espindola78158af2012-04-16 18:46:26 +0000685 for (const DeclContext *DC = D->getDeclContext();
686 !isa<TranslationUnitDecl>(DC);
687 DC = DC->getParent()) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000688 const auto *ND = dyn_cast<NamespaceDecl>(DC);
Rafael Espindola78158af2012-04-16 18:46:26 +0000689 if (!ND) continue;
David Blaikie05785d12013-02-20 22:23:23 +0000690 if (Optional<Visibility> Vis = getExplicitVisibility(ND, computation)) {
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000691 LV.mergeVisibility(*Vis, true);
Rafael Espindola78158af2012-04-16 18:46:26 +0000692 break;
693 }
694 }
695 }
Rafael Espindola78158af2012-04-16 18:46:26 +0000696
John McCalldf25c432013-02-16 00:17:33 +0000697 // Add in global settings if the above didn't give us direct visibility.
Rafael Espindola4a5da442013-02-27 02:56:45 +0000698 if (!LV.isVisibilityExplicit()) {
John McCallb4a99d32013-02-19 01:57:35 +0000699 // Use global type/value visibility as appropriate.
Richard Smithfbe7b462017-09-22 02:22:32 +0000700 Visibility globalVisibility =
701 computation.isValueVisibility()
702 ? Context.getLangOpts().getValueVisibilityMode()
703 : Context.getLangOpts().getTypeVisibilityMode();
John McCallb4a99d32013-02-19 01:57:35 +0000704 LV.mergeVisibility(globalVisibility, /*explicit*/ false);
John McCalldf25c432013-02-16 00:17:33 +0000705
706 // If we're paying attention to global visibility, apply
707 // -finline-visibility-hidden if this is an inline method.
708 if (useInlineVisibilityHidden(D))
709 LV.mergeVisibility(HiddenVisibility, true);
710 }
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000711 }
Rafael Espindolaaf690f52012-04-19 02:55:01 +0000712
Douglas Gregorf73b2822009-11-25 22:24:25 +0000713 // C++ [basic.link]p4:
John McCall457a04e2010-10-22 21:05:15 +0000714
Douglas Gregorf73b2822009-11-25 22:24:25 +0000715 // A name having namespace scope has external linkage if it is the
716 // name of
717 //
718 // - an object or reference, unless it has internal linkage; or
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000719 if (const auto *Var = dyn_cast<VarDecl>(D)) {
John McCall37bb6c92010-10-29 22:22:43 +0000720 // GCC applies the following optimization to variables and static
721 // data members, but not to functions:
722 //
John McCall457a04e2010-10-22 21:05:15 +0000723 // Modify the variable's LV by the LV of its type unless this is
724 // C or extern "C". This follows from [basic.link]p9:
725 // A type without linkage shall not be used as the type of a
726 // variable or function with external linkage unless
727 // - the entity has C language linkage, or
728 // - the entity is declared within an unnamed namespace, or
729 // - the entity is not used or is defined in the same
730 // translation unit.
731 // and [basic.link]p10:
732 // ...the types specified by all declarations referring to a
733 // given variable or function shall be identical...
734 // C does not have an equivalent rule.
735 //
John McCall5fe84122010-10-26 04:59:26 +0000736 // Ignore this if we've got an explicit attribute; the user
737 // probably knows what they're doing.
738 //
John McCall457a04e2010-10-22 21:05:15 +0000739 // Note that we don't want to make the variable non-external
740 // because of this, but unique-external linkage suits us.
Richard Smithc95d2c52017-09-22 04:25:05 +0000741 if (Context.getLangOpts().CPlusPlus && !isFirstInExternCContext(Var) &&
742 !IgnoreVarTypeLinkage) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000743 LinkageInfo TypeLV = getLVForType(*Var->getType(), computation);
Richard Smith405e2db2017-09-20 07:22:00 +0000744 if (!isExternallyVisible(TypeLV.getLinkage()))
John McCallc273f242010-10-30 11:50:40 +0000745 return LinkageInfo::uniqueExternal();
Rafael Espindola4a5da442013-02-27 02:56:45 +0000746 if (!LV.isVisibilityExplicit())
John McCalldf25c432013-02-16 00:17:33 +0000747 LV.mergeVisibility(TypeLV);
John McCall37bb6c92010-10-29 22:22:43 +0000748 }
749
John McCall23032652010-11-02 18:38:13 +0000750 if (Var->getStorageClass() == SC_PrivateExtern)
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000751 LV.mergeVisibility(HiddenVisibility, true);
John McCall23032652010-11-02 18:38:13 +0000752
Rafael Espindolad5ed0332012-11-12 04:10:23 +0000753 // Note that Sema::MergeVarDecl already takes care of implementing
754 // C99 6.2.2p4 and propagating the visibility attribute, so we don't have
755 // to do it here.
Douglas Gregorf73b2822009-11-25 22:24:25 +0000756
Larisse Voufo5899e192014-07-02 23:08:34 +0000757 // As per function and class template specializations (below),
758 // consider LV for the template and template arguments. We're at file
759 // scope, so we do not need to worry about nested specializations.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000760 if (const auto *spec = dyn_cast<VarTemplateSpecializationDecl>(Var)) {
Larisse Voufo5899e192014-07-02 23:08:34 +0000761 mergeTemplateLV(LV, spec, computation);
762 }
763
Douglas Gregorf73b2822009-11-25 22:24:25 +0000764 // - a function, unless it has internal linkage; or
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000765 } else if (const auto *Function = dyn_cast<FunctionDecl>(D)) {
John McCall2efaf112010-10-28 07:07:52 +0000766 // In theory, we can modify the function's LV by the LV of its
767 // type unless it has C linkage (see comment above about variables
768 // for justification). In practice, GCC doesn't do this, so it's
769 // just too painful to make work.
John McCall457a04e2010-10-22 21:05:15 +0000770
John McCall23032652010-11-02 18:38:13 +0000771 if (Function->getStorageClass() == SC_PrivateExtern)
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000772 LV.mergeVisibility(HiddenVisibility, true);
John McCall23032652010-11-02 18:38:13 +0000773
Rafael Espindolaa508c5d2012-11-21 02:47:19 +0000774 // Note that Sema::MergeCompatibleFunctionDecls already takes care of
775 // merging storage classes and visibility attributes, so we don't have to
776 // look at previous decls in here.
Douglas Gregorf73b2822009-11-25 22:24:25 +0000777
John McCallf768aa72011-02-10 06:50:24 +0000778 // In C++, then if the type of the function uses a type with
779 // unique-external linkage, it's not legally usable from outside
780 // this translation unit. However, we should use the C linkage
781 // rules instead for extern "C" declarations.
Richard Smith99f54792018-01-03 02:34:35 +0000782 if (Context.getLangOpts().CPlusPlus && !isFirstInExternCContext(Function)) {
Richard Smithc95d2c52017-09-22 04:25:05 +0000783 // Only look at the type-as-written. Otherwise, deducing the return type
784 // of a function could change its linkage.
Richard Smith50f4afc2013-05-12 23:17:59 +0000785 QualType TypeAsWritten = Function->getType();
786 if (TypeSourceInfo *TSI = Function->getTypeSourceInfo())
787 TypeAsWritten = TSI->getType();
Richard Smith405e2db2017-09-20 07:22:00 +0000788 if (!isExternallyVisible(TypeAsWritten->getLinkage()))
Richard Smith50f4afc2013-05-12 23:17:59 +0000789 return LinkageInfo::uniqueExternal();
790 }
John McCallf768aa72011-02-10 06:50:24 +0000791
John McCall5f46c482013-02-21 23:42:58 +0000792 // Consider LV from the template and the template arguments.
793 // We're at file scope, so we do not need to worry about nested
794 // specializations.
John McCallb8c604a2011-06-27 23:06:04 +0000795 if (FunctionTemplateSpecializationInfo *specInfo
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000796 = Function->getTemplateSpecializationInfo()) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000797 mergeTemplateLV(LV, Function, specInfo, computation);
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000798 }
799
Douglas Gregorf73b2822009-11-25 22:24:25 +0000800 // - a named class (Clause 9), or an unnamed class defined in a
801 // typedef declaration in which the class has the typedef name
802 // for linkage purposes (7.1.3); or
803 // - a named enumeration (7.2), or an unnamed enumeration
804 // defined in a typedef declaration in which the enumeration
805 // has the typedef name for linkage purposes (7.1.3); or
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000806 } else if (const auto *Tag = dyn_cast<TagDecl>(D)) {
John McCall457a04e2010-10-22 21:05:15 +0000807 // Unnamed tags have no linkage.
John McCall5ea95772013-03-09 00:54:27 +0000808 if (!Tag->hasNameForLinkage())
John McCallc273f242010-10-30 11:50:40 +0000809 return LinkageInfo::none();
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000810
John McCall457a04e2010-10-22 21:05:15 +0000811 // If this is a class template specialization, consider the
John McCall5f46c482013-02-21 23:42:58 +0000812 // linkage of the template and template arguments. We're at file
813 // scope, so we do not need to worry about nested specializations.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000814 if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) {
John McCalldf25c432013-02-16 00:17:33 +0000815 mergeTemplateLV(LV, spec, computation);
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000816 }
Douglas Gregorf73b2822009-11-25 22:24:25 +0000817
818 // - an enumerator belonging to an enumeration with external linkage;
John McCall457a04e2010-10-22 21:05:15 +0000819 } else if (isa<EnumConstantDecl>(D)) {
Rafael Espindola46cb6f12012-04-21 23:28:21 +0000820 LinkageInfo EnumLV = getLVForDecl(cast<NamedDecl>(D->getDeclContext()),
John McCalldf25c432013-02-16 00:17:33 +0000821 computation);
Rafael Espindolab97e8962013-05-27 14:14:42 +0000822 if (!isExternalFormalLinkage(EnumLV.getLinkage()))
John McCallc273f242010-10-30 11:50:40 +0000823 return LinkageInfo::none();
824 LV.merge(EnumLV);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000825
826 // - a template, unless it is a function template that has
827 // internal linkage (Clause 14);
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000828 } else if (const auto *temp = dyn_cast<TemplateDecl>(D)) {
John McCalld041a9b2013-02-20 01:54:26 +0000829 bool considerVisibility = !hasExplicitVisibilityAlready(computation);
John McCalldf25c432013-02-16 00:17:33 +0000830 LinkageInfo tempLV =
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000831 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
John McCalldf25c432013-02-16 00:17:33 +0000832 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
833
Douglas Gregorf73b2822009-11-25 22:24:25 +0000834 // - a namespace (7.3), unless it is declared within an unnamed
835 // namespace.
Richard Smith1283e982017-07-07 20:04:28 +0000836 //
837 // We handled names in anonymous namespaces above.
838 } else if (isa<NamespaceDecl>(D)) {
John McCall457a04e2010-10-22 21:05:15 +0000839 return LV;
Douglas Gregorf73b2822009-11-25 22:24:25 +0000840
John McCall457a04e2010-10-22 21:05:15 +0000841 // By extension, we assign external linkage to Objective-C
842 // interfaces.
843 } else if (isa<ObjCInterfaceDecl>(D)) {
844 // fallout
845
Richard Smith97135cc2015-11-12 22:19:45 +0000846 } else if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
847 // A typedef declaration has linkage if it gives a type a name for
848 // linkage purposes.
849 if (!TD->getAnonDeclWithTypedefName(/*AnyRedecl*/true))
850 return LinkageInfo::none();
851
John McCall457a04e2010-10-22 21:05:15 +0000852 // Everything not covered here has no linkage.
853 } else {
John McCallc273f242010-10-30 11:50:40 +0000854 return LinkageInfo::none();
John McCall457a04e2010-10-22 21:05:15 +0000855 }
856
Richard Smithc445d5d2017-10-03 01:58:15 +0000857 // If we ended up with non-externally-visible linkage, visibility should
John McCall457a04e2010-10-22 21:05:15 +0000858 // always be default.
Richard Smithc445d5d2017-10-03 01:58:15 +0000859 if (!isExternallyVisible(LV.getLinkage()))
Rafael Espindola4a5da442013-02-27 02:56:45 +0000860 return LinkageInfo(LV.getLinkage(), DefaultVisibility, false);
John McCall457a04e2010-10-22 21:05:15 +0000861
John McCall457a04e2010-10-22 21:05:15 +0000862 return LV;
Douglas Gregorf73b2822009-11-25 22:24:25 +0000863}
864
George Burgess IV99db3ea2017-08-09 04:02:49 +0000865LinkageInfo
866LinkageComputer::getLVForClassMember(const NamedDecl *D,
Richard Smithc95d2c52017-09-22 04:25:05 +0000867 LVComputationKind computation,
868 bool IgnoreVarTypeLinkage) {
John McCall457a04e2010-10-22 21:05:15 +0000869 // Only certain class members have linkage. Note that fields don't
870 // really have linkage, but it's convenient to say they do for the
871 // purposes of calculating linkage of pointer-to-data-member
872 // template arguments.
Richard Smith26d11be2014-01-08 01:51:59 +0000873 //
874 // Templates also don't officially have linkage, but since we ignore
875 // the C++ standard and look at template arguments when determining
876 // linkage and visibility of a template specialization, we might hit
877 // a template template argument that way. If we do, we need to
878 // consider its linkage.
John McCall8823c652010-08-13 08:35:10 +0000879 if (!(isa<CXXMethodDecl>(D) ||
880 isa<VarDecl>(D) ||
John McCall457a04e2010-10-22 21:05:15 +0000881 isa<FieldDecl>(D) ||
David Majnemer0eb8bbd2013-10-23 20:52:43 +0000882 isa<IndirectFieldDecl>(D) ||
Richard Smith26d11be2014-01-08 01:51:59 +0000883 isa<TagDecl>(D) ||
884 isa<TemplateDecl>(D)))
John McCallc273f242010-10-30 11:50:40 +0000885 return LinkageInfo::none();
John McCall8823c652010-08-13 08:35:10 +0000886
John McCall07072662010-11-02 01:45:15 +0000887 LinkageInfo LV;
888
John McCall07072662010-11-02 01:45:15 +0000889 // If we have an explicit visibility attribute, merge that in.
John McCalld041a9b2013-02-20 01:54:26 +0000890 if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +0000891 if (Optional<Visibility> Vis = getExplicitVisibility(D, computation))
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000892 LV.mergeVisibility(*Vis, true);
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000893 // If we're paying attention to global visibility, apply
894 // -finline-visibility-hidden if this is an inline method.
895 //
896 // Note that we do this before merging information about
897 // the class visibility.
Rafael Espindola4a5da442013-02-27 02:56:45 +0000898 if (!LV.isVisibilityExplicit() && useInlineVisibilityHidden(D))
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000899 LV.mergeVisibility(HiddenVisibility, true);
John McCall07072662010-11-02 01:45:15 +0000900 }
Rafael Espindola53cf2192012-04-19 05:50:08 +0000901
902 // If this class member has an explicit visibility attribute, the only
903 // thing that can change its visibility is the template arguments, so
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000904 // only look for them when processing the class.
John McCalld041a9b2013-02-20 01:54:26 +0000905 LVComputationKind classComputation = computation;
Rafael Espindola4a5da442013-02-27 02:56:45 +0000906 if (LV.isVisibilityExplicit())
John McCalld041a9b2013-02-20 01:54:26 +0000907 classComputation = withExplicitVisibilityAlready(computation);
Rafael Espindola505a7c82012-04-16 18:25:01 +0000908
John McCall5f46c482013-02-21 23:42:58 +0000909 LinkageInfo classLV =
910 getLVForDecl(cast<RecordDecl>(D->getDeclContext()), classComputation);
Richard Smithcdb06f22017-09-23 04:02:17 +0000911 // The member has the same linkage as the class. If that's not externally
912 // visible, we don't need to compute anything about the linkage.
913 // FIXME: If we're only computing linkage, can we bail out here?
Rafael Espindolae6190db2013-05-28 02:22:10 +0000914 if (!isExternallyVisible(classLV.getLinkage()))
Richard Smithcdb06f22017-09-23 04:02:17 +0000915 return classLV;
Rafael Espindolae6190db2013-05-28 02:22:10 +0000916
917
John McCall5f46c482013-02-21 23:42:58 +0000918 // Otherwise, don't merge in classLV yet, because in certain cases
919 // we need to completely ignore the visibility from it.
920
921 // Specifically, if this decl exists and has an explicit attribute.
Craig Topper36250ad2014-05-12 05:36:57 +0000922 const NamedDecl *explicitSpecSuppressor = nullptr;
John McCall5f46c482013-02-21 23:42:58 +0000923
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000924 if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
Richard Smithc95d2c52017-09-22 04:25:05 +0000925 // Only look at the type-as-written. Otherwise, deducing the return type
926 // of a function could change its linkage.
927 QualType TypeAsWritten = MD->getType();
928 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
929 TypeAsWritten = TSI->getType();
930 if (!isExternallyVisible(TypeAsWritten->getLinkage()))
931 return LinkageInfo::uniqueExternal();
932
John McCall457a04e2010-10-22 21:05:15 +0000933 // If this is a method template specialization, use the linkage for
934 // the template parameters and arguments.
John McCallb8c604a2011-06-27 23:06:04 +0000935 if (FunctionTemplateSpecializationInfo *spec
John McCall8823c652010-08-13 08:35:10 +0000936 = MD->getTemplateSpecializationInfo()) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000937 mergeTemplateLV(LV, MD, spec, computation);
John McCall5f46c482013-02-21 23:42:58 +0000938 if (spec->isExplicitSpecialization()) {
939 explicitSpecSuppressor = MD;
940 } else if (isExplicitMemberSpecialization(spec->getTemplate())) {
941 explicitSpecSuppressor = spec->getTemplate()->getTemplatedDecl();
942 }
943 } else if (isExplicitMemberSpecialization(MD)) {
944 explicitSpecSuppressor = MD;
John McCalle6e622e2010-11-01 01:29:57 +0000945 }
John McCall457a04e2010-10-22 21:05:15 +0000946
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000947 } else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
948 if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
John McCalldf25c432013-02-16 00:17:33 +0000949 mergeTemplateLV(LV, spec, computation);
John McCall5f46c482013-02-21 23:42:58 +0000950 if (spec->isExplicitSpecialization()) {
951 explicitSpecSuppressor = spec;
952 } else {
953 const ClassTemplateDecl *temp = spec->getSpecializedTemplate();
954 if (isExplicitMemberSpecialization(temp)) {
955 explicitSpecSuppressor = temp->getTemplatedDecl();
956 }
957 }
958 } else if (isExplicitMemberSpecialization(RD)) {
959 explicitSpecSuppressor = RD;
John McCall37bb6c92010-10-29 22:22:43 +0000960 }
961
John McCall37bb6c92010-10-29 22:22:43 +0000962 // Static data members.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000963 } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
964 if (const auto *spec = dyn_cast<VarTemplateSpecializationDecl>(VD))
Larisse Voufo5899e192014-07-02 23:08:34 +0000965 mergeTemplateLV(LV, spec, computation);
966
John McCall36cd5cc2010-10-30 09:18:49 +0000967 // Modify the variable's linkage by its type, but ignore the
968 // type's visibility unless it's a definition.
Richard Smithc95d2c52017-09-22 04:25:05 +0000969 if (!IgnoreVarTypeLinkage) {
970 LinkageInfo typeLV = getLVForType(*VD->getType(), computation);
971 // FIXME: If the type's linkage is not externally visible, we can
972 // give this static data member UniqueExternalLinkage.
973 if (!LV.isVisibilityExplicit() && !classLV.isVisibilityExplicit())
974 LV.mergeVisibility(typeLV);
975 LV.mergeExternalVisibility(typeLV);
976 }
John McCall5f46c482013-02-21 23:42:58 +0000977
978 if (isExplicitMemberSpecialization(VD)) {
979 explicitSpecSuppressor = VD;
980 }
John McCalldf25c432013-02-16 00:17:33 +0000981
982 // Template members.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000983 } else if (const auto *temp = dyn_cast<TemplateDecl>(D)) {
John McCalldf25c432013-02-16 00:17:33 +0000984 bool considerVisibility =
Rafael Espindola4a5da442013-02-27 02:56:45 +0000985 (!LV.isVisibilityExplicit() &&
986 !classLV.isVisibilityExplicit() &&
John McCalld041a9b2013-02-20 01:54:26 +0000987 !hasExplicitVisibilityAlready(computation));
John McCalldf25c432013-02-16 00:17:33 +0000988 LinkageInfo tempLV =
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000989 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
John McCalldf25c432013-02-16 00:17:33 +0000990 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
John McCall5f46c482013-02-21 23:42:58 +0000991
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000992 if (const auto *redeclTemp = dyn_cast<RedeclarableTemplateDecl>(temp)) {
John McCall5f46c482013-02-21 23:42:58 +0000993 if (isExplicitMemberSpecialization(redeclTemp)) {
994 explicitSpecSuppressor = temp->getTemplatedDecl();
995 }
996 }
John McCall37bb6c92010-10-29 22:22:43 +0000997 }
998
John McCall5f46c482013-02-21 23:42:58 +0000999 // We should never be looking for an attribute directly on a template.
1000 assert(!explicitSpecSuppressor || !isa<TemplateDecl>(explicitSpecSuppressor));
1001
1002 // If this member is an explicit member specialization, and it has
1003 // an explicit attribute, ignore visibility from the parent.
1004 bool considerClassVisibility = true;
1005 if (explicitSpecSuppressor &&
Rafael Espindola4a5da442013-02-27 02:56:45 +00001006 // optimization: hasDVA() is true only with explicit visibility.
1007 LV.isVisibilityExplicit() &&
1008 classLV.getVisibility() != DefaultVisibility &&
John McCall5f46c482013-02-21 23:42:58 +00001009 hasDirectVisibilityAttribute(explicitSpecSuppressor, computation)) {
1010 considerClassVisibility = false;
1011 }
1012
1013 // Finally, merge in information from the class.
1014 LV.mergeMaybeWithVisibility(classLV, considerClassVisibility);
John McCall457a04e2010-10-22 21:05:15 +00001015 return LV;
John McCall8823c652010-08-13 08:35:10 +00001016}
1017
Eugene Zelenkode0215c2017-11-13 23:01:27 +00001018void NamedDecl::anchor() {}
David Blaikie68e081d2011-12-20 02:48:34 +00001019
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001020bool NamedDecl::isLinkageValid() const {
Rafael Espindola50df3a02013-05-25 17:16:20 +00001021 if (!hasCachedLinkage())
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001022 return true;
John McCalld396b972011-02-08 19:01:05 +00001023
Richard Smithfbe7b462017-09-22 02:22:32 +00001024 Linkage L = LinkageComputer{}
1025 .computeLVForDecl(this, LVComputationKind::forLinkageOnly())
1026 .getLinkage();
George Burgess IV99db3ea2017-08-09 04:02:49 +00001027 return L == getCachedLinkage();
John McCalld396b972011-02-08 19:01:05 +00001028}
1029
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001030ObjCStringFormatFamily NamedDecl::getObjCFStringFormattingFamily() const {
1031 StringRef name = getName();
1032 if (name.empty()) return SFF_None;
1033
1034 if (name.front() == 'C')
1035 if (name == "CFStringCreateWithFormat" ||
1036 name == "CFStringCreateWithFormatAndArguments" ||
1037 name == "CFStringAppendFormat" ||
1038 name == "CFStringAppendFormatAndArguments")
1039 return SFF_CFString;
1040 return SFF_None;
1041}
1042
Rafael Espindola3ae00052013-05-13 00:12:11 +00001043Linkage NamedDecl::getLinkageInternal() const {
John McCalld041a9b2013-02-20 01:54:26 +00001044 // We don't care about visibility here, so ask for the cheapest
1045 // possible visibility analysis.
Richard Smithfbe7b462017-09-22 02:22:32 +00001046 return LinkageComputer{}
1047 .getLVForDecl(this, LVComputationKind::forLinkageOnly())
1048 .getLinkage();
Douglas Gregorbf62d642010-12-06 18:36:25 +00001049}
1050
John McCallc273f242010-10-30 11:50:40 +00001051LinkageInfo NamedDecl::getLinkageAndVisibility() const {
George Burgess IV99db3ea2017-08-09 04:02:49 +00001052 return LinkageComputer{}.getDeclLinkageAndVisibility(this);
John McCall033caa52010-10-29 00:29:13 +00001053}
Ted Kremenek926d8602010-04-20 23:15:35 +00001054
Rafael Espindola9ad61122013-11-26 16:09:08 +00001055static Optional<Visibility>
1056getExplicitVisibilityAux(const NamedDecl *ND,
1057 NamedDecl::ExplicitVisibilityKind kind,
1058 bool IsMostRecent) {
1059 assert(!IsMostRecent || ND == ND->getMostRecentDecl());
1060
Rafael Espindola3a52c442013-02-26 19:33:14 +00001061 // Check the declaration itself first.
Rafael Espindola9ad61122013-11-26 16:09:08 +00001062 if (Optional<Visibility> V = getVisibilityOf(ND, kind))
Rafael Espindola3a52c442013-02-26 19:33:14 +00001063 return V;
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001064
Rafael Espindola3a52c442013-02-26 19:33:14 +00001065 // If this is a member class of a specialization of a class template
1066 // and the corresponding decl has explicit visibility, use that.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001067 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND)) {
Rafael Espindola3a52c442013-02-26 19:33:14 +00001068 CXXRecordDecl *InstantiatedFrom = RD->getInstantiatedFromMemberClass();
1069 if (InstantiatedFrom)
1070 return getVisibilityOf(InstantiatedFrom, kind);
1071 }
1072
1073 // If there wasn't explicit visibility there, and this is a
1074 // specialization of a class template, check for visibility
1075 // on the pattern.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001076 if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(ND))
Rafael Espindola3a52c442013-02-26 19:33:14 +00001077 return getVisibilityOf(spec->getSpecializedTemplate()->getTemplatedDecl(),
1078 kind);
1079
1080 // Use the most recent declaration.
Rafael Espindola7ab1ce02013-12-08 01:13:22 +00001081 if (!IsMostRecent && !isa<NamespaceDecl>(ND)) {
Rafael Espindola9ad61122013-11-26 16:09:08 +00001082 const NamedDecl *MostRecent = ND->getMostRecentDecl();
1083 if (MostRecent != ND)
1084 return getExplicitVisibilityAux(MostRecent, kind, true);
1085 }
Rafael Espindola3a52c442013-02-26 19:33:14 +00001086
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001087 if (const auto *Var = dyn_cast<VarDecl>(ND)) {
Rafael Espindola96e68242012-05-16 02:10:38 +00001088 if (Var->isStaticDataMember()) {
1089 VarDecl *InstantiatedFrom = Var->getInstantiatedFromStaticDataMember();
1090 if (InstantiatedFrom)
John McCalld041a9b2013-02-20 01:54:26 +00001091 return getVisibilityOf(InstantiatedFrom, kind);
Rafael Espindola96e68242012-05-16 02:10:38 +00001092 }
1093
David Majnemer35b02bc2014-04-29 07:32:26 +00001094 if (const auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(Var))
1095 return getVisibilityOf(VTSD->getSpecializedTemplate()->getTemplatedDecl(),
1096 kind);
1097
David Blaikie7a30dc52013-02-21 01:47:18 +00001098 return None;
Rafael Espindola96e68242012-05-16 02:10:38 +00001099 }
Rafael Espindola3a52c442013-02-26 19:33:14 +00001100 // Also handle function template specializations.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001101 if (const auto *fn = dyn_cast<FunctionDecl>(ND)) {
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001102 // If the function is a specialization of a template with an
1103 // explicit visibility attribute, use that.
1104 if (FunctionTemplateSpecializationInfo *templateInfo
1105 = fn->getTemplateSpecializationInfo())
John McCalld041a9b2013-02-20 01:54:26 +00001106 return getVisibilityOf(templateInfo->getTemplate()->getTemplatedDecl(),
1107 kind);
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001108
Rafael Espindola8093fdf2012-02-23 04:17:32 +00001109 // If the function is a member of a specialization of a class template
1110 // and the corresponding decl has explicit visibility, use that.
1111 FunctionDecl *InstantiatedFrom = fn->getInstantiatedFromMemberFunction();
1112 if (InstantiatedFrom)
John McCalld041a9b2013-02-20 01:54:26 +00001113 return getVisibilityOf(InstantiatedFrom, kind);
Rafael Espindola8093fdf2012-02-23 04:17:32 +00001114
David Blaikie7a30dc52013-02-21 01:47:18 +00001115 return None;
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001116 }
1117
Rafael Espindolafb4263f2012-07-31 19:02:02 +00001118 // The visibility of a template is stored in the templated decl.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001119 if (const auto *TD = dyn_cast<TemplateDecl>(ND))
John McCalld041a9b2013-02-20 01:54:26 +00001120 return getVisibilityOf(TD->getTemplatedDecl(), kind);
Rafael Espindolafb4263f2012-07-31 19:02:02 +00001121
David Blaikie7a30dc52013-02-21 01:47:18 +00001122 return None;
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001123}
1124
Rafael Espindola9ad61122013-11-26 16:09:08 +00001125Optional<Visibility>
1126NamedDecl::getExplicitVisibility(ExplicitVisibilityKind kind) const {
1127 return getExplicitVisibilityAux(this, kind, false);
1128}
1129
George Burgess IV99db3ea2017-08-09 04:02:49 +00001130LinkageInfo LinkageComputer::getLVForClosure(const DeclContext *DC,
1131 Decl *ContextDecl,
1132 LVComputationKind computation) {
Eli Friedman7e346a82013-07-01 20:22:57 +00001133 // This lambda has its linkage/visibility determined by its owner.
Richard Smithc95d2c52017-09-22 04:25:05 +00001134 const NamedDecl *Owner;
1135 if (!ContextDecl)
1136 Owner = dyn_cast<NamedDecl>(DC);
1137 else if (isa<ParmVarDecl>(ContextDecl))
1138 Owner =
1139 dyn_cast<NamedDecl>(ContextDecl->getDeclContext()->getRedeclContext());
1140 else
1141 Owner = cast<NamedDecl>(ContextDecl);
1142
Richard Smithc95d2c52017-09-22 04:25:05 +00001143 if (!Owner)
Richard Smith7ff83042017-09-22 04:33:20 +00001144 return LinkageInfo::none();
Richard Smithc95d2c52017-09-22 04:25:05 +00001145
1146 // If the owner has a deduced type, we need to skip querying the linkage and
1147 // visibility of that type, because it might involve this closure type. The
1148 // only effect of this is that we might give a lambda VisibleNoLinkage rather
1149 // than NoLinkage when we don't strictly need to, which is benign.
1150 auto *VD = dyn_cast<VarDecl>(Owner);
Richard Smith7ff83042017-09-22 04:33:20 +00001151 LinkageInfo OwnerLV =
Richard Smithc95d2c52017-09-22 04:25:05 +00001152 VD && VD->getType()->getContainedDeducedType()
1153 ? computeLVForDecl(Owner, computation, /*IgnoreVarTypeLinkage*/true)
1154 : getLVForDecl(Owner, computation);
1155
Richard Smith7ff83042017-09-22 04:33:20 +00001156 // A lambda never formally has linkage. But if the owner is externally
1157 // visible, then the lambda is too. We apply the same rules to blocks.
1158 if (!isExternallyVisible(OwnerLV.getLinkage()))
1159 return LinkageInfo::none();
1160 return LinkageInfo(VisibleNoLinkage, OwnerLV.getVisibility(),
1161 OwnerLV.isVisibilityExplicit());
Eli Friedman7e346a82013-07-01 20:22:57 +00001162}
1163
George Burgess IV99db3ea2017-08-09 04:02:49 +00001164LinkageInfo LinkageComputer::getLVForLocalDecl(const NamedDecl *D,
1165 LVComputationKind computation) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001166 if (const auto *Function = dyn_cast<FunctionDecl>(D)) {
John McCalldf25c432013-02-16 00:17:33 +00001167 if (Function->isInAnonymousNamespace() &&
Richard Smith99f54792018-01-03 02:34:35 +00001168 !isFirstInExternCContext(Function))
Richard Smithdf963a32017-09-22 22:21:44 +00001169 return getInternalLinkageFor(Function);
John McCalldf25c432013-02-16 00:17:33 +00001170
1171 // This is a "void f();" which got merged with a file static.
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001172 if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
Richard Smith1283e982017-07-07 20:04:28 +00001173 return getInternalLinkageFor(Function);
John McCalldf25c432013-02-16 00:17:33 +00001174
1175 LinkageInfo LV;
John McCalld041a9b2013-02-20 01:54:26 +00001176 if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +00001177 if (Optional<Visibility> Vis =
1178 getExplicitVisibility(Function, computation))
John McCalldf25c432013-02-16 00:17:33 +00001179 LV.mergeVisibility(*Vis, true);
1180 }
1181
1182 // Note that Sema::MergeCompatibleFunctionDecls already takes care of
1183 // merging storage classes and visibility attributes, so we don't have to
1184 // look at previous decls in here.
1185
1186 return LV;
1187 }
1188
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001189 if (const auto *Var = dyn_cast<VarDecl>(D)) {
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001190 if (Var->hasExternalStorage()) {
Richard Smith99f54792018-01-03 02:34:35 +00001191 if (Var->isInAnonymousNamespace() && !isFirstInExternCContext(Var))
Richard Smithdf963a32017-09-22 22:21:44 +00001192 return getInternalLinkageFor(Var);
John McCalldf25c432013-02-16 00:17:33 +00001193
John McCalldf25c432013-02-16 00:17:33 +00001194 LinkageInfo LV;
1195 if (Var->getStorageClass() == SC_PrivateExtern)
1196 LV.mergeVisibility(HiddenVisibility, true);
John McCalld041a9b2013-02-20 01:54:26 +00001197 else if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +00001198 if (Optional<Visibility> Vis = getExplicitVisibility(Var, computation))
John McCalldf25c432013-02-16 00:17:33 +00001199 LV.mergeVisibility(*Vis, true);
1200 }
1201
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001202 if (const VarDecl *Prev = Var->getPreviousDecl()) {
1203 LinkageInfo PrevLV = getLVForDecl(Prev, computation);
1204 if (PrevLV.getLinkage())
1205 LV.setLinkage(PrevLV.getLinkage());
1206 LV.mergeVisibility(PrevLV);
1207 }
1208
John McCalldf25c432013-02-16 00:17:33 +00001209 return LV;
1210 }
Rafael Espindolaa4184182013-06-17 20:04:51 +00001211
1212 if (!Var->isStaticLocal())
1213 return LinkageInfo::none();
John McCalldf25c432013-02-16 00:17:33 +00001214 }
1215
Rafael Espindolaa4184182013-06-17 20:04:51 +00001216 ASTContext &Context = D->getASTContext();
1217 if (!Context.getLangOpts().CPlusPlus)
Rafael Espindola50df3a02013-05-25 17:16:20 +00001218 return LinkageInfo::none();
1219
Eli Friedman7e346a82013-07-01 20:22:57 +00001220 const Decl *OuterD = getOutermostFuncOrBlockContext(D);
Alexey Bataev0a47e652016-01-12 09:01:25 +00001221 if (!OuterD || OuterD->isInvalidDecl())
Rafael Espindola50df3a02013-05-25 17:16:20 +00001222 return LinkageInfo::none();
Rafael Espindola52189362013-06-04 13:43:35 +00001223
Eli Friedman7e346a82013-07-01 20:22:57 +00001224 LinkageInfo LV;
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001225 if (const auto *BD = dyn_cast<BlockDecl>(OuterD)) {
Eli Friedman7e346a82013-07-01 20:22:57 +00001226 if (!BD->getBlockManglingNumber())
1227 return LinkageInfo::none();
Rafael Espindola52189362013-06-04 13:43:35 +00001228
Eli Friedman7e346a82013-07-01 20:22:57 +00001229 LV = getLVForClosure(BD->getDeclContext()->getRedeclContext(),
1230 BD->getBlockManglingContextDecl(), computation);
1231 } else {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001232 const auto *FD = cast<FunctionDecl>(OuterD);
Eli Friedman7e346a82013-07-01 20:22:57 +00001233 if (!FD->isInlined() &&
David Majnemer9963ade2014-12-16 04:52:14 +00001234 !isTemplateInstantiation(FD->getTemplateSpecializationKind()))
Eli Friedman7e346a82013-07-01 20:22:57 +00001235 return LinkageInfo::none();
1236
1237 LV = getLVForDecl(FD, computation);
1238 }
Rafael Espindola111bb2e2013-05-27 14:50:21 +00001239 if (!isExternallyVisible(LV.getLinkage()))
Rafael Espindola50df3a02013-05-25 17:16:20 +00001240 return LinkageInfo::none();
1241 return LinkageInfo(VisibleNoLinkage, LV.getVisibility(),
1242 LV.isVisibilityExplicit());
John McCalldf25c432013-02-16 00:17:33 +00001243}
1244
Faisal Vali49b4c1f2013-10-01 02:51:53 +00001245static inline const CXXRecordDecl*
1246getOutermostEnclosingLambda(const CXXRecordDecl *Record) {
1247 const CXXRecordDecl *Ret = Record;
1248 while (Record && Record->isLambda()) {
1249 Ret = Record;
1250 if (!Record->getParent()) break;
1251 // Get the Containing Class of this Lambda Class
1252 Record = dyn_cast_or_null<CXXRecordDecl>(
1253 Record->getParent()->getParent());
1254 }
1255 return Ret;
1256}
1257
George Burgess IV99db3ea2017-08-09 04:02:49 +00001258LinkageInfo LinkageComputer::computeLVForDecl(const NamedDecl *D,
Richard Smithc95d2c52017-09-22 04:25:05 +00001259 LVComputationKind computation,
1260 bool IgnoreVarTypeLinkage) {
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00001261 // Internal_linkage attribute overrides other considerations.
1262 if (D->hasAttr<InternalLinkageAttr>())
Richard Smith1283e982017-07-07 20:04:28 +00001263 return getInternalLinkageFor(D);
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00001264
Ted Kremenek926d8602010-04-20 23:15:35 +00001265 // Objective-C: treat all Objective-C declarations as having external
1266 // linkage.
John McCall033caa52010-10-29 00:29:13 +00001267 switch (D->getKind()) {
Ted Kremenek926d8602010-04-20 23:15:35 +00001268 default:
1269 break;
Richard Smith97135cc2015-11-12 22:19:45 +00001270
1271 // Per C++ [basic.link]p2, only the names of objects, references,
1272 // functions, types, templates, namespaces, and values ever have linkage.
1273 //
1274 // Note that the name of a typedef, namespace alias, using declaration,
1275 // and so on are not the name of the corresponding type, namespace, or
1276 // declaration, so they do *not* have linkage.
Richard Smith97135cc2015-11-12 22:19:45 +00001277 case Decl::ImplicitParam:
1278 case Decl::Label:
1279 case Decl::NamespaceAlias:
Argyrios Kyrtzidis79d04282011-12-01 01:28:21 +00001280 case Decl::ParmVar:
Richard Smith97135cc2015-11-12 22:19:45 +00001281 case Decl::Using:
1282 case Decl::UsingShadow:
1283 case Decl::UsingDirective:
Argyrios Kyrtzidis79d04282011-12-01 01:28:21 +00001284 return LinkageInfo::none();
Richard Smith97135cc2015-11-12 22:19:45 +00001285
Richard Smith26210db2015-11-13 03:52:13 +00001286 case Decl::EnumConstant:
1287 // C++ [basic.link]p4: an enumerator has the linkage of its enumeration.
Bruno Cardoso Lopes057c82c2017-07-01 00:06:27 +00001288 if (D->getASTContext().getLangOpts().CPlusPlus)
1289 return getLVForDecl(cast<EnumDecl>(D->getDeclContext()), computation);
1290 return LinkageInfo::visible_none();
Richard Smith26210db2015-11-13 03:52:13 +00001291
Richard Smith97135cc2015-11-12 22:19:45 +00001292 case Decl::Typedef:
1293 case Decl::TypeAlias:
1294 // A typedef declaration has linkage if it gives a type a name for
1295 // linkage purposes.
Vassil Vassilevb00ea082017-07-01 20:44:49 +00001296 if (!cast<TypedefNameDecl>(D)
Richard Smith97135cc2015-11-12 22:19:45 +00001297 ->getAnonDeclWithTypedefName(/*AnyRedecl*/true))
1298 return LinkageInfo::none();
1299 break;
1300
John McCall457a04e2010-10-22 21:05:15 +00001301 case Decl::TemplateTemplateParm: // count these as external
1302 case Decl::NonTypeTemplateParm:
Ted Kremenek926d8602010-04-20 23:15:35 +00001303 case Decl::ObjCAtDefsField:
1304 case Decl::ObjCCategory:
1305 case Decl::ObjCCategoryImpl:
Ted Kremenek926d8602010-04-20 23:15:35 +00001306 case Decl::ObjCCompatibleAlias:
Ted Kremenek926d8602010-04-20 23:15:35 +00001307 case Decl::ObjCImplementation:
Ted Kremenek926d8602010-04-20 23:15:35 +00001308 case Decl::ObjCMethod:
1309 case Decl::ObjCProperty:
1310 case Decl::ObjCPropertyImpl:
1311 case Decl::ObjCProtocol:
Richard Smith1283e982017-07-07 20:04:28 +00001312 return getExternalLinkageFor(D);
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001313
1314 case Decl::CXXRecord: {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001315 const auto *Record = cast<CXXRecordDecl>(D);
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001316 if (Record->isLambda()) {
1317 if (!Record->getLambdaManglingNumber()) {
1318 // This lambda has no mangling number, so it's internal.
Richard Smith1283e982017-07-07 20:04:28 +00001319 return getInternalLinkageFor(D);
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001320 }
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001321
Faisal Vali49b4c1f2013-10-01 02:51:53 +00001322 // This lambda has its linkage/visibility determined:
1323 // - either by the outermost lambda if that lambda has no mangling
1324 // number.
1325 // - or by the parent of the outer most lambda
1326 // This prevents infinite recursion in settings such as nested lambdas
1327 // used in NSDMI's, for e.g.
1328 // struct L {
1329 // int t{};
1330 // int t2 = ([](int a) { return [](int b) { return b; };})(t)(t);
1331 // };
1332 const CXXRecordDecl *OuterMostLambda =
1333 getOutermostEnclosingLambda(Record);
1334 if (!OuterMostLambda->getLambdaManglingNumber())
Richard Smith1283e982017-07-07 20:04:28 +00001335 return getInternalLinkageFor(D);
Faisal Vali49b4c1f2013-10-01 02:51:53 +00001336
1337 return getLVForClosure(
1338 OuterMostLambda->getDeclContext()->getRedeclContext(),
1339 OuterMostLambda->getLambdaContextDecl(), computation);
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001340 }
1341
1342 break;
1343 }
Ted Kremenek926d8602010-04-20 23:15:35 +00001344 }
1345
Douglas Gregorf73b2822009-11-25 22:24:25 +00001346 // Handle linkage for namespace-scope names.
John McCall033caa52010-10-29 00:29:13 +00001347 if (D->getDeclContext()->getRedeclContext()->isFileContext())
Richard Smithc95d2c52017-09-22 04:25:05 +00001348 return getLVForNamespaceScopeDecl(D, computation, IgnoreVarTypeLinkage);
Douglas Gregorf73b2822009-11-25 22:24:25 +00001349
1350 // C++ [basic.link]p5:
1351 // In addition, a member function, static data member, a named
1352 // class or enumeration of class scope, or an unnamed class or
1353 // enumeration defined in a class-scope typedef declaration such
1354 // that the class or enumeration has the typedef name for linkage
1355 // purposes (7.1.3), has external linkage if the name of the class
1356 // has external linkage.
John McCall033caa52010-10-29 00:29:13 +00001357 if (D->getDeclContext()->isRecord())
Richard Smithc95d2c52017-09-22 04:25:05 +00001358 return getLVForClassMember(D, computation, IgnoreVarTypeLinkage);
Douglas Gregorf73b2822009-11-25 22:24:25 +00001359
1360 // C++ [basic.link]p6:
1361 // The name of a function declared in block scope and the name of
1362 // an object declared by a block scope extern declaration have
1363 // linkage. If there is a visible declaration of an entity with
1364 // linkage having the same name and type, ignoring entities
1365 // declared outside the innermost enclosing namespace scope, the
1366 // block scope declaration declares that same entity and receives
1367 // the linkage of the previous declaration. If there is more than
1368 // one such matching entity, the program is ill-formed. Otherwise,
1369 // if no matching entity is found, the block scope entity receives
1370 // external linkage.
John McCalldf25c432013-02-16 00:17:33 +00001371 if (D->getDeclContext()->isFunctionOrMethod())
1372 return getLVForLocalDecl(D, computation);
Douglas Gregorf73b2822009-11-25 22:24:25 +00001373
1374 // C++ [basic.link]p6:
1375 // Names not covered by these rules have no linkage.
John McCallc273f242010-10-30 11:50:40 +00001376 return LinkageInfo::none();
John McCall457a04e2010-10-22 21:05:15 +00001377}
Douglas Gregorf73b2822009-11-25 22:24:25 +00001378
George Burgess IV99db3ea2017-08-09 04:02:49 +00001379/// getLVForDecl - Get the linkage and visibility for the given declaration.
1380LinkageInfo LinkageComputer::getLVForDecl(const NamedDecl *D,
1381 LVComputationKind computation) {
1382 // Internal_linkage attribute overrides other considerations.
1383 if (D->hasAttr<InternalLinkageAttr>())
1384 return getInternalLinkageFor(D);
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00001385
Richard Smithfbe7b462017-09-22 02:22:32 +00001386 if (computation.IgnoreAllVisibility && D->hasCachedLinkage())
George Burgess IV99db3ea2017-08-09 04:02:49 +00001387 return LinkageInfo(D->getCachedLinkage(), DefaultVisibility, false);
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001388
George Burgess IV35cb4f82017-08-09 04:12:17 +00001389 if (llvm::Optional<LinkageInfo> LI = lookup(D, computation))
1390 return *LI;
1391
George Burgess IV99db3ea2017-08-09 04:02:49 +00001392 LinkageInfo LV = computeLVForDecl(D, computation);
1393 if (D->hasCachedLinkage())
1394 assert(D->getCachedLinkage() == LV.getLinkage());
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001395
George Burgess IV99db3ea2017-08-09 04:02:49 +00001396 D->setCachedLinkage(LV.getLinkage());
George Burgess IV35cb4f82017-08-09 04:12:17 +00001397 cache(D, computation, LV);
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001398
1399#ifndef NDEBUG
George Burgess IV99db3ea2017-08-09 04:02:49 +00001400 // In C (because of gnu inline) and in c++ with microsoft extensions an
1401 // static can follow an extern, so we can have two decls with different
1402 // linkages.
1403 const LangOptions &Opts = D->getASTContext().getLangOpts();
1404 if (!Opts.CPlusPlus || Opts.MicrosoftExt)
1405 return LV;
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001406
George Burgess IV99db3ea2017-08-09 04:02:49 +00001407 // We have just computed the linkage for this decl. By induction we know
1408 // that all other computed linkages match, check that the one we just
1409 // computed also does.
1410 NamedDecl *Old = nullptr;
1411 for (auto I : D->redecls()) {
1412 auto *T = cast<NamedDecl>(I);
1413 if (T == D)
1414 continue;
1415 if (!T->isInvalidDecl() && T->hasCachedLinkage()) {
1416 Old = T;
1417 break;
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001418 }
George Burgess IV99db3ea2017-08-09 04:02:49 +00001419 }
1420 assert(!Old || Old->getCachedLinkage() == D->getCachedLinkage());
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001421#endif
1422
George Burgess IV99db3ea2017-08-09 04:02:49 +00001423 return LV;
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001424}
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001425
George Burgess IV99db3ea2017-08-09 04:02:49 +00001426LinkageInfo LinkageComputer::getDeclLinkageAndVisibility(const NamedDecl *D) {
Richard Smithfbe7b462017-09-22 02:22:32 +00001427 return getLVForDecl(D,
1428 LVComputationKind(usesTypeVisibility(D)
1429 ? NamedDecl::VisibilityForType
1430 : NamedDecl::VisibilityForValue));
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001431}
1432
Richard Smithbecb92d2017-10-10 22:33:17 +00001433Module *Decl::getOwningModuleForLinkage(bool IgnoreLinkage) const {
Richard Smithdd8b5332017-09-04 05:37:53 +00001434 Module *M = getOwningModule();
1435 if (!M)
1436 return nullptr;
1437
1438 switch (M->Kind) {
1439 case Module::ModuleMapModule:
1440 // Module map modules have no special linkage semantics.
1441 return nullptr;
1442
1443 case Module::ModuleInterfaceUnit:
1444 return M;
1445
Eugene Zelenkode0215c2017-11-13 23:01:27 +00001446 case Module::GlobalModuleFragment: {
Richard Smithdd8b5332017-09-04 05:37:53 +00001447 // External linkage declarations in the global module have no owning module
1448 // for linkage purposes. But internal linkage declarations in the global
1449 // module fragment of a particular module are owned by that module for
1450 // linkage purposes.
Richard Smithbecb92d2017-10-10 22:33:17 +00001451 if (IgnoreLinkage)
1452 return nullptr;
1453 bool InternalLinkage;
1454 if (auto *ND = dyn_cast<NamedDecl>(this))
1455 InternalLinkage = !ND->hasExternalFormalLinkage();
1456 else {
1457 auto *NSD = dyn_cast<NamespaceDecl>(this);
1458 InternalLinkage = (NSD && NSD->isAnonymousNamespace()) ||
1459 isInAnonymousNamespace();
1460 }
1461 return InternalLinkage ? M->Parent : nullptr;
Richard Smithdd8b5332017-09-04 05:37:53 +00001462 }
Eugene Zelenkode0215c2017-11-13 23:01:27 +00001463 }
Richard Smithdd8b5332017-09-04 05:37:53 +00001464
1465 llvm_unreachable("unknown module kind");
1466}
1467
Richard Smith7873de02016-08-11 22:25:46 +00001468void NamedDecl::printName(raw_ostream &os) const {
1469 os << Name;
1470}
1471
Douglas Gregor2ada0482009-02-04 17:27:36 +00001472std::string NamedDecl::getQualifiedNameAsString() const {
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001473 std::string QualName;
1474 llvm::raw_string_ostream OS(QualName);
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00001475 printQualifiedName(OS, getASTContext().getPrintingPolicy());
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001476 return OS.str();
1477}
1478
1479void NamedDecl::printQualifiedName(raw_ostream &OS) const {
1480 printQualifiedName(OS, getASTContext().getPrintingPolicy());
1481}
1482
1483void NamedDecl::printQualifiedName(raw_ostream &OS,
1484 const PrintingPolicy &P) const {
Douglas Gregor2ada0482009-02-04 17:27:36 +00001485 const DeclContext *Ctx = getDeclContext();
1486
Argyrios Kyrtzidisa166a2b2017-03-07 09:26:07 +00001487 // For ObjC methods, look through categories and use the interface as context.
1488 if (auto *MD = dyn_cast<ObjCMethodDecl>(this))
1489 if (auto *ID = MD->getClassInterface())
1490 Ctx = ID;
1491
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001492 if (Ctx->isFunctionOrMethod()) {
1493 printName(OS);
1494 return;
1495 }
Douglas Gregor2ada0482009-02-04 17:27:36 +00001496
Eugene Zelenkode0215c2017-11-13 23:01:27 +00001497 using ContextsTy = SmallVector<const DeclContext *, 8>;
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001498 ContextsTy Contexts;
1499
Sam McCall34f9d3f2018-02-02 13:34:47 +00001500 // Collect named contexts.
1501 while (Ctx) {
1502 if (isa<NamedDecl>(Ctx))
1503 Contexts.push_back(Ctx);
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001504 Ctx = Ctx->getParent();
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001505 }
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001506
Eugene Zelenkode0215c2017-11-13 23:01:27 +00001507 for (const DeclContext *DC : llvm::reverse(Contexts)) {
David Majnemerf7e36092016-06-23 00:15:04 +00001508 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
Benjamin Kramer9170e912013-02-22 15:46:01 +00001509 OS << Spec->getName();
Douglas Gregor85673582009-05-18 17:01:57 +00001510 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Serge Pavlov03e672c2017-11-28 16:14:14 +00001511 printTemplateArgumentList(OS, TemplateArgs.asArray(), P);
David Majnemerf7e36092016-06-23 00:15:04 +00001512 } else if (const auto *ND = dyn_cast<NamespaceDecl>(DC)) {
Richard Smith46dd5bb2014-05-30 22:16:51 +00001513 if (P.SuppressUnwrittenScope &&
1514 (ND->isAnonymousNamespace() || ND->isInline()))
1515 continue;
Reid Kleckner60103382015-12-16 02:04:40 +00001516 if (ND->isAnonymousNamespace()) {
1517 OS << (P.MSVCFormatting ? "`anonymous namespace\'"
1518 : "(anonymous namespace)");
1519 }
Sam Weinig07d211e2009-12-24 23:15:03 +00001520 else
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001521 OS << *ND;
David Majnemerf7e36092016-06-23 00:15:04 +00001522 } else if (const auto *RD = dyn_cast<RecordDecl>(DC)) {
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001523 if (!RD->getIdentifier())
David Blaikieabe1a392014-04-02 05:58:29 +00001524 OS << "(anonymous " << RD->getKindName() << ')';
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001525 else
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001526 OS << *RD;
David Majnemerf7e36092016-06-23 00:15:04 +00001527 } else if (const auto *FD = dyn_cast<FunctionDecl>(DC)) {
Craig Topper36250ad2014-05-12 05:36:57 +00001528 const FunctionProtoType *FT = nullptr;
Sam Weinigb999f682009-12-28 03:19:38 +00001529 if (FD->hasWrittenPrototype())
Eli Friedman5c27c4c2012-08-30 22:22:09 +00001530 FT = dyn_cast<FunctionProtoType>(FD->getType()->castAs<FunctionType>());
Sam Weinigb999f682009-12-28 03:19:38 +00001531
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001532 OS << *FD << '(';
Sam Weinigb999f682009-12-28 03:19:38 +00001533 if (FT) {
Sam Weinigb999f682009-12-28 03:19:38 +00001534 unsigned NumParams = FD->getNumParams();
1535 for (unsigned i = 0; i < NumParams; ++i) {
1536 if (i)
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001537 OS << ", ";
Argyrios Kyrtzidisa18347e2012-05-05 04:20:37 +00001538 OS << FD->getParamDecl(i)->getType().stream(P);
Sam Weinigb999f682009-12-28 03:19:38 +00001539 }
1540
1541 if (FT->isVariadic()) {
1542 if (NumParams > 0)
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001543 OS << ", ";
1544 OS << "...";
Sam Weinigb999f682009-12-28 03:19:38 +00001545 }
1546 }
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001547 OS << ')';
David Majnemerf7e36092016-06-23 00:15:04 +00001548 } else if (const auto *ED = dyn_cast<EnumDecl>(DC)) {
Alexander Kornienko4f355322015-11-09 16:45:17 +00001549 // C++ [dcl.enum]p10: Each enum-name and each unscoped
1550 // enumerator is declared in the scope that immediately contains
1551 // the enum-specifier. Each scoped enumerator is declared in the
1552 // scope of the enumeration.
Paul Robinsonf1838482017-12-21 21:47:22 +00001553 // For the case of unscoped enumerator, do not include in the qualified
Paul Robinsond1c3dd82017-12-26 18:01:19 +00001554 // name any information about its enum enclosing scope, as its visibility
Paul Robinsonf1838482017-12-21 21:47:22 +00001555 // is global.
1556 if (ED->isScoped())
Alexander Kornienko4f355322015-11-09 16:45:17 +00001557 OS << *ED;
1558 else
1559 continue;
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001560 } else {
David Majnemerf7e36092016-06-23 00:15:04 +00001561 OS << *cast<NamedDecl>(DC);
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001562 }
1563 OS << "::";
Douglas Gregor2ada0482009-02-04 17:27:36 +00001564 }
1565
Richard Smith7873de02016-08-11 22:25:46 +00001566 if (getDeclName() || isa<DecompositionDecl>(this))
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001567 OS << *this;
John McCalla2a3f7d2010-03-16 21:48:18 +00001568 else
David Blaikieabe1a392014-04-02 05:58:29 +00001569 OS << "(anonymous)";
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001570}
Douglas Gregor2ada0482009-02-04 17:27:36 +00001571
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001572void NamedDecl::getNameForDiagnostic(raw_ostream &OS,
1573 const PrintingPolicy &Policy,
1574 bool Qualified) const {
1575 if (Qualified)
1576 printQualifiedName(OS, Policy);
1577 else
1578 printName(OS);
Douglas Gregor2ada0482009-02-04 17:27:36 +00001579}
1580
Richard Smithe8292b12015-02-10 03:28:10 +00001581template<typename T> static bool isRedeclarableImpl(Redeclarable<T> *) {
1582 return true;
1583}
1584static bool isRedeclarableImpl(...) { return false; }
1585static bool isRedeclarable(Decl::Kind K) {
1586 switch (K) {
1587#define DECL(Type, Base) \
1588 case Decl::Type: \
1589 return isRedeclarableImpl((Type##Decl *)nullptr);
1590#define ABSTRACT_DECL(DECL)
1591#include "clang/AST/DeclNodes.inc"
1592 }
1593 llvm_unreachable("unknown decl kind");
1594}
1595
1596bool NamedDecl::declarationReplaces(NamedDecl *OldD, bool IsKnownNewer) const {
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001597 assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch");
1598
Richard Smithfe620d22015-03-05 23:24:12 +00001599 // Never replace one imported declaration with another; we need both results
1600 // when re-exporting.
1601 if (OldD->isFromASTFile() && isFromASTFile())
1602 return false;
1603
Richard Smith5cd86f82015-11-03 03:13:11 +00001604 // A kind mismatch implies that the declaration is not replaced.
1605 if (OldD->getKind() != getKind())
Richard Smithe8292b12015-02-10 03:28:10 +00001606 return false;
1607
Richard Smith5cd86f82015-11-03 03:13:11 +00001608 // For method declarations, we never replace. (Why?)
1609 if (isa<ObjCMethodDecl>(this))
1610 return false;
1611
1612 // For parameters, pick the newer one. This is either an error or (in
1613 // Objective-C) permitted as an extension.
1614 if (isa<ParmVarDecl>(this))
1615 return true;
1616
Richard Smithe8292b12015-02-10 03:28:10 +00001617 // Inline namespaces can give us two declarations with the same
1618 // name and kind in the same scope but different contexts; we should
1619 // keep both declarations in this case.
1620 if (!this->getDeclContext()->getRedeclContext()->Equals(
1621 OldD->getDeclContext()->getRedeclContext()))
1622 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001623
Richard Smith5cd86f82015-11-03 03:13:11 +00001624 // Using declarations can be replaced if they import the same name from the
1625 // same context.
Richard Smithe8292b12015-02-10 03:28:10 +00001626 if (auto *UD = dyn_cast<UsingDecl>(this)) {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00001627 ASTContext &Context = getASTContext();
Richard Smithe8292b12015-02-10 03:28:10 +00001628 return Context.getCanonicalNestedNameSpecifier(UD->getQualifier()) ==
Douglas Gregora9d87bc2011-02-25 00:36:19 +00001629 Context.getCanonicalNestedNameSpecifier(
Richard Smithe8292b12015-02-10 03:28:10 +00001630 cast<UsingDecl>(OldD)->getQualifier());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00001631 }
Richard Smithe8292b12015-02-10 03:28:10 +00001632 if (auto *UUVD = dyn_cast<UnresolvedUsingValueDecl>(this)) {
Eli Friedman0eaf10b2013-08-20 00:39:40 +00001633 ASTContext &Context = getASTContext();
Richard Smithe8292b12015-02-10 03:28:10 +00001634 return Context.getCanonicalNestedNameSpecifier(UUVD->getQualifier()) ==
Eli Friedman0eaf10b2013-08-20 00:39:40 +00001635 Context.getCanonicalNestedNameSpecifier(
1636 cast<UnresolvedUsingValueDecl>(OldD)->getQualifier());
1637 }
1638
Richard Smith5cd86f82015-11-03 03:13:11 +00001639 if (isRedeclarable(getKind())) {
1640 if (getCanonicalDecl() != OldD->getCanonicalDecl())
1641 return false;
1642
1643 if (IsKnownNewer)
1644 return true;
1645
Richard Smithe8292b12015-02-10 03:28:10 +00001646 // Check whether this is actually newer than OldD. We want to keep the
1647 // newer declaration. This loop will usually only iterate once, because
1648 // OldD is usually the previous declaration.
1649 for (auto D : redecls()) {
1650 if (D == OldD)
1651 break;
1652
1653 // If we reach the canonical declaration, then OldD is not actually older
1654 // than this one.
1655 //
1656 // FIXME: In this case, we should not add this decl to the lookup table.
1657 if (D->isCanonicalDecl())
1658 return false;
1659 }
Richard Smith5cd86f82015-11-03 03:13:11 +00001660
1661 // It's a newer declaration of the same kind of declaration in the same
1662 // scope: we want this decl instead of the existing one.
1663 return true;
Richard Smithe8292b12015-02-10 03:28:10 +00001664 }
1665
Richard Smith5cd86f82015-11-03 03:13:11 +00001666 // In all other cases, we need to keep both declarations in case they have
1667 // different visibility. Any attempt to use the name will result in an
1668 // ambiguity if more than one is visible.
1669 return false;
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001670}
1671
Douglas Gregoreddf4332009-02-24 20:03:32 +00001672bool NamedDecl::hasLinkage() const {
Rafael Espindola50df3a02013-05-25 17:16:20 +00001673 return getFormalLinkage() != NoLinkage;
Douglas Gregoreddf4332009-02-24 20:03:32 +00001674}
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001675
Daniel Dunbar166ea9ad2012-03-08 18:20:41 +00001676NamedDecl *NamedDecl::getUnderlyingDeclImpl() {
Anders Carlsson6915bf62009-06-26 06:29:23 +00001677 NamedDecl *ND = this;
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001678 while (auto *UD = dyn_cast<UsingShadowDecl>(ND))
Benjamin Kramerba0495a2012-03-08 21:00:45 +00001679 ND = UD->getTargetDecl();
1680
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001681 if (auto *AD = dyn_cast<ObjCCompatibleAliasDecl>(ND))
Benjamin Kramerba0495a2012-03-08 21:00:45 +00001682 return AD->getClassInterface();
1683
Richard Smithf2005d32015-12-29 23:34:32 +00001684 if (auto *AD = dyn_cast<NamespaceAliasDecl>(ND))
1685 return AD->getNamespace();
1686
Benjamin Kramerba0495a2012-03-08 21:00:45 +00001687 return ND;
Anders Carlsson6915bf62009-06-26 06:29:23 +00001688}
1689
John McCalla8ae2222010-04-06 21:38:20 +00001690bool NamedDecl::isCXXInstanceMember() const {
Douglas Gregor3f28ec22012-03-08 02:08:05 +00001691 if (!isCXXClassMember())
1692 return false;
1693
John McCalla8ae2222010-04-06 21:38:20 +00001694 const NamedDecl *D = this;
1695 if (isa<UsingShadowDecl>(D))
1696 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1697
John McCall5e77d762013-04-16 07:28:30 +00001698 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D) || isa<MSPropertyDecl>(D))
John McCalla8ae2222010-04-06 21:38:20 +00001699 return true;
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001700 if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()))
Alp Tokera2794f92014-01-22 07:29:52 +00001701 return MD->isInstance();
John McCalla8ae2222010-04-06 21:38:20 +00001702 return false;
1703}
1704
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +00001705//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001706// DeclaratorDecl Implementation
1707//===----------------------------------------------------------------------===//
1708
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001709template <typename DeclT>
1710static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) {
1711 if (decl->getNumTemplateParameterLists() > 0)
1712 return decl->getTemplateParameterList(0)->getTemplateLoc();
1713 else
1714 return decl->getInnerLocStart();
1715}
1716
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001717SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const {
John McCallf7bcc812010-05-28 23:32:21 +00001718 TypeSourceInfo *TSI = getTypeSourceInfo();
1719 if (TSI) return TSI->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001720 return SourceLocation();
1721}
1722
Douglas Gregor14454802011-02-25 02:25:35 +00001723void DeclaratorDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
1724 if (QualifierLoc) {
John McCall3e11ebe2010-03-15 10:12:16 +00001725 // Make sure the extended decl info is allocated.
1726 if (!hasExtInfo()) {
1727 // Save (non-extended) type source info pointer.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001728 auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
John McCall3e11ebe2010-03-15 10:12:16 +00001729 // Allocate external info struct.
1730 DeclInfo = new (getASTContext()) ExtInfo;
1731 // Restore savedTInfo into (extended) decl info.
1732 getExtInfo()->TInfo = savedTInfo;
1733 }
1734 // Set qualifier info.
Douglas Gregor14454802011-02-25 02:25:35 +00001735 getExtInfo()->QualifierLoc = QualifierLoc;
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001736 } else {
John McCall3e11ebe2010-03-15 10:12:16 +00001737 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
John McCall3e11ebe2010-03-15 10:12:16 +00001738 if (hasExtInfo()) {
Abramo Bagnara60804e12011-03-18 15:16:37 +00001739 if (getExtInfo()->NumTemplParamLists == 0) {
1740 // Save type source info pointer.
1741 TypeSourceInfo *savedTInfo = getExtInfo()->TInfo;
1742 // Deallocate the extended decl info.
1743 getASTContext().Deallocate(getExtInfo());
1744 // Restore savedTInfo into (non-extended) decl info.
1745 DeclInfo = savedTInfo;
1746 }
1747 else
1748 getExtInfo()->QualifierLoc = QualifierLoc;
John McCall3e11ebe2010-03-15 10:12:16 +00001749 }
1750 }
1751}
1752
Benjamin Kramer9cc210652015-08-05 09:40:49 +00001753void DeclaratorDecl::setTemplateParameterListsInfo(
1754 ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
1755 assert(!TPLists.empty());
Abramo Bagnara60804e12011-03-18 15:16:37 +00001756 // Make sure the extended decl info is allocated.
1757 if (!hasExtInfo()) {
1758 // Save (non-extended) type source info pointer.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001759 auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
Abramo Bagnara60804e12011-03-18 15:16:37 +00001760 // Allocate external info struct.
1761 DeclInfo = new (getASTContext()) ExtInfo;
1762 // Restore savedTInfo into (extended) decl info.
1763 getExtInfo()->TInfo = savedTInfo;
1764 }
1765 // Set the template parameter lists info.
Benjamin Kramer9cc210652015-08-05 09:40:49 +00001766 getExtInfo()->setTemplateParameterListsInfo(Context, TPLists);
Abramo Bagnara60804e12011-03-18 15:16:37 +00001767}
1768
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001769SourceLocation DeclaratorDecl::getOuterLocStart() const {
1770 return getTemplateOrInnerLocStart(this);
1771}
1772
Abramo Bagnaraea947882011-03-08 16:41:52 +00001773// Helper function: returns true if QT is or contains a type
1774// having a postfix component.
Eugene Zelenkode0215c2017-11-13 23:01:27 +00001775static bool typeIsPostfix(QualType QT) {
Abramo Bagnaraea947882011-03-08 16:41:52 +00001776 while (true) {
1777 const Type* T = QT.getTypePtr();
1778 switch (T->getTypeClass()) {
1779 default:
1780 return false;
1781 case Type::Pointer:
1782 QT = cast<PointerType>(T)->getPointeeType();
1783 break;
1784 case Type::BlockPointer:
1785 QT = cast<BlockPointerType>(T)->getPointeeType();
1786 break;
1787 case Type::MemberPointer:
1788 QT = cast<MemberPointerType>(T)->getPointeeType();
1789 break;
1790 case Type::LValueReference:
1791 case Type::RValueReference:
1792 QT = cast<ReferenceType>(T)->getPointeeType();
1793 break;
1794 case Type::PackExpansion:
1795 QT = cast<PackExpansionType>(T)->getPattern();
1796 break;
1797 case Type::Paren:
1798 case Type::ConstantArray:
1799 case Type::DependentSizedArray:
1800 case Type::IncompleteArray:
1801 case Type::VariableArray:
1802 case Type::FunctionProto:
1803 case Type::FunctionNoProto:
1804 return true;
1805 }
1806 }
1807}
1808
Abramo Bagnaraea947882011-03-08 16:41:52 +00001809SourceRange DeclaratorDecl::getSourceRange() const {
1810 SourceLocation RangeEnd = getLocation();
1811 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
Benjamin Kramer3a7cc812014-02-02 15:28:46 +00001812 // If the declaration has no name or the type extends past the name take the
1813 // end location of the type.
1814 if (!getDeclName() || typeIsPostfix(TInfo->getType()))
Abramo Bagnaraea947882011-03-08 16:41:52 +00001815 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
1816 }
1817 return SourceRange(getOuterLocStart(), RangeEnd);
1818}
1819
Benjamin Kramer9cc210652015-08-05 09:40:49 +00001820void QualifierInfo::setTemplateParameterListsInfo(
1821 ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001822 // Free previous template parameters (if any).
1823 if (NumTemplParamLists > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00001824 Context.Deallocate(TemplParamLists);
Craig Topper36250ad2014-05-12 05:36:57 +00001825 TemplParamLists = nullptr;
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001826 NumTemplParamLists = 0;
1827 }
1828 // Set info on matched template parameter lists (if any).
Benjamin Kramer9cc210652015-08-05 09:40:49 +00001829 if (!TPLists.empty()) {
1830 TemplParamLists = new (Context) TemplateParameterList *[TPLists.size()];
1831 NumTemplParamLists = TPLists.size();
1832 std::copy(TPLists.begin(), TPLists.end(), TemplParamLists);
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001833 }
1834}
1835
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001836//===----------------------------------------------------------------------===//
Nuno Lopes394ec982008-12-17 23:39:55 +00001837// VarDecl Implementation
1838//===----------------------------------------------------------------------===//
1839
Sebastian Redl833ef452010-01-26 22:01:41 +00001840const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) {
1841 switch (SC) {
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00001842 case SC_None: break;
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00001843 case SC_Auto: return "auto";
1844 case SC_Extern: return "extern";
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00001845 case SC_PrivateExtern: return "__private_extern__";
1846 case SC_Register: return "register";
1847 case SC_Static: return "static";
Sebastian Redl833ef452010-01-26 22:01:41 +00001848 }
1849
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00001850 llvm_unreachable("Invalid storage class");
Sebastian Redl833ef452010-01-26 22:01:41 +00001851}
1852
Richard Smith053f6c62014-05-16 23:01:30 +00001853VarDecl::VarDecl(Kind DK, ASTContext &C, DeclContext *DC,
1854 SourceLocation StartLoc, SourceLocation IdLoc,
1855 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
1856 StorageClass SC)
1857 : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc),
Eugene Zelenkode0215c2017-11-13 23:01:27 +00001858 redeclarable_base(C) {
Benjamin Kramera939c232014-03-15 18:54:13 +00001859 static_assert(sizeof(VarDeclBitfields) <= sizeof(unsigned),
1860 "VarDeclBitfields too large!");
1861 static_assert(sizeof(ParmVarDeclBitfields) <= sizeof(unsigned),
1862 "ParmVarDeclBitfields too large!");
David Majnemerfa7bc782015-05-19 00:57:16 +00001863 static_assert(sizeof(NonParmVarDeclBitfields) <= sizeof(unsigned),
1864 "NonParmVarDeclBitfields too large!");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001865 AllBits = 0;
1866 VarDeclBits.SClass = SC;
1867 // Everything else is implicitly initialized to false.
1868}
1869
Abramo Bagnaradff19302011-03-08 08:55:46 +00001870VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC,
1871 SourceLocation StartL, SourceLocation IdL,
John McCallbcd03502009-12-07 02:54:59 +00001872 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001873 StorageClass S) {
Richard Smith053f6c62014-05-16 23:01:30 +00001874 return new (C, DC) VarDecl(Var, C, DC, StartL, IdL, Id, T, TInfo, S);
Nuno Lopes394ec982008-12-17 23:39:55 +00001875}
1876
Douglas Gregor72172e92012-01-05 21:55:30 +00001877VarDecl *VarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00001878 return new (C, ID)
1879 VarDecl(Var, C, nullptr, SourceLocation(), SourceLocation(), nullptr,
1880 QualType(), nullptr, SC_None);
Douglas Gregor72172e92012-01-05 21:55:30 +00001881}
1882
Douglas Gregorbf62d642010-12-06 18:36:25 +00001883void VarDecl::setStorageClass(StorageClass SC) {
1884 assert(isLegalForVariable(SC));
John McCallbeaa11c2011-05-01 02:13:58 +00001885 VarDeclBits.SClass = SC;
Douglas Gregorbf62d642010-12-06 18:36:25 +00001886}
1887
Reid Kleckner7d6d2702014-05-01 03:16:47 +00001888VarDecl::TLSKind VarDecl::getTLSKind() const {
1889 switch (VarDeclBits.TSCSpec) {
1890 case TSCS_unspecified:
Samuel Antaof8b50122015-07-13 22:54:53 +00001891 if (!hasAttr<ThreadAttr>() &&
1892 !(getASTContext().getLangOpts().OpenMPUseTLS &&
1893 getASTContext().getTargetInfo().isTLSSupported() &&
1894 hasAttr<OMPThreadPrivateDeclAttr>()))
David Majnemer1b5baff2015-05-14 05:19:23 +00001895 return TLS_None;
Samuel Antaof8b50122015-07-13 22:54:53 +00001896 return ((getASTContext().getLangOpts().isCompatibleWithMSVC(
1897 LangOptions::MSVC2015)) ||
1898 hasAttr<OMPThreadPrivateDeclAttr>())
David Majnemer1b5baff2015-05-14 05:19:23 +00001899 ? TLS_Dynamic
1900 : TLS_Static;
Reid Kleckner7d6d2702014-05-01 03:16:47 +00001901 case TSCS___thread: // Fall through.
1902 case TSCS__Thread_local:
Samuel Antaof8b50122015-07-13 22:54:53 +00001903 return TLS_Static;
Reid Kleckner7d6d2702014-05-01 03:16:47 +00001904 case TSCS_thread_local:
1905 return TLS_Dynamic;
1906 }
1907 llvm_unreachable("Unknown thread storage class specifier!");
1908}
1909
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001910SourceRange VarDecl::getSourceRange() const {
Argyrios Kyrtzidise0d64972012-10-08 23:08:41 +00001911 if (const Expr *Init = getInit()) {
1912 SourceLocation InitEnd = Init->getLocEnd();
Nico Weberbbe13942013-01-22 17:00:09 +00001913 // If Init is implicit, ignore its source range and fallback on
1914 // DeclaratorDecl::getSourceRange() to handle postfix elements.
1915 if (InitEnd.isValid() && InitEnd != getLocation())
Argyrios Kyrtzidise0d64972012-10-08 23:08:41 +00001916 return SourceRange(getOuterLocStart(), InitEnd);
1917 }
Abramo Bagnaraea947882011-03-08 16:41:52 +00001918 return DeclaratorDecl::getSourceRange();
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00001919}
1920
Rafael Espindola88510672013-01-04 21:18:45 +00001921template<typename T>
Alp Toker84212df2014-05-31 06:11:02 +00001922static LanguageLinkage getDeclLanguageLinkage(const T &D) {
Rafael Espindola5bda63f2013-02-14 01:47:04 +00001923 // C++ [dcl.link]p1: All function types, function names with external linkage,
1924 // and variable names with external linkage have a language linkage.
Rafael Espindola3ae00052013-05-13 00:12:11 +00001925 if (!D.hasExternalFormalLinkage())
Rafael Espindola5bda63f2013-02-14 01:47:04 +00001926 return NoLanguageLinkage;
1927
1928 // Language linkage is a C++ concept, but saying that everything else in C has
Rafael Espindola66748e92013-01-04 20:41:40 +00001929 // C language linkage fits the implementation nicely.
Rafael Espindola576127d2012-12-28 14:21:58 +00001930 ASTContext &Context = D.getASTContext();
1931 if (!Context.getLangOpts().CPlusPlus)
Rafael Espindolaf4187652013-02-14 01:18:37 +00001932 return CLanguageLinkage;
1933
Rafael Espindola5bda63f2013-02-14 01:47:04 +00001934 // C++ [dcl.link]p4: A C language linkage is ignored in determining the
1935 // language linkage of the names of class members and the function type of
1936 // class member functions.
Rafael Espindola576127d2012-12-28 14:21:58 +00001937 const DeclContext *DC = D.getDeclContext();
1938 if (DC->isRecord())
Rafael Espindolaf4187652013-02-14 01:18:37 +00001939 return CXXLanguageLinkage;
Rafael Espindola576127d2012-12-28 14:21:58 +00001940
1941 // If the first decl is in an extern "C" context, any other redeclaration
1942 // will have C language linkage. If the first one is not in an extern "C"
1943 // context, we would have reported an error for any other decl being in one.
Rafael Espindola593537a2013-05-05 20:15:21 +00001944 if (isFirstInExternCContext(&D))
Rafael Espindolaf4187652013-02-14 01:18:37 +00001945 return CLanguageLinkage;
1946 return CXXLanguageLinkage;
Rafael Espindola576127d2012-12-28 14:21:58 +00001947}
1948
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001949template<typename T>
Alp Toker84212df2014-05-31 06:11:02 +00001950static bool isDeclExternC(const T &D) {
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001951 // Since the context is ignored for class members, they can only have C++
1952 // language linkage or no language linkage.
1953 const DeclContext *DC = D.getDeclContext();
1954 if (DC->isRecord()) {
1955 assert(D.getASTContext().getLangOpts().CPlusPlus);
1956 return false;
1957 }
1958
1959 return D.getLanguageLinkage() == CLanguageLinkage;
1960}
1961
Rafael Espindolaf4187652013-02-14 01:18:37 +00001962LanguageLinkage VarDecl::getLanguageLinkage() const {
Alp Toker84212df2014-05-31 06:11:02 +00001963 return getDeclLanguageLinkage(*this);
Rafael Espindola576127d2012-12-28 14:21:58 +00001964}
1965
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001966bool VarDecl::isExternC() const {
Alp Toker84212df2014-05-31 06:11:02 +00001967 return isDeclExternC(*this);
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001968}
1969
Rafael Espindola593537a2013-05-05 20:15:21 +00001970bool VarDecl::isInExternCContext() const {
Serge Pavlov3cb80222013-11-14 02:13:03 +00001971 return getLexicalDeclContext()->isExternCContext();
Rafael Espindola593537a2013-05-05 20:15:21 +00001972}
1973
1974bool VarDecl::isInExternCXXContext() const {
Serge Pavlov3cb80222013-11-14 02:13:03 +00001975 return getLexicalDeclContext()->isExternCXXContext();
Rafael Espindola593537a2013-05-05 20:15:21 +00001976}
1977
Rafael Espindola8db352d2013-10-17 15:37:26 +00001978VarDecl *VarDecl::getCanonicalDecl() { return getFirstDecl(); }
Sebastian Redl833ef452010-01-26 22:01:41 +00001979
Nico Weber7f5015a2015-04-15 21:53:00 +00001980VarDecl::DefinitionKind
1981VarDecl::isThisDeclarationADefinition(ASTContext &C) const {
Richard Smitha22d9a52017-12-02 00:55:48 +00001982 if (isThisDeclarationADemotedDefinition())
1983 return DeclarationOnly;
1984
Sebastian Redl35351a92010-01-31 22:27:38 +00001985 // C++ [basic.def]p2:
1986 // A declaration is a definition unless [...] it contains the 'extern'
1987 // specifier or a linkage-specification and neither an initializer [...],
Richard Smith62f19e72016-06-25 00:15:56 +00001988 // it declares a non-inline static data member in a class declaration [...],
1989 // it declares a static data member outside a class definition and the variable
1990 // was defined within the class with the constexpr specifier [...],
Richard Smith8809a0c2013-09-27 20:14:12 +00001991 // C++1y [temp.expl.spec]p15:
1992 // An explicit specialization of a static data member or an explicit
1993 // specialization of a static data member template is a definition if the
1994 // declaration includes an initializer; otherwise, it is a declaration.
1995 //
1996 // FIXME: How do you declare (but not define) a partial specialization of
1997 // a static data member template outside the containing class?
Sebastian Redl35351a92010-01-31 22:27:38 +00001998 if (isStaticDataMember()) {
Richard Smith8809a0c2013-09-27 20:14:12 +00001999 if (isOutOfLine() &&
Richard Smith62f19e72016-06-25 00:15:56 +00002000 !(getCanonicalDecl()->isInline() &&
2001 getCanonicalDecl()->isConstexpr()) &&
Richard Smith8809a0c2013-09-27 20:14:12 +00002002 (hasInit() ||
2003 // If the first declaration is out-of-line, this may be an
2004 // instantiation of an out-of-line partial specialization of a variable
2005 // template for which we have not yet instantiated the initializer.
Rafael Espindola8db352d2013-10-17 15:37:26 +00002006 (getFirstDecl()->isOutOfLine()
Richard Smith8809a0c2013-09-27 20:14:12 +00002007 ? getTemplateSpecializationKind() == TSK_Undeclared
2008 : getTemplateSpecializationKind() !=
2009 TSK_ExplicitSpecialization) ||
2010 isa<VarTemplatePartialSpecializationDecl>(this)))
Sebastian Redl35351a92010-01-31 22:27:38 +00002011 return Definition;
Richard Smith62f19e72016-06-25 00:15:56 +00002012 else if (!isOutOfLine() && isInline())
2013 return Definition;
Sebastian Redl35351a92010-01-31 22:27:38 +00002014 else
2015 return DeclarationOnly;
2016 }
2017 // C99 6.7p5:
2018 // A definition of an identifier is a declaration for that identifier that
2019 // [...] causes storage to be reserved for that object.
2020 // Note: that applies for all non-file-scope objects.
2021 // C99 6.9.2p1:
2022 // If the declaration of an identifier for an object has file scope and an
2023 // initializer, the declaration is an external definition for the identifier
2024 if (hasInit())
2025 return Definition;
Rafael Espindolabff59562013-04-25 12:11:36 +00002026
Dmitry Polukhin85eda122016-04-11 07:48:59 +00002027 if (hasDefiningAttr())
Rafael Espindolad53ffa02013-10-22 21:39:03 +00002028 return Definition;
2029
David Majnemerdd0bed12015-05-14 05:19:20 +00002030 if (const auto *SAA = getAttr<SelectAnyAttr>())
2031 if (!SAA->isInherited())
2032 return Definition;
2033
Richard Smith8809a0c2013-09-27 20:14:12 +00002034 // A variable template specialization (other than a static data member
2035 // template or an explicit specialization) is a declaration until we
2036 // instantiate its initializer.
Richard Smith435e6472017-12-02 02:48:42 +00002037 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(this)) {
2038 if (VTSD->getTemplateSpecializationKind() != TSK_ExplicitSpecialization &&
2039 !isa<VarTemplatePartialSpecializationDecl>(VTSD) &&
2040 !VTSD->IsCompleteDefinition)
2041 return DeclarationOnly;
2042 }
Richard Smith8809a0c2013-09-27 20:14:12 +00002043
Nico Weber608e7682015-04-15 23:04:24 +00002044 if (hasExternalStorage())
Sebastian Redl35351a92010-01-31 22:27:38 +00002045 return DeclarationOnly;
Rafael Espindola8f326a52013-03-07 01:42:44 +00002046
Rafael Espindolabff59562013-04-25 12:11:36 +00002047 // [dcl.link] p7:
2048 // A declaration directly contained in a linkage-specification is treated
2049 // as if it contains the extern specifier for the purpose of determining
2050 // the linkage of the declared name and whether it is a definition.
Nico Weber608e7682015-04-15 23:04:24 +00002051 if (isSingleLineLanguageLinkage(*this))
Rafael Espindola327be3c2013-04-26 01:30:23 +00002052 return DeclarationOnly;
Rafael Espindolabff59562013-04-25 12:11:36 +00002053
Sebastian Redl35351a92010-01-31 22:27:38 +00002054 // C99 6.9.2p2:
2055 // A declaration of an object that has file scope without an initializer,
2056 // and without a storage class specifier or the scs 'static', constitutes
2057 // a tentative definition.
2058 // No such thing in C++.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002059 if (!C.getLangOpts().CPlusPlus && isFileVarDecl())
Sebastian Redl35351a92010-01-31 22:27:38 +00002060 return TentativeDefinition;
2061
2062 // What's left is (in C, block-scope) declarations without initializers or
2063 // external storage. These are definitions.
2064 return Definition;
2065}
2066
Sebastian Redl35351a92010-01-31 22:27:38 +00002067VarDecl *VarDecl::getActingDefinition() {
2068 DefinitionKind Kind = isThisDeclarationADefinition();
2069 if (Kind != TentativeDefinition)
Craig Topper36250ad2014-05-12 05:36:57 +00002070 return nullptr;
Sebastian Redl35351a92010-01-31 22:27:38 +00002071
Craig Topper36250ad2014-05-12 05:36:57 +00002072 VarDecl *LastTentative = nullptr;
Rafael Espindola8db352d2013-10-17 15:37:26 +00002073 VarDecl *First = getFirstDecl();
Aaron Ballman86c93902014-03-06 23:45:36 +00002074 for (auto I : First->redecls()) {
2075 Kind = I->isThisDeclarationADefinition();
Sebastian Redl35351a92010-01-31 22:27:38 +00002076 if (Kind == Definition)
Craig Topper36250ad2014-05-12 05:36:57 +00002077 return nullptr;
Sebastian Redl35351a92010-01-31 22:27:38 +00002078 else if (Kind == TentativeDefinition)
Aaron Ballman86c93902014-03-06 23:45:36 +00002079 LastTentative = I;
Sebastian Redl35351a92010-01-31 22:27:38 +00002080 }
2081 return LastTentative;
2082}
2083
Daniel Dunbar9d355812012-03-09 01:51:51 +00002084VarDecl *VarDecl::getDefinition(ASTContext &C) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00002085 VarDecl *First = getFirstDecl();
Aaron Ballman86c93902014-03-06 23:45:36 +00002086 for (auto I : First->redecls()) {
2087 if (I->isThisDeclarationADefinition(C) == Definition)
2088 return I;
Sebastian Redl5ca79842010-02-01 20:16:42 +00002089 }
Craig Topper36250ad2014-05-12 05:36:57 +00002090 return nullptr;
Sebastian Redl5ca79842010-02-01 20:16:42 +00002091}
2092
Daniel Dunbar9d355812012-03-09 01:51:51 +00002093VarDecl::DefinitionKind VarDecl::hasDefinition(ASTContext &C) const {
John McCall37bb6c92010-10-29 22:22:43 +00002094 DefinitionKind Kind = DeclarationOnly;
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002095
Rafael Espindola8db352d2013-10-17 15:37:26 +00002096 const VarDecl *First = getFirstDecl();
Aaron Ballman86c93902014-03-06 23:45:36 +00002097 for (auto I : First->redecls()) {
2098 Kind = std::max(Kind, I->isThisDeclarationADefinition(C));
Daniel Dunbar082c62d2012-03-06 23:52:46 +00002099 if (Kind == Definition)
2100 break;
2101 }
John McCall37bb6c92010-10-29 22:22:43 +00002102
2103 return Kind;
2104}
2105
Sebastian Redl5ca79842010-02-01 20:16:42 +00002106const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const {
Aaron Ballman86c93902014-03-06 23:45:36 +00002107 for (auto I : redecls()) {
2108 if (auto Expr = I->getInit()) {
2109 D = I;
2110 return Expr;
2111 }
Sebastian Redl833ef452010-01-26 22:01:41 +00002112 }
Craig Topper36250ad2014-05-12 05:36:57 +00002113 return nullptr;
Sebastian Redl833ef452010-01-26 22:01:41 +00002114}
2115
Chandler Carruth813faed2015-12-30 02:51:00 +00002116bool VarDecl::hasInit() const {
2117 if (auto *P = dyn_cast<ParmVarDecl>(this))
2118 if (P->hasUnparsedDefaultArg() || P->hasUninstantiatedDefaultArg())
2119 return false;
2120
2121 return !Init.isNull();
2122}
2123
2124Expr *VarDecl::getInit() {
2125 if (!hasInit())
2126 return nullptr;
2127
2128 if (auto *S = Init.dyn_cast<Stmt *>())
2129 return cast<Expr>(S);
2130
2131 return cast_or_null<Expr>(Init.get<EvaluatedStmt *>()->Value);
2132}
2133
2134Stmt **VarDecl::getInitAddress() {
2135 if (auto *ES = Init.dyn_cast<EvaluatedStmt *>())
2136 return &ES->Value;
2137
2138 return Init.getAddrOfPtr1();
2139}
2140
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002141bool VarDecl::isOutOfLine() const {
Douglas Gregorb11aad82011-02-19 18:51:44 +00002142 if (Decl::isOutOfLine())
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002143 return true;
Chandler Carruthf50ef6e2010-02-21 07:08:09 +00002144
2145 if (!isStaticDataMember())
2146 return false;
2147
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002148 // If this static data member was instantiated from a static data member of
2149 // a class template, check whether that static data member was defined
2150 // out-of-line.
2151 if (VarDecl *VD = getInstantiatedFromStaticDataMember())
2152 return VD->isOutOfLine();
2153
2154 return false;
2155}
2156
Douglas Gregord5058122010-02-11 01:19:42 +00002157void VarDecl::setInit(Expr *I) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002158 if (auto *Eval = Init.dyn_cast<EvaluatedStmt *>()) {
Sebastian Redl833ef452010-01-26 22:01:41 +00002159 Eval->~EvaluatedStmt();
Douglas Gregord5058122010-02-11 01:19:42 +00002160 getASTContext().Deallocate(Eval);
Sebastian Redl833ef452010-01-26 22:01:41 +00002161 }
2162
2163 Init = I;
2164}
2165
Daniel Dunbar9d355812012-03-09 01:51:51 +00002166bool VarDecl::isUsableInConstantExpressions(ASTContext &C) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002167 const LangOptions &Lang = C.getLangOpts();
Richard Smith242ad892011-12-21 02:55:12 +00002168
Richard Smith35ecb362012-03-02 04:14:40 +00002169 if (!Lang.CPlusPlus)
2170 return false;
2171
2172 // In C++11, any variable of reference type can be used in a constant
2173 // expression if it is initialized by a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002174 if (Lang.CPlusPlus11 && getType()->isReferenceType())
Richard Smith35ecb362012-03-02 04:14:40 +00002175 return true;
2176
2177 // Only const objects can be used in constant expressions in C++. C++98 does
Richard Smith242ad892011-12-21 02:55:12 +00002178 // not require the variable to be non-volatile, but we consider this to be a
2179 // defect.
Richard Smith35ecb362012-03-02 04:14:40 +00002180 if (!getType().isConstQualified() || getType().isVolatileQualified())
Richard Smith242ad892011-12-21 02:55:12 +00002181 return false;
2182
2183 // In C++, const, non-volatile variables of integral or enumeration types
2184 // can be used in constant expressions.
2185 if (getType()->isIntegralOrEnumerationType())
2186 return true;
2187
Richard Smith35ecb362012-03-02 04:14:40 +00002188 // Additionally, in C++11, non-volatile constexpr variables can be used in
2189 // constant expressions.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002190 return Lang.CPlusPlus11 && isConstexpr();
Richard Smith242ad892011-12-21 02:55:12 +00002191}
2192
Richard Smithd0b4dd62011-12-19 06:19:21 +00002193/// Convert the initializer for this declaration to the elaborated EvaluatedStmt
2194/// form, which contains extra information on the evaluated value of the
2195/// initializer.
2196EvaluatedStmt *VarDecl::ensureEvaluatedStmt() const {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002197 auto *Eval = Init.dyn_cast<EvaluatedStmt *>();
Richard Smithd0b4dd62011-12-19 06:19:21 +00002198 if (!Eval) {
Manuel Klimeka7328992013-06-03 13:51:33 +00002199 // Note: EvaluatedStmt contains an APValue, which usually holds
2200 // resources not allocated from the ASTContext. We need to do some
2201 // work to avoid leaking those, but we do so in VarDecl::evaluateValue
2202 // where we can detect whether there's anything to clean up or not.
Richard Smithd0b4dd62011-12-19 06:19:21 +00002203 Eval = new (getASTContext()) EvaluatedStmt;
Chandler Carruth813faed2015-12-30 02:51:00 +00002204 Eval->Value = Init.get<Stmt *>();
Richard Smithd0b4dd62011-12-19 06:19:21 +00002205 Init = Eval;
2206 }
2207 return Eval;
2208}
2209
Richard Smithdafff942012-01-14 04:30:29 +00002210APValue *VarDecl::evaluateValue() const {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002211 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithdafff942012-01-14 04:30:29 +00002212 return evaluateValue(Notes);
2213}
2214
2215APValue *VarDecl::evaluateValue(
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002216 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithd0b4dd62011-12-19 06:19:21 +00002217 EvaluatedStmt *Eval = ensureEvaluatedStmt();
2218
2219 // We only produce notes indicating why an initializer is non-constant the
2220 // first time it is evaluated. FIXME: The notes won't always be emitted the
2221 // first time we try evaluation, so might not be produced at all.
2222 if (Eval->WasEvaluated)
Craig Topper36250ad2014-05-12 05:36:57 +00002223 return Eval->Evaluated.isUninit() ? nullptr : &Eval->Evaluated;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002224
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002225 const auto *Init = cast<Expr>(Eval->Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002226 assert(!Init->isValueDependent());
2227
2228 if (Eval->IsEvaluating) {
2229 // FIXME: Produce a diagnostic for self-initialization.
2230 Eval->CheckedICE = true;
2231 Eval->IsICE = false;
Craig Topper36250ad2014-05-12 05:36:57 +00002232 return nullptr;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002233 }
2234
2235 Eval->IsEvaluating = true;
2236
2237 bool Result = Init->EvaluateAsInitializer(Eval->Evaluated, getASTContext(),
2238 this, Notes);
2239
Manuel Klimeka7328992013-06-03 13:51:33 +00002240 // Ensure the computed APValue is cleaned up later if evaluation succeeded,
2241 // or that it's empty (so that there's nothing to clean up) if evaluation
2242 // failed.
Richard Smithd0b4dd62011-12-19 06:19:21 +00002243 if (!Result)
2244 Eval->Evaluated = APValue();
Manuel Klimeka7328992013-06-03 13:51:33 +00002245 else if (Eval->Evaluated.needsCleanup())
George Burgess IVb61bfbd2017-02-14 05:37:36 +00002246 getASTContext().addDestruction(&Eval->Evaluated);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002247
2248 Eval->IsEvaluating = false;
2249 Eval->WasEvaluated = true;
2250
2251 // In C++11, we have determined whether the initializer was a constant
2252 // expression as a side-effect.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002253 if (getASTContext().getLangOpts().CPlusPlus11 && !Eval->CheckedICE) {
Richard Smithd0b4dd62011-12-19 06:19:21 +00002254 Eval->CheckedICE = true;
Eli Friedman8f66cdf2012-02-06 21:50:18 +00002255 Eval->IsICE = Result && Notes.empty();
Richard Smithd0b4dd62011-12-19 06:19:21 +00002256 }
2257
Craig Topper36250ad2014-05-12 05:36:57 +00002258 return Result ? &Eval->Evaluated : nullptr;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002259}
2260
Chandler Carruth813faed2015-12-30 02:51:00 +00002261APValue *VarDecl::getEvaluatedValue() const {
2262 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
2263 if (Eval->WasEvaluated)
2264 return &Eval->Evaluated;
2265
2266 return nullptr;
2267}
2268
2269bool VarDecl::isInitKnownICE() const {
2270 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
2271 return Eval->CheckedICE;
2272
2273 return false;
2274}
2275
2276bool VarDecl::isInitICE() const {
2277 assert(isInitKnownICE() &&
2278 "Check whether we already know that the initializer is an ICE");
2279 return Init.get<EvaluatedStmt *>()->IsICE;
2280}
2281
Richard Smithd0b4dd62011-12-19 06:19:21 +00002282bool VarDecl::checkInitIsICE() const {
John McCalla59dc2f2012-01-05 00:13:19 +00002283 // Initializers of weak variables are never ICEs.
2284 if (isWeak())
2285 return false;
2286
Richard Smithd0b4dd62011-12-19 06:19:21 +00002287 EvaluatedStmt *Eval = ensureEvaluatedStmt();
2288 if (Eval->CheckedICE)
2289 // We have already checked whether this subexpression is an
2290 // integral constant expression.
2291 return Eval->IsICE;
2292
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002293 const auto *Init = cast<Expr>(Eval->Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002294 assert(!Init->isValueDependent());
2295
2296 // In C++11, evaluate the initializer to check whether it's a constant
2297 // expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002298 if (getASTContext().getLangOpts().CPlusPlus11) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002299 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002300 evaluateValue(Notes);
2301 return Eval->IsICE;
2302 }
2303
2304 // It's an ICE whether or not the definition we found is
2305 // out-of-line. See DR 721 and the discussion in Clang PR
2306 // 6206 for details.
2307
2308 if (Eval->CheckingICE)
2309 return false;
2310 Eval->CheckingICE = true;
2311
2312 Eval->IsICE = Init->isIntegerConstantExpr(getASTContext());
2313 Eval->CheckingICE = false;
2314 Eval->CheckedICE = true;
2315 return Eval->IsICE;
2316}
2317
Richard Smith2195ec92017-04-21 01:15:13 +00002318template<typename DeclT>
2319static DeclT *getDefinitionOrSelf(DeclT *D) {
2320 assert(D);
2321 if (auto *Def = D->getDefinition())
2322 return Def;
2323 return D;
2324}
2325
Richard Smithedbc6e92016-10-14 21:41:24 +00002326VarDecl *VarDecl::getTemplateInstantiationPattern() const {
2327 // If it's a variable template specialization, find the template or partial
2328 // specialization from which it was instantiated.
2329 if (auto *VDTemplSpec = dyn_cast<VarTemplateSpecializationDecl>(this)) {
2330 auto From = VDTemplSpec->getInstantiatedFrom();
2331 if (auto *VTD = From.dyn_cast<VarTemplateDecl *>()) {
2332 while (auto *NewVTD = VTD->getInstantiatedFromMemberTemplate()) {
2333 if (NewVTD->isMemberSpecialization())
2334 break;
2335 VTD = NewVTD;
2336 }
Richard Smith2195ec92017-04-21 01:15:13 +00002337 return getDefinitionOrSelf(VTD->getTemplatedDecl());
Richard Smithedbc6e92016-10-14 21:41:24 +00002338 }
2339 if (auto *VTPSD =
2340 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
2341 while (auto *NewVTPSD = VTPSD->getInstantiatedFromMember()) {
2342 if (NewVTPSD->isMemberSpecialization())
2343 break;
2344 VTPSD = NewVTPSD;
2345 }
Richard Smith2195ec92017-04-21 01:15:13 +00002346 return getDefinitionOrSelf<VarDecl>(VTPSD);
Richard Smithedbc6e92016-10-14 21:41:24 +00002347 }
2348 }
2349
2350 if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) {
2351 if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) {
2352 VarDecl *VD = getInstantiatedFromStaticDataMember();
2353 while (auto *NewVD = VD->getInstantiatedFromStaticDataMember())
2354 VD = NewVD;
Richard Smith2195ec92017-04-21 01:15:13 +00002355 return getDefinitionOrSelf(VD);
Richard Smithedbc6e92016-10-14 21:41:24 +00002356 }
2357 }
2358
2359 if (VarTemplateDecl *VarTemplate = getDescribedVarTemplate()) {
Richard Smithedbc6e92016-10-14 21:41:24 +00002360 while (VarTemplate->getInstantiatedFromMemberTemplate()) {
2361 if (VarTemplate->isMemberSpecialization())
2362 break;
2363 VarTemplate = VarTemplate->getInstantiatedFromMemberTemplate();
2364 }
2365
Richard Smith2195ec92017-04-21 01:15:13 +00002366 return getDefinitionOrSelf(VarTemplate->getTemplatedDecl());
Richard Smithedbc6e92016-10-14 21:41:24 +00002367 }
2368 return nullptr;
2369}
2370
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002371VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const {
Douglas Gregor06db9f52009-10-12 20:18:28 +00002372 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
Douglas Gregor86d142a2009-10-08 07:24:58 +00002373 return cast<VarDecl>(MSI->getInstantiatedFrom());
Craig Topper36250ad2014-05-12 05:36:57 +00002374
2375 return nullptr;
Douglas Gregor86d142a2009-10-08 07:24:58 +00002376}
2377
Douglas Gregor3c74d412009-10-14 20:14:33 +00002378TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002379 if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
Larisse Voufo39a1e502013-08-06 01:03:05 +00002380 return Spec->getSpecializationKind();
2381
Sebastian Redl35351a92010-01-31 22:27:38 +00002382 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
Douglas Gregor86d142a2009-10-08 07:24:58 +00002383 return MSI->getTemplateSpecializationKind();
Richard Smith8809a0c2013-09-27 20:14:12 +00002384
Douglas Gregor86d142a2009-10-08 07:24:58 +00002385 return TSK_Undeclared;
2386}
2387
Richard Smith8809a0c2013-09-27 20:14:12 +00002388SourceLocation VarDecl::getPointOfInstantiation() const {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002389 if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
Richard Smith8809a0c2013-09-27 20:14:12 +00002390 return Spec->getPointOfInstantiation();
2391
2392 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2393 return MSI->getPointOfInstantiation();
2394
2395 return SourceLocation();
2396}
2397
Larisse Voufo39a1e502013-08-06 01:03:05 +00002398VarTemplateDecl *VarDecl::getDescribedVarTemplate() const {
2399 return getASTContext().getTemplateOrSpecializationInfo(this)
2400 .dyn_cast<VarTemplateDecl *>();
2401}
2402
2403void VarDecl::setDescribedVarTemplate(VarTemplateDecl *Template) {
2404 getASTContext().setTemplateOrSpecializationInfo(this, Template);
2405}
2406
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002407MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const {
Richard Smithb71782b2013-08-01 04:12:04 +00002408 if (isStaticDataMember())
Larisse Voufo39a1e502013-08-06 01:03:05 +00002409 // FIXME: Remove ?
2410 // return getASTContext().getInstantiatedFromStaticDataMember(this);
2411 return getASTContext().getTemplateOrSpecializationInfo(this)
2412 .dyn_cast<MemberSpecializationInfo *>();
Craig Topper36250ad2014-05-12 05:36:57 +00002413 return nullptr;
Douglas Gregor06db9f52009-10-12 20:18:28 +00002414}
2415
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00002416void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2417 SourceLocation PointOfInstantiation) {
Richard Smith8809a0c2013-09-27 20:14:12 +00002418 assert((isa<VarTemplateSpecializationDecl>(this) ||
2419 getMemberSpecializationInfo()) &&
2420 "not a variable or static data member template specialization");
2421
Larisse Voufo39a1e502013-08-06 01:03:05 +00002422 if (VarTemplateSpecializationDecl *Spec =
2423 dyn_cast<VarTemplateSpecializationDecl>(this)) {
2424 Spec->setSpecializationKind(TSK);
2425 if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
Richard Smith891fc7f2017-12-05 01:31:47 +00002426 Spec->getPointOfInstantiation().isInvalid()) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00002427 Spec->setPointOfInstantiation(PointOfInstantiation);
Richard Smith891fc7f2017-12-05 01:31:47 +00002428 if (ASTMutationListener *L = getASTContext().getASTMutationListener())
2429 L->InstantiationRequested(this);
2430 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002431 }
2432
2433 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) {
2434 MSI->setTemplateSpecializationKind(TSK);
2435 if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
Richard Smith891fc7f2017-12-05 01:31:47 +00002436 MSI->getPointOfInstantiation().isInvalid()) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00002437 MSI->setPointOfInstantiation(PointOfInstantiation);
Richard Smith891fc7f2017-12-05 01:31:47 +00002438 if (ASTMutationListener *L = getASTContext().getASTMutationListener())
2439 L->InstantiationRequested(this);
2440 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002441 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002442}
2443
2444void
2445VarDecl::setInstantiationOfStaticDataMember(VarDecl *VD,
2446 TemplateSpecializationKind TSK) {
2447 assert(getASTContext().getTemplateOrSpecializationInfo(this).isNull() &&
2448 "Previous template or instantiation?");
2449 getASTContext().setInstantiatedFromStaticDataMember(this, VD, TSK);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00002450}
2451
Sebastian Redl833ef452010-01-26 22:01:41 +00002452//===----------------------------------------------------------------------===//
2453// ParmVarDecl Implementation
2454//===----------------------------------------------------------------------===//
Douglas Gregor0760fa12009-03-10 23:43:53 +00002455
Sebastian Redl833ef452010-01-26 22:01:41 +00002456ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00002457 SourceLocation StartLoc,
2458 SourceLocation IdLoc, IdentifierInfo *Id,
Sebastian Redl833ef452010-01-26 22:01:41 +00002459 QualType T, TypeSourceInfo *TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002460 StorageClass S, Expr *DefArg) {
Richard Smith053f6c62014-05-16 23:01:30 +00002461 return new (C, DC) ParmVarDecl(ParmVar, C, DC, StartLoc, IdLoc, Id, T, TInfo,
Richard Smithf7981722013-11-22 09:01:48 +00002462 S, DefArg);
Douglas Gregor0760fa12009-03-10 23:43:53 +00002463}
2464
Reid Kleckner8a365022013-06-24 17:51:48 +00002465QualType ParmVarDecl::getOriginalType() const {
2466 TypeSourceInfo *TSI = getTypeSourceInfo();
2467 QualType T = TSI ? TSI->getType() : getType();
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002468 if (const auto *DT = dyn_cast<DecayedType>(T))
Reid Kleckner8a365022013-06-24 17:51:48 +00002469 return DT->getOriginalType();
2470 return T;
2471}
2472
Douglas Gregor72172e92012-01-05 21:55:30 +00002473ParmVarDecl *ParmVarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00002474 return new (C, ID)
2475 ParmVarDecl(ParmVar, C, nullptr, SourceLocation(), SourceLocation(),
2476 nullptr, QualType(), nullptr, SC_None, nullptr);
Douglas Gregor72172e92012-01-05 21:55:30 +00002477}
2478
Argyrios Kyrtzidis4c6efa622011-07-30 17:23:26 +00002479SourceRange ParmVarDecl::getSourceRange() const {
2480 if (!hasInheritedDefaultArg()) {
2481 SourceRange ArgRange = getDefaultArgRange();
2482 if (ArgRange.isValid())
2483 return SourceRange(getOuterLocStart(), ArgRange.getEnd());
2484 }
2485
Argyrios Kyrtzidisa0772792013-04-17 01:56:48 +00002486 // DeclaratorDecl considers the range of postfix types as overlapping with the
2487 // declaration name, but this is not the case with parameters in ObjC methods.
2488 if (isa<ObjCMethodDecl>(getDeclContext()))
2489 return SourceRange(DeclaratorDecl::getLocStart(), getLocation());
2490
Argyrios Kyrtzidis4c6efa622011-07-30 17:23:26 +00002491 return DeclaratorDecl::getSourceRange();
2492}
2493
Sebastian Redl833ef452010-01-26 22:01:41 +00002494Expr *ParmVarDecl::getDefaultArg() {
2495 assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!");
2496 assert(!hasUninstantiatedDefaultArg() &&
2497 "Default argument is not yet instantiated!");
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002498
Sebastian Redl833ef452010-01-26 22:01:41 +00002499 Expr *Arg = getInit();
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002500 if (auto *E = dyn_cast_or_null<ExprWithCleanups>(Arg))
Sebastian Redl833ef452010-01-26 22:01:41 +00002501 return E->getSubExpr();
Douglas Gregor0760fa12009-03-10 23:43:53 +00002502
Sebastian Redl833ef452010-01-26 22:01:41 +00002503 return Arg;
2504}
2505
Chandler Carruth813faed2015-12-30 02:51:00 +00002506void ParmVarDecl::setDefaultArg(Expr *defarg) {
2507 ParmVarDeclBits.DefaultArgKind = DAK_Normal;
2508 Init = defarg;
2509}
Sebastian Redl833ef452010-01-26 22:01:41 +00002510
Chandler Carruth813faed2015-12-30 02:51:00 +00002511SourceRange ParmVarDecl::getDefaultArgRange() const {
2512 switch (ParmVarDeclBits.DefaultArgKind) {
2513 case DAK_None:
2514 case DAK_Unparsed:
2515 // Nothing we can do here.
2516 return SourceRange();
2517
2518 case DAK_Uninstantiated:
Sebastian Redl833ef452010-01-26 22:01:41 +00002519 return getUninstantiatedDefaultArg()->getSourceRange();
2520
Chandler Carruth813faed2015-12-30 02:51:00 +00002521 case DAK_Normal:
2522 if (const Expr *E = getInit())
2523 return E->getSourceRange();
2524
2525 // Missing an actual expression, may be invalid.
2526 return SourceRange();
2527 }
2528 llvm_unreachable("Invalid default argument kind.");
2529}
2530
2531void ParmVarDecl::setUninstantiatedDefaultArg(Expr *arg) {
2532 ParmVarDeclBits.DefaultArgKind = DAK_Uninstantiated;
2533 Init = arg;
2534}
2535
2536Expr *ParmVarDecl::getUninstantiatedDefaultArg() {
2537 assert(hasUninstantiatedDefaultArg() &&
2538 "Wrong kind of initialization expression!");
2539 return cast_or_null<Expr>(Init.get<Stmt *>());
2540}
2541
2542bool ParmVarDecl::hasDefaultArg() const {
2543 // FIXME: We should just return false for DAK_None here once callers are
2544 // prepared for the case that we encountered an invalid default argument and
2545 // were unable to even build an invalid expression.
2546 return hasUnparsedDefaultArg() || hasUninstantiatedDefaultArg() ||
2547 !Init.isNull();
Argyrios Kyrtzidis02dd4f92009-07-05 22:21:56 +00002548}
2549
Douglas Gregor3c6bd2a2011-01-05 21:11:38 +00002550bool ParmVarDecl::isParameterPack() const {
2551 return isa<PackExpansionType>(getType());
2552}
2553
Ted Kremenek540017e2011-10-06 05:00:56 +00002554void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) {
2555 getASTContext().setParameterIndex(this, parameterIndex);
2556 ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel;
2557}
2558
2559unsigned ParmVarDecl::getParameterIndexLarge() const {
2560 return getASTContext().getParameterIndex(this);
2561}
2562
Nuno Lopes394ec982008-12-17 23:39:55 +00002563//===----------------------------------------------------------------------===//
Chris Lattner59a25942008-03-31 00:36:02 +00002564// FunctionDecl Implementation
2565//===----------------------------------------------------------------------===//
2566
Benjamin Kramer9170e912013-02-22 15:46:01 +00002567void FunctionDecl::getNameForDiagnostic(
2568 raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const {
2569 NamedDecl::getNameForDiagnostic(OS, Policy, Qualified);
Douglas Gregorb11aad82011-02-19 18:51:44 +00002570 const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs();
2571 if (TemplateArgs)
Serge Pavlov03e672c2017-11-28 16:14:14 +00002572 printTemplateArgumentList(OS, TemplateArgs->asArray(), Policy);
Douglas Gregorb11aad82011-02-19 18:51:44 +00002573}
2574
Ted Kremenek186a0742010-04-29 16:49:01 +00002575bool FunctionDecl::isVariadic() const {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002576 if (const auto *FT = getType()->getAs<FunctionProtoType>())
Ted Kremenek186a0742010-04-29 16:49:01 +00002577 return FT->isVariadic();
2578 return false;
2579}
2580
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002581bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const {
Aaron Ballman86c93902014-03-06 23:45:36 +00002582 for (auto I : redecls()) {
Serge Pavlov9a618e12017-02-15 12:30:35 +00002583 if (I->doesThisDeclarationHaveABody()) {
Aaron Ballman86c93902014-03-06 23:45:36 +00002584 Definition = I;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002585 return true;
2586 }
2587 }
2588
2589 return false;
2590}
2591
Anders Carlsson9bd7d162011-05-14 23:26:09 +00002592bool FunctionDecl::hasTrivialBody() const
2593{
2594 Stmt *S = getBody();
2595 if (!S) {
2596 // Since we don't have a body for this function, we don't know if it's
2597 // trivial or not.
2598 return false;
2599 }
2600
2601 if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty())
2602 return true;
2603 return false;
2604}
2605
Alexis Hunt4a8ea102011-05-06 20:44:56 +00002606bool FunctionDecl::isDefined(const FunctionDecl *&Definition) const {
Aaron Ballman86c93902014-03-06 23:45:36 +00002607 for (auto I : redecls()) {
Serge Pavlov10673c92017-06-04 12:53:12 +00002608 if (I->isThisDeclarationADefinition()) {
2609 Definition = I;
Alexis Hunt4a8ea102011-05-06 20:44:56 +00002610 return true;
2611 }
2612 }
2613
2614 return false;
2615}
2616
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00002617Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const {
Rafael Espindola44503012013-10-19 01:37:17 +00002618 if (!hasBody(Definition))
Craig Topper36250ad2014-05-12 05:36:57 +00002619 return nullptr;
Rafael Espindola44503012013-10-19 01:37:17 +00002620
2621 if (Definition->Body)
2622 return Definition->Body.get(getASTContext().getExternalSource());
Douglas Gregor89f238c2008-04-21 02:02:58 +00002623
Craig Topper36250ad2014-05-12 05:36:57 +00002624 return nullptr;
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00002625}
2626
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00002627void FunctionDecl::setBody(Stmt *B) {
2628 Body = B;
Douglas Gregor027ba502010-12-06 17:49:01 +00002629 if (B)
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00002630 EndRangeLoc = B->getLocEnd();
2631}
2632
Douglas Gregor7d9120c2010-09-28 21:55:22 +00002633void FunctionDecl::setPure(bool P) {
2634 IsPure = P;
2635 if (P)
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002636 if (auto *Parent = dyn_cast<CXXRecordDecl>(getDeclContext()))
Douglas Gregor7d9120c2010-09-28 21:55:22 +00002637 Parent->markedVirtualFunctionPure();
2638}
2639
Richard Smith8d0dc312013-07-21 23:12:18 +00002640template<std::size_t Len>
2641static bool isNamed(const NamedDecl *ND, const char (&Str)[Len]) {
2642 IdentifierInfo *II = ND->getIdentifier();
2643 return II && II->isStr(Str);
2644}
2645
Douglas Gregor16618f22009-09-12 00:17:51 +00002646bool FunctionDecl::isMain() const {
John McCall53ffd372011-05-15 17:49:20 +00002647 const TranslationUnitDecl *tunit =
2648 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
2649 return tunit &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002650 !tunit->getASTContext().getLangOpts().Freestanding &&
Richard Smith8d0dc312013-07-21 23:12:18 +00002651 isNamed(this, "main");
John McCall53ffd372011-05-15 17:49:20 +00002652}
2653
David Majnemerc729b0b2013-09-16 22:44:20 +00002654bool FunctionDecl::isMSVCRTEntryPoint() const {
2655 const TranslationUnitDecl *TUnit =
2656 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
2657 if (!TUnit)
2658 return false;
2659
2660 // Even though we aren't really targeting MSVCRT if we are freestanding,
2661 // semantic analysis for these functions remains the same.
2662
2663 // MSVCRT entry points only exist on MSVCRT targets.
2664 if (!TUnit->getASTContext().getTargetInfo().getTriple().isOSMSVCRT())
2665 return false;
2666
2667 // Nameless functions like constructors cannot be entry points.
2668 if (!getIdentifier())
2669 return false;
2670
2671 return llvm::StringSwitch<bool>(getName())
2672 .Cases("main", // an ANSI console app
2673 "wmain", // a Unicode console App
2674 "WinMain", // an ANSI GUI app
2675 "wWinMain", // a Unicode GUI app
2676 "DllMain", // a DLL
2677 true)
2678 .Default(false);
2679}
2680
John McCall53ffd372011-05-15 17:49:20 +00002681bool FunctionDecl::isReservedGlobalPlacementOperator() const {
2682 assert(getDeclName().getNameKind() == DeclarationName::CXXOperatorName);
2683 assert(getDeclName().getCXXOverloadedOperator() == OO_New ||
2684 getDeclName().getCXXOverloadedOperator() == OO_Delete ||
2685 getDeclName().getCXXOverloadedOperator() == OO_Array_New ||
2686 getDeclName().getCXXOverloadedOperator() == OO_Array_Delete);
2687
Richard Smithf6004412014-01-19 23:25:37 +00002688 if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
2689 return false;
John McCall53ffd372011-05-15 17:49:20 +00002690
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002691 const auto *proto = getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00002692 if (proto->getNumParams() != 2 || proto->isVariadic())
2693 return false;
John McCall53ffd372011-05-15 17:49:20 +00002694
2695 ASTContext &Context =
2696 cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext())
2697 ->getASTContext();
2698
2699 // The result type and first argument type are constant across all
2700 // these operators. The second argument must be exactly void*.
Alp Toker9cacbab2014-01-20 20:26:09 +00002701 return (proto->getParamType(1).getCanonicalType() == Context.VoidPtrTy);
Douglas Gregore62c0a42009-02-24 01:23:02 +00002702}
2703
Akira Hatanakacae83f72017-06-29 18:48:40 +00002704bool FunctionDecl::isReplaceableGlobalAllocationFunction(bool *IsAligned) const {
Richard Smith8d0dc312013-07-21 23:12:18 +00002705 if (getDeclName().getNameKind() != DeclarationName::CXXOperatorName)
2706 return false;
2707 if (getDeclName().getCXXOverloadedOperator() != OO_New &&
2708 getDeclName().getCXXOverloadedOperator() != OO_Delete &&
2709 getDeclName().getCXXOverloadedOperator() != OO_Array_New &&
2710 getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
2711 return false;
2712
2713 if (isa<CXXRecordDecl>(getDeclContext()))
2714 return false;
Richard Smithf6004412014-01-19 23:25:37 +00002715
2716 // This can only fail for an invalid 'operator new' declaration.
2717 if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
2718 return false;
Richard Smith8d0dc312013-07-21 23:12:18 +00002719
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002720 const auto *FPT = getType()->castAs<FunctionProtoType>();
Richard Smithb2f0f052016-10-10 18:54:32 +00002721 if (FPT->getNumParams() == 0 || FPT->getNumParams() > 3 || FPT->isVariadic())
Richard Smith8d0dc312013-07-21 23:12:18 +00002722 return false;
2723
2724 // If this is a single-parameter function, it must be a replaceable global
2725 // allocation or deallocation function.
Alp Toker9cacbab2014-01-20 20:26:09 +00002726 if (FPT->getNumParams() == 1)
Richard Smith8d0dc312013-07-21 23:12:18 +00002727 return true;
2728
Richard Smithb2f0f052016-10-10 18:54:32 +00002729 unsigned Params = 1;
2730 QualType Ty = FPT->getParamType(Params);
Richard Smith1cdec012013-09-29 04:40:38 +00002731 ASTContext &Ctx = getASTContext();
Richard Smithb2f0f052016-10-10 18:54:32 +00002732
2733 auto Consume = [&] {
2734 ++Params;
2735 Ty = Params < FPT->getNumParams() ? FPT->getParamType(Params) : QualType();
2736 };
2737
2738 // In C++14, the next parameter can be a 'std::size_t' for sized delete.
2739 bool IsSizedDelete = false;
Richard Smithb47c36f2013-11-05 09:12:18 +00002740 if (Ctx.getLangOpts().SizedDeallocation &&
Richard Smithb2f0f052016-10-10 18:54:32 +00002741 (getDeclName().getCXXOverloadedOperator() == OO_Delete ||
2742 getDeclName().getCXXOverloadedOperator() == OO_Array_Delete) &&
2743 Ctx.hasSameType(Ty, Ctx.getSizeType())) {
2744 IsSizedDelete = true;
2745 Consume();
2746 }
2747
2748 // In C++17, the next parameter can be a 'std::align_val_t' for aligned
2749 // new/delete.
Akira Hatanakacae83f72017-06-29 18:48:40 +00002750 if (Ctx.getLangOpts().AlignedAllocation && !Ty.isNull() && Ty->isAlignValT()) {
2751 if (IsAligned)
2752 *IsAligned = true;
Richard Smithb2f0f052016-10-10 18:54:32 +00002753 Consume();
Akira Hatanakacae83f72017-06-29 18:48:40 +00002754 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002755
2756 // Finally, if this is not a sized delete, the final parameter can
2757 // be a 'const std::nothrow_t&'.
2758 if (!IsSizedDelete && !Ty.isNull() && Ty->isReferenceType()) {
2759 Ty = Ty->getPointeeType();
2760 if (Ty.getCVRQualifiers() != Qualifiers::Const)
2761 return false;
2762 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
2763 if (RD && isNamed(RD, "nothrow_t") && RD->isInStdNamespace())
2764 Consume();
2765 }
2766
2767 return Params == FPT->getNumParams();
Richard Smith8d0dc312013-07-21 23:12:18 +00002768}
2769
Richard Smith5b349582017-10-13 01:55:36 +00002770bool FunctionDecl::isDestroyingOperatorDelete() const {
2771 // C++ P0722:
2772 // Within a class C, a single object deallocation function with signature
2773 // (T, std::destroying_delete_t, <more params>)
2774 // is a destroying operator delete.
2775 if (!isa<CXXMethodDecl>(this) || getOverloadedOperator() != OO_Delete ||
2776 getNumParams() < 2)
2777 return false;
2778
2779 auto *RD = getParamDecl(1)->getType()->getAsCXXRecordDecl();
2780 return RD && RD->isInStdNamespace() && RD->getIdentifier() &&
2781 RD->getIdentifier()->isStr("destroying_delete_t");
2782}
2783
Rafael Espindolaf4187652013-02-14 01:18:37 +00002784LanguageLinkage FunctionDecl::getLanguageLinkage() const {
Alp Toker84212df2014-05-31 06:11:02 +00002785 return getDeclLanguageLinkage(*this);
Rafael Espindola576127d2012-12-28 14:21:58 +00002786}
2787
Rafael Espindola0e0d0092013-03-14 03:07:35 +00002788bool FunctionDecl::isExternC() const {
Alp Toker84212df2014-05-31 06:11:02 +00002789 return isDeclExternC(*this);
Rafael Espindola0e0d0092013-03-14 03:07:35 +00002790}
2791
Rafael Espindola593537a2013-05-05 20:15:21 +00002792bool FunctionDecl::isInExternCContext() const {
Serge Pavlov3cb80222013-11-14 02:13:03 +00002793 return getLexicalDeclContext()->isExternCContext();
Rafael Espindola593537a2013-05-05 20:15:21 +00002794}
2795
2796bool FunctionDecl::isInExternCXXContext() const {
Serge Pavlov3cb80222013-11-14 02:13:03 +00002797 return getLexicalDeclContext()->isExternCXXContext();
Rafael Espindola593537a2013-05-05 20:15:21 +00002798}
2799
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002800bool FunctionDecl::isGlobal() const {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002801 if (const auto *Method = dyn_cast<CXXMethodDecl>(this))
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002802 return Method->isStatic();
2803
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002804 if (getCanonicalDecl()->getStorageClass() == SC_Static)
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002805 return false;
2806
Mike Stump11289f42009-09-09 15:08:12 +00002807 for (const DeclContext *DC = getDeclContext();
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002808 DC->isNamespace();
2809 DC = DC->getParent()) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002810 if (const auto *Namespace = cast<NamespaceDecl>(DC)) {
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002811 if (!Namespace->getDeclName())
2812 return false;
2813 break;
2814 }
2815 }
2816
2817 return true;
2818}
2819
Richard Smith10876ef2013-01-17 01:30:42 +00002820bool FunctionDecl::isNoReturn() const {
Adrian Prantl721c7cb2016-08-17 16:42:15 +00002821 if (hasAttr<NoReturnAttr>() || hasAttr<CXX11NoReturnAttr>() ||
2822 hasAttr<C11NoReturnAttr>())
2823 return true;
2824
2825 if (auto *FnTy = getType()->getAs<FunctionType>())
2826 return FnTy->getNoReturnAttr();
2827
2828 return false;
Richard Smith10876ef2013-01-17 01:30:42 +00002829}
2830
Sebastian Redl833ef452010-01-26 22:01:41 +00002831void
2832FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00002833 redeclarable_base::setPreviousDecl(PrevDecl);
Sebastian Redl833ef452010-01-26 22:01:41 +00002834
2835 if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) {
2836 FunctionTemplateDecl *PrevFunTmpl
Craig Topper36250ad2014-05-12 05:36:57 +00002837 = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : nullptr;
Sebastian Redl833ef452010-01-26 22:01:41 +00002838 assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch");
Rafael Espindola8db352d2013-10-17 15:37:26 +00002839 FunTmpl->setPreviousDecl(PrevFunTmpl);
Sebastian Redl833ef452010-01-26 22:01:41 +00002840 }
Douglas Gregorff76cb92010-12-09 16:59:22 +00002841
Axel Naumannfbc7b982011-11-08 18:21:06 +00002842 if (PrevDecl && PrevDecl->IsInline)
Douglas Gregorff76cb92010-12-09 16:59:22 +00002843 IsInline = true;
Sebastian Redl833ef452010-01-26 22:01:41 +00002844}
2845
Rafael Espindola8db352d2013-10-17 15:37:26 +00002846FunctionDecl *FunctionDecl::getCanonicalDecl() { return getFirstDecl(); }
Sebastian Redl833ef452010-01-26 22:01:41 +00002847
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002848/// \brief Returns a value indicating whether this function
2849/// corresponds to a builtin function.
2850///
2851/// The function corresponds to a built-in function if it is
2852/// declared at translation scope or within an extern "C" block and
2853/// its name matches with the name of a builtin. The returned value
2854/// will be 0 for functions that do not correspond to a builtin, a
Mike Stump11289f42009-09-09 15:08:12 +00002855/// value of type \c Builtin::ID if in the target-independent range
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002856/// \c [1,Builtin::First), or a target-specific builtin value.
Douglas Gregor15fc9562009-09-12 00:22:50 +00002857unsigned FunctionDecl::getBuiltinID() const {
Daniel Dunbar304314d2012-03-06 23:52:37 +00002858 if (!getIdentifier())
Douglas Gregore711f702009-02-14 18:57:46 +00002859 return 0;
2860
2861 unsigned BuiltinID = getIdentifier()->getBuiltinID();
Daniel Dunbar304314d2012-03-06 23:52:37 +00002862 if (!BuiltinID)
2863 return 0;
2864
2865 ASTContext &Context = getASTContext();
Warren Hunt445d83e2013-11-01 23:46:51 +00002866 if (Context.getLangOpts().CPlusPlus) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002867 const auto *LinkageDecl =
2868 dyn_cast<LinkageSpecDecl>(getFirstDecl()->getDeclContext());
Warren Hunt445d83e2013-11-01 23:46:51 +00002869 // In C++, the first declaration of a builtin is always inside an implicit
2870 // extern "C".
2871 // FIXME: A recognised library function may not be directly in an extern "C"
2872 // declaration, for instance "extern "C" { namespace std { decl } }".
David Majnemerba3e5ec2015-03-13 18:26:17 +00002873 if (!LinkageDecl) {
2874 if (BuiltinID == Builtin::BI__GetExceptionInfo &&
David Majnemer145abde2016-01-26 01:12:17 +00002875 Context.getTargetInfo().getCXXABI().isMicrosoft())
David Majnemerba3e5ec2015-03-13 18:26:17 +00002876 return Builtin::BI__GetExceptionInfo;
2877 return 0;
2878 }
2879 if (LinkageDecl->getLanguage() != LinkageSpecDecl::lang_c)
Warren Hunt445d83e2013-11-01 23:46:51 +00002880 return 0;
2881 }
2882
2883 // If the function is marked "overloadable", it has a different mangled name
2884 // and is not the C library function.
Aaron Ballman9ead1242013-12-19 02:39:40 +00002885 if (hasAttr<OverloadableAttr>())
Warren Hunt445d83e2013-11-01 23:46:51 +00002886 return 0;
2887
Douglas Gregore711f702009-02-14 18:57:46 +00002888 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
2889 return BuiltinID;
2890
2891 // This function has the name of a known C library
2892 // function. Determine whether it actually refers to the C library
2893 // function or whether it just has the same name.
2894
Douglas Gregora908e7f2009-02-17 03:23:10 +00002895 // If this is a static function, it's not a builtin.
John McCall8e7d6562010-08-26 03:08:43 +00002896 if (getStorageClass() == SC_Static)
Douglas Gregora908e7f2009-02-17 03:23:10 +00002897 return 0;
2898
Anastasia Stulova1202de32016-02-12 12:07:04 +00002899 // OpenCL v1.2 s6.9.f - The library functions defined in
2900 // the C99 standard headers are not available.
2901 if (Context.getLangOpts().OpenCL &&
2902 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
2903 return 0;
2904
Artem Belevich5ecdb942018-01-23 19:08:18 +00002905 // CUDA does not have device-side standard library. printf and malloc are the
2906 // only special cases that are supported by device-side runtime.
2907 if (Context.getLangOpts().CUDA && hasAttr<CUDADeviceAttr>() &&
2908 !hasAttr<CUDAHostAttr>() &&
2909 !(BuiltinID == Builtin::BIprintf || BuiltinID == Builtin::BImalloc))
2910 return 0;
2911
Warren Hunt445d83e2013-11-01 23:46:51 +00002912 return BuiltinID;
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002913}
2914
Chris Lattner47c0d002009-04-25 06:03:53 +00002915/// getNumParams - Return the number of parameters this function must have
Bob Wilsonb39017a2011-01-10 18:23:55 +00002916/// based on its FunctionType. This is the length of the ParamInfo array
Chris Lattner47c0d002009-04-25 06:03:53 +00002917/// after it has been created.
2918unsigned FunctionDecl::getNumParams() const {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002919 const auto *FPT = getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00002920 return FPT ? FPT->getNumParams() : 0;
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00002921}
2922
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00002923void FunctionDecl::setParams(ASTContext &C,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002924 ArrayRef<ParmVarDecl *> NewParamInfo) {
Craig Topper36250ad2014-05-12 05:36:57 +00002925 assert(!ParamInfo && "Already has param info!");
David Blaikie9c70e042011-09-21 18:16:56 +00002926 assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!");
Mike Stump11289f42009-09-09 15:08:12 +00002927
Chris Lattner8f5bf2f2007-01-21 19:04:10 +00002928 // Zero params -> null pointer.
David Blaikie9c70e042011-09-21 18:16:56 +00002929 if (!NewParamInfo.empty()) {
2930 ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()];
2931 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
Chris Lattner8f5bf2f2007-01-21 19:04:10 +00002932 }
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00002933}
Chris Lattner41943152007-01-25 04:52:46 +00002934
Chris Lattner58258242008-04-10 02:22:51 +00002935/// getMinRequiredArguments - Returns the minimum number of arguments
2936/// needed to call this function. This may be fewer than the number of
2937/// function parameters, if some of the parameters have default
Richard Smith91151782014-04-01 19:18:16 +00002938/// arguments (in C++) or are parameter packs (C++11).
Chris Lattner58258242008-04-10 02:22:51 +00002939unsigned FunctionDecl::getMinRequiredArguments() const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002940 if (!getASTContext().getLangOpts().CPlusPlus)
Douglas Gregor0dd423e2011-01-11 01:52:23 +00002941 return getNumParams();
Chris Lattner58258242008-04-10 02:22:51 +00002942
Richard Smith91151782014-04-01 19:18:16 +00002943 unsigned NumRequiredArgs = 0;
David Majnemer59f77922016-06-24 04:05:48 +00002944 for (auto *Param : parameters())
Richard Smith91151782014-04-01 19:18:16 +00002945 if (!Param->isParameterPack() && !Param->hasDefaultArg())
2946 ++NumRequiredArgs;
Chris Lattner58258242008-04-10 02:22:51 +00002947 return NumRequiredArgs;
2948}
2949
David Majnemer54e3ba52014-04-02 23:17:29 +00002950/// \brief The combination of the extern and inline keywords under MSVC forces
2951/// the function to be required.
2952///
2953/// Note: This function assumes that we will only get called when isInlined()
2954/// would return true for this FunctionDecl.
2955bool FunctionDecl::isMSExternInline() const {
2956 assert(isInlined() && "expected to get called on an inlined function!");
2957
2958 const ASTContext &Context = getASTContext();
David Majnemer3f021502015-10-08 04:53:31 +00002959 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
2960 !hasAttr<DLLExportAttr>())
David Majnemer54e3ba52014-04-02 23:17:29 +00002961 return false;
2962
David Majnemer73768702015-03-20 00:02:27 +00002963 for (const FunctionDecl *FD = getMostRecentDecl(); FD;
2964 FD = FD->getPreviousDecl())
David Majnemerc0c42f32015-07-10 20:55:38 +00002965 if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern)
David Majnemer54e3ba52014-04-02 23:17:29 +00002966 return true;
2967
2968 return false;
2969}
2970
2971static bool redeclForcesDefMSVC(const FunctionDecl *Redecl) {
2972 if (Redecl->getStorageClass() != SC_Extern)
2973 return false;
2974
2975 for (const FunctionDecl *FD = Redecl->getPreviousDecl(); FD;
2976 FD = FD->getPreviousDecl())
David Majnemerc0c42f32015-07-10 20:55:38 +00002977 if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern)
David Majnemer54e3ba52014-04-02 23:17:29 +00002978 return false;
2979
2980 return true;
2981}
2982
Eli Friedman1b125c32012-02-07 03:50:18 +00002983static bool RedeclForcesDefC99(const FunctionDecl *Redecl) {
2984 // Only consider file-scope declarations in this test.
2985 if (!Redecl->getLexicalDeclContext()->isTranslationUnit())
2986 return false;
2987
2988 // Only consider explicit declarations; the presence of a builtin for a
2989 // libcall shouldn't affect whether a definition is externally visible.
2990 if (Redecl->isImplicit())
2991 return false;
2992
2993 if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern)
2994 return true; // Not an inline definition
2995
2996 return false;
2997}
2998
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002999/// \brief For a function declaration in C or C++, determine whether this
3000/// declaration causes the definition to be externally visible.
3001///
David Majnemer54e3ba52014-04-02 23:17:29 +00003002/// For instance, this determines if adding the current declaration to the set
Eli Friedman1b125c32012-02-07 03:50:18 +00003003/// of redeclarations of the given functions causes
3004/// isInlineDefinitionExternallyVisible to change from false to true.
Nick Lewycky26da4dd2011-07-18 05:26:13 +00003005bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const {
Justin Lebar0241c962016-10-28 16:46:39 +00003006 assert(!doesThisDeclarationHaveABody() &&
Nick Lewycky26da4dd2011-07-18 05:26:13 +00003007 "Must have a declaration without a body.");
3008
3009 ASTContext &Context = getASTContext();
3010
David Majnemer54e3ba52014-04-02 23:17:29 +00003011 if (Context.getLangOpts().MSVCCompat) {
3012 const FunctionDecl *Definition;
3013 if (hasBody(Definition) && Definition->isInlined() &&
3014 redeclForcesDefMSVC(this))
3015 return true;
3016 }
3017
David Blaikiebbafb8a2012-03-11 07:00:24 +00003018 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
Eli Friedman1b125c32012-02-07 03:50:18 +00003019 // With GNU inlining, a declaration with 'inline' but not 'extern', forces
3020 // an externally visible definition.
3021 //
3022 // FIXME: What happens if gnu_inline gets added on after the first
3023 // declaration?
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003024 if (!isInlineSpecified() || getStorageClass() == SC_Extern)
Eli Friedman1b125c32012-02-07 03:50:18 +00003025 return false;
3026
3027 const FunctionDecl *Prev = this;
3028 bool FoundBody = false;
3029 while ((Prev = Prev->getPreviousDecl())) {
David Blaikie7d170102013-05-15 07:37:26 +00003030 FoundBody |= Prev->Body.isValid();
Eli Friedman1b125c32012-02-07 03:50:18 +00003031
3032 if (Prev->Body) {
3033 // If it's not the case that both 'inline' and 'extern' are
3034 // specified on the definition, then it is always externally visible.
3035 if (!Prev->isInlineSpecified() ||
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003036 Prev->getStorageClass() != SC_Extern)
Eli Friedman1b125c32012-02-07 03:50:18 +00003037 return false;
3038 } else if (Prev->isInlineSpecified() &&
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003039 Prev->getStorageClass() != SC_Extern) {
Eli Friedman1b125c32012-02-07 03:50:18 +00003040 return false;
3041 }
3042 }
3043 return FoundBody;
3044 }
3045
David Blaikiebbafb8a2012-03-11 07:00:24 +00003046 if (Context.getLangOpts().CPlusPlus)
Nick Lewycky26da4dd2011-07-18 05:26:13 +00003047 return false;
Eli Friedman1b125c32012-02-07 03:50:18 +00003048
3049 // C99 6.7.4p6:
3050 // [...] If all of the file scope declarations for a function in a
3051 // translation unit include the inline function specifier without extern,
3052 // then the definition in that translation unit is an inline definition.
3053 if (isInlineSpecified() && getStorageClass() != SC_Extern)
Nick Lewycky26da4dd2011-07-18 05:26:13 +00003054 return false;
Eli Friedman1b125c32012-02-07 03:50:18 +00003055 const FunctionDecl *Prev = this;
3056 bool FoundBody = false;
3057 while ((Prev = Prev->getPreviousDecl())) {
David Blaikie7d170102013-05-15 07:37:26 +00003058 FoundBody |= Prev->Body.isValid();
Eli Friedman1b125c32012-02-07 03:50:18 +00003059 if (RedeclForcesDefC99(Prev))
3060 return false;
3061 }
3062 return FoundBody;
Nick Lewycky26da4dd2011-07-18 05:26:13 +00003063}
3064
Alp Tokerd0787eb2014-07-02 01:47:15 +00003065SourceRange FunctionDecl::getReturnTypeSourceRange() const {
3066 const TypeSourceInfo *TSI = getTypeSourceInfo();
3067 if (!TSI)
3068 return SourceRange();
Alp Tokerf5b10792014-07-02 12:55:58 +00003069 FunctionTypeLoc FTL =
3070 TSI->getTypeLoc().IgnoreParens().getAs<FunctionTypeLoc>();
3071 if (!FTL)
Alp Tokerd0787eb2014-07-02 01:47:15 +00003072 return SourceRange();
3073
Alp Tokerf5b10792014-07-02 12:55:58 +00003074 // Skip self-referential return types.
3075 const SourceManager &SM = getASTContext().getSourceManager();
3076 SourceRange RTRange = FTL.getReturnLoc().getSourceRange();
3077 SourceLocation Boundary = getNameInfo().getLocStart();
3078 if (RTRange.isInvalid() || Boundary.isInvalid() ||
3079 !SM.isBeforeInTranslationUnit(RTRange.getEnd(), Boundary))
3080 return SourceRange();
Alp Tokerd0787eb2014-07-02 01:47:15 +00003081
Alp Tokerf5b10792014-07-02 12:55:58 +00003082 return RTRange;
Alp Tokerd0787eb2014-07-02 01:47:15 +00003083}
3084
Malcolm Parsonsa3220ce2017-01-12 16:11:28 +00003085SourceRange FunctionDecl::getExceptionSpecSourceRange() const {
3086 const TypeSourceInfo *TSI = getTypeSourceInfo();
3087 if (!TSI)
3088 return SourceRange();
3089 FunctionTypeLoc FTL =
3090 TSI->getTypeLoc().IgnoreParens().getAs<FunctionTypeLoc>();
3091 if (!FTL)
3092 return SourceRange();
3093
3094 return FTL.getExceptionSpecRange();
3095}
3096
Aaron Ballmane7964782016-03-07 22:44:55 +00003097const Attr *FunctionDecl::getUnusedResultAttr() const {
Kaelyn Takata0a2e84c2015-04-09 19:43:04 +00003098 QualType RetType = getReturnType();
3099 if (RetType->isRecordType()) {
Aaron Ballman35713eb2017-10-17 20:33:35 +00003100 if (const auto *Ret =
3101 dyn_cast_or_null<RecordDecl>(RetType->getAsTagDecl())) {
Aaron Ballmane7964782016-03-07 22:44:55 +00003102 if (const auto *R = Ret->getAttr<WarnUnusedResultAttr>())
3103 return R;
3104 }
3105 } else if (const auto *ET = RetType->getAs<EnumType>()) {
3106 if (const EnumDecl *ED = ET->getDecl()) {
3107 if (const auto *R = ED->getAttr<WarnUnusedResultAttr>())
3108 return R;
3109 }
Kaelyn Takata0a2e84c2015-04-09 19:43:04 +00003110 }
Aaron Ballmane7964782016-03-07 22:44:55 +00003111 return getAttr<WarnUnusedResultAttr>();
Kaelyn Takata0a2e84c2015-04-09 19:43:04 +00003112}
3113
Richard Smithf3814ad2013-01-25 00:08:28 +00003114/// \brief For an inline function definition in C, or for a gnu_inline function
3115/// in C++, determine whether the definition will be externally visible.
Douglas Gregor299d76e2009-09-13 07:46:26 +00003116///
3117/// Inline function definitions are always available for inlining optimizations.
3118/// However, depending on the language dialect, declaration specifiers, and
3119/// attributes, the definition of an inline function may or may not be
3120/// "externally" visible to other translation units in the program.
3121///
3122/// In C99, inline definitions are not externally visible by default. However,
Mike Stump13c66702010-01-06 02:05:39 +00003123/// if even one of the global-scope declarations is marked "extern inline", the
Douglas Gregor299d76e2009-09-13 07:46:26 +00003124/// inline definition becomes externally visible (C99 6.7.4p6).
3125///
3126/// In GNU89 mode, or if the gnu_inline attribute is attached to the function
3127/// definition, we use the GNU semantics for inline, which are nearly the
3128/// opposite of C99 semantics. In particular, "inline" by itself will create
3129/// an externally visible symbol, but "extern inline" will not create an
3130/// externally visible symbol.
3131bool FunctionDecl::isInlineDefinitionExternallyVisible() const {
Manuel Klimekda7456a2016-11-01 10:30:50 +00003132 assert((doesThisDeclarationHaveABody() || willHaveBody()) &&
3133 "Must be a function definition");
Douglas Gregor583dcaf2009-10-27 21:11:48 +00003134 assert(isInlined() && "Function must be inline");
Douglas Gregorb7e5c842009-10-27 23:26:40 +00003135 ASTContext &Context = getASTContext();
Douglas Gregor299d76e2009-09-13 07:46:26 +00003136
David Blaikiebbafb8a2012-03-11 07:00:24 +00003137 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
Eli Friedman1b125c32012-02-07 03:50:18 +00003138 // Note: If you change the logic here, please change
3139 // doesDeclarationForceExternallyVisibleDefinition as well.
3140 //
Douglas Gregorff76cb92010-12-09 16:59:22 +00003141 // If it's not the case that both 'inline' and 'extern' are
3142 // specified on the definition, then this inline definition is
3143 // externally visible.
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003144 if (!(isInlineSpecified() && getStorageClass() == SC_Extern))
Douglas Gregorff76cb92010-12-09 16:59:22 +00003145 return true;
3146
3147 // If any declaration is 'inline' but not 'extern', then this definition
3148 // is externally visible.
Aaron Ballman86c93902014-03-06 23:45:36 +00003149 for (auto Redecl : redecls()) {
Douglas Gregorff76cb92010-12-09 16:59:22 +00003150 if (Redecl->isInlineSpecified() &&
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003151 Redecl->getStorageClass() != SC_Extern)
Douglas Gregor299d76e2009-09-13 07:46:26 +00003152 return true;
Douglas Gregorff76cb92010-12-09 16:59:22 +00003153 }
Douglas Gregor299d76e2009-09-13 07:46:26 +00003154
Douglas Gregor76fe50c2009-04-28 06:37:30 +00003155 return false;
Douglas Gregor299d76e2009-09-13 07:46:26 +00003156 }
Eli Friedman1b125c32012-02-07 03:50:18 +00003157
Richard Smithf3814ad2013-01-25 00:08:28 +00003158 // The rest of this function is C-only.
3159 assert(!Context.getLangOpts().CPlusPlus &&
3160 "should not use C inline rules in C++");
3161
Douglas Gregor299d76e2009-09-13 07:46:26 +00003162 // C99 6.7.4p6:
3163 // [...] If all of the file scope declarations for a function in a
3164 // translation unit include the inline function specifier without extern,
3165 // then the definition in that translation unit is an inline definition.
Aaron Ballman86c93902014-03-06 23:45:36 +00003166 for (auto Redecl : redecls()) {
3167 if (RedeclForcesDefC99(Redecl))
Eli Friedman1b125c32012-02-07 03:50:18 +00003168 return true;
Douglas Gregor299d76e2009-09-13 07:46:26 +00003169 }
3170
3171 // C99 6.7.4p6:
3172 // An inline definition does not provide an external definition for the
3173 // function, and does not forbid an external definition in another
3174 // translation unit.
Douglas Gregor76fe50c2009-04-28 06:37:30 +00003175 return false;
3176}
3177
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00003178/// getOverloadedOperator - Which C++ overloaded operator this
3179/// function represents, if any.
3180OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const {
Douglas Gregor163c5852008-11-18 14:39:36 +00003181 if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
3182 return getDeclName().getCXXOverloadedOperator();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00003183 else
3184 return OO_None;
3185}
3186
Alexis Huntc88db062010-01-13 09:01:02 +00003187/// getLiteralIdentifier - The literal suffix identifier this function
3188/// represents, if any.
3189const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const {
3190 if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName)
3191 return getDeclName().getCXXLiteralIdentifier();
3192 else
Craig Topper36250ad2014-05-12 05:36:57 +00003193 return nullptr;
Alexis Huntc88db062010-01-13 09:01:02 +00003194}
3195
Argyrios Kyrtzidiscb6f3462010-06-22 09:54:51 +00003196FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const {
3197 if (TemplateOrSpecialization.isNull())
3198 return TK_NonTemplate;
3199 if (TemplateOrSpecialization.is<FunctionTemplateDecl *>())
3200 return TK_FunctionTemplate;
3201 if (TemplateOrSpecialization.is<MemberSpecializationInfo *>())
3202 return TK_MemberSpecialization;
3203 if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>())
3204 return TK_FunctionTemplateSpecialization;
3205 if (TemplateOrSpecialization.is
3206 <DependentFunctionTemplateSpecializationInfo*>())
3207 return TK_DependentFunctionTemplateSpecialization;
3208
David Blaikie83d382b2011-09-23 05:06:16 +00003209 llvm_unreachable("Did we miss a TemplateOrSpecialization type?");
Argyrios Kyrtzidiscb6f3462010-06-22 09:54:51 +00003210}
3211
Douglas Gregord801b062009-10-07 23:56:10 +00003212FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const {
Douglas Gregor06db9f52009-10-12 20:18:28 +00003213 if (MemberSpecializationInfo *Info = getMemberSpecializationInfo())
Douglas Gregord801b062009-10-07 23:56:10 +00003214 return cast<FunctionDecl>(Info->getInstantiatedFrom());
Craig Topper36250ad2014-05-12 05:36:57 +00003215
3216 return nullptr;
Douglas Gregord801b062009-10-07 23:56:10 +00003217}
3218
Chandler Carruth21c90602015-12-30 03:24:14 +00003219MemberSpecializationInfo *FunctionDecl::getMemberSpecializationInfo() const {
3220 return TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>();
3221}
3222
Douglas Gregord801b062009-10-07 23:56:10 +00003223void
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00003224FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C,
3225 FunctionDecl *FD,
Douglas Gregord801b062009-10-07 23:56:10 +00003226 TemplateSpecializationKind TSK) {
3227 assert(TemplateOrSpecialization.isNull() &&
3228 "Member function is already a specialization");
3229 MemberSpecializationInfo *Info
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00003230 = new (C) MemberSpecializationInfo(FD, TSK);
Douglas Gregord801b062009-10-07 23:56:10 +00003231 TemplateOrSpecialization = Info;
3232}
3233
Chandler Carruth21c90602015-12-30 03:24:14 +00003234FunctionTemplateDecl *FunctionDecl::getDescribedFunctionTemplate() const {
3235 return TemplateOrSpecialization.dyn_cast<FunctionTemplateDecl *>();
3236}
3237
3238void FunctionDecl::setDescribedFunctionTemplate(FunctionTemplateDecl *Template) {
3239 TemplateOrSpecialization = Template;
3240}
3241
Douglas Gregorafca3b42009-10-27 20:53:28 +00003242bool FunctionDecl::isImplicitlyInstantiable() const {
Douglas Gregor69f6a362010-05-17 17:34:56 +00003243 // If the function is invalid, it can't be implicitly instantiated.
3244 if (isInvalidDecl())
Douglas Gregorafca3b42009-10-27 20:53:28 +00003245 return false;
3246
3247 switch (getTemplateSpecializationKind()) {
3248 case TSK_Undeclared:
Douglas Gregorafca3b42009-10-27 20:53:28 +00003249 case TSK_ExplicitInstantiationDefinition:
3250 return false;
3251
3252 case TSK_ImplicitInstantiation:
3253 return true;
3254
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003255 // It is possible to instantiate TSK_ExplicitSpecialization kind
3256 // if the FunctionDecl has a class scope specialization pattern.
3257 case TSK_ExplicitSpecialization:
Craig Topper36250ad2014-05-12 05:36:57 +00003258 return getClassScopeSpecializationPattern() != nullptr;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003259
Douglas Gregorafca3b42009-10-27 20:53:28 +00003260 case TSK_ExplicitInstantiationDeclaration:
3261 // Handled below.
3262 break;
3263 }
3264
3265 // Find the actual template from which we will instantiate.
3266 const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003267 bool HasPattern = false;
Douglas Gregorafca3b42009-10-27 20:53:28 +00003268 if (PatternDecl)
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003269 HasPattern = PatternDecl->hasBody(PatternDecl);
Douglas Gregorafca3b42009-10-27 20:53:28 +00003270
3271 // C++0x [temp.explicit]p9:
3272 // Except for inline functions, other explicit instantiation declarations
3273 // have the effect of suppressing the implicit instantiation of the entity
3274 // to which they refer.
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003275 if (!HasPattern || !PatternDecl)
Douglas Gregorafca3b42009-10-27 20:53:28 +00003276 return true;
3277
Douglas Gregor583dcaf2009-10-27 21:11:48 +00003278 return PatternDecl->isInlined();
Ted Kremenek85825ae2011-12-01 00:59:17 +00003279}
3280
3281bool FunctionDecl::isTemplateInstantiation() const {
3282 switch (getTemplateSpecializationKind()) {
3283 case TSK_Undeclared:
3284 case TSK_ExplicitSpecialization:
3285 return false;
3286 case TSK_ImplicitInstantiation:
3287 case TSK_ExplicitInstantiationDeclaration:
3288 case TSK_ExplicitInstantiationDefinition:
3289 return true;
3290 }
3291 llvm_unreachable("All TSK values handled.");
3292}
Douglas Gregorafca3b42009-10-27 20:53:28 +00003293
3294FunctionDecl *FunctionDecl::getTemplateInstantiationPattern() const {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003295 // Handle class scope explicit specialization special case.
Richard Smith2195ec92017-04-21 01:15:13 +00003296 if (getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
3297 if (auto *Spec = getClassScopeSpecializationPattern())
3298 return getDefinitionOrSelf(Spec);
3299 return nullptr;
3300 }
3301
Faisal Valib90b2112014-04-03 16:32:21 +00003302 // If this is a generic lambda call operator specialization, its
3303 // instantiation pattern is always its primary template's pattern
3304 // even if its primary template was instantiated from another
3305 // member template (which happens with nested generic lambdas).
3306 // Since a lambda's call operator's body is transformed eagerly,
3307 // we don't have to go hunting for a prototype definition template
3308 // (i.e. instantiated-from-member-template) to use as an instantiation
3309 // pattern.
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003310
Faisal Valib90b2112014-04-03 16:32:21 +00003311 if (isGenericLambdaCallOperatorSpecialization(
3312 dyn_cast<CXXMethodDecl>(this))) {
Richard Smith2195ec92017-04-21 01:15:13 +00003313 assert(getPrimaryTemplate() && "not a generic lambda call operator?");
3314 return getDefinitionOrSelf(getPrimaryTemplate()->getTemplatedDecl());
Faisal Valib90b2112014-04-03 16:32:21 +00003315 }
Richard Smith2195ec92017-04-21 01:15:13 +00003316
Douglas Gregorafca3b42009-10-27 20:53:28 +00003317 if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) {
3318 while (Primary->getInstantiatedFromMemberTemplate()) {
3319 // If we have hit a point where the user provided a specialization of
3320 // this template, we're done looking.
3321 if (Primary->isMemberSpecialization())
3322 break;
Douglas Gregorafca3b42009-10-27 20:53:28 +00003323 Primary = Primary->getInstantiatedFromMemberTemplate();
3324 }
Richard Smith2195ec92017-04-21 01:15:13 +00003325
3326 return getDefinitionOrSelf(Primary->getTemplatedDecl());
Douglas Gregorafca3b42009-10-27 20:53:28 +00003327 }
Richard Smith2195ec92017-04-21 01:15:13 +00003328
3329 if (auto *MFD = getInstantiatedFromMemberFunction())
3330 return getDefinitionOrSelf(MFD);
3331
3332 return nullptr;
Douglas Gregorafca3b42009-10-27 20:53:28 +00003333}
3334
Douglas Gregor70d83e22009-06-29 17:30:29 +00003335FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const {
Mike Stump11289f42009-09-09 15:08:12 +00003336 if (FunctionTemplateSpecializationInfo *Info
Douglas Gregor70d83e22009-06-29 17:30:29 +00003337 = TemplateOrSpecialization
3338 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
Douglas Gregore8925db2009-06-29 22:39:32 +00003339 return Info->Template.getPointer();
Douglas Gregor70d83e22009-06-29 17:30:29 +00003340 }
Craig Topper36250ad2014-05-12 05:36:57 +00003341 return nullptr;
Douglas Gregor70d83e22009-06-29 17:30:29 +00003342}
3343
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003344FunctionDecl *FunctionDecl::getClassScopeSpecializationPattern() const {
3345 return getASTContext().getClassScopeSpecializationPattern(this);
3346}
3347
Chandler Carruth21c90602015-12-30 03:24:14 +00003348FunctionTemplateSpecializationInfo *
3349FunctionDecl::getTemplateSpecializationInfo() const {
3350 return TemplateOrSpecialization
3351 .dyn_cast<FunctionTemplateSpecializationInfo *>();
3352}
3353
Douglas Gregor70d83e22009-06-29 17:30:29 +00003354const TemplateArgumentList *
3355FunctionDecl::getTemplateSpecializationArgs() const {
Mike Stump11289f42009-09-09 15:08:12 +00003356 if (FunctionTemplateSpecializationInfo *Info
Douglas Gregorcf915552009-10-13 16:30:37 +00003357 = TemplateOrSpecialization
3358 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
Douglas Gregor70d83e22009-06-29 17:30:29 +00003359 return Info->TemplateArguments;
3360 }
Craig Topper36250ad2014-05-12 05:36:57 +00003361 return nullptr;
Douglas Gregor70d83e22009-06-29 17:30:29 +00003362}
3363
Argyrios Kyrtzidise9a24432011-09-22 20:07:09 +00003364const ASTTemplateArgumentListInfo *
Abramo Bagnara02ccd282010-05-20 15:32:11 +00003365FunctionDecl::getTemplateSpecializationArgsAsWritten() const {
3366 if (FunctionTemplateSpecializationInfo *Info
3367 = TemplateOrSpecialization
3368 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
3369 return Info->TemplateArgumentsAsWritten;
3370 }
Craig Topper36250ad2014-05-12 05:36:57 +00003371 return nullptr;
Abramo Bagnara02ccd282010-05-20 15:32:11 +00003372}
3373
Mike Stump11289f42009-09-09 15:08:12 +00003374void
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00003375FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C,
3376 FunctionTemplateDecl *Template,
Douglas Gregor8f5d4422009-06-29 20:59:39 +00003377 const TemplateArgumentList *TemplateArgs,
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003378 void *InsertPos,
Abramo Bagnara02ccd282010-05-20 15:32:11 +00003379 TemplateSpecializationKind TSK,
Argyrios Kyrtzidis927d8e02010-07-05 10:37:55 +00003380 const TemplateArgumentListInfo *TemplateArgsAsWritten,
3381 SourceLocation PointOfInstantiation) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003382 assert(TSK != TSK_Undeclared &&
3383 "Must specify the type of function template specialization");
Mike Stump11289f42009-09-09 15:08:12 +00003384 FunctionTemplateSpecializationInfo *Info
Douglas Gregor70d83e22009-06-29 17:30:29 +00003385 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00003386 if (!Info)
Argyrios Kyrtzidise262a952010-09-09 11:28:23 +00003387 Info = FunctionTemplateSpecializationInfo::Create(C, this, Template, TSK,
3388 TemplateArgs,
3389 TemplateArgsAsWritten,
3390 PointOfInstantiation);
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00003391 TemplateOrSpecialization = Info;
Douglas Gregorce9978f2012-03-28 14:34:23 +00003392 Template->addSpecialization(Info, InsertPos);
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00003393}
3394
John McCallb9c78482010-04-08 09:05:18 +00003395void
3396FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context,
3397 const UnresolvedSetImpl &Templates,
3398 const TemplateArgumentListInfo &TemplateArgs) {
3399 assert(TemplateOrSpecialization.isNull());
John McCallb9c78482010-04-08 09:05:18 +00003400 DependentFunctionTemplateSpecializationInfo *Info =
James Y Knight7a22b242015-08-06 20:26:32 +00003401 DependentFunctionTemplateSpecializationInfo::Create(Context, Templates,
3402 TemplateArgs);
John McCallb9c78482010-04-08 09:05:18 +00003403 TemplateOrSpecialization = Info;
3404}
3405
James Y Knight7a22b242015-08-06 20:26:32 +00003406DependentFunctionTemplateSpecializationInfo *
Chandler Carruth21c90602015-12-30 03:24:14 +00003407FunctionDecl::getDependentSpecializationInfo() const {
3408 return TemplateOrSpecialization
3409 .dyn_cast<DependentFunctionTemplateSpecializationInfo *>();
3410}
3411
3412DependentFunctionTemplateSpecializationInfo *
James Y Knight7a22b242015-08-06 20:26:32 +00003413DependentFunctionTemplateSpecializationInfo::Create(
3414 ASTContext &Context, const UnresolvedSetImpl &Ts,
3415 const TemplateArgumentListInfo &TArgs) {
3416 void *Buffer = Context.Allocate(
3417 totalSizeToAlloc<TemplateArgumentLoc, FunctionTemplateDecl *>(
3418 TArgs.size(), Ts.size()));
3419 return new (Buffer) DependentFunctionTemplateSpecializationInfo(Ts, TArgs);
3420}
3421
John McCallb9c78482010-04-08 09:05:18 +00003422DependentFunctionTemplateSpecializationInfo::
3423DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts,
3424 const TemplateArgumentListInfo &TArgs)
Benjamin Kramer3ebba522015-04-02 12:43:31 +00003425 : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) {
James Y Knight53c76162015-07-17 18:21:37 +00003426 NumTemplates = Ts.size();
3427 NumArgs = TArgs.size();
Benjamin Kramer3ebba522015-04-02 12:43:31 +00003428
James Y Knight7a22b242015-08-06 20:26:32 +00003429 FunctionTemplateDecl **TsArray = getTrailingObjects<FunctionTemplateDecl *>();
John McCallb9c78482010-04-08 09:05:18 +00003430 for (unsigned I = 0, E = Ts.size(); I != E; ++I)
3431 TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl());
3432
James Y Knight7a22b242015-08-06 20:26:32 +00003433 TemplateArgumentLoc *ArgsArray = getTrailingObjects<TemplateArgumentLoc>();
John McCallb9c78482010-04-08 09:05:18 +00003434 for (unsigned I = 0, E = TArgs.size(); I != E; ++I)
3435 new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]);
3436}
3437
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003438TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const {
Mike Stump11289f42009-09-09 15:08:12 +00003439 // For a function template specialization, query the specialization
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003440 // information object.
Douglas Gregord801b062009-10-07 23:56:10 +00003441 FunctionTemplateSpecializationInfo *FTSInfo
Douglas Gregore8925db2009-06-29 22:39:32 +00003442 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
Douglas Gregord801b062009-10-07 23:56:10 +00003443 if (FTSInfo)
3444 return FTSInfo->getTemplateSpecializationKind();
Mike Stump11289f42009-09-09 15:08:12 +00003445
Douglas Gregord801b062009-10-07 23:56:10 +00003446 MemberSpecializationInfo *MSInfo
3447 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
3448 if (MSInfo)
3449 return MSInfo->getTemplateSpecializationKind();
3450
3451 return TSK_Undeclared;
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003452}
3453
Mike Stump11289f42009-09-09 15:08:12 +00003454void
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003455FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
3456 SourceLocation PointOfInstantiation) {
3457 if (FunctionTemplateSpecializationInfo *FTSInfo
3458 = TemplateOrSpecialization.dyn_cast<
3459 FunctionTemplateSpecializationInfo*>()) {
3460 FTSInfo->setTemplateSpecializationKind(TSK);
3461 if (TSK != TSK_ExplicitSpecialization &&
3462 PointOfInstantiation.isValid() &&
Richard Smith891fc7f2017-12-05 01:31:47 +00003463 FTSInfo->getPointOfInstantiation().isInvalid()) {
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003464 FTSInfo->setPointOfInstantiation(PointOfInstantiation);
Richard Smith891fc7f2017-12-05 01:31:47 +00003465 if (ASTMutationListener *L = getASTContext().getASTMutationListener())
3466 L->InstantiationRequested(this);
3467 }
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003468 } else if (MemberSpecializationInfo *MSInfo
3469 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) {
3470 MSInfo->setTemplateSpecializationKind(TSK);
3471 if (TSK != TSK_ExplicitSpecialization &&
3472 PointOfInstantiation.isValid() &&
Richard Smith891fc7f2017-12-05 01:31:47 +00003473 MSInfo->getPointOfInstantiation().isInvalid()) {
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003474 MSInfo->setPointOfInstantiation(PointOfInstantiation);
Richard Smith891fc7f2017-12-05 01:31:47 +00003475 if (ASTMutationListener *L = getASTContext().getASTMutationListener())
3476 L->InstantiationRequested(this);
3477 }
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003478 } else
David Blaikie83d382b2011-09-23 05:06:16 +00003479 llvm_unreachable("Function cannot have a template specialization kind");
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003480}
3481
3482SourceLocation FunctionDecl::getPointOfInstantiation() const {
Douglas Gregord801b062009-10-07 23:56:10 +00003483 if (FunctionTemplateSpecializationInfo *FTSInfo
3484 = TemplateOrSpecialization.dyn_cast<
3485 FunctionTemplateSpecializationInfo*>())
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003486 return FTSInfo->getPointOfInstantiation();
Douglas Gregord801b062009-10-07 23:56:10 +00003487 else if (MemberSpecializationInfo *MSInfo
3488 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>())
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003489 return MSInfo->getPointOfInstantiation();
3490
3491 return SourceLocation();
Douglas Gregore8925db2009-06-29 22:39:32 +00003492}
3493
Douglas Gregor6411b922009-09-11 20:15:17 +00003494bool FunctionDecl::isOutOfLine() const {
Douglas Gregorb11aad82011-02-19 18:51:44 +00003495 if (Decl::isOutOfLine())
Douglas Gregor6411b922009-09-11 20:15:17 +00003496 return true;
3497
3498 // If this function was instantiated from a member function of a
3499 // class template, check whether that member function was defined out-of-line.
3500 if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) {
3501 const FunctionDecl *Definition;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003502 if (FD->hasBody(Definition))
Douglas Gregor6411b922009-09-11 20:15:17 +00003503 return Definition->isOutOfLine();
3504 }
3505
3506 // If this function was instantiated from a function template,
3507 // check whether that function template was defined out-of-line.
3508 if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) {
3509 const FunctionDecl *Definition;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003510 if (FunTmpl->getTemplatedDecl()->hasBody(Definition))
Douglas Gregor6411b922009-09-11 20:15:17 +00003511 return Definition->isOutOfLine();
3512 }
3513
3514 return false;
3515}
3516
Abramo Bagnaraea947882011-03-08 16:41:52 +00003517SourceRange FunctionDecl::getSourceRange() const {
3518 return SourceRange(getOuterLocStart(), EndRangeLoc);
3519}
3520
Anna Zaks28db7ce2012-01-18 02:45:01 +00003521unsigned FunctionDecl::getMemoryFunctionKind() const {
Anna Zaks201d4892012-01-13 21:52:01 +00003522 IdentifierInfo *FnInfo = getIdentifier();
3523
3524 if (!FnInfo)
Anna Zaks22122702012-01-17 00:37:07 +00003525 return 0;
Anna Zaks201d4892012-01-13 21:52:01 +00003526
3527 // Builtin handling.
3528 switch (getBuiltinID()) {
3529 case Builtin::BI__builtin_memset:
3530 case Builtin::BI__builtin___memset_chk:
3531 case Builtin::BImemset:
Anna Zaks22122702012-01-17 00:37:07 +00003532 return Builtin::BImemset;
Anna Zaks201d4892012-01-13 21:52:01 +00003533
3534 case Builtin::BI__builtin_memcpy:
3535 case Builtin::BI__builtin___memcpy_chk:
3536 case Builtin::BImemcpy:
Anna Zaks22122702012-01-17 00:37:07 +00003537 return Builtin::BImemcpy;
Anna Zaks201d4892012-01-13 21:52:01 +00003538
3539 case Builtin::BI__builtin_memmove:
3540 case Builtin::BI__builtin___memmove_chk:
3541 case Builtin::BImemmove:
Anna Zaks22122702012-01-17 00:37:07 +00003542 return Builtin::BImemmove;
Anna Zaks201d4892012-01-13 21:52:01 +00003543
3544 case Builtin::BIstrlcpy:
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00003545 case Builtin::BI__builtin___strlcpy_chk:
Anna Zaks22122702012-01-17 00:37:07 +00003546 return Builtin::BIstrlcpy;
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00003547
Anna Zaks201d4892012-01-13 21:52:01 +00003548 case Builtin::BIstrlcat:
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00003549 case Builtin::BI__builtin___strlcat_chk:
Anna Zaks22122702012-01-17 00:37:07 +00003550 return Builtin::BIstrlcat;
Anna Zaks201d4892012-01-13 21:52:01 +00003551
3552 case Builtin::BI__builtin_memcmp:
Anna Zaks22122702012-01-17 00:37:07 +00003553 case Builtin::BImemcmp:
3554 return Builtin::BImemcmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003555
3556 case Builtin::BI__builtin_strncpy:
3557 case Builtin::BI__builtin___strncpy_chk:
3558 case Builtin::BIstrncpy:
Anna Zaks22122702012-01-17 00:37:07 +00003559 return Builtin::BIstrncpy;
Anna Zaks201d4892012-01-13 21:52:01 +00003560
3561 case Builtin::BI__builtin_strncmp:
Anna Zaks22122702012-01-17 00:37:07 +00003562 case Builtin::BIstrncmp:
3563 return Builtin::BIstrncmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003564
3565 case Builtin::BI__builtin_strncasecmp:
Anna Zaks22122702012-01-17 00:37:07 +00003566 case Builtin::BIstrncasecmp:
3567 return Builtin::BIstrncasecmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003568
3569 case Builtin::BI__builtin_strncat:
Anna Zaks314cd092012-02-01 19:08:57 +00003570 case Builtin::BI__builtin___strncat_chk:
Anna Zaks201d4892012-01-13 21:52:01 +00003571 case Builtin::BIstrncat:
Anna Zaks22122702012-01-17 00:37:07 +00003572 return Builtin::BIstrncat;
Anna Zaks201d4892012-01-13 21:52:01 +00003573
3574 case Builtin::BI__builtin_strndup:
3575 case Builtin::BIstrndup:
Anna Zaks22122702012-01-17 00:37:07 +00003576 return Builtin::BIstrndup;
Anna Zaks201d4892012-01-13 21:52:01 +00003577
Anna Zaks314cd092012-02-01 19:08:57 +00003578 case Builtin::BI__builtin_strlen:
3579 case Builtin::BIstrlen:
3580 return Builtin::BIstrlen;
3581
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00003582 case Builtin::BI__builtin_bzero:
3583 case Builtin::BIbzero:
3584 return Builtin::BIbzero;
3585
Anna Zaks201d4892012-01-13 21:52:01 +00003586 default:
Rafael Espindola5bda63f2013-02-14 01:47:04 +00003587 if (isExternC()) {
Anna Zaks201d4892012-01-13 21:52:01 +00003588 if (FnInfo->isStr("memset"))
Anna Zaks22122702012-01-17 00:37:07 +00003589 return Builtin::BImemset;
Anna Zaks201d4892012-01-13 21:52:01 +00003590 else if (FnInfo->isStr("memcpy"))
Anna Zaks22122702012-01-17 00:37:07 +00003591 return Builtin::BImemcpy;
Anna Zaks201d4892012-01-13 21:52:01 +00003592 else if (FnInfo->isStr("memmove"))
Anna Zaks22122702012-01-17 00:37:07 +00003593 return Builtin::BImemmove;
Anna Zaks201d4892012-01-13 21:52:01 +00003594 else if (FnInfo->isStr("memcmp"))
Anna Zaks22122702012-01-17 00:37:07 +00003595 return Builtin::BImemcmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003596 else if (FnInfo->isStr("strncpy"))
Anna Zaks22122702012-01-17 00:37:07 +00003597 return Builtin::BIstrncpy;
Anna Zaks201d4892012-01-13 21:52:01 +00003598 else if (FnInfo->isStr("strncmp"))
Anna Zaks22122702012-01-17 00:37:07 +00003599 return Builtin::BIstrncmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003600 else if (FnInfo->isStr("strncasecmp"))
Anna Zaks22122702012-01-17 00:37:07 +00003601 return Builtin::BIstrncasecmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003602 else if (FnInfo->isStr("strncat"))
Anna Zaks22122702012-01-17 00:37:07 +00003603 return Builtin::BIstrncat;
Anna Zaks201d4892012-01-13 21:52:01 +00003604 else if (FnInfo->isStr("strndup"))
Anna Zaks22122702012-01-17 00:37:07 +00003605 return Builtin::BIstrndup;
Anna Zaks314cd092012-02-01 19:08:57 +00003606 else if (FnInfo->isStr("strlen"))
3607 return Builtin::BIstrlen;
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00003608 else if (FnInfo->isStr("bzero"))
3609 return Builtin::BIbzero;
Anna Zaks201d4892012-01-13 21:52:01 +00003610 }
3611 break;
3612 }
Anna Zaks22122702012-01-17 00:37:07 +00003613 return 0;
Anna Zaks201d4892012-01-13 21:52:01 +00003614}
3615
Richard Trieue6caa262017-12-23 00:41:01 +00003616unsigned FunctionDecl::getODRHash() {
3617 if (HasODRHash)
3618 return ODRHash;
3619
3620 if (FunctionDecl *Definition = getDefinition()) {
3621 if (Definition != this) {
3622 HasODRHash = true;
3623 ODRHash = Definition->getODRHash();
3624 return ODRHash;
3625 }
3626 }
3627
3628 class ODRHash Hash;
3629 Hash.AddFunctionDecl(this);
3630 HasODRHash = true;
3631 ODRHash = Hash.CalculateHash();
3632 return ODRHash;
3633}
3634
Chris Lattner59a25942008-03-31 00:36:02 +00003635//===----------------------------------------------------------------------===//
Sebastian Redl833ef452010-01-26 22:01:41 +00003636// FieldDecl Implementation
3637//===----------------------------------------------------------------------===//
3638
Jay Foad39c79802011-01-12 09:06:06 +00003639FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003640 SourceLocation StartLoc, SourceLocation IdLoc,
3641 IdentifierInfo *Id, QualType T,
Richard Smith938f40b2011-06-11 17:19:42 +00003642 TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
Richard Smith2b013182012-06-10 03:12:00 +00003643 InClassInitStyle InitStyle) {
Richard Smithf7981722013-11-22 09:01:48 +00003644 return new (C, DC) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo,
3645 BW, Mutable, InitStyle);
Sebastian Redl833ef452010-01-26 22:01:41 +00003646}
3647
Douglas Gregor72172e92012-01-05 21:55:30 +00003648FieldDecl *FieldDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00003649 return new (C, ID) FieldDecl(Field, nullptr, SourceLocation(),
3650 SourceLocation(), nullptr, QualType(), nullptr,
3651 nullptr, false, ICIS_NoInit);
Douglas Gregor72172e92012-01-05 21:55:30 +00003652}
3653
Sebastian Redl833ef452010-01-26 22:01:41 +00003654bool FieldDecl::isAnonymousStructOrUnion() const {
3655 if (!isImplicit() || getDeclName())
3656 return false;
3657
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00003658 if (const auto *Record = getType()->getAs<RecordType>())
Sebastian Redl833ef452010-01-26 22:01:41 +00003659 return Record->getDecl()->isAnonymousStructOrUnion();
3660
3661 return false;
3662}
3663
Richard Smithcaf33902011-10-10 18:28:20 +00003664unsigned FieldDecl::getBitWidthValue(const ASTContext &Ctx) const {
3665 assert(isBitField() && "not a bitfield");
Richard Smith6b8e3c02017-08-28 00:28:14 +00003666 return getBitWidth()->EvaluateKnownConstInt(Ctx).getZExtValue();
Richard Smithcaf33902011-10-10 18:28:20 +00003667}
3668
John McCall4e819612011-01-20 07:57:12 +00003669unsigned FieldDecl::getFieldIndex() const {
Richard Smith0b87e072013-10-07 08:02:11 +00003670 const FieldDecl *Canonical = getCanonicalDecl();
3671 if (Canonical != this)
3672 return Canonical->getFieldIndex();
3673
John McCall4e819612011-01-20 07:57:12 +00003674 if (CachedFieldIndex) return CachedFieldIndex - 1;
3675
Richard Smithd62306a2011-11-10 06:34:14 +00003676 unsigned Index = 0;
Richard Smith85567dd2017-11-15 01:33:46 +00003677 const RecordDecl *RD = getParent()->getDefinition();
3678 assert(RD && "requested index for field of struct with no definition");
Richard Smithd62306a2011-11-10 06:34:14 +00003679
Hans Wennborga302cd92014-08-21 16:06:57 +00003680 for (auto *Field : RD->fields()) {
3681 Field->getCanonicalDecl()->CachedFieldIndex = Index + 1;
3682 ++Index;
3683 }
John McCall4e819612011-01-20 07:57:12 +00003684
Richard Smithd62306a2011-11-10 06:34:14 +00003685 assert(CachedFieldIndex && "failed to find field in parent");
3686 return CachedFieldIndex - 1;
John McCall4e819612011-01-20 07:57:12 +00003687}
3688
Abramo Bagnara20c9e242011-03-08 11:07:11 +00003689SourceRange FieldDecl::getSourceRange() const {
Richard Smith6b8e3c02017-08-28 00:28:14 +00003690 const Expr *FinalExpr = getInClassInitializer();
3691 if (!FinalExpr)
3692 FinalExpr = getBitWidth();
3693 if (FinalExpr)
3694 return SourceRange(getInnerLocStart(), FinalExpr->getLocEnd());
3695 return DeclaratorDecl::getSourceRange();
Alexey Bataev39c81e22014-08-28 04:28:19 +00003696}
3697
3698void FieldDecl::setCapturedVLAType(const VariableArrayType *VLAType) {
David Blaikie11ab0782014-10-31 17:18:09 +00003699 assert((getParent()->isLambda() || getParent()->isCapturedRecord()) &&
Alexey Bataev330de032014-10-29 12:21:55 +00003700 "capturing type in non-lambda or captured record.");
Richard Smith6b8e3c02017-08-28 00:28:14 +00003701 assert(InitStorage.getInt() == ISK_NoInit &&
John McCallc90c1492014-10-10 18:44:34 +00003702 InitStorage.getPointer() == nullptr &&
Alexey Bataev39c81e22014-08-28 04:28:19 +00003703 "bit width, initializer or captured type already set");
John McCallc90c1492014-10-10 18:44:34 +00003704 InitStorage.setPointerAndInt(const_cast<VariableArrayType *>(VLAType),
3705 ISK_CapturedVLAType);
Alexey Bataev39c81e22014-08-28 04:28:19 +00003706}
3707
Sebastian Redl833ef452010-01-26 22:01:41 +00003708//===----------------------------------------------------------------------===//
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003709// TagDecl Implementation
Ted Kremenek21475702008-09-05 17:16:31 +00003710//===----------------------------------------------------------------------===//
3711
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00003712SourceLocation TagDecl::getOuterLocStart() const {
3713 return getTemplateOrInnerLocStart(this);
3714}
3715
Argyrios Kyrtzidis575fa052009-07-14 03:17:17 +00003716SourceRange TagDecl::getSourceRange() const {
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00003717 SourceLocation RBraceLoc = BraceRange.getEnd();
Argyrios Kyrtzidis575fa052009-07-14 03:17:17 +00003718 SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation();
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00003719 return SourceRange(getOuterLocStart(), E);
Argyrios Kyrtzidis575fa052009-07-14 03:17:17 +00003720}
3721
Rafael Espindola8db352d2013-10-17 15:37:26 +00003722TagDecl *TagDecl::getCanonicalDecl() { return getFirstDecl(); }
Argyrios Kyrtzidis5614aef2009-07-18 00:34:07 +00003723
Rafael Espindolabf5c33b2013-03-12 21:06:00 +00003724void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) {
David Majnemer00350522015-08-31 18:48:39 +00003725 TypedefNameDeclOrQualifier = TDD;
Reid Klecknercae82a22014-04-23 22:03:04 +00003726 if (const Type *T = getTypeForDecl()) {
3727 (void)T;
Richard Smith5b21db82014-04-23 18:20:42 +00003728 assert(T->isLinkageValid());
Reid Klecknercae82a22014-04-23 22:03:04 +00003729 }
Rafael Espindola0e0d0092013-03-14 03:07:35 +00003730 assert(isLinkageValid());
Douglas Gregora72a4e32010-05-19 18:39:18 +00003731}
3732
Douglas Gregordee1be82009-01-17 00:42:38 +00003733void TagDecl::startDefinition() {
Sebastian Redl9d8854e2010-08-02 18:27:05 +00003734 IsBeingDefined = true;
John McCall67da35c2010-02-04 22:26:26 +00003735
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00003736 if (auto *D = dyn_cast<CXXRecordDecl>(this)) {
Richard Smith053f6c62014-05-16 23:01:30 +00003737 struct CXXRecordDecl::DefinitionData *Data =
John McCall67da35c2010-02-04 22:26:26 +00003738 new (getASTContext()) struct CXXRecordDecl::DefinitionData(D);
Aaron Ballman86c93902014-03-06 23:45:36 +00003739 for (auto I : redecls())
Richard Smith64c06302014-05-22 23:19:02 +00003740 cast<CXXRecordDecl>(I)->DefinitionData = Data;
John McCall67da35c2010-02-04 22:26:26 +00003741 }
Douglas Gregordee1be82009-01-17 00:42:38 +00003742}
3743
3744void TagDecl::completeDefinition() {
John McCallae580fe2010-02-05 01:33:36 +00003745 assert((!isa<CXXRecordDecl>(this) ||
3746 cast<CXXRecordDecl>(this)->hasDefinition()) &&
3747 "definition completed but not started");
3748
John McCallf937c022011-10-07 06:10:15 +00003749 IsCompleteDefinition = true;
Sebastian Redl9d8854e2010-08-02 18:27:05 +00003750 IsBeingDefined = false;
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00003751
3752 if (ASTMutationListener *L = getASTMutationListener())
3753 L->CompletedTagDefinition(this);
Douglas Gregordee1be82009-01-17 00:42:38 +00003754}
3755
John McCallf937c022011-10-07 06:10:15 +00003756TagDecl *TagDecl::getDefinition() const {
3757 if (isCompleteDefinition())
Douglas Gregorb6b8f9e2009-07-29 23:36:44 +00003758 return const_cast<TagDecl *>(this);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003759
3760 // If it's possible for us to have an out-of-date definition, check now.
3761 if (MayHaveOutOfDateDef) {
3762 if (IdentifierInfo *II = getIdentifier()) {
3763 if (II->isOutOfDate()) {
3764 updateOutOfDate(*II);
3765 }
3766 }
3767 }
3768
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00003769 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(this))
Andrew Trickba266ee2010-10-19 21:54:32 +00003770 return CXXRD->getDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00003771
Aaron Ballman86c93902014-03-06 23:45:36 +00003772 for (auto R : redecls())
John McCallf937c022011-10-07 06:10:15 +00003773 if (R->isCompleteDefinition())
Aaron Ballman86c93902014-03-06 23:45:36 +00003774 return R;
Mike Stump11289f42009-09-09 15:08:12 +00003775
Craig Topper36250ad2014-05-12 05:36:57 +00003776 return nullptr;
Ted Kremenek21475702008-09-05 17:16:31 +00003777}
3778
Douglas Gregor14454802011-02-25 02:25:35 +00003779void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
3780 if (QualifierLoc) {
John McCall3e11ebe2010-03-15 10:12:16 +00003781 // Make sure the extended qualifier info is allocated.
3782 if (!hasExtInfo())
David Majnemer00350522015-08-31 18:48:39 +00003783 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
John McCall3e11ebe2010-03-15 10:12:16 +00003784 // Set qualifier info.
Douglas Gregor14454802011-02-25 02:25:35 +00003785 getExtInfo()->QualifierLoc = QualifierLoc;
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003786 } else {
John McCall3e11ebe2010-03-15 10:12:16 +00003787 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
John McCall3e11ebe2010-03-15 10:12:16 +00003788 if (hasExtInfo()) {
Abramo Bagnara60804e12011-03-18 15:16:37 +00003789 if (getExtInfo()->NumTemplParamLists == 0) {
3790 getASTContext().Deallocate(getExtInfo());
David Majnemer00350522015-08-31 18:48:39 +00003791 TypedefNameDeclOrQualifier = (TypedefNameDecl *)nullptr;
Abramo Bagnara60804e12011-03-18 15:16:37 +00003792 }
3793 else
3794 getExtInfo()->QualifierLoc = QualifierLoc;
John McCall3e11ebe2010-03-15 10:12:16 +00003795 }
3796 }
3797}
3798
Benjamin Kramer9cc210652015-08-05 09:40:49 +00003799void TagDecl::setTemplateParameterListsInfo(
3800 ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
3801 assert(!TPLists.empty());
Abramo Bagnara60804e12011-03-18 15:16:37 +00003802 // Make sure the extended decl info is allocated.
3803 if (!hasExtInfo())
3804 // Allocate external info struct.
David Majnemer00350522015-08-31 18:48:39 +00003805 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
Abramo Bagnara60804e12011-03-18 15:16:37 +00003806 // Set the template parameter lists info.
Benjamin Kramer9cc210652015-08-05 09:40:49 +00003807 getExtInfo()->setTemplateParameterListsInfo(Context, TPLists);
Abramo Bagnara60804e12011-03-18 15:16:37 +00003808}
3809
Ted Kremenek21475702008-09-05 17:16:31 +00003810//===----------------------------------------------------------------------===//
Sebastian Redl833ef452010-01-26 22:01:41 +00003811// EnumDecl Implementation
3812//===----------------------------------------------------------------------===//
3813
Eugene Zelenkode0215c2017-11-13 23:01:27 +00003814void EnumDecl::anchor() {}
David Blaikie68e081d2011-12-20 02:48:34 +00003815
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003816EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC,
3817 SourceLocation StartLoc, SourceLocation IdLoc,
3818 IdentifierInfo *Id,
Abramo Bagnara0e05e242010-12-03 18:54:17 +00003819 EnumDecl *PrevDecl, bool IsScoped,
3820 bool IsScopedUsingClassTag, bool IsFixed) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00003821 auto *Enum = new (C, DC) EnumDecl(C, DC, StartLoc, IdLoc, Id, PrevDecl,
3822 IsScoped, IsScopedUsingClassTag, IsFixed);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003823 Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules;
Sebastian Redl833ef452010-01-26 22:01:41 +00003824 C.getTypeDeclType(Enum, PrevDecl);
3825 return Enum;
3826}
3827
Douglas Gregor72172e92012-01-05 21:55:30 +00003828EnumDecl *EnumDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00003829 EnumDecl *Enum =
3830 new (C, ID) EnumDecl(C, nullptr, SourceLocation(), SourceLocation(),
3831 nullptr, nullptr, false, false, false);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003832 Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3833 return Enum;
Argyrios Kyrtzidis39f0e302010-07-02 11:54:55 +00003834}
3835
Alp Tokerb9fa5122014-01-06 11:31:18 +00003836SourceRange EnumDecl::getIntegerTypeRange() const {
3837 if (const TypeSourceInfo *TI = getIntegerTypeSourceInfo())
3838 return TI->getTypeLoc().getSourceRange();
3839 return SourceRange();
3840}
3841
Douglas Gregord5058122010-02-11 01:19:42 +00003842void EnumDecl::completeDefinition(QualType NewType,
John McCall9aa35be2010-05-06 08:49:23 +00003843 QualType NewPromotionType,
3844 unsigned NumPositiveBits,
3845 unsigned NumNegativeBits) {
John McCallf937c022011-10-07 06:10:15 +00003846 assert(!isCompleteDefinition() && "Cannot redefine enums!");
Douglas Gregor0bf31402010-10-08 23:50:27 +00003847 if (!IntegerType)
3848 IntegerType = NewType.getTypePtr();
Sebastian Redl833ef452010-01-26 22:01:41 +00003849 PromotionType = NewPromotionType;
John McCall9aa35be2010-05-06 08:49:23 +00003850 setNumPositiveBits(NumPositiveBits);
3851 setNumNegativeBits(NumNegativeBits);
Sebastian Redl833ef452010-01-26 22:01:41 +00003852 TagDecl::completeDefinition();
3853}
3854
Akira Hatanaka3c268af2017-03-21 02:23:00 +00003855bool EnumDecl::isClosed() const {
3856 if (const auto *A = getAttr<EnumExtensibilityAttr>())
3857 return A->getExtensibility() == EnumExtensibilityAttr::Closed;
3858 return true;
3859}
3860
3861bool EnumDecl::isClosedFlag() const {
3862 return isClosed() && hasAttr<FlagEnumAttr>();
3863}
3864
3865bool EnumDecl::isClosedNonFlag() const {
3866 return isClosed() && !hasAttr<FlagEnumAttr>();
3867}
3868
Richard Smith7d137e32012-03-23 03:33:32 +00003869TemplateSpecializationKind EnumDecl::getTemplateSpecializationKind() const {
3870 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
3871 return MSI->getTemplateSpecializationKind();
3872
3873 return TSK_Undeclared;
3874}
3875
3876void EnumDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
3877 SourceLocation PointOfInstantiation) {
3878 MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
3879 assert(MSI && "Not an instantiated member enumeration?");
3880 MSI->setTemplateSpecializationKind(TSK);
3881 if (TSK != TSK_ExplicitSpecialization &&
3882 PointOfInstantiation.isValid() &&
3883 MSI->getPointOfInstantiation().isInvalid())
3884 MSI->setPointOfInstantiation(PointOfInstantiation);
3885}
3886
Richard Smith6739a102016-05-05 00:56:12 +00003887EnumDecl *EnumDecl::getTemplateInstantiationPattern() const {
3888 if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) {
3889 if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) {
3890 EnumDecl *ED = getInstantiatedFromMemberEnum();
3891 while (auto *NewED = ED->getInstantiatedFromMemberEnum())
3892 ED = NewED;
Richard Smith2195ec92017-04-21 01:15:13 +00003893 return getDefinitionOrSelf(ED);
Richard Smith6739a102016-05-05 00:56:12 +00003894 }
3895 }
3896
3897 assert(!isTemplateInstantiation(getTemplateSpecializationKind()) &&
3898 "couldn't find pattern for enum instantiation");
3899 return nullptr;
3900}
3901
Richard Smith4b38ded2012-03-14 23:13:10 +00003902EnumDecl *EnumDecl::getInstantiatedFromMemberEnum() const {
3903 if (SpecializationInfo)
3904 return cast<EnumDecl>(SpecializationInfo->getInstantiatedFrom());
3905
Craig Topper36250ad2014-05-12 05:36:57 +00003906 return nullptr;
Richard Smith4b38ded2012-03-14 23:13:10 +00003907}
3908
3909void EnumDecl::setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
3910 TemplateSpecializationKind TSK) {
3911 assert(!SpecializationInfo && "Member enum is already a specialization");
3912 SpecializationInfo = new (C) MemberSpecializationInfo(ED, TSK);
3913}
3914
Sebastian Redl833ef452010-01-26 22:01:41 +00003915//===----------------------------------------------------------------------===//
Chris Lattner59a25942008-03-31 00:36:02 +00003916// RecordDecl Implementation
3917//===----------------------------------------------------------------------===//
Chris Lattner41943152007-01-25 04:52:46 +00003918
Richard Smith053f6c62014-05-16 23:01:30 +00003919RecordDecl::RecordDecl(Kind DK, TagKind TK, const ASTContext &C,
3920 DeclContext *DC, SourceLocation StartLoc,
3921 SourceLocation IdLoc, IdentifierInfo *Id,
3922 RecordDecl *PrevDecl)
Eugene Zelenkode0215c2017-11-13 23:01:27 +00003923 : TagDecl(DK, TK, C, DC, IdLoc, Id, PrevDecl, StartLoc),
3924 HasFlexibleArrayMember(false), AnonymousStructOrUnion(false),
3925 HasObjectMember(false), HasVolatileMember(false),
3926 LoadedFieldsFromExternalStorage(false) {
Ted Kremenek52baf502008-09-02 21:12:32 +00003927 assert(classof(static_cast<Decl*>(this)) && "Invalid Kind!");
Ted Kremenek52baf502008-09-02 21:12:32 +00003928}
3929
Jay Foad39c79802011-01-12 09:06:06 +00003930RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003931 SourceLocation StartLoc, SourceLocation IdLoc,
3932 IdentifierInfo *Id, RecordDecl* PrevDecl) {
Richard Smith053f6c62014-05-16 23:01:30 +00003933 RecordDecl *R = new (C, DC) RecordDecl(Record, TK, C, DC,
3934 StartLoc, IdLoc, Id, PrevDecl);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003935 R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3936
Ted Kremenek21475702008-09-05 17:16:31 +00003937 C.getTypeDeclType(R, PrevDecl);
3938 return R;
Ted Kremenek52baf502008-09-02 21:12:32 +00003939}
3940
Douglas Gregor72172e92012-01-05 21:55:30 +00003941RecordDecl *RecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00003942 RecordDecl *R =
3943 new (C, ID) RecordDecl(Record, TTK_Struct, C, nullptr, SourceLocation(),
3944 SourceLocation(), nullptr, nullptr);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003945 R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3946 return R;
Argyrios Kyrtzidis39f0e302010-07-02 11:54:55 +00003947}
3948
Douglas Gregordfcad112009-03-25 15:59:44 +00003949bool RecordDecl::isInjectedClassName() const {
Mike Stump11289f42009-09-09 15:08:12 +00003950 return isImplicit() && getDeclName() && getDeclContext()->isRecord() &&
Douglas Gregordfcad112009-03-25 15:59:44 +00003951 cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName();
3952}
3953
Alexey Bataev39c81e22014-08-28 04:28:19 +00003954bool RecordDecl::isLambda() const {
3955 if (auto RD = dyn_cast<CXXRecordDecl>(this))
3956 return RD->isLambda();
3957 return false;
3958}
3959
Alexey Bataev330de032014-10-29 12:21:55 +00003960bool RecordDecl::isCapturedRecord() const {
3961 return hasAttr<CapturedRecordAttr>();
3962}
3963
3964void RecordDecl::setCapturedRecord() {
3965 addAttr(CapturedRecordAttr::CreateImplicit(getASTContext()));
3966}
3967
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003968RecordDecl::field_iterator RecordDecl::field_begin() const {
3969 if (hasExternalLexicalStorage() && !LoadedFieldsFromExternalStorage)
3970 LoadFieldsFromExternalStorage();
3971
3972 return field_iterator(decl_iterator(FirstDecl));
3973}
3974
Douglas Gregorb11aad82011-02-19 18:51:44 +00003975/// completeDefinition - Notes that the definition of this type is now
3976/// complete.
3977void RecordDecl::completeDefinition() {
John McCallf937c022011-10-07 06:10:15 +00003978 assert(!isCompleteDefinition() && "Cannot redefine record!");
Douglas Gregorb11aad82011-02-19 18:51:44 +00003979 TagDecl::completeDefinition();
3980}
3981
Eli Friedman9ee2d0472012-10-12 23:29:20 +00003982/// isMsStruct - Get whether or not this record uses ms_struct layout.
3983/// This which can be turned on with an attribute, pragma, or the
3984/// -mms-bitfields command-line option.
3985bool RecordDecl::isMsStruct(const ASTContext &C) const {
David Majnemer8ab003a2015-02-02 19:30:52 +00003986 return hasAttr<MSStructAttr>() || C.getLangOpts().MSBitfields == 1;
Eli Friedman9ee2d0472012-10-12 23:29:20 +00003987}
3988
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003989void RecordDecl::LoadFieldsFromExternalStorage() const {
3990 ExternalASTSource *Source = getASTContext().getExternalSource();
3991 assert(hasExternalLexicalStorage() && Source && "No external storage?");
3992
3993 // Notify that we have a RecordDecl doing some initialization.
3994 ExternalASTSource::Deserializing TheFields(Source);
3995
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003996 SmallVector<Decl*, 64> Decls;
Richard Smith3cb15722015-08-05 22:41:45 +00003997 LoadedFieldsFromExternalStorage = true;
3998 Source->FindExternalLexicalDecls(this, [](Decl::Kind K) {
3999 return FieldDecl::classofKind(K) || IndirectFieldDecl::classofKind(K);
4000 }, Decls);
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00004001
4002#ifndef NDEBUG
4003 // Check that all decls we got were FieldDecls.
4004 for (unsigned i=0, e=Decls.size(); i != e; ++i)
Argyrios Kyrtzidisf89a9272012-09-10 22:04:22 +00004005 assert(isa<FieldDecl>(Decls[i]) || isa<IndirectFieldDecl>(Decls[i]));
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00004006#endif
4007
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00004008 if (Decls.empty())
4009 return;
4010
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00004011 std::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls,
Argyrios Kyrtzidis094da732011-10-07 21:55:43 +00004012 /*FieldsAlreadyLoaded=*/false);
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00004013}
4014
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00004015bool RecordDecl::mayInsertExtraPadding(bool EmitRemark) const {
4016 ASTContext &Context = getASTContext();
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00004017 const SanitizerMask EnabledAsanMask = Context.getLangOpts().Sanitize.Mask &
4018 (SanitizerKind::Address | SanitizerKind::KernelAddress);
4019 if (!EnabledAsanMask || !Context.getLangOpts().SanitizeAddressFieldPadding)
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00004020 return false;
Alexey Samsonov33e00e22014-10-16 23:50:26 +00004021 const auto &Blacklist = Context.getSanitizerBlacklist();
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00004022 const auto *CXXRD = dyn_cast<CXXRecordDecl>(this);
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00004023 // We may be able to relax some of these requirements.
4024 int ReasonToReject = -1;
4025 if (!CXXRD || CXXRD->isExternCContext())
4026 ReasonToReject = 0; // is not C++.
4027 else if (CXXRD->hasAttr<PackedAttr>())
4028 ReasonToReject = 1; // is packed.
4029 else if (CXXRD->isUnion())
4030 ReasonToReject = 2; // is a union.
4031 else if (CXXRD->isTriviallyCopyable())
4032 ReasonToReject = 3; // is trivially copyable.
4033 else if (CXXRD->hasTrivialDestructor())
4034 ReasonToReject = 4; // has trivial destructor.
4035 else if (CXXRD->isStandardLayout())
4036 ReasonToReject = 5; // is standard layout.
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00004037 else if (Blacklist.isBlacklistedLocation(EnabledAsanMask, getLocation(),
4038 "field-padding"))
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00004039 ReasonToReject = 6; // is in a blacklisted file.
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00004040 else if (Blacklist.isBlacklistedType(EnabledAsanMask,
4041 getQualifiedNameAsString(),
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00004042 "field-padding"))
4043 ReasonToReject = 7; // is blacklisted.
4044
4045 if (EmitRemark) {
4046 if (ReasonToReject >= 0)
4047 Context.getDiagnostics().Report(
4048 getLocation(),
4049 diag::remark_sanitize_address_insert_extra_padding_rejected)
4050 << getQualifiedNameAsString() << ReasonToReject;
4051 else
4052 Context.getDiagnostics().Report(
4053 getLocation(),
4054 diag::remark_sanitize_address_insert_extra_padding_accepted)
4055 << getQualifiedNameAsString();
4056 }
4057 return ReasonToReject < 0;
4058}
4059
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00004060const FieldDecl *RecordDecl::findFirstNamedDataMember() const {
4061 for (const auto *I : fields()) {
4062 if (I->getIdentifier())
4063 return I;
4064
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00004065 if (const auto *RT = I->getType()->getAs<RecordType>())
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00004066 if (const FieldDecl *NamedDataMember =
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00004067 RT->getDecl()->findFirstNamedDataMember())
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00004068 return NamedDataMember;
4069 }
4070
4071 // We didn't find a named data member.
4072 return nullptr;
4073}
4074
Steve Naroff415d3d52008-10-08 17:01:13 +00004075//===----------------------------------------------------------------------===//
4076// BlockDecl Implementation
4077//===----------------------------------------------------------------------===//
4078
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004079void BlockDecl::setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
Craig Topper36250ad2014-05-12 05:36:57 +00004080 assert(!ParamInfo && "Already has param info!");
Mike Stump11289f42009-09-09 15:08:12 +00004081
Steve Naroffc4b30e52009-03-13 16:56:44 +00004082 // Zero params -> null pointer.
David Blaikie9c70e042011-09-21 18:16:56 +00004083 if (!NewParamInfo.empty()) {
4084 NumParams = NewParamInfo.size();
4085 ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()];
4086 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
Steve Naroffc4b30e52009-03-13 16:56:44 +00004087 }
4088}
4089
Benjamin Kramerb40e4af2015-08-05 09:40:35 +00004090void BlockDecl::setCaptures(ASTContext &Context, ArrayRef<Capture> Captures,
4091 bool CapturesCXXThis) {
4092 this->CapturesCXXThis = CapturesCXXThis;
4093 this->NumCaptures = Captures.size();
John McCallc63de662011-02-02 13:00:07 +00004094
Benjamin Kramerb40e4af2015-08-05 09:40:35 +00004095 if (Captures.empty()) {
4096 this->Captures = nullptr;
John McCallc63de662011-02-02 13:00:07 +00004097 return;
4098 }
4099
Benjamin Kramerb40e4af2015-08-05 09:40:35 +00004100 this->Captures = Captures.copy(Context).data();
Steve Naroffc4b30e52009-03-13 16:56:44 +00004101}
Sebastian Redl833ef452010-01-26 22:01:41 +00004102
John McCallce45f882011-06-15 22:51:16 +00004103bool BlockDecl::capturesVariable(const VarDecl *variable) const {
Aaron Ballman9371dd22014-03-14 18:34:04 +00004104 for (const auto &I : captures())
John McCallce45f882011-06-15 22:51:16 +00004105 // Only auto vars can be captured, so no redeclaration worries.
Aaron Ballman9371dd22014-03-14 18:34:04 +00004106 if (I.getVariable() == variable)
John McCallce45f882011-06-15 22:51:16 +00004107 return true;
4108
4109 return false;
4110}
4111
Douglas Gregor70226da2010-12-21 16:27:07 +00004112SourceRange BlockDecl::getSourceRange() const {
4113 return SourceRange(getLocation(), Body? Body->getLocEnd() : getLocation());
4114}
Sebastian Redl833ef452010-01-26 22:01:41 +00004115
4116//===----------------------------------------------------------------------===//
4117// Other Decl Allocation/Deallocation Method Implementations
4118//===----------------------------------------------------------------------===//
4119
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004120void TranslationUnitDecl::anchor() {}
David Blaikie68e081d2011-12-20 02:48:34 +00004121
Sebastian Redl833ef452010-01-26 22:01:41 +00004122TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) {
Craig Topper36250ad2014-05-12 05:36:57 +00004123 return new (C, (DeclContext *)nullptr) TranslationUnitDecl(C);
Sebastian Redl833ef452010-01-26 22:01:41 +00004124}
4125
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004126void PragmaCommentDecl::anchor() {}
Nico Weber66220292016-03-02 17:28:48 +00004127
4128PragmaCommentDecl *PragmaCommentDecl::Create(const ASTContext &C,
4129 TranslationUnitDecl *DC,
4130 SourceLocation CommentLoc,
4131 PragmaMSCommentKind CommentKind,
4132 StringRef Arg) {
4133 PragmaCommentDecl *PCD =
4134 new (C, DC, additionalSizeToAlloc<char>(Arg.size() + 1))
4135 PragmaCommentDecl(DC, CommentLoc, CommentKind);
4136 memcpy(PCD->getTrailingObjects<char>(), Arg.data(), Arg.size());
4137 PCD->getTrailingObjects<char>()[Arg.size()] = '\0';
4138 return PCD;
4139}
4140
4141PragmaCommentDecl *PragmaCommentDecl::CreateDeserialized(ASTContext &C,
4142 unsigned ID,
4143 unsigned ArgSize) {
4144 return new (C, ID, additionalSizeToAlloc<char>(ArgSize + 1))
4145 PragmaCommentDecl(nullptr, SourceLocation(), PCK_Unknown);
4146}
4147
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004148void PragmaDetectMismatchDecl::anchor() {}
Nico Webercbbaeb12016-03-02 19:28:54 +00004149
4150PragmaDetectMismatchDecl *
4151PragmaDetectMismatchDecl::Create(const ASTContext &C, TranslationUnitDecl *DC,
4152 SourceLocation Loc, StringRef Name,
4153 StringRef Value) {
4154 size_t ValueStart = Name.size() + 1;
4155 PragmaDetectMismatchDecl *PDMD =
4156 new (C, DC, additionalSizeToAlloc<char>(ValueStart + Value.size() + 1))
4157 PragmaDetectMismatchDecl(DC, Loc, ValueStart);
4158 memcpy(PDMD->getTrailingObjects<char>(), Name.data(), Name.size());
4159 PDMD->getTrailingObjects<char>()[Name.size()] = '\0';
4160 memcpy(PDMD->getTrailingObjects<char>() + ValueStart, Value.data(),
4161 Value.size());
4162 PDMD->getTrailingObjects<char>()[ValueStart + Value.size()] = '\0';
4163 return PDMD;
4164}
4165
4166PragmaDetectMismatchDecl *
4167PragmaDetectMismatchDecl::CreateDeserialized(ASTContext &C, unsigned ID,
4168 unsigned NameValueSize) {
4169 return new (C, ID, additionalSizeToAlloc<char>(NameValueSize + 1))
4170 PragmaDetectMismatchDecl(nullptr, SourceLocation(), 0);
4171}
Nico Weber66220292016-03-02 17:28:48 +00004172
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004173void ExternCContextDecl::anchor() {}
Richard Smithf19e1272015-03-07 00:04:49 +00004174
4175ExternCContextDecl *ExternCContextDecl::Create(const ASTContext &C,
4176 TranslationUnitDecl *DC) {
4177 return new (C, DC) ExternCContextDecl(DC);
4178}
4179
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004180void LabelDecl::anchor() {}
David Blaikie68e081d2011-12-20 02:48:34 +00004181
Chris Lattnerc8e630e2011-02-17 07:39:24 +00004182LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnara1c3af962011-03-05 18:21:20 +00004183 SourceLocation IdentL, IdentifierInfo *II) {
Craig Topper36250ad2014-05-12 05:36:57 +00004184 return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, IdentL);
Abramo Bagnara1c3af962011-03-05 18:21:20 +00004185}
4186
4187LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
4188 SourceLocation IdentL, IdentifierInfo *II,
4189 SourceLocation GnuLabelL) {
4190 assert(GnuLabelL != IdentL && "Use this only for GNU local labels");
Craig Topper36250ad2014-05-12 05:36:57 +00004191 return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, GnuLabelL);
Chris Lattnerc8e630e2011-02-17 07:39:24 +00004192}
4193
Douglas Gregor72172e92012-01-05 21:55:30 +00004194LabelDecl *LabelDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00004195 return new (C, ID) LabelDecl(nullptr, SourceLocation(), nullptr, nullptr,
4196 SourceLocation());
Douglas Gregor417e87c2010-10-27 19:49:05 +00004197}
4198
Ehsan Akhgari31097582014-09-22 02:21:54 +00004199void LabelDecl::setMSAsmLabel(StringRef Name) {
4200 char *Buffer = new (getASTContext(), 1) char[Name.size() + 1];
4201 memcpy(Buffer, Name.data(), Name.size());
4202 Buffer[Name.size()] = '\0';
4203 MSAsmName = Buffer;
4204}
4205
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004206void ValueDecl::anchor() {}
David Blaikie68e081d2011-12-20 02:48:34 +00004207
Benjamin Kramerea70eb32012-12-01 15:09:41 +00004208bool ValueDecl::isWeak() const {
Aaron Ballmanb97112e2014-03-08 22:19:01 +00004209 for (const auto *I : attrs())
4210 if (isa<WeakAttr>(I) || isa<WeakRefAttr>(I))
Benjamin Kramerea70eb32012-12-01 15:09:41 +00004211 return true;
4212
4213 return isWeakImported();
4214}
4215
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004216void ImplicitParamDecl::anchor() {}
David Blaikie68e081d2011-12-20 02:48:34 +00004217
Sebastian Redl833ef452010-01-26 22:01:41 +00004218ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004219 SourceLocation IdLoc,
Alexey Bataev56223232017-06-09 13:40:18 +00004220 IdentifierInfo *Id, QualType Type,
4221 ImplicitParamKind ParamKind) {
4222 return new (C, DC) ImplicitParamDecl(C, DC, IdLoc, Id, Type, ParamKind);
4223}
4224
4225ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, QualType Type,
4226 ImplicitParamKind ParamKind) {
4227 return new (C, nullptr) ImplicitParamDecl(C, Type, ParamKind);
Sebastian Redl833ef452010-01-26 22:01:41 +00004228}
4229
Richard Smithf7981722013-11-22 09:01:48 +00004230ImplicitParamDecl *ImplicitParamDecl::CreateDeserialized(ASTContext &C,
Douglas Gregor72172e92012-01-05 21:55:30 +00004231 unsigned ID) {
Alexey Bataev56223232017-06-09 13:40:18 +00004232 return new (C, ID) ImplicitParamDecl(C, QualType(), ImplicitParamKind::Other);
Douglas Gregor72172e92012-01-05 21:55:30 +00004233}
4234
Sebastian Redl833ef452010-01-26 22:01:41 +00004235FunctionDecl *FunctionDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004236 SourceLocation StartLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004237 const DeclarationNameInfo &NameInfo,
4238 QualType T, TypeSourceInfo *TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00004239 StorageClass SC,
Richard Smithf7981722013-11-22 09:01:48 +00004240 bool isInlineSpecified,
Richard Smitha77a0a62011-08-15 21:04:07 +00004241 bool hasWrittenPrototype,
4242 bool isConstexprSpecified) {
Richard Smithf7981722013-11-22 09:01:48 +00004243 FunctionDecl *New =
Richard Smith053f6c62014-05-16 23:01:30 +00004244 new (C, DC) FunctionDecl(Function, C, DC, StartLoc, NameInfo, T, TInfo,
4245 SC, isInlineSpecified, isConstexprSpecified);
Sebastian Redl833ef452010-01-26 22:01:41 +00004246 New->HasWrittenPrototype = hasWrittenPrototype;
4247 return New;
4248}
4249
Douglas Gregor72172e92012-01-05 21:55:30 +00004250FunctionDecl *FunctionDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00004251 return new (C, ID) FunctionDecl(Function, C, nullptr, SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004252 DeclarationNameInfo(), QualType(), nullptr,
Richard Smithf7981722013-11-22 09:01:48 +00004253 SC_None, false, false);
Douglas Gregor72172e92012-01-05 21:55:30 +00004254}
4255
Sebastian Redl833ef452010-01-26 22:01:41 +00004256BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
Richard Smithf7981722013-11-22 09:01:48 +00004257 return new (C, DC) BlockDecl(DC, L);
Sebastian Redl833ef452010-01-26 22:01:41 +00004258}
4259
Douglas Gregor72172e92012-01-05 21:55:30 +00004260BlockDecl *BlockDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00004261 return new (C, ID) BlockDecl(nullptr, SourceLocation());
John McCall5e77d762013-04-16 07:28:30 +00004262}
4263
Chandler Carruth21c90602015-12-30 03:24:14 +00004264CapturedDecl::CapturedDecl(DeclContext *DC, unsigned NumParams)
4265 : Decl(Captured, DC, SourceLocation()), DeclContext(Captured),
4266 NumParams(NumParams), ContextParam(0), BodyAndNothrow(nullptr, false) {}
4267
Ben Langmuir37943a72013-05-03 19:00:33 +00004268CapturedDecl *CapturedDecl::Create(ASTContext &C, DeclContext *DC,
4269 unsigned NumParams) {
James Y Knight7a22b242015-08-06 20:26:32 +00004270 return new (C, DC, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams))
Richard Smithf7981722013-11-22 09:01:48 +00004271 CapturedDecl(DC, NumParams);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004272}
4273
Ben Langmuirce914fc2013-05-03 19:20:19 +00004274CapturedDecl *CapturedDecl::CreateDeserialized(ASTContext &C, unsigned ID,
Richard Smithf7981722013-11-22 09:01:48 +00004275 unsigned NumParams) {
James Y Knight7a22b242015-08-06 20:26:32 +00004276 return new (C, ID, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams))
Craig Topper36250ad2014-05-12 05:36:57 +00004277 CapturedDecl(nullptr, NumParams);
Ben Langmuirce914fc2013-05-03 19:20:19 +00004278}
4279
Chandler Carruth21c90602015-12-30 03:24:14 +00004280Stmt *CapturedDecl::getBody() const { return BodyAndNothrow.getPointer(); }
4281void CapturedDecl::setBody(Stmt *B) { BodyAndNothrow.setPointer(B); }
4282
4283bool CapturedDecl::isNothrow() const { return BodyAndNothrow.getInt(); }
4284void CapturedDecl::setNothrow(bool Nothrow) { BodyAndNothrow.setInt(Nothrow); }
4285
Sebastian Redl833ef452010-01-26 22:01:41 +00004286EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD,
4287 SourceLocation L,
4288 IdentifierInfo *Id, QualType T,
4289 Expr *E, const llvm::APSInt &V) {
Richard Smithf7981722013-11-22 09:01:48 +00004290 return new (C, CD) EnumConstantDecl(CD, L, Id, T, E, V);
Sebastian Redl833ef452010-01-26 22:01:41 +00004291}
4292
Douglas Gregor72172e92012-01-05 21:55:30 +00004293EnumConstantDecl *
4294EnumConstantDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00004295 return new (C, ID) EnumConstantDecl(nullptr, SourceLocation(), nullptr,
4296 QualType(), nullptr, llvm::APSInt());
Douglas Gregor72172e92012-01-05 21:55:30 +00004297}
4298
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004299void IndirectFieldDecl::anchor() {}
David Blaikie68e081d2011-12-20 02:48:34 +00004300
Richard Smith9f951822016-01-06 22:49:11 +00004301IndirectFieldDecl::IndirectFieldDecl(ASTContext &C, DeclContext *DC,
4302 SourceLocation L, DeclarationName N,
David Majnemer59f77922016-06-24 04:05:48 +00004303 QualType T,
4304 MutableArrayRef<NamedDecl *> CH)
4305 : ValueDecl(IndirectField, DC, L, N, T), Chaining(CH.data()),
4306 ChainingSize(CH.size()) {
Richard Smith9f951822016-01-06 22:49:11 +00004307 // In C++, indirect field declarations conflict with tag declarations in the
4308 // same scope, so add them to IDNS_Tag so that tag redeclaration finds them.
4309 if (C.getLangOpts().CPlusPlus)
4310 IdentifierNamespace |= IDNS_Tag;
4311}
4312
Benjamin Kramer39593702010-11-21 14:11:41 +00004313IndirectFieldDecl *
4314IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,
David Majnemer59f77922016-06-24 04:05:48 +00004315 IdentifierInfo *Id, QualType T,
4316 llvm::MutableArrayRef<NamedDecl *> CH) {
4317 return new (C, DC) IndirectFieldDecl(C, DC, L, Id, T, CH);
Francois Pichet783dd6e2010-11-21 06:08:52 +00004318}
4319
Douglas Gregor72172e92012-01-05 21:55:30 +00004320IndirectFieldDecl *IndirectFieldDecl::CreateDeserialized(ASTContext &C,
4321 unsigned ID) {
Richard Smith9f951822016-01-06 22:49:11 +00004322 return new (C, ID) IndirectFieldDecl(C, nullptr, SourceLocation(),
David Majnemer59f77922016-06-24 04:05:48 +00004323 DeclarationName(), QualType(), None);
Douglas Gregor72172e92012-01-05 21:55:30 +00004324}
4325
Douglas Gregorbe996932010-09-01 20:41:53 +00004326SourceRange EnumConstantDecl::getSourceRange() const {
4327 SourceLocation End = getLocation();
4328 if (Init)
4329 End = Init->getLocEnd();
4330 return SourceRange(getLocation(), End);
4331}
4332
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004333void TypeDecl::anchor() {}
David Blaikie68e081d2011-12-20 02:48:34 +00004334
Sebastian Redl833ef452010-01-26 22:01:41 +00004335TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnarab3185b02011-03-06 15:48:19 +00004336 SourceLocation StartLoc, SourceLocation IdLoc,
4337 IdentifierInfo *Id, TypeSourceInfo *TInfo) {
Richard Smith053f6c62014-05-16 23:01:30 +00004338 return new (C, DC) TypedefDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
Sebastian Redl833ef452010-01-26 22:01:41 +00004339}
4340
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004341void TypedefNameDecl::anchor() {}
David Blaikie68e081d2011-12-20 02:48:34 +00004342
Richard Smith42413142015-05-15 20:05:43 +00004343TagDecl *TypedefNameDecl::getAnonDeclWithTypedefName(bool AnyRedecl) const {
4344 if (auto *TT = getTypeSourceInfo()->getType()->getAs<TagType>()) {
4345 auto *OwningTypedef = TT->getDecl()->getTypedefNameForAnonDecl();
4346 auto *ThisTypedef = this;
4347 if (AnyRedecl && OwningTypedef) {
4348 OwningTypedef = OwningTypedef->getCanonicalDecl();
4349 ThisTypedef = ThisTypedef->getCanonicalDecl();
4350 }
4351 if (OwningTypedef == ThisTypedef)
Richard Smitha5230222015-03-27 01:37:43 +00004352 return TT->getDecl();
Richard Smith42413142015-05-15 20:05:43 +00004353 }
Richard Smitha5230222015-03-27 01:37:43 +00004354
4355 return nullptr;
4356}
4357
Argyrios Kyrtzidis3b25c912017-03-21 16:56:02 +00004358bool TypedefNameDecl::isTransparentTagSlow() const {
4359 auto determineIsTransparent = [&]() {
4360 if (auto *TT = getUnderlyingType()->getAs<TagType>()) {
4361 if (auto *TD = TT->getDecl()) {
4362 if (TD->getName() != getName())
4363 return false;
4364 SourceLocation TTLoc = getLocation();
4365 SourceLocation TDLoc = TD->getLocation();
4366 if (!TTLoc.isMacroID() || !TDLoc.isMacroID())
4367 return false;
4368 SourceManager &SM = getASTContext().getSourceManager();
4369 return SM.getSpellingLoc(TTLoc) == SM.getSpellingLoc(TDLoc);
4370 }
4371 }
4372 return false;
4373 };
4374
4375 bool isTransparent = determineIsTransparent();
Benjamin Kramerdfb730a2018-01-26 14:14:11 +00004376 MaybeModedTInfo.setInt((isTransparent << 1) | 1);
Argyrios Kyrtzidis3b25c912017-03-21 16:56:02 +00004377 return isTransparent;
4378}
4379
Douglas Gregor72172e92012-01-05 21:55:30 +00004380TypedefDecl *TypedefDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00004381 return new (C, ID) TypedefDecl(C, nullptr, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004382 nullptr, nullptr);
Douglas Gregor72172e92012-01-05 21:55:30 +00004383}
4384
Richard Smithdda56e42011-04-15 14:24:37 +00004385TypeAliasDecl *TypeAliasDecl::Create(ASTContext &C, DeclContext *DC,
4386 SourceLocation StartLoc,
4387 SourceLocation IdLoc, IdentifierInfo *Id,
4388 TypeSourceInfo *TInfo) {
Richard Smith053f6c62014-05-16 23:01:30 +00004389 return new (C, DC) TypeAliasDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
Richard Smithdda56e42011-04-15 14:24:37 +00004390}
4391
Douglas Gregor72172e92012-01-05 21:55:30 +00004392TypeAliasDecl *TypeAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00004393 return new (C, ID) TypeAliasDecl(C, nullptr, SourceLocation(),
4394 SourceLocation(), nullptr, nullptr);
Douglas Gregor72172e92012-01-05 21:55:30 +00004395}
4396
Abramo Bagnaraea947882011-03-08 16:41:52 +00004397SourceRange TypedefDecl::getSourceRange() const {
4398 SourceLocation RangeEnd = getLocation();
4399 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
4400 if (typeIsPostfix(TInfo->getType()))
4401 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
4402 }
4403 return SourceRange(getLocStart(), RangeEnd);
4404}
4405
Richard Smithdda56e42011-04-15 14:24:37 +00004406SourceRange TypeAliasDecl::getSourceRange() const {
4407 SourceLocation RangeEnd = getLocStart();
4408 if (TypeSourceInfo *TInfo = getTypeSourceInfo())
4409 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
4410 return SourceRange(getLocStart(), RangeEnd);
4411}
4412
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004413void FileScopeAsmDecl::anchor() {}
David Blaikie68e081d2011-12-20 02:48:34 +00004414
Sebastian Redl833ef452010-01-26 22:01:41 +00004415FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnara348823a2011-03-03 14:20:18 +00004416 StringLiteral *Str,
4417 SourceLocation AsmLoc,
4418 SourceLocation RParenLoc) {
Richard Smithf7981722013-11-22 09:01:48 +00004419 return new (C, DC) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc);
Sebastian Redl833ef452010-01-26 22:01:41 +00004420}
Douglas Gregorba345522011-12-02 23:23:56 +00004421
Richard Smithf7981722013-11-22 09:01:48 +00004422FileScopeAsmDecl *FileScopeAsmDecl::CreateDeserialized(ASTContext &C,
Douglas Gregor72172e92012-01-05 21:55:30 +00004423 unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00004424 return new (C, ID) FileScopeAsmDecl(nullptr, nullptr, SourceLocation(),
4425 SourceLocation());
Douglas Gregor72172e92012-01-05 21:55:30 +00004426}
4427
Michael Han84324352013-02-22 17:15:32 +00004428void EmptyDecl::anchor() {}
4429
4430EmptyDecl *EmptyDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
Richard Smithf7981722013-11-22 09:01:48 +00004431 return new (C, DC) EmptyDecl(DC, L);
Michael Han84324352013-02-22 17:15:32 +00004432}
4433
4434EmptyDecl *EmptyDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00004435 return new (C, ID) EmptyDecl(nullptr, SourceLocation());
Michael Han84324352013-02-22 17:15:32 +00004436}
4437
Douglas Gregorba345522011-12-02 23:23:56 +00004438//===----------------------------------------------------------------------===//
4439// ImportDecl Implementation
4440//===----------------------------------------------------------------------===//
4441
4442/// \brief Retrieve the number of module identifiers needed to name the given
4443/// module.
4444static unsigned getNumModuleIdentifiers(Module *Mod) {
4445 unsigned Result = 1;
4446 while (Mod->Parent) {
4447 Mod = Mod->Parent;
4448 ++Result;
4449 }
4450 return Result;
4451}
4452
Douglas Gregor22d09742012-01-03 18:04:46 +00004453ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
Douglas Gregorba345522011-12-02 23:23:56 +00004454 Module *Imported,
4455 ArrayRef<SourceLocation> IdentifierLocs)
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004456 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, true) {
Douglas Gregorba345522011-12-02 23:23:56 +00004457 assert(getNumModuleIdentifiers(Imported) == IdentifierLocs.size());
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00004458 auto *StoredLocs = getTrailingObjects<SourceLocation>();
James Y Knight7a22b242015-08-06 20:26:32 +00004459 std::uninitialized_copy(IdentifierLocs.begin(), IdentifierLocs.end(),
4460 StoredLocs);
Douglas Gregorba345522011-12-02 23:23:56 +00004461}
4462
Douglas Gregor22d09742012-01-03 18:04:46 +00004463ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
Douglas Gregorba345522011-12-02 23:23:56 +00004464 Module *Imported, SourceLocation EndLoc)
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004465 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, false) {
James Y Knight7a22b242015-08-06 20:26:32 +00004466 *getTrailingObjects<SourceLocation>() = EndLoc;
Douglas Gregorba345522011-12-02 23:23:56 +00004467}
4468
Richard Smithf7981722013-11-22 09:01:48 +00004469ImportDecl *ImportDecl::Create(ASTContext &C, DeclContext *DC,
Douglas Gregor22d09742012-01-03 18:04:46 +00004470 SourceLocation StartLoc, Module *Imported,
Douglas Gregorba345522011-12-02 23:23:56 +00004471 ArrayRef<SourceLocation> IdentifierLocs) {
James Y Knight7a22b242015-08-06 20:26:32 +00004472 return new (C, DC,
4473 additionalSizeToAlloc<SourceLocation>(IdentifierLocs.size()))
Richard Smithf7981722013-11-22 09:01:48 +00004474 ImportDecl(DC, StartLoc, Imported, IdentifierLocs);
Douglas Gregorba345522011-12-02 23:23:56 +00004475}
4476
Richard Smithf7981722013-11-22 09:01:48 +00004477ImportDecl *ImportDecl::CreateImplicit(ASTContext &C, DeclContext *DC,
Douglas Gregor22d09742012-01-03 18:04:46 +00004478 SourceLocation StartLoc,
Richard Smithf7981722013-11-22 09:01:48 +00004479 Module *Imported,
Douglas Gregorba345522011-12-02 23:23:56 +00004480 SourceLocation EndLoc) {
James Y Knight7a22b242015-08-06 20:26:32 +00004481 ImportDecl *Import = new (C, DC, additionalSizeToAlloc<SourceLocation>(1))
4482 ImportDecl(DC, StartLoc, Imported, EndLoc);
Douglas Gregorba345522011-12-02 23:23:56 +00004483 Import->setImplicit();
4484 return Import;
4485}
4486
Douglas Gregor72172e92012-01-05 21:55:30 +00004487ImportDecl *ImportDecl::CreateDeserialized(ASTContext &C, unsigned ID,
4488 unsigned NumLocations) {
James Y Knight7a22b242015-08-06 20:26:32 +00004489 return new (C, ID, additionalSizeToAlloc<SourceLocation>(NumLocations))
Richard Smithf7981722013-11-22 09:01:48 +00004490 ImportDecl(EmptyShell());
Douglas Gregorba345522011-12-02 23:23:56 +00004491}
4492
4493ArrayRef<SourceLocation> ImportDecl::getIdentifierLocs() const {
4494 if (!ImportedAndComplete.getInt())
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00004495 return None;
Douglas Gregorba345522011-12-02 23:23:56 +00004496
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00004497 const auto *StoredLocs = getTrailingObjects<SourceLocation>();
Craig Topper5fc8fc22014-08-27 06:28:36 +00004498 return llvm::makeArrayRef(StoredLocs,
4499 getNumModuleIdentifiers(getImportedModule()));
Douglas Gregorba345522011-12-02 23:23:56 +00004500}
4501
4502SourceRange ImportDecl::getSourceRange() const {
4503 if (!ImportedAndComplete.getInt())
James Y Knight7a22b242015-08-06 20:26:32 +00004504 return SourceRange(getLocation(), *getTrailingObjects<SourceLocation>());
4505
Douglas Gregorba345522011-12-02 23:23:56 +00004506 return SourceRange(getLocation(), getIdentifierLocs().back());
4507}
Richard Smith8df390f2016-09-08 23:14:54 +00004508
4509//===----------------------------------------------------------------------===//
4510// ExportDecl Implementation
4511//===----------------------------------------------------------------------===//
4512
4513void ExportDecl::anchor() {}
4514
4515ExportDecl *ExportDecl::Create(ASTContext &C, DeclContext *DC,
4516 SourceLocation ExportLoc) {
4517 return new (C, DC) ExportDecl(DC, ExportLoc);
4518}
4519
4520ExportDecl *ExportDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
4521 return new (C, ID) ExportDecl(nullptr, SourceLocation());
4522}